summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CMakeLists.txt18
-rw-r--r--KDE2PORTING.html16
-rw-r--r--KDE3PORTING.html16
-rw-r--r--Mainpage.dox4
-rw-r--r--Makefile.am.in2
-rw-r--r--README4
-rw-r--r--TODO6
-rw-r--r--arts/kde/CMakeLists.txt6
-rw-r--r--arts/kde/kioinputstream_impl.cpp6
-rw-r--r--arts/kde/kioinputstream_impl.h2
-rw-r--r--arts/kde/kplayobjectcreator.cc2
-rw-r--r--arts/kde/kplayobjectfactory.cc4
-rw-r--r--arts/knotify/knotify.cpp2
-rw-r--r--configure.in.in8
-rw-r--r--configure.in.mid2
-rw-r--r--dcop/client/dcopfind.cpp6
-rw-r--r--dcop/client/dcopstart.cpp2
-rw-r--r--dcop/dcopidlng/kalyptus2
-rw-r--r--dnssd/CMakeLists.txt2
-rw-r--r--doc/api/tdefiledialog.png (renamed from doc/api/kfiledialog.png)bin43589 -> 43589 bytes
-rw-r--r--doc/tdelibs/man-kbuildsycoca.8.docbook221
-rw-r--r--doc/tdelibs/man-tdebuildsycoca.8.docbook221
-rw-r--r--interfaces/kio/CMakeLists.txt2
-rw-r--r--interfaces/kio/Makefile.am2
-rw-r--r--interfaces/kregexpeditor/Makefile.am2
-rw-r--r--interfaces/tdeimproxy/library/CMakeLists.txt4
-rw-r--r--interfaces/tdemediaplayer/CMakeLists.txt2
-rw-r--r--interfaces/tdemediaplayer/Makefile.am4
-rw-r--r--interfaces/tdemediaplayer/kfileaudiopreview/CMakeLists.txt46
-rw-r--r--interfaces/tdemediaplayer/kfileaudiopreview/Makefile.am13
-rw-r--r--interfaces/tdemediaplayer/kfileaudiopreview/kfileaudiopreview.cpp146
-rw-r--r--interfaces/tdemediaplayer/tdefileaudiopreview/CMakeLists.txt46
-rw-r--r--interfaces/tdemediaplayer/tdefileaudiopreview/Makefile.am13
-rw-r--r--interfaces/tdemediaplayer/tdefileaudiopreview/tdefileaudiopreview.cpp146
-rw-r--r--interfaces/tdemediaplayer/tdefileaudiopreview/tdefileaudiopreview.h (renamed from interfaces/tdemediaplayer/kfileaudiopreview/kfileaudiopreview.h)0
-rw-r--r--interfaces/tdescript/CMakeLists.txt6
-rw-r--r--interfaces/tdescript/Makefile.am2
-rw-r--r--interfaces/tdescript/sample/Makefile.am2
-rw-r--r--interfaces/tdescript/scriptloader.cpp2
-rw-r--r--interfaces/tdetexteditor/CMakeLists.txt4
-rw-r--r--interfaces/tdetexteditor/Makefile.am2
-rw-r--r--interfaces/tdetexteditor/configinterface.h2
-rw-r--r--interfaces/tdetexteditor/editorchooser.cpp2
-rw-r--r--kabc/CMakeLists.txt14
-rw-r--r--kabc/Makefile.am10
-rw-r--r--kabc/addresseehelper.cpp2
-rw-r--r--kabc/addresslineedit.cpp2
-rw-r--r--kabc/formatfactory.h2
-rw-r--r--kabc/formats/CMakeLists.txt4
-rw-r--r--kabc/kab2kabc.cpp476
-rw-r--r--kabc/kab2kabc.desktop105
-rw-r--r--kabc/ldapclient.cpp2
-rw-r--r--kabc/ldapclient.h2
-rw-r--r--kabc/ldapconfigwidget.h2
-rw-r--r--kabc/plugins/dir/CMakeLists.txt6
-rw-r--r--kabc/plugins/dir/resourcedir.cpp2
-rw-r--r--kabc/plugins/dir/resourcedir.h2
-rw-r--r--kabc/plugins/file/CMakeLists.txt6
-rw-r--r--kabc/plugins/file/resourcefile.cpp4
-rw-r--r--kabc/plugins/file/resourcefile.h2
-rw-r--r--kabc/plugins/ldapkio/CMakeLists.txt8
-rw-r--r--kabc/plugins/ldapkio/resourceldapkio.cpp4
-rw-r--r--kabc/plugins/ldapkio/resourceldapkio.h2
-rw-r--r--kabc/plugins/ldapkio/resourceldapkioconfig.cpp2
-rw-r--r--kabc/plugins/net/CMakeLists.txt6
-rw-r--r--kabc/plugins/net/resourcenet.cpp4
-rw-r--r--kabc/plugins/net/resourcenet.h2
-rw-r--r--kabc/plugins/sql/resourcesql.h2
-rw-r--r--kabc/scripts/field.src.cpp2
-rw-r--r--kabc/tdeab2tdeabc.cpp476
-rw-r--r--kabc/tdeab2tdeabc.desktop105
-rw-r--r--kate/data/bash.xml2
-rw-r--r--kate/data/tcsh.xml2
-rw-r--r--kate/data/zsh.xml2
-rw-r--r--kate/interfaces/katecmd.cpp2
-rw-r--r--kate/part/CMakeLists.txt6
-rw-r--r--kate/part/kateconfig.cpp2
-rw-r--r--kate/part/katedialogs.cpp8
-rw-r--r--kate/part/katedocument.cpp34
-rw-r--r--kate/part/katefiletype.cpp2
-rw-r--r--kate/part/katehighlight.cpp2
-rw-r--r--kate/part/katehighlight.h2
-rw-r--r--kate/part/katejscript.cpp4
-rw-r--r--kate/part/kateluaindentscript.cpp2
-rw-r--r--kate/part/kateschema.h4
-rw-r--r--kate/part/katesyntaxdocument.cpp2
-rw-r--r--kate/part/kateview.cpp4
-rw-r--r--kate/part/test_regression.cpp2
-rw-r--r--kate/plugins/autobookmarker/autobookmarker.cpp2
-rw-r--r--kate/plugins/insertfile/CMakeLists.txt6
-rw-r--r--kate/plugins/insertfile/insertfileplugin.cpp4
-rw-r--r--kate/plugins/isearch/ISearchPlugin.cpp2
-rw-r--r--kate/plugins/kdatatool/CMakeLists.txt4
-rw-r--r--kate/plugins/wordcompletion/docwordcompletion.cpp2
-rw-r--r--kcmshell/CMakeLists.txt41
-rw-r--r--kcmshell/Makefile.am39
-rw-r--r--kcmshell/main.cpp350
-rw-r--r--kcmshell/main.h104
-rw-r--r--kconf_update/CMakeLists.txt34
-rw-r--r--kconf_update/Mainpage.dox31
-rw-r--r--kconf_update/Makefile.am33
-rw-r--r--kconf_update/README.kconf_update251
-rw-r--r--kconf_update/kconf_update.cpp959
-rw-r--r--kded/CMakeLists.txt30
-rw-r--r--kded/DESIGN4
-rw-r--r--kded/Makefile.am22
-rw-r--r--kded/README.kded16
-rw-r--r--kded/kbuildsycoca.cpp959
-rw-r--r--kded/kbuildsycoca.h104
-rw-r--r--kded/kde-menu.cpp171
-rw-r--r--kded/kded.cpp16
-rw-r--r--kded/kded.h2
-rw-r--r--kded/kdedmodule.cpp2
-rw-r--r--kded/tde-menu.cpp171
-rw-r--r--kded/tdebuildsycoca.cpp959
-rw-r--r--kded/tdebuildsycoca.h104
-rw-r--r--kded/tdemimelist.cpp (renamed from kded/kmimelist.cpp)0
-rw-r--r--kdewidgets/CMakeLists.txt4
-rw-r--r--kdewidgets/Makefile.am2
-rw-r--r--kdewidgets/makekdewidgets.cpp2
-rw-r--r--kdoctools/CMakeLists.txt14
-rw-r--r--kdoctools/Makefile.am8
-rw-r--r--kdoctools/docbook/README.kde2
-rw-r--r--kdoctools/kio_help.h4
-rw-r--r--kdoctools/kio_help.upd2
-rw-r--r--kdoctools/move_kio_help_cache.sh2
-rw-r--r--kfile-plugins/elf/CMakeLists.txt42
-rw-r--r--kfile-plugins/elf/kfile_elf.cpp133
-rw-r--r--kfile-plugins/elf/kfile_elf.desktop66
-rw-r--r--kfile-plugins/elf/kfile_elf.h50
-rw-r--r--kimgio/Makefile.am2
-rw-r--r--kimgio/README2
-rw-r--r--kinit/CMakeLists.txt32
-rw-r--r--kinit/Makefile.am30
-rw-r--r--kinit/autostart.cpp2
-rw-r--r--kinit/kdostartupconfig.cpp143
-rw-r--r--kinit/kinit.cpp46
-rw-r--r--kinit/kioslave.cpp93
-rw-r--r--kinit/klauncher.cpp1421
-rw-r--r--kinit/klauncher.h200
-rw-r--r--kinit/klauncher_cmds.h185
-rw-r--r--kinit/klauncher_main.cpp116
-rw-r--r--kinit/kstartupconfig.cpp176
-rw-r--r--kinit/tdedostartupconfig.cpp143
-rw-r--r--kinit/tdeioslave.cpp93
-rw-r--r--kinit/tdelauncher.cpp1421
-rw-r--r--kinit/tdelauncher.h200
-rw-r--r--kinit/tdelauncher_cmds.h185
-rw-r--r--kinit/tdelauncher_main.cpp116
-rw-r--r--kinit/tdestartupconfig.cpp176
-rw-r--r--kinit/tests/Makefile.am6
-rw-r--r--kinit/tests/klaunchertest.cpp54
-rw-r--r--kinit/tests/tdelaunchertest.cpp54
-rw-r--r--kinit/wrapper.c4
-rw-r--r--kio/CMakeLists.txt71
-rw-r--r--kio/DESIGN272
-rw-r--r--kio/DESIGN.krun35
-rw-r--r--kio/Makefile.am67
-rw-r--r--kio/bookmarks/CMakeLists.txt55
-rw-r--r--kio/bookmarks/Makefile.am40
-rw-r--r--kio/bookmarks/kbookmarkbar.cc554
-rw-r--r--kio/bookmarks/kbookmarkimporter.cc101
-rw-r--r--kio/bookmarks/kbookmarkimporter_crash.cc215
-rw-r--r--kio/bookmarks/kbookmarkimporter_ie.cc185
-rw-r--r--kio/bookmarks/kbookmarkimporter_kde1.cc156
-rw-r--r--kio/bookmarks/kbookmarkimporter_ns.cc243
-rw-r--r--kio/bookmarks/kbookmarkimporter_opera.cc170
-rw-r--r--kio/bookmarks/kbookmarkmenu.cc1187
-rw-r--r--kio/data.protocol71
-rw-r--r--kio/httpfilter/CMakeLists.txt32
-rw-r--r--kio/httpfilter/httpfilter.cc372
-rw-r--r--kio/kfile/CMakeLists.txt76
-rw-r--r--kio/kfile/ChangeLog725
-rw-r--r--kio/kfile/Makefile.am78
-rw-r--r--kio/kfile/NOTES100
-rw-r--r--kio/kfile/config-kfile.h32
-rw-r--r--kio/kfile/kacleditwidget.cpp1054
-rw-r--r--kio/kfile/kacleditwidget.h65
-rw-r--r--kio/kfile/kacleditwidget_p.h206
-rw-r--r--kio/kfile/kcombiview.cpp371
-rw-r--r--kio/kfile/kcombiview.h133
-rw-r--r--kio/kfile/kcustommenueditor.cpp242
-rw-r--r--kio/kfile/kdiroperator.cpp1740
-rw-r--r--kio/kfile/kdiroperator.h950
-rw-r--r--kio/kfile/kdirselectdialog.cpp481
-rw-r--r--kio/kfile/kdirsize.cpp166
-rw-r--r--kio/kfile/kdirsize.h106
-rw-r--r--kio/kfile/kdiskfreesp.cpp169
-rw-r--r--kio/kfile/kencodingfiledialog.cpp223
-rw-r--r--kio/kfile/kencodingfiledialog.h313
-rw-r--r--kio/kfile/kfile.h129
-rw-r--r--kio/kfile/kfilebookmarkhandler.cpp81
-rw-r--r--kio/kfile/kfiledetailview.cpp686
-rw-r--r--kio/kfile/kfiledetailview.h219
-rw-r--r--kio/kfile/kfiledialog.cpp2380
-rw-r--r--kio/kfile/kfiledialog.h989
-rw-r--r--kio/kfile/kfilefiltercombo.cpp203
-rw-r--r--kio/kfile/kfileiconview.cpp943
-rw-r--r--kio/kfile/kfileiconview.h267
-rw-r--r--kio/kfile/kfilemetainfowidget.cpp375
-rw-r--r--kio/kfile/kfilemetainfowidget.h95
-rw-r--r--kio/kfile/kfilemetapreview.cpp196
-rw-r--r--kio/kfile/kfilepreview.cpp279
-rw-r--r--kio/kfile/kfilepreview.h122
-rw-r--r--kio/kfile/kfilesharedlg.cpp325
-rw-r--r--kio/kfile/kfilesharedlg.h70
-rw-r--r--kio/kfile/kfilespeedbar.cpp147
-rw-r--r--kio/kfile/kfiletreebranch.cpp528
-rw-r--r--kio/kfile/kfiletreebranch.h242
-rw-r--r--kio/kfile/kfiletreeview.cpp677
-rw-r--r--kio/kfile/kfiletreeview.h273
-rw-r--r--kio/kfile/kfiletreeviewitem.cpp83
-rw-r--r--kio/kfile/kfiletreeviewitem.h106
-rw-r--r--kio/kfile/kfileview.cpp429
-rw-r--r--kio/kfile/kfileview.h444
-rw-r--r--kio/kfile/kicondialog.cpp772
-rw-r--r--kio/kfile/kicondialog.h350
-rw-r--r--kio/kfile/kimagefilepreview.cpp187
-rw-r--r--kio/kfile/kmetaprops.cpp268
-rw-r--r--kio/kfile/knotifydialog.cpp1191
-rw-r--r--kio/kfile/kpreviewprops.cpp89
-rw-r--r--kio/kfile/kpropertiesdialog.cpp4170
-rw-r--r--kio/kfile/kpropertiesdialog.h918
-rw-r--r--kio/kfile/kurlbar.cpp1049
-rw-r--r--kio/kfile/kurlrequester.cpp430
-rw-r--r--kio/kfile/kurlrequester.h301
-rw-r--r--kio/kfile/kurlrequesterdlg.cpp135
-rw-r--r--kio/kfile/tests/Makefile.am41
-rw-r--r--kio/kfile/tests/kcustommenueditortest.cpp19
-rw-r--r--kio/kfile/tests/kfdtest.cpp34
-rw-r--r--kio/kfile/tests/kfiletreeviewtest.cpp165
-rw-r--r--kio/kfile/tests/kfstest.cpp183
-rw-r--r--kio/kio/CMakeLists.txt138
-rw-r--r--kio/kio/Makefile.am129
-rw-r--r--kio/kio/authinfo.cpp332
-rw-r--r--kio/kio/chmodjob.cpp258
-rw-r--r--kio/kio/chmodjob.h109
-rw-r--r--kio/kio/connection.cpp273
-rw-r--r--kio/kio/dataprotocol.cpp339
-rw-r--r--kio/kio/dataprotocol.h71
-rw-r--r--kio/kio/dataslave.h126
-rw-r--r--kio/kio/davjob.cpp142
-rw-r--r--kio/kio/davjob.h127
-rw-r--r--kio/kio/defaultprogress.cpp507
-rw-r--r--kio/kio/defaultprogress.h164
-rw-r--r--kio/kio/forwardingslavebase.cpp475
-rw-r--r--kio/kio/forwardingslavebase.h204
-rw-r--r--kio/kio/global.cpp2009
-rw-r--r--kio/kio/job.cpp4814
-rw-r--r--kio/kio/job.h532
-rw-r--r--kio/kio/jobclasses.h1909
-rw-r--r--kio/kio/kacl.h207
-rw-r--r--kio/kio/kautomount.cpp117
-rw-r--r--kio/kio/kdirlister.cpp2538
-rw-r--r--kio/kio/kdirlister.h634
-rw-r--r--kio/kio/kdirlister_p.h358
-rw-r--r--kio/kio/kdirwatch.cpp1774
-rw-r--r--kio/kio/kemailsettings.cpp272
-rw-r--r--kio/kio/kfilefilter.cpp134
-rw-r--r--kio/kio/kfileitem.cpp1202
-rw-r--r--kio/kio/kfileitem.h671
-rw-r--r--kio/kio/kfilemetainfo.cpp1859
-rw-r--r--kio/kio/kfilemetainfo.h1738
-rw-r--r--kio/kio/kfileshare.cpp346
-rw-r--r--kio/kio/kfileshare.h165
-rw-r--r--kio/kio/kmimetype.cpp1172
-rw-r--r--kio/kio/kmimetypechooser.cpp298
-rw-r--r--kio/kio/knfsshare.cpp219
-rw-r--r--kio/kio/kprotocolinfo.h688
-rw-r--r--kio/kio/kprotocolmanager.cpp534
-rw-r--r--kio/kio/kprotocolmanager.h389
-rw-r--r--kio/kio/krun.cpp1574
-rw-r--r--kio/kio/ksambashare.cpp239
-rw-r--r--kio/kio/kservice.cpp934
-rw-r--r--kio/kio/kshred.h156
-rw-r--r--kio/kio/ktrader.h295
-rw-r--r--kio/kio/kurlcompletion.cpp1604
-rw-r--r--kio/kio/kurlcompletion.h236
-rw-r--r--kio/kio/kuserprofile.cpp355
-rw-r--r--kio/kio/kzip.cpp1460
-rw-r--r--kio/kio/kzip.h284
-rw-r--r--kio/kio/metainfojob.cpp184
-rw-r--r--kio/kio/metainfojob.h119
-rw-r--r--kio/kio/netaccess.cpp536
-rw-r--r--kio/kio/netaccess.h540
-rw-r--r--kio/kio/observer.cpp417
-rw-r--r--kio/kio/observer.h213
-rw-r--r--kio/kio/passdlg.cpp367
-rw-r--r--kio/kio/paste.cpp308
-rw-r--r--kio/kio/previewjob.cpp597
-rw-r--r--kio/kio/previewjob.h182
-rw-r--r--kio/kio/progressbase.h271
-rw-r--r--kio/kio/renamedlg.cpp574
-rw-r--r--kio/kio/renamedlg.h153
-rw-r--r--kio/kio/renamedlgplugin.h59
-rw-r--r--kio/kio/scheduler.cpp922
-rw-r--r--kio/kio/scheduler.h364
-rw-r--r--kio/kio/sessiondata.cpp311
-rw-r--r--kio/kio/sessiondata.h67
-rw-r--r--kio/kio/skipdlg.cpp143
-rw-r--r--kio/kio/slave.cpp519
-rw-r--r--kio/kio/slave.h270
-rw-r--r--kio/kio/slavebase.cpp1315
-rw-r--r--kio/kio/slavebase.h847
-rw-r--r--kio/kio/slaveconfig.cpp225
-rw-r--r--kio/kio/slaveconfig.h106
-rw-r--r--kio/kio/slaveinterface.cpp550
-rw-r--r--kio/kio/slaveinterface.h290
-rw-r--r--kio/kio/tcpslavebase.cpp1343
-rw-r--r--kio/kio/tcpslavebase.h389
-rw-r--r--kio/kio/thumbcreator.h124
-rw-r--r--kio/kioexec/CMakeLists.txt42
-rw-r--r--kio/kioexec/Makefile.am19
-rw-r--r--kio/kioexec/main.cpp294
-rw-r--r--kio/kioslave.upd18
-rw-r--r--kio/kpasswdserver/CMakeLists.txt43
-rw-r--r--kio/kpasswdserver/Makefile.am15
-rw-r--r--kio/kpasswdserver/kpasswdserver.cpp715
-rw-r--r--kio/kpasswdserver/kpasswdserver.h118
-rw-r--r--kio/kssl/configure.in.in7
-rw-r--r--kio/kssl/kopenssl.cc1601
-rw-r--r--kio/kssl/kssl/HOWTO30
-rw-r--r--kio/kssl/ksslinfodlg.cc463
-rw-r--r--kio/kssl/ksslkeygen.cc223
-rw-r--r--kio/kssl/ksslsettings.h224
-rw-r--r--kio/misc/CMakeLists.txt100
-rw-r--r--kio/misc/Makefile.am60
-rw-r--r--kio/misc/kfile/CMakeLists.txt39
-rw-r--r--kio/misc/kfile/Makefile.am10
-rw-r--r--kio/misc/kfile/fileprops.cpp480
-rw-r--r--kio/misc/kfile/fileprops.h74
-rw-r--r--kio/misc/kio_uiserver.desktop100
-rw-r--r--kio/misc/kmailservice.cpp45
-rw-r--r--kio/misc/kmailservice.protocol15
-rw-r--r--kio/misc/kpac/CMakeLists.txt66
-rw-r--r--kio/misc/kpac/downloader.cpp89
-rw-r--r--kio/misc/ksendbugmail/CMakeLists.txt37
-rw-r--r--kio/misc/ksendbugmail/Makefile.am26
-rw-r--r--kio/misc/ksendbugmail/main.cpp142
-rw-r--r--kio/misc/kssld/CMakeLists.txt47
-rw-r--r--kio/misc/kssld/Makefile.am33
-rw-r--r--kio/misc/kssld/kssld.cpp1027
-rw-r--r--kio/misc/ktelnetservice.cpp112
-rw-r--r--kio/misc/rlogin.protocol13
-rw-r--r--kio/misc/ssh.protocol13
-rw-r--r--kio/misc/tdentlm/CMakeLists.txt43
-rw-r--r--kio/misc/tdentlm/Makefile.am12
-rw-r--r--kio/misc/tdesasl/CMakeLists.txt42
-rw-r--r--kio/misc/tdesasl/Makefile.am12
-rw-r--r--kio/misc/tdewalletd/CMakeLists.txt49
-rw-r--r--kio/misc/tdewalletd/tdewalletd.cpp1514
-rw-r--r--kio/misc/telnet.protocol13
-rw-r--r--kio/misc/uiserver.cpp1413
-rw-r--r--kio/misc/uiserver.h430
-rw-r--r--kio/pics/CMakeLists.txt14
-rw-r--r--kio/pics/Makefile.am3
-rw-r--r--kio/tests/CMakeLists.txt36
-rw-r--r--kio/tests/Makefile.am91
-rw-r--r--kio/tests/dataprotocoltest.cpp287
-rw-r--r--kio/tests/dummymeta.h20
-rw-r--r--kio/tests/jobtest.cpp613
-rw-r--r--kio/tests/jobtest.h79
-rw-r--r--kio/tests/kacltest.cpp309
-rw-r--r--kio/tests/kdefaultprogresstest.cpp39
-rw-r--r--kio/tests/kdirlistertest.h120
-rw-r--r--kio/tests/kioslavetest.cpp555
-rw-r--r--kio/tests/kioslavetest.h108
-rw-r--r--kio/tests/kmfitest.cpp28
-rw-r--r--kio/tests/ktradertest.cpp108
-rw-r--r--kio/tests/kurifiltertest.cpp361
-rw-r--r--kio/tests/metatest.cpp321
-rw-r--r--kio/tests/netaccesstest.cpp48
-rw-r--r--kio/tests/previewtest.cpp64
-rw-r--r--kio/tests/previewtest.h25
-rw-r--r--kio/tests/speed.cpp139
-rw-r--r--kio/tests/speed.h24
-rw-r--r--kioslave/bzip2/CMakeLists.txt42
-rw-r--r--kioslave/bzip2/Makefile.am11
-rw-r--r--kioslave/file/CMakeLists.txt55
-rw-r--r--kioslave/file/Makefile.am22
-rw-r--r--kioslave/file/file.cc1831
-rw-r--r--kioslave/file/file.h98
-rw-r--r--kioslave/file/file.protocol15
-rw-r--r--kioslave/ftp/CMakeLists.txt44
-rw-r--r--kioslave/ftp/ftp.cc2675
-rw-r--r--kioslave/ftp/ftp.h603
-rw-r--r--kioslave/ftp/ftp.protocol18
-rw-r--r--kioslave/gzip/CMakeLists.txt41
-rw-r--r--kioslave/gzip/Makefile.am12
-rw-r--r--kioslave/http/CMakeLists.txt69
-rw-r--r--kioslave/http/Makefile.am31
-rw-r--r--kioslave/http/THOUGHTS28
-rw-r--r--kioslave/http/http.cc6108
-rw-r--r--kioslave/http/http.h577
-rw-r--r--kioslave/http/http.protocol12
-rw-r--r--kioslave/http/https.protocol12
-rw-r--r--kioslave/http/kcookiejar/Makefile.am31
-rw-r--r--kioslave/http/kcookiejar/kcookiejar.cpp1559
-rw-r--r--kioslave/http/kcookiejar/kcookieserver.cpp606
-rw-r--r--kioslave/http/kcookiejar/tests/Makefile.am18
-rw-r--r--kioslave/http/webdav.protocol18
-rw-r--r--kioslave/http/webdavs.protocol18
-rw-r--r--kioslave/iso/CMakeLists.txt51
-rw-r--r--kioslave/iso/Makefile.am67
-rw-r--r--kioslave/iso/iso.h51
-rw-r--r--kioslave/iso/iso.protocol11
-rw-r--r--kioslave/iso/kiso.cpp460
-rw-r--r--kioslave/metainfo/CMakeLists.txt43
-rw-r--r--kioslave/metainfo/Makefile.am24
-rw-r--r--kioslave/metainfo/metainfo.cpp103
-rw-r--r--kioslave/metainfo/metainfo.h38
-rw-r--r--knewstuff/CMakeLists.txt16
-rw-r--r--knewstuff/Makefile.am10
-rw-r--r--knewstuff/downloaddialog.cpp6
-rw-r--r--knewstuff/engine.cpp2
-rw-r--r--knewstuff/khotnewstuff.cpp55
-rw-r--r--knewstuff/knewstuffgeneric.cpp2
-rw-r--r--knewstuff/knewstuffsecure.cpp4
-rw-r--r--knewstuff/provider.cpp4
-rw-r--r--knewstuff/tdehotnewstuff.cpp55
-rw-r--r--knewstuff/tdehotnewstuffrc (renamed from knewstuff/khotnewstuffrc)0
-rw-r--r--knewstuff/uploaddialog.cpp2
-rw-r--r--kstyles/plastik/config/CMakeLists.txt2
-rw-r--r--kstyles/plastik/config/Makefile.am4
-rw-r--r--kstyles/plastik/config/plastikconf.cpp223
-rw-r--r--kstyles/plastik/config/plastitdeconf.cpp223
-rw-r--r--kstyles/plastik/config/plastitdeconf.h (renamed from kstyles/plastik/config/plastikconf.h)0
-rw-r--r--libtdemid/deviceman.cc2
-rw-r--r--tdecert/CMakeLists.txt12
-rw-r--r--tdecert/Makefile.am2
-rw-r--r--tdecert/tdecertpart.cc8
-rw-r--r--tdecmshell/CMakeLists.txt41
-rw-r--r--tdecmshell/Makefile.am39
-rw-r--r--tdecmshell/main.cpp350
-rw-r--r--tdecmshell/main.h104
-rw-r--r--tdeconf_update/CMakeLists.txt34
-rw-r--r--tdeconf_update/Mainpage.dox31
-rw-r--r--tdeconf_update/Makefile.am33
-rw-r--r--tdeconf_update/README.tdeconf_update251
-rw-r--r--tdeconf_update/tdeconf_update.cpp959
-rw-r--r--tdecore/CMakeLists.txt16
-rw-r--r--tdecore/DESIGN.kconfig224
-rw-r--r--tdecore/DESIGN.tdeconfig224
-rw-r--r--tdecore/MAINTAINERS10
-rw-r--r--tdecore/Makefile.am22
-rw-r--r--tdecore/README.kiosk2
-rw-r--r--tdecore/README.kstartupinfo2
-rw-r--r--tdecore/kaccelaction.cpp2
-rw-r--r--tdecore/kaccelbase.cpp2
-rw-r--r--tdecore/kappdcopiface.cpp2
-rw-r--r--tdecore/kapplication.cpp4
-rw-r--r--tdecore/kcharsets.cpp2
-rw-r--r--tdecore/kcheckaccelerators.cpp2
-rw-r--r--tdecore/kclipboard.cpp2
-rw-r--r--tdecore/kconfig.cpp367
-rw-r--r--tdecore/kconfig.h296
-rw-r--r--tdecore/kconfig_compiler/CMakeLists.txt29
-rw-r--r--tdecore/kconfig_compiler/Makefile.am18
-rw-r--r--tdecore/kconfig_compiler/README.dox255
-rwxr-xr-xtdecore/kconfig_compiler/checkkcfg.pl83
-rw-r--r--tdecore/kconfig_compiler/example/Makefile.am27
-rw-r--r--tdecore/kconfig_compiler/example/autoexample.cpp64
-rw-r--r--tdecore/kconfig_compiler/example/example.cpp52
-rw-r--r--tdecore/kconfig_compiler/example/exampleprefs_base.kcfgc18
-rw-r--r--tdecore/kconfig_compiler/kconfig_compiler.cpp1700
-rw-r--r--tdecore/kconfig_compiler/tests/Makefile.am134
-rw-r--r--tdecore/kconfig_compiler/tests/kconfigcompiler_test.cpp96
-rw-r--r--tdecore/kconfig_compiler/tests/myprefs.h7
-rw-r--r--tdecore/kconfig_compiler/tests/test1.cpp.ref72
-rw-r--r--tdecore/kconfig_compiler/tests/test1.h.ref196
-rw-r--r--tdecore/kconfig_compiler/tests/test1.kcfgc18
-rw-r--r--tdecore/kconfig_compiler/tests/test2.cpp.ref98
-rw-r--r--tdecore/kconfig_compiler/tests/test2.h.ref333
-rw-r--r--tdecore/kconfig_compiler/tests/test2.kcfgc11
-rw-r--r--tdecore/kconfig_compiler/tests/test3.cpp.ref29
-rw-r--r--tdecore/kconfig_compiler/tests/test3.h.ref138
-rw-r--r--tdecore/kconfig_compiler/tests/test3.kcfgc12
-rw-r--r--tdecore/kconfig_compiler/tests/test4.cpp.ref82
-rw-r--r--tdecore/kconfig_compiler/tests/test4.h.ref135
-rw-r--r--tdecore/kconfig_compiler/tests/test4.kcfgc11
-rw-r--r--tdecore/kconfig_compiler/tests/test5.cpp.ref82
-rw-r--r--tdecore/kconfig_compiler/tests/test5.h.ref127
-rw-r--r--tdecore/kconfig_compiler/tests/test5.kcfgc11
-rw-r--r--tdecore/kconfig_compiler/tests/test6.cpp.ref31
-rw-r--r--tdecore/kconfig_compiler/tests/test6.h.ref93
-rw-r--r--tdecore/kconfig_compiler/tests/test6.kcfgc11
-rw-r--r--tdecore/kconfig_compiler/tests/test7.cpp.ref31
-rw-r--r--tdecore/kconfig_compiler/tests/test7.h.ref93
-rw-r--r--tdecore/kconfig_compiler/tests/test7.kcfgc11
-rw-r--r--tdecore/kconfig_compiler/tests/test8a.cpp.ref22
-rw-r--r--tdecore/kconfig_compiler/tests/test8a.h.ref61
-rw-r--r--tdecore/kconfig_compiler/tests/test8b.cpp.ref46
-rw-r--r--tdecore/kconfig_compiler/tests/test8b.h.ref96
-rw-r--r--tdecore/kconfig_compiler/tests/test9.cpp.ref35
-rw-r--r--tdecore/kconfig_compiler/tests/test9.h.ref82
-rw-r--r--tdecore/kconfig_compiler/tests/test9.kcfgc18
-rw-r--r--tdecore/kconfig_compiler/tests/test_dpointer.cpp.ref344
-rw-r--r--tdecore/kconfig_compiler/tests/test_dpointer.h.ref224
-rw-r--r--tdecore/kconfig_compiler/tests/test_dpointer.kcfgc11
-rw-r--r--tdecore/kconfigbackend.cpp1190
-rw-r--r--tdecore/kconfigbackend.h299
-rw-r--r--tdecore/kconfigbase.cpp1937
-rw-r--r--tdecore/kconfigbase.h2180
-rw-r--r--tdecore/kconfigdialogmanager.cpp398
-rw-r--r--tdecore/kconfigskeleton.cpp1207
-rw-r--r--tdecore/kconfigskeleton.h1230
-rw-r--r--tdecore/kcrash.cpp4
-rw-r--r--tdecore/kdebug.areas20
-rw-r--r--tdecore/kdebug.cpp2
-rw-r--r--tdecore/kdesktopfile.cpp2
-rw-r--r--tdecore/kdesktopfile.h2
-rw-r--r--tdecore/kdetcompmgr.cpp2
-rw-r--r--tdecore/kglobal.cpp2
-rw-r--r--tdecore/kglobalsettings.cpp2
-rw-r--r--tdecore/kiconeffect.cpp2
-rw-r--r--tdecore/kiconloader.cpp2
-rw-r--r--tdecore/kicontheme.cpp2
-rw-r--r--tdecore/kinstance.cpp2
-rw-r--r--tdecore/kkeyserver_x11.cpp2
-rw-r--r--tdecore/klocale.cpp4
-rw-r--r--tdecore/kmdcodec_compat.h2
-rw-r--r--tdecore/knotifyclient.cpp2
-rw-r--r--tdecore/kprotocolinfo_tdecore.cpp4
-rw-r--r--tdecore/kprotocolinfofactory.h2
-rw-r--r--tdecore/kshortcutlist.cpp2
-rw-r--r--tdecore/ksimpleconfig.cpp2
-rw-r--r--tdecore/ksimpleconfig.h2
-rw-r--r--tdecore/ksimpledirwatch.cpp4
-rw-r--r--tdecore/ksocks.cpp2
-rw-r--r--tdecore/kstandarddirs.cpp2
-rw-r--r--tdecore/kstdaccel.cpp2
-rw-r--r--tdecore/kuniqueapplication.cpp2
-rw-r--r--tdecore/networkbackends/network-manager/network-manager.cpp10
-rw-r--r--tdecore/tdeconfig.cpp367
-rw-r--r--tdecore/tdeconfig.h296
-rw-r--r--tdecore/tdeconfig_compiler/CMakeLists.txt29
-rw-r--r--tdecore/tdeconfig_compiler/Makefile.am18
-rw-r--r--tdecore/tdeconfig_compiler/README.dox255
-rw-r--r--tdecore/tdeconfig_compiler/TODO (renamed from tdecore/kconfig_compiler/TODO)0
-rwxr-xr-xtdecore/tdeconfig_compiler/checkkcfg.pl83
-rw-r--r--tdecore/tdeconfig_compiler/example/Makefile.am27
-rw-r--r--tdecore/tdeconfig_compiler/example/autoexample.cpp64
-rw-r--r--tdecore/tdeconfig_compiler/example/example.cpp52
-rw-r--r--tdecore/tdeconfig_compiler/example/example.kcfg (renamed from tdecore/kconfig_compiler/example/example.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/example/exampleprefs_base.kcfgc18
-rw-r--r--tdecore/tdeconfig_compiler/example/general_base.ui (renamed from tdecore/kconfig_compiler/example/general_base.ui)0
-rw-r--r--tdecore/tdeconfig_compiler/example/myoptions_base.ui (renamed from tdecore/kconfig_compiler/example/myoptions_base.ui)0
-rw-r--r--tdecore/tdeconfig_compiler/kcfg.xsd (renamed from tdecore/kconfig_compiler/kcfg.xsd)0
-rw-r--r--tdecore/tdeconfig_compiler/tdeconfig_compiler.cpp1700
-rw-r--r--tdecore/tdeconfig_compiler/tests/Makefile.am134
-rw-r--r--tdecore/tdeconfig_compiler/tests/myprefs.h7
-rw-r--r--tdecore/tdeconfig_compiler/tests/tdeconfigcompiler_test.cpp96
-rw-r--r--tdecore/tdeconfig_compiler/tests/tdeconfigcompiler_test.h (renamed from tdecore/kconfig_compiler/tests/kconfigcompiler_test.h)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test1.cpp.ref72
-rw-r--r--tdecore/tdeconfig_compiler/tests/test1.h.ref196
-rw-r--r--tdecore/tdeconfig_compiler/tests/test1.kcfg (renamed from tdecore/kconfig_compiler/tests/test1.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test1.kcfgc18
-rw-r--r--tdecore/tdeconfig_compiler/tests/test1main.cpp (renamed from tdecore/kconfig_compiler/tests/test1main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test2.cpp.ref98
-rw-r--r--tdecore/tdeconfig_compiler/tests/test2.h.ref333
-rw-r--r--tdecore/tdeconfig_compiler/tests/test2.kcfg (renamed from tdecore/kconfig_compiler/tests/test2.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test2.kcfgc11
-rw-r--r--tdecore/tdeconfig_compiler/tests/test2main.cpp (renamed from tdecore/kconfig_compiler/tests/test2main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test3.cpp.ref29
-rw-r--r--tdecore/tdeconfig_compiler/tests/test3.h.ref138
-rw-r--r--tdecore/tdeconfig_compiler/tests/test3.kcfg (renamed from tdecore/kconfig_compiler/tests/test3.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test3.kcfgc12
-rw-r--r--tdecore/tdeconfig_compiler/tests/test3main.cpp (renamed from tdecore/kconfig_compiler/tests/test3main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test4.cpp.ref82
-rw-r--r--tdecore/tdeconfig_compiler/tests/test4.h.ref135
-rw-r--r--tdecore/tdeconfig_compiler/tests/test4.kcfg (renamed from tdecore/kconfig_compiler/tests/test4.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test4.kcfgc11
-rw-r--r--tdecore/tdeconfig_compiler/tests/test4main.cpp (renamed from tdecore/kconfig_compiler/tests/test4main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test5.cpp.ref82
-rw-r--r--tdecore/tdeconfig_compiler/tests/test5.h.ref127
-rw-r--r--tdecore/tdeconfig_compiler/tests/test5.kcfg (renamed from tdecore/kconfig_compiler/tests/test5.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test5.kcfgc11
-rw-r--r--tdecore/tdeconfig_compiler/tests/test5main.cpp (renamed from tdecore/kconfig_compiler/tests/test5main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test6.cpp.ref31
-rw-r--r--tdecore/tdeconfig_compiler/tests/test6.h.ref93
-rw-r--r--tdecore/tdeconfig_compiler/tests/test6.kcfg (renamed from tdecore/kconfig_compiler/tests/test6.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test6.kcfgc11
-rw-r--r--tdecore/tdeconfig_compiler/tests/test6main.cpp (renamed from tdecore/kconfig_compiler/tests/test6main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test7.cpp.ref31
-rw-r--r--tdecore/tdeconfig_compiler/tests/test7.h.ref93
-rw-r--r--tdecore/tdeconfig_compiler/tests/test7.kcfg (renamed from tdecore/kconfig_compiler/tests/test7.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test7.kcfgc11
-rw-r--r--tdecore/tdeconfig_compiler/tests/test7main.cpp (renamed from tdecore/kconfig_compiler/tests/test7main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8a.cpp.ref22
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8a.h.ref61
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8a.kcfg (renamed from tdecore/kconfig_compiler/tests/test8a.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8a.kcfgc (renamed from tdecore/kconfig_compiler/tests/test8a.kcfgc)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8b.cpp.ref46
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8b.h.ref96
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8b.kcfg (renamed from tdecore/kconfig_compiler/tests/test8b.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8b.kcfgc (renamed from tdecore/kconfig_compiler/tests/test8b.kcfgc)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test8main.cpp (renamed from tdecore/kconfig_compiler/tests/test8main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test9.cpp.ref35
-rw-r--r--tdecore/tdeconfig_compiler/tests/test9.h.ref82
-rw-r--r--tdecore/tdeconfig_compiler/tests/test9.kcfg (renamed from tdecore/kconfig_compiler/tests/test9.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test9.kcfgc18
-rw-r--r--tdecore/tdeconfig_compiler/tests/test9main.cpp (renamed from tdecore/kconfig_compiler/tests/test9main.cpp)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test_dpointer.cpp.ref344
-rw-r--r--tdecore/tdeconfig_compiler/tests/test_dpointer.h.ref224
-rw-r--r--tdecore/tdeconfig_compiler/tests/test_dpointer.kcfg (renamed from tdecore/kconfig_compiler/tests/test_dpointer.kcfg)0
-rw-r--r--tdecore/tdeconfig_compiler/tests/test_dpointer.kcfgc11
-rw-r--r--tdecore/tdeconfig_compiler/tests/test_dpointer_main.cpp (renamed from tdecore/kconfig_compiler/tests/test_dpointer_main.cpp)0
-rw-r--r--tdecore/tdeconfigbackend.cpp1190
-rw-r--r--tdecore/tdeconfigbackend.h299
-rw-r--r--tdecore/tdeconfigbase.cpp1937
-rw-r--r--tdecore/tdeconfigbase.h2180
-rw-r--r--tdecore/tdeconfigdata.h (renamed from tdecore/kconfigdata.h)0
-rw-r--r--tdecore/tdeconfigdialogmanager.cpp398
-rw-r--r--tdecore/tdeconfigdialogmanager.h (renamed from tdecore/kconfigdialogmanager.h)0
-rw-r--r--tdecore/tdeconfigskeleton.cpp1207
-rw-r--r--tdecore/tdeconfigskeleton.h1230
-rw-r--r--tdecore/tdehardwaredevices.cpp2
-rw-r--r--tdecore/tdesycoca.cpp2
-rw-r--r--tdecore/tdesycoca.h4
-rw-r--r--tdecore/tests/Makefile.am12
-rw-r--r--tdecore/tests/kconfigtest.cpp162
-rw-r--r--tdecore/tests/kconfigtestgui.cpp200
-rw-r--r--tdecore/tests/kconfigtestgui.h72
-rw-r--r--tdecore/tests/ksimpleconfigtest.cpp2
-rw-r--r--tdecore/tests/kstddirstest.cpp2
-rw-r--r--tdecore/tests/kurltest.cpp10
-rw-r--r--tdecore/tests/tdeconfigtest.cpp162
-rw-r--r--tdecore/tests/tdeconfigtestgui.cpp200
-rw-r--r--tdecore/tests/tdeconfigtestgui.h72
-rw-r--r--tdefile-plugins/CMakeLists.txt (renamed from kfile-plugins/CMakeLists.txt)0
-rw-r--r--tdefile-plugins/elf/CMakeLists.txt42
-rw-r--r--tdefile-plugins/elf/tdefile_elf.cpp133
-rw-r--r--tdefile-plugins/elf/tdefile_elf.desktop66
-rw-r--r--tdefile-plugins/elf/tdefile_elf.h50
-rw-r--r--tdehtml/CMakeLists.txt10
-rw-r--r--tdehtml/Makefile.am2
-rw-r--r--tdehtml/css/CMakeLists.txt4
-rw-r--r--tdehtml/css/Makefile.am2
-rw-r--r--tdehtml/css/cssstyleselector.cpp2
-rw-r--r--tdehtml/dom/CMakeLists.txt2
-rw-r--r--tdehtml/dom/Makefile.am2
-rw-r--r--tdehtml/ecma/CMakeLists.txt6
-rw-r--r--tdehtml/ecma/Makefile.am2
-rw-r--r--tdehtml/ecma/kjs_debugwin.cpp4
-rw-r--r--tdehtml/ecma/kjs_navigator.cpp10
-rw-r--r--tdehtml/ecma/xmlhttprequest.cpp6
-rw-r--r--tdehtml/ecma/xmlhttprequest.h2
-rw-r--r--tdehtml/ecma/xmlserializer.h2
-rw-r--r--tdehtml/html/CMakeLists.txt8
-rw-r--r--tdehtml/html/Makefile.am2
-rw-r--r--tdehtml/html/html_formimpl.cpp2
-rw-r--r--tdehtml/java/CMakeLists.txt6
-rw-r--r--tdehtml/java/Makefile.am2
-rw-r--r--tdehtml/java/kjavaappletserver.cpp6
-rw-r--r--tdehtml/java/kjavaappletviewer.cpp4
-rw-r--r--tdehtml/java/kjavadownloader.cpp4
-rw-r--r--tdehtml/java/kjavaprocess.cpp2
-rw-r--r--tdehtml/misc/CMakeLists.txt6
-rw-r--r--tdehtml/misc/Makefile.am2
-rw-r--r--tdehtml/misc/helper.cpp2
-rw-r--r--tdehtml/misc/loader.cpp6
-rw-r--r--tdehtml/misc/loader.h2
-rw-r--r--tdehtml/rendering/CMakeLists.txt6
-rw-r--r--tdehtml/rendering/Makefile.am4
-rw-r--r--tdehtml/rendering/render_form.cpp2
-rw-r--r--tdehtml/tdehtml_ext.cpp4
-rw-r--r--tdehtml/tdehtml_ext.h2
-rw-r--r--tdehtml/tdehtml_iface.cc2
-rw-r--r--tdehtml/tdehtml_part.cpp12
-rw-r--r--tdehtml/tdehtml_run.cpp2
-rw-r--r--tdehtml/tdehtml_settings.cc2
-rw-r--r--tdehtml/tdehtmlimage.cpp2
-rw-r--r--tdehtml/tdemultipart/CMakeLists.txt4
-rw-r--r--tdehtml/tdemultipart/Makefile.am4
-rw-r--r--tdehtml/tdemultipart/tdemultipart.cpp2
-rw-r--r--tdehtml/test_regression.cpp2
-rw-r--r--tdehtml/testtdehtml.cpp2
-rw-r--r--tdehtml/xml/CMakeLists.txt4
-rw-r--r--tdehtml/xml/Makefile.am2
-rw-r--r--tdehtml/xml/dom_docimpl.cpp2
-rw-r--r--tdeio/CMakeLists.txt71
-rw-r--r--tdeio/DESIGN272
-rw-r--r--tdeio/DESIGN.krun35
-rw-r--r--tdeio/DESIGN.metadata (renamed from kio/DESIGN.metadata)0
-rw-r--r--tdeio/DESIGN.mimetypes (renamed from kio/DESIGN.mimetypes)0
-rw-r--r--tdeio/DESKTOP_ENTRY_STANDARD (renamed from kio/DESKTOP_ENTRY_STANDARD)0
-rw-r--r--tdeio/Mainpage.dox (renamed from kio/Mainpage.dox)0
-rw-r--r--tdeio/Makefile.am67
-rw-r--r--tdeio/application.desktop (renamed from kio/application.desktop)0
-rw-r--r--tdeio/bookmarks/CMakeLists.txt55
-rw-r--r--tdeio/bookmarks/Makefile.am40
-rw-r--r--tdeio/bookmarks/dptrtemplate.h (renamed from kio/bookmarks/dptrtemplate.h)0
-rw-r--r--tdeio/bookmarks/kbookmark.cc (renamed from kio/bookmarks/kbookmark.cc)0
-rw-r--r--tdeio/bookmarks/kbookmark.h (renamed from kio/bookmarks/kbookmark.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkbar.cc554
-rw-r--r--tdeio/bookmarks/kbookmarkbar.h (renamed from kio/bookmarks/kbookmarkbar.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkdombuilder.cc (renamed from kio/bookmarks/kbookmarkdombuilder.cc)0
-rw-r--r--tdeio/bookmarks/kbookmarkdombuilder.h (renamed from kio/bookmarks/kbookmarkdombuilder.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkdrag.cc (renamed from kio/bookmarks/kbookmarkdrag.cc)0
-rw-r--r--tdeio/bookmarks/kbookmarkdrag.h (renamed from kio/bookmarks/kbookmarkdrag.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkexporter.cc (renamed from kio/bookmarks/kbookmarkexporter.cc)0
-rw-r--r--tdeio/bookmarks/kbookmarkexporter.h (renamed from kio/bookmarks/kbookmarkexporter.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkimporter.cc101
-rw-r--r--tdeio/bookmarks/kbookmarkimporter.h (renamed from kio/bookmarks/kbookmarkimporter.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_crash.cc215
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_crash.h (renamed from kio/bookmarks/kbookmarkimporter_crash.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_ie.cc185
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_ie.h (renamed from kio/bookmarks/kbookmarkimporter_ie.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_kde1.cc156
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_kde1.h (renamed from kio/bookmarks/kbookmarkimporter_kde1.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_ns.cc243
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_ns.h (renamed from kio/bookmarks/kbookmarkimporter_ns.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_opera.cc170
-rw-r--r--tdeio/bookmarks/kbookmarkimporter_opera.h (renamed from kio/bookmarks/kbookmarkimporter_opera.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkmanager.cc (renamed from kio/bookmarks/kbookmarkmanager.cc)0
-rw-r--r--tdeio/bookmarks/kbookmarkmanager.h (renamed from kio/bookmarks/kbookmarkmanager.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkmenu.cc1187
-rw-r--r--tdeio/bookmarks/kbookmarkmenu.h (renamed from kio/bookmarks/kbookmarkmenu.h)0
-rw-r--r--tdeio/bookmarks/kbookmarkmenu_p.h (renamed from kio/bookmarks/kbookmarkmenu_p.h)0
-rw-r--r--tdeio/bookmarks/kbookmarknotifier.h (renamed from kio/bookmarks/kbookmarknotifier.h)0
-rw-r--r--tdeio/data.protocol71
-rw-r--r--tdeio/httpfilter/CMakeLists.txt32
-rw-r--r--tdeio/httpfilter/Makefile.am (renamed from kio/httpfilter/Makefile.am)0
-rw-r--r--tdeio/httpfilter/httpfilter.cc372
-rw-r--r--tdeio/httpfilter/httpfilter.h (renamed from kio/httpfilter/httpfilter.h)0
-rw-r--r--tdeio/kcomprfilter.desktop (renamed from kio/kcomprfilter.desktop)0
-rw-r--r--tdeio/kdatatool.desktop (renamed from kio/kdatatool.desktop)0
-rw-r--r--tdeio/kpasswdserver.desktop (renamed from kio/kpasswdserver.desktop)0
-rw-r--r--tdeio/kpasswdserver/CMakeLists.txt43
-rw-r--r--tdeio/kpasswdserver/DESIGN (renamed from kio/kpasswdserver/DESIGN)0
-rw-r--r--tdeio/kpasswdserver/Makefile.am15
-rw-r--r--tdeio/kpasswdserver/kpasswdserver.cpp715
-rw-r--r--tdeio/kpasswdserver/kpasswdserver.h118
-rw-r--r--tdeio/kscan.desktop (renamed from kio/kscan.desktop)0
-rw-r--r--tdeio/kssl/CMakeLists.txt (renamed from kio/kssl/CMakeLists.txt)0
-rw-r--r--tdeio/kssl/KPMG-CA-16389.0.DC80502.pdf (renamed from kio/kssl/KPMG-CA-16389.0.DC80502.pdf)bin91118 -> 91118 bytes
-rw-r--r--tdeio/kssl/Makefile.am (renamed from kio/kssl/Makefile.am)0
-rw-r--r--tdeio/kssl/README (renamed from kio/kssl/README)0
-rw-r--r--tdeio/kssl/SECURITY-HOLES (renamed from kio/kssl/SECURITY-HOLES)0
-rw-r--r--tdeio/kssl/TODO (renamed from kio/kssl/TODO)0
-rw-r--r--tdeio/kssl/configure.in.in7
-rw-r--r--tdeio/kssl/keygenwizard.ui (renamed from kio/kssl/keygenwizard.ui)0
-rw-r--r--tdeio/kssl/keygenwizard2.ui (renamed from kio/kssl/keygenwizard2.ui)0
-rw-r--r--tdeio/kssl/kopenssl.cc1601
-rw-r--r--tdeio/kssl/kopenssl.h (renamed from kio/kssl/kopenssl.h)0
-rw-r--r--tdeio/kssl/ksmimecrypto.cc (renamed from kio/kssl/ksmimecrypto.cc)0
-rw-r--r--tdeio/kssl/ksmimecrypto.h (renamed from kio/kssl/ksmimecrypto.h)0
-rw-r--r--tdeio/kssl/kssl.cc (renamed from kio/kssl/kssl.cc)0
-rw-r--r--tdeio/kssl/kssl.h (renamed from kio/kssl/kssl.h)0
-rw-r--r--tdeio/kssl/kssl/CMakeLists.txt (renamed from kio/kssl/kssl/CMakeLists.txt)0
-rw-r--r--tdeio/kssl/kssl/DigiCertAssuredIDRootCA.pem (renamed from kio/kssl/kssl/DigiCertAssuredIDRootCA.pem)0
-rw-r--r--tdeio/kssl/kssl/DigiCertGlobalRootCA.pem (renamed from kio/kssl/kssl/DigiCertGlobalRootCA.pem)0
-rw-r--r--tdeio/kssl/kssl/DigiCertHighAssuranceEVRootCA.pem (renamed from kio/kssl/kssl/DigiCertHighAssuranceEVRootCA.pem)0
-rw-r--r--tdeio/kssl/kssl/GeoTrust_Universal_CA.pem (renamed from kio/kssl/kssl/GeoTrust_Universal_CA.pem)0
-rw-r--r--tdeio/kssl/kssl/GeoTrust_Universal_CA2.pem (renamed from kio/kssl/kssl/GeoTrust_Universal_CA2.pem)0
-rw-r--r--tdeio/kssl/kssl/HOWTO30
-rw-r--r--tdeio/kssl/kssl/Makefile.am (renamed from kio/kssl/kssl/Makefile.am)0
-rw-r--r--tdeio/kssl/kssl/StartCom.pem (renamed from kio/kssl/kssl/StartCom.pem)0
-rw-r--r--tdeio/kssl/kssl/SwissSign-Gold-G2.pem (renamed from kio/kssl/kssl/SwissSign-Gold-G2.pem)0
-rw-r--r--tdeio/kssl/kssl/SwissSign-Platinum-G2.pem (renamed from kio/kssl/kssl/SwissSign-Platinum-G2.pem)0
-rw-r--r--tdeio/kssl/kssl/SwissSign-Silver-G2.pem (renamed from kio/kssl/kssl/SwissSign-Silver-G2.pem)0
-rw-r--r--tdeio/kssl/kssl/WiseKey.pem (renamed from kio/kssl/kssl/WiseKey.pem)0
-rw-r--r--tdeio/kssl/kssl/ac_offline_raiz_certicamara.pem (renamed from kio/kssl/kssl/ac_offline_raiz_certicamara.pem)0
-rw-r--r--tdeio/kssl/kssl/argedaten-root-ca-cert.pem (renamed from kio/kssl/kssl/argedaten-root-ca-cert.pem)0
-rw-r--r--tdeio/kssl/kssl/belgacom.pem (renamed from kio/kssl/kssl/belgacom.pem)0
-rw-r--r--tdeio/kssl/kssl/caroot/CMakeLists.txt (renamed from kio/kssl/kssl/caroot/CMakeLists.txt)0
-rw-r--r--tdeio/kssl/kssl/caroot/Makefile.am (renamed from kio/kssl/kssl/caroot/Makefile.am)0
-rw-r--r--tdeio/kssl/kssl/caroot/ca-bundle.crt (renamed from kio/kssl/kssl/caroot/ca-bundle.crt)0
-rwxr-xr-xtdeio/kssl/kssl/cert_bundle (renamed from kio/kssl/kssl/cert_bundle)0
-rw-r--r--tdeio/kssl/kssl/cert_extract.c (renamed from kio/kssl/kssl/cert_extract.c)0
-rw-r--r--tdeio/kssl/kssl/certbundle_Makefile (renamed from kio/kssl/kssl/certbundle_Makefile)0
-rwxr-xr-xtdeio/kssl/kssl/certkde (renamed from kio/kssl/kssl/certkde)0
-rw-r--r--tdeio/kssl/kssl/certum.pem (renamed from kio/kssl/kssl/certum.pem)0
-rw-r--r--tdeio/kssl/kssl/certum1.pem (renamed from kio/kssl/kssl/certum1.pem)0
-rw-r--r--tdeio/kssl/kssl/certum2.pem (renamed from kio/kssl/kssl/certum2.pem)0
-rw-r--r--tdeio/kssl/kssl/certum3.pem (renamed from kio/kssl/kssl/certum3.pem)0
-rw-r--r--tdeio/kssl/kssl/certum4.pem (renamed from kio/kssl/kssl/certum4.pem)0
-rw-r--r--tdeio/kssl/kssl/comodo1.pem (renamed from kio/kssl/kssl/comodo1.pem)0
-rw-r--r--tdeio/kssl/kssl/comodo2.pem (renamed from kio/kssl/kssl/comodo2.pem)0
-rw-r--r--tdeio/kssl/kssl/comodo3.pem (renamed from kio/kssl/kssl/comodo3.pem)0
-rw-r--r--tdeio/kssl/kssl/comodo4.pem (renamed from kio/kssl/kssl/comodo4.pem)0
-rw-r--r--tdeio/kssl/kssl/comodo5.pem (renamed from kio/kssl/kssl/comodo5.pem)0
-rw-r--r--tdeio/kssl/kssl/comodo6.pem (renamed from kio/kssl/kssl/comodo6.pem)0
-rw-r--r--tdeio/kssl/kssl/comodo7.pem (renamed from kio/kssl/kssl/comodo7.pem)0
-rw-r--r--tdeio/kssl/kssl/dfn-root-ca-cert.pem (renamed from kio/kssl/kssl/dfn-root-ca-cert.pem)0
-rw-r--r--tdeio/kssl/kssl/gd-class2-root.pem (renamed from kio/kssl/kssl/gd-class2-root.pem)0
-rw-r--r--tdeio/kssl/kssl/geotrust-global-1.pem (renamed from kio/kssl/kssl/geotrust-global-1.pem)0
-rw-r--r--tdeio/kssl/kssl/geotrust-global-2.pem (renamed from kio/kssl/kssl/geotrust-global-2.pem)0
-rw-r--r--tdeio/kssl/kssl/globalsign-root-r1.pem (renamed from kio/kssl/kssl/globalsign-root-r1.pem)0
-rw-r--r--tdeio/kssl/kssl/globalsign-root-r2.pem (renamed from kio/kssl/kssl/globalsign-root-r2.pem)0
-rw-r--r--tdeio/kssl/kssl/icpbrasil.pem (renamed from kio/kssl/kssl/icpbrasil.pem)0
-rw-r--r--tdeio/kssl/kssl/ipsservidores.pem (renamed from kio/kssl/kssl/ipsservidores.pem)0
-rw-r--r--tdeio/kssl/kssl/ksslcalist (renamed from kio/kssl/kssl/ksslcalist)0
-rw-r--r--tdeio/kssl/kssl/localcerts (renamed from kio/kssl/kssl/localcerts)0
-rwxr-xr-xtdeio/kssl/kssl/mergelocal (renamed from kio/kssl/kssl/mergelocal)0
-rw-r--r--tdeio/kssl/kssl/netlock1.pem (renamed from kio/kssl/kssl/netlock1.pem)0
-rw-r--r--tdeio/kssl/kssl/netlock2.pem (renamed from kio/kssl/kssl/netlock2.pem)0
-rw-r--r--tdeio/kssl/kssl/netlock3.pem (renamed from kio/kssl/kssl/netlock3.pem)0
-rw-r--r--tdeio/kssl/kssl/netlock4.pem (renamed from kio/kssl/kssl/netlock4.pem)0
-rw-r--r--tdeio/kssl/kssl/oces.pem (renamed from kio/kssl/kssl/oces.pem)0
-rw-r--r--tdeio/kssl/kssl/quovadis.pem (renamed from kio/kssl/kssl/quovadis.pem)0
-rw-r--r--tdeio/kssl/kssl/qvrca2.pem (renamed from kio/kssl/kssl/qvrca2.pem)0
-rw-r--r--tdeio/kssl/kssl/qvrca3.pem (renamed from kio/kssl/kssl/qvrca3.pem)0
-rw-r--r--tdeio/kssl/kssl/sf-class2-root.pem (renamed from kio/kssl/kssl/sf-class2-root.pem)0
-rw-r--r--tdeio/kssl/kssl/sonera1.pem (renamed from kio/kssl/kssl/sonera1.pem)0
-rw-r--r--tdeio/kssl/kssl/sonera2.pem (renamed from kio/kssl/kssl/sonera2.pem)0
-rw-r--r--tdeio/kssl/kssl/staatdernederlandenrotca.pem (renamed from kio/kssl/kssl/staatdernederlandenrotca.pem)0
-rw-r--r--tdeio/kssl/kssl/startcom.pem (renamed from kio/kssl/kssl/startcom.pem)0
-rw-r--r--tdeio/kssl/kssl/startssl.pem (renamed from kio/kssl/kssl/startssl.pem)0
-rw-r--r--tdeio/kssl/kssl/tcclass2-2011.pem (renamed from kio/kssl/kssl/tcclass2-2011.pem)0
-rw-r--r--tdeio/kssl/kssl/tcclass3-2011.pem (renamed from kio/kssl/kssl/tcclass3-2011.pem)0
-rw-r--r--tdeio/kssl/kssl/utn-network.pem (renamed from kio/kssl/kssl/utn-network.pem)0
-rw-r--r--tdeio/kssl/kssl/utn-sgc.pem (renamed from kio/kssl/kssl/utn-sgc.pem)0
-rw-r--r--tdeio/kssl/kssl/xgca.pem (renamed from kio/kssl/kssl/xgca.pem)0
-rw-r--r--tdeio/kssl/ksslall.h (renamed from kio/kssl/ksslall.h)0
-rw-r--r--tdeio/kssl/ksslcallback.c (renamed from kio/kssl/ksslcallback.c)0
-rw-r--r--tdeio/kssl/ksslcertchain.cc (renamed from kio/kssl/ksslcertchain.cc)0
-rw-r--r--tdeio/kssl/ksslcertchain.h (renamed from kio/kssl/ksslcertchain.h)0
-rw-r--r--tdeio/kssl/ksslcertdlg.cc (renamed from kio/kssl/ksslcertdlg.cc)0
-rw-r--r--tdeio/kssl/ksslcertdlg.h (renamed from kio/kssl/ksslcertdlg.h)0
-rw-r--r--tdeio/kssl/ksslcertificate.cc (renamed from kio/kssl/ksslcertificate.cc)0
-rw-r--r--tdeio/kssl/ksslcertificate.h (renamed from kio/kssl/ksslcertificate.h)0
-rw-r--r--tdeio/kssl/ksslcertificatecache.cc (renamed from kio/kssl/ksslcertificatecache.cc)0
-rw-r--r--tdeio/kssl/ksslcertificatecache.h (renamed from kio/kssl/ksslcertificatecache.h)0
-rw-r--r--tdeio/kssl/ksslcertificatefactory.cc (renamed from kio/kssl/ksslcertificatefactory.cc)0
-rw-r--r--tdeio/kssl/ksslcertificatefactory.h (renamed from kio/kssl/ksslcertificatefactory.h)0
-rw-r--r--tdeio/kssl/ksslcertificatehome.cc (renamed from kio/kssl/ksslcertificatehome.cc)0
-rw-r--r--tdeio/kssl/ksslcertificatehome.h (renamed from kio/kssl/ksslcertificatehome.h)0
-rw-r--r--tdeio/kssl/ksslconfig.h.cmake (renamed from kio/kssl/ksslconfig.h.cmake)0
-rw-r--r--tdeio/kssl/ksslconfig.h.in (renamed from kio/kssl/ksslconfig.h.in)0
-rw-r--r--tdeio/kssl/ksslconfig_win.h (renamed from kio/kssl/ksslconfig_win.h)0
-rw-r--r--tdeio/kssl/ksslconnectioninfo.cc (renamed from kio/kssl/ksslconnectioninfo.cc)0
-rw-r--r--tdeio/kssl/ksslconnectioninfo.h (renamed from kio/kssl/ksslconnectioninfo.h)0
-rw-r--r--tdeio/kssl/ksslcsessioncache.cc (renamed from kio/kssl/ksslcsessioncache.cc)0
-rw-r--r--tdeio/kssl/ksslcsessioncache.h (renamed from kio/kssl/ksslcsessioncache.h)0
-rw-r--r--tdeio/kssl/kssldefs.h (renamed from kio/kssl/kssldefs.h)0
-rw-r--r--tdeio/kssl/ksslinfodlg.cc463
-rw-r--r--tdeio/kssl/ksslinfodlg.h (renamed from kio/kssl/ksslinfodlg.h)0
-rw-r--r--tdeio/kssl/ksslkeygen.cc223
-rw-r--r--tdeio/kssl/ksslkeygen.h (renamed from kio/kssl/ksslkeygen.h)0
-rw-r--r--tdeio/kssl/ksslpeerinfo.cc (renamed from kio/kssl/ksslpeerinfo.cc)0
-rw-r--r--tdeio/kssl/ksslpeerinfo.h (renamed from kio/kssl/ksslpeerinfo.h)0
-rw-r--r--tdeio/kssl/ksslpemcallback.cc (renamed from kio/kssl/ksslpemcallback.cc)0
-rw-r--r--tdeio/kssl/ksslpemcallback.h (renamed from kio/kssl/ksslpemcallback.h)0
-rw-r--r--tdeio/kssl/ksslpkcs12.cc (renamed from kio/kssl/ksslpkcs12.cc)0
-rw-r--r--tdeio/kssl/ksslpkcs12.h (renamed from kio/kssl/ksslpkcs12.h)0
-rw-r--r--tdeio/kssl/ksslpkcs7.cc (renamed from kio/kssl/ksslpkcs7.cc)0
-rw-r--r--tdeio/kssl/ksslpkcs7.h (renamed from kio/kssl/ksslpkcs7.h)0
-rw-r--r--tdeio/kssl/ksslsession.cc (renamed from kio/kssl/ksslsession.cc)0
-rw-r--r--tdeio/kssl/ksslsession.h (renamed from kio/kssl/ksslsession.h)0
-rw-r--r--tdeio/kssl/ksslsettings.cc (renamed from kio/kssl/ksslsettings.cc)0
-rw-r--r--tdeio/kssl/ksslsettings.h224
-rw-r--r--tdeio/kssl/ksslsigners.cc (renamed from kio/kssl/ksslsigners.cc)0
-rw-r--r--tdeio/kssl/ksslsigners.h (renamed from kio/kssl/ksslsigners.h)0
-rw-r--r--tdeio/kssl/ksslutils.cc (renamed from kio/kssl/ksslutils.cc)0
-rw-r--r--tdeio/kssl/ksslutils.h (renamed from kio/kssl/ksslutils.h)0
-rw-r--r--tdeio/kssl/ksslx509map.cc (renamed from kio/kssl/ksslx509map.cc)0
-rw-r--r--tdeio/kssl/ksslx509map.h (renamed from kio/kssl/ksslx509map.h)0
-rw-r--r--tdeio/kssl/ksslx509v3.cc (renamed from kio/kssl/ksslx509v3.cc)0
-rw-r--r--tdeio/kssl/ksslx509v3.h (renamed from kio/kssl/ksslx509v3.h)0
-rw-r--r--tdeio/kurifilterplugin.desktop (renamed from kio/kurifilterplugin.desktop)0
-rw-r--r--tdeio/magic (renamed from kio/magic)0
-rw-r--r--tdeio/misc/CMakeLists.txt100
-rw-r--r--tdeio/misc/Makefile.am60
-rwxr-xr-xtdeio/misc/fileshareset (renamed from kio/misc/fileshareset)0
-rw-r--r--tdeio/misc/kpac/CMakeLists.txt66
-rw-r--r--tdeio/misc/kpac/Makefile.am (renamed from kio/misc/kpac/Makefile.am)0
-rw-r--r--tdeio/misc/kpac/README (renamed from kio/misc/kpac/README)0
-rw-r--r--tdeio/misc/kpac/README.wpad (renamed from kio/misc/kpac/README.wpad)0
-rw-r--r--tdeio/misc/kpac/TODO (renamed from kio/misc/kpac/TODO)0
-rw-r--r--tdeio/misc/kpac/configure.in.in (renamed from kio/misc/kpac/configure.in.in)0
-rw-r--r--tdeio/misc/kpac/dhcp.h (renamed from kio/misc/kpac/dhcp.h)0
-rw-r--r--tdeio/misc/kpac/discovery.cpp (renamed from kio/misc/kpac/discovery.cpp)0
-rw-r--r--tdeio/misc/kpac/discovery.h (renamed from kio/misc/kpac/discovery.h)0
-rw-r--r--tdeio/misc/kpac/downloader.cpp89
-rw-r--r--tdeio/misc/kpac/downloader.h (renamed from kio/misc/kpac/downloader.h)0
-rw-r--r--tdeio/misc/kpac/eventsrc (renamed from kio/misc/kpac/eventsrc)0
-rw-r--r--tdeio/misc/kpac/kpac_dhcp_helper.c (renamed from kio/misc/kpac/kpac_dhcp_helper.c)0
-rw-r--r--tdeio/misc/kpac/kpactest.pac (renamed from kio/misc/kpac/kpactest.pac)0
-rw-r--r--tdeio/misc/kpac/proxyscout.cpp (renamed from kio/misc/kpac/proxyscout.cpp)0
-rw-r--r--tdeio/misc/kpac/proxyscout.desktop (renamed from kio/misc/kpac/proxyscout.desktop)0
-rw-r--r--tdeio/misc/kpac/proxyscout.h (renamed from kio/misc/kpac/proxyscout.h)0
-rw-r--r--tdeio/misc/kpac/script.cpp (renamed from kio/misc/kpac/script.cpp)0
-rw-r--r--tdeio/misc/kpac/script.h (renamed from kio/misc/kpac/script.h)0
-rw-r--r--tdeio/misc/kssld/CMakeLists.txt47
-rw-r--r--tdeio/misc/kssld/Makefile.am33
-rw-r--r--tdeio/misc/kssld/kssld.cpp1027
-rw-r--r--tdeio/misc/kssld/kssld.desktop (renamed from kio/misc/kssld/kssld.desktop)0
-rw-r--r--tdeio/misc/kssld/kssld.h (renamed from kio/misc/kssld/kssld.h)0
-rw-r--r--tdeio/misc/mms.protocol (renamed from kio/misc/mms.protocol)0
-rw-r--r--tdeio/misc/mmst.protocol (renamed from kio/misc/mmst.protocol)0
-rw-r--r--tdeio/misc/mmsu.protocol (renamed from kio/misc/mmsu.protocol)0
-rw-r--r--tdeio/misc/pnm.protocol (renamed from kio/misc/pnm.protocol)0
-rw-r--r--tdeio/misc/rlogin.protocol13
-rw-r--r--tdeio/misc/rtsp.protocol (renamed from kio/misc/rtsp.protocol)0
-rw-r--r--tdeio/misc/rtspt.protocol (renamed from kio/misc/rtspt.protocol)0
-rw-r--r--tdeio/misc/rtspu.protocol (renamed from kio/misc/rtspu.protocol)0
-rw-r--r--tdeio/misc/ssh.protocol13
-rw-r--r--tdeio/misc/tdefile/CMakeLists.txt39
-rw-r--r--tdeio/misc/tdefile/Makefile.am10
-rw-r--r--tdeio/misc/tdefile/README (renamed from kio/misc/kfile/README)0
-rw-r--r--tdeio/misc/tdefile/fileprops.cpp480
-rw-r--r--tdeio/misc/tdefile/fileprops.h74
-rw-r--r--tdeio/misc/tdeio_uiserver.desktop100
-rw-r--r--tdeio/misc/tdemailservice.cpp45
-rw-r--r--tdeio/misc/tdemailservice.protocol15
-rw-r--r--tdeio/misc/tdentlm/CMakeLists.txt43
-rw-r--r--tdeio/misc/tdentlm/Makefile.am12
-rw-r--r--tdeio/misc/tdentlm/des.cpp (renamed from kio/misc/tdentlm/des.cpp)0
-rw-r--r--tdeio/misc/tdentlm/des.h (renamed from kio/misc/tdentlm/des.h)0
-rw-r--r--tdeio/misc/tdentlm/kswap.h (renamed from kio/misc/tdentlm/kswap.h)0
-rw-r--r--tdeio/misc/tdentlm/tdentlm.cpp (renamed from kio/misc/tdentlm/tdentlm.cpp)0
-rw-r--r--tdeio/misc/tdentlm/tdentlm.h (renamed from kio/misc/tdentlm/tdentlm.h)0
-rw-r--r--tdeio/misc/tdesasl/CMakeLists.txt42
-rw-r--r--tdeio/misc/tdesasl/Makefile.am12
-rw-r--r--tdeio/misc/tdesasl/tdesasl.cpp (renamed from kio/misc/tdesasl/tdesasl.cpp)0
-rw-r--r--tdeio/misc/tdesasl/tdesasl.h (renamed from kio/misc/tdesasl/tdesasl.h)0
-rw-r--r--tdeio/misc/tdesendbugmail/CMakeLists.txt37
-rw-r--r--tdeio/misc/tdesendbugmail/Makefile.am26
-rw-r--r--tdeio/misc/tdesendbugmail/main.cpp142
-rw-r--r--tdeio/misc/tdesendbugmail/main.h (renamed from kio/misc/ksendbugmail/main.h)0
-rw-r--r--tdeio/misc/tdesendbugmail/smtp.cpp (renamed from kio/misc/ksendbugmail/smtp.cpp)0
-rw-r--r--tdeio/misc/tdesendbugmail/smtp.h (renamed from kio/misc/ksendbugmail/smtp.h)0
-rw-r--r--tdeio/misc/tdetelnetservice.cpp112
-rw-r--r--tdeio/misc/tdewalletd/CMakeLists.txt49
-rw-r--r--tdeio/misc/tdewalletd/Makefile.am (renamed from kio/misc/tdewalletd/Makefile.am)0
-rw-r--r--tdeio/misc/tdewalletd/kbetterthankdialogbase.ui (renamed from kio/misc/tdewalletd/kbetterthankdialogbase.ui)0
-rw-r--r--tdeio/misc/tdewalletd/kbetterthankdialogbase.ui.h (renamed from kio/misc/tdewalletd/kbetterthankdialogbase.ui.h)0
-rw-r--r--tdeio/misc/tdewalletd/ktimeout.cpp (renamed from kio/misc/tdewalletd/ktimeout.cpp)0
-rw-r--r--tdeio/misc/tdewalletd/ktimeout.h (renamed from kio/misc/tdewalletd/ktimeout.h)0
-rw-r--r--tdeio/misc/tdewalletd/tdewalletd.cpp1514
-rw-r--r--tdeio/misc/tdewalletd/tdewalletd.desktop (renamed from kio/misc/tdewalletd/tdewalletd.desktop)0
-rw-r--r--tdeio/misc/tdewalletd/tdewalletd.h (renamed from kio/misc/tdewalletd/tdewalletd.h)0
-rw-r--r--tdeio/misc/tdewalletd/tdewalletwizard.ui (renamed from kio/misc/tdewalletd/tdewalletwizard.ui)0
-rw-r--r--tdeio/misc/tdewalletd/tdewalletwizard.ui.h (renamed from kio/misc/tdewalletd/tdewalletwizard.ui.h)0
-rw-r--r--tdeio/misc/telnet.protocol13
-rw-r--r--tdeio/misc/uiserver.cpp1413
-rw-r--r--tdeio/misc/uiserver.h430
-rw-r--r--tdeio/pics/CMakeLists.txt14
-rw-r--r--tdeio/pics/Makefile.am3
-rw-r--r--tdeio/pics/cr16-app-tdeio_uiserver.png (renamed from kio/pics/cr16-app-kio_uiserver.png)bin838 -> 838 bytes
-rwxr-xr-xtdeio/proxytype.pl (renamed from kio/proxytype.pl)0
-rw-r--r--tdeio/renamedlgplugin.desktop (renamed from kio/renamedlgplugin.desktop)0
-rw-r--r--tdeio/tdecmodule.desktop (renamed from kio/tdecmodule.desktop)0
-rw-r--r--tdeio/tdefile/CMakeLists.txt76
-rw-r--r--tdeio/tdefile/ChangeLog725
-rw-r--r--tdeio/tdefile/Makefile.am78
-rw-r--r--tdeio/tdefile/NOTES100
-rw-r--r--tdeio/tdefile/TODO (renamed from kio/kfile/TODO)0
-rw-r--r--tdeio/tdefile/config-tdefile.h32
-rw-r--r--tdeio/tdefile/images.h (renamed from kio/kfile/images.h)0
-rw-r--r--tdeio/tdefile/kacleditwidget.cpp1054
-rw-r--r--tdeio/tdefile/kacleditwidget.h65
-rw-r--r--tdeio/tdefile/kacleditwidget_p.h206
-rw-r--r--tdeio/tdefile/kcombiview.cpp371
-rw-r--r--tdeio/tdefile/kcombiview.h133
-rw-r--r--tdeio/tdefile/kcustommenueditor.cpp242
-rw-r--r--tdeio/tdefile/kcustommenueditor.h (renamed from kio/kfile/kcustommenueditor.h)0
-rw-r--r--tdeio/tdefile/kdiroperator.cpp1740
-rw-r--r--tdeio/tdefile/kdiroperator.h950
-rw-r--r--tdeio/tdefile/kdirselectdialog.cpp481
-rw-r--r--tdeio/tdefile/kdirselectdialog.h (renamed from kio/kfile/kdirselectdialog.h)0
-rw-r--r--tdeio/tdefile/kdirsize.cpp166
-rw-r--r--tdeio/tdefile/kdirsize.h106
-rw-r--r--tdeio/tdefile/kdiskfreesp.cpp169
-rw-r--r--tdeio/tdefile/kdiskfreesp.h (renamed from kio/kfile/kdiskfreesp.h)0
-rw-r--r--tdeio/tdefile/kencodingfiledialog.cpp223
-rw-r--r--tdeio/tdefile/kencodingfiledialog.h313
-rw-r--r--tdeio/tdefile/kicondialog.cpp772
-rw-r--r--tdeio/tdefile/kicondialog.h350
-rw-r--r--tdeio/tdefile/kimagefilepreview.cpp187
-rw-r--r--tdeio/tdefile/kimagefilepreview.h (renamed from kio/kfile/kimagefilepreview.h)0
-rw-r--r--tdeio/tdefile/kmetaprops.cpp268
-rw-r--r--tdeio/tdefile/kmetaprops.h (renamed from kio/kfile/kmetaprops.h)0
-rw-r--r--tdeio/tdefile/knotifydialog.cpp1191
-rw-r--r--tdeio/tdefile/knotifydialog.h (renamed from kio/kfile/knotifydialog.h)0
-rw-r--r--tdeio/tdefile/knotifywidgetbase.ui (renamed from kio/kfile/knotifywidgetbase.ui)0
-rw-r--r--tdeio/tdefile/kopenwith.cpp (renamed from kio/kfile/kopenwith.cpp)0
-rw-r--r--tdeio/tdefile/kopenwith.h (renamed from kio/kfile/kopenwith.h)0
-rw-r--r--tdeio/tdefile/kopenwith_p.h (renamed from kio/kfile/kopenwith_p.h)0
-rw-r--r--tdeio/tdefile/kpreviewprops.cpp89
-rw-r--r--tdeio/tdefile/kpreviewprops.h (renamed from kio/kfile/kpreviewprops.h)0
-rw-r--r--tdeio/tdefile/kpreviewwidgetbase.cpp (renamed from kio/kfile/kpreviewwidgetbase.cpp)0
-rw-r--r--tdeio/tdefile/kpreviewwidgetbase.h (renamed from kio/kfile/kpreviewwidgetbase.h)0
-rw-r--r--tdeio/tdefile/kpropertiesdesktopadvbase.ui (renamed from kio/kfile/kpropertiesdesktopadvbase.ui)0
-rw-r--r--tdeio/tdefile/kpropertiesdesktopbase.ui (renamed from kio/kfile/kpropertiesdesktopbase.ui)0
-rw-r--r--tdeio/tdefile/kpropertiesdialog.cpp4170
-rw-r--r--tdeio/tdefile/kpropertiesdialog.h918
-rw-r--r--tdeio/tdefile/kpropertiesmimetypebase.ui (renamed from kio/kfile/kpropertiesmimetypebase.ui)0
-rw-r--r--tdeio/tdefile/kpropsdlg.h (renamed from kio/kfile/kpropsdlg.h)0
-rw-r--r--tdeio/tdefile/kpropsdlgplugin.desktop (renamed from kio/kfile/kpropsdlgplugin.desktop)0
-rw-r--r--tdeio/tdefile/krecentdirs.cpp (renamed from kio/kfile/krecentdirs.cpp)0
-rw-r--r--tdeio/tdefile/krecentdirs.h (renamed from kio/kfile/krecentdirs.h)0
-rw-r--r--tdeio/tdefile/krecentdocument.cpp (renamed from kio/kfile/krecentdocument.cpp)0
-rw-r--r--tdeio/tdefile/krecentdocument.h (renamed from kio/kfile/krecentdocument.h)0
-rw-r--r--tdeio/tdefile/kurlbar.cpp1049
-rw-r--r--tdeio/tdefile/kurlbar.h (renamed from kio/kfile/kurlbar.h)0
-rw-r--r--tdeio/tdefile/kurlcombobox.cpp (renamed from kio/kfile/kurlcombobox.cpp)0
-rw-r--r--tdeio/tdefile/kurlcombobox.h (renamed from kio/kfile/kurlcombobox.h)0
-rw-r--r--tdeio/tdefile/kurlrequester.cpp430
-rw-r--r--tdeio/tdefile/kurlrequester.h301
-rw-r--r--tdeio/tdefile/kurlrequesterdlg.cpp135
-rw-r--r--tdeio/tdefile/kurlrequesterdlg.h (renamed from kio/kfile/kurlrequesterdlg.h)0
-rw-r--r--tdeio/tdefile/tdefile.h129
-rw-r--r--tdeio/tdefile/tdefilebookmarkhandler.cpp81
-rw-r--r--tdeio/tdefile/tdefilebookmarkhandler.h (renamed from kio/kfile/kfilebookmarkhandler.h)0
-rw-r--r--tdeio/tdefile/tdefiledetailview.cpp686
-rw-r--r--tdeio/tdefile/tdefiledetailview.h219
-rw-r--r--tdeio/tdefile/tdefiledialog.cpp2380
-rw-r--r--tdeio/tdefile/tdefiledialog.h989
-rw-r--r--tdeio/tdefile/tdefilefiltercombo.cpp203
-rw-r--r--tdeio/tdefile/tdefilefiltercombo.h (renamed from kio/kfile/kfilefiltercombo.h)0
-rw-r--r--tdeio/tdefile/tdefileiconview.cpp943
-rw-r--r--tdeio/tdefile/tdefileiconview.h267
-rw-r--r--tdeio/tdefile/tdefilemetainfowidget.cpp375
-rw-r--r--tdeio/tdefile/tdefilemetainfowidget.h95
-rw-r--r--tdeio/tdefile/tdefilemetapreview.cpp196
-rw-r--r--tdeio/tdefile/tdefilemetapreview.h (renamed from kio/kfile/kfilemetapreview.h)0
-rw-r--r--tdeio/tdefile/tdefilepreview.cpp279
-rw-r--r--tdeio/tdefile/tdefilepreview.h122
-rw-r--r--tdeio/tdefile/tdefilesharedlg.cpp325
-rw-r--r--tdeio/tdefile/tdefilesharedlg.h70
-rw-r--r--tdeio/tdefile/tdefilespeedbar.cpp147
-rw-r--r--tdeio/tdefile/tdefilespeedbar.h (renamed from kio/kfile/kfilespeedbar.h)0
-rw-r--r--tdeio/tdefile/tdefiletreebranch.cpp528
-rw-r--r--tdeio/tdefile/tdefiletreebranch.h242
-rw-r--r--tdeio/tdefile/tdefiletreeview.cpp677
-rw-r--r--tdeio/tdefile/tdefiletreeview.h273
-rw-r--r--tdeio/tdefile/tdefiletreeviewitem.cpp83
-rw-r--r--tdeio/tdefile/tdefiletreeviewitem.h106
-rw-r--r--tdeio/tdefile/tdefileview.cpp429
-rw-r--r--tdeio/tdefile/tdefileview.h444
-rw-r--r--tdeio/tdefile/tests/Makefile.am41
-rw-r--r--tdeio/tdefile/tests/kcustommenueditortest.cpp19
-rw-r--r--tdeio/tdefile/tests/kdirselectdialogtest.cpp (renamed from kio/kfile/tests/kdirselectdialogtest.cpp)0
-rw-r--r--tdeio/tdefile/tests/kfdtest.cpp34
-rw-r--r--tdeio/tdefile/tests/kfdtest.h (renamed from kio/kfile/tests/kfdtest.h)0
-rw-r--r--tdeio/tdefile/tests/kfstest.cpp183
-rw-r--r--tdeio/tdefile/tests/kicondialogtest.cpp (renamed from kio/kfile/tests/kicondialogtest.cpp)0
-rw-r--r--tdeio/tdefile/tests/knotifytest.cpp (renamed from kio/kfile/tests/knotifytest.cpp)0
-rw-r--r--tdeio/tdefile/tests/kopenwithtest.cpp (renamed from kio/kfile/tests/kopenwithtest.cpp)0
-rw-r--r--tdeio/tdefile/tests/kurlrequestertest.cpp (renamed from kio/kfile/tests/kurlrequestertest.cpp)0
-rw-r--r--tdeio/tdefile/tests/tdefiletreeviewtest.cpp165
-rw-r--r--tdeio/tdefile/tests/tdefiletreeviewtest.h (renamed from kio/kfile/tests/kfiletreeviewtest.h)0
-rw-r--r--tdeio/tdefileplugin.desktop (renamed from kio/kfileplugin.desktop)0
-rw-r--r--tdeio/tdeio/CMakeLists.txt138
-rw-r--r--tdeio/tdeio/KFILEMETAINFO_ISSUES (renamed from kio/kio/KFILEMETAINFO_ISSUES)0
-rw-r--r--tdeio/tdeio/Makefile.am129
-rw-r--r--tdeio/tdeio/authinfo.cpp332
-rw-r--r--tdeio/tdeio/authinfo.h (renamed from kio/kio/authinfo.h)0
-rw-r--r--tdeio/tdeio/chmodjob.cpp258
-rw-r--r--tdeio/tdeio/chmodjob.h109
-rw-r--r--tdeio/tdeio/configure.in.in (renamed from kio/kio/configure.in.in)0
-rw-r--r--tdeio/tdeio/connection.cpp273
-rw-r--r--tdeio/tdeio/connection.h (renamed from kio/kio/connection.h)0
-rw-r--r--tdeio/tdeio/dataprotocol.cpp339
-rw-r--r--tdeio/tdeio/dataprotocol.h71
-rw-r--r--tdeio/tdeio/dataslave.cpp (renamed from kio/kio/dataslave.cpp)0
-rw-r--r--tdeio/tdeio/dataslave.h126
-rw-r--r--tdeio/tdeio/davjob.cpp142
-rw-r--r--tdeio/tdeio/davjob.h127
-rw-r--r--tdeio/tdeio/defaultprogress.cpp507
-rw-r--r--tdeio/tdeio/defaultprogress.h164
-rw-r--r--tdeio/tdeio/forwardingslavebase.cpp475
-rw-r--r--tdeio/tdeio/forwardingslavebase.h204
-rw-r--r--tdeio/tdeio/global.cpp2009
-rw-r--r--tdeio/tdeio/global.h (renamed from kio/kio/global.h)0
-rw-r--r--tdeio/tdeio/http_slave_defaults.h (renamed from kio/kio/http_slave_defaults.h)0
-rw-r--r--tdeio/tdeio/ioslave_defaults.h (renamed from kio/kio/ioslave_defaults.h)0
-rw-r--r--tdeio/tdeio/job.cpp4814
-rw-r--r--tdeio/tdeio/job.h532
-rw-r--r--tdeio/tdeio/jobclasses.h1909
-rw-r--r--tdeio/tdeio/kacl.cpp (renamed from kio/kio/kacl.cpp)0
-rw-r--r--tdeio/tdeio/kacl.h207
-rw-r--r--tdeio/tdeio/kar.cpp (renamed from kio/kio/kar.cpp)0
-rw-r--r--tdeio/tdeio/kar.h (renamed from kio/kio/kar.h)0
-rw-r--r--tdeio/tdeio/karchive.cpp (renamed from kio/kio/karchive.cpp)0
-rw-r--r--tdeio/tdeio/karchive.h (renamed from kio/kio/karchive.h)0
-rw-r--r--tdeio/tdeio/kautomount.cpp117
-rw-r--r--tdeio/tdeio/kautomount.h (renamed from kio/kio/kautomount.h)0
-rw-r--r--tdeio/tdeio/kdatatool.cpp (renamed from kio/kio/kdatatool.cpp)0
-rw-r--r--tdeio/tdeio/kdatatool.h (renamed from kio/kio/kdatatool.h)0
-rw-r--r--tdeio/tdeio/kdcopservicestarter.cpp (renamed from kio/kio/kdcopservicestarter.cpp)0
-rw-r--r--tdeio/tdeio/kdcopservicestarter.h (renamed from kio/kio/kdcopservicestarter.h)0
-rw-r--r--tdeio/tdeio/kdirlister.cpp2538
-rw-r--r--tdeio/tdeio/kdirlister.h634
-rw-r--r--tdeio/tdeio/kdirlister_p.h358
-rw-r--r--tdeio/tdeio/kdirnotify.cpp (renamed from kio/kio/kdirnotify.cpp)0
-rw-r--r--tdeio/tdeio/kdirnotify.h (renamed from kio/kio/kdirnotify.h)0
-rw-r--r--tdeio/tdeio/kdirnotify_stub.cpp (renamed from kio/kio/kdirnotify_stub.cpp)0
-rw-r--r--tdeio/tdeio/kdirnotify_stub.h (renamed from kio/kio/kdirnotify_stub.h)0
-rw-r--r--tdeio/tdeio/kdirwatch.cpp1774
-rw-r--r--tdeio/tdeio/kdirwatch.h (renamed from kio/kio/kdirwatch.h)0
-rw-r--r--tdeio/tdeio/kdirwatch_p.h (renamed from kio/kio/kdirwatch_p.h)0
-rw-r--r--tdeio/tdeio/kemailsettings.cpp272
-rw-r--r--tdeio/tdeio/kemailsettings.h (renamed from kio/kio/kemailsettings.h)0
-rw-r--r--tdeio/tdeio/kfilterbase.cpp (renamed from kio/kio/kfilterbase.cpp)0
-rw-r--r--tdeio/tdeio/kfilterbase.h (renamed from kio/kio/kfilterbase.h)0
-rw-r--r--tdeio/tdeio/kfilterdev.cpp (renamed from kio/kio/kfilterdev.cpp)0
-rw-r--r--tdeio/tdeio/kfilterdev.h (renamed from kio/kio/kfilterdev.h)0
-rw-r--r--tdeio/tdeio/kimageio.cpp (renamed from kio/kio/kimageio.cpp)0
-rw-r--r--tdeio/tdeio/kimageio.h (renamed from kio/kio/kimageio.h)0
-rw-r--r--tdeio/tdeio/kimageiofactory.h (renamed from kio/kio/kimageiofactory.h)0
-rw-r--r--tdeio/tdeio/klimitediodevice.h (renamed from kio/kio/klimitediodevice.h)0
-rw-r--r--tdeio/tdeio/kmdbase.h (renamed from kio/kio/kmdbase.h)0
-rw-r--r--tdeio/tdeio/kmessageboxwrapper.h (renamed from kio/kio/kmessageboxwrapper.h)0
-rw-r--r--tdeio/tdeio/kmimemagic.cpp (renamed from kio/kio/kmimemagic.cpp)0
-rw-r--r--tdeio/tdeio/kmimemagic.h (renamed from kio/kio/kmimemagic.h)0
-rw-r--r--tdeio/tdeio/kmimetype.cpp1172
-rw-r--r--tdeio/tdeio/kmimetype.h (renamed from kio/kio/kmimetype.h)0
-rw-r--r--tdeio/tdeio/kmimetypechooser.cpp298
-rw-r--r--tdeio/tdeio/kmimetypechooser.h (renamed from kio/kio/kmimetypechooser.h)0
-rw-r--r--tdeio/tdeio/kmimetyperesolver.h (renamed from kio/kio/kmimetyperesolver.h)0
-rw-r--r--tdeio/tdeio/knfsshare.cpp219
-rw-r--r--tdeio/tdeio/knfsshare.h (renamed from kio/kio/knfsshare.h)0
-rw-r--r--tdeio/tdeio/kprotocolinfo.cpp (renamed from kio/kio/kprotocolinfo.cpp)0
-rw-r--r--tdeio/tdeio/kprotocolinfo.h688
-rw-r--r--tdeio/tdeio/kprotocolmanager.cpp534
-rw-r--r--tdeio/tdeio/kprotocolmanager.h389
-rw-r--r--tdeio/tdeio/kremoteencoding.cpp (renamed from kio/kio/kremoteencoding.cpp)0
-rw-r--r--tdeio/tdeio/kremoteencoding.h (renamed from kio/kio/kremoteencoding.h)0
-rw-r--r--tdeio/tdeio/krun.cpp1574
-rw-r--r--tdeio/tdeio/krun.h (renamed from kio/kio/krun.h)0
-rw-r--r--tdeio/tdeio/ksambashare.cpp239
-rw-r--r--tdeio/tdeio/ksambashare.h (renamed from kio/kio/ksambashare.h)0
-rw-r--r--tdeio/tdeio/kscan.cpp (renamed from kio/kio/kscan.cpp)0
-rw-r--r--tdeio/tdeio/kscan.h (renamed from kio/kio/kscan.h)0
-rw-r--r--tdeio/tdeio/kservice.cpp934
-rw-r--r--tdeio/tdeio/kservice.h (renamed from kio/kio/kservice.h)0
-rw-r--r--tdeio/tdeio/kservice_p.h (renamed from kio/kio/kservice_p.h)0
-rw-r--r--tdeio/tdeio/kservicefactory.cpp (renamed from kio/kio/kservicefactory.cpp)0
-rw-r--r--tdeio/tdeio/kservicefactory.h (renamed from kio/kio/kservicefactory.h)0
-rw-r--r--tdeio/tdeio/kservicegroup.cpp (renamed from kio/kio/kservicegroup.cpp)0
-rw-r--r--tdeio/tdeio/kservicegroup.h (renamed from kio/kio/kservicegroup.h)0
-rw-r--r--tdeio/tdeio/kservicegroupfactory.cpp (renamed from kio/kio/kservicegroupfactory.cpp)0
-rw-r--r--tdeio/tdeio/kservicegroupfactory.h (renamed from kio/kio/kservicegroupfactory.h)0
-rw-r--r--tdeio/tdeio/kservicetype.cpp (renamed from kio/kio/kservicetype.cpp)0
-rw-r--r--tdeio/tdeio/kservicetype.h (renamed from kio/kio/kservicetype.h)0
-rw-r--r--tdeio/tdeio/kservicetypefactory.cpp (renamed from kio/kio/kservicetypefactory.cpp)0
-rw-r--r--tdeio/tdeio/kservicetypefactory.h (renamed from kio/kio/kservicetypefactory.h)0
-rw-r--r--tdeio/tdeio/kshellcompletion.cpp (renamed from kio/kio/kshellcompletion.cpp)0
-rw-r--r--tdeio/tdeio/kshellcompletion.h (renamed from kio/kio/kshellcompletion.h)0
-rw-r--r--tdeio/tdeio/kshred.cpp (renamed from kio/kio/kshred.cpp)0
-rw-r--r--tdeio/tdeio/kshred.h156
-rw-r--r--tdeio/tdeio/ktar.cpp (renamed from kio/kio/ktar.cpp)0
-rw-r--r--tdeio/tdeio/ktar.h (renamed from kio/kio/ktar.h)0
-rw-r--r--tdeio/tdeio/ktrader.cpp (renamed from kio/kio/ktrader.cpp)0
-rw-r--r--tdeio/tdeio/ktrader.h295
-rw-r--r--tdeio/tdeio/ktraderparse.cpp (renamed from kio/kio/ktraderparse.cpp)0
-rw-r--r--tdeio/tdeio/ktraderparse.h (renamed from kio/kio/ktraderparse.h)0
-rw-r--r--tdeio/tdeio/ktraderparsetree.cpp (renamed from kio/kio/ktraderparsetree.cpp)0
-rw-r--r--tdeio/tdeio/ktraderparsetree.h (renamed from kio/kio/ktraderparsetree.h)0
-rw-r--r--tdeio/tdeio/kurifilter.cpp (renamed from kio/kio/kurifilter.cpp)0
-rw-r--r--tdeio/tdeio/kurifilter.h (renamed from kio/kio/kurifilter.h)0
-rw-r--r--tdeio/tdeio/kurlcompletion.cpp1604
-rw-r--r--tdeio/tdeio/kurlcompletion.h236
-rw-r--r--tdeio/tdeio/kurlpixmapprovider.cpp (renamed from kio/kio/kurlpixmapprovider.cpp)0
-rw-r--r--tdeio/tdeio/kurlpixmapprovider.h (renamed from kio/kio/kurlpixmapprovider.h)0
-rw-r--r--tdeio/tdeio/kuserprofile.cpp355
-rw-r--r--tdeio/tdeio/kuserprofile.h (renamed from kio/kio/kuserprofile.h)0
-rw-r--r--tdeio/tdeio/kzip.cpp1460
-rw-r--r--tdeio/tdeio/kzip.h284
-rw-r--r--tdeio/tdeio/lex.c (renamed from kio/kio/lex.c)0
-rw-r--r--tdeio/tdeio/lex.l (renamed from kio/kio/lex.l)0
-rw-r--r--tdeio/tdeio/metainfojob.cpp184
-rw-r--r--tdeio/tdeio/metainfojob.h119
-rw-r--r--tdeio/tdeio/netaccess.cpp536
-rw-r--r--tdeio/tdeio/netaccess.h540
-rw-r--r--tdeio/tdeio/observer.cpp417
-rw-r--r--tdeio/tdeio/observer.h213
-rw-r--r--tdeio/tdeio/passdlg.cpp367
-rw-r--r--tdeio/tdeio/passdlg.h (renamed from kio/kio/passdlg.h)0
-rw-r--r--tdeio/tdeio/paste.cpp308
-rw-r--r--tdeio/tdeio/paste.h (renamed from kio/kio/paste.h)0
-rw-r--r--tdeio/tdeio/pastedialog.cpp (renamed from kio/kio/pastedialog.cpp)0
-rw-r--r--tdeio/tdeio/pastedialog.h (renamed from kio/kio/pastedialog.h)0
-rw-r--r--tdeio/tdeio/posixacladdons.cpp (renamed from kio/kio/posixacladdons.cpp)0
-rw-r--r--tdeio/tdeio/posixacladdons.h (renamed from kio/kio/posixacladdons.h)0
-rw-r--r--tdeio/tdeio/previewjob.cpp597
-rw-r--r--tdeio/tdeio/previewjob.h182
-rw-r--r--tdeio/tdeio/progressbase.cpp (renamed from kio/kio/progressbase.cpp)0
-rw-r--r--tdeio/tdeio/progressbase.h271
-rw-r--r--tdeio/tdeio/renamedlg.cpp574
-rw-r--r--tdeio/tdeio/renamedlg.h153
-rw-r--r--tdeio/tdeio/renamedlgplugin.h59
-rw-r--r--tdeio/tdeio/scheduler.cpp922
-rw-r--r--tdeio/tdeio/scheduler.h364
-rw-r--r--tdeio/tdeio/sessiondata.cpp311
-rw-r--r--tdeio/tdeio/sessiondata.h67
-rw-r--r--tdeio/tdeio/skipdlg.cpp143
-rw-r--r--tdeio/tdeio/skipdlg.h (renamed from kio/kio/skipdlg.h)0
-rw-r--r--tdeio/tdeio/slave.cpp519
-rw-r--r--tdeio/tdeio/slave.h270
-rw-r--r--tdeio/tdeio/slavebase.cpp1315
-rw-r--r--tdeio/tdeio/slavebase.h847
-rw-r--r--tdeio/tdeio/slaveconfig.cpp225
-rw-r--r--tdeio/tdeio/slaveconfig.h106
-rw-r--r--tdeio/tdeio/slaveinterface.cpp550
-rw-r--r--tdeio/tdeio/slaveinterface.h290
-rw-r--r--tdeio/tdeio/statusbarprogress.cpp (renamed from kio/kio/statusbarprogress.cpp)0
-rw-r--r--tdeio/tdeio/statusbarprogress.h (renamed from kio/kio/statusbarprogress.h)0
-rw-r--r--tdeio/tdeio/tcpslavebase.cpp1343
-rw-r--r--tdeio/tdeio/tcpslavebase.h389
-rw-r--r--tdeio/tdeio/tdefilefilter.cpp134
-rw-r--r--tdeio/tdeio/tdefilefilter.h (renamed from kio/kio/kfilefilter.h)0
-rw-r--r--tdeio/tdeio/tdefileitem.cpp1202
-rw-r--r--tdeio/tdeio/tdefileitem.h671
-rw-r--r--tdeio/tdeio/tdefilemetainfo.cpp1859
-rw-r--r--tdeio/tdeio/tdefilemetainfo.h1738
-rw-r--r--tdeio/tdeio/tdefileshare.cpp346
-rw-r--r--tdeio/tdeio/tdefileshare.h165
-rw-r--r--tdeio/tdeio/tdelficon.cpp (renamed from kio/kio/tdelficon.cpp)0
-rw-r--r--tdeio/tdeio/tdelficon.h (renamed from kio/kio/tdelficon.h)0
-rw-r--r--tdeio/tdeio/thumbcreator.h124
-rw-r--r--tdeio/tdeio/yacc.c (renamed from kio/kio/yacc.c)0
-rw-r--r--tdeio/tdeio/yacc.h (renamed from kio/kio/yacc.h)0
-rw-r--r--tdeio/tdeio/yacc.y (renamed from kio/kio/yacc.y)0
-rw-r--r--tdeio/tdeioexec/CMakeLists.txt42
-rw-r--r--tdeio/tdeioexec/Makefile.am19
-rw-r--r--tdeio/tdeioexec/README (renamed from kio/kioexec/README)0
-rw-r--r--tdeio/tdeioexec/main.cpp294
-rw-r--r--tdeio/tdeioexec/main.h (renamed from kio/kioexec/main.h)0
-rw-r--r--tdeio/tdeioslave.upd18
-rw-r--r--tdeio/tests/CMakeLists.txt36
-rw-r--r--tdeio/tests/Makefile.am91
-rw-r--r--tdeio/tests/dataprotocoltest.cpp287
-rw-r--r--tdeio/tests/dummymeta.cpp (renamed from kio/tests/dummymeta.cpp)0
-rw-r--r--tdeio/tests/dummymeta.desktop (renamed from kio/tests/dummymeta.desktop)0
-rw-r--r--tdeio/tests/dummymeta.h20
-rw-r--r--tdeio/tests/getalltest.cpp (renamed from kio/tests/getalltest.cpp)0
-rw-r--r--tdeio/tests/jobtest.cpp613
-rw-r--r--tdeio/tests/jobtest.h79
-rw-r--r--tdeio/tests/kacltest.cpp309
-rw-r--r--tdeio/tests/kacltest.h (renamed from kio/tests/kacltest.h)0
-rw-r--r--tdeio/tests/kdcopcheck.cpp (renamed from kio/tests/kdcopcheck.cpp)0
-rw-r--r--tdeio/tests/kdcopcheck.h (renamed from kio/tests/kdcopcheck.h)0
-rw-r--r--tdeio/tests/kdefaultprogresstest.cpp39
-rw-r--r--tdeio/tests/kdirlistertest.cpp (renamed from kio/tests/kdirlistertest.cpp)0
-rw-r--r--tdeio/tests/kdirlistertest.h120
-rw-r--r--tdeio/tests/kdirwatchtest.cpp (renamed from kio/tests/kdirwatchtest.cpp)0
-rw-r--r--tdeio/tests/kdirwatchtest.h (renamed from kio/tests/kdirwatchtest.h)0
-rw-r--r--tdeio/tests/kdirwatchunittest.cpp (renamed from kio/tests/kdirwatchunittest.cpp)0
-rw-r--r--tdeio/tests/kdirwatchunittest.h (renamed from kio/tests/kdirwatchunittest.h)0
-rw-r--r--tdeio/tests/kfiltertest.cpp (renamed from kio/tests/kfiltertest.cpp)0
-rw-r--r--tdeio/tests/kionetrctest.cpp (renamed from kio/tests/kionetrctest.cpp)0
-rw-r--r--tdeio/tests/kiopassdlgtest.cpp (renamed from kio/tests/kiopassdlgtest.cpp)0
-rw-r--r--tdeio/tests/kmfitest.cpp28
-rw-r--r--tdeio/tests/kmimefromext.cpp (renamed from kio/tests/kmimefromext.cpp)0
-rw-r--r--tdeio/tests/kmimemagictest.cpp (renamed from kio/tests/kmimemagictest.cpp)0
-rw-r--r--tdeio/tests/kmimetypetest.cpp (renamed from kio/tests/kmimetypetest.cpp)0
-rw-r--r--tdeio/tests/kpropsdlgtest.cpp (renamed from kio/tests/kpropsdlgtest.cpp)0
-rw-r--r--tdeio/tests/kprotocolinfotest.cpp (renamed from kio/tests/kprotocolinfotest.cpp)0
-rw-r--r--tdeio/tests/kruntest.cpp (renamed from kio/tests/kruntest.cpp)0
-rw-r--r--tdeio/tests/kruntest.h (renamed from kio/tests/kruntest.h)0
-rw-r--r--tdeio/tests/kscantest.cpp (renamed from kio/tests/kscantest.cpp)0
-rw-r--r--tdeio/tests/kshredtest.cpp (renamed from kio/tests/kshredtest.cpp)0
-rw-r--r--tdeio/tests/ktartest.cpp (renamed from kio/tests/ktartest.cpp)0
-rw-r--r--tdeio/tests/kurifiltertest.cpp361
-rw-r--r--tdeio/tests/kurlcompletiontest.cpp (renamed from kio/tests/kurlcompletiontest.cpp)0
-rw-r--r--tdeio/tests/kziptest.cpp (renamed from kio/tests/kziptest.cpp)0
-rw-r--r--tdeio/tests/metatest.cpp321
-rw-r--r--tdeio/tests/netaccesstest.cpp48
-rw-r--r--tdeio/tests/previewtest.cpp64
-rw-r--r--tdeio/tests/previewtest.h25
-rw-r--r--tdeio/tests/speed.cpp139
-rw-r--r--tdeio/tests/speed.h24
-rw-r--r--tdeio/tests/tdeioslavetest.cpp555
-rw-r--r--tdeio/tests/tdeioslavetest.h108
-rw-r--r--tdeio/tests/tdesycocatest.cpp (renamed from kio/tests/tdesycocatest.cpp)0
-rw-r--r--tdeio/tests/tdesycocaupdatetest.cpp (renamed from kio/tests/tdesycocaupdatetest.cpp)0
-rw-r--r--tdeio/tests/tdetradertest.cpp108
-rw-r--r--tdeio/tests/wronglocalsizes.zip (renamed from kio/tests/wronglocalsizes.zip)bin325 -> 325 bytes
-rwxr-xr-xtdeio/useragent.pl (renamed from kio/useragent.pl)0
-rw-r--r--tdeioslave/CMakeLists.txt (renamed from kioslave/CMakeLists.txt)0
-rw-r--r--tdeioslave/Mainpage.dox (renamed from kioslave/Mainpage.dox)0
-rw-r--r--tdeioslave/Makefile.am (renamed from kioslave/Makefile.am)0
-rw-r--r--tdeioslave/bzip2/CMakeLists.txt42
-rw-r--r--tdeioslave/bzip2/Makefile.am11
-rw-r--r--tdeioslave/bzip2/configure.in.in (renamed from kioslave/bzip2/configure.in.in)0
-rw-r--r--tdeioslave/bzip2/kbzip2filter.cpp (renamed from kioslave/bzip2/kbzip2filter.cpp)0
-rw-r--r--tdeioslave/bzip2/kbzip2filter.desktop (renamed from kioslave/bzip2/kbzip2filter.desktop)0
-rw-r--r--tdeioslave/bzip2/kbzip2filter.h (renamed from kioslave/bzip2/kbzip2filter.h)0
-rw-r--r--tdeioslave/file/CMakeLists.txt55
-rw-r--r--tdeioslave/file/Makefile.am22
-rw-r--r--tdeioslave/file/file.cc1831
-rw-r--r--tdeioslave/file/file.h98
-rw-r--r--tdeioslave/file/file.protocol15
-rw-r--r--tdeioslave/ftp/CMakeLists.txt44
-rw-r--r--tdeioslave/ftp/Makefile.am (renamed from kioslave/ftp/Makefile.am)0
-rw-r--r--tdeioslave/ftp/configure.in.in (renamed from kioslave/ftp/configure.in.in)0
-rw-r--r--tdeioslave/ftp/ftp.cc2675
-rw-r--r--tdeioslave/ftp/ftp.h603
-rw-r--r--tdeioslave/ftp/ftp.protocol18
-rw-r--r--tdeioslave/gzip/CMakeLists.txt41
-rw-r--r--tdeioslave/gzip/Makefile.am12
-rw-r--r--tdeioslave/gzip/kgzipfilter.cpp (renamed from kioslave/gzip/kgzipfilter.cpp)0
-rw-r--r--tdeioslave/gzip/kgzipfilter.desktop (renamed from kioslave/gzip/kgzipfilter.desktop)0
-rw-r--r--tdeioslave/gzip/kgzipfilter.h (renamed from kioslave/gzip/kgzipfilter.h)0
-rw-r--r--tdeioslave/http/CMakeLists.txt69
-rw-r--r--tdeioslave/http/Makefile.am31
-rw-r--r--tdeioslave/http/README.http_cache_cleaner (renamed from kioslave/http/README.http_cache_cleaner)0
-rw-r--r--tdeioslave/http/README.webdav (renamed from kioslave/http/README.webdav)0
-rw-r--r--tdeioslave/http/THOUGHTS28
-rw-r--r--tdeioslave/http/TODO (renamed from kioslave/http/TODO)0
-rw-r--r--tdeioslave/http/configure.in.bot (renamed from kioslave/http/configure.in.bot)0
-rw-r--r--tdeioslave/http/configure.in.in (renamed from kioslave/http/configure.in.in)0
-rw-r--r--tdeioslave/http/http.cc6108
-rw-r--r--tdeioslave/http/http.h577
-rw-r--r--tdeioslave/http/http.protocol12
-rw-r--r--tdeioslave/http/http_cache_cleaner.cpp (renamed from kioslave/http/http_cache_cleaner.cpp)0
-rw-r--r--tdeioslave/http/http_cache_cleaner.desktop (renamed from kioslave/http/http_cache_cleaner.desktop)0
-rw-r--r--tdeioslave/http/https.protocol12
-rw-r--r--tdeioslave/http/kcookiejar/CMakeLists.txt (renamed from kioslave/http/kcookiejar/CMakeLists.txt)0
-rw-r--r--tdeioslave/http/kcookiejar/Makefile.am31
-rw-r--r--tdeioslave/http/kcookiejar/domain_info (renamed from kioslave/http/kcookiejar/domain_info)0
-rw-r--r--tdeioslave/http/kcookiejar/kcookiejar.cpp1559
-rw-r--r--tdeioslave/http/kcookiejar/kcookiejar.desktop (renamed from kioslave/http/kcookiejar/kcookiejar.desktop)0
-rw-r--r--tdeioslave/http/kcookiejar/kcookiejar.h (renamed from kioslave/http/kcookiejar/kcookiejar.h)0
-rw-r--r--tdeioslave/http/kcookiejar/kcookiescfg.upd (renamed from kioslave/http/kcookiejar/kcookiescfg.upd)0
-rw-r--r--tdeioslave/http/kcookiejar/kcookieserver.cpp606
-rw-r--r--tdeioslave/http/kcookiejar/kcookieserver.h (renamed from kioslave/http/kcookiejar/kcookieserver.h)0
-rw-r--r--tdeioslave/http/kcookiejar/kcookiewin.cpp (renamed from kioslave/http/kcookiejar/kcookiewin.cpp)0
-rw-r--r--tdeioslave/http/kcookiejar/kcookiewin.h (renamed from kioslave/http/kcookiejar/kcookiewin.h)0
-rw-r--r--tdeioslave/http/kcookiejar/main.cpp (renamed from kioslave/http/kcookiejar/main.cpp)0
-rw-r--r--tdeioslave/http/kcookiejar/netscape_cookie_spec.html (renamed from kioslave/http/kcookiejar/netscape_cookie_spec.html)0
-rw-r--r--tdeioslave/http/kcookiejar/rfc2109 (renamed from kioslave/http/kcookiejar/rfc2109)0
-rw-r--r--tdeioslave/http/kcookiejar/rfc2965 (renamed from kioslave/http/kcookiejar/rfc2965)0
-rw-r--r--tdeioslave/http/kcookiejar/tests/Makefile.am18
-rw-r--r--tdeioslave/http/kcookiejar/tests/cookie.test (renamed from kioslave/http/kcookiejar/tests/cookie.test)0
-rw-r--r--tdeioslave/http/kcookiejar/tests/cookie_rfc.test (renamed from kioslave/http/kcookiejar/tests/cookie_rfc.test)0
-rw-r--r--tdeioslave/http/kcookiejar/tests/cookie_saving.test (renamed from kioslave/http/kcookiejar/tests/cookie_saving.test)0
-rw-r--r--tdeioslave/http/kcookiejar/tests/cookie_settings.test (renamed from kioslave/http/kcookiejar/tests/cookie_settings.test)0
-rw-r--r--tdeioslave/http/kcookiejar/tests/kcookiejartest.cpp (renamed from kioslave/http/kcookiejar/tests/kcookiejartest.cpp)0
-rw-r--r--tdeioslave/http/rfc2518.txt (renamed from kioslave/http/rfc2518.txt)0
-rw-r--r--tdeioslave/http/rfc2616.txt (renamed from kioslave/http/rfc2616.txt)0
-rw-r--r--tdeioslave/http/rfc2617.txt (renamed from kioslave/http/rfc2617.txt)0
-rw-r--r--tdeioslave/http/rfc2817.txt (renamed from kioslave/http/rfc2817.txt)0
-rw-r--r--tdeioslave/http/rfc2818.txt (renamed from kioslave/http/rfc2818.txt)0
-rw-r--r--tdeioslave/http/rfc3229.txt (renamed from kioslave/http/rfc3229.txt)0
-rw-r--r--tdeioslave/http/rfc3253.txt (renamed from kioslave/http/rfc3253.txt)0
-rw-r--r--tdeioslave/http/shoutcast-icecast.txt (renamed from kioslave/http/shoutcast-icecast.txt)0
-rw-r--r--tdeioslave/http/webdav.protocol18
-rw-r--r--tdeioslave/http/webdavs.protocol18
-rw-r--r--tdeioslave/iso/CMakeLists.txt51
-rw-r--r--tdeioslave/iso/Makefile.am67
-rw-r--r--tdeioslave/iso/iso.cpp (renamed from kioslave/iso/iso.cpp)0
-rw-r--r--tdeioslave/iso/iso.h51
-rw-r--r--tdeioslave/iso/iso.protocol11
-rw-r--r--tdeioslave/iso/isoservice.desktop (renamed from kioslave/iso/isoservice.desktop)0
-rw-r--r--tdeioslave/iso/kio_iso.desktop (renamed from kioslave/iso/kio_iso.desktop)0
-rw-r--r--tdeioslave/iso/kio_isorc (renamed from kioslave/iso/kio_isorc)0
-rw-r--r--tdeioslave/iso/kiso.cpp460
-rw-r--r--tdeioslave/iso/kiso.h (renamed from kioslave/iso/kiso.h)0
-rw-r--r--tdeioslave/iso/kisodirectory.cpp (renamed from kioslave/iso/kisodirectory.cpp)0
-rw-r--r--tdeioslave/iso/kisodirectory.h (renamed from kioslave/iso/kisodirectory.h)0
-rw-r--r--tdeioslave/iso/kisofile.cpp (renamed from kioslave/iso/kisofile.cpp)0
-rw-r--r--tdeioslave/iso/kisofile.h (renamed from kioslave/iso/kisofile.h)0
-rw-r--r--tdeioslave/iso/libisofs/CMakeLists.txt (renamed from kioslave/iso/libisofs/CMakeLists.txt)0
-rw-r--r--tdeioslave/iso/libisofs/COPYING (renamed from kioslave/iso/libisofs/COPYING)0
-rw-r--r--tdeioslave/iso/libisofs/ChangeLog (renamed from kioslave/iso/libisofs/ChangeLog)0
-rw-r--r--tdeioslave/iso/libisofs/Makefile.am (renamed from kioslave/iso/libisofs/Makefile.am)0
-rw-r--r--tdeioslave/iso/libisofs/README (renamed from kioslave/iso/libisofs/README)0
-rw-r--r--tdeioslave/iso/libisofs/bswap.h (renamed from kioslave/iso/libisofs/bswap.h)0
-rw-r--r--tdeioslave/iso/libisofs/el_torito.h (renamed from kioslave/iso/libisofs/el_torito.h)0
-rw-r--r--tdeioslave/iso/libisofs/iso_fs.h (renamed from kioslave/iso/libisofs/iso_fs.h)0
-rw-r--r--tdeioslave/iso/libisofs/isofs.c (renamed from kioslave/iso/libisofs/isofs.c)0
-rw-r--r--tdeioslave/iso/libisofs/isofs.h (renamed from kioslave/iso/libisofs/isofs.h)0
-rw-r--r--tdeioslave/iso/libisofs/rock.h (renamed from kioslave/iso/libisofs/rock.h)0
-rw-r--r--tdeioslave/iso/qfilehack.cpp (renamed from kioslave/iso/qfilehack.cpp)0
-rw-r--r--tdeioslave/iso/qfilehack.h (renamed from kioslave/iso/qfilehack.h)0
-rw-r--r--tdeioslave/metainfo/CMakeLists.txt43
-rw-r--r--tdeioslave/metainfo/Makefile.am24
-rw-r--r--tdeioslave/metainfo/metainfo.cpp103
-rw-r--r--tdeioslave/metainfo/metainfo.h38
-rw-r--r--tdeioslave/metainfo/metainfo.protocol (renamed from kioslave/metainfo/metainfo.protocol)0
-rw-r--r--tdemdi/tdemdi/dockcontainer.cpp2
-rw-r--r--tdemdi/tdemdi/guiclient.cpp2
-rw-r--r--tdemdi/tdemdichildarea.cpp2
-rw-r--r--tdemdi/tdemdidockcontainer.cpp2
-rw-r--r--tdemdi/tdemdiguiclient.cpp2
-rw-r--r--tdeparts/CMakeLists.txt8
-rw-r--r--tdeparts/COMMENTS2
-rw-r--r--tdeparts/Makefile.am4
-rw-r--r--tdeparts/browserrun.cpp6
-rw-r--r--tdeparts/part.cpp4
-rw-r--r--tdeparts/part.h2
-rw-r--r--tdeparts/plugin.cpp2
-rw-r--r--tdeparts/tests/Makefile.am2
-rw-r--r--tdeparts/tests/ghostview.cpp2
-rw-r--r--tdeprint/CMakeLists.txt12
-rw-r--r--tdeprint/Makefile.am6
-rw-r--r--tdeprint/cups/CMakeLists.txt6
-rw-r--r--tdeprint/cups/Makefile.am2
-rw-r--r--tdeprint/cups/cupsaddsmb2.cpp2
-rw-r--r--tdeprint/cups/cupsdconf2/CMakeLists.txt8
-rw-r--r--tdeprint/cups/cupsdconf2/Makefile.am2
-rw-r--r--tdeprint/cups/cupsdconf2/cupsdconf.cpp2
-rw-r--r--tdeprint/cups/cupsdconf2/cupsddialog.cpp2
-rw-r--r--tdeprint/cups/cupsdconf2/cupsdlogpage.cpp2
-rw-r--r--tdeprint/cups/cupsdconf2/qdirlineedit.cpp2
-rw-r--r--tdeprint/cups/cupsdconf2/qdirmultilineedit.cpp2
-rw-r--r--tdeprint/cups/cupsinfos.cpp6
-rw-r--r--tdeprint/cups/kmconfigcups.cpp2
-rw-r--r--tdeprint/cups/kmconfigcupsdir.cpp2
-rw-r--r--tdeprint/cups/kmcupsconfigwidget.cpp2
-rw-r--r--tdeprint/cups/kmcupsmanager.cpp2
-rw-r--r--tdeprint/ext/kextprinterimpl.cpp2
-rw-r--r--tdeprint/kfilelist.cpp326
-rw-r--r--tdeprint/kmfactory.cpp4
-rw-r--r--tdeprint/kmjobmanager.cpp2
-rw-r--r--tdeprint/kmmanager.cpp2
-rw-r--r--tdeprint/kmprinter.cpp2
-rw-r--r--tdeprint/kpfileselectpage.cpp2
-rw-r--r--tdeprint/kprintdialog.cpp6
-rw-r--r--tdeprint/kprinter.cpp2
-rw-r--r--tdeprint/kprinterimpl.cpp2
-rw-r--r--tdeprint/kprintpreview.cpp2
-rw-r--r--tdeprint/lpd/kmlpdmanager.cpp2
-rw-r--r--tdeprint/lpr/kmconfiglpr.cpp2
-rw-r--r--tdeprint/lpr/lprsettings.cpp2
-rw-r--r--tdeprint/management/CMakeLists.txt6
-rw-r--r--tdeprint/management/Makefile.am2
-rw-r--r--tdeprint/management/kmconfigdialog.cpp2
-rw-r--r--tdeprint/management/kmconfigfilter.cpp2
-rw-r--r--tdeprint/management/kmconfigfonts.cpp4
-rw-r--r--tdeprint/management/kmconfiggeneral.cpp2
-rw-r--r--tdeprint/management/kmconfigjobs.cpp2
-rw-r--r--tdeprint/management/kmconfigpreview.cpp2
-rw-r--r--tdeprint/management/kmdriverdbwidget.cpp4
-rw-r--r--tdeprint/management/kmjobviewer.cpp4
-rw-r--r--tdeprint/management/kmmainview.cpp2
-rw-r--r--tdeprint/management/kmspecialprinterdlg.cpp2
-rw-r--r--tdeprint/management/kmtimer.cpp2
-rw-r--r--tdeprint/management/kmwdrivertest.cpp2
-rw-r--r--tdeprint/management/kmwfile.cpp2
-rw-r--r--tdeprint/management/kxmlcommandselector.cpp2
-rw-r--r--tdeprint/printerfilter.cpp2
-rw-r--r--tdeprint/rlpr/kmproxywidget.cpp2
-rw-r--r--tdeprint/rlpr/krlprprinterimpl.cpp2
-rw-r--r--tdeprint/specials.desktop2
-rw-r--r--tdeprint/tdefilelist.cpp326
-rw-r--r--tdeprint/tdefilelist.h (renamed from tdeprint/kfilelist.h)0
-rw-r--r--tdeprint/tdeprintcheck.h2
-rw-r--r--tdeprint/tdeprintd.cpp4
-rw-r--r--tderandr/libtderandr.h2
-rw-r--r--tderandr/randr.h2
-rw-r--r--tderesources/CMakeLists.txt8
-rw-r--r--tderesources/configwidget.h2
-rw-r--r--tderesources/factory.h4
-rw-r--r--tderesources/managerimpl.cpp2
-rw-r--r--tderesources/resource.cpp2
-rw-r--r--tderesources/resource.h4
-rw-r--r--tderesources/tderesources.desktop2
-rw-r--r--tdersync/CMakeLists.txt6
-rw-r--r--tdersync/rsyncconfigdialog.cpp2
-rw-r--r--tdersync/rsyncconfigdialog.h2
-rw-r--r--tdersync/tdersync.cpp4
-rw-r--r--tdersync/tdersync.h8
-rw-r--r--tdespell2/CMakeLists.txt4
-rw-r--r--tdespell2/broker.cpp2
-rw-r--r--tdespell2/plugins/ispell/ispell_checker.cpp2
-rw-r--r--tdespell2/plugins/ispell/ispell_checker.h2
-rw-r--r--tdespell2/settings.cpp2
-rw-r--r--tdespell2/ui/dialog.cpp2
-rw-r--r--tdespell2/ui/highlighter.cpp2
-rw-r--r--tdesu/Makefile.am2
-rw-r--r--tdesu/process.cpp2
-rw-r--r--tdesu/su.cpp2
-rw-r--r--tdeui/CMakeLists.txt10
-rw-r--r--tdeui/Makefile.am4
-rw-r--r--tdeui/kactionclasses.cpp2
-rw-r--r--tdeui/kbugreport.cpp10
-rw-r--r--tdeui/kbugreport.h2
-rw-r--r--tdeui/kcmenumngr.cpp2
-rw-r--r--tdeui/kcolorcombo.cpp2
-rw-r--r--tdeui/kcolordialog.cpp2
-rw-r--r--tdeui/kcombobox.h2
-rw-r--r--tdeui/kcompletionbox.cpp2
-rw-r--r--tdeui/kconfigdialog.cpp259
-rw-r--r--tdeui/kcursor.cpp2
-rw-r--r--tdeui/kdatetbl.cpp2
-rw-r--r--tdeui/kdepackages.h126
-rw-r--r--tdeui/kdialog.cpp2
-rw-r--r--tdeui/kdialogbase.cpp2
-rw-r--r--tdeui/kdockwidget.cpp2
-rw-r--r--tdeui/kedittoolbar.cpp6
-rw-r--r--tdeui/kfontcombo.cpp2
-rw-r--r--tdeui/kfontdialog.cpp2
-rw-r--r--tdeui/kiconview.cpp2
-rw-r--r--tdeui/kkeydialog.cpp2
-rw-r--r--tdeui/klineedit.cpp2
-rw-r--r--tdeui/klistview.cpp2
-rw-r--r--tdeui/kmainwindow.cpp2
-rw-r--r--tdeui/kmainwindow.h2
-rw-r--r--tdeui/kmenubar.cpp2
-rw-r--r--tdeui/kmessagebox.cpp2
-rw-r--r--tdeui/kpanelapplet.cpp2
-rw-r--r--tdeui/kpanelapplet.h2
-rw-r--r--tdeui/kpanelextension.cpp2
-rw-r--r--tdeui/kpanelmenu.cpp2
-rw-r--r--tdeui/kpassdlg.cpp2
-rw-r--r--tdeui/kpassivepopup.cpp2
-rw-r--r--tdeui/kpixmapio.cpp2
-rw-r--r--tdeui/kpushbutton.cpp2
-rw-r--r--tdeui/ksconfig.cpp4
-rw-r--r--tdeui/kscrollview.cpp2
-rw-r--r--tdeui/kshortcutdialog.cpp2
-rw-r--r--tdeui/ksplashscreen.cpp2
-rw-r--r--tdeui/kstatusbar.cpp2
-rw-r--r--tdeui/kswitchlanguagedialog.cpp2
-rw-r--r--tdeui/ksyntaxhighlighter.cpp2
-rw-r--r--tdeui/ksystemtray.cpp2
-rw-r--r--tdeui/ktabwidget.cpp2
-rw-r--r--tdeui/ktimezonewidget.cpp2
-rw-r--r--tdeui/ktip.cpp2
-rw-r--r--tdeui/ktoolbar.cpp2
-rw-r--r--tdeui/tdecmodule.cpp4
-rw-r--r--tdeui/tdecmodule.h4
-rw-r--r--tdeui/tdeconfigdialog.cpp259
-rw-r--r--tdeui/tdeconfigdialog.h (renamed from tdeui/kconfigdialog.h)0
-rw-r--r--tdeui/tests/itemcontainertest.cpp2
-rw-r--r--tdeui/tests/kcolordlgtest.cpp2
-rw-r--r--tdeui/tests/kdockwidgetdemo.cpp2
-rw-r--r--tdeui/tests/kfontdialogtest.cpp2
-rw-r--r--tdeutils/CMakeLists.txt2
-rw-r--r--tdeutils/Makefile.am2
-rw-r--r--tdeutils/kplugininfo.cpp2
-rw-r--r--tdeutils/ksettings/CMakeLists.txt2
-rw-r--r--tdeutils/ksettings/componentsdialog.cpp2
-rw-r--r--tdeutils/ksettings/dispatcher.cpp2
-rw-r--r--tdeutils/tdecmoduleloader.cpp4
-rw-r--r--tdeutils/tdecmoduleproxy.cpp10
-rw-r--r--tdeutils/tdecmoduleproxyIface.h4
-rw-r--r--tdeutils/tdecmoduleproxyIfaceImpl.cpp2
-rw-r--r--tdewallet/client/tdewallet.cc2
-rw-r--r--win/pro_files/kate/part/part.pro2
-rw-r--r--win/pro_files/kded/kded.pro10
-rw-r--r--win/pro_files/kded/kded_rel.pro2
-rw-r--r--win/pro_files/kdewidgets/kdewidgets.pro2
-rw-r--r--win/pro_files/kio/kfile/tests/kfiletreeviewtest.pro29
-rw-r--r--win/pro_files/kio/kio.pro246
-rw-r--r--win/pro_files/kio/tdefile/tests/tdefiletreeviewtest.pro29
-rw-r--r--win/pro_files/kioslave/common.pro8
-rw-r--r--win/pro_files/tdecore/kconfig_compiler/kconfig_compiler.pro18
-rw-r--r--win/pro_files/tdecore/tdeconfig_compiler/tdeconfig_compiler.pro18
-rw-r--r--win/pro_files/tdecore/tdecore.pro12
-rw-r--r--win/pro_files/tdeioslave/bzip2/bzip2.pro (renamed from win/pro_files/kioslave/bzip2/bzip2.pro)0
-rw-r--r--win/pro_files/tdeioslave/common.pro8
-rw-r--r--win/pro_files/tdeioslave/gzip/gzip.pro (renamed from win/pro_files/kioslave/gzip/gzip.pro)0
-rw-r--r--win/pro_files/tdeioslave/tdeioslave.pro (renamed from win/pro_files/kioslave/kioslave.pro)0
-rw-r--r--win/pro_files/tdeparts/tdeparts.pro4
-rw-r--r--win/pro_files/tdeui/tdeui.pro2
-rw-r--r--win/pro_files/tdeutils/tdeutils.pro2
-rw-r--r--win/resources/tdebuildsycoca.res (renamed from win/resources/kbuildsycoca.res)bin2332 -> 2332 bytes
-rw-r--r--win/tools/build_tdelibs_dbg4
-rw-r--r--win/tools/build_tdelibs_rel4
-rwxr-xr-xwin/tools/kde_env2
-rw-r--r--win/win32_utils.h2
1558 files changed, 131155 insertions, 131155 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7a1f952dd..3a9f23a4d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -81,7 +81,7 @@ OPTION( WITH_AVAHI "Enable AVAHI support" ${WITH_ALL_OPTIONS} )
OPTION( WITH_ELFICON "Enable ELF embedded icon support" ${WITH_ALL_OPTIONS} )
OPTION( WITH_PCRE "Enable pcre regex support for kjs" ON )
OPTION( WITH_GCC_VISIBILITY "Enable fvisibility and fvisibility-inlines-hidden" ${WITH_ALL_OPTIONS} )
-OPTION( WITH_INOTIFY "Enable inotify support for kio" ON )
+OPTION( WITH_INOTIFY "Enable inotify support for tdeio" ON )
OPTION( WITH_GAMIN "Enable FAM/GAMIN support" ${WITH_ALL_OPTIONS} )
option( WITH_UPOWER "Enable UPOWER support" ${WITH_ALL_OPTIONS} )
OPTION( WITH_NETWORK_MANAGER_BACKEND "Enable network-manager support" OFF )
@@ -745,7 +745,7 @@ endif( )
# before altering the LIBR_VERSION check,
# please ensure that nothing changed in the
# duplicated data definitions present in
-# kio/kio/kfileitem.cpp
+# tdeio/tdeio/tdefileitem.cpp
if( WITH_ELFICON )
pkg_search_module( LIBR libr )
@@ -886,7 +886,7 @@ configure_file( config.h.cmake config.h )
configure_file( dcop/dcop-path.h.cmake dcop/dcop-path.h )
configure_file( tdecore/kdemacros.h.cmake tdecore/kdemacros.h )
configure_file( kjs/global.h.in kjs/global.h )
-configure_file( kio/kssl/ksslconfig.h.cmake kio/kssl/ksslconfig.h )
+configure_file( tdeio/kssl/ksslconfig.h.cmake tdeio/kssl/ksslconfig.h )
configure_file( kdoctools/checkXML.cmake kdoctools/checkXML )
@@ -895,7 +895,7 @@ configure_file( kdoctools/checkXML.cmake kdoctools/checkXML )
set( KDE3_DCOPIDL_EXECUTABLE ${CMAKE_BINARY_DIR}/dcop/dcopidl/dcopidl )
set( KDE3_DCOPIDL2CPP_EXECUTABLE ${CMAKE_BINARY_DIR}/dcop/dcopidl2cpp/dcopidl2cpp )
set( KDE3_MEINPROC_EXECUTABLE ${CMAKE_BINARY_DIR}/kdoctools/meinproc )
-set( KDE3_KCFGC_EXECUTABLE ${CMAKE_BINARY_DIR}/tdecore/kconfig_compiler/kconfig_compiler )
+set( KDE3_KCFGC_EXECUTABLE ${CMAKE_BINARY_DIR}/tdecore/tdeconfig_compiler/tdeconfig_compiler )
##### global compiler settings ##################
@@ -937,7 +937,7 @@ add_subdirectory( tdeui )
add_subdirectory( tdesu )
add_subdirectory( kjs )
add_subdirectory( tdewallet )
-add_subdirectory( kio )
+add_subdirectory( tdeio )
add_subdirectory( kded )
# FIXME this directory/target doesn't exists
@@ -962,11 +962,11 @@ if( XRANDR_FOUND )
add_subdirectory( tderandr )
endif( XRANDR_FOUND )
add_subdirectory( tdehtml )
-add_subdirectory( kcmshell )
-add_subdirectory( kconf_update )
+add_subdirectory( tdecmshell )
+add_subdirectory( tdeconf_update )
add_subdirectory( kdewidgets )
add_subdirectory( kimgio )
-add_subdirectory( kioslave )
+add_subdirectory( tdeioslave )
add_subdirectory( kstyles )
add_subdirectory( libtdemid )
add_subdirectory( libtdescreensaver )
@@ -977,7 +977,7 @@ add_subdirectory( licenses )
add_subdirectory( dnssd )
add_subdirectory( pics )
add_subdirectory( mimetypes )
-add_subdirectory( kfile-plugins )
+add_subdirectory( tdefile-plugins )
##### install import cmake modules ###############
diff --git a/KDE2PORTING.html b/KDE2PORTING.html
index c373e83f5..131c74577 100644
--- a/KDE2PORTING.html
+++ b/KDE2PORTING.html
@@ -205,7 +205,7 @@ must have created a TDEApplication object before the methods can be used.<P>
<TD COLSPAN="2">
<PRE>
#include &lt;kglobal.h&gt;
- #include &lt;kconfig.h&gt; // Needed to use TDEConfig
+ #include &lt;tdeconfig.h&gt; // Needed to use TDEConfig
#include &lt;klocale.h&gt; // Needed to use KLocale
#include &lt;kiconloader.h&gt; // Needed to use KIconLoader
</PRE>
@@ -501,20 +501,20 @@ are necessary to convert your old KDND-based stuff to Qt DND.<P>
<H3><A NAME="libkfm">libkfm has disappeared</A></H3>
Lots of other functionalities have been taken out of kfm, some being
- now in libkio, some in libkonq.<P>
+ now in libtdeio, some in libkonq.<P>
<STRONG> Replacement table :</STRONG><P>
<TABLE BORDER="1">
-<TR><TD>KFM::download </TD><TD>-&gt; TDEIO::NetAccess::download (tdelibs/kio/netaccess.h)</TD></TR>
+<TR><TD>KFM::download </TD><TD>-&gt; TDEIO::NetAccess::download (tdelibs/tdeio/netaccess.h)</TD></TR>
<TR><TD>KFM::removeTempFile </TD><TD>-&gt; TDEIO::NetAccess::removeTempFile</TD></TR>
<TR><TD COLSPAN="2" ROWSPAN="0">refreshDesktop, sortDesktop, selectRootIcons : removed; kdesktop handles it</TD></TR>
<TR><TD>KFM::configure </TD><TD>-&gt; see konqueror DCOP interface</TD></TR>
-<TR><TD>KFM::openURL </TD><TD>-&gt; "(void) new KRun (url)" (tdelibs/kio/krun.h)</TD></TR>
+<TR><TD>KFM::openURL </TD><TD>-&gt; "(void) new KRun (url)" (tdelibs/tdeio/krun.h)</TD></TR>
<TR><TD>KFM::refreshDirectory </TD><TD>-&gt; not needed anymore since konqy/kdesktop use KDirWatch</TD></TR>
-<TR><TD>KFM::openProperties </TD><TD>-&gt; "(void) new KPropertiesDialog (url)" (tdelibs/kfile/kpropsdlg.h)</TD></TR>
-<TR><TD>KFM::exec </TD><TD>-&gt; "(void) new KRun (url)" (tdelibs/kio/krun.h)</TD></TR>
-<TR><TD>KFM::copy, KFM::move </TD><TD>-&gt; TDEIO::Job (async, see kio/job.h)<BR>
- or TDEIO::NetAccess (sync, see kio/netaccess.h)</TD></TR>
+<TR><TD>KFM::openProperties </TD><TD>-&gt; "(void) new KPropertiesDialog (url)" (tdelibs/tdefile/kpropsdlg.h)</TD></TR>
+<TR><TD>KFM::exec </TD><TD>-&gt; "(void) new KRun (url)" (tdelibs/tdeio/krun.h)</TD></TR>
+<TR><TD>KFM::copy, KFM::move </TD><TD>-&gt; TDEIO::Job (async, see tdeio/job.h)<BR>
+ or TDEIO::NetAccess (sync, see tdeio/netaccess.h)</TD></TR>
<TR><TD>DlgLocation </TD><TD>-&gt; Use KLineEditDlg (tdeui/klineeditdlg.h) instead</TD></TR>
</TABLE>
diff --git a/KDE3PORTING.html b/KDE3PORTING.html
index 645bd7612..7d6130ac4 100644
--- a/KDE3PORTING.html
+++ b/KDE3PORTING.html
@@ -23,7 +23,7 @@ or <a href="http://doc.trolltech.com/3.0/porting.html">this page online</a>.<P>
<LI><A HREF="#tdeparts">Changes in tdeparts</A></LI>
<LI><A HREF="#tdespell">Changes in tdespell</A></LI>
<LI><A HREF="#tdehtmlpart">API-cleanup in KHTML</A></LI>
-<LI><A HREF="#kfile">Changes in kfile</A></LI>
+<LI><A HREF="#tdefile">Changes in tdefile</A></LI>
<LI><A HREF="#kcontrol">TDE Control Center</A></LI>
<LI><A HREF="#kicker">Panel Applets and Extensions</A></LI>
</UL>
@@ -214,7 +214,7 @@ The preferred means of defining a shortcut, however, is to use <b>KAction</b>.
<H4>KIconLoader, KIconTheme</H4>
Methods now use KIcon::Group and KIcon::Context instead of int as types for group and context arguments.
The change should affect only code using hardcoded numeric values instead of using the proper enum constants.
-This applies to classes KIconLoader, KIconTheme and (in kio and kfile) KMimeType, KService, KIconDialog, KIconButton,
+This applies to classes KIconLoader, KIconTheme and (in kio and tdefile) KMimeType, KService, KIconDialog, KIconButton,
KURLBar and KURLBarItem.
<H4><P ALIGN="RIGHT"><A HREF="#TOC">Return to the Table of Contents</A></P></H4>
@@ -416,7 +416,7 @@ TQString&) is not a slot anymore.
<H4>KOpenWithHandler / KFileOpenWithHandler</H4>
Those two classes are deprecated, no need to create a KFileOpenWithHandler anymore.
-The merging of libkio, libtdesycoca, libkfile and libkssl into a single libkio has
+The merging of libtdeio, libtdesycoca, libtdefile and libkssl into a single libtdeio has
allowed to fix this dependency problem: KRun can now use the OpenWith dialog directly.
<H4>KMimeType, KService</H4>
@@ -520,14 +520,14 @@ disable this use a #define KDE_NO_COMPAT.
</ul>
<H4><P ALIGN="RIGHT"><A HREF="#TOC">Return to the Table of Contents</A></P></H4>
-<H3><A NAME="kfile">Changes in kfile</A></H3>
-The kfile-library, as used by the KFileDialog provides classes for directory browsing widgets.
+<H3><A NAME="tdefile">Changes in tdefile</A></H3>
+The tdefile-library, as used by the KFileDialog provides classes for directory browsing widgets.
Those classes gained some new features, some parts were merged with other existing classes
-and in some cases the API was cleaned up/fixed. The library is now built as part of libkio
-library (there's no need to modify Makefiles which use $LIB_KFILE instead of hardcoding -lkfile).
+and in some cases the API was cleaned up/fixed. The library is now built as part of libtdeio
+library (there's no need to modify Makefiles which use $LIB_KFILE instead of hardcoding -ltdefile).
<p>
Even if the list of changes is long, the affected code base should be relatively small, as most
-parts are rarely used outside of kfile.
+parts are rarely used outside of tdefile.
<p>
The changes are:
<H4>KFileItem</H4>
diff --git a/Mainpage.dox b/Mainpage.dox
index ef5745224..15904678c 100644
--- a/Mainpage.dox
+++ b/Mainpage.dox
@@ -20,8 +20,8 @@
* - <a target="_top" href="kjs/html/index.html"><b>kjs</b></a>
* (<a target="_top" href="kjs/html/classes.html">classes</a>)\n
* <i>Javascript (aka. ECMAScript and JScript) support.</i>
- * - <a target="_top" href="kio/html/index.html"><b>kio</b></a>
- * (<a target="_top" href="kio/kio/html/classes.html">classes</a>)\n
+ * - <a target="_top" href="tdeio/html/index.html"><b>kio</b></a>
+ * (<a target="_top" href="tdeio/tdeio/html/classes.html">classes</a>)\n
* <i>Low level access to network files. Also provides access to facilities
* such as KDirWatcher which monitors directories for changes.</i>
* - <a target="_top" href="tdeparts/html/index.html"><b>tdeparts</b></a>
diff --git a/Makefile.am.in b/Makefile.am.in
index 10e9219dd..83d0901fa 100644
--- a/Makefile.am.in
+++ b/Makefile.am.in
@@ -27,7 +27,7 @@ COMPILE_BEFORE_kabc = kab tderesources
COMPILE_BEFORE_kate = interfaces tdeutils
COMPILE_BEFORE_tdemdi = tdeutils
COMPILE_BEFORE_tdespell2 = tdeutils
-COMPILE_BEFORE_kcmshell = tdeutils
+COMPILE_BEFORE_tdecmshell = tdeutils
COMPILE_BEFORE_kdewidgets = kabc tdehtml
COMPILE_BEFORE_interfaces = arts kabc
diff --git a/README b/README
index 1392e27c5..c96978eb9 100644
--- a/README
+++ b/README
@@ -42,7 +42,7 @@ Here is an alphabetical list:
* tdecert
Personal certification manager.
-* kconf_update
+* tdeconf_update
Auto-Updater for config files.
* tdecore
@@ -89,7 +89,7 @@ Here is an alphabetical list:
contains "tdesycoca", the system configure cache containing services,
applications, servicetypes and mimetypes.
-* kioslave
+* tdeioslave
I/O subprocesses to handle files, ftp, http, gzip and bzip2 streams.
* kjs
diff --git a/TODO b/TODO
index dcbfec292..75f989156 100644
--- a/TODO
+++ b/TODO
@@ -180,9 +180,9 @@ that we would like to make for the next binary incompatible release.
- KWallet::Wallet::* functions - remove the default = 0 argument for mainwindow for the dialog
-- Make libtdewalletclient part of libkio and get rid of libtdewalletclient.
+- Make libtdewalletclient part of libtdeio and get rid of libtdewalletclient.
-- Get rid of libtdesu dependency in libkio, get rid of SessionData::AuthData*,
+- Get rid of libtdesu dependency in libtdeio, get rid of SessionData::AuthData*,
get rid of SlaveInterface::authorizationKey and SlaveInterface::delAuthorization
- Make functions in KHelpMenu virtual so they can be overridden (ex: to provide
@@ -215,7 +215,7 @@ an alternative help->contents action)
- Move TDEIO::findDeviceMountPoint, findPathMoundPoint, probably_slow_mounted, and testFileSystemFlag to KMountPoint,
to merge that code.
-- Refactor the kio/bookmarks code so we don't need to use the static d-pointer trick anymore.
+- Refactor the tdeio/bookmarks code so we don't need to use the static d-pointer trick anymore.
- Rename the parameters to KDEDesktopMimeType::pixmap so that they use meaningful names rather than
just a, b, c, and d. Probably not something that has to wait for KDE 4, but seems like a good idea
diff --git a/arts/kde/CMakeLists.txt b/arts/kde/CMakeLists.txt
index 3877ddb9d..3b585256d 100644
--- a/arts/kde/CMakeLists.txt
+++ b/arts/kde/CMakeLists.txt
@@ -18,8 +18,8 @@ include_directories(
${CMAKE_BINARY_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
link_directories(
@@ -65,6 +65,6 @@ add_custom_command(
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 1.2.0
- LINK kio-shared mcop artsflow_idl kmedia2_idl soundserver_idl artsflow qtmcop
+ LINK tdeio-shared mcop artsflow_idl kmedia2_idl soundserver_idl artsflow qtmcop
DESTINATION ${LIB_INSTALL_DIR}
)
diff --git a/arts/kde/kioinputstream_impl.cpp b/arts/kde/kioinputstream_impl.cpp
index 4ff509980..bf6b3654a 100644
--- a/arts/kde/kioinputstream_impl.cpp
+++ b/arts/kde/kioinputstream_impl.cpp
@@ -31,9 +31,9 @@
#include <kapplication.h>
#include <kdebug.h>
-#include <kio/job.h>
-#include <kio/kmimetype.h>
-#include <kio/jobclasses.h>
+#include <tdeio/job.h>
+#include <tdeio/kmimetype.h>
+#include <tdeio/jobclasses.h>
#include <tqtimer.h>
#include <tqdatastream.h>
#include "artsversion.h"
diff --git a/arts/kde/kioinputstream_impl.h b/arts/kde/kioinputstream_impl.h
index d0a872881..1d18f6421 100644
--- a/arts/kde/kioinputstream_impl.h
+++ b/arts/kde/kioinputstream_impl.h
@@ -24,7 +24,7 @@
#include <tqobject.h>
#include <tqcstring.h>
-#include <kio/jobclasses.h>
+#include <tdeio/jobclasses.h>
#include <kurl.h>
#include "artskde.h"
#include "stdsynthmodule.h"
diff --git a/arts/kde/kplayobjectcreator.cc b/arts/kde/kplayobjectcreator.cc
index 2e8187e67..039c8a3bc 100644
--- a/arts/kde/kplayobjectcreator.cc
+++ b/arts/kde/kplayobjectcreator.cc
@@ -19,7 +19,7 @@
*/
-#include <kio/kmimetype.h>
+#include <tdeio/kmimetype.h>
#include "artskde.h"
#include "kplayobjectcreator.h"
#include "kplayobjectcreator.moc"
diff --git a/arts/kde/kplayobjectfactory.cc b/arts/kde/kplayobjectfactory.cc
index db4110792..fa9e2c5a1 100644
--- a/arts/kde/kplayobjectfactory.cc
+++ b/arts/kde/kplayobjectfactory.cc
@@ -19,7 +19,7 @@
*/
-#include <kio/kmimetype.h>
+#include <tdeio/kmimetype.h>
#include "kplayobject.h"
#include "artskde.h"
#include "kplayobjectfactory.h"
@@ -33,7 +33,7 @@
#include <kdebug.h>
#include "kaudiomanagerplay.h"
#include <flowsystem.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
using namespace std;
diff --git a/arts/knotify/knotify.cpp b/arts/knotify/knotify.cpp
index b8c1642f9..71006c1a7 100644
--- a/arts/knotify/knotify.cpp
+++ b/arts/knotify/knotify.cpp
@@ -50,7 +50,7 @@
#include <kartsserver.h>
#endif
#include <kcmdlineargs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
diff --git a/configure.in.in b/configure.in.in
index c899ee519..00870d24c 100644
--- a/configure.in.in
+++ b/configure.in.in
@@ -252,9 +252,9 @@ AC_SUBST(LIB_KAB, '$(top_builddir)/kab/libkab.la')
AC_SUBST(LIB_KABC, '$(top_builddir)/kabc/libkabc.la')
AC_SUBST(LIB_TDECORE, '$(top_builddir)/tdecore/libtdecore.la')
AC_SUBST(LIB_TDEUI, '$(top_builddir)/tdeui/libtdeui.la')
-AC_SUBST(LIB_KIO, '$(top_builddir)/kio/libkio.la')
-AC_SUBST(LIB_KFILE, '$(top_builddir)/kio/libkio.la')
-AC_SUBST(LIB_KSYCOCA, '$(top_builddir)/kio/libkio.la')
+AC_SUBST(LIB_KIO, '$(top_builddir)/tdeio/libtdeio.la')
+AC_SUBST(LIB_KFILE, '$(top_builddir)/tdeio/libtdeio.la')
+AC_SUBST(LIB_KSYCOCA, '$(top_builddir)/tdeio/libtdeio.la')
AC_SUBST(LIB_KHTML, '$(top_builddir)/tdehtml/libtdehtml.la')
AC_SUBST(LIB_TDEPRINT, '$(top_builddir)/tdeprint/libtdeprint.la')
AC_SUBST(LIB_KPARTS, '$(top_builddir)/tdeparts/libtdeparts.la')
@@ -308,7 +308,7 @@ AC_SUBST(DCOPIDL, '$(top_builddir)/dcop/dcopidl/dcopidl')
AC_SUBST(DCOPIDLNG, '$(top_srcdir)/dcop/dcopidlng/dcopidlng')
AC_SUBST(DCOPIDL2CPP, '$(top_builddir)/dcop/dcopidl2cpp/dcopidl2cpp')
AC_SUBST(MAKEKDEWIDGETS, '$(top_builddir)/kdewidgets/makekdewidgets')
-AC_SUBST(KCONFIG_COMPILER, '$(top_builddir)/tdecore/kconfig_compiler/kconfig_compiler')
+AC_SUBST(KCONFIG_COMPILER, '$(top_builddir)/tdecore/tdeconfig_compiler/tdeconfig_compiler')
ac_save_LIBS="$LIBS"
LIBS="$LIBS $X_LDFLAGS -lICE"
diff --git a/configure.in.mid b/configure.in.mid
index 669f0d13c..bf0c8d021 100644
--- a/configure.in.mid
+++ b/configure.in.mid
@@ -1,7 +1,7 @@
dnl put here things which have to be done after all usual autoconf macros
dnl have been run, but before the Makefiles are created
-all_includes='-I$(top_srcdir)/dcop -I$(top_srcdir)/libltdl -I$(top_srcdir)/tdefx -I$(top_builddir)/tdecore -I$(top_srcdir)/tdecore -I$(top_srcdir)/tdecore/network -I$(top_srcdir)/tdeui -I$(top_srcdir)/kio -I$(top_srcdir)/kio/kio -I$(top_srcdir)/kio/kfile -I$(top_srcdir) $(QT_INCLUDES) $(X_INCLUDES) $(KDE_INCLUDES) $(USER_INCLUDES)'
+all_includes='-I$(top_srcdir)/dcop -I$(top_srcdir)/libltdl -I$(top_srcdir)/tdefx -I$(top_builddir)/tdecore -I$(top_srcdir)/tdecore -I$(top_srcdir)/tdecore/network -I$(top_srcdir)/tdeui -I$(top_srcdir)/tdeio -I$(top_srcdir)/tdeio/tdeio -I$(top_srcdir)/tdeio/tdefile -I$(top_srcdir) $(QT_INCLUDES) $(X_INCLUDES) $(KDE_INCLUDES) $(USER_INCLUDES)'
AC_SUBST(all_includes)
CXXFLAGS="$CXXFLAGS $KDE_DEFAULT_CXXFLAGS"
diff --git a/dcop/client/dcopfind.cpp b/dcop/client/dcopfind.cpp
index a4bcb67bb..940d62fd6 100644
--- a/dcop/client/dcopfind.cpp
+++ b/dcop/client/dcopfind.cpp
@@ -166,16 +166,16 @@ bool launchApp(TQString app)
TQDataStream arg(data, IO_WriteOnly);
arg << app << URLs;
- if ( !dcop->call( "klauncher", "klauncher", "start_service_by_desktop_name(TQString,TQStringList)",
+ if ( !dcop->call( "tdelauncher", "tdelauncher", "start_service_by_desktop_name(TQString,TQStringList)",
data, replyType, replyData) ) {
- tqWarning( "call to klauncher failed.");
+ tqWarning( "call to tdelauncher failed.");
return false;
}
TQDataStream reply(replyData, IO_ReadOnly);
if ( replyType != "serviceResult" )
{
- tqWarning( "unexpected result '%s' from klauncher.", replyType.data());
+ tqWarning( "unexpected result '%s' from tdelauncher.", replyType.data());
return false;
}
int result;
diff --git a/dcop/client/dcopstart.cpp b/dcop/client/dcopstart.cpp
index 737184385..a3ea04726 100644
--- a/dcop/client/dcopstart.cpp
+++ b/dcop/client/dcopstart.cpp
@@ -49,7 +49,7 @@ void startApp(const char *_app, int argc, const char **args)
TQDataStream arg(data, IO_WriteOnly);
arg << app << URLs;
- if ( !dcop->call( "klauncher", "klauncher", function, data, replyType, replyData) ) {
+ if ( !dcop->call( "tdelauncher", "tdelauncher", function, data, replyType, replyData) ) {
tqWarning( "call failed");
exit(1);
} else {
diff --git a/dcop/dcopidlng/kalyptus b/dcop/dcopidlng/kalyptus
index 41f49333d..ec16d8fa8 100644
--- a/dcop/dcopidlng/kalyptus
+++ b/dcop/dcopidlng/kalyptus
@@ -1514,7 +1514,7 @@ sub makeParamList($$$)
}
if (defined $defaultparam && $isEnum) {
- # Remove any casts in enum values, for example this in kfileitem.h:
+ # Remove any casts in enum values, for example this in tdefileitem.h:
# 'enum { Unknown = (mode_t) - 1 };'
$defaultparam =~ s/\([^\)]+\)(.*[0-9].*)/$1/;
}
diff --git a/dnssd/CMakeLists.txt b/dnssd/CMakeLists.txt
index 09d96161d..01be9831c 100644
--- a/dnssd/CMakeLists.txt
+++ b/dnssd/CMakeLists.txt
@@ -45,6 +45,6 @@ tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 1.0.0
LINK tdecore-shared
- DEPENDENCIES kconfig_compiler
+ DEPENDENCIES tdeconfig_compiler
DESTINATION ${LIB_INSTALL_DIR}
)
diff --git a/doc/api/kfiledialog.png b/doc/api/tdefiledialog.png
index fa54aa3b2..fa54aa3b2 100644
--- a/doc/api/kfiledialog.png
+++ b/doc/api/tdefiledialog.png
Binary files differ
diff --git a/doc/tdelibs/man-kbuildsycoca.8.docbook b/doc/tdelibs/man-kbuildsycoca.8.docbook
deleted file mode 100644
index 670c000c0..000000000
--- a/doc/tdelibs/man-kbuildsycoca.8.docbook
+++ /dev/null
@@ -1,221 +0,0 @@
-<?xml version="1.0" ?>
-<!DOCTYPE refentry PUBLIC "-//KDE//DTD DocBook XML V4.1-Based Variant V1.0//EN" "dtd/kdex.dtd" [
- <!ENTITY % English "INCLUDE"><!-- change language only here -->
-]>
-
-<refentry>
-
-<refentryinfo>
-
-<author>
-<firstname>Darian</firstname>
-<surname>Lanx</surname>
-<affiliation>
-<address><email>content@openprojects.net</email></address>
-</affiliation>
-</author>
-
-<date>2001-04-25</date>
-<releaseinfo>0.01.01</releaseinfo>
-
-</refentryinfo>
-
-<refmeta>
-<refentrytitle>KBuildSycoca</refentrytitle>
-<manvolnum>8</manvolnum>
-</refmeta>
-
-<refnamediv>
-<refname>Description</refname>
-<refpurpose>Rebuilds the system configuration cache.</refpurpose>
-</refnamediv>
-
-<refsynopsisdiv>
-<title>Synopsis</title>
-
-<cmdsynopsis>
-<command>kbuildsycoca</command>
-
-<group>
-<arg choice="opt">--nosignal</arg>
-<arg choice="opt">--incremental</arg>
-<arg choice="opt">--help</arg>
-<arg choice="opt">--help-qt</arg>
-<arg choice="opt">--help-kde</arg>
-<arg choice="opt">--help-all</arg>
-<arg choice="opt">--author</arg>
-<arg choice="opt">-v, --version</arg>
-<arg choice="opt">--license</arg>
-</group>
-</cmdsynopsis>
-
-</refsynopsisdiv>
-
-<refsect1>
-<title>Description</title>
-
-<para>
-<command>kbuildsyscoca</command>, as part of the &tde; command line
-tools ensures the proper operation of &tde; by reading in all the
-<literal role="extension">.desktop</literal>, <literal
-role="extension">.directory</literal>, <literal
-role="extension">.kimgio</literal> and <literal
-role="extension">.protocol</literal> files to constructs a binary
-database.
-</para>
-
-<para>
-&tde; itself accesses this databse during operation to provide
-configurational information a program needs to run.
-</para>
-
-<para>
-This tool is part of ksyscoca, which stands for &tde; System
-Configuration Cache
-</para>
-
-</refsect1>
-
-<refsect1>
-<title>Options</title>
-
-<variablelist>
-<varlistentry>
-<term><option>--nosignal</option></term>
-<listitem>
-<para>Don't signal applications </para>
-</listitem>
-</varlistentry>
-
-<varlistentry>
-<term><option>--incremental</option></term>
-<listitem>
-<para>Incremental Update</para>
-</listitem>
-</varlistentry>
-
-<!-- this entire section from here to the end of the section could be an -->
-<!-- entity.. or maybe just so irrelevant as to leave it out -->
-
-<varlistentry>
-<term><option>--help</option></term>
-<listitem>
-<para>
-Show help about options
-</para>
-</listitem>
-</varlistentry>
-
-<varlistentry>
-<term><option>--help-qt</option></term>
-<listitem>
-<para>
-Show Qt specific options
-</para>
-</listitem>
-</varlistentry>
-
-<varlistentry>
-<term><option>--help-kde</option></term>
-<listitem>
-<para>
-Show KDE specific options
-</para>
-</listitem>
-</varlistentry>
-
-<varlistentry>
-<term><option>--help-all</option></term>
-<listitem>
-<para>
-Show all options
-</para>
-</listitem>
-</varlistentry>
-
-<varlistentry>
-<term><option>--author</option></term>
-<listitem>
-<para>
-Show author information
-</para>
-</listitem>
-</varlistentry>
-
-<varlistentry>
-<term><option>--version</option></term>
-<listitem>
-<para>
-Show version information
-</para>
-</listitem>
-</varlistentry>
-
-<varlistentry>
-<term><option>--license</option></term>
-<listitem>
-<para>
-Show license information
-</para>
-</listitem>
-</varlistentry>
-</variablelist>
-
-</refsect1>
-
-<refsect1>
-<title>Usage</title>
-<para>
-A standard way to run this program is by simply specifying the following
-command at the prompt
-<userinput><command>kbuildsyscoca</command></userinput>
-</para>
-
-</refsect1>
-
-<refsect1>
-<title>Files</title>
-
-<variablelist>
-<varlistentry>
-<term><filename>/tmp/tde-$USER/ksyscoca</filename></term>
-<listitem>
-<para>...</para>
-</listitem>
-</varlistentry>
-</variablelist>
-
-</refsect1>
-
-<refsect1>
-<title>Environment Variables</title>
-<variablelist>
-<varlistentry>
-<term>$<envar>TDEDIRS</envar></term>
-<listitem>
-<para>Specifies which directories are part of the KDE
-installations</para>
-</listitem>
-</varlistentry>
-</variablelist>
-
-</refsect1>
-
-<refsect1>
-<title>See Also</title>
-
-<para>tdesycoca(3), kblah(4), knogga(6)</para>
-
-</refsect1>
-
-<refsect1>
-<title>Bugs</title>
-
-<para>There are no known bugs at the time of writing.</para>
-
-</refsect1>
-
-</refentry>
-
-
-
diff --git a/doc/tdelibs/man-tdebuildsycoca.8.docbook b/doc/tdelibs/man-tdebuildsycoca.8.docbook
new file mode 100644
index 000000000..243e0f9a5
--- /dev/null
+++ b/doc/tdelibs/man-tdebuildsycoca.8.docbook
@@ -0,0 +1,221 @@
+<?xml version="1.0" ?>
+<!DOCTYPE refentry PUBLIC "-//KDE//DTD DocBook XML V4.1-Based Variant V1.0//EN" "dtd/kdex.dtd" [
+ <!ENTITY % English "INCLUDE"><!-- change language only here -->
+]>
+
+<refentry>
+
+<refentryinfo>
+
+<author>
+<firstname>Darian</firstname>
+<surname>Lanx</surname>
+<affiliation>
+<address><email>content@openprojects.net</email></address>
+</affiliation>
+</author>
+
+<date>2001-04-25</date>
+<releaseinfo>0.01.01</releaseinfo>
+
+</refentryinfo>
+
+<refmeta>
+<refentrytitle>KBuildSycoca</refentrytitle>
+<manvolnum>8</manvolnum>
+</refmeta>
+
+<refnamediv>
+<refname>Description</refname>
+<refpurpose>Rebuilds the system configuration cache.</refpurpose>
+</refnamediv>
+
+<refsynopsisdiv>
+<title>Synopsis</title>
+
+<cmdsynopsis>
+<command>tdebuildsycoca</command>
+
+<group>
+<arg choice="opt">--nosignal</arg>
+<arg choice="opt">--incremental</arg>
+<arg choice="opt">--help</arg>
+<arg choice="opt">--help-qt</arg>
+<arg choice="opt">--help-kde</arg>
+<arg choice="opt">--help-all</arg>
+<arg choice="opt">--author</arg>
+<arg choice="opt">-v, --version</arg>
+<arg choice="opt">--license</arg>
+</group>
+</cmdsynopsis>
+
+</refsynopsisdiv>
+
+<refsect1>
+<title>Description</title>
+
+<para>
+<command>kbuildsyscoca</command>, as part of the &tde; command line
+tools ensures the proper operation of &tde; by reading in all the
+<literal role="extension">.desktop</literal>, <literal
+role="extension">.directory</literal>, <literal
+role="extension">.kimgio</literal> and <literal
+role="extension">.protocol</literal> files to constructs a binary
+database.
+</para>
+
+<para>
+&tde; itself accesses this databse during operation to provide
+configurational information a program needs to run.
+</para>
+
+<para>
+This tool is part of ksyscoca, which stands for &tde; System
+Configuration Cache
+</para>
+
+</refsect1>
+
+<refsect1>
+<title>Options</title>
+
+<variablelist>
+<varlistentry>
+<term><option>--nosignal</option></term>
+<listitem>
+<para>Don't signal applications </para>
+</listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--incremental</option></term>
+<listitem>
+<para>Incremental Update</para>
+</listitem>
+</varlistentry>
+
+<!-- this entire section from here to the end of the section could be an -->
+<!-- entity.. or maybe just so irrelevant as to leave it out -->
+
+<varlistentry>
+<term><option>--help</option></term>
+<listitem>
+<para>
+Show help about options
+</para>
+</listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--help-qt</option></term>
+<listitem>
+<para>
+Show Qt specific options
+</para>
+</listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--help-kde</option></term>
+<listitem>
+<para>
+Show KDE specific options
+</para>
+</listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--help-all</option></term>
+<listitem>
+<para>
+Show all options
+</para>
+</listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--author</option></term>
+<listitem>
+<para>
+Show author information
+</para>
+</listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--version</option></term>
+<listitem>
+<para>
+Show version information
+</para>
+</listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--license</option></term>
+<listitem>
+<para>
+Show license information
+</para>
+</listitem>
+</varlistentry>
+</variablelist>
+
+</refsect1>
+
+<refsect1>
+<title>Usage</title>
+<para>
+A standard way to run this program is by simply specifying the following
+command at the prompt
+<userinput><command>kbuildsyscoca</command></userinput>
+</para>
+
+</refsect1>
+
+<refsect1>
+<title>Files</title>
+
+<variablelist>
+<varlistentry>
+<term><filename>/tmp/tde-$USER/ksyscoca</filename></term>
+<listitem>
+<para>...</para>
+</listitem>
+</varlistentry>
+</variablelist>
+
+</refsect1>
+
+<refsect1>
+<title>Environment Variables</title>
+<variablelist>
+<varlistentry>
+<term>$<envar>TDEDIRS</envar></term>
+<listitem>
+<para>Specifies which directories are part of the KDE
+installations</para>
+</listitem>
+</varlistentry>
+</variablelist>
+
+</refsect1>
+
+<refsect1>
+<title>See Also</title>
+
+<para>tdesycoca(3), kblah(4), knogga(6)</para>
+
+</refsect1>
+
+<refsect1>
+<title>Bugs</title>
+
+<para>There are no known bugs at the time of writing.</para>
+
+</refsect1>
+
+</refentry>
+
+
+
diff --git a/interfaces/kio/CMakeLists.txt b/interfaces/kio/CMakeLists.txt
index efcecf65e..a8d8a2189 100644
--- a/interfaces/kio/CMakeLists.txt
+++ b/interfaces/kio/CMakeLists.txt
@@ -13,5 +13,5 @@
install( FILES
http.h
- DESTINATION ${INCLUDE_INSTALL_DIR}/kio )
+ DESTINATION ${INCLUDE_INSTALL_DIR}/tdeio )
diff --git a/interfaces/kio/Makefile.am b/interfaces/kio/Makefile.am
index 8fad24200..daa98db05 100644
--- a/interfaces/kio/Makefile.am
+++ b/interfaces/kio/Makefile.am
@@ -1,3 +1,3 @@
-kioincludedir = $(includedir)/kio
+kioincludedir = $(includedir)/tdeio
kioinclude_HEADERS = http.h
diff --git a/interfaces/kregexpeditor/Makefile.am b/interfaces/kregexpeditor/Makefile.am
index 2007129da..4e8f5af2a 100644
--- a/interfaces/kregexpeditor/Makefile.am
+++ b/interfaces/kregexpeditor/Makefile.am
@@ -1,6 +1,6 @@
# $Id$
-INCLUDES = -I$(top_srcdir)/kio -I$(top_srcdir) $(all_includes)
+INCLUDES = -I$(top_srcdir)/tdeio -I$(top_srcdir) $(all_includes)
include_HEADERS = kregexpeditorinterface.h
diff --git a/interfaces/tdeimproxy/library/CMakeLists.txt b/interfaces/tdeimproxy/library/CMakeLists.txt
index 9aa1f60ee..40974d722 100644
--- a/interfaces/tdeimproxy/library/CMakeLists.txt
+++ b/interfaces/tdeimproxy/library/CMakeLists.txt
@@ -18,7 +18,7 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
link_directories(
@@ -45,7 +45,7 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 0.0.0
- LINK kio-shared
+ LINK tdeio-shared
DESTINATION ${LIB_INSTALL_DIR}
DEPENDENCIES dcopidl
)
diff --git a/interfaces/tdemediaplayer/CMakeLists.txt b/interfaces/tdemediaplayer/CMakeLists.txt
index 00ab7f3d9..0c9355560 100644
--- a/interfaces/tdemediaplayer/CMakeLists.txt
+++ b/interfaces/tdemediaplayer/CMakeLists.txt
@@ -10,7 +10,7 @@
#################################################
if( ARTS_FOUND )
- add_subdirectory( kfileaudiopreview )
+ add_subdirectory( tdefileaudiopreview )
endif( ARTS_FOUND )
include_directories(
diff --git a/interfaces/tdemediaplayer/Makefile.am b/interfaces/tdemediaplayer/Makefile.am
index 0b7aded07..91ed342bd 100644
--- a/interfaces/tdemediaplayer/Makefile.am
+++ b/interfaces/tdemediaplayer/Makefile.am
@@ -1,8 +1,8 @@
if include_ARTS
-kfileaudiopreview_subdir = kfileaudiopreview
+tdefileaudiopreview_subdir = tdefileaudiopreview
endif
-SUBDIRS = . $(kfileaudiopreview_subdir)
+SUBDIRS = . $(tdefileaudiopreview_subdir)
INCLUDES = -I$(srcdir)/.. $(all_includes)
lib_LTLIBRARIES = libtdemediaplayer.la
diff --git a/interfaces/tdemediaplayer/kfileaudiopreview/CMakeLists.txt b/interfaces/tdemediaplayer/kfileaudiopreview/CMakeLists.txt
deleted file mode 100644
index 17485b65a..000000000
--- a/interfaces/tdemediaplayer/kfileaudiopreview/CMakeLists.txt
+++ /dev/null
@@ -1,46 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${ARTS_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/interfaces
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
- ${CMAKE_SOURCE_DIR}/arts/kde
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
- ${ARTS_LIBRARY_DIRS}
-)
-
-
-##### kfileaudiopreview #########################
-
-set( target kfileaudiopreview )
-
-set( ${target}_SRCS
- kfileaudiopreview.cpp
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK tdemediaplayer-shared artskde-shared
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/interfaces/tdemediaplayer/kfileaudiopreview/Makefile.am b/interfaces/tdemediaplayer/kfileaudiopreview/Makefile.am
deleted file mode 100644
index 4f88a0c87..000000000
--- a/interfaces/tdemediaplayer/kfileaudiopreview/Makefile.am
+++ /dev/null
@@ -1,13 +0,0 @@
-INCLUDES = -I$(top_srcdir)/interfaces/ -I$(top_srcdir)/arts/kde -I$(includedir)/arts $(all_includes)
-METASOURCES = AUTO
-
-kde_module_LTLIBRARIES = kfileaudiopreview.la
-
-kfileaudiopreview_la_SOURCES = kfileaudiopreview.cpp
-kfileaudiopreview_la_LDFLAGS = $(all_libraries) $(KDE_RPATH) -module -avoid-version -no-undefined
-kfileaudiopreview_la_LIBADD = $(top_builddir)/interfaces/tdemediaplayer/libtdemediaplayer.la $(top_builddir)/arts/kde/libartskde.la $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE)
-
-noinst_HEADERS = kfileaudiopreview.h
-
-messages:
- $(XGETTEXT) $(kfileaudiopreview_la_SOURCES) -o $(podir)/kfileaudiopreview.pot
diff --git a/interfaces/tdemediaplayer/kfileaudiopreview/kfileaudiopreview.cpp b/interfaces/tdemediaplayer/kfileaudiopreview/kfileaudiopreview.cpp
deleted file mode 100644
index 1d83fc590..000000000
--- a/interfaces/tdemediaplayer/kfileaudiopreview/kfileaudiopreview.cpp
+++ /dev/null
@@ -1,146 +0,0 @@
-#include "kfileaudiopreview.h"
-
-#include <tqcheckbox.h>
-#include <tqhbox.h>
-#include <tqlayout.h>
-#include <tqvgroupbox.h>
-
-#include <kglobal.h>
-#include <kconfig.h>
-#include <klibloader.h>
-#include <klocale.h>
-#include <tdemediaplayer/player.h>
-#include <kmimetype.h>
-#include <tdeparts/componentfactory.h>
-
-#include <kplayobjectfactory.h>
-
-#include <config-kfile.h>
-
-class KFileAudioPreviewFactory : public KLibFactory
-{
-protected:
- virtual TQObject *createObject( TQObject *parent, const char *name,
- const char *className, const TQStringList & args)
- {
- Q_UNUSED(className);
- Q_UNUSED(args);
- return TQT_TQOBJECT(new KFileAudioPreview( dynamic_cast<TQWidget*>( parent ), name ));
- }
-};
-
-K_EXPORT_COMPONENT_FACTORY( kfileaudiopreview, KFileAudioPreviewFactory )
-
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-class KFileAudioPreview::KFileAudioPreviewPrivate
-{
-public:
- KFileAudioPreviewPrivate( TQWidget *parent )
- {
- player = KParts::ComponentFactory::createInstanceFromQuery<KMediaPlayer::Player>( "KMediaPlayer/Player", TQString(), TQT_TQOBJECT(parent) );
- }
-
- ~KFileAudioPreviewPrivate()
- {
- delete player;
- }
-
- KMediaPlayer::Player *player;
-};
-
-
-KFileAudioPreview::KFileAudioPreview( TQWidget *parent, const char *name )
- : KPreviewWidgetBase( parent, name )
-{
- TDEGlobal::locale()->insertCatalogue("kfileaudiopreview");
-
- TQStringList formats = KDE::PlayObjectFactory::mimeTypes();
- // ###
- TQStringList::ConstIterator it = formats.begin();
- for ( ; it != formats.end(); ++it )
- m_supportedFormats.insert( *it, (void*) 1 );
-
- TQVGroupBox *box = new TQVGroupBox( i18n("Media Player"), this );
- TQVBoxLayout *layout = new TQVBoxLayout( this );
- layout->addWidget( box );
-
- (void) new TQWidget( box ); // spacer
-
- d = new KFileAudioPreviewPrivate( 0L ); // not box -- being reparented anyway
- if ( d->player ) // only if there actually is a component...
- {
- setSupportedMimeTypes( formats );
- KMediaPlayer::View *view = d->player->view();
- view->setEnabled( false );
-
- // if we have access to the video widget, show it above the player
- // So, reparent first the video widget, then the view.
- if ( view->videoWidget() )
- {
- TQHBox *frame = new TQHBox( box );
- frame->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
- frame->setSizePolicy( TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Expanding ) );
- view->videoWidget()->reparent( frame, TQPoint(0,0) );
- }
-
- view->reparent( box, TQPoint(0,0) );
- }
-
- m_autoPlay = new TQCheckBox( i18n("Play &automatically"), box );
- TDEConfigGroup config( TDEGlobal::config(), ConfigGroup );
- m_autoPlay->setChecked( config.readBoolEntry( "Autoplay sounds", true ) );
- connect( m_autoPlay, TQT_SIGNAL(toggled(bool)), TQT_SLOT(toggleAuto(bool)) );
-}
-
-KFileAudioPreview::~KFileAudioPreview()
-{
- TDEConfigGroup config( TDEGlobal::config(), ConfigGroup );
- config.writeEntry( "Autoplay sounds", m_autoPlay->isChecked() );
-
- delete d;
-}
-
-void KFileAudioPreview::showPreview( const KURL &url )
-{
- if ( !d->player || !url.isValid() )
- return;
-
- KMimeType::Ptr mt = KMimeType::findByURL( url );
- bool supported = m_supportedFormats.find( mt->name() );
- d->player->view()->setEnabled( supported );
- if ( !supported )
- return;
-
- static_cast<KParts::ReadOnlyPart*>(d->player)->openURL( url );
- if ( m_autoPlay->isChecked() )
- d->player->play();
-}
-
-void KFileAudioPreview::clearPreview()
-{
- if ( d->player )
- {
- d->player->stop();
- d->player->closeURL();
- }
-}
-
-void KFileAudioPreview::toggleAuto( bool on )
-{
- if ( !d->player )
- return;
-
- if ( on && m_currentURL.isValid() && d->player->view()->isEnabled() )
- d->player->play();
- else
- d->player->stop();
-}
-
-void KFileAudioPreview::virtual_hook( int, void* )
-{}
-
-#include "kfileaudiopreview.moc"
diff --git a/interfaces/tdemediaplayer/tdefileaudiopreview/CMakeLists.txt b/interfaces/tdemediaplayer/tdefileaudiopreview/CMakeLists.txt
new file mode 100644
index 000000000..8e561e1f3
--- /dev/null
+++ b/interfaces/tdemediaplayer/tdefileaudiopreview/CMakeLists.txt
@@ -0,0 +1,46 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${ARTS_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/interfaces
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
+ ${CMAKE_SOURCE_DIR}/arts/kde
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+ ${ARTS_LIBRARY_DIRS}
+)
+
+
+##### tdefileaudiopreview #########################
+
+set( target tdefileaudiopreview )
+
+set( ${target}_SRCS
+ tdefileaudiopreview.cpp
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdemediaplayer-shared artskde-shared
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/interfaces/tdemediaplayer/tdefileaudiopreview/Makefile.am b/interfaces/tdemediaplayer/tdefileaudiopreview/Makefile.am
new file mode 100644
index 000000000..d73cf545f
--- /dev/null
+++ b/interfaces/tdemediaplayer/tdefileaudiopreview/Makefile.am
@@ -0,0 +1,13 @@
+INCLUDES = -I$(top_srcdir)/interfaces/ -I$(top_srcdir)/arts/kde -I$(includedir)/arts $(all_includes)
+METASOURCES = AUTO
+
+kde_module_LTLIBRARIES = tdefileaudiopreview.la
+
+tdefileaudiopreview_la_SOURCES = tdefileaudiopreview.cpp
+tdefileaudiopreview_la_LDFLAGS = $(all_libraries) $(KDE_RPATH) -module -avoid-version -no-undefined
+tdefileaudiopreview_la_LIBADD = $(top_builddir)/interfaces/tdemediaplayer/libtdemediaplayer.la $(top_builddir)/arts/kde/libartskde.la $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE)
+
+noinst_HEADERS = tdefileaudiopreview.h
+
+messages:
+ $(XGETTEXT) $(tdefileaudiopreview_la_SOURCES) -o $(podir)/tdefileaudiopreview.pot
diff --git a/interfaces/tdemediaplayer/tdefileaudiopreview/tdefileaudiopreview.cpp b/interfaces/tdemediaplayer/tdefileaudiopreview/tdefileaudiopreview.cpp
new file mode 100644
index 000000000..7dd746c4f
--- /dev/null
+++ b/interfaces/tdemediaplayer/tdefileaudiopreview/tdefileaudiopreview.cpp
@@ -0,0 +1,146 @@
+#include "tdefileaudiopreview.h"
+
+#include <tqcheckbox.h>
+#include <tqhbox.h>
+#include <tqlayout.h>
+#include <tqvgroupbox.h>
+
+#include <kglobal.h>
+#include <tdeconfig.h>
+#include <klibloader.h>
+#include <klocale.h>
+#include <tdemediaplayer/player.h>
+#include <kmimetype.h>
+#include <tdeparts/componentfactory.h>
+
+#include <kplayobjectfactory.h>
+
+#include <config-tdefile.h>
+
+class KFileAudioPreviewFactory : public KLibFactory
+{
+protected:
+ virtual TQObject *createObject( TQObject *parent, const char *name,
+ const char *className, const TQStringList & args)
+ {
+ Q_UNUSED(className);
+ Q_UNUSED(args);
+ return TQT_TQOBJECT(new KFileAudioPreview( dynamic_cast<TQWidget*>( parent ), name ));
+ }
+};
+
+K_EXPORT_COMPONENT_FACTORY( tdefileaudiopreview, KFileAudioPreviewFactory )
+
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+class KFileAudioPreview::KFileAudioPreviewPrivate
+{
+public:
+ KFileAudioPreviewPrivate( TQWidget *parent )
+ {
+ player = KParts::ComponentFactory::createInstanceFromQuery<KMediaPlayer::Player>( "KMediaPlayer/Player", TQString(), TQT_TQOBJECT(parent) );
+ }
+
+ ~KFileAudioPreviewPrivate()
+ {
+ delete player;
+ }
+
+ KMediaPlayer::Player *player;
+};
+
+
+KFileAudioPreview::KFileAudioPreview( TQWidget *parent, const char *name )
+ : KPreviewWidgetBase( parent, name )
+{
+ TDEGlobal::locale()->insertCatalogue("tdefileaudiopreview");
+
+ TQStringList formats = KDE::PlayObjectFactory::mimeTypes();
+ // ###
+ TQStringList::ConstIterator it = formats.begin();
+ for ( ; it != formats.end(); ++it )
+ m_supportedFormats.insert( *it, (void*) 1 );
+
+ TQVGroupBox *box = new TQVGroupBox( i18n("Media Player"), this );
+ TQVBoxLayout *layout = new TQVBoxLayout( this );
+ layout->addWidget( box );
+
+ (void) new TQWidget( box ); // spacer
+
+ d = new KFileAudioPreviewPrivate( 0L ); // not box -- being reparented anyway
+ if ( d->player ) // only if there actually is a component...
+ {
+ setSupportedMimeTypes( formats );
+ KMediaPlayer::View *view = d->player->view();
+ view->setEnabled( false );
+
+ // if we have access to the video widget, show it above the player
+ // So, reparent first the video widget, then the view.
+ if ( view->videoWidget() )
+ {
+ TQHBox *frame = new TQHBox( box );
+ frame->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
+ frame->setSizePolicy( TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Expanding ) );
+ view->videoWidget()->reparent( frame, TQPoint(0,0) );
+ }
+
+ view->reparent( box, TQPoint(0,0) );
+ }
+
+ m_autoPlay = new TQCheckBox( i18n("Play &automatically"), box );
+ TDEConfigGroup config( TDEGlobal::config(), ConfigGroup );
+ m_autoPlay->setChecked( config.readBoolEntry( "Autoplay sounds", true ) );
+ connect( m_autoPlay, TQT_SIGNAL(toggled(bool)), TQT_SLOT(toggleAuto(bool)) );
+}
+
+KFileAudioPreview::~KFileAudioPreview()
+{
+ TDEConfigGroup config( TDEGlobal::config(), ConfigGroup );
+ config.writeEntry( "Autoplay sounds", m_autoPlay->isChecked() );
+
+ delete d;
+}
+
+void KFileAudioPreview::showPreview( const KURL &url )
+{
+ if ( !d->player || !url.isValid() )
+ return;
+
+ KMimeType::Ptr mt = KMimeType::findByURL( url );
+ bool supported = m_supportedFormats.find( mt->name() );
+ d->player->view()->setEnabled( supported );
+ if ( !supported )
+ return;
+
+ static_cast<KParts::ReadOnlyPart*>(d->player)->openURL( url );
+ if ( m_autoPlay->isChecked() )
+ d->player->play();
+}
+
+void KFileAudioPreview::clearPreview()
+{
+ if ( d->player )
+ {
+ d->player->stop();
+ d->player->closeURL();
+ }
+}
+
+void KFileAudioPreview::toggleAuto( bool on )
+{
+ if ( !d->player )
+ return;
+
+ if ( on && m_currentURL.isValid() && d->player->view()->isEnabled() )
+ d->player->play();
+ else
+ d->player->stop();
+}
+
+void KFileAudioPreview::virtual_hook( int, void* )
+{}
+
+#include "tdefileaudiopreview.moc"
diff --git a/interfaces/tdemediaplayer/kfileaudiopreview/kfileaudiopreview.h b/interfaces/tdemediaplayer/tdefileaudiopreview/tdefileaudiopreview.h
index de48e4712..de48e4712 100644
--- a/interfaces/tdemediaplayer/kfileaudiopreview/kfileaudiopreview.h
+++ b/interfaces/tdemediaplayer/tdefileaudiopreview/tdefileaudiopreview.h
diff --git a/interfaces/tdescript/CMakeLists.txt b/interfaces/tdescript/CMakeLists.txt
index bcddb1068..6b57cdeb9 100644
--- a/interfaces/tdescript/CMakeLists.txt
+++ b/interfaces/tdescript/CMakeLists.txt
@@ -19,8 +19,8 @@ include_directories(
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
link_directories(
@@ -51,6 +51,6 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 0.0.0
- LINK kio-shared
+ LINK tdeio-shared
DESTINATION ${LIB_INSTALL_DIR}
)
diff --git a/interfaces/tdescript/Makefile.am b/interfaces/tdescript/Makefile.am
index 55d4cac35..03c7efc87 100644
--- a/interfaces/tdescript/Makefile.am
+++ b/interfaces/tdescript/Makefile.am
@@ -1,6 +1,6 @@
SUBDIRS = . sample
-INCLUDES = -I$(top_srcdir)/kio -I$(top_srcdir) -I$(srcdir) -I$(srcdir)/.. $(all_includes)
+INCLUDES = -I$(top_srcdir)/tdeio -I$(top_srcdir) -I$(srcdir) -I$(srcdir)/.. $(all_includes)
#lib_LTLIBRARIES = libtdescriptloader.la libtdescript.la
lib_LTLIBRARIES = libtdescript.la
diff --git a/interfaces/tdescript/sample/Makefile.am b/interfaces/tdescript/sample/Makefile.am
index 77d39b28c..e20854c70 100644
--- a/interfaces/tdescript/sample/Makefile.am
+++ b/interfaces/tdescript/sample/Makefile.am
@@ -1,4 +1,4 @@
-INCLUDES = -I$(top_srcdir)/kio -I$(top_srcdir)/interfaces -I$(srcdir) -I$(top_srcdir) -I$(top_srcdir)/interfaces/tdescript $(all_includes)
+INCLUDES = -I$(top_srcdir)/tdeio -I$(top_srcdir)/interfaces -I$(srcdir) -I$(top_srcdir) -I$(top_srcdir)/interfaces/tdescript $(all_includes)
kde_module_LTLIBRARIES = libshellscript.la
diff --git a/interfaces/tdescript/scriptloader.cpp b/interfaces/tdescript/scriptloader.cpp
index 79fa2055a..1ff34f98a 100644
--- a/interfaces/tdescript/scriptloader.cpp
+++ b/interfaces/tdescript/scriptloader.cpp
@@ -23,7 +23,7 @@
#include <tdeparts/componentfactory.h>
#include <kglobal.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdesktopfile.h>
#include <kstandarsdirs.h>
#include <kstdaccel.h>
diff --git a/interfaces/tdetexteditor/CMakeLists.txt b/interfaces/tdetexteditor/CMakeLists.txt
index a9d39edbb..0808a84f3 100644
--- a/interfaces/tdetexteditor/CMakeLists.txt
+++ b/interfaces/tdetexteditor/CMakeLists.txt
@@ -20,8 +20,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/kabc
${CMAKE_SOURCE_DIR}/interfaces
)
diff --git a/interfaces/tdetexteditor/Makefile.am b/interfaces/tdetexteditor/Makefile.am
index 5663bb761..fce0ec563 100644
--- a/interfaces/tdetexteditor/Makefile.am
+++ b/interfaces/tdetexteditor/Makefile.am
@@ -1,4 +1,4 @@
-INCLUDES = -I$(top_srcdir)/kio -I$(top_srcdir) -I$(top_srcdir)/interfaces -I$(top_builddir)/interfaces -I$(top_srcdir)/kabc -I$(top_builddir)/kabc $(all_includes)
+INCLUDES = -I$(top_srcdir)/tdeio -I$(top_srcdir) -I$(top_srcdir)/interfaces -I$(top_builddir)/interfaces -I$(top_srcdir)/kabc -I$(top_builddir)/kabc $(all_includes)
lib_LTLIBRARIES = libtdetexteditor.la
diff --git a/interfaces/tdetexteditor/configinterface.h b/interfaces/tdetexteditor/configinterface.h
index ed6a80d81..10a6173a0 100644
--- a/interfaces/tdetexteditor/configinterface.h
+++ b/interfaces/tdetexteditor/configinterface.h
@@ -57,7 +57,7 @@ class KTEXTEDITOR_EXPORT ConfigInterface
virtual void writeConfig () = 0;
/**
- Read/Write the config of the part to a given kconfig object
+ Read/Write the config of the part to a given tdeconfig object
to store the settings in a different place than the standard
*/
virtual void readConfig (TDEConfig *) = 0;
diff --git a/interfaces/tdetexteditor/editorchooser.cpp b/interfaces/tdetexteditor/editorchooser.cpp
index 807d342d0..ce493018d 100644
--- a/interfaces/tdetexteditor/editorchooser.cpp
+++ b/interfaces/tdetexteditor/editorchooser.cpp
@@ -3,7 +3,7 @@
#include <tqcombobox.h>
#include <ktrader.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqstringlist.h>
#include <kservice.h>
#include <klocale.h>
diff --git a/kabc/CMakeLists.txt b/kabc/CMakeLists.txt
index 5f2619cf9..57c4741fe 100644
--- a/kabc/CMakeLists.txt
+++ b/kabc/CMakeLists.txt
@@ -29,8 +29,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/kab
)
@@ -58,7 +58,7 @@ install( FILES
##### other data ################################
-install( FILES kab2kabc.desktop DESTINATION ${AUTOSTART_INSTALL_DIR} )
+install( FILES tdeab2tdeabc.desktop DESTINATION ${AUTOSTART_INSTALL_DIR} )
install( FILES kabc_manager.desktop DESTINATION ${SERVICES_INSTALL_DIR}/tderesources )
install( FILES countrytransl.map DESTINATION ${DATA_INSTALL_DIR}/kabc )
@@ -102,18 +102,18 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 1.2.0
- LINK vcards-static vcard-shared kio-shared tderesources-shared
+ LINK vcards-static vcard-shared tdeio-shared tderesources-shared
DEPENDENCIES addressee.h dcopidl
DESTINATION ${LIB_INSTALL_DIR}
)
-##### kab2kabc ##################################
+##### tdeab2tdeabc ##################################
-set( target kab2kabc )
+set( target tdeab2tdeabc )
set( ${target}_SRCS
- kab2kabc.cpp
+ tdeab2tdeabc.cpp
)
tde_add_executable( ${target}
diff --git a/kabc/Makefile.am b/kabc/Makefile.am
index ef989662f..57e72aec2 100644
--- a/kabc/Makefile.am
+++ b/kabc/Makefile.am
@@ -50,13 +50,13 @@ kabcinclude_HEADERS = address.h addressbook.h addressee.h addresseedialog.h \
METASOURCES = AUTO
-bin_PROGRAMS = kab2kabc
+bin_PROGRAMS = tdeab2tdeabc
-kab2kabc_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-kab2kabc_LDADD = libkabc.la ../kab/libkab.la
-kab2kabc_SOURCES = kab2kabc.cpp
+tdeab2tdeabc_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+tdeab2tdeabc_LDADD = libkabc.la ../kab/libkab.la
+tdeab2tdeabc_SOURCES = tdeab2tdeabc.cpp
-autostart_DATA = kab2kabc.desktop
+autostart_DATA = tdeab2tdeabc.desktop
autostartdir = $(datadir)/autostart
manager_DATA = kabc_manager.desktop
diff --git a/kabc/addresseehelper.cpp b/kabc/addresseehelper.cpp
index 908795869..5b8998852 100644
--- a/kabc/addresseehelper.cpp
+++ b/kabc/addresseehelper.cpp
@@ -19,7 +19,7 @@
#include <tqapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
#include "addresseehelper.h"
diff --git a/kabc/addresslineedit.cpp b/kabc/addresslineedit.cpp
index 76d99f634..efb0738aa 100644
--- a/kabc/addresslineedit.cpp
+++ b/kabc/addresslineedit.cpp
@@ -33,7 +33,7 @@
#include <tqdragobject.h>
#include <kcompletionbox.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kcursor.h>
#include <kstandarddirs.h>
#include <kstaticdeleter.h>
diff --git a/kabc/formatfactory.h b/kabc/formatfactory.h
index 76a3704d5..ff9da5504 100644
--- a/kabc/formatfactory.h
+++ b/kabc/formatfactory.h
@@ -24,7 +24,7 @@
#include <tqdict.h>
#include <tqstring.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klibloader.h>
#include "formatplugin.h"
diff --git a/kabc/formats/CMakeLists.txt b/kabc/formats/CMakeLists.txt
index 327cb1ea6..60ea1c3fd 100644
--- a/kabc/formats/CMakeLists.txt
+++ b/kabc/formats/CMakeLists.txt
@@ -18,8 +18,8 @@ include_directories(
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
link_directories(
diff --git a/kabc/kab2kabc.cpp b/kabc/kab2kabc.cpp
deleted file mode 100644
index 11b80639a..000000000
--- a/kabc/kab2kabc.cpp
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- This file is part of libkabc.
- Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqfile.h>
-#include <tqtextstream.h>
-
-#include <kabapi.h>
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kcmdlineargs.h>
-#include <kconfig.h>
-#include <kdebug.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <kstandarddirs.h>
-
-#include "addressbook.h"
-#include "stdaddressbook.h"
-
-using namespace KABC;
-
-static const KCmdLineOptions options[] =
-{
- { "disable-autostart", I18N_NOOP( "Disable automatic startup on login" ), 0 },
- { "quiet", "", 0 },
- { "o", 0, 0 },
- { "override", I18N_NOOP( "Override existing entries" ), "1" },
- KCmdLineLastOption
-};
-
-void readKMailEntry( const TQString &kmailEntry, KABC::AddressBook *ab )
-{
- kdDebug() << "KMAILENTRY: " << kmailEntry << endl;
-
- TQString entry = kmailEntry.simplifyWhiteSpace();
- if ( entry.isEmpty() ) return;
-
- TQString email;
- TQString name;
- TQString comment;
-
- if ( entry.at( entry.length() -1 ) == ')' ) {
- int br = entry.findRev( '(' );
- if ( br >= 0 ) {
- comment = entry.mid( br + 1, entry.length() - br - 2 );
- entry.truncate( br );
- if ( entry.at( entry.length() - 1 ).isSpace() ) {
- entry.truncate( br - 1 );
- }
- }
- }
-
- int posSpace = entry.findRev( ' ' );
- if ( posSpace < 0 ) {
- email = entry;
- if ( !comment.isEmpty() ) {
- name = comment;
- comment = "";
- }
- } else {
- email = entry.mid( posSpace + 1 );
- name = entry.left( posSpace );
- }
-
- if ( email.at( 0 ) == '<' && email.at( email.length() - 1) == '>' ) {
- email = email.mid( 1, email.length() - 2 );
- }
- if ( name.at( 0 ) == '"' && name.at( name.length() - 1) == '"' ) {
- name = name.mid( 1, name.length() - 2 );
- }
- if ( name.at( 0 ) == '\'' && name.at( name.length() - 1) == '\'' ) {
- name = name.mid( 1, name.length() - 2 );
- }
-
- if ( name.at( name.length() -1 ) == ')' ) {
- int br = name.findRev( '(' );
- if ( br >= 0 ) {
- comment = name.mid( br + 1, name.length() - br - 2 ) + " " + comment;
- name.truncate( br );
- if ( name.at( name.length() - 1 ).isSpace() ) {
- name.truncate( br - 1 );
- }
- }
- }
-
- kdDebug() << " EMAIL : " << email << endl;
- kdDebug() << " NAME : " << name << endl;
- kdDebug() << " COMMENT : " << comment << endl;
-
- KABC::Addressee::List al = ab->findByEmail( email );
- if ( al.isEmpty() ) {
- KABC::Addressee a;
- a.setNameFromString( name );
- a.insertEmail( email );
- a.setNote( comment );
-
- ab->insertAddressee( a );
-
- kdDebug() << "--INSERTED: " << a.realName() << endl;
- }
-}
-
-void importKMailAddressBook( KABC::AddressBook *ab )
-{
- TQString fileName = locateLocal( "data", "kmail/addressbook" );
- TQString kmailConfigName = locate( "config", "kmailrc" );
- if ( !kmailConfigName.isEmpty() ) {
- TDEConfig cfg( kmailConfigName );
- cfg.setGroup( "Addressbook" );
- fileName = cfg.readPathEntry( "default", fileName );
- }
- if ( !KStandardDirs::exists( fileName ) ) {
- kdDebug(5700) << "Couldn't find KMail addressbook." << endl;
- return;
- }
-
- TQFile f( fileName );
- if ( !f.open(IO_ReadOnly) ) {
- kdDebug(5700) << "Couldn't open file '" << fileName << "'" << endl;
- return;
- }
-
- TQStringList kmailEntries;
-
- TQTextStream t( &f );
- while ( !t.eof() ) {
- kmailEntries.append( t.readLine() );
- }
- f.close();
-
- TQStringList::ConstIterator it;
- for ( it = kmailEntries.begin(); it != kmailEntries.end(); ++it ) {
- if ( (*it).at( 0 ) == '#' ) continue;
- bool insideQuote = false;
- int end = (*it).length() - 1;
- for ( int i = end; i; i-- ) {
- if ( (*it).at( i ) == '"' ) {
- if ( insideQuote )
- insideQuote = false;
- else
- insideQuote = true;
- } else if ( (*it).at( i ) == ',' && !insideQuote ) {
- readKMailEntry( (*it).mid( i + 1, end - i ), ab );
- end = i - 1;
- }
- }
-
- readKMailEntry( (*it).mid( 0, end + 1 ), ab );
- }
-}
-
-void readKAddressBookEntries( const TQString &dataString, Addressee &a )
-{
- // Strip "KMail:1.0" prefix and "[EOS]" suffix.
- TQString str = dataString.mid( 11, dataString.length() - 24 );
-
- TQStringList entries = TQStringList::split( "\n[EOR]\n ", str );
-
- Address homeAddress( Address::Home );
- Address businessAddress( Address::Work );
- Address otherAddress;
-
- TQStringList::ConstIterator it;
- for ( it = entries.begin(); it != entries.end(); ++it ) {
- int pos = (*it).find( "\n" );
- TQString fieldName = (*it).left( pos );
- TQString fieldValue = (*it).mid( pos + 2 );
-
- if ( fieldName == "X-HomeFax" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Home |
- PhoneNumber::Fax ) );
- } else if ( fieldName == "X-OtherPhone" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, 0 ) );
- } else if ( fieldName == "X-PrimaryPhone" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Pref ) );
- } else if ( fieldName == "X-BusinessFax" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Work |
- PhoneNumber::Fax ) );
- } else if ( fieldName == "X-CarPhone" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Car ) );
- } else if ( fieldName == "X-MobilePhone" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Cell ) );
- } else if ( fieldName == "X-ISDN" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Isdn ) );
- } else if ( fieldName == "X-OtherFax" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Fax ) );
- } else if ( fieldName == "X-Pager" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Pager ) );
- } else if ( fieldName == "X-BusinessPhone" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Work ) );
- } else if ( fieldName == "X-HomePhone" ) {
- a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Home ) );
- } else if ( fieldName == "X-HomeAddress" ) {
- homeAddress.setLabel( fieldValue );
- } else if ( fieldName == "X-HomeAddressStreet" ) {
- homeAddress.setStreet( fieldValue );
- } else if ( fieldName == "X-HomeAddressCity" ) {
- homeAddress.setLocality( fieldValue );
- } else if ( fieldName == "X-HomeAddressPostalCode" ) {
- homeAddress.setPostalCode( fieldValue );
- } else if ( fieldName == "X-HomeAddressState" ) {
- homeAddress.setRegion( fieldValue );
- } else if ( fieldName == "X-HomeAddressCountry" ) {
- homeAddress.setCountry( fieldValue );
- } else if ( fieldName == "X-BusinessAddress" ) {
- businessAddress.setLabel( fieldValue );
- } else if ( fieldName == "X-BusinessAddressStreet" ) {
- businessAddress.setStreet( fieldValue );
- } else if ( fieldName == "X-BusinessAddressCity" ) {
- businessAddress.setLocality( fieldValue );
- } else if ( fieldName == "X-BusinessAddressPostalCode" ) {
- businessAddress.setPostalCode( fieldValue );
- } else if ( fieldName == "X-BusinessAddressState" ) {
- businessAddress.setRegion( fieldValue );
- } else if ( fieldName == "X-BusinessAddressCountry" ) {
- businessAddress.setCountry( fieldValue );
- } else if ( fieldName == "X-OtherAddress" ) {
- otherAddress.setLabel( fieldValue );
- } else if ( fieldName == "X-OtherAddressStreet" ) {
- otherAddress.setStreet( fieldValue );
- } else if ( fieldName == "X-OtherAddressCity" ) {
- otherAddress.setLocality( fieldValue );
- } else if ( fieldName == "X-OtherAddressPostalCode" ) {
- otherAddress.setPostalCode( fieldValue );
- } else if ( fieldName == "X-OtherAddressState" ) {
- otherAddress.setRegion( fieldValue );
- } else if ( fieldName == "X-OtherAddressCountry" ) {
- otherAddress.setCountry( fieldValue );
- } else if ( fieldName == "NICKNAME" ) {
- a.setNickName( fieldValue );
- } else if ( fieldName == "ORG" ) {
- a.setOrganization( fieldValue );
- } else if ( fieldName == "ROLE" ) {
- a.setRole( fieldValue );
- } else if ( fieldName == "BDAY" ) {
- a.setBirthday( TDEGlobal::locale()->readDate( fieldValue ) );
- } else if ( fieldName == "WEBPAGE" ) {
- a.setUrl( KURL( fieldValue ) );
- } else if ( fieldName == "N" ) {
- } else if ( fieldName == "X-FirstName" ) {
- } else if ( fieldName == "X-MiddleName" ) {
- } else if ( fieldName == "X-LastName" ) {
- } else if ( fieldName == "X-Title" ) {
- } else if ( fieldName == "X-Suffix" ) {
- } else if ( fieldName == "X-FileAs" ) {
- } else if ( fieldName == "EMAIL" ) {
- a.insertEmail( fieldValue, true );
- } else if ( fieldName == "X-E-mail2" ) {
- a.insertEmail( fieldValue );
- } else if ( fieldName == "X-E-mail3" ) {
- a.insertEmail( fieldValue );
- } else if ( fieldName == "X-Notes" ) {
- } else {
- a.insertCustom( "KADDRESSBOOK", fieldName, fieldValue );
- }
- }
-
- if ( !homeAddress.isEmpty() ) a.insertAddress( homeAddress );
- if ( !businessAddress.isEmpty() ) a.insertAddress( businessAddress );
- if ( !otherAddress.isEmpty() ) a.insertAddress( otherAddress );
-}
-
-void importKab( KABC::AddressBook *ab, bool override, bool quiet )
-{
- TQString fileName = TDEGlobal::dirs()->saveLocation( "data", "kab/" );
- fileName += "addressbook.kab";
- if ( !TQFile::exists( fileName ) ) {
- if ( !quiet ) {
- KMessageBox::error( 0, "<qt>" + i18n( "Address book file <b>%1</b> not found! Make sure the old address book is located there and you have read permission for this file." )
- .arg( fileName ) + "</qt>" );
- }
- kdDebug(5700) << "No KDE 2 addressbook found." << endl;
- return;
- }
-
- kdDebug(5700) << "Converting old-style kab addressbook to "
- "new-style kabc addressbook." << endl;
-
- KabAPI kab( 0 );
- if ( kab.init() != ::AddressBook::NoError ) {
- kdDebug(5700) << "Error initing kab" << endl;
- exit( 1 );
- }
-
- KabKey key;
- ::AddressBook::Entry entry;
-
- int num = kab.addressbook()->noOfEntries();
-
- kdDebug(5700) << "kab Addressbook has " << num << " entries." << endl;
-
- for ( int i = 0; i < num; ++i ) {
- if ( ::AddressBook::NoError != kab.addressbook()->getKey( i, key ) ) {
- kdDebug(5700) << "Error getting key for index " << i << " from kab." << endl;
- continue;
- }
- if ( ::AddressBook::NoError != kab.addressbook()->getEntry( key, entry ) ) {
- kdDebug(5700) << "Error getting entry for index " << i << " from kab." << endl;
- continue;
- }
-
- Addressee a;
-
- // Convert custom entries
- int count = 0;
- bool idFound = false;
- TQStringList::ConstIterator customIt;
- for ( customIt = entry.custom.begin(); customIt != entry.custom.end(); ++customIt ) {
- if ( (*customIt).startsWith( "X-KABC-UID:" ) ) {
- a.setUid( (*customIt).mid( (*customIt).find( ":" ) + 1 ) );
- idFound = true;
- } else if ( (*customIt).startsWith( "KMail:1.0\n" ) ) {
- readKAddressBookEntries( *customIt, a );
- } else {
- a.insertCustom( "kab2kabc", TQString::number( count++ ), *customIt );
- }
- }
- if ( idFound ) {
- if ( !override ) continue;
- } else {
- entry.custom << "X-KABC-UID:" + a.uid();
- ::AddressBook::ErrorCode error = kab.addressbook()->change( key, entry );
- if ( error != ::AddressBook::NoError ) {
- kdDebug(5700) << "kab.change returned with error " << error << endl;
- } else {
- kdDebug(5700) << "Wrote back to kab uid " << a.uid() << endl;
- }
- }
-
- a.setTitle( entry.title );
- a.setFormattedName( entry.fn );
- a.setPrefix( entry.nameprefix );
- a.setGivenName( entry.firstname );
- a.setAdditionalName( entry.middlename );
- a.setFamilyName( entry.lastname );
- a.setBirthday( entry.birthday );
-
- TQStringList::ConstIterator emailIt;
- for ( emailIt = entry.emails.begin(); emailIt != entry.emails.end(); ++emailIt )
- a.insertEmail( *emailIt );
-
- TQStringList::ConstIterator phoneIt;
- for ( phoneIt = entry.telephone.begin(); phoneIt != entry.telephone.end(); ++phoneIt ) {
- int kabType = (*phoneIt++).toInt();
- if ( phoneIt == entry.telephone.end() ) break;
- TQString number = *phoneIt;
- int type = 0;
- if ( kabType == ::AddressBook::Fixed ) type = PhoneNumber::Voice;
- else if ( kabType == ::AddressBook::Mobile ) type = PhoneNumber::Cell | PhoneNumber::Voice;
- else if ( kabType == ::AddressBook::Fax ) type = PhoneNumber::Fax;
- else if ( kabType == ::AddressBook::Modem ) type = PhoneNumber::Modem;
- a.insertPhoneNumber( PhoneNumber( number, type ) );
- }
-
- if ( entry.URLs.count() > 0 ) {
- a.setUrl( KURL( entry.URLs.first() ) );
- if ( entry.URLs.count() > 1 ) {
- kdWarning() << "More than one URL. Ignoring all but the first." << endl;
- }
- }
-
- int noAdr = entry.noOfAddresses();
- for ( int j = 0; j < noAdr; ++j ) {
- ::AddressBook::Entry::Address kabAddress;
- entry.getAddress( j, kabAddress );
-
- Address adr;
-
- adr.setStreet( kabAddress.address );
- adr.setPostalCode( kabAddress.zip );
- adr.setLocality( kabAddress.town );
- adr.setCountry( kabAddress.country );
- adr.setRegion( kabAddress.state );
-
- TQString label;
- if ( !kabAddress.headline.isEmpty() ) label += kabAddress.headline + "\n";
- if ( !kabAddress.position.isEmpty() ) label += kabAddress.position + "\n";
- if ( !kabAddress.org.isEmpty() ) label += kabAddress.org + "\n";
- if ( !kabAddress.orgUnit.isEmpty() ) label += kabAddress.orgUnit + "\n";
- if ( !kabAddress.orgSubUnit.isEmpty() ) label += kabAddress.orgSubUnit + "\n";
- if ( !kabAddress.deliveryLabel.isEmpty() ) label += kabAddress.deliveryLabel + "\n";
- adr.setLabel( label );
-
- a.insertAddress( adr );
- }
-
- TQString note = entry.comment;
-
- if ( !entry.user1.isEmpty() ) note += "\nUser1: " + entry.user1;
- if ( !entry.user2.isEmpty() ) note += "\nUser2: " + entry.user2;
- if ( !entry.user3.isEmpty() ) note += "\nUser3: " + entry.user3;
- if ( !entry.user4.isEmpty() ) note += "\nUser4: " + entry.user4;
-
- if ( !entry.keywords.count() == 0 ) note += "\nKeywords: " + entry.keywords.join( ", " );
-
- TQStringList::ConstIterator talkIt;
- for ( talkIt = entry.talk.begin(); talkIt != entry.talk.end(); ++talkIt ) {
- note += "\nTalk: " + (*talkIt);
- }
-
- a.setNote( note );
-
- a.setPrefix( entry.rank + a.prefix() ); // Add rank to prefix
-
- a.setCategories( entry.categories );
-
- kdDebug(5700) << "Addressee: " << a.familyName() << endl;
-
- ab->insertAddressee( a );
- }
-
- kab.save( true );
-}
-
-int main( int argc, char **argv )
-{
- TDEAboutData aboutData( "kab2kabc", I18N_NOOP( "Kab to Kabc Converter" ), "0.1" );
- aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
-
- TDECmdLineArgs::init( argc, argv, &aboutData );
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDEApplication app;
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- bool override = false;
-
- if ( args->isSet( "override" ) ) {
- kdDebug() << "Override existing entries." << endl;
-
- override = true;
- }
-
- bool quiet = false;
-
- if ( args->isSet( "quiet" ) )
- quiet = true;
-
- if ( args->isSet( "disable-autostart" ) ) {
- kdDebug() << "Disable autostart." << endl;
-
- TDEConfig *config = app.config();
- config->setGroup( "Startup" );
- config->writeEntry( "EnableAutostart", false );
- }
-
- KABC::AddressBook *kabcBook = StdAddressBook::self();
-
- importKMailAddressBook( kabcBook );
-
- importKab( kabcBook, override, quiet );
-
- StdAddressBook::save();
-
- kdDebug(5700) << "Saved kabc addressbook to '" << kabcBook->identifier() << "'" << endl;
-}
-
diff --git a/kabc/kab2kabc.desktop b/kabc/kab2kabc.desktop
deleted file mode 100644
index 3015b3935..000000000
--- a/kabc/kab2kabc.desktop
+++ /dev/null
@@ -1,105 +0,0 @@
-[Desktop Entry]
-Name=kab2kabc
-Name[af]=kab-na-kabc
-Name[csb]=Kònwersëjô adresowi knéżczi
-Name[eo]=Konvertilo de "kab" al "kabc"
-Name[fr]=KAB2KABC
-Name[fy]=Kab2kabc
-Name[hu]=Kab2kabc
-Name[it]=Kab2Kabc
-Name[nl]=Kab2kabc
-Name[pl]=Konwersja książki adresowej
-Name[pt_BR]=Conversão de kab para kabc
-Name[ro]=Kab2kabc
-Name[sv]=Kab2kabc
-Name[te]=కెఎబి2కెఎబిసి
-Name[zu]=i-kab2kabc
-Exec=kab2kabc --disable-autostart --quiet
-Icon=misc
-Type=Application
-Comment=libkab to libkabc conversion tool.
-Comment[af]=libkab na libkabc omskakeling program.
-Comment[ar]=أداة تحويل libkab إلى libkabc.
-Comment[az]=libkab - libkabc dönüşdürmə vasitəsi.
-Comment[be]=ІнÑтрумент пераўтварÑÐ½Ð½Ñ libkab у libkabc.
-Comment[bg]=Програма за конвертиране на libkab до libkabc.
-Comment[bn]=libkab থেকে libkabc-তে পরিবরà§à¦¤à¦¨ করার পà§à¦°à§‹à¦—à§à¦°à¦¾à¦®à¥¤
-Comment[bs]=alat za pretvaranje libkab u libkabc.
-Comment[ca]=Eina de conversió de libkab a libkabc.
-Comment[cs]=Převod dat z libkab do libkabc.
-Comment[csb]=Nôrzãdze do kònwersëji z libkab do libkabc.
-Comment[cy]=erfyn trosi libkab i libkabc
-Comment[da]=libkab-til-libkabc-konverteringsværktøj.
-Comment[de]=Konvertierung von libkab in libkabc
-Comment[el]=ΕÏγαλείο μετατÏοπής από το libkab στο libkabc.
-Comment[eo]=Konvertilo de "libkab" al "libkabc"
-Comment[es]=Conversor libkab a libkabc.
-Comment[et]=libkab -> libkabc teisendamine
-Comment[eu]=libkab-etik libkabc-era bihurtzeko tresna.
-Comment[fa]=ابزار تبدیل libkab به libcabc.
-Comment[fi]=libkab-libkabc -muunnin
-Comment[fr]=Outil de conversion de libkab vers libkabc.
-Comment[fy]=Konversjeprogramma fan libkab nei libkabc.
-Comment[ga]=Uirlis tiontaithe ó libkab go libkabc.
-Comment[gl]=Ferramenta de conversión de libkab a libkabc.
-Comment[he]=כלי המרה מ־libkab ל־libkabc
-Comment[hi]=libkab से libkabc बदलने वाला औजार
-Comment[hr]=Alat za pretvaranje iz libkab u libkabc
-Comment[hsb]=libkab -> libkabc konwerter
-Comment[hu]=libkab -> libkabc konvertáló.
-Comment[id]=konverter libkab ke libkabc.
-Comment[is]=libkab í libkabc breytingatól.
-Comment[it]=Strumento di conversione da libkab a libkabc.
-Comment[ja]=libkab ã‹ã‚‰ libkabc ã¸ã®å¤‰æ›ãƒ„ール
-Comment[ka]=libkab => libkabc გáƒáƒ áƒ“áƒáƒ¥áƒ›áƒœáƒ˜áƒ¡ ხელსáƒáƒ¬áƒ§áƒ.
-Comment[kk]=libkab дегеннен libkabc дегенге айналдыру құралы.
-Comment[km]=ឧបករណáŸâ€‹áž”ម្លែង​ពី libkab ទៅ libkabc
-Comment[ko]=libkabì„ libkabcë¡œ 바꿔주는 연장.
-Comment[lb]=libkab op libkabc Konvertéierungs-Hëllefsmëttel.
-Comment[lt]=libkab į libkabc konvertavimo įrankis.
-Comment[lv]=libkab uz libkabc kovertēšanas rīks.
-Comment[mk]=алатка за претворање од libkab во libkabc.
-Comment[mn]=libkab-Ð°Ð°Ñ libkabc-руу хөрвүүлÑгч
-Comment[ms]=perkakasan penukaran libkab to libkabc.
-Comment[mt]=Għodda għall-konverżjoni libkab għal libkabc
-Comment[nb]=libkab til libkabc konverteringsverktøy.
-Comment[nds]=Warktüüch för't Ümwanneln vun libkab na libkabc.
-Comment[ne]=libkab to libkabc रूपानà¥à¤¤à¤°à¤£ उपकरण ।
-Comment[nl]=Conversieprogramma van libkab naar libkabc.
-Comment[nn]=Konverterer libkab til libkabc
-Comment[nso]=Sebereka sa phetosetso ya libkab go libkabc
-Comment[pa]=libkab ਤੋ libkabc ਤਬਦੀਲੀ ਸੰਦ।
-Comment[pl]=Narzędzie do konwersji z libkab do libkabc.
-Comment[pt]=Ferramenta de conversão de libkab para libkabc.
-Comment[pt_BR]=Ferramenta de conversão de libkab para libkabc.
-Comment[ro]=Utilitar de conversie de la "libkab" la "libkabc".
-Comment[ru]=утилита Ð¿Ñ€ÐµÐ¾Ð±Ñ€Ð°Ð·Ð¾Ð²Ð°Ð½Ð¸Ñ libkab в libkabc.
-Comment[rw]=Igikoresho cy'ihindura libkab muri libkabc.
-Comment[se]=konverterenreaidu libkab:as libkabc:ai
-Comment[sk]=Prevod dát z libkab do libkabc.
-Comment[sl]=Orodje za pretvorbo iz libkab v libkabc
-Comment[sq]=Vegla për shëndrimin e libkab në libkabc.
-Comment[sr]=Ðлат за конверзију из libkab-а у libkabc.
-Comment[sr@Latn]=Alat za konverziju iz libkab-a u libkabc.
-Comment[ss]=Lithulusi lekutjintja le-libkab kuya ku-libkabc.
-Comment[sv]=Konverteringsverktyg från libkab till libkabc
-Comment[ta]=libkab இலிரà¯à®¨à¯à®¤à¯ libkabc கà¯à®•à¯ மாறà¯à®±à¯à®®à¯ கரà¯à®µà®¿.
-Comment[te]=libkab à°¨à±à°‚à°šà°¿ libkabc కౠమారà±à°šà± పనిమà±à°Ÿà±à°Ÿà±
-Comment[tg]=аÑбоби дигаргунÑози libkab ба libkabc
-Comment[th]=เครื่องมือเปลี่ยน libkab เป็น libkabc
-Comment[tr]=libkab' tan libkabc' ye dönüştürme aracı
-Comment[tt]=libkab-›libkabc äyländerü qoralı.
-Comment[uk]=ЗаÑіб Ð¿ÐµÑ€ÐµÑ‚Ð²Ð¾Ñ€ÐµÐ½Ð½Ñ libkab до libkabc.
-Comment[uz]=libkab'ni libkabc'ga aylantiradigan vosita.
-Comment[uz@cyrillic]=libkab'ни libkabc'га айлантирадиган воÑита.
-Comment[ven]=Tshishumiswa tsha u shandukisa libkab itshi ya kha libkabc
-Comment[vi]=Công cụ chuyển đổi libkab sang libkabc.
-Comment[xh]=libkab kwi libkabc isixhobo sokuguqulela.
-Comment[zh_CN]=libkab 到 libkabc 的转æ¢å·¥å…·ã€‚
-Comment[zh_HK]=libkab 至 libkabc 的轉æ›å·¥å…·
-Comment[zh_TW]=libkab 至 libkabc 轉æ›å·¥å…·
-Comment[zu]=Ithuluzi lokuguqula le-libkab kuyaku-libkabc
-Terminal=false
-NoDisplay=true
-X-TDE-autostart-condition=kab2kabcrc:Startup:EnableAutostart:true
-OnlyShowIn=TDE;
diff --git a/kabc/ldapclient.cpp b/kabc/ldapclient.cpp
index 568408ba2..f696ae915 100644
--- a/kabc/ldapclient.cpp
+++ b/kabc/ldapclient.cpp
@@ -30,7 +30,7 @@
#include <tqurl.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kmdcodec.h>
#include <kprotocolinfo.h>
diff --git a/kabc/ldapclient.h b/kabc/ldapclient.h
index 5f8513599..f43a644ce 100644
--- a/kabc/ldapclient.h
+++ b/kabc/ldapclient.h
@@ -31,7 +31,7 @@
#include <tqguardedptr.h>
#include <tqtimer.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
namespace KABC {
diff --git a/kabc/ldapconfigwidget.h b/kabc/ldapconfigwidget.h
index 0fd0dd7e5..01074292e 100644
--- a/kabc/ldapconfigwidget.h
+++ b/kabc/ldapconfigwidget.h
@@ -27,7 +27,7 @@
#include <kabc/ldapurl.h>
#include <kabc/ldif.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
class TQGridLayout;
class TQSpinBox;
diff --git a/kabc/plugins/dir/CMakeLists.txt b/kabc/plugins/dir/CMakeLists.txt
index 47f81a355..737d1144e 100644
--- a/kabc/plugins/dir/CMakeLists.txt
+++ b/kabc/plugins/dir/CMakeLists.txt
@@ -20,9 +20,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
diff --git a/kabc/plugins/dir/resourcedir.cpp b/kabc/plugins/dir/resourcedir.cpp
index 0dfd0352a..6b1759f1d 100644
--- a/kabc/plugins/dir/resourcedir.cpp
+++ b/kabc/plugins/dir/resourcedir.cpp
@@ -29,7 +29,7 @@
#include <tqwidget.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <kglobal.h>
diff --git a/kabc/plugins/dir/resourcedir.h b/kabc/plugins/dir/resourcedir.h
index a7b041643..f62ee91ba 100644
--- a/kabc/plugins/dir/resourcedir.h
+++ b/kabc/plugins/dir/resourcedir.h
@@ -21,7 +21,7 @@
#ifndef KABC_RESOURCEDIR_H
#define KABC_RESOURCEDIR_H
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdirwatch.h>
#include <sys/types.h>
diff --git a/kabc/plugins/file/CMakeLists.txt b/kabc/plugins/file/CMakeLists.txt
index 3dbcd639f..f8847d7e9 100644
--- a/kabc/plugins/file/CMakeLists.txt
+++ b/kabc/plugins/file/CMakeLists.txt
@@ -20,9 +20,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
diff --git a/kabc/plugins/file/resourcefile.cpp b/kabc/plugins/file/resourcefile.cpp
index 3e5b1fa8f..2d2008c0d 100644
--- a/kabc/plugins/file/resourcefile.cpp
+++ b/kabc/plugins/file/resourcefile.cpp
@@ -30,9 +30,9 @@
#include <tqtimer.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
-#include <kio/scheduler.h>
+#include <tdeio/scheduler.h>
#include <klocale.h>
#include <ksavefile.h>
#include <kstandarddirs.h>
diff --git a/kabc/plugins/file/resourcefile.h b/kabc/plugins/file/resourcefile.h
index 494c43ea6..3d2efe85f 100644
--- a/kabc/plugins/file/resourcefile.h
+++ b/kabc/plugins/file/resourcefile.h
@@ -21,7 +21,7 @@
#ifndef KABC_RESOURCEFILE_H
#define KABC_RESOURCEFILE_H
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdirwatch.h>
#include <sys/types.h>
diff --git a/kabc/plugins/ldapkio/CMakeLists.txt b/kabc/plugins/ldapkio/CMakeLists.txt
index 150377bd9..0869c54e1 100644
--- a/kabc/plugins/ldapkio/CMakeLists.txt
+++ b/kabc/plugins/ldapkio/CMakeLists.txt
@@ -20,9 +20,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfiles
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefiles
)
link_directories(
@@ -68,6 +68,6 @@ set( ${target}_SRCS
tde_add_kpart( ${target}
SOURCES ${${target}_SRCS}
- LINK kabc_ldapkio-shared
+ LINK kabc_ldaptdeio-shared
DESTINATION ${PLUGIN_INSTALL_DIR}
)
diff --git a/kabc/plugins/ldapkio/resourceldapkio.cpp b/kabc/plugins/ldapkio/resourceldapkio.cpp
index cdf21fb82..034fb0ef8 100644
--- a/kabc/plugins/ldapkio/resourceldapkio.cpp
+++ b/kabc/plugins/ldapkio/resourceldapkio.cpp
@@ -29,12 +29,12 @@
#include <kstandarddirs.h>
#include <klineedit.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstringhandler.h>
#include <ktempfile.h>
#include <stdlib.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
#include <kabc/ldif.h>
#include <kabc/ldapurl.h>
diff --git a/kabc/plugins/ldapkio/resourceldapkio.h b/kabc/plugins/ldapkio/resourceldapkio.h
index 6f40b12f8..5c9282b9c 100644
--- a/kabc/plugins/ldapkio/resourceldapkio.h
+++ b/kabc/plugins/ldapkio/resourceldapkio.h
@@ -24,7 +24,7 @@
#include <kabc/resource.h>
#include <kabc/ldif.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
class TDEConfig;
diff --git a/kabc/plugins/ldapkio/resourceldapkioconfig.cpp b/kabc/plugins/ldapkio/resourceldapkioconfig.cpp
index 53c72aa2b..b517cffa5 100644
--- a/kabc/plugins/ldapkio/resourceldapkioconfig.cpp
+++ b/kabc/plugins/ldapkio/resourceldapkioconfig.cpp
@@ -36,7 +36,7 @@
#include <klocale.h>
#include <klineedit.h>
#include <kmessagebox.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
#include "resourceldapkio.h"
diff --git a/kabc/plugins/net/CMakeLists.txt b/kabc/plugins/net/CMakeLists.txt
index 365922d6c..e92fbfc32 100644
--- a/kabc/plugins/net/CMakeLists.txt
+++ b/kabc/plugins/net/CMakeLists.txt
@@ -20,9 +20,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
diff --git a/kabc/plugins/net/resourcenet.cpp b/kabc/plugins/net/resourcenet.cpp
index 78fb16256..9ef909904 100644
--- a/kabc/plugins/net/resourcenet.cpp
+++ b/kabc/plugins/net/resourcenet.cpp
@@ -21,8 +21,8 @@
#include <tqfile.h>
#include <kdebug.h>
-#include <kio/netaccess.h>
-#include <kio/scheduler.h>
+#include <tdeio/netaccess.h>
+#include <tdeio/scheduler.h>
#include <klocale.h>
#include <ksavefile.h>
#include <ktempfile.h>
diff --git a/kabc/plugins/net/resourcenet.h b/kabc/plugins/net/resourcenet.h
index a13bfa175..940627ecb 100644
--- a/kabc/plugins/net/resourcenet.h
+++ b/kabc/plugins/net/resourcenet.h
@@ -21,7 +21,7 @@
#ifndef KABC_RESOURCENET_H
#define KABC_RESOURCENET_H
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <sys/types.h>
diff --git a/kabc/plugins/sql/resourcesql.h b/kabc/plugins/sql/resourcesql.h
index 9f1201844..770e5b73b 100644
--- a/kabc/plugins/sql/resourcesql.h
+++ b/kabc/plugins/sql/resourcesql.h
@@ -21,7 +21,7 @@
#ifndef KABC_RESOURCESQL_H
#define KABC_RESOURCESQL_H
-#include <kconfig.h>
+#include <tdeconfig.h>
#include "addressbook.h"
#include "resource.h"
diff --git a/kabc/scripts/field.src.cpp b/kabc/scripts/field.src.cpp
index 6362d223c..2c80810b7 100644
--- a/kabc/scripts/field.src.cpp
+++ b/kabc/scripts/field.src.cpp
@@ -19,7 +19,7 @@
*/
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include "field.h"
diff --git a/kabc/tdeab2tdeabc.cpp b/kabc/tdeab2tdeabc.cpp
new file mode 100644
index 000000000..afb688078
--- /dev/null
+++ b/kabc/tdeab2tdeabc.cpp
@@ -0,0 +1,476 @@
+/*
+ This file is part of libkabc.
+ Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqfile.h>
+#include <tqtextstream.h>
+
+#include <kabapi.h>
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kcmdlineargs.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kstandarddirs.h>
+
+#include "addressbook.h"
+#include "stdaddressbook.h"
+
+using namespace KABC;
+
+static const KCmdLineOptions options[] =
+{
+ { "disable-autostart", I18N_NOOP( "Disable automatic startup on login" ), 0 },
+ { "quiet", "", 0 },
+ { "o", 0, 0 },
+ { "override", I18N_NOOP( "Override existing entries" ), "1" },
+ KCmdLineLastOption
+};
+
+void readKMailEntry( const TQString &kmailEntry, KABC::AddressBook *ab )
+{
+ kdDebug() << "KMAILENTRY: " << kmailEntry << endl;
+
+ TQString entry = kmailEntry.simplifyWhiteSpace();
+ if ( entry.isEmpty() ) return;
+
+ TQString email;
+ TQString name;
+ TQString comment;
+
+ if ( entry.at( entry.length() -1 ) == ')' ) {
+ int br = entry.findRev( '(' );
+ if ( br >= 0 ) {
+ comment = entry.mid( br + 1, entry.length() - br - 2 );
+ entry.truncate( br );
+ if ( entry.at( entry.length() - 1 ).isSpace() ) {
+ entry.truncate( br - 1 );
+ }
+ }
+ }
+
+ int posSpace = entry.findRev( ' ' );
+ if ( posSpace < 0 ) {
+ email = entry;
+ if ( !comment.isEmpty() ) {
+ name = comment;
+ comment = "";
+ }
+ } else {
+ email = entry.mid( posSpace + 1 );
+ name = entry.left( posSpace );
+ }
+
+ if ( email.at( 0 ) == '<' && email.at( email.length() - 1) == '>' ) {
+ email = email.mid( 1, email.length() - 2 );
+ }
+ if ( name.at( 0 ) == '"' && name.at( name.length() - 1) == '"' ) {
+ name = name.mid( 1, name.length() - 2 );
+ }
+ if ( name.at( 0 ) == '\'' && name.at( name.length() - 1) == '\'' ) {
+ name = name.mid( 1, name.length() - 2 );
+ }
+
+ if ( name.at( name.length() -1 ) == ')' ) {
+ int br = name.findRev( '(' );
+ if ( br >= 0 ) {
+ comment = name.mid( br + 1, name.length() - br - 2 ) + " " + comment;
+ name.truncate( br );
+ if ( name.at( name.length() - 1 ).isSpace() ) {
+ name.truncate( br - 1 );
+ }
+ }
+ }
+
+ kdDebug() << " EMAIL : " << email << endl;
+ kdDebug() << " NAME : " << name << endl;
+ kdDebug() << " COMMENT : " << comment << endl;
+
+ KABC::Addressee::List al = ab->findByEmail( email );
+ if ( al.isEmpty() ) {
+ KABC::Addressee a;
+ a.setNameFromString( name );
+ a.insertEmail( email );
+ a.setNote( comment );
+
+ ab->insertAddressee( a );
+
+ kdDebug() << "--INSERTED: " << a.realName() << endl;
+ }
+}
+
+void importKMailAddressBook( KABC::AddressBook *ab )
+{
+ TQString fileName = locateLocal( "data", "kmail/addressbook" );
+ TQString kmailConfigName = locate( "config", "kmailrc" );
+ if ( !kmailConfigName.isEmpty() ) {
+ TDEConfig cfg( kmailConfigName );
+ cfg.setGroup( "Addressbook" );
+ fileName = cfg.readPathEntry( "default", fileName );
+ }
+ if ( !KStandardDirs::exists( fileName ) ) {
+ kdDebug(5700) << "Couldn't find KMail addressbook." << endl;
+ return;
+ }
+
+ TQFile f( fileName );
+ if ( !f.open(IO_ReadOnly) ) {
+ kdDebug(5700) << "Couldn't open file '" << fileName << "'" << endl;
+ return;
+ }
+
+ TQStringList kmailEntries;
+
+ TQTextStream t( &f );
+ while ( !t.eof() ) {
+ kmailEntries.append( t.readLine() );
+ }
+ f.close();
+
+ TQStringList::ConstIterator it;
+ for ( it = kmailEntries.begin(); it != kmailEntries.end(); ++it ) {
+ if ( (*it).at( 0 ) == '#' ) continue;
+ bool insideQuote = false;
+ int end = (*it).length() - 1;
+ for ( int i = end; i; i-- ) {
+ if ( (*it).at( i ) == '"' ) {
+ if ( insideQuote )
+ insideQuote = false;
+ else
+ insideQuote = true;
+ } else if ( (*it).at( i ) == ',' && !insideQuote ) {
+ readKMailEntry( (*it).mid( i + 1, end - i ), ab );
+ end = i - 1;
+ }
+ }
+
+ readKMailEntry( (*it).mid( 0, end + 1 ), ab );
+ }
+}
+
+void readKAddressBookEntries( const TQString &dataString, Addressee &a )
+{
+ // Strip "KMail:1.0" prefix and "[EOS]" suffix.
+ TQString str = dataString.mid( 11, dataString.length() - 24 );
+
+ TQStringList entries = TQStringList::split( "\n[EOR]\n ", str );
+
+ Address homeAddress( Address::Home );
+ Address businessAddress( Address::Work );
+ Address otherAddress;
+
+ TQStringList::ConstIterator it;
+ for ( it = entries.begin(); it != entries.end(); ++it ) {
+ int pos = (*it).find( "\n" );
+ TQString fieldName = (*it).left( pos );
+ TQString fieldValue = (*it).mid( pos + 2 );
+
+ if ( fieldName == "X-HomeFax" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Home |
+ PhoneNumber::Fax ) );
+ } else if ( fieldName == "X-OtherPhone" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, 0 ) );
+ } else if ( fieldName == "X-PrimaryPhone" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Pref ) );
+ } else if ( fieldName == "X-BusinessFax" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Work |
+ PhoneNumber::Fax ) );
+ } else if ( fieldName == "X-CarPhone" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Car ) );
+ } else if ( fieldName == "X-MobilePhone" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Cell ) );
+ } else if ( fieldName == "X-ISDN" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Isdn ) );
+ } else if ( fieldName == "X-OtherFax" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Fax ) );
+ } else if ( fieldName == "X-Pager" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Pager ) );
+ } else if ( fieldName == "X-BusinessPhone" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Work ) );
+ } else if ( fieldName == "X-HomePhone" ) {
+ a.insertPhoneNumber( PhoneNumber( fieldValue, PhoneNumber::Home ) );
+ } else if ( fieldName == "X-HomeAddress" ) {
+ homeAddress.setLabel( fieldValue );
+ } else if ( fieldName == "X-HomeAddressStreet" ) {
+ homeAddress.setStreet( fieldValue );
+ } else if ( fieldName == "X-HomeAddressCity" ) {
+ homeAddress.setLocality( fieldValue );
+ } else if ( fieldName == "X-HomeAddressPostalCode" ) {
+ homeAddress.setPostalCode( fieldValue );
+ } else if ( fieldName == "X-HomeAddressState" ) {
+ homeAddress.setRegion( fieldValue );
+ } else if ( fieldName == "X-HomeAddressCountry" ) {
+ homeAddress.setCountry( fieldValue );
+ } else if ( fieldName == "X-BusinessAddress" ) {
+ businessAddress.setLabel( fieldValue );
+ } else if ( fieldName == "X-BusinessAddressStreet" ) {
+ businessAddress.setStreet( fieldValue );
+ } else if ( fieldName == "X-BusinessAddressCity" ) {
+ businessAddress.setLocality( fieldValue );
+ } else if ( fieldName == "X-BusinessAddressPostalCode" ) {
+ businessAddress.setPostalCode( fieldValue );
+ } else if ( fieldName == "X-BusinessAddressState" ) {
+ businessAddress.setRegion( fieldValue );
+ } else if ( fieldName == "X-BusinessAddressCountry" ) {
+ businessAddress.setCountry( fieldValue );
+ } else if ( fieldName == "X-OtherAddress" ) {
+ otherAddress.setLabel( fieldValue );
+ } else if ( fieldName == "X-OtherAddressStreet" ) {
+ otherAddress.setStreet( fieldValue );
+ } else if ( fieldName == "X-OtherAddressCity" ) {
+ otherAddress.setLocality( fieldValue );
+ } else if ( fieldName == "X-OtherAddressPostalCode" ) {
+ otherAddress.setPostalCode( fieldValue );
+ } else if ( fieldName == "X-OtherAddressState" ) {
+ otherAddress.setRegion( fieldValue );
+ } else if ( fieldName == "X-OtherAddressCountry" ) {
+ otherAddress.setCountry( fieldValue );
+ } else if ( fieldName == "NICKNAME" ) {
+ a.setNickName( fieldValue );
+ } else if ( fieldName == "ORG" ) {
+ a.setOrganization( fieldValue );
+ } else if ( fieldName == "ROLE" ) {
+ a.setRole( fieldValue );
+ } else if ( fieldName == "BDAY" ) {
+ a.setBirthday( TDEGlobal::locale()->readDate( fieldValue ) );
+ } else if ( fieldName == "WEBPAGE" ) {
+ a.setUrl( KURL( fieldValue ) );
+ } else if ( fieldName == "N" ) {
+ } else if ( fieldName == "X-FirstName" ) {
+ } else if ( fieldName == "X-MiddleName" ) {
+ } else if ( fieldName == "X-LastName" ) {
+ } else if ( fieldName == "X-Title" ) {
+ } else if ( fieldName == "X-Suffix" ) {
+ } else if ( fieldName == "X-FileAs" ) {
+ } else if ( fieldName == "EMAIL" ) {
+ a.insertEmail( fieldValue, true );
+ } else if ( fieldName == "X-E-mail2" ) {
+ a.insertEmail( fieldValue );
+ } else if ( fieldName == "X-E-mail3" ) {
+ a.insertEmail( fieldValue );
+ } else if ( fieldName == "X-Notes" ) {
+ } else {
+ a.insertCustom( "KADDRESSBOOK", fieldName, fieldValue );
+ }
+ }
+
+ if ( !homeAddress.isEmpty() ) a.insertAddress( homeAddress );
+ if ( !businessAddress.isEmpty() ) a.insertAddress( businessAddress );
+ if ( !otherAddress.isEmpty() ) a.insertAddress( otherAddress );
+}
+
+void importKab( KABC::AddressBook *ab, bool override, bool quiet )
+{
+ TQString fileName = TDEGlobal::dirs()->saveLocation( "data", "kab/" );
+ fileName += "addressbook.kab";
+ if ( !TQFile::exists( fileName ) ) {
+ if ( !quiet ) {
+ KMessageBox::error( 0, "<qt>" + i18n( "Address book file <b>%1</b> not found! Make sure the old address book is located there and you have read permission for this file." )
+ .arg( fileName ) + "</qt>" );
+ }
+ kdDebug(5700) << "No KDE 2 addressbook found." << endl;
+ return;
+ }
+
+ kdDebug(5700) << "Converting old-style kab addressbook to "
+ "new-style kabc addressbook." << endl;
+
+ KabAPI kab( 0 );
+ if ( kab.init() != ::AddressBook::NoError ) {
+ kdDebug(5700) << "Error initing kab" << endl;
+ exit( 1 );
+ }
+
+ KabKey key;
+ ::AddressBook::Entry entry;
+
+ int num = kab.addressbook()->noOfEntries();
+
+ kdDebug(5700) << "kab Addressbook has " << num << " entries." << endl;
+
+ for ( int i = 0; i < num; ++i ) {
+ if ( ::AddressBook::NoError != kab.addressbook()->getKey( i, key ) ) {
+ kdDebug(5700) << "Error getting key for index " << i << " from kab." << endl;
+ continue;
+ }
+ if ( ::AddressBook::NoError != kab.addressbook()->getEntry( key, entry ) ) {
+ kdDebug(5700) << "Error getting entry for index " << i << " from kab." << endl;
+ continue;
+ }
+
+ Addressee a;
+
+ // Convert custom entries
+ int count = 0;
+ bool idFound = false;
+ TQStringList::ConstIterator customIt;
+ for ( customIt = entry.custom.begin(); customIt != entry.custom.end(); ++customIt ) {
+ if ( (*customIt).startsWith( "X-KABC-UID:" ) ) {
+ a.setUid( (*customIt).mid( (*customIt).find( ":" ) + 1 ) );
+ idFound = true;
+ } else if ( (*customIt).startsWith( "KMail:1.0\n" ) ) {
+ readKAddressBookEntries( *customIt, a );
+ } else {
+ a.insertCustom( "tdeab2tdeabc", TQString::number( count++ ), *customIt );
+ }
+ }
+ if ( idFound ) {
+ if ( !override ) continue;
+ } else {
+ entry.custom << "X-KABC-UID:" + a.uid();
+ ::AddressBook::ErrorCode error = kab.addressbook()->change( key, entry );
+ if ( error != ::AddressBook::NoError ) {
+ kdDebug(5700) << "kab.change returned with error " << error << endl;
+ } else {
+ kdDebug(5700) << "Wrote back to kab uid " << a.uid() << endl;
+ }
+ }
+
+ a.setTitle( entry.title );
+ a.setFormattedName( entry.fn );
+ a.setPrefix( entry.nameprefix );
+ a.setGivenName( entry.firstname );
+ a.setAdditionalName( entry.middlename );
+ a.setFamilyName( entry.lastname );
+ a.setBirthday( entry.birthday );
+
+ TQStringList::ConstIterator emailIt;
+ for ( emailIt = entry.emails.begin(); emailIt != entry.emails.end(); ++emailIt )
+ a.insertEmail( *emailIt );
+
+ TQStringList::ConstIterator phoneIt;
+ for ( phoneIt = entry.telephone.begin(); phoneIt != entry.telephone.end(); ++phoneIt ) {
+ int kabType = (*phoneIt++).toInt();
+ if ( phoneIt == entry.telephone.end() ) break;
+ TQString number = *phoneIt;
+ int type = 0;
+ if ( kabType == ::AddressBook::Fixed ) type = PhoneNumber::Voice;
+ else if ( kabType == ::AddressBook::Mobile ) type = PhoneNumber::Cell | PhoneNumber::Voice;
+ else if ( kabType == ::AddressBook::Fax ) type = PhoneNumber::Fax;
+ else if ( kabType == ::AddressBook::Modem ) type = PhoneNumber::Modem;
+ a.insertPhoneNumber( PhoneNumber( number, type ) );
+ }
+
+ if ( entry.URLs.count() > 0 ) {
+ a.setUrl( KURL( entry.URLs.first() ) );
+ if ( entry.URLs.count() > 1 ) {
+ kdWarning() << "More than one URL. Ignoring all but the first." << endl;
+ }
+ }
+
+ int noAdr = entry.noOfAddresses();
+ for ( int j = 0; j < noAdr; ++j ) {
+ ::AddressBook::Entry::Address kabAddress;
+ entry.getAddress( j, kabAddress );
+
+ Address adr;
+
+ adr.setStreet( kabAddress.address );
+ adr.setPostalCode( kabAddress.zip );
+ adr.setLocality( kabAddress.town );
+ adr.setCountry( kabAddress.country );
+ adr.setRegion( kabAddress.state );
+
+ TQString label;
+ if ( !kabAddress.headline.isEmpty() ) label += kabAddress.headline + "\n";
+ if ( !kabAddress.position.isEmpty() ) label += kabAddress.position + "\n";
+ if ( !kabAddress.org.isEmpty() ) label += kabAddress.org + "\n";
+ if ( !kabAddress.orgUnit.isEmpty() ) label += kabAddress.orgUnit + "\n";
+ if ( !kabAddress.orgSubUnit.isEmpty() ) label += kabAddress.orgSubUnit + "\n";
+ if ( !kabAddress.deliveryLabel.isEmpty() ) label += kabAddress.deliveryLabel + "\n";
+ adr.setLabel( label );
+
+ a.insertAddress( adr );
+ }
+
+ TQString note = entry.comment;
+
+ if ( !entry.user1.isEmpty() ) note += "\nUser1: " + entry.user1;
+ if ( !entry.user2.isEmpty() ) note += "\nUser2: " + entry.user2;
+ if ( !entry.user3.isEmpty() ) note += "\nUser3: " + entry.user3;
+ if ( !entry.user4.isEmpty() ) note += "\nUser4: " + entry.user4;
+
+ if ( !entry.keywords.count() == 0 ) note += "\nKeywords: " + entry.keywords.join( ", " );
+
+ TQStringList::ConstIterator talkIt;
+ for ( talkIt = entry.talk.begin(); talkIt != entry.talk.end(); ++talkIt ) {
+ note += "\nTalk: " + (*talkIt);
+ }
+
+ a.setNote( note );
+
+ a.setPrefix( entry.rank + a.prefix() ); // Add rank to prefix
+
+ a.setCategories( entry.categories );
+
+ kdDebug(5700) << "Addressee: " << a.familyName() << endl;
+
+ ab->insertAddressee( a );
+ }
+
+ kab.save( true );
+}
+
+int main( int argc, char **argv )
+{
+ TDEAboutData aboutData( "tdeab2tdeabc", I18N_NOOP( "Kab to Kabc Converter" ), "0.1" );
+ aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
+
+ TDECmdLineArgs::init( argc, argv, &aboutData );
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDEApplication app;
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ bool override = false;
+
+ if ( args->isSet( "override" ) ) {
+ kdDebug() << "Override existing entries." << endl;
+
+ override = true;
+ }
+
+ bool quiet = false;
+
+ if ( args->isSet( "quiet" ) )
+ quiet = true;
+
+ if ( args->isSet( "disable-autostart" ) ) {
+ kdDebug() << "Disable autostart." << endl;
+
+ TDEConfig *config = app.config();
+ config->setGroup( "Startup" );
+ config->writeEntry( "EnableAutostart", false );
+ }
+
+ KABC::AddressBook *kabcBook = StdAddressBook::self();
+
+ importKMailAddressBook( kabcBook );
+
+ importKab( kabcBook, override, quiet );
+
+ StdAddressBook::save();
+
+ kdDebug(5700) << "Saved kabc addressbook to '" << kabcBook->identifier() << "'" << endl;
+}
+
diff --git a/kabc/tdeab2tdeabc.desktop b/kabc/tdeab2tdeabc.desktop
new file mode 100644
index 000000000..945f044d4
--- /dev/null
+++ b/kabc/tdeab2tdeabc.desktop
@@ -0,0 +1,105 @@
+[Desktop Entry]
+Name=tdeab2tdeabc
+Name[af]=kab-na-kabc
+Name[csb]=Kònwersëjô adresowi knéżczi
+Name[eo]=Konvertilo de "kab" al "kabc"
+Name[fr]=KAB2KABC
+Name[fy]=Kab2kabc
+Name[hu]=Kab2kabc
+Name[it]=Kab2Kabc
+Name[nl]=Kab2kabc
+Name[pl]=Konwersja książki adresowej
+Name[pt_BR]=Conversão de kab para kabc
+Name[ro]=Kab2kabc
+Name[sv]=Kab2kabc
+Name[te]=కెఎబి2కెఎబిసి
+Name[zu]=i-tdeab2tdeabc
+Exec=tdeab2tdeabc --disable-autostart --quiet
+Icon=misc
+Type=Application
+Comment=libkab to libkabc conversion tool.
+Comment[af]=libkab na libkabc omskakeling program.
+Comment[ar]=أداة تحويل libkab إلى libkabc.
+Comment[az]=libkab - libkabc dönüşdürmə vasitəsi.
+Comment[be]=ІнÑтрумент пераўтварÑÐ½Ð½Ñ libkab у libkabc.
+Comment[bg]=Програма за конвертиране на libkab до libkabc.
+Comment[bn]=libkab থেকে libkabc-তে পরিবরà§à¦¤à¦¨ করার পà§à¦°à§‹à¦—à§à¦°à¦¾à¦®à¥¤
+Comment[bs]=alat za pretvaranje libkab u libkabc.
+Comment[ca]=Eina de conversió de libkab a libkabc.
+Comment[cs]=Převod dat z libkab do libkabc.
+Comment[csb]=Nôrzãdze do kònwersëji z libkab do libkabc.
+Comment[cy]=erfyn trosi libkab i libkabc
+Comment[da]=libkab-til-libkabc-konverteringsværktøj.
+Comment[de]=Konvertierung von libkab in libkabc
+Comment[el]=ΕÏγαλείο μετατÏοπής από το libkab στο libkabc.
+Comment[eo]=Konvertilo de "libkab" al "libkabc"
+Comment[es]=Conversor libkab a libkabc.
+Comment[et]=libkab -> libkabc teisendamine
+Comment[eu]=libkab-etik libkabc-era bihurtzeko tresna.
+Comment[fa]=ابزار تبدیل libkab به libcabc.
+Comment[fi]=libkab-libkabc -muunnin
+Comment[fr]=Outil de conversion de libkab vers libkabc.
+Comment[fy]=Konversjeprogramma fan libkab nei libkabc.
+Comment[ga]=Uirlis tiontaithe ó libkab go libkabc.
+Comment[gl]=Ferramenta de conversión de libkab a libkabc.
+Comment[he]=כלי המרה מ־libkab ל־libkabc
+Comment[hi]=libkab से libkabc बदलने वाला औजार
+Comment[hr]=Alat za pretvaranje iz libkab u libkabc
+Comment[hsb]=libkab -> libkabc konwerter
+Comment[hu]=libkab -> libkabc konvertáló.
+Comment[id]=konverter libkab ke libkabc.
+Comment[is]=libkab í libkabc breytingatól.
+Comment[it]=Strumento di conversione da libkab a libkabc.
+Comment[ja]=libkab ã‹ã‚‰ libkabc ã¸ã®å¤‰æ›ãƒ„ール
+Comment[ka]=libkab => libkabc გáƒáƒ áƒ“áƒáƒ¥áƒ›áƒœáƒ˜áƒ¡ ხელსáƒáƒ¬áƒ§áƒ.
+Comment[kk]=libkab дегеннен libkabc дегенге айналдыру құралы.
+Comment[km]=ឧបករណáŸâ€‹áž”ម្លែង​ពី libkab ទៅ libkabc
+Comment[ko]=libkabì„ libkabcë¡œ 바꿔주는 연장.
+Comment[lb]=libkab op libkabc Konvertéierungs-Hëllefsmëttel.
+Comment[lt]=libkab į libkabc konvertavimo įrankis.
+Comment[lv]=libkab uz libkabc kovertēšanas rīks.
+Comment[mk]=алатка за претворање од libkab во libkabc.
+Comment[mn]=libkab-Ð°Ð°Ñ libkabc-руу хөрвүүлÑгч
+Comment[ms]=perkakasan penukaran libkab to libkabc.
+Comment[mt]=Għodda għall-konverżjoni libkab għal libkabc
+Comment[nb]=libkab til libkabc konverteringsverktøy.
+Comment[nds]=Warktüüch för't Ümwanneln vun libkab na libkabc.
+Comment[ne]=libkab to libkabc रूपानà¥à¤¤à¤°à¤£ उपकरण ।
+Comment[nl]=Conversieprogramma van libkab naar libkabc.
+Comment[nn]=Konverterer libkab til libkabc
+Comment[nso]=Sebereka sa phetosetso ya libkab go libkabc
+Comment[pa]=libkab ਤੋ libkabc ਤਬਦੀਲੀ ਸੰਦ।
+Comment[pl]=Narzędzie do konwersji z libkab do libkabc.
+Comment[pt]=Ferramenta de conversão de libkab para libkabc.
+Comment[pt_BR]=Ferramenta de conversão de libkab para libkabc.
+Comment[ro]=Utilitar de conversie de la "libkab" la "libkabc".
+Comment[ru]=утилита Ð¿Ñ€ÐµÐ¾Ð±Ñ€Ð°Ð·Ð¾Ð²Ð°Ð½Ð¸Ñ libkab в libkabc.
+Comment[rw]=Igikoresho cy'ihindura libkab muri libkabc.
+Comment[se]=konverterenreaidu libkab:as libkabc:ai
+Comment[sk]=Prevod dát z libkab do libkabc.
+Comment[sl]=Orodje za pretvorbo iz libkab v libkabc
+Comment[sq]=Vegla për shëndrimin e libkab në libkabc.
+Comment[sr]=Ðлат за конверзију из libkab-а у libkabc.
+Comment[sr@Latn]=Alat za konverziju iz libkab-a u libkabc.
+Comment[ss]=Lithulusi lekutjintja le-libkab kuya ku-libkabc.
+Comment[sv]=Konverteringsverktyg från libkab till libkabc
+Comment[ta]=libkab இலிரà¯à®¨à¯à®¤à¯ libkabc கà¯à®•à¯ மாறà¯à®±à¯à®®à¯ கரà¯à®µà®¿.
+Comment[te]=libkab à°¨à±à°‚à°šà°¿ libkabc కౠమారà±à°šà± పనిమà±à°Ÿà±à°Ÿà±
+Comment[tg]=аÑбоби дигаргунÑози libkab ба libkabc
+Comment[th]=เครื่องมือเปลี่ยน libkab เป็น libkabc
+Comment[tr]=libkab' tan libkabc' ye dönüştürme aracı
+Comment[tt]=libkab-›libkabc äyländerü qoralı.
+Comment[uk]=ЗаÑіб Ð¿ÐµÑ€ÐµÑ‚Ð²Ð¾Ñ€ÐµÐ½Ð½Ñ libkab до libkabc.
+Comment[uz]=libkab'ni libkabc'ga aylantiradigan vosita.
+Comment[uz@cyrillic]=libkab'ни libkabc'га айлантирадиган воÑита.
+Comment[ven]=Tshishumiswa tsha u shandukisa libkab itshi ya kha libkabc
+Comment[vi]=Công cụ chuyển đổi libkab sang libkabc.
+Comment[xh]=libkab kwi libkabc isixhobo sokuguqulela.
+Comment[zh_CN]=libkab 到 libkabc 的转æ¢å·¥å…·ã€‚
+Comment[zh_HK]=libkab 至 libkabc 的轉æ›å·¥å…·
+Comment[zh_TW]=libkab 至 libkabc 轉æ›å·¥å…·
+Comment[zu]=Ithuluzi lokuguqula le-libkab kuyaku-libkabc
+Terminal=false
+NoDisplay=true
+X-TDE-autostart-condition=tdeab2tdeabcrc:Startup:EnableAutostart:true
+OnlyShowIn=TDE;
diff --git a/kate/data/bash.xml b/kate/data/bash.xml
index 84c91596d..e3bc4abdd 100644
--- a/kate/data/bash.xml
+++ b/kate/data/bash.xml
@@ -439,7 +439,7 @@
<!-- others -->
<item> dcop </item>
<item> kdialog </item>
- <item> kfile </item>
+ <item> tdefile </item>
<item> xhost </item>
<item> xmodmap </item>
<item> xset </item>
diff --git a/kate/data/tcsh.xml b/kate/data/tcsh.xml
index f9dffa2e4..19c94beaa 100644
--- a/kate/data/tcsh.xml
+++ b/kate/data/tcsh.xml
@@ -431,7 +431,7 @@
<!-- others -->
<item> dcop </item>
<item> kdialog </item>
- <item> kfile </item>
+ <item> tdefile </item>
<item> xhost </item>
<item> xmodmap </item>
<item> xset </item>
diff --git a/kate/data/zsh.xml b/kate/data/zsh.xml
index 5d0575ab9..e69c15354 100644
--- a/kate/data/zsh.xml
+++ b/kate/data/zsh.xml
@@ -497,7 +497,7 @@
<!-- others -->
<item> dcop </item>
<item> kdialog </item>
- <item> kfile </item>
+ <item> tdefile </item>
<item> xhost </item>
<item> xmodmap </item>
<item> xset </item>
diff --git a/kate/interfaces/katecmd.cpp b/kate/interfaces/katecmd.cpp
index 69263b57c..2104ef157 100644
--- a/kate/interfaces/katecmd.cpp
+++ b/kate/interfaces/katecmd.cpp
@@ -118,7 +118,7 @@ const TQString KateCmd::fromHistory( uint index ) const
//BEGIN KateCmdShellCompletion
/*
A lot of the code in the below class is copied from
- tdelibs/kio/kio/kshellcompletion.cpp
+ tdelibs/tdeio/tdeio/kshellcompletion.cpp
Copyright (C) 2000 David Smith <dsmith@algonet.se>
Copyright (C) 2004 Anders Lund <anders@alweb.dk>
*/
diff --git a/kate/part/CMakeLists.txt b/kate/part/CMakeLists.txt
index 72ac36f8a..dcbc0eecd 100644
--- a/kate/part/CMakeLists.txt
+++ b/kate/part/CMakeLists.txt
@@ -21,9 +21,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdefx
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
${CMAKE_SOURCE_DIR}/kjs
${CMAKE_SOURCE_DIR}/tdeutils
${CMAKE_SOURCE_DIR}/tdeprint
diff --git a/kate/part/kateconfig.cpp b/kate/part/kateconfig.cpp
index 81b001c3c..d1c9fd1ee 100644
--- a/kate/part/kateconfig.cpp
+++ b/kate/part/kateconfig.cpp
@@ -28,7 +28,7 @@
#include <math.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobalsettings.h>
#include <kcharsets.h>
#include <klocale.h>
diff --git a/kate/part/katedialogs.cpp b/kate/part/katedialogs.cpp
index 43f5977d8..5006ddd6c 100644
--- a/kate/part/katedialogs.cpp
+++ b/kate/part/katedialogs.cpp
@@ -38,9 +38,9 @@
#include <tdetexteditor/configinterfaceextension.h>
#include <tdetexteditor/plugin.h>
-#include <kio/job.h>
-#include <kio/jobclasses.h>
-#include <kio/netaccess.h>
+#include <tdeio/job.h>
+#include <tdeio/jobclasses.h>
+#include <tdeio/netaccess.h>
#include <kaccel.h>
#include <kapplication.h>
@@ -50,7 +50,7 @@
#include <kcolorcombo.h>
#include <kcolordialog.h>
#include <kcombobox.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kfontdialog.h>
#include <kglobal.h>
diff --git a/kate/part/katedocument.cpp b/kate/part/katedocument.cpp
index 03c8ac638..74e5c3225 100644
--- a/kate/part/katedocument.cpp
+++ b/kate/part/katedocument.cpp
@@ -42,9 +42,9 @@
#include "katetemplatehandler.h"
#include <tdetexteditor/plugin.h>
-#include <kio/job.h>
-#include <kio/netaccess.h>
-#include <kio/kfileitem.h>
+#include <tdeio/job.h>
+#include <tdeio/netaccess.h>
+#include <tdeio/tdefileitem.h>
#include <tdeparts/event.h>
@@ -53,8 +53,8 @@
#include <kglobal.h>
#include <kapplication.h>
#include <kpopupmenu.h>
-#include <kconfig.h>
-#include <kfiledialog.h>
+#include <tdeconfig.h>
+#include <tdefiledialog.h>
#include <kmessagebox.h>
#include <kstdaction.h>
#include <kiconloader.h>
@@ -1924,13 +1924,13 @@ void KateDocument::writeConfig()
config->sync();
}
-void KateDocument::readSessionConfig(TDEConfig *kconfig)
+void KateDocument::readSessionConfig(TDEConfig *tdeconfig)
{
// restore the url
- KURL url (kconfig->readEntry("URL"));
+ KURL url (tdeconfig->readEntry("URL"));
// get the encoding
- TQString tmpenc=kconfig->readEntry("Encoding");
+ TQString tmpenc=tdeconfig->readEntry("Encoding");
if (!tmpenc.isEmpty() && (tmpenc != encoding()))
setEncoding(tmpenc);
@@ -1939,34 +1939,34 @@ void KateDocument::readSessionConfig(TDEConfig *kconfig)
openURL (url);
// restore the hl stuff
- m_buffer->setHighlight(KateHlManager::self()->nameFind(kconfig->readEntry("Highlighting")));
+ m_buffer->setHighlight(KateHlManager::self()->nameFind(tdeconfig->readEntry("Highlighting")));
if (hlMode() > 0)
hlSetByUser = true;
// indent mode
- config()->setIndentationMode( (uint)kconfig->readNumEntry("Indentation Mode", config()->indentationMode() ) );
+ config()->setIndentationMode( (uint)tdeconfig->readNumEntry("Indentation Mode", config()->indentationMode() ) );
// Restore Bookmarks
- TQValueList<int> marks = kconfig->readIntListEntry("Bookmarks");
+ TQValueList<int> marks = tdeconfig->readIntListEntry("Bookmarks");
for( uint i = 0; i < marks.count(); i++ )
addMark( marks[i], KateDocument::markType01 );
}
-void KateDocument::writeSessionConfig(TDEConfig *kconfig)
+void KateDocument::writeSessionConfig(TDEConfig *tdeconfig)
{
if ( m_url.isLocalFile() && !TDEGlobal::dirs()->relativeLocation("tmp", m_url.path()).startsWith("/"))
return;
// save url
- kconfig->writeEntry("URL", m_url.prettyURL() );
+ tdeconfig->writeEntry("URL", m_url.prettyURL() );
// save encoding
- kconfig->writeEntry("Encoding",encoding());
+ tdeconfig->writeEntry("Encoding",encoding());
// save hl
- kconfig->writeEntry("Highlighting", highlight()->name());
+ tdeconfig->writeEntry("Highlighting", highlight()->name());
- kconfig->writeEntry("Indentation Mode", config()->indentationMode() );
+ tdeconfig->writeEntry("Indentation Mode", config()->indentationMode() );
// Save Bookmarks
TQValueList<int> marks;
@@ -1975,7 +1975,7 @@ void KateDocument::writeSessionConfig(TDEConfig *kconfig)
++it )
marks << it.current()->line;
- kconfig->writeEntry( "Bookmarks", marks );
+ tdeconfig->writeEntry( "Bookmarks", marks );
}
void KateDocument::configDialog()
diff --git a/kate/part/katefiletype.cpp b/kate/part/katefiletype.cpp
index a00d39bfb..15dd7c9f6 100644
--- a/kate/part/katefiletype.cpp
+++ b/kate/part/katefiletype.cpp
@@ -25,7 +25,7 @@
#include "kateview.h"
#include "katefactory.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kmimemagic.h>
#include <kmimetype.h>
#include <kmimetypechooser.h>
diff --git a/kate/part/katehighlight.cpp b/kate/part/katehighlight.cpp
index 08da7e97f..f06518649 100644
--- a/kate/part/katehighlight.cpp
+++ b/kate/part/katehighlight.cpp
@@ -32,7 +32,7 @@
#include "kateschema.h"
#include "kateconfig.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kinstance.h>
#include <kmimetype.h>
diff --git a/kate/part/katehighlight.h b/kate/part/katehighlight.h
index 1b71e454a..8ff5e31b2 100644
--- a/kate/part/katehighlight.h
+++ b/kate/part/katehighlight.h
@@ -26,7 +26,7 @@
#include "../interfaces/document.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqptrlist.h>
#include <tqvaluelist.h>
diff --git a/kate/part/katejscript.cpp b/kate/part/katejscript.cpp
index 28b22c74e..f3a5cd548 100644
--- a/kate/part/katejscript.cpp
+++ b/kate/part/katejscript.cpp
@@ -37,7 +37,7 @@
#include <kstandarddirs.h>
#include <klocale.h>
#include <kmessagebox.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kjs/function_object.h>
#include <kjs/interpreter.h>
@@ -688,7 +688,7 @@ void KateJScriptManager::collectScripts (bool force)
TDEConfig df (desktopFile, true, false);
df.setDesktopGroup ();
- // get cmdname, fallback to baseName, if it is empty, therefor not use the kconfig fallback
+ // get cmdname, fallback to baseName, if it is empty, therefor not use the tdeconfig fallback
TQString cmdname = df.readEntry ("X-Kate-Command");
if (cmdname.isEmpty())
{
diff --git a/kate/part/kateluaindentscript.cpp b/kate/part/kateluaindentscript.cpp
index c06f3864e..46cf531a7 100644
--- a/kate/part/kateluaindentscript.cpp
+++ b/kate/part/kateluaindentscript.cpp
@@ -31,7 +31,7 @@
#include <tqfileinfo.h>
#include <kstandarddirs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <klocale.h>
diff --git a/kate/part/kateschema.h b/kate/part/kateschema.h
index f6eb8ef60..2e92812de 100644
--- a/kate/part/kateschema.h
+++ b/kate/part/kateschema.h
@@ -29,7 +29,7 @@
#include <tqlistview.h>
#include <tqfont.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kaction.h>
class KateView;
@@ -53,7 +53,7 @@ class KateSchemaManager
void update (bool readfromfile = true);
/**
- * return kconfig with right group set or set to Normal if not there
+ * return tdeconfig with right group set or set to Normal if not there
*/
TDEConfig *schema (uint number);
diff --git a/kate/part/katesyntaxdocument.cpp b/kate/part/katesyntaxdocument.cpp
index 4093f8722..d90f5de73 100644
--- a/kate/part/katesyntaxdocument.cpp
+++ b/kate/part/katesyntaxdocument.cpp
@@ -27,7 +27,7 @@
#include <kstandarddirs.h>
#include <klocale.h>
#include <kmessagebox.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqfile.h>
diff --git a/kate/part/kateview.cpp b/kate/part/kateview.cpp
index 193f411fd..22a4799d6 100644
--- a/kate/part/kateview.cpp
+++ b/kate/part/kateview.cpp
@@ -50,9 +50,9 @@
#include <tdeparts/event.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kurldrag.h>
#include <kdebug.h>
#include <kapplication.h>
diff --git a/kate/part/test_regression.cpp b/kate/part/test_regression.cpp
index 4f2ef26a5..1463c8bcd 100644
--- a/kate/part/test_regression.cpp
+++ b/kate/part/test_regression.cpp
@@ -42,7 +42,7 @@
#include <kaction.h>
#include <kcmdlineargs.h>
#include "katefactory.h"
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <kmainwindow.h>
#include <ksimpleconfig.h>
#include <kglobalsettings.h>
diff --git a/kate/plugins/autobookmarker/autobookmarker.cpp b/kate/plugins/autobookmarker/autobookmarker.cpp
index ceb76eedd..cf3190c4e 100644
--- a/kate/plugins/autobookmarker/autobookmarker.cpp
+++ b/kate/plugins/autobookmarker/autobookmarker.cpp
@@ -30,7 +30,7 @@
#include <kaction.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kgenericfactory.h>
#include <kiconloader.h>
#include <klistview.h>
diff --git a/kate/plugins/insertfile/CMakeLists.txt b/kate/plugins/insertfile/CMakeLists.txt
index 0c80a1e0c..56bdfd9cd 100644
--- a/kate/plugins/insertfile/CMakeLists.txt
+++ b/kate/plugins/insertfile/CMakeLists.txt
@@ -16,9 +16,9 @@ include_directories(
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
${CMAKE_SOURCE_DIR}/interfaces
)
diff --git a/kate/plugins/insertfile/insertfileplugin.cpp b/kate/plugins/insertfile/insertfileplugin.cpp
index ee46a7cff..aa9f998b6 100644
--- a/kate/plugins/insertfile/insertfileplugin.cpp
+++ b/kate/plugins/insertfile/insertfileplugin.cpp
@@ -24,9 +24,9 @@
#include <tdetexteditor/editinterface.h>
#include <assert.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <kaction.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kgenericfactory.h>
#include <klocale.h>
#include <kmessagebox.h>
diff --git a/kate/plugins/isearch/ISearchPlugin.cpp b/kate/plugins/isearch/ISearchPlugin.cpp
index 26c49576d..de1c1c376 100644
--- a/kate/plugins/isearch/ISearchPlugin.cpp
+++ b/kate/plugins/isearch/ISearchPlugin.cpp
@@ -24,7 +24,7 @@
#include <klocale.h>
#include <kaction.h>
#include <kcombobox.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include "ISearchPlugin.h"
diff --git a/kate/plugins/kdatatool/CMakeLists.txt b/kate/plugins/kdatatool/CMakeLists.txt
index 1adced175..7ceccc10d 100644
--- a/kate/plugins/kdatatool/CMakeLists.txt
+++ b/kate/plugins/kdatatool/CMakeLists.txt
@@ -17,8 +17,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdefx
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/interfaces
)
diff --git a/kate/plugins/wordcompletion/docwordcompletion.cpp b/kate/plugins/wordcompletion/docwordcompletion.cpp
index a468edd13..fbd5a4db7 100644
--- a/kate/plugins/wordcompletion/docwordcompletion.cpp
+++ b/kate/plugins/wordcompletion/docwordcompletion.cpp
@@ -34,7 +34,7 @@
#include <tdetexteditor/variableinterface.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdialog.h>
#include <kgenericfactory.h>
#include <klocale.h>
diff --git a/kcmshell/CMakeLists.txt b/kcmshell/CMakeLists.txt
deleted file mode 100644
index 92c2205d0..000000000
--- a/kcmshell/CMakeLists.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/tdeutils
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### kcmshell ##################################
-
-set( target kcmshell )
-
-set( ${target}_SRCS
- main.cpp main.skel
-)
-
-tde_add_tdeinit_executable( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK tdeutils-shared
- DEPENDENCIES dcopidl
-)
diff --git a/kcmshell/Makefile.am b/kcmshell/Makefile.am
deleted file mode 100644
index 9c755d8bb..000000000
--- a/kcmshell/Makefile.am
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# Copyright (c) 1999 Matthias Hoelzer-Kluepfel <hoelzer@kde.org>
-# Copyright (c) 2000 Matthias Elter <elter@kde.org>
-# Copyright (c) 2004 Frans Englich <frans.englich@telia.com>
-#
-# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-
-AM_CPPFLAGS = -I$(top_srcdir)/tdeutils $(all_includes)
-METASOURCES = AUTO
-
-lib_LTLIBRARIES =
-bin_PROGRAMS =
-tdeinit_LTLIBRARIES = kcmshell.la
-
-kcmshell_la_SOURCES = main.cpp main.skel
-kcmshell_la_LIBADD = ../tdeutils/libtdeutils.la $(LIB_QT) $(LIB_TDEUI) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE) $(LIB_KFILE)
-kcmshell_la_LDFLAGS = $(all_libraries) -module -avoid-version
-
-noinst_HEADERS = main.h
-
-messages: rc.cpp
- $(XGETTEXT) *.cpp -o $(podir)/kcmshell.pot
-
-
-include $(top_srcdir)/admin/Doxyfile.am
-
diff --git a/kcmshell/main.cpp b/kcmshell/main.cpp
deleted file mode 100644
index 29aba0501..000000000
--- a/kcmshell/main.cpp
+++ /dev/null
@@ -1,350 +0,0 @@
-/*
- Copyright (c) 1999 Matthias Hoelzer-Kluepfel <hoelzer@kde.org>
- Copyright (c) 2000 Matthias Elter <elter@kde.org>
- Copyright (c) 2004 Frans Englich <frans.englich@telia.com>
-
- 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
-*/
-
-#include <iostream>
-
-#include <tqcstring.h>
-#include <tqfile.h>
-
-#include <dcopclient.h>
-#include <qxembed.h>
-
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kcmdlineargs.h>
-#include <tdecmoduleinfo.h>
-#include <tdecmoduleloader.h>
-#include <tdecmoduleproxy.h>
-#include <kcmultidialog.h>
-#include <kdebug.h>
-#include <kdialogbase.h>
-#include <kiconloader.h>
-#include <klocale.h>
-#include <kservice.h>
-#include <kservicegroup.h>
-#include <kstartupinfo.h>
-#include <twin.h>
-#include <kglobal.h>
-
-#include "main.h"
-#include "main.moc"
-
-using namespace std;
-
-KService::List m_modules;
-
-static KCmdLineOptions options[] =
-{
- { "list", I18N_NOOP("List all possible modules"), 0},
- { "+module", I18N_NOOP("Configuration module to open"), 0 },
- { "lang <language>", I18N_NOOP("Specify a particular language"), 0 },
- { "embed <id>", I18N_NOOP("Embeds the module with buttons in window with id <id>"), 0 },
- { "embed-proxy <id>", I18N_NOOP("Embeds the module without buttons in window with id <id>"), 0 },
- { "silent", I18N_NOOP("Do not display main window"), 0 },
- KCmdLineLastOption
-};
-
-static void listModules(const TQString &baseGroup)
-{
-
- KServiceGroup::Ptr group = KServiceGroup::group(baseGroup);
-
- if (!group || !group->isValid())
- return;
-
- KServiceGroup::List list = group->entries(true, true);
-
- for( KServiceGroup::List::ConstIterator it = list.begin();
- it != list.end(); it++)
- {
- KSycocaEntry *p = (*it);
- if (p->isType(KST_KService))
- {
- KService *s = static_cast<KService*>(p);
- if (!kapp->authorizeControlModule(s->menuId()))
- continue;
- m_modules.append(s);
- }
- else if (p->isType(KST_KServiceGroup))
- listModules(p->entryPath());
- }
-}
-
-static KService::Ptr locateModule(const TQCString& module)
-{
- TQString path = TQFile::decodeName(module);
-
- if (!path.endsWith(".desktop"))
- path += ".desktop";
-
- KService::Ptr service = KService::serviceByStorageId( path );
- if (!service)
- {
- kdWarning(780) << "Could not find module '" << module << "'." << endl;
- return 0;
- }
-
- // avoid finding random non-TDE applications
- if ( module.left( 4 ) != "kde-" && service->library().isEmpty() )
- return locateModule( "kde-" + module );
-
- if(!TDECModuleLoader::testModule( module ))
- {
- kdDebug(780) << "According to \"" << module << "\"'s test function, it should Not be loaded." << endl;
- return 0;
- }
-
- return service;
-}
-
-bool KCMShell::isRunning()
-{
- if( dcopClient()->appId() == m_dcopName )
- return false; // We are the one and only.
-
- kdDebug(780) << "kcmshell with modules '" <<
- m_dcopName << "' is already running." << endl;
-
- dcopClient()->attach(); // Reregister as anonymous
- dcopClient()->setNotifications(true);
-
- TQByteArray data;
- TQDataStream str( data, IO_WriteOnly );
- str << kapp->startupId();
- TQCString replyType;
- TQByteArray replyData;
- if (!dcopClient()->call(m_dcopName, "dialog", "activate(TQCString)",
- data, replyType, replyData))
- {
- kdDebug(780) << "Calling DCOP function dialog::activate() failed." << endl;
- return false; // Error, we have to do it ourselves.
- }
-
- return true;
-}
-
-KCMShellMultiDialog::KCMShellMultiDialog( int dialogFace, const TQString& caption,
- TQWidget *parent, const char *name, bool modal)
- : KCMultiDialog( dialogFace, caption, parent, name, modal ),
- DCOPObject("dialog")
-{
-}
-
-void KCMShellMultiDialog::activate( TQCString asn_id )
-{
- kdDebug(780) << k_funcinfo << endl;
-
- KStartupInfo::setNewStartupId( this, asn_id );
-}
-
-void KCMShell::setDCOPName(const TQCString &dcopName, bool rootMode )
-{
- m_dcopName = "kcmshell_";
- if( rootMode )
- m_dcopName += "rootMode_";
-
- m_dcopName += dcopName;
-
- dcopClient()->registerAs(m_dcopName, false);
-}
-
-void KCMShell::waitForExit()
-{
- kdDebug(780) << k_funcinfo << endl;
-
- connect(dcopClient(), TQT_SIGNAL(applicationRemoved(const TQCString&)),
- TQT_SLOT( appExit(const TQCString&) ));
- exec();
-}
-
-void KCMShell::appExit(const TQCString &appId)
-{
- kdDebug(780) << k_funcinfo << endl;
-
- if( appId == m_dcopName )
- {
- kdDebug(780) << "'" << appId << "' closed, dereferencing." << endl;
- deref();
- }
-}
-
-static void setIcon(TQWidget *w, const TQString &iconName)
-{
- TQPixmap icon = DesktopIcon(iconName);
- TQPixmap miniIcon = SmallIcon(iconName);
- w->setIcon( icon ); //standard X11
-#if defined Q_WS_X11 && ! defined K_WS_QTONLY
- KWin::setIcons(w->winId(), icon, miniIcon );
-#endif
-}
-
-extern "C" KDE_EXPORT int kdemain(int _argc, char *_argv[])
-{
- TDEAboutData aboutData( "kcmshell", I18N_NOOP("TDE Control Module"),
- 0,
- I18N_NOOP("A tool to start single TDE control modules"),
- TDEAboutData::License_GPL,
- I18N_NOOP("(c) 1999-2004, The KDE Developers") );
-
- aboutData.addAuthor("Frans Englich", I18N_NOOP("Maintainer"), "frans.englich@kde.org");
- aboutData.addAuthor("Daniel Molkentin", 0, "molkentin@kde.org");
- aboutData.addAuthor("Matthias Hoelzer-Kluepfel",0, "hoelzer@kde.org");
- aboutData.addAuthor("Matthias Elter",0, "elter@kde.org");
- aboutData.addAuthor("Matthias Ettrich",0, "ettrich@kde.org");
- aboutData.addAuthor("Waldo Bastian",0, "bastian@kde.org");
-
- TDEGlobal::locale()->setMainCatalogue("kcmshell");
-
- TDECmdLineArgs::init(_argc, _argv, &aboutData);
- TDECmdLineArgs::addCmdLineOptions( options ); // Add our own options.
- KCMShell app;
-
- const TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- const TQCString lang = args->getOption("lang");
- if( !lang.isNull() )
- TDEGlobal::locale()->setLanguage(lang);
-
- if (args->isSet("list"))
- {
- cout << static_cast<const char *>(i18n("The following modules are available:").local8Bit()) << endl;
-
- listModules( "Settings/" );
-
- int maxLen=0;
-
- for( KService::List::ConstIterator it = m_modules.begin(); it != m_modules.end(); ++it)
- {
- int len = (*it)->desktopEntryName().length();
- if (len > maxLen)
- maxLen = len;
- }
-
- for( KService::List::ConstIterator it = m_modules.begin(); it != m_modules.end(); ++it)
- {
- TQString entry("%1 - %2");
-
- entry = entry.arg((*it)->desktopEntryName().leftJustify(maxLen, ' '))
- .arg(!(*it)->comment().isEmpty() ? (*it)->comment()
- : i18n("No description available"));
-
- cout << static_cast<const char *>(entry.local8Bit()) << endl;
- }
- return 0;
- }
-
- if (args->count() < 1)
- {
- args->usage();
- return -1;
- }
-
- TQCString dcopName;
- KService::List modules;
- for (int i = 0; i < args->count(); i++)
- {
- KService::Ptr service = locateModule(args->arg(i));
- if( service )
- {
- modules.append(service);
- if( !dcopName.isEmpty() )
- dcopName += "_";
-
- dcopName += args->arg(i);
- }
- }
-
- /* Check if this particular module combination is already running, but
- * allow the same module to run when embedding(root mode) */
- app.setDCOPName(dcopName,
- ( args->isSet( "embed-proxy" ) || args->isSet( "embed" )));
- if( app.isRunning() )
- {
- app.waitForExit();
- return 0;
- }
-
- //KDialogBase::DialogType dtype = KDialogBase::Plain; // FIXME
- KDialogBase::DialogType dtype = KDialogBase::IconList; // Work around a bug whereby several kcontrol modules (such as displayconfig) use an incorrect size when loaded with kcmshell in the Plain mode
- // This bug is possibly related to kcmultidialog.cpp:266 [( new TQHBoxLayout( page ) )->setAutoAdd( true );]
- // In fact, this method of display may be preferable to the Plain mode from a UX perspective,
- // as the icon shows the user what the active kcontrol module is called.
-
- if ( modules.count() < 1 )
- return 0;
- else if( modules.count() > 1 )
- dtype = KDialogBase::IconList;
-
- bool idValid;
- int id;
-
- if ( args->isSet( "embed-proxy" ))
- {
- id = args->getOption( "embed-proxy" ).toInt(&idValid);
- if( idValid )
- {
- TDECModuleProxy *module = new TDECModuleProxy( modules.first()->desktopEntryName() );
- module->realModule();
- QXEmbed::embedClientIntoWindow( module, id);
- app.exec();
- delete module;
- }
- else
- kdDebug(780) << "Supplied id '" << id << "' is not valid." << endl;
-
- return 0;
-
- }
-
- KCMShellMultiDialog *dlg = new KCMShellMultiDialog( dtype,
- i18n("Configure - %1").arg(kapp->caption()), 0, "", true );
-
- for (KService::List::ConstIterator it = modules.begin(); it != modules.end(); ++it)
- dlg->addModule(TDECModuleInfo(*it));
-
- if ( args->isSet( "embed" ))
- {
- id = args->getOption( "embed" ).toInt(&idValid);
- if( idValid )
- {
- QXEmbed::embedClientIntoWindow( dlg, id );
- dlg->exec();
- delete dlg;
- }
- else
- kdDebug(780) << "Supplied id '" << id << "' is not valid." << endl;
-
- }
- else
- {
-
- if (kapp->iconName() != kapp->name())
- setIcon(dlg, kapp->iconName());
- else if ( modules.count() == 1 )
- setIcon(dlg, TDECModuleInfo( modules.first()).icon());
-
- dlg->exec();
- delete dlg;
- }
-
- return 0;
-}
-// vim: sw=4 et sts=4
diff --git a/kcmshell/main.h b/kcmshell/main.h
deleted file mode 100644
index f43cf98cb..000000000
--- a/kcmshell/main.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
- Copyright (c) 2004 Frans Englich <frans.englich@telia.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
-*/
-
-#ifndef __kcmshell_h__
-#define __kcmshell_h__
-
-#include <dcopobject.h>
-
-#include <kapplication.h>
-#include <kcmultidialog.h>
-
-/**
- * The TDEApplication instance for kcmshell.
- */
-class KCMShell : public TDEApplication
-{
- Q_OBJECT
-
-public:
-
- /**
- * Sets m_dcopName basically to @p dcopName,
- * and then registers with DCOP.
- *
- * @param dcopName name to set the DCOP name to
- * @param rootMode true if the kcmshell is embedding
- */
- void setDCOPName(const TQCString &dcopName, bool rootMode );
-
- /**
- * Waits until the last instance of kcmshell with the same
- * module as this one exits, and then exits.
- */
- void waitForExit();
-
- /**
- * @return true if the shell is running
- */
- bool isRunning();
-
-private slots:
-
- /**
- */
- void appExit( const TQCString &appId );
-
-private:
-
- /**
- * The DCOP name which actually is registered.
- * For example "kcmshell_mouse".
- */
- TQCString m_dcopName;
-
-};
-
-
-/**
- * Essentially a plain KCMultiDialog, but has the additional functionality
- * of allowing it to be told to request windows focus.
- *
- * @author Waldo Bastian <bastian@kde.org>
- */
-class KCMShellMultiDialog : public KCMultiDialog, public DCOPObject
-{
- Q_OBJECT
- K_DCOP
-
-public:
-
- /**
- */
- KCMShellMultiDialog( int dialogFace, const TQString& caption,
- TQWidget *parent=0, const char *name=0, bool modal=false);
-
-k_dcop:
-
- /**
- */
- virtual void activate( TQCString asn_id );
-
-};
-
-
-// vim: sw=4 et sts=4
-#endif //__kcmshell_h__
diff --git a/kconf_update/CMakeLists.txt b/kconf_update/CMakeLists.txt
deleted file mode 100644
index 2e25811a7..000000000
--- a/kconf_update/CMakeLists.txt
+++ /dev/null
@@ -1,34 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### kconf_update ##############################
-
-set( target kconf_update )
-
-set( ${target}_SRCS
- kconf_update.cpp
-)
-
-tde_add_tdeinit_executable( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK tdecore-shared
-)
diff --git a/kconf_update/Mainpage.dox b/kconf_update/Mainpage.dox
deleted file mode 100644
index 9db5adb3b..000000000
--- a/kconf_update/Mainpage.dox
+++ /dev/null
@@ -1,31 +0,0 @@
-/** @mainpage ./kconf_update
-
-kconf_update is a tool designed to update config files. Over time applications
-sometimes need to rearrange the way configuration options are stored. Since
-such an update shouldn't influence the configuration options that the user
-has selected, the application must take care that the options stored in the
-old way will still be honored.
-
-What used to happen is that the application looks up both the old and the
-new configuration option and then decides which one to use. This method has
-several drawbacks:
-- The application may need to read more configuration files than strictly
- needed, resulting in a slower startup.
-- The application becomes bigger with code that will only be used once.
-
-kconf_update addresses these problems by offering a framework to update
-configuration files without adding code to the application itself.
-
-See the README file for more information.
-
-@authors
-Waldo Bastian \<bastian@kde.org\>
-
-@maintainers
-[Unknown/None]
-
-@licenses
-@lgpl
-
-*/
-// vim:ts=4:sw=4:expandtab:filetype=doxygen
diff --git a/kconf_update/Makefile.am b/kconf_update/Makefile.am
deleted file mode 100644
index afe3864d9..000000000
--- a/kconf_update/Makefile.am
+++ /dev/null
@@ -1,33 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 2001 Waldo Bastian <bastian@kde.org>
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-INCLUDES= -I../kded $(all_includes)
-
-bin_PROGRAMS =
-lib_LTLIBRARIES =
-tdeinit_LTLIBRARIES = kconf_update.la
-
-kconf_update_la_SOURCES = kconf_update.cpp
-kconf_update_la_LIBADD = $(LIB_TDECORE) $(LIB_QT)
-kconf_update_la_LDFLAGS = $(all_libraries) -module -avoid-version
-
-METASOURCES = AUTO
-
-# Internal
-# noinst_HEADERS = kconf_update.h
-
diff --git a/kconf_update/README.kconf_update b/kconf_update/README.kconf_update
deleted file mode 100644
index c8229c735..000000000
--- a/kconf_update/README.kconf_update
+++ /dev/null
@@ -1,251 +0,0 @@
-README kconf_update
-
-Version: 1.1
-Author: Waldo Bastian <bastian@kde.org>, <bastian@suse.com>
-
-What it does
-============
-
-kconf_update is a tool designed to update config files. Over time applications
-sometimes need to rearrange the way configuration options are stored. Since
-such an update shouldn't influence the configuration options that the user
-has selected, the application must take care that the options stored in the
-old way will still be honored.
-
-What used to happen is that the application looks up both the old and the
-new configuration option and then decides which one to use. This method has
-several drawbacks:
-* The application may need to read more configuration files than strictly
-needed, resulting in a slower startup.
-* The application becomes bigger with code that will only be used once.
-
-kconf_update addresses these problems by offering a framework to update
-configuration files without adding code to the application itself.
-
-
-How it works
-============
-
-Applications can install so called "update files" under
-$TDEDIR/share/apps/kconf_update. An update file has ".upd" as extension and
-contains instructions for transferring/converting configuration information
-from one place to another.
-
-Updating the configuration happens automatically, either when KDE gets started
-or when kded detects a new update file in the above mentioned location.
-
-Update files are separated into sections. Each section has an Id. When a
-section describing a configuration change has been applied, the Id will be
-stored in the file "kconf_updaterc". This information is used to make sure
-that a configuration update is only performed once.
-
-If you overwrite an existing update file with a new version that contains a
-new section, only the update instructions from this extra section will be
-performed.
-
-File format of the update file
-==============================
-
-Empty lines or lines that start with '#' are considered comments.
-Commas (,) are used to seperate fields and may not occur as part
-of any field and all of the keywords are case-sensitive, i.e. you
-cannot say "key" instead of "Key" for example.
-
-For the rest the file is parsed and executed sequentially from top to bottom.
-Each line can contain one entry. The following entries are recognized:
-
-
-Id=<id>
-
-With <id> identifying the group of update entries that follows. Once a group
-of entries have been applied, their <id> is stored and this group of entries
-will not be applied again.
-
-
-File=<oldfile>,<newfile>
-File=<oldfile>
-
-Specifies that configuration information is read from <oldfile> and written
-to <newfile>. If you only specify <oldfile>, the information is read from
-as well as written to <oldfile>.
-
-Script=<script>[,<interpreter>]
-
-All entries from <oldfile> are piped into <script>. The output of script
-is used as new entries for <newfile>. Existing entries can be deleted by
-adding lines with "# DELETE [group]key" in the output of the script.
-To delete a whole group use "# DELETEGROUP [group]".
-
-<script> should be installed into $(kde_datadir)/kconf_update, or
-kconf_update will not be able to find it. It is not portable to install
-binary applications in $kde_datadir, so you have to stick with interpreted
-scripts like sh or perl scripts. From KDE 3.2 onwards it's also possible
-to install kconf_update applications in $(kde_bindir)/kconf_update_bin,
-which opens the door to kconf_update applications that are written in C++
-and use Qt's powerful string API instead.
-
-A workaround for KDE 3.1.x and older is to install a .sh script in
-$(kde_datadir) that contains a simple exec:
-
- exec "`tde-config --prefix`/bin/kconf_update_bin/my_update_app"
-
-This is equivalent to what KDE 3.2 can do directly, but of course the .upd
-file now points to the .sh script instead of the binary application.
-
-If Script was issued after a "Group" command the behavior is slightly
-different:
-All entries from <oldfile>/<oldgroup> are piped into <script>. The output
-of script is used as new entries for <newfile>/<newgroup>, unless a different
-group is specified with "[group]". Existing entries can be deleted from
-<oldgroup> by adding lines with "# DELETE key" in the output of the script.
-To delete <oldgroup> use "# DELETEGROUP".
-
-<interpreter> can be something like "perl".
-
-Since KDE 3.3 it is also possible to have a Script without specifying
-<oldfile> or <newfile>. In that case the script is run but it will not be
-fed any input and its output will simply be discarded.
-
-ScriptArguments=<arguments>
-
-If specified, the arguments will be passed to <script>.
-IMPORTANT: It has to be specified before Script=.
-
-Group=<oldgroup>,<newgroup>
-Group=<oldgroup>
-
-Specifies that configuration information is read from the group <oldgroup>
-and written to <newgroup>. If you only specify <oldgroup>, the information
-is read from as well as written to <oldgroup>. You can use <default> to
-specify keys that are not under any group.
-
-RemoveGroup=<oldgroup>
-
-Specifies that <oldgroup> is removed entirely. This can be used
-to remove obsolete entries or to force a revert to default values.
-
-Options=<option1>, <option2>, ....
-
-With this entry you can specify options that apply to the next "Script",
-"Key" or "AllKeys" entry (only to the first!). Possible options are:
-
-- "copy" Copy the configuration item instead of moving it. This means that
- the configuration item will not be deleted from <oldfile>/<oldgroup>.
-
-- "overwrite" Normally, a configuration item is not moved if an item with the
- new name already exists. When this option is specified the old
- configuration item will overwrite any existing item.
-
-
-Key=<oldkey>,<newkey>
-Key=<oldkey>
-
-Specifies that configuration information is read from the key <oldkey>
-and written to <newkey>. If you only specify <oldkey>, the information
-is read from as well as written to <oldkey>.
-
-
-AllKeys
-
-Specifies that all configuration information in the selected group should
-be moved (All keys).
-
-AllGroups
-
-Specifies that all configuration information from all keys in ALL
-groups should be moved.
-
-
-RemoveKey=<oldkey>
-
-Specifies that <oldkey> is removed from the selected group. This can be used
-to remove obsolete entries or to force a revert to default values.
-
-
-Example update file
-===================
-
-# This is comment
-Id=kde2.2
-File=kioslaverc,kio_httprc
-Group=Proxy Settings
-Key=NoProxyFor
-Key=UseProxy
-Key=httpProxy,Proxy
-Group=Cache Settings,Cache
-Key=MaxCacheSize
-Key=UseCache
-Group=UserAgent
-AllKeys
-RemoveGroup=KDE
-# End of file
-
-
-The above update file extracts config information from the file "kioslaverc"
-and stores it into the file "kio_httprc".
-
-It reads the keys "NoProxyFor", "UseProxy" and "httpProxy" from the group
-"Proxy Settings" in the "kioslaverc" file. If any of these options are present
-they are written to the keys "NoProxyFor", "UseProxy" and "Proxy" (!) in
-the group "Proxy Settings" in the "kio_httprc" file.
-
-It also reads the keys "MaxCacheSize" and "UseCache" from the group
-"Cache Settings" in the "kioslaverc" file and writes this information to the
-keys "MaxCacheSize" and "UseCache" in the group "Cache" (!) in the
-"kio_httprc" file.
-
-Then it takes all keys in the "UserAgent" group of the file "kioslaverc"
-and moves then to the "UserAgent" group in the "kio_httprc" file.
-
-Finally it removes the entire "KDE" group in the kioslaverc file.
-
-
-Debugging and testing
-=====================
-
-If you are developing a kconf_update script and want to test or debug it you
-need to make sure kconf_update runs again after each of your changes. There
-are a number of ways to achieve this.
-
-The easiest is to not install the kconf_update script in the first place, but
-manually call it through a pipe. If you want to test the update script for
-your application KHello's config file khellorc, you can test by using
-
- cat ~/.trinity/share/config/khellorc | khello_conf_update.sh
-
-(assuming khello_conf_update.sh is the kconf_update script and ~/.trinity is your
-$TDEHOME). This is easier than making install every time, but has the obvious
-downside that you need to 'parse' your script's output yourself instead of
-letting kconf_update do it and check the resulting output file.
-
-After 'make install' the kconf_update script is run by kded, but it does so
-only once. This is of course the idea behind it, but while developing it can
-be a problem. You can increase the revision number for each subsequent run
-of 'make install' to force a new kconf_update run, but there's a better
-approach that doesn't skyrocket the version number for a mediocre debug
-session.
-
-kded doesn't really ignore scripts that it has already run right away.
-Instead it checks the affected config file every time a .upd file is added
-or changed. The reason it still doesn't run again on your config file lies
-in the traces kconf_update leaves behind: it adds a special config group
-'[$Version]' with a key 'update_info'. This key lists all kconf_update
-scripts that have already been run on this config file. Just remove your
-file's entry, 'make install', and kconf_update will happily run your script
-again, without you having to increase the version number.
-
-If you want to know what kconf_update has been up to lately, have a look
-at $TDEHOME/share/apps/kconf_update/update.log
-
-
-Common Problems
-===============
-
-* kconf_update refuses to update an entry
-If you change the value of an entry without changing the key or file,
-make sure to tell kconf_update that it should overwrite the old entry
-by adding "Options=overwrite".
-
-
-Have fun,
-Waldo
diff --git a/kconf_update/kconf_update.cpp b/kconf_update/kconf_update.cpp
deleted file mode 100644
index daf66ca9b..000000000
--- a/kconf_update/kconf_update.cpp
+++ /dev/null
@@ -1,959 +0,0 @@
-/*
- *
- * This file is part of the KDE libraries
- * Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
- *
- * $Id$
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <stdlib.h>
-
-#include <tqfile.h>
-#include <tqtextstream.h>
-
-#include <kconfig.h>
-#include <ksimpleconfig.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-#include <kglobal.h>
-#include <kstandarddirs.h>
-#include <kaboutdata.h>
-#include <kinstance.h>
-#include <ktempfile.h>
-
-static KCmdLineOptions options[] =
-{
- { "debug", I18N_NOOP("Keep output results from scripts"), 0 },
- { "check <update-file>", I18N_NOOP("Check whether config file itself requires updating"), 0 },
- { "+[file]", I18N_NOOP("File to read update instructions from"), 0 },
- KCmdLineLastOption
-};
-
-class KonfUpdate
-{
-public:
- KonfUpdate();
- ~KonfUpdate();
- TQStringList findUpdateFiles(bool dirtyOnly);
-
- TQTextStream &log();
-
- bool checkFile(const TQString &filename);
- void checkGotFile(const TQString &_file, const TQString &id);
-
- bool updateFile(const TQString &filename);
-
- void gotId(const TQString &_id);
- void gotFile(const TQString &_file);
- void gotGroup(const TQString &_group);
- void gotRemoveGroup(const TQString &_group);
- void gotKey(const TQString &_key);
- void gotRemoveKey(const TQString &_key);
- void gotAllKeys();
- void gotAllGroups();
- void gotOptions(const TQString &_options);
- void gotScript(const TQString &_script);
- void gotScriptArguments(const TQString &_arguments);
- void resetOptions();
-
- void copyGroup(TDEConfigBase *cfg1, const TQString &grp1,
- TDEConfigBase *cfg2, const TQString &grp2);
-
-protected:
- TDEConfig *config;
- TQString currentFilename;
- bool skip;
- bool debug;
- TQString id;
-
- TQString oldFile;
- TQString newFile;
- TQString newFileName;
- TDEConfig *oldConfig1; // Config to read keys from.
- TDEConfig *oldConfig2; // Config to delete keys from.
- TDEConfig *newConfig;
-
- TQString oldGroup;
- TQString newGroup;
- TQString oldKey;
- TQString newKey;
-
- bool m_bCopy;
- bool m_bOverwrite;
- bool m_bUseConfigInfo;
- TQString m_arguments;
- TQTextStream *m_textStream;
- TQFile *m_file;
- TQString m_line;
- int m_lineCount;
-};
-
-KonfUpdate::KonfUpdate()
- : m_textStream(0), m_file(0)
-{
- bool updateAll = false;
- oldConfig1 = 0;
- oldConfig2 = 0;
- newConfig = 0;
-
- config = new TDEConfig("kconf_updaterc");
-
- TQStringList updateFiles;
- TDECmdLineArgs *args=TDECmdLineArgs::parsedArgs();
-
- debug = args->isSet("debug");
-
- m_bUseConfigInfo = false;
- if (args->isSet("check"))
- {
- m_bUseConfigInfo = true;
- TQString file = locate("data", "kconf_update/"+TQFile::decodeName(args->getOption("check")));
- if (file.isEmpty())
- {
- tqWarning("File '%s' not found.", args->getOption("check").data());
- log() << "File '" << TQFile::decodeName(args->getOption("check")) << "' passed on command line not found" << endl;
- return;
- }
- updateFiles.append(file);
- }
- else if (args->count())
- {
- for(int i = 0; i < args->count(); i++)
- {
- KURL url = args->url(i);
- if (!url.isLocalFile())
- TDECmdLineArgs::usage(i18n("Only local files are supported."));
- updateFiles.append(url.path());
- }
- }
- else
- {
- if (config->readBoolEntry("autoUpdateDisabled", false))
- return;
- updateFiles = findUpdateFiles(true);
- updateAll = true;
- }
-
- for(TQStringList::ConstIterator it = updateFiles.begin();
- it != updateFiles.end();
- ++it)
- {
- TQString file = *it;
- updateFile(file);
- }
-
- config->setGroup(TQString::null);
- if (updateAll && !config->readBoolEntry("updateInfoAdded", false))
- {
- config->writeEntry("updateInfoAdded", true);
- updateFiles = findUpdateFiles(false);
-
- for(TQStringList::ConstIterator it = updateFiles.begin();
- it != updateFiles.end();
- ++it)
- {
- TQString file = *it;
- checkFile(file);
- }
- updateFiles.clear();
- }
-}
-
-KonfUpdate::~KonfUpdate()
-{
- delete config;
- delete m_file;
- delete m_textStream;
-}
-
-TQTextStream &
-KonfUpdate::log()
-{
- if (!m_textStream)
- {
- TQString file = locateLocal("data", "kconf_update/log/update.log");
- m_file = new TQFile(file);
- if (m_file->open(IO_WriteOnly | IO_Append))
- {
- m_textStream = new TQTextStream(m_file);
- }
- else
- {
- // Error
- m_textStream = new TQTextStream(stderr, IO_WriteOnly);
- }
- }
-
- (*m_textStream) << TQDateTime::currentDateTime().toString( Qt::ISODate ) << " ";
-
- return *m_textStream;
-}
-
-TQStringList KonfUpdate::findUpdateFiles(bool dirtyOnly)
-{
- TQStringList result;
- TQStringList list = TDEGlobal::dirs()->findAllResources("data", "kconf_update/*.upd", false, true);
- for(TQStringList::ConstIterator it = list.begin();
- it != list.end();
- ++it)
- {
- TQString file = *it;
- struct stat buff;
- if (stat( TQFile::encodeName(file), &buff) == 0)
- {
- int i = file.findRev('/');
- if (i != -1)
- file = file.mid(i+1);
- config->setGroup(file);
- time_t ctime = config->readUnsignedLongNumEntry("ctime");
- time_t mtime = config->readUnsignedLongNumEntry("mtime");
- if (!dirtyOnly ||
- (ctime != buff.st_ctime) || (mtime != buff.st_mtime))
- {
- result.append(*it);
- }
- }
- }
- return result;
-}
-
-bool KonfUpdate::checkFile(const TQString &filename)
-{
- currentFilename = filename;
- int i = currentFilename.findRev('/');
- if (i != -1)
- currentFilename = currentFilename.mid(i+1);
- skip = true;
- TQFile file(filename);
- if (!file.open(IO_ReadOnly))
- return false;
-
- TQTextStream ts(&file);
- ts.setEncoding(TQTextStream::Latin1);
- int lineCount = 0;
- resetOptions();
- TQString id;
- while(!ts.atEnd())
- {
- TQString line = ts.readLine().stripWhiteSpace();
- lineCount++;
- if (line.isEmpty() || (line[0] == '#'))
- continue;
- if (line.startsWith("Id="))
- id = currentFilename+":"+line.mid(3);
- else if (line.startsWith("File="))
- checkGotFile(line.mid(5), id);
- }
-
- return true;
-}
-
-void KonfUpdate::checkGotFile(const TQString &_file, const TQString &id)
-{
- TQString file;
- int i = _file.find(',');
- if (i == -1)
- {
- file = _file.stripWhiteSpace();
- }
- else
- {
- file = _file.mid(i+1).stripWhiteSpace();
- }
-
-// tqDebug("File %s, id %s", file.latin1(), id.latin1());
-
- KSimpleConfig cfg(file);
- cfg.setGroup("$Version");
- TQStringList ids = cfg.readListEntry("update_info");
- if (ids.contains(id))
- return;
- ids.append(id);
- cfg.writeEntry("update_info", ids);
-}
-
-/**
- * Syntax:
- * # Comment
- * Id=id
- * File=oldfile[,newfile]
- * AllGroups
- * Group=oldgroup[,newgroup]
- * RemoveGroup=oldgroup
- * Options=[copy,][overwrite,]
- * Key=oldkey[,newkey]
- * RemoveKey=ldkey
- * AllKeys
- * Keys= [Options](AllKeys|(Key|RemoveKey)*)
- * ScriptArguments=arguments
- * Script=scriptfile[,interpreter]
- *
- * Sequence:
- * (Id,(File(Group,Keys)*)*)*
- **/
-bool KonfUpdate::updateFile(const TQString &filename)
-{
- currentFilename = filename;
- int i = currentFilename.findRev('/');
- if (i != -1)
- currentFilename = currentFilename.mid(i+1);
- skip = true;
- TQFile file(filename);
- if (!file.open(IO_ReadOnly))
- return false;
-
- log() << "Checking update-file '" << filename << "' for new updates" << endl;
-
- TQTextStream ts(&file);
- ts.setEncoding(TQTextStream::Latin1);
- m_lineCount = 0;
- resetOptions();
- while(!ts.atEnd())
- {
- m_line = ts.readLine().stripWhiteSpace();
- m_lineCount++;
- if (m_line.isEmpty() || (m_line[0] == '#'))
- continue;
- if (m_line.startsWith("Id="))
- gotId(m_line.mid(3));
- else if (skip)
- continue;
- else if (m_line.startsWith("Options="))
- gotOptions(m_line.mid(8));
- else if (m_line.startsWith("File="))
- gotFile(m_line.mid(5));
- else if (m_line.startsWith("Group="))
- gotGroup(m_line.mid(6));
- else if (m_line.startsWith("RemoveGroup="))
- {
- gotRemoveGroup(m_line.mid(12));
- resetOptions();
- }
- else if (m_line.startsWith("Script="))
- {
- gotScript(m_line.mid(7));
- resetOptions();
- }
- else if (m_line.startsWith("ScriptArguments="))
- gotScriptArguments(m_line.mid(16));
- else if (m_line.startsWith("Key="))
- {
- gotKey(m_line.mid(4));
- resetOptions();
- }
- else if (m_line.startsWith("RemoveKey="))
- {
- gotRemoveKey(m_line.mid(10));
- resetOptions();
- }
- else if (m_line == "AllKeys")
- {
- gotAllKeys();
- resetOptions();
- }
- else if (m_line == "AllGroups")
- {
- gotAllGroups();
- resetOptions();
- }
- else
- {
- log() << currentFilename << ": parse error in line " << m_lineCount << " : '" << m_line << "'" << endl;
- }
- }
- // Flush.
- gotId(TQString::null);
-
- struct stat buff;
- stat( TQFile::encodeName(filename), &buff);
- config->setGroup(currentFilename);
- config->writeEntry("ctime", buff.st_ctime);
- config->writeEntry("mtime", buff.st_mtime);
- config->sync();
- return true;
-}
-
-
-
-void KonfUpdate::gotId(const TQString &_id)
-{
- if (!id.isEmpty() && !skip)
- {
- config->setGroup(currentFilename);
- TQStringList ids = config->readListEntry("done");
- if (!ids.contains(id))
- {
- ids.append(id);
- config->writeEntry("done", ids);
- config->sync();
- }
- }
-
- // Flush pending changes
- gotFile(TQString::null);
-
- config->setGroup(currentFilename);
- TQStringList ids = config->readListEntry("done");
- if (!_id.isEmpty())
- {
- if (ids.contains(_id))
- {
- //tqDebug("Id '%s' was already in done-list", _id.latin1());
- if (!m_bUseConfigInfo)
- {
- skip = true;
- return;
- }
- }
- skip = false;
- id = _id;
- if (m_bUseConfigInfo)
- log() << currentFilename << ": Checking update '" << _id << "'" << endl;
- else
- log() << currentFilename << ": Found new update '" << _id << "'" << endl;
- }
-}
-
-void KonfUpdate::gotFile(const TQString &_file)
-{
- // Reset group
- gotGroup(TQString::null);
-
- if (!oldFile.isEmpty())
- {
- // Close old file.
- delete oldConfig1;
- oldConfig1 = 0;
-
- oldConfig2->setGroup("$Version");
- TQStringList ids = oldConfig2->readListEntry("update_info");
- TQString cfg_id = currentFilename + ":" + id;
- if (!ids.contains(cfg_id) && !skip)
- {
- ids.append(cfg_id);
- oldConfig2->writeEntry("update_info", ids);
- }
- oldConfig2->sync();
- delete oldConfig2;
- oldConfig2 = 0;
-
- TQString file = locateLocal("config", oldFile);
- struct stat s_buf;
- if (stat(TQFile::encodeName(file), &s_buf) == 0)
- {
- if (s_buf.st_size == 0)
- {
- // Delete empty file.
- unlink(TQFile::encodeName(file));
- }
- }
-
- oldFile = TQString::null;
- }
- if (!newFile.isEmpty())
- {
- // Close new file.
- newConfig->setGroup("$Version");
- TQStringList ids = newConfig->readListEntry("update_info");
- TQString cfg_id = currentFilename + ":" + id;
- if (!ids.contains(cfg_id) && !skip)
- {
- ids.append(cfg_id);
- newConfig->writeEntry("update_info", ids);
- }
- newConfig->sync();
- delete newConfig;
- newConfig = 0;
-
- newFile = TQString::null;
- }
- newConfig = 0;
-
- int i = _file.find(',');
- if (i == -1)
- {
- oldFile = _file.stripWhiteSpace();
- }
- else
- {
- oldFile = _file.left(i).stripWhiteSpace();
- newFile = _file.mid(i+1).stripWhiteSpace();
- if (oldFile == newFile)
- newFile = TQString::null;
- }
-
- if (!oldFile.isEmpty())
- {
- oldConfig2 = new TDEConfig(oldFile, false, false);
- TQString cfg_id = currentFilename + ":" + id;
- oldConfig2->setGroup("$Version");
- TQStringList ids = oldConfig2->readListEntry("update_info");
- if (ids.contains(cfg_id))
- {
- skip = true;
- newFile = TQString::null;
- log() << currentFilename << ": Skipping update '" << id << "'" << endl;
- }
-
- if (!newFile.isEmpty())
- {
- newConfig = new TDEConfig(newFile, false, false);
- newConfig->setGroup("$Version");
- ids = newConfig->readListEntry("update_info");
- if (ids.contains(cfg_id))
- {
- skip = true;
- log() << currentFilename << ": Skipping update '" << id << "'" << endl;
- }
- }
- else
- {
- newConfig = oldConfig2;
- }
-
- oldConfig1 = new TDEConfig(oldFile, true, false);
- }
- else
- {
- newFile = TQString::null;
- }
- newFileName = newFile;
- if (newFileName.isEmpty())
- newFileName = oldFile;
-}
-
-void KonfUpdate::gotGroup(const TQString &_group)
-{
- int i = _group.find(',');
- if (i == -1)
- {
- oldGroup = _group.stripWhiteSpace();
- newGroup = oldGroup;
- }
- else
- {
- oldGroup = _group.left(i).stripWhiteSpace();
- newGroup = _group.mid(i+1).stripWhiteSpace();
- }
-}
-
-void KonfUpdate::gotRemoveGroup(const TQString &_group)
-{
- oldGroup = _group.stripWhiteSpace();
-
- if (!oldConfig1)
- {
- log() << currentFilename << ": !! RemoveGroup without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
- return;
- }
-
- if (!oldConfig1->hasGroup(oldGroup))
- return;
- // Delete group.
- oldConfig2->deleteGroup(oldGroup, true);
- log() << currentFilename << ": RemoveGroup removes group " << oldFile << ":" << oldGroup << endl;
-}
-
-
-void KonfUpdate::gotKey(const TQString &_key)
-{
- int i = _key.find(',');
- if (i == -1)
- {
- oldKey = _key.stripWhiteSpace();
- newKey = oldKey;
- }
- else
- {
- oldKey = _key.left(i).stripWhiteSpace();
- newKey = _key.mid(i+1).stripWhiteSpace();
- }
-
- if (oldKey.isEmpty() || newKey.isEmpty())
- {
- log() << currentFilename << ": !! Key specifies invalid key in line " << m_lineCount << " : '" << m_line << "'" << endl;
- return;
- }
- if (!oldConfig1)
- {
- log() << currentFilename << ": !! Key without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
- return;
- }
- oldConfig1->setGroup(oldGroup);
- if (!oldConfig1->hasKey(oldKey))
- return;
- TQString value = oldConfig1->readEntry(oldKey);
- newConfig->setGroup(newGroup);
- if (!m_bOverwrite && newConfig->hasKey(newKey))
- {
- log() << currentFilename << ": Skipping " << newFileName << ":" << newGroup << ":" << newKey << ", already exists."<< endl;
- return;
- }
- log() << currentFilename << ": Updating " << newFileName << ":" << newGroup << ":" << newKey << " to '" << value << "'" << endl;
- newConfig->writeEntry(newKey, value);
-
- if (m_bCopy)
- return; // Done.
-
- // Delete old entry
- if ((oldConfig2 == newConfig) &&
- (oldGroup == newGroup) &&
- (oldKey == newKey))
- return; // Don't delete!
- oldConfig2->setGroup(oldGroup);
- oldConfig2->deleteEntry(oldKey, false);
- log() << currentFilename << ": Removing " << oldFile << ":" << oldGroup << ":" << oldKey << ", moved." << endl;
- if (oldConfig2->deleteGroup(oldGroup, false)) { // Delete group if empty.
- log() << currentFilename << ": Removing empty group " << oldFile << ":" << oldGroup << endl;
- }
-}
-
-void KonfUpdate::gotRemoveKey(const TQString &_key)
-{
- oldKey = _key.stripWhiteSpace();
-
- if (oldKey.isEmpty())
- {
- log() << currentFilename << ": !! RemoveKey specifies invalid key in line " << m_lineCount << " : '" << m_line << "'" << endl;
- return;
- }
-
- if (!oldConfig1)
- {
- log() << currentFilename << ": !! Key without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
- return;
- }
-
- oldConfig1->setGroup(oldGroup);
- if (!oldConfig1->hasKey(oldKey))
- return;
- log() << currentFilename << ": RemoveKey removes " << oldFile << ":" << oldGroup << ":" << oldKey << endl;
-
- // Delete old entry
- oldConfig2->setGroup(oldGroup);
- oldConfig2->deleteEntry(oldKey, false);
- if (oldConfig2->deleteGroup(oldGroup, false)) { // Delete group if empty.
- log() << currentFilename << ": Removing empty group " << oldFile << ":" << oldGroup << endl;
- }
-}
-
-void KonfUpdate::gotAllKeys()
-{
- if (!oldConfig1)
- {
- log() << currentFilename << ": !! AllKeys without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
- return;
- }
-
- TQMap<TQString, TQString> list = oldConfig1->entryMap(oldGroup);
- for(TQMap<TQString, TQString>::Iterator it = list.begin();
- it != list.end(); ++it)
- {
- gotKey(it.key());
- }
-}
-
-void KonfUpdate::gotAllGroups()
-{
- if (!oldConfig1)
- {
- log() << currentFilename << ": !! AllGroups without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
- return;
- }
-
- TQStringList allGroups = oldConfig1->groupList();
- for(TQStringList::ConstIterator it = allGroups.begin();
- it != allGroups.end(); ++it)
- {
- oldGroup = *it;
- newGroup = oldGroup;
- gotAllKeys();
- }
-}
-
-void KonfUpdate::gotOptions(const TQString &_options)
-{
- TQStringList options = TQStringList::split(',', _options);
- for(TQStringList::ConstIterator it = options.begin();
- it != options.end();
- ++it)
- {
- if ( (*it).lower().stripWhiteSpace() == "copy")
- m_bCopy = true;
-
- if ( (*it).lower().stripWhiteSpace() == "overwrite")
- m_bOverwrite = true;
- }
-}
-
-void KonfUpdate::copyGroup(TDEConfigBase *cfg1, const TQString &grp1,
- TDEConfigBase *cfg2, const TQString &grp2)
-{
- cfg1->setGroup(grp1);
- cfg2->setGroup(grp2);
- TQMap<TQString, TQString> list = cfg1->entryMap(grp1);
- for(TQMap<TQString, TQString>::Iterator it = list.begin();
- it != list.end(); ++it)
- {
- cfg2->writeEntry(it.key(), cfg1->readEntry(it.key()));
- }
-}
-
-void KonfUpdate::gotScriptArguments(const TQString &_arguments)
-{
- m_arguments = _arguments;
-}
-
-void KonfUpdate::gotScript(const TQString &_script)
-{
- TQString script, interpreter;
- int i = _script.find(',');
- if (i == -1)
- {
- script = _script.stripWhiteSpace();
- }
- else
- {
- script = _script.left(i).stripWhiteSpace();
- interpreter = _script.mid(i+1).stripWhiteSpace();
- }
-
-
- if (script.isEmpty())
- {
- log() << currentFilename << ": !! Script fails to specifiy filename in line " << m_lineCount << " : '" << m_line << "'" << endl;
- skip = true;
- return;
- }
-
-
-
- TQString path = locate("data","kconf_update/"+script);
- if (path.isEmpty())
- {
- if (interpreter.isEmpty())
- path = locate("lib", "kconf_update_bin/"+script);
-
- if (path.isEmpty())
- {
- log() << currentFilename << ": !! Script '" << script << "' not found in line " << m_lineCount << " : '" << m_line << "'" << endl;
- skip = true;
- return;
- }
- }
-
- if( !m_arguments.isNull())
- log() << currentFilename << ": Running script '" << script << "' with arguments '" << m_arguments << "'" << endl;
- else
- log() << currentFilename << ": Running script '" << script << "'" << endl;
-
- TQString cmd;
- if (interpreter.isEmpty())
- cmd = path;
- else
- cmd = interpreter + " " + path;
-
- if( !m_arguments.isNull())
- {
- cmd += ' ';
- cmd += m_arguments;
- }
-
- KTempFile tmp1;
- tmp1.setAutoDelete(true);
- KTempFile tmp2;
- tmp2.setAutoDelete(true);
- KTempFile tmp3;
- tmp3.setAutoDelete(true);
-
- int result;
- if (oldConfig1)
- {
- if (debug)
- {
- tmp1.setAutoDelete(false);
- log() << "Script input stored in " << tmp1.name() << endl;
- }
- KSimpleConfig cfg(tmp1.name());
-
- if (oldGroup.isEmpty())
- {
- // Write all entries to tmpFile;
- TQStringList grpList = oldConfig1->groupList();
- for(TQStringList::ConstIterator it = grpList.begin();
- it != grpList.end();
- ++it)
- {
- copyGroup(oldConfig1, *it, &cfg, *it);
- }
- }
- else
- {
- copyGroup(oldConfig1, oldGroup, &cfg, TQString::null);
- }
- cfg.sync();
- result = system(TQFile::encodeName(TQString("%1 < %2 > %3 2> %4").arg(cmd, tmp1.name(), tmp2.name(), tmp3.name())));
- }
- else
- {
- // No config file
- result = system(TQFile::encodeName(TQString("%1 2> %2").arg(cmd, tmp3.name())));
- }
-
- // Copy script stderr to log file
- {
- TQFile output(tmp3.name());
- if (output.open(IO_ReadOnly))
- {
- TQTextStream ts( &output );
- ts.setEncoding(TQTextStream::UnicodeUTF8);
- while(!ts.atEnd())
- {
- TQString line = ts.readLine();
- log() << "[Script] " << line << endl;
- }
- }
- }
-
- if (result)
- {
- log() << currentFilename << ": !! An error occured while running '" << cmd << "'" << endl;
- return;
- }
-
- if (!oldConfig1)
- return; // Nothing to merge
-
- if (debug)
- {
- tmp2.setAutoDelete(false);
- log() << "Script output stored in " << tmp2.name() << endl;
- }
-
- // Deleting old entries
- {
- TQString group = oldGroup;
- TQFile output(tmp2.name());
- if (output.open(IO_ReadOnly))
- {
- TQTextStream ts( &output );
- ts.setEncoding(TQTextStream::UnicodeUTF8);
- while(!ts.atEnd())
- {
- TQString line = ts.readLine();
- if (line.startsWith("["))
- {
- int j = line.find(']')+1;
- if (j > 0)
- group = line.mid(1, j-2);
- }
- else if (line.startsWith("# DELETE "))
- {
- TQString key = line.mid(9);
- if (key[0] == '[')
- {
- int j = key.find(']')+1;
- if (j > 0)
- {
- group = key.mid(1,j-2);
- key = key.mid(j);
- }
- }
- oldConfig2->setGroup(group);
- oldConfig2->deleteEntry(key, false);
- log() << currentFilename << ": Script removes " << oldFile << ":" << group << ":" << key << endl;
- if (oldConfig2->deleteGroup(group, false)) { // Delete group if empty.
- log() << currentFilename << ": Removing empty group " << oldFile << ":" << group << endl;
- }
- }
- else if (line.startsWith("# DELETEGROUP"))
- {
- TQString key = line.mid(13).stripWhiteSpace();
- if (key[0] == '[')
- {
- int j = key.find(']')+1;
- if (j > 0)
- {
- group = key.mid(1,j-2);
- }
- }
- if (oldConfig2->deleteGroup(group, true)) { // Delete group
- log() << currentFilename << ": Script removes group " << oldFile << ":" << group << endl;
- }
- }
- }
- }
- }
-
- // Merging in new entries.
- m_bCopy = true;
- {
- TDEConfig *saveOldConfig1 = oldConfig1;
- TQString saveOldGroup = oldGroup;
- TQString saveNewGroup = newGroup;
- oldConfig1 = new TDEConfig(tmp2.name(), true, false);
-
- // For all groups...
- TQStringList grpList = oldConfig1->groupList();
- for(TQStringList::ConstIterator it = grpList.begin();
- it != grpList.end();
- ++it)
- {
- oldGroup = *it;
- if (oldGroup != "<default>")
- {
- newGroup = oldGroup;
- }
- gotAllKeys(); // Copy all keys
- }
- delete oldConfig1;
- oldConfig1 = saveOldConfig1;
- oldGroup = saveOldGroup;
- newGroup = saveNewGroup;
- }
-}
-
-void KonfUpdate::resetOptions()
-{
- m_bCopy = false;
- m_bOverwrite = false;
- m_arguments = TQString::null;
-}
-
-
-extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
-{
- TDEAboutData aboutData("kconf_update", I18N_NOOP("KConf Update"),
- "1.0.2",
- I18N_NOOP("TDE Tool for updating user configuration files"),
- TDEAboutData::License_GPL,
- "(c) 2001, Waldo Bastian");
-
- aboutData.addAuthor("Waldo Bastian", 0, "bastian@kde.org");
-
- TDECmdLineArgs::init(argc, argv, &aboutData);
- TDECmdLineArgs::addCmdLineOptions(options);
-
- TDEInstance instance(&aboutData);
-
- KonfUpdate konfUpdate;
-
- return 0;
-}
diff --git a/kded/CMakeLists.txt b/kded/CMakeLists.txt
index 903126ca8..ee693fb4a 100644
--- a/kded/CMakeLists.txt
+++ b/kded/CMakeLists.txt
@@ -18,8 +18,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
link_directories(
@@ -51,16 +51,16 @@ set( ${target}_SRCS
# modules need this library
tde_add_tdeinit_executable( ${target} AUTOMOC EXPORT
SOURCES ${${target}_SRCS}
- LINK kio-shared
+ LINK tdeio-shared
)
-#### kbuildsycoca ###############################
+#### tdebuildsycoca ###############################
-set( target kbuildsycoca )
+set( target tdebuildsycoca )
set( ${target}_SRCS
- kbuildsycoca.cpp kbuildservicetypefactory.cpp
+ tdebuildsycoca.cpp kbuildservicetypefactory.cpp
kbuildservicefactory.cpp kbuildservicegroupfactory.cpp
kbuildimageiofactory.cpp kbuildprotocolinfofactory.cpp
kctimefactory.cpp vfolder_menu.cpp
@@ -68,7 +68,7 @@ set( ${target}_SRCS
tde_add_tdeinit_executable( ${target} AUTOMOC
SOURCES ${${target}_SRCS}
- LINK kio-shared
+ LINK tdeio-shared
)
@@ -87,31 +87,31 @@ tde_add_executable( ${target}
)
-#### kde-menu ###################################
+#### tde-menu ###################################
-set( target kde-menu )
+set( target tde-menu )
set( ${target}_SRCS
- kde-menu.cpp
+ tde-menu.cpp
)
tde_add_executable( ${target}
SOURCES ${${target}_SRCS}
- LINK kio-shared
+ LINK tdeio-shared
DESTINATION ${BIN_INSTALL_DIR}
)
-#### kmimelist ##################################
+#### tdemimelist ##################################
-set( target kmimelist )
+set( target tdemimelist )
set( ${target}_SRCS
- kmimelist.cpp
+ tdemimelist.cpp
)
tde_add_executable( ${target}
SOURCES ${${target}_SRCS}
- LINK kio-shared
+ LINK tdeio-shared
DESTINATION ${BIN_INSTALL_DIR}
)
diff --git a/kded/DESIGN b/kded/DESIGN
index e6653807b..0fffb0456 100644
--- a/kded/DESIGN
+++ b/kded/DESIGN
@@ -6,9 +6,9 @@ cache of servicetypes, mimetypes and services, for a particular user.
It uses KDirWatch to monitor the directories contain the .desktop files.
When a file is added/removed, it waits 5 seconds (in case of series of
-updates), and then launches kbuildsycoca.
+updates), and then launches tdebuildsycoca.
-kbuildsycoca recreates the sycoca file by:
+tdebuildsycoca recreates the sycoca file by:
* parsing all .desktop files, replacing global ones by local ones (at any
level of the hierarchy)
* creating all objects in memory
diff --git a/kded/Makefile.am b/kded/Makefile.am
index 1baf30e4f..093b5db0e 100644
--- a/kded/Makefile.am
+++ b/kded/Makefile.am
@@ -20,15 +20,15 @@
INCLUDES= -I$(srcdir)/.. -I$(top_srcdir) $(all_includes)
lib_LTLIBRARIES =
-tdeinit_LTLIBRARIES = kded.la kbuildsycoca.la
+tdeinit_LTLIBRARIES = kded.la tdebuildsycoca.la
kded_la_LDFLAGS = $(all_libraries) -module -avoid-version
kded_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la $(LIB_X11)
kded_la_SOURCES = kded.cpp kdedmodule.cpp
-kbuildsycoca_la_LDFLAGS = $(all_libraries) -module -avoid-version
-kbuildsycoca_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE)
-kbuildsycoca_la_SOURCES = kbuildsycoca.cpp kbuildservicetypefactory.cpp \
+tdebuildsycoca_la_LDFLAGS = $(all_libraries) -module -avoid-version
+tdebuildsycoca_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE)
+tdebuildsycoca_la_SOURCES = tdebuildsycoca.cpp kbuildservicetypefactory.cpp \
kbuildservicefactory.cpp \
kbuildservicegroupfactory.cpp \
kbuildimageiofactory.cpp \
@@ -36,25 +36,25 @@ kbuildsycoca_la_SOURCES = kbuildsycoca.cpp kbuildservicetypefactory.cpp \
kctimefactory.cpp \
vfolder_menu.cpp
-bin_PROGRAMS = kdontchangethehostname kde-menu kmimelist
+bin_PROGRAMS = kdontchangethehostname tde-menu tdemimelist
kdontchangethehostname_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
kdontchangethehostname_LDADD = $(LIB_TDECORE)
kdontchangethehostname_SOURCES = khostname.cpp
-kmimelist_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-kmimelist_LDADD = ../kio/libkio.la
-kmimelist_SOURCES = kmimelist.cpp
+tdemimelist_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+tdemimelist_LDADD = ../tdeio/libtdeio.la
+tdemimelist_SOURCES = tdemimelist.cpp
kde_menu_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
kde_menu_LDADD = $(LIB_KIO)
-kde_menu_SOURCES = kde-menu.cpp
+kde_menu_SOURCES = tde-menu.cpp
METASOURCES = AUTO
include_HEADERS = kdedmodule.h
-noinst_HEADERS = kbuildsycoca.h kbuildservicetypefactory.h \
+noinst_HEADERS = tdebuildsycoca.h kbuildservicetypefactory.h \
kbuildservicefactory.h kbuildservicegroupfactory.h \
kbuildimageiofactory.h kresourcelist.h \
kbuildprotocolinfofactory.h
@@ -65,7 +65,7 @@ servicetypedir = $(kde_servicetypesdir)
xdg_menu_DATA = applications.menu applications.menu-no-kde
update_DATA = kded.upd
-updatedir = $(kde_datadir)/kconf_update
+updatedir = $(kde_datadir)/tdeconf_update
include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kded/README.kded b/kded/README.kded
index 1cf382279..7265a1084 100644
--- a/kded/README.kded
+++ b/kded/README.kded
@@ -7,19 +7,19 @@ Some of these tasks are built in, others are started on demand.
Built in tasks
==============
*) Checking for newly installed software and updating tdesycoca when new
-software is detected. Updating of tdesycoca is done by the program kbuildsycoca
+software is detected. Updating of tdesycoca is done by the program tdebuildsycoca
which gets started by kded. When kded is first started it always runs
-kbuildsycoca to ensure that tdesycoca is up to date.
+tdebuildsycoca to ensure that tdesycoca is up to date.
*) Checking for newly installed update files. Applications can install
*.upd update files. These *.upd files are used to update configuration files
of users, primarily when new versions of applications are installed with
(slightly) different configuration file formats. Updating of configuration
-files is done by kconf_update. kded starts kconf_update when it detects a
-new update file. When kded is first started it always runs kconf_update to
-ensure that it has not missed any update files. kconf_update keeps track
+files is done by tdeconf_update. kded starts tdeconf_update when it detects a
+new update file. When kded is first started it always runs tdeconf_update to
+ensure that it has not missed any update files. tdeconf_update keeps track
of which update files have been processed already in the config-file
-kconf_updaterc. It only performs a certain update once.
+tdeconf_updaterc. It only performs a certain update once.
*) Checking for hostname changes. It is a really bad idea to change the
hostname of a running system and it usually only happens with incorrectly
@@ -42,12 +42,12 @@ and has a default of 5000 (5 seconds).
CheckSycoca: This option can be used to disable checking for new software.
tdesycoca will still be built when kded starts up and when applications
explicitly request a rebuild of the tdesycoca database. The user can
-also manually rebuild tdesycoca by running the kbuildsycoca program.
+also manually rebuild tdesycoca by running the tdebuildsycoca program.
The default value of this option is "true". Checking can be disabled by
setting this option to "false".
CheckUpdates: This option can be used to disable checking for update files.
-kconf_update will still be run when kded starts up.
+tdeconf_update will still be run when kded starts up.
The default value of this option is "true". Checking can be disabled by
setting this option to "false".
diff --git a/kded/kbuildsycoca.cpp b/kded/kbuildsycoca.cpp
deleted file mode 100644
index 13a645395..000000000
--- a/kded/kbuildsycoca.cpp
+++ /dev/null
@@ -1,959 +0,0 @@
-/* This file is part of the KDE libraries
- * Copyright (C) 1999 David Faure <faure@kde.org>
- * Copyright (C) 2002-2003 Waldo Bastian <bastian@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#include <tqdir.h>
-#include <tqeventloop.h>
-#include <config.h>
-
-#include "kbuildsycoca.h"
-#include "kresourcelist.h"
-#include "vfolder_menu.h"
-
-#include <kservice.h>
-#include <kmimetype.h>
-#include <kbuildservicetypefactory.h>
-#include <kbuildservicefactory.h>
-#include <kbuildservicegroupfactory.h>
-#include <kbuildimageiofactory.h>
-#include <kbuildprotocolinfofactory.h>
-#include <kctimefactory.h>
-#include <kdatastream.h>
-
-#include <tqdatastream.h>
-#include <tqfile.h>
-#include <tqtimer.h>
-
-#include <assert.h>
-#include <kapplication.h>
-#include <dcopclient.h>
-#include <kglobal.h>
-#include <kdebug.h>
-#include <kdirwatch.h>
-#include <kstandarddirs.h>
-#include <ksavefile.h>
-#include <klocale.h>
-#include <kaboutdata.h>
-#include <kcmdlineargs.h>
-#include <kcrash.h>
-
-#ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build
- // GUI version of kbuildsycoca, so-called "kbuildsycocaw".
-# include <tqlabel.h>
-# include <kmessagebox.h>
- bool silent;
- bool showprogress;
-#endif
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <time.h>
-#include <memory> // auto_ptr
-
-typedef TQDict<KSycocaEntry> KBSEntryDict;
-typedef TQValueList<KSycocaEntry::List> KSycocaEntryListList;
-
-static TQ_UINT32 newTimestamp = 0;
-
-static KBuildServiceFactory *g_bsf = 0;
-static KBuildServiceGroupFactory *g_bsgf = 0;
-static KSycocaFactory *g_factory = 0;
-static KCTimeInfo *g_ctimeInfo = 0;
-static TQDict<TQ_UINT32> *g_ctimeDict = 0;
-static const char *g_resource = 0;
-static KBSEntryDict *g_entryDict = 0;
-static KBSEntryDict *g_serviceGroupEntryDict = 0;
-static KSycocaEntryListList *g_allEntries = 0;
-static TQStringList *g_changeList = 0;
-static TQStringList *g_allResourceDirs = 0;
-static bool g_changed = false;
-static KSycocaEntry::List g_tempStorage;
-static VFolderMenu *g_vfolder = 0;
-
-static const char *cSycocaPath = 0;
-
-static bool bGlobalDatabase = false;
-static bool bMenuTest = false;
-
-void crashHandler(int)
-{
- // If we crash while reading sycoca, we delete the database
- // in an attempt to recover.
- if (cSycocaPath)
- unlink(cSycocaPath);
-}
-
-static TQString sycocaPath()
-{
- TQString path;
-
- if (bGlobalDatabase)
- {
- path = TDEGlobal::dirs()->saveLocation("services")+"tdesycoca";
- }
- else
- {
- TQCString tdesycoca_env = getenv("TDESYCOCA");
- if (tdesycoca_env.isEmpty())
- path = TDEGlobal::dirs()->saveLocation("cache")+"tdesycoca";
- else
- path = TQFile::decodeName(tdesycoca_env);
- }
-
- return path;
-}
-
-static TQString oldSycocaPath()
-{
- TQCString tdesycoca_env = getenv("TDESYCOCA");
- if (tdesycoca_env.isEmpty())
- return TDEGlobal::dirs()->saveLocation("tmp")+"tdesycoca";
-
- return TQString::null;
-}
-
-KBuildSycoca::KBuildSycoca()
- : KSycoca( true )
-{
-}
-
-KBuildSycoca::~KBuildSycoca()
-{
-
-}
-
-void KBuildSycoca::processGnomeVfs()
-{
- TQString file = locate("app-reg", "gnome-vfs.applications");
- if (file.isEmpty())
- {
-// kdDebug(7021) << "gnome-vfs.applications not found." << endl;
- return;
- }
-
- TQString app;
-
- char line[1024*64];
-
- FILE *f = fopen(TQFile::encodeName(file), "r");
- while (!feof(f))
- {
- if (!fgets(line, sizeof(line)-1, f))
- {
- break;
- }
-
- if (line[0] != '\t')
- {
- app = TQString::fromLatin1(line);
- app.truncate(app.length()-1);
- }
- else if (strncmp(line+1, "mime_types=", 11) == 0)
- {
- TQString mimetypes = TQString::fromLatin1(line+12);
- mimetypes.truncate(mimetypes.length()-1);
- mimetypes.replace(TQRegExp("\\*"), "all");
- KService *s = g_bsf->findServiceByName(app);
- if (!s)
- continue;
-
- TQStringList &serviceTypes = s->accessServiceTypes();
- if (serviceTypes.count() <= 1)
- {
- serviceTypes += TQStringList::split(',', mimetypes);
-// kdDebug(7021) << "Adding gnome mimetypes for '" << app << "'.\n";
-// kdDebug(7021) << "ServiceTypes=" << s->serviceTypes().join(":") << endl;
- }
- }
- }
- fclose( f );
-}
-
-KSycocaEntry *KBuildSycoca::createEntry(const TQString &file, bool addToFactory)
-{
- TQ_UINT32 timeStamp = g_ctimeInfo->ctime(file);
- if (!timeStamp)
- {
- timeStamp = TDEGlobal::dirs()->calcResourceHash( g_resource, file, true);
- }
- KSycocaEntry* entry = 0;
- if (g_allEntries)
- {
- assert(g_ctimeDict);
- TQ_UINT32 *timeP = (*g_ctimeDict)[file];
- TQ_UINT32 oldTimestamp = timeP ? *timeP : 0;
-
- if (timeStamp && (timeStamp == oldTimestamp))
- {
- // Re-use old entry
- if (g_factory == g_bsgf) // Strip .directory from service-group entries
- {
- entry = g_entryDict->find(file.left(file.length()-10));
- }
- else if (g_factory == g_bsf)
- {
- entry = g_entryDict->find(file);
- }
- else
- {
- entry = g_entryDict->find(file);
- }
- // remove from g_ctimeDict; if g_ctimeDict is not empty
- // after all files have been processed, it means
- // some files were removed since last time
- g_ctimeDict->remove( file );
- }
- else if (oldTimestamp)
- {
- g_changed = true;
- kdDebug(7021) << "modified: " << file << endl;
- }
- else
- {
- g_changed = true;
- kdDebug(7021) << "new: " << file << endl;
- }
- }
- g_ctimeInfo->addCTime(file, timeStamp );
- if (!entry)
- {
- // Create a new entry
- entry = g_factory->createEntry( file, g_resource );
- }
- if ( entry && entry->isValid() )
- {
- if (addToFactory)
- g_factory->addEntry( entry, g_resource );
- else
- g_tempStorage.append(entry);
- return entry;
- }
- return 0;
-}
-
-void KBuildSycoca::slotCreateEntry(const TQString &file, KService **service)
-{
- KSycocaEntry *entry = createEntry(file, false);
- *service = dynamic_cast<KService *>(entry);
-}
-
-// returns false if the database is up to date
-bool KBuildSycoca::build()
-{
- typedef TQPtrList<KBSEntryDict> KBSEntryDictList;
- KBSEntryDictList *entryDictList = 0;
- KBSEntryDict *serviceEntryDict = 0;
-
- entryDictList = new KBSEntryDictList();
- // Convert for each factory the entryList to a Dict.
- int i = 0;
- // For each factory
- for (KSycocaFactory *factory = m_lstFactories->first();
- factory;
- factory = m_lstFactories->next() )
- {
- KBSEntryDict *entryDict = new KBSEntryDict();
- if (g_allEntries)
- {
- KSycocaEntry::List list = (*g_allEntries)[i++];
- for( KSycocaEntry::List::Iterator it = list.begin();
- it != list.end();
- ++it)
- {
- entryDict->insert( (*it)->entryPath(), static_cast<KSycocaEntry *>(*it));
- }
- }
- if (factory == g_bsf)
- serviceEntryDict = entryDict;
- else if (factory == g_bsgf)
- g_serviceGroupEntryDict = entryDict;
- entryDictList->append(entryDict);
- }
-
- TQStringList allResources;
- // For each factory
- for (KSycocaFactory *factory = m_lstFactories->first();
- factory;
- factory = m_lstFactories->next() )
- {
- // For each resource the factory deals with
- const KSycocaResourceList *list = factory->resourceList();
- if (!list) continue;
-
- for( KSycocaResourceList::ConstIterator it1 = list->begin();
- it1 != list->end();
- ++it1 )
- {
- KSycocaResource res = (*it1);
- if (!allResources.contains(res.resource))
- allResources.append(res.resource);
- }
- }
-
- g_ctimeInfo = new KCTimeInfo(); // This is a build factory too, don't delete!!
- bool uptodate = true;
- // For all resources
- for( TQStringList::ConstIterator it1 = allResources.begin();
- it1 != allResources.end();
- ++it1 )
- {
- g_changed = false;
- g_resource = (*it1).ascii();
-
- TQStringList relFiles;
-
- (void) TDEGlobal::dirs()->findAllResources( g_resource,
- TQString::null,
- true, // Recursive!
- true, // uniq
- relFiles);
-
-
- // Now find all factories that use this resource....
- // For each factory
- g_entryDict = entryDictList->first();
- for (g_factory = m_lstFactories->first();
- g_factory;
- g_factory = m_lstFactories->next(),
- g_entryDict = entryDictList->next() )
- {
- // For each resource the factory deals with
- const KSycocaResourceList *list = g_factory->resourceList();
- if (!list) continue;
-
- for( KSycocaResourceList::ConstIterator it2 = list->begin();
- it2 != list->end();
- ++it2 )
- {
- KSycocaResource res = (*it2);
- if (res.resource != (*it1)) continue;
-
- // For each file in the resource
- for( TQStringList::ConstIterator it3 = relFiles.begin();
- it3 != relFiles.end();
- ++it3 )
- {
- // Check if file matches filter
- if ((*it3).endsWith(res.extension))
- createEntry(*it3, true);
- }
- }
- if ((g_factory == g_bsf) && (strcmp(g_resource, "services") == 0))
- processGnomeVfs();
- }
- if (g_changed || !g_allEntries)
- {
- uptodate = false;
- g_changeList->append(g_resource);
- }
- }
-
- bool result = !uptodate || !g_ctimeDict->isEmpty();
-
- if (result || bMenuTest)
- {
- g_resource = "apps";
- g_factory = g_bsf;
- g_entryDict = serviceEntryDict;
- g_changed = false;
-
- g_vfolder = new VFolderMenu;
- if (!m_trackId.isEmpty())
- g_vfolder->setTrackId(m_trackId);
-
- connect(g_vfolder, TQT_SIGNAL(newService(const TQString &, KService **)),
- this, TQT_SLOT(slotCreateEntry(const TQString &, KService **)));
-
- VFolderMenu::SubMenu *kdeMenu = g_vfolder->parseMenu("applications.menu", true);
-
- KServiceGroup *entry = g_bsgf->addNew("/", kdeMenu->directoryFile, 0, false);
- entry->setLayoutInfo(kdeMenu->layoutList);
- createMenu(TQString::null, TQString::null, kdeMenu);
-
- KServiceGroup::Ptr g(entry);
-
- (void) existingResourceDirs();
- *g_allResourceDirs += g_vfolder->allDirectories();
-
- disconnect(g_vfolder, TQT_SIGNAL(newService(const TQString &, KService **)),
- this, TQT_SLOT(slotCreateEntry(const TQString &, KService **)));
-
- if (g_changed || !g_allEntries)
- {
- uptodate = false;
- g_changeList->append(g_resource);
- }
- if (bMenuTest)
- return false;
- }
-
- return result;
-}
-
-void KBuildSycoca::createMenu(TQString caption, TQString name, VFolderMenu::SubMenu *menu)
-{
- for(VFolderMenu::SubMenu *subMenu = menu->subMenus.first(); subMenu; subMenu = menu->subMenus.next())
- {
- TQString subName = name+subMenu->name+"/";
-
- TQString directoryFile = subMenu->directoryFile;
- if (directoryFile.isEmpty())
- directoryFile = subName+".directory";
- TQ_UINT32 timeStamp = g_ctimeInfo->ctime(directoryFile);
- if (!timeStamp)
- {
- timeStamp = TDEGlobal::dirs()->calcResourceHash( g_resource, directoryFile, true);
- }
-
- KServiceGroup* entry = 0;
- if (g_allEntries)
- {
- TQ_UINT32 *timeP = (*g_ctimeDict)[directoryFile];
- TQ_UINT32 oldTimestamp = timeP ? *timeP : 0;
-
- if (timeStamp && (timeStamp == oldTimestamp))
- {
- entry = dynamic_cast<KServiceGroup *> (g_serviceGroupEntryDict->find(subName));
- if (entry && (entry->directoryEntryPath() != directoryFile))
- entry = 0; // Can't reuse this one!
- }
- }
- g_ctimeInfo->addCTime(directoryFile, timeStamp);
-
- entry = g_bsgf->addNew(subName, subMenu->directoryFile, entry, subMenu->isDeleted);
- entry->setLayoutInfo(subMenu->layoutList);
- if (! (bMenuTest && entry->noDisplay()) )
- createMenu(caption + entry->caption() + "/", subName, subMenu);
- }
- if (caption.isEmpty())
- caption += "/";
- if (name.isEmpty())
- name += "/";
- for(TQDictIterator<KService> it(menu->items); it.current(); ++it)
- {
- if (bMenuTest)
- {
- if (!menu->isDeleted && !it.current()->noDisplay())
- printf("%s\t%s\t%s\n", caption.local8Bit().data(), it.current()->menuId().local8Bit().data(), locate("apps", it.current()->desktopEntryPath()).local8Bit().data());
- }
- else
- {
- g_bsf->addEntry( it.current(), g_resource );
- g_bsgf->addNewEntryTo(name, it.current());
- }
- }
-}
-
-bool KBuildSycoca::recreate()
-{
- TQString path(sycocaPath());
-#ifdef Q_WS_WIN
- printf("kbuildsycoca: path='%s'\n", (const char*)path);
-#endif
-
- // KSaveFile first writes to a temp file.
- // Upon close() it moves the stuff to the right place.
- std::auto_ptr<KSaveFile> database( new KSaveFile(path) );
- if (database->status() == EACCES && TQFile::exists(path))
- {
- TQFile::remove( path );
- database.reset( new KSaveFile(path) ); // try again
- }
- if (database->status() != 0)
- {
- fprintf(stderr, "[kbuildsycoca] ERROR creating database '%s'! %s\n", path.local8Bit().data(),strerror(database->status()));
-#ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build
- // GUI version of kbuildsycoca, so-called "kbuildsycocaw".
- if (!silent)
- KMessageBox::error(0, i18n("Error creating database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n").arg(path.local8Bit().data()), i18n("KBuildSycoca"));
-#endif
- return false;
- }
-
- m_str = database->dataStream();
-
- kdDebug(7021) << "Recreating tdesycoca file (" << path << ", version " << KSycoca::version() << ")" << endl;
-
- // It is very important to build the servicetype one first
- // Both are registered in KSycoca, no need to keep the pointers
- KSycocaFactory *stf = new KBuildServiceTypeFactory;
- g_bsgf = new KBuildServiceGroupFactory();
- g_bsf = new KBuildServiceFactory(stf, g_bsgf);
- (void) new KBuildImageIOFactory();
- (void) new KBuildProtocolInfoFactory();
-
- if( build()) // Parse dirs
- {
- save(); // Save database
- if (m_str->device()->status())
- database->abort(); // Error
- m_str = 0L;
- if (!database->close())
- {
- fprintf(stderr, "[kbuildsycoca] ERROR writing database '%s'!\n", database->name().local8Bit().data());
- fprintf(stderr, "[kbuildsycoca] Disk full?\n");
-#ifdef KBUILDSYCOCA_GUI
- if (!silent)
- KMessageBox::error(0, i18n("[kbuildsycoca] Error writing database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n").arg(path.local8Bit().data()), i18n("KBuildSycoca"));
-#endif
- return false;
- }
- }
- else
- {
- m_str = 0L;
- database->abort();
- if (bMenuTest)
- return true;
- kdDebug(7021) << "Database is up to date" << endl;
- }
-
- if (!bGlobalDatabase)
- {
- // update the timestamp file
- TQString stamppath = path + "stamp";
- TQFile tdesycocastamp(stamppath);
- tdesycocastamp.open( IO_WriteOnly );
- TQDataStream str( &tdesycocastamp );
- str << newTimestamp;
- str << existingResourceDirs();
- if (g_vfolder)
- str << g_vfolder->allDirectories(); // Extra resource dirs
- }
- return true;
-}
-
-void KBuildSycoca::save()
-{
- // Write header (#pass 1)
- m_str->device()->at(0);
-
- (*m_str) << (TQ_INT32) KSycoca::version();
- KSycocaFactory * servicetypeFactory = 0L;
- KSycocaFactory * serviceFactory = 0L;
- for(KSycocaFactory *factory = m_lstFactories->first();
- factory;
- factory = m_lstFactories->next())
- {
- TQ_INT32 aId;
- TQ_INT32 aOffset;
- aId = factory->factoryId();
- if ( aId == KST_KServiceTypeFactory )
- servicetypeFactory = factory;
- else if ( aId == KST_KServiceFactory )
- serviceFactory = factory;
- aOffset = factory->offset();
- (*m_str) << aId;
- (*m_str) << aOffset;
- }
- (*m_str) << (TQ_INT32) 0; // No more factories.
- // Write TDEDIRS
- (*m_str) << TDEGlobal::dirs()->kfsstnd_prefixes();
- (*m_str) << newTimestamp;
- (*m_str) << TDEGlobal::locale()->language();
- (*m_str) << TDEGlobal::dirs()->calcResourceHash("services", "update_tdesycoca", true);
- (*m_str) << (*g_allResourceDirs);
-
- // Write factory data....
- for(KSycocaFactory *factory = m_lstFactories->first();
- factory;
- factory = m_lstFactories->next())
- {
- factory->save(*m_str);
- if (m_str->device()->status())
- return; // error
- }
-
- int endOfData = m_str->device()->at();
-
- // Write header (#pass 2)
- m_str->device()->at(0);
-
- (*m_str) << (TQ_INT32) KSycoca::version();
- for(KSycocaFactory *factory = m_lstFactories->first();
- factory;
- factory = m_lstFactories->next())
- {
- TQ_INT32 aId;
- TQ_INT32 aOffset;
- aId = factory->factoryId();
- aOffset = factory->offset();
- (*m_str) << aId;
- (*m_str) << aOffset;
- }
- (*m_str) << (TQ_INT32) 0; // No more factories.
-
- // Jump to end of database
- m_str->device()->at(endOfData);
-}
-
-bool KBuildSycoca::checkDirTimestamps( const TQString& dirname, const TQDateTime& stamp, bool top )
-{
- if( top )
- {
- TQFileInfo inf( dirname );
- if( inf.lastModified() > stamp )
- {
- kdDebug( 7021 ) << "timestamp changed:" << dirname << endl;
- return false;
- }
- }
- TQDir dir( dirname );
- const TQFileInfoList *list = dir.entryInfoList( TQDir::DefaultFilter, TQDir::Unsorted );
- if (!list)
- return true;
-
- for( TQFileInfoListIterator it( *list );
- it.current() != NULL;
- ++it )
- {
- TQFileInfo* fi = it.current();
- if( fi->fileName() == "." || fi->fileName() == ".." )
- continue;
- if( fi->lastModified() > stamp )
- {
- kdDebug( 7201 ) << "timestamp changed:" << fi->filePath() << endl;
- return false;
- }
- if( fi->isDir() && !checkDirTimestamps( fi->filePath(), stamp, false ))
- return false;
- }
- return true;
-}
-
-// check times of last modification of all files on which tdesycoca depens,
-// and also their directories
-// if all of them all older than the timestamp in file tdesycocastamp, this
-// means that there's no need to rebuild tdesycoca
-bool KBuildSycoca::checkTimestamps( TQ_UINT32 timestamp, const TQStringList &dirs )
-{
- kdDebug( 7021 ) << "checking file timestamps" << endl;
- TQDateTime stamp;
- stamp.setTime_t( timestamp );
- for( TQStringList::ConstIterator it = dirs.begin();
- it != dirs.end();
- ++it )
- {
- if( !checkDirTimestamps( *it, stamp, true ))
- return false;
- }
- kdDebug( 7021 ) << "timestamps check ok" << endl;
- return true;
-}
-
-TQStringList KBuildSycoca::existingResourceDirs()
-{
- static TQStringList* dirs = NULL;
- if( dirs != NULL )
- return *dirs;
- dirs = new TQStringList;
- g_allResourceDirs = new TQStringList;
- // these are all resources cached by tdesycoca
- TQStringList resources;
- resources += KBuildServiceTypeFactory::resourceTypes();
- resources += KBuildServiceGroupFactory::resourceTypes();
- resources += KBuildServiceFactory::resourceTypes();
- resources += KBuildImageIOFactory::resourceTypes();
- resources += KBuildProtocolInfoFactory::resourceTypes();
- while( !resources.empty())
- {
- TQString res = resources.front();
- *dirs += TDEGlobal::dirs()->resourceDirs( res.latin1());
- resources.remove( res ); // remove this 'res' and all its duplicates
- }
-
- *g_allResourceDirs = *dirs;
-
- for( TQStringList::Iterator it = dirs->begin();
- it != dirs->end(); )
- {
- TQFileInfo inf( *it );
- if( !inf.exists() || !inf.isReadable() )
- it = dirs->remove( it );
- else
- ++it;
- }
- return *dirs;
-}
-
-static KCmdLineOptions options[] = {
- { "nosignal", I18N_NOOP("Do not signal applications to update"), 0 },
- { "noincremental", I18N_NOOP("Disable incremental update, re-read everything"), 0 },
- { "checkstamps", I18N_NOOP("Check file timestamps"), 0 },
- { "nocheckfiles", I18N_NOOP("Disable checking files (dangerous)"), 0 },
- { "global", I18N_NOOP("Create global database"), 0 },
- { "menutest", I18N_NOOP("Perform menu generation test run only"), 0 },
- { "track <menu-id>", I18N_NOOP("Track menu id for debug purposes"), 0 },
-#ifdef KBUILDSYCOCA_GUI
- { "silent", I18N_NOOP("Silent - work without windows and stderr"), 0 },
- { "showprogress", I18N_NOOP("Show progress information (even if 'silent' mode is on)"), 0 },
-#endif
- KCmdLineLastOption
-};
-
-static const char appName[] = "kbuildsycoca";
-static const char appVersion[] = "1.1";
-
-class WaitForSignal : public QObject
-{
-public:
- ~WaitForSignal() { kapp->eventLoop()->exitLoop(); }
-};
-
-extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
-{
- KLocale::setMainCatalogue("tdelibs");
- TDEAboutData d(appName, I18N_NOOP("KBuildSycoca"), appVersion,
- I18N_NOOP("Rebuilds the system configuration cache."),
- TDEAboutData::License_GPL, "(c) 1999-2002 KDE Developers");
- d.addAuthor("David Faure", I18N_NOOP("Author"), "faure@kde.org");
- d.addAuthor("Waldo Bastian", I18N_NOOP("Author"), "bastian@kde.org");
-
- TDECmdLineArgs::init(argc, argv, &d);
- TDECmdLineArgs::addCmdLineOptions(options);
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
- bGlobalDatabase = args->isSet("global");
- bMenuTest = args->isSet("menutest");
-
- if (bGlobalDatabase)
- {
- setenv("TDEHOME", "-", 1);
- setenv("TDEROOTHOME", "-", 1);
- }
-
- TDEApplication::disableAutoDcopRegistration();
-#ifdef KBUILDSYCOCA_GUI
- TDEApplication k;
-#else
- TDEApplication k(false, false);
-#endif
- k.disableSessionManagement();
-
-#ifdef KBUILDSYCOCA_GUI
- silent = args->isSet("silent");
- showprogress = args->isSet("showprogress");
- TQLabel progress( TQString("<p><br><nobr> %1 </nobr><br>").arg( i18n("Reloading TDE configuration, please wait...") ), 0, "", Qt::WType_Dialog | Qt::WStyle_DialogBorder | Qt::WStyle_Customize| Qt::WStyle_Title );
- TQString capt = i18n("TDE Configuration Manager");
- if (!silent) {
- if (KMessageBox::No == KMessageBox::questionYesNo(0, i18n("Do you want to reload TDE configuration?"), capt, i18n("Reload"), i18n("Do Not Reload")))
- return 0;
- }
- if (!silent || showprogress) {
- progress.setCaption( capt );
- progress.show();
- }
-#endif
-
- KCrash::setCrashHandler(KCrash::defaultCrashHandler);
- KCrash::setEmergencySaveFunction(crashHandler);
- KCrash::setApplicationName(TQString(appName));
-
- // this program is in tdelibs so it uses tdelibs as catalog
- KLocale::setMainCatalogue("tdelibs");
- // force generating of KLocale object. if not, the database will get
- // be translated
- TDEGlobal::locale();
- TDEGlobal::dirs()->addResourceType("app-reg", "share/application-registry" );
-
- DCOPClient *dcopClient = new DCOPClient();
-
- while(true)
- {
- TQCString registeredName = dcopClient->registerAs(appName, false);
- if (registeredName.isEmpty())
- {
- fprintf(stderr, "[kbuildsycoca] Warning: %s is unable to register with DCOP.\n", appName);
- break;
- }
- else if (registeredName == appName)
- {
- break; // Go
- }
- fprintf(stderr, "[kbuildsycoca] Waiting for already running %s to finish.\n", appName);
-
- dcopClient->setNotifications( true );
- while (dcopClient->isApplicationRegistered(appName))
- {
- WaitForSignal *obj = new WaitForSignal;
- obj->connect(dcopClient, TQT_SIGNAL(applicationRemoved(const TQCString &)),
- TQT_SLOT(deleteLater()));
- kapp->eventLoop()->enterLoop();
- }
- dcopClient->setNotifications( false );
- }
- fprintf(stderr, "[kbuildsycoca] %s running...\n", appName);
-
- bool checkfiles = bGlobalDatabase || args->isSet("checkfiles");
-
- bool incremental = !bGlobalDatabase && args->isSet("incremental") && checkfiles;
- if (incremental || !checkfiles)
- {
- KSycoca::self()->disableAutoRebuild(); // Prevent deadlock
- TQString current_language = TDEGlobal::locale()->language();
- TQString tdesycoca_language = KSycoca::self()->language();
- TQ_UINT32 current_update_sig = TDEGlobal::dirs()->calcResourceHash("services", "update_tdesycoca", true);
- TQ_UINT32 tdesycoca_update_sig = KSycoca::self()->updateSignature();
-
- if ((current_update_sig != tdesycoca_update_sig) ||
- (current_language != tdesycoca_language) ||
- (KSycoca::self()->timeStamp() == 0))
- {
- incremental = false;
- checkfiles = true;
- delete KSycoca::self();
- }
- }
-
- g_changeList = new TQStringList;
-
- bool checkstamps = incremental && args->isSet("checkstamps") && checkfiles;
- TQ_UINT32 filestamp = 0;
- TQStringList oldresourcedirs;
- if( checkstamps && incremental )
- {
- TQString path = sycocaPath()+"stamp";
- TQCString qPath = TQFile::encodeName(path);
- cSycocaPath = qPath.data(); // Delete timestamps on crash
- TQFile tdesycocastamp(path);
- if( tdesycocastamp.open( IO_ReadOnly ))
- {
- TQDataStream str( &tdesycocastamp );
- if (!str.atEnd())
- str >> filestamp;
- if (!str.atEnd())
- {
- str >> oldresourcedirs;
- if( oldresourcedirs != KBuildSycoca::existingResourceDirs())
- checkstamps = false;
- }
- else
- {
- checkstamps = false;
- }
- if (!str.atEnd())
- {
- TQStringList extraResourceDirs;
- str >> extraResourceDirs;
- oldresourcedirs += extraResourceDirs;
- }
- }
- else
- {
- checkstamps = false;
- }
- cSycocaPath = 0;
- }
-
- newTimestamp = (TQ_UINT32) time(0);
-
- if( checkfiles && ( !checkstamps || !KBuildSycoca::checkTimestamps( filestamp, oldresourcedirs )))
- {
- TQCString qSycocaPath = TQFile::encodeName(sycocaPath());
- cSycocaPath = qSycocaPath.data();
-
- g_allEntries = 0;
- g_ctimeDict = 0;
- if (incremental)
- {
- tqWarning("[kbuildsycoca] Reusing existing tdesycoca.");
- KSycoca *oldSycoca = KSycoca::self();
- KSycocaFactoryList *factories = new KSycocaFactoryList;
- g_allEntries = new KSycocaEntryListList;
- g_ctimeDict = new TQDict<TQ_UINT32>(523);
-
- // Must be in same order as in KBuildSycoca::recreate()!
- factories->append( new KServiceTypeFactory );
- factories->append( new KServiceGroupFactory );
- factories->append( new KServiceFactory );
- factories->append( new KImageIOFactory );
- factories->append( new KProtocolInfoFactory );
-
- // For each factory
- for (KSycocaFactory *factory = factories->first();
- factory;
- factory = factories->next() )
- {
- KSycocaEntry::List list;
- list = factory->allEntries();
- g_allEntries->append( list );
- }
- delete factories; factories = 0;
- KCTimeInfo *ctimeInfo = new KCTimeInfo;
- ctimeInfo->fillCTimeDict(*g_ctimeDict);
- delete oldSycoca;
- }
- cSycocaPath = 0;
-
- KBuildSycoca *sycoca= new KBuildSycoca; // Build data base
- if (args->isSet("track"))
- sycoca->setTrackId(TQString::fromLocal8Bit(args->getOption("track")));
- if (!sycoca->recreate()) {
-#ifdef KBUILDSYCOCA_GUI
- if (!silent || showprogress)
- progress.close();
-#endif
- return -1;
- }
-
- if (bGlobalDatabase)
- {
- // These directories may have been created with 0700 permission
- // better delete them if they are empty
- TQString applnkDir = TDEGlobal::dirs()->saveLocation("apps", TQString::null, false);
- ::rmdir(TQFile::encodeName(applnkDir));
- TQString servicetypesDir = TDEGlobal::dirs()->saveLocation("servicetypes", TQString::null, false);
- ::rmdir(TQFile::encodeName(servicetypesDir));
- }
- }
-
- if (!bGlobalDatabase)
- {
- // Recreate compatibility symlink
- TQString oldPath = oldSycocaPath();
- if (!oldPath.isEmpty())
- {
- KTempFile tmp;
- if (tmp.status() == 0)
- {
- TQString tmpFile = tmp.name();
- tmp.unlink();
- symlink(TQFile::encodeName(sycocaPath()), TQFile::encodeName(tmpFile));
- rename(TQFile::encodeName(tmpFile), TQFile::encodeName(oldPath));
- }
- }
- }
-
- if (args->isSet("signal"))
- {
- // Notify ALL applications that have a tdesycoca object, using a broadcast
- TQByteArray data;
- TQDataStream stream(data, IO_WriteOnly);
- stream << *g_changeList;
- dcopClient->send( "*", "tdesycoca", "notifyDatabaseChanged(TQStringList)", data );
- }
-
-#ifdef KBUILDSYCOCA_GUI
- if (!silent) {
- progress.close();
- KMessageBox::information(0, i18n("[kbuildsycoca] Configuration information reloaded successfully."), capt);
- }
-#endif
- return 0;
-}
-
-#include "kbuildsycoca.moc"
diff --git a/kded/kbuildsycoca.h b/kded/kbuildsycoca.h
deleted file mode 100644
index 443f5b120..000000000
--- a/kded/kbuildsycoca.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/* This file is part of the KDE libraries
- * Copyright (C) 1999 David Faure <faure@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-#ifndef __kbuildsycoca_h__
-#define __kbuildsycoca_h__
-
-#include <sys/stat.h>
-
-#include <tqobject.h>
-#include <tqstring.h>
-#include <tqdict.h>
-
-#include <kservice.h>
-#include <tdesycoca.h>
-#include <tdesycocatype.h>
-#include <tdesycocaentry.h>
-#include <kservicegroup.h>
-
-#include "vfolder_menu.h"
-
-class TQDataStream;
-
-// No need for this in libkio - apps only get readonly access
-class KBuildSycoca : public KSycoca
-{
- Q_OBJECT
-public:
- KBuildSycoca();
- virtual ~KBuildSycoca();
-
- /**
- * Recreate the database file
- */
- bool recreate();
-
- static bool checkTimestamps( TQ_UINT32 timestamp, const TQStringList &dirs );
-
- static TQStringList existingResourceDirs();
-
- void setTrackId(const TQString &id) { m_trackId = id; }
-
-protected slots:
- void slotCreateEntry(const TQString &file, KService **entry);
-
-protected:
-
- /**
- * Look up gnome mimetypes.
- */
- void processGnomeVfs();
-
- /**
- * Add single entry to the sycoca database.
- * Either from a previous database or regenerated from file.
- */
- KSycocaEntry *createEntry(const TQString &file, bool addToFactory);
-
- /**
- * Convert a VFolderMenu::SubMenu to KServiceGroups.
- */
- void createMenu(TQString caption, TQString name, VFolderMenu::SubMenu *menu);
-
- /**
- * Build the whole system cache, from .desktop files
- */
- bool build();
-
- /**
- * Save the tdesycoca file
- */
- void save();
-
- /**
- * Clear the factories
- */
- void clear();
-
- static bool checkDirTimestamps( const TQString& dir, const TQDateTime& stamp, bool top );
-
- /**
- * @internal
- * @return true if building (i.e. if a KBuildSycoca);
- */
- virtual bool isBuilding() { return true; }
-
- TQStringList m_allResourceDirs;
- TQString m_trackId;
-};
-
-#endif
diff --git a/kded/kde-menu.cpp b/kded/kde-menu.cpp
deleted file mode 100644
index 5c1a38b4d..000000000
--- a/kded/kde-menu.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/* This file is part of the KDE libraries
- * Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#include <stdlib.h>
-
-#include <tqfile.h>
-
-#include <dcopclient.h>
-#include <dcopref.h>
-
-#include "kaboutdata.h"
-#include "kapplication.h"
-#include "kcmdlineargs.h"
-#include "kglobal.h"
-#include "klocale.h"
-#include "kservice.h"
-#include "kservicegroup.h"
-#include "kstandarddirs.h"
-
-static KCmdLineOptions options[] = {
- { "utf8", I18N_NOOP("Output data in UTF-8 instead of local encoding"), 0 },
- { "print-menu-id", I18N_NOOP("Print menu-id of the menu that contains\nthe application"), 0 },
- { "print-menu-name", I18N_NOOP("Print menu name (caption) of the menu that\ncontains the application"), 0 },
- { "highlight", I18N_NOOP("Highlight the entry in the menu"), 0 },
- { "nocache-update", I18N_NOOP("Do not check if sycoca database is up to date"), 0 },
- { "+<application-id>", I18N_NOOP("The id of the menu entry to locate"), 0 },
- KCmdLineLastOption
-};
-
-static const char appName[] = "kde-menu";
-static const char appVersion[] = "1.0";
-static bool utf8;
-
-static bool bPrintMenuId;
-static bool bPrintMenuName;
-static bool bHighlight;
-
-static void result(const TQString &txt)
-{
- if (utf8)
- puts( txt.utf8() );
- else
- puts( txt.local8Bit() );
-}
-
-static void error(int exitCode, const TQString &txt)
-{
- tqWarning("kde-menu: %s", txt.local8Bit().data());
- exit(exitCode);
-}
-
-static void findMenuEntry(KServiceGroup::Ptr parent, const TQString &name, const TQString &menuId)
-{
- KServiceGroup::List list = parent->entries(true, true, false);
- KServiceGroup::List::ConstIterator it = list.begin();
- for (; it != list.end(); ++it)
- {
- KSycocaEntry * e = *it;
-
- if (e->isType(KST_KServiceGroup))
- {
- KServiceGroup::Ptr g(static_cast<KServiceGroup *>(e));
-
- findMenuEntry(g, name.isEmpty() ? g->caption() : name+"/"+g->caption(), menuId);
- }
- else if (e->isType(KST_KService))
- {
- KService::Ptr s(static_cast<KService *>(e));
- if (s->menuId() == menuId)
- {
- if (bPrintMenuId)
- {
- result(parent->relPath());
- }
- if (bPrintMenuName)
- {
- result(name);
- }
- if (bHighlight)
- {
- DCOPRef kicker( "kicker", "kicker" );
- bool result = kicker.call( "highlightMenuItem", menuId );
- if (!result)
- error(3, TQString(i18n("Menu item '%1' could not be highlighted.").arg(menuId)).local8Bit());
- }
- exit(0);
- }
- }
- }
-}
-
-
-int main(int argc, char **argv)
-{
- KLocale::setMainCatalogue("tdelibs");
- const char *description = I18N_NOOP("TDE Menu query tool.\n"
- "This tool can be used to find in which menu a specific application is shown.\n"
- "The --highlight option can be used to visually indicate to the user where\n"
- "in the TDE menu a specific application is located.");
-
- TDEAboutData d(appName, I18N_NOOP("kde-menu"), appVersion,
- description,
- TDEAboutData::License_GPL, "(c) 2003 Waldo Bastian");
- d.addAuthor("Waldo Bastian", I18N_NOOP("Author"), "bastian@kde.org");
-
- TDECmdLineArgs::init(argc, argv, &d);
- TDECmdLineArgs::addCmdLineOptions(options);
-
-// TDEApplication k(false, false);
- TDEApplication k(false);
- k.disableSessionManagement();
-
- // this program is in tdelibs so it uses tdelibs as catalog
- KLocale::setMainCatalogue("tdelibs");
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
- if (args->count() != 1)
- TDECmdLineArgs::usage(i18n("You must specify an application-id such as 'tde-konsole.desktop'"));
-
- utf8 = args->isSet("utf8");
-
- bPrintMenuId = args->isSet("print-menu-id");
- bPrintMenuName = args->isSet("print-menu-name");
- bHighlight = args->isSet("highlight");
-
- if (!bPrintMenuId && !bPrintMenuName && !bHighlight)
- TDECmdLineArgs::usage(i18n("You must specify at least one of --print-menu-id, --print-menu-name or --highlight"));
-
- if (args->isSet("cache-update"))
- {
- TQStringList args;
- args.append("--incremental");
- args.append("--checkstamps");
- TQString command = "kbuildsycoca";
- TQCString _launcher = TDEApplication::launcher();
- if (!DCOPRef(_launcher, _launcher).call("tdeinit_exec_wait", command, args).isValid())
- {
- tqWarning("Can't talk to klauncher!");
- command = TDEGlobal::dirs()->findExe(command);
- command += " " + args.join(" ");
- system(command.local8Bit());
- }
- }
-
- TQString menuId = TQFile::decodeName(args->arg(0));
- KService::Ptr s = KService::serviceByMenuId(menuId);
-
- if (!s)
- error(1, i18n("No menu item '%1'.").arg(menuId));
-
- findMenuEntry(KServiceGroup::root(), "", menuId);
-
- error(2, i18n("Menu item '%1' not found in menu.").arg(menuId));
- return 2;
-}
-
diff --git a/kded/kded.cpp b/kded/kded.cpp
index 11c46e064..b769fa508 100644
--- a/kded/kded.cpp
+++ b/kded/kded.cpp
@@ -45,7 +45,7 @@
#include <kdirwatch.h>
#include <kstandarddirs.h>
#include <kdatastream.h>
-#include <kio/global.h>
+#include <tdeio/global.h>
#include <kservicetype.h>
#ifdef Q_WS_X11
@@ -65,27 +65,27 @@ static void runBuildSycoca(TQObject *callBackObj=0, const char *callBackSlot=0)
if(checkStamps)
args.append("--checkstamps");
if(delayedCheck)
- args.append("--nocheckfiles");
+ args.append("--nochectdefiles");
else
checkStamps = false; // useful only during kded startup
if (callBackObj)
{
TQByteArray data;
TQDataStream dataStream( data, IO_WriteOnly );
- dataStream << TQString("kbuildsycoca") << args;
+ dataStream << TQString("tdebuildsycoca") << args;
TQCString _launcher = TDEApplication::launcher();
kapp->dcopClient()->callAsync(_launcher, _launcher, "tdeinit_exec_wait(TQString,TQStringList)", data, callBackObj, callBackSlot);
}
else
{
- TDEApplication::tdeinitExecWait( "kbuildsycoca", args );
+ TDEApplication::tdeinitExecWait( "tdebuildsycoca", args );
}
}
static void runKonfUpdate()
{
- TDEApplication::tdeinitExecWait( "kconf_update", TQStringList(), 0, 0, "0" /*no startup notification*/ );
+ TDEApplication::tdeinitExecWait( "tdeconf_update", TQStringList(), 0, 0, "0" /*no startup notification*/ );
}
static void runDontChangeHostname(const TQCString &oldName, const TQCString &newName)
@@ -97,7 +97,7 @@ static void runDontChangeHostname(const TQCString &oldName, const TQCString &new
}
Kded::Kded(bool checkUpdates, bool new_startup)
- : DCOPObject("kbuildsycoca"), DCOPObjectProxy(),
+ : DCOPObject("tdebuildsycoca"), DCOPObjectProxy(),
b_checkUpdates(checkUpdates),
m_needDelayedCheck(false),
m_newStartup( new_startup )
@@ -665,7 +665,7 @@ KUpdateD::KUpdateD()
TQObject::connect( m_pDirWatch, TQT_SIGNAL(dirty(const TQString&)),
this, TQT_SLOT(slotNewUpdateFile()));
- TQStringList dirs = TDEGlobal::dirs()->findDirs("data", "kconf_update");
+ TQStringList dirs = TDEGlobal::dirs()->findDirs("data", "tdeconf_update");
for( TQStringList::ConstIterator it = dirs.begin();
it != dirs.end();
++it )
@@ -957,7 +957,7 @@ extern "C" KDE_EXPORT int kdemain(int argc, char *argv[])
// During startup kdesktop waits for KDED to finish.
// Send a notifyDatabaseChanged signal even if the database hasn't
// changed.
- // If the database changed, kbuildsycoca's signal didn't go anywhere
+ // If the database changed, tdebuildsycoca's signal didn't go anywhere
// anyway, because it was too early, so let's send this signal
// unconditionnally (David)
TQByteArray data;
diff --git a/kded/kded.h b/kded/kded.h
index 93aac0ab6..a4968624a 100644
--- a/kded/kded.h
+++ b/kded/kded.h
@@ -37,7 +37,7 @@
class KDirWatch;
class KService;
-// No need for this in libkio - apps only get readonly access
+// No need for this in libtdeio - apps only get readonly access
class Kded : public TQObject, public DCOPObject, public DCOPObjectProxy
{
Q_OBJECT
diff --git a/kded/kdedmodule.cpp b/kded/kdedmodule.cpp
index ca28a5c62..6371b2534 100644
--- a/kded/kdedmodule.cpp
+++ b/kded/kdedmodule.cpp
@@ -24,7 +24,7 @@
#include "kded.h"
#include "kdedmodule.h"
-#include "kconfigdata.h"
+#include "tdeconfigdata.h"
typedef TQMap<KEntryKey, KSharedPtr<KShared> > KDEDObjectMap;
diff --git a/kded/tde-menu.cpp b/kded/tde-menu.cpp
new file mode 100644
index 000000000..6a8721915
--- /dev/null
+++ b/kded/tde-menu.cpp
@@ -0,0 +1,171 @@
+/* This file is part of the KDE libraries
+ * Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#include <stdlib.h>
+
+#include <tqfile.h>
+
+#include <dcopclient.h>
+#include <dcopref.h>
+
+#include "kaboutdata.h"
+#include "kapplication.h"
+#include "kcmdlineargs.h"
+#include "kglobal.h"
+#include "klocale.h"
+#include "kservice.h"
+#include "kservicegroup.h"
+#include "kstandarddirs.h"
+
+static KCmdLineOptions options[] = {
+ { "utf8", I18N_NOOP("Output data in UTF-8 instead of local encoding"), 0 },
+ { "print-menu-id", I18N_NOOP("Print menu-id of the menu that contains\nthe application"), 0 },
+ { "print-menu-name", I18N_NOOP("Print menu name (caption) of the menu that\ncontains the application"), 0 },
+ { "highlight", I18N_NOOP("Highlight the entry in the menu"), 0 },
+ { "nocache-update", I18N_NOOP("Do not check if sycoca database is up to date"), 0 },
+ { "+<application-id>", I18N_NOOP("The id of the menu entry to locate"), 0 },
+ KCmdLineLastOption
+};
+
+static const char appName[] = "tde-menu";
+static const char appVersion[] = "1.0";
+static bool utf8;
+
+static bool bPrintMenuId;
+static bool bPrintMenuName;
+static bool bHighlight;
+
+static void result(const TQString &txt)
+{
+ if (utf8)
+ puts( txt.utf8() );
+ else
+ puts( txt.local8Bit() );
+}
+
+static void error(int exitCode, const TQString &txt)
+{
+ tqWarning("tde-menu: %s", txt.local8Bit().data());
+ exit(exitCode);
+}
+
+static void findMenuEntry(KServiceGroup::Ptr parent, const TQString &name, const TQString &menuId)
+{
+ KServiceGroup::List list = parent->entries(true, true, false);
+ KServiceGroup::List::ConstIterator it = list.begin();
+ for (; it != list.end(); ++it)
+ {
+ KSycocaEntry * e = *it;
+
+ if (e->isType(KST_KServiceGroup))
+ {
+ KServiceGroup::Ptr g(static_cast<KServiceGroup *>(e));
+
+ findMenuEntry(g, name.isEmpty() ? g->caption() : name+"/"+g->caption(), menuId);
+ }
+ else if (e->isType(KST_KService))
+ {
+ KService::Ptr s(static_cast<KService *>(e));
+ if (s->menuId() == menuId)
+ {
+ if (bPrintMenuId)
+ {
+ result(parent->relPath());
+ }
+ if (bPrintMenuName)
+ {
+ result(name);
+ }
+ if (bHighlight)
+ {
+ DCOPRef kicker( "kicker", "kicker" );
+ bool result = kicker.call( "highlightMenuItem", menuId );
+ if (!result)
+ error(3, TQString(i18n("Menu item '%1' could not be highlighted.").arg(menuId)).local8Bit());
+ }
+ exit(0);
+ }
+ }
+ }
+}
+
+
+int main(int argc, char **argv)
+{
+ KLocale::setMainCatalogue("tdelibs");
+ const char *description = I18N_NOOP("TDE Menu query tool.\n"
+ "This tool can be used to find in which menu a specific application is shown.\n"
+ "The --highlight option can be used to visually indicate to the user where\n"
+ "in the TDE menu a specific application is located.");
+
+ TDEAboutData d(appName, I18N_NOOP("tde-menu"), appVersion,
+ description,
+ TDEAboutData::License_GPL, "(c) 2003 Waldo Bastian");
+ d.addAuthor("Waldo Bastian", I18N_NOOP("Author"), "bastian@kde.org");
+
+ TDECmdLineArgs::init(argc, argv, &d);
+ TDECmdLineArgs::addCmdLineOptions(options);
+
+// TDEApplication k(false, false);
+ TDEApplication k(false);
+ k.disableSessionManagement();
+
+ // this program is in tdelibs so it uses tdelibs as catalog
+ KLocale::setMainCatalogue("tdelibs");
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+ if (args->count() != 1)
+ TDECmdLineArgs::usage(i18n("You must specify an application-id such as 'tde-konsole.desktop'"));
+
+ utf8 = args->isSet("utf8");
+
+ bPrintMenuId = args->isSet("print-menu-id");
+ bPrintMenuName = args->isSet("print-menu-name");
+ bHighlight = args->isSet("highlight");
+
+ if (!bPrintMenuId && !bPrintMenuName && !bHighlight)
+ TDECmdLineArgs::usage(i18n("You must specify at least one of --print-menu-id, --print-menu-name or --highlight"));
+
+ if (args->isSet("cache-update"))
+ {
+ TQStringList args;
+ args.append("--incremental");
+ args.append("--checkstamps");
+ TQString command = "tdebuildsycoca";
+ TQCString _launcher = TDEApplication::launcher();
+ if (!DCOPRef(_launcher, _launcher).call("tdeinit_exec_wait", command, args).isValid())
+ {
+ tqWarning("Can't talk to tdelauncher!");
+ command = TDEGlobal::dirs()->findExe(command);
+ command += " " + args.join(" ");
+ system(command.local8Bit());
+ }
+ }
+
+ TQString menuId = TQFile::decodeName(args->arg(0));
+ KService::Ptr s = KService::serviceByMenuId(menuId);
+
+ if (!s)
+ error(1, i18n("No menu item '%1'.").arg(menuId));
+
+ findMenuEntry(KServiceGroup::root(), "", menuId);
+
+ error(2, i18n("Menu item '%1' not found in menu.").arg(menuId));
+ return 2;
+}
+
diff --git a/kded/tdebuildsycoca.cpp b/kded/tdebuildsycoca.cpp
new file mode 100644
index 000000000..47b7a9bf4
--- /dev/null
+++ b/kded/tdebuildsycoca.cpp
@@ -0,0 +1,959 @@
+/* This file is part of the KDE libraries
+ * Copyright (C) 1999 David Faure <faure@kde.org>
+ * Copyright (C) 2002-2003 Waldo Bastian <bastian@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#include <tqdir.h>
+#include <tqeventloop.h>
+#include <config.h>
+
+#include "tdebuildsycoca.h"
+#include "kresourcelist.h"
+#include "vfolder_menu.h"
+
+#include <kservice.h>
+#include <kmimetype.h>
+#include <kbuildservicetypefactory.h>
+#include <kbuildservicefactory.h>
+#include <kbuildservicegroupfactory.h>
+#include <kbuildimageiofactory.h>
+#include <kbuildprotocolinfofactory.h>
+#include <kctimefactory.h>
+#include <kdatastream.h>
+
+#include <tqdatastream.h>
+#include <tqfile.h>
+#include <tqtimer.h>
+
+#include <assert.h>
+#include <kapplication.h>
+#include <dcopclient.h>
+#include <kglobal.h>
+#include <kdebug.h>
+#include <kdirwatch.h>
+#include <kstandarddirs.h>
+#include <ksavefile.h>
+#include <klocale.h>
+#include <kaboutdata.h>
+#include <kcmdlineargs.h>
+#include <kcrash.h>
+
+#ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build
+ // GUI version of tdebuildsycoca, so-called "tdebuildsycocaw".
+# include <tqlabel.h>
+# include <kmessagebox.h>
+ bool silent;
+ bool showprogress;
+#endif
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <time.h>
+#include <memory> // auto_ptr
+
+typedef TQDict<KSycocaEntry> KBSEntryDict;
+typedef TQValueList<KSycocaEntry::List> KSycocaEntryListList;
+
+static TQ_UINT32 newTimestamp = 0;
+
+static KBuildServiceFactory *g_bsf = 0;
+static KBuildServiceGroupFactory *g_bsgf = 0;
+static KSycocaFactory *g_factory = 0;
+static KCTimeInfo *g_ctimeInfo = 0;
+static TQDict<TQ_UINT32> *g_ctimeDict = 0;
+static const char *g_resource = 0;
+static KBSEntryDict *g_entryDict = 0;
+static KBSEntryDict *g_serviceGroupEntryDict = 0;
+static KSycocaEntryListList *g_allEntries = 0;
+static TQStringList *g_changeList = 0;
+static TQStringList *g_allResourceDirs = 0;
+static bool g_changed = false;
+static KSycocaEntry::List g_tempStorage;
+static VFolderMenu *g_vfolder = 0;
+
+static const char *cSycocaPath = 0;
+
+static bool bGlobalDatabase = false;
+static bool bMenuTest = false;
+
+void crashHandler(int)
+{
+ // If we crash while reading sycoca, we delete the database
+ // in an attempt to recover.
+ if (cSycocaPath)
+ unlink(cSycocaPath);
+}
+
+static TQString sycocaPath()
+{
+ TQString path;
+
+ if (bGlobalDatabase)
+ {
+ path = TDEGlobal::dirs()->saveLocation("services")+"tdesycoca";
+ }
+ else
+ {
+ TQCString tdesycoca_env = getenv("TDESYCOCA");
+ if (tdesycoca_env.isEmpty())
+ path = TDEGlobal::dirs()->saveLocation("cache")+"tdesycoca";
+ else
+ path = TQFile::decodeName(tdesycoca_env);
+ }
+
+ return path;
+}
+
+static TQString oldSycocaPath()
+{
+ TQCString tdesycoca_env = getenv("TDESYCOCA");
+ if (tdesycoca_env.isEmpty())
+ return TDEGlobal::dirs()->saveLocation("tmp")+"tdesycoca";
+
+ return TQString::null;
+}
+
+KBuildSycoca::KBuildSycoca()
+ : KSycoca( true )
+{
+}
+
+KBuildSycoca::~KBuildSycoca()
+{
+
+}
+
+void KBuildSycoca::processGnomeVfs()
+{
+ TQString file = locate("app-reg", "gnome-vfs.applications");
+ if (file.isEmpty())
+ {
+// kdDebug(7021) << "gnome-vfs.applications not found." << endl;
+ return;
+ }
+
+ TQString app;
+
+ char line[1024*64];
+
+ FILE *f = fopen(TQFile::encodeName(file), "r");
+ while (!feof(f))
+ {
+ if (!fgets(line, sizeof(line)-1, f))
+ {
+ break;
+ }
+
+ if (line[0] != '\t')
+ {
+ app = TQString::fromLatin1(line);
+ app.truncate(app.length()-1);
+ }
+ else if (strncmp(line+1, "mime_types=", 11) == 0)
+ {
+ TQString mimetypes = TQString::fromLatin1(line+12);
+ mimetypes.truncate(mimetypes.length()-1);
+ mimetypes.replace(TQRegExp("\\*"), "all");
+ KService *s = g_bsf->findServiceByName(app);
+ if (!s)
+ continue;
+
+ TQStringList &serviceTypes = s->accessServiceTypes();
+ if (serviceTypes.count() <= 1)
+ {
+ serviceTypes += TQStringList::split(',', mimetypes);
+// kdDebug(7021) << "Adding gnome mimetypes for '" << app << "'.\n";
+// kdDebug(7021) << "ServiceTypes=" << s->serviceTypes().join(":") << endl;
+ }
+ }
+ }
+ fclose( f );
+}
+
+KSycocaEntry *KBuildSycoca::createEntry(const TQString &file, bool addToFactory)
+{
+ TQ_UINT32 timeStamp = g_ctimeInfo->ctime(file);
+ if (!timeStamp)
+ {
+ timeStamp = TDEGlobal::dirs()->calcResourceHash( g_resource, file, true);
+ }
+ KSycocaEntry* entry = 0;
+ if (g_allEntries)
+ {
+ assert(g_ctimeDict);
+ TQ_UINT32 *timeP = (*g_ctimeDict)[file];
+ TQ_UINT32 oldTimestamp = timeP ? *timeP : 0;
+
+ if (timeStamp && (timeStamp == oldTimestamp))
+ {
+ // Re-use old entry
+ if (g_factory == g_bsgf) // Strip .directory from service-group entries
+ {
+ entry = g_entryDict->find(file.left(file.length()-10));
+ }
+ else if (g_factory == g_bsf)
+ {
+ entry = g_entryDict->find(file);
+ }
+ else
+ {
+ entry = g_entryDict->find(file);
+ }
+ // remove from g_ctimeDict; if g_ctimeDict is not empty
+ // after all files have been processed, it means
+ // some files were removed since last time
+ g_ctimeDict->remove( file );
+ }
+ else if (oldTimestamp)
+ {
+ g_changed = true;
+ kdDebug(7021) << "modified: " << file << endl;
+ }
+ else
+ {
+ g_changed = true;
+ kdDebug(7021) << "new: " << file << endl;
+ }
+ }
+ g_ctimeInfo->addCTime(file, timeStamp );
+ if (!entry)
+ {
+ // Create a new entry
+ entry = g_factory->createEntry( file, g_resource );
+ }
+ if ( entry && entry->isValid() )
+ {
+ if (addToFactory)
+ g_factory->addEntry( entry, g_resource );
+ else
+ g_tempStorage.append(entry);
+ return entry;
+ }
+ return 0;
+}
+
+void KBuildSycoca::slotCreateEntry(const TQString &file, KService **service)
+{
+ KSycocaEntry *entry = createEntry(file, false);
+ *service = dynamic_cast<KService *>(entry);
+}
+
+// returns false if the database is up to date
+bool KBuildSycoca::build()
+{
+ typedef TQPtrList<KBSEntryDict> KBSEntryDictList;
+ KBSEntryDictList *entryDictList = 0;
+ KBSEntryDict *serviceEntryDict = 0;
+
+ entryDictList = new KBSEntryDictList();
+ // Convert for each factory the entryList to a Dict.
+ int i = 0;
+ // For each factory
+ for (KSycocaFactory *factory = m_lstFactories->first();
+ factory;
+ factory = m_lstFactories->next() )
+ {
+ KBSEntryDict *entryDict = new KBSEntryDict();
+ if (g_allEntries)
+ {
+ KSycocaEntry::List list = (*g_allEntries)[i++];
+ for( KSycocaEntry::List::Iterator it = list.begin();
+ it != list.end();
+ ++it)
+ {
+ entryDict->insert( (*it)->entryPath(), static_cast<KSycocaEntry *>(*it));
+ }
+ }
+ if (factory == g_bsf)
+ serviceEntryDict = entryDict;
+ else if (factory == g_bsgf)
+ g_serviceGroupEntryDict = entryDict;
+ entryDictList->append(entryDict);
+ }
+
+ TQStringList allResources;
+ // For each factory
+ for (KSycocaFactory *factory = m_lstFactories->first();
+ factory;
+ factory = m_lstFactories->next() )
+ {
+ // For each resource the factory deals with
+ const KSycocaResourceList *list = factory->resourceList();
+ if (!list) continue;
+
+ for( KSycocaResourceList::ConstIterator it1 = list->begin();
+ it1 != list->end();
+ ++it1 )
+ {
+ KSycocaResource res = (*it1);
+ if (!allResources.contains(res.resource))
+ allResources.append(res.resource);
+ }
+ }
+
+ g_ctimeInfo = new KCTimeInfo(); // This is a build factory too, don't delete!!
+ bool uptodate = true;
+ // For all resources
+ for( TQStringList::ConstIterator it1 = allResources.begin();
+ it1 != allResources.end();
+ ++it1 )
+ {
+ g_changed = false;
+ g_resource = (*it1).ascii();
+
+ TQStringList relFiles;
+
+ (void) TDEGlobal::dirs()->findAllResources( g_resource,
+ TQString::null,
+ true, // Recursive!
+ true, // uniq
+ relFiles);
+
+
+ // Now find all factories that use this resource....
+ // For each factory
+ g_entryDict = entryDictList->first();
+ for (g_factory = m_lstFactories->first();
+ g_factory;
+ g_factory = m_lstFactories->next(),
+ g_entryDict = entryDictList->next() )
+ {
+ // For each resource the factory deals with
+ const KSycocaResourceList *list = g_factory->resourceList();
+ if (!list) continue;
+
+ for( KSycocaResourceList::ConstIterator it2 = list->begin();
+ it2 != list->end();
+ ++it2 )
+ {
+ KSycocaResource res = (*it2);
+ if (res.resource != (*it1)) continue;
+
+ // For each file in the resource
+ for( TQStringList::ConstIterator it3 = relFiles.begin();
+ it3 != relFiles.end();
+ ++it3 )
+ {
+ // Check if file matches filter
+ if ((*it3).endsWith(res.extension))
+ createEntry(*it3, true);
+ }
+ }
+ if ((g_factory == g_bsf) && (strcmp(g_resource, "services") == 0))
+ processGnomeVfs();
+ }
+ if (g_changed || !g_allEntries)
+ {
+ uptodate = false;
+ g_changeList->append(g_resource);
+ }
+ }
+
+ bool result = !uptodate || !g_ctimeDict->isEmpty();
+
+ if (result || bMenuTest)
+ {
+ g_resource = "apps";
+ g_factory = g_bsf;
+ g_entryDict = serviceEntryDict;
+ g_changed = false;
+
+ g_vfolder = new VFolderMenu;
+ if (!m_trackId.isEmpty())
+ g_vfolder->setTrackId(m_trackId);
+
+ connect(g_vfolder, TQT_SIGNAL(newService(const TQString &, KService **)),
+ this, TQT_SLOT(slotCreateEntry(const TQString &, KService **)));
+
+ VFolderMenu::SubMenu *kdeMenu = g_vfolder->parseMenu("applications.menu", true);
+
+ KServiceGroup *entry = g_bsgf->addNew("/", kdeMenu->directoryFile, 0, false);
+ entry->setLayoutInfo(kdeMenu->layoutList);
+ createMenu(TQString::null, TQString::null, kdeMenu);
+
+ KServiceGroup::Ptr g(entry);
+
+ (void) existingResourceDirs();
+ *g_allResourceDirs += g_vfolder->allDirectories();
+
+ disconnect(g_vfolder, TQT_SIGNAL(newService(const TQString &, KService **)),
+ this, TQT_SLOT(slotCreateEntry(const TQString &, KService **)));
+
+ if (g_changed || !g_allEntries)
+ {
+ uptodate = false;
+ g_changeList->append(g_resource);
+ }
+ if (bMenuTest)
+ return false;
+ }
+
+ return result;
+}
+
+void KBuildSycoca::createMenu(TQString caption, TQString name, VFolderMenu::SubMenu *menu)
+{
+ for(VFolderMenu::SubMenu *subMenu = menu->subMenus.first(); subMenu; subMenu = menu->subMenus.next())
+ {
+ TQString subName = name+subMenu->name+"/";
+
+ TQString directoryFile = subMenu->directoryFile;
+ if (directoryFile.isEmpty())
+ directoryFile = subName+".directory";
+ TQ_UINT32 timeStamp = g_ctimeInfo->ctime(directoryFile);
+ if (!timeStamp)
+ {
+ timeStamp = TDEGlobal::dirs()->calcResourceHash( g_resource, directoryFile, true);
+ }
+
+ KServiceGroup* entry = 0;
+ if (g_allEntries)
+ {
+ TQ_UINT32 *timeP = (*g_ctimeDict)[directoryFile];
+ TQ_UINT32 oldTimestamp = timeP ? *timeP : 0;
+
+ if (timeStamp && (timeStamp == oldTimestamp))
+ {
+ entry = dynamic_cast<KServiceGroup *> (g_serviceGroupEntryDict->find(subName));
+ if (entry && (entry->directoryEntryPath() != directoryFile))
+ entry = 0; // Can't reuse this one!
+ }
+ }
+ g_ctimeInfo->addCTime(directoryFile, timeStamp);
+
+ entry = g_bsgf->addNew(subName, subMenu->directoryFile, entry, subMenu->isDeleted);
+ entry->setLayoutInfo(subMenu->layoutList);
+ if (! (bMenuTest && entry->noDisplay()) )
+ createMenu(caption + entry->caption() + "/", subName, subMenu);
+ }
+ if (caption.isEmpty())
+ caption += "/";
+ if (name.isEmpty())
+ name += "/";
+ for(TQDictIterator<KService> it(menu->items); it.current(); ++it)
+ {
+ if (bMenuTest)
+ {
+ if (!menu->isDeleted && !it.current()->noDisplay())
+ printf("%s\t%s\t%s\n", caption.local8Bit().data(), it.current()->menuId().local8Bit().data(), locate("apps", it.current()->desktopEntryPath()).local8Bit().data());
+ }
+ else
+ {
+ g_bsf->addEntry( it.current(), g_resource );
+ g_bsgf->addNewEntryTo(name, it.current());
+ }
+ }
+}
+
+bool KBuildSycoca::recreate()
+{
+ TQString path(sycocaPath());
+#ifdef Q_WS_WIN
+ printf("tdebuildsycoca: path='%s'\n", (const char*)path);
+#endif
+
+ // KSaveFile first writes to a temp file.
+ // Upon close() it moves the stuff to the right place.
+ std::auto_ptr<KSaveFile> database( new KSaveFile(path) );
+ if (database->status() == EACCES && TQFile::exists(path))
+ {
+ TQFile::remove( path );
+ database.reset( new KSaveFile(path) ); // try again
+ }
+ if (database->status() != 0)
+ {
+ fprintf(stderr, "[tdebuildsycoca] ERROR creating database '%s'! %s\n", path.local8Bit().data(),strerror(database->status()));
+#ifdef KBUILDSYCOCA_GUI // KBUILDSYCOCA_GUI is used on win32 to build
+ // GUI version of tdebuildsycoca, so-called "tdebuildsycocaw".
+ if (!silent)
+ KMessageBox::error(0, i18n("Error creating database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n").arg(path.local8Bit().data()), i18n("KBuildSycoca"));
+#endif
+ return false;
+ }
+
+ m_str = database->dataStream();
+
+ kdDebug(7021) << "Recreating tdesycoca file (" << path << ", version " << KSycoca::version() << ")" << endl;
+
+ // It is very important to build the servicetype one first
+ // Both are registered in KSycoca, no need to keep the pointers
+ KSycocaFactory *stf = new KBuildServiceTypeFactory;
+ g_bsgf = new KBuildServiceGroupFactory();
+ g_bsf = new KBuildServiceFactory(stf, g_bsgf);
+ (void) new KBuildImageIOFactory();
+ (void) new KBuildProtocolInfoFactory();
+
+ if( build()) // Parse dirs
+ {
+ save(); // Save database
+ if (m_str->device()->status())
+ database->abort(); // Error
+ m_str = 0L;
+ if (!database->close())
+ {
+ fprintf(stderr, "[tdebuildsycoca] ERROR writing database '%s'!\n", database->name().local8Bit().data());
+ fprintf(stderr, "[tdebuildsycoca] Disk full?\n");
+#ifdef KBUILDSYCOCA_GUI
+ if (!silent)
+ KMessageBox::error(0, i18n("[tdebuildsycoca] Error writing database '%1'.\nCheck that the permissions are correct on the directory and the disk is not full.\n").arg(path.local8Bit().data()), i18n("KBuildSycoca"));
+#endif
+ return false;
+ }
+ }
+ else
+ {
+ m_str = 0L;
+ database->abort();
+ if (bMenuTest)
+ return true;
+ kdDebug(7021) << "Database is up to date" << endl;
+ }
+
+ if (!bGlobalDatabase)
+ {
+ // update the timestamp file
+ TQString stamppath = path + "stamp";
+ TQFile tdesycocastamp(stamppath);
+ tdesycocastamp.open( IO_WriteOnly );
+ TQDataStream str( &tdesycocastamp );
+ str << newTimestamp;
+ str << existingResourceDirs();
+ if (g_vfolder)
+ str << g_vfolder->allDirectories(); // Extra resource dirs
+ }
+ return true;
+}
+
+void KBuildSycoca::save()
+{
+ // Write header (#pass 1)
+ m_str->device()->at(0);
+
+ (*m_str) << (TQ_INT32) KSycoca::version();
+ KSycocaFactory * servicetypeFactory = 0L;
+ KSycocaFactory * serviceFactory = 0L;
+ for(KSycocaFactory *factory = m_lstFactories->first();
+ factory;
+ factory = m_lstFactories->next())
+ {
+ TQ_INT32 aId;
+ TQ_INT32 aOffset;
+ aId = factory->factoryId();
+ if ( aId == KST_KServiceTypeFactory )
+ servicetypeFactory = factory;
+ else if ( aId == KST_KServiceFactory )
+ serviceFactory = factory;
+ aOffset = factory->offset();
+ (*m_str) << aId;
+ (*m_str) << aOffset;
+ }
+ (*m_str) << (TQ_INT32) 0; // No more factories.
+ // Write TDEDIRS
+ (*m_str) << TDEGlobal::dirs()->kfsstnd_prefixes();
+ (*m_str) << newTimestamp;
+ (*m_str) << TDEGlobal::locale()->language();
+ (*m_str) << TDEGlobal::dirs()->calcResourceHash("services", "update_tdesycoca", true);
+ (*m_str) << (*g_allResourceDirs);
+
+ // Write factory data....
+ for(KSycocaFactory *factory = m_lstFactories->first();
+ factory;
+ factory = m_lstFactories->next())
+ {
+ factory->save(*m_str);
+ if (m_str->device()->status())
+ return; // error
+ }
+
+ int endOfData = m_str->device()->at();
+
+ // Write header (#pass 2)
+ m_str->device()->at(0);
+
+ (*m_str) << (TQ_INT32) KSycoca::version();
+ for(KSycocaFactory *factory = m_lstFactories->first();
+ factory;
+ factory = m_lstFactories->next())
+ {
+ TQ_INT32 aId;
+ TQ_INT32 aOffset;
+ aId = factory->factoryId();
+ aOffset = factory->offset();
+ (*m_str) << aId;
+ (*m_str) << aOffset;
+ }
+ (*m_str) << (TQ_INT32) 0; // No more factories.
+
+ // Jump to end of database
+ m_str->device()->at(endOfData);
+}
+
+bool KBuildSycoca::checkDirTimestamps( const TQString& dirname, const TQDateTime& stamp, bool top )
+{
+ if( top )
+ {
+ TQFileInfo inf( dirname );
+ if( inf.lastModified() > stamp )
+ {
+ kdDebug( 7021 ) << "timestamp changed:" << dirname << endl;
+ return false;
+ }
+ }
+ TQDir dir( dirname );
+ const TQFileInfoList *list = dir.entryInfoList( TQDir::DefaultFilter, TQDir::Unsorted );
+ if (!list)
+ return true;
+
+ for( TQFileInfoListIterator it( *list );
+ it.current() != NULL;
+ ++it )
+ {
+ TQFileInfo* fi = it.current();
+ if( fi->fileName() == "." || fi->fileName() == ".." )
+ continue;
+ if( fi->lastModified() > stamp )
+ {
+ kdDebug( 7201 ) << "timestamp changed:" << fi->filePath() << endl;
+ return false;
+ }
+ if( fi->isDir() && !checkDirTimestamps( fi->filePath(), stamp, false ))
+ return false;
+ }
+ return true;
+}
+
+// check times of last modification of all files on which tdesycoca depens,
+// and also their directories
+// if all of them all older than the timestamp in file tdesycocastamp, this
+// means that there's no need to rebuild tdesycoca
+bool KBuildSycoca::checkTimestamps( TQ_UINT32 timestamp, const TQStringList &dirs )
+{
+ kdDebug( 7021 ) << "checking file timestamps" << endl;
+ TQDateTime stamp;
+ stamp.setTime_t( timestamp );
+ for( TQStringList::ConstIterator it = dirs.begin();
+ it != dirs.end();
+ ++it )
+ {
+ if( !checkDirTimestamps( *it, stamp, true ))
+ return false;
+ }
+ kdDebug( 7021 ) << "timestamps check ok" << endl;
+ return true;
+}
+
+TQStringList KBuildSycoca::existingResourceDirs()
+{
+ static TQStringList* dirs = NULL;
+ if( dirs != NULL )
+ return *dirs;
+ dirs = new TQStringList;
+ g_allResourceDirs = new TQStringList;
+ // these are all resources cached by tdesycoca
+ TQStringList resources;
+ resources += KBuildServiceTypeFactory::resourceTypes();
+ resources += KBuildServiceGroupFactory::resourceTypes();
+ resources += KBuildServiceFactory::resourceTypes();
+ resources += KBuildImageIOFactory::resourceTypes();
+ resources += KBuildProtocolInfoFactory::resourceTypes();
+ while( !resources.empty())
+ {
+ TQString res = resources.front();
+ *dirs += TDEGlobal::dirs()->resourceDirs( res.latin1());
+ resources.remove( res ); // remove this 'res' and all its duplicates
+ }
+
+ *g_allResourceDirs = *dirs;
+
+ for( TQStringList::Iterator it = dirs->begin();
+ it != dirs->end(); )
+ {
+ TQFileInfo inf( *it );
+ if( !inf.exists() || !inf.isReadable() )
+ it = dirs->remove( it );
+ else
+ ++it;
+ }
+ return *dirs;
+}
+
+static KCmdLineOptions options[] = {
+ { "nosignal", I18N_NOOP("Do not signal applications to update"), 0 },
+ { "noincremental", I18N_NOOP("Disable incremental update, re-read everything"), 0 },
+ { "checkstamps", I18N_NOOP("Check file timestamps"), 0 },
+ { "nochectdefiles", I18N_NOOP("Disable checking files (dangerous)"), 0 },
+ { "global", I18N_NOOP("Create global database"), 0 },
+ { "menutest", I18N_NOOP("Perform menu generation test run only"), 0 },
+ { "track <menu-id>", I18N_NOOP("Track menu id for debug purposes"), 0 },
+#ifdef KBUILDSYCOCA_GUI
+ { "silent", I18N_NOOP("Silent - work without windows and stderr"), 0 },
+ { "showprogress", I18N_NOOP("Show progress information (even if 'silent' mode is on)"), 0 },
+#endif
+ KCmdLineLastOption
+};
+
+static const char appName[] = "tdebuildsycoca";
+static const char appVersion[] = "1.1";
+
+class WaitForSignal : public QObject
+{
+public:
+ ~WaitForSignal() { kapp->eventLoop()->exitLoop(); }
+};
+
+extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
+{
+ KLocale::setMainCatalogue("tdelibs");
+ TDEAboutData d(appName, I18N_NOOP("KBuildSycoca"), appVersion,
+ I18N_NOOP("Rebuilds the system configuration cache."),
+ TDEAboutData::License_GPL, "(c) 1999-2002 KDE Developers");
+ d.addAuthor("David Faure", I18N_NOOP("Author"), "faure@kde.org");
+ d.addAuthor("Waldo Bastian", I18N_NOOP("Author"), "bastian@kde.org");
+
+ TDECmdLineArgs::init(argc, argv, &d);
+ TDECmdLineArgs::addCmdLineOptions(options);
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+ bGlobalDatabase = args->isSet("global");
+ bMenuTest = args->isSet("menutest");
+
+ if (bGlobalDatabase)
+ {
+ setenv("TDEHOME", "-", 1);
+ setenv("TDEROOTHOME", "-", 1);
+ }
+
+ TDEApplication::disableAutoDcopRegistration();
+#ifdef KBUILDSYCOCA_GUI
+ TDEApplication k;
+#else
+ TDEApplication k(false, false);
+#endif
+ k.disableSessionManagement();
+
+#ifdef KBUILDSYCOCA_GUI
+ silent = args->isSet("silent");
+ showprogress = args->isSet("showprogress");
+ TQLabel progress( TQString("<p><br><nobr> %1 </nobr><br>").arg( i18n("Reloading TDE configuration, please wait...") ), 0, "", Qt::WType_Dialog | Qt::WStyle_DialogBorder | Qt::WStyle_Customize| Qt::WStyle_Title );
+ TQString capt = i18n("TDE Configuration Manager");
+ if (!silent) {
+ if (KMessageBox::No == KMessageBox::questionYesNo(0, i18n("Do you want to reload TDE configuration?"), capt, i18n("Reload"), i18n("Do Not Reload")))
+ return 0;
+ }
+ if (!silent || showprogress) {
+ progress.setCaption( capt );
+ progress.show();
+ }
+#endif
+
+ KCrash::setCrashHandler(KCrash::defaultCrashHandler);
+ KCrash::setEmergencySaveFunction(crashHandler);
+ KCrash::setApplicationName(TQString(appName));
+
+ // this program is in tdelibs so it uses tdelibs as catalog
+ KLocale::setMainCatalogue("tdelibs");
+ // force generating of KLocale object. if not, the database will get
+ // be translated
+ TDEGlobal::locale();
+ TDEGlobal::dirs()->addResourceType("app-reg", "share/application-registry" );
+
+ DCOPClient *dcopClient = new DCOPClient();
+
+ while(true)
+ {
+ TQCString registeredName = dcopClient->registerAs(appName, false);
+ if (registeredName.isEmpty())
+ {
+ fprintf(stderr, "[tdebuildsycoca] Warning: %s is unable to register with DCOP.\n", appName);
+ break;
+ }
+ else if (registeredName == appName)
+ {
+ break; // Go
+ }
+ fprintf(stderr, "[tdebuildsycoca] Waiting for already running %s to finish.\n", appName);
+
+ dcopClient->setNotifications( true );
+ while (dcopClient->isApplicationRegistered(appName))
+ {
+ WaitForSignal *obj = new WaitForSignal;
+ obj->connect(dcopClient, TQT_SIGNAL(applicationRemoved(const TQCString &)),
+ TQT_SLOT(deleteLater()));
+ kapp->eventLoop()->enterLoop();
+ }
+ dcopClient->setNotifications( false );
+ }
+ fprintf(stderr, "[tdebuildsycoca] %s running...\n", appName);
+
+ bool chectdefiles = bGlobalDatabase || args->isSet("chectdefiles");
+
+ bool incremental = !bGlobalDatabase && args->isSet("incremental") && chectdefiles;
+ if (incremental || !chectdefiles)
+ {
+ KSycoca::self()->disableAutoRebuild(); // Prevent deadlock
+ TQString current_language = TDEGlobal::locale()->language();
+ TQString tdesycoca_language = KSycoca::self()->language();
+ TQ_UINT32 current_update_sig = TDEGlobal::dirs()->calcResourceHash("services", "update_tdesycoca", true);
+ TQ_UINT32 tdesycoca_update_sig = KSycoca::self()->updateSignature();
+
+ if ((current_update_sig != tdesycoca_update_sig) ||
+ (current_language != tdesycoca_language) ||
+ (KSycoca::self()->timeStamp() == 0))
+ {
+ incremental = false;
+ chectdefiles = true;
+ delete KSycoca::self();
+ }
+ }
+
+ g_changeList = new TQStringList;
+
+ bool checkstamps = incremental && args->isSet("checkstamps") && chectdefiles;
+ TQ_UINT32 filestamp = 0;
+ TQStringList oldresourcedirs;
+ if( checkstamps && incremental )
+ {
+ TQString path = sycocaPath()+"stamp";
+ TQCString qPath = TQFile::encodeName(path);
+ cSycocaPath = qPath.data(); // Delete timestamps on crash
+ TQFile tdesycocastamp(path);
+ if( tdesycocastamp.open( IO_ReadOnly ))
+ {
+ TQDataStream str( &tdesycocastamp );
+ if (!str.atEnd())
+ str >> filestamp;
+ if (!str.atEnd())
+ {
+ str >> oldresourcedirs;
+ if( oldresourcedirs != KBuildSycoca::existingResourceDirs())
+ checkstamps = false;
+ }
+ else
+ {
+ checkstamps = false;
+ }
+ if (!str.atEnd())
+ {
+ TQStringList extraResourceDirs;
+ str >> extraResourceDirs;
+ oldresourcedirs += extraResourceDirs;
+ }
+ }
+ else
+ {
+ checkstamps = false;
+ }
+ cSycocaPath = 0;
+ }
+
+ newTimestamp = (TQ_UINT32) time(0);
+
+ if( chectdefiles && ( !checkstamps || !KBuildSycoca::checkTimestamps( filestamp, oldresourcedirs )))
+ {
+ TQCString qSycocaPath = TQFile::encodeName(sycocaPath());
+ cSycocaPath = qSycocaPath.data();
+
+ g_allEntries = 0;
+ g_ctimeDict = 0;
+ if (incremental)
+ {
+ tqWarning("[tdebuildsycoca] Reusing existing tdesycoca.");
+ KSycoca *oldSycoca = KSycoca::self();
+ KSycocaFactoryList *factories = new KSycocaFactoryList;
+ g_allEntries = new KSycocaEntryListList;
+ g_ctimeDict = new TQDict<TQ_UINT32>(523);
+
+ // Must be in same order as in KBuildSycoca::recreate()!
+ factories->append( new KServiceTypeFactory );
+ factories->append( new KServiceGroupFactory );
+ factories->append( new KServiceFactory );
+ factories->append( new KImageIOFactory );
+ factories->append( new KProtocolInfoFactory );
+
+ // For each factory
+ for (KSycocaFactory *factory = factories->first();
+ factory;
+ factory = factories->next() )
+ {
+ KSycocaEntry::List list;
+ list = factory->allEntries();
+ g_allEntries->append( list );
+ }
+ delete factories; factories = 0;
+ KCTimeInfo *ctimeInfo = new KCTimeInfo;
+ ctimeInfo->fillCTimeDict(*g_ctimeDict);
+ delete oldSycoca;
+ }
+ cSycocaPath = 0;
+
+ KBuildSycoca *sycoca= new KBuildSycoca; // Build data base
+ if (args->isSet("track"))
+ sycoca->setTrackId(TQString::fromLocal8Bit(args->getOption("track")));
+ if (!sycoca->recreate()) {
+#ifdef KBUILDSYCOCA_GUI
+ if (!silent || showprogress)
+ progress.close();
+#endif
+ return -1;
+ }
+
+ if (bGlobalDatabase)
+ {
+ // These directories may have been created with 0700 permission
+ // better delete them if they are empty
+ TQString applnkDir = TDEGlobal::dirs()->saveLocation("apps", TQString::null, false);
+ ::rmdir(TQFile::encodeName(applnkDir));
+ TQString servicetypesDir = TDEGlobal::dirs()->saveLocation("servicetypes", TQString::null, false);
+ ::rmdir(TQFile::encodeName(servicetypesDir));
+ }
+ }
+
+ if (!bGlobalDatabase)
+ {
+ // Recreate compatibility symlink
+ TQString oldPath = oldSycocaPath();
+ if (!oldPath.isEmpty())
+ {
+ KTempFile tmp;
+ if (tmp.status() == 0)
+ {
+ TQString tmpFile = tmp.name();
+ tmp.unlink();
+ symlink(TQFile::encodeName(sycocaPath()), TQFile::encodeName(tmpFile));
+ rename(TQFile::encodeName(tmpFile), TQFile::encodeName(oldPath));
+ }
+ }
+ }
+
+ if (args->isSet("signal"))
+ {
+ // Notify ALL applications that have a tdesycoca object, using a broadcast
+ TQByteArray data;
+ TQDataStream stream(data, IO_WriteOnly);
+ stream << *g_changeList;
+ dcopClient->send( "*", "tdesycoca", "notifyDatabaseChanged(TQStringList)", data );
+ }
+
+#ifdef KBUILDSYCOCA_GUI
+ if (!silent) {
+ progress.close();
+ KMessageBox::information(0, i18n("[tdebuildsycoca] Configuration information reloaded successfully."), capt);
+ }
+#endif
+ return 0;
+}
+
+#include "tdebuildsycoca.moc"
diff --git a/kded/tdebuildsycoca.h b/kded/tdebuildsycoca.h
new file mode 100644
index 000000000..51e7af337
--- /dev/null
+++ b/kded/tdebuildsycoca.h
@@ -0,0 +1,104 @@
+/* This file is part of the KDE libraries
+ * Copyright (C) 1999 David Faure <faure@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+#ifndef __tdebuildsycoca_h__
+#define __tdebuildsycoca_h__
+
+#include <sys/stat.h>
+
+#include <tqobject.h>
+#include <tqstring.h>
+#include <tqdict.h>
+
+#include <kservice.h>
+#include <tdesycoca.h>
+#include <tdesycocatype.h>
+#include <tdesycocaentry.h>
+#include <kservicegroup.h>
+
+#include "vfolder_menu.h"
+
+class TQDataStream;
+
+// No need for this in libtdeio - apps only get readonly access
+class KBuildSycoca : public KSycoca
+{
+ Q_OBJECT
+public:
+ KBuildSycoca();
+ virtual ~KBuildSycoca();
+
+ /**
+ * Recreate the database file
+ */
+ bool recreate();
+
+ static bool checkTimestamps( TQ_UINT32 timestamp, const TQStringList &dirs );
+
+ static TQStringList existingResourceDirs();
+
+ void setTrackId(const TQString &id) { m_trackId = id; }
+
+protected slots:
+ void slotCreateEntry(const TQString &file, KService **entry);
+
+protected:
+
+ /**
+ * Look up gnome mimetypes.
+ */
+ void processGnomeVfs();
+
+ /**
+ * Add single entry to the sycoca database.
+ * Either from a previous database or regenerated from file.
+ */
+ KSycocaEntry *createEntry(const TQString &file, bool addToFactory);
+
+ /**
+ * Convert a VFolderMenu::SubMenu to KServiceGroups.
+ */
+ void createMenu(TQString caption, TQString name, VFolderMenu::SubMenu *menu);
+
+ /**
+ * Build the whole system cache, from .desktop files
+ */
+ bool build();
+
+ /**
+ * Save the tdesycoca file
+ */
+ void save();
+
+ /**
+ * Clear the factories
+ */
+ void clear();
+
+ static bool checkDirTimestamps( const TQString& dir, const TQDateTime& stamp, bool top );
+
+ /**
+ * @internal
+ * @return true if building (i.e. if a KBuildSycoca);
+ */
+ virtual bool isBuilding() { return true; }
+
+ TQStringList m_allResourceDirs;
+ TQString m_trackId;
+};
+
+#endif
diff --git a/kded/kmimelist.cpp b/kded/tdemimelist.cpp
index c82f6d9f7..c82f6d9f7 100644
--- a/kded/kmimelist.cpp
+++ b/kded/tdemimelist.cpp
diff --git a/kdewidgets/CMakeLists.txt b/kdewidgets/CMakeLists.txt
index d68fbd3d6..a0a6f29df 100644
--- a/kdewidgets/CMakeLists.txt
+++ b/kdewidgets/CMakeLists.txt
@@ -23,8 +23,8 @@ include_directories(
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
diff --git a/kdewidgets/Makefile.am b/kdewidgets/Makefile.am
index dc30a767a..3afb3947b 100644
--- a/kdewidgets/Makefile.am
+++ b/kdewidgets/Makefile.am
@@ -21,7 +21,7 @@
SUBDIRS=. pics tests
AM_CXXFLAGS = -DQT_PLUGIN
-INCLUDES = -I$(top_srcdir)/kfile $(all_includes)
+INCLUDES = -I$(top_srcdir)/tdefile $(all_includes)
bin_PROGRAMS = makekdewidgets
makekdewidgets_SOURCES = makekdewidgets.cpp
diff --git a/kdewidgets/makekdewidgets.cpp b/kdewidgets/makekdewidgets.cpp
index 8e2856c53..ea84c61b7 100644
--- a/kdewidgets/makekdewidgets.cpp
+++ b/kdewidgets/makekdewidgets.cpp
@@ -2,7 +2,7 @@
#include <kaboutdata.h>
#include <kinstance.h>
#include <kcmdlineargs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kmacroexpander.h>
#include <kdebug.h>
diff --git a/kdoctools/CMakeLists.txt b/kdoctools/CMakeLists.txt
index 9d97712c6..09b04a8ea 100644
--- a/kdoctools/CMakeLists.txt
+++ b/kdoctools/CMakeLists.txt
@@ -18,9 +18,9 @@ include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_BINARY_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kioslave
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeioslave
${LIBXML2_INCLUDE_DIRS}
${LIBXSLT_INCLUDE_DIRS}
)
@@ -54,7 +54,7 @@ install( FILES man-template.docbook template.docbook DESTINATION ${DATA_INSTALL_
##### kbzipfilter_dummy ##############################
tde_add_library( kbzipfilter_dummy STATIC_PIC
- SOURCES ${CMAKE_SOURCE_DIR}/kioslave/bzip2/kbzip2filter.cpp
+ SOURCES ${CMAKE_SOURCE_DIR}/tdeioslave/bzip2/kbzip2filter.cpp
)
@@ -68,7 +68,7 @@ set( ${target}_SRCS
tde_add_kpart( ${target} SHARED
SOURCES ${${target}_SRCS}
- LINK kbzipfilter_dummy-static kio-shared ${BZIP2_LIBRARIES} ${LIBXML2_LIBRARIES} ${LIBXSLT_LIBRARIES}
+ LINK kbzipfilter_dummy-static tdeio-shared ${BZIP2_LIBRARIES} ${LIBXML2_LIBRARIES} ${LIBXSLT_LIBRARIES}
DESTINATION ${PLUGIN_INSTALL_DIR}
)
@@ -83,7 +83,7 @@ set( ${target}_SRCS
tde_add_kpart( ${target} SHARED
SOURCES ${${target}_SRCS}
- LINK kbzipfilter_dummy-static kio-shared ${BZIP2_LIBRARIES} ${LIBXML2_LIBRARIES} ${LIBXSLT_LIBRARIES}
+ LINK kbzipfilter_dummy-static tdeio-shared ${BZIP2_LIBRARIES} ${LIBXML2_LIBRARIES} ${LIBXSLT_LIBRARIES}
DESTINATION ${PLUGIN_INSTALL_DIR}
)
@@ -102,6 +102,6 @@ set_source_files_properties( xslt_pure.cpp PROPERTIES COMPILE_FLAGS -DSIMPLE_XSL
tde_add_executable( ${target}
SOURCES ${${target}_SRCS}
- LINK kbzipfilter_dummy-static kio-shared ${BZIP2_LIBRARIES} ${LIBXML2_LIBRARIES} ${LIBXSLT_LIBRARIES}
+ LINK kbzipfilter_dummy-static tdeio-shared ${BZIP2_LIBRARIES} ${LIBXML2_LIBRARIES} ${LIBXSLT_LIBRARIES}
DESTINATION ${BIN_INSTALL_DIR}
)
diff --git a/kdoctools/Makefile.am b/kdoctools/Makefile.am
index f5aab5ebe..05c3487cd 100644
--- a/kdoctools/Makefile.am
+++ b/kdoctools/Makefile.am
@@ -1,5 +1,5 @@
-INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/kioslave -I$(top_srcdir)/kioslave/bzip2 $(all_includes) $(LIBXML_CFLAGS) $(LIBXSLT_CFLAGS)
+INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/tdeioslave -I$(top_srcdir)/tdeioslave/bzip2 $(all_includes) $(LIBXML_CFLAGS) $(LIBXSLT_CFLAGS)
AM_LDFLAGS = $(KDE_RPATH) $(LIBXML_RPATH) $(LIBXSLT_RPATH) $(all_libraries)
noinst_LTLIBRARIES = libkbzipfilter_dummy.la
@@ -38,10 +38,10 @@ METASOURCES = AUTO
update_DATA = kio_help.upd
update_SCRIPTS = move_kio_help_cache.sh
-updatedir = $(kde_datadir)/kconf_update
+updatedir = $(kde_datadir)/tdeconf_update
messages:
- $(XGETTEXT) *.cpp -o $(podir)/kio_help.pot
+ $(XGETTEXT) *.cpp -o $(podir)/tdeio_help.pot
install-data-local:
@(for subdir in customization docbook; do \
@@ -59,7 +59,7 @@ uninstall-local:
-rm -rf $(DESTDIR)$(kde_datadir)/ksgmltools2/docbook
kbzip2filter.cpp:
- -$(LN_S) $(srcdir)/../kioslave/bzip2/kbzip2filter.cpp .
+ -$(LN_S) $(srcdir)/../tdeioslave/bzip2/kbzip2filter.cpp .
CLEANFILES = kbzip2filter.cpp xslt_pure.o xslt_pure.cpp checkXML
diff --git a/kdoctools/docbook/README.kde b/kdoctools/docbook/README.kde
index df33a8cba..ae080b287 100644
--- a/kdoctools/docbook/README.kde
+++ b/kdoctools/docbook/README.kde
@@ -1,4 +1,4 @@
-README file for tdebase/kioslave/help/docbook
+README file for tdebase/tdeioslave/help/docbook
=============================================
This are copies of
diff --git a/kdoctools/kio_help.h b/kdoctools/kio_help.h
index 957a0e2e5..df002df15 100644
--- a/kdoctools/kio_help.h
+++ b/kdoctools/kio_help.h
@@ -15,8 +15,8 @@
#include <tqvaluelist.h>
-#include <kio/global.h>
-#include <kio/slavebase.h>
+#include <tdeio/global.h>
+#include <tdeio/slavebase.h>
class HelpProtocol : public TDEIO::SlaveBase
{
diff --git a/kdoctools/kio_help.upd b/kdoctools/kio_help.upd
index 2f067b148..cca96f64b 100644
--- a/kdoctools/kio_help.upd
+++ b/kdoctools/kio_help.upd
@@ -1,3 +1,3 @@
-# Move kio_help cache from $TDEHOME/share/apps/kio_help/cache to $TDEHOME/cache-$HOST/kio_help
+# Move kio_help cache from $TDEHOME/share/apps/tdeio_help/cache to $TDEHOME/cache-$HOST/tdeio_help
Id=trinity_2
Script=move_kio_help_cache.sh,sh
diff --git a/kdoctools/move_kio_help_cache.sh b/kdoctools/move_kio_help_cache.sh
index c31331c9e..f1342c5b4 100644
--- a/kdoctools/move_kio_help_cache.sh
+++ b/kdoctools/move_kio_help_cache.sh
@@ -1,6 +1,6 @@
#!/bin/sh
-bas=`tde-config --localprefix`share/apps/kio_help
+bas=`tde-config --localprefix`share/apps/tdeio_help
mv "$bas/cache" "`tde-config --path cache`kio_help"
rmdir "$bas"
exit 0
diff --git a/kfile-plugins/elf/CMakeLists.txt b/kfile-plugins/elf/CMakeLists.txt
deleted file mode 100644
index 91e9d5e32..000000000
--- a/kfile-plugins/elf/CMakeLists.txt
+++ /dev/null
@@ -1,42 +0,0 @@
-#################################################
-#
-# (C) 2012 Timothy Pearson
-# kb9vqf (AT) pearsoncomputing.net
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${TDE_INCLUDE_DIR}
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_BINARY_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${LIBR_INCLUDEDIR}
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
- ${LIBR_LIBDIR}
-)
-
-#### other data #################################
-
-install( FILES kfile_elf.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-#### kfile_elf (module) #########################
-
-tde_add_kpart( kfile_elf AUTOMOC
- SOURCES kfile_elf.cpp
- EMBED tdelficon-static
- LINK kio-shared ${LIBR_LIBRARIES}
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kfile-plugins/elf/kfile_elf.cpp b/kfile-plugins/elf/kfile_elf.cpp
deleted file mode 100644
index 2357f0617..000000000
--- a/kfile-plugins/elf/kfile_elf.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/* This file is part of the KDE project
- * Copyright (C) 2012 Timothy Pearson <kb9vqf@pearsoncomputing.net>
- *
- * 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 version 2.
- *
- * 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; see the file COPYING. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include <config.h>
-#include "kfile_elf.h"
-
-#include <kprocess.h>
-#include <klocale.h>
-#include <kgenericfactory.h>
-#include <kstringvalidator.h>
-#include <kdebug.h>
-
-#include <tqdict.h>
-#include <tqvalidator.h>
-#include <tqcstring.h>
-#include <tqfile.h>
-#include <tqdatetime.h>
-
-#include "tdelficon.h"
-
-#if !defined(__osf__)
-#include <inttypes.h>
-#else
-typedef unsigned long uint32_t;
-typedef unsigned short uint16_t;
-#endif
-
-typedef KGenericFactory<KElfPlugin> ElfFactory;
-
-K_EXPORT_COMPONENT_FACTORY(kfile_elf, ElfFactory( "kfile_elf" ))
-
-KElfPlugin::KElfPlugin(TQObject *parent, const char *name,
- const TQStringList &args)
-
- : KFilePlugin(parent, name, args)
-{
- KFileMimeTypeInfo* info = addMimeTypeInfo( "application/x-executable" );
-
- KFileMimeTypeInfo::GroupInfo* group = 0L;
- KFileMimeTypeInfo::GroupInfo* group2 = 0L;
-
- group = addGroupInfo(info, "Technical", i18n("Embedded Metadata"));
- group2 = addGroupInfo(info, "Icon", i18n("Embedded Icon(s)"));
-
- KFileMimeTypeInfo::ItemInfo* item;
-
- item = addItemInfo(group, "Name", i18n("Internal Name"), TQVariant::String);
- item = addItemInfo(group, "Description", i18n("Description"), TQVariant::String);
- item = addItemInfo(group, "License", i18n("License"), TQVariant::String);
- item = addItemInfo(group, "Copyright", i18n("Copyright"), TQVariant::String);
- item = addItemInfo(group, "Authors", i18n("Author(s)"), TQVariant::String);
- item = addItemInfo(group, "Product", i18n("Product"), TQVariant::String);
- item = addItemInfo(group, "Organization", i18n("Organization"), TQVariant::String);
- item = addItemInfo(group, "Version", i18n("Version"), TQVariant::String);
- item = addItemInfo(group, "DateTime", i18n("Compilation Date/Time"), TQVariant::String);
- item = addItemInfo(group, "SystemIcon", i18n("Requested Icon"), TQVariant::String);
- item = addItemInfo(group, "Notes", i18n("Comments"), TQVariant::String);
-
- item = addItemInfo(group2, "EmbeddedIcon", i18n("Icon Name(s)"), TQVariant::String);
-}
-
-
-bool KElfPlugin::readInfo( KFileMetaInfo& info, uint what)
-{
- libr_icon *icon = NULL;
- libr_file *handle = NULL;
- libr_access_t access = LIBR_READ;
-
- if((handle = libr_open(const_cast<char*>(info.path().ascii()), access)) == NULL)
- {
- kdWarning() << "failed to open file" << info.path() << endl;
- }
-
- KFileMetaInfoGroup group = appendGroup(info, "Technical");
- KFileMetaInfoGroup group2 = appendGroup(info, "Icon");
-
- appendItem(group, "Name", elf_get_resource(handle, ".metadata_name"));
- appendItem(group, "Description", elf_get_resource(handle, ".metadata_description"));
- appendItem(group, "License", elf_get_resource(handle, ".metadata_license"));
- appendItem(group, "Copyright", elf_get_resource(handle, ".metadata_copyright"));
- appendItem(group, "Authors", elf_get_resource(handle, ".metadata_authors"));
- appendItem(group, "Product", elf_get_resource(handle, ".metadata_product"));
- appendItem(group, "Organization", elf_get_resource(handle, ".metadata_organization"));
- appendItem(group, "Version", elf_get_resource(handle, ".metadata_version"));
- appendItem(group, "DateTime", elf_get_resource(handle, ".metadata_datetime"));
- appendItem(group, "SystemIcon", elf_get_resource(handle, ".metadata_sysicon"));
- appendItem(group, "Notes", elf_get_resource(handle, ".metadata_notes"));
-
- TQString iconListing;
-
- iconentry *entry = NULL;
- iconlist icons;
- if(!get_iconlist(handle, &icons))
- {
- // Failed to obtain a list of ELF icons
- }
- else {
- while((entry = get_nexticon(&icons, entry)) != NULL)
- {
- if (iconListing.isEmpty()) {
- iconListing = entry->name;
- }
- else {
- iconListing = iconListing.append("\n").append(entry->name);
- }
- break;
- }
- }
-
- appendItem(group2, "EmbeddedIcon", iconListing);
-
- libr_close(handle);
-
- return true;
-}
-
-#include "kfile_elf.moc"
diff --git a/kfile-plugins/elf/kfile_elf.desktop b/kfile-plugins/elf/kfile_elf.desktop
deleted file mode 100644
index cc993d36a..000000000
--- a/kfile-plugins/elf/kfile_elf.desktop
+++ /dev/null
@@ -1,66 +0,0 @@
-[Desktop Entry]
-Type=Service
-Name=ELF Info
-Name[af]=ELF Inligting
-Name[ar]=معلومات ELF
-Name[br]=Titouroù ELF
-Name[ca]=Informació de ELF
-Name[cs]=ELF info
-Name[cy]=Gwybodaeth ELF
-Name[da]=ELF-info
-Name[de]=ELF-Info
-Name[el]=ΠληÏοφοÏίες ELF
-Name[eo]=ELF-informo
-Name[es]=Info ELF
-Name[et]=ELF info
-Name[fa]=اطلاعات ELF
-Name[fi]=ELF-tiedot
-Name[fr]=Informations ELF
-Name[ga]=Eolas faoi ELF
-Name[gl]=Inf. ELF
-Name[he]=מידע ELF
-Name[hi]=ELF जानकारी
-Name[hr]=ELF informacije
-Name[hu]=ELF-jellemzők
-Name[is]=ELF upplýsingar
-Name[it]=Informazioni ELF
-Name[ja]=ELF 情報
-Name[kk]=ELF мәліметі
-Name[km]=áž–áŸážáŸŒáž˜áž¶áž“ ELF
-Name[lt]=ELF informacija
-Name[ms]=Maklumat ELF
-Name[nds]=ELF-Info
-Name[ne]=ELF सूचना
-Name[nl]=ELF-info
-Name[nn]=ELF-info
-Name[nso]=Tshedimoso ya ELF
-Name[pa]=ELF ਜਾਣਕਾਰੀ
-Name[pl]=Informacja o pliku ELF
-Name[pt]=Informação do ELF
-Name[pt_BR]=Informação sobre ELF
-Name[ro]=Informaţii ELF
-Name[ru]=Ð˜Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ ELF
-Name[se]=ELF-dieđut
-Name[sl]=Podatki o ELF
-Name[sr]=ELF информације
-Name[sr@Latn]=ELF informacije
-Name[sv]=ELF-information
-Name[ta]=ELF தகவலà¯
-Name[tg]=Иттилоот оиди ELF
-Name[th]=ข้อมูลà¹à¸Ÿà¹‰à¸¡ ELF
-Name[tr]=ELF Bilgisi
-Name[uk]=Ð†Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ñ–Ñ Ð¿Ð¾ ELF
-Name[uz]=ELF haqida maʼlumot
-Name[uz@cyrillic]=ELF ҳақида маълумот
-Name[ven]=Mafhungo ELF
-Name[wa]=Informåcion sol imådje ELF
-Name[xh]=Ulwazi lwe ELF
-Name[zh_CN]=ELF ä¿¡æ¯
-Name[zh_HK]=ELF 資訊
-Name[zh_TW]=ELF 資訊
-Name[zu]=Ulwazi lwe-ELF
-ServiceTypes=KFilePlugin
-X-TDE-Library=kfile_elf
-MimeType=application/x-executable
-PreferredItems=Name,Description,License,Copyright,Authors,Product,Organization,Version,DateTime,Notes"
-SupportsThumbnail=false \ No newline at end of file
diff --git a/kfile-plugins/elf/kfile_elf.h b/kfile-plugins/elf/kfile_elf.h
deleted file mode 100644
index 1e6247a46..000000000
--- a/kfile-plugins/elf/kfile_elf.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/* This file is part of the KDE project
- * Copyright (C) 2002 Shane Wright <me@shanewright.co.uk>
- *
- * 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 version 2.
- *
- * 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; see the file COPYING. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef __KFILE_BMP_H__
-#define __KFILE_BMP_H__
-
-#include <kfilemetainfo.h>
-
-// Elven things
-extern "C" {
- #include <libr.h>
- #include <libr-icons.h>
-}
-
-#include <string.h>
-
-#include <sys/stat.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-class TQStringList;
-
-class KElfPlugin: public KFilePlugin
-{
- Q_OBJECT
-
-
-public:
- KElfPlugin( TQObject *parent, const char *name, const TQStringList& args );
-
- virtual bool readInfo( KFileMetaInfo& info, uint what);
-};
-
-#endif
diff --git a/kimgio/Makefile.am b/kimgio/Makefile.am
index ad833c292..41ca9a892 100644
--- a/kimgio/Makefile.am
+++ b/kimgio/Makefile.am
@@ -81,7 +81,7 @@ kimg_hdr_la_LIBADD = $(LIB_QT)
noinst_HEADERS= xview.h eps.h tiffr.h g3r.h ico.h jp2.h pcx.h tga.h rgb.h xcf.h gimp.h exr.h dds.h psd.h hdr.h
-INCLUDES = -I$(top_srcdir)/kio -I$(top_srcdir)/dcop -I$(top_srcdir)/libltdl $(all_includes) -Drestrict= $(EXR_FLAGS)
+INCLUDES = -I$(top_srcdir)/tdeio -I$(top_srcdir)/dcop -I$(top_srcdir)/libltdl $(all_includes) -Drestrict= $(EXR_FLAGS)
servicedir = $(kde_servicesdir)
service_DATA = png.kimgio xpm.kimgio bmp.kimgio pbm.kimgio pgm.kimgio \
diff --git a/kimgio/README b/kimgio/README
index 6c9cec844..142823e6c 100644
--- a/kimgio/README
+++ b/kimgio/README
@@ -22,7 +22,7 @@ XCF <read>
To use these formats, you only need to:
-1. link the application with the libkio library
+1. link the application with the libtdeio library
2. Include the <kimageio.h> header
3. call KImageIO::registerFormats() once, somewhere in your code
before you load an image.
diff --git a/kinit/CMakeLists.txt b/kinit/CMakeLists.txt
index 834242bf1..88be32621 100644
--- a/kinit/CMakeLists.txt
+++ b/kinit/CMakeLists.txt
@@ -19,8 +19,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${FREETYPE_INCLUDE_DIRS}
)
@@ -94,34 +94,34 @@ tde_add_executable( ${target}
)
-#### kioslave ###################################
+#### tdeioslave ###################################
-set( target kioslave )
+set( target tdeioslave )
tde_add_executable( ${target} AUTOMOC
- SOURCES kioslave.cpp
- LINK ltdlc-static kio-shared
+ SOURCES tdeioslave.cpp
+ LINK ltdlc-static tdeio-shared
DESTINATION ${BIN_INSTALL_DIR}
)
-#### kstartupconfig #############################
+#### tdestartupconfig #############################
-set( target kstartupconfig )
+set( target tdestartupconfig )
tde_add_executable( ${target} AUTOMOC
- SOURCES kstartupconfig.cpp
+ SOURCES tdestartupconfig.cpp
LINK tdefakes-shared ${TQT_LIBRARIES}
DESTINATION ${BIN_INSTALL_DIR}
)
-#### kdostartupconfig ###########################
+#### tdedostartupconfig ###########################
-set( target kdostartupconfig )
+set( target tdedostartupconfig )
tde_add_executable( ${target} AUTOMOC
- SOURCES kdostartupconfig.cpp
+ SOURCES tdedostartupconfig.cpp
LINK tdecore-shared
DESTINATION ${BIN_INSTALL_DIR}
)
@@ -153,15 +153,15 @@ tde_add_executable( ${target}
)
-#### klauncher ##################################
+#### tdelauncher ##################################
-set( target klauncher )
+set( target tdelauncher )
set( ${target}_SRCS
- klauncher.cpp klauncher_main.cpp autostart.cpp
+ tdelauncher.cpp tdelauncher_main.cpp autostart.cpp
)
tde_add_tdeinit_executable( ${target} AUTOMOC
SOURCES ${${target}_SRCS}
- LINK kio-shared
+ LINK tdeio-shared
)
diff --git a/kinit/Makefile.am b/kinit/Makefile.am
index ef329980a..3090d041e 100644
--- a/kinit/Makefile.am
+++ b/kinit/Makefile.am
@@ -19,11 +19,11 @@ INCLUDES = -I$(srcdir)/../libltdl/ $(all_includes) $(TDEINIT_XFT_INCLUDES)
SUBDIRS = . tests
-bin_PROGRAMS = tdeinit tdeinit_wrapper kshell tdeinit_shutdown lnusertemp kwrapper kioslave \
- kstartupconfig kdostartupconfig start_tdeinit start_tdeinit_wrapper
+bin_PROGRAMS = tdeinit tdeinit_wrapper kshell tdeinit_shutdown lnusertemp kwrapper tdeioslave \
+ tdestartupconfig tdedostartupconfig start_tdeinit start_tdeinit_wrapper
lib_LTLIBRARIES =
-tdeinit_LTLIBRARIES = klauncher.la
+tdeinit_LTLIBRARIES = tdelauncher.la
tdeinit_SOURCES = kinit.cpp setproctitle.cpp
# NOTE: We link against all common libraries even if we don't need them ourselves.
@@ -35,10 +35,10 @@ tdeinit_LDFLAGS = $(KDE_MT_LDFLAGS) $(QT_LDFLAGS) $(X_LDFLAGS) $(USER_LDFLAGS) \
$(KDE_RPATH)
tdeinit_LDADD = $(LIB_KPARTS) -lXft $(LIB_QT)
-kioslave_SOURCES = kioslave.cpp
-kioslave_LDFLAGS = $(KDE_MT_LDFLAGS) $(QT_LDFLAGS) $(X_LDFLAGS) $(USER_LDFLAGS) \
+tdeioslave_SOURCES = tdeioslave.cpp
+tdeioslave_LDFLAGS = $(KDE_MT_LDFLAGS) $(QT_LDFLAGS) $(X_LDFLAGS) $(USER_LDFLAGS) \
$(KDE_RPATH)
-kioslave_LDADD = $(LIB_KIO)
+tdeioslave_LDADD = $(LIB_KIO)
tdeinit_wrapper_SOURCES = wrapper.c
tdeinit_wrapper_LDADD = $(LIBSOCKET)
@@ -55,16 +55,16 @@ lnusertemp_LDFLAGS = $(KDE_RPATH)
kwrapper_SOURCES = kwrapper.c
kwrapper_LDADD = $(LIBSOCKET)
-klauncher_la_LDFLAGS = $(all_libraries) -module -avoid-version
-klauncher_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la $(LIB_X11)
-klauncher_la_SOURCES = klauncher.cpp klauncher_main.cpp autostart.cpp
+tdelauncher_la_LDFLAGS = $(all_libraries) -module -avoid-version
+tdelauncher_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la $(LIB_X11)
+tdelauncher_la_SOURCES = tdelauncher.cpp tdelauncher_main.cpp autostart.cpp
-kstartupconfig_SOURCES = kstartupconfig.cpp
-kstartupconfig_LDADD = $(top_builddir)/tdecore/libtdefakes.la $(LIB_QT)
-kdostartupconfig_SOURCES = kdostartupconfig.cpp
-kdostartupconfig_LDFLAGS = $(KDE_MT_LDFLAGS) $(QT_LDFLAGS) $(X_LDFLAGS) $(USER_LDFLAGS) \
+tdestartupconfig_SOURCES = tdestartupconfig.cpp
+tdestartupconfig_LDADD = $(top_builddir)/tdecore/libtdefakes.la $(LIB_QT)
+tdedostartupconfig_SOURCES = tdedostartupconfig.cpp
+tdedostartupconfig_LDFLAGS = $(KDE_MT_LDFLAGS) $(QT_LDFLAGS) $(X_LDFLAGS) $(USER_LDFLAGS) \
$(KDE_RPATH)
-kdostartupconfig_LDADD = $(LIB_TDECORE)
+tdedostartupconfig_LDADD = $(LIB_TDECORE)
start_tdeinit_SOURCES = start_tdeinit.c
tdeinitpath = $(bindir)/tdeinit
@@ -75,7 +75,7 @@ start_tdeinit_wrapper_SOURCES = start_tdeinit_wrapper.c
METASOURCES = AUTO
-noinst_HEADERS = klauncher.h autostart.h klauncher_cmds.h setproctitle.h
+noinst_HEADERS = tdelauncher.h autostart.h tdelauncher_cmds.h setproctitle.h
kwrapper.o: wrapper.c
diff --git a/kinit/autostart.cpp b/kinit/autostart.cpp
index 3fe0825a4..4e4ad1f56 100644
--- a/kinit/autostart.cpp
+++ b/kinit/autostart.cpp
@@ -22,7 +22,7 @@
#include "autostart.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdesktopfile.h>
#include <kglobal.h>
#include <kstandarddirs.h>
diff --git a/kinit/kdostartupconfig.cpp b/kinit/kdostartupconfig.cpp
deleted file mode 100644
index b74417c3f..000000000
--- a/kinit/kdostartupconfig.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-
- Copyright (C) 2005 Lubos Lunak <l.lunak@kde.org>
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the "Software"),
-to deal in the Software without restriction, including without limitation
-the rights to use, copy, modify, merge, publish, distribute, sublicense,
-and/or sell copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE.
-
-****************************************************************************/
-
-#undef QT_NO_CAST_ASCII
-
-// See description in kstartupconfig.cpp .
-
-#include <tqfile.h>
-#include <tqtextstream.h>
-#include <kinstance.h>
-#include <kstandarddirs.h>
-#include <kconfig.h>
-#include <kdebug.h>
-
-TQString get_entry( TQString* ll )
- {
- TQString& l = *ll;
- l = l.stripWhiteSpace();
- if( l.isEmpty())
- return TQString::null;
- TQString ret;
- if( l[ 0 ] == '\'' )
- {
- unsigned int pos = 1;
- while( pos < l.length() && l[ pos ] != '\'' )
- ret += l[ pos++ ];
- if( pos >= l.length())
- {
- *ll = TQString::null;
- return TQString::null;
- }
- *ll = l.mid( pos + 1 );
- return ret;
- }
- unsigned int pos = 0;
- while( pos < l.length() && l[ pos ] != ' ' )
- ret += l[ pos++ ];
- *ll = l.mid( pos );
- return ret;
- }
-
-int main()
- {
- TDEInstance inst( "kdostartupconfig" );
- kdDebug() << "Running kdostartupconfig." << endl;
- TQString keysname = locateLocal( "config", "startupconfigkeys" );
- TQFile keys( keysname );
- if( !keys.open( IO_ReadOnly ))
- return 3;
- TQFile f1( locateLocal( "config", "startupconfig" ));
- if( !f1.open( IO_WriteOnly ))
- return 4;
- TQFile f2( locateLocal( "config", "startupconfigfiles" ));
- if( !f2.open( IO_WriteOnly ))
- return 5;
- TQTextStream startupconfig( &f1 );
- TQTextStream startupconfigfiles( &f2 );
- startupconfig << "#! /bin/sh\n";
- for(;;)
- {
- TQString line;
- if( keys.readLine( line, 1024 ) < 0 )
- break;
- line = line.stripWhiteSpace();
- if( line.isEmpty())
- break;
- TQString tmp = line;
- TQString file, group, key, def;
- file = get_entry( &tmp );
- group = get_entry( &tmp );
- key = get_entry( &tmp );
- def = get_entry( &tmp );
- if( file.isEmpty() || group.isEmpty())
- return 6;
- if( group.left( 1 ) == "[" && group.right( 1 ) == "]" )
- { // whole config group
- TDEConfig cfg( file );
- group = group.mid( 1, group.length() - 2 );
- TQMap< TQString, TQString > entries = cfg.entryMap( group );
- startupconfig << "# " << line << "\n";
- for( TQMap< TQString, TQString >::ConstIterator it = entries.begin();
- it != entries.end();
- ++it )
- {
- TQString key = it.key();
- TQString value = *it;
- startupconfig << TQString(file.replace( ' ', '_' )).lower()
- << "_" << TQString(group.replace( ' ', '_' )).lower()
- << "_" << TQString(key.replace( ' ', '_' )).lower()
- << "=\"" << value.replace( "\"", "\\\"" ) << "\"\n";
- }
- }
- else
- { // a single key
- if( key.isEmpty())
- return 7;
- TDEConfig cfg( file );
- cfg.setGroup( group );
- TQString value = cfg.readEntry( key, def );
- startupconfig << "# " << line << "\n";
- startupconfig << TQString(file.replace( ' ', '_' )).lower()
- << "_" << TQString(group.replace( ' ', '_' )).lower()
- << "_" <<TQString( key.replace( ' ', '_' )).lower()
- << "=\"" << value.replace( "\"", "\\\"" ) << "\"\n";
- }
- startupconfigfiles << line << endl;
- // use even currently non-existing paths in $TDEDIRS
- TQStringList dirs = TQStringList::split( KPATH_SEPARATOR, TDEGlobal::dirs()->kfsstnd_prefixes());
- for( TQStringList::ConstIterator it = dirs.begin();
- it != dirs.end();
- ++it )
- {
- TQString cfg = *it + "share/config/" + file;
- if( KStandardDirs::exists( cfg ))
- startupconfigfiles << cfg << "\n";
- else
- startupconfigfiles << "!" << cfg << "\n";
- }
- startupconfigfiles << "*\n";
- }
- return 0;
- }
diff --git a/kinit/kinit.cpp b/kinit/kinit.cpp
index 6cf9293d6..63e6ab832 100644
--- a/kinit/kinit.cpp
+++ b/kinit/kinit.cpp
@@ -55,7 +55,7 @@
#include <kinstance.h>
#include <kstandarddirs.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klibloader.h>
#include <kapplication.h>
#include <klocale.h>
@@ -74,7 +74,7 @@
#include <tdeversion.h>
#include "ltdl.h"
-#include "klauncher_cmds.h"
+#include "tdelauncher_cmds.h"
//#if defined Q_WS_X11 && ! defined K_WS_QTONLY
#ifdef Q_WS_X11
@@ -169,9 +169,9 @@ int tdeinit_x_errhandler( Display *, XErrorEvent *err );
/* These are to link libtdeparts even if 'smart' linker is used */
#include <tdeparts/plugin.h>
extern "C" KParts::Plugin* _kinit_init_tdeparts() { return new KParts::Plugin(); }
-/* These are to link libkio even if 'smart' linker is used */
-#include <kio/authinfo.h>
-extern "C" TDEIO::AuthInfo* _kioslave_init_kio() { return new TDEIO::AuthInfo(); }
+/* These are to link libtdeio even if 'smart' linker is used */
+#include <tdeio/authinfo.h>
+extern "C" TDEIO::AuthInfo* _tdeioslave_init_kio() { return new TDEIO::AuthInfo(); }
/*
* Close fd's which are only useful for the parent process.
@@ -429,8 +429,8 @@ static pid_t launch(int argc, const char *_name, const char *args,
TQCString name;
TQCString exec;
- if (strcmp(_name, "klauncher") == 0) {
- /* klauncher is launched in a special way:
+ if (strcmp(_name, "tdelauncher") == 0) {
+ /* tdelauncher is launched in a special way:
* It has a communication socket on LAUNCHER_FD
*/
if (0 > socketpair(AF_UNIX, SOCK_STREAM, 0, d.launcher))
@@ -891,7 +891,7 @@ static void init_tdeinit_socket()
if(connect(s, (struct sockaddr *)&server, socklen) == 0)
{
fprintf(stderr, "[tdeinit] Shutting down running client.\n");
- klauncher_header request_header;
+ tdelauncher_header request_header;
request_header.cmd = LAUNCHER_TERMINATE_TDEINIT;
request_header.arg_length = 0;
write(s, &request_header, sizeof(request_header));
@@ -1090,7 +1090,7 @@ static void launcher_died()
close(d.launcher[0]);
d.launcher[0] = -1;
- pid_t pid = launch( 1, "klauncher", 0 );
+ pid_t pid = launch( 1, "tdelauncher", 0 );
#ifndef NDEBUG
fprintf(stderr, "[tdeinit] Relaunching KLauncher, pid = %ld result = %d\n", (long) pid, d.result);
#endif
@@ -1105,7 +1105,7 @@ static void handle_launcher_request(int sock = -1)
launcher = true;
}
- klauncher_header request_header;
+ tdelauncher_header request_header;
char *request_data = 0L;
int result = read_socket(sock, (char *) &request_header, sizeof(request_header));
if (result != 0)
@@ -1141,7 +1141,7 @@ static void handle_launcher_request(int sock = -1)
(request_header.cmd == LAUNCHER_EXEC_NEW)))
{
pid_t pid;
- klauncher_header response_header;
+ tdelauncher_header response_header;
long response_data;
long l;
memcpy( &l, request_data, sizeof( long ));
@@ -1273,7 +1273,7 @@ static void handle_launcher_request(int sock = -1)
#ifndef NDEBUG
if (launcher)
- fprintf(stderr, "[tdeinit] Got SETENV '%s=%s' from klauncher.\n", env_name, env_value);
+ fprintf(stderr, "[tdeinit] Got SETENV '%s=%s' from tdelauncher.\n", env_name, env_value);
else
fprintf(stderr, "[tdeinit] Got SETENV '%s=%s' from socket.\n", env_name, env_value);
#endif
@@ -1301,7 +1301,7 @@ static void handle_launcher_request(int sock = -1)
else if (request_header.cmd == LAUNCHER_TERMINATE_TDEINIT)
{
#ifndef NDEBUG
- fprintf(stderr,"[tdeinit] Killing tdeinit/klauncher.\n");
+ fprintf(stderr,"[tdeinit] Killing tdeinit/tdelauncher.\n");
#endif
if (d.launcher_pid)
kill(d.launcher_pid, SIGTERM);
@@ -1359,7 +1359,7 @@ static void handle_requests(pid_t waitForPid)
if (d.launcher_pid)
{
// TODO send process died message
- klauncher_header request_header;
+ tdelauncher_header request_header;
long request_data[2];
request_header.cmd = LAUNCHER_DIED;
request_header.arg_length = sizeof(long) * 2;
@@ -1686,7 +1686,7 @@ int main(int argc, char **argv, char **envp)
int i;
pid_t pid;
int launch_dcop = 1;
- int launch_klauncher = 1;
+ int launch_tdelauncher = 1;
int launch_kded = 1;
int keep_running = 1;
int new_startup = 0;
@@ -1699,8 +1699,8 @@ int main(int argc, char **argv, char **envp)
safe_argv[i] = strcpy((char*)malloc(strlen(argv[i])+1), argv[i]);
if (strcmp(safe_argv[i], "--no-dcop") == 0)
launch_dcop = 0;
- if (strcmp(safe_argv[i], "--no-klauncher") == 0)
- launch_klauncher = 0;
+ if (strcmp(safe_argv[i], "--no-tdelauncher") == 0)
+ launch_tdelauncher = 0;
if (strcmp(safe_argv[i], "--no-kded") == 0)
launch_kded = 0;
if (strcmp(safe_argv[i], "--suicide") == 0)
@@ -1717,7 +1717,7 @@ int main(int argc, char **argv, char **envp)
{
printf("Usage: tdeinit [options]\n");
// printf(" --no-dcop Do not start dcopserver\n");
- // printf(" --no-klauncher Do not start klauncher\n");
+ // printf(" --no-tdelauncher Do not start tdelauncher\n");
printf(" --no-kded Do not start kded\n");
printf(" --suicide Terminate when no TDE applications are left running\n");
// printf(" --exit Terminate when kded has run\n");
@@ -1729,7 +1729,7 @@ int main(int argc, char **argv, char **envp)
// Fork here and let parent process exit.
// Parent process may only exit after all required services have been
- // launched. (dcopserver/klauncher and services which start with '+')
+ // launched. (dcopserver/tdelauncher and services which start with '+')
signal( SIGCHLD, secondary_child_handler);
if (fork() > 0) // Go into background
{
@@ -1812,16 +1812,16 @@ int main(int argc, char **argv, char **envp)
(void) lt_dlopen(TQFile::encodeName(konq).data());
}
#endif
- if (launch_klauncher)
+ if (launch_tdelauncher)
{
if( new_startup )
- pid = launch( 2, "klauncher", "--new-startup" );
+ pid = launch( 2, "tdelauncher", "--new-startup" );
else
- pid = launch( 1, "klauncher", 0 );
+ pid = launch( 1, "tdelauncher", 0 );
#ifndef NDEBUG
fprintf(stderr, "[tdeinit] Launched KLauncher, pid = %ld result = %d\n", (long) pid, d.result);
#endif
- handle_requests(pid); // Wait for klauncher to be ready
+ handle_requests(pid); // Wait for tdelauncher to be ready
}
#if defined Q_WS_X11 && ! defined K_WS_QTONLY
diff --git a/kinit/kioslave.cpp b/kinit/kioslave.cpp
deleted file mode 100644
index 0cb77db02..000000000
--- a/kinit/kioslave.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (c) 1999-2000 Waldo Bastian <bastian@kde.org>
- * (c) 1999 Mario Weilguni <mweilguni@sime.com>
- * (c) 2001 Lubos Lunak <l.lunak@kde.org>
- *
- * $Id$
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <errno.h>
-
-#include <tqstring.h>
-
-#include "ltdl.h"
-
-#ifdef HAVE_DLFCN_H
-# include <dlfcn.h>
-#endif
-
-#ifdef RTLD_GLOBAL
-# define LTDL_GLOBAL RTLD_GLOBAL
-#else
-# ifdef DL_GLOBAL
-# define LTDL_GLOBAL DL_GLOBAL
-# else
-# define LTDL_GLOBAL 0
-# endif
-#endif
-
-/* These are to link libkio even if 'smart' linker is used */
-#include <kio/authinfo.h>
-extern "C" TDEIO::AuthInfo* _kioslave_init_kio() { return new TDEIO::AuthInfo(); }
-
-int main(int argc, char **argv)
-{
- if (argc < 5)
- {
- fprintf(stderr, "Usage: kioslave <slave-lib> <protocol> <klauncher-socket> <app-socket>\n\nThis program is part of TDE.\n");
- exit(1);
- }
- TQCString libpath = argv[1];
-
- if (libpath.isEmpty())
- {
- fprintf(stderr, "library path is empty.\n");
- exit(1);
- }
- lt_dlinit();
-
- lt_dlhandle handle = lt_dlopen( libpath.data() );
- if (!handle )
- {
- const char * ltdlError = lt_dlerror();
- fprintf(stderr, "could not open %s: %s", libpath.data(), ltdlError != 0 ? ltdlError : "(null)" );
- exit(1);
- }
-
- lt_ptr sym = lt_dlsym( handle, "kdemain");
- if (!sym )
- {
- sym = lt_dlsym( handle, "main");
- if (!sym )
- {
- const char * ltdlError = lt_dlerror();
- fprintf(stderr, "Could not find main: %s\n", ltdlError != 0 ? ltdlError : "(null)" );
- exit(1);
- }
- }
-
- int (*func)(int, char *[]) = (int (*)(int, char *[])) sym;
-
- exit( func(argc-1, argv+1)); /* Launch! */
-}
diff --git a/kinit/klauncher.cpp b/kinit/klauncher.cpp
deleted file mode 100644
index 8c66789e7..000000000
--- a/kinit/klauncher.cpp
+++ /dev/null
@@ -1,1421 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <stdio.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <signal.h>
-#include <sys/time.h>
-
-#include <tqfile.h>
-
-#include <kconfig.h>
-#include <kdebug.h>
-#include <klibloader.h>
-#include <klocale.h>
-#include <kprotocolmanager.h>
-#include <kprotocolinfo.h>
-#include <krun.h>
-#include <kstandarddirs.h>
-#include <ktempfile.h>
-#include <kurl.h>
-
-#if defined Q_WS_X11 && ! defined K_WS_QTONLY
-#include <kstartupinfo.h> // schroder
-#endif
-
-
-#include "kio/global.h"
-#include "kio/connection.h"
-#include "kio/slaveinterface.h"
-
-#include "klauncher.h"
-#include "klauncher_cmds.h"
-
-//#if defined Q_WS_X11 && ! defined K_WS_QTONLY
-#ifdef Q_WS_X11
-//#undef K_WS_QTONLY
-#include <X11/Xlib.h> // schroder
-#endif
-
-// Dispose slaves after being idle for SLAVE_MAX_IDLE seconds
-#define SLAVE_MAX_IDLE 30
-
-using namespace TDEIO;
-
-template class TQPtrList<KLaunchRequest>;
-template class TQPtrList<IdleSlave>;
-
-IdleSlave::IdleSlave(TDESocket *socket)
-{
- mConn.init(socket);
- mConn.connect(this, TQT_SLOT(gotInput()));
- mConn.send( CMD_SLAVE_STATUS );
- mPid = 0;
- mBirthDate = time(0);
- mOnHold = false;
-}
-
-void
-IdleSlave::gotInput()
-{
- int cmd;
- TQByteArray data;
- if (mConn.read( &cmd, data) == -1)
- {
- // Communication problem with slave.
- kdError(7016) << "SlavePool: No communication with slave." << endl;
- delete this;
- }
- else if (cmd == MSG_SLAVE_ACK)
- {
- delete this;
- }
- else if (cmd != MSG_SLAVE_STATUS)
- {
- kdError(7016) << "SlavePool: Unexpected data from slave." << endl;
- delete this;
- }
- else
- {
- TQDataStream stream( data, IO_ReadOnly );
- pid_t pid;
- TQCString protocol;
- TQString host;
- TQ_INT8 b;
- stream >> pid >> protocol >> host >> b;
-// Overload with (bool) onHold, (KURL) url.
- if (!stream.atEnd())
- {
- KURL url;
- stream >> url;
- mOnHold = true;
- mUrl = url;
- }
-
- mPid = pid;
- mConnected = (b != 0);
- mProtocol = protocol;
- mHost = host;
- emit statusUpdate(this);
- }
-}
-
-void
-IdleSlave::connect(const TQString &app_socket)
-{
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly);
- stream << app_socket;
- mConn.send( CMD_SLAVE_CONNECT, data );
- // Timeout!
-}
-
-void
-IdleSlave::reparseConfiguration()
-{
- mConn.send( CMD_REPARSECONFIGURATION );
-}
-
-bool
-IdleSlave::match(const TQString &protocol, const TQString &host, bool connected)
-{
- if (mOnHold) return false;
- if (protocol != mProtocol) return false;
- if (host.isEmpty()) return true;
- if (host != mHost) return false;
- if (!connected) return true;
- if (!mConnected) return false;
- return true;
-}
-
-bool
-IdleSlave::onHold(const KURL &url)
-{
- if (!mOnHold) return false;
- return (url == mUrl);
-}
-
-int
-IdleSlave::age(time_t now)
-{
- return (int) difftime(now, mBirthDate);
-}
-
-KLauncher::KLauncher(int _tdeinitSocket, bool new_startup)
-// : TDEApplication( false, false ), // No Styles, No GUI
- : TDEApplication( false, true ), // TQClipboard tries to construct a QWidget so a GUI is technically needed, even though it is not used
- DCOPObject("klauncher"),
- tdeinitSocket(_tdeinitSocket), mAutoStart( new_startup ),
- dontBlockReading(false), newStartup( new_startup )
-{
-#ifdef Q_WS_X11
- mCached_dpy = NULL;
-#endif
- connect(&mAutoTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotAutoStart()));
- requestList.setAutoDelete(true);
- mSlaveWaitRequest.setAutoDelete(true);
- dcopClient()->setNotifications( true );
- connect(dcopClient(), TQT_SIGNAL( applicationRegistered( const TQCString &)),
- this, TQT_SLOT( slotAppRegistered( const TQCString &)));
- dcopClient()->connectDCOPSignal( "DCOPServer", "", "terminateKDE()",
- objId(), "terminateKDE()", false );
-
- TQString prefix = locateLocal("socket", "klauncher");
- KTempFile domainname(prefix, TQString::fromLatin1(".slave-socket"));
- if (domainname.status() != 0)
- {
- // Sever error!
- tqDebug("KLauncher: Fatal error, can't create tempfile!");
- ::exit(1);
- }
- mPoolSocketName = domainname.name();
-#ifdef __CYGWIN__
- domainname.close();
- domainname.unlink();
-#endif
- mPoolSocket = new TDEServerSocket(static_cast<const char*>(TQFile::encodeName(mPoolSocketName)));
- connect(mPoolSocket, TQT_SIGNAL(accepted( TDESocket *)),
- TQT_SLOT(acceptSlave(TDESocket *)));
-
- connect(&mTimer, TQT_SIGNAL(timeout()), TQT_SLOT(idleTimeout()));
-
- tdeinitNotifier = new TQSocketNotifier(tdeinitSocket, TQSocketNotifier::Read);
- connect(tdeinitNotifier, TQT_SIGNAL( activated( int )),
- this, TQT_SLOT( slotKDEInitData( int )));
- tdeinitNotifier->setEnabled( true );
- lastRequest = 0;
- bProcessingQueue = false;
-
- mSlaveDebug = getenv("TDE_SLAVE_DEBUG_WAIT");
- if (!mSlaveDebug.isEmpty())
- {
- tqWarning("Klauncher running in slave-debug mode for slaves of protocol '%s'", mSlaveDebug.data());
- }
- mSlaveValgrind = getenv("TDE_SLAVE_VALGRIND");
- if (!mSlaveValgrind.isEmpty())
- {
- mSlaveValgrindSkin = getenv("TDE_SLAVE_VALGRIND_SKIN");
- tqWarning("Klauncher running slaves through valgrind for slaves of protocol '%s'", mSlaveValgrind.data());
- }
- klauncher_header request_header;
- request_header.cmd = LAUNCHER_OK;
- request_header.arg_length = 0;
- write(tdeinitSocket, &request_header, sizeof(request_header));
-}
-
-KLauncher::~KLauncher()
-{
- close();
-}
-
-void KLauncher::close()
-{
- if (!mPoolSocketName.isEmpty())
- {
- TQCString filename = TQFile::encodeName(mPoolSocketName);
- unlink(filename.data());
- }
-#if defined Q_WS_X11 && ! defined K_WS_QTONLY
-//#ifdef Q_WS_X11
- if( mCached_dpy != NULL )
- XCloseDisplay( mCached_dpy );
-#endif
-}
-
-void
-KLauncher::destruct(int exit_code)
-{
- if (kapp) ((KLauncher*)kapp)->close();
- // We don't delete kapp here, that's intentional.
- ::exit(exit_code);
-}
-
-bool
-KLauncher::process(const TQCString &fun, const TQByteArray &data,
- TQCString &replyType, TQByteArray &replyData)
-{
- if ((fun == "exec_blind(TQCString,TQValueList<TQCString>)")
- || (fun == "exec_blind(TQCString,TQValueList<TQCString>,TQValueList<TQCString>,TQCString)"))
- {
- TQDataStream stream(data, IO_ReadOnly);
- replyType = "void";
- TQCString name;
- TQValueList<TQCString> arg_list;
- TQCString startup_id = "0";
- TQValueList<TQCString> envs;
- stream >> name >> arg_list;
- if( fun == "exec_blind(TQCString,TQValueList<TQCString>,TQValueList<TQCString>,TQCString)" )
- stream >> envs >> startup_id;
- kdDebug(7016) << "KLauncher: Got exec_blind('" << name << "', ...)" << endl;
- exec_blind( name, arg_list, envs, startup_id);
- return true;
- }
- if ((fun == "start_service_by_name(TQString,TQStringList)") ||
- (fun == "start_service_by_desktop_path(TQString,TQStringList)")||
- (fun == "start_service_by_desktop_name(TQString,TQStringList)")||
- (fun == "tdeinit_exec(TQString,TQStringList)") ||
- (fun == "tdeinit_exec_wait(TQString,TQStringList)") ||
- (fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
- (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString)")||
- (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
- (fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)") ||
- (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)")||
- (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)") ||
- (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)") ||
- (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>)") ||
- (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
- (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
- {
- TQDataStream stream(data, IO_ReadOnly);
- bool bNoWait = false;
- TQString serviceName;
- TQStringList urls;
- TQValueList<TQCString> envs;
- TQCString startup_id = "";
- DCOPresult.result = -1;
- DCOPresult.dcopName = 0;
- DCOPresult.error = TQString::null;
- DCOPresult.pid = 0;
- stream >> serviceName >> urls;
- if ((fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)") ||
- (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)")||
- (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)"))
- stream >> envs >> startup_id >> bNoWait;
- else if ((fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
- (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString)")||
- (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
- stream >> envs >> startup_id;
- else if ((fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)") ||
- (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>)"))
- stream >> envs;
- else if ((fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
- (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
- stream >> envs >> startup_id;
- bool finished;
- if (strncmp(fun, "start_service_by_name(", 22) == 0)
- {
- kdDebug(7016) << "KLauncher: Got start_service_by_name('" << serviceName << "', ...)" << endl;
- finished = start_service_by_name(serviceName, urls, envs, startup_id, bNoWait);
- }
- else if (strncmp(fun, "start_service_by_desktop_path(", 30) == 0)
- {
- kdDebug(7016) << "KLauncher: Got start_service_by_desktop_path('" << serviceName << "', ...)" << endl;
- finished = start_service_by_desktop_path(serviceName, urls, envs, startup_id, bNoWait);
- }
- else if (strncmp(fun, "start_service_by_desktop_name(", 30) == 0)
- {
- kdDebug(7016) << "KLauncher: Got start_service_by_desktop_name('" << serviceName << "', ...)" << endl;
- finished = start_service_by_desktop_name(serviceName, urls, envs, startup_id, bNoWait );
- }
- else if ((fun == "tdeinit_exec(TQString,TQStringList)")
- || (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)")
- || (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
- {
- kdDebug(7016) << "KLauncher: Got tdeinit_exec('" << serviceName << "', ...)" << endl;
- finished = tdeinit_exec(serviceName, urls, envs, startup_id, false);
- }
- else
- {
- kdDebug(7016) << "KLauncher: Got tdeinit_exec_wait('" << serviceName << "', ...)" << endl;
- finished = tdeinit_exec(serviceName, urls, envs, startup_id, true);
- }
- if (!finished)
- {
- replyType = "serviceResult";
- TQDataStream stream2(replyData, IO_WriteOnly);
- stream2 << DCOPresult.result << DCOPresult.dcopName << DCOPresult.error << DCOPresult.pid;
- }
- return true;
- }
- else if (fun == "requestSlave(TQString,TQString,TQString)")
- {
- TQDataStream stream(data, IO_ReadOnly);
- TQString protocol;
- TQString host;
- TQString app_socket;
- stream >> protocol >> host >> app_socket;
- replyType = "TQString";
- TQString error;
- pid_t pid = requestSlave(protocol, host, app_socket, error);
- TQDataStream stream2(replyData, IO_WriteOnly);
- stream2 << pid << error;
- return true;
- }
- else if (fun == "requestHoldSlave(KURL,TQString)")
- {
- TQDataStream stream(data, IO_ReadOnly);
- KURL url;
- TQString app_socket;
- stream >> url >> app_socket;
- replyType = "pid_t";
- pid_t pid = requestHoldSlave(url, app_socket);
- TQDataStream stream2(replyData, IO_WriteOnly);
- stream2 << pid;
- return true;
- }
- else if (fun == "waitForSlave(pid_t)")
- {
- TQDataStream stream(data, IO_ReadOnly);
- pid_t pid;
- stream >> pid;
- waitForSlave(pid);
- replyType = "void";
- return true;
-
- }
- else if (fun == "setLaunchEnv(TQCString,TQCString)")
- {
- TQDataStream stream(data, IO_ReadOnly);
- TQCString name;
- TQCString value;
- stream >> name >> value;
- setLaunchEnv(name, value);
- replyType = "void";
- return true;
- }
- else if (fun == "reparseConfiguration()")
- {
- TDEGlobal::config()->reparseConfiguration();
- kdDebug(7016) << "KLauncher::process : reparseConfiguration" << endl;
- KProtocolManager::reparseConfiguration();
- IdleSlave *slave;
- for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
- slave->reparseConfiguration();
- replyType = "void";
- return true;
- }
- else if (fun == "terminateKDE()")
- {
- ::signal( SIGHUP, SIG_IGN);
- ::signal( SIGTERM, SIG_IGN);
- kdDebug() << "KLauncher::process ---> terminateKDE" << endl;
- klauncher_header request_header;
- request_header.cmd = LAUNCHER_TERMINATE_KDE;
- request_header.arg_length = 0;
- write(tdeinitSocket, &request_header, sizeof(request_header));
- destruct(0);
- }
- else if (fun == "autoStart()")
- {
- kdDebug() << "KLauncher::process ---> autoStart" << endl;
- autoStart(1);
- replyType = "void";
- return true;
- }
- else if (fun == "autoStart(int)")
- {
- kdDebug() << "KLauncher::process ---> autoStart(int)" << endl;
- TQDataStream stream(data, IO_ReadOnly);
- int phase;
- stream >> phase;
- autoStart(phase);
- replyType = "void";
- return true;
- }
-
- if (DCOPObject::process(fun, data, replyType, replyData))
- {
- return true;
- }
- kdWarning(7016) << "Got unknown DCOP function: " << fun << endl;
- return false;
-}
-
-QCStringList
-KLauncher::interfaces()
-{
- QCStringList ifaces = DCOPObject::interfaces();
- ifaces += "KLauncher";
- return ifaces;
-}
-
-QCStringList
-KLauncher::functions()
-{
- QCStringList funcs = DCOPObject::functions();
- funcs << "void exec_blind(TQCString,TQValueList<TQCString>)";
- funcs << "void exec_blind(TQCString,TQValueList<TQCString>,TQValueList<TQCString>,TQCString)";
- funcs << "serviceResult start_service_by_name(TQString,TQStringList)";
- funcs << "serviceResult start_service_by_desktop_path(TQString,TQStringList)";
- funcs << "serviceResult start_service_by_desktop_name(TQString,TQStringList)";
- funcs << "serviceResult tdeinit_exec(TQString,TQStringList)";
- funcs << "serviceResult tdeinit_exec_wait(TQString,TQStringList)";
- funcs << "serviceResult start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)";
- funcs << "serviceResult start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString)";
- funcs << "serviceResult start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)";
- funcs << "serviceResult start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)";
- funcs << "serviceResult start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)";
- funcs << "serviceResult start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)";
- funcs << "serviceResult tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)";
- funcs << "serviceResult tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>)";
- funcs << "TQString requestSlave(TQString,TQString,TQString)";
- funcs << "pid_t requestHoldSlave(KURL,TQString)";
- funcs << "void waitForSlave(pid_t)";
- funcs << "void setLaunchEnv(TQCString,TQCString)";
- funcs << "void reparseConfiguration()";
-// funcs << "void terminateKDE()";
- funcs << "void autoStart()";
- funcs << "void autoStart(int)";
- return funcs;
-}
-
-void KLauncher::setLaunchEnv(const TQCString &name, const TQCString &_value)
-{
- TQCString value(_value);
- if (value.isNull())
- value = "";
- klauncher_header request_header;
- TQByteArray requestData(name.length()+value.length()+2);
- memcpy(requestData.data(), name.data(), name.length()+1);
- memcpy(requestData.data()+name.length()+1, value.data(), value.length()+1);
- request_header.cmd = LAUNCHER_SETENV;
- request_header.arg_length = requestData.size();
- write(tdeinitSocket, &request_header, sizeof(request_header));
- write(tdeinitSocket, requestData.data(), request_header.arg_length);
-}
-
-/*
- * Read 'len' bytes from 'sock' into buffer.
- * returns -1 on failure, 0 on no data.
- */
-static int
-read_socket(int sock, char *buffer, int len)
-{
- ssize_t result;
- int bytes_left = len;
- while ( bytes_left > 0)
- {
- result = read(sock, buffer, bytes_left);
- if (result > 0)
- {
- buffer += result;
- bytes_left -= result;
- }
- else if (result == 0)
- return -1;
- else if ((result == -1) && (errno != EINTR))
- return -1;
- }
- return 0;
-}
-
-
-void
-KLauncher::slotKDEInitData(int)
-{
- klauncher_header request_header;
- TQByteArray requestData;
- if( dontBlockReading )
- {
- // in case we get a request to start an application and data arrive
- // to tdeinitSocket at the same time, requestStart() will already
- // call slotKDEInitData(), so we must check there's still something
- // to read, otherwise this would block
- fd_set in;
- timeval tm = { 0, 0 };
- FD_ZERO ( &in );
- FD_SET( tdeinitSocket, &in );
- select( tdeinitSocket + 1, &in, 0, 0, &tm );
- if( !FD_ISSET( tdeinitSocket, &in ))
- return;
- }
- dontBlockReading = false;
- int result = read_socket(tdeinitSocket, (char *) &request_header,
- sizeof( request_header));
- if (result == -1)
- {
- kdDebug() << "Exiting on read_socket errno: " << errno << endl;
- ::signal( SIGHUP, SIG_IGN);
- ::signal( SIGTERM, SIG_IGN);
- destruct(255); // Exit!
- }
- requestData.resize(request_header.arg_length);
- result = read_socket(tdeinitSocket, (char *) requestData.data(),
- request_header.arg_length);
-
- if (request_header.cmd == LAUNCHER_DIED)
- {
- long *request_data;
- request_data = (long *) requestData.data();
- processDied(request_data[0], request_data[1]);
- return;
- }
- if (lastRequest && (request_header.cmd == LAUNCHER_OK))
- {
- long *request_data;
- request_data = (long *) requestData.data();
- lastRequest->pid = (pid_t) (*request_data);
- kdDebug(7016) << lastRequest->name << " (pid " << lastRequest->pid <<
- ") up and running." << endl;
- switch(lastRequest->dcop_service_type)
- {
- case KService::DCOP_None:
- {
- lastRequest->status = KLaunchRequest::Running;
- break;
- }
-
- case KService::DCOP_Unique:
- {
- lastRequest->status = KLaunchRequest::Launching;
- break;
- }
-
- case KService::DCOP_Wait:
- {
- lastRequest->status = KLaunchRequest::Launching;
- break;
- }
-
- case KService::DCOP_Multi:
- {
- lastRequest->status = KLaunchRequest::Launching;
- break;
- }
- }
- lastRequest = 0;
- return;
- }
- if (lastRequest && (request_header.cmd == LAUNCHER_ERROR))
- {
- lastRequest->status = KLaunchRequest::Error;
- if (!requestData.isEmpty())
- lastRequest->errorMsg = TQString::fromUtf8((char *) requestData.data());
- lastRequest = 0;
- return;
- }
-
- kdWarning(7016) << "Unexpected command from KDEInit (" << (unsigned int) request_header.cmd
- << ")" << endl;
-}
-
-void
-KLauncher::processDied(pid_t pid, long /* exitStatus */)
-{
- KLaunchRequest *request = requestList.first();
- for(; request; request = requestList.next())
- {
- if (request->pid == pid)
- {
- if (request->dcop_service_type == KService::DCOP_Wait)
- request->status = KLaunchRequest::Done;
- else if ((request->dcop_service_type == KService::DCOP_Unique) &&
- (dcopClient()->isApplicationRegistered(request->dcop_name)))
- request->status = KLaunchRequest::Running;
- else
- request->status = KLaunchRequest::Error;
- requestDone(request);
- return;
- }
- }
-}
-
-void
-KLauncher::slotAppRegistered(const TQCString &appId)
-{
- const char *cAppId = appId.data();
- if (!cAppId) return;
-
- KLaunchRequest *request = requestList.first();
- KLaunchRequest *nextRequest;
- for(; request; request = nextRequest)
- {
- nextRequest = requestList.next();
- if (request->status != KLaunchRequest::Launching)
- continue;
-
- // For unique services check the requested service name first
- if ((request->dcop_service_type == KService::DCOP_Unique) &&
- ((appId == request->dcop_name) ||
- dcopClient()->isApplicationRegistered(request->dcop_name)))
- {
- request->status = KLaunchRequest::Running;
- requestDone(request);
- continue;
- }
-
- const char *rAppId = request->dcop_name.data();
- if (!rAppId) continue;
-
- int l = strlen(rAppId);
- if ((strncmp(rAppId, cAppId, l) == 0) &&
- ((cAppId[l] == '\0') || (cAppId[l] == '-')))
- {
- request->dcop_name = appId;
- request->status = KLaunchRequest::Running;
- requestDone(request);
- continue;
- }
- }
-}
-
-void
-KLauncher::autoStart(int phase)
-{
- if( mAutoStart.phase() >= phase )
- return;
- mAutoStart.setPhase(phase);
- if( newStartup )
- {
- if (phase == 0)
- mAutoStart.loadAutoStartList();
- }
- else
- {
- if (phase == 1)
- mAutoStart.loadAutoStartList();
- }
- mAutoTimer.start(0, true);
-}
-
-void
-KLauncher::slotAutoStart()
-{
- KService::Ptr s;
- do
- {
- TQString service = mAutoStart.startService();
- if (service.isEmpty())
- {
- // Done
- if( !mAutoStart.phaseDone())
- {
- mAutoStart.setPhaseDone();
- // Emit signal
- if( newStartup )
- {
- TQCString autoStartSignal;
- autoStartSignal.sprintf( "autoStart%dDone()", mAutoStart.phase());
- emitDCOPSignal(autoStartSignal, TQByteArray());
- }
- else
- {
- TQCString autoStartSignal( "autoStartDone()" );
- int phase = mAutoStart.phase();
- if ( phase > 1 )
- autoStartSignal.sprintf( "autoStart%dDone()", phase );
- emitDCOPSignal(autoStartSignal, TQByteArray());
- }
- }
- return;
- }
- s = new KService(service);
- }
- while (!start_service(s, TQStringList(), TQValueList<TQCString>(), "0", false, true));
- // Loop till we find a service that we can start.
-}
-
-void
-KLauncher::requestDone(KLaunchRequest *request)
-{
- if ((request->status == KLaunchRequest::Running) ||
- (request->status == KLaunchRequest::Done))
- {
- DCOPresult.result = 0;
- DCOPresult.dcopName = request->dcop_name;
- DCOPresult.error = TQString::null;
- DCOPresult.pid = request->pid;
- }
- else
- {
- DCOPresult.result = 1;
- DCOPresult.dcopName = "";
- DCOPresult.error = i18n("KDEInit could not launch '%1'.").arg(TQString(request->name));
- if (!request->errorMsg.isEmpty())
- DCOPresult.error += ":\n" + request->errorMsg;
- DCOPresult.pid = 0;
-
-#if defined Q_WS_X11 && ! defined K_WS_QTONLY
-//#ifdef Q_WS_X11
- if (!request->startup_dpy.isEmpty())
- {
- Display* dpy = NULL;
- if( (mCached_dpy != NULL) &&
- (request->startup_dpy == XDisplayString( mCached_dpy )))
- dpy = mCached_dpy;
- if( dpy == NULL )
- dpy = XOpenDisplay( request->startup_dpy );
- if( dpy )
- {
- KStartupInfoId id;
- id.initId( request->startup_id );
- KStartupInfo::sendFinishX( dpy, id );
- if( mCached_dpy != dpy && mCached_dpy != NULL )
- XCloseDisplay( mCached_dpy );
- mCached_dpy = dpy;
- }
- }
-#endif
- }
-
- if (request->autoStart)
- {
- mAutoTimer.start(0, true);
- }
-
- if (request->transaction)
- {
- TQByteArray replyData;
- TQCString replyType;
- replyType = "serviceResult";
- TQDataStream stream2(replyData, IO_WriteOnly);
- stream2 << DCOPresult.result << DCOPresult.dcopName << DCOPresult.error << DCOPresult.pid;
- dcopClient()->endTransaction( request->transaction,
- replyType, replyData);
- }
- requestList.removeRef( request );
-}
-
-void
-KLauncher::requestStart(KLaunchRequest *request)
-{
- requestList.append( request );
- // Send request to tdeinit.
- klauncher_header request_header;
- TQByteArray requestData;
- int length = 0;
- length += sizeof(long); // Nr of. Args
- length += request->name.length() + 1; // Cmd
- for(TQValueList<TQCString>::Iterator it = request->arg_list.begin();
- it != request->arg_list.end();
- it++)
- {
- length += (*it).length() + 1; // Args...
- }
- length += sizeof(long); // Nr of. envs
- for(TQValueList<TQCString>::ConstIterator it = request->envs.begin();
- it != request->envs.end();
- it++)
- {
- length += (*it).length() + 1; // Envs...
- }
- length += sizeof( long ); // avoid_loops
-#ifdef Q_WS_X11
- bool startup_notify = !request->startup_id.isNull() && request->startup_id != "0";
- if( startup_notify )
- length += request->startup_id.length() + 1;
-#endif
- if (!request->cwd.isEmpty())
- length += request->cwd.length() + 1;
-
- requestData.resize( length );
-
- char *p = requestData.data();
- long l = request->arg_list.count()+1;
- memcpy(p, &l, sizeof(long));
- p += sizeof(long);
- strcpy(p, request->name.data());
- p += strlen(p) + 1;
- for(TQValueList<TQCString>::Iterator it = request->arg_list.begin();
- it != request->arg_list.end();
- it++)
- {
- strcpy(p, (*it).data());
- p += strlen(p) + 1;
- }
- l = request->envs.count();
- memcpy(p, &l, sizeof(long));
- p += sizeof(long);
- for(TQValueList<TQCString>::ConstIterator it = request->envs.begin();
- it != request->envs.end();
- it++)
- {
- strcpy(p, (*it).data());
- p += strlen(p) + 1;
- }
- l = 0; // avoid_loops, always false here
- memcpy(p, &l, sizeof(long));
- p += sizeof(long);
-#ifdef Q_WS_X11
- if( startup_notify )
- {
- strcpy(p, request->startup_id.data());
- p += strlen( p ) + 1;
- }
-#endif
- if (!request->cwd.isEmpty())
- {
- strcpy(p, request->cwd.data());
- p += strlen( p ) + 1;
- }
-#ifdef Q_WS_X11
- request_header.cmd = startup_notify ? LAUNCHER_EXT_EXEC : LAUNCHER_EXEC_NEW;
-#else
- request_header.cmd = LAUNCHER_EXEC_NEW;
-#endif
- request_header.arg_length = length;
- write(tdeinitSocket, &request_header, sizeof(request_header));
- write(tdeinitSocket, requestData.data(), request_header.arg_length);
-
- // Wait for pid to return.
- lastRequest = request;
- dontBlockReading = false;
- do {
- slotKDEInitData( tdeinitSocket );
- }
- while (lastRequest != 0);
- dontBlockReading = true;
-}
-
-void
-KLauncher::exec_blind( const TQCString &name, const TQValueList<TQCString> &arg_list,
- const TQValueList<TQCString> &envs, const TQCString& startup_id )
-{
- KLaunchRequest *request = new KLaunchRequest;
- request->autoStart = false;
- request->name = name;
- request->arg_list = arg_list;
- request->dcop_name = 0;
- request->dcop_service_type = KService::DCOP_None;
- request->pid = 0;
- request->status = KLaunchRequest::Launching;
- request->transaction = 0; // No confirmation is send
- request->envs = envs;
- // Find service, if any - strip path if needed
- KService::Ptr service = KService::serviceByDesktopName( name.mid( name.findRev( '/' ) + 1 ));
- if (service != NULL)
- send_service_startup_info( request, service,
- startup_id, TQValueList< TQCString >());
- else // no .desktop file, no startup info
- cancel_service_startup_info( request, startup_id, envs );
-
- requestStart(request);
- // We don't care about this request any longer....
- requestDone(request);
-}
-
-
-bool
-KLauncher::start_service_by_name(const TQString &serviceName, const TQStringList &urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind)
-{
- KService::Ptr service = 0;
- // Find service
- service = KService::serviceByName(serviceName);
- if (!service)
- {
- DCOPresult.result = ENOENT;
- DCOPresult.error = i18n("Could not find service '%1'.").arg(serviceName);
- cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
- return false;
- }
- return start_service(service, urls, envs, startup_id, blind);
-}
-
-bool
-KLauncher::start_service_by_desktop_path(const TQString &serviceName, const TQStringList &urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind)
-{
- KService::Ptr service = 0;
- // Find service
- if (serviceName[0] == '/')
- {
- // Full path
- service = new KService(serviceName);
- }
- else
- {
- service = KService::serviceByDesktopPath(serviceName);
- }
- if (!service)
- {
- DCOPresult.result = ENOENT;
- DCOPresult.error = i18n("Could not find service '%1'.").arg(serviceName);
- cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
- return false;
- }
- return start_service(service, urls, envs, startup_id, blind);
-}
-
-bool
-KLauncher::start_service_by_desktop_name(const TQString &serviceName, const TQStringList &urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind)
-{
- KService::Ptr service = 0;
- // Find service
- service = KService::serviceByDesktopName(serviceName);
- if (!service)
- {
- DCOPresult.result = ENOENT;
- DCOPresult.error = i18n("Could not find service '%1'.").arg(serviceName);
- cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
- return false;
- }
- return start_service(service, urls, envs, startup_id, blind);
-}
-
-bool
-KLauncher::start_service(KService::Ptr service, const TQStringList &_urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind, bool autoStart)
-{
- TQStringList urls = _urls;
- if (!service->isValid())
- {
- DCOPresult.result = ENOEXEC;
- DCOPresult.error = i18n("Service '%1' is malformatted.").arg(service->desktopEntryPath());
- cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
- return false;
- }
- KLaunchRequest *request = new KLaunchRequest;
- request->autoStart = autoStart;
-
- if ((urls.count() > 1) && !service->allowMultipleFiles())
- {
- // We need to launch the application N times. That sucks.
- // We ignore the result for application 2 to N.
- // For the first file we launch the application in the
- // usual way. The reported result is based on this
- // application.
- TQStringList::ConstIterator it = urls.begin();
- for(++it;
- it != urls.end();
- ++it)
- {
- TQStringList singleUrl;
- singleUrl.append(*it);
- TQCString startup_id2 = startup_id;
- if( !startup_id2.isEmpty() && startup_id2 != "0" )
- startup_id2 = "0"; // can't use the same startup_id several times
- start_service( service, singleUrl, envs, startup_id2, true);
- }
- TQString firstURL = *(urls.begin());
- urls.clear();
- urls.append(firstURL);
- }
- createArgs(request, service, urls);
-
- // We must have one argument at least!
- if (!request->arg_list.count())
- {
- DCOPresult.result = ENOEXEC;
- DCOPresult.error = i18n("Service '%1' is malformatted.").arg(service->desktopEntryPath());
- delete request;
- cancel_service_startup_info( NULL, startup_id, envs );
- return false;
- }
-
- request->name = request->arg_list.first();
- request->arg_list.remove(request->arg_list.begin());
-
- request->dcop_service_type = service->DCOPServiceType();
-
- if ((request->dcop_service_type == KService::DCOP_Unique) ||
- (request->dcop_service_type == KService::DCOP_Multi))
- {
- TQVariant v = service->property("X-DCOP-ServiceName");
- if (v.isValid())
- request->dcop_name = v.toString().utf8();
- if (request->dcop_name.isEmpty())
- {
- request->dcop_name = TQFile::encodeName(KRun::binaryName(service->exec(), true));
- }
- }
-
- request->pid = 0;
- request->transaction = 0;
- request->envs = envs;
- send_service_startup_info( request, service, startup_id, envs );
-
- // Request will be handled later.
- if (!blind && !autoStart)
- {
- request->transaction = dcopClient()->beginTransaction();
- }
- queueRequest(request);
- return true;
-}
-
-void
-KLauncher::send_service_startup_info( KLaunchRequest *request, KService::Ptr service, const TQCString& startup_id,
- const TQValueList<TQCString> &envs )
-{
-#if defined Q_WS_X11 && ! defined K_WS_QTONLY
-//#ifdef Q_WS_X11 // KStartup* isn't implemented for Qt/Embedded yet
- request->startup_id = "0";
- if( startup_id == "0" )
- return;
- bool silent;
- TQCString wmclass;
- if( !KRun::checkStartupNotify( TQString::null, service, &silent, &wmclass ))
- return;
- KStartupInfoId id;
- id.initId( startup_id );
- const char* dpy_str = NULL;
- for( TQValueList<TQCString>::ConstIterator it = envs.begin();
- it != envs.end();
- ++it )
- if( strncmp( *it, "DISPLAY=", 8 ) == 0 )
- dpy_str = static_cast< const char* >( *it ) + 8;
- Display* dpy = NULL;
- if( dpy_str != NULL && mCached_dpy != NULL
- && qstrcmp( dpy_str, XDisplayString( mCached_dpy )) == 0 )
- dpy = mCached_dpy;
- if( dpy == NULL )
- dpy = XOpenDisplay( dpy_str );
- request->startup_id = id.id();
- if( dpy == NULL )
- {
- cancel_service_startup_info( request, startup_id, envs );
- return;
- }
-
- request->startup_dpy = dpy_str;
-
- KStartupInfoData data;
- data.setName( service->name());
- data.setIcon( service->icon());
- data.setDescription( i18n( "Launching %1" ).arg( service->name()));
- if( !wmclass.isEmpty())
- data.setWMClass( wmclass );
- if( silent )
- data.setSilent( KStartupInfoData::Yes );
- // the rest will be sent by tdeinit
- KStartupInfo::sendStartupX( dpy, id, data );
- if( mCached_dpy != dpy && mCached_dpy != NULL )
- XCloseDisplay( mCached_dpy );
- mCached_dpy = dpy;
- return;
-#else
- return;
-#endif
-}
-
-void
-KLauncher::cancel_service_startup_info( KLaunchRequest* request, const TQCString& startup_id,
- const TQValueList<TQCString> &envs )
-{
-#if defined Q_WS_X11 && ! defined K_WS_QTONLY
-//#ifdef Q_WS_X11 // KStartup* isn't implemented for Qt/Embedded yet
- if( request != NULL )
- request->startup_id = "0";
- if( !startup_id.isEmpty() && startup_id != "0" )
- {
- const char* dpy_str = NULL;
- for( TQValueList<TQCString>::ConstIterator it = envs.begin();
- it != envs.end();
- ++it )
- if( strncmp( *it, "DISPLAY=", 8 ) == 0 )
- dpy_str = static_cast< const char* >( *it ) + 8;
- Display* dpy = NULL;
- if( dpy_str != NULL && mCached_dpy != NULL
- && qstrcmp( dpy_str, XDisplayString( mCached_dpy )) == 0 )
- dpy = mCached_dpy;
- if( dpy == NULL )
- dpy = XOpenDisplay( dpy_str );
- if( dpy == NULL )
- return;
- KStartupInfoId id;
- id.initId( startup_id );
- KStartupInfo::sendFinishX( dpy, id );
- if( mCached_dpy != dpy && mCached_dpy != NULL )
- XCloseDisplay( mCached_dpy );
- mCached_dpy = dpy;
- }
-#endif
-}
-
-bool
-KLauncher::tdeinit_exec(const TQString &app, const TQStringList &args,
- const TQValueList<TQCString> &envs, TQCString startup_id, bool wait)
-{
- KLaunchRequest *request = new KLaunchRequest;
- request->autoStart = false;
-
- for(TQStringList::ConstIterator it = args.begin();
- it != args.end();
- it++)
- {
- TQString arg = *it;
- request->arg_list.append(arg.local8Bit());
- }
-
- request->name = app.local8Bit();
-
- if (wait)
- request->dcop_service_type = KService::DCOP_Wait;
- else
- request->dcop_service_type = KService::DCOP_None;
- request->dcop_name = 0;
- request->pid = 0;
-#ifdef Q_WS_X11
- request->startup_id = startup_id;
-#endif
- request->envs = envs;
- if( app != "kbuildsycoca" ) // avoid stupid loop
- {
- // Find service, if any - strip path if needed
- KService::Ptr service = KService::serviceByDesktopName( app.mid( app.findRev( '/' ) + 1 ));
- if (service != NULL)
- send_service_startup_info( request, service,
- startup_id, TQValueList< TQCString >());
- else // no .desktop file, no startup info
- cancel_service_startup_info( request, startup_id, envs );
- }
- request->transaction = dcopClient()->beginTransaction();
- queueRequest(request);
- return true;
-}
-
-void
-KLauncher::queueRequest(KLaunchRequest *request)
-{
- requestQueue.append( request );
- if (!bProcessingQueue)
- {
- bProcessingQueue = true;
- TQTimer::singleShot(0, this, TQT_SLOT( slotDequeue() ));
- }
-}
-
-void
-KLauncher::slotDequeue()
-{
- do {
- KLaunchRequest *request = requestQueue.take(0);
- // process request
- request->status = KLaunchRequest::Launching;
- requestStart(request);
- if (request->status != KLaunchRequest::Launching)
- {
- // Request handled.
- requestDone( request );
- continue;
- }
- } while(requestQueue.count());
- bProcessingQueue = false;
-}
-
-void
-KLauncher::createArgs( KLaunchRequest *request, const KService::Ptr service ,
- const TQStringList &urls)
-{
- TQStringList params = KRun::processDesktopExec(*service, urls, false);
-
- for(TQStringList::ConstIterator it = params.begin();
- it != params.end(); ++it)
- {
- request->arg_list.append((*it).local8Bit());
- }
- request->cwd = TQFile::encodeName(service->path());
-}
-
-///// IO-Slave functions
-
-pid_t
-KLauncher::requestHoldSlave(const KURL &url, const TQString &app_socket)
-{
- IdleSlave *slave;
- for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
- {
- if (slave->onHold(url))
- break;
- }
- if (slave)
- {
- mSlaveList.removeRef(slave);
- slave->connect(app_socket);
- return slave->pid();
- }
- return 0;
-}
-
-
-pid_t
-KLauncher::requestSlave(const TQString &protocol,
- const TQString &host,
- const TQString &app_socket,
- TQString &error)
-{
- IdleSlave *slave;
- for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
- {
- if (slave->match(protocol, host, true))
- break;
- }
- if (!slave)
- {
- for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
- {
- if (slave->match(protocol, host, false))
- break;
- }
- }
- if (!slave)
- {
- for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
- {
- if (slave->match(protocol, TQString::null, false))
- break;
- }
- }
- if (slave)
- {
- mSlaveList.removeRef(slave);
- slave->connect(app_socket);
- return slave->pid();
- }
-
- TQString _name = KProtocolInfo::exec(protocol);
- if (_name.isEmpty())
- {
- error = i18n("Unknown protocol '%1'.\n").arg(protocol);
- return 0;
- }
-
- TQCString name = _name.latin1(); // ex: "kio_ftp"
- TQCString arg1 = protocol.latin1();
- TQCString arg2 = TQFile::encodeName(mPoolSocketName);
- TQCString arg3 = TQFile::encodeName(app_socket);
- TQValueList<TQCString> arg_list;
- arg_list.append(arg1);
- arg_list.append(arg2);
- arg_list.append(arg3);
-
-// kdDebug(7016) << "KLauncher: launching new slave " << _name << " with protocol=" << protocol << endl;
- if (mSlaveDebug == arg1)
- {
- klauncher_header request_header;
- request_header.cmd = LAUNCHER_DEBUG_WAIT;
- request_header.arg_length = 0;
- write(tdeinitSocket, &request_header, sizeof(request_header));
- }
- if (mSlaveValgrind == arg1)
- {
- arg_list.prepend(TQFile::encodeName(KLibLoader::findLibrary(name)));
- arg_list.prepend(TQFile::encodeName(locate("exe", "kioslave")));
- name = "valgrind";
- if (!mSlaveValgrindSkin.isEmpty()) {
- arg_list.prepend(TQCString("--tool=") + mSlaveValgrindSkin);
- } else
- arg_list.prepend("--tool=memcheck");
- }
-
- KLaunchRequest *request = new KLaunchRequest;
- request->autoStart = false;
- request->name = name;
- request->arg_list = arg_list;
- request->dcop_name = 0;
- request->dcop_service_type = KService::DCOP_None;
- request->pid = 0;
-#ifdef Q_WS_X11
- request->startup_id = "0";
-#endif
- request->status = KLaunchRequest::Launching;
- request->transaction = 0; // No confirmation is send
- requestStart(request);
- pid_t pid = request->pid;
-
-// kdDebug(7016) << "Slave launched, pid = " << pid << endl;
-
- // We don't care about this request any longer....
- requestDone(request);
- if (!pid)
- {
- error = i18n("Error loading '%1'.\n").arg(TQString(name));
- }
- return pid;
-}
-
-void
-KLauncher::waitForSlave(pid_t pid)
-{
- IdleSlave *slave;
- for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
- {
- if (slave->pid() == pid)
- return; // Already here.
- }
- SlaveWaitRequest *waitRequest = new SlaveWaitRequest;
- waitRequest->transaction = dcopClient()->beginTransaction();
- waitRequest->pid = pid;
- mSlaveWaitRequest.append(waitRequest);
-}
-
-void
-KLauncher::acceptSlave(TDESocket *slaveSocket)
-{
- IdleSlave *slave = new IdleSlave(slaveSocket);
- // Send it a SLAVE_STATUS command.
- mSlaveList.append(slave);
- connect(slave, TQT_SIGNAL(destroyed()), this, TQT_SLOT(slotSlaveGone()));
- connect(slave, TQT_SIGNAL(statusUpdate(IdleSlave *)),
- this, TQT_SLOT(slotSlaveStatus(IdleSlave *)));
- if (!mTimer.isActive())
- {
- mTimer.start(1000*10);
- }
-}
-
-void
-KLauncher::slotSlaveStatus(IdleSlave *slave)
-{
- SlaveWaitRequest *waitRequest = mSlaveWaitRequest.first();
- while(waitRequest)
- {
- if (waitRequest->pid == slave->pid())
- {
- TQByteArray replyData;
- TQCString replyType;
- replyType = "void";
- dcopClient()->endTransaction( waitRequest->transaction, replyType, replyData);
- mSlaveWaitRequest.removeRef(waitRequest);
- waitRequest = mSlaveWaitRequest.current();
- }
- else
- {
- waitRequest = mSlaveWaitRequest.next();
- }
- }
-}
-
-void
-KLauncher::slotSlaveGone()
-{
- IdleSlave *slave = (IdleSlave *) sender();
- mSlaveList.removeRef(slave);
- if ((mSlaveList.count() == 0) && (mTimer.isActive()))
- {
- mTimer.stop();
- }
-}
-
-void
-KLauncher::idleTimeout()
-{
- bool keepOneFileSlave=true;
- time_t now = time(0);
- IdleSlave *slave;
- for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
- {
- if ((slave->protocol()=="file") && (keepOneFileSlave))
- keepOneFileSlave=false;
- else if (slave->age(now) > SLAVE_MAX_IDLE)
- {
- // killing idle slave
- delete slave;
- }
- }
-}
-
-#include "klauncher.moc"
diff --git a/kinit/klauncher.h b/kinit/klauncher.h
deleted file mode 100644
index 37b10f059..000000000
--- a/kinit/klauncher.h
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KLAUNCHER_H_
-#define _KLAUNCHER_H_
-
-#include <sys/types.h>
-#include <unistd.h>
-#include <time.h>
-#include <tqstring.h>
-#include <tqvaluelist.h>
-#include <tqsocketnotifier.h>
-#include <tqptrlist.h>
-#include <tqtimer.h>
-
-#include <dcopclient.h>
-#include <kio/connection.h>
-#include <ksock.h>
-#include <kurl.h>
-#include <kuniqueapplication.h>
-
-#include <kservice.h>
-
-#include "autostart.h"
-
-class IdleSlave : public TQObject
-{
- Q_OBJECT
-public:
- IdleSlave(TDESocket *socket);
- bool match( const TQString &protocol, const TQString &host, bool connected);
- void connect( const TQString &app_socket);
- pid_t pid() const { return mPid;}
- int age(time_t now);
- void reparseConfiguration();
- bool onHold(const KURL &url);
- TQString protocol() const {return mProtocol;}
-
-signals:
- void statusUpdate(IdleSlave *);
-
-protected slots:
- void gotInput();
-
-protected:
- TDEIO::Connection mConn;
- TQString mProtocol;
- TQString mHost;
- bool mConnected;
- pid_t mPid;
- time_t mBirthDate;
- bool mOnHold;
- KURL mUrl;
-};
-
-class SlaveWaitRequest
-{
-public:
- pid_t pid;
- DCOPClientTransaction *transaction;
-};
-
-class KLaunchRequest
-{
-public:
- TQCString name;
- TQValueList<TQCString> arg_list;
- TQCString dcop_name;
- enum status_t { Init = 0, Launching, Running, Error, Done };
- pid_t pid;
- status_t status;
- DCOPClientTransaction *transaction;
- KService::DCOPServiceType_t dcop_service_type;
- bool autoStart;
- TQString errorMsg;
-#ifdef Q_WS_X11
- TQCString startup_id; // "" is the default, "0" for none
- TQCString startup_dpy; // Display to send startup notification to.
-#endif
- TQValueList<TQCString> envs; // env. variables to be app's environment
- TQCString cwd;
-};
-
-struct serviceResult
-{
- int result; // 0 means success. > 0 means error (-1 means pending)
- TQCString dcopName; // Contains DCOP name on success
- TQString error; // Contains error description on failure.
- pid_t pid;
-};
-
-class KLauncher : public TDEApplication, public DCOPObject
-{
- Q_OBJECT
-
-public:
- KLauncher(int _tdeinitSocket, bool new_startup);
-
- ~KLauncher();
-
- void close();
- static void destruct(int exit_code); // exit!
-
- // DCOP
- virtual bool process(const TQCString &fun, const TQByteArray &data,
- TQCString &replyType, TQByteArray &replyData);
- virtual QCStringList functions();
- virtual QCStringList interfaces();
-
-protected:
- void processDied(pid_t pid, long exitStatus);
-
- void requestStart(KLaunchRequest *request);
- void requestDone(KLaunchRequest *request);
-
- void setLaunchEnv(const TQCString &name, const TQCString &value);
- void exec_blind(const TQCString &name, const TQValueList<TQCString> &arg_list,
- const TQValueList<TQCString> &envs, const TQCString& startup_id = "" );
- bool start_service(KService::Ptr service, const TQStringList &urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id = "",
- bool blind = false, bool autoStart = false );
- bool start_service_by_name(const TQString &serviceName, const TQStringList &urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind);
- bool start_service_by_desktop_path(const TQString &serviceName, const TQStringList &urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind);
- bool start_service_by_desktop_name(const TQString &serviceName, const TQStringList &urls,
- const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind);
- bool tdeinit_exec(const TQString &app, const TQStringList &args,
- const TQValueList<TQCString> &envs, TQCString startup_id, bool wait);
-
- void waitForSlave(pid_t pid);
-
- void autoStart(int phase);
-
- void createArgs( KLaunchRequest *request, const KService::Ptr service,
- const TQStringList &url);
-
- pid_t requestHoldSlave(const KURL &url, const TQString &app_socket);
- pid_t requestSlave(const TQString &protocol, const TQString &host,
- const TQString &app_socket, TQString &error);
-
-
- void queueRequest(KLaunchRequest *);
-
- void send_service_startup_info( KLaunchRequest *request, KService::Ptr service, const TQCString& startup_id,
- const TQValueList<TQCString> &envs );
- void cancel_service_startup_info( KLaunchRequest *request, const TQCString& startup_id,
- const TQValueList<TQCString> &envs );
-
-public slots:
- void slotAutoStart();
- void slotDequeue();
- void slotKDEInitData(int);
- void slotAppRegistered(const TQCString &appId);
- void slotSlaveStatus(IdleSlave *);
- void acceptSlave( TDESocket *);
- void slotSlaveGone();
- void idleTimeout();
-
-protected:
- TQPtrList<KLaunchRequest> requestList; // Requests being handled
- TQPtrList<KLaunchRequest> requestQueue; // Requests waiting to being handled
- int tdeinitSocket;
- TQSocketNotifier *tdeinitNotifier;
- serviceResult DCOPresult;
- KLaunchRequest *lastRequest;
- TQPtrList<SlaveWaitRequest> mSlaveWaitRequest;
- TQString mPoolSocketName;
- TDEServerSocket *mPoolSocket;
- TQPtrList<IdleSlave> mSlaveList;
- TQTimer mTimer;
- TQTimer mAutoTimer;
- bool bProcessingQueue;
- AutoStart mAutoStart;
- TQCString mSlaveDebug;
- TQCString mSlaveValgrind;
- TQCString mSlaveValgrindSkin;
- bool dontBlockReading;
- bool newStartup;
-#ifdef Q_WS_X11
- Display *mCached_dpy;
-#endif
-};
-#endif
diff --git a/kinit/klauncher_cmds.h b/kinit/klauncher_cmds.h
deleted file mode 100644
index 54b13f45a..000000000
--- a/kinit/klauncher_cmds.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KLAUNCHER_CMDS_H_
-#define _KLAUNCHER_CMDS_H_
-
-typedef struct
-{
- long cmd;
- long arg_length;
-} klauncher_header;
-
-/* Launcher commands: */
-
-#define LAUNCHER_EXEC 1
-/*
- * LAUNCHER_EXEC
- *
- * Start a new process. Try using LAUNCHER_EXEC_NEW instead.
- * There will be no app startup notification.
- *
- * long argc: number of arguments
- * char *args: arguments, argument 0 is the program to start.
- */
-
-
-#define LAUNCHER_SETENV 2
-/*
- * LAUNCHER_SETENV
- *
- * Change environment of future processes launched via tdeinit.
- * DON'T use this if you want to change environment only for one
- * application you're going to start.
- *
- * char *env_name;
- * char *env_value;
- */
-
-#define LAUNCHER_DIED 3
-/*
- * LAUNCHER_DIED
- *
- * Notification A child of tdeinit died.
- *
- * long pid;
- * long exit_code;
- */
-
-#define LAUNCHER_OK 4
-/*
- * LAUNCHER_OK
- *
- * Notification Last process launched ok.
- *
- * long pid;
- */
-
-#define LAUNCHER_ERROR 5
-/*
- * LAUNCHER_ERROR
- *
- * Notification Last process could not be launched.
- *
- * char *error msg (utf8)
- */
-
-#define LAUNCHER_SHELL 6
-/*
- * LAUNCHER_SHELL
- *
- * Start a new process and use given environment.
- * Starts app-startup notification.
- *
- * long argc: number of arguments
- * char *args: arguments, argument 0 is the program to start.
- * char *cwd: Working directory.
- * long envc: number of environment vars
- * char *envs: environment strings.
- * int avoid_loops : avoid using the first path in $PATH where
- * this process binary is found in order to avoid
- * infinite loop by binary->tdeinit_wrapper link in $PATH
- * char* startup_id: app startup notification id, "0" for none,
- * "" ( empty string ) is the default
- */
-
-#define LAUNCHER_TERMINATE_KDE 7
-
-/*
- * LAUNCHER_TERMINATE_TDEINIT
- *
- * Suicide is painless
- */
-#define LAUNCHER_TERMINATE_TDEINIT 8
-
-#define LAUNCHER_DEBUG_WAIT 9
-/*
- * LAUNCHER_DEBUG_WAIT
- *
- * Next process started will do a sleep(1000000)
- * before calling main()/kdemain()
- *
- * (Used for debugging io-slaves)
- */
-
-#define LAUNCHER_EXT_EXEC 10
-/*
- * LAUNCHER_EXT_EXEC
- *
- * Start a new process. The given environment variables will
- * be added to its environment before starting it.
- * Starts app-startup notification.
- *
- * long argc: number of arguments
- * char *args: arguments, argument 0 is the program to start.
- * long envc: number of environment vars
- * char *envs: environment strings.
- * int avoid_loops : avoid using the first path in $PATH where
- * this process binary is found in order to avoid
- * infinite loop by binary->tdeinit_wrapper link in $PATH
- * char* startup_id: app startup notification id, "0" for none,
- * "" ( empty string ) is the default
- *
- */
-
-
-#define LAUNCHER_KWRAPPER 11
-/*
- * LAUNCHER_KWRAPPER
- *
- * Start a new process, use given environment, pass signals and output.
- * Starts app-startup notification.
- *
- * long argc: number of arguments
- * char *args: arguments, argument 0 is the program to start.
- * char *cwd: Working directory.
- * long envc: number of environment vars
- * char *envs: environment strings.
- * char *tty: tty to redirect stdout/stderr to.
- * int avoid_loops : avoid using the first path in $PATH where
- * this process binary is found in order to avoid
- * infinite loop by binary->tdeinit_wrapper link in $PATH
- * char* startup_id: app startup notification id, "0" for none,
- * "" ( empty string ) is the default
- */
-
-#define LAUNCHER_EXEC_NEW 12
-/*
- * LAUNCHER_EXEC_NEW
- *
- * Start a new process. An improved version of LAUNCHER_EXEC.
- * The given environment variables will be added
- * to its environment before starting it.
- * There will be no app startup notification.
- *
- * long argc: number of arguments
- * char *args: arguments, argument 0 is the program to start.
- * long envc: number of environment vars
- * char *envs: environment strings.
- * int avoid_loops : avoid using the first path in $PATH where
- * this process binary is found in order to avoid
- * infinite loop by binary->tdeinit_wrapper link in $PATH
- */
-
-#define LAUNCHER_FD 42
-/*
- * File descriptor to use for communication with tdeinit.
- */
-
-#endif
diff --git a/kinit/klauncher_main.cpp b/kinit/klauncher_main.cpp
deleted file mode 100644
index f22da9386..000000000
--- a/kinit/klauncher_main.cpp
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "config.h"
-
-#include <unistd.h>
-#include <fcntl.h>
-
-#include "kapplication.h"
-#include "klauncher.h"
-#include "kcmdlineargs.h"
-#include "kcrash.h"
-#include "kdebug.h"
-#include <stdio.h>
-#include <stdlib.h>
-#include <signal.h>
-#include <tqcstring.h>
-#include <klocale.h>
-
-#include "klauncher_cmds.h"
-
-static void sig_handler(int sig_num)
-{
- // No recursion
- signal( SIGHUP, SIG_IGN);
- signal( SIGTERM, SIG_IGN);
- fprintf(stderr, "[klauncher] Exiting on signal %d\n", sig_num);
- KLauncher::destruct(255);
-}
-
-static KCmdLineOptions options[] =
-{
- { "new-startup", "Internal", 0 },
- KCmdLineLastOption
-};
-
-extern "C" KDE_EXPORT int kdemain( int argc, char**argv )
-{
- // Started via tdeinit.
- if (fcntl(LAUNCHER_FD, F_GETFD) == -1)
- {
- fprintf(stderr, "%s", i18n("[klauncher] This program is not supposed to be started manually.\n"
- "[klauncher] It is started automatically by tdeinit.\n").local8Bit().data());
- return 1;
- }
-
- TQCString cname = TDEApplication::launcher();
- char *name = cname.data();
- TDECmdLineArgs::init(argc, argv, name, "KLauncher", "A service launcher.",
- "v1.0");
-
- KLauncher::addCmdLineOptions();
- TDECmdLineArgs::addCmdLineOptions( options );
-
- // WABA: Make sure not to enable session management.
- putenv(strdup("SESSION_MANAGER="));
-
- // Allow the locale to initialize properly
- KLocale::setMainCatalogue("tdelibs");
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- int maxTry = 3;
- while(true)
- {
- TQCString dcopName = TDEApplication::dcopClient()->registerAs(name, false);
- if (dcopName.isEmpty())
- {
- kdWarning() << "[klauncher] DCOP communication problem!" << endl;
- return 1;
- }
- if (dcopName == cname)
- break; // Good!
-
- if (--maxTry == 0)
- {
- kdWarning() << "[klauncher] Another instance of klauncher is already running!" << endl;
- return 1;
- }
-
- // Wait a bit...
- kdWarning() << "[klauncher] Waiting for already running klauncher to exit." << endl;
- sleep(1);
-
- // Try again...
- }
-
- KLauncher *launcher = new KLauncher(LAUNCHER_FD, args->isSet("new-startup"));
- launcher->dcopClient()->setDefaultObject( name );
- launcher->dcopClient()->setDaemonMode( true );
-
- KCrash::setEmergencySaveFunction(sig_handler);
- signal( SIGHUP, sig_handler);
- signal( SIGPIPE, SIG_IGN);
- signal( SIGTERM, sig_handler);
-
- launcher->exec();
- return 0;
-}
-
diff --git a/kinit/kstartupconfig.cpp b/kinit/kstartupconfig.cpp
deleted file mode 100644
index 3204d6f7d..000000000
--- a/kinit/kstartupconfig.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/****************************************************************************
-
- Copyright (C) 2005 Lubos Lunak <l.lunak@kde.org>
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the "Software"),
-to deal in the Software without restriction, including without limitation
-the rights to use, copy, modify, merge, publish, distribute, sublicense,
-and/or sell copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE.
-
-****************************************************************************/
-
-/*
-
-This utility helps to have some configuration options available in starttde
-without the need to launch anything linked to KDE libraries (which may need
-some time to load).
-
-The configuration options are written to $TDEHOME/share/config/startupconfigkeys,
-one option per line, as <file> <group> <key> <default>. It is possible to
-use ' for quoting multiword entries. Values of these options will be written
-to $TDEHOME/share/config/startupconfig as a shell script that will set
-the values to shell variables, named <file>_<group>_<key> (all spaces replaced
-by underscores, everything lowercase). So e.g. line
-"ksplashrc KSplash Theme Default" may result in "ksplashrc_ksplash_theme=Default".
-
-In order to real a whole group it is possible to use <file> <[group]>, e.g.
-"ksplashrc [KSplash]", which will set shell variables for all keys in the group.
-It is not possible to specify default values, but since the configuration options
-are processed in the order they are specified this can be solved by first
-specifying a group and then all the entries that need default values.
-
-When a kconf_update script is used to update such option, kstartupconfig is run
-before kconf_update and therefore cannot see the change in time. To avoid this
-problem, together with the kconf_update script also the matching global config
-file should be updated (any change, kstartupconfig will see the timestamp change).
-
-Note that the kdeglobals config file is not used as a depedendency for other config
-files.
-
-Since the checking is timestamp-based, config files that are frequently updated
-should not be used.
-
-Kstartupconfig works by storing every line from startupconfigkeys in file startupconfigfiles
-followed by paths of all files that are relevant to the option. Non-existent files
-have '!' prepended (for the case they'll be later created), the list of files is
-terminated by line containing '*'. If the timestamps of all relevant files are older
-than the timestamp of the startupconfigfile file, there's no need to update anything.
-Otherwise kdostartupconfig is launched to create or update all the necessary files
-(which already requires loading KDE libraries, but this case should be rare).
-
-*/
-
-#include <config.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-int main()
- {
- char tdehome[ 1024 ];
- if( getenv( "TDEHOME" ))
- strlcpy( tdehome, getenv( "TDEHOME" ), 1024 );
- else if( getenv( "HOME" ))
- {
- strlcpy( tdehome, getenv( "HOME" ), 1024 );
- strlcat( tdehome, "/.trinity", 1024 );
- }
- else
- return 1;
- char filename[ 1024 ];
- strlcpy( filename, tdehome, 1024 );
- strlcat( filename, "/share/config/startupconfig", 1024 );
- if( access( filename, R_OK ) != 0 )
- {
- int ret = system( "kdostartupconfig" );
- return WEXITSTATUS( ret );
- }
- strlcpy( filename, tdehome, 1024 );
- strlcat( filename, "/share/config/startupconfigfiles", 1024 );
- struct stat st;
- if( stat( filename, &st ) != 0 )
- {
- int ret = system( "kdostartupconfig" );
- return WEXITSTATUS( ret );
- }
- time_t config_time = st.st_mtime;
- FILE* config = fopen( filename, "r" );
- if( config == NULL )
- {
- int ret = system( "kdostartupconfig" );
- return WEXITSTATUS( ret );
- }
- strlcpy( filename, tdehome, 1024 );
- strlcat( filename, "/share/config/startupconfigkeys", 1024 );
- FILE* keys = fopen( filename, "r" );
- if( keys == NULL )
- {
- fclose( config );
- return 2;
- }
- bool need_update = true;
- for(;;)
- {
- char keyline[ 1024 ];
- if( fgets( keyline, 1023, keys ) == NULL )
- {
- need_update = false;
- break;
- }
- if( char* nl = strchr( keyline, '\n' ))
- *nl = '\0';
- char line[ 1024 ];
- if( fgets( line, 1023, config ) == NULL )
- break;
- if( char* nl = strchr( line, '\n' ))
- *nl = '\0';
- if( strcmp( keyline, line ) != 0 )
- break;
- bool ok = false;
- for(;;)
- {
- if( fgets( line, 1023, config ) == NULL )
- break;
- if( char* nl = strchr( line, '\n' ))
- *nl = '\0';
- if( *line == '\0' )
- break;
- if( *line == '*' )
- {
- ok = true;
- break;
- }
- if( *line == '!' )
- {
- if( access( line + 1, R_OK ) == 0 )
- break; // file now exists -> update
- }
- else
- {
- struct stat st;
- if( stat( line, &st ) != 0 )
- break;
- if( st.st_mtime > config_time )
- break;
- }
- }
- if( !ok )
- break;
- }
- fclose( keys );
- fclose( config );
- if( need_update )
- {
- int ret = system( "kdostartupconfig" );
- return WEXITSTATUS( ret );
- }
- return 0;
- }
diff --git a/kinit/tdedostartupconfig.cpp b/kinit/tdedostartupconfig.cpp
new file mode 100644
index 000000000..d964a900b
--- /dev/null
+++ b/kinit/tdedostartupconfig.cpp
@@ -0,0 +1,143 @@
+/****************************************************************************
+
+ Copyright (C) 2005 Lubos Lunak <l.lunak@kde.org>
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+****************************************************************************/
+
+#undef QT_NO_CAST_ASCII
+
+// See description in tdestartupconfig.cpp .
+
+#include <tqfile.h>
+#include <tqtextstream.h>
+#include <kinstance.h>
+#include <kstandarddirs.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+
+TQString get_entry( TQString* ll )
+ {
+ TQString& l = *ll;
+ l = l.stripWhiteSpace();
+ if( l.isEmpty())
+ return TQString::null;
+ TQString ret;
+ if( l[ 0 ] == '\'' )
+ {
+ unsigned int pos = 1;
+ while( pos < l.length() && l[ pos ] != '\'' )
+ ret += l[ pos++ ];
+ if( pos >= l.length())
+ {
+ *ll = TQString::null;
+ return TQString::null;
+ }
+ *ll = l.mid( pos + 1 );
+ return ret;
+ }
+ unsigned int pos = 0;
+ while( pos < l.length() && l[ pos ] != ' ' )
+ ret += l[ pos++ ];
+ *ll = l.mid( pos );
+ return ret;
+ }
+
+int main()
+ {
+ TDEInstance inst( "tdedostartupconfig" );
+ kdDebug() << "Running tdedostartupconfig." << endl;
+ TQString keysname = locateLocal( "config", "startupconfigkeys" );
+ TQFile keys( keysname );
+ if( !keys.open( IO_ReadOnly ))
+ return 3;
+ TQFile f1( locateLocal( "config", "startupconfig" ));
+ if( !f1.open( IO_WriteOnly ))
+ return 4;
+ TQFile f2( locateLocal( "config", "startupconfigfiles" ));
+ if( !f2.open( IO_WriteOnly ))
+ return 5;
+ TQTextStream startupconfig( &f1 );
+ TQTextStream startupconfigfiles( &f2 );
+ startupconfig << "#! /bin/sh\n";
+ for(;;)
+ {
+ TQString line;
+ if( keys.readLine( line, 1024 ) < 0 )
+ break;
+ line = line.stripWhiteSpace();
+ if( line.isEmpty())
+ break;
+ TQString tmp = line;
+ TQString file, group, key, def;
+ file = get_entry( &tmp );
+ group = get_entry( &tmp );
+ key = get_entry( &tmp );
+ def = get_entry( &tmp );
+ if( file.isEmpty() || group.isEmpty())
+ return 6;
+ if( group.left( 1 ) == "[" && group.right( 1 ) == "]" )
+ { // whole config group
+ TDEConfig cfg( file );
+ group = group.mid( 1, group.length() - 2 );
+ TQMap< TQString, TQString > entries = cfg.entryMap( group );
+ startupconfig << "# " << line << "\n";
+ for( TQMap< TQString, TQString >::ConstIterator it = entries.begin();
+ it != entries.end();
+ ++it )
+ {
+ TQString key = it.key();
+ TQString value = *it;
+ startupconfig << TQString(file.replace( ' ', '_' )).lower()
+ << "_" << TQString(group.replace( ' ', '_' )).lower()
+ << "_" << TQString(key.replace( ' ', '_' )).lower()
+ << "=\"" << value.replace( "\"", "\\\"" ) << "\"\n";
+ }
+ }
+ else
+ { // a single key
+ if( key.isEmpty())
+ return 7;
+ TDEConfig cfg( file );
+ cfg.setGroup( group );
+ TQString value = cfg.readEntry( key, def );
+ startupconfig << "# " << line << "\n";
+ startupconfig << TQString(file.replace( ' ', '_' )).lower()
+ << "_" << TQString(group.replace( ' ', '_' )).lower()
+ << "_" <<TQString( key.replace( ' ', '_' )).lower()
+ << "=\"" << value.replace( "\"", "\\\"" ) << "\"\n";
+ }
+ startupconfigfiles << line << endl;
+ // use even currently non-existing paths in $TDEDIRS
+ TQStringList dirs = TQStringList::split( KPATH_SEPARATOR, TDEGlobal::dirs()->kfsstnd_prefixes());
+ for( TQStringList::ConstIterator it = dirs.begin();
+ it != dirs.end();
+ ++it )
+ {
+ TQString cfg = *it + "share/config/" + file;
+ if( KStandardDirs::exists( cfg ))
+ startupconfigfiles << cfg << "\n";
+ else
+ startupconfigfiles << "!" << cfg << "\n";
+ }
+ startupconfigfiles << "*\n";
+ }
+ return 0;
+ }
diff --git a/kinit/tdeioslave.cpp b/kinit/tdeioslave.cpp
new file mode 100644
index 000000000..1690ca2f7
--- /dev/null
+++ b/kinit/tdeioslave.cpp
@@ -0,0 +1,93 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (c) 1999-2000 Waldo Bastian <bastian@kde.org>
+ * (c) 1999 Mario Weilguni <mweilguni@sime.com>
+ * (c) 2001 Lubos Lunak <l.lunak@kde.org>
+ *
+ * $Id$
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <errno.h>
+
+#include <tqstring.h>
+
+#include "ltdl.h"
+
+#ifdef HAVE_DLFCN_H
+# include <dlfcn.h>
+#endif
+
+#ifdef RTLD_GLOBAL
+# define LTDL_GLOBAL RTLD_GLOBAL
+#else
+# ifdef DL_GLOBAL
+# define LTDL_GLOBAL DL_GLOBAL
+# else
+# define LTDL_GLOBAL 0
+# endif
+#endif
+
+/* These are to link libtdeio even if 'smart' linker is used */
+#include <tdeio/authinfo.h>
+extern "C" TDEIO::AuthInfo* _tdeioslave_init_kio() { return new TDEIO::AuthInfo(); }
+
+int main(int argc, char **argv)
+{
+ if (argc < 5)
+ {
+ fprintf(stderr, "Usage: tdeioslave <slave-lib> <protocol> <tdelauncher-socket> <app-socket>\n\nThis program is part of TDE.\n");
+ exit(1);
+ }
+ TQCString libpath = argv[1];
+
+ if (libpath.isEmpty())
+ {
+ fprintf(stderr, "library path is empty.\n");
+ exit(1);
+ }
+ lt_dlinit();
+
+ lt_dlhandle handle = lt_dlopen( libpath.data() );
+ if (!handle )
+ {
+ const char * ltdlError = lt_dlerror();
+ fprintf(stderr, "could not open %s: %s", libpath.data(), ltdlError != 0 ? ltdlError : "(null)" );
+ exit(1);
+ }
+
+ lt_ptr sym = lt_dlsym( handle, "kdemain");
+ if (!sym )
+ {
+ sym = lt_dlsym( handle, "main");
+ if (!sym )
+ {
+ const char * ltdlError = lt_dlerror();
+ fprintf(stderr, "Could not find main: %s\n", ltdlError != 0 ? ltdlError : "(null)" );
+ exit(1);
+ }
+ }
+
+ int (*func)(int, char *[]) = (int (*)(int, char *[])) sym;
+
+ exit( func(argc-1, argv+1)); /* Launch! */
+}
diff --git a/kinit/tdelauncher.cpp b/kinit/tdelauncher.cpp
new file mode 100644
index 000000000..306903a55
--- /dev/null
+++ b/kinit/tdelauncher.cpp
@@ -0,0 +1,1421 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <signal.h>
+#include <sys/time.h>
+
+#include <tqfile.h>
+
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <klibloader.h>
+#include <klocale.h>
+#include <kprotocolmanager.h>
+#include <kprotocolinfo.h>
+#include <krun.h>
+#include <kstandarddirs.h>
+#include <ktempfile.h>
+#include <kurl.h>
+
+#if defined Q_WS_X11 && ! defined K_WS_QTONLY
+#include <kstartupinfo.h> // schroder
+#endif
+
+
+#include "tdeio/global.h"
+#include "tdeio/connection.h"
+#include "tdeio/slaveinterface.h"
+
+#include "tdelauncher.h"
+#include "tdelauncher_cmds.h"
+
+//#if defined Q_WS_X11 && ! defined K_WS_QTONLY
+#ifdef Q_WS_X11
+//#undef K_WS_QTONLY
+#include <X11/Xlib.h> // schroder
+#endif
+
+// Dispose slaves after being idle for SLAVE_MAX_IDLE seconds
+#define SLAVE_MAX_IDLE 30
+
+using namespace TDEIO;
+
+template class TQPtrList<KLaunchRequest>;
+template class TQPtrList<IdleSlave>;
+
+IdleSlave::IdleSlave(TDESocket *socket)
+{
+ mConn.init(socket);
+ mConn.connect(this, TQT_SLOT(gotInput()));
+ mConn.send( CMD_SLAVE_STATUS );
+ mPid = 0;
+ mBirthDate = time(0);
+ mOnHold = false;
+}
+
+void
+IdleSlave::gotInput()
+{
+ int cmd;
+ TQByteArray data;
+ if (mConn.read( &cmd, data) == -1)
+ {
+ // Communication problem with slave.
+ kdError(7016) << "SlavePool: No communication with slave." << endl;
+ delete this;
+ }
+ else if (cmd == MSG_SLAVE_ACK)
+ {
+ delete this;
+ }
+ else if (cmd != MSG_SLAVE_STATUS)
+ {
+ kdError(7016) << "SlavePool: Unexpected data from slave." << endl;
+ delete this;
+ }
+ else
+ {
+ TQDataStream stream( data, IO_ReadOnly );
+ pid_t pid;
+ TQCString protocol;
+ TQString host;
+ TQ_INT8 b;
+ stream >> pid >> protocol >> host >> b;
+// Overload with (bool) onHold, (KURL) url.
+ if (!stream.atEnd())
+ {
+ KURL url;
+ stream >> url;
+ mOnHold = true;
+ mUrl = url;
+ }
+
+ mPid = pid;
+ mConnected = (b != 0);
+ mProtocol = protocol;
+ mHost = host;
+ emit statusUpdate(this);
+ }
+}
+
+void
+IdleSlave::connect(const TQString &app_socket)
+{
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly);
+ stream << app_socket;
+ mConn.send( CMD_SLAVE_CONNECT, data );
+ // Timeout!
+}
+
+void
+IdleSlave::reparseConfiguration()
+{
+ mConn.send( CMD_REPARSECONFIGURATION );
+}
+
+bool
+IdleSlave::match(const TQString &protocol, const TQString &host, bool connected)
+{
+ if (mOnHold) return false;
+ if (protocol != mProtocol) return false;
+ if (host.isEmpty()) return true;
+ if (host != mHost) return false;
+ if (!connected) return true;
+ if (!mConnected) return false;
+ return true;
+}
+
+bool
+IdleSlave::onHold(const KURL &url)
+{
+ if (!mOnHold) return false;
+ return (url == mUrl);
+}
+
+int
+IdleSlave::age(time_t now)
+{
+ return (int) difftime(now, mBirthDate);
+}
+
+KLauncher::KLauncher(int _tdeinitSocket, bool new_startup)
+// : TDEApplication( false, false ), // No Styles, No GUI
+ : TDEApplication( false, true ), // TQClipboard tries to construct a QWidget so a GUI is technically needed, even though it is not used
+ DCOPObject("tdelauncher"),
+ tdeinitSocket(_tdeinitSocket), mAutoStart( new_startup ),
+ dontBlockReading(false), newStartup( new_startup )
+{
+#ifdef Q_WS_X11
+ mCached_dpy = NULL;
+#endif
+ connect(&mAutoTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotAutoStart()));
+ requestList.setAutoDelete(true);
+ mSlaveWaitRequest.setAutoDelete(true);
+ dcopClient()->setNotifications( true );
+ connect(dcopClient(), TQT_SIGNAL( applicationRegistered( const TQCString &)),
+ this, TQT_SLOT( slotAppRegistered( const TQCString &)));
+ dcopClient()->connectDCOPSignal( "DCOPServer", "", "terminateKDE()",
+ objId(), "terminateKDE()", false );
+
+ TQString prefix = locateLocal("socket", "tdelauncher");
+ KTempFile domainname(prefix, TQString::fromLatin1(".slave-socket"));
+ if (domainname.status() != 0)
+ {
+ // Sever error!
+ tqDebug("KLauncher: Fatal error, can't create tempfile!");
+ ::exit(1);
+ }
+ mPoolSocketName = domainname.name();
+#ifdef __CYGWIN__
+ domainname.close();
+ domainname.unlink();
+#endif
+ mPoolSocket = new TDEServerSocket(static_cast<const char*>(TQFile::encodeName(mPoolSocketName)));
+ connect(mPoolSocket, TQT_SIGNAL(accepted( TDESocket *)),
+ TQT_SLOT(acceptSlave(TDESocket *)));
+
+ connect(&mTimer, TQT_SIGNAL(timeout()), TQT_SLOT(idleTimeout()));
+
+ tdeinitNotifier = new TQSocketNotifier(tdeinitSocket, TQSocketNotifier::Read);
+ connect(tdeinitNotifier, TQT_SIGNAL( activated( int )),
+ this, TQT_SLOT( slotKDEInitData( int )));
+ tdeinitNotifier->setEnabled( true );
+ lastRequest = 0;
+ bProcessingQueue = false;
+
+ mSlaveDebug = getenv("TDE_SLAVE_DEBUG_WAIT");
+ if (!mSlaveDebug.isEmpty())
+ {
+ tqWarning("Klauncher running in slave-debug mode for slaves of protocol '%s'", mSlaveDebug.data());
+ }
+ mSlaveValgrind = getenv("TDE_SLAVE_VALGRIND");
+ if (!mSlaveValgrind.isEmpty())
+ {
+ mSlaveValgrindSkin = getenv("TDE_SLAVE_VALGRIND_SKIN");
+ tqWarning("Klauncher running slaves through valgrind for slaves of protocol '%s'", mSlaveValgrind.data());
+ }
+ tdelauncher_header request_header;
+ request_header.cmd = LAUNCHER_OK;
+ request_header.arg_length = 0;
+ write(tdeinitSocket, &request_header, sizeof(request_header));
+}
+
+KLauncher::~KLauncher()
+{
+ close();
+}
+
+void KLauncher::close()
+{
+ if (!mPoolSocketName.isEmpty())
+ {
+ TQCString filename = TQFile::encodeName(mPoolSocketName);
+ unlink(filename.data());
+ }
+#if defined Q_WS_X11 && ! defined K_WS_QTONLY
+//#ifdef Q_WS_X11
+ if( mCached_dpy != NULL )
+ XCloseDisplay( mCached_dpy );
+#endif
+}
+
+void
+KLauncher::destruct(int exit_code)
+{
+ if (kapp) ((KLauncher*)kapp)->close();
+ // We don't delete kapp here, that's intentional.
+ ::exit(exit_code);
+}
+
+bool
+KLauncher::process(const TQCString &fun, const TQByteArray &data,
+ TQCString &replyType, TQByteArray &replyData)
+{
+ if ((fun == "exec_blind(TQCString,TQValueList<TQCString>)")
+ || (fun == "exec_blind(TQCString,TQValueList<TQCString>,TQValueList<TQCString>,TQCString)"))
+ {
+ TQDataStream stream(data, IO_ReadOnly);
+ replyType = "void";
+ TQCString name;
+ TQValueList<TQCString> arg_list;
+ TQCString startup_id = "0";
+ TQValueList<TQCString> envs;
+ stream >> name >> arg_list;
+ if( fun == "exec_blind(TQCString,TQValueList<TQCString>,TQValueList<TQCString>,TQCString)" )
+ stream >> envs >> startup_id;
+ kdDebug(7016) << "KLauncher: Got exec_blind('" << name << "', ...)" << endl;
+ exec_blind( name, arg_list, envs, startup_id);
+ return true;
+ }
+ if ((fun == "start_service_by_name(TQString,TQStringList)") ||
+ (fun == "start_service_by_desktop_path(TQString,TQStringList)")||
+ (fun == "start_service_by_desktop_name(TQString,TQStringList)")||
+ (fun == "tdeinit_exec(TQString,TQStringList)") ||
+ (fun == "tdeinit_exec_wait(TQString,TQStringList)") ||
+ (fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
+ (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString)")||
+ (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
+ (fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)") ||
+ (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)")||
+ (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)") ||
+ (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)") ||
+ (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>)") ||
+ (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
+ (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
+ {
+ TQDataStream stream(data, IO_ReadOnly);
+ bool bNoWait = false;
+ TQString serviceName;
+ TQStringList urls;
+ TQValueList<TQCString> envs;
+ TQCString startup_id = "";
+ DCOPresult.result = -1;
+ DCOPresult.dcopName = 0;
+ DCOPresult.error = TQString::null;
+ DCOPresult.pid = 0;
+ stream >> serviceName >> urls;
+ if ((fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)") ||
+ (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)")||
+ (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)"))
+ stream >> envs >> startup_id >> bNoWait;
+ else if ((fun == "start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
+ (fun == "start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString)")||
+ (fun == "start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
+ stream >> envs >> startup_id;
+ else if ((fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)") ||
+ (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>)"))
+ stream >> envs;
+ else if ((fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>,TQCString)") ||
+ (fun == "tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
+ stream >> envs >> startup_id;
+ bool finished;
+ if (strncmp(fun, "start_service_by_name(", 22) == 0)
+ {
+ kdDebug(7016) << "KLauncher: Got start_service_by_name('" << serviceName << "', ...)" << endl;
+ finished = start_service_by_name(serviceName, urls, envs, startup_id, bNoWait);
+ }
+ else if (strncmp(fun, "start_service_by_desktop_path(", 30) == 0)
+ {
+ kdDebug(7016) << "KLauncher: Got start_service_by_desktop_path('" << serviceName << "', ...)" << endl;
+ finished = start_service_by_desktop_path(serviceName, urls, envs, startup_id, bNoWait);
+ }
+ else if (strncmp(fun, "start_service_by_desktop_name(", 30) == 0)
+ {
+ kdDebug(7016) << "KLauncher: Got start_service_by_desktop_name('" << serviceName << "', ...)" << endl;
+ finished = start_service_by_desktop_name(serviceName, urls, envs, startup_id, bNoWait );
+ }
+ else if ((fun == "tdeinit_exec(TQString,TQStringList)")
+ || (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)")
+ || (fun == "tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>,TQCString)"))
+ {
+ kdDebug(7016) << "KLauncher: Got tdeinit_exec('" << serviceName << "', ...)" << endl;
+ finished = tdeinit_exec(serviceName, urls, envs, startup_id, false);
+ }
+ else
+ {
+ kdDebug(7016) << "KLauncher: Got tdeinit_exec_wait('" << serviceName << "', ...)" << endl;
+ finished = tdeinit_exec(serviceName, urls, envs, startup_id, true);
+ }
+ if (!finished)
+ {
+ replyType = "serviceResult";
+ TQDataStream stream2(replyData, IO_WriteOnly);
+ stream2 << DCOPresult.result << DCOPresult.dcopName << DCOPresult.error << DCOPresult.pid;
+ }
+ return true;
+ }
+ else if (fun == "requestSlave(TQString,TQString,TQString)")
+ {
+ TQDataStream stream(data, IO_ReadOnly);
+ TQString protocol;
+ TQString host;
+ TQString app_socket;
+ stream >> protocol >> host >> app_socket;
+ replyType = "TQString";
+ TQString error;
+ pid_t pid = requestSlave(protocol, host, app_socket, error);
+ TQDataStream stream2(replyData, IO_WriteOnly);
+ stream2 << pid << error;
+ return true;
+ }
+ else if (fun == "requestHoldSlave(KURL,TQString)")
+ {
+ TQDataStream stream(data, IO_ReadOnly);
+ KURL url;
+ TQString app_socket;
+ stream >> url >> app_socket;
+ replyType = "pid_t";
+ pid_t pid = requestHoldSlave(url, app_socket);
+ TQDataStream stream2(replyData, IO_WriteOnly);
+ stream2 << pid;
+ return true;
+ }
+ else if (fun == "waitForSlave(pid_t)")
+ {
+ TQDataStream stream(data, IO_ReadOnly);
+ pid_t pid;
+ stream >> pid;
+ waitForSlave(pid);
+ replyType = "void";
+ return true;
+
+ }
+ else if (fun == "setLaunchEnv(TQCString,TQCString)")
+ {
+ TQDataStream stream(data, IO_ReadOnly);
+ TQCString name;
+ TQCString value;
+ stream >> name >> value;
+ setLaunchEnv(name, value);
+ replyType = "void";
+ return true;
+ }
+ else if (fun == "reparseConfiguration()")
+ {
+ TDEGlobal::config()->reparseConfiguration();
+ kdDebug(7016) << "KLauncher::process : reparseConfiguration" << endl;
+ KProtocolManager::reparseConfiguration();
+ IdleSlave *slave;
+ for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
+ slave->reparseConfiguration();
+ replyType = "void";
+ return true;
+ }
+ else if (fun == "terminateKDE()")
+ {
+ ::signal( SIGHUP, SIG_IGN);
+ ::signal( SIGTERM, SIG_IGN);
+ kdDebug() << "KLauncher::process ---> terminateKDE" << endl;
+ tdelauncher_header request_header;
+ request_header.cmd = LAUNCHER_TERMINATE_KDE;
+ request_header.arg_length = 0;
+ write(tdeinitSocket, &request_header, sizeof(request_header));
+ destruct(0);
+ }
+ else if (fun == "autoStart()")
+ {
+ kdDebug() << "KLauncher::process ---> autoStart" << endl;
+ autoStart(1);
+ replyType = "void";
+ return true;
+ }
+ else if (fun == "autoStart(int)")
+ {
+ kdDebug() << "KLauncher::process ---> autoStart(int)" << endl;
+ TQDataStream stream(data, IO_ReadOnly);
+ int phase;
+ stream >> phase;
+ autoStart(phase);
+ replyType = "void";
+ return true;
+ }
+
+ if (DCOPObject::process(fun, data, replyType, replyData))
+ {
+ return true;
+ }
+ kdWarning(7016) << "Got unknown DCOP function: " << fun << endl;
+ return false;
+}
+
+QCStringList
+KLauncher::interfaces()
+{
+ QCStringList ifaces = DCOPObject::interfaces();
+ ifaces += "KLauncher";
+ return ifaces;
+}
+
+QCStringList
+KLauncher::functions()
+{
+ QCStringList funcs = DCOPObject::functions();
+ funcs << "void exec_blind(TQCString,TQValueList<TQCString>)";
+ funcs << "void exec_blind(TQCString,TQValueList<TQCString>,TQValueList<TQCString>,TQCString)";
+ funcs << "serviceResult start_service_by_name(TQString,TQStringList)";
+ funcs << "serviceResult start_service_by_desktop_path(TQString,TQStringList)";
+ funcs << "serviceResult start_service_by_desktop_name(TQString,TQStringList)";
+ funcs << "serviceResult tdeinit_exec(TQString,TQStringList)";
+ funcs << "serviceResult tdeinit_exec_wait(TQString,TQStringList)";
+ funcs << "serviceResult start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)";
+ funcs << "serviceResult start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString)";
+ funcs << "serviceResult start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString)";
+ funcs << "serviceResult start_service_by_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)";
+ funcs << "serviceResult start_service_by_desktop_path(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)";
+ funcs << "serviceResult start_service_by_desktop_name(TQString,TQStringList,TQValueList<TQCString>,TQCString,bool)";
+ funcs << "serviceResult tdeinit_exec(TQString,TQStringList,TQValueList<TQCString>)";
+ funcs << "serviceResult tdeinit_exec_wait(TQString,TQStringList,TQValueList<TQCString>)";
+ funcs << "TQString requestSlave(TQString,TQString,TQString)";
+ funcs << "pid_t requestHoldSlave(KURL,TQString)";
+ funcs << "void waitForSlave(pid_t)";
+ funcs << "void setLaunchEnv(TQCString,TQCString)";
+ funcs << "void reparseConfiguration()";
+// funcs << "void terminateKDE()";
+ funcs << "void autoStart()";
+ funcs << "void autoStart(int)";
+ return funcs;
+}
+
+void KLauncher::setLaunchEnv(const TQCString &name, const TQCString &_value)
+{
+ TQCString value(_value);
+ if (value.isNull())
+ value = "";
+ tdelauncher_header request_header;
+ TQByteArray requestData(name.length()+value.length()+2);
+ memcpy(requestData.data(), name.data(), name.length()+1);
+ memcpy(requestData.data()+name.length()+1, value.data(), value.length()+1);
+ request_header.cmd = LAUNCHER_SETENV;
+ request_header.arg_length = requestData.size();
+ write(tdeinitSocket, &request_header, sizeof(request_header));
+ write(tdeinitSocket, requestData.data(), request_header.arg_length);
+}
+
+/*
+ * Read 'len' bytes from 'sock' into buffer.
+ * returns -1 on failure, 0 on no data.
+ */
+static int
+read_socket(int sock, char *buffer, int len)
+{
+ ssize_t result;
+ int bytes_left = len;
+ while ( bytes_left > 0)
+ {
+ result = read(sock, buffer, bytes_left);
+ if (result > 0)
+ {
+ buffer += result;
+ bytes_left -= result;
+ }
+ else if (result == 0)
+ return -1;
+ else if ((result == -1) && (errno != EINTR))
+ return -1;
+ }
+ return 0;
+}
+
+
+void
+KLauncher::slotKDEInitData(int)
+{
+ tdelauncher_header request_header;
+ TQByteArray requestData;
+ if( dontBlockReading )
+ {
+ // in case we get a request to start an application and data arrive
+ // to tdeinitSocket at the same time, requestStart() will already
+ // call slotKDEInitData(), so we must check there's still something
+ // to read, otherwise this would block
+ fd_set in;
+ timeval tm = { 0, 0 };
+ FD_ZERO ( &in );
+ FD_SET( tdeinitSocket, &in );
+ select( tdeinitSocket + 1, &in, 0, 0, &tm );
+ if( !FD_ISSET( tdeinitSocket, &in ))
+ return;
+ }
+ dontBlockReading = false;
+ int result = read_socket(tdeinitSocket, (char *) &request_header,
+ sizeof( request_header));
+ if (result == -1)
+ {
+ kdDebug() << "Exiting on read_socket errno: " << errno << endl;
+ ::signal( SIGHUP, SIG_IGN);
+ ::signal( SIGTERM, SIG_IGN);
+ destruct(255); // Exit!
+ }
+ requestData.resize(request_header.arg_length);
+ result = read_socket(tdeinitSocket, (char *) requestData.data(),
+ request_header.arg_length);
+
+ if (request_header.cmd == LAUNCHER_DIED)
+ {
+ long *request_data;
+ request_data = (long *) requestData.data();
+ processDied(request_data[0], request_data[1]);
+ return;
+ }
+ if (lastRequest && (request_header.cmd == LAUNCHER_OK))
+ {
+ long *request_data;
+ request_data = (long *) requestData.data();
+ lastRequest->pid = (pid_t) (*request_data);
+ kdDebug(7016) << lastRequest->name << " (pid " << lastRequest->pid <<
+ ") up and running." << endl;
+ switch(lastRequest->dcop_service_type)
+ {
+ case KService::DCOP_None:
+ {
+ lastRequest->status = KLaunchRequest::Running;
+ break;
+ }
+
+ case KService::DCOP_Unique:
+ {
+ lastRequest->status = KLaunchRequest::Launching;
+ break;
+ }
+
+ case KService::DCOP_Wait:
+ {
+ lastRequest->status = KLaunchRequest::Launching;
+ break;
+ }
+
+ case KService::DCOP_Multi:
+ {
+ lastRequest->status = KLaunchRequest::Launching;
+ break;
+ }
+ }
+ lastRequest = 0;
+ return;
+ }
+ if (lastRequest && (request_header.cmd == LAUNCHER_ERROR))
+ {
+ lastRequest->status = KLaunchRequest::Error;
+ if (!requestData.isEmpty())
+ lastRequest->errorMsg = TQString::fromUtf8((char *) requestData.data());
+ lastRequest = 0;
+ return;
+ }
+
+ kdWarning(7016) << "Unexpected command from KDEInit (" << (unsigned int) request_header.cmd
+ << ")" << endl;
+}
+
+void
+KLauncher::processDied(pid_t pid, long /* exitStatus */)
+{
+ KLaunchRequest *request = requestList.first();
+ for(; request; request = requestList.next())
+ {
+ if (request->pid == pid)
+ {
+ if (request->dcop_service_type == KService::DCOP_Wait)
+ request->status = KLaunchRequest::Done;
+ else if ((request->dcop_service_type == KService::DCOP_Unique) &&
+ (dcopClient()->isApplicationRegistered(request->dcop_name)))
+ request->status = KLaunchRequest::Running;
+ else
+ request->status = KLaunchRequest::Error;
+ requestDone(request);
+ return;
+ }
+ }
+}
+
+void
+KLauncher::slotAppRegistered(const TQCString &appId)
+{
+ const char *cAppId = appId.data();
+ if (!cAppId) return;
+
+ KLaunchRequest *request = requestList.first();
+ KLaunchRequest *nextRequest;
+ for(; request; request = nextRequest)
+ {
+ nextRequest = requestList.next();
+ if (request->status != KLaunchRequest::Launching)
+ continue;
+
+ // For unique services check the requested service name first
+ if ((request->dcop_service_type == KService::DCOP_Unique) &&
+ ((appId == request->dcop_name) ||
+ dcopClient()->isApplicationRegistered(request->dcop_name)))
+ {
+ request->status = KLaunchRequest::Running;
+ requestDone(request);
+ continue;
+ }
+
+ const char *rAppId = request->dcop_name.data();
+ if (!rAppId) continue;
+
+ int l = strlen(rAppId);
+ if ((strncmp(rAppId, cAppId, l) == 0) &&
+ ((cAppId[l] == '\0') || (cAppId[l] == '-')))
+ {
+ request->dcop_name = appId;
+ request->status = KLaunchRequest::Running;
+ requestDone(request);
+ continue;
+ }
+ }
+}
+
+void
+KLauncher::autoStart(int phase)
+{
+ if( mAutoStart.phase() >= phase )
+ return;
+ mAutoStart.setPhase(phase);
+ if( newStartup )
+ {
+ if (phase == 0)
+ mAutoStart.loadAutoStartList();
+ }
+ else
+ {
+ if (phase == 1)
+ mAutoStart.loadAutoStartList();
+ }
+ mAutoTimer.start(0, true);
+}
+
+void
+KLauncher::slotAutoStart()
+{
+ KService::Ptr s;
+ do
+ {
+ TQString service = mAutoStart.startService();
+ if (service.isEmpty())
+ {
+ // Done
+ if( !mAutoStart.phaseDone())
+ {
+ mAutoStart.setPhaseDone();
+ // Emit signal
+ if( newStartup )
+ {
+ TQCString autoStartSignal;
+ autoStartSignal.sprintf( "autoStart%dDone()", mAutoStart.phase());
+ emitDCOPSignal(autoStartSignal, TQByteArray());
+ }
+ else
+ {
+ TQCString autoStartSignal( "autoStartDone()" );
+ int phase = mAutoStart.phase();
+ if ( phase > 1 )
+ autoStartSignal.sprintf( "autoStart%dDone()", phase );
+ emitDCOPSignal(autoStartSignal, TQByteArray());
+ }
+ }
+ return;
+ }
+ s = new KService(service);
+ }
+ while (!start_service(s, TQStringList(), TQValueList<TQCString>(), "0", false, true));
+ // Loop till we find a service that we can start.
+}
+
+void
+KLauncher::requestDone(KLaunchRequest *request)
+{
+ if ((request->status == KLaunchRequest::Running) ||
+ (request->status == KLaunchRequest::Done))
+ {
+ DCOPresult.result = 0;
+ DCOPresult.dcopName = request->dcop_name;
+ DCOPresult.error = TQString::null;
+ DCOPresult.pid = request->pid;
+ }
+ else
+ {
+ DCOPresult.result = 1;
+ DCOPresult.dcopName = "";
+ DCOPresult.error = i18n("KDEInit could not launch '%1'.").arg(TQString(request->name));
+ if (!request->errorMsg.isEmpty())
+ DCOPresult.error += ":\n" + request->errorMsg;
+ DCOPresult.pid = 0;
+
+#if defined Q_WS_X11 && ! defined K_WS_QTONLY
+//#ifdef Q_WS_X11
+ if (!request->startup_dpy.isEmpty())
+ {
+ Display* dpy = NULL;
+ if( (mCached_dpy != NULL) &&
+ (request->startup_dpy == XDisplayString( mCached_dpy )))
+ dpy = mCached_dpy;
+ if( dpy == NULL )
+ dpy = XOpenDisplay( request->startup_dpy );
+ if( dpy )
+ {
+ KStartupInfoId id;
+ id.initId( request->startup_id );
+ KStartupInfo::sendFinishX( dpy, id );
+ if( mCached_dpy != dpy && mCached_dpy != NULL )
+ XCloseDisplay( mCached_dpy );
+ mCached_dpy = dpy;
+ }
+ }
+#endif
+ }
+
+ if (request->autoStart)
+ {
+ mAutoTimer.start(0, true);
+ }
+
+ if (request->transaction)
+ {
+ TQByteArray replyData;
+ TQCString replyType;
+ replyType = "serviceResult";
+ TQDataStream stream2(replyData, IO_WriteOnly);
+ stream2 << DCOPresult.result << DCOPresult.dcopName << DCOPresult.error << DCOPresult.pid;
+ dcopClient()->endTransaction( request->transaction,
+ replyType, replyData);
+ }
+ requestList.removeRef( request );
+}
+
+void
+KLauncher::requestStart(KLaunchRequest *request)
+{
+ requestList.append( request );
+ // Send request to tdeinit.
+ tdelauncher_header request_header;
+ TQByteArray requestData;
+ int length = 0;
+ length += sizeof(long); // Nr of. Args
+ length += request->name.length() + 1; // Cmd
+ for(TQValueList<TQCString>::Iterator it = request->arg_list.begin();
+ it != request->arg_list.end();
+ it++)
+ {
+ length += (*it).length() + 1; // Args...
+ }
+ length += sizeof(long); // Nr of. envs
+ for(TQValueList<TQCString>::ConstIterator it = request->envs.begin();
+ it != request->envs.end();
+ it++)
+ {
+ length += (*it).length() + 1; // Envs...
+ }
+ length += sizeof( long ); // avoid_loops
+#ifdef Q_WS_X11
+ bool startup_notify = !request->startup_id.isNull() && request->startup_id != "0";
+ if( startup_notify )
+ length += request->startup_id.length() + 1;
+#endif
+ if (!request->cwd.isEmpty())
+ length += request->cwd.length() + 1;
+
+ requestData.resize( length );
+
+ char *p = requestData.data();
+ long l = request->arg_list.count()+1;
+ memcpy(p, &l, sizeof(long));
+ p += sizeof(long);
+ strcpy(p, request->name.data());
+ p += strlen(p) + 1;
+ for(TQValueList<TQCString>::Iterator it = request->arg_list.begin();
+ it != request->arg_list.end();
+ it++)
+ {
+ strcpy(p, (*it).data());
+ p += strlen(p) + 1;
+ }
+ l = request->envs.count();
+ memcpy(p, &l, sizeof(long));
+ p += sizeof(long);
+ for(TQValueList<TQCString>::ConstIterator it = request->envs.begin();
+ it != request->envs.end();
+ it++)
+ {
+ strcpy(p, (*it).data());
+ p += strlen(p) + 1;
+ }
+ l = 0; // avoid_loops, always false here
+ memcpy(p, &l, sizeof(long));
+ p += sizeof(long);
+#ifdef Q_WS_X11
+ if( startup_notify )
+ {
+ strcpy(p, request->startup_id.data());
+ p += strlen( p ) + 1;
+ }
+#endif
+ if (!request->cwd.isEmpty())
+ {
+ strcpy(p, request->cwd.data());
+ p += strlen( p ) + 1;
+ }
+#ifdef Q_WS_X11
+ request_header.cmd = startup_notify ? LAUNCHER_EXT_EXEC : LAUNCHER_EXEC_NEW;
+#else
+ request_header.cmd = LAUNCHER_EXEC_NEW;
+#endif
+ request_header.arg_length = length;
+ write(tdeinitSocket, &request_header, sizeof(request_header));
+ write(tdeinitSocket, requestData.data(), request_header.arg_length);
+
+ // Wait for pid to return.
+ lastRequest = request;
+ dontBlockReading = false;
+ do {
+ slotKDEInitData( tdeinitSocket );
+ }
+ while (lastRequest != 0);
+ dontBlockReading = true;
+}
+
+void
+KLauncher::exec_blind( const TQCString &name, const TQValueList<TQCString> &arg_list,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id )
+{
+ KLaunchRequest *request = new KLaunchRequest;
+ request->autoStart = false;
+ request->name = name;
+ request->arg_list = arg_list;
+ request->dcop_name = 0;
+ request->dcop_service_type = KService::DCOP_None;
+ request->pid = 0;
+ request->status = KLaunchRequest::Launching;
+ request->transaction = 0; // No confirmation is send
+ request->envs = envs;
+ // Find service, if any - strip path if needed
+ KService::Ptr service = KService::serviceByDesktopName( name.mid( name.findRev( '/' ) + 1 ));
+ if (service != NULL)
+ send_service_startup_info( request, service,
+ startup_id, TQValueList< TQCString >());
+ else // no .desktop file, no startup info
+ cancel_service_startup_info( request, startup_id, envs );
+
+ requestStart(request);
+ // We don't care about this request any longer....
+ requestDone(request);
+}
+
+
+bool
+KLauncher::start_service_by_name(const TQString &serviceName, const TQStringList &urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind)
+{
+ KService::Ptr service = 0;
+ // Find service
+ service = KService::serviceByName(serviceName);
+ if (!service)
+ {
+ DCOPresult.result = ENOENT;
+ DCOPresult.error = i18n("Could not find service '%1'.").arg(serviceName);
+ cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
+ return false;
+ }
+ return start_service(service, urls, envs, startup_id, blind);
+}
+
+bool
+KLauncher::start_service_by_desktop_path(const TQString &serviceName, const TQStringList &urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind)
+{
+ KService::Ptr service = 0;
+ // Find service
+ if (serviceName[0] == '/')
+ {
+ // Full path
+ service = new KService(serviceName);
+ }
+ else
+ {
+ service = KService::serviceByDesktopPath(serviceName);
+ }
+ if (!service)
+ {
+ DCOPresult.result = ENOENT;
+ DCOPresult.error = i18n("Could not find service '%1'.").arg(serviceName);
+ cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
+ return false;
+ }
+ return start_service(service, urls, envs, startup_id, blind);
+}
+
+bool
+KLauncher::start_service_by_desktop_name(const TQString &serviceName, const TQStringList &urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind)
+{
+ KService::Ptr service = 0;
+ // Find service
+ service = KService::serviceByDesktopName(serviceName);
+ if (!service)
+ {
+ DCOPresult.result = ENOENT;
+ DCOPresult.error = i18n("Could not find service '%1'.").arg(serviceName);
+ cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
+ return false;
+ }
+ return start_service(service, urls, envs, startup_id, blind);
+}
+
+bool
+KLauncher::start_service(KService::Ptr service, const TQStringList &_urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind, bool autoStart)
+{
+ TQStringList urls = _urls;
+ if (!service->isValid())
+ {
+ DCOPresult.result = ENOEXEC;
+ DCOPresult.error = i18n("Service '%1' is malformatted.").arg(service->desktopEntryPath());
+ cancel_service_startup_info( NULL, startup_id, envs ); // cancel it if any
+ return false;
+ }
+ KLaunchRequest *request = new KLaunchRequest;
+ request->autoStart = autoStart;
+
+ if ((urls.count() > 1) && !service->allowMultipleFiles())
+ {
+ // We need to launch the application N times. That sucks.
+ // We ignore the result for application 2 to N.
+ // For the first file we launch the application in the
+ // usual way. The reported result is based on this
+ // application.
+ TQStringList::ConstIterator it = urls.begin();
+ for(++it;
+ it != urls.end();
+ ++it)
+ {
+ TQStringList singleUrl;
+ singleUrl.append(*it);
+ TQCString startup_id2 = startup_id;
+ if( !startup_id2.isEmpty() && startup_id2 != "0" )
+ startup_id2 = "0"; // can't use the same startup_id several times
+ start_service( service, singleUrl, envs, startup_id2, true);
+ }
+ TQString firstURL = *(urls.begin());
+ urls.clear();
+ urls.append(firstURL);
+ }
+ createArgs(request, service, urls);
+
+ // We must have one argument at least!
+ if (!request->arg_list.count())
+ {
+ DCOPresult.result = ENOEXEC;
+ DCOPresult.error = i18n("Service '%1' is malformatted.").arg(service->desktopEntryPath());
+ delete request;
+ cancel_service_startup_info( NULL, startup_id, envs );
+ return false;
+ }
+
+ request->name = request->arg_list.first();
+ request->arg_list.remove(request->arg_list.begin());
+
+ request->dcop_service_type = service->DCOPServiceType();
+
+ if ((request->dcop_service_type == KService::DCOP_Unique) ||
+ (request->dcop_service_type == KService::DCOP_Multi))
+ {
+ TQVariant v = service->property("X-DCOP-ServiceName");
+ if (v.isValid())
+ request->dcop_name = v.toString().utf8();
+ if (request->dcop_name.isEmpty())
+ {
+ request->dcop_name = TQFile::encodeName(KRun::binaryName(service->exec(), true));
+ }
+ }
+
+ request->pid = 0;
+ request->transaction = 0;
+ request->envs = envs;
+ send_service_startup_info( request, service, startup_id, envs );
+
+ // Request will be handled later.
+ if (!blind && !autoStart)
+ {
+ request->transaction = dcopClient()->beginTransaction();
+ }
+ queueRequest(request);
+ return true;
+}
+
+void
+KLauncher::send_service_startup_info( KLaunchRequest *request, KService::Ptr service, const TQCString& startup_id,
+ const TQValueList<TQCString> &envs )
+{
+#if defined Q_WS_X11 && ! defined K_WS_QTONLY
+//#ifdef Q_WS_X11 // KStartup* isn't implemented for Qt/Embedded yet
+ request->startup_id = "0";
+ if( startup_id == "0" )
+ return;
+ bool silent;
+ TQCString wmclass;
+ if( !KRun::checkStartupNotify( TQString::null, service, &silent, &wmclass ))
+ return;
+ KStartupInfoId id;
+ id.initId( startup_id );
+ const char* dpy_str = NULL;
+ for( TQValueList<TQCString>::ConstIterator it = envs.begin();
+ it != envs.end();
+ ++it )
+ if( strncmp( *it, "DISPLAY=", 8 ) == 0 )
+ dpy_str = static_cast< const char* >( *it ) + 8;
+ Display* dpy = NULL;
+ if( dpy_str != NULL && mCached_dpy != NULL
+ && qstrcmp( dpy_str, XDisplayString( mCached_dpy )) == 0 )
+ dpy = mCached_dpy;
+ if( dpy == NULL )
+ dpy = XOpenDisplay( dpy_str );
+ request->startup_id = id.id();
+ if( dpy == NULL )
+ {
+ cancel_service_startup_info( request, startup_id, envs );
+ return;
+ }
+
+ request->startup_dpy = dpy_str;
+
+ KStartupInfoData data;
+ data.setName( service->name());
+ data.setIcon( service->icon());
+ data.setDescription( i18n( "Launching %1" ).arg( service->name()));
+ if( !wmclass.isEmpty())
+ data.setWMClass( wmclass );
+ if( silent )
+ data.setSilent( KStartupInfoData::Yes );
+ // the rest will be sent by tdeinit
+ KStartupInfo::sendStartupX( dpy, id, data );
+ if( mCached_dpy != dpy && mCached_dpy != NULL )
+ XCloseDisplay( mCached_dpy );
+ mCached_dpy = dpy;
+ return;
+#else
+ return;
+#endif
+}
+
+void
+KLauncher::cancel_service_startup_info( KLaunchRequest* request, const TQCString& startup_id,
+ const TQValueList<TQCString> &envs )
+{
+#if defined Q_WS_X11 && ! defined K_WS_QTONLY
+//#ifdef Q_WS_X11 // KStartup* isn't implemented for Qt/Embedded yet
+ if( request != NULL )
+ request->startup_id = "0";
+ if( !startup_id.isEmpty() && startup_id != "0" )
+ {
+ const char* dpy_str = NULL;
+ for( TQValueList<TQCString>::ConstIterator it = envs.begin();
+ it != envs.end();
+ ++it )
+ if( strncmp( *it, "DISPLAY=", 8 ) == 0 )
+ dpy_str = static_cast< const char* >( *it ) + 8;
+ Display* dpy = NULL;
+ if( dpy_str != NULL && mCached_dpy != NULL
+ && qstrcmp( dpy_str, XDisplayString( mCached_dpy )) == 0 )
+ dpy = mCached_dpy;
+ if( dpy == NULL )
+ dpy = XOpenDisplay( dpy_str );
+ if( dpy == NULL )
+ return;
+ KStartupInfoId id;
+ id.initId( startup_id );
+ KStartupInfo::sendFinishX( dpy, id );
+ if( mCached_dpy != dpy && mCached_dpy != NULL )
+ XCloseDisplay( mCached_dpy );
+ mCached_dpy = dpy;
+ }
+#endif
+}
+
+bool
+KLauncher::tdeinit_exec(const TQString &app, const TQStringList &args,
+ const TQValueList<TQCString> &envs, TQCString startup_id, bool wait)
+{
+ KLaunchRequest *request = new KLaunchRequest;
+ request->autoStart = false;
+
+ for(TQStringList::ConstIterator it = args.begin();
+ it != args.end();
+ it++)
+ {
+ TQString arg = *it;
+ request->arg_list.append(arg.local8Bit());
+ }
+
+ request->name = app.local8Bit();
+
+ if (wait)
+ request->dcop_service_type = KService::DCOP_Wait;
+ else
+ request->dcop_service_type = KService::DCOP_None;
+ request->dcop_name = 0;
+ request->pid = 0;
+#ifdef Q_WS_X11
+ request->startup_id = startup_id;
+#endif
+ request->envs = envs;
+ if( app != "tdebuildsycoca" ) // avoid stupid loop
+ {
+ // Find service, if any - strip path if needed
+ KService::Ptr service = KService::serviceByDesktopName( app.mid( app.findRev( '/' ) + 1 ));
+ if (service != NULL)
+ send_service_startup_info( request, service,
+ startup_id, TQValueList< TQCString >());
+ else // no .desktop file, no startup info
+ cancel_service_startup_info( request, startup_id, envs );
+ }
+ request->transaction = dcopClient()->beginTransaction();
+ queueRequest(request);
+ return true;
+}
+
+void
+KLauncher::queueRequest(KLaunchRequest *request)
+{
+ requestQueue.append( request );
+ if (!bProcessingQueue)
+ {
+ bProcessingQueue = true;
+ TQTimer::singleShot(0, this, TQT_SLOT( slotDequeue() ));
+ }
+}
+
+void
+KLauncher::slotDequeue()
+{
+ do {
+ KLaunchRequest *request = requestQueue.take(0);
+ // process request
+ request->status = KLaunchRequest::Launching;
+ requestStart(request);
+ if (request->status != KLaunchRequest::Launching)
+ {
+ // Request handled.
+ requestDone( request );
+ continue;
+ }
+ } while(requestQueue.count());
+ bProcessingQueue = false;
+}
+
+void
+KLauncher::createArgs( KLaunchRequest *request, const KService::Ptr service ,
+ const TQStringList &urls)
+{
+ TQStringList params = KRun::processDesktopExec(*service, urls, false);
+
+ for(TQStringList::ConstIterator it = params.begin();
+ it != params.end(); ++it)
+ {
+ request->arg_list.append((*it).local8Bit());
+ }
+ request->cwd = TQFile::encodeName(service->path());
+}
+
+///// IO-Slave functions
+
+pid_t
+KLauncher::requestHoldSlave(const KURL &url, const TQString &app_socket)
+{
+ IdleSlave *slave;
+ for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
+ {
+ if (slave->onHold(url))
+ break;
+ }
+ if (slave)
+ {
+ mSlaveList.removeRef(slave);
+ slave->connect(app_socket);
+ return slave->pid();
+ }
+ return 0;
+}
+
+
+pid_t
+KLauncher::requestSlave(const TQString &protocol,
+ const TQString &host,
+ const TQString &app_socket,
+ TQString &error)
+{
+ IdleSlave *slave;
+ for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
+ {
+ if (slave->match(protocol, host, true))
+ break;
+ }
+ if (!slave)
+ {
+ for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
+ {
+ if (slave->match(protocol, host, false))
+ break;
+ }
+ }
+ if (!slave)
+ {
+ for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
+ {
+ if (slave->match(protocol, TQString::null, false))
+ break;
+ }
+ }
+ if (slave)
+ {
+ mSlaveList.removeRef(slave);
+ slave->connect(app_socket);
+ return slave->pid();
+ }
+
+ TQString _name = KProtocolInfo::exec(protocol);
+ if (_name.isEmpty())
+ {
+ error = i18n("Unknown protocol '%1'.\n").arg(protocol);
+ return 0;
+ }
+
+ TQCString name = _name.latin1(); // ex: "kio_ftp"
+ TQCString arg1 = protocol.latin1();
+ TQCString arg2 = TQFile::encodeName(mPoolSocketName);
+ TQCString arg3 = TQFile::encodeName(app_socket);
+ TQValueList<TQCString> arg_list;
+ arg_list.append(arg1);
+ arg_list.append(arg2);
+ arg_list.append(arg3);
+
+// kdDebug(7016) << "KLauncher: launching new slave " << _name << " with protocol=" << protocol << endl;
+ if (mSlaveDebug == arg1)
+ {
+ tdelauncher_header request_header;
+ request_header.cmd = LAUNCHER_DEBUG_WAIT;
+ request_header.arg_length = 0;
+ write(tdeinitSocket, &request_header, sizeof(request_header));
+ }
+ if (mSlaveValgrind == arg1)
+ {
+ arg_list.prepend(TQFile::encodeName(KLibLoader::findLibrary(name)));
+ arg_list.prepend(TQFile::encodeName(locate("exe", "tdeioslave")));
+ name = "valgrind";
+ if (!mSlaveValgrindSkin.isEmpty()) {
+ arg_list.prepend(TQCString("--tool=") + mSlaveValgrindSkin);
+ } else
+ arg_list.prepend("--tool=memcheck");
+ }
+
+ KLaunchRequest *request = new KLaunchRequest;
+ request->autoStart = false;
+ request->name = name;
+ request->arg_list = arg_list;
+ request->dcop_name = 0;
+ request->dcop_service_type = KService::DCOP_None;
+ request->pid = 0;
+#ifdef Q_WS_X11
+ request->startup_id = "0";
+#endif
+ request->status = KLaunchRequest::Launching;
+ request->transaction = 0; // No confirmation is send
+ requestStart(request);
+ pid_t pid = request->pid;
+
+// kdDebug(7016) << "Slave launched, pid = " << pid << endl;
+
+ // We don't care about this request any longer....
+ requestDone(request);
+ if (!pid)
+ {
+ error = i18n("Error loading '%1'.\n").arg(TQString(name));
+ }
+ return pid;
+}
+
+void
+KLauncher::waitForSlave(pid_t pid)
+{
+ IdleSlave *slave;
+ for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
+ {
+ if (slave->pid() == pid)
+ return; // Already here.
+ }
+ SlaveWaitRequest *waitRequest = new SlaveWaitRequest;
+ waitRequest->transaction = dcopClient()->beginTransaction();
+ waitRequest->pid = pid;
+ mSlaveWaitRequest.append(waitRequest);
+}
+
+void
+KLauncher::acceptSlave(TDESocket *slaveSocket)
+{
+ IdleSlave *slave = new IdleSlave(slaveSocket);
+ // Send it a SLAVE_STATUS command.
+ mSlaveList.append(slave);
+ connect(slave, TQT_SIGNAL(destroyed()), this, TQT_SLOT(slotSlaveGone()));
+ connect(slave, TQT_SIGNAL(statusUpdate(IdleSlave *)),
+ this, TQT_SLOT(slotSlaveStatus(IdleSlave *)));
+ if (!mTimer.isActive())
+ {
+ mTimer.start(1000*10);
+ }
+}
+
+void
+KLauncher::slotSlaveStatus(IdleSlave *slave)
+{
+ SlaveWaitRequest *waitRequest = mSlaveWaitRequest.first();
+ while(waitRequest)
+ {
+ if (waitRequest->pid == slave->pid())
+ {
+ TQByteArray replyData;
+ TQCString replyType;
+ replyType = "void";
+ dcopClient()->endTransaction( waitRequest->transaction, replyType, replyData);
+ mSlaveWaitRequest.removeRef(waitRequest);
+ waitRequest = mSlaveWaitRequest.current();
+ }
+ else
+ {
+ waitRequest = mSlaveWaitRequest.next();
+ }
+ }
+}
+
+void
+KLauncher::slotSlaveGone()
+{
+ IdleSlave *slave = (IdleSlave *) sender();
+ mSlaveList.removeRef(slave);
+ if ((mSlaveList.count() == 0) && (mTimer.isActive()))
+ {
+ mTimer.stop();
+ }
+}
+
+void
+KLauncher::idleTimeout()
+{
+ bool keepOneFileSlave=true;
+ time_t now = time(0);
+ IdleSlave *slave;
+ for(slave = mSlaveList.first(); slave; slave = mSlaveList.next())
+ {
+ if ((slave->protocol()=="file") && (keepOneFileSlave))
+ keepOneFileSlave=false;
+ else if (slave->age(now) > SLAVE_MAX_IDLE)
+ {
+ // killing idle slave
+ delete slave;
+ }
+ }
+}
+
+#include "tdelauncher.moc"
diff --git a/kinit/tdelauncher.h b/kinit/tdelauncher.h
new file mode 100644
index 000000000..27c49ef7f
--- /dev/null
+++ b/kinit/tdelauncher.h
@@ -0,0 +1,200 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KLAUNCHER_H_
+#define _KLAUNCHER_H_
+
+#include <sys/types.h>
+#include <unistd.h>
+#include <time.h>
+#include <tqstring.h>
+#include <tqvaluelist.h>
+#include <tqsocketnotifier.h>
+#include <tqptrlist.h>
+#include <tqtimer.h>
+
+#include <dcopclient.h>
+#include <tdeio/connection.h>
+#include <ksock.h>
+#include <kurl.h>
+#include <kuniqueapplication.h>
+
+#include <kservice.h>
+
+#include "autostart.h"
+
+class IdleSlave : public TQObject
+{
+ Q_OBJECT
+public:
+ IdleSlave(TDESocket *socket);
+ bool match( const TQString &protocol, const TQString &host, bool connected);
+ void connect( const TQString &app_socket);
+ pid_t pid() const { return mPid;}
+ int age(time_t now);
+ void reparseConfiguration();
+ bool onHold(const KURL &url);
+ TQString protocol() const {return mProtocol;}
+
+signals:
+ void statusUpdate(IdleSlave *);
+
+protected slots:
+ void gotInput();
+
+protected:
+ TDEIO::Connection mConn;
+ TQString mProtocol;
+ TQString mHost;
+ bool mConnected;
+ pid_t mPid;
+ time_t mBirthDate;
+ bool mOnHold;
+ KURL mUrl;
+};
+
+class SlaveWaitRequest
+{
+public:
+ pid_t pid;
+ DCOPClientTransaction *transaction;
+};
+
+class KLaunchRequest
+{
+public:
+ TQCString name;
+ TQValueList<TQCString> arg_list;
+ TQCString dcop_name;
+ enum status_t { Init = 0, Launching, Running, Error, Done };
+ pid_t pid;
+ status_t status;
+ DCOPClientTransaction *transaction;
+ KService::DCOPServiceType_t dcop_service_type;
+ bool autoStart;
+ TQString errorMsg;
+#ifdef Q_WS_X11
+ TQCString startup_id; // "" is the default, "0" for none
+ TQCString startup_dpy; // Display to send startup notification to.
+#endif
+ TQValueList<TQCString> envs; // env. variables to be app's environment
+ TQCString cwd;
+};
+
+struct serviceResult
+{
+ int result; // 0 means success. > 0 means error (-1 means pending)
+ TQCString dcopName; // Contains DCOP name on success
+ TQString error; // Contains error description on failure.
+ pid_t pid;
+};
+
+class KLauncher : public TDEApplication, public DCOPObject
+{
+ Q_OBJECT
+
+public:
+ KLauncher(int _tdeinitSocket, bool new_startup);
+
+ ~KLauncher();
+
+ void close();
+ static void destruct(int exit_code); // exit!
+
+ // DCOP
+ virtual bool process(const TQCString &fun, const TQByteArray &data,
+ TQCString &replyType, TQByteArray &replyData);
+ virtual QCStringList functions();
+ virtual QCStringList interfaces();
+
+protected:
+ void processDied(pid_t pid, long exitStatus);
+
+ void requestStart(KLaunchRequest *request);
+ void requestDone(KLaunchRequest *request);
+
+ void setLaunchEnv(const TQCString &name, const TQCString &value);
+ void exec_blind(const TQCString &name, const TQValueList<TQCString> &arg_list,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id = "" );
+ bool start_service(KService::Ptr service, const TQStringList &urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id = "",
+ bool blind = false, bool autoStart = false );
+ bool start_service_by_name(const TQString &serviceName, const TQStringList &urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind);
+ bool start_service_by_desktop_path(const TQString &serviceName, const TQStringList &urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind);
+ bool start_service_by_desktop_name(const TQString &serviceName, const TQStringList &urls,
+ const TQValueList<TQCString> &envs, const TQCString& startup_id, bool blind);
+ bool tdeinit_exec(const TQString &app, const TQStringList &args,
+ const TQValueList<TQCString> &envs, TQCString startup_id, bool wait);
+
+ void waitForSlave(pid_t pid);
+
+ void autoStart(int phase);
+
+ void createArgs( KLaunchRequest *request, const KService::Ptr service,
+ const TQStringList &url);
+
+ pid_t requestHoldSlave(const KURL &url, const TQString &app_socket);
+ pid_t requestSlave(const TQString &protocol, const TQString &host,
+ const TQString &app_socket, TQString &error);
+
+
+ void queueRequest(KLaunchRequest *);
+
+ void send_service_startup_info( KLaunchRequest *request, KService::Ptr service, const TQCString& startup_id,
+ const TQValueList<TQCString> &envs );
+ void cancel_service_startup_info( KLaunchRequest *request, const TQCString& startup_id,
+ const TQValueList<TQCString> &envs );
+
+public slots:
+ void slotAutoStart();
+ void slotDequeue();
+ void slotKDEInitData(int);
+ void slotAppRegistered(const TQCString &appId);
+ void slotSlaveStatus(IdleSlave *);
+ void acceptSlave( TDESocket *);
+ void slotSlaveGone();
+ void idleTimeout();
+
+protected:
+ TQPtrList<KLaunchRequest> requestList; // Requests being handled
+ TQPtrList<KLaunchRequest> requestQueue; // Requests waiting to being handled
+ int tdeinitSocket;
+ TQSocketNotifier *tdeinitNotifier;
+ serviceResult DCOPresult;
+ KLaunchRequest *lastRequest;
+ TQPtrList<SlaveWaitRequest> mSlaveWaitRequest;
+ TQString mPoolSocketName;
+ TDEServerSocket *mPoolSocket;
+ TQPtrList<IdleSlave> mSlaveList;
+ TQTimer mTimer;
+ TQTimer mAutoTimer;
+ bool bProcessingQueue;
+ AutoStart mAutoStart;
+ TQCString mSlaveDebug;
+ TQCString mSlaveValgrind;
+ TQCString mSlaveValgrindSkin;
+ bool dontBlockReading;
+ bool newStartup;
+#ifdef Q_WS_X11
+ Display *mCached_dpy;
+#endif
+};
+#endif
diff --git a/kinit/tdelauncher_cmds.h b/kinit/tdelauncher_cmds.h
new file mode 100644
index 000000000..5763e5a38
--- /dev/null
+++ b/kinit/tdelauncher_cmds.h
@@ -0,0 +1,185 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KLAUNCHER_CMDS_H_
+#define _KLAUNCHER_CMDS_H_
+
+typedef struct
+{
+ long cmd;
+ long arg_length;
+} tdelauncher_header;
+
+/* Launcher commands: */
+
+#define LAUNCHER_EXEC 1
+/*
+ * LAUNCHER_EXEC
+ *
+ * Start a new process. Try using LAUNCHER_EXEC_NEW instead.
+ * There will be no app startup notification.
+ *
+ * long argc: number of arguments
+ * char *args: arguments, argument 0 is the program to start.
+ */
+
+
+#define LAUNCHER_SETENV 2
+/*
+ * LAUNCHER_SETENV
+ *
+ * Change environment of future processes launched via tdeinit.
+ * DON'T use this if you want to change environment only for one
+ * application you're going to start.
+ *
+ * char *env_name;
+ * char *env_value;
+ */
+
+#define LAUNCHER_DIED 3
+/*
+ * LAUNCHER_DIED
+ *
+ * Notification A child of tdeinit died.
+ *
+ * long pid;
+ * long exit_code;
+ */
+
+#define LAUNCHER_OK 4
+/*
+ * LAUNCHER_OK
+ *
+ * Notification Last process launched ok.
+ *
+ * long pid;
+ */
+
+#define LAUNCHER_ERROR 5
+/*
+ * LAUNCHER_ERROR
+ *
+ * Notification Last process could not be launched.
+ *
+ * char *error msg (utf8)
+ */
+
+#define LAUNCHER_SHELL 6
+/*
+ * LAUNCHER_SHELL
+ *
+ * Start a new process and use given environment.
+ * Starts app-startup notification.
+ *
+ * long argc: number of arguments
+ * char *args: arguments, argument 0 is the program to start.
+ * char *cwd: Working directory.
+ * long envc: number of environment vars
+ * char *envs: environment strings.
+ * int avoid_loops : avoid using the first path in $PATH where
+ * this process binary is found in order to avoid
+ * infinite loop by binary->tdeinit_wrapper link in $PATH
+ * char* startup_id: app startup notification id, "0" for none,
+ * "" ( empty string ) is the default
+ */
+
+#define LAUNCHER_TERMINATE_KDE 7
+
+/*
+ * LAUNCHER_TERMINATE_TDEINIT
+ *
+ * Suicide is painless
+ */
+#define LAUNCHER_TERMINATE_TDEINIT 8
+
+#define LAUNCHER_DEBUG_WAIT 9
+/*
+ * LAUNCHER_DEBUG_WAIT
+ *
+ * Next process started will do a sleep(1000000)
+ * before calling main()/kdemain()
+ *
+ * (Used for debugging io-slaves)
+ */
+
+#define LAUNCHER_EXT_EXEC 10
+/*
+ * LAUNCHER_EXT_EXEC
+ *
+ * Start a new process. The given environment variables will
+ * be added to its environment before starting it.
+ * Starts app-startup notification.
+ *
+ * long argc: number of arguments
+ * char *args: arguments, argument 0 is the program to start.
+ * long envc: number of environment vars
+ * char *envs: environment strings.
+ * int avoid_loops : avoid using the first path in $PATH where
+ * this process binary is found in order to avoid
+ * infinite loop by binary->tdeinit_wrapper link in $PATH
+ * char* startup_id: app startup notification id, "0" for none,
+ * "" ( empty string ) is the default
+ *
+ */
+
+
+#define LAUNCHER_KWRAPPER 11
+/*
+ * LAUNCHER_KWRAPPER
+ *
+ * Start a new process, use given environment, pass signals and output.
+ * Starts app-startup notification.
+ *
+ * long argc: number of arguments
+ * char *args: arguments, argument 0 is the program to start.
+ * char *cwd: Working directory.
+ * long envc: number of environment vars
+ * char *envs: environment strings.
+ * char *tty: tty to redirect stdout/stderr to.
+ * int avoid_loops : avoid using the first path in $PATH where
+ * this process binary is found in order to avoid
+ * infinite loop by binary->tdeinit_wrapper link in $PATH
+ * char* startup_id: app startup notification id, "0" for none,
+ * "" ( empty string ) is the default
+ */
+
+#define LAUNCHER_EXEC_NEW 12
+/*
+ * LAUNCHER_EXEC_NEW
+ *
+ * Start a new process. An improved version of LAUNCHER_EXEC.
+ * The given environment variables will be added
+ * to its environment before starting it.
+ * There will be no app startup notification.
+ *
+ * long argc: number of arguments
+ * char *args: arguments, argument 0 is the program to start.
+ * long envc: number of environment vars
+ * char *envs: environment strings.
+ * int avoid_loops : avoid using the first path in $PATH where
+ * this process binary is found in order to avoid
+ * infinite loop by binary->tdeinit_wrapper link in $PATH
+ */
+
+#define LAUNCHER_FD 42
+/*
+ * File descriptor to use for communication with tdeinit.
+ */
+
+#endif
diff --git a/kinit/tdelauncher_main.cpp b/kinit/tdelauncher_main.cpp
new file mode 100644
index 000000000..54ab94d54
--- /dev/null
+++ b/kinit/tdelauncher_main.cpp
@@ -0,0 +1,116 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "config.h"
+
+#include <unistd.h>
+#include <fcntl.h>
+
+#include "kapplication.h"
+#include "tdelauncher.h"
+#include "kcmdlineargs.h"
+#include "kcrash.h"
+#include "kdebug.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <tqcstring.h>
+#include <klocale.h>
+
+#include "tdelauncher_cmds.h"
+
+static void sig_handler(int sig_num)
+{
+ // No recursion
+ signal( SIGHUP, SIG_IGN);
+ signal( SIGTERM, SIG_IGN);
+ fprintf(stderr, "[tdelauncher] Exiting on signal %d\n", sig_num);
+ KLauncher::destruct(255);
+}
+
+static KCmdLineOptions options[] =
+{
+ { "new-startup", "Internal", 0 },
+ KCmdLineLastOption
+};
+
+extern "C" KDE_EXPORT int kdemain( int argc, char**argv )
+{
+ // Started via tdeinit.
+ if (fcntl(LAUNCHER_FD, F_GETFD) == -1)
+ {
+ fprintf(stderr, "%s", i18n("[tdelauncher] This program is not supposed to be started manually.\n"
+ "[tdelauncher] It is started automatically by tdeinit.\n").local8Bit().data());
+ return 1;
+ }
+
+ TQCString cname = TDEApplication::launcher();
+ char *name = cname.data();
+ TDECmdLineArgs::init(argc, argv, name, "KLauncher", "A service launcher.",
+ "v1.0");
+
+ KLauncher::addCmdLineOptions();
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ // WABA: Make sure not to enable session management.
+ putenv(strdup("SESSION_MANAGER="));
+
+ // Allow the locale to initialize properly
+ KLocale::setMainCatalogue("tdelibs");
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ int maxTry = 3;
+ while(true)
+ {
+ TQCString dcopName = TDEApplication::dcopClient()->registerAs(name, false);
+ if (dcopName.isEmpty())
+ {
+ kdWarning() << "[tdelauncher] DCOP communication problem!" << endl;
+ return 1;
+ }
+ if (dcopName == cname)
+ break; // Good!
+
+ if (--maxTry == 0)
+ {
+ kdWarning() << "[tdelauncher] Another instance of tdelauncher is already running!" << endl;
+ return 1;
+ }
+
+ // Wait a bit...
+ kdWarning() << "[tdelauncher] Waiting for already running tdelauncher to exit." << endl;
+ sleep(1);
+
+ // Try again...
+ }
+
+ KLauncher *launcher = new KLauncher(LAUNCHER_FD, args->isSet("new-startup"));
+ launcher->dcopClient()->setDefaultObject( name );
+ launcher->dcopClient()->setDaemonMode( true );
+
+ KCrash::setEmergencySaveFunction(sig_handler);
+ signal( SIGHUP, sig_handler);
+ signal( SIGPIPE, SIG_IGN);
+ signal( SIGTERM, sig_handler);
+
+ launcher->exec();
+ return 0;
+}
+
diff --git a/kinit/tdestartupconfig.cpp b/kinit/tdestartupconfig.cpp
new file mode 100644
index 000000000..373ac6787
--- /dev/null
+++ b/kinit/tdestartupconfig.cpp
@@ -0,0 +1,176 @@
+/****************************************************************************
+
+ Copyright (C) 2005 Lubos Lunak <l.lunak@kde.org>
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+****************************************************************************/
+
+/*
+
+This utility helps to have some configuration options available in starttde
+without the need to launch anything linked to KDE libraries (which may need
+some time to load).
+
+The configuration options are written to $TDEHOME/share/config/startupconfigkeys,
+one option per line, as <file> <group> <key> <default>. It is possible to
+use ' for quoting multiword entries. Values of these options will be written
+to $TDEHOME/share/config/startupconfig as a shell script that will set
+the values to shell variables, named <file>_<group>_<key> (all spaces replaced
+by underscores, everything lowercase). So e.g. line
+"ksplashrc KSplash Theme Default" may result in "ksplashrc_ksplash_theme=Default".
+
+In order to real a whole group it is possible to use <file> <[group]>, e.g.
+"ksplashrc [KSplash]", which will set shell variables for all keys in the group.
+It is not possible to specify default values, but since the configuration options
+are processed in the order they are specified this can be solved by first
+specifying a group and then all the entries that need default values.
+
+When a tdeconf_update script is used to update such option, tdestartupconfig is run
+before tdeconf_update and therefore cannot see the change in time. To avoid this
+problem, together with the tdeconf_update script also the matching global config
+file should be updated (any change, tdestartupconfig will see the timestamp change).
+
+Note that the kdeglobals config file is not used as a depedendency for other config
+files.
+
+Since the checking is timestamp-based, config files that are frequently updated
+should not be used.
+
+Kstartupconfig works by storing every line from startupconfigkeys in file startupconfigfiles
+followed by paths of all files that are relevant to the option. Non-existent files
+have '!' prepended (for the case they'll be later created), the list of files is
+terminated by line containing '*'. If the timestamps of all relevant files are older
+than the timestamp of the startupconfigfile file, there's no need to update anything.
+Otherwise tdedostartupconfig is launched to create or update all the necessary files
+(which already requires loading KDE libraries, but this case should be rare).
+
+*/
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+int main()
+ {
+ char tdehome[ 1024 ];
+ if( getenv( "TDEHOME" ))
+ strlcpy( tdehome, getenv( "TDEHOME" ), 1024 );
+ else if( getenv( "HOME" ))
+ {
+ strlcpy( tdehome, getenv( "HOME" ), 1024 );
+ strlcat( tdehome, "/.trinity", 1024 );
+ }
+ else
+ return 1;
+ char filename[ 1024 ];
+ strlcpy( filename, tdehome, 1024 );
+ strlcat( filename, "/share/config/startupconfig", 1024 );
+ if( access( filename, R_OK ) != 0 )
+ {
+ int ret = system( "tdedostartupconfig" );
+ return WEXITSTATUS( ret );
+ }
+ strlcpy( filename, tdehome, 1024 );
+ strlcat( filename, "/share/config/startupconfigfiles", 1024 );
+ struct stat st;
+ if( stat( filename, &st ) != 0 )
+ {
+ int ret = system( "tdedostartupconfig" );
+ return WEXITSTATUS( ret );
+ }
+ time_t config_time = st.st_mtime;
+ FILE* config = fopen( filename, "r" );
+ if( config == NULL )
+ {
+ int ret = system( "tdedostartupconfig" );
+ return WEXITSTATUS( ret );
+ }
+ strlcpy( filename, tdehome, 1024 );
+ strlcat( filename, "/share/config/startupconfigkeys", 1024 );
+ FILE* keys = fopen( filename, "r" );
+ if( keys == NULL )
+ {
+ fclose( config );
+ return 2;
+ }
+ bool need_update = true;
+ for(;;)
+ {
+ char keyline[ 1024 ];
+ if( fgets( keyline, 1023, keys ) == NULL )
+ {
+ need_update = false;
+ break;
+ }
+ if( char* nl = strchr( keyline, '\n' ))
+ *nl = '\0';
+ char line[ 1024 ];
+ if( fgets( line, 1023, config ) == NULL )
+ break;
+ if( char* nl = strchr( line, '\n' ))
+ *nl = '\0';
+ if( strcmp( keyline, line ) != 0 )
+ break;
+ bool ok = false;
+ for(;;)
+ {
+ if( fgets( line, 1023, config ) == NULL )
+ break;
+ if( char* nl = strchr( line, '\n' ))
+ *nl = '\0';
+ if( *line == '\0' )
+ break;
+ if( *line == '*' )
+ {
+ ok = true;
+ break;
+ }
+ if( *line == '!' )
+ {
+ if( access( line + 1, R_OK ) == 0 )
+ break; // file now exists -> update
+ }
+ else
+ {
+ struct stat st;
+ if( stat( line, &st ) != 0 )
+ break;
+ if( st.st_mtime > config_time )
+ break;
+ }
+ }
+ if( !ok )
+ break;
+ }
+ fclose( keys );
+ fclose( config );
+ if( need_update )
+ {
+ int ret = system( "tdedostartupconfig" );
+ return WEXITSTATUS( ret );
+ }
+ return 0;
+ }
diff --git a/kinit/tests/Makefile.am b/kinit/tests/Makefile.am
index 909e7c14b..e1157bf72 100644
--- a/kinit/tests/Makefile.am
+++ b/kinit/tests/Makefile.am
@@ -3,8 +3,8 @@
INCLUDES= -I$(srcdir)/../.. $(all_includes)
####### Files
-check_PROGRAMS = klaunchertest
+check_PROGRAMS = tdelaunchertest
-klaunchertest_SOURCES = klaunchertest.cpp
-klaunchertest_LDADD = $(LIB_KIO)
+tdelaunchertest_SOURCES = tdelaunchertest.cpp
+tdelaunchertest_LDADD = $(LIB_KIO)
diff --git a/kinit/tests/klaunchertest.cpp b/kinit/tests/klaunchertest.cpp
deleted file mode 100644
index 3293c07be..000000000
--- a/kinit/tests/klaunchertest.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- This file is part of KDE
-
- Copyright (C) 1998 Waldo Bastian (bastian@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- version 2 as published by the Free Software Foundation.
-
- This software 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 library; see the file COPYING. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqstring.h>
-#include <kapplication.h>
-#include <dcopclient.h>
-#include <stdio.h>
-#include <tqvaluelist.h>
-#include <kservice.h>
-
-
-int main(int argc, char *argv[])
-{
- TDEApplication::tdeinitExec("konsole");
-
- TDEApplication k(argc, argv, "klaunchertest");
-
- kapp->dcopClient()->registerAs( kapp->name()) ;
-
-#if 0
- TQString error;
- TQCString dcopService;
- int pid;
- int result = TDEApplication::startServiceByDesktopName(
- TQString::fromLatin1("konsole"), TQString::null, &error, &dcopService, &pid );
-
- printf("Result = %d, error = \"%s\", dcopService = \"%s\", pid = %d\n",
- result, error.ascii(), dcopService.data(), pid);
-
- result = TDEApplication::startServiceByDesktopName(
- TQString::fromLatin1("konqueror"), TQString::null, &error, &dcopService, &pid );
-
- printf("Result = %d, error = \"%s\", dcopService = \"%s\", pid = %d\n",
- result, error.ascii(), dcopService.data(), pid);
-#endif
-}
-
diff --git a/kinit/tests/tdelaunchertest.cpp b/kinit/tests/tdelaunchertest.cpp
new file mode 100644
index 000000000..a8989870b
--- /dev/null
+++ b/kinit/tests/tdelaunchertest.cpp
@@ -0,0 +1,54 @@
+/*
+ This file is part of KDE
+
+ Copyright (C) 1998 Waldo Bastian (bastian@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License
+ version 2 as published by the Free Software Foundation.
+
+ This software 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 library; see the file COPYING. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqstring.h>
+#include <kapplication.h>
+#include <dcopclient.h>
+#include <stdio.h>
+#include <tqvaluelist.h>
+#include <kservice.h>
+
+
+int main(int argc, char *argv[])
+{
+ TDEApplication::tdeinitExec("konsole");
+
+ TDEApplication k(argc, argv, "tdelaunchertest");
+
+ kapp->dcopClient()->registerAs( kapp->name()) ;
+
+#if 0
+ TQString error;
+ TQCString dcopService;
+ int pid;
+ int result = TDEApplication::startServiceByDesktopName(
+ TQString::fromLatin1("konsole"), TQString::null, &error, &dcopService, &pid );
+
+ printf("Result = %d, error = \"%s\", dcopService = \"%s\", pid = %d\n",
+ result, error.ascii(), dcopService.data(), pid);
+
+ result = TDEApplication::startServiceByDesktopName(
+ TQString::fromLatin1("konqueror"), TQString::null, &error, &dcopService, &pid );
+
+ printf("Result = %d, error = \"%s\", dcopService = \"%s\", pid = %d\n",
+ result, error.ascii(), dcopService.data(), pid);
+#endif
+}
+
diff --git a/kinit/wrapper.c b/kinit/wrapper.c
index 36a75d46b..565c9a152 100644
--- a/kinit/wrapper.c
+++ b/kinit/wrapper.c
@@ -21,7 +21,7 @@
#include <config.h>
-#include "klauncher_cmds.h"
+#include "tdelauncher_cmds.h"
#include <sys/types.h>
#include <sys/param.h>
@@ -310,7 +310,7 @@ int main(int argc, char **argv)
int kwrapper = 0;
long arg_count;
long env_count;
- klauncher_header header;
+ tdelauncher_header header;
char *start, *p, *buffer;
char cwd[8192];
const char *tty = NULL;
diff --git a/kio/CMakeLists.txt b/kio/CMakeLists.txt
deleted file mode 100644
index cd2dfd80e..000000000
--- a/kio/CMakeLists.txt
+++ /dev/null
@@ -1,71 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-add_definitions(
- -D_LARGEFILE64_SOURCE=1
-)
-
-add_subdirectory( kssl )
-add_subdirectory( kio )
-add_subdirectory( bookmarks )
-add_subdirectory( kfile )
-add_subdirectory( pics )
-add_subdirectory( kioexec )
-add_subdirectory( httpfilter )
-add_subdirectory( misc )
-add_subdirectory( kpasswdserver )
-add_subdirectory( tests )
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
- ${LIBR_LIBDIR}
-)
-
-
-##### other data ################################
-
-install( FILES magic DESTINATION ${MIME_INSTALL_DIR} )
-
-install( FILES
- application.desktop kurifilterplugin.desktop
- kcomprfilter.desktop kscan.desktop kdatatool.desktop
- kfileplugin.desktop tdecmodule.desktop
- DESTINATION ${SERVICETYPES_INSTALL_DIR} )
-
-install( FILES kioslave.upd DESTINATION ${KCONF_UPDATE_INSTALL_DIR} )
-install( PROGRAMS useragent.pl proxytype.pl DESTINATION ${KCONF_UPDATE_INSTALL_DIR} )
-install( FILES renamedlgplugin.desktop DESTINATION ${SERVICETYPES_INSTALL_DIR} )
-install( FILES kpasswdserver.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
-install( FILES data.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-if( HAVE_ELFICON )
- set( ELFICON_STATIC_LIB tdelficon-static )
-endif( HAVE_ELFICON )
-
-
-##### libkio ####################################
-
-set( target kio )
-
-configure_file( ${CMAKE_SOURCE_DIR}/cmake/modules/template_dummy_cpp.cmake dummy.cpp COPYONLY )
-
-tde_add_library( ${target} SHARED
- SOURCES ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp
- VERSION 4.2.0
- EMBED kssl-static kiocore-static tdesycoca-static kbookmarks-static kfile-static ${ELFICON_STATIC_LIB}
- LINK ltdlc-static tdeui-shared tdesu-shared tdewalletclient-shared ${LIBR_LIBRARIES}
- DESTINATION ${LIB_INSTALL_DIR}
-)
diff --git a/kio/DESIGN b/kio/DESIGN
deleted file mode 100644
index 08617bbda..000000000
--- a/kio/DESIGN
+++ /dev/null
@@ -1,272 +0,0 @@
-DESIGN:
-=======
-
-libkio uses kioslaves (separate processes) that handle a given protocol.
-Launching those slaves is taken care of by the tdeinit/klauncher tandem,
-which are notified by DCOP.
-
-Connection is the most low-level class, the one that encapsulates the pipe.
-
-SlaveInterface is the main class for transferring anything to the slave
-and Slave, which inherits SlaveInterface, is the sub class that Job should handle.
-
-A slave inherits SlaveBase, which is the other half of SlaveInterface.
-
-The scheduling is supposed to be on a two level basis. One is in the daemon
-and one is in the application. The daemon one (as opposite to the holy one? :)
-will determine how many slaves are ok for this app to be opened and it will
-also assign tasks to actually existing slaves.
-The application will still have some kind of a scheduler, but it should be
-a lot simpler as it doesn't have to decide anything besides which
-task goes to which pool of slaves (related to the protocol/host/user/port)
-and move tasks around.
-Currently a design study to name it cool is in scheduler.cpp but in the
-application side. This is just to test other things like recursive jobs
-and signals/slots within SlaveInterface. If someone feels brave, the scheduler
-is yours!
-On a second thought: at the daemon side there is no real scheduler, but a
-pool of slaves. So what we need is some kind of load calculation of the
-scheduler in the application and load balancing in the daemon.
-
-A third thought: Maybe the daemon can just take care of a number of 'unused'
-slaves. When an application needs a slave, it can request it from the daemon.
-The application will get one, either from the pool of unused slaves,
-or a new one will be created. This keeps things simple at the daemon level.
-It is up to the application to give the slaves back to the daemon.
-The scheduler in the application must take care not to request too many
-slaves and could implement priorities.
-
-Thought on usage:
-* Typically a single slave-type is used exclusively in one application. E.g.
-http slaves are used in a web-browser. POP3 slaves used in a mail program.
-
-* Sometimes a single program can have multiple roles. E.g. konqueror is
-both a web-browser and a file-manager. As a web-browser it primarily uses
-http-slaves as a file-manager file-slaves.
-
-* Selecting a link in konqueror: konqueror does a partial download of
-the file to check the mimetype (right??) then the application is
-started which downloads the complete file. In this case it should
-be able to pass the slave which does the partial download from konqueror
-to the application where it can do the complete download.
-
-Do we need to have a hard limit on the number of slaves/host?
-It seems so, because some protocols are about to fail if you
-have two slaves running in parralel (e.g. POP3)
-This has to be implemented in the daemon because only at daemon
-level all the slaves are known. As a consequence slaves must
-be returned to the daemon before connecting to another host.
-(Returning the slaves back to the daemon after every job is not
-strictly needed and only causes extra overhead)
-
-Instead of actually returning the slave to the daemon, it could
-be enough to ask 'recycling permission' from the daemon: the
-application asks the daemon whether it is ok to use a slave for
-another host. The daemon can then update its administration of
-which slave is connected to which host.
-
-The above does of course not apply to hostless protocols (like file).
-(They will never change host).
-
-Apart from a 'hard limit' on the number of slaves/host we can have
-a 'soft limit'. E.g. upon connection to a HTTP 1.1 server, the web-
-server tells the slave the number of parallel connections allowed.
-THe simplest solution seems to be to treat 'soft limits' the same
-as 'hard limits'. This means that the slave has to communicate the
-'soft limit' to the daemon.
-
-Jobs using multiple slaves.
-
-If a job needs multiple slaves in parallel (e.g. copying a file from
-a web-server to a ftp-server or browsing a tar-file on a ftp-site)
-we must make sure to request the daemon for all slaves together since
-otherwise there is a risk of deadlock.
-
-(If two applications both need a 'pop3' and a 'ftp' slave for a single
-job and only a single slave/host is allowed for pop3 and ftp, we must
-prevent giving the single pop3 slave to application #1 and the single
-ftp slave to application #2. Both applications will then wait till the
-end of times till they get the other slave so that they can start the
-job. (This is a quite unlikely situation, but nevertheless possible))
-
-
-File Operations:
-listRecursive is implemented as listDir and finding out if in the result
- is a directory. If there is, another listDir job is issued. As listDir
- is a readonly operation it fails when a directory isn't readable
- .. but the main job goes on and discards the error, because
-bIgnoreSubJobsError is true, which is what we want (David)
-
-del is implemented as listRecursive, removing all files and removing all
- empty directories. This basically means if one directory isn't readable
- we don't remove it as listRecursive didn't find it. But the del will later
- on try to remove it's parent directory and fail. But there are cases when
- it would be possible to delete the dir in chmod the dir before. On the
- other hand del("/") shouldn't list the whole file system and remove all
- user owned files just to find out it can't remove everything else (this
- basically means we have to take care of things we can remove before we try)
-
- ... Well, rm -rf / refuses to do anything, so we should just do the same:
- use a listRecursive with bIgnoreSubJobsError = false. If anything can't
- be removed, we just abort. (David)
-
- ... My concern was more that the fact we can list / doesn't mean we can
- remove it. So we shouldn't remove everything we could list without checking
- we can. But then the question arises how do we check whether we can remove it?
- (Stephan)
-
- ... I was wrong, rm -rf /, even as a user, lists everything and removes
- everything it can (don't try this at home!). I don't think we can do
- better, unless we add a protocol-dependent "canDelete(path)", which is
- _really_ not easy to implement, whatever protocol. (David)
-
-
-Lib docu
-========
-
-mkdir: ...
-
-rmdir: ...
-
-chmod: ...
-
-special: ...
-
-stat: ...
-
-get is implemented as TransferJob. Clients get 'data' signals with the data.
-A data block of zero size indicates end of data (EOD)
-
-put is implemented as TransferJob. Clients have to connect to the
-'dataReq' signal. The slave will call you when it needs your data.
-
-mimetype: ...
-
-file_copy: copies a single file, either using CMD_COPY if the slave
- supports that or get & put otherwise.
-
-file_move: moves a single file, either using CMD_RENAME if the slave
- supports that, CMD_COPY + del otherwise, or eventually
- get & put & del.
-
-file_delete: delete a single file.
-
-copy: copies a file or directory, recursively if the latter
-
-move: moves a file or directory, recursively if the latter
-
-del: deletes a file or directory, recursively if the latter
-
-PROGRESS DISPLAYING :
-=====================
-Taj brought up the idea of deligating all progress informations to an extern
-GUI daemon which could be provided in several implementations - examples
-are popup dialogs (most are annoyed by them, like me :) or a kicker applet
-or something completely different. This would also remove the dependency on
-libtdeui (I hope).
-Conclusion: kio_uiserver is this single GUI daemon, but the dependency on
-libtdeui couldn't be removed (for many reasons, including Job::showErrorDialog())
-
-A. progress handling
----------------------
-There will be two ways how the application can display progress :
-
-1. regular apps will use NetAccess for all kio operations and will not care
- about progress handling :
- - NetAccess creates Job
- - NetAccess creates JobObserver that will connect to the Job's signals and
- pass them via dcop to the running GUI Progress Server
-
-2. apps that want to do some handling with progress dialogs like Caitoo or
- KMail :
- - app creates Job
- - app creates a progress dialog : this should be a ProgressBase descendant
- e.g. StatusProgress or custom progress dialog
- - app calls progress->setJob( job ) in order to connect job's signals with
- progress dialog slots
-
-B. customized progress dialogs
--------------------------------
- This will be similar to what we had before.
-
- - ProgressBase class that all other dialogs will inherit.
- will contain an initialization method setJob( TDEIO::Job*) for apps of the
- second class (see A.2 above), that will connect job's signals to dialog's
- slots
-
- - DefaultProgress ( former KIOSimpleProgressDialog ) that will be used for
- regular progress dialogs created by GUI Progress Server
-
- - StatusProgress ( former KIOLittleProgressDialog ) that can be used for
- embedding in status bar
-
-C. GUI Progress Server
------------------------
- This is a special progress server.
- - createProgress() will either create a DefaultProgress dialog or add new entry
- in a ListProgress ( an all-jobs-in-one progress dialog )
- - after receiving signals from the JobObserver via DCOP it will call
- appropriate method of progress dialog ( either in DefaultProgress or ListProgress )
- - ListProgres can be a Caitoo style dialog, kicker applet or both in one.
-
-D. Some notes
---------------
- 1. most of the apps will not care at all about the progress display
- 2. user will be able to choose whether he wants to see separate progress
- dialogs or all-in-one ListProgress dialog
- 3. developers can create their custom progress dialogs that inherit
- ProgressBase and do any manipulation with a dialog if they use a second
- approach ( see A.2 above )
-
-
-Streaming
----------
-
- 1. We currently support a streaming "GET": e.g. file:/tmp/test.gz#gzip:/
- works. The following should also work: file:/tmp/test.gz.gz#gzip:/#gzip:/
- The current approach makes a TrasnferJob for gzip:/ and then adds a
- subjob for "file:/tmp/test.gz.gz#gzip:/" which itself adds a subjob
- for "file:/tmp/test.gz.gz".
- 2. This doesn't extend very well to PUT, because there the order should
- basically be the other way around, but the "input" to the job as a whole
- should go to the "gzip:/" job, not to the "file:/tmp/test.gz.gz."
- It would probably be easier to implement such a job in the way the
- current "CopyJob" is done. Have a Job and make all sub-urls sub-jobs of
- this Job.
- 3. As a result of 1. COPY FROM an url like file:/tmp/test.gz#gzip:/ should
- work. COPY TO does not, because that would require PUT.
-
-
-Resuming
---------
-
-A rough note for now, just to have this somewhere :
-(PJ=put-job, GJ=get-job)
-
-PJ can't resume:
-PJ-->app: canResume(0) (emitted by dataReq)
-GJ-->app: data()
-PJ-->app: dataReq()
-app->PJ: data()
-
-PJ can resume but GJ can't resume:
-PJ-->app: canResume(xx)
-app->GJ: start job with "resume=xxx" metadata.
-GJ-->app: data()
-PJ-->app: dataReq()
-app->PJ: data()
-
-PJ can resume and GJ can resume:
-PJ-->app: canResume(xx)
-app->GJ: start job with "resume=xxx" metadata.
-GJ-->app: canResume(xx)
-GJ-->app: data()
-PJ-->app: dataReq()
-app->PJ: canResume(xx)
-app->PJ: data()
-
-So when the slave supports resume for "put" it has to check after the first
-dataRequest() whether it has got a canResume() back from the app. If it did
-it must resume. Otherwise it must start from 0.
-
-
diff --git a/kio/DESIGN.krun b/kio/DESIGN.krun
deleted file mode 100644
index 948ef79a3..000000000
--- a/kio/DESIGN.krun
+++ /dev/null
@@ -1,35 +0,0 @@
-
-konq_run / krun should determine the mimetype by actually
-getting the contents of the URL. It should then put the slave
-on hold and tell the job-scheduler which request the
-slave is currently handling. (Status: implemented in konq_run)
-
-Now krun/konq_run should determine which client should process the
-result of the request.
-
-* When the client belongs to the same process, no action needs to be
-taken. When a new job is created for the request which is on hold the
-existing slave will be re-used and the request resumed.
-(Status: implemented)
-
-* When the client is an external process, the on-hold-slave should be
-removed from the job-scheduler and should connect itself with
-klauncher. This is hard because it must ensure that the external
-program does not request the slave before it has been transfered to
-klauncher. (Status: to be done)
-
-* When a slave is on hold but not used for a certain period of time,
-or, when another slave is put on hold, the slave should be killed.
-(Status: almost done)
-
-=====
-
-The slave must emit "mimetype" during a GET before the first data is send.
-
-It may wait with sending "mimetype" until it has enough data to
-determine the mimetype, but it should not pass any data along before it has
-send the mimetype.
-
-Currently only http _always_ sends a mimetype.
-
-
diff --git a/kio/Makefile.am b/kio/Makefile.am
deleted file mode 100644
index fbe0d75dc..000000000
--- a/kio/Makefile.am
+++ /dev/null
@@ -1,67 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 1997 Torben Weis (weis@kde.org)
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
-
-INCLUDES= -I$(srcdir)/.. $(all_includes) $(SSL_INCLUDES)
-
-SUBDIRS = kssl kio bookmarks kfile . pics tests kioexec httpfilter misc kpasswdserver
-
-lib_LTLIBRARIES = libkio.la
-
-libkio_la_SOURCES = dummy.cpp
-
-libkio_la_LDFLAGS = -version-info 6:0:2 -no-undefined $(all_libraries) \
- $(KDE_MT_LDFLAGS)
-libkio_la_LIBADD = kssl/libkssl.la kio/libkiocore.la \
- kio/libtdesycoca.la bookmarks/libkbookmarks.la kfile/libkfile.la \
- ../tdeui/libtdeui.la ../tdesu/libtdesu.la \
- ../tdewallet/client/libtdewalletclient.la \
- $(LIBZ) $(LIBFAM) $(LIBVOLMGT) $(ACL_LIBS) $(LIB_QT) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la $(LIB_X11)
-
-kde_mime_DATA = magic
-kde_servicetypes_DATA = application.desktop kurifilterplugin.desktop \
- kcomprfilter.desktop kscan.desktop kdatatool.desktop \
- kfileplugin.desktop tdecmodule.desktop
-
-EXTRA_DIST = $(kde_mime_DATA)
-
-update_DATA = kioslave.upd
-update_SCRIPTS = useragent.pl proxytype.pl
-updatedir = $(kde_datadir)/kconf_update
-
-servicetype_DATA = renamedlgplugin.desktop
-servicetypedir = $(kde_servicetypesdir)
-
-kded_DATA = kpasswdserver.desktop
-kdeddir = $(kde_servicesdir)/kded
-
-dataprotocol_DATA = data.protocol
-dataprotocoldir = $(kde_servicesdir)
-
-dummy.cpp:
- echo >dummy.cpp
-
-messages:
- $(EXTRACTRC) `find . ../kioslave -name "*.rc" -o -name "*.ui"` > rc.cpp
- $(XGETTEXT) `find . ../kioslave -name "*.cpp" -o -name "*.cc" -o -name "*.h"` -o $(podir)/kio.pot
- rm -f rc.cpp
-
-DOXYGEN_REFERENCES = tdecore tdefx kjs dcop tdeui kio/kio kio/kfile
-DOXYGEN_EXCLUDE = kssl/kssl
-include ../admin/Doxyfile.am
diff --git a/kio/bookmarks/CMakeLists.txt b/kio/bookmarks/CMakeLists.txt
deleted file mode 100644
index 7c2fd72c6..000000000
--- a/kio/bookmarks/CMakeLists.txt
+++ /dev/null
@@ -1,55 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdefx
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
-)
-
-
-##### headers ###################################
-
-install( FILES
- kbookmark.h kbookmarkbar.h kbookmarkdrag.h kbookmarkexporter.h
- kbookmarkimporter.h kbookmarkmanager.h kbookmarkmenu.h
- kbookmarknotifier.h kbookmarkimporter_crash.h
- kbookmarkimporter_opera.h kbookmarkimporter_ie.h
- kbookmarkimporter_ns.h kbookmarkimporter_kde1.h
- kbookmarkdombuilder.h
- DESTINATION ${INCLUDE_INSTALL_DIR} )
-
-
-##### kbookmarks ################################
-
-set( target kbookmarks )
-
-set( ${target}_SRCS
- kbookmark.cc kbookmarkbar.cc kbookmarkdrag.cc kbookmarkexporter.cc
- kbookmarkimporter.cc kbookmarkmanager.cc kbookmarkmenu.cc
- kbookmarkimporter_crash.cc kbookmarkimporter_opera.cc
- kbookmarkimporter_ie.cc kbookmarkimporter_ns.cc
- kbookmarkimporter_kde1.cc kbookmarkdombuilder.cc
- kbookmarkmanager.skel kbookmarknotifier.skel
-)
-
-tde_add_library( ${target} STATIC_PIC AUTOMOC
- SOURCES ${${target}_SRCS}
- DEPENDENCIES dcopidl
-)
diff --git a/kio/bookmarks/Makefile.am b/kio/bookmarks/Makefile.am
deleted file mode 100644
index 63b535e13..000000000
--- a/kio/bookmarks/Makefile.am
+++ /dev/null
@@ -1,40 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 1997 Stephan Kulow (coolo@kde.org)
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this library; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-
-INCLUDES= -I$(srcdir)/../libltdl/ -I$(top_srcdir) -I$(top_srcdir)/tdefx -I$(top_builddir)/kio/kio $(all_includes)
-
-noinst_LTLIBRARIES = libkbookmarks.la
-
-METASOURCES = AUTO
-
-# convenience lib - no _LDFLAGS or _LIBADD !
-
-include_HEADERS = \
- kbookmark.h kbookmarkbar.h kbookmarkdrag.h kbookmarkexporter.h \
- kbookmarkimporter.h kbookmarkmanager.h kbookmarkmenu.h kbookmarknotifier.h \
- kbookmarkimporter_crash.h kbookmarkimporter_opera.h kbookmarkimporter_ie.h \
- kbookmarkimporter_ns.h kbookmarkimporter_kde1.h kbookmarkdombuilder.h
-libkbookmarks_la_SOURCES = \
- kbookmark.cc kbookmarkbar.cc kbookmarkdrag.cc kbookmarkexporter.cc \
- kbookmarkimporter.cc kbookmarkmanager.cc kbookmarkmenu.cc \
- kbookmarkimporter_crash.cc kbookmarkimporter_opera.cc kbookmarkimporter_ie.cc \
- kbookmarkimporter_ns.cc kbookmarkimporter_kde1.cc kbookmarkdombuilder.cc \
- kbookmarkmanager.skel kbookmarknotifier.skel
-
-include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kio/bookmarks/kbookmarkbar.cc b/kio/bookmarks/kbookmarkbar.cc
deleted file mode 100644
index dc2ad0cde..000000000
--- a/kio/bookmarks/kbookmarkbar.cc
+++ /dev/null
@@ -1,554 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE project
- Copyright (C) 1999 Kurt Granroth <granroth@kde.org>
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#include <tqregexp.h>
-#include <tqfile.h>
-
-#include <kbookmarkbar.h>
-#include <kbookmarkdrag.h>
-
-#include <kbookmarkmenu.h>
-#include <kdebug.h>
-
-#include <ktoolbar.h>
-#include <ktoolbarbutton.h>
-
-#include <kconfig.h>
-#include <kpopupmenu.h>
-
-#include "kbookmarkdrag.h"
-#include "kbookmarkmenu_p.h"
-#include "kbookmarkdombuilder.h"
-
-#include "dptrtemplate.h"
-
-#include <tqapplication.h>
-
-class KBookmarkBarPrivate : public dPtrTemplate<KBookmarkBar, KBookmarkBarPrivate>
-{
-public:
- TQPtrList<KAction> m_actions;
- bool m_readOnly;
- KBookmarkManager* m_filteredMgr;
- KToolBar* m_sepToolBar;
- int m_sepIndex;
- bool m_atFirst;
- TQString m_dropAddress;
- TQString m_highlightedAddress;
-public:
- KBookmarkBarPrivate() {
- m_readOnly = false;
- m_filteredMgr = 0;
- m_sepToolBar = 0;
- m_sepIndex = -1;
- m_atFirst = false;
- }
-};
-template<> TQPtrDict<KBookmarkBarPrivate>* dPtrTemplate<KBookmarkBar, KBookmarkBarPrivate>::d_ptr = 0;
-
-KBookmarkBarPrivate* KBookmarkBar::dptr() const
-{
- return KBookmarkBarPrivate::d( this );
-}
-
-// usage of KXBELBookmarkImporterImpl is just plain evil, but it reduces code dup. so...
-class ToolbarFilter : public KXBELBookmarkImporterImpl
-{
-public:
- ToolbarFilter() : m_visible(false) { ; }
- void filter( const KBookmarkGroup &grp ) { traverse(grp); }
-private:
- virtual void visit( const KBookmark & );
- virtual void visitEnter( const KBookmarkGroup & );
- virtual void visitLeave( const KBookmarkGroup & );
-private:
- bool m_visible;
- KBookmarkGroup m_visibleStart;
-};
-
-KBookmarkBar::KBookmarkBar( KBookmarkManager* mgr,
- KBookmarkOwner *_owner, KToolBar *_toolBar,
- KActionCollection *coll,
- TQObject *parent, const char *name )
- : TQObject( parent, name ), m_pOwner(_owner), m_toolBar(_toolBar),
- m_actionCollection( coll ), m_pManager(mgr)
-{
- m_lstSubMenus.setAutoDelete( true );
-
- m_toolBar->setAcceptDrops( true );
- m_toolBar->installEventFilter( this ); // for drops
-
- dptr()->m_actions.setAutoDelete( true );
-
- connect( mgr, TQT_SIGNAL( changed(const TQString &, const TQString &) ),
- TQT_SLOT( slotBookmarksChanged(const TQString &) ) );
-
- KBookmarkGroup toolbar = getToolbar();
- fillBookmarkBar( toolbar );
-}
-
-TQString KBookmarkBar::parentAddress()
-{
- return dptr()->m_filteredMgr ? TQString::null : m_pManager->toolbar().address();
-}
-
-#define CURRENT_TOOLBAR() ( \
- dptr()->m_filteredMgr ? dptr()->m_filteredMgr->root() \
- : m_pManager->toolbar() )
-
-#define CURRENT_MANAGER() ( \
- dptr()->m_filteredMgr ? dptr()->m_filteredMgr \
- : m_pManager )
-
-KBookmarkGroup KBookmarkBar::getToolbar()
-{
- if ( KBookmarkSettings::self()->m_filteredtoolbar )
- {
- if ( !dptr()->m_filteredMgr ) {
- dptr()->m_filteredMgr = KBookmarkManager::createTempManager();
- } else {
- KBookmarkGroup bkRoot = dptr()->m_filteredMgr->root();
- TQValueList<KBookmark> bks;
- for (KBookmark bm = bkRoot.first(); !bm.isNull(); bm = bkRoot.next(bm))
- bks << bm;
- for ( TQValueListConstIterator<KBookmark> it = bks.begin(); it != bks.end(); ++it )
- bkRoot.deleteBookmark( (*it) );
- }
- ToolbarFilter filter;
- KBookmarkDomBuilder builder( dptr()->m_filteredMgr->root(),
- dptr()->m_filteredMgr );
- builder.connectImporter( &filter );
- filter.filter( m_pManager->root() );
- }
-
- return CURRENT_TOOLBAR();
-}
-
-KBookmarkBar::~KBookmarkBar()
-{
- //clear();
- KBookmarkBarPrivate::delete_d(this);
-}
-
-void KBookmarkBar::clear()
-{
- TQPtrListIterator<KAction> it( dptr()->m_actions );
- m_toolBar->clear();
- for (; it.current(); ++it ) {
- (*it)->unplugAll();
- }
- dptr()->m_actions.clear();
- m_lstSubMenus.clear();
-}
-
-void KBookmarkBar::slotBookmarksChanged( const TQString & group )
-{
- KBookmarkGroup tb = getToolbar(); // heavy for non cached toolbar version
- kdDebug(7043) << "slotBookmarksChanged( " << group << " )" << endl;
-
- if ( tb.isNull() )
- return;
-
- if ( KBookmark::commonParent(group, tb.address()) == group // Is group a parent of tb.address?
- || KBookmarkSettings::self()->m_filteredtoolbar )
- {
- clear();
- fillBookmarkBar( tb );
- }
- else
- {
- // Iterate recursively into child menus
- TQPtrListIterator<KBookmarkMenu> it( m_lstSubMenus );
- for (; it.current(); ++it )
- {
- it.current()->slotBookmarksChanged( group );
- }
- }
-}
-
-void KBookmarkBar::fillBookmarkBar(KBookmarkGroup & parent)
-{
- if (parent.isNull())
- return;
-
- for (KBookmark bm = parent.first(); !bm.isNull(); bm = parent.next(bm))
- {
- TQString text = bm.text();
- text.replace( '&', "&&" );
- if (!bm.isGroup())
- {
- if ( bm.isSeparator() )
- m_toolBar->insertLineSeparator();
- else
- {
- KAction *action = new KBookmarkAction( text, bm.icon(), 0, m_actionCollection, 0 );
- connect(action, TQT_SIGNAL( activated ( KAction::ActivationReason, TQt::ButtonState )),
- this, TQT_SLOT( slotBookmarkSelected( KAction::ActivationReason, TQt::ButtonState ) ));
-
- action->setProperty( "url", bm.url().url() );
- action->setProperty( "address", bm.address() );
-
- action->setToolTip( bm.url().pathOrURL() );
-
- action->plug(m_toolBar);
-
- dptr()->m_actions.append( action );
- }
- }
- else
- {
- KActionMenu *action = new KBookmarkActionMenu( text, bm.icon(),
- m_actionCollection,
- "bookmarkbar-actionmenu");
- action->setProperty( "address", bm.address() );
- action->setProperty( "readOnly", dptr()->m_readOnly );
- action->setDelayed( false );
-
- // this flag doesn't have any UI yet
- TDEGlobal::config()->setGroup( "Settings" );
- bool addEntriesBookmarkBar = TDEGlobal::config()->readBoolEntry("AddEntriesBookmarkBar",true);
-
- KBookmarkMenu *menu = new KBookmarkMenu(CURRENT_MANAGER(), m_pOwner, action->popupMenu(),
- m_actionCollection, false, addEntriesBookmarkBar,
- bm.address());
- connect(menu, TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu * ) ),
- this, TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu * ) ));
- connect(menu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState) ),
- this, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState) ));
- menu->fillBookmarkMenu();
- action->plug(m_toolBar);
- m_lstSubMenus.append( menu );
-
- dptr()->m_actions.append( action );
- }
- }
-}
-
-void KBookmarkBar::setReadOnly(bool readOnly)
-{
- dptr()->m_readOnly = readOnly;
-}
-
-bool KBookmarkBar::isReadOnly() const
-{
- return dptr()->m_readOnly;
-}
-
-void KBookmarkBar::slotBookmarkSelected( KAction::ActivationReason /*reason*/, TQt::ButtonState state )
-{
- if (!m_pOwner) return; // this view doesn't handle bookmarks...
-
- const KAction* action = dynamic_cast<const KAction *>(sender());
- if(action)
- {
- const TQString & url = sender()->property("url").toString();
- m_pOwner->openBookmarkURL(url);
- emit openBookmark( url, state );
- }
-}
-
-void KBookmarkBar::slotBookmarkSelected()
-{
- slotBookmarkSelected(KAction::ToolBarActivation, Qt::NoButton);
-}
-
-static const int const_sepId = -9999; // FIXME this is ugly,
- // surely there is another
- // way of doing this...
-
-static void removeTempSep(KBookmarkBarPrivate* p)
-{
- if (p->m_sepToolBar) {
- p->m_sepToolBar->removeItem(const_sepId);
- p->m_sepToolBar = 0; // needed?
- }
-}
-
-static KAction* findPluggedAction(TQPtrList<KAction> actions, KToolBar *tb, int id)
-{
- TQPtrListIterator<KAction> it( actions );
- for (; (*it); ++it )
- if ((*it)->isPlugged(tb, id))
- return (*it);
- return 0;
-}
-
-/**
- * Handle a TQDragMoveEvent event on a toolbar drop
- * @return the address of the bookmark to be dropped after/before
- * else a TQString::null if event should be ignored
- * @param pos the current TQDragMoveEvent position
- * @param the toolbar
- * @param actions the list of actions plugged into the bar
- * @param atFirst bool reference, when true the position before the
- * returned action was dropped on
- */
-static TQString handleToolbarDragMoveEvent(
- KBookmarkBarPrivate *p, KToolBar *tb, TQPoint pos, TQPtrList<KAction> actions,
- bool &atFirst, KBookmarkManager *mgr
-) {
- Q_UNUSED( mgr );
- Q_ASSERT( actions.isEmpty() || (tb == dynamic_cast<KToolBar*>(actions.first()->container(0))) );
- p->m_sepToolBar = tb;
- p->m_sepToolBar->removeItemDelayed(const_sepId);
-
- int index = 0;
- KToolBarButton* b;
-
- b = dynamic_cast<KToolBarButton*>(tb->childAt(pos));
- KAction *a = 0;
- TQString address;
- atFirst = false;
-
- if (b)
- {
- index = tb->itemIndex(b->id());
- TQRect r = b->geometry();
- if (pos.x() < ((r.left() + r.right())/2))
- {
- // if in first half of button then
- // we jump to previous index
- if ( index == 0 )
- atFirst = true;
- else {
- index--;
- b = tb->getButton(tb->idAt(index));
- }
- }
- }
- else if (actions.isEmpty())
- {
- atFirst = true;
- index = 0;
- // we skip the action related stuff
- // and do what it should have...
- // FIXME - here we want to get the
- // parent address of the bookmark
- // bar itself and return that + "/0"
- p->m_sepIndex = 0;
- goto skipact;
- }
- else // (!b)
- {
- index = actions.count() - 1;
- b = tb->getButton(tb->idAt(index));
- // if !b and not past last button, we didn't find button
- if (pos.x() <= b->geometry().left())
- goto skipact; // TODO - rename
- }
-
- if ( !b )
- return TQString::null; // TODO Make it works for that case
-
- a = findPluggedAction(actions, tb, b->id());
- Q_ASSERT(a);
- address = a->property("address").toString();
- p->m_sepIndex = index + (atFirst ? 0 : 1);
-
-#if 0
- { // ugly workaround to fix the goto scoping problems...
- KBookmark bk = mgr->findByAddress( address );
- if (bk.isGroup()) // TODO - fix this ****!!!, manhatten distance should be used!!!
- {
- kdDebug() << "kbookmarkbar:: popping up " << bk.text() << endl;
- KBookmarkActionMenu *menu = dynamic_cast<KBookmarkActionMenu*>(a);
- Q_ASSERT(menu);
- menu->popup(tb->mapToGlobal(b->geometry().center()));
- }
- }
-#endif
-
-skipact:
- tb->insertLineSeparator(p->m_sepIndex, const_sepId);
- return address;
-}
-
-// TODO - document!!!!
-static KAction* handleToolbarMouseButton(TQPoint pos, TQPtrList<KAction> actions,
- KBookmarkManager * /*mgr*/, TQPoint & pt)
-{
- KAction *act = actions.first();
- if (!act) {
- return 0;
- }
-
- KToolBar *tb = dynamic_cast<KToolBar*>(act->container(0));
- Q_ASSERT(tb);
-
- KToolBarButton *b;
- b = dynamic_cast<KToolBarButton*>(tb->childAt(pos));
- if (!b)
- return 0;
-
- KAction *a = 0;
- a = findPluggedAction(actions, tb, b->id());
- Q_ASSERT(a);
- pt = tb->mapToGlobal(pos);
-
- return a;
-}
-
-// TODO *** drop improvements ***
-// open submenus on drop interactions
-
-// TODO *** generic rmb improvements ***
-// don't *ever* show the rmb on press, always relase, possible???
-
-class KBookmarkBarRMBAssoc : public dPtrTemplate<KBookmarkBar, RMB> { };
-template<> TQPtrDict<RMB>* dPtrTemplate<KBookmarkBar, RMB>::d_ptr = 0;
-
-static RMB* rmbSelf(KBookmarkBar *m) { return KBookmarkBarRMBAssoc::d(m); }
-
-void RMB::begin_rmb_action(KBookmarkBar *self)
-{
- RMB *s = rmbSelf(self);
- s->recv = self;
- s->m_parentAddress = self->parentAddress();
- s->s_highlightedAddress = self->dptr()->m_highlightedAddress; // rename in RMB
- s->m_pManager = self->m_pManager;
- s->m_pOwner = self->m_pOwner;
- s->m_parentMenu = 0;
-}
-
-void KBookmarkBar::slotRMBActionEditAt( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionEditAt( val ); }
-
-void KBookmarkBar::slotRMBActionProperties( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionProperties( val ); }
-
-void KBookmarkBar::slotRMBActionInsert( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionInsert( val ); }
-
-void KBookmarkBar::slotRMBActionRemove( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionRemove( val ); }
-
-void KBookmarkBar::slotRMBActionCopyLocation( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionCopyLocation( val ); }
-
-bool KBookmarkBar::eventFilter( TQObject *o, TQEvent *e )
-{
- if (dptr()->m_readOnly || dptr()->m_filteredMgr) // note, we assume m_pManager in various places,
- // this shouldn't really be the case
- return false; // todo: make this limit the actions
-
- if ( (e->type() == TQEvent::MouseButtonRelease) || (e->type() == TQEvent::MouseButtonPress) ) // FIXME, which one?
- {
- TQMouseEvent *mev = (TQMouseEvent*)e;
-
- TQPoint pt;
- KAction *_a;
-
- // FIXME, see how this holds up on an empty toolbar
- _a = handleToolbarMouseButton( mev->pos(), dptr()->m_actions, m_pManager, pt );
- if (_a && mev->button() == Qt::RightButton)
- {
- dptr()->m_highlightedAddress = _a->property("address").toString();
- KBookmark bookmark = m_pManager->findByAddress( dptr()->m_highlightedAddress );
- RMB::begin_rmb_action(this);
- KPopupMenu *pm = new KPopupMenu;
- rmbSelf(this)->fillContextMenu( pm, dptr()->m_highlightedAddress, 0 );
- emit aboutToShowContextMenu( rmbSelf(this)->atAddress( dptr()->m_highlightedAddress ), pm );
- rmbSelf(this)->fillContextMenu2( pm, dptr()->m_highlightedAddress, 0 );
- pm->popup( pt );
- mev->accept();
- }
-
- return !!_a; // ignore the event if we didn't find the button
- }
- else if ( e->type() == TQEvent::DragLeave )
- {
- removeTempSep(dptr());
- dptr()->m_dropAddress = TQString::null;
- }
- else if ( e->type() == TQEvent::Drop )
- {
- removeTempSep(dptr());
- TQDropEvent *dev = (TQDropEvent*)e;
- if ( !KBookmarkDrag::canDecode( dev ) )
- return false;
- TQValueList<KBookmark> list = KBookmarkDrag::decode( dev );
- if (list.count() > 1)
- kdWarning(7043) << "Sorry, currently you can only drop one address "
- "onto the bookmark bar!" << endl;
- KBookmark toInsert = list.first();
- KBookmark bookmark = m_pManager->findByAddress( dptr()->m_dropAddress );
- Q_ASSERT(!bookmark.isNull());
- kdDebug(7043) << "inserting "
- << TQString(dptr()->m_atFirst ? "before" : "after")
- << " dptr()->m_dropAddress == " << dptr()->m_dropAddress << endl;
- KBookmarkGroup parentBookmark = bookmark.parentGroup();
- Q_ASSERT(!parentBookmark.isNull());
- KBookmark newBookmark = parentBookmark.addBookmark(
- m_pManager, toInsert.fullText(),
- toInsert.url() );
- parentBookmark.moveItem( newBookmark, dptr()->m_atFirst ? KBookmark() : bookmark );
- m_pManager->emitChanged( parentBookmark );
- return true;
- }
- else if ( e->type() == TQEvent::DragMove )
- {
- TQDragMoveEvent *dme = (TQDragMoveEvent*)e;
- if (!KBookmarkDrag::canDecode( dme ))
- return false;
- bool _atFirst;
- TQString dropAddress;
- KToolBar *tb = (KToolBar*)o;
- dropAddress = handleToolbarDragMoveEvent(dptr(), tb, dme->pos(), dptr()->m_actions, _atFirst, m_pManager);
- if (!dropAddress.isNull())
- {
- dptr()->m_dropAddress = dropAddress;
- dptr()->m_atFirst = _atFirst;
- dme->accept();
- }
- }
- return false;
-}
-
-static bool showInToolbar( const KBookmark &bk ) {
- return (bk.internalElement().attributes().namedItem("showintoolbar").toAttr().value() == "yes");
-}
-
-void ToolbarFilter::visit( const KBookmark &bk ) {
- //kdDebug() << "visit(" << bk.text() << ")" << endl;
- if ( m_visible || showInToolbar(bk) )
- KXBELBookmarkImporterImpl::visit(bk);
-}
-
-void ToolbarFilter::visitEnter( const KBookmarkGroup &grp ) {
- //kdDebug() << "visitEnter(" << grp.text() << ")" << endl;
- if ( !m_visible && showInToolbar(grp) )
- {
- m_visibleStart = grp;
- m_visible = true;
- }
- if ( m_visible )
- KXBELBookmarkImporterImpl::visitEnter(grp);
-}
-
-void ToolbarFilter::visitLeave( const KBookmarkGroup &grp ) {
- //kdDebug() << "visitLeave()" << endl;
- if ( m_visible )
- KXBELBookmarkImporterImpl::visitLeave(grp);
- if ( m_visible && grp.address() == m_visibleStart.address() )
- m_visible = false;
-}
-
-#include "kbookmarkbar.moc"
diff --git a/kio/bookmarks/kbookmarkimporter.cc b/kio/bookmarks/kbookmarkimporter.cc
deleted file mode 100644
index 8a31fa3d2..000000000
--- a/kio/bookmarks/kbookmarkimporter.cc
+++ /dev/null
@@ -1,101 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE libraries
- Copyright (C) 2003 Alexander Kellett <lypanov@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kfiledialog.h>
-#include <kstringhandler.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <kcharsets.h>
-#include <tqtextcodec.h>
-
-#include <sys/types.h>
-#include <stddef.h>
-#include <dirent.h>
-#include <sys/stat.h>
-#include <assert.h>
-
-#include "kbookmarkmanager.h"
-
-#include "kbookmarkimporter_ns.h"
-#include "kbookmarkimporter_opera.h"
-#include "kbookmarkimporter_ie.h"
-
-#include "kbookmarkimporter.h"
-
-void KXBELBookmarkImporterImpl::parse()
-{
- //kdDebug() << "KXBELBookmarkImporterImpl::parse()" << endl;
- KBookmarkManager *manager = KBookmarkManager::managerForFile(m_fileName);
- KBookmarkGroup root = manager->root();
- traverse(root);
- // FIXME delete it!
- // delete manager;
-}
-
-void KXBELBookmarkImporterImpl::visit(const KBookmark &bk)
-{
- //kdDebug() << "KXBELBookmarkImporterImpl::visit" << endl;
- if (bk.isSeparator())
- emit newSeparator();
- else
- emit newBookmark(bk.fullText(), bk.url().url().utf8(), "");
-}
-
-void KXBELBookmarkImporterImpl::visitEnter(const KBookmarkGroup &grp)
-{
- //kdDebug() << "KXBELBookmarkImporterImpl::visitEnter" << endl;
- emit newFolder(grp.fullText(), false, "");
-}
-
-void KXBELBookmarkImporterImpl::visitLeave(const KBookmarkGroup &)
-{
- //kdDebug() << "KXBELBookmarkImporterImpl::visitLeave" << endl;
- emit endFolder();
-}
-
-void KBookmarkImporterBase::setupSignalForwards(TQObject *src, TQObject *dst)
-{
- connect(src, TQT_SIGNAL( newBookmark( const TQString &, const TQCString &, const TQString & ) ),
- dst, TQT_SIGNAL( newBookmark( const TQString &, const TQCString &, const TQString & ) ));
- connect(src, TQT_SIGNAL( newFolder( const TQString &, bool, const TQString & ) ),
- dst, TQT_SIGNAL( newFolder( const TQString &, bool, const TQString & ) ));
- connect(src, TQT_SIGNAL( newSeparator() ),
- dst, TQT_SIGNAL( newSeparator() ) );
- connect(src, TQT_SIGNAL( endFolder() ),
- dst, TQT_SIGNAL( endFolder() ) );
-}
-
-KBookmarkImporterBase* KBookmarkImporterBase::factory( const TQString &type )
-{
- if (type == "netscape")
- return new KNSBookmarkImporterImpl;
- else if (type == "mozilla")
- return new KMozillaBookmarkImporterImpl;
- else if (type == "xbel")
- return new KXBELBookmarkImporterImpl;
- else if (type == "ie")
- return new KIEBookmarkImporterImpl;
- else if (type == "opera")
- return new KOperaBookmarkImporterImpl;
- else
- return 0;
-}
-
-#include <kbookmarkimporter.moc>
diff --git a/kio/bookmarks/kbookmarkimporter_crash.cc b/kio/bookmarks/kbookmarkimporter_crash.cc
deleted file mode 100644
index 988e1f673..000000000
--- a/kio/bookmarks/kbookmarkimporter_crash.cc
+++ /dev/null
@@ -1,215 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE libraries
- Copyright (C) 2002-2003 Alexander Kellett <lypanov@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kbookmarkimporter_crash.h"
-
-#include <kfiledialog.h>
-#include <kstringhandler.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <kapplication.h>
-#include <kstandarddirs.h>
-#include <tqfile.h>
-#include <tqdir.h>
-#include <tqstring.h>
-#include <tqtextcodec.h>
-#include <dcopclient.h>
-
-#include <sys/types.h>
-#include <stddef.h>
-#include <dirent.h>
-#include <sys/stat.h>
-
-typedef TQMap<TQString, TQString> ViewMap;
-
-// KDE 4.0: remove this BC keeping stub
-void KCrashBookmarkImporter::parseCrashLog( TQString /*filename*/, bool /*del*/ )
-{
- ;
-}
-
-ViewMap KCrashBookmarkImporterImpl::parseCrashLog_noemit( const TQString & filename, bool del )
-{
- static const int g_lineLimit = 16*1024;
-
- TQFile f( filename );
- ViewMap views;
-
- if ( !f.open( IO_ReadOnly ) )
- return views;
-
- TQCString s( g_lineLimit );
-
- TQTextCodec * codec = TQTextCodec::codecForName( "UTF-8" );
- Q_ASSERT( codec );
- if ( !codec )
- return views;
-
- while ( f.readLine( s.data(), g_lineLimit ) >=0 )
- {
- if ( s[s.length()-1] != '\n' )
- {
- kdWarning() << "Crash bookmarks contain a line longer than " << g_lineLimit << ". Skipping." << endl;
- continue;
- }
- TQString t = codec->toUnicode( s.stripWhiteSpace() );
- TQRegExp rx( "(.*)\\((.*)\\):(.*)$" );
- rx.setMinimal( true );
- if ( !rx.exactMatch( t ) )
- continue;
- if ( rx.cap(1) == "opened" )
- views[rx.cap(2)] = rx.cap(3);
- else if ( rx.cap(1) == "close" )
- views.remove( rx.cap(2) );
- }
-
- f.close();
-
- if ( del )
- f.remove();
-
- return views;
-}
-
-TQStringList KCrashBookmarkImporter::getCrashLogs()
-{
- return KCrashBookmarkImporterImpl::getCrashLogs();
-}
-
-TQStringList KCrashBookmarkImporterImpl::getCrashLogs()
-{
- TQMap<TQString, bool> activeLogs;
-
- DCOPClient* dcop = kapp->dcopClient();
-
- QCStringList apps = dcop->registeredApplications();
- for ( QCStringList::Iterator it = apps.begin(); it != apps.end(); ++it )
- {
- TQCString &clientId = *it;
-
- if ( tqstrncmp(clientId, "konqueror", 9) != 0 )
- continue;
-
- TQByteArray data, replyData;
- TQCString replyType;
- TQDataStream arg( data, IO_WriteOnly );
-
- if ( !dcop->call( clientId.data(), "KonquerorIface",
- "crashLogFile()", data, replyType, replyData) )
- {
- kdWarning() << "can't find dcop function KonquerorIface::crashLogFile()" << endl;
- continue;
- }
-
- if ( replyType != "TQString" )
- continue;
-
- TQDataStream reply( replyData, IO_ReadOnly );
- TQString ret;
- reply >> ret;
- activeLogs[ret] = true;
- }
-
- TQDir d( KCrashBookmarkImporterImpl().findDefaultLocation() );
- d.setSorting( TQDir::Time );
- d.setFilter( TQDir::Files );
- d.setNameFilter( "konqueror-crash-*.log" );
-
- const TQFileInfoList *list = d.entryInfoList();
- TQFileInfoListIterator it( *list );
-
- TQFileInfo *fi;
- TQStringList crashFiles;
-
- int count = 0;
- for ( ; (( fi = it.current() ) != 0) && (count < 20); ++it, ++count )
- {
- bool stillAlive = activeLogs.contains( fi->absFilePath() );
- if ( !stillAlive )
- crashFiles << fi->absFilePath();
- }
- // Delete remaining ones
- for ( ; ( fi = it.current() ) != 0; ++it )
- {
- TQFile::remove( fi->absFilePath() );
- }
-
- return crashFiles;
-}
-
-void KCrashBookmarkImporterImpl::parse()
-{
- TQDict<bool> signatureMap;
- TQStringList crashFiles = KCrashBookmarkImporterImpl::getCrashLogs();
- int count = 1;
- for ( TQStringList::Iterator it = crashFiles.begin(); it != crashFiles.end(); ++it )
- {
- ViewMap views;
- views = parseCrashLog_noemit( *it, m_shouldDelete );
- TQString signature;
- for ( ViewMap::Iterator vit = views.begin(); vit != views.end(); ++vit )
- signature += "|"+vit.data();
- if (signatureMap[signature])
- {
- // Duplicate... throw away and skip
- TQFile::remove(*it);
- continue;
- }
-
- signatureMap.insert(signature, (bool *) true); // hack
-
- int outerFolder = ( crashFiles.count() > 1 ) && (views.count() > 0);
- if ( outerFolder )
- emit newFolder( TQString("Konqueror Window %1").arg(count++), false, "" );
- for ( ViewMap::Iterator vit = views.begin(); vit != views.end(); ++vit )
- emit newBookmark( vit.data(), vit.data().latin1(), TQString("") );
- if ( outerFolder )
- emit endFolder();
- }
-}
-
-TQString KCrashBookmarkImporter::crashBookmarksDir()
-{
- static KCrashBookmarkImporterImpl *p = 0;
- if (!p)
- p = new KCrashBookmarkImporterImpl;
- return p->findDefaultLocation();
-}
-
-void KCrashBookmarkImporterImpl::setShouldDelete( bool shouldDelete )
-{
- m_shouldDelete = shouldDelete;
-}
-
-void KCrashBookmarkImporter::parseCrashBookmarks( bool del )
-{
- KCrashBookmarkImporterImpl importer;
- importer.setFilename( m_fileName );
- importer.setShouldDelete( del );
- importer.setupSignalForwards( &importer, this );
- importer.parse();
-}
-
-TQString KCrashBookmarkImporterImpl::findDefaultLocation( bool ) const
-{
- return locateLocal( "tmp", "" );
-}
-
-#include "kbookmarkimporter_crash.moc"
diff --git a/kio/bookmarks/kbookmarkimporter_ie.cc b/kio/bookmarks/kbookmarkimporter_ie.cc
deleted file mode 100644
index 8d1372194..000000000
--- a/kio/bookmarks/kbookmarkimporter_ie.cc
+++ /dev/null
@@ -1,185 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE libraries
- Copyright (C) 2002-2003 Alexander Kellett <lypanov@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kfiledialog.h>
-#include <kstringhandler.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <tqtextcodec.h>
-
-#include <sys/types.h>
-#include <stddef.h>
-#include <dirent.h>
-#include <sys/stat.h>
-
-#include "kbookmarkimporter.h"
-#include "kbookmarkimporter_ie.h"
-
-/* antlarr: KDE 4: Make them const TQString & */
-void KIEBookmarkImporter::parseIEBookmarks_url_file( TQString filename, TQString name ) {
- static const int g_lineLimit = 16*1024;
-
- TQFile f(filename);
-
- if(f.open(IO_ReadOnly)) {
-
- TQCString s(g_lineLimit);
-
- while(f.readLine(s.data(), g_lineLimit)>=0) {
- if ( s[s.length()-1] != '\n' ) // Gosh, this line is longer than g_lineLimit. Skipping.
- {
- kdWarning() << "IE bookmarks contain a line longer than " << g_lineLimit << ". Skipping." << endl;
- continue;
- }
- TQCString t = s.stripWhiteSpace();
- TQRegExp rx( "URL=(.*)" );
- if (rx.exactMatch(t)) {
- emit newBookmark( name, TQString(rx.cap(1)).latin1(), TQString("") );
- }
- }
-
- f.close();
- }
-}
-
-/* antlarr: KDE 4: Make them const TQString & */
-void KIEBookmarkImporter::parseIEBookmarks_dir( TQString dirname, TQString foldername )
-{
-
- TQDir dir(dirname);
- dir.setFilter( TQDir::Files | TQDir::Dirs );
- dir.setSorting( TQDir::Name | TQDir::DirsFirst );
- dir.setNameFilter("*.url"); // AK - possibly add ";index.ini" ?
- dir.setMatchAllDirs(true);
-
- const TQFileInfoList *list = dir.entryInfoList();
- if (!list) return;
-
- if (dirname != m_fileName)
- emit newFolder( foldername, false, "" );
-
- TQFileInfoListIterator it( *list );
- TQFileInfo *fi;
-
- while ( (fi = it.current()) != 0 ) {
- ++it;
-
- if (fi->fileName() == "." || fi->fileName() == "..") continue;
-
- if (fi->isDir()) {
- parseIEBookmarks_dir(fi->absFilePath(), fi->fileName());
-
- } else if (fi->isFile()) {
- if (fi->fileName().endsWith(".url")) {
- TQString name = fi->fileName();
- name.truncate(name.length() - 4); // .url
- parseIEBookmarks_url_file(fi->absFilePath(), name);
- }
- // AK - add index.ini
- }
- }
-
- if (dirname != m_fileName)
- emit endFolder();
-}
-
-
-void KIEBookmarkImporter::parseIEBookmarks( )
-{
- parseIEBookmarks_dir( m_fileName );
-}
-
-TQString KIEBookmarkImporter::IEBookmarksDir()
-{
- static KIEBookmarkImporterImpl* p = 0;
- if (!p)
- p = new KIEBookmarkImporterImpl;
- return p->findDefaultLocation();
-}
-
-void KIEBookmarkImporterImpl::parse() {
- KIEBookmarkImporter importer(m_fileName);
- setupSignalForwards(&importer, this);
- importer.parseIEBookmarks();
-}
-
-TQString KIEBookmarkImporterImpl::findDefaultLocation(bool) const
-{
- // notify user that they must give a new dir such
- // as "Favourites" as otherwise it'll just place
- // lots of .url files in the given dir and gui
- // stuff in the exporter is ugly so that exclues
- // the possibility of just writing to Favourites
- // and checking if overwriting...
- return KFileDialog::getExistingDirectory();
-}
-
-/////////////////////////////////////////////////
-
-class IEExporter : private KBookmarkGroupTraverser {
-public:
- IEExporter( const TQString & );
- void write( const KBookmarkGroup &grp ) { traverse(grp); };
-private:
- virtual void visit( const KBookmark & );
- virtual void visitEnter( const KBookmarkGroup & );
- virtual void visitLeave( const KBookmarkGroup & );
-private:
- TQDir m_currentDir;
-};
-
-static TQString ieStyleQuote( const TQString &str ) {
- TQString s(str);
- s.replace(TQRegExp("[/\\:*?\"<>|]"), "_");
- return s;
-}
-
-IEExporter::IEExporter( const TQString & dname ) {
- m_currentDir.setPath( dname );
-}
-
-void IEExporter::visit( const KBookmark &bk ) {
- TQString fname = m_currentDir.path() + "/" + ieStyleQuote( bk.fullText() ) + ".url";
- // kdDebug() << "visit(" << bk.text() << "), fname == " << fname << endl;
- TQFile file( fname );
- file.open( IO_WriteOnly );
- TQTextStream ts( &file );
- ts << "[InternetShortcut]\r\n";
- ts << "URL=" << bk.url().url().utf8() << "\r\n";
-}
-
-void IEExporter::visitEnter( const KBookmarkGroup &grp ) {
- TQString dname = m_currentDir.path() + "/" + ieStyleQuote( grp.fullText() );
- // kdDebug() << "visitEnter(" << grp.text() << "), dname == " << dname << endl;
- m_currentDir.mkdir( dname );
- m_currentDir.cd( dname );
-}
-
-void IEExporter::visitLeave( const KBookmarkGroup & ) {
- // kdDebug() << "visitLeave()" << endl;
- m_currentDir.cdUp();
-}
-
-void KIEBookmarkExporterImpl::write(KBookmarkGroup parent) {
- IEExporter exporter( m_fileName );
- exporter.write( parent );
-}
-
-#include "kbookmarkimporter_ie.moc"
diff --git a/kio/bookmarks/kbookmarkimporter_kde1.cc b/kio/bookmarks/kbookmarkimporter_kde1.cc
deleted file mode 100644
index ac0d29b97..000000000
--- a/kio/bookmarks/kbookmarkimporter_kde1.cc
+++ /dev/null
@@ -1,156 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kbookmarkimporter_kde1.h"
-#include <kfiledialog.h>
-#include <kstringhandler.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <kcharsets.h>
-#include <tqtextcodec.h>
-
-#include <sys/types.h>
-#include <stddef.h>
-#include <dirent.h>
-#include <sys/stat.h>
-#include <assert.h>
-
-////////////////////
-
-void KBookmarkImporter::import( const TQString & path )
-{
- TQDomElement elem = m_pDoc->documentElement();
- Q_ASSERT(!elem.isNull());
- scanIntern( elem, path );
-}
-
-void KBookmarkImporter::scanIntern( TQDomElement & parentElem, const TQString & _path )
-{
- kdDebug(7043) << "KBookmarkImporter::scanIntern " << _path << endl;
- // Substitute all symbolic links in the path
- TQDir dir( _path );
- TQString canonical = dir.canonicalPath();
-
- if ( m_lstParsedDirs.contains(canonical) )
- {
- kdWarning() << "Directory " << canonical << " already parsed" << endl;
- return;
- }
-
- m_lstParsedDirs.append( canonical );
-
- DIR *dp;
- struct dirent *ep;
- dp = opendir( TQFile::encodeName(_path) );
- if ( dp == 0L )
- return;
-
- // Loop thru all directory entries
- while ( ( ep = readdir( dp ) ) != 0L )
- {
- if ( strcmp( ep->d_name, "." ) != 0 && strcmp( ep->d_name, ".." ) != 0 )
- {
- KURL file;
- file.setPath( TQString( _path ) + '/' + TQFile::decodeName(ep->d_name) );
-
- KMimeType::Ptr res = KMimeType::findByURL( file, 0, true );
- //kdDebug(7043) << " - " << file.url() << " -> " << res->name() << endl;
-
- if ( res->name() == "inode/directory" )
- {
- // We could use KBookmarkGroup::createNewFolder, but then it
- // would notify about the change, so we'd need a flag, etc.
- TQDomElement groupElem = m_pDoc->createElement( "folder" );
- parentElem.appendChild( groupElem );
- TQDomElement textElem = m_pDoc->createElement( "title" );
- groupElem.appendChild( textElem );
- textElem.appendChild( m_pDoc->createTextNode( TDEIO::decodeFileName( ep->d_name ) ) );
- if ( TDEIO::decodeFileName( ep->d_name ) == "Toolbar" )
- groupElem.setAttribute("toolbar","yes");
- scanIntern( groupElem, file.path() );
- }
- else if ( (res->name() == "application/x-desktop")
- || (res->name() == "media/builtin-mydocuments")
- || (res->name() == "media/builtin-mycomputer")
- || (res->name() == "media/builtin-mynetworkplaces")
- || (res->name() == "media/builtin-printers")
- || (res->name() == "media/builtin-trash")
- || (res->name() == "media/builtin-webbrowser") )
- {
- KSimpleConfig cfg( file.path(), true );
- cfg.setDesktopGroup();
- TQString type = cfg.readEntry( "Type" );
- // Is it really a bookmark file ?
- if ( type == "Link" )
- parseBookmark( parentElem, ep->d_name, cfg, 0 /* desktop group */ );
- else
- kdWarning(7043) << " Not a link ? Type=" << type << endl;
- }
- else if ( res->name() == "text/plain")
- {
- // maybe its an IE Favourite..
- KSimpleConfig cfg( file.path(), true );
- TQStringList grp = cfg.groupList().grep( "internetshortcut", false );
- if ( grp.count() == 0 )
- continue;
- cfg.setGroup( *grp.begin() );
-
- TQString url = cfg.readPathEntry("URL");
- if (!url.isEmpty() )
- parseBookmark( parentElem, ep->d_name, cfg, *grp.begin() );
- } else
- kdWarning(7043) << "Invalid bookmark : found mimetype='" << res->name() << "' for file='" << file.path() << "'!" << endl;
- }
- }
-
- closedir( dp );
-}
-
-void KBookmarkImporter::parseBookmark( TQDomElement & parentElem, TQCString _text,
- KSimpleConfig& _cfg, const TQString &_group )
-{
- if ( !_group.isEmpty() )
- _cfg.setGroup( _group );
- else
- _cfg.setDesktopGroup();
-
- TQString url = _cfg.readPathEntry( "URL" );
- TQString icon = _cfg.readEntry( "Icon" );
- if (icon.right( 4 ) == ".xpm" ) // prevent warnings
- icon.truncate( icon.length() - 4 );
-
- TQString text = TDEIO::decodeFileName( TQString::fromLocal8Bit(_text) );
- if ( text.length() > 8 && text.right( 8 ) == ".desktop" )
- text.truncate( text.length() - 8 );
- if ( text.length() > 7 && text.right( 7 ) == ".kdelnk" )
- text.truncate( text.length() - 7 );
-
- TQDomElement elem = m_pDoc->createElement( "bookmark" );
- parentElem.appendChild( elem );
- elem.setAttribute( "href", url );
- //if ( icon != "www" ) // No need to save the default
- // Hmm, after all, it makes KBookmark::pixmapFile faster,
- // and it shows a nice feature to those reading the file
- elem.setAttribute( "icon", icon );
- TQDomElement textElem = m_pDoc->createElement( "title" );
- elem.appendChild( textElem );
- textElem.appendChild( m_pDoc->createTextNode( text ) );
- kdDebug(7043) << "KBookmarkImporter::parseBookmark text=" << text << endl;
-}
diff --git a/kio/bookmarks/kbookmarkimporter_ns.cc b/kio/bookmarks/kbookmarkimporter_ns.cc
deleted file mode 100644
index 5521bee7e..000000000
--- a/kio/bookmarks/kbookmarkimporter_ns.cc
+++ /dev/null
@@ -1,243 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE libraries
- Copyright (C) 1996-1998 Martin R. Jones <mjones@kde.org>
- Copyright (C) 2000 David Faure <faure@kde.org>
- Copyright (C) 2003 Alexander Kellett <lypanov@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kbookmarkimporter.h"
-#include "kbookmarkexporter.h"
-#include "kbookmarkmanager.h"
-#include <kfiledialog.h>
-#include <kstringhandler.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <kcharsets.h>
-#include <tqtextcodec.h>
-#include <tqstylesheet.h>
-
-#include <sys/types.h>
-#include <stddef.h>
-#include <dirent.h>
-#include <sys/stat.h>
-#include <assert.h>
-
-void KNSBookmarkImporterImpl::parse()
-{
- TQFile f(m_fileName);
- TQTextCodec * codec = m_utf8 ? TQTextCodec::codecForName("UTF-8") : TQTextCodec::codecForLocale();
- Q_ASSERT(codec);
- if (!codec)
- return;
-
- if(f.open(IO_ReadOnly)) {
-
- static const int g_lineLimit = 16*1024;
- TQCString s(g_lineLimit);
- // skip header
- while(f.readLine(s.data(), g_lineLimit) >= 0 && !s.contains("<DL>"));
-
- while(f.readLine(s.data(), g_lineLimit)>=0) {
- if ( s[s.length()-1] != '\n' ) // Gosh, this line is longer than g_lineLimit. Skipping.
- {
- kdWarning() << "Netscape bookmarks contain a line longer than " << g_lineLimit << ". Skipping." << endl;
- continue;
- }
- TQCString t = s.stripWhiteSpace();
- if(t.left(12).upper() == "<DT><A HREF=" ||
- t.left(16).upper() == "<DT><H3><A HREF=") {
- int firstQuotes = t.find('"')+1;
- int secondQuotes = t.find('"', firstQuotes);
- if (firstQuotes != -1 && secondQuotes != -1)
- {
- TQCString link = t.mid(firstQuotes, secondQuotes-firstQuotes);
- int endTag = t.find('>', secondQuotes+1);
- TQCString name = t.mid(endTag+1);
- name = name.left(name.findRev('<'));
- if ( name.right(4) == "</A>" )
- name = name.left( name.length() - 4 );
- TQString qname = KCharsets::resolveEntities( codec->toUnicode( name ) );
- TQCString additionalInfo = t.mid( secondQuotes+1, endTag-secondQuotes-1 );
-
- emit newBookmark( qname,
- link, codec->toUnicode(additionalInfo) );
- }
- }
- else if(t.left(7).upper() == "<DT><H3") {
- int endTag = t.find('>', 7);
- TQCString name = t.mid(endTag+1);
- name = name.left(name.findRev('<'));
- TQString qname = KCharsets::resolveEntities( codec->toUnicode( name ) );
- TQCString additionalInfo = t.mid( 8, endTag-8 );
- bool folded = (additionalInfo.left(6) == "FOLDED");
- if (folded) additionalInfo.remove(0,7);
-
- emit newFolder( qname,
- !folded,
- codec->toUnicode(additionalInfo) );
- }
- else if(t.left(4).upper() == "<HR>")
- emit newSeparator();
- else if(t.left(8).upper() == "</DL><P>")
- emit endFolder();
- }
-
- f.close();
- }
-}
-
-TQString KNSBookmarkImporterImpl::findDefaultLocation(bool forSaving) const
-{
- if (m_utf8)
- {
- if ( forSaving )
- return KFileDialog::getSaveFileName( TQDir::homeDirPath() + "/.mozilla",
- i18n("*.html|HTML Files (*.html)") );
- else
- return KFileDialog::getOpenFileName( TQDir::homeDirPath() + "/.mozilla",
- i18n("*.html|HTML Files (*.html)") );
- }
- else
- {
- return TQDir::homeDirPath() + "/.netscape/bookmarks.html";
- }
-}
-
-////////////////////////////////////////////////////////////////
-
-
-void KNSBookmarkImporter::parseNSBookmarks( bool utf8 )
-{
- KNSBookmarkImporterImpl importer;
- importer.setFilename(m_fileName);
- importer.setUtf8(utf8);
- importer.setupSignalForwards(&importer, this);
- importer.parse();
-}
-
-TQString KNSBookmarkImporter::netscapeBookmarksFile( bool forSaving )
-{
- static KNSBookmarkImporterImpl *p = 0;
- if (!p)
- {
- p = new KNSBookmarkImporterImpl;
- p->setUtf8(false);
- }
- return p->findDefaultLocation(forSaving);
-}
-
-TQString KNSBookmarkImporter::mozillaBookmarksFile( bool forSaving )
-{
- static KNSBookmarkImporterImpl *p = 0;
- if (!p)
- {
- p = new KNSBookmarkImporterImpl;
- p->setUtf8(true);
- }
- return p->findDefaultLocation(forSaving);
-}
-
-
-////////////////////////////////////////////////////////////////
-// compat only
-////////////////////////////////////////////////////////////////
-
-void KNSBookmarkExporter::write(bool utf8) {
- KNSBookmarkExporterImpl exporter(m_pManager, m_fileName);
- exporter.setUtf8(utf8);
- exporter.write(m_pManager->root());
-}
-
-void KNSBookmarkExporter::writeFolder(TQTextStream &/*stream*/, KBookmarkGroup /*gp*/) {
- // TODO - requires a d pointer workaround hack?
-}
-
-////////////////////////////////////////////////////////////////
-
-void KNSBookmarkExporterImpl::setUtf8(bool utf8) {
- m_utf8 = utf8;
-}
-
-void KNSBookmarkExporterImpl::write(KBookmarkGroup parent) {
- if (TQFile::exists(m_fileName)) {
- ::rename(
- TQFile::encodeName(m_fileName),
- TQFile::encodeName(m_fileName + ".beforekde"));
- }
-
- TQFile file(m_fileName);
-
- if (!file.open(IO_WriteOnly)) {
- kdError(7043) << "Can't write to file " << m_fileName << endl;
- return;
- }
-
- TQTextStream fstream(&file);
- fstream.setEncoding(m_utf8 ? TQTextStream::UnicodeUTF8 : TQTextStream::Locale);
-
- TQString charset
- = m_utf8 ? "UTF-8" : TQString::fromLatin1(TQTextCodec::codecForLocale()->name()).upper();
-
- fstream << "<!DOCTYPE NETSCAPE-Bookmark-file-1>" << endl
- << i18n("<!-- This file was generated by Konqueror -->") << endl
- << "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset="
- << charset << "\">" << endl
- << "<TITLE>" << i18n("Bookmarks") << "</TITLE>" << endl
- << "<H1>" << i18n("Bookmarks") << "</H1>" << endl
- << "<DL><p>" << endl
- << folderAsString(parent)
- << "</DL><P>" << endl;
-}
-
-TQString KNSBookmarkExporterImpl::folderAsString(KBookmarkGroup parent) const {
- TQString str;
- TQTextStream fstream(&str, IO_WriteOnly);
-
- for (KBookmark bk = parent.first(); !bk.isNull(); bk = parent.next(bk)) {
- if (bk.isSeparator()) {
- fstream << "<HR>" << endl;
- continue;
- }
-
- TQString text = TQStyleSheet::escape(bk.fullText());
-
- if (bk.isGroup() ) {
- fstream << "<DT><H3 "
- << (!bk.toGroup().isOpen() ? "FOLDED " : "")
- << bk.internalElement().attribute("netscapeinfo") << ">"
- << text << "</H3>" << endl
- << "<DL><P>" << endl
- << folderAsString(bk.toGroup())
- << "</DL><P>" << endl;
- continue;
-
- } else {
- // note - netscape seems to use local8bit for url...
- fstream << "<DT><A HREF=\"" << bk.url().url() << "\""
- << bk.internalElement().attribute("netscapeinfo") << ">"
- << text << "</A>" << endl;
- continue;
- }
- }
-
- return str;
-}
-
-////
-
-#include "kbookmarkimporter_ns.moc"
diff --git a/kio/bookmarks/kbookmarkimporter_opera.cc b/kio/bookmarks/kbookmarkimporter_opera.cc
deleted file mode 100644
index 45ac1a7ca..000000000
--- a/kio/bookmarks/kbookmarkimporter_opera.cc
+++ /dev/null
@@ -1,170 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE libraries
- Copyright (C) 2002-2003 Alexander Kellett <lypanov@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kfiledialog.h>
-#include <kstringhandler.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <tqtextcodec.h>
-
-#include <sys/types.h>
-#include <stddef.h>
-#include <dirent.h>
-#include <sys/stat.h>
-
-#include "kbookmarkimporter.h"
-#include "kbookmarkimporter_opera.h"
-
-void KOperaBookmarkImporter::parseOperaBookmarks( )
-{
- TQFile file(m_fileName);
- if(!file.open(IO_ReadOnly)) {
- return;
- }
-
- TQTextCodec * codec = TQTextCodec::codecForName("UTF-8");
- Q_ASSERT(codec);
- if (!codec)
- return;
-
- int lineno = 0;
- TQString url, name, type;
- static const int g_lineLimit = 16*1024;
- TQCString line(g_lineLimit);
-
- while ( file.readLine(line.data(), g_lineLimit) >=0 ) {
- lineno++;
-
- // skip lines that didn't fit in buffer and first two headers lines
- if ( line[line.length()-1] != '\n' || lineno <= 2 )
- continue;
-
- TQString currentLine = codec->toUnicode(line).stripWhiteSpace();
-
- if (currentLine.isEmpty()) {
- // end of data block
- if (type.isNull())
- continue;
- else if ( type == "URL")
- emit newBookmark( name, url.latin1(), "" );
- else if (type == "FOLDER" )
- emit newFolder( name, false, "" );
-
- type = TQString::null;
- name = TQString::null;
- url = TQString::null;
-
- } else if (currentLine == "-") {
- // end of folder
- emit endFolder();
-
- } else {
- // data block line
- TQString tag;
- if ( tag = "#", currentLine.startsWith( tag ) )
- type = currentLine.remove( 0, tag.length() );
- else if ( tag = "NAME=", currentLine.startsWith( tag ) )
- name = currentLine.remove(0, tag.length());
- else if ( tag = "URL=", currentLine.startsWith( tag ) )
- url = currentLine.remove(0, tag.length());
- }
- }
-
-}
-
-TQString KOperaBookmarkImporter::operaBookmarksFile()
-{
- static KOperaBookmarkImporterImpl *p = 0;
- if (!p)
- p = new KOperaBookmarkImporterImpl;
- return p->findDefaultLocation();
-}
-
-void KOperaBookmarkImporterImpl::parse() {
- KOperaBookmarkImporter importer(m_fileName);
- setupSignalForwards(&importer, this);
- importer.parseOperaBookmarks();
-}
-
-TQString KOperaBookmarkImporterImpl::findDefaultLocation(bool saving) const
-{
- return saving ? KFileDialog::getSaveFileName(
- TQDir::homeDirPath() + "/.opera",
- i18n("*.adr|Opera Bookmark Files (*.adr)") )
- : KFileDialog::getOpenFileName(
- TQDir::homeDirPath() + "/.opera",
- i18n("*.adr|Opera Bookmark Files (*.adr)") );
-}
-
-/////////////////////////////////////////////////
-
-class OperaExporter : private KBookmarkGroupTraverser {
-public:
- OperaExporter();
- TQString generate( const KBookmarkGroup &grp ) { traverse(grp); return m_string; };
-private:
- virtual void visit( const KBookmark & );
- virtual void visitEnter( const KBookmarkGroup & );
- virtual void visitLeave( const KBookmarkGroup & );
-private:
- TQString m_string;
- TQTextStream m_out;
-};
-
-OperaExporter::OperaExporter() : m_out(&m_string, IO_WriteOnly) {
- m_out << "Opera Hotlist version 2.0" << endl;
- m_out << "Options: encoding = utf8, version=3" << endl;
-}
-
-void OperaExporter::visit( const KBookmark &bk ) {
- // kdDebug() << "visit(" << bk.text() << ")" << endl;
- m_out << "#URL" << endl;
- m_out << "\tNAME=" << bk.fullText() << endl;
- m_out << "\tURL=" << bk.url().url().utf8() << endl;
- m_out << endl;
-}
-
-void OperaExporter::visitEnter( const KBookmarkGroup &grp ) {
- // kdDebug() << "visitEnter(" << grp.text() << ")" << endl;
- m_out << "#FOLDER" << endl;
- m_out << "\tNAME="<< grp.fullText() << endl;
- m_out << endl;
-}
-
-void OperaExporter::visitLeave( const KBookmarkGroup & ) {
- // kdDebug() << "visitLeave()" << endl;
- m_out << "-" << endl;
- m_out << endl;
-}
-
-void KOperaBookmarkExporterImpl::write(KBookmarkGroup parent) {
- OperaExporter exporter;
- TQString content = exporter.generate( parent );
- TQFile file(m_fileName);
- if (!file.open(IO_WriteOnly)) {
- kdError(7043) << "Can't write to file " << m_fileName << endl;
- return;
- }
- TQTextStream fstream(&file);
- fstream.setEncoding(TQTextStream::UnicodeUTF8);
- fstream << content;
-}
-
-#include "kbookmarkimporter_opera.moc"
diff --git a/kio/bookmarks/kbookmarkmenu.cc b/kio/bookmarks/kbookmarkmenu.cc
deleted file mode 100644
index 5e85bc1f6..000000000
--- a/kio/bookmarks/kbookmarkmenu.cc
+++ /dev/null
@@ -1,1187 +0,0 @@
-// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
-// vim: set ts=4 sts=4 sw=4 et:
-/* This file is part of the KDE project
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kbookmarkmenu.h"
-#include "kbookmarkmenu_p.h"
-#include "kbookmarkimporter.h"
-#include "kbookmarkimporter_opera.h"
-#include "kbookmarkimporter_ie.h"
-#include "kbookmarkdrag.h"
-
-#include <kapplication.h>
-#include <kconfig.h>
-#include <kdebug.h>
-#include <kdialogbase.h>
-#include <kiconloader.h>
-#include <klineedit.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <kpopupmenu.h>
-#include <kstdaccel.h>
-#include <kstdaction.h>
-#include <kstringhandler.h>
-
-#include <tqclipboard.h>
-#include <tqfile.h>
-#include <tqheader.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqlineedit.h>
-#include <tqlistview.h>
-#include <tqpushbutton.h>
-
-#include <dptrtemplate.h>
-
-template class TQPtrList<KBookmarkMenu>;
-
-static TQString makeTextNodeMod(KBookmark bk, const TQString &m_nodename, const TQString &m_newText) {
- TQDomNode subnode = bk.internalElement().namedItem(m_nodename);
- if (subnode.isNull()) {
- subnode = bk.internalElement().ownerDocument().createElement(m_nodename);
- bk.internalElement().appendChild(subnode);
- }
-
- if (subnode.firstChild().isNull()) {
- TQDomText domtext = subnode.ownerDocument().createTextNode("");
- subnode.appendChild(domtext);
- }
-
- TQDomText domtext = subnode.firstChild().toText();
-
- TQString m_oldText = domtext.data();
- domtext.setData(m_newText);
-
- return m_oldText;
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-KBookmarkMenu::KBookmarkMenu( KBookmarkManager* mgr,
- KBookmarkOwner * _owner, KPopupMenu * _parentMenu,
- KActionCollection *collec, bool _isRoot, bool _add,
- const TQString & parentAddress )
- : TQObject(),
- m_bIsRoot(_isRoot), m_bAddBookmark(_add),
- m_bAddShortcuts(true),
- m_pManager(mgr), m_pOwner(_owner),
- m_parentMenu( _parentMenu ),
- m_actionCollection( collec ),
- m_parentAddress( parentAddress )
-{
- m_parentMenu->setKeyboardShortcutsEnabled( true );
-
- m_lstSubMenus.setAutoDelete( true );
- m_actions.setAutoDelete( true );
-
- if (m_actionCollection)
- {
- m_actionCollection->setHighlightingEnabled(true);
- disconnect( m_actionCollection, TQT_SIGNAL( actionHighlighted( KAction * ) ), 0, 0 );
- connect( m_actionCollection, TQT_SIGNAL( actionHighlighted( KAction * ) ),
- this, TQT_SLOT( slotActionHighlighted( KAction * ) ) );
- }
-
- m_bNSBookmark = m_parentAddress.isNull();
- if ( !m_bNSBookmark ) // not for the netscape bookmark
- {
- //kdDebug(7043) << "KBookmarkMenu::KBookmarkMenu " << this << " address : " << m_parentAddress << endl;
-
- connect( _parentMenu, TQT_SIGNAL( aboutToShow() ),
- TQT_SLOT( slotAboutToShow() ) );
-
- if ( KBookmarkSettings::self()->m_contextmenu )
- {
- (void) _parentMenu->contextMenu();
- connect( _parentMenu, TQT_SIGNAL( aboutToShowContextMenu(KPopupMenu*, int, TQPopupMenu*) ),
- this, TQT_SLOT( slotAboutToShowContextMenu(KPopupMenu*, int, TQPopupMenu*) ));
- }
-
- if ( m_bIsRoot )
- {
- connect( m_pManager, TQT_SIGNAL( changed(const TQString &, const TQString &) ),
- TQT_SLOT( slotBookmarksChanged(const TQString &) ) );
- }
- }
-
- // add entries that possibly have a shortcut, so they are available _before_ first popup
- if ( m_bIsRoot )
- {
- if ( m_bAddBookmark )
- {
- addAddBookmark();
- if ( extOwner() )
- addAddBookmarksList(); // FIXME
- }
-
- addEditBookmarks();
- }
-
- m_bDirty = true;
-}
-
-KBookmarkMenu::~KBookmarkMenu()
-{
- //kdDebug(7043) << "KBookmarkMenu::~KBookmarkMenu() " << this << endl;
- TQPtrListIterator<KAction> it( m_actions );
- for (; it.current(); ++it )
- it.current()->unplugAll();
-
- m_lstSubMenus.clear();
- m_actions.clear();
-}
-
-void KBookmarkMenu::ensureUpToDate()
-{
- slotAboutToShow();
-}
-
-void KBookmarkMenu::slotAboutToShow()
-{
- // Did the bookmarks change since the last time we showed them ?
- if ( m_bDirty )
- {
- m_bDirty = false;
- refill();
- }
-}
-
-TQString KBookmarkMenu::s_highlightedAddress;
-TQString KBookmarkMenu::s_highlightedImportType;
-TQString KBookmarkMenu::s_highlightedImportLocation;
-
-void KBookmarkMenu::slotActionHighlighted( KAction* action )
-{
- if (action->isA("KBookmarkActionMenu") || action->isA("KBookmarkAction"))
- {
- s_highlightedAddress = action->property("address").toString();
- //kdDebug() << "KBookmarkMenu::slotActionHighlighted" << s_highlightedAddress << endl;
- }
- else if (action->isA("KImportedBookmarksActionMenu"))
- {
- s_highlightedImportType = action->property("type").toString();
- s_highlightedImportLocation = action->property("location").toString();
- }
- else
- {
- s_highlightedAddress = TQString::null;
- s_highlightedImportType = TQString::null;
- s_highlightedImportLocation = TQString::null;
- }
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-class KBookmarkMenuRMBAssoc : public dPtrTemplate<KBookmarkMenu, RMB> { };
-template<> TQPtrDict<RMB>* dPtrTemplate<KBookmarkMenu, RMB>::d_ptr = 0;
-
-static RMB* rmbSelf(KBookmarkMenu *m) { return KBookmarkMenuRMBAssoc::d(m); }
-
-// TODO check via dcop before making any changes to the bookmarks file???
-
-void RMB::begin_rmb_action(KBookmarkMenu *self)
-{
- RMB *s = rmbSelf(self);
- s->recv = self;
- s->m_parentAddress = self->m_parentAddress;
- s->s_highlightedAddress = KBookmarkMenu::s_highlightedAddress;
- s->m_pManager = self->m_pManager;
- s->m_pOwner = self->m_pOwner;
- s->m_parentMenu = self->m_parentMenu;
-}
-
-bool RMB::invalid( int val )
-{
- bool valid = true;
-
- if (val == 1)
- s_highlightedAddress = m_parentAddress;
-
- if (s_highlightedAddress.isNull())
- valid = false;
-
- return !valid;
-}
-
-KBookmark RMB::atAddress(const TQString & address)
-{
- KBookmark bookmark = m_pManager->findByAddress( address );
- Q_ASSERT(!bookmark.isNull());
- return bookmark;
-}
-
-void KBookmarkMenu::slotAboutToShowContextMenu( KPopupMenu*, int, TQPopupMenu* contextMenu )
-{
- //kdDebug(7043) << "KBookmarkMenu::slotAboutToShowContextMenu" << s_highlightedAddress << endl;
- if (s_highlightedAddress.isNull())
- {
- KPopupMenu::contextMenuFocus()->hideContextMenu();
- return;
- }
- contextMenu->clear();
- fillContextMenu( contextMenu, s_highlightedAddress, 0 );
-}
-
-void RMB::fillContextMenu( TQPopupMenu* contextMenu, const TQString & address, int val )
-{
- KBookmark bookmark = atAddress(address);
-
- int id;
-
- // binner:
- // "Add Bookmark Here" when pointing at a bookmark looks strange and if you
- // call it you have to close and reopen the menu to see an entry was added?
- //
- // TODO rename these, but, message freeze... umm...
-
-// if (bookmark.isGroup()) {
- id = contextMenu->insertItem( SmallIcon("bookmark_add"), i18n( "Add Bookmark Here" ), recv, TQT_SLOT(slotRMBActionInsert(int)) );
- contextMenu->setItemParameter( id, val );
-/* }
- else
- {
- id = contextMenu->insertItem( SmallIcon("bookmark_add"), i18n( "Add Bookmark Here" ), recv, TQT_SLOT(slotRMBActionInsert(int)) );
- contextMenu->setItemParameter( id, val );
- }*/
-}
-
-void RMB::fillContextMenu2( TQPopupMenu* contextMenu, const TQString & address, int val )
-{
- KBookmark bookmark = atAddress(address);
-
- int id;
-
- if (bookmark.isGroup()) {
- id = contextMenu->insertItem( i18n( "Open Folder in Bookmark Editor" ), recv, TQT_SLOT(slotRMBActionEditAt(int)) );
- contextMenu->setItemParameter( id, val );
- contextMenu->insertSeparator();
- id = contextMenu->insertItem( SmallIcon("editdelete"), i18n( "Delete Folder" ), recv, TQT_SLOT(slotRMBActionRemove(int)) );
- contextMenu->setItemParameter( id, val );
- contextMenu->insertSeparator();
- id = contextMenu->insertItem( i18n( "Properties" ), recv, TQT_SLOT(slotRMBActionProperties(int)) );
- contextMenu->setItemParameter( id, val );
- }
- else
- {
- id = contextMenu->insertItem( i18n( "Copy Link Address" ), recv, TQT_SLOT(slotRMBActionCopyLocation(int)) );
- contextMenu->setItemParameter( id, val );
- contextMenu->insertSeparator();
- id = contextMenu->insertItem( SmallIcon("editdelete"), i18n( "Delete Bookmark" ), recv, TQT_SLOT(slotRMBActionRemove(int)) );
- contextMenu->setItemParameter( id, val );
- contextMenu->insertSeparator();
- id = contextMenu->insertItem( i18n( "Properties" ), recv, TQT_SLOT(slotRMBActionProperties(int)) );
- contextMenu->setItemParameter( id, val );
- }
-}
-
-void RMB::slotRMBActionEditAt( int val )
-{
- kdDebug(7043) << "KBookmarkMenu::slotRMBActionEditAt" << s_highlightedAddress << endl;
- if (invalid(val)) { hidePopup(); return; }
-
- KBookmark bookmark = atAddress(s_highlightedAddress);
-
- m_pManager->slotEditBookmarksAtAddress( s_highlightedAddress );
-}
-
-void RMB::slotRMBActionProperties( int val )
-{
- kdDebug(7043) << "KBookmarkMenu::slotRMBActionProperties" << s_highlightedAddress << endl;
- if (invalid(val)) { hidePopup(); return; }
-
- KBookmark bookmark = atAddress(s_highlightedAddress);
-
- TQString folder = bookmark.isGroup() ? TQString::null : bookmark.url().pathOrURL();
- KBookmarkEditDialog dlg( bookmark.fullText(), folder,
- m_pManager, KBookmarkEditDialog::ModifyMode, 0,
- 0, 0, i18n("Bookmark Properties") );
- if ( dlg.exec() != KDialogBase::Accepted )
- return;
-
- makeTextNodeMod(bookmark, "title", dlg.finalTitle());
- if ( !dlg.finalUrl().isNull() )
- {
- KURL u = KURL::fromPathOrURL(dlg.finalUrl());
- bookmark.internalElement().setAttribute("href", u.url(0, 106));
- }
-
- kdDebug(7043) << "Requested move to " << dlg.finalAddress() << "!" << endl;
-
- KBookmarkGroup parentBookmark = atAddress(m_parentAddress).toGroup();
- m_pManager->emitChanged( parentBookmark );
-}
-
-void RMB::slotRMBActionInsert( int val )
-{
- kdDebug(7043) << "KBookmarkMenu::slotRMBActionInsert" << s_highlightedAddress << endl;
- if (invalid(val)) { hidePopup(); return; }
-
- TQString url = m_pOwner->currentURL();
- if (url.isEmpty())
- {
- KMessageBox::error( 0L, i18n("Cannot add bookmark with empty URL."));
- return;
- }
- TQString title = m_pOwner->currentTitle();
- if (title.isEmpty())
- title = url;
-
- KBookmark bookmark = atAddress( s_highlightedAddress );
-
- // TODO use unique title
-
- if (bookmark.isGroup())
- {
- KBookmarkGroup parentBookmark = bookmark.toGroup();
- Q_ASSERT(!parentBookmark.isNull());
- parentBookmark.addBookmark( m_pManager, title, KURL( url ) );
- m_pManager->emitChanged( parentBookmark );
- }
- else
- {
- KBookmarkGroup parentBookmark = bookmark.parentGroup();
- Q_ASSERT(!parentBookmark.isNull());
- KBookmark newBookmark = parentBookmark.addBookmark( m_pManager, title, KURL( url ) );
- parentBookmark.moveItem( newBookmark, parentBookmark.previous(bookmark) );
- m_pManager->emitChanged( parentBookmark );
- }
-}
-
-void RMB::slotRMBActionRemove( int val )
-{
- //kdDebug(7043) << "KBookmarkMenu::slotRMBActionRemove" << s_highlightedAddress << endl;
- if (invalid(val)) { hidePopup(); return; }
-
- KBookmark bookmark = atAddress( s_highlightedAddress );
- bool folder = bookmark.isGroup();
-
- if (KMessageBox::warningContinueCancel(
- m_parentMenu,
- folder ? i18n("Are you sure you wish to remove the bookmark folder\n\"%1\"?").arg(bookmark.text())
- : i18n("Are you sure you wish to remove the bookmark\n\"%1\"?").arg(bookmark.text()),
- folder ? i18n("Bookmark Folder Deletion")
- : i18n("Bookmark Deletion"),
- KStdGuiItem::del())
- != KMessageBox::Continue
- )
- return;
-
- KBookmarkGroup parentBookmark = atAddress( m_parentAddress ).toGroup();
- parentBookmark.deleteBookmark( bookmark );
- m_pManager->emitChanged( parentBookmark );
- if (m_parentMenu)
- m_parentMenu->hide();
-}
-
-void RMB::slotRMBActionCopyLocation( int val )
-{
- //kdDebug(7043) << "KBookmarkMenu::slotRMBActionCopyLocation" << s_highlightedAddress << endl;
- if (invalid(val)) { hidePopup(); return; }
-
- KBookmark bookmark = atAddress( s_highlightedAddress );
-
- if ( !bookmark.isGroup() )
- {
- kapp->clipboard()->setData( KBookmarkDrag::newDrag(bookmark, 0),
- TQClipboard::Selection );
- kapp->clipboard()->setData( KBookmarkDrag::newDrag(bookmark, 0),
- TQClipboard::Clipboard );
- }
-}
-
-void RMB::hidePopup() {
- KPopupMenu::contextMenuFocus()->hideContextMenu();
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-void KBookmarkMenu::fillContextMenu( TQPopupMenu* contextMenu, const TQString & address, int val )
-{
- RMB::begin_rmb_action(this);
- rmbSelf(this)->fillContextMenu(contextMenu, address, val);
- emit aboutToShowContextMenu( rmbSelf(this)->atAddress(address), contextMenu);
- rmbSelf(this)->fillContextMenu2(contextMenu, address, val);
-}
-
-void KBookmarkMenu::slotRMBActionEditAt( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionEditAt( val ); }
-
-void KBookmarkMenu::slotRMBActionProperties( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionProperties( val ); }
-
-void KBookmarkMenu::slotRMBActionInsert( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionInsert( val ); }
-
-void KBookmarkMenu::slotRMBActionRemove( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionRemove( val ); }
-
-void KBookmarkMenu::slotRMBActionCopyLocation( int val )
-{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionCopyLocation( val ); }
-
-void KBookmarkMenu::slotBookmarksChanged( const TQString & groupAddress )
-{
- if (m_bNSBookmark)
- return;
-
- if ( groupAddress == m_parentAddress )
- {
- //kdDebug(7043) << "KBookmarkMenu::slotBookmarksChanged -> setting m_bDirty on " << groupAddress << endl;
- m_bDirty = true;
- }
- else
- {
- // Iterate recursively into child menus
- TQPtrListIterator<KBookmarkMenu> it( m_lstSubMenus );
- for (; it.current(); ++it )
- {
- it.current()->slotBookmarksChanged( groupAddress );
- }
- }
-}
-
-void KBookmarkMenu::refill()
-{
- //kdDebug(7043) << "KBookmarkMenu::refill()" << endl;
- m_lstSubMenus.clear();
-
- TQPtrListIterator<KAction> it( m_actions );
- for (; it.current(); ++it )
- it.current()->unplug( m_parentMenu );
-
- m_parentMenu->clear();
- m_actions.clear();
-
- fillBookmarkMenu();
- m_parentMenu->adjustSize();
-}
-
-void KBookmarkMenu::addAddBookmarksList()
-{
- if (!kapp->authorizeKAction("bookmarks"))
- return;
-
- TQString title = i18n( "Bookmark Tabs as Folder..." );
-
- KAction * paAddBookmarksList = new KAction( title,
- "bookmarks_list_add",
- 0,
- this,
- TQT_SLOT( slotAddBookmarksList() ),
- m_actionCollection, m_bIsRoot ? "add_bookmarks_list" : 0 );
-
- paAddBookmarksList->setToolTip( i18n( "Add a folder of bookmarks for all open tabs." ) );
-
- paAddBookmarksList->plug( m_parentMenu );
- m_actions.append( paAddBookmarksList );
-}
-
-void KBookmarkMenu::addAddBookmark()
-{
- if (!kapp->authorizeKAction("bookmarks"))
- return;
-
- TQString title = i18n( "Add Bookmark" );
-
- KAction * paAddBookmarks = new KAction( title,
- "bookmark_add",
- m_bIsRoot && m_bAddShortcuts ? KStdAccel::addBookmark() : KShortcut(),
- this,
- TQT_SLOT( slotAddBookmark() ),
- m_actionCollection, m_bIsRoot ? "add_bookmark" : 0 );
-
- paAddBookmarks->setToolTip( i18n( "Add a bookmark for the current document" ) );
-
- paAddBookmarks->plug( m_parentMenu );
- m_actions.append( paAddBookmarks );
-}
-
-void KBookmarkMenu::addEditBookmarks()
-{
- if (!kapp->authorizeKAction("bookmarks"))
- return;
-
- KAction * m_paEditBookmarks = KStdAction::editBookmarks( m_pManager, TQT_SLOT( slotEditBookmarks() ),
- m_actionCollection, "edit_bookmarks" );
- m_paEditBookmarks->plug( m_parentMenu );
- m_paEditBookmarks->setToolTip( i18n( "Edit your bookmark collection in a separate window" ) );
- m_actions.append( m_paEditBookmarks );
-}
-
-void KBookmarkMenu::addNewFolder()
-{
- if (!kapp->authorizeKAction("bookmarks"))
- return;
-
- TQString title = i18n( "&New Bookmark Folder..." );
- int p;
- while ( ( p = title.find( '&' ) ) >= 0 )
- title.remove( p, 1 );
-
- KAction * paNewFolder = new KAction( title,
- "folder_new", //"folder",
- 0,
- this,
- TQT_SLOT( slotNewFolder() ),
- m_actionCollection );
-
- paNewFolder->setToolTip( i18n( "Create a new bookmark folder in this menu" ) );
-
- paNewFolder->plug( m_parentMenu );
- m_actions.append( paNewFolder );
-}
-
-void KBookmarkMenu::fillBookmarkMenu()
-{
- if (!kapp->authorizeKAction("bookmarks"))
- return;
-
- if ( m_bIsRoot )
- {
- if ( m_bAddBookmark )
- {
- addAddBookmark();
- if ( extOwner() )
- addAddBookmarksList(); // FIXME
- }
-
- addEditBookmarks();
-
- if ( m_bAddBookmark && !KBookmarkSettings::self()->m_advancedaddbookmark )
- addNewFolder();
- }
-
- if ( m_bIsRoot
- && KBookmarkManager::userBookmarksFile() == m_pManager->path() )
- {
- bool haveSep = false;
-
- TQValueList<TQString> keys = KBookmarkMenu::dynamicBookmarksList();
- TQValueList<TQString>::const_iterator it;
- for ( it = keys.begin(); it != keys.end(); ++it )
- {
- DynMenuInfo info;
- info = showDynamicBookmarks((*it));
-
- if ( !info.show || !TQFile::exists( info.location ) )
- continue;
-
- if (!haveSep)
- {
- m_parentMenu->insertSeparator();
- haveSep = true;
- }
-
- KActionMenu * actionMenu;
- actionMenu = new KImportedBookmarksActionMenu(
- info.name, info.type,
- m_actionCollection, "kbookmarkmenu" );
-
- actionMenu->setProperty( "type", info.type );
- actionMenu->setProperty( "location", info.location );
-
- actionMenu->plug( m_parentMenu );
- m_actions.append( actionMenu );
-
- KBookmarkMenu *subMenu =
- new KBookmarkMenu( m_pManager, m_pOwner, actionMenu->popupMenu(),
- m_actionCollection, false,
- m_bAddBookmark, TQString::null );
- connect( subMenu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ),
- this, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ));
- m_lstSubMenus.append(subMenu);
-
- connect(actionMenu->popupMenu(), TQT_SIGNAL(aboutToShow()), subMenu, TQT_SLOT(slotNSLoad()));
- }
- }
-
- KBookmarkGroup parentBookmark = m_pManager->findByAddress( m_parentAddress ).toGroup();
- Q_ASSERT(!parentBookmark.isNull());
- bool separatorInserted = false;
- for ( KBookmark bm = parentBookmark.first(); !bm.isNull(); bm = parentBookmark.next(bm) )
- {
- TQString text = KStringHandler::csqueeze(bm.fullText(), 60);
- text.replace( '&', "&&" );
- if ( !separatorInserted && m_bIsRoot) {
- // inserted before the first konq bookmark, to avoid the separator if no konq bookmark
- m_parentMenu->insertSeparator();
- separatorInserted = true;
- }
- if ( !bm.isGroup() )
- {
- if ( bm.isSeparator() )
- {
- m_parentMenu->insertSeparator();
- }
- else
- {
- //kdDebug(7043) << "Creating URL bookmark menu item for " << bm.text() << endl;
- KAction * action = new KBookmarkAction( text, bm.icon(), 0, m_actionCollection, 0 );
- connect(action, TQT_SIGNAL( activated ( KAction::ActivationReason, TQt::ButtonState )),
- this, TQT_SLOT( slotBookmarkSelected( KAction::ActivationReason, TQt::ButtonState ) ));
-
- action->setProperty( "url", bm.url().url() );
- action->setProperty( "address", bm.address() );
-
- action->setToolTip( bm.url().pathOrURL() );
-
- action->plug( m_parentMenu );
- m_actions.append( action );
- }
- }
- else
- {
- //kdDebug(7043) << "Creating bookmark submenu named " << bm.text() << endl;
- KActionMenu * actionMenu = new KBookmarkActionMenu( text, bm.icon(),
- m_actionCollection,
- "kbookmarkmenu" );
- actionMenu->setProperty( "address", bm.address() );
- actionMenu->plug( m_parentMenu );
- m_actions.append( actionMenu );
-
- KBookmarkMenu *subMenu = new KBookmarkMenu( m_pManager, m_pOwner, actionMenu->popupMenu(),
- m_actionCollection, false,
- m_bAddBookmark,
- bm.address() );
-
- connect(subMenu, TQT_SIGNAL( aboutToShowContextMenu( const KBookmark &, TQPopupMenu * ) ),
- this, TQT_SIGNAL( aboutToShowContextMenu( const KBookmark &, TQPopupMenu * ) ));
- connect(subMenu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ),
- this, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ));
- m_lstSubMenus.append( subMenu );
- }
- }
-
- if ( !m_bIsRoot && m_bAddBookmark )
- {
- if ( m_parentMenu->count() > 0 )
- m_parentMenu->insertSeparator();
-
- if ( KBookmarkSettings::self()->m_quickactions )
- {
- KActionMenu * actionMenu = new KActionMenu( i18n("Quick Actions"), m_actionCollection, 0L );
- fillContextMenu( actionMenu->popupMenu(), m_parentAddress, 1 );
- actionMenu->plug( m_parentMenu );
- m_actions.append( actionMenu );
- }
- else
- {
- addAddBookmark();
- if ( extOwner() )
- addAddBookmarksList(); // FIXME
- addNewFolder();
- }
- }
-}
-
-void KBookmarkMenu::slotAddBookmarksList()
-{
- KExtendedBookmarkOwner *extOwner = dynamic_cast<KExtendedBookmarkOwner*>(m_pOwner);
- if (!extOwner)
- {
- kdWarning() << "erm, sorry ;-)" << endl;
- return;
- }
-
- KExtendedBookmarkOwner::QStringPairList list;
- extOwner->fillBookmarksList( list );
-
- KBookmarkGroup parentBookmark = m_pManager->findByAddress( m_parentAddress ).toGroup();
- Q_ASSERT(!parentBookmark.isNull());
- KBookmarkGroup group = parentBookmark.createNewFolder( m_pManager );
- if ( group.isNull() )
- return; // user canceled i guess
-
- KExtendedBookmarkOwner::QStringPairList::const_iterator it;
- for ( it = list.begin(); it != list.end(); ++it )
- group.addBookmark( m_pManager, (*it).first, KURL((*it).second) );
-
- m_pManager->emitChanged( parentBookmark );
-}
-
-
-void KBookmarkMenu::slotAddBookmark()
-{
- KBookmarkGroup parentBookmark;
- parentBookmark = m_pManager->addBookmarkDialog(m_pOwner->currentURL(), m_pOwner->currentTitle(), m_parentAddress);
- if (!parentBookmark.isNull())
- m_pManager->emitChanged( parentBookmark );
-}
-
-void KBookmarkMenu::slotNewFolder()
-{
- if ( !m_pOwner ) return; // this view doesn't handle bookmarks...
- KBookmarkGroup parentBookmark = m_pManager->findByAddress( m_parentAddress ).toGroup();
- Q_ASSERT(!parentBookmark.isNull());
- KBookmarkGroup group = parentBookmark.createNewFolder( m_pManager );
- if ( !group.isNull() )
- {
- KBookmarkGroup parentGroup = group.parentGroup();
- m_pManager->emitChanged( parentGroup );
- }
-}
-
-void KBookmarkMenu::slotBookmarkSelected( KAction::ActivationReason /*reason*/, TQt::ButtonState state )
-{
- kdDebug(7043) << "KBookmarkMenu::slotBookmarkSelected()" << endl;
- if ( !m_pOwner ) return; // this view doesn't handle bookmarks...
- const KAction* action = dynamic_cast<const KAction *>(sender());
- if(action)
- {
- const TQString& url = sender()->property("url").toString();
- m_pOwner->openBookmarkURL( url );
- emit openBookmark( url, state );
- }
-}
-
-void KBookmarkMenu::slotBookmarkSelected()
-{
- slotBookmarkSelected(KAction::PopupMenuActivation, Qt::NoButton);
-}
-
-KExtendedBookmarkOwner* KBookmarkMenu::extOwner()
-{
- return dynamic_cast<KExtendedBookmarkOwner*>(m_pOwner);
-}
-
-void KBookmarkMenu::slotNSLoad()
-{
- // only fill menu once
- m_parentMenu->disconnect(TQT_SIGNAL(aboutToShow()));
-
- // not NSImporter, but kept old name for BC reasons
- KBookmarkMenuNSImporter importer( m_pManager, this, m_actionCollection );
- importer.openBookmarks(s_highlightedImportLocation, s_highlightedImportType);
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-KBookmarkEditFields::KBookmarkEditFields(TQWidget *main, TQBoxLayout *vbox, FieldsSet fieldsSet)
-{
- bool isF = (fieldsSet != FolderFieldsSet);
-
- TQGridLayout *grid = new TQGridLayout( vbox, 2, isF ? 2 : 1 );
-
- m_title = new KLineEdit( main );
- grid->addWidget( m_title, 0, 1 );
- grid->addWidget( new TQLabel( m_title, i18n( "Name:" ), main ), 0, 0 );
- m_title->setFocus();
- if (isF)
- {
- m_url = new KLineEdit( main );
- grid->addWidget( m_url, 1, 1 );
- grid->addWidget( new TQLabel( m_url, i18n( "Location:" ), main ), 1, 0 );
- }
- else
- {
- m_url = 0;
- }
-
- main->setMinimumSize( 300, 0 );
-}
-
-void KBookmarkEditFields::setName(const TQString &str)
-{
- m_title->setText(str);
-}
-
-void KBookmarkEditFields::setLocation(const TQString &str)
-{
- m_url->setText(str);
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-// TODO - make the dialog use Properties as a title when in Modify mode... (dirk noticed the bug...)
-KBookmarkEditDialog::KBookmarkEditDialog(const TQString& title, const TQString& url, KBookmarkManager * mgr, BookmarkEditType editType, const TQString& address,
- TQWidget * parent, const char * name, const TQString& caption )
- : KDialogBase(parent, name, true, caption,
- (editType == InsertionMode) ? (User1|Ok|Cancel) : (Ok|Cancel),
- Ok, false, KGuiItem()),
- m_folderTree(0), m_mgr(mgr), m_editType(editType), m_address(address)
-{
- setButtonOK( (editType == InsertionMode) ? KGuiItem( i18n( "&Add" ), "bookmark_add") : i18n( "&Update" ) );
- if (editType == InsertionMode) {
- setButtonGuiItem( User1, KGuiItem( i18n( "&New Folder..." ), "folder_new") );
- }
-
- bool folder = url.isNull();
-
- m_main = new TQWidget( this );
- setMainWidget( m_main );
-
- TQBoxLayout *vbox = new TQVBoxLayout( m_main, 0, spacingHint() );
- KBookmarkEditFields::FieldsSet fs =
- folder ? KBookmarkEditFields::FolderFieldsSet
- : KBookmarkEditFields::BookmarkFieldsSet;
- m_fields = new KBookmarkEditFields(m_main, vbox, fs);
- m_fields->setName(title);
- if ( !folder )
- m_fields->setLocation(url);
-
- if ( editType == InsertionMode )
- {
- m_folderTree = KBookmarkFolderTree::createTree( m_mgr, m_main, name, m_address );
- connect( m_folderTree, TQT_SIGNAL( doubleClicked(TQListViewItem*) ),
- this, TQT_SLOT( slotDoubleClicked(TQListViewItem*) ) );
- vbox->addWidget( m_folderTree );
- connect( this, TQT_SIGNAL( user1Clicked() ), TQT_SLOT( slotUser1() ) );
- }
-}
-
-void KBookmarkEditDialog::slotDoubleClicked( TQListViewItem* item )
-{
- Q_ASSERT( m_folderTree );
- m_folderTree->setCurrentItem( item );
- accept();
-}
-
-void KBookmarkEditDialog::slotOk()
-{
- accept();
-}
-
-void KBookmarkEditDialog::slotCancel()
-{
- reject();
-}
-
-TQString KBookmarkEditDialog::finalAddress() const
-{
- Q_ASSERT( m_folderTree );
- return KBookmarkFolderTree::selectedAddress( m_folderTree );
-}
-
-TQString KBookmarkEditDialog::finalUrl() const
-{
- return m_fields->m_url ? m_fields->m_url->text() : TQString::null;
-}
-
-TQString KBookmarkEditDialog::finalTitle() const
-{
- return m_fields->m_title ? m_fields->m_title->text() : TQString::null;
-}
-
-void KBookmarkEditDialog::slotUser1()
-{
- // kdDebug(7043) << "KBookmarkEditDialog::slotUser1" << endl;
- Q_ASSERT( m_folderTree );
-
- TQString address = KBookmarkFolderTree::selectedAddress( m_folderTree );
- if ( address.isNull() ) return;
- KBookmarkGroup bm = m_mgr->findByAddress( address ).toGroup();
- Q_ASSERT(!bm.isNull());
- Q_ASSERT(m_editType == InsertionMode);
-
- KBookmarkGroup group = bm.createNewFolder( m_mgr );
- if ( !group.isNull() )
- {
- KBookmarkGroup parentGroup = group.parentGroup();
- m_mgr->emitChanged( parentGroup );
- }
- KBookmarkFolderTree::fillTree( m_folderTree, m_mgr );
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-static void fillGroup( TQListView* listview, KBookmarkFolderTreeItem * parentItem, KBookmarkGroup group, bool expandOpenGroups = true, const TQString& address = TQString::null )
-{
- bool noSubGroups = true;
- KBookmarkFolderTreeItem * lastItem = 0L;
- KBookmarkFolderTreeItem * item = 0L;
- for ( KBookmark bk = group.first() ; !bk.isNull() ; bk = group.next(bk) )
- {
- if ( bk.isGroup() )
- {
- KBookmarkGroup grp = bk.toGroup();
- item = new KBookmarkFolderTreeItem( parentItem, lastItem, grp );
- fillGroup( listview, item, grp, expandOpenGroups, address );
- if ( expandOpenGroups && grp.isOpen() )
- item->setOpen( true );
- lastItem = item;
- noSubGroups = false;
- }
- if (bk.address() == address) {
- listview->setCurrentItem( lastItem );
- listview->ensureItemVisible( item );
- }
- }
- if ( noSubGroups ) {
- parentItem->setOpen( true );
- }
-}
-
-TQListView* KBookmarkFolderTree::createTree( KBookmarkManager* mgr, TQWidget* parent, const char* name, const TQString& address )
-{
- TQListView *listview = new TQListView( parent, name );
-
- listview->setRootIsDecorated( false );
- listview->header()->hide();
- listview->addColumn( i18n("Bookmark"), 200 );
- listview->setSorting( -1, false );
- listview->setSelectionMode( TQListView::Single );
- listview->setAllColumnsShowFocus( true );
- listview->setResizeMode( TQListView::AllColumns );
- listview->setMinimumSize( 60, 100 );
-
- fillTree( listview, mgr, address );
-
- return listview;
-}
-
-void KBookmarkFolderTree::fillTree( TQListView *listview, KBookmarkManager* mgr, const TQString& address )
-{
- listview->clear();
-
- KBookmarkGroup root = mgr->root();
- KBookmarkFolderTreeItem * rootItem = new KBookmarkFolderTreeItem( listview, root );
- listview->setCurrentItem( rootItem );
- rootItem->setSelected( true );
- fillGroup( listview, rootItem, root, (address == root.groupAddress() || address.isNull()) ? true : false, address );
- rootItem->setOpen( true );
-}
-
-static KBookmarkFolderTreeItem* ft_cast( TQListViewItem *i )
-{
- return static_cast<KBookmarkFolderTreeItem*>( i );
-}
-
-TQString KBookmarkFolderTree::selectedAddress( TQListView *listview )
-{
- if ( !listview)
- return TQString::null;
- KBookmarkFolderTreeItem *item = ft_cast( listview->currentItem() );
- return item ? item->m_bookmark.address() : TQString::null;
-}
-
-void KBookmarkFolderTree::setAddress( TQListView *listview, const TQString & address )
-{
- KBookmarkFolderTreeItem* it = ft_cast( listview->firstChild() );
- while ( true ) {
- kdDebug(7043) << it->m_bookmark.address() << endl;
- it = ft_cast( it->itemBelow() );
- if ( !it )
- return;
- if ( it->m_bookmark.address() == address )
- break;
- }
- it->setSelected( true );
- listview->setCurrentItem( it );
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-// toplevel item
-KBookmarkFolderTreeItem::KBookmarkFolderTreeItem( TQListView *parent, const KBookmark & gp )
- : TQListViewItem(parent, i18n("Bookmarks")), m_bookmark(gp)
-{
- setPixmap(0, SmallIcon("bookmark"));
- setExpandable(true);
-}
-
-// group
-KBookmarkFolderTreeItem::KBookmarkFolderTreeItem( KBookmarkFolderTreeItem *parent, TQListViewItem *after, const KBookmarkGroup & gp )
- : TQListViewItem(parent, after, gp.fullText()), m_bookmark(gp)
-{
- setPixmap(0, SmallIcon( gp.icon() ) );
- setExpandable(true);
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-// NOTE - KBookmarkMenuNSImporter is really === KBookmarkMenuImporter
-// i.e, it is _not_ ns specific. and in KDE4 it should be renamed.
-
-void KBookmarkMenuNSImporter::openNSBookmarks()
-{
- openBookmarks( KNSBookmarkImporter::netscapeBookmarksFile(), "netscape" );
-}
-
-void KBookmarkMenuNSImporter::openBookmarks( const TQString &location, const TQString &type )
-{
- mstack.push(m_menu);
-
- KBookmarkImporterBase *importer = KBookmarkImporterBase::factory(type);
- if (!importer)
- return;
- importer->setFilename(location);
- connectToImporter(*importer);
- importer->parse();
-
- delete importer;
-}
-
-void KBookmarkMenuNSImporter::connectToImporter(const TQObject &importer)
-{
- connect( &importer, TQT_SIGNAL( newBookmark( const TQString &, const TQCString &, const TQString & ) ),
- TQT_SLOT( newBookmark( const TQString &, const TQCString &, const TQString & ) ) );
- connect( &importer, TQT_SIGNAL( newFolder( const TQString &, bool, const TQString & ) ),
- TQT_SLOT( newFolder( const TQString &, bool, const TQString & ) ) );
- connect( &importer, TQT_SIGNAL( newSeparator() ), TQT_SLOT( newSeparator() ) );
- connect( &importer, TQT_SIGNAL( endFolder() ), TQT_SLOT( endFolder() ) );
-}
-
-void KBookmarkMenuNSImporter::newBookmark( const TQString & text, const TQCString & url, const TQString & )
-{
- TQString _text = KStringHandler::csqueeze(text);
- _text.replace( '&', "&&" );
- KAction * action = new KBookmarkAction(_text, "html", 0, 0, "", m_actionCollection, 0);
- connect(action, TQT_SIGNAL( activated ( KAction::ActivationReason, TQt::ButtonState )),
- m_menu, TQT_SLOT( slotBookmarkSelected( KAction::ActivationReason, TQt::ButtonState ) ));
- action->setProperty( "url", url );
- action->setToolTip( url );
- action->plug( mstack.top()->m_parentMenu );
- mstack.top()->m_actions.append( action );
-}
-
-void KBookmarkMenuNSImporter::newFolder( const TQString & text, bool, const TQString & )
-{
- TQString _text = KStringHandler::csqueeze(text);
- _text.replace( '&', "&&" );
- KActionMenu * actionMenu = new KActionMenu( _text, "folder", m_actionCollection, 0L );
- actionMenu->plug( mstack.top()->m_parentMenu );
- mstack.top()->m_actions.append( actionMenu );
- KBookmarkMenu *subMenu = new KBookmarkMenu( m_pManager, m_menu->m_pOwner, actionMenu->popupMenu(),
- m_actionCollection, false,
- m_menu->m_bAddBookmark, TQString::null );
- connect( subMenu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ),
- m_menu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ));
- mstack.top()->m_lstSubMenus.append( subMenu );
-
- mstack.push(subMenu);
-}
-
-void KBookmarkMenuNSImporter::newSeparator()
-{
- mstack.top()->m_parentMenu->insertSeparator();
-}
-
-void KBookmarkMenuNSImporter::endFolder()
-{
- mstack.pop();
-}
-
-/********************************************************************/
-/********************************************************************/
-/********************************************************************/
-
-KBookmarkMenu::DynMenuInfo KBookmarkMenu::showDynamicBookmarks( const TQString &id )
-{
- TDEConfig config("kbookmarkrc", false, false);
- config.setGroup("Bookmarks");
-
- DynMenuInfo info;
- info.show = false;
-
- if (!config.hasKey("DynamicMenus")) {
- // upgrade path
- if (id == "netscape") {
- KBookmarkManager *manager = KBookmarkManager::userBookmarksManager();
- info.show = manager->root().internalElement().attribute("hide_nsbk") != "yes";
- info.location = KNSBookmarkImporter::netscapeBookmarksFile();
- info.type = "netscape";
- info.name = i18n("Netscape Bookmarks");
- } // else, no show
-
- } else {
- // have new version config
- if (config.hasGroup("DynamicMenu-" + id)) {
- config.setGroup("DynamicMenu-" + id);
- info.show = config.readBoolEntry("Show");
- info.location = config.readPathEntry("Location");
- info.type = config.readEntry("Type");
- info.name = config.readEntry("Name");
- } // else, no show
- }
-
- return info;
-}
-
-TQStringList KBookmarkMenu::dynamicBookmarksList()
-{
- TDEConfig config("kbookmarkrc", false, false);
- config.setGroup("Bookmarks");
-
- TQStringList mlist;
- if (config.hasKey("DynamicMenus"))
- mlist = config.readListEntry("DynamicMenus");
- else
- mlist << "netscape";
-
- return mlist;
-}
-
-void KBookmarkMenu::setDynamicBookmarks(const TQString &id, const DynMenuInfo &newMenu)
-{
- TDEConfig config("kbookmarkrc", false, false);
-
- // add group unconditionally
- config.setGroup("DynamicMenu-" + id);
- config.writeEntry("Show", newMenu.show);
- config.writePathEntry("Location", newMenu.location);
- config.writeEntry("Type", newMenu.type);
- config.writeEntry("Name", newMenu.name);
-
- TQStringList elist;
-
- config.setGroup("Bookmarks");
- if (!config.hasKey("DynamicMenus")) {
- if (newMenu.type != "netscape") {
- // update from old xbel method to new rc method
- // though only if not writing the netscape setting
- config.setGroup("DynamicMenu-" "netscape");
- DynMenuInfo xbelSetting;
- xbelSetting = showDynamicBookmarks("netscape");
- config.writeEntry("Show", xbelSetting.show);
- config.writePathEntry("Location", xbelSetting.location);
- config.writeEntry("Type", xbelSetting.type);
- config.writeEntry("Name", xbelSetting.name);
- }
- } else {
- elist = config.readListEntry("DynamicMenus");
- }
-
- // make sure list includes type
- config.setGroup("Bookmarks");
- if (elist.contains(id) < 1) {
- elist << id;
- config.writeEntry("DynamicMenus", elist);
- }
-
- config.sync();
-}
-
-#include "kbookmarkmenu.moc"
-#include "kbookmarkmenu_p.moc"
diff --git a/kio/data.protocol b/kio/data.protocol
deleted file mode 100644
index 85b0e8b66..000000000
--- a/kio/data.protocol
+++ /dev/null
@@ -1,71 +0,0 @@
-[Protocol]
-protocol=data
-input=stream
-output=none
-reading=true
-Icon=www
-Class=:internet
-Description=A kioslave for data URIs (rfc2397)
-Description[af]= ´n kioslave vir data URIs (rfc2397)
-Description[be]=Модуль kioslave Ð´Ð»Ñ URI з даннÑмі (rfc2397)
-Description[br]=Ur kioslave evit an URIoù roadoù (rfc2397)
-Description[bs]=Kioslave za data URIs (rfc2397)
-Description[ca]=Un kioslave per a URIs de dades (rfc2397)
-Description[cs]=Kioslave pro datová URI (rfc2397)
-Description[csb]=Plugins protokółu pòdôwków URI (rfc2397)
-Description[da]=En kioslave for data-URI'er (rfc2397)
-Description[de]=Ein-/Ausgabemodul für Daten-URIs (rfc2397)
-Description[el]=Ένα kioslave για URI δεδομένων (rfc2397)
-Description[es]=Un kioslave para datos URIs (rfc2397)
-Description[et]=Andme-URI-de I/O-moodul (rfc2397)
-Description[eu]=Datuen URLen (rfc2397) kioslave-a
-Description[fa]=یک kioslave برای URIهای داده )rfc2397(
-Description[fi]=kioslave data URI:lle (rfc2397)
-Description[fr]=Un module d'entrée / sortie pour les URI de données (rfc2397)
-Description[fy]=In kioslave foar data-URI-adresse (rfc2397)
-Description[gl]=Un kioslave para URIs de dados (rfc2397)
-Description[hi]=डाटा यूआरआई (आरà¤à¤«à¤¸à¥€2397) के लिठà¤à¤• के-आई-ओ-सà¥à¤²à¥‡à¤µ
-Description[hr]=kioslave za podatkovne URI-ije (rfc2397)
-Description[hu]=KDE-protokoll adat-URI-k használataához (RFC 2397)
-Description[id]=Kioslave for URI data (rfc2397)
-Description[is]=kioslave fyrir gagnaslóðir (rfc2397)
-Description[it]=Un kioslave per il protocollo di URI di dati (rfc2397)
-Description[ja]=データ URIs (rfc2397) 㮠kioslave
-Description[ka]=URI მáƒáƒœáƒáƒªáƒ”მთრ(rfc2397) დáƒáƒ›áƒ›áƒ£áƒ¨áƒáƒ•áƒ”ბელი
-Description[kk]=URI деректерді өңдеу kioslave модулі (rfc2397)
-Description[km]=kioslave មួយ​សម្រាប់​ទិន្ននáŸáž™ URIs (rfc2397)
-Description[lb]=E kioslave fir Donnéen-URIs (rfc2397)
-Description[lt]=Antrinė KDE programa duomenų URI (rfc2397)
-Description[mk]=kio-Ñлужител за податочни URI (rfc2397)
-Description[ms]=Kioslave untuk URI data (rfc2397)
-Description[nb]=kioslave for data URI-er (rfc2397)
-Description[nds]=In-/Utgaavmoduul för Daten-URIs (rfc2397)
-Description[ne]=डेटा URIs का लागि किओसà¥à¤²à¥‡à¤­ (rfc2397)
-Description[nl]=Een kioslave voor data-URI-adressen (rfc2397)
-Description[nn]=A kioslave for data URI-ar (rfc2397)
-Description[pa]= ਡਾਟਾ URI ਲਈ kioslave(rfc2397)
-Description[pl]=Wtyczka protokołu URI danych (rfc2397)
-Description[pt]=Um 'kioslave' para URIs data (rfc2397)
-Description[pt_BR]=Uma implementação para o protocolo de URIs de dados (rfc2397)
-Description[ro]=Un dispozitiv de I/E pentru URI-urile de date (rfc2397)
-Description[ru]=Обработчик URI данных (rfc2397)
-Description[rw]=Kioslave y'ibyatanzwe URI (rfc2397)
-Description[se]=kiošláva dáhta-URI:aid várás (rfc2397)
-Description[sk]=IO klient pre dátové URI (rfc2397)
-Description[sl]=kioslave za podatkovne URI-je (rfc2397)
-Description[sr]=kioslave за URI-ије података (rfc2397)
-Description[sr@Latn]=kioslave za URI-ije podataka (rfc2397)
-Description[sv]=En I/O-slav för datawebbadresser (RFC 2397)
-Description[ta]=தரவ௠வலைமனைகளà¯à®•à¯à®•à®¾à®© ஒர௠kioslave (rfc2397)
-Description[te]=దతà±à°¤à°¾à°‚శం à°¯à±à°†à°°à±ˆà°² కొరకౠకెà°à°“బానిస (rfc2397)
-Description[tg]=kioslave барои URIs (rfc2397)
-Description[th]=kioslave สำหรับข้อมูล URIs (rfc2397)
-Description[tr]= Veri adresleri için bir kioslave (rfc2397)
-Description[tt]=Biremle URI öçen kioslave (rfc2397)
-Description[uk]=Підлеглий Ð’/Ð’ Ð´Ð»Ñ Ð°Ð´Ñ€ÐµÑ (URI) даних (rfc2397)
-Description[vi]=Một kioslave cho các địa điểm URI kiểu dữ liệu (rfc2397).
-Description[zh_CN]=data URI(rfc2397) çš„ kioslave
-DocPath=kioslave/data.html
-URIMode=rawuri
-defaultMimetype=application/octet-stream
-determineMimetypeFromExtension=false
diff --git a/kio/httpfilter/CMakeLists.txt b/kio/httpfilter/CMakeLists.txt
deleted file mode 100644
index eec4e78a7..000000000
--- a/kio/httpfilter/CMakeLists.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio
-)
-
-
-##### httpfilter ################################
-
-set( target httpfilter )
-
-set( ${target}_SRCS
- httpfilter.cc
-)
-
-tde_add_library( ${target} STATIC_PIC AUTOMOC
- SOURCES ${${target}_SRCS}
-)
diff --git a/kio/httpfilter/httpfilter.cc b/kio/httpfilter/httpfilter.cc
deleted file mode 100644
index 0f2adf20a..000000000
--- a/kio/httpfilter/httpfilter.cc
+++ /dev/null
@@ -1,372 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 2002 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kio/global.h>
-
-#include <klocale.h>
-
-#include "httpfilter.h"
-
-HTTPFilterBase::HTTPFilterBase()
- : last(0)
-{
-}
-
-HTTPFilterBase::~HTTPFilterBase()
-{
- delete last;
-}
-
-void
-HTTPFilterBase::chain(HTTPFilterBase *previous)
-{
- last = previous;
- connect(last, TQT_SIGNAL(output(const TQByteArray &)),
- this, TQT_SLOT(slotInput(const TQByteArray &)));
-}
-
-HTTPFilterChain::HTTPFilterChain()
- : first(0)
-{
-}
-
-void
-HTTPFilterChain::addFilter(HTTPFilterBase *filter)
-{
- if (!last)
- {
- first = filter;
- }
- else
- {
- disconnect(last, TQT_SIGNAL(output(const TQByteArray &)), 0, 0);
- filter->chain(last);
- }
- last = filter;
- connect(filter, TQT_SIGNAL(output(const TQByteArray &)),
- this, TQT_SIGNAL(output(const TQByteArray &)));
- connect(filter, TQT_SIGNAL(error(int, const TQString &)),
- this, TQT_SIGNAL(error(int, const TQString &)));
-}
-
-void
-HTTPFilterChain::slotInput(const TQByteArray &d)
-{
- if (first)
- first->slotInput(d);
- else
- emit output(d);
-}
-
-HTTPFilterMD5::HTTPFilterMD5()
-{
-}
-
-TQString
-HTTPFilterMD5::md5()
-{
- return TQString::fromLatin1(context.base64Digest());
-}
-
-void
-HTTPFilterMD5::slotInput(const TQByteArray &d)
-{
- context.update(d);
- emit output(d);
-}
-
-
-HTTPFilterGZip::HTTPFilterGZip()
-{
-#ifdef DO_GZIP
- bHasHeader = false;
- bHasFinished = false;
- bPlainText = false;
- bEatTrailer = false;
- bEof = false;
- zstr.next_in = (Bytef *) Z_NULL;
- zstr.avail_in = 0;
- zstr.zalloc = Z_NULL;
- zstr.zfree = Z_NULL;
- zstr.opaque = Z_NULL;
-
- inflateInit2(&zstr, -MAX_WBITS);
-
- iTrailer = 8;
-#endif
-}
-
-HTTPFilterGZip::~HTTPFilterGZip()
-{
-#ifdef DO_GZIP
- inflateEnd(&zstr);
-#endif
-
-}
-
-/* The get_byte() and checkHeader() functions are modified version from */
-/* the correpsonding functions that can be found in zlib, the following */
-/* copyright notice applies to these functions: */
-
-/* zlib.h -- interface of the 'zlib' general purpose compression library
- version 1.1.3, July 9th, 1998
-
- Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
-
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
-
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
-
- Jean-loup Gailly Mark Adler
- jloup@gzip.org madler@alumni.caltech.edu
-
-
- The data format used by the zlib library is described by RFCs (Request for
- Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
- (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
-*/
-
-int
-HTTPFilterGZip::get_byte()
-{
-#ifdef DO_GZIP
- if (bEof) return EOF;
- if (zstr.avail_in == 0)
- {
- bEof = true;
- return EOF;
- }
- zstr.avail_in--;
- zstr.total_in++;
- return *(zstr.next_in)++;
-#else
- return 0;
-#endif
-}
-
-#ifdef DO_GZIP
-
-static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
-
-/* gzip flag byte */
-#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
-#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
-#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
-#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
-#define COMMENT 0x10 /* bit 4 set: file comment present */
-#define RESERVED 0xE0 /* bits 5..7: reserved */
-#endif
-
-// 0 : ok
-// 1 : not gzip
-// 2 : no header
-int
-HTTPFilterGZip::checkHeader()
-{
-#ifdef DO_GZIP
- uInt len;
- int c;
-
- /* Check the gzip magic header */
- for (len = 0; len < 2; len++) {
- c = get_byte();
- if (c != gz_magic[len]) {
- if (len != 0)
- {
- zstr.avail_in++;
- zstr.next_in--;
- }
- if (c != EOF) {
- zstr.avail_in++;
- zstr.next_in--;
- return 1;
- }
- return 2;
- }
- }
-
- int method = get_byte(); /* method byte */
- int flags = get_byte(); /* flags byte */
-
- if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
- return bEof ? 2 : 1;
- }
-
- /* Discard time, xflags and OS code: */
- for (len = 0; len < 6; len++) (void)get_byte();
-
- if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
- len = (uInt)get_byte();
- len += ((uInt)get_byte())<<8;
- /* len is garbage if EOF but the loop below will quit anyway */
- while (len-- != 0 && get_byte() != EOF) ;
- }
- if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
- while ((c = get_byte()) != 0 && c != EOF) ;
- }
- if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
- while ((c = get_byte()) != 0 && c != EOF) ;
- }
- if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
- for (len = 0; len < 2; len++) (void)get_byte();
- }
-
- return bEof ? 2 : 0;
-#else
- return 0;
-#endif
-}
-
-void
-HTTPFilterGZip::slotInput(const TQByteArray &d)
-{
-#ifdef DO_GZIP
- if (bPlainText)
- {
- emit output(d);
- return;
- }
- if (d.size() == 0)
- {
- if (bEatTrailer)
- bHasFinished = true;
- if (!bHasFinished)
- {
- // Make sure we get the last bytes still in the pipe.
- // Needed with "deflate".
- TQByteArray flush(4);
- flush.fill(0);
- slotInput(flush);
- if (!bHasFinished && !bHasHeader)
- {
- // Send as-is
- emit output(headerData);
- bHasFinished = true;
- // End of data
- emit output(TQByteArray());
- }
- }
- if (!bHasFinished)
- emit error( TDEIO::ERR_SLAVE_DEFINED, i18n("Unexpected end of data, some information may be lost."));
- return;
- }
- if (bHasFinished)
- return;
-
- if (bEatTrailer)
- {
- iTrailer -= d.size();
- if (iTrailer <= 0)
- {
- bHasFinished = true;
- // End of data
- emit output(TQByteArray());
- }
- return;
- }
-
- if (!bHasHeader)
- {
- bEof = false;
-
- // Add data to header.
- int orig_size = headerData.size();
- headerData.resize(orig_size+d.size());
- memcpy(headerData.data()+orig_size, d.data(), d.size());
-
- zstr.avail_in = headerData.size();
- zstr.next_in = (Bytef *) headerData.data();
-
- int result = checkHeader();
- if (result == 1)
- {
- bPlainText = true;
- output(headerData);
- return;
- }
-
- if (result != 0)
- return; // next time better
-
- bHasHeader = true;
- }
- else
- {
- zstr.avail_in = d.size();
- zstr.next_in = (Bytef *) d.data();
- }
-
- while( zstr.avail_in )
- {
- char buf[8192];
- zstr.next_out = (Bytef *) buf;
- zstr.avail_out = 8192;
- int result = inflate( &zstr, Z_NO_FLUSH );
- if ((result != Z_OK) && (result != Z_STREAM_END))
- {
- emit error( TDEIO::ERR_SLAVE_DEFINED, i18n("Receiving corrupt data."));
- break;
- }
- int bytesOut = 8192 - zstr.avail_out;
- if (bytesOut)
- {
- TQByteArray d;
- d.setRawData( buf, bytesOut );
- emit output(d);
- d.resetRawData( buf, bytesOut );
- }
- if (result == Z_STREAM_END)
- {
- if (iTrailer)
- {
- bEatTrailer = true;
- }
- else
- {
- bHasFinished = true;
- // End of data
- emit output(TQByteArray());
- }
- return;
- }
- }
-#endif
-}
-
-HTTPFilterDeflate::HTTPFilterDeflate()
-{
-#ifdef DO_GZIP
- bHasHeader = true;
- iTrailer = 0;
-#endif
-}
-
-#include "httpfilter.moc"
diff --git a/kio/kfile/CMakeLists.txt b/kio/kfile/CMakeLists.txt
deleted file mode 100644
index 3444fa0da..000000000
--- a/kio/kfile/CMakeLists.txt
+++ /dev/null
@@ -1,76 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdefx
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/bookmarks
- ${LIBART_INCLUDE_DIRS}
-)
-
-
-##### headers ###################################
-
-install( FILES
- kfiledialog.h kencodingfiledialog.h
- kdiroperator.h kfileview.h kfilefiltercombo.h
- kfiledetailview.h kcombiview.h kdiskfreesp.h
- kfileiconview.h krecentdocument.h
- kurlrequester.h kfilepreview.h kfile.h
- kurlcombobox.h kurlrequesterdlg.h kopenwith.h kpropsdlg.h
- kicondialog.h kdirsize.h kpreviewwidgetbase.h kimagefilepreview.h kfilesharedlg.h
- kfiletreeview.h kfiletreeviewitem.h kfiletreebranch.h
- kdirselectdialog.h kurlbar.h kpropertiesdialog.h knotifydialog.h
- kcustommenueditor.h ${CMAKE_CURRENT_BINARY_DIR}/knotifywidgetbase.h
- DESTINATION ${INCLUDE_INSTALL_DIR} )
-
-
-##### other data ################################
-
-install( FILES
- kpropsdlgplugin.desktop
- DESTINATION ${SERVICETYPES_INSTALL_DIR} )
-
-
-##### kfile #####################################
-
-set( target kfile )
-
-set( ${target}_SRCS
- kfilefiltercombo.cpp kfileview.cpp kfileiconview.cpp
- krecentdocument.cpp kfiledialog.cpp kdiroperator.cpp
- kfiledetailview.cpp kcombiview.cpp kurlrequester.cpp
- kfilepreview.cpp kurlcombobox.cpp kurlrequesterdlg.cpp
- kopenwith.cpp kpropertiesdialog.cpp kicondialog.cpp
- kdirsize.cpp krecentdirs.cpp kdiskfreesp.cpp kimagefilepreview.cpp
- kfilesharedlg.cpp kurlbar.cpp kmetaprops.cpp kpreviewprops.cpp
- kfiletreeview.cpp kfiletreeviewitem.cpp kfiletreebranch.cpp
- kdirselectdialog.cpp kfilebookmarkhandler.cpp kfilemetainfowidget.cpp
- kcustommenueditor.cpp knotifywidgetbase.ui knotifydialog.cpp
- kfilespeedbar.cpp kpreviewwidgetbase.cpp kfilemetapreview.cpp
- kpropertiesdesktopbase.ui kpropertiesdesktopadvbase.ui
- kpropertiesmimetypebase.ui kencodingfiledialog.cpp
- kacleditwidget.cpp
-)
-
-tde_add_library( ${target} STATIC_PIC AUTOMOC
- SOURCES ${${target}_SRCS}
-)
diff --git a/kio/kfile/ChangeLog b/kio/kfile/ChangeLog
deleted file mode 100644
index 2c9651390..000000000
--- a/kio/kfile/ChangeLog
+++ /dev/null
@@ -1,725 +0,0 @@
-Sat Feb 26 00:26:55 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kdiroperator.cpp:
- lottsa changes, e.g. action handling more clear now.
- fixed completed item not clearning the previous selection
-
- * kfileviewitem.cpp:
- fixed unreadable pixmap not shown, when files were deleted
-
- * kfiledialog.cpp (selectedURLs):
- re-enabled the hack to support multi-selection, until we have something
- better
-
- * kcombiview.*:
- forward the sorting to the right view (or should it apply to the dir-
- view as well?) Sort of broken tho.
-
-Sun Feb 20 01:50:44 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kdiroperator.*, kfiledialog.* (saveConfig):
- implemented loading, saving and applying configuration
-
- * kfiledialog.cpp (setURL):
- KDirComboBox is now a combo for recent directories as well as the
- root-dir, home-dir and Desktop-dir.
- Recent dirs will be saved in kdeglobals.
-
-Fri Feb 18 23:35:04 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfilefilter.cpp (eventFilter):
- intercept Key_Return and Key_Enter in the filter-combo and emit
- filterChanged instead of letting the dialog close
-
-Thu Feb 17 19:09:54 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfiledialog.{cpp,h} (KDirComboBox):
- Added KDirComboBox and replaced the directory combobox with it. It
- even does something now :) Items need to be indented tho.
-
- * kfilereader.cpp, kdiroperator.{cpp,h}:
- fixed showHidden default
-
-Tue Feb 15 14:21:41 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfile.h (class KFile):
- added a small class that contains all the enums now.
- cleaned up the enums (hope not too many apps will be broken)
- added flags for "Existing files only" and "local files only"
-
- * all views (setSelected()):
- replaced highlightItem(item) with setSelected(item, bool) which makes
- it more suitable and more consistent with Qt.
- added selectionChanged() method (necessary for multiselection)
-
- * kfileview.*:
- added invertSelection()
-
- * kfiledialog.cpp:
- made it work with multiselection
- added static methods for multiselection
- added getOpenURL(), getOpenURLs and getSaveURL()
-
- * kdiroperator.cpp (setSorting):
- added setSorting() and sorting() to keep sorting when switching views
- a few cosmetic and KAction changes
-
-Sun Feb 13 00:45:12 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfiledialog.cpp (completion):
- small fix: completion and auto-directory following works also
- without protocol-part in the location.
-
-Sat Feb 12 15:30:40 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfileview.h:
- made setSorting() and sortReversed() virtual so that subclasses
- can intercept that to show sorting order
-
- * kfiledetailview.cpp,h (setSortIndicator):
- enable header-clicking again to set the sorting
-
-Fri Feb 11 12:17:59 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfiledialog.cpp (KFileDialog):
- fixed filefilter not being applied in constructor
-
-Thu Feb 10 17:06:36 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kdiroperator.cpp (connectView):
- - Now that KToggleAction is fixed, I can commit the new stuff:
- Offer Actions for all the common functionality, i.e. sorting, setting
- the view, home(), cdUp(), back, forward, etc.
- All actions are exposed through a QActionCollection
-
- BTW, I'd really like to have a way to change the state of an action
- without it calling the associated slot. For now I use blockSignals()
- (thanks, Simon), but this sucks.
-
- - renamed fileList to fileView (that was an old relic of KDE 1)
-
- * kfiledialog.*:
- - make use of the new Actions and fill the toolbar again (up, back,
- forward, reload, home).
-
- - the combo in the toolbar is going to change, it does nothing now
- (only shows the Root and Desktop dirs with a nice icon).
-
-Thu Feb 10 12:59:29 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kdiroperator.cpp (insertNewFiles):
- aahhh, finally fixed that infinite loop in KFileView::mergeLists
- clear the view before calling view->addItemList( currentContents );
-
- * kfilereader.cpp (setURL):
- don't disable dirWatch update (setAutoUpdate) when setting a remote URL
-
-Fri Feb 4 12:42:37 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfiledetailview.cpp (insertItem):
- - don't let QListView sort the items
- I disabled clicking at the headers for now, will fix that later
- - don't flicker on mimetype-pixmap update
-
-Thu Feb 3 12:15:16 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfileview.h + all views where necessary
- added selectAll()
- added isSelected( const KFileViewItem * )
- added const KFileViewItemList * selectedItems()
- added const KFileViewItemList * items()
-
- spiced up documentation of KFileView a bit
-
-Sun Jan 30 22:20:14 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfileviewitem.cpp (pixmap):
- fixed some issues for different pixmap sizes
-
- * kfileiconview.{h,cpp} (setPixmapSize):
- added configurability for different pixmap sizes
-
-Sun Jan 30 16:49:12 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfileview.h + all views:
- A view can now have a name (setViewName() and viewName())
- This is useful to differentiate views and to display the names in a
- popupmenu for switching between views.
-
-Sun Jan 30 12:41:04 2000 Werner Trobin <wtrobin@carinthia.com>
- The preview mode works again. It's very similar to the Qt-2.1 QFD
- preview mode - but it's not totally the same. There are some rough
- edges which have to be ironed out, but it works :)
- For further information, see kfilepreview.*
- Note: kpreview and so on are obsolete (IMHO)
-
-Sat Jan 29 15:33:37 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- Time to add some changelogs again, all the recent hard work of the
- restructuring is only in CVS-log...
-
- * kfileview.cpp (compareItems):
- - added support to disable sorting directories first (QDir::DirsFirst)
- - added support to sort by date and to sort reversed
- - removed unused findCompletion method
- - sort case insensitive by default
- - some optimization for mergeList
- - fixed infinite loop in mergeLists, when the lists are the same
- (I think another one is still there, but I'm tired now)
- - changed setSortMode stuff: Switching-mode replaced with
- sortReversed(). The enum Switching will be removed, soon.
- - made setSortMode public
-
- * kfileviewitem.cpp:
- - added time_t mTime() to enable sorting by modification time
-
- * kdiroperator.cpp:
- - offer sorting options in popupmenu
- - use checkAccess before creating directories. I guess this will again
- change when the new kio will be used, tho.
- - show progress widget at the bottom (otherwise the header of e.g.
- the detail-view would be covered).
- - Added LGPL copyright header
-
- * kfilewidget.cpp (connectSignals):
- - connect to all signals of KDirOperator
- - directly connect SIGNAL to SIGNAL -> removed slotFileHighlighted etc.
- - fixed some sorting/merging bugs
-
- * {kfiledialog,kdiroperator}.{cpp,h};
- - support for disabling chdir (some apps may not want KFileDialog /
- KFileReader change the working directory under their feet)
- - Added LGPL header in cpp-file
-
- * kfilereader.cpp (stat):
- - fixed: some special files were recognized as directories
-
- * kfstest.cpp:
- - added test for KFileWidget (widget -> KFileWidget,
- diroperator -> KDirOperator)
-
-Sun Oct 31 00:56:23 1999 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfileinfo.cpp (readUserInfo): Don't call getpwnam() and getgrgid()
- all the time over and over again! This opens and parses /etc/passwd
- or /etc/group with every call!
- Now we load /etc/passwd and /etc/group once and store the interesting
- stuff in static QMaps, which need to be freed with KFileInfo::cleanup()
- cleanup() is called from KFileBaseDialog's destructor.
-
- This speeds up KFileDialog a LOT!
-
-Sat Oct 23 01:55:00 1999 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfiledetaillist.cpp (key): hopefully implemented correct mapping
- from KFileInfo to QListViewItem and back. I had a hard time convincing
- QListView that KFileInfoContents knows best where to insert an item
- Now the detaillist is even usable :)
- Fixed a problem with selection and highlighting
- Disable clicking on listview headers that can't be used for sorting
-
- * kfileinfocontents.cpp (setSorting): call insertItem() with a correct
- (is it?) index, instead of -1
-
-Thu Oct 21 23:18:54 1999 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfiledialog.cpp (init): removed "[development only] from tooltip
- (sorry to break the translations, but this HAD to go)
-
- * don't update anything when leaving the configure-dialog with Cancel
-
-Wed Oct 20 15:07:16 1999 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfileinfo.cpp,h: implemented KFileInfo::filePath() and fixed
- KFileInfo::absURL() not being set in some cases
-
- * kdir.cpp: fixed a buglet in the path (double slashes)
-
- * kfiledetaillist.cpp (KFileDetailList): improved selecting files
- (single click, double click, Return-key)
- but the mapping from QListViewItem to KFileInfo is still quite broken
-
-1999-06-09 Woohyun JANG <louis@mizi.co.kr>
-
- * kdir.cpp: used QString::local8Bit() instead of QString::ascii()
- for file names and directory names.
-
- * kfiledialog.cpp: used QStringList instead of QStrIList.
-
-1999-01-14 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: fixed some GUI problems and moved all default
- configurations into config-kfile.h.
- Changed some default values, so that users that never looked into
- the config dialog gets a nice suprise with 1.1 ;-)
-
- * kfiledialog.cpp: changed selectedFile to return decoded path instead
- of encoded one
-
-Thu Jan 7 23:14:39 1999 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfilesimpleview.cpp (keyPressEvent): fixed segfault on keypress,
- when there were no files at all in the list
-
-1998-12-19 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: fixing an ugly bug when "." is used as argument
-
-Mon Dec 14 23:00:41 1998 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfilebookmark.cpp: renamed class KBookmark to KFileBookmark to
- avoid problems with KFM's KBookmark class. Renamed bookmark.* to
- kfilebookmark.*, too and changed all occurrences of bookmark.* to
- kfilebookmark.* (especially all the .po-files)
-
-Wed Dec 2 15:59:13 1998 Carsten Pfeiffer <pfeiffer@kde.org>
-
- * kfilesimpleview.cpp: Fixed some more keyboard navigation bugs.
- Added method isColCompletelyVisible( int col ), now you can scroll
- perfectly to make items completely visible.
- Moreover, in resizeEvent() the number of columns was not calculated
- correctly in a special case.
- And the currently selected item is rehighlighted correctly after
- resizing, now.
-
-1998-10-12 Jochen Küpper <jochen@uni-duesseldorf.de>
-
- * kfiledialog.cpp (okPressed): Changed okPressed to store the correct
- filename before leaving the dialog.
-
-1998-06-07 Stephan Kulow <coolo@kde.org>
-
- * kfilesimpleview.cpp: added some checks to prevent division with
- zero using the latest qt snapshots
-
- * kfilesimpleview.cpp: added a repaint call after a resize
-
- * kfiledialog.cpp: new experimental button order
-
- * kfiledialog.cpp: added lastDirectory to remember the last visited
- directory for next open
-
-1998-05-24 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: use setSelection also for the initial filename
- given
-
- * kfiledialog.cpp: introduced KFileFilter to make an abstraction
- for the used filter widget. Currently only QComboBox is supported,
- but this may change in the future
-
-1998-05-20 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: changed the accelerator for completion
- to CTRL-T
-
- * kfiledialog.cpp: fixed the setSelection() feature
-
-1998-05-19 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.h: added setSelection
-
-1998-05-18 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: bugfixes
-
-1998-05-15 Stephan Kulow <coolo@kde.org>
-
- * kfileinfocontents.cpp: some more changes and speed ups
- (caching and some other little things)
-
-1998-05-14 Stephan Kulow <coolo@kde.org>
-
- * kfileinfocontents.cpp: added addItemList
-
- * kfileinfocontents.h: introduced KFileInfoContentsSignaler
-
- * kfileinfocontents.cpp: some more speed improvment
-
-1998-05-10 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: tried to speed up the refresh
-
-1998-04-17 Stephan Kulow <coolo@kde.org>
-
- * kfiledetaillist.cpp: implemented the date field
-
- * kfiledetaillist.cpp: made the columns wider
-
- * kfileinfocontents.cpp: use the new icons by Mark
-
-Thu Apr 16 10:51:24 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- * kfiledialog.*: some small fixes concerning preview
-
- * kfileinfocontents.cpp: fixed sorting bug in preview
-
- * kfilepreview.*: small bug fixes
-
- * kpreview.*: small bug fixes
-
- * added some documentation
-
-1998-04-15 Stephan Kulow <coolo@kde.org>
-
- * kfilepreview.cpp: use a list box instead of simple view
-
- * kfiledialog.cpp: fixed an ugly bug
-
-1998-04-14 Stephan Kulow <coolo@kde.org>
-
- * kfiledialogconf.cpp: removed the width/height sliders
-
- * kfiledialog.cpp: save the width and height on exit
-
- * kfiledialogconf.cpp: added more guys to the about box
-
- * kfiledialog.h: removed init*Children. They were useless
-
- * kfiledialog.cpp: set the default size to a useful value
-
-Mon Apr 6 17:30:18 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- * kfilepreview.*: restructured previewing, one can now easily
- use custom previewers, dynamically
-
- * kpreview.*: changes for allowing custom previewers, two previewers
- are hardcoded so far
-
- * kfiledialog.*: changes changes for allowing custom previewers
-
- * kfstest.cpp: changes to preview mode
-
- * xview.*: QimageIO module allowing the visual-schnauzer generated
- images to be loaded
-
-1998-04-06 Stephan Kulow <coolo@kde.org>
-
- * debug.h: added debugC. An empty macro to hide debug output
-
-Thu Apr 2 19:39:37 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- * kpreview.*: widget which for now shows some info about a
- file/folder along with the first 20-30 lines of it
-
- * kfilepreview.*: added a new view which has a preview of any text
- file in the right part
-
- * kfstest.cpp: added the new mode "preview" which shows the above
- view
-
-1998-03-30 Stephan Kulow <coolo@kde.org>
-
- * kfilesimpleview.cpp: fixed highlightning
-
- * kfiledialog.cpp: some fixes for the dir selection
-
- * kfiledialog.h: Moved KFileDialog into KFileBaseDialog and made
- KFileDialog and KDirDialog a derived class of KFileBaseDialog to
- make this virtual functions work
-
-Mon Mar 30 17:53:20 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- * kcombiview.cpp: bug fixes for completion & corresponding
- highlighting
-
- * kfiledialog.cpp: small bug fix, too much copying into location
-
- * kfileinfocontents.cpp: completion slightly remodeled, should
- work in all views now
-
- * kfileinfocontents.h: changed nameList to case insensitive
- list
-
-1998-03-28 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: changed the filter separator to \n.
- This looks nicer in the source code of the call
-
-Sat Mar 28 14:49:00 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: changed the meaning of the dirName argument
-
- * kfiledialog.h: added getShowFilter
-
-Thu Mar 26 12:47:42 1998 Stephan Kulow <coolo@kde.org>
-
- * kfilesimpleview.cpp: improved scrolling in simple view
-
- * kfileinfocontents.cpp: add a / after a found dir
-
- * kfiledialog.cpp: fixed bug for !showFilter
-
-Wed Mar 25 18:39:09 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- * kfileinfocontents.cpp: completion now working
-
- * kcombiview.cpp: changed behavior for completion, it
- now highlights completed directory and file
-
-Tue Mar 24 16:08:46 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- * kfileinfocontents.cpp: sorting now fully working
-
- * kfiledialog.cpp: modifications for sorting in the on the
- fly reconfiguration
-
- * kfileinfocontents.*: modification to the constructor
- to pass along the sorting
-
- * kfiledetaillist.*: modification to the constructor
- to pass along the sorting
-
- * kcombiview.*: modification to the constructor
- to pass along the sorting
-
- * kfilesimpleview.*: modification to the constructor
- to pass along the sorting
-
-Tue Mar 24 10:45:15 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- * kfileinfocontents.cpp: sorting fixed, the feature of keeping
- directories grouped is still missing though
-
-Mon Mar 23 22:59:18 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledetaillist.h: added acceptsFiles() and acceptsDirs() to
- make dirs-only views useful
-
- * kfileinfocontents.cpp: OK, completion is back again, but
- currently not working, because the code is missing ;-)
-
-Mon Mar 23 00:08:02 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: moved all GM related things into initGUI() to
- make recreation possible
-
-Sun Mar 22 00:22:46 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: use KShellProcess now
-
- * kfiledialog.h: added virtual function initFileList to made
- KFileDialog customable
-
- * kfiledialog.cpp: show a combo box, in case more filters are given
-
- * kfiledialog.cpp: some bug fixes. I can't get the sorting to work
-
- * Makefile.am: install some toolbar pixmaps
-
- * kfiledetailview.cpp: added pixmaps to the detail view
-
- * Kfiledialog.cpp: made KComboView customable through virtual
- functions
-
- * kcombiview.cpp: took out the completion for now, added
- kcombiview and some little changes in setCurrentItem
-
- * kdirlistbox.cpp: fixed the use of single click
-
- * kdir.h: moved the header files a little bit to remove
- some dependencies
-
- * kdirlistbox.cpp: KDirListBox is now a KFileInfoContents too
-
- * kfiledialog.cpp: another change in the API. It uses now QSignal.
- I didn't liked the old way
-
-1998-03-21 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: implemented mixDirsAndFiles. Need some work and currently
- only supported by the simple view
-
-Sat Mar 21 01:00:48 1998 Stephan Kulow <coolo@kde.org>
-
- * kfilesimpleview.cpp: added pixmaps to indicate access on the file
-
- * kfilesimpleview.cpp: improved keyboard navigation
-
- * kfilesimpleview.cpp: first almost working simple view
-
- * kfilesimpleview.cpp: started implementing a simple view. Needs
- still some work
-
-
-Fri Mar 20 22:42:31 1998 Stephan Kulow <coolo@kde.org>
-
- * kfileinfocontents.h: bugfixes
-
- * kfileinfo.cpp: KFileInfo is no longer a derived class of
- QFileInfo. This should reduce memory use too
-
- * kfileinfocontents.h: moved the actual sorting in
- KFileInfoContents. Derived classes are for viewing only
-
- * kfiledialog.h: fixed some header files locations
-
-1998-03-20 Stephan Kulow <coolo@kde.org>
-
- * kfileinfo.cpp: show lockedfolder.xpm for folders, that are not
- allowed to enter or read
-
- * kfiledialog.cpp: bug fixes
-
-Fri Mar 20 13:10:11 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- * kfilgdialog.*, remodeled the configuration dialog to reflect the
- current possible settings
- * kfiledetailList.cpp: added the PageUp PageDown navigation
-
-1998-03-19 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: fixed the forward/back back reported by
- Stefan Tafener
-
-1998-03-18 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: set the initial focus to the line edit
-
- * kfiledialog.cpp: use kapp->invokeHTMLHelp now
-
- * kfiledialog.h: removed treeList, since it's not implemented
-
-Wed Mar 18 02:56:32 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledetaillist.cpp: fixed sorting again
-
-1998-03-17 Stephan Kulow <coolo@kde.org>
-
- * added a virtual class KInfoListContent to make an abstraction
- for the file contents. Currently there is just one implementation
- KFileDetailList
-
-1998-03-16 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: don't accept the first entry of the combo
- box as a file name
-
- * kfiledialog.cpp: added an accelerator for completion, since
- KCombo no longer emits such a thing (currently CTRL-A)
-
- * kdir.cpp: disable parent button in /
-
- * kfiledialog.cpp: fixed layout of mkdir dialog
-
- * kdir.cpp: use currentDir instead of homeDir as default
-
- * kfiledialog.cpp: added member acceptOnlyExisting and set it
- for now to always false. I guess, we need an extra parameter for this
-
- * kfiledialog.cpp: changed dirList and fileList to fix the
- focus handling
-
- * kfileinfolistwidget.cpp: added focus handling
-
- * kfileinfolistwidget.cpp: added keyevent handling to handle
- cursor and enter
-
- * kfiledialog.cpp: changed the filter edit to a QLineEdit, since
- we don't need the completion, but the tabing for focus changes
-
-Mon Mar 16 11:36:07 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- * added create directory, pops up a modal dialog, should add
- a mkdir method to kdir in near future
-
-Mon Mar 16 20:04:00 1998 Martin Jones <mjones@kde.org>
- * Added booktoken.* to remove dependancy on tdehtmlw and jscript
-
-Thu Mar 12 09:32:06 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- * worked on the dir and file completion, should do both now,
- text in the location box will be added as much as possible
- (right now it's the lowest denominator of dir&file&location-text)
- * added sorting for the detailed list, so far only name and size
- sorting implemented
- * added single click selection for directories
- * added a status line, which shows the number of directories and
- files showed
-
-Thu Mar 12 00:36:05 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: made a library out of the file selector
- * kfiledialog.cpp: added an extra parameter acceptURLs to seperate
- between getOpenFileName and getOpenFileURL
-
-Sun Feb 15 23:13:47 1998 Richard Moore <rich@kde.org>
-
- * More work on the bookmarks - they should work properly now, you
- must create the directory ~/.kde/share/apps/tdeui to store the
- bookmarks in.
-
- * Regenerated docs
-
-Thu Feb 12 17:27:51 1998 Stephan Kulow <coolo@kde.org>
-
- * kfileinfo.cpp: added determination of group and other things to
- be display the correct values in the kfileinfolistwidget
-
-Thu Feb 12 16:01:44 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: removed the #ifdef code. Now the combo box for
- the path is the only option
-
-Tue Feb 10 01:09:16 1998 Richard Moore <rich@kde.org>
-
- * Added details widget - this is currently selected by a config
- file entry, but it there should be a toolbar button. Many changes
- to kfiledialog to allow the switch (need an abstract fileview class).
-
-Fri Feb 6 18:08:14 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: replaced the location lineedit with an combo
- box. Currently configurable with a compiler define.
-
-Fri Feb 6 17:07:26 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: fixed the en- and decoding of URLs. Now it's
- possible to move into directories called "sdasd#sdsd" for example
-
-Sat Jan 24 17:18:10 1998 Mario Weilguni <mweilguni@sime.com>
-
- * fixed a bug in kdir.cpp/parsePermissions()
-
- * implemented error handling for KFM URL errors
-
-Tue Jan 20 00:51:55 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: some fixes to make kfm support more robust
-
-Mon Jan 19 01:10:11 1998 Stephan Kulow <coolo@kde.org>
-
- * kdir.cpp: re-added ftp support
-
- * kfiledialog.cpp: take care of the case, when the user enters a
- complete filename
-
- * kdir.cpp: added isReadable() to indicate, that the dir is not
- correct
-
- * kfiledialog.cpp: played a little bit with the geometry management
-
-
-Sun Jan 18 15:00:06 1998 Stephan Kulow <coolo@kde.org>
-
- * kfiledialog.cpp: - back/forward work now as expected
- - show the correct filter
- - the combo box works now as expected
-
- * kdir.cpp: check if the directory is correct (for local
- files). If not, go back to the old value
-
- * kfiledialog.cpp: - disable parent button, when in root
- - treat the case, that the URL ends with "/"
- - strip white spaces out of the location text
-
- * kfileinfo.cpp: don't insert broken links
-
- * kfiledialog.cpp: just set the dir, if it's different
- from the already set one
-
-Sun Jan 18 11:53:32 1998 Mario Weilguni <mweilguni@sime.com>
-
- * symbolic links to subdirectories are now correctly reported as
- directories
-
- * symbolic links are show as italic text
-
- * The toolbar button "Home" works now as expected
diff --git a/kio/kfile/Makefile.am b/kio/kfile/Makefile.am
deleted file mode 100644
index 1951f30c0..000000000
--- a/kio/kfile/Makefile.am
+++ /dev/null
@@ -1,78 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 1997 Stephan Kulow (coolo@kde.org)
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this library; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-
-INCLUDES= -I$(srcdir)/../libltdl/ -I$(top_srcdir) -I$(top_srcdir)/tdefx \
- -I$(top_builddir)/kio/kio -I$(top_srcdir)/kio/bookmarks $(all_includes) $(LIBART_CFLAGS)
-
-noinst_LTLIBRARIES = libkfile.la
-
-METASOURCES = AUTO
-
-#SUBDIRS = . acl_prop_page
-
-include_HEADERS = kfiledialog.h kencodingfiledialog.h\
- kdiroperator.h kfileview.h kfilefiltercombo.h \
- kfiledetailview.h kcombiview.h kdiskfreesp.h \
- kfileiconview.h krecentdocument.h \
- kurlrequester.h kfilepreview.h kfile.h \
- kurlcombobox.h kurlrequesterdlg.h kopenwith.h kpropsdlg.h \
- kicondialog.h kdirsize.h kpreviewwidgetbase.h kimagefilepreview.h kfilesharedlg.h \
- kfiletreeview.h kfiletreeviewitem.h kfiletreebranch.h \
- kdirselectdialog.h kurlbar.h kpropertiesdialog.h knotifydialog.h \
- kcustommenueditor.h knotifywidgetbase.h
-
-noinst_HEADERS = config-kfile.h krecentdirs.h kmetaprops.h \
- kfilebookmarkhandler.h kfilemetainfowidget.h kopenwith_p.h \
- kfilespeedbar.h kpreviewprops.h kacleditwidget.h kacleditwidget_p.h images.h
-
-libkfile_la_SOURCES = \
- kfilefiltercombo.cpp \
- kfileview.cpp kfileiconview.cpp \
- krecentdocument.cpp kfiledialog.cpp kdiroperator.cpp \
- kfiledetailview.cpp kcombiview.cpp kurlrequester.cpp \
- kfilepreview.cpp kurlcombobox.cpp kurlrequesterdlg.cpp \
- kopenwith.cpp kpropertiesdialog.cpp kicondialog.cpp kdirsize.cpp \
- krecentdirs.cpp kdiskfreesp.cpp kimagefilepreview.cpp kfilesharedlg.cpp \
- kurlbar.cpp kmetaprops.cpp kpreviewprops.cpp \
- kfiletreeview.cpp kfiletreeviewitem.cpp kfiletreebranch.cpp \
- kdirselectdialog.cpp kfilebookmarkhandler.cpp \
- kfilemetainfowidget.cpp kcustommenueditor.cpp knotifywidgetbase.ui \
- knotifydialog.cpp kfilespeedbar.cpp kpreviewwidgetbase.cpp \
- kfilemetapreview.cpp kpropertiesdesktopbase.ui \
- kpropertiesdesktopadvbase.ui kpropertiesmimetypebase.ui \
- kencodingfiledialog.cpp kacleditwidget.cpp
-
-libkfile_la_COMPILE_FIRST = $(srcdir)/../kio/kdirnotify_stub.h
-
-EXTRA_DIST = NOTES
-
-# convenience lib - no _LDFLAGS or _LIBADD !
-
-servicetype_DATA = kpropsdlgplugin.desktop
-servicetypedir = $(kde_servicetypesdir)
-
-
-#Can't be a module, we need to link to it for readConfig
-#kde_module_LTLIBRARIES = libkfileshare.la
-#libkfileshare_la_SOURCES = kfileshare.cpp
-#libkfileshare_la_LIBADD = libkfile.la
-#libkfileshare_la_LDFLAGS = -module $(KDE_PLUGIN)
-#kde_services_DATA = kfilesharepropsplugin.desktop
-
-include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kio/kfile/NOTES b/kio/kfile/NOTES
deleted file mode 100644
index c3fb6fbcb..000000000
--- a/kio/kfile/NOTES
+++ /dev/null
@@ -1,100 +0,0 @@
-Rewrite
-=======
-
-Here is the result of a long discussion between the kfile developers
-(Carsten) and the konqueror developers (Simon and David), about the plans
-for more integration between kfile and konqueror. 16/08/2000.
-
-
-
- KDirLister -----(1)---------------------> KFileView (3)
- <----(2)------ [Signaller] --- | |
- | |
- | |
- | |
- | |
- KFileIconView KFileListView
- (4) (5)
-
-
-(1) Gives items found when listing, and the key for each item
- (KDirLister has all the sorting code)
-(2) KFileView inherited classes emit requests for listing a new
- directory (with a bool for treeviews), and emit requests for
- the mimetype of a given item. If all KFileView inherited classes
- are QScrollViews, then it could even implement the "ask for mimetype
- of the visible icons first" algorithm, currently in KonqIconView.
-(3) KFileView, the base class for any view, knows about KFileItem, has
- signals for dropped(), popupMenu(list of actions provided by the view),
- has a QWidget * canvas() method, xOffset() and yOffset()
-(4) KFileIconView holds a QPtrDict to look up a QIconViewItem quickly from a
- given KFileItem. This will help for e.g. deleteItems and refreshItems.
-(5) KFileListView holds a QPtrDict to find the QListViewItem for a
- KFileItem. It implements different modes if we want the tree view in
- kfile ?
-
-
- KFileChooserWidget
-
-This (base) class is the container widget that can contain any kfileview and
-switch between them. It is embeddable into an application that wants a widget
-for choosing a file or directory. Features listing, selecting, popupmenu for
-switching modes, and a virtual createView( viewmode ) method, which
-only knows about the builtin views, in this class.
-It knows the current URL, has setURL(), and triggers the listing, connecting
-KFileView's requests to KDirLister's methods.
-
- KFileManagerWidget
-
-This class inherits from KFileChooserWidget and adds the file management
-operations. It uses a KFileOperations class (taken from the current
-KonqOperations) for all KIO operations, and it uses KFileUndo, taken from
-the KonqUndo stuff. The popupMenu method is reimplemented to add those
-operations to it.
-
- KFileWidget
-
-This class is the full widget that can be seen in the dialog. It has the
-toolbar buttons, the combo, etc. It embeds a KFileChooserWidget or a
-KFileManagerWidget, the latter being a specialisation of the former.
-
-The Konqueror side of things
-============================
-
- KonqFileIconView
-
-Inherits KFileIconView and adds image preview - unless we want it in
-KFileIconView, and the line-up-icons algorithm, etc.
-
- KonqFileListView
-
-Inherits KFileListView to add more stuff if needed. The mc-like text view
-could be implemented here as well, unless we want it in kfile. Same for the
-tree view.
-
- KonqFileManagerWidget
-
-This class inherits KFileManagerWidget and adds the konqueror stuff, like
-the enableAction signal. It also reimplements createView to create the
-konqueror versions of the views.
-
- KonqDirPart
-
-This class inherits KParts::ReadOnlyPart, and provides a BrowserExtension.
-It integrates KonqFileManagerWidget as its KParts widget, and provides
-KActions for it.
-
-Important :
-
-Make sure to take kfind into account. It would be nice if it could use the
-same views as konqueror, to have access to all the view modes, as well as
-image preview, etc.
-
-Unrelated:
-To Add
-======
-
-Mime Mappings?
-
-Filter= ( Mime Type | shell glob list )
-Mime Type -> shell glob list
diff --git a/kio/kfile/config-kfile.h b/kio/kfile/config-kfile.h
deleted file mode 100644
index 8715ed273..000000000
--- a/kio/kfile/config-kfile.h
+++ /dev/null
@@ -1,32 +0,0 @@
-#ifndef CONFIG_KFILE_H
-#define CONFIG_KFILE_H
-
-const int kfile_area = 250;
-
-#define DefaultViewStyle TQString::fromLatin1("SimpleView")
-#define DefaultPannerPosition 40
-#define DefaultMixDirsAndFiles false
-#define DefaultShowStatusLine false
-#define DefaultShowHidden false
-#define DefaultCaseInsensitive true
-#define DefaultDirsFirst true
-#define DefaultSortReversed false
-#define DefaultRecentURLsNumber 15
-#define DefaultDirectoryFollowing true
-#define DefaultAutoSelectExtChecked true
-#define ConfigGroup TQString::fromLatin1("KFileDialog Settings")
-#define RecentURLs TQString::fromLatin1("Recent URLs")
-#define RecentFiles TQString::fromLatin1("Recent Files")
-#define RecentURLsNumber TQString::fromLatin1("Maximum of recent URLs")
-#define RecentFilesNumber TQString::fromLatin1("Maximum of recent files")
-#define DialogWidth TQString::fromLatin1("Width (%1)")
-#define DialogHeight TQString::fromLatin1("Height (%1)")
-#define ConfigShowStatusLine TQString::fromLatin1("ShowStatusLine")
-#define AutoDirectoryFollowing TQString::fromLatin1("Automatic directory following")
-#define PathComboCompletionMode TQString::fromLatin1("PathCombo Completionmode")
-#define LocationComboCompletionMode TQString::fromLatin1("LocationCombo Completionmode")
-#define ShowSpeedbar TQString::fromLatin1("Show Speedbar")
-#define ShowBookmarks TQString::fromLatin1("Show Bookmarks")
-#define AutoSelectExtChecked TQString::fromLatin1("Automatically select filename extension")
-
-#endif
diff --git a/kio/kfile/kacleditwidget.cpp b/kio/kfile/kacleditwidget.cpp
deleted file mode 100644
index 7f253f8c5..000000000
--- a/kio/kfile/kacleditwidget.cpp
+++ /dev/null
@@ -1,1054 +0,0 @@
-/***************************************************************************
- * Copyright (C) 2005 by Sean Harmer <sh@rama.homelinux.org> *
- * Till Adam <adam@kde.org> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU Library 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., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-
-
-#include "kacleditwidget.h"
-#include "kacleditwidget_p.h"
-
-#ifdef USE_POSIX_ACL
-
-#include <tqpainter.h>
-#include <tqptrlist.h>
-#include <tqvbox.h>
-#include <tqhbox.h>
-#include <tqpushbutton.h>
-#include <tqvbuttongroup.h>
-#include <tqradiobutton.h>
-#include <tqcombobox.h>
-#include <tqlabel.h>
-#include <tqcheckbox.h>
-#include <tqlayout.h>
-#include <tqwidgetstack.h>
-#include <tqheader.h>
-
-#include <klocale.h>
-#include <kfileitem.h>
-#include <kdebug.h>
-#include <kdialog.h>
-#include <kdialogbase.h>
-
-#ifdef HAVE_ACL_LIBACL_H
-# include <acl/libacl.h>
-#endif
-extern "C" {
-#include <pwd.h>
-#include <grp.h>
-}
-#include <assert.h>
-
-#include "images.h"
-
-static struct {
- const char* label;
- const char* pixmapName;
- TQPixmap* pixmap;
-} s_itemAttributes[] = {
- { I18N_NOOP( "Owner" ), "user-grey", 0 },
- { I18N_NOOP( "Owning Group" ), "group-grey", 0 },
- { I18N_NOOP( "Others" ), "others-grey", 0 },
- { I18N_NOOP( "Mask" ), "mask", 0 },
- { I18N_NOOP( "Named User" ), "user", 0 },
- { I18N_NOOP( "Named Group" ), "group", 0 },
-};
-
-KACLEditWidget::KACLEditWidget( TQWidget *parent, const char *name )
- :TQWidget( parent, name )
-{
- TQHBox *hbox = new TQHBox( parent );
- hbox->setSpacing( KDialog::spacingHint() );
- m_listView = new KACLListView( hbox, "acl_listview" );
- connect( m_listView, TQT_SIGNAL( selectionChanged() ),
- this, TQT_SLOT( slotUpdateButtons() ) );
- TQVBox *vbox = new TQVBox( hbox );
- vbox->setSpacing( KDialog::spacingHint() );
- m_AddBtn = new TQPushButton( i18n( "Add Entry..." ), vbox, "add_entry_button" );
- connect( m_AddBtn, TQT_SIGNAL( clicked() ), m_listView, TQT_SLOT( slotAddEntry() ) );
- m_EditBtn = new TQPushButton( i18n( "Edit Entry..." ), vbox, "edit_entry_button" );
- connect( m_EditBtn, TQT_SIGNAL( clicked() ), m_listView, TQT_SLOT( slotEditEntry() ) );
- m_DelBtn = new TQPushButton( i18n( "Delete Entry" ), vbox, "delete_entry_button" );
- connect( m_DelBtn, TQT_SIGNAL( clicked() ), m_listView, TQT_SLOT( slotRemoveEntry() ) );
- TQWidget *spacer = new TQWidget( vbox );
- spacer->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::Expanding );
- slotUpdateButtons();
-}
-
-void KACLEditWidget::slotUpdateButtons()
-{
- bool atLeastOneIsNotDeletable = false;
- bool atLeastOneIsNotAllowedToChangeType = false;
- int selectedCount = 0;
- TQListViewItemIterator it( m_listView, TQListViewItemIterator::Selected );
- while ( KACLListViewItem *item = dynamic_cast<KACLListViewItem*>( it.current() ) ) {
- ++it; ++selectedCount;
- if ( !item->isDeletable() )
- atLeastOneIsNotDeletable = true;
- if ( !item->isAllowedToChangeType() )
- atLeastOneIsNotAllowedToChangeType = true;
- }
- m_EditBtn->setEnabled( selectedCount && !atLeastOneIsNotAllowedToChangeType );
- m_DelBtn->setEnabled( selectedCount && !atLeastOneIsNotDeletable );
-}
-
-KACL KACLEditWidget::getACL() const
-{
- return m_listView->getACL();
-}
-
-KACL KACLEditWidget::getDefaultACL() const
-{
- return m_listView->getDefaultACL();
-}
-
-void KACLEditWidget::setACL( const KACL &acl )
-{
- return m_listView->setACL( acl );
-}
-
-void KACLEditWidget::setDefaultACL( const KACL &acl )
-{
- return m_listView->setDefaultACL( acl );
-}
-
-void KACLEditWidget::setAllowDefaults( bool value )
-{
- m_listView->setAllowDefaults( value );
-}
-
-void KACLEditWidget::setReadOnly( bool on )
-{
- m_listView->setEnabled( !on );
- m_AddBtn->setEnabled( !on );
- if ( !on )
- slotUpdateButtons();
-}
-
-KACLListViewItem::KACLListViewItem( TQListView* parent,
- KACLListView::EntryType _type,
- unsigned short _value, bool defaults,
- const TQString& _qualifier )
- : KListViewItem( parent, parent->lastItem() ), // we want to append
- type( _type ), value( _value ), isDefault( defaults ),
- qualifier( _qualifier ), isPartial( false )
-{
- m_pACLListView = dynamic_cast<KACLListView*>( parent );
- repaint();
-}
-
-
-KACLListViewItem::~ KACLListViewItem()
-{
-
-}
-
-TQString KACLListViewItem::key( int, bool ) const
-{
- TQString key;
- if ( !isDefault )
- key = "A";
- else
- key = "B";
- switch ( type )
- {
- case KACLListView::User:
- key += "A";
- break;
- case KACLListView::Group:
- key += "B";
- break;
- case KACLListView::Others:
- key += "C";
- break;
- case KACLListView::Mask:
- key += "D";
- break;
- case KACLListView::NamedUser:
- key += "E" + text( 1 );
- break;
- case KACLListView::NamedGroup:
- key += "F" + text( 1 );
- break;
- default:
- key += text( 0 );
- break;
- }
- return key;
-}
-
-void KACLListViewItem::paintCell( TQPainter* p, const TQColorGroup &cg,
- int column, int width, int alignment )
-{
- TQColorGroup mycg = cg;
- if ( isDefault ) {
- mycg.setColor( TQColorGroup::Text, TQColor( 0, 0, 255 ) );
- }
- if ( isPartial ) {
- TQFont font = p->font();
- font.setItalic( true );
- mycg.setColor( TQColorGroup::Text, TQColor( 100, 100, 100 ) );
- p->setFont( font );
- }
- KListViewItem::paintCell( p, mycg, column, width, alignment );
-
- KACLListViewItem *below =0;
- if ( itemBelow() )
- below = static_cast<KACLListViewItem*>( itemBelow() );
- const bool lastUser = type == KACLListView::NamedUser && below && below->type == KACLListView::NamedGroup;
- const bool lastNonDefault = !isDefault && below && below->isDefault;
- if ( type == KACLListView::Mask || lastUser || lastNonDefault )
- {
- p->setPen( TQPen( Qt::gray, 0, TQPen::DotLine ) );
- if ( type == KACLListView::Mask )
- p->drawLine( 0, 0, width - 1, 0 );
- p->drawLine( 0, height() - 1, width - 1, height() - 1 );
- }
-}
-
-
-void KACLListViewItem::updatePermPixmaps()
-{
- unsigned int partialPerms = value;
-
- if ( value & ACL_READ )
- setPixmap( 2, m_pACLListView->getYesPixmap() );
- else if ( partialPerms & ACL_READ )
- setPixmap( 2, m_pACLListView->getYesPartialPixmap() );
- else
- setPixmap( 2, TQPixmap() );
-
- if ( value & ACL_WRITE )
- setPixmap( 3, m_pACLListView->getYesPixmap() );
- else if ( partialPerms & ACL_WRITE )
- setPixmap( 3, m_pACLListView->getYesPartialPixmap() );
- else
- setPixmap( 3, TQPixmap() );
-
- if ( value & ACL_EXECUTE )
- setPixmap( 4, m_pACLListView->getYesPixmap() );
- else if ( partialPerms & ACL_EXECUTE )
- setPixmap( 4, m_pACLListView->getYesPartialPixmap() );
- else
- setPixmap( 4, TQPixmap() );
-}
-
-void KACLListViewItem::repaint()
-{
- int idx = 0;
- switch ( type )
- {
- case KACLListView::User:
- idx = KACLListView::OWNER_IDX;
- break;
- case KACLListView::Group:
- idx = KACLListView::GROUP_IDX;
- break;
- case KACLListView::Others:
- idx = KACLListView::OTHERS_IDX;
- break;
- case KACLListView::Mask:
- idx = KACLListView::MASK_IDX;
- break;
- case KACLListView::NamedUser:
- idx = KACLListView::NAMED_USER_IDX;
- break;
- case KACLListView::NamedGroup:
- idx = KACLListView::NAMED_GROUP_IDX;
- break;
- default:
- idx = KACLListView::OWNER_IDX;
- break;
- }
- setText( 0, i18n(s_itemAttributes[idx].label) );
- setPixmap( 0, *s_itemAttributes[idx].pixmap );
- if ( isDefault )
- setText( 0, text( 0 ) + i18n( " (Default)" ) );
- setText( 1, qualifier );
- // Set the pixmaps for which of the perms are set
- updatePermPixmaps();
-}
-
-void KACLListViewItem::calcEffectiveRights()
-{
- TQString strEffective = TQString( "---" );
-
- // Do we need to worry about the mask entry? It applies to named users,
- // owning group, and named groups
- if ( m_pACLListView->hasMaskEntry()
- && ( type == KACLListView::NamedUser
- || type == KACLListView::Group
- || type == KACLListView::NamedGroup )
- && !isDefault )
- {
-
- strEffective[0] = ( m_pACLListView->maskPermissions() & value & ACL_READ ) ? 'r' : '-';
- strEffective[1] = ( m_pACLListView->maskPermissions() & value & ACL_WRITE ) ? 'w' : '-';
- strEffective[2] = ( m_pACLListView->maskPermissions() & value & ACL_EXECUTE ) ? 'x' : '-';
-/*
- // What about any partial perms?
- if ( maskPerms & partialPerms & ACL_READ || // Partial perms on entry
- maskPartialPerms & perms & ACL_READ || // Partial perms on mask
- maskPartialPerms & partialPerms & ACL_READ ) // Partial perms on mask and entry
- strEffective[0] = 'R';
- if ( maskPerms & partialPerms & ACL_WRITE || // Partial perms on entry
- maskPartialPerms & perms & ACL_WRITE || // Partial perms on mask
- maskPartialPerms & partialPerms & ACL_WRITE ) // Partial perms on mask and entry
- strEffective[1] = 'W';
- if ( maskPerms & partialPerms & ACL_EXECUTE || // Partial perms on entry
- maskPartialPerms & perms & ACL_EXECUTE || // Partial perms on mask
- maskPartialPerms & partialPerms & ACL_EXECUTE ) // Partial perms on mask and entry
- strEffective[2] = 'X';
-*/
- }
- else
- {
- // No, the effective value are just the value in this entry
- strEffective[0] = ( value & ACL_READ ) ? 'r' : '-';
- strEffective[1] = ( value & ACL_WRITE ) ? 'w' : '-';
- strEffective[2] = ( value & ACL_EXECUTE ) ? 'x' : '-';
-
- /*
- // What about any partial perms?
- if ( partialPerms & ACL_READ )
- strEffective[0] = 'R';
- if ( partialPerms & ACL_WRITE )
- strEffective[1] = 'W';
- if ( partialPerms & ACL_EXECUTE )
- strEffective[2] = 'X';
- */
- }
- setText( 5, strEffective );
-}
-
-bool KACLListViewItem::isDeletable() const
-{
- bool isMaskAndDeletable = false;
- if (type == KACLListView::Mask ) {
- if ( !isDefault && m_pACLListView->maskCanBeDeleted() )
- isMaskAndDeletable = true;
- else if ( isDefault && m_pACLListView->defaultMaskCanBeDeleted() )
- isMaskAndDeletable = true;
- }
- return type != KACLListView::User &&
- type != KACLListView::Group &&
- type != KACLListView::Others &&
- ( type != KACLListView::Mask || isMaskAndDeletable );
-}
-
-bool KACLListViewItem::isAllowedToChangeType() const
-{
- return type != KACLListView::User &&
- type != KACLListView::Group &&
- type != KACLListView::Others &&
- type != KACLListView::Mask;
-}
-
-void KACLListViewItem::togglePerm( acl_perm_t perm )
-{
- value ^= perm; // Toggle the perm
- if ( type == KACLListView::Mask && !isDefault ) {
- m_pACLListView->setMaskPermissions( value );
- }
- calcEffectiveRights();
- updatePermPixmaps();
-/*
- // If the perm is in the partial perms then remove it. i.e. Once
- // a user changes a partial perm it then applies to all selected files.
- if ( m_pEntry->m_partialPerms & perm )
- m_pEntry->m_partialPerms ^= perm;
-
- m_pEntry->setPartialEntry( false );
- // Make sure that all entries have their effective rights calculated if
- // we are changing the ACL_MASK entry.
- if ( type == Mask )
- {
- m_pACLListView->setMaskPartialPermissions( m_pEntry->m_partialPerms );
- m_pACLListView->setMaskPermissions( value );
- m_pACLListView->calculateEffectiveRights();
- }
-*/
-}
-
-
-
-EditACLEntryDialog::EditACLEntryDialog( KACLListView *listView, KACLListViewItem *item,
- const TQStringList &users,
- const TQStringList &groups,
- const TQStringList &defaultUsers,
- const TQStringList &defaultGroups,
- int allowedTypes, int allowedDefaultTypes,
- bool allowDefaults )
- : KDialogBase( listView, "edit_entry_dialog", true,
- i18n( "Edit ACL Entry" ), KDialogBase::Ok|KDialogBase::Cancel,
- KDialogBase::Ok, false ),
- m_listView( listView ), m_item( item ), m_users( users ), m_groups( groups ),
- m_defaultUsers( defaultUsers ), m_defaultGroups( defaultGroups ),
- m_allowedTypes( allowedTypes ), m_allowedDefaultTypes( allowedDefaultTypes ),
- m_defaultCB( 0 )
-{
- TQWidget *page = new TQWidget( this );
- setMainWidget( page );
- TQVBoxLayout *mainLayout = new TQVBoxLayout( page, 0, spacingHint(), "mainLayout" );
- m_buttonGroup = new TQVButtonGroup( i18n("Entry Type"), page, "bg" );
-
- if ( allowDefaults ) {
- m_defaultCB = new TQCheckBox( i18n("Default for new files in this folder"), page, "defaultCB" );
- mainLayout->addWidget( m_defaultCB );
- connect( m_defaultCB, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SLOT( slotUpdateAllowedUsersAndGroups() ) );
- connect( m_defaultCB, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SLOT( slotUpdateAllowedTypes() ) );
-
- }
-
- mainLayout->addWidget( m_buttonGroup );
-
- TQRadioButton *ownerType = new TQRadioButton( i18n("Owner"), m_buttonGroup, "ownerType" );
- m_buttonGroup->insert( ownerType, KACLListView::User );
- TQRadioButton *owningGroupType = new TQRadioButton( i18n("Owning Group"), m_buttonGroup, "owningGroupType" );
- m_buttonGroup->insert( owningGroupType, KACLListView::Group );
- TQRadioButton *othersType = new TQRadioButton( i18n("Others"), m_buttonGroup, "othersType" );
- m_buttonGroup->insert( othersType, KACLListView::Others );
- TQRadioButton *maskType = new TQRadioButton( i18n("Mask"), m_buttonGroup, "maskType" );
- m_buttonGroup->insert( maskType, KACLListView::Mask );
- TQRadioButton *namedUserType = new TQRadioButton( i18n("Named User"), m_buttonGroup, "namesUserType" );
- m_buttonGroup->insert( namedUserType, KACLListView::NamedUser );
- TQRadioButton *namedGroupType = new TQRadioButton( i18n("Named Group"), m_buttonGroup, "namedGroupType" );
- m_buttonGroup->insert( namedGroupType, KACLListView::NamedGroup );
-
- connect( m_buttonGroup, TQT_SIGNAL( clicked( int ) ),
- this, TQT_SLOT( slotSelectionChanged( int ) ) );
-
- m_widgetStack = new TQWidgetStack( page );
- mainLayout->addWidget( m_widgetStack );
-
- TQHBox *usersBox = new TQHBox( m_widgetStack );
- m_widgetStack->addWidget( usersBox, KACLListView::NamedUser );
-
- TQHBox *groupsBox = new TQHBox( m_widgetStack );
- m_widgetStack->addWidget( groupsBox, KACLListView::NamedGroup );
-
- TQLabel *usersLabel = new TQLabel( i18n( "User: " ), usersBox );
- m_usersCombo = new TQComboBox( false, usersBox, "users" );
- usersLabel->setBuddy( m_usersCombo );
-
- TQLabel *groupsLabel = new TQLabel( i18n( "Group: " ), groupsBox );
- m_groupsCombo = new TQComboBox( false, groupsBox, "groups" );
- groupsLabel->setBuddy( m_groupsCombo );
-
- if ( m_item ) {
- m_buttonGroup->setButton( m_item->type );
- if ( m_defaultCB )
- m_defaultCB->setChecked( m_item->isDefault );
- slotUpdateAllowedTypes();
- slotSelectionChanged( m_item->type );
- slotUpdateAllowedUsersAndGroups();
- if ( m_item->type == KACLListView::NamedUser ) {
- m_usersCombo->setCurrentText( m_item->qualifier );
- } else if ( m_item->type == KACLListView::NamedGroup ) {
- m_groupsCombo->setCurrentText( m_item->qualifier );
- }
- } else {
- // new entry, preselect "named user", arguably the most common one
- m_buttonGroup->setButton( KACLListView::NamedUser );
- slotUpdateAllowedTypes();
- slotSelectionChanged( KACLListView::NamedUser );
- slotUpdateAllowedUsersAndGroups();
- }
- incInitialSize( TQSize( 100, 0 ) );
-}
-
-void EditACLEntryDialog::slotUpdateAllowedTypes()
-{
- int allowedTypes = m_allowedTypes;
- if ( m_defaultCB && m_defaultCB->isChecked() ) {
- allowedTypes = m_allowedDefaultTypes;
- }
- for ( int i=1; i < KACLListView::AllTypes; i=i*2 ) {
- if ( allowedTypes & i )
- m_buttonGroup->find( i )->show();
- else
- m_buttonGroup->find( i )->hide();
- }
-}
-
-void EditACLEntryDialog::slotUpdateAllowedUsersAndGroups()
-{
- const TQString oldUser = m_usersCombo->currentText();
- const TQString oldGroup = m_groupsCombo->currentText();
- m_usersCombo->clear();
- m_groupsCombo->clear();
- if ( m_defaultCB && m_defaultCB->isChecked() ) {
- m_usersCombo->insertStringList( m_defaultUsers );
- if ( m_defaultUsers.find( oldUser ) != m_defaultUsers.end() )
- m_usersCombo->setCurrentText( oldUser );
- m_groupsCombo->insertStringList( m_defaultGroups );
- if ( m_defaultGroups.find( oldGroup ) != m_defaultGroups.end() )
- m_groupsCombo->setCurrentText( oldGroup );
- } else {
- m_usersCombo->insertStringList( m_users );
- if ( m_users.find( oldUser ) != m_users.end() )
- m_usersCombo->setCurrentText( oldUser );
- m_groupsCombo->insertStringList( m_groups );
- if ( m_groups.find( oldGroup ) != m_groups.end() )
- m_groupsCombo->setCurrentText( oldGroup );
- }
-}
-void EditACLEntryDialog::slotOk()
-{
- KACLListView::EntryType type = static_cast<KACLListView::EntryType>( m_buttonGroup->selectedId() );
-
- TQString qualifier;
- if ( type == KACLListView::NamedUser )
- qualifier = m_usersCombo->currentText();
- if ( type == KACLListView::NamedGroup )
- qualifier = m_groupsCombo->currentText();
-
- if ( !m_item ) {
- m_item = new KACLListViewItem( m_listView, type, ACL_READ | ACL_WRITE | ACL_EXECUTE, false, qualifier );
- } else {
- m_item->type = type;
- m_item->qualifier = qualifier;
- }
- if ( m_defaultCB )
- m_item->isDefault = m_defaultCB->isChecked();
- m_item->repaint();
-
- KDialogBase::slotOk();
-}
-
-void EditACLEntryDialog::slotSelectionChanged( int id )
-{
- switch ( id ) {
- case KACLListView::User:
- case KACLListView::Group:
- case KACLListView::Others:
- case KACLListView::Mask:
- m_widgetStack->setEnabled( false );
- break;
- case KACLListView::NamedUser:
- m_widgetStack->setEnabled( true );
- m_widgetStack->raiseWidget( KACLListView::NamedUser );
- break;
- case KACLListView::NamedGroup:
- m_widgetStack->setEnabled( true );
- m_widgetStack->raiseWidget( KACLListView::NamedGroup );
- break;
- default:
- break;
- }
-}
-
-
-KACLListView::KACLListView( TQWidget* parent, const char* name )
- : KListView( parent, name ),
- m_hasMask( false ), m_allowDefaults( false )
-{
- // Add the columns
- addColumn( i18n( "Type" ) );
- addColumn( i18n( "Name" ) );
- addColumn( i18n( "read permission", "r" ) );
- addColumn( i18n( "write permission", "w" ) );
- addColumn( i18n( "execute permission", "x" ) );
- addColumn( i18n( "Effective" ) );
-
- header()->setClickEnabled( false );
-
- // Load the avatars
- for ( int i=0; i < LAST_IDX; ++i ) {
- s_itemAttributes[i].pixmap = new TQPixmap( qembed_findImage( s_itemAttributes[i].pixmapName ) );
- }
- m_yesPixmap = new TQPixmap( qembed_findImage( "yes" ) );
- m_yesPartialPixmap = new TQPixmap( qembed_findImage( "yespartial" ) );
-
- setSelectionMode( TQListView::Extended );
-
- // fill the lists of all legal users and groups
- struct passwd *user = 0;
- setpwent();
- while ( ( user = getpwent() ) != 0 ) {
- m_allUsers << TQString::fromLatin1( user->pw_name );
- }
- endpwent();
-
- struct group *gr = 0;
- setgrent();
- while ( ( gr = getgrent() ) != 0 ) {
- m_allGroups << TQString::fromLatin1( gr->gr_name );
- }
- endgrent();
- m_allUsers.sort();
- m_allGroups.sort();
-}
-
-
-KACLListView::~KACLListView()
-{
- for ( int i=0; i < LAST_IDX; ++i ) {
- delete s_itemAttributes[i].pixmap;
- }
- delete m_yesPixmap;
- delete m_yesPartialPixmap;
-}
-
-TQStringList KACLListView::allowedUsers( bool defaults, KACLListViewItem *allowedItem )
-{
- TQStringList allowedUsers = m_allUsers;
- TQListViewItemIterator it( this );
- while ( it.current() ) {
- const KACLListViewItem *item = static_cast<const KACLListViewItem*>( *it );
- ++it;
- if ( !item->type == NamedUser || item->isDefault != defaults ) continue;
- if ( allowedItem && item == allowedItem && allowedItem->isDefault == defaults ) continue;
- allowedUsers.remove( item->qualifier );
- }
- return allowedUsers;
-}
-
-TQStringList KACLListView::allowedGroups( bool defaults, KACLListViewItem *allowedItem )
-{
- TQStringList allowedGroups = m_allGroups;
- TQListViewItemIterator it( this );
- while ( it.current() ) {
- const KACLListViewItem *item = static_cast<const KACLListViewItem*>( *it );
- ++it;
- if ( !item->type == NamedGroup || item->isDefault != defaults ) continue;
- if ( allowedItem && item == allowedItem && allowedItem->isDefault == defaults ) continue;
- allowedGroups.remove( item->qualifier );
- }
- return allowedGroups;
-}
-
-void KACLListView::fillItemsFromACL( const KACL &pACL, bool defaults )
-{
- // clear out old entries of that ilk
- TQListViewItemIterator it( this );
- while ( KACLListViewItem *item = static_cast<KACLListViewItem*>( it.current() ) ) {
- ++it;
- if ( item->isDefault == defaults )
- delete item;
- }
- KACLListViewItem *item =
- new KACLListViewItem( this, User, pACL.ownerPermissions(), defaults );
-
- item = new KACLListViewItem( this, Group, pACL.owningGroupPermissions(), defaults );
-
- item = new KACLListViewItem( this, Others, pACL.othersPermissions(), defaults );
-
- bool hasMask = false;
- unsigned short mask = pACL.maskPermissions( hasMask );
- if ( hasMask ) {
- item = new KACLListViewItem( this, Mask, mask, defaults );
- }
-
- // read all named user entries
- const ACLUserPermissionsList &userList = pACL.allUserPermissions();
- ACLUserPermissionsConstIterator itu = userList.begin();
- while ( itu != userList.end() ) {
- new KACLListViewItem( this, NamedUser, (*itu).second, defaults, (*itu).first );
- ++itu;
- }
-
- // and now all named groups
- const ACLUserPermissionsList &groupList = pACL.allGroupPermissions();
- ACLUserPermissionsConstIterator itg = groupList.begin();
- while ( itg != groupList.end() ) {
- new KACLListViewItem( this, NamedGroup, (*itg).second, defaults, (*itg).first );
- ++itg;
- }
-}
-
-void KACLListView::setACL( const KACL &acl )
-{
- if ( !acl.isValid() ) return;
- // Remove any entries left over from displaying a previous ACL
- m_ACL = acl;
- fillItemsFromACL( m_ACL );
-
- m_mask = acl.maskPermissions( m_hasMask );
- calculateEffectiveRights();
-}
-
-void KACLListView::setDefaultACL( const KACL &acl )
-{
- if ( !acl.isValid() ) return;
- m_defaultACL = acl;
- fillItemsFromACL( m_defaultACL, true );
- calculateEffectiveRights();
-}
-
-KACL KACLListView::itemsToACL( bool defaults ) const
-{
- KACL newACL( 0 );
- bool atLeastOneEntry = false;
- ACLUserPermissionsList users;
- ACLGroupPermissionsList groups;
- TQListViewItemIterator it( const_cast<KACLListView*>( this ) );
- while ( TQListViewItem* qlvi = it.current() ) {
- ++it;
- const KACLListViewItem* item = static_cast<KACLListViewItem*>( qlvi );
- if ( item->isDefault != defaults ) continue;
- atLeastOneEntry = true;
- switch ( item->type ) {
- case User:
- newACL.setOwnerPermissions( item->value );
- break;
- case Group:
- newACL.setOwningGroupPermissions( item->value );
- break;
- case Others:
- newACL.setOthersPermissions( item->value );
- break;
- case Mask:
- newACL.setMaskPermissions( item->value );
- break;
- case NamedUser:
- users.append( qMakePair( item->text( 1 ), item->value ) );
- break;
- case NamedGroup:
- groups.append( qMakePair( item->text( 1 ), item->value ) );
- break;
- default:
- break;
- }
- }
- if ( atLeastOneEntry ) {
- newACL.setAllUserPermissions( users );
- newACL.setAllGroupPermissions( groups );
- if ( newACL.isValid() )
- return newACL;
- }
- return KACL();
-}
-
-KACL KACLListView::getACL()
-{
- return itemsToACL( false );
-}
-
-
-KACL KACLListView::getDefaultACL()
-{
- return itemsToACL( true );
-}
-
-void KACLListView::contentsMousePressEvent( TQMouseEvent * e )
-{
- TQListViewItem *clickedItem = itemAt( contentsToViewport( e->pos() ) );
- if ( !clickedItem ) return;
- // if the click is on an as yet unselected item, select it first
- if ( !clickedItem->isSelected() )
- KListView::contentsMousePressEvent( e );
-
- if ( !currentItem() ) return;
- int column = header()->sectionAt( e->x() );
- acl_perm_t perm;
- switch ( column )
- {
- case 2:
- perm = ACL_READ;
- break;
- case 3:
- perm = ACL_WRITE;
- break;
- case 4:
- perm = ACL_EXECUTE;
- break;
- default:
- return KListView::contentsMousePressEvent( e );
- }
- KACLListViewItem* referenceItem = static_cast<KACLListViewItem*>( clickedItem );
- unsigned short referenceHadItSet = referenceItem->value & perm;
- TQListViewItemIterator it( this );
- while ( KACLListViewItem* item = static_cast<KACLListViewItem*>( it.current() ) ) {
- ++it;
- if ( !item->isSelected() ) continue;
- // toggle those with the same value as the clicked item, leave the others
- if ( referenceHadItSet == ( item->value & perm ) )
- item->togglePerm( perm );
- }
-}
-
-void KACLListView::entryClicked( TQListViewItem* pItem, const TQPoint& /*pt*/, int col )
-{
- if ( !pItem ) return;
-
- TQListViewItemIterator it( this );
- while ( KACLListViewItem* item = static_cast<KACLListViewItem*>( it.current() ) ) {
- ++it;
- if ( !item->isSelected() ) continue;
- switch ( col )
- {
- case 2:
- item->togglePerm( ACL_READ );
- break;
- case 3:
- item->togglePerm( ACL_WRITE );
- break;
- case 4:
- item->togglePerm( ACL_EXECUTE );
- break;
-
- default:
- ; // Do nothing
- }
- }
- /*
- // Has the user changed one of the required entries in a default ACL?
- if ( m_pACL->aclType() == ACL_TYPE_DEFAULT &&
- ( col == 2 || col == 3 || col == 4 ) &&
- ( pACLItem->entryType() == ACL_USER_OBJ ||
- pACLItem->entryType() == ACL_GROUP_OBJ ||
- pACLItem->entryType() == ACL_OTHER ) )
- {
- // Mark the required entries as no longer being partial entries.
- // That is, they will get applied to all selected directories.
- KACLListViewItem* pUserObj = findACLEntryByType( this, ACL_USER_OBJ );
- pUserObj->entry()->setPartialEntry( false );
-
- KACLListViewItem* pGroupObj = findACLEntryByType( this, ACL_GROUP_OBJ );
- pGroupObj->entry()->setPartialEntry( false );
-
- KACLListViewItem* pOther = findACLEntryByType( this, ACL_OTHER );
- pOther->entry()->setPartialEntry( false );
-
- update();
- }
- */
-}
-
-
-void KACLListView::calculateEffectiveRights()
-{
- TQListViewItemIterator it( this );
- KACLListViewItem* pItem;
- while ( ( pItem = dynamic_cast<KACLListViewItem*>( it.current() ) ) != 0 )
- {
- ++it;
- pItem->calcEffectiveRights();
- }
-}
-
-
-unsigned short KACLListView::maskPermissions() const
-{
- return m_mask;
-}
-
-
-void KACLListView::setMaskPermissions( unsigned short maskPerms )
-{
- m_mask = maskPerms;
- calculateEffectiveRights();
-}
-
-
-acl_perm_t KACLListView::maskPartialPermissions() const
-{
- // return m_pMaskEntry->m_partialPerms;
- return 0;
-}
-
-
-void KACLListView::setMaskPartialPermissions( acl_perm_t /*maskPartialPerms*/ )
-{
- //m_pMaskEntry->m_partialPerms = maskPartialPerms;
- calculateEffectiveRights();
-}
-
-bool KACLListView::hasDefaultEntries() const
-{
- TQListViewItemIterator it( const_cast<KACLListView*>( this ) );
- while ( it.current() ) {
- const KACLListViewItem *item = static_cast<const KACLListViewItem*>( it.current() );
- ++it;
- if ( item->isDefault ) return true;
- }
- return false;
-}
-
-const KACLListViewItem* KACLListView::findDefaultItemByType( EntryType type ) const
-{
- return findItemByType( type, true );
-}
-
-const KACLListViewItem* KACLListView::findItemByType( EntryType type, bool defaults ) const
-{
- TQListViewItemIterator it( const_cast<KACLListView*>( this ) );
- while ( it.current() ) {
- const KACLListViewItem *item = static_cast<const KACLListViewItem*>( it.current() );
- ++it;
- if ( item->isDefault == defaults && item->type == type ) {
- return item;
- }
- }
- return 0;
-}
-
-
-unsigned short KACLListView::calculateMaskValue( bool defaults ) const
-{
- // KACL auto-adds the relevant maks entries, so we can simply query
- bool dummy;
- return itemsToACL( defaults ).maskPermissions( dummy );
-}
-
-void KACLListView::slotAddEntry()
-{
- int allowedTypes = NamedUser | NamedGroup;
- if ( !m_hasMask )
- allowedTypes |= Mask;
- int allowedDefaultTypes = NamedUser | NamedGroup;
- if ( !findDefaultItemByType( Mask ) )
- allowedDefaultTypes |= Mask;
- if ( !hasDefaultEntries() )
- allowedDefaultTypes |= User | Group;
- EditACLEntryDialog dlg( this, 0,
- allowedUsers( false ), allowedGroups( false ),
- allowedUsers( true ), allowedGroups( true ),
- allowedTypes, allowedDefaultTypes, m_allowDefaults );
- dlg.exec();
- KACLListViewItem *item = dlg.item();
- if ( !item ) return; // canceled
- if ( item->type == Mask && !item->isDefault ) {
- m_hasMask = true;
- m_mask = item->value;
- }
- if ( item->isDefault && !hasDefaultEntries() ) {
- // first default entry, fill in what is needed
- if ( item->type != User ) {
- unsigned short v = findDefaultItemByType( User )->value;
- new KACLListViewItem( this, User, v, true );
- }
- if ( item->type != Group ) {
- unsigned short v = findDefaultItemByType( Group )->value;
- new KACLListViewItem( this, Group, v, true );
- }
- if ( item->type != Others ) {
- unsigned short v = findDefaultItemByType( Others )->value;
- new KACLListViewItem( this, Others, v, true );
- }
- }
- const KACLListViewItem *defaultMaskItem = findDefaultItemByType( Mask );
- if ( item->isDefault && !defaultMaskItem ) {
- unsigned short v = calculateMaskValue( true );
- new KACLListViewItem( this, Mask, v, true );
- }
- if ( !item->isDefault && !m_hasMask &&
- ( item->type == Group
- || item->type == NamedUser
- || item->type == NamedGroup ) ) {
- // auto-add a mask entry
- unsigned short v = calculateMaskValue( false );
- new KACLListViewItem( this, Mask, v, false );
- m_hasMask = true;
- m_mask = v;
- }
- calculateEffectiveRights();
- sort();
- setCurrentItem( item );
- // TQListView doesn't seem to emit, in this case, and we need to update
- // the buttons...
- if ( childCount() == 1 )
- emit currentChanged( item );
-}
-
-void KACLListView::slotEditEntry()
-{
- TQListViewItem * current = currentItem();
- if ( !current ) return;
- KACLListViewItem *item = static_cast<KACLListViewItem*>( current );
- int allowedTypes = item->type | NamedUser | NamedGroup;
- bool itemWasMask = item->type == Mask;
- if ( !m_hasMask || itemWasMask )
- allowedTypes |= Mask;
- int allowedDefaultTypes = item->type | NamedUser | NamedGroup;
- if ( !findDefaultItemByType( Mask ) )
- allowedDefaultTypes |= Mask;
- if ( !hasDefaultEntries() )
- allowedDefaultTypes |= User | Group;
-
- EditACLEntryDialog dlg( this, item,
- allowedUsers( false, item ), allowedGroups( false, item ),
- allowedUsers( true, item ), allowedGroups( true, item ),
- allowedTypes, allowedDefaultTypes, m_allowDefaults );
- dlg.exec();
- if ( itemWasMask && item->type != Mask ) {
- m_hasMask = false;
- m_mask = 0;
- }
- if ( !itemWasMask && item->type == Mask ) {
- m_mask = item->value;
- m_hasMask = true;
- }
- calculateEffectiveRights();
- sort();
-}
-
-void KACLListView::slotRemoveEntry()
-{
- TQListViewItemIterator it( this, TQListViewItemIterator::Selected );
- while ( it.current() ) {
- KACLListViewItem *item = static_cast<KACLListViewItem*>( it.current() );
- ++it;
- /* First check if it's a mask entry and if so, make sure that there is
- * either no name user or group entry, which means the mask can be
- * removed, or don't remove it, but reset it. That is allowed. */
- if ( item->type == Mask ) {
- bool itemWasDefault = item->isDefault;
- if ( !itemWasDefault && maskCanBeDeleted() ) {
- m_hasMask= false;
- m_mask = 0;
- delete item;
- } else if ( itemWasDefault && defaultMaskCanBeDeleted() ) {
- delete item;
- } else {
- item->value = 0;
- item->repaint();
- }
- if ( !itemWasDefault )
- calculateEffectiveRights();
- } else {
- // for the base permissions, disable them, which is what libacl does
- if ( !item->isDefault &&
- ( item->type == User
- || item->type == Group
- || item->type == Others ) ) {
- item->value = 0;
- item->repaint();
- } else {
- delete item;
- }
- }
- }
-}
-
-bool KACLListView::maskCanBeDeleted() const
-{
- return !findItemByType( NamedUser ) && !findItemByType( NamedGroup );
-}
-
-bool KACLListView::defaultMaskCanBeDeleted() const
-{
- return !findDefaultItemByType( NamedUser ) && !findDefaultItemByType( NamedGroup );
-}
-
-#include "kacleditwidget.moc"
-#include "kacleditwidget_p.moc"
-#endif
-// vim:set ts=8 sw=4:
diff --git a/kio/kfile/kacleditwidget.h b/kio/kfile/kacleditwidget.h
deleted file mode 100644
index d0f30f60a..000000000
--- a/kio/kfile/kacleditwidget.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/***************************************************************************
- * Copyright (C) 2005 by Sean Harmer <sh@rama.homelinux.org> *
- * Till Adam <adam@kde.org> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU Library 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., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#ifndef KACLEDITWIDGET_H
-#define KACLEDITWIDGET_H
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#ifdef Q_MOC_RUN
-#define USE_POSIX_ACL
-#endif // Q_MOC_RUN
-
-#ifdef USE_POSIX_ACL
-
-#include <klistview.h>
-#include <kacl.h>
-#include <kfileitem.h>
-
-class KACLListViewItem;
-class KACLListView;
-class TQPushButton;
-
-class KACLEditWidget : TQWidget
-{
- Q_OBJECT
-
-public:
- KACLEditWidget( TQWidget *parent = 0, const char *name = 0 );
- KACL getACL() const;
- KACL getDefaultACL() const;
- void setACL( const KACL & );
- void setDefaultACL( const KACL & );
- void setAllowDefaults( bool value );
- void setReadOnly( bool value );
-private slots:
- void slotUpdateButtons();
-
-private:
- KACLListView* m_listView;
- TQPushButton *m_AddBtn;
- TQPushButton *m_EditBtn;
- TQPushButton *m_DelBtn;
-};
-
-
-#endif
-#endif
diff --git a/kio/kfile/kacleditwidget_p.h b/kio/kfile/kacleditwidget_p.h
deleted file mode 100644
index 166725638..000000000
--- a/kio/kfile/kacleditwidget_p.h
+++ /dev/null
@@ -1,206 +0,0 @@
-/***************************************************************************
- * Copyright (C) 2005 by Sean Harmer <sh@rama.homelinux.org> *
- * Till Adam <adam@kde.org> *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU Library 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., *
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
- ***************************************************************************/
-#ifndef KACLEDITWIDGET_P_H
-#define KACLEDITWIDGET_P_H
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#ifdef Q_MOC_RUN
-#define USE_POSIX_ACL
-#endif // Q_MOC_RUN
-
-#ifdef USE_POSIX_ACL
-#include <klistview.h>
-#include <sys/acl.h>
-#include <kacl.h>
-#include <kfileitem.h>
-#include <kdialogbase.h>
-#include <tqpixmap.h>
-#include <tqcombobox.h>
-
-class KACLListViewItem;
-class TQPushButton;
-class TQVButtonGroup;
-class KACLListView;
-class TQWidgetStack;
-class TQCheckBox;
-
-/**
-@author Sean Harmer
-*/
-class KACLListView : public KListView
-{
- Q_OBJECT
-
- friend class KACLListViewItem;
-public:
- enum Types
- {
- OWNER_IDX = 0,
- GROUP_IDX,
- OTHERS_IDX,
- MASK_IDX,
- NAMED_USER_IDX,
- NAMED_GROUP_IDX,
- LAST_IDX
- };
- enum EntryType { User = 1,
- Group = 2,
- Others = 4,
- Mask = 8,
- NamedUser = 16,
- NamedGroup = 32,
- AllTypes = 63 };
-
- KACLListView( TQWidget* parent = 0, const char* name = 0 );
- ~KACLListView();
-
- bool hasMaskEntry() const { return m_hasMask; }
- bool hasDefaultEntries() const;
- bool allowDefaults() const { return m_allowDefaults; }
- void setAllowDefaults( bool v ) { m_allowDefaults = v; }
- unsigned short maskPermissions() const;
- void setMaskPermissions( unsigned short maskPerms );
- acl_perm_t maskPartialPermissions() const;
- void setMaskPartialPermissions( acl_perm_t maskPerms );
-
- bool maskCanBeDeleted() const;
- bool defaultMaskCanBeDeleted() const;
-
- const KACLListViewItem* findDefaultItemByType( EntryType type ) const;
- const KACLListViewItem* findItemByType( EntryType type,
- bool defaults = false ) const;
- unsigned short calculateMaskValue( bool defaults ) const;
- void calculateEffectiveRights();
-
- TQStringList allowedUsers( bool defaults, KACLListViewItem *allowedItem = 0 );
- TQStringList allowedGroups( bool defaults, KACLListViewItem *allowedItem = 0 );
-
- const KACL getACL() const { return getACL(); }
- KACL getACL();
-
- const KACL getDefaultACL() const { return getDefaultACL(); }
- KACL getDefaultACL();
-
- TQPixmap getYesPixmap() const { return *m_yesPixmap; }
- TQPixmap getYesPartialPixmap() const { return *m_yesPartialPixmap; }
-
-public slots:
- void slotAddEntry();
- void slotEditEntry();
- void slotRemoveEntry();
- void setACL( const KACL &anACL );
- void setDefaultACL( const KACL &anACL );
-
-protected slots:
- void entryClicked( TQListViewItem* pItem, const TQPoint& pt, int col );
-protected:
- void contentsMousePressEvent( TQMouseEvent * e );
-
-private:
- void fillItemsFromACL( const KACL &pACL, bool defaults = false );
- KACL itemsToACL( bool defaults ) const;
-
- KACL m_ACL;
- KACL m_defaultACL;
- unsigned short m_mask;
- bool m_hasMask;
- bool m_allowDefaults;
- TQStringList m_allUsers;
- TQStringList m_allGroups;
- TQPixmap* m_yesPixmap;
- TQPixmap* m_yesPartialPixmap;
-};
-
-class EditACLEntryDialog : public KDialogBase
-{
- Q_OBJECT
-
-public:
- EditACLEntryDialog( KACLListView *listView, KACLListViewItem *item,
- const TQStringList &users,
- const TQStringList &groups,
- const TQStringList &defaultUsers,
- const TQStringList &defaultGroups,
- int allowedTypes = KACLListView::AllTypes,
- int allowedDefaultTypes = KACLListView::AllTypes,
- bool allowDefault = false );
- KACLListViewItem* item() const { return m_item; }
-public slots:
- void slotOk();
- void slotSelectionChanged( int id );
-private slots:
- void slotUpdateAllowedUsersAndGroups();
- void slotUpdateAllowedTypes();
-private:
- KACLListView *m_listView;
- KACLListViewItem *m_item;
- TQStringList m_users;
- TQStringList m_groups;
- TQStringList m_defaultUsers;
- TQStringList m_defaultGroups;
- int m_allowedTypes;
- int m_allowedDefaultTypes;
- TQVButtonGroup *m_buttonGroup;
- TQComboBox *m_usersCombo;
- TQComboBox *m_groupsCombo;
- TQWidgetStack *m_widgetStack;
- TQCheckBox *m_defaultCB;
-};
-
-
-class KACLListViewItem : public KListViewItem
-{
-public:
- KACLListViewItem( TQListView* parent, KACLListView::EntryType type,
- unsigned short value,
- bool defaultEntry,
- const TQString& qualifier = TQString::null );
- virtual ~KACLListViewItem();
- virtual TQString key( int column, bool ascending ) const;
-
- void calcEffectiveRights();
-
- bool isDeletable() const;
- bool isAllowedToChangeType() const;
-
- void togglePerm( acl_perm_t perm );
-
- virtual void paintCell( TQPainter *p, const TQColorGroup &cg,
- int column, int width, int alignment );
-
- void updatePermPixmaps();
- void repaint();
-
- KACLListView::EntryType type;
- unsigned short value;
- bool isDefault;
- TQString qualifier;
- bool isPartial;
-
-private:
- KACLListView* m_pACLListView;
-};
-
-
-#endif
-#endif
diff --git a/kio/kfile/kcombiview.cpp b/kio/kfile/kcombiview.cpp
deleted file mode 100644
index 3f199fb92..000000000
--- a/kio/kfile/kcombiview.cpp
+++ /dev/null
@@ -1,371 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
- 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#include <assert.h>
-
-#include "kfileitem.h"
-#include "kcombiview.h"
-#include "kfileiconview.h"
-#include "kfiledetailview.h"
-#include "config-kfile.h"
-
-#include <tqevent.h>
-
-#include <tqdir.h>
-
-#include <kapplication.h>
-#include <kconfig.h>
-#include <kdebug.h>
-#include <kglobal.h>
-
-#include <tqvaluelist.h>
-
-KCombiView::KCombiView( TQWidget *parent, const char *name)
- : TQSplitter( parent, name),
- KFileView(),
- right(0),
- m_lastViewForNextItem(0),
- m_lastViewForPrevItem(0)
-{
- left = new KFileIconView( this, "left" );
- left->setAcceptDrops(false);
- left->viewport()->setAcceptDrops(false);
- left->setGridX( 160 );
- left->KFileView::setViewMode( Directories );
- left->setArrangement( TQIconView::LeftToRight );
- left->setParentView( this );
- left->setAcceptDrops(false);
- left->installEventFilter( this );
-
- connect( sig, TQT_SIGNAL( sortingChanged( TQDir::SortSpec ) ),
- TQT_SLOT( slotSortingChanged( TQDir::SortSpec ) ));
-}
-
-KCombiView::~KCombiView()
-{
- delete right;
-}
-
-void KCombiView::setRight(KFileView *view)
-{
- delete right;
- right = view;
- right->KFileView::setViewMode( Files );
- setViewName( right->viewName() );
-
- TQValueList<int> lst;
- lst << left->gridX() + 2 * left->spacing();
- setSizes( lst );
- setResizeMode( left, TQSplitter::KeepSize );
-
- right->setParentView( this );
- right->widget()->setAcceptDrops(acceptDrops());
- right->setDropOptions(dropOptions());
- right->widget()->installEventFilter( this );
-}
-
-
-void KCombiView::insertItem( KFileItem *item )
-{
- KFileView::insertItem( item );
-
- if ( item->isDir() ) {
- left->updateNumbers( item );
- left->insertItem( item );
- }
- else {
- right->updateNumbers( item );
- right->insertItem( item );
- }
-}
-
-void KCombiView::setSorting( TQDir::SortSpec sort )
-{
- if ( !right )
- kdFatal() << "You need to call setRight( someview ) before!" << endl;
- right->setSorting( sort );
- left->setSorting( sort );
-
- KFileView::setSorting( right->sorting() );
-}
-
-void KCombiView::clearView()
-{
- left->clearView();
- if ( right )
- right->clearView();
-}
-
-void KCombiView::updateView( bool b )
-{
- left->updateView( b );
- if ( right )
- right->updateView( b );
-}
-
-void KCombiView::updateView( const KFileItem *i )
-{
- left->updateView( i );
- if ( right )
- right->updateView( i );
-}
-
-void KCombiView::removeItem( const KFileItem *i )
-{
- left->removeItem( i );
- if ( right )
- right->removeItem( i );
- KFileView::removeItem( i );
-}
-
-void KCombiView::listingCompleted()
-{
- left->listingCompleted();
- if ( right )
- right->listingCompleted();
-}
-
-void KCombiView::clear()
-{
- KFileView::clear();
- left->KFileView::clear();
- if ( right )
- right->clear();
-}
-
-void KCombiView::clearSelection()
-{
- left->clearSelection();
- if ( right )
- right->clearSelection();
-}
-
-void KCombiView::selectAll()
-{
- left->selectAll();
- if ( right )
- right->selectAll();
-}
-
-void KCombiView::invertSelection()
-{
- left->invertSelection();
- if ( right )
- right->invertSelection();
-}
-
-bool KCombiView::isSelected( const KFileItem *item ) const
-{
- assert( right ); // for performance reasons no if ( right ) check.
- return (right->isSelected( item ) || left->isSelected( item ));
-}
-
-void KCombiView::setSelectionMode( KFile::SelectionMode sm )
-{
- // I think the left view (directories should always be in
- // Single-Mode, right?
- // left->setSelectionMode( sm );
- if ( !right )
- kdFatal() << "You need to call setRight( someview ) before!" << endl;
- right->setSelectionMode( sm );
-}
-
-void KCombiView::setSelected( const KFileItem *item, bool enable )
-{
- left->setSelected( item, enable );
- if ( right )
- right->setSelected( item, enable );
-}
-
-void KCombiView::setCurrentItem( const KFileItem *item )
-{
- left->setCurrentItem( item );
- if ( right )
- right->setCurrentItem( item );
-}
-
-KFileItem * KCombiView::currentFileItem() const
-{
- // we can actually have two current items, one in each view. So we simply
- // prefer the fileview's item over the directory's.
- // Smarter: if the right view has focus, prefer that over the left.
- if ( !right )
- return left->currentFileItem();
-
- KFileView *preferredView = focusView( right );
- KFileItem *item = preferredView->currentFileItem();
- if ( !item && preferredView != left )
- item = left->currentFileItem();
-
- return item;
-}
-
-void KCombiView::ensureItemVisible(const KFileItem *item)
-{
- left->ensureItemVisible( item );
- if ( right )
- right->ensureItemVisible( item );
-}
-
-KFileItem * KCombiView::firstFileItem() const
-{
- if ( !right )
- return left->firstFileItem();
-
- KFileView *preferredView = focusView( left );
- KFileView *otherView = (preferredView == left) ? right : left;
- KFileItem *item = preferredView->firstFileItem();
- if ( !item )
- item = otherView->firstFileItem();
-
- return item;
-}
-
-KFileItem * KCombiView::nextItem( const KFileItem *fileItem ) const
-{
- if ( !right )
- return left->nextItem( fileItem );
-
- KFileView *preferredView = focusView( left );
- KFileView *otherView = (preferredView == left) ? right : left;
- KFileItem *item = preferredView->nextItem( fileItem );
-
- if ( item )
- m_lastViewForNextItem = preferredView;
- else { // no item, check other view
- // when changing from one to another view, we need to continue
- // with the next view's first item!
- if ( m_lastViewForNextItem != otherView ) {
- m_lastViewForNextItem = otherView;
- return otherView->firstFileItem();
- }
-
- item = otherView->nextItem( fileItem );
- m_lastViewForNextItem = otherView;
- }
-
- return item;
-}
-
-KFileItem * KCombiView::prevItem( const KFileItem *fileItem ) const
-{
- if ( !right )
- return left->nextItem( fileItem );
-
- KFileView *preferredView = focusView( left );
- KFileView *otherView = (preferredView == left) ? right : left;
- KFileItem *item = preferredView->prevItem( fileItem );
- if ( item )
- m_lastViewForPrevItem = preferredView;
-
- else { // no item, check other view
- // when changing from one to another view, we need to continue
- // with the next view's last item!
- if ( m_lastViewForPrevItem != otherView ) {
- fileItem = otherView->firstFileItem();
- while ( otherView->nextItem( fileItem ) ) // find the last item
- fileItem = otherView->nextItem( fileItem );
- }
-
- item = otherView->prevItem( fileItem );
- m_lastViewForPrevItem = otherView;
- }
-
- return item;
-}
-
-void KCombiView::slotSortingChanged( TQDir::SortSpec sorting )
-{
- KFileView::setSorting( sorting );
-}
-
-KFileView *KCombiView::focusView( KFileView *preferred ) const
-{
- TQWidget *w = focusWidget();
- KFileView *other = (right == preferred) ? left : right;
- return (preferred && w == preferred->widget()) ? preferred : other;
-}
-
-void KCombiView::readConfig( TDEConfig *config, const TQString& group )
-{
- left->readConfig( config, group );
- if ( right )
- right->readConfig( config, group );
-}
-
-void KCombiView::writeConfig( TDEConfig *config, const TQString& group )
-{
- left->writeConfig( config, group );
- if ( right )
- right->writeConfig( config, group );
-}
-
-KActionCollection * KCombiView::actionCollection() const
-{
- return focusView( right )->actionCollection();
-}
-
-void KCombiView::setAcceptDrops(bool b)
-{
- left->setAcceptDrops(b);
- if (right)
- right->widget()->setAcceptDrops(b);
- TQSplitter::setAcceptDrops(b);
-}
-
-void KCombiView::setDropOptions_impl(int options)
-{
- KFileView::setDropOptions_impl(options);
- left->setDropOptions(options);
- if (right)
- right->setDropOptions(options);
-}
-
-void KCombiView::virtual_hook( int id, void* data )
-{
- switch(id) {
- case VIRTUAL_SET_DROP_OPTIONS:
- setDropOptions_impl(*(int *)data);
- break;
- default:
- KFileView::virtual_hook( id, data );
- }
-}
-
-bool KCombiView::eventFilter( TQObject *o, TQEvent *e )
-{
- int type = e->type();
-
- // only the focused view may have a selection
- if ( type == TQEvent::FocusIn )
- {
- if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(left) )
- right->clearSelection();
- else if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(right->widget()) )
- left->clearSelection();
- }
-
- return TQSplitter::eventFilter( o, e );
-}
-
-#include "kcombiview.moc"
-
diff --git a/kio/kfile/kcombiview.h b/kio/kfile/kcombiview.h
deleted file mode 100644
index 5d56b8257..000000000
--- a/kio/kfile/kcombiview.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/* -*- c++ -*-
- This file is part of the KDE libraries
- Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
- 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KCOMBIVIEW_H
-#define _KCOMBIVIEW_H
-
-#include <tqsplitter.h>
-#include <klocale.h>
-
-#include <kfile.h>
-#include <kfileview.h>
-
-class KFileIconView;
-class TQEvent;
-class TQIconViewItem;
-
-/**
- * This view is designed to combine two KFileViews into one widget, to show
- * directories on the left side and files on the right side.
- *
- * Methods like selectedItems() to query status _only_ work on the right side,
- * i.e. on the files.
- *
- * After creating the KCombiView, you need to supply the view shown in the
- * right, (see setRight()). Available KFileView implementations are
- * KFileIconView and KFileDetailView.
- *
- * Most of the below methods are just implementations of the baseclass
- * KFileView, so look there for documentation.
- *
- * @see KFileView
- * @see KFileIconView
- * @see KFileDetailView
- * @see KDirOperator
- */
-class TDEIO_EXPORT KCombiView : public TQSplitter,
- public KFileView
-{
- Q_OBJECT
-
-public:
- KCombiView( TQWidget *parent, const char *name);
- virtual ~KCombiView();
-
- virtual TQWidget *widget() { return this; }
- virtual void clearView();
-
- virtual void updateView( bool );
- virtual void updateView(const KFileItem*);
- virtual void removeItem( const KFileItem * );
- virtual void listingCompleted();
-
- /**
- * Sets the view to be shown in the right. You need to call this before
- * doing anything else with this widget.
- */
- void setRight(KFileView *view);
-
- virtual void setSelectionMode( KFile::SelectionMode sm );
-
- virtual void setSelected(const KFileItem *, bool);
- virtual bool isSelected( const KFileItem * ) const;
- virtual void clearSelection();
- virtual void selectAll();
- virtual void invertSelection();
-
- virtual void setCurrentItem( const KFileItem * );
- virtual KFileItem * currentFileItem() const;
- virtual KFileItem * firstFileItem() const;
- virtual KFileItem * nextItem( const KFileItem * ) const;
- virtual KFileItem * prevItem( const KFileItem * ) const;
-
- virtual void insertItem( KFileItem *i );
- virtual void clear();
-
- virtual void setSorting( TQDir::SortSpec sort );
-
- virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
- virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
-
- void ensureItemVisible( const KFileItem * );
-
- virtual KActionCollection * actionCollection() const;
-
- virtual void setAcceptDrops(bool b);
-
-protected:
- KFileIconView *left;
- KFileView *right;
-
-protected slots:
- void slotSortingChanged( TQDir::SortSpec );
-
-private:
- KFileView *focusView( KFileView *preferred ) const;
-
- // in nextItem() and prevItem(), we have to switch views, when the first
- // view returns 0L. So we need to remember which view was used in the
- // previous call to next/prevItem(). Yes, it's a hack, but it works for
- // some cases at least.
- mutable KFileView *m_lastViewForNextItem;
- mutable KFileView *m_lastViewForPrevItem;
-
-protected:
- virtual bool eventFilter( TQObject *o, TQEvent *e );
- void setDropOptions_impl(int options);
-
- virtual void virtual_hook( int id, void* data );
-private:
- class KCombiViewPrivate;
- KCombiViewPrivate *d;
-
-};
-
-#endif
diff --git a/kio/kfile/kcustommenueditor.cpp b/kio/kfile/kcustommenueditor.cpp
deleted file mode 100644
index 2049860d1..000000000
--- a/kio/kfile/kcustommenueditor.cpp
+++ /dev/null
@@ -1,242 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; version 2
- of the License.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqhbox.h>
-#include <tqregexp.h>
-#include <tqimage.h>
-#include <tqpushbutton.h>
-#include <tqdir.h>
-
-#include <kbuttonbox.h>
-#include <klocale.h>
-#include <kglobal.h>
-#include <kiconloader.h>
-#include <klistview.h>
-#include <kservice.h>
-#include <kstandarddirs.h>
-#include <kconfigbase.h>
-#include <kopenwith.h>
-
-#include "kcustommenueditor.h"
-
-class KCustomMenuEditor::Item : public TQListViewItem
-{
-public:
- Item(TQListView *parent, KService::Ptr service)
- : TQListViewItem(parent),
- s(service)
- {
- init();
- }
-
- Item(TQListViewItem *parent, KService::Ptr service)
- : TQListViewItem(parent),
- s(service)
- {
- init();
- }
-
- void init()
- {
- TQString serviceName = s->name();
-
- // item names may contain ampersands. To avoid them being converted
- // to accelators, replace them with two ampersands.
- serviceName.replace("&", "&&");
-
- TQPixmap normal = TDEGlobal::instance()->iconLoader()->loadIcon(s->icon(), KIcon::Small,
- 0, KIcon::DefaultState, 0L, true);
-
- // make sure they are not larger than 16x16
- if (normal.width() > 16 || normal.height() > 16) {
- TQImage tmp = normal.convertToImage();
- tmp = tmp.smoothScale(16, 16);
- normal.convertFromImage(tmp);
- }
- setText(0, serviceName);
- setPixmap(0, normal);
- }
-
- KService::Ptr s;
-};
-
-class KCustomMenuEditor::KCustomMenuEditorPrivate
-{
-public:
- TQPushButton * pbRemove;
- TQPushButton * pbMoveUp;
- TQPushButton * pbMoveDown;
-};
-
-KCustomMenuEditor::KCustomMenuEditor(TQWidget *parent)
- : KDialogBase(parent, "custommenueditor", true, i18n("Menu Editor"), Ok|Cancel, Ok, true),
- m_listView(0)
-{
- d = new KCustomMenuEditorPrivate;
- TQHBox *page = makeHBoxMainWidget();
- m_listView = new KListView(page);
- m_listView->addColumn(i18n("Menu"));
- m_listView->setFullWidth(true);
- m_listView->setSorting(-1);
- KButtonBox *buttonBox = new KButtonBox(page, Qt::Vertical);
- buttonBox->addButton(i18n("New..."), TQT_TQOBJECT(this), TQT_SLOT(slotNewItem()));
- d->pbRemove=buttonBox->addButton(i18n("Remove"), TQT_TQOBJECT(this), TQT_SLOT(slotRemoveItem()));
- d->pbMoveUp=buttonBox->addButton(i18n("Move Up"), TQT_TQOBJECT(this), TQT_SLOT(slotMoveUp()));
- d->pbMoveDown=buttonBox->addButton(i18n("Move Down"), TQT_TQOBJECT(this), TQT_SLOT(slotMoveDown()));
- buttonBox->layout();
- connect( m_listView, TQT_SIGNAL( selectionChanged () ), this, TQT_SLOT( refreshButton() ) );
- refreshButton();
-}
-
-KCustomMenuEditor::~KCustomMenuEditor()
-{
- delete d;
- d=0;
-}
-
-void KCustomMenuEditor::refreshButton()
-{
- TQListViewItem *item = m_listView->currentItem();
- d->pbRemove->setEnabled( item );
- d->pbMoveUp->setEnabled( item && item->itemAbove() );
- d->pbMoveDown->setEnabled( item && item->itemBelow() );
-}
-
-void
-KCustomMenuEditor::load(TDEConfigBase *cfg)
-{
- cfg->setGroup(TQString::null);
- int count = cfg->readNumEntry("NrOfItems");
- TQListViewItem *last = 0;
- for(int i = 0; i < count; i++)
- {
- TQString entry = cfg->readPathEntry(TQString("Item%1").arg(i+1));
- if (entry.isEmpty())
- continue;
-
- // Try KSycoca first.
- KService::Ptr menuItem = KService::serviceByDesktopPath( entry );
- if (!menuItem)
- menuItem = KService::serviceByDesktopName( entry );
- if (!menuItem)
- menuItem = new KService( entry );
-
- if (!menuItem->isValid())
- continue;
-
- TQListViewItem *item = new Item(m_listView, menuItem);
- item->moveItem(last);
- last = item;
- }
-}
-
-void
-KCustomMenuEditor::save(TDEConfigBase *cfg)
-{
- // First clear the whole config file.
- TQStringList groups = cfg->groupList();
- for(TQStringList::ConstIterator it = groups.begin();
- it != groups.end(); ++it)
- {
- cfg->deleteGroup(*it);
- }
-
- cfg->setGroup(TQString::null);
- Item * item = (Item *) m_listView->firstChild();
- int i = 0;
- while(item)
- {
- i++;
- TQString path = item->s->desktopEntryPath();
- if (TQDir::isRelativePath(path) || TQDir::isRelativePath(TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path)))
- path = item->s->desktopEntryName();
- cfg->writePathEntry(TQString("Item%1").arg(i), path);
- item = (Item *) item->nextSibling();
- }
- cfg->writeEntry("NrOfItems", i);
-}
-
-void
-KCustomMenuEditor::slotNewItem()
-{
- TQListViewItem *item = m_listView->currentItem();
-
- KOpenWithDlg dlg(this);
- dlg.setSaveNewApplications(true);
-
- if (dlg.exec())
- {
- KService::Ptr s = dlg.service();
- if (s && s->isValid())
- {
- Item *newItem = new Item(m_listView, s);
- newItem->moveItem(item);
- }
- refreshButton();
- }
-}
-
-void
-KCustomMenuEditor::slotRemoveItem()
-{
- TQListViewItem *item = m_listView->currentItem();
- if (!item)
- return;
-
- delete item;
- refreshButton();
-}
-
-void
-KCustomMenuEditor::slotMoveUp()
-{
- TQListViewItem *item = m_listView->currentItem();
- if (!item)
- return;
-
- TQListViewItem *searchItem = m_listView->firstChild();
- while(searchItem)
- {
- TQListViewItem *next = searchItem->nextSibling();
- if (next == item)
- {
- searchItem->moveItem(item);
- break;
- }
- searchItem = next;
- }
- refreshButton();
-}
-
-void
-KCustomMenuEditor::slotMoveDown()
-{
- TQListViewItem *item = m_listView->currentItem();
- if (!item)
- return;
-
- TQListViewItem *after = item->nextSibling();
- if (!after)
- return;
-
- item->moveItem( after );
- refreshButton();
-}
-
-#include "kcustommenueditor.moc"
diff --git a/kio/kfile/kdiroperator.cpp b/kio/kfile/kdiroperator.cpp
deleted file mode 100644
index 1b7e11356..000000000
--- a/kio/kfile/kdiroperator.cpp
+++ /dev/null
@@ -1,1740 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1999,2000 Stephan Kulow <coolo@kde.org>
- 1999,2000,2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <unistd.h>
-
-#include <tqdir.h>
-#include <tqapplication.h>
-#include <tqdialog.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqpushbutton.h>
-#include <tqpopupmenu.h>
-#include <tqregexp.h>
-#include <tqtimer.h>
-#include <tqvbox.h>
-
-#include <kaction.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kdialog.h>
-#include <kdialogbase.h>
-#include <kdirlister.h>
-#include <kinputdialog.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <kpopupmenu.h>
-#include <kprogress.h>
-#include <kstdaction.h>
-#include <kio/job.h>
-#include <kio/jobclasses.h>
-#include <kio/netaccess.h>
-#include <kio/previewjob.h>
-#include <kio/renamedlg.h>
-#include <kpropertiesdialog.h>
-#include <kservicetypefactory.h>
-#include <kstdaccel.h>
-#include <kde_file.h>
-
-#include "config-kfile.h"
-#include "kcombiview.h"
-#include "kdiroperator.h"
-#include "kfiledetailview.h"
-#include "kfileiconview.h"
-#include "kfilepreview.h"
-#include "kfileview.h"
-#include "kfileitem.h"
-#include "kfilemetapreview.h"
-
-
-template class TQPtrStack<KURL>;
-template class TQDict<KFileItem>;
-
-
-class KDirOperator::KDirOperatorPrivate
-{
-public:
- KDirOperatorPrivate() {
- onlyDoubleClickSelectsFiles = false;
- progressDelayTimer = 0L;
- dirHighlighting = false;
- config = 0L;
- dropOptions = 0;
- }
-
- ~KDirOperatorPrivate() {
- delete progressDelayTimer;
- }
-
- bool dirHighlighting;
- TQString lastURL; // used for highlighting a directory on cdUp
- bool onlyDoubleClickSelectsFiles;
- TQTimer *progressDelayTimer;
- KActionSeparator *viewActionSeparator;
- int dropOptions;
-
- TDEConfig *config;
- TQString configGroup;
-};
-
-KDirOperator::KDirOperator(const KURL& _url,
- TQWidget *parent, const char* _name)
- : TQWidget(parent, _name),
- dir(0),
- m_fileView(0),
- progress(0)
-{
- myPreview = 0L;
- myMode = KFile::File;
- m_viewKind = KFile::Simple;
- mySorting = static_cast<TQDir::SortSpec>(TQDir::Name | TQDir::DirsFirst);
- d = new KDirOperatorPrivate;
-
- if (_url.isEmpty()) { // no dir specified -> current dir
- TQString strPath = TQDir::currentDirPath();
- strPath.append('/');
- currUrl = KURL();
- currUrl.setProtocol(TQString::fromLatin1("file"));
- currUrl.setPath(strPath);
- }
- else {
- currUrl = _url;
- if ( currUrl.protocol().isEmpty() )
- currUrl.setProtocol(TQString::fromLatin1("file"));
-
- currUrl.addPath("/"); // make sure we have a trailing slash!
- }
-
- setDirLister( new KDirLister( true ) );
-
- connect(&myCompletion, TQT_SIGNAL(match(const TQString&)),
- TQT_SLOT(slotCompletionMatch(const TQString&)));
-
- progress = new KProgress(this, "progress");
- progress->adjustSize();
- progress->move(2, height() - progress->height() -2);
-
- d->progressDelayTimer = new TQTimer( this, "progress delay timer" );
- connect( d->progressDelayTimer, TQT_SIGNAL( timeout() ),
- TQT_SLOT( slotShowProgress() ));
-
- myCompleteListDirty = false;
-
- backStack.setAutoDelete( true );
- forwardStack.setAutoDelete( true );
-
- // action stuff
- setupActions();
- setupMenu();
-
- setFocusPolicy(TQ_WheelFocus);
-}
-
-KDirOperator::~KDirOperator()
-{
- resetCursor();
- if ( m_fileView )
- {
- if ( d->config )
- m_fileView->writeConfig( d->config, d->configGroup );
-
- delete m_fileView;
- m_fileView = 0L;
- }
-
- delete myPreview;
- delete dir;
- delete d;
-}
-
-
-void KDirOperator::setSorting( TQDir::SortSpec spec )
-{
- if ( m_fileView )
- m_fileView->setSorting( spec );
- mySorting = spec;
- updateSortActions();
-}
-
-void KDirOperator::resetCursor()
-{
- TQApplication::restoreOverrideCursor();
- progress->hide();
-}
-
-void KDirOperator::insertViewDependentActions()
-{
- // If we have a new view actionCollection(), insert its actions
- // into viewActionMenu.
-
- if( !m_fileView )
- return;
-
- if ( (viewActionMenu->popupMenu()->count() == 0) || // Not yet initialized or...
- (viewActionCollection != m_fileView->actionCollection()) ) // ...changed since.
- {
- if (viewActionCollection)
- {
- disconnect( viewActionCollection, TQT_SIGNAL( inserted( KAction * )),
- this, TQT_SLOT( slotViewActionAdded( KAction * )));
- disconnect( viewActionCollection, TQT_SIGNAL( removed( KAction * )),
- this, TQT_SLOT( slotViewActionRemoved( KAction * )));
- }
-
- viewActionMenu->popupMenu()->clear();
-// viewActionMenu->insert( shortAction );
-// viewActionMenu->insert( detailedAction );
-// viewActionMenu->insert( actionSeparator );
- viewActionMenu->insert( myActionCollection->action( "short view" ) );
- viewActionMenu->insert( myActionCollection->action( "detailed view" ) );
- viewActionMenu->insert( actionSeparator );
- viewActionMenu->insert( showHiddenAction );
-// viewActionMenu->insert( myActionCollection->action( "single" ));
- viewActionMenu->insert( separateDirsAction );
- // Warning: adjust slotViewActionAdded() and slotViewActionRemoved()
- // when you add/remove actions here!
-
- viewActionCollection = m_fileView->actionCollection();
- if (!viewActionCollection)
- return;
-
- if ( !viewActionCollection->isEmpty() )
- {
- viewActionMenu->insert( d->viewActionSeparator );
-
- // first insert the normal actions, then the grouped ones
- TQStringList groups = viewActionCollection->groups();
- groups.prepend( TQString::null ); // actions without group
- TQStringList::ConstIterator git = groups.begin();
- KActionPtrList list;
- KAction *sep = actionCollection()->action("separator");
- for ( ; git != groups.end(); ++git )
- {
- if ( git != groups.begin() )
- viewActionMenu->insert( sep );
-
- list = viewActionCollection->actions( *git );
- KActionPtrList::ConstIterator it = list.begin();
- for ( ; it != list.end(); ++it )
- viewActionMenu->insert( *it );
- }
- }
-
- connect( viewActionCollection, TQT_SIGNAL( inserted( KAction * )),
- TQT_SLOT( slotViewActionAdded( KAction * )));
- connect( viewActionCollection, TQT_SIGNAL( removed( KAction * )),
- TQT_SLOT( slotViewActionRemoved( KAction * )));
- }
-}
-
-void KDirOperator::activatedMenu( const KFileItem *, const TQPoint& pos )
-{
- setupMenu();
- updateSelectionDependentActions();
-
- actionMenu->popup( pos );
-}
-
-void KDirOperator::updateSelectionDependentActions()
-{
- bool hasSelection = m_fileView && m_fileView->selectedItems() &&
- !m_fileView->selectedItems()->isEmpty();
- myActionCollection->action( "trash" )->setEnabled( hasSelection );
- myActionCollection->action( "delete" )->setEnabled( hasSelection );
- myActionCollection->action( "properties" )->setEnabled( hasSelection );
-}
-
-void KDirOperator::setPreviewWidget(const TQWidget *w)
-{
- if(w != 0L)
- m_viewKind = (m_viewKind | KFile::PreviewContents);
- else
- m_viewKind = (m_viewKind & ~KFile::PreviewContents);
-
- delete myPreview;
- myPreview = w;
-
- KToggleAction *preview = static_cast<KToggleAction*>(myActionCollection->action("preview"));
- preview->setEnabled( w != 0L );
- preview->setChecked( w != 0L );
- setView( static_cast<KFile::FileView>(m_viewKind) );
-}
-
-int KDirOperator::numDirs() const
-{
- return m_fileView ? m_fileView->numDirs() : 0;
-}
-
-int KDirOperator::numFiles() const
-{
- return m_fileView ? m_fileView->numFiles() : 0;
-}
-
-void KDirOperator::slotDetailedView()
-{
- KFile::FileView view = static_cast<KFile::FileView>( (m_viewKind & ~KFile::Simple) | KFile::Detail );
- setView( view );
-}
-
-void KDirOperator::slotSimpleView()
-{
- KFile::FileView view = static_cast<KFile::FileView>( (m_viewKind & ~KFile::Detail) | KFile::Simple );
- setView( view );
-}
-
-void KDirOperator::slotToggleHidden( bool show )
-{
- dir->setShowingDotFiles( show );
- updateDir();
- if ( m_fileView )
- m_fileView->listingCompleted();
-}
-
-void KDirOperator::slotSeparateDirs()
-{
- if (separateDirsAction->isChecked())
- {
- KFile::FileView view = static_cast<KFile::FileView>( m_viewKind | KFile::SeparateDirs );
- setView( view );
- }
- else
- {
- KFile::FileView view = static_cast<KFile::FileView>( m_viewKind & ~KFile::SeparateDirs );
- setView( view );
- }
-}
-
-void KDirOperator::slotDefaultPreview()
-{
- m_viewKind = m_viewKind | KFile::PreviewContents;
- if ( !myPreview ) {
- myPreview = new KFileMetaPreview( this );
- (static_cast<KToggleAction*>( myActionCollection->action("preview") ))->setChecked(true);
- }
-
- setView( static_cast<KFile::FileView>(m_viewKind) );
-}
-
-void KDirOperator::slotSortByName()
-{
- int sorting = (m_fileView->sorting()) & ~TQDir::SortByMask;
- m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::Name ));
- mySorting = m_fileView->sorting();
- caseInsensitiveAction->setEnabled( true );
-}
-
-void KDirOperator::slotSortBySize()
-{
- int sorting = (m_fileView->sorting()) & ~TQDir::SortByMask;
- m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::Size ));
- mySorting = m_fileView->sorting();
- caseInsensitiveAction->setEnabled( false );
-}
-
-void KDirOperator::slotSortByDate()
-{
- int sorting = (m_fileView->sorting()) & ~TQDir::SortByMask;
- m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::Time ));
- mySorting = m_fileView->sorting();
- caseInsensitiveAction->setEnabled( false );
-}
-
-void KDirOperator::slotSortReversed()
-{
- if ( m_fileView )
- m_fileView->sortReversed();
-}
-
-void KDirOperator::slotToggleDirsFirst()
-{
- TQDir::SortSpec sorting = m_fileView->sorting();
- if ( !KFile::isSortDirsFirst( sorting ) )
- m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::DirsFirst ));
- else
- m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting & ~TQDir::DirsFirst));
- mySorting = m_fileView->sorting();
-}
-
-void KDirOperator::slotToggleIgnoreCase()
-{
- TQDir::SortSpec sorting = m_fileView->sorting();
- if ( !KFile::isSortCaseInsensitive( sorting ) )
- m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::IgnoreCase ));
- else
- m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting & ~TQDir::IgnoreCase));
- mySorting = m_fileView->sorting();
-}
-
-void KDirOperator::mkdir()
-{
- bool ok;
- TQString where = url().pathOrURL();
- TQString name = i18n( "New Folder" );
- if ( url().isLocalFile() && TQFileInfo( url().path(+1) + name ).exists() )
- name = TDEIO::RenameDlg::suggestName( url(), name );
-
- TQString dir = KInputDialog::getText( i18n( "New Folder" ),
- i18n( "Create new folder in:\n%1" ).arg( where ),
- name, &ok, this);
- if (ok)
- mkdir( TDEIO::encodeFileName( dir ), true );
-}
-
-bool KDirOperator::mkdir( const TQString& directory, bool enterDirectory )
-{
- // Creates "directory", relative to the current directory (currUrl).
- // The given path may contain any number directories, existant or not.
- // They will all be created, if possible.
-
- bool writeOk = false;
- bool exists = false;
- KURL url( currUrl );
-
- TQStringList dirs = TQStringList::split( TQDir::separator(), directory );
- TQStringList::ConstIterator it = dirs.begin();
-
- for ( ; it != dirs.end(); ++it )
- {
- url.addPath( *it );
- exists = TDEIO::NetAccess::exists( url, false, 0 );
- writeOk = !exists && TDEIO::NetAccess::mkdir( url, topLevelWidget() );
- }
-
- if ( exists ) // url was already existant
- {
- KMessageBox::sorry(viewWidget(), i18n("A file or folder named %1 already exists.").arg(url.pathOrURL()));
- enterDirectory = false;
- }
- else if ( !writeOk ) {
- KMessageBox::sorry(viewWidget(), i18n("You do not have permission to "
- "create that folder." ));
- }
- else if ( enterDirectory ) {
- setURL( url, true );
- }
-
- return writeOk;
-}
-
-TDEIO::DeleteJob * KDirOperator::del( const KFileItemList& items,
- bool ask, bool showProgress )
-{
- return del( items, this, ask, showProgress );
-}
-
-TDEIO::DeleteJob * KDirOperator::del( const KFileItemList& items,
- TQWidget *parent,
- bool ask, bool showProgress )
-{
- if ( items.isEmpty() ) {
- KMessageBox::information( parent,
- i18n("You did not select a file to delete."),
- i18n("Nothing to Delete") );
- return 0L;
- }
-
- KURL::List urls;
- TQStringList files;
- KFileItemListIterator it( items );
-
- for ( ; it.current(); ++it ) {
- KURL url = (*it)->url();
- urls.append( url );
- if ( url.isLocalFile() )
- files.append( url.path() );
- else
- files.append( url.prettyURL() );
- }
-
- bool doIt = !ask;
- if ( ask ) {
- int ret;
- if ( items.count() == 1 ) {
- ret = KMessageBox::warningContinueCancel( parent,
- i18n( "<qt>Do you really want to delete\n <b>'%1'</b>?</qt>" )
- .arg( files.first() ),
- i18n("Delete File"),
- KStdGuiItem::del(), "AskForDelete" );
- }
- else
- ret = KMessageBox::warningContinueCancelList( parent,
- i18n("Do you really want to delete this item?", "Do you really want to delete these %n items?", items.count() ),
- files,
- i18n("Delete Files"),
- KStdGuiItem::del(), "AskForDelete" );
- doIt = (ret == KMessageBox::Continue);
- }
-
- if ( doIt ) {
- TDEIO::DeleteJob *job = TDEIO::del( urls, false, showProgress );
- job->setWindow (topLevelWidget());
- job->setAutoErrorHandlingEnabled( true, parent );
- return job;
- }
-
- return 0L;
-}
-
-void KDirOperator::deleteSelected()
-{
- if ( !m_fileView )
- return;
-
- const KFileItemList *list = m_fileView->selectedItems();
- if ( list )
- del( *list );
-}
-
-TDEIO::CopyJob * KDirOperator::trash( const KFileItemList& items,
- TQWidget *parent,
- bool ask, bool showProgress )
-{
- if ( items.isEmpty() ) {
- KMessageBox::information( parent,
- i18n("You did not select a file to trash."),
- i18n("Nothing to Trash") );
- return 0L;
- }
-
- KURL::List urls;
- TQStringList files;
- KFileItemListIterator it( items );
-
- for ( ; it.current(); ++it ) {
- KURL url = (*it)->url();
- urls.append( url );
- if ( url.isLocalFile() )
- files.append( url.path() );
- else
- files.append( url.prettyURL() );
- }
-
- bool doIt = !ask;
- if ( ask ) {
- int ret;
- if ( items.count() == 1 ) {
- ret = KMessageBox::warningContinueCancel( parent,
- i18n( "<qt>Do you really want to trash\n <b>'%1'</b>?</qt>" )
- .arg( files.first() ),
- i18n("Trash File"),
- KGuiItem(i18n("to trash", "&Trash"),"edittrash"), "AskForTrash" );
- }
- else
- ret = KMessageBox::warningContinueCancelList( parent,
- i18n("translators: not called for n == 1", "Do you really want to trash these %n items?", items.count() ),
- files,
- i18n("Trash Files"),
- KGuiItem(i18n("to trash", "&Trash"),"edittrash"), "AskForTrash" );
- doIt = (ret == KMessageBox::Continue);
- }
-
- if ( doIt ) {
- TDEIO::CopyJob *job = TDEIO::trash( urls, showProgress );
- job->setWindow (topLevelWidget());
- job->setAutoErrorHandlingEnabled( true, parent );
- return job;
- }
-
- return 0L;
-}
-
-void KDirOperator::trashSelected(KAction::ActivationReason reason, TQt::ButtonState state)
-{
- if ( !m_fileView )
- return;
-
- if ( reason == KAction::PopupMenuActivation && ( state & ShiftButton ) ) {
- deleteSelected();
- return;
- }
-
- const KFileItemList *list = m_fileView->selectedItems();
- if ( list )
- trash( *list, this );
-}
-
-void KDirOperator::close()
-{
- resetCursor();
- pendingMimeTypes.clear();
- myCompletion.clear();
- myDirCompletion.clear();
- myCompleteListDirty = true;
- dir->stop();
-}
-
-void KDirOperator::checkPath(const TQString &, bool /*takeFiles*/) // SLOT
-{
-#if 0
- // copy the argument in a temporary string
- TQString text = _txt;
- // it's unlikely to happen, that at the beginning are spaces, but
- // for the end, it happens quite often, I guess.
- text = text.stripWhiteSpace();
- // if the argument is no URL (the check is quite fragil) and it's
- // no absolute path, we add the current directory to get a correct url
- if (text.find(':') < 0 && text[0] != '/')
- text.insert(0, currUrl);
-
- // in case we have a selection defined and someone patched the file-
- // name, we check, if the end of the new name is changed.
- if (!selection.isNull()) {
- int position = text.findRev('/');
- ASSERT(position >= 0); // we already inserted the current dir in case
- TQString filename = text.mid(position + 1, text.length());
- if (filename != selection)
- selection = TQString::null;
- }
-
- KURL u(text); // I have to take care of entered URLs
- bool filenameEntered = false;
-
- if (u.isLocalFile()) {
- // the empty path is kind of a hack
- KFileItem i("", u.path());
- if (i.isDir())
- setURL(text, true);
- else {
- if (takeFiles)
- if (acceptOnlyExisting && !i.isFile())
- warning("you entered an invalid URL");
- else
- filenameEntered = true;
- }
- } else
- setURL(text, true);
-
- if (filenameEntered) {
- filename_ = u.url();
- emit fileSelected(filename_);
-
- TQApplication::restoreOverrideCursor();
-
- accept();
- }
-#endif
- kdDebug(kfile_area) << "TODO KDirOperator::checkPath()" << endl;
-}
-
-void KDirOperator::setURL(const KURL& _newurl, bool clearforward)
-{
- KURL newurl;
-
- if ( !_newurl.isValid() )
- newurl.setPath( TQDir::homeDirPath() );
- else
- newurl = _newurl;
-
- TQString pathstr = newurl.path(+1);
- newurl.setPath(pathstr);
-
- // already set
- if ( newurl.equals( currUrl, true ) )
- return;
-
- if ( !isReadable( newurl ) ) {
- // maybe newurl is a file? check its parent directory
- newurl.cd(TQString::fromLatin1(".."));
- if ( !isReadable( newurl ) ) {
- resetCursor();
- KMessageBox::error(viewWidget(),
- i18n("The specified folder does not exist "
- "or was not readable."));
- return;
- }
- }
-
- if (clearforward) {
- // autodelete should remove this one
- backStack.push(new KURL(currUrl));
- forwardStack.clear();
- }
-
- d->lastURL = currUrl.url(-1);
- currUrl = newurl;
-
- pathChanged();
- emit urlEntered(newurl);
-
- // enable/disable actions
- forwardAction->setEnabled( !forwardStack.isEmpty() );
- backAction->setEnabled( !backStack.isEmpty() );
- upAction->setEnabled( !isRoot() );
-
- openURL( newurl );
-}
-
-void KDirOperator::updateDir()
-{
- dir->emitChanges();
- if ( m_fileView )
- m_fileView->listingCompleted();
-}
-
-void KDirOperator::rereadDir()
-{
- pathChanged();
- openURL( currUrl, false, true );
-}
-
-
-bool KDirOperator::openURL( const KURL& url, bool keep, bool reload )
-{
- bool result = dir->openURL( url, keep, reload );
- if ( !result ) // in that case, neither completed() nor canceled() will be emitted by KDL
- slotCanceled();
-
- return result;
-}
-
-// Protected
-void KDirOperator::pathChanged()
-{
- if (!m_fileView)
- return;
-
- pendingMimeTypes.clear();
- m_fileView->clear();
- myCompletion.clear();
- myDirCompletion.clear();
-
- // it may be, that we weren't ready at this time
- TQApplication::restoreOverrideCursor();
-
- // when TDEIO::Job emits finished, the slot will restore the cursor
- TQApplication::setOverrideCursor( tqwaitCursor );
-
- if ( !isReadable( currUrl )) {
- KMessageBox::error(viewWidget(),
- i18n("The specified folder does not exist "
- "or was not readable."));
- if (backStack.isEmpty())
- home();
- else
- back();
- }
-}
-
-void KDirOperator::slotRedirected( const KURL& newURL )
-{
- currUrl = newURL;
- pendingMimeTypes.clear();
- myCompletion.clear();
- myDirCompletion.clear();
- myCompleteListDirty = true;
- emit urlEntered( newURL );
-}
-
-// Code pinched from kfm then hacked
-void KDirOperator::back()
-{
- if ( backStack.isEmpty() )
- return;
-
- forwardStack.push( new KURL(currUrl) );
-
- KURL *s = backStack.pop();
-
- setURL(*s, false);
- delete s;
-}
-
-// Code pinched from kfm then hacked
-void KDirOperator::forward()
-{
- if ( forwardStack.isEmpty() )
- return;
-
- backStack.push(new KURL(currUrl));
-
- KURL *s = forwardStack.pop();
- setURL(*s, false);
- delete s;
-}
-
-KURL KDirOperator::url() const
-{
- return currUrl;
-}
-
-void KDirOperator::cdUp()
-{
- KURL tmp(currUrl);
- tmp.cd(TQString::fromLatin1(".."));
- setURL(tmp, true);
-}
-
-void KDirOperator::home()
-{
- KURL u;
- u.setPath( TQDir::homeDirPath() );
- setURL(u, true);
-}
-
-void KDirOperator::clearFilter()
-{
- dir->setNameFilter( TQString::null );
- dir->clearMimeFilter();
- checkPreviewSupport();
-}
-
-void KDirOperator::setNameFilter(const TQString& filter)
-{
- dir->setNameFilter(filter);
- checkPreviewSupport();
-}
-
-void KDirOperator::setMimeFilter( const TQStringList& mimetypes )
-{
- dir->setMimeFilter( mimetypes );
- checkPreviewSupport();
-}
-
-bool KDirOperator::checkPreviewSupport()
-{
- KToggleAction *previewAction = static_cast<KToggleAction*>( myActionCollection->action( "preview" ));
-
- bool hasPreviewSupport = false;
- TDEConfig *kc = TDEGlobal::config();
- TDEConfigGroupSaver cs( kc, ConfigGroup );
- if ( kc->readBoolEntry( "Show Default Preview", true ) )
- hasPreviewSupport = checkPreviewInternal();
-
- previewAction->setEnabled( hasPreviewSupport );
- return hasPreviewSupport;
-}
-
-bool KDirOperator::checkPreviewInternal() const
-{
- TQStringList supported = TDEIO::PreviewJob::supportedMimeTypes();
- // no preview support for directories?
- if ( dirOnlyMode() && supported.findIndex( "inode/directory" ) == -1 )
- return false;
-
- TQStringList mimeTypes = dir->mimeFilters();
- TQStringList nameFilter = TQStringList::split( " ", dir->nameFilter() );
-
- if ( mimeTypes.isEmpty() && nameFilter.isEmpty() && !supported.isEmpty() )
- return true;
- else {
- TQRegExp r;
- r.setWildcard( true ); // the "mimetype" can be "image/*"
-
- if ( !mimeTypes.isEmpty() ) {
- TQStringList::Iterator it = supported.begin();
-
- for ( ; it != supported.end(); ++it ) {
- r.setPattern( *it );
-
- TQStringList result = mimeTypes.grep( r );
- if ( !result.isEmpty() ) { // matches! -> we want previews
- return true;
- }
- }
- }
-
- if ( !nameFilter.isEmpty() ) {
- // find the mimetypes of all the filter-patterns and
- KServiceTypeFactory *fac = KServiceTypeFactory::self();
- TQStringList::Iterator it1 = nameFilter.begin();
- for ( ; it1 != nameFilter.end(); ++it1 ) {
- if ( (*it1) == "*" ) {
- return true;
- }
-
- KMimeType *mt = fac->findFromPattern( *it1 );
- if ( !mt )
- continue;
- TQString mime = mt->name();
- delete mt;
-
- // the "mimetypes" we get from the PreviewJob can be "image/*"
- // so we need to check in wildcard mode
- TQStringList::Iterator it2 = supported.begin();
- for ( ; it2 != supported.end(); ++it2 ) {
- r.setPattern( *it2 );
- if ( r.search( mime ) != -1 ) {
- return true;
- }
- }
- }
- }
- }
-
- return false;
-}
-
-KFileView* KDirOperator::createView( TQWidget* parent, KFile::FileView view )
-{
- KFileView* new_view = 0L;
- bool separateDirs = KFile::isSeparateDirs( view );
- bool preview = ( KFile::isPreviewInfo(view) || KFile::isPreviewContents( view ) );
-
- if ( separateDirs || preview ) {
- KCombiView *combi = 0L;
- if (separateDirs)
- {
- combi = new KCombiView( parent, "combi view" );
- combi->setOnlyDoubleClickSelectsFiles(d->onlyDoubleClickSelectsFiles);
- }
-
- KFileView* v = 0L;
- if ( KFile::isSimpleView( view ) )
- v = createView( combi, KFile::Simple );
- else
- v = createView( combi, KFile::Detail );
-
- v->setOnlyDoubleClickSelectsFiles(d->onlyDoubleClickSelectsFiles);
-
- if (combi)
- combi->setRight( v );
-
- if (preview)
- {
- KFilePreview* pView = new KFilePreview( combi ? combi : v, parent, "preview" );
- pView->setOnlyDoubleClickSelectsFiles(d->onlyDoubleClickSelectsFiles);
- new_view = pView;
- }
- else
- new_view = combi;
- }
- else if ( KFile::isDetailView( view ) && !preview ) {
- new_view = new KFileDetailView( parent, "detail view");
- new_view->setViewName( i18n("Detailed View") );
- }
- else /* if ( KFile::isSimpleView( view ) && !preview ) */ {
- KFileIconView *iconView = new KFileIconView( parent, "simple view");
- new_view = iconView;
- new_view->setViewName( i18n("Short View") );
- }
-
- new_view->widget()->setAcceptDrops(acceptDrops());
- return new_view;
-}
-
-void KDirOperator::setAcceptDrops(bool b)
-{
- if (m_fileView)
- m_fileView->widget()->setAcceptDrops(b);
- TQWidget::setAcceptDrops(b);
-}
-
-void KDirOperator::setDropOptions(int options)
-{
- d->dropOptions = options;
- if (m_fileView)
- m_fileView->setDropOptions(options);
-}
-
-void KDirOperator::setView( KFile::FileView view )
-{
- bool separateDirs = KFile::isSeparateDirs( view );
- bool preview=( KFile::isPreviewInfo(view) || KFile::isPreviewContents( view ) );
-
- if (view == KFile::Default) {
- if ( KFile::isDetailView( (KFile::FileView) defaultView ) )
- view = KFile::Detail;
- else
- view = KFile::Simple;
-
- separateDirs = KFile::isSeparateDirs( static_cast<KFile::FileView>(defaultView) );
- preview = ( KFile::isPreviewInfo( static_cast<KFile::FileView>(defaultView) ) ||
- KFile::isPreviewContents( static_cast<KFile::FileView>(defaultView) ) )
- && myActionCollection->action("preview")->isEnabled();
-
- if ( preview ) { // instantiates KFileMetaPreview and calls setView()
- m_viewKind = defaultView;
- slotDefaultPreview();
- return;
- }
- else if ( !separateDirs )
- separateDirsAction->setChecked(true);
- }
-
- // if we don't have any files, we can't separate dirs from files :)
- if ( (mode() & KFile::File) == 0 &&
- (mode() & KFile::Files) == 0 ) {
- separateDirs = false;
- separateDirsAction->setEnabled( false );
- }
-
- m_viewKind = static_cast<int>(view) | (separateDirs ? KFile::SeparateDirs : 0);
- view = static_cast<KFile::FileView>(m_viewKind);
-
- KFileView *new_view = createView( this, view );
- if ( preview ) {
- // we keep the preview-_widget_ around, but not the KFilePreview.
- // KFilePreview::setPreviewWidget handles the reparenting for us
- static_cast<KFilePreview*>(new_view)->setPreviewWidget(myPreview, url());
- }
-
- setView( new_view );
-}
-
-
-void KDirOperator::connectView(KFileView *view)
-{
- // TODO: do a real timer and restart it after that
- pendingMimeTypes.clear();
- bool listDir = true;
-
- if ( dirOnlyMode() )
- view->setViewMode(KFileView::Directories);
- else
- view->setViewMode(KFileView::All);
-
- if ( myMode & KFile::Files )
- view->setSelectionMode( KFile::Extended );
- else
- view->setSelectionMode( KFile::Single );
-
- if (m_fileView)
- {
- if ( d->config ) // save and restore the views' configuration
- {
- m_fileView->writeConfig( d->config, d->configGroup );
- view->readConfig( d->config, d->configGroup );
- }
-
- // transfer the state from old view to new view
- view->clear();
- view->addItemList( *m_fileView->items() );
- listDir = false;
-
- if ( m_fileView->widget()->hasFocus() )
- view->widget()->setFocus();
-
- KFileItem *oldCurrentItem = m_fileView->currentFileItem();
- if ( oldCurrentItem ) {
- view->setCurrentItem( oldCurrentItem );
- view->setSelected( oldCurrentItem, false );
- view->ensureItemVisible( oldCurrentItem );
- }
-
- const KFileItemList *oldSelected = m_fileView->selectedItems();
- if ( !oldSelected->isEmpty() ) {
- KFileItemListIterator it( *oldSelected );
- for ( ; it.current(); ++it )
- view->setSelected( it.current(), true );
- }
-
- m_fileView->widget()->hide();
- delete m_fileView;
- }
-
- else
- {
- if ( d->config )
- view->readConfig( d->config, d->configGroup );
- }
-
- m_fileView = view;
- m_fileView->setDropOptions(d->dropOptions);
- viewActionCollection = 0L;
- KFileViewSignaler *sig = view->signaler();
-
- connect(sig, TQT_SIGNAL( activatedMenu(const KFileItem *, const TQPoint& ) ),
- this, TQT_SLOT( activatedMenu(const KFileItem *, const TQPoint& )));
- connect(sig, TQT_SIGNAL( dirActivated(const KFileItem *) ),
- this, TQT_SLOT( selectDir(const KFileItem*) ) );
- connect(sig, TQT_SIGNAL( fileSelected(const KFileItem *) ),
- this, TQT_SLOT( selectFile(const KFileItem*) ) );
- connect(sig, TQT_SIGNAL( fileHighlighted(const KFileItem *) ),
- this, TQT_SLOT( highlightFile(const KFileItem*) ));
- connect(sig, TQT_SIGNAL( sortingChanged( TQDir::SortSpec ) ),
- this, TQT_SLOT( slotViewSortingChanged( TQDir::SortSpec )));
- connect(sig, TQT_SIGNAL( dropped(const KFileItem *, TQDropEvent*, const KURL::List&) ),
- this, TQT_SIGNAL( dropped(const KFileItem *, TQDropEvent*, const KURL::List&)) );
-
- if ( reverseAction->isChecked() != m_fileView->isReversed() )
- slotSortReversed();
-
- updateViewActions();
- m_fileView->widget()->resize(size());
- m_fileView->widget()->show();
-
- if ( listDir ) {
- TQApplication::setOverrideCursor( tqwaitCursor );
- openURL( currUrl );
- }
- else
- view->listingCompleted();
-}
-
-KFile::Mode KDirOperator::mode() const
-{
- return myMode;
-}
-
-void KDirOperator::setMode(KFile::Mode m)
-{
- if (myMode == m)
- return;
-
- myMode = m;
-
- dir->setDirOnlyMode( dirOnlyMode() );
-
- // reset the view with the different mode
- setView( static_cast<KFile::FileView>(m_viewKind) );
-}
-
-void KDirOperator::setView(KFileView *view)
-{
- if ( view == m_fileView ) {
- return;
- }
-
- setFocusProxy(view->widget());
- view->setSorting( mySorting );
- view->setOnlyDoubleClickSelectsFiles( d->onlyDoubleClickSelectsFiles );
- connectView(view); // also deletes the old view
-
- emit viewChanged( view );
-}
-
-void KDirOperator::setDirLister( KDirLister *lister )
-{
- if ( lister == dir ) // sanity check
- return;
-
- delete dir;
- dir = lister;
-
- dir->setAutoUpdate( true );
-
- TQWidget* mainWidget = topLevelWidget();
- dir->setMainWindow (mainWidget);
- kdDebug (kfile_area) << "mainWidget=" << mainWidget << endl;
-
- connect( dir, TQT_SIGNAL( percent( int )),
- TQT_SLOT( slotProgress( int ) ));
- connect( dir, TQT_SIGNAL(started( const KURL& )), TQT_SLOT(slotStarted()));
- connect( dir, TQT_SIGNAL(newItems(const KFileItemList &)),
- TQT_SLOT(insertNewFiles(const KFileItemList &)));
- connect( dir, TQT_SIGNAL(completed()), TQT_SLOT(slotIOFinished()));
- connect( dir, TQT_SIGNAL(canceled()), TQT_SLOT(slotCanceled()));
- connect( dir, TQT_SIGNAL(deleteItem(KFileItem *)),
- TQT_SLOT(itemDeleted(KFileItem *)));
- connect( dir, TQT_SIGNAL(redirection( const KURL& )),
- TQT_SLOT( slotRedirected( const KURL& )));
- connect( dir, TQT_SIGNAL( clear() ), TQT_SLOT( slotClearView() ));
- connect( dir, TQT_SIGNAL( refreshItems( const KFileItemList& ) ),
- TQT_SLOT( slotRefreshItems( const KFileItemList& ) ) );
-}
-
-void KDirOperator::insertNewFiles(const KFileItemList &newone)
-{
- if ( newone.isEmpty() || !m_fileView )
- return;
-
- myCompleteListDirty = true;
- m_fileView->addItemList( newone );
- emit updateInformation(m_fileView->numDirs(), m_fileView->numFiles());
-
- KFileItem *item;
- KFileItemListIterator it( newone );
-
- while ( (item = it.current()) ) {
- // highlight the dir we come from, if possible
- if ( d->dirHighlighting && item->isDir() &&
- item->url().url(-1) == d->lastURL ) {
- m_fileView->setCurrentItem( item );
- m_fileView->ensureItemVisible( item );
- }
-
- ++it;
- }
-
- TQTimer::singleShot(200, this, TQT_SLOT(resetCursor()));
-}
-
-void KDirOperator::selectDir(const KFileItem *item)
-{
- setURL(item->url(), true);
-}
-
-void KDirOperator::itemDeleted(KFileItem *item)
-{
- pendingMimeTypes.removeRef( item );
- if ( m_fileView )
- {
- m_fileView->removeItem( static_cast<KFileItem *>( item ));
- emit updateInformation(m_fileView->numDirs(), m_fileView->numFiles());
- }
-}
-
-void KDirOperator::selectFile(const KFileItem *item)
-{
- TQApplication::restoreOverrideCursor();
-
- emit fileSelected( item );
-}
-
-void KDirOperator::setCurrentItem( const TQString& filename )
-{
- if ( m_fileView ) {
- const KFileItem *item = 0L;
-
- if ( !filename.isNull() )
- item = static_cast<KFileItem *>(dir->findByName( filename ));
-
- m_fileView->clearSelection();
- if ( item ) {
- m_fileView->setCurrentItem( item );
- m_fileView->setSelected( item, true );
- m_fileView->ensureItemVisible( item );
- }
- }
-}
-
-TQString KDirOperator::makeCompletion(const TQString& string)
-{
- if ( string.isEmpty() ) {
- m_fileView->clearSelection();
- return TQString::null;
- }
-
- prepareCompletionObjects();
- return myCompletion.makeCompletion( string );
-}
-
-TQString KDirOperator::makeDirCompletion(const TQString& string)
-{
- if ( string.isEmpty() ) {
- m_fileView->clearSelection();
- return TQString::null;
- }
-
- prepareCompletionObjects();
- return myDirCompletion.makeCompletion( string );
-}
-
-void KDirOperator::prepareCompletionObjects()
-{
- if ( !m_fileView )
- return;
-
- if ( myCompleteListDirty ) { // create the list of all possible completions
- KFileItemListIterator it( *(m_fileView->items()) );
- for( ; it.current(); ++it ) {
- KFileItem *item = it.current();
-
- myCompletion.addItem( item->name() );
- if ( item->isDir() )
- myDirCompletion.addItem( item->name() );
- }
- myCompleteListDirty = false;
- }
-}
-
-void KDirOperator::slotCompletionMatch(const TQString& match)
-{
- setCurrentItem( match );
- emit completion( match );
-}
-
-void KDirOperator::setupActions()
-{
- myActionCollection = new KActionCollection( topLevelWidget(), TQT_TQOBJECT(this), "KDirOperator::myActionCollection" );
-
- actionMenu = new KActionMenu( i18n("Menu"), myActionCollection, "popupMenu" );
- upAction = KStdAction::up( TQT_TQOBJECT(this), TQT_SLOT( cdUp() ), myActionCollection, "up" );
- upAction->setText( i18n("Parent Folder") );
- backAction = KStdAction::back( TQT_TQOBJECT(this), TQT_SLOT( back() ), myActionCollection, "back" );
- forwardAction = KStdAction::forward( TQT_TQOBJECT(this), TQT_SLOT(forward()), myActionCollection, "forward" );
- homeAction = KStdAction::home( TQT_TQOBJECT(this), TQT_SLOT( home() ), myActionCollection, "home" );
- homeAction->setText(i18n("Home Folder"));
- reloadAction = KStdAction::redisplay( TQT_TQOBJECT(this), TQT_SLOT(rereadDir()), myActionCollection, "reload" );
- actionSeparator = new KActionSeparator( myActionCollection, "separator" );
- d->viewActionSeparator = new KActionSeparator( myActionCollection,
- "viewActionSeparator" );
- mkdirAction = new KAction( i18n("New Folder..."), 0,
- TQT_TQOBJECT(this), TQT_SLOT( mkdir() ), myActionCollection, "mkdir" );
- KAction* trash = new KAction( i18n( "Move to Trash" ), "edittrash", Key_Delete, myActionCollection, "trash" );
- connect( trash, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState ) ),
- this, TQT_SLOT( trashSelected( KAction::ActivationReason, TQt::ButtonState ) ) );
- new KAction( i18n( "Delete" ), "editdelete", SHIFT+Key_Delete, TQT_TQOBJECT(this),
- TQT_SLOT( deleteSelected() ), myActionCollection, "delete" );
- mkdirAction->setIcon( TQString::fromLatin1("folder_new") );
- reloadAction->setText( i18n("Reload") );
- reloadAction->setShortcut( KStdAccel::shortcut( KStdAccel::Reload ));
-
-
- // the sort menu actions
- sortActionMenu = new KActionMenu( i18n("Sorting"), myActionCollection, "sorting menu");
- byNameAction = new KRadioAction( i18n("By Name"), 0,
- TQT_TQOBJECT(this), TQT_SLOT( slotSortByName() ),
- myActionCollection, "by name" );
- byDateAction = new KRadioAction( i18n("By Date"), 0,
- TQT_TQOBJECT(this), TQT_SLOT( slotSortByDate() ),
- myActionCollection, "by date" );
- bySizeAction = new KRadioAction( i18n("By Size"), 0,
- TQT_TQOBJECT(this), TQT_SLOT( slotSortBySize() ),
- myActionCollection, "by size" );
- reverseAction = new KToggleAction( i18n("Reverse"), 0,
- TQT_TQOBJECT(this), TQT_SLOT( slotSortReversed() ),
- myActionCollection, "reversed" );
-
- TQString sortGroup = TQString::fromLatin1("sort");
- byNameAction->setExclusiveGroup( sortGroup );
- byDateAction->setExclusiveGroup( sortGroup );
- bySizeAction->setExclusiveGroup( sortGroup );
-
-
- dirsFirstAction = new KToggleAction( i18n("Folders First"), 0,
- myActionCollection, "dirs first");
- caseInsensitiveAction = new KToggleAction(i18n("Case Insensitive"), 0,
- myActionCollection, "case insensitive" );
-
- connect( dirsFirstAction, TQT_SIGNAL( toggled( bool ) ),
- TQT_SLOT( slotToggleDirsFirst() ));
- connect( caseInsensitiveAction, TQT_SIGNAL( toggled( bool ) ),
- TQT_SLOT( slotToggleIgnoreCase() ));
-
-
-
- // the view menu actions
- viewActionMenu = new KActionMenu( i18n("&View"), myActionCollection, "view menu" );
- connect( viewActionMenu->popupMenu(), TQT_SIGNAL( aboutToShow() ),
- TQT_SLOT( insertViewDependentActions() ));
-
- shortAction = new KRadioAction( i18n("Short View"), "view_multicolumn",
- KShortcut(), myActionCollection, "short view" );
- detailedAction = new KRadioAction( i18n("Detailed View"), "view_detailed",
- KShortcut(), myActionCollection, "detailed view" );
-
- showHiddenAction = new KToggleAction( i18n("Show Hidden Files"), KShortcut(),
- myActionCollection, "show hidden" );
-// showHiddenAction->setCheckedState( i18n("Hide Hidden Files") );
- separateDirsAction = new KToggleAction( i18n("Separate Folders"), KShortcut(),
- TQT_TQOBJECT(this),
- TQT_SLOT(slotSeparateDirs()),
- myActionCollection, "separate dirs" );
- KToggleAction *previewAction = new KToggleAction(i18n("Show Preview"),
- "thumbnail", KShortcut(),
- myActionCollection,
- "preview" );
- previewAction->setCheckedState(i18n("Hide Preview"));
- connect( previewAction, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( togglePreview( bool )));
-
-
- TQString viewGroup = TQString::fromLatin1("view");
- shortAction->setExclusiveGroup( viewGroup );
- detailedAction->setExclusiveGroup( viewGroup );
-
- connect( shortAction, TQT_SIGNAL( activated() ),
- TQT_SLOT( slotSimpleView() ));
- connect( detailedAction, TQT_SIGNAL( activated() ),
- TQT_SLOT( slotDetailedView() ));
- connect( showHiddenAction, TQT_SIGNAL( toggled( bool ) ),
- TQT_SLOT( slotToggleHidden( bool ) ));
-
- new KAction( i18n("Properties"), KShortcut(ALT+Key_Return), TQT_TQOBJECT(this),
- TQT_SLOT(slotProperties()), myActionCollection, "properties" );
-}
-
-void KDirOperator::setupMenu()
-{
- setupMenu(AllActions);
-}
-
-void KDirOperator::setupMenu(int whichActions)
-{
- // first fill the submenus (sort and view)
- sortActionMenu->popupMenu()->clear();
- sortActionMenu->insert( byNameAction );
- sortActionMenu->insert( byDateAction );
- sortActionMenu->insert( bySizeAction );
- sortActionMenu->insert( actionSeparator );
- sortActionMenu->insert( reverseAction );
- sortActionMenu->insert( dirsFirstAction );
- sortActionMenu->insert( caseInsensitiveAction );
-
- // now plug everything into the popupmenu
- actionMenu->popupMenu()->clear();
- if (whichActions & NavActions)
- {
- actionMenu->insert( upAction );
- actionMenu->insert( backAction );
- actionMenu->insert( forwardAction );
- actionMenu->insert( homeAction );
- actionMenu->insert( actionSeparator );
- }
-
- if (whichActions & FileActions)
- {
- actionMenu->insert( mkdirAction );
- if (currUrl.isLocalFile() && !(TDEApplication::keyboardMouseState() & TQt::ShiftButton))
- actionMenu->insert( myActionCollection->action( "trash" ) );
- TDEConfig *globalconfig = TDEGlobal::config();
- TDEConfigGroupSaver cs( globalconfig, TQString::fromLatin1("KDE") );
- if (!currUrl.isLocalFile() || (TDEApplication::keyboardMouseState() & TQt::ShiftButton) ||
- globalconfig->readBoolEntry("ShowDeleteCommand", false))
- actionMenu->insert( myActionCollection->action( "delete" ) );
- actionMenu->insert( actionSeparator );
- }
-
- if (whichActions & SortActions)
- {
- actionMenu->insert( sortActionMenu );
- actionMenu->insert( actionSeparator );
- }
-
- if (whichActions & ViewActions)
- {
- actionMenu->insert( viewActionMenu );
- actionMenu->insert( actionSeparator );
- }
-
- if (whichActions & FileActions)
- {
- actionMenu->insert( myActionCollection->action( "properties" ) );
- }
-}
-
-void KDirOperator::updateSortActions()
-{
- if ( KFile::isSortByName( mySorting ) )
- byNameAction->setChecked( true );
- else if ( KFile::isSortByDate( mySorting ) )
- byDateAction->setChecked( true );
- else if ( KFile::isSortBySize( mySorting ) )
- bySizeAction->setChecked( true );
-
- dirsFirstAction->setChecked( KFile::isSortDirsFirst( mySorting ) );
- caseInsensitiveAction->setChecked( KFile::isSortCaseInsensitive(mySorting) );
- caseInsensitiveAction->setEnabled( KFile::isSortByName( mySorting ) );
-
- if ( m_fileView )
- reverseAction->setChecked( m_fileView->isReversed() );
-}
-
-void KDirOperator::updateViewActions()
-{
- KFile::FileView fv = static_cast<KFile::FileView>( m_viewKind );
-
- separateDirsAction->setChecked( KFile::isSeparateDirs( fv ) &&
- separateDirsAction->isEnabled() );
-
- shortAction->setChecked( KFile::isSimpleView( fv ));
- detailedAction->setChecked( KFile::isDetailView( fv ));
-}
-
-void KDirOperator::readConfig( TDEConfig *kc, const TQString& group )
-{
- if ( !kc )
- return;
- TQString oldGroup = kc->group();
- if ( !group.isEmpty() )
- kc->setGroup( group );
-
- defaultView = 0;
- int sorting = 0;
-
- TQString viewStyle = kc->readEntry( TQString::fromLatin1("View Style"),
- TQString::fromLatin1("Simple") );
- if ( viewStyle == TQString::fromLatin1("Detail") )
- defaultView |= KFile::Detail;
- else
- defaultView |= KFile::Simple;
- if ( kc->readBoolEntry( TQString::fromLatin1("Separate Directories"),
- DefaultMixDirsAndFiles ) )
- defaultView |= KFile::SeparateDirs;
- if ( kc->readBoolEntry(TQString::fromLatin1("Show Preview"), false))
- defaultView |= KFile::PreviewContents;
-
- if ( kc->readBoolEntry( TQString::fromLatin1("Sort case insensitively"),
- DefaultCaseInsensitive ) )
- sorting |= TQDir::IgnoreCase;
- if ( kc->readBoolEntry( TQString::fromLatin1("Sort directories first"),
- DefaultDirsFirst ) )
- sorting |= TQDir::DirsFirst;
-
-
- TQString name = TQString::fromLatin1("Name");
- TQString sortBy = kc->readEntry( TQString::fromLatin1("Sort by"), name );
- if ( sortBy == name )
- sorting |= TQDir::Name;
- else if ( sortBy == TQString::fromLatin1("Size") )
- sorting |= TQDir::Size;
- else if ( sortBy == TQString::fromLatin1("Date") )
- sorting |= TQDir::Time;
-
- mySorting = static_cast<TQDir::SortSpec>( sorting );
- setSorting( mySorting );
-
-
- if ( kc->readBoolEntry( TQString::fromLatin1("Show hidden files"),
- DefaultShowHidden ) ) {
- showHiddenAction->setChecked( true );
- dir->setShowingDotFiles( true );
- }
- if ( kc->readBoolEntry( TQString::fromLatin1("Sort reversed"),
- DefaultSortReversed ) )
- reverseAction->setChecked( true );
-
- kc->setGroup( oldGroup );
-}
-
-void KDirOperator::writeConfig( TDEConfig *kc, const TQString& group )
-{
- if ( !kc )
- return;
-
- const TQString oldGroup = kc->group();
-
- if ( !group.isEmpty() )
- kc->setGroup( group );
-
- TQString sortBy = TQString::fromLatin1("Name");
- if ( KFile::isSortBySize( mySorting ) )
- sortBy = TQString::fromLatin1("Size");
- else if ( KFile::isSortByDate( mySorting ) )
- sortBy = TQString::fromLatin1("Date");
- kc->writeEntry( TQString::fromLatin1("Sort by"), sortBy );
-
- kc->writeEntry( TQString::fromLatin1("Sort reversed"),
- reverseAction->isChecked() );
- kc->writeEntry( TQString::fromLatin1("Sort case insensitively"),
- caseInsensitiveAction->isChecked() );
- kc->writeEntry( TQString::fromLatin1("Sort directories first"),
- dirsFirstAction->isChecked() );
-
- // don't save the separate dirs or preview when an application specific
- // preview is in use.
- bool appSpecificPreview = false;
- if ( myPreview ) {
- TQWidget *preview = const_cast<TQWidget*>( myPreview ); // grmbl
- KFileMetaPreview *tmp = dynamic_cast<KFileMetaPreview*>( preview );
- appSpecificPreview = (tmp == 0L);
- }
-
- if ( !appSpecificPreview ) {
- if ( separateDirsAction->isEnabled() )
- kc->writeEntry( TQString::fromLatin1("Separate Directories"),
- separateDirsAction->isChecked() );
-
- KToggleAction *previewAction = static_cast<KToggleAction*>(myActionCollection->action("preview"));
- if ( previewAction->isEnabled() ) {
- bool hasPreview = previewAction->isChecked();
- kc->writeEntry( TQString::fromLatin1("Show Preview"), hasPreview );
- }
- }
-
- kc->writeEntry( TQString::fromLatin1("Show hidden files"),
- showHiddenAction->isChecked() );
-
- KFile::FileView fv = static_cast<KFile::FileView>( m_viewKind );
- TQString style;
- if ( KFile::isDetailView( fv ) )
- style = TQString::fromLatin1("Detail");
- else if ( KFile::isSimpleView( fv ) )
- style = TQString::fromLatin1("Simple");
- kc->writeEntry( TQString::fromLatin1("View Style"), style );
-
- kc->setGroup( oldGroup );
-}
-
-
-void KDirOperator::resizeEvent( TQResizeEvent * )
-{
- if (m_fileView)
- m_fileView->widget()->resize( size() );
-
- if ( TQT_BASE_OBJECT(progress->parent()) == TQT_BASE_OBJECT(this) ) // might be reparented into a statusbar
- progress->move(2, height() - progress->height() -2);
-}
-
-void KDirOperator::setOnlyDoubleClickSelectsFiles( bool enable )
-{
- d->onlyDoubleClickSelectsFiles = enable;
- if ( m_fileView )
- m_fileView->setOnlyDoubleClickSelectsFiles( enable );
-}
-
-bool KDirOperator::onlyDoubleClickSelectsFiles() const
-{
- return d->onlyDoubleClickSelectsFiles;
-}
-
-void KDirOperator::slotStarted()
-{
- progress->setProgress( 0 );
- // delay showing the progressbar for one second
- d->progressDelayTimer->start( 1000, true );
-}
-
-void KDirOperator::slotShowProgress()
-{
- progress->raise();
- progress->show();
- TQApplication::flushX();
-}
-
-void KDirOperator::slotProgress( int percent )
-{
- progress->setProgress( percent );
- // we have to redraw this as fast as possible
- if ( progress->isVisible() )
- TQApplication::flushX();
-}
-
-
-void KDirOperator::slotIOFinished()
-{
- d->progressDelayTimer->stop();
- slotProgress( 100 );
- progress->hide();
- emit finishedLoading();
- resetCursor();
-
- if ( m_fileView )
- m_fileView->listingCompleted();
-}
-
-void KDirOperator::slotCanceled()
-{
- emit finishedLoading();
- resetCursor();
-
- if ( m_fileView )
- m_fileView->listingCompleted();
-}
-
-KProgress * KDirOperator::progressBar() const
-{
- return progress;
-}
-
-void KDirOperator::clearHistory()
-{
- backStack.clear();
- backAction->setEnabled( false );
- forwardStack.clear();
- forwardAction->setEnabled( false );
-}
-
-void KDirOperator::slotViewActionAdded( KAction *action )
-{
- if ( viewActionMenu->popupMenu()->count() == 5 ) // need to add a separator
- viewActionMenu->insert( d->viewActionSeparator );
-
- viewActionMenu->insert( action );
-}
-
-void KDirOperator::slotViewActionRemoved( KAction *action )
-{
- viewActionMenu->remove( action );
-
- if ( viewActionMenu->popupMenu()->count() == 6 ) // remove the separator
- viewActionMenu->remove( d->viewActionSeparator );
-}
-
-void KDirOperator::slotViewSortingChanged( TQDir::SortSpec sort )
-{
- mySorting = sort;
- updateSortActions();
-}
-
-void KDirOperator::setEnableDirHighlighting( bool enable )
-{
- d->dirHighlighting = enable;
-}
-
-bool KDirOperator::dirHighlighting() const
-{
- return d->dirHighlighting;
-}
-
-void KDirOperator::slotProperties()
-{
- if ( m_fileView ) {
- const KFileItemList *list = m_fileView->selectedItems();
- if ( !list->isEmpty() )
- (void) new KPropertiesDialog( *list, this, "props dlg", true);
- }
-}
-
-void KDirOperator::slotClearView()
-{
- if ( m_fileView )
- m_fileView->clearView();
-}
-
-// ### temporary code
-#include <dirent.h>
-bool KDirOperator::isReadable( const KURL& url )
-{
- if ( !url.isLocalFile() )
- return true; // what else can we say?
-
- KDE_struct_stat buf;
- TQString ts = url.path(+1);
- bool readable = ( KDE_stat( TQFile::encodeName( ts ), &buf) == 0 );
- if (readable) { // further checks
- DIR *test;
- test = opendir( TQFile::encodeName( ts )); // we do it just to test here
- readable = (test != 0);
- if (test)
- closedir(test);
- }
- return readable;
-}
-
-void KDirOperator::togglePreview( bool on )
-{
- if ( on )
- slotDefaultPreview();
- else
- setView( (KFile::FileView) (m_viewKind & ~(KFile::PreviewContents|KFile::PreviewInfo)) );
-}
-
-void KDirOperator::slotRefreshItems( const KFileItemList& items )
-{
- if ( !m_fileView )
- return;
-
- KFileItemListIterator it( items );
- for ( ; it.current(); ++it )
- m_fileView->updateView( it.current() );
-}
-
-void KDirOperator::setViewConfig( TDEConfig *config, const TQString& group )
-{
- d->config = config;
- d->configGroup = group;
-}
-
-TDEConfig * KDirOperator::viewConfig()
-{
- return d->config;
-}
-
-TQString KDirOperator::viewConfigGroup() const
-{
- return d->configGroup;
-}
-
-void KDirOperator::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-#include "kdiroperator.moc"
diff --git a/kio/kfile/kdiroperator.h b/kio/kfile/kdiroperator.h
deleted file mode 100644
index 3dbd42759..000000000
--- a/kio/kfile/kdiroperator.h
+++ /dev/null
@@ -1,950 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1999 Stephan Kulow <coolo@kde.org>
- 2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef KDIROPERATOR_H_
-#define KDIROPERATOR_H_
-
-#include <tqwidget.h>
-#include <tqptrstack.h>
-
-#include <kaction.h>
-#include <kcompletion.h>
-#include <kdirlister.h>
-#include <kfileview.h>
-#include <kfileitem.h>
-#include <kfile.h>
-
-class TQPopupMenu;
-class TQTimer;
-
-class KAction;
-class KDirLister;
-class KToggleAction;
-class KActionSeparator;
-class KActionMenu;
-class TQWidgetStack;
-class KProgress;
-namespace TDEIO {
- class CopyJob;
- class DeleteJob;
-}
-
-/**
- * This widget works as a network transparent filebrowser. You specify a URL
- * to display and this url will be loaded via KDirLister. The user can
- * browse through directories, highlight and select files, delete or rename
- * files.
- *
- * It supports different views, e.g. a detailed view (see KFileDetailView),
- * a simple icon view (see KFileIconView), a combination of two views,
- * separating directories and files ( KCombiView).
- *
- * Additionally, a preview view is available (see KFilePreview), which can
- * show either a simple or detailed view and additionally a preview widget
- * (see setPreviewWidget()). KImageFilePreview is one implementation
- * of a preview widget, that displays previews for all supported filetypes
- * utilizing TDEIO::PreviewJob.
- *
- * Currently, those classes don't support Drag&Drop out of the box -- there
- * you have to use your own view-classes. You can use some DnD-aware views
- * from Bj�n Sahlstr� <bjorn@kbear.org> until they will be integrated
- * into this library. See http://devel-home.kde.org/~pfeiffer/DnD-classes.tar.gz
- *
- * This widget is the one used in the KFileDialog.
- *
- * Basic usage is like this:
- * \code
- * KDirOperator *op = new KDirOperator( KURL( "file:/home/gis" ), this );
- * // some signals you might be interested in
- * connect(op, TQT_SIGNAL(urlEntered(const KURL&)),
- * TQT_SLOT(urlEntered(const KURL&)));
- * connect(op, TQT_SIGNAL(fileHighlighted(const KFileItem *)),
- * TQT_SLOT(fileHighlighted(const KFileItem *)));
- * connect(op, TQT_SIGNAL(fileSelected(const KFileItem *)),
- * TQT_SLOT(fileSelected(const KFileItem *)));
- * connect(op, TQT_SIGNAL(finishedLoading()),
- * TQT_SLOT(slotLoadingFinished()));
- *
- * op->readConfig( TDEGlobal::config(), "Your KDiroperator ConfigGroup" );
- * op->setView(KFile::Default);
- * \endcode
- *
- * This will create a childwidget of 'this' showing the directory contents
- * of /home/gis in the default-view. The view is determined by the readConfig()
- * call, which will read the KDirOperator settings, the user left your program
- * with (and which you saved with op->writeConfig()).
- *
- * @short A widget for displaying files and browsing directories.
- * @author Stephan Kulow <coolo@kde.org>, Carsten Pfeiffer <pfeiffer@kde.org>
- */
-class TDEIO_EXPORT KDirOperator : public TQWidget
-{
- Q_OBJECT
-
- public:
- /**
- * The various action types. These values can be or'd together
- * @since 3.1
- */
- enum ActionTypes { SortActions = 1,
- ViewActions = 2,
- NavActions = 4,
- FileActions = 8,
- AllActions = 15 };
- /**
- * Constructs the KDirOperator with no initial view. As the views are
- * configurable, call readConfig() to load the user's configuration
- * and then setView to explicitly set a view.
- *
- * This constructor doesn't start loading the url, setView will do it.
- */
- KDirOperator(const KURL& urlName = KURL(),
- TQWidget *parent = 0, const char* name = 0);
- /**
- * Destroys the KDirOperator.
- */
- virtual ~KDirOperator();
-
- /**
- * Enables/disables showing hidden files.
- */
- // ### KDE4: make virtual
- void setShowHiddenFiles ( bool s ) { showHiddenAction->setChecked( s ); }
-
- /**
- * @returns true when hidden files are shown or false otherwise.
- */
- bool showHiddenFiles () const { return showHiddenAction->isChecked(); }
-
- /**
- * Stops loading immediately. You don't need to call this, usually.
- */
- void close();
- /// Reimplemented to avoid "hidden virtual" warnings
- virtual bool close( bool alsoDelete ) { return TQWidget::close( alsoDelete ); }
-
- /**
- * Sets a filter like "*.cpp *.h *.o". Only files matching that filter
- * will be shown. Call updateDir() to apply it.
- *
- * @see KDirLister::setNameFilter
- * @see nameFilter
- */
- void setNameFilter(const TQString& filter);
-
- /**
- * @returns the current namefilter.
- * @see setNameFilter
- */
- const TQString& nameFilter() const { return dir->nameFilter(); }
-
- /**
- * Sets a list of mimetypes as filter. Only files of those mimetypes
- * will be shown.
- *
- * Example:
- * \code
- * TQStringList filter;
- * filter << "text/html" << "image/png" << "inode/directory";
- * dirOperator->setMimefilter( filter );
- * \endcode
- *
- * Node: Without the mimetype inode/directory, only files would be shown.
- * Call updateDir() to apply it.
- *
- * @see KDirLister::setMimeFilter
- * @see mimeFilter
- */
- void setMimeFilter( const TQStringList& mimetypes );
-
- /**
- * @returns the current mime filter.
- */
- TQStringList mimeFilter() const { return dir->mimeFilters(); }
-
- /**
- * Clears both the namefilter and mimetype filter, so that all files and
- * directories will be shown. Call updateDir() to apply it.
- *
- * @see setMimeFilter
- * @see setNameFilter
- */
- void clearFilter();
-
- /**
- * @returns the current url
- */
- KURL url() const;
-
- /**
- * Sets a new url to list.
- * @param clearforward specifies whether the "forward" history should be cleared.
- * @param url the URL to set
- */
- // ### KDE4: make virtual
- void setURL(const KURL& url, bool clearforward);
-
- /**
- * Clears the current selection and attempts to set @p filename
- * the current file. filename is just the name, no path or url.
- */
- void setCurrentItem( const TQString& filename );
-
- /**
- * Sets a new KFileView to be used for showing and browsing files.
- * Note: this will read the current url() to fill the view.
- *
- * @see KFileView
- * @see KFileIconView
- * @see KFileDetailView
- * @see KCombiView
- * @see view
- */
- // ### KDE4: make virtual
- void setView(KFileView *view);
-
- /**
- * @returns the currently used view.
- * @see setView
- */
- KFileView * view() const { return m_fileView; }
-
- /**
- * Returns the widget of the current view. 0L if there is no view/widget.
- * (KFileView itself is not a widget.)
- */
- TQWidget * viewWidget() const { return m_fileView ? m_fileView->widget() : 0L; }
-
- /**
- * Sets one of the predefined fileviews
- * @see KFile::FileView
- */
- // ### KDE4: make virtual
- void setView(KFile::FileView view);
-
- /**
- * Sets the way to sort files and directories.
- */
- void setSorting( TQDir::SortSpec );
-
- /**
- * @returns the current way of sorting files and directories
- */
- TQDir::SortSpec sorting() const { return mySorting; }
-
- /**
- * @returns true if we are displaying the root directory of the current url
- */
- bool isRoot() const { return url().path() == TQChar('/'); }
-
- /**
- * @returns the object listing the directory
- */
- KDirLister *dirLister() const { return dir; }
-
- /**
- * @returns the progress widget, that is shown during directory listing.
- * You can for example reparent() it to put it into a statusbar.
- */
- KProgress * progressBar() const;
-
- /**
- * Sets the listing/selection mode for the views, an OR'ed combination of
- * @li File
- * @li Directory
- * @li Files
- * @li ExistingOnly
- * @li LocalOnly
- *
- * You cannot mix File and Files of course, as the former means
- * single-selection mode, the latter multi-selection.
- */
- // ### KDE4: make virtual
- void setMode( KFile::Mode m );
- /**
- * @returns the listing/selection mode.
- */
- KFile::Mode mode() const;
-
- /**
- * Sets a preview-widget to be shown next to the file-view.
- * The ownership of @p w is transferred to KDirOperator, so don't
- * delete it yourself!
- */
- // ### KDE4: make virtual
- void setPreviewWidget(const TQWidget *w);
-
- /**
- * @returns a list of all currently selected items. If there is no view,
- * then 0L is returned.
- */
- const KFileItemList * selectedItems() const {
- return ( m_fileView ? m_fileView->selectedItems() : 0L );
- }
-
- /**
- * @returns true if @p item is currently selected, or false otherwise.
- */
- inline bool isSelected( const KFileItem *item ) const {
- return ( m_fileView ? m_fileView->isSelected( item ) : false );
- }
-
- /**
- * @returns the number of directories in the currently listed url.
- * Returns 0 if there is no view.
- */
- int numDirs() const;
-
- /**
- * @returns the number of files in the currently listed url.
- * Returns 0 if there is no view.
- */
- int numFiles() const;
-
- /**
- * @returns a KCompletion object, containing all filenames and
- * directories of the current directory/URL.
- * You can use it to insert it into a KLineEdit or KComboBox
- * Note: it will only contain files, after prepareCompletionObjects()
- * has been called. It will be implicitly called from makeCompletion()
- * or makeDirCompletion()
- */
- KCompletion * completionObject() const {
- return const_cast<KCompletion *>( &myCompletion );
- }
-
- /**
- * @returns a KCompletion object, containing only all directories of the
- * current directory/URL.
- * You can use it to insert it into a KLineEdit or KComboBox
- * Note: it will only contain directories, after
- * prepareCompletionObjects() has been called. It will be implicitly
- * called from makeCompletion() or makeDirCompletion()
- */
- KCompletion *dirCompletionObject() const {
- return const_cast<KCompletion *>( &myDirCompletion );
- }
-
- /**
- * an accessor to a collection of all available Actions. The actions
- * are static, they will be there all the time (no need to connect to
- * the signals KActionCollection::inserted() or removed().
- *
- * There are the following actions:
- *
- * @li popupMenu : an ActionMenu presenting a popupmenu with all actions
- * @li up : changes to the parent directory
- * @li back : goes back to the previous directory
- * @li forward : goes forward in the history
- * @li home : changes to the user's home directory
- * @li reload : reloads the current directory
- * @li separator : a separator
- * @li mkdir : opens a dialog box to create a directory
- * @li delete : deletes the selected files/directories
- * @li sorting menu : an ActionMenu containing all sort-options
- * @li by name : sorts by name
- * @li by date : sorts by date
- * @li by size : sorts by size
- * @li reversed : reverses the sort order
- * @li dirs first : sorts directories before files
- * @li case insensitive : sorts case insensitively
- * @li view menu : an ActionMenu containing all actions concerning the view
- * @li short view : shows a simple fileview
- * @li detailed view : shows a detailed fileview (dates, permissions ,...)
- * @li show hidden : shows hidden files
- * @li separate dirs : shows directories in a separate pane
- * @li preview : shows a preview next to the fileview
- * @li single : hides the separate view for directories or the preview
- * @li properties : shows a KPropertiesDialog for the selected files
- *
- * The short and detailed view are in an exclusive group. The sort-by
- * actions are in an exclusive group as well. Also the "separate dirs",
- * "preview" and "single" actions are in an exclusive group.
- *
- * You can e.g. use
- * \code
- * actionCollection()->action( "up" )->plug( someToolBar );
- * \endcode
- * to add a button into a toolbar, which makes the dirOperator change to
- * its parent directory.
- *
- * @returns all available Actions
- */
- KActionCollection * actionCollection() const { return myActionCollection; }
-
- /**
- * Sets the config object and the to be used group in KDirOperator. This
- * will be used to store the view's configuration via
- * KFileView::writeConfig() (and for KFileView::readConfig()).
- * If you don't set this, the views cannot save and restore their
- * configuration.
- *
- * Usually you call this right after KDirOperator creation so that the view
- * instantiation can make use of it already.
- *
- * Note that KDirOperator does NOT take ownership of that object (typically
- * it's TDEGlobal::config() anyway.
- *
- * @see viewConfig
- * @see viewConfigGroup
- * @since 3.1
- */
- // ### KDE4: make virtual
- void setViewConfig( TDEConfig *config, const TQString& group );
-
- /**
- * Returns the TDEConfig object used for saving and restoring view's
- * configuration.
- * @returns the TDEConfig object used for saving and restoring view's
- * configuration.
- * @since 3.1
- */
- TDEConfig *viewConfig();
-
- /**
- * Returns the group name used for saving and restoring view's
- * configuration.
- * @returns the group name used for saving and restoring view's
- * configuration.
- * @since 3.1
- */
- TQString viewConfigGroup() const;
-
- /**
- * Reads the default settings for a view, i.e. the default KFile::FileView.
- * Also reads the sorting and whether hidden files should be shown.
- * Note: the default view will not be set - you have to call
- * \code
- * setView( KFile::Default )
- * \endcode
- * to apply it.
- *
- * @see setView
- * @see setViewConfig
- * @see writeConfig
- */
- virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
-
- /**
- * Saves the current settings like sorting, simple or detailed view.
- *
- * @see readConfig
- * @see setViewConfig
- */
- virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null );
-
-
- /**
- * This is a KFileDialog specific hack: we want to select directories with
- * single click, but not files. But as a generic class, we have to be able
- * to select files on single click as well.
- *
- * This gives us the opportunity to do both.
- *
- * The default is false, set it to true if you don't want files selected
- * with single click.
- */
- void setOnlyDoubleClickSelectsFiles( bool enable );
-
- /**
- * @returns whether files (not directories) should only be select()ed by
- * double-clicks.
- * @see setOnlyDoubleClickSelectsFiles
- */
- bool onlyDoubleClickSelectsFiles() const;
-
- /**
- * Creates the given directory/url. If it is a relative path,
- * it will be completed with the current directory.
- * If enterDirectory is true, the directory will be entered after a
- * successful operation. If unsuccessful, a messagebox will be presented
- * to the user.
- * @returns true if the directory could be created.
- */
- // ### KDE4: make virtual and turn TQString into KURL
- bool mkdir( const TQString& directory, bool enterDirectory = true );
-
- /**
- * Starts and returns a TDEIO::DeleteJob to delete the given @p items.
- *
- * @param items the list of items to be deleted
- * @param ask specifies whether a confirmation dialog should be shown
- * @param showProgress passed to the DeleteJob to show a progress dialog
- */
- // ### KDE4: make virtual
- TDEIO::DeleteJob * del( const KFileItemList& items,
- bool ask = true, bool showProgress = true );
-
- /**
- * Starts and returns a TDEIO::DeleteJob to delete the given @p items.
- *
- * @param items the list of items to be deleted
- * @param parent the parent widget used for the confirmation dialog
- * @param ask specifies whether a confirmation dialog should be shown
- * @param showProgress passed to the DeleteJob to show a progress dialog
- * @since 3.1
- */
- // ### KDE4: make virtual
- TDEIO::DeleteJob * del( const KFileItemList& items, TQWidget *parent,
- bool ask = true, bool showProgress = true );
-
- /**
- * Clears the forward and backward history.
- */
- void clearHistory();
-
- /**
- * When going up in the directory hierarchy, KDirOperator can highlight
- * the directory that was just left.
- *
- * I.e. when you go from /home/gis/src to /home/gis, the item "src" will
- * be made the current item.
- *
- * Default is off, because this behavior introduces bug #136630.
- * Don't enable until this bug is fixed.
- */
- // ### KDE4: make virtual
- void setEnableDirHighlighting( bool enable );
-
- /**
- * @returns whether the last directory will be made the current item
- * when going up in the directory hierarchy.
- *
- * Default is false.
- */
- bool dirHighlighting() const;
-
- /**
- * @returns true if we are in directory-only mode, that is, no files are
- * shown.
- */
- bool dirOnlyMode() const { return dirOnlyMode( myMode ); }
-
- static bool dirOnlyMode( uint mode ) {
- return ( (mode & KFile::Directory) &&
- (mode & (KFile::File | KFile::Files)) == 0 );
- }
-
- /**
- * Sets up the action menu.
- * @param whichActions is an value of OR'd ActionTypes that controls which actions to show in the action menu
- */
- void setupMenu(int whichActions);
-
- /**
- * Reimplemented - allow dropping of files if @p b is true
- * @param b true if the widget should allow dropping of files
- */
- virtual void setAcceptDrops(bool b);
-
- /**
- * Sets the options for dropping files.
- * @see KFileView::DropOptions
- * @since 3.2
- */
- // ### KDE4: make virtual
- void setDropOptions(int options);
-
- /**
- * Starts and returns a TDEIO::CopyJob to trash the given @p items.
- *
- * @param items the list of items to be trashed
- * @param parent the parent widget used for the confirmation dialog
- * @param ask specifies whether a confirmation dialog should be shown
- * @param showProgress passed to the CopyJob to show a progress dialog
- * @since 3.4
- */
- // ### KDE4: make virtual
- TDEIO::CopyJob * trash( const KFileItemList& items, TQWidget *parent,
- bool ask = true, bool showProgress = true );
-
-protected:
- /**
- * A view factory for creating predefined fileviews. Called internally by setView
- * , but you can also call it directly. Reimplement this if you depend on self defined fileviews.
- * @param parent is the TQWidget to be set as parent
- * @param view is the predefined view to be set, note: this can be several ones OR:ed together.
- * @returns the created KFileView
- * @see KFileView
- * @see KCombiView
- * @see KFileDetailView
- * @see KFileIconView
- * @see KFilePreview
- * @see KFile::FileView
- * @see setView
- */
- virtual KFileView* createView( TQWidget* parent, KFile::FileView view );
- /**
- * Sets a custom KDirLister to list directories.
- */
- // ### KDE4: make virtual
- void setDirLister( KDirLister *lister );
-
- virtual void resizeEvent( TQResizeEvent * );
-
- /**
- * Sets up all the actions. Called from the constructor, you usually
- * better not call this.
- */
- void setupActions();
-
- /**
- * Updates the sorting-related actions to comply with the current sorting
- * @see sorting
- */
- void updateSortActions();
-
- /**
- * Updates the view-related actions to comply with the current
- * KFile::FileView
- */
- void updateViewActions();
-
- /**
- * Sets up the context-menu with all the necessary actions. Called from the
- * constructor, you usually don't need to call this.
- * @since 3.1
- */
- void setupMenu();
-
- /**
- * Synchronizes the completion objects with the entries of the
- * currently listed url.
- *
- * Automatically called from makeCompletion() and
- * makeDirCompletion()
- */
- void prepareCompletionObjects();
-
- /**
- * Checks if there support from TDEIO::PreviewJob for the currently
- * shown files, taking mimeFilter() and nameFilter() into account
- * Enables/disables the preview-action accordingly.
- */
- bool checkPreviewSupport();
-
-public slots:
- /**
- * Goes one step back in the history and opens that url.
- */
- // ### KDE4: make virtual
- void back();
-
- /**
- * Goes one step forward in the history and opens that url.
- */
- // ### KDE4: make virtual
- void forward();
-
- /**
- * Enters the home directory.
- */
- // ### KDE4: make virtual
- void home();
-
- /**
- * Goes one directory up from the current url.
- */
- // ### KDE4: make virtual
- void cdUp();
-
- /**
- * to update the view after changing the settings
- */
- void updateDir();
-
- /**
- * Re-reads the current url.
- */
- // ### KDE4: make virtual
- void rereadDir();
-
- /**
- * Opens a dialog to create a new directory.
- */
- // ### KDE4: make virtual
- void mkdir();
-
- /**
- * Deletes the currently selected files/directories.
- */
- // ### KDE4: make virtual
- void deleteSelected();
-
- /**
- * Enables/disables actions that are selection dependent. Call this e.g.
- * when you are about to show a popup menu using some of KDirOperators
- * actions.
- */
- void updateSelectionDependentActions();
-
- /**
- * Tries to complete the given string (only completes files).
- */
- TQString makeCompletion(const TQString&);
-
- /**
- * Tries to complete the given string (only completes directores).
- */
- TQString makeDirCompletion(const TQString&);
-
- /**
- * Trashes the currently selected files/directories.
- * @since 3.4
- */
- // ### KDE4: make virtual
- void trashSelected(KAction::ActivationReason, TQt::ButtonState);
-
-protected slots:
- /**
- * Restores the normal cursor after showing the busy-cursor. Also hides
- * the progressbar.
- */
- void resetCursor();
-
- /**
- * Called after setURL() to load the directory, update the history,
- * etc.
- */
- void pathChanged();
-
- /**
- * Adds a new list of KFileItems to the view
- * (coming from KDirLister)
- */
- void insertNewFiles(const KFileItemList &newone);
-
- /**
- * Removes the given KFileItem item from the view (usually called from
- * KDirLister).
- */
- void itemDeleted(KFileItem *);
-
- /**
- * Enters the directory specified by the given @p item.
- */
- // ### KDE4: make virtual
- void selectDir(const KFileItem *item );
-
- /**
- * Emits fileSelected( item )
- */
- void selectFile(const KFileItem *item);
-
- /**
- * Emits fileHighlighted( i )
- */
- void highlightFile(const KFileItem* i) { emit fileHighlighted( i ); }
-
- /**
- * Called upon right-click to activate the popupmenu.
- */
- virtual void activatedMenu( const KFileItem *, const TQPoint& pos );
-
- /**
- * Changes sorting to sort by name
- */
- void sortByName() { byNameAction->setChecked( true ); }
-
- /**
- * Changes sorting to sort by size
- */
- void sortBySize() { bySizeAction->setChecked( true ); }
-
- /**
- * Changes sorting to sort by date
- */
- void sortByDate() { byDateAction->setChecked( true ); }
-
- /**
- * Changes sorting to reverse sorting
- */
- void sortReversed() { reverseAction->setChecked( !reverseAction->isChecked() ); }
-
- /**
- * Toggles showing directories first / having them sorted like files.
- */
- void toggleDirsFirst() { dirsFirstAction->setChecked( !dirsFirstAction->isChecked() ); }
-
- /**
- * Toggles case sensitive / case insensitive sorting
- */
- void toggleIgnoreCase() { caseInsensitiveAction->setChecked( !caseInsensitiveAction->isChecked() ); }
-
- /**
- * Tries to make the given @p match as current item in the view and emits
- * completion( match )
- */
- void slotCompletionMatch(const TQString& match);
-
-signals:
- void urlEntered(const KURL& );
- void updateInformation(int files, int dirs);
- void completion(const TQString&);
- void finishedLoading();
-
- /**
- * Emitted whenever the current fileview is changed, either by an explicit
- * call to setView() or by the user selecting a different view thru
- * the GUI.
- */
- void viewChanged( KFileView * newView );
-
- /**
- * Emitted when a file is highlighted or generally the selection changes in
- * multiselection mode. In the latter case, @p item is 0L. You can access
- * the selected items with selectedItems().
- */
- void fileHighlighted( const KFileItem *item );
- void dirActivated( const KFileItem *item );
- void fileSelected( const KFileItem *item );
- /**
- * Emitted when files are dropped. Dropping files is disabled by
- * default. You need to enable it with setAcceptDrops()
- * @param item the item on which the drop occurred or 0.
- * @param event the drop event itself.
- * @param urls the urls that where dropped.
- * @since 3.2
- */
- void dropped(const KFileItem *item, TQDropEvent*event, const KURL::List&urls);
-private:
- /**
- * Contains all URLs you can reach with the back button.
- */
- TQPtrStack<KURL> backStack;
-
- /**
- * Contains all URLs you can reach with the forward button.
- */
- TQPtrStack<KURL> forwardStack;
-
- KDirLister *dir;
- KURL currUrl;
-
- KCompletion myCompletion;
- KCompletion myDirCompletion;
- bool myCompleteListDirty;
- TQDir::SortSpec mySorting;
-
- /**
- * Checks whether we preview support is available for the current
- * mimetype/namefilter
- */
- bool checkPreviewInternal() const;
-
- /**
- * takes action on the new location. If it's a directory, change
- * into it, if it's a file, correct the name, etc.
- */
- void checkPath(const TQString& txt, bool takeFiles = false);
-
- void connectView(KFileView *);
-
- bool openURL( const KURL& url, bool keep = false, bool reload = false );
-
- KFileView *m_fileView;
- KFileItemList pendingMimeTypes;
-
- // the enum KFile::FileView as an int
- int m_viewKind;
- int defaultView;
-
- KFile::Mode myMode;
- KProgress *progress;
-
- const TQWidget *myPreview; // temporary pointer for the preview widget
-
- // actions for the popupmenus
- // ### clean up all those -- we have them all in the actionMenu!
- KActionMenu *actionMenu;
-
- KAction *backAction;
- KAction *forwardAction;
- KAction *homeAction;
- KAction *upAction;
- KAction *reloadAction;
- KActionSeparator *actionSeparator;
- KAction *mkdirAction;
-
- KActionMenu *sortActionMenu;
- KRadioAction *byNameAction;
- KRadioAction *byDateAction;
- KRadioAction *bySizeAction;
- KToggleAction *reverseAction;
- KToggleAction *dirsFirstAction;
- KToggleAction *caseInsensitiveAction;
-
- KActionMenu *viewActionMenu;
- KRadioAction *shortAction;
- KRadioAction *detailedAction;
- KToggleAction *showHiddenAction;
- KToggleAction *separateDirsAction;
-
- KActionCollection *myActionCollection;
- KActionCollection *viewActionCollection;
-
-private slots:
- /**
- * @internal
- */
- void slotDetailedView();
- void slotSimpleView();
- void slotToggleHidden( bool );
-
- void slotSeparateDirs();
- void slotDefaultPreview();
- void togglePreview( bool );
-
- void slotSortByName();
- void slotSortBySize();
- void slotSortByDate();
- void slotSortReversed();
- void slotToggleDirsFirst();
- void slotToggleIgnoreCase();
-
- void slotStarted();
- void slotProgress( int );
- void slotShowProgress();
- void slotIOFinished();
- void slotCanceled();
- void slotRedirected( const KURL& );
-
- void slotViewActionAdded( KAction * );
- void slotViewActionRemoved( KAction * );
- void slotViewSortingChanged( TQDir::SortSpec );
-
- void slotClearView();
- void slotRefreshItems( const KFileItemList& items );
-
- void slotProperties();
-
- void insertViewDependentActions();
-
-private:
- static bool isReadable( const KURL& url );
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KDirOperatorPrivate;
- KDirOperatorPrivate *d;
-};
-
-#endif
diff --git a/kio/kfile/kdirselectdialog.cpp b/kio/kfile/kdirselectdialog.cpp
deleted file mode 100644
index 48dd3a2e4..000000000
--- a/kio/kfile/kdirselectdialog.cpp
+++ /dev/null
@@ -1,481 +0,0 @@
-/*
- Copyright (C) 2001,2002 Carsten Pfeiffer <pfeiffer@kde.org>
- Copyright (C) 2001 Michael Jarrett <michaelj@corel.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqdir.h>
-#include <tqlayout.h>
-#include <tqpopupmenu.h>
-#include <tqstringlist.h>
-#include <tqvaluestack.h>
-
-#include <kactionclasses.h>
-#include <kapplication.h>
-#include <kcombobox.h>
-#include <kconfig.h>
-#include <kfiledialog.h>
-#include <kfilespeedbar.h>
-#include <kglobalsettings.h>
-#include <kiconloader.h>
-#include <klocale.h>
-#include <kprotocolinfo.h>
-#include <krecentdirs.h>
-#include <kshell.h>
-#include <kurl.h>
-#include <kurlcompletion.h>
-#include <kurlpixmapprovider.h>
-#include <kinputdialog.h>
-#include <kio/netaccess.h>
-#include <kio/renamedlg.h>
-#include <kmessagebox.h>
-
-#include "kfiletreeview.h"
-#include "kdirselectdialog.h"
-
-// ### add mutator for treeview!
-
-class KDirSelectDialog::KDirSelectDialogPrivate
-{
-public:
- KDirSelectDialogPrivate()
- {
- urlCombo = 0L;
- branch = 0L;
- comboLocked = false;
- }
-
- KFileSpeedBar *speedBar;
- KHistoryCombo *urlCombo;
- KFileTreeBranch *branch;
- TQString recentDirClass;
- KURL startURL;
- TQValueStack<KURL> dirsToList;
-
- bool comboLocked : 1;
-};
-
-static KURL rootUrl(const KURL &url)
-{
- KURL root = url;
- root.setPath( "/" );
-
- if (!kapp->authorizeURLAction("list", KURL(), root))
- {
- root = KURL::fromPathOrURL( TQDir::homeDirPath() );
- if (!kapp->authorizeURLAction("list", KURL(), root))
- {
- root = url;
- }
- }
- return root;
-}
-
-KDirSelectDialog::KDirSelectDialog(const TQString &startDir, bool localOnly,
- TQWidget *parent, const char *name,
- bool modal)
- : KDialogBase( parent, name, modal, i18n("Select Folder"),
- Ok|Cancel|User1, Ok, false,
- KGuiItem( i18n("New Folder..."), "folder_new" ) ),
- m_localOnly( localOnly )
-{
- d = new KDirSelectDialogPrivate;
- d->branch = 0L;
-
- TQFrame *page = makeMainWidget();
- TQHBoxLayout *hlay = new TQHBoxLayout( page, 0, spacingHint() );
- m_mainLayout = new TQVBoxLayout();
- d->speedBar = new KFileSpeedBar( page, "speedbar" );
- connect( d->speedBar, TQT_SIGNAL( activated( const KURL& )),
- TQT_SLOT( setCurrentURL( const KURL& )) );
- hlay->addWidget( d->speedBar, 0 );
- hlay->addLayout( m_mainLayout, 1 );
-
- // Create dir list
- m_treeView = new KFileTreeView( page );
- m_treeView->addColumn( i18n("Folders") );
- m_treeView->setColumnWidthMode( 0, TQListView::Maximum );
- m_treeView->setResizeMode( TQListView::AllColumns );
-
- d->urlCombo = new KHistoryCombo( page, "url combo" );
- d->urlCombo->setTrapReturnKey( true );
- d->urlCombo->setPixmapProvider( new KURLPixmapProvider() );
- KURLCompletion *comp = new KURLCompletion();
- comp->setMode( KURLCompletion::DirCompletion );
- d->urlCombo->setCompletionObject( comp, true );
- d->urlCombo->setAutoDeleteCompletionObject( true );
- d->urlCombo->setDuplicatesEnabled( false );
- connect( d->urlCombo, TQT_SIGNAL( textChanged( const TQString& ) ),
- TQT_SLOT( slotComboTextChanged( const TQString& ) ));
-
- m_contextMenu = new TQPopupMenu( this );
- KAction* newFolder = new KAction( i18n("New Folder..."), "folder_new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotMkdir() ), TQT_TQOBJECT(this));
- newFolder->plug(m_contextMenu);
- m_contextMenu->insertSeparator();
- m_showHiddenFolders = new KToggleAction ( i18n( "Show Hidden Folders" ), 0, TQT_TQOBJECT(this),
- TQT_SLOT( slotShowHiddenFoldersToggled() ), TQT_TQOBJECT(this));
- m_showHiddenFolders->plug(m_contextMenu);
-
- d->startURL = KFileDialog::getStartURL( startDir, d->recentDirClass );
- if ( localOnly && !d->startURL.isLocalFile() )
- {
- d->startURL = KURL();
- TQString docPath = TDEGlobalSettings::documentPath();
- if (TQDir(docPath).exists())
- d->startURL.setPath( docPath );
- else
- d->startURL.setPath( TQDir::homeDirPath() );
- }
-
- KURL root = rootUrl(d->startURL);
-
- m_startDir = d->startURL.url();
-
- d->branch = createBranch( root );
-
- readConfig( TDEGlobal::config(), "DirSelect Dialog" );
-
- m_mainLayout->addWidget( m_treeView, 1 );
- m_mainLayout->addWidget( d->urlCombo, 0 );
-
- connect( m_treeView, TQT_SIGNAL( currentChanged( TQListViewItem * )),
- TQT_SLOT( slotCurrentChanged() ));
- connect( m_treeView, TQT_SIGNAL( contextMenu( KListView *, TQListViewItem *, const TQPoint & )),
- TQT_SLOT( slotContextMenu( KListView *, TQListViewItem *, const TQPoint & )));
-
- connect( d->urlCombo, TQT_SIGNAL( activated( const TQString& )),
- TQT_SLOT( slotURLActivated( const TQString& )));
- connect( d->urlCombo, TQT_SIGNAL( returnPressed( const TQString& )),
- TQT_SLOT( slotURLActivated( const TQString& )));
-
- setCurrentURL( d->startURL );
-}
-
-
-KDirSelectDialog::~KDirSelectDialog()
-{
- delete d;
-}
-
-void KDirSelectDialog::setCurrentURL( const KURL& url )
-{
- if ( !url.isValid() )
- return;
-
- KURL root = rootUrl(url);
-
- d->startURL = url;
- if ( !d->branch ||
- url.protocol() != d->branch->url().protocol() ||
- url.host() != d->branch->url().host() )
- {
- if ( d->branch )
- {
- // removing the root-item causes the currentChanged() signal to be
- // emitted, but we don't want to update the location-combo yet.
- d->comboLocked = true;
- view()->removeBranch( d->branch );
- d->comboLocked = false;
- }
-
- d->branch = createBranch( root );
- }
-
- d->branch->disconnect( TQT_SIGNAL( populateFinished( KFileTreeViewItem * )),
- this, TQT_SLOT( slotNextDirToList( KFileTreeViewItem *)));
- connect( d->branch, TQT_SIGNAL( populateFinished( KFileTreeViewItem * )),
- TQT_SLOT( slotNextDirToList( KFileTreeViewItem * ) ));
-
- KURL dirToList = root;
- d->dirsToList.clear();
- TQString path = url.path(+1);
- int pos = path.length();
-
- if ( path.isEmpty() ) // e.g. ftp://host.com/ -> just list the root dir
- d->dirsToList.push( root );
-
- else
- {
- while ( pos > 0 )
- {
- pos = path.findRev( '/', pos -1 );
- if ( pos >= 0 )
- {
- dirToList.setPath( path.left( pos +1 ) );
- d->dirsToList.push( dirToList );
-// tqDebug( "List: %s", dirToList.url().latin1());
- }
- }
- }
-
- if ( !d->dirsToList.isEmpty() )
- openNextDir( d->branch->root() );
-}
-
-void KDirSelectDialog::openNextDir( KFileTreeViewItem * /*parent*/ )
-{
- if ( !d->branch )
- return;
-
- KURL url = d->dirsToList.pop();
-
- KFileTreeViewItem *item = view()->findItem( d->branch, url.path().mid(1));
- if ( item )
- {
- if ( !item->isOpen() )
- item->setOpen( true );
- else // already open -> go to next one
- slotNextDirToList( item );
- }
-// else
-// tqDebug("###### openNextDir: item not found!");
-}
-
-void KDirSelectDialog::slotNextDirToList( KFileTreeViewItem *item )
-{
- // scroll to make item the topmost item
- view()->ensureItemVisible( item );
- TQRect r = view()->itemRect( item );
- if ( r.isValid() )
- {
- int x, y;
- view()->viewportToContents( view()->contentsX(), r.y(), x, y );
- view()->setContentsPos( x, y );
- }
-
- if ( !d->dirsToList.isEmpty() )
- openNextDir( item );
- else
- {
- d->branch->disconnect( TQT_SIGNAL( populateFinished( KFileTreeViewItem * )),
- this, TQT_SLOT( slotNextDirToList( KFileTreeViewItem *)));
- view()->setCurrentItem( item );
- item->setSelected( true );
- }
-}
-
-void KDirSelectDialog::readConfig( TDEConfig *config, const TQString& group )
-{
- d->urlCombo->clear();
-
- TDEConfigGroup conf( config, group );
- d->urlCombo->setHistoryItems( conf.readPathListEntry( "History Items" ));
-
- TQSize defaultSize( 400, 450 );
- resize( conf.readSizeEntry( "DirSelectDialog Size", &defaultSize ));
-}
-
-void KDirSelectDialog::saveConfig( TDEConfig *config, const TQString& group )
-{
- TDEConfigGroup conf( config, group );
- conf.writePathEntry( "History Items", d->urlCombo->historyItems(), ',',
- true, true);
- conf.writeEntry( "DirSelectDialog Size", size(), true, true );
-
- d->speedBar->save( config );
-
- config->sync();
-}
-
-void KDirSelectDialog::slotUser1()
-{
- slotMkdir();
-}
-
-void KDirSelectDialog::accept()
-{
- KFileTreeViewItem *item = m_treeView->currentKFileTreeViewItem();
- if ( !item )
- return;
-
- if ( !d->recentDirClass.isEmpty() )
- {
- KURL dir = item->url();
- if ( !item->isDir() )
- dir = dir.upURL();
-
- KRecentDirs::add(d->recentDirClass, dir.url());
- }
-
- d->urlCombo->addToHistory( item->url().prettyURL() );
- KFileDialog::setStartDir( url() );
-
- KDialogBase::accept();
- saveConfig( TDEGlobal::config(), "DirSelect Dialog" );
-}
-
-
-KURL KDirSelectDialog::url() const
-{
- return m_treeView->currentURL();
-}
-
-void KDirSelectDialog::slotCurrentChanged()
-{
- if ( d->comboLocked )
- return;
-
- KFileTreeViewItem *current = view()->currentKFileTreeViewItem();
- KURL u = current ? current->url() : (d->branch ? d->branch->rootUrl() : KURL());
-
- if ( u.isValid() )
- {
- if ( u.isLocalFile() )
- d->urlCombo->setEditText( u.path() );
-
- else // remote url
- d->urlCombo->setEditText( u.prettyURL() );
- }
- else
- d->urlCombo->setEditText( TQString::null );
-}
-
-void KDirSelectDialog::slotURLActivated( const TQString& text )
-{
- if ( text.isEmpty() )
- return;
-
- KURL url = KURL::fromPathOrURL( text );
- d->urlCombo->addToHistory( url.prettyURL() );
-
- if ( localOnly() && !url.isLocalFile() )
- return; // ### messagebox
-
- KURL oldURL = m_treeView->currentURL();
- if ( oldURL.isEmpty() )
- oldURL = KURL::fromPathOrURL( m_startDir );
-
- setCurrentURL( url );
-}
-
-KFileTreeBranch * KDirSelectDialog::createBranch( const KURL& url )
-{
- TQString title = url.isLocalFile() ? url.path() : url.prettyURL();
- KFileTreeBranch *branch = view()->addBranch( url, title, m_showHiddenFolders->isChecked() );
- branch->setChildRecurse( false );
- view()->setDirOnlyMode( branch, true );
-
- return branch;
-}
-
-void KDirSelectDialog::slotComboTextChanged( const TQString& text )
-{
- if ( d->branch )
- {
- KURL url = KURL::fromPathOrURL( KShell::tildeExpand( text ) );
- KFileTreeViewItem *item = d->branch->findTVIByURL( url );
- if ( item )
- {
- view()->setCurrentItem( item );
- view()->setSelected( item, true );
- view()->ensureItemVisible( item );
- return;
- }
- }
-
- TQListViewItem *item = view()->currentItem();
- if ( item )
- {
- item->setSelected( false );
- // 2002/12/27, deselected item is not repainted, so force it
- item->repaint();
- }
-}
-
-void KDirSelectDialog::slotContextMenu( KListView *, TQListViewItem *, const TQPoint& pos )
-{
- m_contextMenu->popup( pos );
-}
-
-void KDirSelectDialog::slotMkdir()
-{
- bool ok;
- TQString where = url().pathOrURL();
- TQString name = i18n( "New Folder" );
- if ( url().isLocalFile() && TQFileInfo( url().path(+1) + name ).exists() )
- name = TDEIO::RenameDlg::suggestName( url(), name );
-
- TQString directory = TDEIO::encodeFileName( KInputDialog::getText( i18n( "New Folder" ),
- i18n( "Create new folder in:\n%1" ).arg( where ),
- name, &ok, this));
- if (!ok)
- return;
-
- bool selectDirectory = true;
- bool writeOk = false;
- bool exists = false;
- KURL folderurl( url() );
-
- TQStringList dirs = TQStringList::split( TQDir::separator(), directory );
- TQStringList::ConstIterator it = dirs.begin();
-
- for ( ; it != dirs.end(); ++it )
- {
- folderurl.addPath( *it );
- exists = TDEIO::NetAccess::exists( folderurl, false, 0 );
- writeOk = !exists && TDEIO::NetAccess::mkdir( folderurl, topLevelWidget() );
- }
-
- if ( exists ) // url was already existant
- {
- TQString which = folderurl.isLocalFile() ? folderurl.path() : folderurl.prettyURL();
- KMessageBox::sorry(this, i18n("A file or folder named %1 already exists.").arg(which));
- selectDirectory = false;
- }
- else if ( !writeOk ) {
- KMessageBox::sorry(this, i18n("You do not have permission to create that folder." ));
- }
- else if ( selectDirectory ) {
- setCurrentURL( folderurl );
- }
-}
-
-void KDirSelectDialog::slotShowHiddenFoldersToggled()
-{
- KURL currentURL = url();
-
- d->comboLocked = true;
- view()->removeBranch( d->branch );
- d->comboLocked = false;
-
- KURL root = rootUrl(d->startURL);
- d->branch = createBranch( root );
-
- setCurrentURL( currentURL );
-}
-
-// static
-KURL KDirSelectDialog::selectDirectory( const TQString& startDir,
- bool localOnly,
- TQWidget *parent,
- const TQString& caption)
-{
- KDirSelectDialog myDialog( startDir, localOnly, parent,
- "kdirselect dialog", true );
-
- if ( !caption.isNull() )
- myDialog.setCaption( caption );
-
- if ( myDialog.exec() == TQDialog::Accepted )
- return TDEIO::NetAccess::mostLocalURL(myDialog.url(),parent);
- else
- return KURL();
-}
-
-void KDirSelectDialog::virtual_hook( int id, void* data )
-{ KDialogBase::virtual_hook( id, data ); }
-
-#include "kdirselectdialog.moc"
diff --git a/kio/kfile/kdirsize.cpp b/kio/kfile/kdirsize.cpp
deleted file mode 100644
index 14936679a..000000000
--- a/kio/kfile/kdirsize.cpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kdirsize.h"
-#include <kdebug.h>
-#include <kglobal.h>
-#include <tqapplication.h>
-#include <tqtimer.h>
-#include <config-kfile.h>
-
-using namespace TDEIO;
-
-KDirSize::KDirSize( const KURL & directory )
- : TDEIO::Job(false /*No GUI*/), m_bAsync(true), m_totalSize(0L), m_totalFiles(0L), m_totalSubdirs(0L)
-{
- startNextJob( directory );
-}
-
-KDirSize::KDirSize( const KFileItemList & lstItems )
- : TDEIO::Job(false /*No GUI*/), m_bAsync(true), m_totalSize(0L), m_totalFiles(0L), m_totalSubdirs(0L), m_lstItems(lstItems)
-{
- TQTimer::singleShot( 0, this, TQT_SLOT(processList()) );
-}
-
-void KDirSize::processList()
-{
- while (!m_lstItems.isEmpty())
- {
- KFileItem * item = m_lstItems.first();
- m_lstItems.removeFirst();
- if ( !item->isLink() )
- {
- if ( item->isDir() )
- {
- kdDebug(kfile_area) << "KDirSize::processList dir -> listing" << endl;
- KURL url = item->url();
- startNextJob( url );
- return; // we'll come back later, when this one's finished
- }
- else
- {
- m_totalSize += item->size();
-// no long long with kdDebug()
-// kdDebug(kfile_area) << "KDirSize::processList file -> " << m_totalSize << endl;
- }
- }
- }
- kdDebug(kfile_area) << "KDirSize::processList finished" << endl;
- if ( !m_bAsync )
- tqApp->exit_loop();
- emitResult();
-}
-
-void KDirSize::startNextJob( const KURL & url )
-{
- TDEIO::ListJob * listJob = TDEIO::listRecursive( url, false /* no GUI */ );
- connect( listJob, TQT_SIGNAL(entries( TDEIO::Job *,
- const TDEIO::UDSEntryList& )),
- TQT_SLOT( slotEntries( TDEIO::Job*,
- const TDEIO::UDSEntryList& )));
- addSubjob( listJob );
-}
-
-void KDirSize::slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList & list )
-{
- static const TQString& dot = TDEGlobal::staticQString( "." );
- static const TQString& dotdot = TDEGlobal::staticQString( ".." );
- TDEIO::UDSEntryListConstIterator it = list.begin();
- TDEIO::UDSEntryListConstIterator end = list.end();
- for (; it != end; ++it) {
- TDEIO::UDSEntry::ConstIterator it2 = (*it).begin();
- TDEIO::filesize_t size = 0;
- bool isLink = false;
- bool isDir = false;
- TQString name;
- for( ; it2 != (*it).end(); it2++ ) {
- switch( (*it2).m_uds ) {
- case TDEIO::UDS_NAME:
- name = (*it2).m_str;
- break;
- case TDEIO::UDS_LINK_DEST:
- isLink = !(*it2).m_str.isEmpty();
- break;
- case TDEIO::UDS_SIZE:
- size = ((*it2).m_long);
- break;
- case TDEIO::UDS_FILE_TYPE:
- isDir = S_ISDIR((*it2).m_long);
- break;
- default:
- break;
- }
- }
- if ( name == dot )
- m_totalSize += size;
- else if ( name != dotdot )
- {
- if (!isLink)
- m_totalSize += size;
- if (!isDir)
- m_totalFiles++;
- else
- m_totalSubdirs++;
- //kdDebug(kfile_area) << name << ":" << size << endl;
- }
- }
-}
-
-//static
-KDirSize * KDirSize::dirSizeJob( const KURL & directory )
-{
- return new KDirSize( directory ); // useless - but consistent with other jobs
-}
-
-//static
-KDirSize * KDirSize::dirSizeJob( const KFileItemList & lstItems )
-{
- return new KDirSize( lstItems );
-}
-
-//static
-TDEIO::filesize_t KDirSize::dirSize( const KURL & directory )
-{
- KDirSize * dirSize = dirSizeJob( directory );
- dirSize->setSync();
- tqApp->enter_loop();
- return dirSize->totalSize();
-}
-
-
-void KDirSize::slotResult( TDEIO::Job * job )
-{
- kdDebug(kfile_area) << " KDirSize::slotResult( TDEIO::Job * job ) m_lstItems:" << m_lstItems.count() << endl;
- if ( !m_lstItems.isEmpty() )
- {
- subjobs.remove(job); // Remove job, but don't kill this job.
- processList();
- }
- else
- {
- if ( !m_bAsync )
- tqApp->exit_loop();
- TDEIO::Job::slotResult( job );
- }
-}
-
-void KDirSize::virtual_hook( int id, void* data )
-{ TDEIO::Job::virtual_hook( id, data ); }
-
-#include "kdirsize.moc"
diff --git a/kio/kfile/kdirsize.h b/kio/kfile/kdirsize.h
deleted file mode 100644
index b0f2c8fc2..000000000
--- a/kio/kfile/kdirsize.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __KDIRSIZE_H
-#define __KDIRSIZE_H
-
-#include <kio/job.h>
-#include <kfileitem.h>
-
-/**
- * Computes a directory size (similar to "du", but doesn't give the same results
- * since we simply sum up the dir and file sizes, whereas du speaks disk blocks)
- */
-class TDEIO_EXPORT KDirSize : public TDEIO::Job
-{
- Q_OBJECT
-protected:
- KDirSize( const KURL & directory );
- KDirSize( const KFileItemList & lstItems );
- ~KDirSize() {}
-
-public:
- /**
- * @return the size we found
- */
- TDEIO::filesize_t totalSize() const { return m_totalSize; }
-
- /**
- * @return the total number of files (counting symlinks to files, sockets
- * and character devices as files) in this directory and all sub-directories
- * @since 3.3
- */
- TDEIO::filesize_t totalFiles() const { return m_totalFiles; }
-
- /**
- * @return the total number of sub-directories found (not including the
- * directory the search started from and treating symlinks to directories
- * as directories)
- * @since 3.3
- */
- TDEIO::filesize_t totalSubdirs() const { return m_totalSubdirs; }
-
- /**
- * Asynchronous method. Connect to the result signal.
- * This one lists a single directory.
- */
- static KDirSize * dirSizeJob( const KURL & directory );
-
- /**
- * Asynchronous method. Connect to the result signal.
- * This one lists the items from @p lstItems.
- * The reason we asks for items instead of just urls, is so that
- * we directly know if the item is a file or a directory,
- * and in case of a file, we already have its size.
- */
- static KDirSize * dirSizeJob( const KFileItemList & lstItems );
-
- /**
- * Synchronous method - you get the result as soon as
- * the call returns.
- */
- static TDEIO::filesize_t dirSize( const KURL & directory );
-
-protected:
- /**
- * @internal
- */
- void setSync() { m_bAsync = false; }
-
- void startNextJob( const KURL & url );
-
-protected slots:
-
- virtual void slotResult( TDEIO::Job *job );
- void slotEntries( TDEIO::Job * , const TDEIO::UDSEntryList &);
- void processList();
-
-private:
- bool m_bAsync;
- TDEIO::filesize_t m_totalSize;
- TDEIO::filesize_t m_totalFiles;
- TDEIO::filesize_t m_totalSubdirs;
- KFileItemList m_lstItems;
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KDirSize* d;
-};
-
-#endif
diff --git a/kio/kfile/kdiskfreesp.cpp b/kio/kfile/kdiskfreesp.cpp
deleted file mode 100644
index 18245bdcd..000000000
--- a/kio/kfile/kdiskfreesp.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * kdiskfreesp.cpp
- *
- * Copyright (c) 1999 Michael Kropfberger <michael.kropfberger@gmx.net>
- *
- * Requires the Qt widget libraries, available at no cost at
- * http://www.troll.no/
- *
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "kdiskfreesp.h"
-#include <tqfile.h>
-#include <tqtextstream.h>
-
-#include <kdebug.h>
-#include <kprocess.h>
-#include <kio/global.h>
-#include <config-kfile.h>
-
-#include "kdiskfreesp.moc"
-
-#define DF_COMMAND "df"
-#define DF_ARGS "-k"
-#define NO_FS_TYPE true
-
-#define BLANK ' '
-#define FULL_PERCENT 95.0
-
-/***************************************************************************
- * constructor
-**/
-KDiskFreeSp::KDiskFreeSp(TQObject *parent, const char *name)
- : TQObject(parent,name)
-{
- dfProc = new TDEProcess(); TQ_CHECK_PTR(dfProc);
- dfProc->setEnvironment("LANGUAGE", "C");
- connect( dfProc, TQT_SIGNAL(receivedStdout(TDEProcess *, char *, int) ),
- this, TQT_SLOT (receivedDFStdErrOut(TDEProcess *, char *, int)) );
- connect(dfProc,TQT_SIGNAL(processExited(TDEProcess *) ),
- this, TQT_SLOT(dfDone() ) );
-
- readingDFStdErrOut=false;
-}
-
-
-/***************************************************************************
- * destructor
-**/
-KDiskFreeSp::~KDiskFreeSp()
-{
- delete dfProc;
-}
-
-/***************************************************************************
- * is called, when the df-command writes on StdOut
-**/
-void KDiskFreeSp::receivedDFStdErrOut(TDEProcess *, char *data, int len)
-{
- TQCString tmp(data,len+1); // adds a zero-byte
- dfStringErrOut.append(tmp);
-}
-
-/***************************************************************************
- * reads the df-commands results
-**/
-int KDiskFreeSp::readDF( const TQString & mountPoint )
-{
- if (readingDFStdErrOut || dfProc->isRunning())
- return -1;
- m_mountPoint = mountPoint;
- dfStringErrOut=""; // yet no data received
- dfProc->clearArguments();
- (*dfProc) << TQString::fromLocal8Bit(DF_COMMAND) << TQString::fromLocal8Bit(DF_ARGS);
- if (!dfProc->start( TDEProcess::NotifyOnExit, TDEProcess::AllOutput ))
- kdError() << "could not execute ["<< DF_COMMAND << "]" << endl;
- return 1;
-}
-
-
-/***************************************************************************
- * is called, when the df-command has finished
-**/
-void KDiskFreeSp::dfDone()
-{
- readingDFStdErrOut=true;
-
- TQTextStream t (dfStringErrOut, IO_ReadOnly);
- TQString s=t.readLine();
- if ( (s.isEmpty()) || ( s.left(10) != TQString::fromLatin1("Filesystem") ) )
- kdError() << "Error running df command... got [" << s << "]" << endl;
- while ( !t.eof() ) {
- TQString u,v;
- s=t.readLine();
- s=s.simplifyWhiteSpace();
- if ( !s.isEmpty() ) {
- //kdDebug(kfile_area) << "GOT: [" << s << "]" << endl;
-
- if (s.find(BLANK)<0) // devicename was too long, rest in next line
- if ( !t.eof() ) { // just appends the next line
- v=t.readLine();
- s=s.append(v);
- s=s.simplifyWhiteSpace();
- //kdDebug(kfile_area) << "SPECIAL GOT: [" << s << "]" << endl;
- }//if silly linefeed
-
- //kdDebug(kfile_area) << "[" << s << "]" << endl;
-
- //TQString deviceName = s.left(s.find(BLANK));
- s=s.remove(0,s.find(BLANK)+1 );
- //kdDebug(kfile_area) << " DeviceName: [" << deviceName << "]" << endl;
-
- if (!NO_FS_TYPE)
- s=s.remove(0,s.find(BLANK)+1 ); // eat fs type
-
- u=s.left(s.find(BLANK));
- unsigned long kBSize = u.toULong();
- s=s.remove(0,s.find(BLANK)+1 );
- //kdDebug(kfile_area) << " Size: [" << kBSize << "]" << endl;
-
- u=s.left(s.find(BLANK));
- unsigned long kBUsed = u.toULong();
- s=s.remove(0,s.find(BLANK)+1 );
- //kdDebug(kfile_area) << " Used: [" << kBUsed << "]" << endl;
-
- u=s.left(s.find(BLANK));
- unsigned long kBAvail = u.toULong();
- s=s.remove(0,s.find(BLANK)+1 );
- //kdDebug(kfile_area) << " Avail: [" << kBAvail << "]" << endl;
-
-
- s=s.remove(0,s.find(BLANK)+1 ); // delete the capacity 94%
- TQString mountPoint = s.stripWhiteSpace();
- //kdDebug(kfile_area) << " MountPoint: [" << mountPoint << "]" << endl;
-
- if ( mountPoint == m_mountPoint )
- {
- //kdDebug(kfile_area) << "Found mount point. Emitting" << endl;
- emit foundMountPoint( mountPoint, kBSize, kBUsed, kBAvail );
- emit foundMountPoint( kBSize, kBUsed, kBAvail, mountPoint ); // sic!
- }
- }//if not header
- }//while further lines available
-
- readingDFStdErrOut=false;
- emit done();
- delete this;
-}
-
-KDiskFreeSp * KDiskFreeSp::findUsageInfo( const TQString & path )
-{
- KDiskFreeSp * job = new KDiskFreeSp;
- TQString mountPoint = TDEIO::findPathMountPoint( path );
- job->readDF( mountPoint );
- return job;
-}
diff --git a/kio/kfile/kencodingfiledialog.cpp b/kio/kfile/kencodingfiledialog.cpp
deleted file mode 100644
index 183023cf5..000000000
--- a/kio/kfile/kencodingfiledialog.cpp
+++ /dev/null
@@ -1,223 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2003 Joseph Wenninger <jowenn@kde.org>
- 2003 Andras Mantia <amantia@freemail.hu>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "config-kfile.h"
-
-#include "kencodingfiledialog.h"
-#include <kcombobox.h>
-#include <ktoolbar.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kcharsets.h>
-#include <tqtextcodec.h>
-#include <kdiroperator.h>
-#include <krecentdocument.h>
-
-struct KEncodingFileDialogPrivate
-{
- KComboBox *encoding;
-};
-
-KEncodingFileDialog::KEncodingFileDialog(const TQString& startDir, const TQString& encoding , const TQString& filter,
- const TQString& caption, KFileDialog::OperationMode type, TQWidget *parent, const char* name, bool modal)
- : KFileDialog(startDir,filter,parent,name,modal), d(new KEncodingFileDialogPrivate)
-{
- setCaption(caption);
-
- setOperationMode( type );
-
- KToolBar *tb = toolBar();
- tb->insertSeparator();
- int index = tb->insertCombo(TQStringList(), -1 /*id*/, false /*writable*/, 0 /*signal*/, 0 /*receiver*/, 0 /*slot*/ );
- d->encoding = tb->getCombo( tb->idAt( index ) );
- if ( !d->encoding )
- return;
-
- d->encoding->clear ();
- TQString sEncoding = encoding;
- if (sEncoding.isEmpty())
- sEncoding = TQString::fromLatin1(TDEGlobal::locale()->encoding());
-
- TQStringList encodings (TDEGlobal::charsets()->availableEncodingNames());
- int insert = 0;
- for (uint i=0; i < encodings.count(); i++)
- {
- bool found = false;
- TQTextCodec *codecForEnc = TDEGlobal::charsets()->codecForName(encodings[i], found);
-
- if (found)
- {
- d->encoding->insertItem (encodings[i]);
- if ( (codecForEnc->name() == sEncoding) || (encodings[i] == sEncoding) )
- {
- d->encoding->setCurrentItem(insert);
- }
-
- insert++;
- }
- }
-
-
-}
-
-KEncodingFileDialog::~KEncodingFileDialog()
-{
- delete d;
-}
-
-
-TQString KEncodingFileDialog::selectedEncoding() const
-{
- if (d->encoding)
- return d->encoding->currentText();
- else
- return TQString::null;
-}
-
-
-KEncodingFileDialog::Result KEncodingFileDialog::getOpenFileNameAndEncoding(const TQString& encoding,
- const TQString& startDir,
- const TQString& filter,
- TQWidget *parent, const TQString& caption)
-{
- KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
- "filedialog", true);
-
- dlg.setMode( KFile::File | KFile::LocalOnly );
- dlg.ops->clearHistory();
- dlg.exec();
-
- Result res;
- res.fileNames<<dlg.selectedFile();
- res.encoding=dlg.selectedEncoding();
- return res;
-}
-
-KEncodingFileDialog::Result KEncodingFileDialog::getOpenFileNamesAndEncoding(const TQString& encoding,
- const TQString& startDir,
- const TQString& filter,
- TQWidget *parent,
- const TQString& caption)
-{
- KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
- "filedialog", true);
- dlg.setMode(KFile::Files | KFile::LocalOnly);
- dlg.ops->clearHistory();
- dlg.exec();
-
- Result res;
- res.fileNames=dlg.selectedFiles();
- res.encoding=dlg.selectedEncoding();
- return res;
-}
-
-KEncodingFileDialog::Result KEncodingFileDialog::getOpenURLAndEncoding(const TQString& encoding, const TQString& startDir,
- const TQString& filter, TQWidget *parent, const TQString& caption)
-{
- KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
- "filedialog", true);
-
- dlg.setMode( KFile::File );
- dlg.ops->clearHistory();
- dlg.exec();
-
- Result res;
- res.URLs<<dlg.selectedURL();
- res.encoding=dlg.selectedEncoding();
- return res;
-}
-
-KEncodingFileDialog::Result KEncodingFileDialog::getOpenURLsAndEncoding(const TQString& encoding, const TQString& startDir,
- const TQString& filter,
- TQWidget *parent,
- const TQString& caption)
-{
- KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
- "filedialog", true);
-
- dlg.setMode(KFile::Files);
- dlg.ops->clearHistory();
- dlg.exec();
-
- Result res;
- res.URLs=dlg.selectedURLs();
- res.encoding=dlg.selectedEncoding();
- return res;
-}
-
-
-KEncodingFileDialog::Result KEncodingFileDialog::getSaveFileNameAndEncoding(const TQString& encoding,
- const TQString& dir,
- const TQString& filter,
- TQWidget *parent,
- const TQString& caption)
-{
- bool specialDir = dir.at(0) == ':';
- KEncodingFileDialog dlg(specialDir?dir:TQString::null, encoding,filter,caption.isNull() ? i18n("Save As") : caption,
- Saving,parent, "filedialog", true);
-
- if ( !specialDir )
- dlg.setSelection( dir ); // may also be a filename
- dlg.exec();
-
- TQString filename = dlg.selectedFile();
- if (!filename.isEmpty())
- KRecentDocument::add(filename);
-
- Result res;
- res.fileNames<<filename;
- res.encoding=dlg.selectedEncoding();
- return res;
-}
-
-
-KEncodingFileDialog::Result KEncodingFileDialog::getSaveURLAndEncoding(const TQString& encoding,
- const TQString& dir, const TQString& filter,
- TQWidget *parent, const TQString& caption)
-{
- bool specialDir = dir.at(0) == ':';
- KEncodingFileDialog dlg(specialDir?dir:TQString::null, encoding,filter,caption.isNull() ? i18n("Save As") :
- caption, Saving,parent, "filedialog", true);
-
- if ( !specialDir )
- dlg.setSelection( dir ); // may also be a filename
-
- dlg.exec();
-
- KURL url = dlg.selectedURL();
- if (url.isValid())
- KRecentDocument::add( url );
-
- Result res;
- res.URLs<<url;
- res.encoding=dlg.selectedEncoding();
- return res;
-}
-
-
-
-void KEncodingFileDialog::virtual_hook( int id, void* data )
-{
- KFileDialog::virtual_hook( id, data );
-}
-
-
-#include "kencodingfiledialog.moc"
diff --git a/kio/kfile/kencodingfiledialog.h b/kio/kfile/kencodingfiledialog.h
deleted file mode 100644
index 95daca6ce..000000000
--- a/kio/kfile/kencodingfiledialog.h
+++ /dev/null
@@ -1,313 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2003 Joseph Wenninger <jowenn@kde.org>
- 2003 Andras Mantia <amantia@freemail.hu>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __KENCODINGFILEDIALOG_H__
-#define __KENCODINGFILEDIALOG_H__
-
-#include <kfiledialog.h>
-
-struct KEncodingFileDialogPrivate;
-
-/**
- * Provides a user (and developer) friendly way to
- * select files with support for choosing encoding
- *
- *
- * The dialog has been designed to allow applications to customise it
- * by subclassing. It uses geometry management to ensure that subclasses
- * can easily add children that will be incorporated into the layout.
- */
-
-class TDEIO_EXPORT KEncodingFileDialog : public KFileDialog
-{
- Q_OBJECT
-
-public:
- class Result {
- public:
- TQStringList fileNames;
- KURL::List URLs;
- TQString encoding;
- };
-
- /**
- * Constructs a file dialog for text files with encoding selection possibility.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- *
- * @param encoding The encoding shown in the encoding combo. If it's
- * TQString::null, the global default encoding will be shown.
- *
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- *
- * @param caption The caption of the dialog
- *
- * @param type This can either be
- * @li Opening (open dialog, the default setting)
- * @li Saving
- * @param parent The parent widget of this dialog
- * @param name The name of this object
- * @param modal Whether to create a modal dialog or not
- *
- * @since 3.2
- */
- KEncodingFileDialog (const TQString& startDir = TQString::null,
- const TQString& encoding = TQString::null,
- const TQString& filter = TQString::null,
- const TQString& caption = TQString::null, KFileDialog::OperationMode type = KFileDialog::Opening,
- TQWidget *parent= 0, const char *name="", bool modal = true);
- /**
- * Destructs the file dialog.
- */
- ~KEncodingFileDialog();
-
-
- /**
- * @returns The selected encoding if the constructor with the encoding parameter was used, otherwise TQString::null.
- */
- TQString selectedEncoding() const;
-
-
- /**
- * Creates a modal file dialog and return the selected
- * filename or an empty string if none was chosen additionally a chosen
- * encoding value is returned.
- *
- * Note that with
- * this method the user must select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param encoding The encoding shown in the encoding combo.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static Result getOpenFileNameAndEncoding(const TQString& encoding=TQString::null,
- const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
- /**
- * Creates a modal file dialog and returns the selected encoding and the selected
- * filenames or an empty list if none was chosen.
- *
- * Note that with
- * this method the user must select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param encoding The encoding shown in the encoding combo.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this.
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static Result getOpenFileNamesAndEncoding(const TQString& encoding=TQString::null,
- const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent = 0,
- const TQString& caption= TQString::null);
-
- /**
- * Creates a modal file dialog and returns the selected encoding and
- * URL or an empty string if none was chosen.
- *
- * Note that with
- * this method the user must select an existing URL.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param encoding The encoding shown in the encoding combo.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static Result getOpenURLAndEncoding(const TQString& encoding=TQString::null,
- const TQString& startDir = TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
-
-
-
- /**
- * Creates a modal file dialog and returns the selected encoding
- * URLs or an empty list if none was chosen.
- *
- * Note that with
- * this method the user must select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param encoding The encoding shown in the encoding combo.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static Result getOpenURLsAndEncoding(const TQString& encoding=TQString::null,
- const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent = 0,
- const TQString& caption= TQString::null);
-
-
-
- /**
- * Creates a modal file dialog and returns the selected encoding and
- * filename or an empty string if none was chosen.
- *
- * Note that with this
- * method the user need not select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li a relative path or a filename determining the
- * directory to start in and the file to be selected.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param encoding The encoding shown in the encoding combo.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static Result getSaveFileNameAndEncoding(const TQString& encoding=TQString::null,
- const TQString& startDir=TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
-
- /**
- * Creates a modal file dialog and returns the selected encoding and
- * filename or an empty string if none was chosen.
- *
- * Note that with this
- * method the user need not select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li a relative path or a filename determining the
- * directory to start in and the file to be selected.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param encoding The encoding shown in the encoding combo.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static Result getSaveURLAndEncoding(const TQString& encoding=TQString::null,
- const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
-
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- KEncodingFileDialogPrivate *d;
-};
-
-#endif
diff --git a/kio/kfile/kfile.h b/kio/kfile/kfile.h
deleted file mode 100644
index 7209a1d25..000000000
--- a/kio/kfile/kfile.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- version 2, License as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef KFILE_H
-#define KFILE_H
-
-#include <tqdir.h>
-
-#include "tdelibs_export.h"
-
-/**
- * KFile is a class which provides a namespace for some enumerated
- * values associated with the kfile library. You will never need to
- * construct a KFile object itself.
- */
-
-class TDEIO_EXPORT KFile
-{
-public:
- /**
- * Modes of operation for the dialog.
- * @li @p File - Get a single file name from the user.
- * @li @p Directory - Get a directory name from the user.
- * @li @p Files - Get multiple file names from the user.
- * @li @p ExistingOnly - Never return a filename which does not exist yet
- * @li @p LocalOnly - Don't return remote filenames
- */
- enum Mode {
- File = 1,
- Directory = 2,
- Files = 4,
- ExistingOnly = 8,
- LocalOnly = 16,
- ModeMax = 65536
- };
-
- enum FileView {
- Default = 0,
- Simple = 1,
- Detail = 2,
- SeparateDirs = 4,
- PreviewContents = 8,
- PreviewInfo = 16,
- FileViewMax = 65536
- };
-
- enum SelectionMode {
- Single = 1,
- Multi = 2,
- Extended = 4,
- NoSelection = 8
- };
-
-
- //
- // some bittests
- //
-
-
- // sorting specific
-
- // grr, who had the idea to set TQDir::Name to 0x0?
- static bool isSortByName( const TQDir::SortSpec& sort ) {
- return (sort & TQDir::Time) != TQDir::Time &&
- (sort & TQDir::Size) != TQDir::Size;
- }
-
- static bool isSortBySize( const TQDir::SortSpec& sort ) {
- return (sort & TQDir::Size) == TQDir::Size;
- }
-
- static bool isSortByDate( const TQDir::SortSpec& sort ) {
- return (sort & TQDir::Time) == TQDir::Time;
- }
-
- static bool isSortDirsFirst( const TQDir::SortSpec& sort ) {
- return (sort & TQDir::DirsFirst) == TQDir::DirsFirst;
- }
-
- static bool isSortCaseInsensitive( const TQDir::SortSpec& sort ) {
- return (sort & TQDir::IgnoreCase) == TQDir::IgnoreCase;
- }
-
-
- // view specific
- static bool isDefaultView( const FileView& view ) {
- return (view & Default) == Default;
- }
-
- static bool isSimpleView( const FileView& view ) {
- return (view & Simple) == Simple;
- }
-
- static bool isDetailView( const FileView& view ) {
- return (view & Detail) == Detail;
- }
-
- static bool isSeparateDirs( const FileView& view ) {
- return (view & SeparateDirs) == SeparateDirs;
- }
-
- static bool isPreviewContents( const FileView& view ) {
- return (view & PreviewContents) == PreviewContents;
- }
-
- /**
- * @since 3.1
- */
- static bool isPreviewInfo( const FileView& view ) {
- return (view & PreviewInfo) == PreviewInfo;
- }
-
-};
-
-#endif // KFILE_H
diff --git a/kio/kfile/kfilebookmarkhandler.cpp b/kio/kfile/kfilebookmarkhandler.cpp
deleted file mode 100644
index f78fe2547..000000000
--- a/kio/kfile/kfilebookmarkhandler.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation, version 2.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <kbookmarkimporter.h>
-#include <kbookmarkdombuilder.h>
-#include <kpopupmenu.h>
-#include <kstandarddirs.h>
-
-#include "kfiledialog.h"
-#include "kfilebookmarkhandler.h"
-
-KFileBookmarkHandler::KFileBookmarkHandler( KFileDialog *dialog )
- : TQObject( dialog, "KFileBookmarkHandler" ),
- KBookmarkOwner(),
- m_dialog( dialog )
-{
- m_menu = new KPopupMenu( dialog, "bookmark menu" );
-
- TQString file = locate( "data", "kfile/bookmarks.xml" );
- if ( file.isEmpty() )
- file = locateLocal( "data", "kfile/bookmarks.xml" );
-
- KBookmarkManager *manager = KBookmarkManager::managerForFile( file, false);
-
- // import old bookmarks
- if ( !KStandardDirs::exists( file ) ) {
- TQString oldFile = locate( "data", "kfile/bookmarks.html" );
- if ( !oldFile.isEmpty() )
- importOldBookmarks( oldFile, manager );
- }
-
- manager->setUpdate( true );
- manager->setShowNSBookmarks( false );
-
- m_bookmarkMenu = new KBookmarkMenu( manager, this, m_menu,
- dialog->actionCollection(), true );
-}
-
-KFileBookmarkHandler::~KFileBookmarkHandler()
-{
- delete m_bookmarkMenu;
-}
-
-TQString KFileBookmarkHandler::currentURL() const
-{
- return m_dialog->baseURL().url();
-}
-
-void KFileBookmarkHandler::importOldBookmarks( const TQString& path,
- KBookmarkManager *manager )
-{
- KBookmarkDomBuilder *builder = new KBookmarkDomBuilder( manager->root(), manager );
- KNSBookmarkImporter importer( path );
- builder->connectImporter( &importer );
- importer.parseNSBookmarks();
- delete builder;
- manager->save();
-}
-
-void KFileBookmarkHandler::virtual_hook( int id, void* data )
-{ KBookmarkOwner::virtual_hook( id, data ); }
-
-#include "kfilebookmarkhandler.moc"
diff --git a/kio/kfile/kfiledetailview.cpp b/kio/kfile/kfiledetailview.cpp
deleted file mode 100644
index da61d0a9f..000000000
--- a/kio/kfile/kfiledetailview.cpp
+++ /dev/null
@@ -1,686 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
- 2000, 2001 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqevent.h>
-#include <tqkeycode.h>
-#include <tqheader.h>
-#include <tqpainter.h>
-#include <tqpixmap.h>
-
-#include <kapplication.h>
-#include <kfileitem.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <kiconloader.h>
-#include <kicontheme.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <kurldrag.h>
-
-#include "kfiledetailview.h"
-#include "config-kfile.h"
-
-#define COL_NAME 0
-#define COL_SIZE 1
-#define COL_DATE 2
-#define COL_PERM 3
-#define COL_OWNER 4
-#define COL_GROUP 5
-
-class KFileDetailView::KFileDetailViewPrivate
-{
-public:
- KFileDetailViewPrivate() : dropItem(0)
- { }
-
- KFileListViewItem *dropItem;
- TQTimer autoOpenTimer;
-};
-
-KFileDetailView::KFileDetailView(TQWidget *parent, const char *name)
- : KListView(parent, name), KFileView(), d(new KFileDetailViewPrivate())
-{
- // this is always the static section, not the index depending on column order
- m_sortingCol = COL_NAME;
- m_blockSortingSignal = false;
- setViewName( i18n("Detailed View") );
-
- addColumn( i18n( "Name" ) );
- addColumn( i18n( "Size" ) );
- addColumn( i18n( "Date" ) );
- addColumn( i18n( "Permissions" ) );
- addColumn( i18n( "Owner" ) );
- addColumn( i18n( "Group" ) );
- setShowSortIndicator( true );
- setAllColumnsShowFocus( true );
- setDragEnabled(true);
-
- connect( header(), TQT_SIGNAL( clicked(int)),
- TQT_SLOT(slotSortingChanged(int) ));
-
-
- connect( this, TQT_SIGNAL( returnPressed(TQListViewItem *) ),
- TQT_SLOT( slotActivate( TQListViewItem *) ) );
-
- connect( this, TQT_SIGNAL( clicked(TQListViewItem *, const TQPoint&, int)),
- TQT_SLOT( selected( TQListViewItem *) ) );
- connect( this, TQT_SIGNAL( doubleClicked(TQListViewItem *, const TQPoint&, int)),
- TQT_SLOT( slotActivate( TQListViewItem *) ) );
-
- connect( this, TQT_SIGNAL(contextMenuRequested( TQListViewItem *,
- const TQPoint &, int )),
- this, TQT_SLOT( slotActivateMenu( TQListViewItem *, const TQPoint& )));
-
- KFile::SelectionMode sm = KFileView::selectionMode();
- switch ( sm ) {
- case KFile::Multi:
- TQListView::setSelectionMode( TQListView::Multi );
- break;
- case KFile::Extended:
- TQListView::setSelectionMode( TQListView::Extended );
- break;
- case KFile::NoSelection:
- TQListView::setSelectionMode( TQListView::NoSelection );
- break;
- default: // fall through
- case KFile::Single:
- TQListView::setSelectionMode( TQListView::Single );
- break;
- }
-
- // for highlighting
- if ( sm == KFile::Multi || sm == KFile::Extended )
- connect( this, TQT_SIGNAL( selectionChanged() ),
- TQT_SLOT( slotSelectionChanged() ));
- else
- connect( this, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ),
- TQT_SLOT( highlighted( TQListViewItem * ) ));
-
- // DND
- connect( &(d->autoOpenTimer), TQT_SIGNAL( timeout() ),
- this, TQT_SLOT( slotAutoOpen() ));
-
- setSorting( sorting() );
-
- m_resolver =
- new KMimeTypeResolver<KFileListViewItem,KFileDetailView>( this );
-}
-
-KFileDetailView::~KFileDetailView()
-{
- delete m_resolver;
- delete d;
-}
-
-void KFileDetailView::readConfig( TDEConfig *config, const TQString& group )
-{
- restoreLayout( config, group );
-}
-
-void KFileDetailView::writeConfig( TDEConfig *config, const TQString& group )
-{
- saveLayout( config, group );
-}
-
-void KFileDetailView::setSelected( const KFileItem *info, bool enable )
-{
- if ( !info )
- return;
-
- // we can only hope that this casts works
- KFileListViewItem *item = (KFileListViewItem*)info->extraData( this );
-
- if ( item )
- KListView::setSelected( item, enable );
-}
-
-void KFileDetailView::setCurrentItem( const KFileItem *item )
-{
- if ( !item )
- return;
- KFileListViewItem *it = (KFileListViewItem*) item->extraData( this );
- if ( it )
- KListView::setCurrentItem( it );
-}
-
-KFileItem * KFileDetailView::currentFileItem() const
-{
- KFileListViewItem *current = static_cast<KFileListViewItem*>( currentItem() );
- if ( current )
- return current->fileInfo();
-
- return 0L;
-}
-
-void KFileDetailView::clearSelection()
-{
- KListView::clearSelection();
-}
-
-void KFileDetailView::selectAll()
-{
- if (KFileView::selectionMode() == KFile::NoSelection ||
- KFileView::selectionMode() == KFile::Single)
- return;
-
- KListView::selectAll( true );
-}
-
-void KFileDetailView::invertSelection()
-{
- KListView::invertSelection();
-}
-
-void KFileDetailView::slotActivateMenu (TQListViewItem *item,const TQPoint& pos )
-{
- if ( !item ) {
- sig->activateMenu( 0, pos );
- return;
- }
- KFileListViewItem *i = (KFileListViewItem*) item;
- sig->activateMenu( i->fileInfo(), pos );
-}
-
-void KFileDetailView::clearView()
-{
- m_resolver->m_lstPendingMimeIconItems.clear();
- KListView::clear();
-}
-
-void KFileDetailView::insertItem( KFileItem *i )
-{
- KFileView::insertItem( i );
-
- KFileListViewItem *item = new KFileListViewItem( (TQListView*) this, i );
-
- setSortingKey( item, i );
-
- i->setExtraData( this, item );
-
- if ( !i->isMimeTypeKnown() )
- m_resolver->m_lstPendingMimeIconItems.append( item );
-}
-
-void KFileDetailView::slotActivate( TQListViewItem *item )
-{
- if ( !item )
- return;
-
- const KFileItem *fi = ( (KFileListViewItem*)item )->fileInfo();
- if ( fi )
- sig->activate( fi );
-}
-
-void KFileDetailView::selected( TQListViewItem *item )
-{
- if ( !item )
- return;
-
- if ( TDEGlobalSettings::singleClick() ) {
- const KFileItem *fi = ( (KFileListViewItem*)item )->fileInfo();
- if ( fi && (fi->isDir() || !onlyDoubleClickSelectsFiles()) )
- sig->activate( fi );
- }
-}
-
-void KFileDetailView::highlighted( TQListViewItem *item )
-{
- if ( !item )
- return;
-
- const KFileItem *fi = ( (KFileListViewItem*)item )->fileInfo();
- if ( fi )
- sig->highlightFile( fi );
-}
-
-
-void KFileDetailView::setSelectionMode( KFile::SelectionMode sm )
-{
- disconnect( this, TQT_SIGNAL( selectionChanged() ));
- disconnect( this, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ));
-
- KFileView::setSelectionMode( sm );
-
- switch ( KFileView::selectionMode() ) {
- case KFile::Multi:
- TQListView::setSelectionMode( TQListView::Multi );
- break;
- case KFile::Extended:
- TQListView::setSelectionMode( TQListView::Extended );
- break;
- case KFile::NoSelection:
- TQListView::setSelectionMode( TQListView::NoSelection );
- break;
- default: // fall through
- case KFile::Single:
- TQListView::setSelectionMode( TQListView::Single );
- break;
- }
-
- if ( sm == KFile::Multi || sm == KFile::Extended )
- connect( this, TQT_SIGNAL( selectionChanged() ),
- TQT_SLOT( slotSelectionChanged() ));
- else
- connect( this, TQT_SIGNAL( selectionChanged( TQListViewItem * )),
- TQT_SLOT( highlighted( TQListViewItem * )));
-}
-
-bool KFileDetailView::isSelected( const KFileItem *i ) const
-{
- if ( !i )
- return false;
-
- KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
- return (item && item->isSelected());
-}
-
-
-void KFileDetailView::updateView( bool b )
-{
- if ( !b )
- return;
-
- TQListViewItemIterator it( (TQListView*)this );
- for ( ; it.current(); ++it ) {
- KFileListViewItem *item=static_cast<KFileListViewItem *>(it.current());
- item->setPixmap( 0, item->fileInfo()->pixmap(KIcon::SizeSmall) );
- }
-}
-
-void KFileDetailView::updateView( const KFileItem *i )
-{
- if ( !i )
- return;
-
- KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
- if ( !item )
- return;
-
- item->init();
- setSortingKey( item, i );
-
- //item->repaint(); // only repaints if visible
-}
-
-void KFileDetailView::setSortingKey( KFileListViewItem *item,
- const KFileItem *i )
-{
- // see also setSorting()
- TQDir::SortSpec spec = KFileView::sorting();
-
- if ( spec & TQDir::Time )
- item->setKey( sortingKey( i->time( TDEIO::UDS_MODIFICATION_TIME ),
- i->isDir(), spec ));
- else if ( spec & TQDir::Size )
- item->setKey( sortingKey( i->size(), i->isDir(), spec ));
-
- else // Name or Unsorted
- item->setKey( sortingKey( i->text(), i->isDir(), spec ));
-}
-
-
-void KFileDetailView::removeItem( const KFileItem *i )
-{
- if ( !i )
- return;
-
- KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
- m_resolver->m_lstPendingMimeIconItems.remove( item );
- delete item;
-
- KFileView::removeItem( i );
-}
-
-void KFileDetailView::slotSortingChanged( int col )
-{
- // col is the section here, not the index!
-
- TQDir::SortSpec sort = sorting();
- int sortSpec = -1;
- bool reversed = (col == m_sortingCol) && (sort & TQDir::Reversed) == 0;
- m_sortingCol = col;
-
- switch( col ) {
- case COL_NAME:
- sortSpec = (sort & ~TQDir::SortByMask | TQDir::Name);
- break;
- case COL_SIZE:
- sortSpec = (sort & ~TQDir::SortByMask | TQDir::Size);
- break;
- case COL_DATE:
- sortSpec = (sort & ~TQDir::SortByMask | TQDir::Time);
- break;
-
- // the following columns have no equivalent in TQDir, so we set it
- // to TQDir::Unsorted and remember the column (m_sortingCol)
- case COL_OWNER:
- case COL_GROUP:
- case COL_PERM:
- // grmbl, TQDir::Unsorted == SortByMask.
- sortSpec = (sort & ~TQDir::SortByMask);// | TQDir::Unsorted;
- break;
- default:
- break;
- }
-
- if ( reversed )
- sortSpec |= TQDir::Reversed;
- else
- sortSpec &= ~TQDir::Reversed;
-
- if ( sort & TQDir::IgnoreCase )
- sortSpec |= TQDir::IgnoreCase;
- else
- sortSpec &= ~TQDir::IgnoreCase;
-
-
- KFileView::setSorting( static_cast<TQDir::SortSpec>( sortSpec ) );
-
- KFileItem *item;
- KFileItemListIterator it( *items() );
-
- if ( sortSpec & TQDir::Time ) {
- for ( ; (item = it.current()); ++it )
- viewItem(item)->setKey( sortingKey( item->time( TDEIO::UDS_MODIFICATION_TIME ), item->isDir(), sortSpec ));
- }
-
- else if ( sortSpec & TQDir::Size ) {
- for ( ; (item = it.current()); ++it )
- viewItem(item)->setKey( sortingKey( item->size(), item->isDir(),
- sortSpec ));
- }
- else { // Name or Unsorted -> use column text
- for ( ; (item = it.current()); ++it ) {
- KFileListViewItem *i = viewItem( item );
- i->setKey( sortingKey( i->text(m_sortingCol), item->isDir(),
- sortSpec ));
- }
- }
-
- KListView::setSorting( m_sortingCol, !reversed );
- KListView::sort();
-
- if ( !m_blockSortingSignal )
- sig->changeSorting( static_cast<TQDir::SortSpec>( sortSpec ) );
-}
-
-
-void KFileDetailView::setSorting( TQDir::SortSpec spec )
-{
- int col = 0;
- if ( spec & TQDir::Time )
- col = COL_DATE;
- else if ( spec & TQDir::Size )
- col = COL_SIZE;
- else if ( spec & TQDir::Unsorted )
- col = m_sortingCol;
- else
- col = COL_NAME;
-
- // inversed, because slotSortingChanged will reverse it
- if ( spec & TQDir::Reversed )
- spec = (TQDir::SortSpec) (spec & ~TQDir::Reversed);
- else
- spec = (TQDir::SortSpec) (spec | TQDir::Reversed);
-
- m_sortingCol = col;
- KFileView::setSorting( (TQDir::SortSpec) spec );
-
-
- // don't emit sortingChanged() when called via setSorting()
- m_blockSortingSignal = true; // can't use blockSignals()
- slotSortingChanged( col );
- m_blockSortingSignal = false;
-}
-
-void KFileDetailView::ensureItemVisible( const KFileItem *i )
-{
- if ( !i )
- return;
-
- KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
-
- if ( item )
- KListView::ensureItemVisible( item );
-}
-
-// we're in multiselection mode
-void KFileDetailView::slotSelectionChanged()
-{
- sig->highlightFile( 0L );
-}
-
-KFileItem * KFileDetailView::firstFileItem() const
-{
- KFileListViewItem *item = static_cast<KFileListViewItem*>( firstChild() );
- if ( item )
- return item->fileInfo();
- return 0L;
-}
-
-KFileItem * KFileDetailView::nextItem( const KFileItem *fileItem ) const
-{
- if ( fileItem ) {
- KFileListViewItem *item = viewItem( fileItem );
- if ( item && item->itemBelow() )
- return ((KFileListViewItem*) item->itemBelow())->fileInfo();
- else
- return 0L;
- }
- else
- return firstFileItem();
-}
-
-KFileItem * KFileDetailView::prevItem( const KFileItem *fileItem ) const
-{
- if ( fileItem ) {
- KFileListViewItem *item = viewItem( fileItem );
- if ( item && item->itemAbove() )
- return ((KFileListViewItem*) item->itemAbove())->fileInfo();
- else
- return 0L;
- }
- else
- return firstFileItem();
-}
-
-void KFileDetailView::keyPressEvent( TQKeyEvent *e )
-{
- KListView::keyPressEvent( e );
-
- if ( e->key() == Key_Return || e->key() == Key_Enter ) {
- if ( e->state() & ControlButton )
- e->ignore();
- else
- e->accept();
- }
-}
-
-//
-// mimetype determination on demand
-//
-void KFileDetailView::mimeTypeDeterminationFinished()
-{
- // anything to do?
-}
-
-void KFileDetailView::determineIcon( KFileListViewItem *item )
-{
- (void) item->fileInfo()->determineMimeType();
- updateView( item->fileInfo() );
-}
-
-void KFileDetailView::listingCompleted()
-{
- m_resolver->start();
-}
-
-TQDragObject *KFileDetailView::dragObject()
-{
- // create a list of the URL:s that we want to drag
- KURL::List urls;
- KFileItemListIterator it( * KFileView::selectedItems() );
- for ( ; it.current(); ++it ){
- urls.append( (*it)->url() );
- }
- TQPixmap pixmap;
- if( urls.count() > 1 )
- pixmap = DesktopIcon( "tdemultiple", KIcon::SizeSmall );
- if( pixmap.isNull() )
- pixmap = currentFileItem()->pixmap( KIcon::SizeSmall );
-
- TQPoint hotspot;
- hotspot.setX( pixmap.width() / 2 );
- hotspot.setY( pixmap.height() / 2 );
- TQDragObject* myDragObject = new KURLDrag( urls, widget() );
- myDragObject->setPixmap( pixmap, hotspot );
- return myDragObject;
-}
-
-void KFileDetailView::slotAutoOpen()
-{
- d->autoOpenTimer.stop();
- if( !d->dropItem )
- return;
-
- KFileItem *fileItem = d->dropItem->fileInfo();
- if (!fileItem)
- return;
-
- if( fileItem->isFile() )
- return;
-
- if ( fileItem->isDir() || fileItem->isLink())
- sig->activate( fileItem );
-}
-
-bool KFileDetailView::acceptDrag(TQDropEvent* e) const
-{
- return KURLDrag::canDecode( e ) &&
- (e->source()!= const_cast<KFileDetailView*>(this)) &&
- ( e->action() == TQDropEvent::Copy
- || e->action() == TQDropEvent::Move
- || e->action() == TQDropEvent::Link );
-}
-
-void KFileDetailView::contentsDragEnterEvent( TQDragEnterEvent *e )
-{
- if ( ! acceptDrag( e ) ) { // can we decode this ?
- e->ignore(); // No
- return;
- }
- e->acceptAction(); // Yes
-
- if ((dropOptions() & AutoOpenDirs) == 0)
- return;
-
- KFileListViewItem *item = dynamic_cast<KFileListViewItem*>(itemAt( contentsToViewport( e->pos() ) ));
- if ( item ) { // are we over an item ?
- d->dropItem = item;
- d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
- }
- else
- {
- d->dropItem = 0;
- d->autoOpenTimer.stop();
- }
-}
-
-void KFileDetailView::contentsDragMoveEvent( TQDragMoveEvent *e )
-{
- if ( ! acceptDrag( e ) ) { // can we decode this ?
- e->ignore(); // No
- return;
- }
- e->acceptAction(); // Yes
-
- if ((dropOptions() & AutoOpenDirs) == 0)
- return;
-
- KFileListViewItem *item = dynamic_cast<KFileListViewItem*>(itemAt( contentsToViewport( e->pos() ) ));
- if ( item ) { // are we over an item ?
- if (d->dropItem != item)
- {
- d->dropItem = item;
- d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
- }
- }
- else
- {
- d->dropItem = 0;
- d->autoOpenTimer.stop();
- }
-}
-
-void KFileDetailView::contentsDragLeaveEvent( TQDragLeaveEvent * )
-{
- d->dropItem = 0;
- d->autoOpenTimer.stop();
-}
-
-void KFileDetailView::contentsDropEvent( TQDropEvent *e )
-{
- d->dropItem = 0;
- d->autoOpenTimer.stop();
-
- if ( ! acceptDrag( e ) ) { // can we decode this ?
- e->ignore(); // No
- return;
- }
- e->acceptAction(); // Yes
-
- KFileListViewItem *item = dynamic_cast<KFileListViewItem*>(itemAt( contentsToViewport( e->pos() ) ));
- KFileItem * fileItem = 0;
- if (item)
- fileItem = item->fileInfo();
-
- emit dropped(e, fileItem);
-
- KURL::List urls;
- if (KURLDrag::decode( e, urls ) && !urls.isEmpty())
- {
- emit dropped(e, urls, fileItem ? fileItem->url() : KURL());
- sig->dropURLs(fileItem, e, urls);
- }
-}
-
-
-/////////////////////////////////////////////////////////////////
-
-
-void KFileListViewItem::init()
-{
- KFileListViewItem::setPixmap( COL_NAME, inf->pixmap(KIcon::SizeSmall));
-
- setText( COL_NAME, inf->text() );
- setText( COL_SIZE, TDEGlobal::locale()->formatNumber( inf->size(), 0));
- setText( COL_DATE, inf->timeString() );
- setText( COL_PERM, inf->permissionsString() );
- setText( COL_OWNER, inf->user() );
- setText( COL_GROUP, inf->group() );
-}
-
-
-void KFileDetailView::virtual_hook( int id, void* data )
-{ KListView::virtual_hook( id, data );
- KFileView::virtual_hook( id, data ); }
-
-#include "kfiledetailview.moc"
diff --git a/kio/kfile/kfiledetailview.h b/kio/kfile/kfiledetailview.h
deleted file mode 100644
index 37e71720f..000000000
--- a/kio/kfile/kfiledetailview.h
+++ /dev/null
@@ -1,219 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef KFILEDETAILVIEW_H
-#define KFILEDETAILVIEW_H
-
-class KFileItem;
-class TQWidget;
-class TQKeyEvent;
-
-#include <klistview.h>
-#include <kmimetyperesolver.h>
-
-#include "kfileview.h"
-
-/**
- * An item for the listiew, that has a reference to its corresponding
- * KFileItem.
- */
-class TDEIO_EXPORT KFileListViewItem : public KListViewItem
-{
-public:
- KFileListViewItem( TQListView *parent, const TQString &text,
- const TQPixmap &icon, KFileItem *fi )
- : KListViewItem( parent, text ), inf( fi ) {
- setPixmap( 0, icon );
- setText( 0, text );
- }
-
- /**
- * @since 3.1
- */
- KFileListViewItem( TQListView *parent, KFileItem *fi )
- : KListViewItem( parent ), inf( fi ) {
- init();
- }
-
- KFileListViewItem( TQListView *parent, const TQString &text,
- const TQPixmap &icon, KFileItem *fi,
- TQListViewItem *after)
- : KListViewItem( parent, after ), inf( fi ) {
- setPixmap( 0, icon );
- setText( 0, text );
- }
- ~KFileListViewItem() {
- inf->removeExtraData( listView() );
- }
-
- /**
- * @returns the corresponding KFileItem
- */
- KFileItem *fileInfo() const {
- return inf;
- }
-
- virtual TQString key( int /*column*/, bool /*ascending*/ ) const {
- return m_key;
- }
-
- void setKey( const TQString& key ) { m_key = key; }
-
- TQRect rect() const
- {
- TQRect r = listView()->itemRect(this);
- return TQRect( listView()->viewportToContents( r.topLeft() ),
- TQSize( r.width(), r.height() ) );
- }
-
- /**
- * @since 3.1
- */
- void init();
-
-private:
- KFileItem *inf;
- TQString m_key;
-
-private:
- class KFileListViewItemPrivate;
- KFileListViewItemPrivate *d;
-
-};
-
-/**
- * A list-view capable of showing KFileItem'. Used in the filedialog
- * for example. Most of the documentation is in KFileView class.
- *
- * @see KDirOperator
- * @see KCombiView
- * @see KFileIconView
- */
-class TDEIO_EXPORT KFileDetailView : public KListView, public KFileView
-{
- Q_OBJECT
-
-public:
- KFileDetailView(TQWidget *parent, const char *name);
- virtual ~KFileDetailView();
-
- virtual TQWidget *widget() { return this; }
- virtual void clearView();
- virtual void setAutoUpdate( bool ) {} // ### unused. remove in KDE4
-
- virtual void setSelectionMode( KFile::SelectionMode sm );
-
- virtual void updateView( bool );
- virtual void updateView(const KFileItem*);
- virtual void removeItem( const KFileItem *);
- virtual void listingCompleted();
-
- virtual void setSelected(const KFileItem *, bool);
- virtual bool isSelected(const KFileItem *i) const;
- virtual void clearSelection();
- virtual void selectAll();
- virtual void invertSelection();
-
- virtual void setCurrentItem( const KFileItem * );
- virtual KFileItem * currentFileItem() const;
- virtual KFileItem * firstFileItem() const;
- virtual KFileItem * nextItem( const KFileItem * ) const;
- virtual KFileItem * prevItem( const KFileItem * ) const;
-
- virtual void insertItem( KFileItem *i );
-
- // implemented to get noticed about sorting changes (for sortingIndicator)
- virtual void setSorting( TQDir::SortSpec );
-
- void ensureItemVisible( const KFileItem * );
-
- // for KMimeTypeResolver
- void mimeTypeDeterminationFinished();
- void determineIcon( KFileListViewItem *item );
- TQScrollView *scrollWidget() const { return (TQScrollView*) this; }
-
- virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
- virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
-
-signals:
- /**
- * The user dropped something.
- * @p fileItem points to the item dropped on or can be 0 if the
- * user dropped on empty space.
- * @since 3.2
- */
- void dropped(TQDropEvent *event, KFileItem *fileItem);
- /**
- * The user dropped the URLs @p urls.
- * @p url points to the item dropped on or can be empty if the
- * user dropped on empty space.
- * @since 3.2
- */
- void dropped(TQDropEvent *event, const KURL::List &urls, const KURL &url);
-
-protected:
- virtual void keyPressEvent( TQKeyEvent * );
-
- // DND support
- virtual TQDragObject *dragObject();
- virtual void contentsDragEnterEvent( TQDragEnterEvent *e );
- virtual void contentsDragMoveEvent( TQDragMoveEvent *e );
- virtual void contentsDragLeaveEvent( TQDragLeaveEvent *e );
- virtual void contentsDropEvent( TQDropEvent *ev );
- virtual bool acceptDrag(TQDropEvent* e ) const;
-
- int m_sortingCol;
-
-protected slots:
- void slotSelectionChanged();
-
-private slots:
- void slotSortingChanged( int );
- void selected( TQListViewItem *item );
- void slotActivate( TQListViewItem *item );
- void highlighted( TQListViewItem *item );
- void slotActivateMenu ( TQListViewItem *item, const TQPoint& pos );
- void slotAutoOpen();
-
-private:
- virtual void insertItem(TQListViewItem *i) { KListView::insertItem(i); }
- virtual void setSorting(int i, bool b) { KListView::setSorting(i, b); }
- virtual void setSelected(TQListViewItem *i, bool b) { KListView::setSelected(i, b); }
-
- inline KFileListViewItem * viewItem( const KFileItem *item ) const {
- if ( item )
- return (KFileListViewItem *) item->extraData( this );
- return 0L;
- }
-
- void setSortingKey( KFileListViewItem *item, const KFileItem *i );
-
-
- bool m_blockSortingSignal;
- KMimeTypeResolver<KFileListViewItem,KFileDetailView> *m_resolver;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KFileDetailViewPrivate;
- KFileDetailViewPrivate *d;
-};
-
-#endif // KFILEDETAILVIEW_H
diff --git a/kio/kfile/kfiledialog.cpp b/kio/kfile/kfiledialog.cpp
deleted file mode 100644
index 1538d5dbc..000000000
--- a/kio/kfile/kfiledialog.cpp
+++ /dev/null
@@ -1,2380 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1997, 1998 Richard Moore <rich@kde.org>
- 1998 Stephan Kulow <coolo@kde.org>
- 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- 1999,2000,2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
- 2003 Clarence Dang <dang@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kfiledialog.h"
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#include <tqptrcollection.h>
-#include <tqcheckbox.h>
-#include <tqcombobox.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqlineedit.h>
-#include <tqptrlist.h>
-#include <tqpixmap.h>
-#include <tqtextcodec.h>
-#include <tqtooltip.h>
-#include <tqtimer.h>
-#include <tqwhatsthis.h>
-#include <tqfiledialog.h>
-
-#include <kaccel.h>
-#include <kaction.h>
-#include <kapplication.h>
-#include <kcharsets.h>
-#include <kcmdlineargs.h>
-#include <kcompletionbox.h>
-#include <kconfig.h>
-#include <kdebug.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <kiconloader.h>
-#include <kimageio.h>
-#include <kio/job.h>
-#include <kio/netaccess.h>
-#include <kio/scheduler.h>
-#include <kio/kservicetypefactory.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <kmimetype.h>
-#include <kpopupmenu.h>
-#include <kprotocolinfo.h>
-#include <kpushbutton.h>
-#include <krecentdirs.h>
-#include <kshell.h>
-#include <kstandarddirs.h>
-#include <kstdguiitem.h>
-#include <kstaticdeleter.h>
-#include <ktoolbar.h>
-#include <ktoolbarbutton.h>
-#include <kurl.h>
-#include <kurlcombobox.h>
-#include <kurlcompletion.h>
-#include <kuser.h>
-
-#include "config-kfile.h"
-#include "kpreviewwidgetbase.h"
-
-#include <kdirselectdialog.h>
-#include <kfileview.h>
-#include <krecentdocument.h>
-#include <kfilefiltercombo.h>
-#include <kdiroperator.h>
-#include <kimagefilepreview.h>
-
-#include <kfilespeedbar.h>
-#include <kfilebookmarkhandler.h>
-
-#ifdef Q_WS_X11
-#include <X11/Xlib.h>
-#include <fixx11h.h>
-#endif
-
-enum Buttons { HOTLIST_BUTTON,
- PATH_COMBO, CONFIGURE_BUTTON };
-
-template class TQPtrList<TDEIO::StatJob>;
-
-namespace {
- static void silenceQToolBar(TQtMsgType, const char *)
- {
- }
-}
-
-struct KFileDialogPrivate
-{
- // the last selected url
- KURL url;
-
- // the selected filenames in multiselection mode -- FIXME
- TQString filenames;
-
- // the name of the filename set by setSelection
- TQString selection;
-
- // now following all kind of widgets, that I need to rebuild
- // the geometry management
- TQBoxLayout *boxLayout;
- TQWidget *mainWidget;
-
- TQLabel *locationLabel;
-
- // @deprecated remove in KDE4
- TQLabel *filterLabel;
- KURLComboBox *pathCombo;
- KPushButton *okButton, *cancelButton;
- KFileSpeedBar *urlBar;
- TQHBoxLayout *urlBarLayout;
- TQWidget *customWidget;
-
- // Automatically Select Extension stuff
- TQCheckBox *autoSelectExtCheckBox;
- bool autoSelectExtChecked; // whether or not the _user_ has checked the above box
- TQString extension; // current extension for this filter
-
- TQPtrList<TDEIO::StatJob> statJobs;
-
- KURL::List urlList; //the list of selected urls
-
- TQStringList mimetypes; //the list of possible mimetypes to save as
-
- // indicates if the location edit should be kept or cleared when changing
- // directories
- bool keepLocation :1;
-
- // the KDirOperators view is set in KFileDialog::show(), so to avoid
- // setting it again and again, we have this nice little boolean :)
- bool hasView :1;
-
- bool hasDefaultFilter :1; // necessary for the operationMode
- KFileDialog::OperationMode operationMode;
-
- // The file class used for KRecentDirs
- TQString fileClass;
-
- KFileBookmarkHandler *bookmarkHandler;
-
- // the ID of the path drop down so subclasses can place their custom widgets properly
- int m_pathComboIndex;
-};
-
-KURL *KFileDialog::lastDirectory; // to set the start path
-
-static KStaticDeleter<KURL> ldd;
-
-KFileDialog::KFileDialog(const TQString& startDir, const TQString& filter,
- TQWidget *parent, const char* name, bool modal)
- : KDialogBase( parent, name, modal, TQString::null, 0 )
-{
- init( startDir, filter, 0 );
-}
-
-KFileDialog::KFileDialog(const TQString& startDir, const TQString& filter,
- TQWidget *parent, const char* name, bool modal, TQWidget* widget)
- : KDialogBase( parent, name, modal, TQString::null, 0 )
-{
- init( startDir, filter, widget );
-}
-
-
-KFileDialog::~KFileDialog()
-{
- hide();
-
- TDEConfig *config = TDEGlobal::config();
-
- if (d->urlBar)
- d->urlBar->save( config );
-
- config->sync();
-
- delete d->bookmarkHandler; // Should be deleted before ops!
- delete ops;
- delete d;
-}
-
-void KFileDialog::setLocationLabel(const TQString& text)
-{
- d->locationLabel->setText(text);
-}
-
-void KFileDialog::setFilter(const TQString& filter)
-{
- int pos = filter.find('/');
-
- // Check for an un-escaped '/', if found
- // interpret as a MIME filter.
-
- if (pos > 0 && filter[pos - 1] != '\\') {
- TQStringList filters = TQStringList::split( " ", filter );
- setMimeFilter( filters );
- return;
- }
-
- // Strip the escape characters from
- // escaped '/' characters.
-
- TQString copy (filter);
- for (pos = 0; (pos = copy.find("\\/", pos)) != -1; ++pos)
- copy.remove(pos, 1);
-
- ops->clearFilter();
- filterWidget->setFilter(copy);
- ops->setNameFilter(filterWidget->currentFilter());
- d->hasDefaultFilter = false;
- filterWidget->setEditable( true );
-
- updateAutoSelectExtension ();
-}
-
-TQString KFileDialog::currentFilter() const
-{
- return filterWidget->currentFilter();
-}
-
-// deprecated
-void KFileDialog::setFilterMimeType(const TQString &label,
- const KMimeType::List &types,
- const KMimeType::Ptr &defaultType)
-{
- d->mimetypes.clear();
- d->filterLabel->setText(label);
-
- KMimeType::List::ConstIterator it;
- for( it = types.begin(); it != types.end(); ++it)
- d->mimetypes.append( (*it)->name() );
-
- setMimeFilter( d->mimetypes, defaultType->name() );
-}
-
-void KFileDialog::setMimeFilter( const TQStringList& mimeTypes,
- const TQString& defaultType )
-{
- d->mimetypes = mimeTypes;
- filterWidget->setMimeFilter( mimeTypes, defaultType );
-
- TQStringList types = TQStringList::split(" ", filterWidget->currentFilter());
- types.append( TQString::fromLatin1( "inode/directory" ));
- ops->clearFilter();
- ops->setMimeFilter( types );
- d->hasDefaultFilter = !defaultType.isEmpty();
- filterWidget->setEditable( !d->hasDefaultFilter ||
- d->operationMode != Saving );
-
- updateAutoSelectExtension ();
-}
-
-void KFileDialog::clearFilter()
-{
- d->mimetypes.clear();
- filterWidget->setFilter( TQString::null );
- ops->clearFilter();
- d->hasDefaultFilter = false;
- filterWidget->setEditable( true );
-
- updateAutoSelectExtension ();
-}
-
-TQString KFileDialog::currentMimeFilter() const
-{
- int i = filterWidget->currentItem();
- if (filterWidget->showsAllTypes())
- i--;
-
- if ((i >= 0) && (i < (int) d->mimetypes.count()))
- return d->mimetypes[i];
- return TQString::null; // The "all types" item has no mimetype
-}
-
-KMimeType::Ptr KFileDialog::currentFilterMimeType()
-{
- return KMimeType::mimeType( currentMimeFilter() );
-}
-
-void KFileDialog::setPreviewWidget(const TQWidget *w) {
- ops->setPreviewWidget(w);
- ops->clearHistory();
- d->hasView = true;
-}
-
-void KFileDialog::setPreviewWidget(const KPreviewWidgetBase *w) {
- ops->setPreviewWidget(w);
- ops->clearHistory();
- d->hasView = true;
-}
-
-KURL KFileDialog::getCompleteURL(const TQString &_url)
-{
- TQString url = KShell::tildeExpand(_url);
- KURL u;
-
- if ( KURL::isRelativeURL(url) ) // only a full URL isn't relative. Even /path is.
- {
- if (!url.isEmpty() && !TQDir::isRelativePath(url) ) // absolute path
- u.setPath( url );
- else
- {
- u = ops->url();
- u.addPath( url ); // works for filenames and relative paths
- u.cleanPath(); // fix "dir/.."
- }
- }
- else // complete URL
- u = url;
-
- return u;
-}
-
-// FIXME: check for "existing" flag here?
-void KFileDialog::slotOk()
-{
- kdDebug(kfile_area) << "slotOK\n";
-
- // a list of all selected files/directories (if any)
- // can only be used if the user didn't type any filenames/urls himself
- const KFileItemList *items = ops->selectedItems();
-
- if ( (mode() & KFile::Directory) != KFile::Directory ) {
- if ( locationEdit->currentText().stripWhiteSpace().isEmpty() ) {
- if ( !items || items->isEmpty() )
- {
- TQString msg;
- if ( d->operationMode == Saving )
- msg = i18n("Please specify the filename to save to.");
- else
- msg = i18n("Please select the file to open.");
- KMessageBox::information(this, msg);
- return;
- }
-
- // weird case: the location edit is empty, but there are
- // highlighted files
- else {
-
- bool multi = (mode() & KFile::Files) != 0;
- KFileItemListIterator it( *items );
- TQString endQuote = TQString::fromLatin1("\" ");
- TQString name, files;
- while ( it.current() ) {
- name = (*it)->name();
- if ( multi ) {
- name.prepend( '"' );
- name.append( endQuote );
- }
-
- files.append( name );
- ++it;
- }
- setLocationText( files );
- return;
- }
- }
- }
-
- bool dirOnly = ops->dirOnlyMode();
-
- // we can use our kfileitems, no need to parse anything
- if ( items && !locationEdit->lineEdit()->edited() &&
- !(items->isEmpty() && !dirOnly) ) {
-
- d->urlList.clear();
- d->filenames = TQString::null;
-
- if ( dirOnly ) {
- d->url = ops->url();
- }
- else {
- if ( !(mode() & KFile::Files) ) {// single selection
- d->url = items->getFirst()->url();
- }
-
- else { // multi (dirs and/or files)
- d->url = ops->url();
- KFileItemListIterator it( *items );
- while ( it.current() ) {
- d->urlList.append( (*it)->url() );
- ++it;
- }
- }
- }
-
- KURL url = TDEIO::NetAccess::mostLocalURL(d->url,topLevelWidget());
- if ( (mode() & KFile::LocalOnly) == KFile::LocalOnly &&
- !url.isLocalFile() ) {
-// ### after message freeze, add message for directories!
- KMessageBox::sorry( d->mainWidget,
- i18n("You can only select local files."),
- i18n("Remote Files Not Accepted") );
- return;
- }
-
- d->url = url;
- accept();
- return;
- }
-
-
- KURL selectedURL;
-
- if ( (mode() & KFile::Files) == KFile::Files ) {// multiselection mode
- TQString locationText = locationEdit->currentText();
- if ( locationText.contains( '/' )) {
- // relative path? -> prepend the current directory
- KURL u( ops->url(), KShell::tildeExpand(locationText));
- if ( u.isValid() )
- selectedURL = u;
- else
- selectedURL = ops->url();
- }
- else // simple filename -> just use the current URL
- selectedURL = ops->url();
- }
-
- else {
- selectedURL = getCompleteURL(locationEdit->currentText());
-
- // appendExtension() may change selectedURL
- appendExtension (selectedURL);
- }
-
- if ( !selectedURL.isValid() ) {
- KMessageBox::sorry( d->mainWidget, i18n("%1\ndoes not appear to be a valid URL.\n").arg(d->url.url()), i18n("Invalid URL") );
- return;
- }
-
- KURL url = TDEIO::NetAccess::mostLocalURL(selectedURL,topLevelWidget());
- if ( (mode() & KFile::LocalOnly) == KFile::LocalOnly &&
- !url.isLocalFile() ) {
- KMessageBox::sorry( d->mainWidget,
- i18n("You can only select local files."),
- i18n("Remote Files Not Accepted") );
- return;
- }
-
- d->url = url;
-
- // d->url is a correct URL now
-
- if ( (mode() & KFile::Directory) == KFile::Directory ) {
- kdDebug(kfile_area) << "Directory" << endl;
- bool done = true;
- if ( d->url.isLocalFile() ) {
- if ( locationEdit->currentText().stripWhiteSpace().isEmpty() ) {
- TQFileInfo info( d->url.path() );
- if ( info.isDir() ) {
- d->filenames = TQString::null;
- d->urlList.clear();
- d->urlList.append( d->url );
- accept();
- }
- else if (!info.exists() && (mode() & KFile::File) != KFile::File) {
- // directory doesn't exist, create and enter it
- if ( ops->mkdir( d->url.url(), true ))
- return;
- else
- accept();
- }
- else { // d->url is not a directory,
- // maybe we are in File(s) | Directory mode
- if ( (mode() & KFile::File) == KFile::File ||
- (mode() & KFile::Files) == KFile::Files )
- done = false;
- }
- }
- else // Directory mode, with file[s]/dir[s] selected
- {
- if ( mode() & KFile::ExistingOnly )
- {
- if ( ops->dirOnlyMode() )
- {
- KURL fullURL(d->url, locationEdit->currentText());
- if ( TQFile::exists( fullURL.path() ) )
- {
- d->url = fullURL;
- d->filenames = TQString::null;
- d->urlList.clear();
- accept();
- return;
- }
- else // doesn't exist -> reject
- return;
- }
- }
-
- d->filenames = locationEdit->currentText();
- accept(); // what can we do?
- }
-
- }
- else { // FIXME: remote directory, should we allow that?
-// tqDebug( "**** Selected remote directory: %s", d->url.url().latin1());
- d->filenames = TQString::null;
- d->urlList.clear();
- d->urlList.append( d->url );
-
- if ( mode() & KFile::ExistingOnly )
- done = false;
- else
- accept();
- }
-
- if ( done )
- return;
- }
-
- if (!kapp->authorizeURLAction("open", KURL(), d->url))
- {
- TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, d->url.prettyURL());
- KMessageBox::error( d->mainWidget, msg);
- return;
- }
-
- TDEIO::StatJob *job = 0L;
- d->statJobs.clear();
- d->filenames = KShell::tildeExpand(locationEdit->currentText());
-
- if ( (mode() & KFile::Files) == KFile::Files &&
- !locationEdit->currentText().contains( '/' )) {
- kdDebug(kfile_area) << "Files\n";
- KURL::List list = parseSelectedURLs();
- for ( KURL::List::ConstIterator it = list.begin();
- it != list.end(); ++it )
- {
- if (!kapp->authorizeURLAction("open", KURL(), *it))
- {
- TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, (*it).prettyURL());
- KMessageBox::error( d->mainWidget, msg);
- return;
- }
- }
- for ( KURL::List::ConstIterator it = list.begin();
- it != list.end(); ++it )
- {
- job = TDEIO::stat( *it, !(*it).isLocalFile() );
- job->setWindow (topLevelWidget());
- TDEIO::Scheduler::scheduleJob( job );
- d->statJobs.append( job );
- connect( job, TQT_SIGNAL( result(TDEIO::Job *) ),
- TQT_SLOT( slotStatResult( TDEIO::Job *) ));
- }
- return;
- }
-
- job = TDEIO::stat(d->url,!d->url.isLocalFile());
- job->setWindow (topLevelWidget());
- d->statJobs.append( job );
- connect(job, TQT_SIGNAL(result(TDEIO::Job*)), TQT_SLOT(slotStatResult(TDEIO::Job*)));
-}
-
-
-static bool isDirectory (const TDEIO::UDSEntry &t)
-{
- bool isDir = false;
-
- for (TDEIO::UDSEntry::ConstIterator it = t.begin();
- it != t.end();
- it++)
- {
- if ((*it).m_uds == TDEIO::UDS_FILE_TYPE)
- {
- isDir = S_ISDIR ((mode_t) ((*it).m_long));
- break;
- }
- }
-
- return isDir;
-}
-
-// FIXME : count all errors and show messagebox when d->statJobs.count() == 0
-// in case of an error, we cancel the whole operation (clear d->statJobs and
-// don't call accept)
-void KFileDialog::slotStatResult(TDEIO::Job* job)
-{
- kdDebug(kfile_area) << "slotStatResult" << endl;
- TDEIO::StatJob *sJob = static_cast<TDEIO::StatJob *>( job );
-
- if ( !d->statJobs.removeRef( sJob ) ) {
- return;
- }
-
- int count = d->statJobs.count();
-
- // errors mean in general, the location is no directory ;/
- // Can we be sure that it is exististant at all? (pfeiffer)
- if (sJob->error() && count == 0 && !ops->dirOnlyMode())
- {
- accept();
- return;
- }
-
- TDEIO::UDSEntry t = sJob->statResult();
- if (isDirectory (t))
- {
- if ( ops->dirOnlyMode() )
- {
- d->filenames = TQString::null;
- d->urlList.clear();
- accept();
- }
- else // in File[s] mode, directory means error -> cd into it
- {
- if ( count == 0 ) {
- locationEdit->clearEdit();
- locationEdit->lineEdit()->setEdited( false );
- setURL( sJob->url() );
- }
- }
- d->statJobs.clear();
- return;
- }
- else if ( ops->dirOnlyMode() )
- {
- return; // ### error message?
- }
-
- kdDebug(kfile_area) << "filename " << sJob->url().url() << endl;
-
- if ( count == 0 )
- accept();
-}
-
-void KFileDialog::accept()
-{
- setResult( TQDialog::Accepted ); // parseSelectedURLs() checks that
-
- *lastDirectory = ops->url();
- if (!d->fileClass.isEmpty())
- KRecentDirs::add(d->fileClass, ops->url().url());
-
- // clear the topmost item, we insert it as full path later on as item 1
- locationEdit->changeItem( TQString::null, 0 );
-
- KURL::List list = selectedURLs();
- TQValueListConstIterator<KURL> it = list.begin();
- for ( ; it != list.end(); ++it ) {
- const KURL& url = *it;
- // we strip the last slash (-1) because KURLComboBox does that as well
- // when operating in file-mode. If we wouldn't , dupe-finding wouldn't
- // work.
- TQString file = url.isLocalFile() ? url.path(-1) : url.prettyURL(-1);
-
- // remove dupes
- for ( int i = 1; i < locationEdit->count(); i++ ) {
- if ( locationEdit->text( i ) == file ) {
- locationEdit->removeItem( i-- );
- break;
- }
- }
- locationEdit->insertItem( file, 1 );
- }
-
- TDEConfig *config = TDEGlobal::config();
- config->setForceGlobal( true );
- writeConfig( config, ConfigGroup );
- config->setForceGlobal( false );
-
- saveRecentFiles( config );
- config->sync();
-
- KDialogBase::accept();
-
- addToRecentDocuments();
-
- if ( (mode() & KFile::Files) != KFile::Files ) // single selection
- emit fileSelected(d->url.url());
-
- ops->close();
- emit okClicked();
-}
-
-
-void KFileDialog::fileHighlighted(const KFileItem *i)
-{
- if (i && i->isDir())
- return;
-
-
- if ( (ops->mode() & KFile::Files) != KFile::Files ) {
- if ( !i )
- return;
-
- d->url = i->url();
-
- if ( !locationEdit->hasFocus() ) { // don't disturb while editing
- setLocationText( i->name() );
- }
- emit fileHighlighted(d->url.url());
- }
-
- else {
- multiSelectionChanged();
- emit selectionChanged();
- }
-}
-
-void KFileDialog::fileSelected(const KFileItem *i)
-{
- if (i && i->isDir())
- return;
-
- if ( (ops->mode() & KFile::Files) != KFile::Files ) {
- if ( !i )
- return;
-
- d->url = i->url();
- setLocationText( i->name() );
- }
- else {
- multiSelectionChanged();
- emit selectionChanged();
- }
- slotOk();
-}
-
-
-// I know it's slow to always iterate thru the whole filelist
-// (ops->selectedItems()), but what can we do?
-void KFileDialog::multiSelectionChanged()
-{
- if ( locationEdit->hasFocus() ) // don't disturb
- return;
-
- locationEdit->lineEdit()->setEdited( false );
- KFileItem *item;
- const KFileItemList *list = ops->selectedItems();
- if ( !list ) {
- locationEdit->clearEdit();
- return;
- }
-
- static const TQString &begin = TDEGlobal::staticQString(" \"");
- KFileItemListIterator it ( *list );
- TQString text;
- while ( (item = it.current()) ) {
- text.append( begin ).append( item->name() ).append( '\"' );
- ++it;
- }
-
- setLocationText( text.stripWhiteSpace() );
-}
-
-void KFileDialog::setLocationText( const TQString& text )
-{
- // setCurrentItem() will cause textChanged() being emitted,
- // so slotLocationChanged() will be called. Make sure we don't clear
- // the KDirOperator's view-selection in there
- disconnect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
- this, TQT_SLOT( slotLocationChanged( const TQString& ) ) );
- locationEdit->setCurrentItem( 0 );
- connect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
- TQT_SLOT( slotLocationChanged( const TQString& )) );
- locationEdit->setEditText( text );
-
- // don't change selection when user has clicked on an item
- if ( d->operationMode == Saving && !locationEdit->isVisible())
- setNonExtSelection();
-}
-
-static const char autocompletionWhatsThisText[] = I18N_NOOP("<p>While typing in the text area, you may be presented "
- "with possible matches. "
- "This feature can be controlled by clicking with the right mouse button "
- "and selecting a preferred mode from the <b>Text Completion</b> menu.") "</qt>";
-void KFileDialog::updateLocationWhatsThis (void)
-{
- TQString whatsThisText;
- if (d->operationMode == KFileDialog::Saving)
- {
- whatsThisText = "<qt>" + i18n("This is the name to save the file as.") +
- i18n (autocompletionWhatsThisText);
- }
- else if (ops->mode() & KFile::Files)
- {
- whatsThisText = "<qt>" + i18n("This is the list of files to open. More than "
- "one file can be specified by listing several "
- "files, separated by spaces.") +
- i18n (autocompletionWhatsThisText);
- }
- else
- {
- whatsThisText = "<qt>" + i18n("This is the name of the file to open.") +
- i18n (autocompletionWhatsThisText);
- }
-
- TQWhatsThis::add(d->locationLabel, whatsThisText);
- TQWhatsThis::add(locationEdit, whatsThisText);
-}
-
-void KFileDialog::init(const TQString& startDir, const TQString& filter, TQWidget* widget)
-{
- initStatic();
- d = new KFileDialogPrivate();
-
- d->boxLayout = 0;
- d->keepLocation = false;
- d->operationMode = Opening;
- d->bookmarkHandler = 0;
- d->hasDefaultFilter = false;
- d->hasView = false;
- d->mainWidget = new TQWidget( this, "KFileDialog::mainWidget");
- setMainWidget( d->mainWidget );
- d->okButton = new KPushButton( KStdGuiItem::ok(), d->mainWidget );
- d->okButton->setDefault( true );
- d->cancelButton = new KPushButton(KStdGuiItem::cancel(), d->mainWidget);
- connect( d->okButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOk() ));
- connect( d->cancelButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotCancel() ));
- d->customWidget = widget;
- d->autoSelectExtCheckBox = 0; // delayed loading
- d->autoSelectExtChecked = false;
- d->urlBar = 0; // delayed loading
-
- TQtMsgHandler oldHandler = tqInstallMsgHandler( silenceQToolBar );
- toolbar = new KToolBar( d->mainWidget, "KFileDialog::toolbar", true);
- toolbar->setFlat(true);
- tqInstallMsgHandler( oldHandler );
-
- d->pathCombo = new KURLComboBox( KURLComboBox::Directories, true,
- toolbar, "path combo" );
- TQToolTip::add( d->pathCombo, i18n("Current location") );
- TQWhatsThis::add( d->pathCombo, "<qt>" + i18n("This is the currently listed location. "
- "The drop-down list also lists commonly used locations. "
- "This includes standard locations, such as your home folder, as well as "
- "locations that have been visited recently.") + i18n (autocompletionWhatsThisText));
-
- KURL u;
- u.setPath( TQDir::rootDirPath() );
- TQString text = i18n("Root Folder: %1").arg( u.path() );
- d->pathCombo->addDefaultURL( u,
- KMimeType::pixmapForURL( u, 0, KIcon::Small ),
- text );
-
- u.setPath( TQDir::homeDirPath() );
- text = i18n("Home Folder: %1").arg( u.path( +1 ) );
- d->pathCombo->addDefaultURL( u, KMimeType::pixmapForURL( u, 0, KIcon::Small ),
- text );
-
- KURL docPath;
- docPath.setPath( TDEGlobalSettings::documentPath() );
- if ( (u.path(+1) != docPath.path(+1)) &&
- TQDir(docPath.path(+1)).exists() )
- {
- text = i18n("Documents: %1").arg( docPath.path( +1 ) );
- d->pathCombo->addDefaultURL( docPath,
- KMimeType::pixmapForURL( docPath, 0, KIcon::Small ),
- text );
- }
-
- u.setPath( TDEGlobalSettings::desktopPath() );
- text = i18n("Desktop: %1").arg( u.path( +1 ) );
- d->pathCombo->addDefaultURL( u,
- KMimeType::pixmapForURL( u, 0, KIcon::Small ),
- text );
-
- d->url = getStartURL( startDir, d->fileClass );
- d->selection = d->url.url();
-
- // If local, check it exists. If not, go up until it exists.
- if ( d->url.isLocalFile() )
- {
- if ( !TQFile::exists( d->url.path() ) )
- {
- d->url = d->url.upURL();
- TQDir dir( d->url.path() );
- while ( !dir.exists() )
- {
- d->url = d->url.upURL();
- dir.setPath( d->url.path() );
- }
- }
- }
-
- ops = new KDirOperator(d->url, d->mainWidget, "KFileDialog::ops");
- ops->setOnlyDoubleClickSelectsFiles( true );
- connect(ops, TQT_SIGNAL(urlEntered(const KURL&)),
- TQT_SLOT(urlEntered(const KURL&)));
- connect(ops, TQT_SIGNAL(fileHighlighted(const KFileItem *)),
- TQT_SLOT(fileHighlighted(const KFileItem *)));
- connect(ops, TQT_SIGNAL(fileSelected(const KFileItem *)),
- TQT_SLOT(fileSelected(const KFileItem *)));
- connect(ops, TQT_SIGNAL(finishedLoading()),
- TQT_SLOT(slotLoadingFinished()));
-
- ops->setupMenu(KDirOperator::SortActions |
- KDirOperator::FileActions |
- KDirOperator::ViewActions);
- KActionCollection *coll = ops->actionCollection();
-
- // plug nav items into the toolbar
- coll->action( "up" )->plug( toolbar );
- coll->action( "up" )->setWhatsThis(i18n("<qt>Click this button to enter the parent folder.<p>"
- "For instance, if the current location is file:/home/%1 clicking this "
- "button will take you to file:/home.</qt>").arg( KUser().loginName() ));
- coll->action( "back" )->plug( toolbar );
- coll->action( "back" )->setWhatsThis(i18n("Click this button to move backwards one step in the browsing history."));
- coll->action( "forward" )->plug( toolbar );
- coll->action( "forward" )->setWhatsThis(i18n("Click this button to move forward one step in the browsing history."));
- coll->action( "reload" )->plug( toolbar );
- coll->action( "reload" )->setWhatsThis(i18n("Click this button to reload the contents of the current location."));
- coll->action( "mkdir" )->setShortcut(Key_F10);
- coll->action( "mkdir" )->plug( toolbar );
- coll->action( "mkdir" )->setWhatsThis(i18n("Click this button to create a new folder."));
-
- KToggleAction *showSidebarAction =
- new KToggleAction(i18n("Show Quick Access Navigation Panel"), Key_F9, coll,"toggleSpeedbar");
- showSidebarAction->setCheckedState(i18n("Hide Quick Access Navigation Panel"));
- connect( showSidebarAction, TQT_SIGNAL( toggled( bool ) ),
- TQT_SLOT( toggleSpeedbar( bool )) );
-
- KToggleAction *showBookmarksAction =
- new KToggleAction(i18n("Show Bookmarks"), 0, coll, "toggleBookmarks");
- showBookmarksAction->setCheckedState(i18n("Hide Bookmarks"));
- connect( showBookmarksAction, TQT_SIGNAL( toggled( bool ) ),
- TQT_SLOT( toggleBookmarks( bool )) );
-
- KActionMenu *menu = new KActionMenu( i18n("Configure"), "configure", TQT_TQOBJECT(this), "extra menu" );
- menu->setWhatsThis(i18n("<qt>This is the configuration menu for the file dialog. "
- "Various options can be accessed from this menu including: <ul>"
- "<li>how files are sorted in the list</li>"
- "<li>types of view, including icon and list</li>"
- "<li>showing of hidden files</li>"
- "<li>the Quick Access navigation panel</li>"
- "<li>file previews</li>"
- "<li>separating folders from files</li></ul></qt>"));
- menu->insert( coll->action( "sorting menu" ));
- menu->insert( coll->action( "separator" ));
- coll->action( "short view" )->setShortcut(Key_F6);
- menu->insert( coll->action( "short view" ));
- coll->action( "detailed view" )->setShortcut(Key_F7);
- menu->insert( coll->action( "detailed view" ));
- menu->insert( coll->action( "separator" ));
- coll->action( "show hidden" )->setShortcut(Key_F8);
- menu->insert( coll->action( "show hidden" ));
- menu->insert( showSidebarAction );
- menu->insert( showBookmarksAction );
- coll->action( "preview" )->setShortcut(Key_F11);
- menu->insert( coll->action( "preview" ));
- coll->action( "separate dirs" )->setShortcut(Key_F12);
- menu->insert( coll->action( "separate dirs" ));
-
- menu->setDelayed( false );
- connect( menu->popupMenu(), TQT_SIGNAL( aboutToShow() ),
- ops, TQT_SLOT( updateSelectionDependentActions() ));
- menu->plug( toolbar );
-
- //Insert a separator.
- KToolBarSeparator* spacerWidget = new KToolBarSeparator(Qt::Horizontal, false /*no line*/,
- toolbar);
- d->m_pathComboIndex = toolbar->insertWidget(-1, -1, spacerWidget);
- toolbar->insertWidget(PATH_COMBO, 0, d->pathCombo);
-
-
- toolbar->setItemAutoSized (PATH_COMBO);
- toolbar->setIconText(KToolBar::IconOnly);
- toolbar->setBarPos(KToolBar::Top);
- toolbar->setMovingEnabled(false);
- toolbar->adjustSize();
-
- KURLCompletion *pathCompletionObj = new KURLCompletion( KURLCompletion::DirCompletion );
- d->pathCombo->setCompletionObject( pathCompletionObj );
- d->pathCombo->setAutoDeleteCompletionObject( true );
-
- connect( d->pathCombo, TQT_SIGNAL( urlActivated( const KURL& )),
- this, TQT_SLOT( enterURL( const KURL& ) ));
- connect( d->pathCombo, TQT_SIGNAL( returnPressed( const TQString& )),
- this, TQT_SLOT( enterURL( const TQString& ) ));
-
- TQString whatsThisText;
-
- // the Location label/edit
- d->locationLabel = new TQLabel(i18n("&Location:"), d->mainWidget);
- locationEdit = new KURLComboBox(KURLComboBox::Files, true,
- d->mainWidget, "LocationEdit");
- locationEdit->setSizePolicy(TQSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Fixed));
- connect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
- TQT_SLOT( slotLocationChanged( const TQString& )) );
-
- updateLocationWhatsThis ();
- d->locationLabel->setBuddy(locationEdit);
-
- locationEdit->setFocus();
- KURLCompletion *fileCompletionObj = new KURLCompletion( KURLCompletion::FileCompletion );
- TQString dir = d->url.url(+1);
- pathCompletionObj->setDir( dir );
- fileCompletionObj->setDir( dir );
- locationEdit->setCompletionObject( fileCompletionObj );
- locationEdit->setAutoDeleteCompletionObject( true );
- connect( fileCompletionObj, TQT_SIGNAL( match( const TQString& ) ),
- TQT_SLOT( fileCompletion( const TQString& )) );
-
- connect( locationEdit, TQT_SIGNAL( returnPressed() ),
- this, TQT_SLOT( slotOk()));
- connect(locationEdit, TQT_SIGNAL( activated( const TQString& )),
- this, TQT_SLOT( locationActivated( const TQString& ) ));
-
- // the Filter label/edit
- whatsThisText = i18n("<qt>This is the filter to apply to the file list. "
- "File names that do not match the filter will not be shown.<p>"
- "You may select from one of the preset filters in the "
- "drop down menu, or you may enter a custom filter "
- "directly into the text area.<p>"
- "Wildcards such as * and ? are allowed.</qt>");
- d->filterLabel = new TQLabel(i18n("&Filter:"), d->mainWidget);
- TQWhatsThis::add(d->filterLabel, whatsThisText);
- filterWidget = new KFileFilterCombo(d->mainWidget,
- "KFileDialog::filterwidget");
- filterWidget->setSizePolicy(TQSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Fixed));
- TQWhatsThis::add(filterWidget, whatsThisText);
- setFilter(filter);
- d->filterLabel->setBuddy(filterWidget);
- connect(filterWidget, TQT_SIGNAL(filterChanged()), TQT_SLOT(slotFilterChanged()));
-
- // the Automatically Select Extension checkbox
- // (the text, visibility etc. is set in updateAutoSelectExtension(), which is called by readConfig())
- d->autoSelectExtCheckBox = new TQCheckBox (d->mainWidget);
- connect(d->autoSelectExtCheckBox, TQT_SIGNAL(clicked()), TQT_SLOT(slotAutoSelectExtClicked()));
-
- initGUI(); // activate GM
-
- TDEConfig* config = TDEGlobal::config();
- readRecentFiles( config );
-
- adjustSize();
-
- ops->setViewConfig( config, ConfigGroup );
- readConfig( config, ConfigGroup );
- setSelection(d->selection);
-}
-
-void KFileDialog::initSpeedbar()
-{
- d->urlBar = new KFileSpeedBar( d->mainWidget, "url bar" );
- connect( d->urlBar, TQT_SIGNAL( activated( const KURL& )),
- TQT_SLOT( enterURL( const KURL& )) );
-
- // need to set the current url of the urlbar manually (not via urlEntered()
- // here, because the initial url of KDirOperator might be the same as the
- // one that will be set later (and then urlEntered() won't be emitted).
- // ### REMOVE THIS when KDirOperator's initial URL (in the c'tor) is gone.
- d->urlBar->setCurrentItem( d->url );
-
- d->urlBarLayout->insertWidget( 0, d->urlBar );
-}
-
-void KFileDialog::initGUI()
-{
- delete d->boxLayout; // deletes all sub layouts
-
- d->boxLayout = new TQVBoxLayout( d->mainWidget, 0, KDialog::spacingHint());
- d->boxLayout->addWidget(toolbar, AlignTop);
-
- d->urlBarLayout = new TQHBoxLayout( d->boxLayout ); // needed for the urlBar that may appear
- TQVBoxLayout *vbox = new TQVBoxLayout( d->urlBarLayout );
-
- vbox->addWidget(ops, 4);
- vbox->addSpacing(3);
-
- TQGridLayout* lafBox= new TQGridLayout(2, 3, KDialog::spacingHint());
-
- lafBox->addWidget(d->locationLabel, 0, 0, Qt::AlignVCenter);
- lafBox->addWidget(locationEdit, 0, 1, Qt::AlignVCenter);
- lafBox->addWidget(d->okButton, 0, 2, Qt::AlignVCenter);
-
- lafBox->addWidget(d->filterLabel, 1, 0, Qt::AlignVCenter);
- lafBox->addWidget(filterWidget, 1, 1, Qt::AlignVCenter);
- lafBox->addWidget(d->cancelButton, 1, 2, Qt::AlignVCenter);
-
- lafBox->setColStretch(1, 4);
-
- vbox->addLayout(TQT_TQLAYOUT(lafBox), 0);
- vbox->addSpacing(3);
-
- // add the Automatically Select Extension checkbox
- vbox->addWidget (d->autoSelectExtCheckBox);
- vbox->addSpacing (3);
-
- setTabOrder(ops, d->autoSelectExtCheckBox);
- setTabOrder (d->autoSelectExtCheckBox, locationEdit);
- setTabOrder(locationEdit, filterWidget);
- setTabOrder(filterWidget, d->okButton);
- setTabOrder(d->okButton, d->cancelButton);
- setTabOrder(d->cancelButton, d->pathCombo);
- setTabOrder(d->pathCombo, ops);
-
- // If a custom widget was specified...
- if ( d->customWidget != 0 )
- {
- // ...add it to the dialog, below the filter list box.
-
- // Change the parent so that this widget is a child of the main widget
- d->customWidget->reparent( d->mainWidget, TQPoint() );
-
- vbox->addWidget( d->customWidget );
- vbox->addSpacing(3);
-
- // FIXME: This should adjust the tab orders so that the custom widget
- // comes after the Cancel button. The code appears to do this, but the result
- // somehow screws up the tab order of the file path combo box. Not a major
- // problem, but ideally the tab order with a custom widget should be
- // the same as the order without one.
- setTabOrder(d->cancelButton, d->customWidget);
- setTabOrder(d->customWidget, d->pathCombo);
- }
- else
- {
- setTabOrder(d->cancelButton, d->pathCombo);
- }
-
- setTabOrder(d->pathCombo, ops);
-}
-
-void KFileDialog::slotFilterChanged()
-{
- TQString filter = filterWidget->currentFilter();
- ops->clearFilter();
-
- if ( filter.find( '/' ) > -1 ) {
- TQStringList types = TQStringList::split( " ", filter );
- types.prepend( "inode/directory" );
- ops->setMimeFilter( types );
- }
- else
- ops->setNameFilter( filter );
-
- ops->updateDir();
-
- updateAutoSelectExtension ();
-
- emit filterChanged( filter );
-}
-
-
-void KFileDialog::setURL(const KURL& url, bool clearforward)
-{
- d->selection = TQString::null;
- ops->setURL( url, clearforward);
-}
-
-// Protected
-void KFileDialog::urlEntered(const KURL& url)
-{
- TQString filename = locationEdit->currentText();
- d->selection = TQString::null;
-
- if ( d->pathCombo->count() != 0 ) { // little hack
- d->pathCombo->setURL( url );
- }
-
- if (url.protocol()=="beagle" && url.path()=="/") {
- d->pathCombo->setEditText("beagle:/<"+i18n("search term")+">");
- d->pathCombo->lineEdit()->setSelection(8,255);
- d->pathCombo->setFocus();
- }
-
- locationEdit->blockSignals( true );
- locationEdit->setCurrentItem( 0 );
- if ( d->keepLocation )
- locationEdit->setEditText( filename );
-
- locationEdit->blockSignals( false );
-
- TQString dir = url.url(+1);
- static_cast<KURLCompletion*>( d->pathCombo->completionObject() )->setDir( dir );
- static_cast<KURLCompletion*>( locationEdit->completionObject() )->setDir( dir );
-
- if ( d->urlBar )
- d->urlBar->setCurrentItem( url );
-}
-
-void KFileDialog::locationActivated( const TQString& url )
-{
- // This guard prevents any URL _typed_ by the user from being interpreted
- // twice (by returnPressed/slotOk and here, activated/locationActivated)
- // after the user presses Enter. Without this, _both_ setSelection and
- // slotOk would "u.addPath( url )" ...so instead we leave it up to just
- // slotOk....
- if (!locationEdit->lineEdit()->edited())
- setSelection( url );
-}
-
-void KFileDialog::enterURL( const KURL& url)
-{
- setURL( url );
-}
-
-void KFileDialog::enterURL( const TQString& url )
-{
- setURL( KURL::fromPathOrURL( KURLCompletion::replacedPath( url, true, true )) );
-}
-
-void KFileDialog::toolbarCallback(int) // SLOT
-{
- /*
- * yes, nothing uses this anymore.
- * it used to be used to show the configure dialog
- */
-}
-
-
-void KFileDialog::setSelection(const TQString& url)
-{
- kdDebug(kfile_area) << "setSelection " << url << endl;
-
- if (url.isEmpty()) {
- d->selection = TQString::null;
- return;
- }
-
- KURL u = getCompleteURL(url);
- if (!u.isValid()) { // if it still is
- kdWarning() << url << " is not a correct argument for setSelection!" << endl;
- return;
- }
-
- if (!KProtocolInfo::supportsListing(u)) {
- locationEdit->lineEdit()->setEdited( true );
- return;
- }
-
- /* we strip the first / from the path to avoid file://usr which means
- * / on host usr
- */
- KFileItem i(KFileItem::Unknown, KFileItem::Unknown, u, true );
- // KFileItem i(u.path());
- if ( i.isDir() && u.isLocalFile() && TQFile::exists( u.path() ) ) {
- // trust isDir() only if the file is
- // local (we cannot stat non-local urls) and if it exists!
- // (as KFileItem does not check if the file exists or not
- // -> the statbuffer is undefined -> isDir() is unreliable) (Simon)
- setURL(u, true);
- }
- else {
- TQString filename = u.url();
- int sep = filename.findRev('/');
- if (sep >= 0) { // there is a / in it
- if ( KProtocolInfo::supportsListing( u )) {
- KURL dir(u);
- dir.setQuery( TQString::null );
- dir.setFileName( TQString::null );
- setURL(dir, true );
- }
-
- // filename must be decoded, or "name with space" would become
- // "name%20with%20space", so we use KURL::fileName()
- filename = u.fileName();
- kdDebug(kfile_area) << "filename " << filename << endl;
- d->selection = filename;
- setLocationText( filename );
-
- // tell the line edit that it has been edited
- // otherwise we won't know this was set by the user
- // and it will be ignored if there has been an
- // auto completion. this caused bugs where automcompletion
- // would start, the user would pick something from the
- // history and then hit Ok only to get the autocompleted
- // selection. OOOPS.
- locationEdit->lineEdit()->setEdited( true );
- }
-
- d->url = ops->url();
- d->url.addPath(filename);
- }
-}
-
-void KFileDialog::slotLoadingFinished()
-{
- if ( !d->selection.isNull() )
- ops->setCurrentItem( d->selection );
-}
-
-// ### remove in KDE4
-void KFileDialog::pathComboChanged( const TQString& )
-{
-}
-void KFileDialog::dirCompletion( const TQString& ) // SLOT
-{
-}
-void KFileDialog::fileCompletion( const TQString& match )
-{
- if ( match.isEmpty() && ops->view() )
- ops->view()->clearSelection();
- else
- ops->setCurrentItem( match );
-}
-
-void KFileDialog::slotLocationChanged( const TQString& text )
-{
- if ( text.isEmpty() && ops->view() )
- ops->view()->clearSelection();
-
- updateFilter();
-}
-
-void KFileDialog::updateStatusLine(int /* dirs */, int /* files */)
-{
- kdWarning() << "KFileDialog::updateStatusLine is deprecated! The status line no longer exists. Do not try and use it!" << endl;
-}
-
-TQString KFileDialog::getOpenFileName(const TQString& startDir,
- const TQString& filter,
- TQWidget *parent, const TQString& caption)
-{
- KFileDialog dlg(startDir, filter, parent, "filedialog", true);
- dlg.setOperationMode( Opening );
-
- dlg.setMode( KFile::File | KFile::LocalOnly );
- dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
-
- dlg.ops->clearHistory();
- dlg.exec();
-
- return dlg.selectedFile();
-}
-
-TQString KFileDialog::getOpenFileNameWId(const TQString& startDir,
- const TQString& filter,
- WId parent_id, const TQString& caption)
-{
- TQWidget* parent = TQT_TQWIDGET(TQWidget::find( parent_id ));
- KFileDialog dlg(startDir, filter, parent, "filedialog", true);
-#ifdef Q_WS_X11
- if( parent == NULL && parent_id != 0 )
- XSetTransientForHint( tqt_xdisplay(), dlg.winId(), parent_id );
-#else
- // TODO
-#endif
-
- dlg.setOperationMode( KFileDialog::Opening );
-
- dlg.setMode( KFile::File | KFile::LocalOnly );
- dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
-
- dlg.ops->clearHistory();
- dlg.exec();
-
- return dlg.selectedFile();
-}
-
-TQStringList KFileDialog::getOpenFileNames(const TQString& startDir,
- const TQString& filter,
- TQWidget *parent,
- const TQString& caption)
-{
- KFileDialog dlg(startDir, filter, parent, "filedialog", true);
- dlg.setOperationMode( Opening );
-
- dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
- dlg.setMode(KFile::Files | KFile::LocalOnly);
- dlg.ops->clearHistory();
- dlg.exec();
-
- return dlg.selectedFiles();
-}
-
-KURL KFileDialog::getOpenURL(const TQString& startDir, const TQString& filter,
- TQWidget *parent, const TQString& caption)
-{
- KFileDialog dlg(startDir, filter, parent, "filedialog", true);
- dlg.setOperationMode( Opening );
-
- dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
- dlg.setMode( KFile::File );
- dlg.ops->clearHistory();
- dlg.exec();
-
- return dlg.selectedURL();
-}
-
-KURL::List KFileDialog::getOpenURLs(const TQString& startDir,
- const TQString& filter,
- TQWidget *parent,
- const TQString& caption)
-{
- KFileDialog dlg(startDir, filter, parent, "filedialog", true);
- dlg.setOperationMode( Opening );
-
- dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
- dlg.setMode(KFile::Files);
- dlg.ops->clearHistory();
- dlg.exec();
-
- return dlg.selectedURLs();
-}
-
-KURL KFileDialog::getExistingURL(const TQString& startDir,
- TQWidget *parent,
- const TQString& caption)
-{
- return KDirSelectDialog::selectDirectory(startDir, false, parent, caption);
-}
-
-TQString KFileDialog::getExistingDirectory(const TQString& startDir,
- TQWidget *parent,
- const TQString& caption)
-{
-#ifdef Q_WS_WIN
- return TQFileDialog::getExistingDirectory(startDir, parent, "getExistingDirectory",
- caption, true, true);
-#else
- KURL url = KDirSelectDialog::selectDirectory(startDir, true, parent,
- caption);
- if ( url.isValid() )
- return url.path();
-
- return TQString::null;
-#endif
-}
-
-KURL KFileDialog::getImageOpenURL( const TQString& startDir, TQWidget *parent,
- const TQString& caption)
-{
- TQStringList mimetypes = KImageIO::mimeTypes( KImageIO::Reading );
- KFileDialog dlg(startDir,
- mimetypes.join(" "),
- parent, "filedialog", true);
- dlg.setOperationMode( Opening );
- dlg.setCaption( caption.isNull() ? i18n("Open") : caption );
- dlg.setMode( KFile::File );
-
- KImageFilePreview *ip = new KImageFilePreview( &dlg );
- dlg.setPreviewWidget( ip );
- dlg.exec();
-
- return dlg.selectedURL();
-}
-
-KURL KFileDialog::selectedURL() const
-{
- if ( result() == TQDialog::Accepted )
- return d->url;
- else
- return KURL();
-}
-
-KURL::List KFileDialog::selectedURLs() const
-{
- KURL::List list;
- if ( result() == TQDialog::Accepted ) {
- if ( (ops->mode() & KFile::Files) == KFile::Files )
- list = parseSelectedURLs();
- else
- list.append( d->url );
- }
- return list;
-}
-
-
-KURL::List& KFileDialog::parseSelectedURLs() const
-{
- if ( d->filenames.isEmpty() ) {
- return d->urlList;
- }
-
- d->urlList.clear();
- if ( d->filenames.contains( '/' )) { // assume _one_ absolute filename
- static const TQString &prot = TDEGlobal::staticQString(":/");
- KURL u;
- if ( d->filenames.find( prot ) != -1 )
- u = d->filenames;
- else
- u.setPath( d->filenames );
-
- if ( u.isValid() )
- d->urlList.append( u );
- else
- KMessageBox::error( d->mainWidget,
- i18n("The chosen filenames do not\n"
- "appear to be valid."),
- i18n("Invalid Filenames") );
- }
-
- else
- d->urlList = tokenize( d->filenames );
-
- d->filenames = TQString::null; // indicate that we parsed that one
-
- return d->urlList;
-}
-
-
-// FIXME: current implementation drawback: a filename can't contain quotes
-KURL::List KFileDialog::tokenize( const TQString& line ) const
-{
- KURL::List urls;
- KURL u( ops->url() );
- TQString name;
-
- int count = line.contains( '"' );
- if ( count == 0 ) { // no " " -> assume one single file
- u.setFileName( line );
- if ( u.isValid() )
- urls.append( u );
-
- return urls;
- }
-
- if ( (count % 2) == 1 ) { // odd number of " -> error
- TQWidget *that = const_cast<KFileDialog *>(this);
- KMessageBox::sorry(that, i18n("The requested filenames\n"
- "%1\n"
- "do not appear to be valid;\n"
- "make sure every filename is enclosed in double quotes.").arg(line),
- i18n("Filename Error"));
- return urls;
- }
-
- int start = 0;
- int index1 = -1, index2 = -1;
- while ( true ) {
- index1 = line.find( '"', start );
- index2 = line.find( '"', index1 + 1 );
-
- if ( index1 < 0 )
- break;
-
- // get everything between the " "
- name = line.mid( index1 + 1, index2 - index1 - 1 );
- u.setFileName( name );
- if ( u.isValid() )
- urls.append( u );
-
- start = index2 + 1;
- }
- return urls;
-}
-
-
-TQString KFileDialog::selectedFile() const
-{
- if ( result() == TQDialog::Accepted )
- {
- KURL url = TDEIO::NetAccess::mostLocalURL(d->url,topLevelWidget());
- if (url.isLocalFile())
- return url.path();
- else {
- KMessageBox::sorry( d->mainWidget,
- i18n("You can only select local files."),
- i18n("Remote Files Not Accepted") );
- }
- }
- return TQString::null;
-}
-
-TQStringList KFileDialog::selectedFiles() const
-{
- TQStringList list;
- KURL url;
-
- if ( result() == TQDialog::Accepted ) {
- if ( (ops->mode() & KFile::Files) == KFile::Files ) {
- KURL::List urls = parseSelectedURLs();
- TQValueListConstIterator<KURL> it = urls.begin();
- while ( it != urls.end() ) {
- url = TDEIO::NetAccess::mostLocalURL(*it,topLevelWidget());
- if ( url.isLocalFile() )
- list.append( url.path() );
- ++it;
- }
- }
-
- else { // single-selection mode
- if ( d->url.isLocalFile() )
- list.append( d->url.path() );
- }
- }
-
- return list;
-}
-
-KURL KFileDialog::baseURL() const
-{
- return ops->url();
-}
-
-TQString KFileDialog::getSaveFileName(const TQString& dir, const TQString& filter,
- TQWidget *parent,
- const TQString& caption)
-{
- bool specialDir = dir.at(0) == ':';
- KFileDialog dlg( specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
- if ( !specialDir )
- dlg.setSelection( dir ); // may also be a filename
-
- dlg.setOperationMode( Saving );
- dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
-
- dlg.exec();
-
- TQString filename = dlg.selectedFile();
- if (!filename.isEmpty())
- KRecentDocument::add(filename);
-
- return filename;
-}
-
-TQString KFileDialog::getSaveFileNameWId(const TQString& dir, const TQString& filter,
- WId parent_id,
- const TQString& caption)
-{
- bool specialDir = dir.at(0) == ':';
- TQWidget* parent = TQT_TQWIDGET(TQWidget::find( parent_id ));
- KFileDialog dlg( specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
-#ifdef Q_WS_X11
- if( parent == NULL && parent_id != 0 )
- XSetTransientForHint(tqt_xdisplay(), dlg.winId(), parent_id);
-#else
- // TODO
-#endif
-
- if ( !specialDir )
- dlg.setSelection( dir ); // may also be a filename
-
- dlg.setOperationMode( KFileDialog::Saving);
- dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
-
- dlg.exec();
-
- TQString filename = dlg.selectedFile();
- if (!filename.isEmpty())
- KRecentDocument::add(filename);
-
- return filename;
-}
-
-KURL KFileDialog::getSaveURL(const TQString& dir, const TQString& filter,
- TQWidget *parent, const TQString& caption)
-{
- bool specialDir = dir.at(0) == ':';
- KFileDialog dlg(specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
- if ( !specialDir )
- dlg.setSelection( dir ); // may also be a filename
-
- dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
- dlg.setOperationMode( Saving );
-
- dlg.exec();
-
- KURL url = dlg.selectedURL();
- if (url.isValid())
- KRecentDocument::add( url );
-
- return url;
-}
-
-void KFileDialog::show()
-{
- if ( !d->hasView ) { // delayed view-creation
- ops->setView(KFile::Default);
- ops->clearHistory();
- d->hasView = true;
- }
-
- KDialogBase::show();
-}
-
-void KFileDialog::setMode( KFile::Mode m )
-{
- ops->setMode(m);
- if ( ops->dirOnlyMode() ) {
- filterWidget->setDefaultFilter( i18n("*|All Folders") );
- }
- else {
- filterWidget->setDefaultFilter( i18n("*|All Files") );
- }
-
- updateAutoSelectExtension ();
-}
-
-void KFileDialog::setMode( unsigned int m )
-{
- setMode(static_cast<KFile::Mode>( m ));
-}
-
-KFile::Mode KFileDialog::mode() const
-{
- return ops->mode();
-}
-
-
-void KFileDialog::readConfig( TDEConfig *kc, const TQString& group )
-{
- if ( !kc )
- return;
-
- TQString oldGroup = kc->group();
- if ( !group.isEmpty() )
- kc->setGroup( group );
-
- ops->readConfig( kc, group );
-
- KURLComboBox *combo = d->pathCombo;
- combo->setURLs( kc->readPathListEntry( RecentURLs ), KURLComboBox::RemoveTop );
- combo->setMaxItems( kc->readNumEntry( RecentURLsNumber,
- DefaultRecentURLsNumber ) );
- combo->setURL( ops->url() );
- autoDirectoryFollowing = kc->readBoolEntry( AutoDirectoryFollowing,
- DefaultDirectoryFollowing );
-
- TDEGlobalSettings::Completion cm = (TDEGlobalSettings::Completion)
- kc->readNumEntry( PathComboCompletionMode,
- TDEGlobalSettings::completionMode() );
- if ( cm != TDEGlobalSettings::completionMode() )
- combo->setCompletionMode( cm );
-
- cm = (TDEGlobalSettings::Completion)
- kc->readNumEntry( LocationComboCompletionMode,
- TDEGlobalSettings::completionMode() );
- if ( cm != TDEGlobalSettings::completionMode() )
- locationEdit->setCompletionMode( cm );
-
- // show or don't show the speedbar
- toggleSpeedbar( kc->readBoolEntry(ShowSpeedbar, true) );
-
- // show or don't show the bookmarks
- toggleBookmarks( kc->readBoolEntry(ShowBookmarks, false) );
-
- // does the user want Automatically Select Extension?
- d->autoSelectExtChecked = kc->readBoolEntry (AutoSelectExtChecked, DefaultAutoSelectExtChecked);
- updateAutoSelectExtension ();
-
- int w1 = minimumSize().width();
- int w2 = toolbar->sizeHint().width() + 10;
- if (w1 < w2)
- setMinimumWidth(w2);
-
- TQSize size = configDialogSize( group );
- resize( size );
- kc->setGroup( oldGroup );
-}
-
-void KFileDialog::writeConfig( TDEConfig *kc, const TQString& group )
-{
- if ( !kc )
- return;
-
- TQString oldGroup = kc->group();
- if ( !group.isEmpty() )
- kc->setGroup( group );
-
- kc->writePathEntry( RecentURLs, d->pathCombo->urls() );
- saveDialogSize( group, true );
- kc->writeEntry( PathComboCompletionMode, static_cast<int>(d->pathCombo->completionMode()) );
- kc->writeEntry( LocationComboCompletionMode, static_cast<int>(locationEdit->completionMode()) );
- kc->writeEntry( ShowSpeedbar, d->urlBar && !d->urlBar->isHidden() );
- kc->writeEntry( ShowBookmarks, d->bookmarkHandler != 0 );
- kc->writeEntry( AutoSelectExtChecked, d->autoSelectExtChecked );
-
- ops->writeConfig( kc, group );
- kc->setGroup( oldGroup );
-}
-
-
-void KFileDialog::readRecentFiles( TDEConfig *kc )
-{
- TQString oldGroup = kc->group();
- kc->setGroup( ConfigGroup );
-
- locationEdit->setMaxItems( kc->readNumEntry( RecentFilesNumber,
- DefaultRecentURLsNumber ) );
- locationEdit->setURLs( kc->readPathListEntry( RecentFiles ),
- KURLComboBox::RemoveBottom );
- locationEdit->insertItem( TQString::null, 0 ); // dummy item without pixmap
- locationEdit->setCurrentItem( 0 );
-
- kc->setGroup( oldGroup );
-}
-
-void KFileDialog::saveRecentFiles( TDEConfig *kc )
-{
- TQString oldGroup = kc->group();
- kc->setGroup( ConfigGroup );
-
- kc->writePathEntry( RecentFiles, locationEdit->urls() );
-
- kc->setGroup( oldGroup );
-}
-
-KPushButton * KFileDialog::okButton() const
-{
- return d->okButton;
-}
-
-KPushButton * KFileDialog::cancelButton() const
-{
- return d->cancelButton;
-}
-
-KURLBar * KFileDialog::speedBar()
-{
- return d->urlBar;
-}
-
-void KFileDialog::slotCancel()
-{
- ops->close();
- KDialogBase::slotCancel();
-
- TDEConfig *config = TDEGlobal::config();
- config->setForceGlobal( true );
- writeConfig( config, ConfigGroup );
- config->setForceGlobal( false );
-}
-
-void KFileDialog::setKeepLocation( bool keep )
-{
- d->keepLocation = keep;
-}
-
-bool KFileDialog::keepsLocation() const
-{
- return d->keepLocation;
-}
-
-void KFileDialog::setOperationMode( OperationMode mode )
-{
- d->operationMode = mode;
- d->keepLocation = (mode == Saving);
- filterWidget->setEditable( !d->hasDefaultFilter || mode != Saving );
- if ( mode == Opening )
- d->okButton->setGuiItem( KGuiItem( i18n("&Open"), "fileopen") );
- else if ( mode == Saving ) {
- d->okButton->setGuiItem( KStdGuiItem::save() );
- setNonExtSelection();
- }
- else
- d->okButton->setGuiItem( KStdGuiItem::ok() );
- updateLocationWhatsThis ();
- updateAutoSelectExtension ();
-}
-
-KFileDialog::OperationMode KFileDialog::operationMode() const
-{
- return d->operationMode;
-}
-
-void KFileDialog::slotAutoSelectExtClicked()
-{
- kdDebug (kfile_area) << "slotAutoSelectExtClicked(): "
- << d->autoSelectExtCheckBox->isChecked () << endl;
-
- // whether the _user_ wants it on/off
- d->autoSelectExtChecked = d->autoSelectExtCheckBox->isChecked ();
-
- // update the current filename's extension
- updateLocationEditExtension (d->extension /* extension hasn't changed */);
-}
-
-static TQString getExtensionFromPatternList (const TQStringList &patternList)
-{
- TQString ret;
- kdDebug (kfile_area) << "\tgetExtension " << patternList << endl;
-
- TQStringList::ConstIterator patternListEnd = patternList.end ();
- for (TQStringList::ConstIterator it = patternList.begin ();
- it != patternListEnd;
- it++)
- {
- kdDebug (kfile_area) << "\t\ttry: \'" << (*it) << "\'" << endl;
-
- // is this pattern like "*.BMP" rather than useless things like:
- //
- // README
- // *.
- // *.*
- // *.JP*G
- // *.JP?
- if ((*it).startsWith ("*.") &&
- (*it).length () > 2 &&
- (*it).find ('*', 2) < 0 && (*it).find ('?', 2) < 0)
- {
- ret = (*it).mid (1);
- break;
- }
- }
-
- return ret;
-}
-
-static TQString stripUndisplayable (const TQString &string)
-{
- TQString ret = string;
-
- ret.remove (':');
- ret.remove ('&');
-
- return ret;
-}
-
-
-TQString KFileDialog::currentFilterExtension (void)
-{
- return d->extension;
-}
-
-void KFileDialog::updateAutoSelectExtension (void)
-{
- if (!d->autoSelectExtCheckBox) return;
-
- //
- // Figure out an extension for the Automatically Select Extension thing
- // (some Windows users apparently don't know what to do when confronted
- // with a text file called "COPYING" but do know what to do with
- // COPYING.txt ...)
- //
-
- kdDebug (kfile_area) << "Figure out an extension: " << endl;
- TQString lastExtension = d->extension;
- d->extension = TQString::null;
-
- // Automatically Select Extension is only valid if the user is _saving_ a _file_
- if ((operationMode () == Saving) && (mode () & KFile::File))
- {
- //
- // Get an extension from the filter
- //
-
- TQString filter = currentFilter ();
- if (!filter.isEmpty ())
- {
- // e.g. "*.cpp"
- if (filter.find ('/') < 0)
- {
- d->extension = getExtensionFromPatternList (TQStringList::split (" ", filter)).lower ();
- kdDebug (kfile_area) << "\tsetFilter-style: pattern ext=\'"
- << d->extension << "\'" << endl;
- }
- // e.g. "text/html"
- else
- {
- KMimeType::Ptr mime = KMimeType::mimeType (filter);
-
- // first try X-TDE-NativeExtension
- TQString nativeExtension = mime->property ("X-TDE-NativeExtension").toString ();
- if (nativeExtension.at (0) == '.')
- {
- d->extension = nativeExtension.lower ();
- kdDebug (kfile_area) << "\tsetMimeFilter-style: native ext=\'"
- << d->extension << "\'" << endl;
- }
-
- // no X-TDE-NativeExtension
- if (d->extension.isEmpty ())
- {
- d->extension = getExtensionFromPatternList (mime->patterns ()).lower ();
- kdDebug (kfile_area) << "\tsetMimeFilter-style: pattern ext=\'"
- << d->extension << "\'" << endl;
- }
- }
- }
-
-
- //
- // GUI: checkbox
- //
-
- TQString whatsThisExtension;
- if (!d->extension.isEmpty ())
- {
- // remember: sync any changes to the string with below
- d->autoSelectExtCheckBox->setText (i18n ("Automatically select filename e&xtension (%1)").arg (d->extension));
- whatsThisExtension = i18n ("the extension <b>%1</b>").arg (d->extension);
-
- d->autoSelectExtCheckBox->setEnabled (true);
- d->autoSelectExtCheckBox->setChecked (d->autoSelectExtChecked);
- }
- else
- {
- // remember: sync any changes to the string with above
- d->autoSelectExtCheckBox->setText (i18n ("Automatically select filename e&xtension"));
- whatsThisExtension = i18n ("a suitable extension");
-
- d->autoSelectExtCheckBox->setChecked (false);
- d->autoSelectExtCheckBox->setEnabled (false);
- }
-
- const TQString locationLabelText = stripUndisplayable (d->locationLabel->text ());
- const TQString filterLabelText = stripUndisplayable (d->filterLabel->text ());
- TQWhatsThis::add (d->autoSelectExtCheckBox,
- "<qt>" +
- i18n (
- "This option enables some convenient features for "
- "saving files with extensions:<br>"
- "<ol>"
- "<li>Any extension specified in the <b>%1</b> text "
- "area will be updated if you change the file type "
- "to save in.<br>"
- "<br></li>"
- "<li>If no extension is specified in the <b>%2</b> "
- "text area when you click "
- "<b>Save</b>, %3 will be added to the end of the "
- "filename (if the filename does not already exist). "
- "This extension is based on the file type that you "
- "have chosen to save in.<br>"
- "<br>"
- "If you do not want TDE to supply an extension for the "
- "filename, you can either turn this option off or you "
- "can suppress it by adding a period (.) to the end of "
- "the filename (the period will be automatically "
- "removed)."
- "</li>"
- "</ol>"
- "If unsure, keep this option enabled as it makes your "
- "files more manageable."
- )
- .arg (locationLabelText)
- .arg (locationLabelText)
- .arg (whatsThisExtension)
- + "</qt>"
- );
-
- d->autoSelectExtCheckBox->show ();
-
-
- // update the current filename's extension
- updateLocationEditExtension (lastExtension);
- }
- // Automatically Select Extension not valid
- else
- {
- d->autoSelectExtCheckBox->setChecked (false);
- d->autoSelectExtCheckBox->hide ();
- }
-}
-
-// Updates the extension of the filename specified in locationEdit if the
-// Automatically Select Extension feature is enabled.
-// (this prevents you from accidently saving "file.kwd" as RTF, for example)
-void KFileDialog::updateLocationEditExtension (const TQString &lastExtension)
-{
- if (!d->autoSelectExtCheckBox->isChecked () || d->extension.isEmpty ())
- return;
-
- TQString urlStr = locationEdit->currentText ();
- if (urlStr.isEmpty ())
- return;
-
- KURL url = getCompleteURL (urlStr);
- kdDebug (kfile_area) << "updateLocationEditExtension (" << url << ")" << endl;
-
- const int fileNameOffset = urlStr.findRev ('/') + 1;
- TQString fileName = urlStr.mid (fileNameOffset);
-
- const int dot = fileName.findRev ('.');
- const int len = fileName.length ();
- if (dot > 0 && // has an extension already and it's not a hidden file
- // like ".hidden" (but we do accept ".hidden.ext")
- dot != len - 1 // and not deliberately suppressing extension
- )
- {
- // exists?
- TDEIO::UDSEntry t;
- if (TDEIO::NetAccess::stat (url, t, topLevelWidget()))
- {
- kdDebug (kfile_area) << "\tfile exists" << endl;
-
- if (isDirectory (t))
- {
- kdDebug (kfile_area) << "\tisDir - won't alter extension" << endl;
- return;
- }
-
- // --- fall through ---
- }
-
-
- //
- // try to get rid of the current extension
- //
-
- // catch "double extensions" like ".tar.gz"
- if (lastExtension.length () && fileName.endsWith (lastExtension))
- fileName.truncate (len - lastExtension.length ());
- // can only handle "single extensions"
- else
- fileName.truncate (dot);
-
- // add extension
- const TQString newText = urlStr.left (fileNameOffset) + fileName + d->extension;
- if ( newText != locationEdit->currentText() )
- {
- locationEdit->setCurrentText (urlStr.left (fileNameOffset) + fileName + d->extension);
- locationEdit->lineEdit()->setEdited (true);
- }
- }
-}
-
-// Updates the filter if the extension of the filename specified in locationEdit is changed
-// (this prevents you from accidently saving "file.kwd" as RTF, for example)
-void KFileDialog::updateFilter ()
-{
- if ((operationMode() == Saving) && (mode() & KFile::File) ) {
- const TQString urlStr = locationEdit->currentText ();
- if (urlStr.isEmpty ())
- return;
-
- KMimeType::Ptr mime = KMimeType::findByPath(urlStr, 0, true);
- if (mime && mime->name() != KMimeType::defaultMimeType()) {
- if (filterWidget->currentFilter() != mime->name() &&
- filterWidget->filters.findIndex(mime->name()) != -1) {
- filterWidget->setCurrentFilter(mime->name());
- }
- }
- }
-}
-
-// applies only to a file that doesn't already exist
-void KFileDialog::appendExtension (KURL &url)
-{
- if (!d->autoSelectExtCheckBox->isChecked () || d->extension.isEmpty ())
- return;
-
- TQString fileName = url.fileName ();
- if (fileName.isEmpty ())
- return;
-
- kdDebug (kfile_area) << "appendExtension(" << url << ")" << endl;
-
- const int len = fileName.length ();
- const int dot = fileName.findRev ('.');
-
- const bool suppressExtension = (dot == len - 1);
- const bool unspecifiedExtension = (dot <= 0);
-
- // don't TDEIO::NetAccess::Stat if unnecessary
- if (!(suppressExtension || unspecifiedExtension))
- return;
-
- // exists?
- TDEIO::UDSEntry t;
- if (TDEIO::NetAccess::stat (url, t, topLevelWidget()))
- {
- kdDebug (kfile_area) << "\tfile exists - won't append extension" << endl;
- return;
- }
-
- // suppress automatically append extension?
- if (suppressExtension)
- {
- //
- // Strip trailing dot
- // This allows lazy people to have autoSelectExtCheckBox->isChecked
- // but don't want a file extension to be appended
- // e.g. "README." will make a file called "README"
- //
- // If you really want a name like "README.", then type "README.."
- // and the trailing dot will be removed (or just stop being lazy and
- // turn off this feature so that you can type "README.")
- //
- kdDebug (kfile_area) << "\tstrip trailing dot" << endl;
- url.setFileName (fileName.left (len - 1));
- }
- // evilmatically append extension :) if the user hasn't specified one
- else if (unspecifiedExtension)
- {
- kdDebug (kfile_area) << "\tappending extension \'" << d->extension << "\'..." << endl;
- url.setFileName (fileName + d->extension);
- kdDebug (kfile_area) << "\tsaving as \'" << url << "\'" << endl;
- }
-}
-
-
-// adds the selected files/urls to 'recent documents'
-void KFileDialog::addToRecentDocuments()
-{
- int m = ops->mode();
-
- if ( m & KFile::LocalOnly ) {
- TQStringList files = selectedFiles();
- TQStringList::ConstIterator it = files.begin();
- for ( ; it != files.end(); ++it )
- KRecentDocument::add( *it );
- }
-
- else { // urls
- KURL::List urls = selectedURLs();
- KURL::List::ConstIterator it = urls.begin();
- for ( ; it != urls.end(); ++it ) {
- if ( (*it).isValid() )
- KRecentDocument::add( *it );
- }
- }
-}
-
-KActionCollection * KFileDialog::actionCollection() const
-{
- return ops->actionCollection();
-}
-
-void KFileDialog::keyPressEvent( TQKeyEvent *e )
-{
- if ( e->key() == Key_Escape )
- {
- e->accept();
- d->cancelButton->animateClick();
- }
- else
- KDialogBase::keyPressEvent( e );
-}
-
-void KFileDialog::toggleSpeedbar( bool show )
-{
- if ( show )
- {
- if ( !d->urlBar )
- initSpeedbar();
-
- d->urlBar->show();
-
- // check to see if they have a home item defined, if not show the home button
- KURLBarItem *urlItem = static_cast<KURLBarItem*>( d->urlBar->listBox()->firstItem() );
- KURL homeURL;
- homeURL.setPath( TQDir::homeDirPath() );
- while ( urlItem )
- {
- if ( homeURL.equals( urlItem->url(), true ) )
- {
- ops->actionCollection()->action( "home" )->unplug( toolbar );
- break;
- }
-
- urlItem = static_cast<KURLBarItem*>( urlItem->next() );
- }
- }
- else
- {
- if (d->urlBar)
- d->urlBar->hide();
-
- if ( !ops->actionCollection()->action( "home" )->isPlugged( toolbar ) )
- ops->actionCollection()->action( "home" )->plug( toolbar, 3 );
- }
-
- static_cast<KToggleAction *>(actionCollection()->action("toggleSpeedbar"))->setChecked( show );
-}
-
-void KFileDialog::toggleBookmarks(bool show)
-{
- if (show)
- {
- if (d->bookmarkHandler)
- {
- return;
- }
-
- d->bookmarkHandler = new KFileBookmarkHandler( this );
- connect( d->bookmarkHandler, TQT_SIGNAL( openURL( const TQString& )),
- TQT_SLOT( enterURL( const TQString& )));
-
- toolbar->insertButton(TQString::fromLatin1("bookmark"),
- (int)HOTLIST_BUTTON, true,
- i18n("Bookmarks"), 5);
- toolbar->getButton(HOTLIST_BUTTON)->setPopup(d->bookmarkHandler->menu(),
- true);
- TQWhatsThis::add(toolbar->getButton(HOTLIST_BUTTON),
- i18n("<qt>This button allows you to bookmark specific locations. "
- "Click on this button to open the bookmark menu where you may add, "
- "edit or select a bookmark.<p>"
- "These bookmarks are specific to the file dialog, but otherwise operate "
- "like bookmarks elsewhere in TDE.</qt>"));
- }
- else if (d->bookmarkHandler)
- {
- delete d->bookmarkHandler;
- d->bookmarkHandler = 0;
- toolbar->removeItem(HOTLIST_BUTTON);
- }
-
- static_cast<KToggleAction *>(actionCollection()->action("toggleBookmarks"))->setChecked( show );
-}
-
-int KFileDialog::pathComboIndex()
-{
- return d->m_pathComboIndex;
-}
-
-// static
-void KFileDialog::initStatic()
-{
- if ( lastDirectory )
- return;
-
- lastDirectory = ldd.setObject(lastDirectory, new KURL());
-}
-
-// static
-KURL KFileDialog::getStartURL( const TQString& startDir,
- TQString& recentDirClass )
-{
- initStatic();
-
- recentDirClass = TQString::null;
- KURL ret;
-
- bool useDefaultStartDir = startDir.isEmpty();
- if ( !useDefaultStartDir )
- {
- if (startDir[0] == ':')
- {
- recentDirClass = startDir;
- ret = KURL::fromPathOrURL( KRecentDirs::dir(recentDirClass) );
- }
- else
- {
- ret = TDECmdLineArgs::makeURL( TQFile::encodeName(startDir) );
- // If we won't be able to list it (e.g. http), then use default
- if ( !KProtocolInfo::supportsListing( ret ) )
- useDefaultStartDir = true;
- }
- }
-
- if ( useDefaultStartDir )
- {
- if (lastDirectory->isEmpty()) {
- lastDirectory->setPath(TDEGlobalSettings::documentPath());
- KURL home;
- home.setPath( TQDir::homeDirPath() );
- // if there is no docpath set (== home dir), we prefer the current
- // directory over it. We also prefer the homedir when our CWD is
- // different from our homedirectory or when the document dir
- // does not exist
- if ( lastDirectory->path(+1) == home.path(+1) ||
- TQDir::currentDirPath() != TQDir::homeDirPath() ||
- !TQDir(lastDirectory->path(+1)).exists() )
- lastDirectory->setPath(TQDir::currentDirPath());
- }
- ret = *lastDirectory;
- }
-
- return ret;
-}
-
-void KFileDialog::setStartDir( const KURL& directory )
-{
- initStatic();
- if ( directory.isValid() )
- *lastDirectory = directory;
-}
-
-void KFileDialog::setNonExtSelection()
-{
- // Enhanced rename: Don't highlight the file extension.
- TQString pattern, filename = locationEdit->currentText().stripWhiteSpace();
- KServiceTypeFactory::self()->findFromPattern( filename, &pattern );
-
- if ( !pattern.isEmpty() && pattern.at( 0 ) == '*' && pattern.find( '*' , 1 ) == -1 )
- locationEdit->lineEdit()->setSelection( 0, filename.length() - pattern.stripWhiteSpace().length()+1 );
- else
- {
- int lastDot = filename.findRev( '.' );
- if ( lastDot > 0 )
- locationEdit->lineEdit()->setSelection( 0, lastDot );
- }
-}
-
-void KFileDialog::virtual_hook( int id, void* data )
-{ KDialogBase::virtual_hook( id, data ); }
-
-
-#include "kfiledialog.moc"
diff --git a/kio/kfile/kfiledialog.h b/kio/kfile/kfiledialog.h
deleted file mode 100644
index 2f986d351..000000000
--- a/kio/kfile/kfiledialog.h
+++ /dev/null
@@ -1,989 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1997, 1998 Richard Moore <rich@kde.org>
- 1998 Stephan Kulow <coolo@kde.org>
- 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- 2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
- 2001 Frerich Raabe <raabe@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __KFILEDIALOG_H__
-#define __KFILEDIALOG_H__
-
-#include <tqstring.h>
-
-#include <kdialogbase.h>
-#include <kfile.h>
-#include <kurl.h>
-#include <kmimetype.h>
-#include <kio/jobclasses.h>
-
-class TQCheckBox;
-class TQHBoxLayout;
-class TQGridLayout;
-class TQLabel;
-class TQPopupMenu;
-class TQVBoxLayout;
-
-class KActionCollection;
-class KDirOperator;
-class KURLBar;
-class KURLComboBox;
-class KFileFilterCombo;
-class KFileView;
-class KFileItem;
-class KPushButton;
-class KToolBar;
-class KPreviewWidgetBase;
-
-struct KFileDialogPrivate;
-
-/**
- * Provides a user (and developer) friendly way to
- * select files and directories.
- *
- * The widget can be used as a drop in replacement for the
- * TQFileDialog widget, but has greater functionality and a nicer GUI.
- *
- * You will usually want to use one of the static methods
- * getOpenFileName(), getSaveFileName(), getOpenURL()
- * or for multiple files getOpenFileNames() or getOpenURLs().
- *
- * The dialog has been designed to allow applications to customise it
- * by subclassing. It uses geometry management to ensure that subclasses
- * can easily add children that will be incorporated into the layout.
- *
- * \image html kfiledialog.png "KDE File Dialog"
- *
- * @short A file selection dialog.
- *
- * @author Richard J. Moore <rich@kde.org>, Carsten Pfeiffer <pfeiffer@kde.org>
- */
-class TDEIO_EXPORT KFileDialog : public KDialogBase
-{
- Q_OBJECT
-
-public:
-
- /**
- * Defines some default behavior of the filedialog.
- * E.g. in mode @p Opening and @p Saving, the selected files/urls will
- * be added to the "recent documents" list. The Saving mode also implies
- * setKeepLocation() being set.
- *
- * @p Other means that no default actions are performed.
- *
- * @see setOperationMode
- * @see operationMode
- */
- enum OperationMode { Other = 0, Opening, Saving };
-
- /**
- * Constructs a file dialog.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- *
- * @param filter A shell glob or a mime-type-filter that specifies
- * which files to display.
- * @param parent The parent widget of this dialog
- * @param name The name of this object
- * @param modal Whether to create a modal dialog or not
- * See setFilter() for details on how to use this argument.
- *
- */
- KFileDialog(const TQString& startDir, const TQString& filter,
- TQWidget *parent, const char *name,
- bool modal);
-
- /**
- * Constructs a file dialog.
- *
- * The parameters here are identical to the first constructor except
- * for the addition of a TQWidget parameter.
- *
- * Historical note: The original version of KFileDialog did not have this extra
- * parameter. It was added later, and, in order to maintain binary compatibility,
- * it was placed in a new constructor instead of added to the original one.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- *
- * @param filter A shell glob or a mime-type-filter that specifies
- * which files to display.
- * See setFilter() for details on how to use this argument.
- *
- * @param widget A widget, or a widget of widgets, for displaying custom
- * data in the dialog. This can be used, for example, to
- * display a check box with the caption "Open as read-only".
- * When creating this widget, you don't need to specify a parent,
- * since the widget's parent will be set automatically by KFileDialog.
- * @param parent The parent widget of this dialog
- * @param name The name of this object
- * @param modal Whether to create a modal dialog or not
- * @since 3.1
- */
- KFileDialog(const TQString& startDir, const TQString& filter,
- TQWidget *parent, const char *name,
- bool modal, TQWidget* widget);
-
-
- /**
- * Destructs the file dialog.
- */
- ~KFileDialog();
-
- /**
- * @returns The selected fully qualified filename.
- */
- KURL selectedURL() const;
-
- /**
- * @returns The list of selected URLs.
- */
- KURL::List selectedURLs() const;
-
- /**
- * @returns the currently shown directory.
- */
- KURL baseURL() const;
-
- /**
- * Returns the full path of the selected file in the local filesystem.
- * (Local files only)
- */
- TQString selectedFile() const;
-
- /**
- * Returns a list of all selected local files.
- */
- TQStringList selectedFiles() const;
-
- /**
- * Sets the directory to view.
- *
- * @param url URL to show.
- * @param clearforward Indicates whether the forward queue
- * should be cleared.
- */
- void setURL(const KURL &url, bool clearforward = true);
-
- /**
- * Sets the file name to preselect to @p name
- *
- * This takes absolute URLs and relative file names.
- */
- void setSelection(const TQString& name);
-
- /**
- * Sets the operational mode of the filedialog to @p Saving, @p Opening
- * or @p Other. This will set some flags that are specific to loading
- * or saving files. E.g. setKeepLocation() makes mostly sense for
- * a save-as dialog. So setOperationMode( KFileDialog::Saving ); sets
- * setKeepLocation for example.
- *
- * The mode @p Saving, together with a default filter set via
- * setMimeFilter() will make the filter combobox read-only.
- *
- * The default mode is @p Opening.
- *
- * Call this method right after instantiating KFileDialog.
- *
- * @see operationMode
- * @see KFileDialog::OperationMode
- */
- void setOperationMode( KFileDialog::OperationMode );
-
- /**
- * @returns the current operation mode, Opening, Saving or Other. Default
- * is Other.
- *
- * @see operationMode
- * @see KFileDialog::OperationMode
- */
- OperationMode operationMode() const;
-
- /**
- * Sets whether the filename/url should be kept when changing directories.
- * This is for example useful when having a predefined filename where
- * the full path for that file is searched.
- *
- * This is implicitly set when operationMode() is KFileDialog::Saving
- *
- * getSaveFileName() and getSaveURL() set this to true by default, so that
- * you can type in the filename and change the directory without having
- * to type the name again.
- */
- void setKeepLocation( bool keep );
-
- /**
- * @returns whether the contents of the location edit are kept when
- * changing directories.
- */
- bool keepsLocation() const;
-
- /**
- * Sets the filter to be used to @p filter.
- *
- * You can set more
- * filters for the user to select separated by '\n'. Every
- * filter entry is defined through namefilter|text to diplay.
- * If no | is found in the expression, just the namefilter is
- * shown. Examples:
- *
- * \code
- * kfile->setFilter("*.cpp|C++ Source Files\n*.h|Header files");
- * kfile->setFilter("*.cpp");
- * kfile->setFilter("*.cpp|Sources (*.cpp)");
- * kfile->setFilter("*.cpp|" + i18n("Sources (*.cpp)"));
- * kfile->setFilter("*.cpp *.cc *.C|C++ Source Files\n*.h *.H|Header files");
- * \endcode
- *
- * Note: The text to display is not parsed in any way. So, if you
- * want to show the suffix to select by a specific filter, you must
- * repeat it.
- *
- * If the filter contains an unescaped '/', a mimetype-filter is assumed.
- * If you would like a '/' visible in your filter it can be escaped with
- * a '\'. You can specify multiple mimetypes like this (separated with
- * space):
- *
- * \code
- * kfile->setFilter( "image/png text/html text/plain" );
- * kfile->setFilter( "*.cue|CUE\\/BIN Files (*.cue)" );
- * \endcode
- *
- * @see filterChanged
- * @see setMimeFilter
- */
- void setFilter(const TQString& filter);
-
- /**
- * Returns the current filter as entered by the user or one of the
- * predefined set via setFilter().
- *
- * @see setFilter()
- * @see filterChanged()
- */
- TQString currentFilter() const;
-
- /**
- * Sets the filter up to specify the output type.
- *
- * @param label the label to use instead of "Filter:"
- * @param types a list of mimetypes that can be used as output format
- * @param defaultType the default mimetype to use as output format.
- *
- * Do not use in conjunction with setFilter()
- * @deprecated
- */
- void setFilterMimeType(const TQString &label, const KMimeType::List &types, const KMimeType::Ptr &defaultType) KDE_DEPRECATED;
-
- /**
- * Returns the mimetype for the desired output format.
- *
- * This is only valid if setFilterMimeType() has been called
- * previously.
- *
- * @see setFilterMimeType()
- */
- KMimeType::Ptr currentFilterMimeType();
-
- /**
- * Sets the filter up to specify the output type.
- *
- * @param types a list of mimetypes that can be used as output format
- * @param defaultType the default mimetype to use as output format, if any.
- * If @p defaultType is set, it will be set as the current item.
- * Otherwise, a first item showing all the mimetypes will be created.
- * Typically, @p defaultType should be empty for loading and set for saving.
- *
- * Do not use in conjunction with setFilter()
- */
- void setMimeFilter( const TQStringList& types,
- const TQString& defaultType = TQString::null );
-
- /**
- * The mimetype for the desired output format.
- *
- * This is only valid if setMimeFilter() has been called
- * previously.
- *
- * @see setMimeFilter()
- */
- TQString currentMimeFilter() const;
-
- /**
- * Clears any mime- or namefilter. Does not reload the directory.
- */
- void clearFilter();
-
- /**
- * @deprecated
- * Add a preview widget and enter the preview mode.
- *
- * In this mode
- * the dialog is split and the right part contains your widget.
- * This widget has to inherit TQWidget and it has to implement
- * a slot showPreview(const KURL &); which is called
- * every time the file changes. You may want to look at
- * koffice/lib/kofficecore/koFilterManager.cc for some hints :)
- *
- * Ownership is transferred to KFileDialog. You need to create the
- * preview-widget with "new", i.e. on the heap.
- */
- void setPreviewWidget(const TQWidget *w) KDE_DEPRECATED;
-
- /**
- * Adds a preview widget and enters the preview mode.
- *
- * In this mode the dialog is split and the right part contains your
- * preview widget.
- *
- * Ownership is transferred to KFileDialog. You need to create the
- * preview-widget with "new", i.e. on the heap.
- *
- * @param w The widget to be used for the preview.
- */
- void setPreviewWidget(const KPreviewWidgetBase *w);
-
- /**
- * Creates a modal file dialog and return the selected
- * filename or an empty string if none was chosen.
- *
- * Note that with
- * this method the user must select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static TQString getOpenFileName(const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
-
- /**
- * Use this version only if you have no TQWidget available as
- * parent widget. This can be the case if the parent widget is
- * a widget in another process or if the parent widget is a
- * non-Qt widget. For example, in a GTK program.
- *
- * @since 3.4
- */
- static TQString getOpenFileNameWId(const TQString& startDir,
- const TQString& filter,
- WId parent_id, const TQString& caption);
-
- /**
- * Creates a modal file dialog and returns the selected
- * filenames or an empty list if none was chosen.
- *
- * Note that with
- * this method the user must select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static TQStringList getOpenFileNames(const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent = 0,
- const TQString& caption= TQString::null);
-
-
-
- /**
- * Creates a modal file dialog and returns the selected
- * URL or an empty string if none was chosen.
- *
- * Note that with
- * this method the user must select an existing URL.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static KURL getOpenURL(const TQString& startDir = TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
-
-
- /**
- * Creates a modal file dialog and returns the selected
- * URLs or an empty list if none was chosen.
- *
- * Note that with
- * this method the user must select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static KURL::List getOpenURLs(const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent = 0,
- const TQString& caption= TQString::null);
-
-
-
- /**
- * Creates a modal file dialog and returns the selected
- * filename or an empty string if none was chosen.
- *
- * Note that with this
- * method the user need not select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li a relative path or a filename determining the
- * directory to start in and the file to be selected.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static TQString getSaveFileName(const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
-
- /**
- * This function accepts the window id of the parent window, instead
- * of TQWidget*. It should be used only when necessary.
- * @since 3.4
- */
- static TQString getSaveFileNameWId(const TQString& dir, const TQString& filter,
- WId parent_id,
- const TQString& caption);
-
- /**
- * Creates a modal file dialog and returns the selected
- * filename or an empty string if none was chosen.
- *
- * Note that with this
- * method the user need not select an existing filename.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li a relative path or a filename determining the
- * directory to start in and the file to be selected.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param filter This is a space separated list of shell globs.
- * You can set the text to be displayed for the glob, and
- * provide multiple globs. See setFilter() for details on
- * how to do this...
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static KURL getSaveURL(const TQString& startDir= TQString::null,
- const TQString& filter= TQString::null,
- TQWidget *parent= 0,
- const TQString& caption = TQString::null);
-
-
- /**
- * Creates a modal file dialog and returns the selected
- * directory or an empty string if none was chosen.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static TQString getExistingDirectory(const TQString & startDir = TQString::null,
- TQWidget * parent = 0,
- const TQString& caption= TQString::null);
-
- /**
- * Creates a modal file dialog and returns the selected
- * directory or an empty string if none was chosen.
- *
- * Contrary to getExistingDirectory(), this method allows the
- * selection of a remote directory.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- * @since 3.1
- */
- static KURL getExistingURL(const TQString & startDir = TQString::null,
- TQWidget * parent = 0,
- const TQString& caption= TQString::null);
- /**
- * Creates a modal file dialog with an image previewer and returns the
- * selected url or an empty string if none was chosen.
- *
- * @param startDir This can either be
- * @li The URL of the directory to start in.
- * @li TQString::null to start in the current working
- * directory, or the last directory where a file has been
- * selected.
- * @li ':&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in the same application that specified
- * the same keyword.
- * @li '::&lt;keyword&gt;' to start in the directory last used
- * by a filedialog in any application that specified the
- * same keyword.
- * @param parent The widget the dialog will be centered on initially.
- * @param caption The name of the dialog widget.
- */
- static KURL getImageOpenURL( const TQString& startDir = TQString::null,
- TQWidget *parent = 0,
- const TQString& caption = TQString::null );
- virtual void show();
-
- /**
- * Convenient overload of the other setMode(unsigned int) method.
- */
- void setMode( KFile::Mode m );
-
- /**
- * Sets the mode of the dialog.
- *
- * The mode is defined as (in kfile.h):
- * \code
- * enum Mode {
- * File = 1,
- * Directory = 2,
- * Files = 4,
- * ExistingOnly = 8,
- * LocalOnly = 16
- * };
- * \endcode
- * You can OR the values, e.g.
- * \code
- * KFile::Mode mode = static_cast<KFile::Mode>( KFile::Files |
- * KFile::ExistingOnly |
- * KFile::LocalOnly );
- * setMode( mode );
- * \endcode
- */
- void setMode( unsigned int m );
-
- /**
- * Returns the mode of the filedialog.
- * @see setMode()
- */
- KFile::Mode mode() const;
-
- /**
- * Sets the text to be displayed in front of the selection.
- *
- * The default is "Location".
- * Most useful if you want to make clear what
- * the location is used for.
- */
- void setLocationLabel(const TQString& text);
-
- /**
- * Returns a pointer to the toolbar.
- *
- * You can use this to insert custom
- * items into it, e.g.:
- * \code
- * yourAction = new KAction( i18n("Your Action"), 0,
- * this, TQT_SLOT( yourSlot() ),
- * this, "action name" );
- * yourAction->plug( kfileDialog->toolBar() );
- * \endcode
- */
- KToolBar *toolBar() const { return toolbar; }
-
- /**
- * @returns a pointer to the OK-Button in the filedialog. You may use it
- * e.g. to set a custom text to it.
- */
- KPushButton *okButton() const;
-
- /**
- * @returns a pointer to the Cancel-Button in the filedialog. You may use
- * it e.g. to set a custom text to it.
- */
- KPushButton *cancelButton() const;
-
- /**
- * @returns the KURLBar object used as the "speed bar". You can add custom
- * entries to it like that:
- * \code
- * KURLBar *urlBar = fileDialog->speedBar();
- * if ( urlBar )
- * urlBar->insertDynamicItem( someURL, i18n("The URL's description") );
- * \endcode
- *
- * Note that this method may return a null-pointer if the user configured
- * to not use the speed-bar.
- * @see KURLBar
- * @see KURLBar::insertDynamicItem
- * @since 3.2
- */
- KURLBar *speedBar();
-
- /**
- * @returns a pointer to the action collection, holding all the used
- * KActions.
- */
- KActionCollection *actionCollection() const;
-
- /**
- * @returns the index of the path combobox so when inserting widgets into
- * the dialog (e.g. subclasses) they can do so without hardcoding in an index
- */
- int pathComboIndex();
-
- /**
- * This method implements the logic to determine the user's default directory
- * to be listed. E.g. the documents direcory, home directory or a recently
- * used directory.
- * @param startDir A url/directory, to be used. May use the ':' and '::' syntax
- * as documented in the KFileDialog() constructor.
- * @param recentDirClass If the ':' or '::' syntax is used, recentDirClass
- * will contain the string to be used later for KRecentDir::dir()
- * @return The URL that should be listed by default (e.g. by KFileDialog or
- * KDirSelectDialog).
- * @since 3.1
- */
- static KURL getStartURL( const TQString& startDir, TQString& recentDirClass );
-
- /**
- * @internal
- * Used by KDirSelectDialog to share the dialog's start directory.
- */
- static void setStartDir( const KURL& directory );
-
-signals:
- /**
- * Emitted when the user selects a file. It is only emitted in single-
- * selection mode. The best way to get notified about selected file(s)
- * is to connect to the okClicked() signal inherited from KDialogBase
- * and call selectedFile(), selectedFiles(),
- * selectedURL() or selectedURLs().
- */
- void fileSelected(const TQString&);
-
- /**
- * Emitted when the user highlights a file.
- */
- void fileHighlighted(const TQString&);
-
- /**
- * Emitted when the user hilights one or more files in multiselection mode.
- *
- * Note: fileHighlighted() or fileSelected() are @em not
- * emitted in multiselection mode. You may use selectedItems() to
- * ask for the current highlighted items.
- * @see fileSelected
- */
- void selectionChanged();
-
- /**
- * Emitted when the filter changed, i.e. the user entered an own filter
- * or chose one of the predefined set via setFilter().
- *
- * @param filter contains the new filter (only the extension part,
- * not the explanation), i.e. "*.cpp" or "*.cpp *.cc".
- *
- * @see setFilter()
- * @see currentFilter()
- */
- void filterChanged( const TQString& filter );
-
-protected:
- KToolBar *toolbar;
-
- static KURL *lastDirectory;
-
- KURLComboBox *locationEdit;
-
- KFileFilterCombo *filterWidget;
-
- /**
- * Reimplemented to animate the cancel button.
- */
- virtual void keyPressEvent( TQKeyEvent *e );
-
- /**
- * Perform basic initialization tasks. Called by constructors.
- * @since 3.1
- */
- void init(const TQString& startDir, const TQString& filter, TQWidget* widget);
-
- /**
- * rebuild geometry management.
- *
- */
- virtual void initGUI();
-
- /**
- * called when an item is highlighted/selected in multiselection mode.
- * handles setting the locationEdit.
- */
- void multiSelectionChanged();
-
- /**
- * Reads configuration and applies it (size, recent directories, ...)
- */
- virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
-
- /**
- * Saves the current configuration
- */
- virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null );
-
- /**
- * Reads the recent used files and inserts them into the location combobox
- */
- virtual void readRecentFiles( TDEConfig * );
-
- /**
- * Saves the entries from the location combobox.
- */
- virtual void saveRecentFiles( TDEConfig * );
-
- /**
- * Parses the string "line" for files. If line doesn't contain any ", the
- * whole line will be interpreted as one file. If the number of " is odd,
- * an empty list will be returned. Otherwise, all items enclosed in " "
- * will be returned as correct urls.
- */
- KURL::List tokenize(const TQString& line) const;
-
- /**
- * Returns the absolute version of the URL specified in locationEdit.
- * @since 3.2
- */
- KURL getCompleteURL(const TQString&);
-
- /**
- * Returns the filename extension associated with the currentFilter().
- * TQString::null is returned if an extension is not available or if
- * operationMode() != Saving.
- * @since 3.2
- */
- TQString currentFilterExtension();
-
- /**
- * Updates the currentFilterExtension and the availability of the
- * Automatically Select Extension Checkbox (visible if operationMode()
- * == Saving and enabled if an extension _will_ be associated with the
- * currentFilter(), _after_ this call). You should call this after
- * filterWidget->setCurrentItem().
- * @since 3.2
- */
- void updateAutoSelectExtension();
-
-
-protected slots:
- void urlEntered( const KURL& );
- void enterURL( const KURL& url );
- void enterURL( const TQString& url );
- void locationActivated( const TQString& url );
-
- /**
- * @deprecated,
- */
- // ### remove in KDE4
- void toolbarCallback(int);
- /**
- * @deprecated
- */
- // ### remove in KDE4
- void pathComboChanged( const TQString& );
- /**
- * @deprecated
- */
- // ### remove in KDE4
- void dirCompletion( const TQString& );
-
- void slotFilterChanged();
- void fileHighlighted(const KFileItem *i);
- void fileSelected(const KFileItem *i);
- void slotStatResult(TDEIO::Job* job);
- void slotLoadingFinished();
-
- void fileCompletion( const TQString& );
- /**
- * @since 3.1
- */
- void toggleSpeedbar( bool );
-
- /**
- * @since 3.4
- */
- void toggleBookmarks(bool show);
-
- /**
- * @deprecated
- */
- virtual void updateStatusLine(int dirs, int files);
-
- virtual void slotOk();
- virtual void accept();
- virtual void slotCancel();
-
- void slotAutoSelectExtClicked();
- void addToRecentDocuments();
- void initSpeedbar();
-
-private slots:
- void slotLocationChanged( const TQString& text );
-
-private:
- KFileDialog(const KFileDialog&);
- KFileDialog operator=(const KFileDialog&);
-
- void setLocationText( const TQString& text );
- void updateLocationWhatsThis();
-
- void appendExtension(KURL &url);
- void updateLocationEditExtension(const TQString &);
- void updateFilter();
-
- static void initStatic();
-
- void setNonExtSelection();
-
-protected:
- KDirOperator *ops;
- bool autoDirectoryFollowing;
-
- KURL::List& parseSelectedURLs() const;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- KFileDialogPrivate *d;
-};
-
-#endif
diff --git a/kio/kfile/kfilefiltercombo.cpp b/kio/kfile/kfilefiltercombo.cpp
deleted file mode 100644
index 12a51db8e..000000000
--- a/kio/kfile/kfilefiltercombo.cpp
+++ /dev/null
@@ -1,203 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) Stephan Kulow <coolo@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <klocale.h>
-#include <kdebug.h>
-#include <kstaticdeleter.h>
-#include <config-kfile.h>
-
-#include "kfilefiltercombo.h"
-
-class KFileFilterCombo::KFileFilterComboPrivate
-{
-public:
- KFileFilterComboPrivate() {
- hasAllSupportedFiles = false;
- defaultFilter = i18n("*|All Files");
- isMimeFilter = false;
- }
-
- // when we have more than 3 mimefilters and no default-filter,
- // we don't show the comments of all mimefilters in one line,
- // instead we show "All supported files". We have to translate
- // that back to the list of mimefilters in currentFilter() tho.
- bool hasAllSupportedFiles;
- // true when setMimeFilter was called
- bool isMimeFilter;
- TQString lastFilter;
- TQString defaultFilter;
-};
-
-KFileFilterCombo::KFileFilterCombo( TQWidget *parent, const char *name)
- : KComboBox(true, parent, name), d( new KFileFilterComboPrivate )
-{
- setTrapReturnKey( true );
- setInsertionPolicy(NoInsertion);
- connect( this, TQT_SIGNAL( activated( int )), this, TQT_SIGNAL( filterChanged() ));
- connect( this, TQT_SIGNAL( returnPressed() ), this, TQT_SIGNAL( filterChanged() ));
- connect( this, TQT_SIGNAL( filterChanged() ), TQT_SLOT( slotFilterChanged() ));
- m_allTypes = false;
-}
-
-KFileFilterCombo::~KFileFilterCombo()
-{
- delete d;
-}
-
-void KFileFilterCombo::setFilter(const TQString& filter)
-{
- clear();
- filters.clear();
- d->hasAllSupportedFiles = false;
-
- if (!filter.isEmpty()) {
- TQString tmp = filter;
- int index = tmp.find('\n');
- while (index > 0) {
- filters.append(tmp.left(index));
- tmp = tmp.mid(index + 1);
- index = tmp.find('\n');
- }
- filters.append(tmp);
- }
- else
- filters.append( d->defaultFilter );
-
- TQStringList::ConstIterator it;
- TQStringList::ConstIterator end(filters.end());
- for (it = filters.begin(); it != end; ++it) {
- int tab = (*it).find('|');
- insertItem((tab < 0) ? *it :
- (*it).mid(tab + 1));
- }
-
- d->lastFilter = currentText();
- d->isMimeFilter = false;
-}
-
-TQString KFileFilterCombo::currentFilter() const
-{
- TQString f = currentText();
- if (f == text(currentItem())) { // user didn't edit the text
- f = *filters.at(currentItem());
- if ( d->isMimeFilter || (currentItem() == 0 && d->hasAllSupportedFiles) ) {
- return f; // we have a mimetype as filter
- }
- }
-
- int tab = f.find('|');
- if (tab < 0)
- return f;
- else
- return f.left(tab);
-}
-
-void KFileFilterCombo::setCurrentFilter( const TQString& filter )
-{
- int pos = 0;
- for( TQStringList::ConstIterator it = filters.begin();
- it != filters.end();
- ++it, ++pos ) {
- if( *it == filter ) {
- setCurrentItem( pos );
- filterChanged();
- return;
- }
- }
- setCurrentText( filter );
- filterChanged();
-}
-
-void KFileFilterCombo::setMimeFilter( const TQStringList& types,
- const TQString& defaultType )
-{
- clear();
- filters.clear();
- TQString delim = TQString::fromLatin1(", ");
- d->hasAllSupportedFiles = false;
-
- m_allTypes = defaultType.isEmpty() && (types.count() > 1);
-
- TQString allComments, allTypes;
- int i = 0;
- for(TQStringList::ConstIterator it = types.begin(); it != types.end(); ++it, ++i)
- {
- if ( m_allTypes && it != types.begin() ) {
- allComments += delim;
- allTypes += ' ';
- }
-
- kdDebug(kfile_area) << *it << endl;
- KMimeType::Ptr type = KMimeType::mimeType( *it );
- filters.append( type->name() );
- if ( m_allTypes )
- {
- allTypes += type->name();
- allComments += type->comment();
- }
- insertItem( type->comment() );
- if ( type->name() == defaultType )
- setCurrentItem( i );
- }
-
- if ( m_allTypes )
- {
- if ( i < 3 ) // show the mime-comments of at max 3 types
- insertItem( allComments, 0 );
- else {
- insertItem( i18n("All Supported Files"), 0 );
- d->hasAllSupportedFiles = true;
- }
-
- filters.prepend( allTypes );
- }
-
- d->lastFilter = currentText();
- d->isMimeFilter = true;
-}
-
-void KFileFilterCombo::slotFilterChanged()
-{
- d->lastFilter = currentText();
-}
-
-bool KFileFilterCombo::eventFilter( TQObject *o, TQEvent *e )
-{
- if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(lineEdit()) && e->type() == TQEvent::FocusOut ) {
- if ( currentText() != d->lastFilter )
- emit filterChanged();
- }
-
- return KComboBox::eventFilter( o, e );
-}
-
-void KFileFilterCombo::setDefaultFilter( const TQString& filter )
-{
- d->defaultFilter = filter;
-}
-
-TQString KFileFilterCombo::defaultFilter() const
-{
- return d->defaultFilter;
-}
-
-void KFileFilterCombo::virtual_hook( int id, void* data )
-{ KComboBox::virtual_hook( id, data ); }
-
-#include "kfilefiltercombo.moc"
diff --git a/kio/kfile/kfileiconview.cpp b/kio/kfile/kfileiconview.cpp
deleted file mode 100644
index f0ef11bfe..000000000
--- a/kio/kfile/kfileiconview.cpp
+++ /dev/null
@@ -1,943 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
- 2000,2001,2002 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#include <tqt.h>
-
-#include <tqfontmetrics.h>
-#include <tqkeycode.h>
-#include <tqlabel.h>
-#include <tqpainter.h>
-#include <tqpixmap.h>
-#include <tqregexp.h>
-#include <tqtimer.h>
-#include <tqtooltip.h>
-
-#include <kaction.h>
-#include <kapplication.h>
-#include <klocale.h>
-#include <kfileitem.h>
-#include <kiconeffect.h>
-#include <kglobalsettings.h>
-#include <kurldrag.h>
-#include <kio/previewjob.h>
-
-#include "kfileiconview.h"
-#include "config-kfile.h"
-
-#define DEFAULT_PREVIEW_SIZE 60
-#define DEFAULT_SHOW_PREVIEWS false
-#define DEFAULT_VIEW_MODE "SmallColumns"
-
-KFileIconViewItem::~KFileIconViewItem()
-{
- fileInfo()->removeExtraData( iconView() );
-}
-
-class KFileIconView::KFileIconViewPrivate
-{
-public:
- KFileIconViewPrivate( KFileIconView *parent ) {
- previewIconSize = 60;
- job = 0;
- dropItem = 0;
-
- noArrangement = false;
- ignoreMaximumSize = false;
- smallColumns = new KRadioAction( i18n("Small Icons"), 0, TQT_TQOBJECT(parent),
- TQT_SLOT( slotSmallColumns() ),
- parent->actionCollection(),
- "small columns" );
-
- largeRows = new KRadioAction( i18n("Large Icons"), 0, TQT_TQOBJECT(parent),
- TQT_SLOT( slotLargeRows() ),
- parent->actionCollection(),
- "large rows" );
-
- smallColumns->setExclusiveGroup(TQString::fromLatin1("IconView mode"));
- largeRows->setExclusiveGroup(TQString::fromLatin1("IconView mode"));
-
- previews = new KToggleAction( i18n("Thumbnail Previews"), 0,
- parent->actionCollection(),
- "show previews" );
- zoomIn = KStdAction::zoomIn( TQT_TQOBJECT(parent), TQT_SLOT( zoomIn() ),
- parent->actionCollection(), "zoomIn" );
- zoomOut = KStdAction::zoomOut( TQT_TQOBJECT(parent), TQT_SLOT( zoomOut() ),
- parent->actionCollection(), "zoomOut" );
-
- previews->setGroup("previews");
- zoomIn->setGroup("previews");
- zoomOut->setGroup("previews");
-
- connect( previews, TQT_SIGNAL( toggled( bool )),
- parent, TQT_SLOT( slotPreviewsToggled( bool )));
-
- connect( &previewTimer, TQT_SIGNAL( timeout() ),
- parent, TQT_SLOT( showPreviews() ));
- connect( &autoOpenTimer, TQT_SIGNAL( timeout() ),
- parent, TQT_SLOT( slotAutoOpen() ));
- }
-
- ~KFileIconViewPrivate() {
- if ( job )
- job->kill();
- }
-
- KRadioAction *smallColumns, *largeRows;
- KAction *zoomIn, *zoomOut;
- KToggleAction *previews;
- TDEIO::PreviewJob *job;
- KFileIconViewItem *dropItem;
- TQTimer previewTimer;
- TQTimer autoOpenTimer;
- TQStringList previewMimeTypes;
- int previewIconSize;
- bool noArrangement :1;
- bool ignoreMaximumSize :1;
-};
-
-KFileIconView::KFileIconView(TQWidget *parent, const char *name)
- : KIconView(parent, name), KFileView()
-{
- d = new KFileIconViewPrivate( this );
-
- setViewName( i18n("Icon View") );
-
- toolTip = 0;
- setResizeMode( Adjust );
- setMaxItemWidth( 300 );
- setWordWrapIconText( false );
- setArrangement( TopToBottom );
- setAutoArrange( true );
- setItemsMovable( false );
- setMode( KIconView::Select );
- KIconView::setSorting( true );
- // as long as TQIconView only shows tooltips when the cursor is over the
- // icon (and not the text), we have to create our own tooltips
- setShowToolTips( false );
- slotSmallColumns();
- d->smallColumns->setChecked( true );
-
- connect( this, TQT_SIGNAL( returnPressed(TQIconViewItem *) ),
- TQT_SLOT( slotActivate( TQIconViewItem *) ) );
-
- // we want single click _and_ double click (as convenience)
- connect( this, TQT_SIGNAL( clicked(TQIconViewItem *, const TQPoint&) ),
- TQT_SLOT( selected( TQIconViewItem *) ) );
- connect( this, TQT_SIGNAL( doubleClicked(TQIconViewItem *, const TQPoint&) ),
- TQT_SLOT( slotActivate( TQIconViewItem *) ) );
-
- connect( this, TQT_SIGNAL( onItem( TQIconViewItem * ) ),
- TQT_SLOT( showToolTip( TQIconViewItem * ) ) );
- connect( this, TQT_SIGNAL( onViewport() ),
- TQT_SLOT( removeToolTip() ) );
- connect( this, TQT_SIGNAL( contextMenuRequested(TQIconViewItem*,const TQPoint&)),
- TQT_SLOT( slotActivateMenu( TQIconViewItem*, const TQPoint& ) ) );
-
- KFile::SelectionMode sm = KFileView::selectionMode();
- switch ( sm ) {
- case KFile::Multi:
- TQIconView::setSelectionMode( TQIconView::Multi );
- break;
- case KFile::Extended:
- TQIconView::setSelectionMode( TQIconView::Extended );
- break;
- case KFile::NoSelection:
- TQIconView::setSelectionMode( TQIconView::NoSelection );
- break;
- default: // fall through
- case KFile::Single:
- TQIconView::setSelectionMode( TQIconView::Single );
- break;
- }
-
- if ( sm == KFile::Multi || sm == KFile::Extended )
- connect( this, TQT_SIGNAL( selectionChanged() ),
- TQT_SLOT( slotSelectionChanged() ));
- else
- connect( this, TQT_SIGNAL( selectionChanged( TQIconViewItem * )),
- TQT_SLOT( highlighted( TQIconViewItem * )));
-
- viewport()->installEventFilter( this );
-
- // for mimetype resolving
- m_resolver = new KMimeTypeResolver<KFileIconViewItem,KFileIconView>(this);
-}
-
-KFileIconView::~KFileIconView()
-{
- delete m_resolver;
- removeToolTip();
- delete d;
-}
-
-void KFileIconView::readConfig( TDEConfig *kc, const TQString& group )
-{
- TQString gr = group.isEmpty() ? TQString("KFileIconView") : group;
- TDEConfigGroupSaver cs( kc, gr );
- TQString small = TQString::fromLatin1("SmallColumns");
- d->previewIconSize = kc->readNumEntry( "Preview Size", DEFAULT_PREVIEW_SIZE );
- d->previews->setChecked( kc->readBoolEntry( "ShowPreviews", DEFAULT_SHOW_PREVIEWS ) );
-
- if ( kc->readEntry("ViewMode", DEFAULT_VIEW_MODE ) == small ) {
- d->smallColumns->setChecked( true );
- slotSmallColumns();
- }
- else {
- d->largeRows->setChecked( true );
- slotLargeRows();
- }
-
- if ( d->previews->isChecked() )
- showPreviews();
-}
-
-void KFileIconView::writeConfig( TDEConfig *kc, const TQString& group )
-{
- TQString gr = group.isEmpty() ? TQString("KFileIconView") : group;
- TDEConfigGroupSaver cs( kc, gr );
-
- TQString viewMode = d->smallColumns->isChecked() ?
- TQString::fromLatin1("SmallColumns") :
- TQString::fromLatin1("LargeRows");
- if(!kc->hasDefault( "ViewMode" ) && viewMode == DEFAULT_VIEW_MODE )
- kc->revertToDefault( "ViewMode" );
- else
- kc->writeEntry( "ViewMode", viewMode );
-
- int previewsIconSize = d->previewIconSize;
- if(!kc->hasDefault( "Preview Size" ) && previewsIconSize == DEFAULT_PREVIEW_SIZE )
- kc->revertToDefault( "Preview Size" );
- else
- kc->writeEntry( "Preview Size", previewsIconSize );
-
- bool showPreviews = d->previews->isChecked();
- if(!kc->hasDefault( "ShowPreviews" ) && showPreviews == DEFAULT_SHOW_PREVIEWS )
- kc->revertToDefault( "ShowPreviews" );
- else
- kc->writeEntry( "ShowPreviews", showPreviews );
-}
-
-void KFileIconView::removeToolTip()
-{
- delete toolTip;
- toolTip = 0;
-}
-
-void KFileIconView::showToolTip( TQIconViewItem *item )
-{
- delete toolTip;
- toolTip = 0;
-
- if ( !item )
- return;
-
- int w = maxItemWidth() - ( itemTextPos() == TQIconView::Bottom ? 0 :
- item->pixmapRect().width() ) - 4;
- if ( fontMetrics().width( item->text() ) >= w ) {
- toolTip = new TQLabel( TQString::fromLatin1(" %1 ").arg(item->text()), 0,
- "myToolTip",
- (WFlags)(WStyle_StaysOnTop | WStyle_Customize | WStyle_NoBorder | WStyle_Tool | WX11BypassWM) );
- toolTip->setFrameStyle( TQFrame::Plain | TQFrame::Box );
- toolTip->setLineWidth( 1 );
- toolTip->setAlignment( AlignLeft | AlignTop );
- toolTip->move( TQCursor::pos() + TQPoint( 14, 14 ) );
- toolTip->adjustSize();
- TQRect screen = TQApplication::desktop()->screenGeometry(
- TQApplication::desktop()->screenNumber(TQCursor::pos()));
- if (toolTip->x()+toolTip->width() > screen.right()) {
- toolTip->move(toolTip->x()+screen.right()-toolTip->x()-toolTip->width(), toolTip->y());
- }
- if (toolTip->y()+toolTip->height() > screen.bottom()) {
- toolTip->move(toolTip->x(), screen.bottom()-toolTip->y()-toolTip->height()+toolTip->y());
- }
- toolTip->setFont( TQToolTip::font() );
- toolTip->setPalette( TQToolTip::palette(), true );
- toolTip->show();
- }
-}
-
-void KFileIconView::slotActivateMenu( TQIconViewItem* item, const TQPoint& pos )
-{
- if ( !item ) {
- sig->activateMenu( 0, pos );
- return;
- }
- KFileIconViewItem *i = (KFileIconViewItem*) item;
- sig->activateMenu( i->fileInfo(), pos );
-}
-
-void KFileIconView::hideEvent( TQHideEvent *e )
-{
- removeToolTip();
- KIconView::hideEvent( e );
-}
-
-void KFileIconView::keyPressEvent( TQKeyEvent *e )
-{
- KIconView::keyPressEvent( e );
-
- // ignore Ctrl-Return so that the dialog can catch it.
- if ( (e->state() & ControlButton) &&
- (e->key() == Key_Return || e->key() == Key_Enter) )
- e->ignore();
-}
-
-void KFileIconView::setSelected( const KFileItem *info, bool enable )
-{
- KFileIconViewItem *item = viewItem( info );
- if ( item )
- KIconView::setSelected( item, enable, true );
-}
-
-void KFileIconView::selectAll()
-{
- if (KFileView::selectionMode() == KFile::NoSelection ||
- KFileView::selectionMode() == KFile::Single)
- return;
-
- KIconView::selectAll( true );
-}
-
-void KFileIconView::clearSelection()
-{
- KIconView::clearSelection();
-}
-
-void KFileIconView::invertSelection()
-{
- KIconView::invertSelection();
-}
-
-void KFileIconView::clearView()
-{
- m_resolver->m_lstPendingMimeIconItems.clear();
-
- KIconView::clear();
- stopPreview();
-}
-
-void KFileIconView::insertItem( KFileItem *i )
-{
- KFileView::insertItem( i );
-
- TQIconView* qview = static_cast<TQIconView*>( this );
- // Since creating and initializing an item leads to a repaint,
- // we disable updates on the IconView for a while.
- qview->setUpdatesEnabled( false );
- KFileIconViewItem *item = new KFileIconViewItem( qview, i );
- initItem( item, i, true );
- qview->setUpdatesEnabled( true );
-
- if ( !i->isMimeTypeKnown() )
- m_resolver->m_lstPendingMimeIconItems.append( item );
-
- i->setExtraData( this, item );
-}
-
-void KFileIconView::slotActivate( TQIconViewItem *item )
-{
- if ( !item )
- return;
- const KFileItem *fi = ( (KFileIconViewItem*)item )->fileInfo();
- if ( fi )
- sig->activate( fi );
-}
-
-void KFileIconView::selected( TQIconViewItem *item )
-{
- if ( !item || (TDEApplication::keyboardMouseState() & (ShiftButton | ControlButton)) != 0 )
- return;
-
- if ( TDEGlobalSettings::singleClick() ) {
- const KFileItem *fi = ( (KFileIconViewItem*)item )->fileInfo();
- if ( fi && (fi->isDir() || !onlyDoubleClickSelectsFiles()) )
- sig->activate( fi );
- }
-}
-
-void KFileIconView::setCurrentItem( const KFileItem *item )
-{
- KFileIconViewItem *it = viewItem( item );
- if ( it )
- KIconView::setCurrentItem( it );
-}
-
-KFileItem * KFileIconView::currentFileItem() const
-{
- KFileIconViewItem *current = static_cast<KFileIconViewItem*>( currentItem() );
- if ( current )
- return current->fileInfo();
-
- return 0L;
-}
-
-void KFileIconView::highlighted( TQIconViewItem *item )
-{
- if ( !item )
- return;
- const KFileItem *fi = ( (KFileIconViewItem*)item )->fileInfo();
- if ( fi )
- sig->highlightFile( fi );
-}
-
-void KFileIconView::setSelectionMode( KFile::SelectionMode sm )
-{
- disconnect( TQT_SIGNAL( selectionChanged() ), this );
- disconnect( TQT_SIGNAL( selectionChanged( TQIconViewItem * )), this );
-
- KFileView::setSelectionMode( sm );
- switch ( KFileView::selectionMode() ) {
- case KFile::Multi:
- TQIconView::setSelectionMode( TQIconView::Multi );
- break;
- case KFile::Extended:
- TQIconView::setSelectionMode( TQIconView::Extended );
- break;
- case KFile::NoSelection:
- TQIconView::setSelectionMode( TQIconView::NoSelection );
- break;
- default: // fall through
- case KFile::Single:
- TQIconView::setSelectionMode( TQIconView::Single );
- break;
- }
-
- if ( sm == KFile::Multi || sm == KFile::Extended )
- connect( this, TQT_SIGNAL( selectionChanged() ),
- TQT_SLOT( slotSelectionChanged() ));
- else
- connect( this, TQT_SIGNAL( selectionChanged( TQIconViewItem * )),
- TQT_SLOT( highlighted( TQIconViewItem * )));
-}
-
-bool KFileIconView::isSelected( const KFileItem *i ) const
-{
- KFileIconViewItem *item = viewItem( i );
- return (item && item->isSelected());
-}
-
-void KFileIconView::updateView( bool b )
-{
- if ( !b )
- return; // eh?
-
- KFileIconViewItem *item = static_cast<KFileIconViewItem*>(TQIconView::firstItem());
- if ( item ) {
- do {
- if ( d->previews->isChecked() ) {
- if ( canPreview( item->fileInfo() ) )
- item->setPixmapSize( TQSize( d->previewIconSize, d->previewIconSize ) );
- }
- else {
- // unset pixmap size (used for previews)
- if ( !item->pixmapSize().isNull() )
- item->setPixmapSize( TQSize( 0, 0 ) );
- }
- // recalculate item parameters but avoid an in-place repaint
- item->setPixmap( (item->fileInfo())->pixmap( myIconSize ), true, false );
- item = static_cast<KFileIconViewItem *>(item->nextItem());
- } while ( item != 0L );
- }
-}
-
-void KFileIconView::updateView( const KFileItem *i )
-{
- KFileIconViewItem *item = viewItem( i );
- if ( item )
- initItem( item, i, true );
-}
-
-void KFileIconView::removeItem( const KFileItem *i )
-{
- if ( !i )
- return;
-
- if ( d->job )
- d->job->removeItem( i );
-
- KFileIconViewItem *item = viewItem( i );
- m_resolver->m_lstPendingMimeIconItems.remove( item );
- delete item;
-
- KFileView::removeItem( i );
-}
-
-void KFileIconView::setIconSize( int size )
-{
- myIconSize = size;
- updateIcons();
-}
-
-void KFileIconView::setPreviewSize( int size )
-{
- if ( size < 30 )
- size = 30; // minimum
-
- d->previewIconSize = size;
- if ( d->previews->isChecked() )
- showPreviews();
-}
-
-void KFileIconView::setIgnoreMaximumSize(bool ignoreSize)
-{
- d->ignoreMaximumSize = ignoreSize;
-}
-
-void KFileIconView::updateIcons()
-{
- updateView( true );
- arrangeItemsInGrid();
-}
-
-void KFileIconView::ensureItemVisible( const KFileItem *i )
-{
- KFileIconViewItem *item = viewItem( i );
- if ( item )
- KIconView::ensureItemVisible( item );
-}
-
-void KFileIconView::slotSelectionChanged()
-{
- sig->highlightFile( 0L );
-}
-
-void KFileIconView::slotSmallColumns()
-{
- // setItemTextPos(), setArrangement(), setWordWrapIconText() and
- // setIconSize() all call arrangeItemsInGrid() :( Prevent this.
- d->noArrangement = true; // stop arrangeItemsInGrid()!
-
- // Make sure to uncheck previews if selected
- if ( d->previews->isChecked() )
- {
- stopPreview();
- d->previews->setChecked( false );
- }
- setGridX( -1 );
- setMaxItemWidth( 300 );
- setItemTextPos( Right );
- setArrangement( TopToBottom );
- setWordWrapIconText( false );
- setSpacing( 0 );
-
- d->noArrangement = false; // now we can arrange
- setIconSize( KIcon::SizeSmall );
-}
-
-void KFileIconView::slotLargeRows()
-{
- // setItemTextPos(), setArrangement(), setWordWrapIconText() and
- // setIconSize() all call arrangeItemsInGrid() :( Prevent this.
- d->noArrangement = true; // stop arrangeItemsInGrid()!
-
- setGridX( TDEGlobal::iconLoader()->currentSize( KIcon::Desktop ) + 50 );
- setItemTextPos( Bottom );
- setArrangement( LeftToRight );
- setWordWrapIconText( true );
- setSpacing( 5 ); // default in QIconView
-
- d->noArrangement = false; // now we can arrange
- setIconSize( KIcon::SizeMedium );
-}
-
-void KFileIconView::stopPreview()
-{
- if ( d->job ) {
- d->job->kill();
- d->job = 0L;
- }
-}
-
-void KFileIconView::slotPreviewsToggled( bool on )
-{
- if ( on )
- showPreviews();
- else {
- stopPreview();
- slotLargeRows();
- }
-}
-
-void KFileIconView::showPreviews()
-{
- if ( d->previewMimeTypes.isEmpty() )
- d->previewMimeTypes = TDEIO::PreviewJob::supportedMimeTypes();
-
- stopPreview();
- d->previews->setChecked( true );
-
- if ( !d->largeRows->isChecked() ) {
- d->largeRows->setChecked( true );
- slotLargeRows(); // also sets the icon size and updates the grid
- }
- else {
- updateIcons();
- }
-
- d->job = TDEIO::filePreview(*items(), d->previewIconSize,d->previewIconSize);
- d->job->setIgnoreMaximumSize(d->ignoreMaximumSize);
-
- connect( d->job, TQT_SIGNAL( result( TDEIO::Job * )),
- this, TQT_SLOT( slotPreviewResult( TDEIO::Job * )));
- connect( d->job, TQT_SIGNAL( gotPreview( const KFileItem*, const TQPixmap& )),
- TQT_SLOT( gotPreview( const KFileItem*, const TQPixmap& ) ));
-// connect( d->job, TQT_SIGNAL( failed( const KFileItem* )),
-// this, TQT_SLOT( slotFailed( const KFileItem* ) ));
-}
-
-void KFileIconView::slotPreviewResult( TDEIO::Job *job )
-{
- if ( job == d->job )
- d->job = 0L;
-}
-
-void KFileIconView::gotPreview( const KFileItem *item, const TQPixmap& pix )
-{
- KFileIconViewItem *it = viewItem( item );
- if ( it )
- if( item->overlays() & KIcon::HiddenOverlay )
- {
- TQPixmap p( pix );
-
- KIconEffect::semiTransparent( p );
- it->setPixmap( p );
- }
- else
- it->setPixmap( pix );
-}
-
-bool KFileIconView::canPreview( const KFileItem *item ) const
-{
- TQStringList::Iterator it = d->previewMimeTypes.begin();
- TQRegExp r;
- r.setWildcard( true );
-
- for ( ; it != d->previewMimeTypes.end(); ++it ) {
- TQString type = *it;
- // the "mimetype" can be "image/*"
- if ( type.at( type.length() - 1 ) == '*' ) {
- r.setPattern( type );
- if ( r.search( item->mimetype() ) != -1 )
- return true;
- }
- else
- if ( item->mimetype() == type )
- return true;
- }
-
- return false;
-}
-
-KFileItem * KFileIconView::firstFileItem() const
-{
- KFileIconViewItem *item = static_cast<KFileIconViewItem*>( firstItem() );
- if ( item )
- return item->fileInfo();
- return 0L;
-}
-
-KFileItem * KFileIconView::nextItem( const KFileItem *fileItem ) const
-{
- if ( fileItem ) {
- KFileIconViewItem *item = viewItem( fileItem );
- if ( item && item->nextItem() )
- return ((KFileIconViewItem*) item->nextItem())->fileInfo();
- }
- return 0L;
-}
-
-KFileItem * KFileIconView::prevItem( const KFileItem *fileItem ) const
-{
- if ( fileItem ) {
- KFileIconViewItem *item = viewItem( fileItem );
- if ( item && item->prevItem() )
- return ((KFileIconViewItem*) item->prevItem())->fileInfo();
- }
- return 0L;
-}
-
-void KFileIconView::setSorting( TQDir::SortSpec spec )
-{
- KFileView::setSorting( spec );
- KFileItemListIterator it( *items() );
-
- KFileItem *item;
-
- if ( spec & TQDir::Time ) {
- for ( ; (item = it.current()); ++it )
- // warning, time_t is often signed -> cast it
- viewItem(item)->setKey( sortingKey( (unsigned long)item->time( TDEIO::UDS_MODIFICATION_TIME ), item->isDir(), spec ));
- }
-
- else if ( spec & TQDir::Size ) {
- for ( ; (item = it.current()); ++it )
- viewItem(item)->setKey( sortingKey( item->size(), item->isDir(),
- spec ));
- }
- else { // Name or Unsorted
- for ( ; (item = it.current()); ++it )
- viewItem(item)->setKey( sortingKey( item->text(), item->isDir(),
- spec ));
- }
-
- KIconView::setSorting( true, !isReversed() );
- sort( !isReversed() );
-}
-
-//
-// mimetype determination on demand
-//
-void KFileIconView::mimeTypeDeterminationFinished()
-{
- // anything to do?
-}
-
-void KFileIconView::determineIcon( KFileIconViewItem *item )
-{
- (void) item->fileInfo()->determineMimeType();
- updateView( item->fileInfo() );
-}
-
-void KFileIconView::listingCompleted()
-{
- arrangeItemsInGrid();
-
- // TQIconView doesn't set the current item automatically, so we have to do
- // that. We don't want to emit selectionChanged() tho.
- if ( !currentItem() ) {
- bool block = signalsBlocked();
- blockSignals( true );
- TQIconViewItem *item = viewItem( firstFileItem() );
- KIconView::setCurrentItem( item );
- KIconView::setSelected( item, false );
- blockSignals( block );
- }
-
- m_resolver->start( d->previews->isChecked() ? 0 : 10 );
-}
-
-// need to remove our tooltip, eventually
-bool KFileIconView::eventFilter( TQObject *o, TQEvent *e )
-{
- if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(viewport()) || TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(this) ) {
- int type = e->type();
- if ( type == TQEvent::Leave ||
- type == TQEvent::FocusOut )
- removeToolTip();
- }
-
- return KIconView::eventFilter( o, e );
-}
-
-/////////////////////////////////////////////////////////////////
-
-// ### workaround for Qt3 Bug
-void KFileIconView::showEvent( TQShowEvent *e )
-{
- KIconView::showEvent( e );
-}
-
-
-void KFileIconView::initItem( KFileIconViewItem *item, const KFileItem *i,
- bool updateTextAndPixmap )
-{
- if ( d->previews->isChecked() && canPreview( i ) )
- item->setPixmapSize( TQSize( d->previewIconSize, d->previewIconSize ) );
-
- if ( updateTextAndPixmap )
- {
- // this causes a repaint of the item, which we want to avoid during
- // directory listing, when all items are created. We want to paint all
- // items at once, not every single item in that case.
- item->setText( i->text() , false, false );
- item->setPixmap( i->pixmap( myIconSize ) );
- }
-
- // see also setSorting()
- TQDir::SortSpec spec = KFileView::sorting();
-
- if ( spec & TQDir::Time )
- // warning, time_t is often signed -> cast it
- item->setKey( sortingKey( (unsigned long) i->time( TDEIO::UDS_MODIFICATION_TIME ),
- i->isDir(), spec ));
- else if ( spec & TQDir::Size )
- item->setKey( sortingKey( i->size(), i->isDir(), spec ));
-
- else // Name or Unsorted
- item->setKey( sortingKey( i->text(), i->isDir(), spec ));
-
- //tqDebug("** key for: %s: %s", i->text().latin1(), item->key().latin1());
-
- if ( d->previews->isChecked() )
- d->previewTimer.start( 10, true );
-}
-
-void KFileIconView::arrangeItemsInGrid( bool update )
-{
- if ( d->noArrangement )
- return;
-
- KIconView::arrangeItemsInGrid( update );
-}
-
-void KFileIconView::zoomIn()
-{
- setPreviewSize( d->previewIconSize + 30 );
-}
-
-void KFileIconView::zoomOut()
-{
- setPreviewSize( d->previewIconSize - 30 );
-}
-
-TQDragObject *KFileIconView::dragObject()
-{
- // create a list of the URL:s that we want to drag
- KURL::List urls;
- KFileItemListIterator it( * KFileView::selectedItems() );
- for ( ; it.current(); ++it ){
- urls.append( (*it)->url() );
- }
- TQPixmap pixmap;
- if( urls.count() > 1 )
- pixmap = DesktopIcon( "tdemultiple", iconSize() );
- if( pixmap.isNull() )
- pixmap = currentFileItem()->pixmap( iconSize() );
-
- TQPoint hotspot;
- hotspot.setX( pixmap.width() / 2 );
- hotspot.setY( pixmap.height() / 2 );
- TQDragObject* myDragObject = new KURLDrag( urls, widget() );
- myDragObject->setPixmap( pixmap, hotspot );
- return myDragObject;
-}
-
-void KFileIconView::slotAutoOpen()
-{
- d->autoOpenTimer.stop();
- if( !d->dropItem )
- return;
-
- KFileItem *fileItem = d->dropItem->fileInfo();
- if (!fileItem)
- return;
-
- if( fileItem->isFile() )
- return;
-
- if ( fileItem->isDir() || fileItem->isLink())
- sig->activate( fileItem );
-}
-
-bool KFileIconView::acceptDrag(TQDropEvent* e) const
-{
- return KURLDrag::canDecode( e ) &&
- (e->source()!=const_cast<KFileIconView*>(this)) &&
- ( e->action() == TQDropEvent::Copy
- || e->action() == TQDropEvent::Move
- || e->action() == TQDropEvent::Link );
-}
-
-void KFileIconView::contentsDragEnterEvent( TQDragEnterEvent *e )
-{
- if ( ! acceptDrag( e ) ) { // can we decode this ?
- e->ignore(); // No
- return;
- }
- e->acceptAction(); // Yes
-
- if ((dropOptions() & AutoOpenDirs) == 0)
- return;
-
- KFileIconViewItem *item = dynamic_cast<KFileIconViewItem*>(findItem( contentsToViewport( e->pos() ) ));
- if ( item ) { // are we over an item ?
- d->dropItem = item;
- d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
- }
- else
- {
- d->dropItem = 0;
- d->autoOpenTimer.stop();
- }
-}
-
-void KFileIconView::contentsDragMoveEvent( TQDragMoveEvent *e )
-{
- if ( ! acceptDrag( e ) ) { // can we decode this ?
- e->ignore(); // No
- return;
- }
- e->acceptAction(); // Yes
-
- if ((dropOptions() & AutoOpenDirs) == 0)
- return;
-
- KFileIconViewItem *item = dynamic_cast<KFileIconViewItem*>(findItem( contentsToViewport( e->pos() ) ));
- if ( item ) { // are we over an item ?
- if (d->dropItem != item)
- {
- d->dropItem = item;
- d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
- }
- }
- else
- {
- d->dropItem = 0;
- d->autoOpenTimer.stop();
- }
-}
-
-void KFileIconView::contentsDragLeaveEvent( TQDragLeaveEvent * )
-{
- d->dropItem = 0;
- d->autoOpenTimer.stop();
-}
-
-void KFileIconView::contentsDropEvent( TQDropEvent *e )
-{
- d->dropItem = 0;
- d->autoOpenTimer.stop();
-
- if ( ! acceptDrag( e ) ) { // can we decode this ?
- e->ignore(); // No
- return;
- }
- e->acceptAction(); // Yes
-
- KFileIconViewItem *item = dynamic_cast<KFileIconViewItem*>(findItem( contentsToViewport( e->pos() ) ));
- KFileItem * fileItem = 0;
- if (item)
- fileItem = item->fileInfo();
-
- emit dropped(e, fileItem);
-
- KURL::List urls;
- if (KURLDrag::decode( e, urls ) && !urls.isEmpty())
- {
- emit dropped(e, urls, fileItem ? fileItem->url() : KURL());
- sig->dropURLs(fileItem, e, urls);
- }
-}
-
-void KFileIconView::virtual_hook( int id, void* data )
-{ KIconView::virtual_hook( id, data );
- KFileView::virtual_hook( id, data ); }
-
-#include "kfileiconview.moc"
diff --git a/kio/kfile/kfileiconview.h b/kio/kfile/kfileiconview.h
deleted file mode 100644
index 98afc0a6e..000000000
--- a/kio/kfile/kfileiconview.h
+++ /dev/null
@@ -1,267 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef KFILEICONVIEW_H
-#define KFILEICONVIEW_H
-
-#include <tqt.h>
-
-#include <kiconview.h>
-#include <kiconloader.h>
-#include <kfileview.h>
-#include <kmimetyperesolver.h>
-#include <kfile.h>
-
-class KFileItem;
-class TQWidget;
-class TQLabel;
-
-/**
- * An item for the iconview, that has a reference to its corresponding
- * KFileItem.
- */
-class TDEIO_EXPORT KFileIconViewItem : public KIconViewItem
-{
-public:
- KFileIconViewItem( TQIconView *parent, const TQString &text,
- const TQPixmap &pixmap,
- KFileItem *fi )
- : KIconViewItem( parent, text, pixmap ), inf( fi ) {}
- /**
- * @since 3.1
- */
- KFileIconViewItem( TQIconView *parent, KFileItem *fi )
- : KIconViewItem( parent ), inf( fi ) {}
-
- virtual ~KFileIconViewItem();
-
- /**
- * @returns the corresponding KFileItem
- */
- KFileItem *fileInfo() const {
- return inf;
- }
-
-private:
- KFileItem *inf;
-
-private:
- class KFileIconViewItemPrivate;
- KFileIconViewItemPrivate *d;
-
-};
-
-namespace TDEIO {
- class Job;
-}
-
-/**
- * An icon-view capable of showing KFileItem's. Used in the filedialog
- * for example. Most of the documentation is in KFileView class.
- *
- * @see KDirOperator
- * @see KCombiView
- * @see KFileDetailView
- */
-class TDEIO_EXPORT KFileIconView : public KIconView, public KFileView
-{
- Q_OBJECT
-
-public:
- KFileIconView(TQWidget *parent, const char *name);
- virtual ~KFileIconView();
-
- virtual TQWidget *widget() { return this; }
- virtual void clearView();
- virtual void setAutoUpdate( bool ) {} // ### unused. remove in KDE4
-
- virtual void updateView( bool );
- virtual void updateView(const KFileItem*);
- virtual void removeItem(const KFileItem*);
-
- virtual void listingCompleted();
-
- virtual void insertItem( KFileItem *i );
- virtual void setSelectionMode( KFile::SelectionMode sm );
-
- virtual void setSelected(const KFileItem *, bool);
- virtual bool isSelected(const KFileItem *i) const;
- virtual void clearSelection();
- virtual void selectAll();
- virtual void invertSelection();
-
- virtual void setCurrentItem( const KFileItem * );
- virtual KFileItem * currentFileItem() const;
- virtual KFileItem * firstFileItem() const;
- virtual KFileItem * nextItem( const KFileItem * ) const;
- virtual KFileItem * prevItem( const KFileItem * ) const;
-
- /**
- * Sets the size of the icons to show. Defaults to KIcon::SizeSmall.
- */
- void setIconSize( int size );
-
- /**
- * Sets the size of the previews. Defaults to KIcon::SizeLarge.
- */
- void setPreviewSize( int size );
-
- /**
- * Disables the "Maximum file size" configuration option for previews
- *
- * Set this before calling showPreviews()
- *
- * @since 3.4
- **/
- void setIgnoreMaximumSize(bool ignoreSize=true);
-
- /**
- * @returns the current size used for icons.
- */
- int iconSize() const { return myIconSize; }
-
- void ensureItemVisible( const KFileItem * );
-
- virtual void setSorting(TQDir::SortSpec sort);
-
- virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
- virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
-
- // for KMimeTypeResolver
- void mimeTypeDeterminationFinished();
- void determineIcon( KFileIconViewItem *item );
- TQScrollView *scrollWidget() const { return (TQScrollView*) this; }
- void setAcceptDrops(bool b)
- {
- KIconView::setAcceptDrops(b);
- viewport()->setAcceptDrops(b);
- }
-
-public slots:
- /**
- * Starts loading previews for all files shown and shows them. Switches
- * into 'large rows' mode, if that isn't the current mode yet.
- *
- * @sa setIgnoreMaximumSize
- */
- void showPreviews();
-
- void zoomIn();
-
- void zoomOut();
-
- /**
- * Reimplemented for performance reasons.
- * @since 3.1
- */
- virtual void arrangeItemsInGrid( bool updated = true );
-
-protected:
- /**
- * Reimplemented to not let TQIconView eat return-key events
- */
- virtual void keyPressEvent( TQKeyEvent * );
-
- /**
- * Reimplemented to remove an eventual tooltip
- */
- virtual void hideEvent( TQHideEvent * );
-
- // ### workaround for Qt3 bug (see #35080)
- virtual void showEvent( TQShowEvent * );
-
- virtual bool eventFilter( TQObject *o, TQEvent *e );
-
- // DND support
- virtual TQDragObject *dragObject();
- virtual void contentsDragEnterEvent( TQDragEnterEvent *e );
- virtual void contentsDragMoveEvent( TQDragMoveEvent *e );
- virtual void contentsDragLeaveEvent( TQDragLeaveEvent *e );
- virtual void contentsDropEvent( TQDropEvent *ev );
-
- // KDE4: Make virtual
- bool acceptDrag(TQDropEvent* e ) const;
-
-private slots:
- void selected( TQIconViewItem *item );
- void slotActivate( TQIconViewItem * );
- void highlighted( TQIconViewItem *item );
- void showToolTip( TQIconViewItem *item );
- void removeToolTip();
- void slotActivateMenu( TQIconViewItem *, const TQPoint& );
- void slotSelectionChanged();
-
- void slotSmallColumns();
- void slotLargeRows();
- void slotPreviewsToggled( bool );
-
- void slotPreviewResult( TDEIO::Job * );
- void gotPreview( const KFileItem *item, const TQPixmap& pix );
- void slotAutoOpen();
-
-signals:
- /**
- * The user dropped something.
- * @p fileItem points to the item dropped on or can be 0 if the
- * user dropped on empty space.
- * @since 3.2
- */
- void dropped(TQDropEvent *event, KFileItem *fileItem);
- /**
- * The user dropped the URLs @p urls.
- * @p url points to the item dropped on or can be empty if the
- * user dropped on empty space.
- * @since 3.2
- */
- void dropped(TQDropEvent *event, const KURL::List &urls, const KURL &url);
-
-private:
- KMimeTypeResolver<KFileIconViewItem,KFileIconView> *m_resolver;
-
- TQLabel *toolTip;
- int th;
- int myIconSize;
-
- virtual void insertItem(TQIconViewItem *a, TQIconViewItem *b) { KIconView::insertItem(a, b); }
- virtual void setSelectionMode(TQIconView::SelectionMode m) { KIconView::setSelectionMode(m); }
- virtual void setSelected(TQIconViewItem *i, bool a, bool b) { KIconView::setSelected(i, a, b); }
-
- bool canPreview( const KFileItem * ) const;
- void stopPreview();
-
- void updateIcons();
-
- inline KFileIconViewItem * viewItem( const KFileItem *item ) const {
- if ( item )
- return (KFileIconViewItem *) item->extraData( this );
- return 0L;
- }
-
- void initItem(KFileIconViewItem *item, const KFileItem *i,
- bool updateTextAndPixmap );
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KFileIconViewPrivate;
- KFileIconViewPrivate *d;
-};
-
-#endif // KFILESIMPLEVIEW_H
diff --git a/kio/kfile/kfilemetainfowidget.cpp b/kio/kfile/kfilemetainfowidget.cpp
deleted file mode 100644
index c4df4a15d..000000000
--- a/kio/kfile/kfilemetainfowidget.cpp
+++ /dev/null
@@ -1,375 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001,2002 Rolf Magnus <ramagnus@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
- $Id$
- */
-
-#include "kfilemetainfowidget.h"
-
-#include <keditcl.h>
-#include <klocale.h>
-#include <knuminput.h>
-#include <kcombobox.h>
-#include <klineedit.h>
-#include <kstringvalidator.h>
-#include <kdebug.h>
-
-#include <tqlabel.h>
-#include <tqcheckbox.h>
-#include <tqspinbox.h>
-#include <tqdatetimeedit.h>
-#include <tqpixmap.h>
-#include <tqimage.h>
-#include <tqlayout.h>
-#include <tqvalidator.h>
-
-/*
- Widgets used for different types:
-
- bool : QCheckBox
- int : QSpinBox
- TQString : KComboBox if the validator is a KStringListValidator, else lineedit
- TQDateTime : QDateTimeEdit
-
-*/
-
-KFileMetaInfoWidget::KFileMetaInfoWidget(KFileMetaInfoItem item,
- TQValidator* val,
- TQWidget* parent, const char* name)
- : TQWidget(parent, name),
- m_value(item.value()),
- m_item(item),
- m_validator(val)
-{
- init(item, ReadWrite);
-}
-
-KFileMetaInfoWidget::KFileMetaInfoWidget(KFileMetaInfoItem item,
- Mode mode,
- TQValidator* val,
- TQWidget* parent, const char* name)
- : TQWidget(parent, name),
- m_value(item.value()),
- m_item(item),
- m_validator(val)
-{
- init(item, mode);
-}
-
-void KFileMetaInfoWidget::init(KFileMetaInfoItem item, Mode mode)
-{
- kdDebug(7033) << "*** item " << m_item.key()
- << " is a " << value().typeName() << endl;
-
- if (m_item.isEditable() && !(mode & ReadOnly))
- m_widget = makeWidget();
- else
- switch (m_value.type())
- {
- case TQVariant::Image :
- m_widget = new TQLabel(this, "info image");
- static_cast<TQLabel*>(m_widget)->setPixmap(TQPixmap(m_value.toImage()));
- break;
- case TQVariant::Pixmap :
- m_widget = new TQLabel(this, "info pixmap");
- static_cast<TQLabel*>(m_widget)->setPixmap(m_value.toPixmap());
- break;
- default:
- m_widget = new TQLabel(item.string(true), this, "info label");
- }
-
- (new TQHBoxLayout(this))->addWidget(m_widget);
-}
-
-KFileMetaInfoWidget::~KFileMetaInfoWidget()
-{
-}
-
-TQWidget* KFileMetaInfoWidget::makeWidget()
-{
- TQString valClass;
- TQWidget* w;
-
- switch (m_value.type())
- {
- case TQVariant::Invalid: // no type
- // just make a label
- w = new TQLabel(i18n("<Error>"), this, "label");
- break;
-
- case TQVariant::Int: // an int
- case TQVariant::UInt: // an unsigned int
- w = makeIntWidget();
- break;
-
- case TQVariant::Bool: // a bool
- w = makeBoolWidget();
- break;
-
- case TQVariant::Double: // a double
- w = makeDoubleWidget();
- break;
-
-
- case TQVariant::Date: // a QDate
- w = makeDateWidget();
- break;
-
- case TQVariant::Time: // a QTime
- w = makeTimeWidget();
- break;
-
- case TQVariant::DateTime: // a QDateTime
- w = makeDateTimeWidget();
- break;
-
-#if 0
- case TQVariant::Size: // a QSize
- case TQVariant::String: // a QString
- case TQVariant::List: // a QValueList
- case TQVariant::Map: // a QMap
- case TQVariant::StringList: // a QStringList
- case TQVariant::Font: // a QFont
- case TQVariant::Pixmap: // a QPixmap
- case TQVariant::Brush: // a QBrush
- case TQVariant::Rect: // a QRect
- case TQVariant::Color: // a QColor
- case TQVariant::Palette: // a QPalette
- case TQVariant::ColorGroup: // a QColorGroup
- case TQVariant::IconSet: // a QIconSet
- case TQVariant::Point: // a QPoint
- case TQVariant::Image: // a QImage
- case TQVariant::CString: // a QCString
- case TQVariant::PointArray: // a QPointArray
- case TQVariant::Region: // a QRegion
- case TQVariant::Bitmap: // a QBitmap
- case TQVariant::Cursor: // a QCursor
- case TQVariant::ByteArray: // a QByteArray
- case TQVariant::BitArray: // a QBitArray
- case TQVariant::SizePolicy: // a QSizePolicy
- case TQVariant::KeySequence: // a QKeySequence
-#endif
- default:
- w = makeStringWidget();
- }
-
- kdDebug(7033) << "*** item " << m_item.key()
- << "is a " << m_item.value().typeName() << endl;
- if (m_validator)
- kdDebug(7033) << " and validator is a " << m_validator->className() << endl;
-
- kdDebug(7033) << "*** created a " << w->className() << " for it\n";
-
- return w;
-}
-
-// ****************************************************************
-// now the different methods to make the widgets for specific types
-// ****************************************************************
-
-TQWidget* KFileMetaInfoWidget::makeBoolWidget()
-{
- TQCheckBox* cb = new TQCheckBox(this, "metainfo bool widget");
- cb->setChecked(m_item.value().toBool());
- connect(cb, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotChanged(bool)));
- return cb;
-}
-
-TQWidget* KFileMetaInfoWidget::makeIntWidget()
-{
- TQSpinBox* sb = new TQSpinBox(this, "metainfo integer widget");
- sb->setValue(m_item.value().toInt());
-
- if (m_validator)
- {
- if (m_validator->inherits(TQINTVALIDATOR_OBJECT_NAME_STRING))
- {
- sb->setMinValue(static_cast<TQIntValidator*>(m_validator)->bottom());
- sb->setMaxValue(static_cast<TQIntValidator*>(m_validator)->top());
- }
- reparentValidator(sb, m_validator);
- sb->setValidator(m_validator);
- }
-
- // make sure that an uint cannot be set to a value < 0
- if (m_item.type() == TQVariant::UInt)
- sb->setMinValue(QMAX(sb->minValue(), 0));
-
- connect(sb, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(slotChanged(int)));
- return sb;
-}
-
-TQWidget* KFileMetaInfoWidget::makeDoubleWidget()
-{
- KDoubleNumInput* dni = new KDoubleNumInput(m_item.value().toDouble(),
- this, "metainfo double widget");
-
-
- if (m_validator)
- {
- if (m_validator->inherits("QDoubleValidator"))
- {
- dni->setMinValue(static_cast<TQDoubleValidator*>(m_validator)->bottom());
- dni->setMaxValue(static_cast<TQDoubleValidator*>(m_validator)->top());
- }
- reparentValidator(dni, m_validator);
- }
-
- connect(dni, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(slotChanged(double)));
- return dni;
-}
-
-TQWidget* KFileMetaInfoWidget::makeStringWidget()
-{
- if (m_validator && m_validator->inherits("KStringListValidator"))
- {
- KComboBox* b = new KComboBox(true, this, "metainfo combobox");
- KStringListValidator* val = static_cast<KStringListValidator*>
- (m_validator);
- b->insertStringList(val->stringList());
- b->setCurrentText(m_item.value().toString());
- connect(b, TQT_SIGNAL(activated(const TQString &)), this, TQT_SLOT(slotComboChanged(const TQString &)));
- b->setValidator(val);
- reparentValidator(b, val);
- return b;
- }
-
- if ( m_item.attributes() & KFileMimeTypeInfo::MultiLine ) {
- KEdit *edit = new KEdit( this );
- edit->setText( m_item.value().toString() );
- connect( edit, TQT_SIGNAL( textChanged() ),
- this, TQT_SLOT( slotMultiLineEditChanged() ));
- // can't use a validator with a TQTextEdit, but we may need to delete it
- if ( m_validator )
- reparentValidator( edit, m_validator );
- return edit;
- }
-
- KLineEdit* e = new KLineEdit(m_item.value().toString(), this);
- if (m_validator)
- {
- e->setValidator(m_validator);
- reparentValidator(e, m_validator);
- }
- connect(e, TQT_SIGNAL(textChanged(const TQString&)),
- this, TQT_SLOT(slotLineEditChanged(const TQString&)));
- return e;
-}
-
-TQWidget* KFileMetaInfoWidget::makeDateWidget()
-{
- TQWidget *e = new TQDateEdit(m_item.value().toDate(), this);
- connect(e, TQT_SIGNAL(valueChanged(const TQDate&)),
- this, TQT_SLOT(slotDateChanged(const TQDate&)));
- return e;
-}
-
-TQWidget* KFileMetaInfoWidget::makeTimeWidget()
-{
- return new TQTimeEdit(m_item.value().toTime(), this);
-}
-
-TQWidget* KFileMetaInfoWidget::makeDateTimeWidget()
-{
- return new TQDateTimeEdit(m_item.value().toDateTime(), this);
-}
-
-void KFileMetaInfoWidget::reparentValidator( TQWidget *widget,
- TQValidator *validator )
-{
- if ( !validator->parent() )
- widget->insertChild( validator );
-}
-
-// ****************************************************************
-// now the slots that let us get notified if the value changed in the child
-// ****************************************************************
-
-void KFileMetaInfoWidget::slotChanged(bool value)
-{
- Q_ASSERT(m_widget->inherits(TQCOMBOBOX_OBJECT_NAME_STRING));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-void KFileMetaInfoWidget::slotChanged(int value)
-{
- Q_ASSERT(m_widget->inherits(TQSPINBOX_OBJECT_NAME_STRING));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-void KFileMetaInfoWidget::slotChanged(double value)
-{
- Q_ASSERT(m_widget->inherits("KDoubleNumInput"));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-void KFileMetaInfoWidget::slotComboChanged(const TQString &value)
-{
- Q_ASSERT(m_widget->inherits("KComboBox"));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-void KFileMetaInfoWidget::slotLineEditChanged(const TQString& value)
-{
- Q_ASSERT(m_widget->inherits("KLineEdit"));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-// that may be a little expensive for long texts, but what can we do?
-void KFileMetaInfoWidget::slotMultiLineEditChanged()
-{
- Q_ASSERT(m_widget->inherits(TQTEXTEDIT_OBJECT_NAME_STRING));
- m_value = TQVariant( static_cast<const TQTextEdit*>( sender() )->text() );
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-void KFileMetaInfoWidget::slotDateChanged(const TQDate& value)
-{
- Q_ASSERT(m_widget->inherits(TQDATEEDIT_OBJECT_NAME_STRING));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-void KFileMetaInfoWidget::slotTimeChanged(const TQTime& value)
-{
- Q_ASSERT(m_widget->inherits(TQTIMEEDIT_OBJECT_NAME_STRING));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-void KFileMetaInfoWidget::slotDateTimeChanged(const TQDateTime& value)
-{
- Q_ASSERT(m_widget->inherits(TQDATETIMEEDIT_OBJECT_NAME_STRING));
- m_value = TQVariant(value);
- emit valueChanged(m_value);
- m_dirty = true;
-}
-
-#include "kfilemetainfowidget.moc"
diff --git a/kio/kfile/kfilemetainfowidget.h b/kio/kfile/kfilemetainfowidget.h
deleted file mode 100644
index a42846bea..000000000
--- a/kio/kfile/kfilemetainfowidget.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001,2002 Rolf Magnus <ramagnus@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
- */
-
-#ifndef __KFILEMETAINFOWIDGET_H__
-#define __KFILEMETAINFOWIDGET_H__
-
-#include <tqwidget.h>
-#include <tqvariant.h>
-#include <kfilemetainfo.h>
-
-/*!
- * A widget to display file meta infos (like id3 for mp3)
- */
-class TDEIO_EXPORT KFileMetaInfoWidget: public TQWidget
-{
- Q_OBJECT
-public:
- enum Mode
- {
- ReadOnly = 1, ///Only display the meta infos, and do not permit the user to edit them
- ReadWrite = 0, ///Permits user to edit the displayed meta-info
- Reserve = 0xff
- };
-
- KFileMetaInfoWidget(KFileMetaInfoItem item, TQValidator* val = 0,
- TQWidget* parent = 0, const char* name = 0);
-
- KFileMetaInfoWidget(KFileMetaInfoItem item, Mode mode, TQValidator* val = 0,
- TQWidget* parent = 0, const char* name = 0);
-
- virtual ~KFileMetaInfoWidget();
-
- bool apply()
- {
- return m_item.isEditable() && m_item.setValue(m_value);
- }
-
- void setValue(const TQVariant& value) { m_value = value; }
- TQVariant value()const { return m_value; }
- TQValidator* validator() const { return m_validator; }
- KFileMetaInfoItem item()const { return m_item; }
-
-signals:
- void valueChanged(const TQVariant& value);
-
-protected:
- void reparentValidator(TQWidget *widget, TQValidator *validator);
- virtual TQWidget* makeWidget();
-
- TQWidget* makeBoolWidget();
- TQWidget* makeIntWidget();
- TQWidget* makeDoubleWidget();
- TQWidget* makeStringWidget();
- TQWidget* makeDateWidget();
- TQWidget* makeTimeWidget();
- TQWidget* makeDateTimeWidget();
-
-private slots:
- void slotChanged(bool value);
- void slotChanged(int value);
- void slotChanged(double value);
- void slotComboChanged(const TQString &value);
- void slotLineEditChanged(const TQString& value);
- void slotMultiLineEditChanged();
- void slotDateChanged(const TQDate& value);
- void slotTimeChanged(const TQTime& value);
- void slotDateTimeChanged(const TQDateTime& value);
-
-private:
- void init(KFileMetaInfoItem item, Mode mode);
-
- TQVariant m_value; // the value will be saved here until apply() is called
- KFileMetaInfoItem m_item;
- TQWidget* m_widget;
- TQValidator* m_validator;
- bool m_dirty : 1;
-};
-
-#endif
diff --git a/kio/kfile/kfilemetapreview.cpp b/kio/kfile/kfilemetapreview.cpp
deleted file mode 100644
index 155e1194c..000000000
--- a/kio/kfile/kfilemetapreview.cpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * This file is part of the KDE project.
- * Copyright (C) 2003 Carsten Pfeiffer <pfeiffer@kde.org>
- *
- * You can Freely distribute this program under the GNU Library General Public
- * License. See the file "COPYING" for the exact licensing terms.
- */
-
-#include "kfilemetapreview.h"
-
-#include <tqlayout.h>
-
-#include <kio/previewjob.h>
-#include <klibloader.h>
-#include <kimagefilepreview.h>
-#include <kmimetype.h>
-
-bool KFileMetaPreview::s_tryAudioPreview = true;
-
-KFileMetaPreview::KFileMetaPreview( TQWidget *parent, const char *name )
- : KPreviewWidgetBase( parent, name ),
- haveAudioPreview( false )
-{
- TQHBoxLayout *layout = new TQHBoxLayout( this, 0, 0 );
- m_stack = new TQWidgetStack( this );
- layout->addWidget( m_stack );
-
- // ###
-// m_previewProviders.setAutoDelete( true );
- initPreviewProviders();
-}
-
-KFileMetaPreview::~KFileMetaPreview()
-{
-}
-
-void KFileMetaPreview::initPreviewProviders()
-{
- m_previewProviders.clear();
- // hardcoded so far
-
- // image previews
- KImageFilePreview *imagePreview = new KImageFilePreview( m_stack );
- (void) m_stack->addWidget( imagePreview );
- m_stack->raiseWidget( imagePreview );
- resize( imagePreview->sizeHint() );
-
- TQStringList mimeTypes = imagePreview->supportedMimeTypes();
- TQStringList::ConstIterator it = mimeTypes.begin();
- for ( ; it != mimeTypes.end(); ++it )
- {
-// tqDebug(".... %s", (*it).latin1());
- m_previewProviders.insert( *it, imagePreview );
- }
-}
-
-KPreviewWidgetBase * KFileMetaPreview::previewProviderFor( const TQString& mimeType )
-{
-// tqDebug("### looking for: %s", mimeType.latin1());
- // often the first highlighted item, where we can be sure, there is no plugin
- // (this "folders reflect icons" is a konq-specific thing, right?)
- if ( mimeType == "inode/directory" )
- return 0L;
-
- KPreviewWidgetBase *provider = m_previewProviders.find( mimeType );
- if ( provider )
- return provider;
-
-//tqDebug("#### didn't find anything for: %s", mimeType.latin1());
-
- if ( s_tryAudioPreview &&
- !mimeType.startsWith("text/") && !mimeType.startsWith("image/") )
- {
- if ( !haveAudioPreview )
- {
- KPreviewWidgetBase *audioPreview = createAudioPreview( m_stack );
- if ( audioPreview )
- {
- haveAudioPreview = true;
- (void) m_stack->addWidget( audioPreview );
- TQStringList mimeTypes = audioPreview->supportedMimeTypes();
- TQStringList::ConstIterator it = mimeTypes.begin();
- for ( ; it != mimeTypes.end(); ++it )
- m_previewProviders.insert( *it, audioPreview );
- }
- }
- }
-
- // with the new mimetypes from the audio-preview, try again
- provider = m_previewProviders.find( mimeType );
- if ( provider )
- return provider;
-
- // ### mimetype may be image/* for example, try that
- int index = mimeType.find( '/' );
- if ( index > 0 )
- {
- provider = m_previewProviders.find( mimeType.left( index + 1 ) + "*" );
- if ( provider )
- return provider;
- }
-
- KMimeType::Ptr mimeInfo = KMimeType::mimeType( mimeType );
- if ( mimeInfo )
- {
- // check mime type inheritance
- TQString parentMimeType = mimeInfo->parentMimeType();
- while ( !parentMimeType.isEmpty() )
- {
- provider = m_previewProviders.find( parentMimeType );
- if ( provider )
- return provider;
-
- KMimeType::Ptr parentMimeInfo = KMimeType::mimeType( parentMimeType );
- if ( !parentMimeInfo ) break;
-
- parentMimeType = parentMimeInfo->parentMimeType();
- }
-
- // check X-TDE-Text property
- TQVariant textProperty = mimeInfo->property( "X-TDE-text" );
- if ( textProperty.isValid() && textProperty.type() == TQVariant::Bool )
- {
- if ( textProperty.toBool() )
- {
- provider = m_previewProviders.find( "text/plain" );
- if ( provider )
- return provider;
-
- provider = m_previewProviders.find( "text/*" );
- if ( provider )
- return provider;
- }
- }
- }
-
- return 0L;
-}
-
-void KFileMetaPreview::showPreview(const KURL &url)
-{
- KMimeType::Ptr mt = KMimeType::findByURL( url );
- KPreviewWidgetBase *provider = previewProviderFor( mt->name() );
- if ( provider )
- {
- if ( provider != m_stack->visibleWidget() ) // stop the previous preview
- clearPreview();
-
- m_stack->setEnabled( true );
- m_stack->raiseWidget( provider );
- provider->showPreview( url );
- }
- else
- {
- clearPreview();
- m_stack->setEnabled( false );
- }
-}
-
-void KFileMetaPreview::clearPreview()
-{
- if ( m_stack->visibleWidget() )
- static_cast<KPreviewWidgetBase*>( m_stack->visibleWidget() )->clearPreview();
-}
-
-void KFileMetaPreview::addPreviewProvider( const TQString& mimeType,
- KPreviewWidgetBase *provider )
-{
- m_previewProviders.insert( mimeType, provider );
-}
-
-void KFileMetaPreview::clearPreviewProviders()
-{
- TQDictIterator<KPreviewWidgetBase> it( m_previewProviders );
- for ( ; it.current(); ++it )
- m_stack->removeWidget( it.current() );
-
- m_previewProviders.clear();
-}
-
-// static
-KPreviewWidgetBase * KFileMetaPreview::createAudioPreview( TQWidget *parent )
-{
- KLibFactory *factory = KLibLoader::self()->factory( "kfileaudiopreview" );
- if ( !factory )
- {
- s_tryAudioPreview = false;
- return 0L;
- }
-
- return dynamic_cast<KPreviewWidgetBase*>( factory->create( TQT_TQOBJECT(parent), "kfileaudiopreview" ));
-}
-
-void KFileMetaPreview::virtual_hook( int, void* ) {}
-
-#include "kfilemetapreview.moc"
diff --git a/kio/kfile/kfilepreview.cpp b/kio/kfile/kfilepreview.cpp
deleted file mode 100644
index 04124570b..000000000
--- a/kio/kfile/kfilepreview.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
- 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- 2000 Werner Trobin <wtrobin@carinthia.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kaction.h>
-#include <kfilepreview.h>
-#include <kfilepreview.moc>
-#include <klocale.h>
-
-#include <tqlabel.h>
-
-#include "config-kfile.h"
-
-KFilePreview::KFilePreview(KFileView *view, TQWidget *parent, const char *name)
- : TQSplitter(parent, name), KFileView()
-{
- if ( view )
- init( view );
- else
- init( new KFileIconView( (TQSplitter*) this, "left" ));
-}
-
-
-KFilePreview::KFilePreview(TQWidget *parent, const char *name) :
- TQSplitter(parent, name), KFileView()
-{
- init( new KFileIconView((TQSplitter*)this, "left") );
-}
-
-KFilePreview::~KFilePreview()
-{
- // Why copy the actions in the first place? --ellis, 13 Jan 02.
- //// don't delete the view's actions (inserted into our collection)!
- //for ( uint i = 0; i < left->actionCollection()->count(); i++ )
- // actionCollection()->take( left->actionCollection()->action( i ));
-
- // don't delete the preview, we can reuse it
- // (it will get deleted by ~KDirOperator)
- if ( preview && preview->parentWidget() == this ) {
- preview->reparent(0L, 0, TQPoint(0, 0), false);
- }
-}
-
-void KFilePreview::init( KFileView *view )
-{
- setViewName( i18n("Preview") );
-
- left = 0L;
- setFileView( view );
-
- preview = new TQWidget((TQSplitter*)this, "preview");
- TQString tmp = i18n("No preview available.");
- TQLabel *l = new TQLabel(tmp, preview);
- l->setMinimumSize(l->sizeHint());
- l->move(10, 5);
- preview->setMinimumWidth(l->sizeHint().width()+20);
- setResizeMode(preview, TQSplitter::KeepSize);
-
- // Why copy the actions? --ellis, 13 Jan 02.
- //for ( uint i = 0; i < view->actionCollection()->count(); i++ )
- // actionCollection()->insert( view->actionCollection()->action( i ));
-}
-
-void KFilePreview::setFileView( KFileView *view )
-{
- Q_ASSERT( view );
-
- // Why copy the actions? --ellis, 13 Jan 02.
- //if ( left ) { // remove any previous actions
- // for ( uint i = 0; i < left->actionCollection()->count(); i++ )
- // actionCollection()->take( left->actionCollection()->action( i ));
- //}
-
- delete left;
- view->widget()->reparent( this, TQPoint(0,0) );
- view->KFileView::setViewMode(All);
- view->setParentView(this);
- view->setSorting( sorting() );
- left = view;
-
- connect( left->signaler(), TQT_SIGNAL( fileHighlighted(const KFileItem*) ),
- TQT_SLOT( slotHighlighted( const KFileItem * )));
-
- // Why copy the actions? --ellis, 13 Jan 02.
- //for ( uint i = 0; i < view->actionCollection()->count(); i++ )
- // actionCollection()->insert( view->actionCollection()->action( i ));
-}
-
-// this url parameter is useless... it's the url of the current directory.
-// what for?
-void KFilePreview::setPreviewWidget(const TQWidget *w, const KURL &)
-{
- left->setOnlyDoubleClickSelectsFiles( onlyDoubleClickSelectsFiles() );
-
- if (w) {
- connect(this, TQT_SIGNAL( showPreview(const KURL &) ),
- w, TQT_SLOT( showPreview(const KURL &) ));
- connect( this, TQT_SIGNAL( clearPreview() ),
- w, TQT_SLOT( clearPreview() ));
- }
- else {
- preview->hide();
- return;
- }
-
- delete preview;
- preview = const_cast<TQWidget*>(w);
- preview->reparent((TQSplitter*)this, 0, TQPoint(0, 0), true);
- preview->resize(preview->sizeHint());
- preview->show();
-}
-
-void KFilePreview::insertItem(KFileItem *item)
-{
- KFileView::insertItem( item );
- left->insertItem(item);
-}
-
-void KFilePreview::setSorting( TQDir::SortSpec sort )
-{
- left->setSorting( sort );
- KFileView::setSorting( left->sorting() );
-}
-
-void KFilePreview::clearView()
-{
- left->clearView();
- emit clearPreview();
-}
-
-void KFilePreview::updateView(bool b)
-{
- left->updateView(b);
- if(preview)
- preview->repaint(b);
-}
-
-void KFilePreview::updateView(const KFileItem *i)
-{
- left->updateView(i);
-}
-
-void KFilePreview::removeItem(const KFileItem *i)
-{
- if ( left->isSelected( i ) )
- emit clearPreview();
-
- left->removeItem(i);
- KFileView::removeItem( i );
-}
-
-void KFilePreview::listingCompleted()
-{
- left->listingCompleted();
-}
-
-void KFilePreview::clear()
-{
- KFileView::clear();
- left->KFileView::clear();
-}
-
-void KFilePreview::clearSelection()
-{
- left->clearSelection();
- emit clearPreview();
-}
-
-void KFilePreview::selectAll()
-{
- left->selectAll();
-}
-
-void KFilePreview::invertSelection()
-{
- left->invertSelection();
-}
-
-bool KFilePreview::isSelected( const KFileItem *i ) const
-{
- return left->isSelected( i );
-}
-
-void KFilePreview::setSelectionMode(KFile::SelectionMode sm) {
- left->setSelectionMode( sm );
-}
-
-void KFilePreview::setSelected(const KFileItem *item, bool enable) {
- left->setSelected( item, enable );
-}
-
-void KFilePreview::setCurrentItem( const KFileItem *item )
-{
- left->setCurrentItem( item );
-}
-
-KFileItem * KFilePreview::currentFileItem() const
-{
- return left->currentFileItem();
-}
-
-void KFilePreview::slotHighlighted(const KFileItem* item)
-{
- if ( item )
- emit showPreview( item->url() );
-
- else { // item = 0 -> multiselection mode
- const KFileItemList *items = selectedItems();
- if ( items->count() == 1 )
- emit showPreview( items->getFirst()->url() );
- else
- emit clearPreview();
- }
-
- // the preview widget appears and takes some space of the left view,
- // so we may have to scroll to make the current item visible
- left->ensureItemVisible(item);
- }
-
-void KFilePreview::ensureItemVisible(const KFileItem *item)
-{
- left->ensureItemVisible(item);
-}
-
-KFileItem * KFilePreview::firstFileItem() const
-{
- return left->firstFileItem();
-}
-
-KFileItem * KFilePreview::nextItem( const KFileItem *item ) const
-{
- return left->nextItem( item );
-}
-
-KFileItem * KFilePreview::prevItem( const KFileItem *item ) const
-{
- return left->prevItem( item );
-}
-
-KActionCollection * KFilePreview::actionCollection() const
-{
- if ( left )
- return left->actionCollection();
- else {
- kdWarning() << "KFilePreview::actionCollection(): called before setFileView()." << endl; //ellis
- return KFileView::actionCollection();
- }
-}
-
-void KFilePreview::readConfig( TDEConfig *config, const TQString& group )
-{
- left->readConfig( config, group );
-}
-
-void KFilePreview::writeConfig( TDEConfig *config, const TQString& group )
-{
- left->writeConfig( config, group );
-}
-
-void KFilePreview::virtual_hook( int id, void* data )
-{ KFileView::virtual_hook( id, data ); }
-
diff --git a/kio/kfile/kfilepreview.h b/kio/kfile/kfilepreview.h
deleted file mode 100644
index af6fe13d2..000000000
--- a/kio/kfile/kfilepreview.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/* -*- c++ -*-
- This file is part of the KDE libraries
- Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
- 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- 2000 Werner Trobin <wtrobin@carinthia.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KFILEPREVIEW_H
-#define _KFILEPREVIEW_H
-
-#include <tqsplitter.h>
-#include <tqwidget.h>
-#include <tqstring.h>
-
-#include <kurl.h>
-#include <kfileitem.h>
-#include <kfileiconview.h>
-#include <kfiledetailview.h>
-#include <kfile.h>
-
-/*!
- * This KFileView is an empbedded preview for some file types.
- */
-class TDEIO_EXPORT KFilePreview : public TQSplitter, public KFileView
-{
- Q_OBJECT
-
-public:
- KFilePreview(TQWidget *parent, const char *name);
- KFilePreview(KFileView *view, TQWidget *parent, const char *name);
- virtual ~KFilePreview();
-
- virtual TQWidget *widget() { return this; }
- virtual void clearView();
-
- /**
- * Delets the current view and sets the view to the given @p view.
- * The view is reparented to have this as parent, if necessary.
- */
- void setFileView(KFileView *view);
-
- /**
- * @returns the current fileview
- */
- KFileView* fileView() const { return left; }
-
- virtual void updateView( bool );
- virtual void updateView(const KFileItem*);
- virtual void removeItem(const KFileItem*);
- virtual void listingCompleted();
-
- virtual void setSelectionMode( KFile::SelectionMode sm );
-
- virtual void setSelected(const KFileItem *, bool);
- virtual bool isSelected( const KFileItem * ) const;
- virtual void clearSelection();
- virtual void selectAll();
- virtual void invertSelection();
-
- virtual void insertItem(KFileItem *);
- virtual void clear();
-
- virtual void setCurrentItem( const KFileItem * );
- virtual KFileItem * currentFileItem() const;
- virtual KFileItem * firstFileItem() const;
- virtual KFileItem * nextItem( const KFileItem * ) const;
- virtual KFileItem * prevItem( const KFileItem * ) const;
-
- virtual void setSorting( TQDir::SortSpec sort );
-
- virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
- virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
-
- /**
- * This overrides KFileView::actionCollection() by returning
- * the actionCollection() of the KFileView (member left) it contains.
- * This means that KFilePreview will never create a KActionCollection
- * object of its own.
- */
- virtual KActionCollection * actionCollection() const;
-
- void ensureItemVisible(const KFileItem *);
-
- void setPreviewWidget(const TQWidget *w, const KURL &u);
-
-protected slots:
- virtual void slotHighlighted( const KFileItem * );
-
-signals:
- void showPreview(const KURL &);
- void clearPreview();
-
-private:
- void init( KFileView *view );
-
- KFileView *left;
- TQWidget *preview;
- TQString viewname;
-
-protected:
- /** \internal */
- virtual void virtual_hook( int id, void* data );
-private:
- class KFilePreviewPrivate;
- KFilePreviewPrivate *d;
-};
-#endif
diff --git a/kio/kfile/kfilesharedlg.cpp b/kio/kfile/kfilesharedlg.cpp
deleted file mode 100644
index e9b4c2673..000000000
--- a/kio/kfile/kfilesharedlg.cpp
+++ /dev/null
@@ -1,325 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2001 David Faure <david@mandrakesoft.com>
- Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kfilesharedlg.h"
-#include <tqvbox.h>
-#include <tqlabel.h>
-#include <tqdir.h>
-#include <tqradiobutton.h>
-#include <tqbuttongroup.h>
-#include <tqlayout.h>
-#include <tqlineedit.h>
-#include <kprocess.h>
-#include <kprocio.h>
-#include <klocale.h>
-#include <kglobalsettings.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <kio/kfileshare.h>
-#include <kseparator.h>
-#include <tqpushbutton.h>
-#include <kapplication.h>
-#include <ksimpleconfig.h>
-#include <kmessagebox.h>
-
-class KFileSharePropsPlugin::Private
-{
-public:
- TQVBox *m_vBox;
- TDEProcess *m_configProc;
- bool m_bAllShared;
- bool m_bAllUnshared;
- bool m_bAllReadOnly;
-};
-
-KFileSharePropsPlugin::KFileSharePropsPlugin( KPropertiesDialog *_props )
- : KPropsDlgPlugin( _props )
-{
- d = new Private;
- d->m_vBox = _props->addVBoxPage( i18n("&Share") );
- d->m_configProc = 0;
- properties->setFileSharingPage(d->m_vBox);
- m_widget = 0L;
- init();
-}
-
-KFileSharePropsPlugin::~KFileSharePropsPlugin()
-{
- if (d->m_configProc)
- d->m_configProc->detach(); // Detach to prevent that we kill the process
- delete d;
-}
-
-bool KFileSharePropsPlugin::supports( const KFileItemList& items )
-{
- // Do not show dialog if in advanced mode,
- // because the advanced dialog is shown already.
- if (KFileShare::shareMode() == KFileShare::Advanced) {
- kdDebug() << "KFileSharePropsPlugin::supports: false because sharemode is advanced" << endl;
- return false;
- }
-
- KFileItemListIterator it( items );
- for ( ; it.current(); ++it )
- {
- bool isLocal = ( *it )->isLocalFile();
- // We only support local dirs
- if ( !(*it)->isDir() || !isLocal )
- return false;
- // And sharing the trash doesn't make sense
- if ( isLocal && (*it)->url().path( 1 ) == TDEGlobalSettings::trashPath() )
- return false;
- }
- return true;
-}
-
-void KFileSharePropsPlugin::init()
-{
- // We store the main widget, so that it's possible (later) to call init()
- // more than once, to update the page if something changed (e.g. after
- // the user has been authorized)
- delete m_widget;
- m_rbShare = 0L;
- m_rbUnShare = 0L;
- m_rbSharerw = 0L;
- m_widget = new TQWidget( d->m_vBox );
- TQVBoxLayout * vbox = new TQVBoxLayout( m_widget );
- //TQHBoxLayout * hbox = new TQHBoxLayout( vbox );
-
- switch ( KFileShare::authorization() ) {
- case KFileShare::Authorized:
- {
- // Check if all selected dirs are in $HOME
- TQString home = TQDir::homeDirPath();
- if ( home[home.length()-1] != '/' )
- home += '/';
- bool ok = true;
- KFileItemList items = properties->items();
- // We have 3 possibilities: all shared, all unshared (ro,rw), or mixed.
- d->m_bAllShared = true;
- d->m_bAllUnshared = true;
- d->m_bAllReadOnly = true;
- KFileItemListIterator it( items );
- for ( ; it.current() && ok; ++it ) {
- TQString path = (*it)->url().path();
- // 0 => not shared
- // 1 => shared read only
- // 3 => shared writeable
- int dirStatus = KFileShare::isDirectoryShared( path );
- if ( !path.startsWith( home ) )
- ok = false;
- if ( dirStatus == 1 ) {
- d->m_bAllUnshared = false;
- }
- else if ( dirStatus == 3 ) {
- d->m_bAllUnshared = false;
- d->m_bAllReadOnly = false;
- }
- else {
- d->m_bAllReadOnly = false;
- }
- }
- if ( !ok )
- {
- vbox->addWidget( new TQLabel( i18n( "Only folders in your home folder can be shared."),
- m_widget ), 0 );
- }
- else
- {
- // Everything ok, show the share/unshare GUI
- vbox->setSpacing( KDialog::spacingHint() );
- vbox->setMargin( KDialog::marginHint() );
-
- TQButtonGroup *rbGroup = new TQButtonGroup( m_widget );
- rbGroup->hide();
- m_rbUnShare = new TQRadioButton( i18n("Not shared"), m_widget );
- connect( m_rbUnShare, TQT_SIGNAL( toggled(bool) ), TQT_SIGNAL( changed() ) );
- vbox->addWidget( m_rbUnShare, 0 );
- rbGroup->insert( m_rbUnShare );
-
- m_rbShare = new TQRadioButton( i18n("Shared - read only for others"), m_widget );
- connect( m_rbShare, TQT_SIGNAL( toggled(bool) ), TQT_SIGNAL( changed() ) );
- vbox->addWidget( m_rbShare, 0 );
- rbGroup->insert( m_rbShare );
-
- m_rbSharerw = new TQRadioButton( i18n("Shared - writeable for others"), m_widget );
- connect( m_rbSharerw, TQT_SIGNAL( toggled(bool) ), TQT_SIGNAL( changed() ) );
- vbox->addWidget( m_rbSharerw, 0 );
- rbGroup->insert( m_rbSharerw );
-
- //TQLabel *testlabel1 = new TQLabel(i18n("Enter Samba Share Name here"),m_widget);
- //m_leSmbShareName = new TQLineEdit(m_widget);
- //m_leSmbShareName->setMaxLength(12);
-
- //hbox->addWidget( testlabel1, 0 );
- //hbox->addWidget( m_leSmbShareName );
- //vbox->addLayout( hbox );
-
- // Activate depending on status
- if ( d->m_bAllShared )
- m_rbSharerw->setChecked(true);
- if ( d->m_bAllUnshared )
- m_rbUnShare->setChecked(true);
- if ( d->m_bAllReadOnly )
- m_rbShare->setChecked(true);
-
- // Some help text
- TQLabel *label = new TQLabel( i18n("Sharing this folder makes it available under Linux/UNIX (NFS) and Windows (Samba).") , m_widget );
- label->setAlignment( TQt::AlignAuto | TQt::AlignVCenter | TQt::WordBreak );
- vbox->addWidget( label, 0 );
-
- KSeparator* sep=new KSeparator(m_widget);
- vbox->addWidget( sep, 0 );
- label = new TQLabel( i18n("You can also reconfigure file sharing authorization.") , m_widget );
- label->setAlignment( TQt::AlignAuto | TQt::AlignVCenter | TQt::WordBreak );
- vbox->addWidget( label, 0 );
- m_pbConfig = new TQPushButton( i18n("Configure File Sharing..."), m_widget );
- connect( m_pbConfig, TQT_SIGNAL( clicked() ), TQT_SLOT( slotConfigureFileSharing() ) );
- vbox->addWidget( m_pbConfig, 0, Qt::AlignHCenter );
-
- vbox->addStretch( 10 );
-
- if( !KFileShare::sambaActive() && !KFileShare::nfsActive())
- m_widget->setEnabled( false );
- }
- }
- break;
- case KFileShare::ErrorNotFound:
- vbox->addWidget( new TQLabel( i18n("Error running 'filesharelist'. Check if installed and in $PATH or /usr/sbin."),
- m_widget ), 0 );
- break;
- case KFileShare::UserNotAllowed:
- {
- vbox->setSpacing( 10 );
- if (KFileShare::sharingEnabled()) {
- vbox->addWidget( new TQLabel( i18n("You need to be authorized to share folders."),
- m_widget ), 0 );
- } else {
- vbox->addWidget( new TQLabel( i18n("File sharing is disabled."),
- m_widget ), 0 );
- }
- TQHBoxLayout* hBox = new TQHBoxLayout( (TQWidget *)0L );
- vbox->addLayout( hBox, 0 );
- m_pbConfig = new TQPushButton( i18n("Configure File Sharing..."), m_widget );
- connect( m_pbConfig, TQT_SIGNAL( clicked() ), TQT_SLOT( slotConfigureFileSharing() ) );
- hBox->addWidget( m_pbConfig, 0, Qt::AlignHCenter );
- vbox->addStretch( 10 ); // align items on top
- break;
- }
- case KFileShare::NotInitialized:
- kdWarning() << "KFileShare Authorization still NotInitialized after calling authorization() - impossible" << endl;
- break;
- }
- m_widget->show(); // In case the dialog was shown already.
-}
-
-void KFileSharePropsPlugin::slotConfigureFileSharing()
-{
- if (d->m_configProc) return;
-
- d->m_configProc = new TDEProcess(this);
- (*d->m_configProc) << KStandardDirs::findExe("tdesu") << locate("exe", "kcmshell") << "fileshare";
- if (!d->m_configProc->start( TDEProcess::NotifyOnExit ))
- {
- delete d->m_configProc;
- d->m_configProc = 0;
- return;
- }
- connect(d->m_configProc, TQT_SIGNAL(processExited(TDEProcess *)),
- this, TQT_SLOT(slotConfigureFileSharingDone()));
- m_pbConfig->setEnabled(false);
-}
-
-void KFileSharePropsPlugin::slotConfigureFileSharingDone()
-{
- delete d->m_configProc;
- d->m_configProc = 0;
- KFileShare::readConfig();
- KFileShare::readShareList();
- init();
-}
-
-void KFileSharePropsPlugin::applyChanges()
-{
- kdDebug() << "KFileSharePropsPlugin::applyChanges" << endl;
- if ( m_rbShare && m_rbUnShare && m_rbSharerw )
- {
- bool share = m_rbShare->isChecked();
-
- if (share && d->m_bAllShared)
- return; // Nothing to do
- if (!share && d->m_bAllUnshared)
- return; // Nothing to do
-
- KFileItemList items = properties->items();
- KFileItemListIterator it( items );
- bool ok = true;
- for ( ; it.current() && ok; ++it ) {
- TQString path = (*it)->url().path();
- ok = SuSEsetShared( path, share, m_rbSharerw->isChecked() );
- if (!ok) {
- if (share)
- KMessageBox::detailedError(properties,
- i18n("Sharing folder '%1' failed.").arg(path),
- i18n("An error occurred while trying to share folder '%1'. "
- "Make sure that the Perl script 'fileshareset' is set suid root.")
- .arg(path));
- else
- KMessageBox::error(properties,
- i18n("Unsharing folder '%1' failed.").arg(path),
- i18n("An error occurred while trying to unshare folder '%1'. "
- "Make sure that the Perl script 'fileshareset' is set suid root.")
- .arg(path));
-
- properties->abortApplying();
- break;
- }
- }
-
- // Get the change back into our cached info
- KFileShare::readShareList();
- }
-}
-
-bool KFileSharePropsPlugin::setShared( const TQString& path, bool shared )
-{
- return SuSEsetShared( path, shared, true );
-}
-
-bool KFileSharePropsPlugin::SuSEsetShared( const TQString& path, bool shared, bool readonly )
-{
- kdDebug() << "KFileSharePropsPlugin::setShared " << path << ","
- << shared << readonly << endl;
- return KFileShare::SuSEsetShared( path, shared, readonly );
-}
-
-TQWidget* KFileSharePropsPlugin::page() const
-{
- return d->m_vBox;
-}
-
-#include "kfilesharedlg.moc"
-
-//TODO: do we need to monitor /etc/security/fileshare.conf ?
-// if the user is added to the 'fileshare' group, we wouldn't be notified
-// Of course the config module can notify us.
-// TODO: listen to such notifications ;)
diff --git a/kio/kfile/kfilesharedlg.h b/kio/kfile/kfilesharedlg.h
deleted file mode 100644
index e7998ad66..000000000
--- a/kio/kfile/kfilesharedlg.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2001 David Faure <david@mandrakesoft.com>
- Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef kfilesharedlg_h
-#define kfilesharedlg_h
-
-#include <kpropertiesdialog.h>
-class TQVBoxLayout;
-class TQRadioButton;
-class TQPushButton;
-
-/**
- * This plugin provides a page to KPropsDlg, showing the "file sharing" options
- * @author David Faure <david@mandrakesoft.com>
- * @since 3.1
- */
-class TDEIO_EXPORT KFileSharePropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- KFileSharePropsPlugin( KPropertiesDialog *_props );
- virtual ~KFileSharePropsPlugin();
-
- /**
- * Apply all changes to the file.
- * This function is called when the user presses 'Ok'. The last plugin inserted
- * is called first.
- */
- virtual void applyChanges();
-
- static bool supports( const KFileItemList& items );
-
- TQWidget* page() const;
-
-protected slots:
- void slotConfigureFileSharing();
- void slotConfigureFileSharingDone();
-
-private:
- void init();
- bool setShared( const TQString&path, bool shared );
- bool SuSEsetShared( const TQString&path, bool shared, bool readonly );
-
- TQWidget *m_widget;
- TQRadioButton *m_rbShare;
- TQRadioButton *m_rbSharerw;
- TQRadioButton *m_rbUnShare;
- //TQLineEdit *m_leSmbShareName;
- TQPushButton *m_pbConfig;
- class Private;
- Private *d;
-};
-
-#endif
diff --git a/kio/kfile/kfilespeedbar.cpp b/kio/kfile/kfilespeedbar.cpp
deleted file mode 100644
index 567d929eb..000000000
--- a/kio/kfile/kfilespeedbar.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation, version 2.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kfilespeedbar.h"
-#include "config-kfile.h"
-
-#include <tqdir.h>
-#include <tqfile.h>
-#include <tqtextcodec.h>
-#include <tqtextstream.h>
-
-#include <kconfig.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <klocale.h>
-#include <kprotocolinfo.h>
-#include <kstandarddirs.h>
-#include <kurl.h>
-
-KFileSpeedBar::KFileSpeedBar( TQWidget *parent, const char *name )
- : KURLBar( true, parent, name )
-{
- TDEConfig *config = TDEGlobal::config();
- TDEConfigGroupSaver cs( config, ConfigGroup );
- m_initializeSpeedbar = config->readBoolEntry( "Set speedbar defaults",
- true );
- setIconSize(KIcon::SizeSmallMedium);
- readConfig( TDEGlobal::config(), "KFileDialog Speedbar" );
-
- if ( m_initializeSpeedbar )
- {
- KURL u;
- u.setPath( TDEGlobalSettings::desktopPath() );
- insertItem( u, i18n("Desktop"), false );
-
-//TODO: win32
- if ((TDEGlobalSettings::documentPath() != (TQDir::homeDirPath()+"/")) &&
- TQDir(TDEGlobalSettings::documentPath()).exists())
- {
- u.setPath( TDEGlobalSettings::documentPath() );
- insertItem( u, i18n("Documents"), false, "folder_txt" );
- }
-
- u.setPath( TQDir::homeDirPath() );
- insertItem( u, i18n("Home Folder"), false,
- "folder_home" );
-
- u = "media:/";
- if ( KProtocolInfo::isKnownProtocol( u ) )
- insertItem( u, i18n("Storage Media"), false,
- KProtocolInfo::icon( "media" ) );
-
- if ( TQFile::exists( TQDir::homeDirPath()+"/.config/user-dirs.dirs" ) )
- {
- TQString download, music, pictures, videos, templates, publicShares;
-
- TQFile f( TQDir::homeDirPath()+"/.config/user-dirs.dirs" );
- if (!f.open(IO_ReadOnly))
- return;
-
- TQTextStream s( &f );
- s.setCodec( TQTextCodec::codecForLocale() );
-
- // read the xdg user dirs
- TQString line = s.readLine();
- while (!line.isNull())
- {
- if (line.startsWith("XDG_DOWNLOAD_DIR="))
- download = line.remove("XDG_DOWNLOAD_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
- else if (line.startsWith("XDG_MUSIC_DIR="))
- music = line.remove("XDG_MUSIC_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
- else if (line.startsWith("XDG_PICTURES_DIR="))
- pictures = line.remove("XDG_PICTURES_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
- else if (line.startsWith("XDG_VIDEOS_DIR="))
- videos = line.remove("XDG_VIDEOS_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
- else if (line.startsWith("XDG_TEMPLATES_DIR="))
- templates = line.remove("XDG_TEMPLATES_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
- else if (line.startsWith("XDG_PUBLICSHARES_DIR="))
- publicShares = line.remove("XDG_PUBLICSHARES_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
-
- line = s.readLine();
- }
- // now add in the speedbar
- if (!download.isEmpty())
- insertItem( download, i18n( "Download" ), false, "folder_html" );
- if (!music.isEmpty())
- insertItem( music, i18n( "Music" ), false, "folder_sound" );
- if (!pictures.isEmpty())
- insertItem( pictures, i18n( "Pictures" ), false, "folder_image" );
- if (!videos.isEmpty())
- insertItem( videos, i18n( "Videos" ), false, "folder_video" );
- if (!templates.isEmpty())
- insertItem( templates, i18n( "Templates" ), false, "folder_video" );
- if (!publicShares.isEmpty())
- insertItem( publicShares, i18n( "Public" ), false, "folder_video" );
- }
-
- u = "remote:/";
- if ( KProtocolInfo::isKnownProtocol( u ) )
- insertItem( u, i18n("Network Folders"), false,
- KProtocolInfo::icon( "remote" ) );
- }
-}
-
-KFileSpeedBar::~KFileSpeedBar()
-{
-}
-
-void KFileSpeedBar::save( TDEConfig *config )
-{
- if ( m_initializeSpeedbar && isModified() )
- {
- TDEConfigGroup conf( config, ConfigGroup );
- // write to kdeglobals
- conf.writeEntry( "Set speedbar defaults", false, true, true );
- }
-
- writeConfig( config, "KFileDialog Speedbar" );
-}
-
-TQSize KFileSpeedBar::sizeHint() const
-{
- TQSize sizeHint = KURLBar::sizeHint();
- int ems = fontMetrics().width("mmmmmmmmmmmm");
- if (sizeHint.width() < ems)
- {
- sizeHint.setWidth(ems);
- }
- return sizeHint;
-}
-
-#include "kfilespeedbar.moc"
diff --git a/kio/kfile/kfiletreebranch.cpp b/kio/kfile/kfiletreebranch.cpp
deleted file mode 100644
index 352bd875e..000000000
--- a/kio/kfile/kfiletreebranch.cpp
+++ /dev/null
@@ -1,528 +0,0 @@
-/* This file is part of the KDEproject
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
- 2002 Klaas Freitag <freitag@suse.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqfile.h>
-
-#include <kfileitem.h>
-#include <kdebug.h>
-#include <kde_file.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include "kfiletreeviewitem.h"
-#include "kfiletreebranch.h"
-
-
-/* --- KFileTreeViewToplevelItem --- */
-KFileTreeBranch::KFileTreeBranch( KFileTreeView *parent, const KURL& url,
- const TQString& name,
- const TQPixmap& pix, bool showHidden,
- KFileTreeViewItem *branchRoot )
-
- : KDirLister( false ),
- m_root( branchRoot ),
- m_startURL( url ),
- m_name ( name ),
- m_rootIcon( pix ),
- m_openRootIcon( pix ),
- m_recurseChildren(true),
- m_showExtensions(true)
-{
- kdDebug( 250) << "Creating branch for url " << url.prettyURL() << endl;
-
- /* if non exists, create one */
- if( ! branchRoot )
- {
- m_root = new KFileTreeViewItem( parent,
- new KFileItem( url, "inode/directory",
- S_IFDIR ),
- this );
- }
-
- m_root->setExpandable( true );
- m_root->setPixmap( 0, pix );
- m_root->setText( 0, name );
-
- setShowingDotFiles( showHidden );
-
- connect( this, TQT_SIGNAL( refreshItems(const KFileItemList&)),
- this, TQT_SLOT ( slotRefreshItems( const KFileItemList& )));
-
- connect( this, TQT_SIGNAL( newItems(const KFileItemList&)),
- this, TQT_SLOT ( addItems( const KFileItemList& )));
-
- connect( this, TQT_SIGNAL( completed(const KURL& )),
- this, TQT_SLOT(slCompleted(const KURL&)));
-
- connect( this, TQT_SIGNAL( started( const KURL& )),
- this, TQT_SLOT( slotListerStarted( const KURL& )));
-
- connect( this, TQT_SIGNAL( deleteItem( KFileItem* )),
- this, TQT_SLOT( slotDeleteItem( KFileItem* )));
-
- connect( this, TQT_SIGNAL( canceled(const KURL&) ),
- this, TQT_SLOT( slotCanceled(const KURL&) ));
-
- connect( this, TQT_SIGNAL( clear()),
- this, TQT_SLOT( slotDirlisterClear()));
-
- connect( this, TQT_SIGNAL( clear(const KURL&)),
- this, TQT_SLOT( slotDirlisterClearURL(const KURL&)));
-
- connect( this, TQT_SIGNAL( redirection( const KURL& , const KURL& ) ),
- this, TQT_SLOT( slotRedirect( const KURL&, const KURL& )));
-
- m_openChildrenURLs.append( url );
-}
-
-void KFileTreeBranch::setOpenPixmap( const TQPixmap& pix )
-{
- m_openRootIcon = pix;
-
- if( root()->isOpen())
- {
- root()->setPixmap( 0, pix );
- }
-}
-
-void KFileTreeBranch::slotListerStarted( const KURL &url )
-{
- /* set the parent correct if it is zero. */
- kdDebug( 250) << "Starting to list " << url.prettyURL() << endl;
-}
-
-
-KFileTreeViewItem *KFileTreeBranch::parentKFTVItem( KFileItem *item )
-{
- KFileTreeViewItem *parent = 0;
-
- if( ! item ) return 0;
-
- /* If it is a directory, check, if it exists in the dict. If not, go one up
- * and check again.
- */
- KURL url = item->url();
- // kdDebug(250) << "Item's url is " << url.prettyURL() << endl;
- KURL dirUrl( url );
- dirUrl.setFileName( TQString::null );
- // kdDebug(250) << "Directory url is " << dirUrl.prettyURL() << endl;
-
- parent = findTVIByURL( dirUrl );
- // kdDebug(250) << "Returning as parent item <" << parent << ">" << endl;
- return( parent );
-}
-
-
-void KFileTreeBranch::slotRefreshItems( const KFileItemList& list )
-{
- KFileItemListIterator it( list );
- kdDebug(250) << "Refreshing " << list.count() << " items !" << endl;
- KFileItem *currItem;
- KFileTreeViewItem *item = 0;
-
- while ( (currItem = it.current()) != 0 )
- {
- item = findTVIByURL(currItem->url());
- if (item) {
- item->setPixmap(0, item->fileItem()->pixmap( KIcon::SizeSmall ));
- item->setText( 0, item->fileItem()->text());
- }
- ++it;
- }
-}
-
-void KFileTreeBranch::addItems( const KFileItemList& list )
-{
- KFileItemListIterator it( list );
- kdDebug(250) << "Adding " << list.count() << " items !" << endl;
- KFileItem *currItem;
- KFileTreeViewItemList treeViewItList;
- KFileTreeViewItem *parentItem = 0;
-
- while ( (currItem = it.current()) != 0 )
- {
- parentItem = parentKFTVItem( currItem );
-
-
- /* Only create a new KFileTreeViewItem if it does not yet exist */
- KFileTreeViewItem *newKFTVI =
- static_cast<KFileTreeViewItem *>(currItem->extraData( this ));
-
- if( ! newKFTVI )
- {
- newKFTVI = createTreeViewItem( parentItem, currItem );
- if (!newKFTVI)
- {
- // TODO: Don't fail if parentItem == 0
- ++it;
- continue;
- }
- currItem->setExtraData( this, newKFTVI );
-
- /* Cut off the file extension in case it is not a directory */
- if( !m_showExtensions && !currItem->isDir() ) /* Need to cut the extension */
- {
- TQString name = currItem->text();
- int mPoint = name.findRev( '.' );
- if( mPoint > 0 )
- name = name.left( mPoint );
- newKFTVI->setText( 0, name );
- }
- }
-
- /* Now try to find out if there are children for dirs in the treeview */
- /* This stats a directory on the local file system and checks the */
- /* hardlink entry in the stat-buf. This works only for local directories. */
- if( dirOnlyMode() && !m_recurseChildren && currItem->isLocalFile( ) && currItem->isDir() )
- {
- KURL url = currItem->url();
- TQString filename = url.directory( false, true ) + url.fileName();
- /* do the stat trick of Carsten. The problem is, that the hardlink
- * count only contains directory links. Thus, this method only seem
- * to work in dir-only mode */
- kdDebug(250) << "Doing stat on " << filename << endl;
- KDE_struct_stat statBuf;
- if( KDE_stat( TQFile::encodeName( filename ), &statBuf ) == 0 )
- {
- int hardLinks = statBuf.st_nlink; /* Count of dirs */
- kdDebug(250) << "stat succeeded, hardlinks: " << hardLinks << endl;
- // If the link count is > 2, the directory likely has subdirs. If it's < 2
- // it's something weird like a mounted SMB share. In that case we don't know
- // if there are subdirs, thus show it as expandable.
-
- if( hardLinks != 2 )
- {
- newKFTVI->setExpandable(true);
- }
- else
- {
- newKFTVI->setExpandable(false);
- }
- if( hardLinks >= 2 ) // "Normal" directory with subdirs
- {
- kdDebug(250) << "Emitting for " << url.prettyURL() << endl;
- emit( directoryChildCount( newKFTVI, hardLinks-2)); // parentItem, hardLinks-1 ));
- }
- }
- else
- {
- kdDebug(250) << "stat of " << filename << " failed !" << endl;
- }
- }
- ++it;
-
- treeViewItList.append( newKFTVI );
- }
-
- emit newTreeViewItems( this, treeViewItList );
-}
-
-KFileTreeViewItem* KFileTreeBranch::createTreeViewItem( KFileTreeViewItem *parent,
- KFileItem *fileItem )
-{
- KFileTreeViewItem *tvi = 0;
- if( parent && fileItem )
- {
- tvi = new KFileTreeViewItem( parent,
- fileItem,
- this );
- }
- else
- {
- kdDebug(250) << "createTreeViewItem: Have no parent" << endl;
- }
- return( tvi );
-}
-
-void KFileTreeBranch::setChildRecurse( bool t )
-{
- m_recurseChildren = t;
- if( t == false )
- m_openChildrenURLs.clear();
-}
-
-
-void KFileTreeBranch::setShowExtensions( bool visible )
-{
- m_showExtensions = visible;
-}
-
-bool KFileTreeBranch::showExtensions( ) const
-{
- return( m_showExtensions );
-}
-
-/*
- * The signal that tells that a directory was deleted may arrive before the signal
- * for its children arrive. Thus, we must walk through the children of a dir and
- * remove them before removing the dir itself.
- */
-void KFileTreeBranch::slotDeleteItem( KFileItem *it )
-{
- if( !it ) return;
- kdDebug(250) << "Slot Delete Item hitted for " << it->url().prettyURL() << endl;
-
- KFileTreeViewItem *kfti = static_cast<KFileTreeViewItem*>(it->extraData(this));
-
- if( kfti )
- {
- kdDebug( 250 ) << "Child count: " << kfti->childCount() << endl;
- if( kfti->childCount() > 0 )
- {
- KFileTreeViewItem *child = static_cast<KFileTreeViewItem*>(kfti->firstChild());
-
- while( child )
- {
- kdDebug(250) << "Calling child to be deleted !" << endl;
- KFileTreeViewItem *nextChild = static_cast<KFileTreeViewItem*>(child->nextSibling());
- slotDeleteItem( child->fileItem());
- child = nextChild;
- }
- }
-
- kdDebug(250) << "Found corresponding KFileTreeViewItem" << endl;
- if( m_lastFoundURL.equals(it->url(), true ))
- {
- m_lastFoundURL = KURL();
- m_lastFoundItem = 0L;
- }
- delete( kfti );
- }
- else
- {
- kdDebug(250) << "Error: kfiletreeviewitem: "<< kfti << endl;
- }
-}
-
-
-void KFileTreeBranch::slotCanceled( const KURL& url )
-{
- // ### anything else to do?
- // remove the url from the childrento-recurse-list
- m_openChildrenURLs.remove( url);
-
- // stop animations etc.
- KFileTreeViewItem *item = findTVIByURL(url);
- if (!item) return; // Uh oh...
- emit populateFinished(item);
-}
-
-void KFileTreeBranch::slotDirlisterClear()
-{
- kdDebug(250)<< "*** Clear all !" << endl;
- /* this slots needs to clear all listed items, but NOT the root item */
- if( m_root )
- deleteChildrenOf( m_root );
-}
-
-void KFileTreeBranch::slotDirlisterClearURL( const KURL& url )
-{
- kdDebug(250)<< "*** Clear for URL !" << url.prettyURL() << endl;
- KFileItem *item = findByURL( url );
- if( item )
- {
- KFileTreeViewItem *ftvi =
- static_cast<KFileTreeViewItem *>(item->extraData( this ));
- deleteChildrenOf( ftvi );
- }
-}
-
-void KFileTreeBranch::deleteChildrenOf( TQListViewItem *parent )
-{
- // for some strange reason, slotDirlisterClearURL() sometimes calls us
- // with a 0L parent.
- if ( !parent )
- return;
-
- while ( parent->firstChild() )
- delete parent->firstChild();
-}
-
-void KFileTreeBranch::slotRedirect( const KURL& oldUrl, const KURL&newUrl )
-{
- if( oldUrl.equals( m_startURL, true ))
- {
- m_startURL = newUrl;
- }
-}
-
-KFileTreeViewItem* KFileTreeBranch::findTVIByURL( const KURL& url )
-{
- KFileTreeViewItem *resultItem = 0;
-
- if( m_startURL.equals(url, true) )
- {
- kdDebug(250) << "findByURL: Returning root as a parent !" << endl;
- resultItem = m_root;
- }
- else if( m_lastFoundURL.equals( url, true ))
- {
- kdDebug(250) << "findByURL: Returning from lastFoundURL!" << endl;
- resultItem = m_lastFoundItem;
- }
- else
- {
- kdDebug(250) << "findByURL: searching by dirlister: " << url.url() << endl;
-
- KFileItem *it = findByURL( url );
-
- if( it )
- {
- resultItem = static_cast<KFileTreeViewItem*>(it->extraData(this));
- m_lastFoundItem = resultItem;
- m_lastFoundURL = url;
- }
- }
-
- return( resultItem );
-}
-
-
-void KFileTreeBranch::slCompleted( const KURL& url )
-{
- kdDebug(250) << "SlotCompleted hit for " << url.prettyURL() << endl;
- KFileTreeViewItem *currParent = findTVIByURL( url );
- if( ! currParent ) return;
-
- kdDebug(250) << "current parent " << currParent << " is already listed: "
- << currParent->alreadyListed() << endl;
-
- emit( populateFinished(currParent));
- emit( directoryChildCount(currParent, currParent->childCount()));
-
- /* This is a walk through the children of the last populated directory.
- * Here we start the dirlister on every child of the dir and wait for its
- * finish. When it has finished, we go to the next child.
- * This must be done for non local file systems in dirOnly- and Full-Mode
- * and for local file systems only in full mode, because the stat trick
- * (see addItem-Method) does only work for dirs, not for files in the directory.
- */
- /* Set bit that the parent dir was listed completely */
- currParent->setListed(true);
-
- kdDebug(250) << "recurseChildren: " << m_recurseChildren << endl;
- kdDebug(250) << "isLocalFile: " << m_startURL.isLocalFile() << endl;
- kdDebug(250) << "dirOnlyMode: " << dirOnlyMode() << endl;
-
-
- if( m_recurseChildren && (!m_startURL.isLocalFile() || ! dirOnlyMode()) )
- {
- bool wantRecurseUrl = false;
- /* look if the url is in the list for url to recurse */
- for ( KURL::List::Iterator it = m_openChildrenURLs.begin();
- it != m_openChildrenURLs.end(); ++it )
- {
- /* it is only interesting that the url _is_in_ the list. */
- if( (*it).equals( url, true ) )
- wantRecurseUrl = true;
- }
-
- KFileTreeViewItem *nextChild = 0;
- kdDebug(250) << "Recursing " << url.prettyURL() << "? " << wantRecurseUrl << endl;
-
- if( wantRecurseUrl && currParent )
- {
-
- /* now walk again through the tree and populate the children to get +-signs */
- /* This is the starting point. The visible folder has finished,
- processing the children has not yet started */
- nextChild = static_cast<KFileTreeViewItem*>
- (static_cast<TQListViewItem*>(currParent)->firstChild());
-
- if( ! nextChild )
- {
- /* This happens if there is no child at all */
- kdDebug( 250 ) << "No children to recuse" << endl;
- }
-
- /* Since we have listed the children to recurse, we can remove the entry
- * in the list of the URLs to see the children.
- */
- m_openChildrenURLs.remove(url);
- }
-
- if( nextChild ) /* This implies that idx > -1 */
- {
- /* Next child is defined. We start a dirlister job on every child item
- * which is a directory to find out how much children are in the child
- * of the last opened dir
- */
-
- /* Skip non directory entries */
- while( nextChild )
- {
- if( nextChild->isDir() && ! nextChild->alreadyListed())
- {
- KFileItem *kfi = nextChild->fileItem();
- if( kfi && kfi->isReadable())
- {
- KURL recurseUrl = kfi->url();
- kdDebug(250) << "Starting to recurse NOW " << recurseUrl.prettyURL() << endl;
- openURL( recurseUrl, true );
- }
- }
- nextChild = static_cast<KFileTreeViewItem*>(static_cast<TQListViewItem*>(nextChild->nextSibling()));
- // kdDebug(250) << "Next child " << m_nextChild << endl;
- }
- }
- }
- else
- {
- kdDebug(250) << "skipping to recurse in complete-slot" << endl;
- }
-}
-
-/* This slot is called when a treeviewitem is expanded in the gui */
-bool KFileTreeBranch::populate( const KURL& url, KFileTreeViewItem *currItem )
-{
- bool ret = false;
- if( ! currItem )
- return ret;
-
- kdDebug(250) << "Populating <" << url.prettyURL() << ">" << endl;
-
- /* Add this url to the list of urls to recurse for children */
- if( m_recurseChildren )
- {
- m_openChildrenURLs.append( url );
- kdDebug(250) << "Appending to list " << url.prettyURL() << endl;
- }
-
- if( ! currItem->alreadyListed() )
- {
- /* start the lister */
- ret = openURL( url, true );
- }
- else
- {
- kdDebug(250) << "Children already existing in treeview!" << endl;
- slCompleted( url );
- ret = true;
- }
- return ret;
-}
-
-void KFileTreeBranch::virtual_hook( int id, void* data )
-{ KDirLister::virtual_hook( id, data ); }
-
-#include "kfiletreebranch.moc"
-
diff --git a/kio/kfile/kfiletreebranch.h b/kio/kfile/kfiletreebranch.h
deleted file mode 100644
index 31e6dcfc0..000000000
--- a/kio/kfile/kfiletreebranch.h
+++ /dev/null
@@ -1,242 +0,0 @@
-
-/* This file is part of the KDE project
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
- 2001 Klaas Freitag <freitag@suse.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef kfile_tree_branch_h
-#define kfile_tree_branch_h
-
-#include <tqdict.h>
-#include <tqlistview.h>
-
-#include <kfileitem.h>
-#include <kio/global.h>
-#include <kdirlister.h>
-#include <kio/job.h>
-#include <kfiletreeviewitem.h>
-
-class KURL;
-class KFileTreeView;
-
-
-/**
- * This is the branch class of the KFileTreeView, which represents one
- * branch in the treeview. Every branch has a root which is an url. The branch
- * lists the files under the root. Every branch uses its own dirlister and can
- * have its own filter etc.
- *
- * @short Branch object for KFileTreeView object.
- *
- */
-
-class TDEIO_EXPORT KFileTreeBranch : public KDirLister
-{
- Q_OBJECT
-public:
- /**
- * constructs a branch for KFileTreeView. Does not yet start to list it.
- * @param url start url of the branch.
- * @param name the name of the branch, which is displayed in the first column of the treeview.
- * @param pix is a pixmap to display as an icon of the branch.
- * @param showHidden flag to make hidden files visible or not.
- * @param branchRoot is the KFileTreeViewItem to use as the root of the
- * branch, with the default 0 meaning to let KFileTreeBranch create
- * it for you.
- */
- KFileTreeBranch( KFileTreeView*, const KURL& url, const TQString& name,
- const TQPixmap& pix, bool showHidden = false,
- KFileTreeViewItem *branchRoot = 0 );
-
- /**
- * @returns the root url of the branch.
- */
- KURL rootUrl() const { return( m_startURL ); }
-
- /**
- * sets a KFileTreeViewItem as root widget for the branch.
- * That must be created outside of the branch. All KFileTreeViewItems
- * the branch is allocating will become children of that object.
- * @param r the KFileTreeViewItem to become the root item.
- */
- virtual void setRoot( KFileTreeViewItem *r ){ m_root = r; };
-
- /**
- * @returns the root item.
- */
- KFileTreeViewItem *root( ) { return( m_root );}
-
- /**
- * @returns the name of the branch.
- */
- TQString name() const { return( m_name ); }
-
- /**
- * sets the name of the branch.
- */
- virtual void setName( const TQString n ) { m_name = n; };
-
- /*
- * returns the current root item pixmap set in the constructor. The root
- * item pixmap defaults to the icon for directories.
- * @see openPixmap()
- */
- const TQPixmap& pixmap(){ return(m_rootIcon); }
-
- /*
- * returns the current root item pixmap set by setOpenPixmap()
- * which is displayed if the branch is expanded.
- * The root item pixmap defaults to the icon for directories.
- * @see pixmap()
- * Note that it depends on KFileTreeView::showFolderOpenPximap weather
- * open pixmap are displayed or not.
- */
- const TQPixmap& openPixmap() { return(m_openRootIcon); }
-
- /**
- * @returns whether the items in the branch show their file extensions in the
- * tree or not. See setShowExtensions for more information.
- */
- bool showExtensions( ) const;
-
- /**
- * sets the root of the branch open or closed.
- */
- void setOpen( bool setopen = true )
- { if( root() ) root()->setOpen( setopen ); }
-
- /**
- * sets if children recursion is wanted or not. If this is switched off, the
- * child directories of a just opened directory are not listed internally.
- * That means that it can not be determined if the sub directories are
- * expandable or not. If this is switched off there will be no call to
- * setExpandable.
- * @param t set to true to switch on child recursion
- */
- void setChildRecurse( bool t=true );
-
- /**
- * @returns if child recursion is on or off.
- * @see setChildRecurse
- */
- bool childRecurse()
- { return m_recurseChildren; }
-
-public slots:
- /**
- * populates a branch. This method must be called after a branch was added
- * to a KFileTreeView using method addBranch.
- * @param url is the url of the root item where the branch starts.
- * @param currItem is the current parent.
- */
- virtual bool populate( const KURL &url, KFileTreeViewItem* currItem );
-
- /**
- * sets printing of the file extensions on or off. If you pass false to this
- * slot, all items of this branch will not show their file extensions in the
- * tree.
- * @param visible flags if the extensions should be visible or not.
- */
- virtual void setShowExtensions( bool visible = true );
-
- void setOpenPixmap( const TQPixmap& pix );
-
-protected:
- /**
- * allocates a KFileTreeViewItem for the branch
- * for new items.
- */
- virtual KFileTreeViewItem *createTreeViewItem( KFileTreeViewItem *parent,
- KFileItem *fileItem );
-
-public:
- /**
- * find the according KFileTreeViewItem by an url
- */
- virtual KFileTreeViewItem *findTVIByURL( const KURL& );
-
-signals:
- /**
- * emitted with the item of a directory which was finished to populate
- */
- void populateFinished( KFileTreeViewItem * );
-
- /**
- * emitted with a list of new or updated KFileTreeViewItem which were
- * found in a branch. Note that this signal is emitted very often and may slow
- * down the performance of the treeview !
- */
- void newTreeViewItems( KFileTreeBranch*, const KFileTreeViewItemList& );
-
- /**
- * emitted with the exact count of children for a directory.
- */
- void directoryChildCount( KFileTreeViewItem* item, int count );
-
-private slots:
- void slotRefreshItems( const KFileItemList& );
- void addItems( const KFileItemList& );
- void slCompleted( const KURL& );
- void slotCanceled( const KURL& );
- void slotListerStarted( const KURL& );
- void slotDeleteItem( KFileItem* );
- void slotDirlisterClear();
- void slotDirlisterClearURL( const KURL& url );
- void slotRedirect( const KURL& oldUrl, const KURL&newUrl );
-
-private:
- KFileTreeViewItem *parentKFTVItem( KFileItem *item );
- static void deleteChildrenOf( TQListViewItem *parent );
-
- KFileTreeViewItem *m_root;
- KURL m_startURL;
- TQString m_name;
- TQPixmap m_rootIcon;
- TQPixmap m_openRootIcon;
-
- /* this list holds the url's which children are opened. */
- KURL::List m_openChildrenURLs;
-
-
- /* The next two members are used for caching purposes in findTVIByURL. */
- KURL m_lastFoundURL;
- KFileTreeViewItem *m_lastFoundItem;
-
- bool m_recurseChildren :1;
- bool m_showExtensions :1;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KFileTreeBranchPrivate;
- KFileTreeBranchPrivate *d;
-};
-
-
-/**
- * List of KFileTreeBranches
- */
-typedef TQPtrList<KFileTreeBranch> KFileTreeBranchList;
-
-/**
- * Iterator for KFileTreeBranchLists
- */
-typedef TQPtrListIterator<KFileTreeBranch> KFileTreeBranchIterator;
-
-#endif
-
diff --git a/kio/kfile/kfiletreeview.cpp b/kio/kfile/kfiletreeview.cpp
deleted file mode 100644
index 0b8504fd6..000000000
--- a/kio/kfile/kfiletreeview.cpp
+++ /dev/null
@@ -1,677 +0,0 @@
-/* This file is part of the KDEproject
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqapplication.h>
-#include <tqheader.h>
-#include <tqtimer.h>
-#include <kdebug.h>
-#include <kdirnotify_stub.h>
-#include <kglobalsettings.h>
-#include <kfileitem.h>
-#include <kfileview.h>
-#include <kmimetype.h>
-#include <kstandarddirs.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <kio/job.h>
-#include <kio/global.h>
-#include <kurldrag.h>
-#include <kiconloader.h>
-
-
-#include "kfiletreeview.h"
-#include "kfiletreebranch.h"
-#include "kfiletreeviewitem.h"
-
-KFileTreeView::KFileTreeView( TQWidget *parent, const char *name )
- : KListView( parent, name ),
- m_wantOpenFolderPixmaps( true ),
- m_toolTip( this )
-{
- setDragEnabled(true);
- setSelectionModeExt( KListView::Single );
-
- m_animationTimer = new TQTimer( this );
- connect( m_animationTimer, TQT_SIGNAL( timeout() ),
- this, TQT_SLOT( slotAnimation() ) );
-
- m_currentBeforeDropItem = 0;
- m_dropItem = 0;
-
- m_autoOpenTimer = new TQTimer( this );
- connect( m_autoOpenTimer, TQT_SIGNAL( timeout() ),
- this, TQT_SLOT( slotAutoOpenFolder() ) );
-
- /* The executed-Slot only opens a path, while the expanded-Slot populates it */
- connect( this, TQT_SIGNAL( executed( TQListViewItem * ) ),
- this, TQT_SLOT( slotExecuted( TQListViewItem * ) ) );
- connect( this, TQT_SIGNAL( expanded ( TQListViewItem *) ),
- this, TQT_SLOT( slotExpanded( TQListViewItem *) ));
- connect( this, TQT_SIGNAL( collapsed( TQListViewItem *) ),
- this, TQT_SLOT( slotCollapsed( TQListViewItem* )));
-
-
- /* connections from the konqtree widget */
- connect( this, TQT_SIGNAL( selectionChanged() ),
- this, TQT_SLOT( slotSelectionChanged() ) );
- connect( this, TQT_SIGNAL( onItem( TQListViewItem * )),
- this, TQT_SLOT( slotOnItem( TQListViewItem * ) ) );
- connect( this, TQT_SIGNAL(itemRenamed(TQListViewItem*, const TQString &, int)),
- this, TQT_SLOT(slotItemRenamed(TQListViewItem*, const TQString &, int)));
-
-
- m_bDrag = false;
- m_branches.setAutoDelete( true );
-
- m_openFolderPixmap = DesktopIcon( "folder_open",KIcon::SizeSmall,KIcon::ActiveState );
-}
-
-KFileTreeView::~KFileTreeView()
-{
- // we must make sure that the KFileTreeViewItems are deleted _before_ the
- // branches are deleted. Otherwise, the KFileItems would be destroyed
- // and the KFileTreeViewItems had dangling pointers to them.
- hide();
- clear();
- m_branches.clear(); // finally delete the branches and KFileItems
-}
-
-
-bool KFileTreeView::isValidItem( TQListViewItem *item)
-{
- if (!item)
- return false;
- TQPtrList<TQListViewItem> lst;
- TQListViewItemIterator it( this );
- while ( it.current() )
- {
- if ( it.current() == item )
- return true;
- ++it;
- }
- return false;
-}
-
-void KFileTreeView::contentsDragEnterEvent( TQDragEnterEvent *ev )
-{
- if ( ! acceptDrag( ev ) )
- {
- ev->ignore();
- return;
- }
- ev->acceptAction();
- m_currentBeforeDropItem = selectedItem();
-
- TQListViewItem *item = itemAt( contentsToViewport( ev->pos() ) );
- if( item )
- {
- m_dropItem = item;
- m_autoOpenTimer->start( KFileView::autoOpenDelay() );
- }
- else
- {
- m_dropItem = 0;
-}
-}
-
-void KFileTreeView::contentsDragMoveEvent( TQDragMoveEvent *e )
-{
- if( ! acceptDrag( e ) )
- {
- e->ignore();
- return;
- }
- e->acceptAction();
-
-
- TQListViewItem *afterme;
- TQListViewItem *parent;
-
- findDrop( e->pos(), parent, afterme );
-
- // "afterme" is 0 when aiming at a directory itself
- TQListViewItem *item = afterme ? afterme : parent;
-
- if( item && item->isSelectable() )
- {
- setSelected( item, true );
- if( item != m_dropItem ) {
- m_autoOpenTimer->stop();
- m_dropItem = item;
- m_autoOpenTimer->start( KFileView::autoOpenDelay() );
- }
- }
- else
- {
- m_autoOpenTimer->stop();
- m_dropItem = 0;
- }
-}
-
-void KFileTreeView::contentsDragLeaveEvent( TQDragLeaveEvent * )
-{
- // Restore the current item to what it was before the dragging (#17070)
- if ( isValidItem(m_currentBeforeDropItem) )
- {
- setSelected( m_currentBeforeDropItem, true );
- ensureItemVisible( m_currentBeforeDropItem );
- }
- else if ( isValidItem(m_dropItem) )
- setSelected( m_dropItem, false ); // no item selected
- m_currentBeforeDropItem = 0;
- m_dropItem = 0;
-
-}
-
-void KFileTreeView::contentsDropEvent( TQDropEvent *e )
-{
-
- m_autoOpenTimer->stop();
- m_dropItem = 0;
-
- kdDebug(250) << "contentsDropEvent !" << endl;
- if( ! acceptDrag( e ) ) {
- e->ignore();
- return;
- }
-
- e->acceptAction();
- TQListViewItem *afterme;
- TQListViewItem *parent;
- findDrop(e->pos(), parent, afterme);
-
- //kdDebug(250) << " parent=" << (parent?parent->text(0):TQString::null)
- // << " afterme=" << (afterme?afterme->text(0):TQString::null) << endl;
-
- if (e->source() == viewport() && itemsMovable())
- movableDropEvent(parent, afterme);
- else
- {
- emit dropped(e, afterme);
- emit dropped(this, e, afterme);
- emit dropped(e, parent, afterme);
- emit dropped(this, e, parent, afterme);
-
- KURL::List urls;
- KURLDrag::decode( e, urls );
- emit dropped( this, e, urls );
-
- KURL parentURL;
- if( parent )
- parentURL = static_cast<KFileTreeViewItem*>(parent)->url();
- else
- // can happen when dropping above the root item
- // Should we choose the first branch in such a case ??
- return;
-
- emit dropped( urls, parentURL );
- emit dropped( this , e, urls, parentURL );
- }
-}
-
-bool KFileTreeView::acceptDrag(TQDropEvent* e ) const
-{
-
- bool ancestOK= acceptDrops();
- // kdDebug(250) << "Do accept drops: " << ancestOK << endl;
- ancestOK = ancestOK && itemsMovable();
- // kdDebug(250) << "acceptDrag: " << ancestOK << endl;
- // kdDebug(250) << "canDecode: " << KURLDrag::canDecode(e) << endl;
- // kdDebug(250) << "action: " << e->action() << endl;
-
- /* KListView::acceptDrag(e); */
- /* this is what KListView does:
- * acceptDrops() && itemsMovable() && (e->source()==viewport());
- * ask acceptDrops and itemsMovable, but not the third
- */
- return ancestOK && KURLDrag::canDecode( e ) &&
- // Why this test? All DnDs are one of those AFAIK (DF)
- ( e->action() == TQDropEvent::Copy
- || e->action() == TQDropEvent::Move
- || e->action() == TQDropEvent::Link );
-}
-
-
-
-TQDragObject * KFileTreeView::dragObject()
-{
-
- KURL::List urls;
- const TQPtrList<TQListViewItem> fileList = selectedItems();
- TQPtrListIterator<TQListViewItem> it( fileList );
- for ( ; it.current(); ++it )
- {
- urls.append( static_cast<KFileTreeViewItem*>(it.current())->url() );
- }
- TQPoint hotspot;
- TQPixmap pixmap;
- if( urls.count() > 1 ){
- pixmap = DesktopIcon( "tdemultiple", 16 );
- }
- if( pixmap.isNull() )
- pixmap = currentKFileTreeViewItem()->fileItem()->pixmap( 16 );
- hotspot.setX( pixmap.width() / 2 );
- hotspot.setY( pixmap.height() / 2 );
- TQDragObject* dragObject = new KURLDrag( urls, this );
- if( dragObject )
- dragObject->setPixmap( pixmap, hotspot );
- return dragObject;
-}
-
-
-
-void KFileTreeView::slotCollapsed( TQListViewItem *item )
-{
- KFileTreeViewItem *kftvi = static_cast<KFileTreeViewItem*>(item);
- kdDebug(250) << "hit slotCollapsed" << endl;
- if( kftvi && kftvi->isDir())
- {
- item->setPixmap( 0, itemIcon(kftvi));
- }
-}
-
-void KFileTreeView::slotExpanded( TQListViewItem *item )
-{
- kdDebug(250) << "slotExpanded here !" << endl;
-
- if( ! item ) return;
-
- KFileTreeViewItem *it = static_cast<KFileTreeViewItem*>(item);
- KFileTreeBranch *branch = it->branch();
-
- /* Start the animation for the branch object */
- if( it->isDir() && branch && item->childCount() == 0 )
- {
- /* check here if the branch really needs to be populated again */
- kdDebug(250 ) << "starting to open " << it->url().prettyURL() << endl;
- startAnimation( it );
- bool branchAnswer = branch->populate( it->url(), it );
- kdDebug(250) << "Branches answer: " << branchAnswer << endl;
- if( ! branchAnswer )
- {
- kdDebug(250) << "ERR: Could not populate!" << endl;
- stopAnimation( it );
- }
- }
-
- /* set a pixmap 'open folder' */
- if( it->isDir() && isOpen( item ) )
- {
- kdDebug(250)<< "Setting open Pixmap" << endl;
- item->setPixmap( 0, itemIcon( it )); // 0, m_openFolderPixmap );
- }
-}
-
-
-
-void KFileTreeView::slotExecuted( TQListViewItem *item )
-{
- if ( !item )
- return;
- /* This opens the dir and causes the Expanded-slot to be called,
- * which strolls through the children.
- */
- if( static_cast<KFileTreeViewItem*>(item)->isDir())
- {
- item->setOpen( !item->isOpen() );
- }
-}
-
-
-void KFileTreeView::slotAutoOpenFolder()
-{
- m_autoOpenTimer->stop();
-
- if ( !isValidItem(m_dropItem) || m_dropItem->isOpen() )
- return;
-
- m_dropItem->setOpen( true );
- m_dropItem->repaint();
-}
-
-
-void KFileTreeView::slotSelectionChanged()
-{
- if ( !m_dropItem ) // don't do this while the dragmove thing
- {
- }
-}
-
-
-KFileTreeBranch* KFileTreeView::addBranch( const KURL &path, const TQString& name,
- bool showHidden )
-{
- const TQPixmap& folderPix = KMimeType::mimeType("inode/directory")->pixmap( KIcon::Desktop,KIcon::SizeSmall );
-
- return addBranch( path, name, folderPix, showHidden);
-}
-
-KFileTreeBranch* KFileTreeView::addBranch( const KURL &path, const TQString& name,
- const TQPixmap& pix, bool showHidden )
-{
- kdDebug(250) << "adding another root " << path.prettyURL() << endl;
-
- /* Open a new branch */
- KFileTreeBranch *newBranch = new KFileTreeBranch( this, path, name, pix,
- showHidden );
- return addBranch(newBranch);
-}
-
-KFileTreeBranch *KFileTreeView::addBranch(KFileTreeBranch *newBranch)
-{
- connect( newBranch, TQT_SIGNAL(populateFinished( KFileTreeViewItem* )),
- this, TQT_SLOT( slotPopulateFinished( KFileTreeViewItem* )));
-
- connect( newBranch, TQT_SIGNAL( newTreeViewItems( KFileTreeBranch*,
- const KFileTreeViewItemList& )),
- this, TQT_SLOT( slotNewTreeViewItems( KFileTreeBranch*,
- const KFileTreeViewItemList& )));
-
- m_branches.append( newBranch );
- return( newBranch );
-}
-
-KFileTreeBranch *KFileTreeView::branch( const TQString& searchName )
-{
- KFileTreeBranch *branch = 0;
- TQPtrListIterator<KFileTreeBranch> it( m_branches );
-
- while ( (branch = it.current()) != 0 ) {
- ++it;
- TQString bname = branch->name();
- kdDebug(250) << "This is the branches name: " << bname << endl;
- if( bname == searchName )
- {
- kdDebug(250) << "Found branch " << bname << " and return ptr" << endl;
- return( branch );
- }
- }
- return ( 0L );
-}
-
-KFileTreeBranchList& KFileTreeView::branches()
-{
- return( m_branches );
-}
-
-
-bool KFileTreeView::removeBranch( KFileTreeBranch *branch )
-{
- if(m_branches.contains(branch))
- {
- delete (branch->root());
- m_branches.remove( branch );
- return true;
- }
- else
- {
- return false;
- }
-}
-
-void KFileTreeView::setDirOnlyMode( KFileTreeBranch* branch, bool bom )
-{
- if( branch )
- {
- branch->setDirOnlyMode( bom );
- }
-}
-
-
-void KFileTreeView::slotPopulateFinished( KFileTreeViewItem *it )
-{
- if( it && it->isDir())
- stopAnimation( it );
-}
-
-void KFileTreeView::slotNewTreeViewItems( KFileTreeBranch* branch, const KFileTreeViewItemList& itemList )
-{
- if( ! branch ) return;
- kdDebug(250) << "hitting slotNewTreeViewItems" << endl;
-
- /* Sometimes it happens that new items should become selected, i.e. if the user
- * creates a new dir, he probably wants it to be selected. This can not be done
- * right after creating the directory or file, because it takes some time until
- * the item appears here in the treeview. Thus, the creation code sets the member
- * m_neUrlToSelect to the required url. If this url appears here, the item becomes
- * selected and the member nextUrlToSelect will be cleared.
- */
- if( ! m_nextUrlToSelect.isEmpty() )
- {
- KFileTreeViewItemListIterator it( itemList );
-
- bool end = false;
- for( ; !end && it.current(); ++it )
- {
- KURL url = (*it)->url();
-
- if( m_nextUrlToSelect.equals(url, true )) // ignore trailing / on dirs
- {
- setCurrentItem( static_cast<TQListViewItem*>(*it) );
- m_nextUrlToSelect = KURL();
- end = true;
- }
- }
- }
-}
-
-TQPixmap KFileTreeView::itemIcon( KFileTreeViewItem *item, int gap ) const
-{
- TQPixmap pix;
- kdDebug(250) << "Setting icon for column " << gap << endl;
-
- if( item )
- {
- /* Check if it is a branch root */
- KFileTreeBranch *brnch = item->branch();
- if( item == brnch->root() )
- {
- pix = brnch->pixmap();
- if( m_wantOpenFolderPixmaps && brnch->root()->isOpen() )
- {
- pix = brnch->openPixmap();
- }
- }
- else
- {
- // TODO: different modes, user Pixmaps ?
- pix = item->fileItem()->pixmap( KIcon::SizeSmall ); // , KIcon::DefaultState);
-
- /* Only if it is a dir and the user wants open dir pixmap and it is open,
- * change the fileitem's pixmap to the open folder pixmap. */
- if( item->isDir() && m_wantOpenFolderPixmaps )
- {
- if( isOpen( static_cast<TQListViewItem*>(item)))
- pix = m_openFolderPixmap;
- }
- }
- }
-
- return pix;
-}
-
-
-void KFileTreeView::slotAnimation()
-{
- MapCurrentOpeningFolders::Iterator it = m_mapCurrentOpeningFolders.begin();
- MapCurrentOpeningFolders::Iterator end = m_mapCurrentOpeningFolders.end();
- for (; it != end;)
- {
- KFileTreeViewItem *item = it.key();
- if (!isValidItem(item))
- {
- ++it;
- m_mapCurrentOpeningFolders.remove(item);
- continue;
- }
-
- uint & iconNumber = it.data().iconNumber;
- TQString icon = TQString::fromLatin1( it.data().iconBaseName ).append( TQString::number( iconNumber ) );
- // kdDebug(250) << "Loading icon " << icon << endl;
- item->setPixmap( 0, DesktopIcon( icon,KIcon::SizeSmall,KIcon::ActiveState )); // KFileTreeViewFactory::instance() ) );
-
- iconNumber++;
- if ( iconNumber > it.data().iconCount )
- iconNumber = 1;
-
- ++it;
- }
-}
-
-
-void KFileTreeView::startAnimation( KFileTreeViewItem * item, const char * iconBaseName, uint iconCount )
-{
- /* TODO: allow specific icons */
- if( ! item )
- {
- kdDebug(250) << " startAnimation Got called without valid item !" << endl;
- return;
- }
-
- m_mapCurrentOpeningFolders.insert( item,
- AnimationInfo( iconBaseName,
- iconCount,
- itemIcon(item, 0) ) );
- if ( !m_animationTimer->isActive() )
- m_animationTimer->start( 50 );
-}
-
-void KFileTreeView::stopAnimation( KFileTreeViewItem * item )
-{
- if( ! item ) return;
-
- kdDebug(250) << "Stoping Animation !" << endl;
-
- MapCurrentOpeningFolders::Iterator it = m_mapCurrentOpeningFolders.find(item);
- if ( it != m_mapCurrentOpeningFolders.end() )
- {
- if( item->isDir() && isOpen( item) )
- {
- kdDebug(250) << "Setting folder open pixmap !" << endl;
- item->setPixmap( 0, itemIcon( item ));
- }
- else
- {
- item->setPixmap( 0, it.data().originalPixmap );
- }
- m_mapCurrentOpeningFolders.remove( item );
- }
- else
- {
- if( item )
- kdDebug(250)<< "StopAnimation - could not find item " << item->url().prettyURL()<< endl;
- else
- kdDebug(250)<< "StopAnimation - item is zero !" << endl;
- }
- if (m_mapCurrentOpeningFolders.isEmpty())
- m_animationTimer->stop();
-}
-
-KFileTreeViewItem * KFileTreeView::currentKFileTreeViewItem() const
-{
- return static_cast<KFileTreeViewItem *>( selectedItem() );
-}
-
-KURL KFileTreeView::currentURL() const
-{
- KFileTreeViewItem *item = currentKFileTreeViewItem();
- if ( item )
- return currentKFileTreeViewItem()->url();
- else
- return KURL();
-}
-
-void KFileTreeView::slotOnItem( TQListViewItem *item )
-{
- KFileTreeViewItem *i = static_cast<KFileTreeViewItem *>( item );
- if( i )
- {
- const KURL url = i->url();
- if ( url.isLocalFile() )
- emit onItem( url.path() );
- else
- emit onItem( url.prettyURL() );
- }
-}
-
-void KFileTreeView::slotItemRenamed(TQListViewItem* item, const TQString &name, int col)
-{
- (void) item;
- kdDebug(250) << "Do not bother: " << name << col << endl;
-}
-
-KFileTreeViewItem *KFileTreeView::findItem( const TQString& branchName, const TQString& relUrl )
-{
- KFileTreeBranch *br = branch( branchName );
- return( findItem( br, relUrl ));
-}
-
-KFileTreeViewItem *KFileTreeView::findItem( KFileTreeBranch* brnch, const TQString& relUrl )
-{
- KFileTreeViewItem *ret = 0;
- if( brnch )
- {
- KURL url = brnch->rootUrl();
-
- if( ! relUrl.isEmpty() && TQDir::isRelativePath(relUrl) )
- {
- TQString partUrl( relUrl );
-
- if( partUrl.endsWith("/"))
- partUrl.truncate( relUrl.length()-1 );
-
- url.addPath( partUrl );
-
- kdDebug(250) << "assembled complete dir string " << url.prettyURL() << endl;
-
- KFileItem *fi = brnch->findByURL( url );
- if( fi )
- {
- ret = static_cast<KFileTreeViewItem*>( fi->extraData( brnch ));
- kdDebug(250) << "Found item !" <<ret << endl;
- }
- }
- else
- {
- ret = brnch->root();
- }
- }
- return( ret );
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-void KFileTreeViewToolTip::maybeTip( const TQPoint & )
-{
-#if 0
- TQListViewItem *item = m_view->itemAt( point );
- if ( item ) {
- TQString text = static_cast<KFileViewItem*>( item )->toolTipText();
- if ( !text.isEmpty() )
- tip ( m_view->itemRect( item ), text );
- }
-#endif
-}
-
-void KFileTreeView::virtual_hook( int id, void* data )
-{ KListView::virtual_hook( id, data ); }
-
-#include "kfiletreeview.moc"
diff --git a/kio/kfile/kfiletreeview.h b/kio/kfile/kfiletreeview.h
deleted file mode 100644
index f28f0f01e..000000000
--- a/kio/kfile/kfiletreeview.h
+++ /dev/null
@@ -1,273 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
- 2002 Klaas Freitag <freitag@suse.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef kfile_tree_view_h
-#define kfile_tree_view_h
-
-#include <tqmap.h>
-#include <tqpoint.h>
-#include <tqpixmap.h>
-#include <tqstrlist.h>
-#include <tqtooltip.h>
-
-#include <klistview.h>
-#include <kdirnotify.h>
-#include <kio/job.h>
-#include <kfiletreeviewitem.h>
-#include <kfiletreebranch.h>
-
-class TQTimer;
-
-
-
-class TDEIO_EXPORT KFileTreeViewToolTip : public TQToolTip
-{
-public:
- KFileTreeViewToolTip( TQListView *view ) : TQToolTip( view ), m_view( view ) {}
-
-protected:
- virtual void maybeTip( const TQPoint & );
-
-private:
- TQListView *m_view;
-};
-
-
-/**
- * The filetreeview offers a treeview on the file system which behaves like
- * a QTreeView showing files and/or directories in the file system.
- *
- * KFileTreeView is able to handle more than one URL, represented by
- * KFileTreeBranch.
- *
- * Typical usage:
- * 1. create a KFileTreeView fitting in your layout and add columns to it
- * 2. call addBranch to create one or more branches
- * 3. retrieve the root item with KFileTreeBranch::root() and set it open
- * if desired. That starts the listing.
- */
-class TDEIO_EXPORT KFileTreeView : public KListView
-{
- Q_OBJECT
-public:
- KFileTreeView( TQWidget *parent, const char *name = 0 );
- virtual ~KFileTreeView();
-
- /**
- * @return the current (i.e. selected) item
- */
- KFileTreeViewItem * currentKFileTreeViewItem() const;
-
- /**
- * @return the URL of the current selected item.
- */
- KURL currentURL() const;
-
- /**
- * Adds a branch to the treeview item.
- *
- * This high-level function creates the branch, adds it to the treeview and
- * connects some signals. Note that directory listing does not start until
- * a branch is expanded either by opening the root item by user or by setOpen
- * on the root item.
- *
- * @returns a pointer to the new branch or zero
- * @param path is the base url of the branch
- * @param name is the name of the branch, which will be the text for column 0
- * @param showHidden says if hidden files and directories should be visible
- */
- KFileTreeBranch* addBranch( const KURL &path, const TQString& name, bool showHidden = false );
-
- /**
- * same as the function above but with a pixmap to set for the branch.
- */
- virtual KFileTreeBranch* addBranch( const KURL &path, const TQString& name ,
- const TQPixmap& pix, bool showHidden = false );
-
- /**
- * same as the function above but letting the user create the branch.
- */
- virtual KFileTreeBranch* addBranch( KFileTreeBranch * );
-
- /**
- * removes the branch from the treeview.
- * @param branch is a pointer to the branch
- * @returns true on success.
- */
- virtual bool removeBranch( KFileTreeBranch *branch );
-
- /**
- * @returns a pointer to the KFileTreeBranch in the KFileTreeView or zero on failure.
- * @param searchName is the name of a branch
- */
- KFileTreeBranch *branch( const TQString& searchName );
-
-
- /**
- * @returns a list of pointers to all existing branches in the treeview.
- **/
- KFileTreeBranchList& branches();
-
- /**
- * set the directory mode for branches. If true is passed, only directories will be loaded.
- * @param branch is a pointer to a KFileTreeBranch
- */
- virtual void setDirOnlyMode( KFileTreeBranch *branch, bool );
-
- /**
- * searches a branch for a KFileTreeViewItem identified by the relative url given as
- * second parameter. The method adds the branches base url to the relative path and finds
- * the item.
- * @returns a pointer to the item or zero if the item does not exist.
- * @param brnch is a pointer to the branch to search in
- * @param relUrl is the branch relativ url
- */
- KFileTreeViewItem *findItem( KFileTreeBranch* brnch, const TQString& relUrl );
-
- /**
- * see method above, differs only in the first parameter. Finds the branch by its name.
- */
- KFileTreeViewItem *findItem( const TQString& branchName, const TQString& relUrl );
-
- /**
- * @returns a flag indicating if extended folder pixmaps are displayed or not.
- */
- bool showFolderOpenPixmap() const { return m_wantOpenFolderPixmaps; };
-
-public slots:
-
- /**
- * set the flag to show 'extended' folder icons on or off. If switched on, folders will
- * have an open folder pixmap displayed if their children are visible, and the standard
- * closed folder pixmap (from mimetype folder) if they are closed.
- * If switched off, the plain mime pixmap is displayed.
- * @param showIt = false displays mime type pixmap only
- */
- virtual void setShowFolderOpenPixmap( bool showIt = true )
- { m_wantOpenFolderPixmaps = showIt; }
-
-protected:
- /**
- * @returns true if we can decode the drag and support the action
- */
-
- virtual bool acceptDrag(TQDropEvent* event) const;
- virtual TQDragObject * dragObject();
-
- virtual void startAnimation( KFileTreeViewItem* item, const char * iconBaseName = "kde", uint iconCount = 6 );
- virtual void stopAnimation( KFileTreeViewItem* item );
- virtual void contentsDragEnterEvent( TQDragEnterEvent *e );
- virtual void contentsDragMoveEvent( TQDragMoveEvent *e );
- virtual void contentsDragLeaveEvent( TQDragLeaveEvent *e );
- virtual void contentsDropEvent( TQDropEvent *ev );
-
-protected slots:
- virtual void slotNewTreeViewItems( KFileTreeBranch*,
- const KFileTreeViewItemList& );
-
- virtual void slotSetNextUrlToSelect( const KURL &url )
- { m_nextUrlToSelect = url; }
-
- virtual TQPixmap itemIcon( KFileTreeViewItem*, int gap = 0 ) const;
-
-private slots:
- void slotExecuted( TQListViewItem * );
- void slotExpanded( TQListViewItem * );
- void slotCollapsed( TQListViewItem *item );
-
- void slotSelectionChanged();
-
- void slotAnimation();
-
- void slotAutoOpenFolder();
-
- void slotOnItem( TQListViewItem * );
- void slotItemRenamed(TQListViewItem*, const TQString &, int);
-
- void slotPopulateFinished( KFileTreeViewItem* );
-
-
-signals:
-
- void onItem( const TQString& );
- /* New signals if you like it ? */
- void dropped( TQWidget*, TQDropEvent* );
- void dropped( TQWidget*, TQDropEvent*, KURL::List& );
- void dropped( KURL::List&, KURL& );
- // The drop event allows to differentiate between move and copy
- void dropped( TQWidget*, TQDropEvent*, KURL::List&, KURL& );
-
- void dropped( TQDropEvent *e, TQListViewItem * after);
- void dropped(KFileTreeView *, TQDropEvent *, TQListViewItem *);
- void dropped(TQDropEvent *e, TQListViewItem * parent, TQListViewItem * after);
- void dropped(KFileTreeView *, TQDropEvent *, TQListViewItem *, TQListViewItem *);
-
-protected:
- KURL m_nextUrlToSelect;
-
-
-private:
- // Returns whether item is still a valid item in the tree
- bool isValidItem( TQListViewItem *item);
- void clearTree();
-
-
- /* List that holds the branches */
- KFileTreeBranchList m_branches;
-
-
- struct AnimationInfo
- {
- AnimationInfo( const char * _iconBaseName, uint _iconCount, const TQPixmap & _originalPixmap )
- : iconBaseName(_iconBaseName), iconCount(_iconCount), iconNumber(1), originalPixmap(_originalPixmap) {}
- AnimationInfo() : iconCount(0) {}
- TQCString iconBaseName;
- uint iconCount;
- uint iconNumber;
- TQPixmap originalPixmap;
- };
- typedef TQMap<KFileTreeViewItem *, AnimationInfo> MapCurrentOpeningFolders;
- MapCurrentOpeningFolders m_mapCurrentOpeningFolders;
-
-
- TQTimer *m_animationTimer;
-
- TQPoint m_dragPos;
- bool m_bDrag;
-
- bool m_wantOpenFolderPixmaps; // Flag weather the folder should have open-folder pixmaps
-
- TQListViewItem *m_currentBeforeDropItem; // The item that was current before the drag-enter event happened
- TQListViewItem *m_dropItem; // The item we are moving the mouse over (during a drag)
- TQStrList m_lstDropFormats;
- TQPixmap m_openFolderPixmap;
- TQTimer *m_autoOpenTimer;
-
- KFileTreeViewToolTip m_toolTip;
-
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KFileTreeViewPrivate;
- KFileTreeViewPrivate *d;
-};
-
-#endif
diff --git a/kio/kfile/kfiletreeviewitem.cpp b/kio/kfile/kfiletreeviewitem.cpp
deleted file mode 100644
index 17e2d9abe..000000000
--- a/kio/kfile/kfiletreeviewitem.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/* This file is part of the KDEproject
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kdebug.h>
-#include <kfileitem.h>
-#include <kicontheme.h>
-
-#include "kfiletreeviewitem.h"
-
-/* --- KFileTreeViewItem --- */
-/*
- */
-KFileTreeViewItem::KFileTreeViewItem( KFileTreeViewItem *parent,
- KFileItem* item,
- KFileTreeBranch *brnch )
- : KListViewItem( parent ),
- m_kfileitem( item ),
- m_branch( brnch ),
- m_wasListed(false)
-{
- setPixmap(0, item->pixmap( KIcon::SizeSmall ));
- setText( 0, item->text());
-
-}
-
-KFileTreeViewItem::KFileTreeViewItem( KFileTreeView* parent,
- KFileItem* item,
- KFileTreeBranch *brnch )
- :KListViewItem( (TQListView*)parent ),
- m_kfileitem(item ),
- m_branch( brnch ),
- m_wasListed(false)
-{
- setPixmap(0, item->pixmap( KIcon::SizeSmall ));
- setText( 0, item->text());
-}
-
-KFileTreeViewItem::~KFileTreeViewItem()
-{
- if ( m_kfileitem )
- m_kfileitem->removeExtraData( m_branch );
-}
-
-bool KFileTreeViewItem::alreadyListed() const
-{
- return m_wasListed;
-}
-
-void KFileTreeViewItem::setListed( bool wasListed )
-{
- m_wasListed = wasListed;
-}
-
-KURL KFileTreeViewItem::url() const
-{
- return m_kfileitem ? m_kfileitem->url() : KURL();
-}
-
-TQString KFileTreeViewItem::path() const
-{
- return m_kfileitem ? m_kfileitem->url().path() : TQString::null;
-}
-
-bool KFileTreeViewItem::isDir() const
-{
- return m_kfileitem ? m_kfileitem->isDir() : false;
-}
diff --git a/kio/kfile/kfiletreeviewitem.h b/kio/kfile/kfiletreeviewitem.h
deleted file mode 100644
index 0fefc5dc1..000000000
--- a/kio/kfile/kfiletreeviewitem.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef kfile_tree_view_item_h
-#define kfile_tree_view_item_h
-
-#include <tqptrlist.h>
-#include <klistview.h>
-
-#include <kfileitem.h>
-#include <kio/global.h>
-#include <kdirlister.h>
-#include <kio/job.h>
-
-class KURL;
-class KFileTreeView;
-class KFileTreeBranch;
-class KFileTreeItem;
-
-
-/**
- * An item for a KFileTreeView that knows about its own KFileItem.
- */
-class TDEIO_EXPORT KFileTreeViewItem : public KListViewItem
-{
-public:
- KFileTreeViewItem( KFileTreeViewItem*, KFileItem*, KFileTreeBranch * );
- KFileTreeViewItem( KFileTreeView*, KFileItem*, KFileTreeBranch * );
- ~KFileTreeViewItem();
-
- /**
- * @return the KFileTreeBranch the item is sorted in.
- */
- KFileTreeBranch* branch() const { return m_branch; }
-
- /**
- * @return the KFileItem the viewitem is representing.
- */
- KFileItem *fileItem() const { return m_kfileitem; }
-
- /**
- * @return the path of the item.
- */
- TQString path() const;
-
- /**
- * @return the items KURL
- */
- KURL url() const;
-
- /**
- * @return if the item represents a directory
- */
- bool isDir() const;
-
- /**
- * @return if this directory was already seen by a KDirLister.
- */
- bool alreadyListed() const;
-
- /**
- * set the flag if the directory was already listed.
- */
- void setListed( bool wasListed );
-
-protected:
-
-private:
-
- KFileItem *m_kfileitem;
- KFileTreeBranch *m_branch;
- bool m_wasListed;
- class KFileTreeViewItemPrivate;
- KFileTreeViewItemPrivate *d;
-};
-
-
-/**
- * List of KFileTreeViewItems
- */
-typedef TQPtrList<KFileTreeViewItem> KFileTreeViewItemList;
-
-/**
- * Iterator for KFileTreeViewItemList
- */
-typedef TQPtrListIterator<KFileTreeViewItem> KFileTreeViewItemListIterator;
-
-
-#endif
-
diff --git a/kio/kfile/kfileview.cpp b/kio/kfile/kfileview.cpp
deleted file mode 100644
index a62b8aa50..000000000
--- a/kio/kfile/kfileview.cpp
+++ /dev/null
@@ -1,429 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
- 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
- 2001 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <assert.h>
-#include <stdlib.h>
-
-#include <kaction.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kstandarddirs.h>
-
-#include "config-kfile.h"
-#include "kfileview.h"
-
-#ifdef Unsorted // the "I hate X.h" modus
-#undef Unsorted
-#endif
-
-TQDir::SortSpec KFileView::defaultSortSpec = static_cast<TQDir::SortSpec>(TQDir::Name | TQDir::IgnoreCase | TQDir::DirsFirst);
-
-class KFileView::KFileViewPrivate
-{
-public:
- KFileViewPrivate()
- {
- actions = 0;
- dropOptions = 0;
- }
-
- ~KFileViewPrivate()
- {
- if( actions ) {
- actions->clear(); // so that the removed() signal is emitted!
- delete actions;
- }
- }
-
- TQGuardedPtr<KActionCollection> actions;
- int dropOptions;
-};
-
-
-KFileView::KFileView()
-{
- d = new KFileViewPrivate();
- m_sorting = KFileView::defaultSortSpec;
-
- sig = new KFileViewSignaler();
- sig->setName("view-signaller");
-
- m_selectedList = 0L;
- filesNumber = 0;
- dirsNumber = 0;
-
- view_mode = All;
- selection_mode = KFile::Single;
- m_viewName = i18n("Unknown View");
-
- myOnlyDoubleClickSelectsFiles = false;
- m_itemList.setAutoDelete( false ); // just references
-}
-
-KFileView::~KFileView()
-{
- delete d;
- delete sig;
- delete m_selectedList;
-}
-
-void KFileView::setParentView(KFileView *parent)
-{
- if ( parent ) { // pass all signals right to our parent
- TQObject::connect(sig, TQT_SIGNAL( activatedMenu(const KFileItem *,
- const TQPoint& ) ),
- parent->sig, TQT_SIGNAL( activatedMenu(const KFileItem *,
- const TQPoint& )));
- TQObject::connect(sig, TQT_SIGNAL( dirActivated(const KFileItem *)),
- parent->sig, TQT_SIGNAL( dirActivated(const KFileItem*)));
- TQObject::connect(sig, TQT_SIGNAL( fileSelected(const KFileItem *)),
- parent->sig, TQT_SIGNAL( fileSelected(const KFileItem*)));
- TQObject::connect(sig, TQT_SIGNAL( fileHighlighted(const KFileItem *) ),
- parent->sig,TQT_SIGNAL(fileHighlighted(const KFileItem*)));
- TQObject::connect(sig, TQT_SIGNAL( sortingChanged( TQDir::SortSpec ) ),
- parent->sig, TQT_SIGNAL(sortingChanged( TQDir::SortSpec)));
- TQObject::connect(sig, TQT_SIGNAL( dropped(const KFileItem *, TQDropEvent*, const KURL::List&) ),
- parent->sig, TQT_SIGNAL(dropped(const KFileItem *, TQDropEvent*, const KURL::List&)));
- }
-}
-
-bool KFileView::updateNumbers(const KFileItem *i)
-{
- if (!( viewMode() & Files ) && i->isFile())
- return false;
-
- if (!( viewMode() & Directories ) && i->isDir())
- return false;
-
- if (i->isDir())
- dirsNumber++;
- else
- filesNumber++;
-
- return true;
-}
-
-void qt_qstring_stats();
-
-// filter out files if we're in directory mode and count files/directories
-// and insert into the view
-void KFileView::addItemList(const KFileItemList& list)
-{
- KFileItem *tmp;
-
- for (KFileItemListIterator it(list); (tmp = it.current()); ++it)
- {
- if (!updateNumbers(tmp))
- continue;
-
- insertItem( tmp );
- }
-
-#ifdef Q2HELPER
- qt_qstring_stats();
-#endif
-}
-
-void KFileView::insertItem( KFileItem * )
-{
-}
-
-void KFileView::setSorting(TQDir::SortSpec new_sort)
-{
- m_sorting = new_sort;
-}
-
-void KFileView::clear()
-{
- m_itemList.clear();
- filesNumber = 0;
- dirsNumber = 0;
- clearView();
-}
-
-void KFileView::sortReversed()
-{
- int spec = sorting();
-
- setSorting( static_cast<TQDir::SortSpec>( spec ^ TQDir::Reversed ) );
-}
-
-#if 0
-int KFileView::compareItems(const KFileItem *fi1, const KFileItem *fi2) const
-{
- static const TQString &dirup = TDEGlobal::staticQString("..");
- bool bigger = true;
- bool keepFirst = false;
- bool dirsFirst = ((m_sorting & TQDir::DirsFirst) == TQDir::DirsFirst);
-
- if (fi1 == fi2)
- return 0;
-
- // .. is always bigger, independent of the sort criteria
- if ( fi1->name() == dirup ) {
- bigger = false;
- keepFirst = dirsFirst;
- }
- else if ( fi2->name() == dirup ) {
- bigger = true;
- keepFirst = dirsFirst;
- }
-
- else {
- if ( fi1->isDir() != fi2->isDir() && dirsFirst ) {
- bigger = fi2->isDir();
- keepFirst = true;
- }
- else {
-
- TQDir::SortSpec sort = static_cast<TQDir::SortSpec>(m_sorting & TQDir::SortByMask);
-
- //if (fi1->isDir() || fi2->isDir())
- // sort = static_cast<TQDir::SortSpec>(KFileView::defaultSortSpec & TQDir::SortByMask);
-
- switch (sort) {
- case TQDir::Name:
- default:
-sort_by_name:
- if ( (m_sorting & TQDir::IgnoreCase) == TQDir::IgnoreCase )
- bigger = (fi1->name( true ) > fi2->name( true ));
- else
- bigger = (fi1->name() > fi2->name());
- break;
- case TQDir::Time:
- {
- time_t t1 = fi1->time( TDEIO::UDS_MODIFICATION_TIME );
- time_t t2 = fi2->time( TDEIO::UDS_MODIFICATION_TIME );
- if ( t1 != t2 ) {
- bigger = (t1 > t2);
- break;
- }
-
- // Sort by name if both items have the same timestamp.
- // Don't honor the reverse flag tho.
- else {
- keepFirst = true;
- goto sort_by_name;
- }
- }
- case TQDir::Size:
- {
- TDEIO::filesize_t s1 = fi1->size();
- TDEIO::filesize_t s2 = fi2->size();
- if ( s1 != s2 ) {
- bigger = (s1 > s2);
- break;
- }
-
- // Sort by name if both items have the same size.
- // Don't honor the reverse flag tho.
- else {
- keepFirst = true;
- goto sort_by_name;
- }
- }
- case TQDir::Unsorted:
- bigger = true; // nothing
- break;
- }
- }
- }
-
- if (reversed && !keepFirst ) // don't reverse dirs to the end!
- bigger = !bigger;
-
- return (bigger ? 1 : -1);
-}
-#endif
-
-void KFileView::updateView(bool f)
-{
- widget()->repaint(f);
-}
-
-void KFileView::updateView(const KFileItem *)
-{
-}
-
-void KFileView::setCurrentItem(const TQString &filename )
-{
- if (!filename.isNull()) {
- KFileItem *item;
- for ( (item = firstFileItem()); item; item = nextItem( item ) ) {
- if (item->name() == filename) {
- setCurrentItem( item );
- return;
- }
- }
- }
-
- kdDebug(kfile_area) << "setCurrentItem: no match found: " << filename << endl;
-}
-
-const KFileItemList * KFileView::items() const
-{
- KFileItem *item = 0L;
-
- // only ever use m_itemList in this method!
- m_itemList.clear();
- for ( (item = firstFileItem()); item; item = nextItem( item ) )
- m_itemList.append( item );
-
- return &m_itemList;
-}
-
-
-const KFileItemList * KFileView::selectedItems() const
-{
- if ( !m_selectedList )
- m_selectedList = new KFileItemList;
-
- m_selectedList->clear();
-
- KFileItem *item;
- for ( (item = firstFileItem()); item; item = nextItem( item ) ) {
- if ( isSelected( item ) )
- m_selectedList->append( item );
- }
-
- return m_selectedList;
-}
-
-void KFileView::selectAll()
-{
- if (selection_mode == KFile::NoSelection || selection_mode== KFile::Single)
- return;
-
- KFileItem *item = 0L;
- for ( (item = firstFileItem()); item; item = nextItem( item ) )
- setSelected( item, true );
-}
-
-
-void KFileView::invertSelection()
-{
- KFileItem *item = 0L;
- for ( (item = firstFileItem()); item; item = nextItem( item ) )
- setSelected( item, !isSelected( item ) );
-}
-
-
-void KFileView::setSelectionMode( KFile::SelectionMode sm )
-{
- selection_mode = sm;
-}
-
-KFile::SelectionMode KFileView::selectionMode() const
-{
- return selection_mode;
-}
-
-void KFileView::setViewMode( ViewMode vm )
-{
- view_mode = vm;
-}
-
-void KFileView::removeItem( const KFileItem *item )
-{
- if ( !item )
- return;
-
- if ( item->isDir() )
- dirsNumber--;
- else
- filesNumber--;
-
- if ( m_selectedList )
- m_selectedList->removeRef( item );
-}
-
-void KFileView::listingCompleted()
-{
- // empty default impl.
-}
-
-KActionCollection * KFileView::actionCollection() const
-{
- if ( !d->actions )
- d->actions = new KActionCollection( widget(), "KFileView::d->actions" );
- return d->actions;
-}
-
-void KFileView::readConfig( TDEConfig *, const TQString& )
-{
-}
-
-void KFileView::writeConfig( TDEConfig *, const TQString& )
-{
-}
-
-TQString KFileView::sortingKey( const TQString& value, bool isDir, int sortSpec )
-{
- bool reverse = sortSpec & TQDir::Reversed;
- bool dirsFirst = sortSpec & TQDir::DirsFirst;
- char start = (isDir && dirsFirst) ? (reverse ? '2' : '0') : '1';
- TQString result = (sortSpec & TQDir::IgnoreCase) ? value.lower() : value;
- return result.prepend( start );
-}
-
-TQString KFileView::sortingKey( TDEIO::filesize_t value, bool isDir, int sortSpec)
-{
- bool reverse = sortSpec & TQDir::Reversed;
- bool dirsFirst = sortSpec & TQDir::DirsFirst;
- char start = (isDir && dirsFirst) ? (reverse ? '2' : '0') : '1';
- return TDEIO::number( value ).rightJustify( 24, '0' ).prepend( start );
-}
-
-void KFileView::setDropOptions(int options)
-{
- virtual_hook(VIRTUAL_SET_DROP_OPTIONS, &options); // Virtual call
-}
-
-void KFileView::setDropOptions_impl(int options)
-{
- d->dropOptions = options;
-}
-
-int KFileView::dropOptions()
-{
- return d->dropOptions;
-}
-
-int KFileView::autoOpenDelay()
-{
- return (TQApplication::startDragTime() * 3) / 2;
-}
-
-void KFileView::virtual_hook( int id, void* data)
-{
- switch(id) {
- case VIRTUAL_SET_DROP_OPTIONS:
- setDropOptions_impl(*(int *)data);
- break;
- default:
- /*BASE::virtual_hook( id, data );*/
- break;
- }
-}
-
-#include "kfileview.moc"
diff --git a/kio/kfile/kfileview.h b/kio/kfile/kfileview.h
deleted file mode 100644
index 7e88fc9d8..000000000
--- a/kio/kfile/kfileview.h
+++ /dev/null
@@ -1,444 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
- Copyright (C) 2001 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef KFILEVIEW_H
-#define KFILEVIEW_H
-
-class TQPoint;
-class KActionCollection;
-
-#include <tqwidget.h>
-
-#include "kfileitem.h"
-#include "kfile.h"
-
-/**
- * internal class to make easier to use signals possible
- * @internal
- **/
-class TDEIO_EXPORT KFileViewSignaler : public TQObject
-{
- Q_OBJECT
-
-public:
- /**
- * Call this method when an item is selected (depends on single click /
- * double click configuration). Emits the appropriate signal.
- **/
- void activate( const KFileItem *item ) {
- if ( item->isDir() )
- emit dirActivated( item );
- else
- emit fileSelected( item );
- }
- /**
- * emits the highlighted signal for item. Call this in your view class
- * whenever the selection changes.
- */
- void highlightFile(const KFileItem *i) { emit fileHighlighted(i); }
-
- void activateMenu( const KFileItem *i, const TQPoint& pos ) {
- emit activatedMenu( i, pos );
- }
-
- void changeSorting( TQDir::SortSpec sorting ) {
- emit sortingChanged( sorting );
- }
-
- void dropURLs(const KFileItem *i, TQDropEvent*e, const KURL::List&urls) {
- emit dropped(i, e, urls);
- }
-
-signals:
- void dirActivated(const KFileItem*);
-
- void sortingChanged( TQDir::SortSpec );
-
- /**
- * the item maybe be 0L, indicating that we're in multiselection mode and
- * the selection has changed.
- */
- void fileHighlighted(const KFileItem*);
- void fileSelected(const KFileItem*);
- void activatedMenu( const KFileItem *i, const TQPoint& );
- void dropped(const KFileItem *, TQDropEvent*, const KURL::List&);
-};
-
-/**
- * This class defines an interface to all file views. Its intent is
- * to allow to switch the view of the files in the selector very easily.
- * It defines some pure virtual functions, that must be implemented to
- * make a file view working.
- *
- * Since this class is not a widget, but it's meant to be added to other
- * widgets, its most important function is widget. This should return
- * a pointer to the implemented widget.
- *
- * @short A base class for views of the KDE file selector
- * @author Stephan Kulow <coolo@kde.org>
- **/
-class TDEIO_EXPORT KFileView {
-
-public:
- KFileView();
-
- /**
- * Destructor
- */
- virtual ~KFileView();
-
- /**
- * inserts a list of items.
- **/
- void addItemList(const KFileItemList &list);
-
- /**
- * a pure virtual function to get a TQWidget, that can be added to
- * other widgets. This function is needed to make it possible for
- * derived classes to derive from other widgets.
- **/
- virtual TQWidget *widget() = 0;
-
- /**
- * ### As const-method, to be fixed in 3.0
- */
- TQWidget *widget() const { return const_cast<KFileView*>(this)->widget(); }
-
- /**
- * Sets @p filename the current item in the view, if available.
- */
- void setCurrentItem( const TQString &filename );
-
- /**
- * Reimplement this to set @p item the current item in the view, e.g.
- * the item having focus.
- */
- virtual void setCurrentItem( const KFileItem *item ) = 0;
-
- /**
- * @returns the "current" KFileItem, e.g. where the cursor is.
- * Returns 0L when there is no current item (e.g. in an empty view).
- * Subclasses have to implement this.
- */
- virtual KFileItem *currentFileItem() const = 0;
-
- /**
- * Clears the view and all item lists.
- */
- virtual void clear();
-
- /**
- * does a repaint of the view.
- *
- * The default implementation calls
- * \code
- * widget()->repaint(f)
- * \endcode
- **/
- virtual void updateView(bool f = true);
-
- virtual void updateView(const KFileItem*);
-
- /**
- * Removes an item from the list; has to be implemented by the view.
- * Call KFileView::removeItem( item ) after removing it.
- */
- virtual void removeItem(const KFileItem *item);
-
- /**
- * This hook is called when all items of the currently listed directory
- * are listed and inserted into the view, i.e. there won't come any new
- * items anymore.
- */
- virtual void listingCompleted();
-
- /**
- * Returns the sorting order of the internal list. Newly added files
- * are added through this sorting.
- */
- TQDir::SortSpec sorting() const { return m_sorting; }
-
- /**
- * Sets the sorting order of the view.
- *
- * Default is TQDir::Name | TQDir::IgnoreCase | TQDir::DirsFirst
- * Override this in your subclass and sort accordingly (usually by
- * setting the sorting-key for every item and telling QIconView
- * or TQListView to sort.
- *
- * A view may choose to use a different sorting than TQDir::Name, Time
- * or Size. E.g. to sort by mimetype or any possible string. Set the
- * sorting to TQDir::Unsorted for that and do the rest internally.
- *
- * @see sortingKey
- */
- virtual void setSorting(TQDir::SortSpec sort);
-
- /**
- * Tells whether the current items are in reversed order (shortcut to
- * sorting() & TQDir::Reversed).
- */
- bool isReversed() const { return (m_sorting & TQDir::Reversed); }
-
- void sortReversed();
-
- /**
- * @returns the number of dirs and files
- **/
- uint count() const { return filesNumber + dirsNumber; }
-
- /**
- * @returns the number of files.
- **/
- uint numFiles() const { return filesNumber; }
-
- /**
- * @returns the number of directories
- **/
- uint numDirs() const { return dirsNumber; }
-
- virtual void setSelectionMode( KFile::SelectionMode sm );
- virtual KFile::SelectionMode selectionMode() const;
-
- enum ViewMode {
- Files = 1,
- Directories = 2,
- All = Files | Directories
- };
- virtual void setViewMode( ViewMode vm );
- virtual ViewMode viewMode() const { return view_mode; }
-
- /**
- * @returns the localized name of the view, which could be displayed
- * somewhere, e.g. in a menu, where the user can choose between views.
- * @see setViewName
- */
- TQString viewName() const { return m_viewName; }
-
- /**
- * Sets the name of the view, which could be displayed somewhere.
- * E.g. "Image Preview".
- */
- void setViewName( const TQString& name ) { m_viewName = name; }
-
- virtual void setParentView(KFileView *parent);
-
- /**
- * The derived view must implement this function to add
- * the file in the widget.
- *
- * Make sure to call this implementation, i.e.
- * KFileView::insertItem( i );
- *
- */
- virtual void insertItem( KFileItem *i);
-
- /**
- * pure virtual function, that should be implemented to clear
- * the view. At this moment the list is already empty
- **/
- virtual void clearView() = 0;
-
- /**
- * pure virtual function, that should be implemented to make item i
- * visible, i.e. by scrolling the view appropriately.
- */
- virtual void ensureItemVisible( const KFileItem *i ) = 0;
-
- /**
- * Clears any selection, unhighlights everything. Must be implemented by
- * the view.
- */
- virtual void clearSelection() = 0;
-
- /**
- * Selects all items. You may want to override this, if you can implement
- * it more efficiently than calling setSelected() with every item.
- * This works only in Multiselection mode of course.
- */
- virtual void selectAll();
-
- /**
- * Inverts the current selection, i.e. selects all items, that were up to
- * now not selected and deselects the other.
- */
- virtual void invertSelection();
-
- /**
- * Tells the view that it should highlight the item.
- * This function must be implemented by the view.
- **/
- virtual void setSelected(const KFileItem *, bool enable) = 0;
-
- /**
- * @returns whether the given item is currently selected.
- * Must be implemented by the view.
- */
- virtual bool isSelected( const KFileItem * ) const = 0;
-
- /**
- * @returns all currently highlighted items.
- */
- const KFileItemList * selectedItems() const;
-
- /**
- * @returns all items currently available in the current sort-order
- */
- const KFileItemList * items() const;
-
- virtual KFileItem * firstFileItem() const = 0;
- virtual KFileItem * nextItem( const KFileItem * ) const = 0;
- virtual KFileItem * prevItem( const KFileItem * ) const = 0;
-
- /**
- * This is a KFileDialog specific hack: we want to select directories with
- * single click, but not files. But as a generic class, we have to be able
- * to select files on single click as well.
- *
- * This gives us the opportunity to do both.
- *
- * Every view has to decide when to call select( item ) when a file was
- * single-clicked, based on onlyDoubleClickSelectsFiles().
- */
- void setOnlyDoubleClickSelectsFiles( bool enable ) {
- myOnlyDoubleClickSelectsFiles = enable;
- }
-
- /**
- * @returns whether files (not directories) should only be select()ed by
- * double-clicks.
- * @see setOnlyDoubleClickSelectsFiles
- */
- bool onlyDoubleClickSelectsFiles() const {
- return myOnlyDoubleClickSelectsFiles;
- }
-
- /**
- * increases the number of dirs and files.
- * @returns true if the item fits the view mode
- */
- bool updateNumbers(const KFileItem *i);
-
- /**
- * @returns the view-specific action-collection. Every view should
- * add its actions here (if it has any) to make them available to
- * e.g. the KDirOperator's popup-menu.
- */
- virtual KActionCollection * actionCollection() const;
-
- KFileViewSignaler * signaler() const { return sig; }
-
- virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
- virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
-
- /**
- * Various options for drag and drop support.
- * These values can be or'd together.
- * @li @p AutoOpenDirs Automatically open directory after hovering above it
- * for a short while while dragging.
- * @since 3.2
- */
- enum DropOptions {
- AutoOpenDirs = 1
- };
- /**
- * Specify DND options. See DropOptions for details.
- * All options are disabled by default.
- * @since 3.2
- */
- // KDE 4: Make virtual
- void setDropOptions(int options);
-
- /**
- * Returns the DND options in effect.
- * See DropOptions for details.
- * @since 3.2
- */
- int dropOptions();
-
- /**
- * This method calculates a TQString from the given parameters, that is
- * suitable for sorting with e.g. TQIconView or TQListView. Their
- * Item-classes usually have a setKey( const TQString& ) method or a virtual
- * method TQString key() that is used for sorting.
- *
- * @param value Any string that should be used as sort criterion
- * @param isDir Tells whether the key is computed for an item representing
- * a directory (directories are usually sorted before files)
- * @param sortSpec An ORed combination of TQDir::SortSpec flags.
- * Currently, the values IgnoreCase, Reversed and
- * DirsFirst are taken into account.
- */
- static TQString sortingKey( const TQString& value, bool isDir, int sortSpec);
-
- /**
- * An overloaded method that takes not a TQString, but a number as sort
- * criterion. You can use this for file-sizes or dates/times for example.
- * If you use a time_t, you need to cast that to TDEIO::filesize_t because
- * of ambiguity problems.
- */
- static TQString sortingKey( TDEIO::filesize_t value, bool isDir,int sortSpec);
-
- /**
- * @internal
- * delay before auto opening a directory
- */
- static int autoOpenDelay();
-
-protected:
- /**
- * @internal
- * class to distribute the signals
- **/
- KFileViewSignaler *sig;
-
-private:
- static TQDir::SortSpec defaultSortSpec;
- TQDir::SortSpec m_sorting;
- TQString m_viewName;
-
- /**
- * counters
- **/
- uint filesNumber;
- uint dirsNumber;
-
- ViewMode view_mode;
- KFile::SelectionMode selection_mode;
-
- // never use! It's only guaranteed to contain valid items in the items()
- // method!
- mutable KFileItemList m_itemList;
-
- mutable KFileItemList *m_selectedList;
- bool myOnlyDoubleClickSelectsFiles;
-
-protected:
- virtual void virtual_hook( int id, void* data );
- /* @internal for virtual_hook */
- enum { VIRTUAL_SET_DROP_OPTIONS = 1 };
- void setDropOptions_impl(int options);
-private:
- class KFileViewPrivate;
- KFileViewPrivate *d;
-};
-
-#endif // KFILEINFOLISTWIDGET_H
diff --git a/kio/kfile/kicondialog.cpp b/kio/kfile/kicondialog.cpp
deleted file mode 100644
index dfbf47d0d..000000000
--- a/kio/kfile/kicondialog.cpp
+++ /dev/null
@@ -1,772 +0,0 @@
-/* vi: ts=8 sts=4 sw=4
- *
- * This file is part of the KDE project, module kfile.
- * Copyright (C) 2000 Geert Jansen <jansen@kde.org>
- * (C) 2000 Kurt Granroth <granroth@kde.org>
- * (C) 1997 Christoph Neerfeld <chris@kde.org>
- * (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
- *
- * This is free software; it comes under the GNU Library General
- * Public License, version 2. See the file "COPYING.LIB" for the
- * exact licensing terms.
- */
-
-#include "kicondialog.h"
-
-#include <config.h>
-
-#include <assert.h>
-
-#include <kiconviewsearchline.h>
-
-#include <kapplication.h>
-#include <klocale.h>
-#include <kglobal.h>
-#include <kstandarddirs.h>
-#include <kiconloader.h>
-#include <kprogress.h>
-#include <kiconview.h>
-#include <kfiledialog.h>
-#include <kimagefilepreview.h>
-
-#include <tqlayout.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqsortedlist.h>
-#include <tqimage.h>
-#include <tqpixmap.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-#include <tqtimer.h>
-#include <tqbuttongroup.h>
-#include <tqradiobutton.h>
-#include <tqfileinfo.h>
-#include <tqtoolbutton.h>
-#include <tqwhatsthis.h>
-
-#ifdef HAVE_LIBART
-#include <svgicons/ksvgiconengine.h>
-#include <svgicons/ksvgiconpainter.h>
-#endif
-
-class KIconCanvas::KIconCanvasPrivate
-{
- public:
- KIconCanvasPrivate() { m_bLoading = false; }
- ~KIconCanvasPrivate() {}
- bool m_bLoading;
-};
-
-/**
- * Helper class for sorting icon paths by icon name
- */
-class IconPath : public TQString
-{
-protected:
- TQString m_iconName;
-
-public:
- IconPath(const TQString &ip) : TQString (ip)
- {
- int n = findRev('/');
- m_iconName = (n==-1) ? static_cast<TQString>(*this) : mid(n+1);
- }
-
-
- IconPath() : TQString ()
- { }
-
- bool operator== (const IconPath &ip) const
- { return m_iconName == ip.m_iconName; }
-
- bool operator< (const IconPath &ip) const
- { return m_iconName < ip.m_iconName; }
-
-};
-
-/*
- * KIconCanvas: Iconview for the iconloader dialog.
- */
-
-KIconCanvas::KIconCanvas(TQWidget *parent, const char *name)
- : KIconView(parent, name)
-{
- d = new KIconCanvasPrivate;
- mpTimer = new TQTimer(this);
- connect(mpTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotLoadFiles()));
- connect(this, TQT_SIGNAL(currentChanged(TQIconViewItem *)),
- TQT_SLOT(slotCurrentChanged(TQIconViewItem *)));
- setGridX(80);
- setWordWrapIconText(false);
- setShowToolTips(true);
-}
-
-KIconCanvas::~KIconCanvas()
-{
- delete mpTimer;
- delete d;
-}
-
-void KIconCanvas::loadFiles(const TQStringList& files)
-{
- clear();
- mFiles = files;
- emit startLoading(mFiles.count());
- mpTimer->start(10, true); // #86680
- d->m_bLoading = false;
-}
-
-void KIconCanvas::slotLoadFiles()
-{
- setResizeMode(Fixed);
- TQApplication::setOverrideCursor(tqwaitCursor);
-
- // disable updates to not trigger paint events when adding child items
- setUpdatesEnabled( false );
-
-#ifdef HAVE_LIBART
- KSVGIconEngine *svgEngine = new KSVGIconEngine();
-#endif
-
- d->m_bLoading = true;
- int i;
- TQStringList::ConstIterator it;
- uint emitProgress = 10; // so we will emit it once in the beginning
- TQStringList::ConstIterator end(mFiles.end());
- for (it=mFiles.begin(), i=0; it!=end; ++it, i++)
- {
- // Calling kapp->processEvents() makes the iconview flicker like hell
- // (it's being repainted once for every new item), so we don't do this.
- // Instead, we directly repaint the progress bar without going through
- // the event-loop. We do that just once for every 10th item so that
- // the progress bar doesn't flicker in turn. (pfeiffer)
- if ( emitProgress >= 10 ) {
- emit progress(i);
- emitProgress = 0;
- }
-
- emitProgress++;
-// kapp->processEvents();
- if ( !d->m_bLoading ) // user clicked on a button that will load another set of icons
- break;
- TQImage img;
-
- // Use the extension as the format. Works for XPM and PNG, but not for SVG
- TQString path= *it;
- TQString ext = path.right(3).upper();
-
- if (ext != "SVG" && ext != "VGZ")
- img.load(*it);
-#ifdef HAVE_LIBART
- else
- if (svgEngine->load(60, 60, *it))
- img = *svgEngine->painter()->image();
-#endif
-
- if (img.isNull())
- continue;
- if (img.width() > 60 || img.height() > 60)
- {
- if (img.width() > img.height())
- {
- int height = (int) ((60.0 / img.width()) * img.height());
- img = img.smoothScale(60, height);
- } else
- {
- int width = (int) ((60.0 / img.height()) * img.width());
- img = img.smoothScale(width, 60);
- }
- }
- TQPixmap pm;
- pm.convertFromImage(img);
- TQFileInfo fi(*it);
- TQIconViewItem *item = new TQIconViewItem(this, fi.baseName(), pm);
- item->setKey(*it);
- item->setDragEnabled(false);
- item->setDropEnabled(false);
- }
-
-#ifdef HAVE_LIBART
- delete svgEngine;
-#endif
-
- // enable updates since we have to draw the whole view now
- setUpdatesEnabled( true );
-
- TQApplication::restoreOverrideCursor();
- d->m_bLoading = false;
- emit finished();
- setResizeMode(Adjust);
-}
-
-TQString KIconCanvas::getCurrent() const
-{
- if (!currentItem())
- return TQString::null;
- return currentItem()->key();
-}
-
-void KIconCanvas::stopLoading()
-{
- d->m_bLoading = false;
-}
-
-void KIconCanvas::slotCurrentChanged(TQIconViewItem *item)
-{
- emit nameChanged((item != 0L) ? item->text() : TQString::null);
-}
-
-class KIconDialog::KIconDialogPrivate
-{
- public:
- KIconDialogPrivate() {
- m_bStrictIconSize = true;
- m_bLockUser = false;
- m_bLockCustomDir = false;
- searchLine = 0;
- }
- ~KIconDialogPrivate() {}
- bool m_bStrictIconSize, m_bLockUser, m_bLockCustomDir;
- TQString custom;
- TQString customLocation;
- KIconViewSearchLine *searchLine;
-};
-
-/*
- * KIconDialog: Dialog for selecting icons. Both system and user
- * specified icons can be chosen.
- */
-
-KIconDialog::KIconDialog(TQWidget *parent, const char *name)
- : KDialogBase(parent, name, true, i18n("Select Icon"), Ok|Cancel, Ok)
-{
- d = new KIconDialogPrivate;
- mpLoader = TDEGlobal::iconLoader();
- init();
-}
-
-KIconDialog::KIconDialog(KIconLoader *loader, TQWidget *parent,
- const char *name)
- : KDialogBase(parent, name, true, i18n("Select Icon"), Ok|Cancel, Ok)
-{
- d = new KIconDialogPrivate;
- mpLoader = loader;
- init();
-}
-
-void KIconDialog::init()
-{
- mGroupOrSize = KIcon::Desktop;
- mContext = KIcon::Any;
- mType = 0;
- mFileList = TDEGlobal::dirs()->findAllResources("appicon", TQString::fromLatin1("*.png"));
-
- TQWidget *main = new TQWidget( this );
- setMainWidget(main);
-
- TQVBoxLayout *top = new TQVBoxLayout(main);
- top->setSpacing( spacingHint() );
-
- TQButtonGroup *bgroup = new TQButtonGroup(0, Qt::Vertical, i18n("Icon Source"), main);
- bgroup->layout()->setSpacing(KDialog::spacingHint());
- bgroup->layout()->setMargin(KDialog::marginHint());
- top->addWidget(bgroup);
- connect(bgroup, TQT_SIGNAL(clicked(int)), TQT_SLOT(slotButtonClicked(int)));
- TQGridLayout *grid = new TQGridLayout(bgroup->layout(), 3, 2);
- mpRb1 = new TQRadioButton(i18n("S&ystem icons:"), bgroup);
- grid->addWidget(mpRb1, 1, 0);
- mpCombo = new TQComboBox(bgroup);
- connect(mpCombo, TQT_SIGNAL(activated(int)), TQT_SLOT(slotContext(int)));
- grid->addWidget(mpCombo, 1, 1);
- mpRb2 = new TQRadioButton(i18n("O&ther icons:"), bgroup);
- grid->addWidget(mpRb2, 2, 0);
- mpBrowseBut = new TQPushButton(i18n("&Browse..."), bgroup);
- grid->addWidget(mpBrowseBut, 2, 1);
-
- //
- // ADD SEARCHLINE
- //
- TQHBoxLayout *searchLayout = new TQHBoxLayout(0, 0, KDialog::spacingHint());
- top->addLayout(searchLayout);
-
- TQToolButton *clearSearch = new TQToolButton(main);
- clearSearch->setTextLabel(i18n("Clear Search"), true);
- clearSearch->setIconSet(SmallIconSet(TQApplication::reverseLayout() ? "clear_left" :"locationbar_erase"));
- searchLayout->addWidget(clearSearch);
-
- TQLabel *searchLabel = new TQLabel(i18n("&Search:"), main);
- searchLayout->addWidget(searchLabel);
-
- d->searchLine = new KIconViewSearchLine(main, "searchLine");
- searchLayout->addWidget(d->searchLine);
- searchLabel->setBuddy(d->searchLine);
-
-
- // signals and slots connections
- connect(clearSearch, TQT_SIGNAL(clicked()), d->searchLine, TQT_SLOT(clear()));
-
- TQString wtstr = i18n("Search interactively for icon names (e.g. folder).");
- TQWhatsThis::add(searchLabel, wtstr);
- TQWhatsThis::add(d->searchLine, wtstr);
-
-
- mpCanvas = new KIconCanvas(main);
- connect(mpCanvas, TQT_SIGNAL(executed(TQIconViewItem *)), TQT_SLOT(slotAcceptIcons()));
- connect(mpCanvas, TQT_SIGNAL(returnPressed(TQIconViewItem *)), TQT_SLOT(slotAcceptIcons()));
- mpCanvas->setMinimumSize(400, 125);
- top->addWidget(mpCanvas);
- d->searchLine->setIconView(mpCanvas);
-
- mpProgress = new KProgress(main);
- top->addWidget(mpProgress);
- connect(mpCanvas, TQT_SIGNAL(startLoading(int)), TQT_SLOT(slotStartLoading(int)));
- connect(mpCanvas, TQT_SIGNAL(progress(int)), TQT_SLOT(slotProgress(int)));
- connect(mpCanvas, TQT_SIGNAL(finished()), TQT_SLOT(slotFinished()));
-
- // When pressing Ok or Cancel, stop loading icons
- connect(this, TQT_SIGNAL(hidden()), mpCanvas, TQT_SLOT(stopLoading()));
-
- static const char* const context_text[] = {
- I18N_NOOP( "Actions" ),
- I18N_NOOP( "Animations" ),
- I18N_NOOP( "Applications" ),
- I18N_NOOP( "Categories" ),
- I18N_NOOP( "Devices" ),
- I18N_NOOP( "Emblems" ),
- I18N_NOOP( "Emotes" ),
- I18N_NOOP( "Filesystems" ),
- I18N_NOOP( "International" ),
- I18N_NOOP( "Mimetypes" ),
- I18N_NOOP( "Places" ),
- I18N_NOOP( "Status" ) };
- static const KIcon::Context context_id[] = {
- KIcon::Action,
- KIcon::Animation,
- KIcon::Application,
- KIcon::Category,
- KIcon::Device,
- KIcon::Emblem,
- KIcon::Emote,
- KIcon::FileSystem,
- KIcon::International,
- KIcon::MimeType,
- KIcon::Place,
- KIcon::StatusIcon };
- mNumContext = 0;
- int cnt = sizeof( context_text ) / sizeof( context_text[ 0 ] );
- // check all 3 arrays have same sizes
- assert( cnt == sizeof( context_id ) / sizeof( context_id[ 0 ] )
- && cnt == sizeof( mContextMap ) / sizeof( mContextMap[ 0 ] ));
- for( int i = 0;
- i < cnt;
- ++i )
- {
- if( mpLoader->hasContext( context_id[ i ] ))
- {
- mpCombo->insertItem(i18n( context_text[ i ] ));
- mContextMap[ mNumContext++ ] = context_id[ i ];
- }
- }
- mpCombo->setFixedSize(mpCombo->sizeHint());
-
- mpBrowseBut->setFixedWidth(mpCombo->width());
-
- // Make the dialog a little taller
- incInitialSize(TQSize(0,100));
-}
-
-
-KIconDialog::~KIconDialog()
-{
- delete d;
-}
-
-void KIconDialog::slotAcceptIcons()
-{
- d->custom=TQString::null;
- slotOk();
-}
-
-void KIconDialog::showIcons()
-{
- mpCanvas->clear();
- TQStringList filelist;
- if (mType == 0)
- if (d->m_bStrictIconSize)
- filelist=mpLoader->queryIcons(mGroupOrSize, mContext);
- else
- filelist=mpLoader->queryIconsByContext(mGroupOrSize, mContext);
- else if ( !d->customLocation.isNull() )
- filelist=mpLoader->queryIconsByDir( d->customLocation );
- else
- filelist=mFileList;
-
- TQSortedList <IconPath>iconlist;
- iconlist.setAutoDelete(true);
- TQStringList::Iterator it;
- for( it = filelist.begin(); it != filelist.end(); ++it )
- iconlist.append(new IconPath(*it));
-
- iconlist.sort();
- filelist.clear();
-
- for ( IconPath *ip=iconlist.first(); ip != 0; ip=iconlist.next() )
- filelist.append(*ip);
-
- d->searchLine->clear();
- mpCanvas->loadFiles(filelist);
-}
-
-void KIconDialog::setStrictIconSize(bool b)
-{
- d->m_bStrictIconSize=b;
-}
-
-bool KIconDialog::strictIconSize() const
-{
- return d->m_bStrictIconSize;
-}
-
-void KIconDialog::setIconSize( int size )
-{
- // see KIconLoader, if you think this is weird
- if ( size == 0 )
- mGroupOrSize = KIcon::Desktop; // default Group
- else
- mGroupOrSize = -size; // yes, KIconLoader::queryIconsByContext is weird
-}
-
-int KIconDialog::iconSize() const
-{
- // 0 or any other value ==> mGroupOrSize is a group, so we return 0
- return (mGroupOrSize < 0) ? -mGroupOrSize : 0;
-}
-
-#ifndef KDE_NO_COMPAT
-TQString KIconDialog::selectIcon(KIcon::Group group, KIcon::Context context, bool user)
-{
- setup( group, context, false, 0, user );
- return openDialog();
-}
-#endif
-
-void KIconDialog::setup(KIcon::Group group, KIcon::Context context,
- bool strictIconSize, int iconSize, bool user )
-{
- d->m_bStrictIconSize = strictIconSize;
- mGroupOrSize = (iconSize == 0) ? group : -iconSize;
- mType = user ? 1 : 0;
- mpRb1->setChecked(!user);
- mpRb2->setChecked(user);
- mpCombo->setEnabled(!user);
- mpBrowseBut->setEnabled(user);
- setContext( context );
-}
-
-void KIconDialog::setup(KIcon::Group group, KIcon::Context context,
- bool strictIconSize, int iconSize, bool user,
- bool lockUser, bool lockCustomDir )
-{
- d->m_bStrictIconSize = strictIconSize;
- d->m_bLockUser = lockUser;
- d->m_bLockCustomDir = lockCustomDir;
- mGroupOrSize = (iconSize == 0) ? group : -iconSize;
- mType = user ? 1 : 0;
- mpRb1->setChecked(!user);
- mpRb1->setEnabled( !lockUser || !user );
- mpRb2->setChecked(user);
- mpRb2->setEnabled( !lockUser || user );
- mpCombo->setEnabled(!user);
- mpBrowseBut->setEnabled( user && !lockCustomDir );
- setContext( context );
-}
-
-void KIconDialog::setContext( KIcon::Context context )
-{
- mContext = context;
- for( int i = 0;
- i < mNumContext;
- ++i )
- if( mContextMap[ i ] == context )
- {
- mpCombo->setCurrentItem( i );
- return;
- }
-}
-
-void KIconDialog::setCustomLocation( const TQString& location )
-{
- d->customLocation = location;
-}
-
-TQString KIconDialog::openDialog()
-{
- showIcons();
-
- if ( exec() == Accepted )
- {
- if (!d->custom.isNull())
- return d->custom;
- TQString name = mpCanvas->getCurrent();
- if (name.isEmpty() || (mType == 1))
- return name;
- TQFileInfo fi(name);
- return fi.baseName();
- }
- return TQString::null;
-}
-
-void KIconDialog::showDialog()
-{
- setModal(false);
- showIcons();
- show();
-}
-
-void KIconDialog::slotOk()
-{
- TQString name;
- if (!d->custom.isNull())
- {
- name = d->custom;
- }
- else
- {
- name = mpCanvas->getCurrent();
- if (!name.isEmpty() && (mType != 1))
- {
- TQFileInfo fi(name);
- name = fi.baseName();
- }
- }
-
- emit newIconName(name);
- KDialogBase::slotOk();
-}
-
-TQString KIconDialog::getIcon(KIcon::Group group, KIcon::Context context,
- bool strictIconSize, int iconSize, bool user,
- TQWidget *parent, const TQString &caption)
-{
- KIconDialog dlg(parent, "icon dialog");
- dlg.setup( group, context, strictIconSize, iconSize, user );
- if (!caption.isNull())
- dlg.setCaption(caption);
-
- return dlg.openDialog();
-}
-
-void KIconDialog::slotButtonClicked(int id)
-{
- TQString file;
-
- switch (id)
- {
- case 0:
- if(mType!=0)
- {
- mType = 0;
- mpBrowseBut->setEnabled(false);
- mpCombo->setEnabled(true);
- showIcons();
- }
- break;
-
- case 1:
- if(mType!=1)
- {
- mType = 1;
- mpBrowseBut->setEnabled( !d->m_bLockCustomDir );
- mpCombo->setEnabled(false);
- showIcons();
- }
- break;
- case 2:
- {
- // Create a file dialog to select a PNG, XPM or SVG file,
- // with the image previewer shown.
- // KFileDialog::getImageOpenURL doesn't allow svg.
- KFileDialog dlg(TQString::null, i18n("*.png *.xpm *.svg *.svgz|Icon Files (*.png *.xpm *.svg *.svgz)"),
- this, "filedialog", true);
- dlg.setOperationMode( KFileDialog::Opening );
- dlg.setCaption( i18n("Open") );
- dlg.setMode( KFile::File );
-
- KImageFilePreview *ip = new KImageFilePreview( &dlg );
- dlg.setPreviewWidget( ip );
- dlg.exec();
-
- file = dlg.selectedFile();
- if (!file.isEmpty())
- {
- d->custom = file;
- if ( mType == 1 )
- d->customLocation = TQFileInfo( file ).dirPath( true );
- slotOk();
- }
- }
- break;
- }
-}
-
-void KIconDialog::slotContext(int id)
-{
- mContext = static_cast<KIcon::Context>( mContextMap[ id ] );
- showIcons();
-}
-
-void KIconDialog::slotStartLoading(int steps)
-{
- if (steps < 10)
- mpProgress->hide();
- else
- {
- mpProgress->setTotalSteps(steps);
- mpProgress->setProgress(0);
- mpProgress->show();
- }
-}
-
-void KIconDialog::slotProgress(int p)
-{
- mpProgress->setProgress(p);
- // commented out the following since setProgress already paints ther
- // progress bar. ->repaint() only makes it flicker
- //mpProgress->repaint();
-}
-
-void KIconDialog::slotFinished()
-{
- mpProgress->hide();
-}
-
-class KIconButton::KIconButtonPrivate
-{
- public:
- KIconButtonPrivate() {
- m_bStrictIconSize = false;
- iconSize = 0; // let KIconLoader choose the default
- }
- ~KIconButtonPrivate() {}
- bool m_bStrictIconSize;
- int iconSize;
-};
-
-
-/*
- * KIconButton: A "choose icon" pushbutton.
- */
-
-KIconButton::KIconButton(TQWidget *parent, const char *name)
- : TQPushButton(parent, name)
-{
- init( TDEGlobal::iconLoader() );
-}
-
-KIconButton::KIconButton(KIconLoader *loader,
- TQWidget *parent, const char *name)
- : TQPushButton(parent, name)
-{
- init( loader );
-}
-
-void KIconButton::init( KIconLoader *loader )
-{
- d = new KIconButtonPrivate;
- mGroup = KIcon::Desktop;
- mContext = KIcon::Application;
- mbUser = false;
-
- mpLoader = loader;
- mpDialog = 0L;
- connect(this, TQT_SIGNAL(clicked()), TQT_SLOT(slotChangeIcon()));
-}
-
-KIconButton::~KIconButton()
-{
- delete mpDialog;
- delete d;
-}
-
-void KIconButton::setStrictIconSize(bool b)
-{
- d->m_bStrictIconSize=b;
-}
-
-bool KIconButton::strictIconSize() const
-{
- return d->m_bStrictIconSize;
-}
-
-void KIconButton::setIconSize( int size )
-{
- d->iconSize = size;
-}
-
-int KIconButton::iconSize() const
-{
- return d->iconSize;
-}
-
-void KIconButton::setIconType(KIcon::Group group, KIcon::Context context, bool user)
-{
- mGroup = group;
- mContext = context;
- mbUser = user;
-}
-
-void KIconButton::setIcon(const TQString& icon)
-{
- mIcon = icon;
- setIconSet(mpLoader->loadIconSet(mIcon, mGroup, d->iconSize));
-
- if (!mpDialog)
- {
- mpDialog = new KIconDialog(mpLoader, this);
- connect(mpDialog, TQT_SIGNAL(newIconName(const TQString&)), TQT_SLOT(newIconName(const TQString&)));
- }
-
- if ( mbUser )
- mpDialog->setCustomLocation( TQFileInfo( mpLoader->iconPath(mIcon, mGroup, true) ).dirPath( true ) );
-}
-
-void KIconButton::resetIcon()
-{
- mIcon = TQString::null;
- setIconSet(TQIconSet());
-}
-
-void KIconButton::slotChangeIcon()
-{
- if (!mpDialog)
- {
- mpDialog = new KIconDialog(mpLoader, this);
- connect(mpDialog, TQT_SIGNAL(newIconName(const TQString&)), TQT_SLOT(newIconName(const TQString&)));
- }
-
- mpDialog->setup( mGroup, mContext, d->m_bStrictIconSize, d->iconSize, mbUser );
- mpDialog->showDialog();
-}
-
-void KIconButton::newIconName(const TQString& name)
-{
- if (name.isEmpty())
- return;
-
- TQIconSet iconset = mpLoader->loadIconSet(name, mGroup, d->iconSize);
- setIconSet(iconset);
- mIcon = name;
-
- if ( mbUser )
- mpDialog->setCustomLocation( TQFileInfo( mpLoader->iconPath(mIcon, mGroup, true) ).dirPath( true ) );
-
- emit iconChanged(name);
-}
-
-void KIconCanvas::virtual_hook( int id, void* data )
-{ KIconView::virtual_hook( id, data ); }
-
-void KIconDialog::virtual_hook( int id, void* data )
-{ KDialogBase::virtual_hook( id, data ); }
-
-#include "kicondialog.moc"
diff --git a/kio/kfile/kicondialog.h b/kio/kfile/kicondialog.h
deleted file mode 100644
index 30d9f1579..000000000
--- a/kio/kfile/kicondialog.h
+++ /dev/null
@@ -1,350 +0,0 @@
-/* vi: ts=8 sts=4 sw=4
- *
- * This file is part of the KDE project, module kfile.
- * Copyright (C) 2000 Geert Jansen <jansen@kde.org>
- * (C) 2000 Kurt Granroth <granroth@kde.org>
- * (C) 1997 Christoph Neerfeld <chris@kde.org>
- * (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
- *
- * This is free software; it comes under the GNU Library General
- * Public License, version 2. See the file "COPYING.LIB" for the
- * exact licensing terms.
- */
-
-#ifndef __KIconDialog_h__
-#define __KIconDialog_h__
-
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqpushbutton.h>
-
-#include <kicontheme.h>
-#include <kdialogbase.h>
-#include <kiconview.h>
-
-class TQComboBox;
-class TQTimer;
-class TQKeyEvent;
-class TQRadioButton;
-class KProgress;
-class KIconLoader;
-
-/**
- * Icon canvas for KIconDialog.
- */
-class TDEIO_EXPORT KIconCanvas: public KIconView
-{
- Q_OBJECT
-
-public:
- KIconCanvas(TQWidget *parent=0L, const char *name=0L);
- ~KIconCanvas();
-
- /**
- * Load icons into the canvas.
- */
- void loadFiles(const TQStringList& files);
-
- /**
- * Returns the current icon.
- */
- TQString getCurrent() const;
-
-public slots:
- void stopLoading();
-
-signals:
- /**
- * Emitted when the current icon has changed.
- */
- void nameChanged(TQString);
- /* KDE 4: Make it const TQString & */
-
- void startLoading(int);
- void progress(int);
- void finished();
-
-private slots:
- void slotLoadFiles();
- void slotCurrentChanged(TQIconViewItem *item);
-
-private:
- TQStringList mFiles;
- TQTimer *mpTimer;
- KIconLoader *mpLoader; // unused
-
-protected:
- virtual void virtual_hook( int id, void* data );
-
-private:
- class KIconCanvasPrivate;
- KIconCanvasPrivate *d;
-};
-
-
-/**
- * Dialog for interactive selection of icons. Use the function
- * getIcon() let the user select an icon.
- *
- * @short An icon selection dialog.
- */
-class TDEIO_EXPORT KIconDialog: public KDialogBase
-{
- Q_OBJECT
-
-public:
- /**
- * Constructs an icon selection dialog using the global iconloader.
- */
- KIconDialog(TQWidget *parent=0L, const char *name=0L);
- /**
- * Constructs an icon selection dialog using a specific iconloader.
- */
- KIconDialog(KIconLoader *loader, TQWidget *parent=0,
- const char *name=0);
- /**
- * Destructs the dialog.
- */
- ~KIconDialog();
-
- /**
- * Sets a strict icon size policy for allowed icons. When true,
- * only icons of the specified group's size in getIcon() are shown.
- * When false, icons not available at the desired group's size will
- * also be selectable.
- */
- void setStrictIconSize(bool b);
- /**
- * Returns true if a strict icon size policy is set.
- */
- bool strictIconSize() const;
- /**
- * sets a custom icon directory
- * @since 3.1
- */
- void setCustomLocation( const TQString& location );
-
- /**
- * Sets the size of the icons to be shown / selected.
- * @see KIcon::StdSizes
- * @see iconSize
- */
- void setIconSize(int size);
-
- /**
- * Returns the iconsize set via setIconSize() or 0, if the default
- * iconsize will be used.
- */
- int iconSize() const;
-
-#ifndef KDE_NO_COMPAT
- /**
- * @deprecated in KDE 3.0, use the static method getIcon instead.
- */
- TQString selectIcon(KIcon::Group group=KIcon::Desktop, KIcon::Context
- context=KIcon::Application, bool user=false);
-#endif
-
- /**
- * Allows you to set the same parameters as in the class method
- * getIcon().
- */
- void setup( KIcon::Group group,
- KIcon::Context context = KIcon::Application,
- bool strictIconSize = false, int iconSize = 0,
- bool user = false );
-
- /**
- * Allows you to set the same parameters as in the class method
- * getIcon(), as well as two additional parameters to lock
- * the choice between system and user dirs and to lock the custom user
- * dir itself.
- *
- * @since 3.3
- */
-
- void setup( KIcon::Group group, KIcon::Context context,
- bool strictIconSize, int iconSize, bool user, bool lockUser,
- bool lockCustomDir );
-
- /**
- * exec()utes this modal dialog and returns the name of the selected icon,
- * or TQString::null if the dialog was aborted.
- * @returns the name of the icon, suitable for loading with KIconLoader.
- * @see getIcon
- */
- TQString openDialog();
-
- /**
- * show()es this dialog and emits a newIcon(const TQString&) signal when
- * successful. TQString::null will be emitted if the dialog was aborted.
- */
- void showDialog();
-
- /**
- * Pops up the dialog an lets the user select an icon.
- *
- * @param group The icon group this icon is intended for. Providing the
- * group shows the icons in the dialog with the same appearance as when
- * used outside the dialog.
- * @param context The initial icon context. Initially, the icons having
- * this context are shown in the dialog. The user can change this.
- * @param strictIconSize When true, only icons of the specified group's size
- * are shown, otherwise icon not available in the desired group's size
- * will also be selectable.
- * @param iconSize the size of the icons -- the default of the icongroup
- * if set to 0
- * @param user Begin with the "user icons" instead of "system icons".
- * @param parent The parent widget of the dialog.
- * @param caption The caption to use for the dialog.
- * @return The name of the icon, suitable for loading with KIconLoader.
- * @version New in 3.0
- */
- static TQString getIcon(KIcon::Group group=KIcon::Desktop,
- KIcon::Context context=KIcon::Application,
- bool strictIconSize=false, int iconSize = 0,
- bool user=false, TQWidget *parent=0,
- const TQString &caption=TQString::null);
-
-signals:
- void newIconName(const TQString&);
-
-protected slots:
- void slotOk();
-
-private slots:
- void slotButtonClicked(int);
- void slotContext(int);
- void slotStartLoading(int);
- void slotProgress(int);
- void slotFinished();
- void slotAcceptIcons();
-private:
- void init();
- void showIcons();
- void setContext( KIcon::Context context );
-
- int mGroupOrSize;
- KIcon::Context mContext;
- int mType;
-
- TQStringList mFileList;
- TQComboBox *mpCombo;
- TQPushButton *mpBrowseBut;
- TQRadioButton *mpRb1, *mpRb2;
- KProgress *mpProgress;
- KIconLoader *mpLoader;
- KIconCanvas *mpCanvas;
- int mNumContext;
- KIcon::Context mContextMap[ 12 ]; // must match KIcon::Context size, code has assert
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KIconDialogPrivate;
- KIconDialogPrivate *d;
-};
-
-
-/**
- * A pushbutton for choosing an icon. Pressing on the button will open a
- * KIconDialog for the user to select an icon. The current icon will be
- * displayed on the button.
- *
- * @see KIconDialog
- * @short A push button that allows selection of an icon.
- */
-class TDEIO_EXPORT KIconButton: public TQPushButton
-{
- Q_OBJECT
- TQ_PROPERTY( TQString icon READ icon WRITE setIcon RESET resetIcon )
- TQ_PROPERTY( int iconSize READ iconSize WRITE setIconSize)
- TQ_PROPERTY( bool strictIconSize READ strictIconSize WRITE setStrictIconSize )
-
-public:
- /**
- * Constructs a KIconButton using the global iconloader.
- */
- KIconButton(TQWidget *parent=0L, const char *name=0L);
-
- /**
- * Constructs a KIconButton using a specific KIconLoader.
- */
- KIconButton(KIconLoader *loader, TQWidget *parent, const char *name=0L);
- /**
- * Destructs the button.
- */
- ~KIconButton();
-
- /**
- * Sets a strict icon size policy for allowed icons. When true,
- * only icons of the specified group's size in setIconType are allowed,
- * and only icons of that size will be shown in the icon dialog.
- */
- void setStrictIconSize(bool b);
- /**
- * Returns true if a strict icon size policy is set.
- */
- bool strictIconSize() const;
-
- /**
- * Sets the icon group and context. Use KIcon::NoGroup if you want to
- * allow icons for any group in the given context.
- */
- void setIconType(KIcon::Group group, KIcon::Context context, bool user=false);
-
- /**
- * Sets the button's initial icon.
- */
- void setIcon(const TQString& icon);
-
- /**
- * Resets the icon (reverts to an empty button).
- */
- void resetIcon();
-
- /**
- * Returns the name of the selected icon.
- */
- TQString icon() const { return mIcon; }
-
- /**
- * Sets the size of the icon to be shown / selected.
- * @see KIcon::StdSizes
- * @see iconSize
- */
- void setIconSize( int size );
-
- /**
- * Returns the iconsize set via setIconSize() or 0, if the default
- * iconsize will be used.
- */
- int iconSize() const;
-
-signals:
- /**
- * Emitted when the icon has changed.
- */
- void iconChanged(TQString icon);
- /* KDE 4: Make it const TQString & */
-
-private slots:
- void slotChangeIcon();
- void newIconName(const TQString& name);
-
-private:
- void init( KIconLoader *loader );
-
- bool mbUser;
- KIcon::Group mGroup;
- KIcon::Context mContext;
-
- TQString mIcon;
- KIconDialog *mpDialog;
- KIconLoader *mpLoader;
- class KIconButtonPrivate;
- KIconButtonPrivate *d;
-};
-
-
-#endif // __KIconDialog_h__
diff --git a/kio/kfile/kimagefilepreview.cpp b/kio/kfile/kimagefilepreview.cpp
deleted file mode 100644
index 0cc0ef2a7..000000000
--- a/kio/kfile/kimagefilepreview.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * This file is part of the KDE project
- * Copyright (C) 2001 Martin R. Jones <mjones@kde.org>
- * 2001 Carsten Pfeiffer <pfeiffer@kde.org>
- *
- * You can Freely distribute this program under the GNU Library General Public
- * License. See the file "COPYING" for the exact licensing terms.
- */
-
-#include <tqlayout.h>
-#include <tqlabel.h>
-#include <tqcombobox.h>
-#include <tqcheckbox.h>
-#include <tqwhatsthis.h>
-#include <tqtimer.h>
-
-#include <kapplication.h>
-#include <kconfig.h>
-#include <kglobal.h>
-#include <kiconloader.h>
-#include <kpushbutton.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kfiledialog.h>
-#include <kfileitem.h>
-#include <kio/previewjob.h>
-
-#include "kimagefilepreview.h"
-#include "config-kfile.h"
-
-/**** KImageFilePreview ****/
-
-KImageFilePreview::KImageFilePreview( TQWidget *parent )
- : KPreviewWidgetBase( parent ),
- m_job( 0L )
-{
- TDEConfig *config = TDEGlobal::config();
- TDEConfigGroupSaver cs( config, ConfigGroup );
- autoMode = config->readBoolEntry( "Automatic Preview", true );
-
- TQVBoxLayout *vb = new TQVBoxLayout( this, 0, KDialog::spacingHint() );
-
- imageLabel = new TQLabel( this );
- imageLabel->setFrameStyle( TQFrame::NoFrame );
- imageLabel->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
- imageLabel->setSizePolicy( TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Expanding) );
- vb->addWidget( imageLabel );
-
- TQHBoxLayout *hb = new TQHBoxLayout( 0 );
- vb->addLayout( hb );
-
- autoPreview = new TQCheckBox( i18n("&Automatic preview"), this );
- autoPreview->setChecked( autoMode );
- hb->addWidget( autoPreview );
- connect( autoPreview, TQT_SIGNAL(toggled(bool)), TQT_SLOT(toggleAuto(bool)) );
-
- previewButton = new KPushButton( SmallIconSet("thumbnail"), i18n("&Preview"), this );
- hb->addWidget( previewButton );
- connect( previewButton, TQT_SIGNAL(clicked()), TQT_SLOT(showPreview()) );
-
- timer = new TQTimer( this );
- connect( timer, TQT_SIGNAL(timeout()), TQT_SLOT(showPreview()) );
-
- setSupportedMimeTypes( TDEIO::PreviewJob::supportedMimeTypes() );
-}
-
-KImageFilePreview::~KImageFilePreview()
-{
- if ( m_job )
- m_job->kill();
-
- TDEConfig *config = TDEGlobal::config();
- TDEConfigGroupSaver cs( config, ConfigGroup );
- config->writeEntry( "Automatic Preview", autoPreview->isChecked() );
-}
-
-void KImageFilePreview::showPreview()
-{
- // Pass a copy since clearPreview() will clear currentURL
- KURL url = currentURL;
- showPreview( url, true );
-}
-
-// called via KPreviewWidgetBase interface
-void KImageFilePreview::showPreview( const KURL& url )
-{
- showPreview( url, false );
-}
-
-void KImageFilePreview::showPreview( const KURL &url, bool force )
-{
- if ( !url.isValid() ) {
- clearPreview();
- return;
- }
-
- if ( url != currentURL || force )
- {
- clearPreview();
- currentURL = url;
-
- if ( autoMode || force )
- {
- int w = imageLabel->contentsRect().width() - 4;
- int h = imageLabel->contentsRect().height() - 4;
-
- m_job = createJob( url, w, h );
- if ( force ) // explicitly requested previews shall always be generated!
- m_job->setIgnoreMaximumSize( true );
-
- connect( m_job, TQT_SIGNAL( result( TDEIO::Job * )),
- this, TQT_SLOT( slotResult( TDEIO::Job * )));
- connect( m_job, TQT_SIGNAL( gotPreview( const KFileItem*,
- const TQPixmap& )),
- TQT_SLOT( gotPreview( const KFileItem*, const TQPixmap& ) ));
-
- connect( m_job, TQT_SIGNAL( failed( const KFileItem* )),
- this, TQT_SLOT( slotFailed( const KFileItem* ) ));
- }
- }
-}
-
-void KImageFilePreview::toggleAuto( bool a )
-{
- autoMode = a;
- if ( autoMode )
- {
- // Pass a copy since clearPreview() will clear currentURL
- KURL url = currentURL;
- showPreview( url, true );
- }
-}
-
-void KImageFilePreview::resizeEvent( TQResizeEvent * )
-{
- timer->start( 100, true ); // forces a new preview
-}
-
-TQSize KImageFilePreview::sizeHint() const
-{
- return TQSize( 20, 200 ); // otherwise it ends up huge???
-}
-
-TDEIO::PreviewJob * KImageFilePreview::createJob( const KURL& url, int w, int h )
-{
- KURL::List urls;
- urls.append( url );
- return TDEIO::filePreview( urls, w, h, 0, 0, true, false );
-}
-
-void KImageFilePreview::gotPreview( const KFileItem* item, const TQPixmap& pm )
-{
- if ( item->url() == currentURL ) // should always be the case
- imageLabel->setPixmap( pm );
-}
-
-void KImageFilePreview::slotFailed( const KFileItem* item )
-{
- if ( item->isDir() )
- imageLabel->clear();
- else if ( item->url() == currentURL ) // should always be the case
- imageLabel->setPixmap( SmallIcon( "file_broken", KIcon::SizeLarge,
- KIcon::DisabledState ));
-}
-
-void KImageFilePreview::slotResult( TDEIO::Job *job )
-{
- if ( job == m_job )
- m_job = 0L;
-}
-
-void KImageFilePreview::clearPreview()
-{
- if ( m_job ) {
- m_job->kill();
- m_job = 0L;
- }
-
- imageLabel->clear();
- currentURL = KURL();
-}
-
-void KImageFilePreview::virtual_hook( int id, void* data )
-{ KPreviewWidgetBase::virtual_hook( id, data ); }
-
-#include "kimagefilepreview.moc"
diff --git a/kio/kfile/kmetaprops.cpp b/kio/kfile/kmetaprops.cpp
deleted file mode 100644
index c349693e5..000000000
--- a/kio/kfile/kmetaprops.cpp
+++ /dev/null
@@ -1,268 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001,2002 Rolf Magnus <ramagnus@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
- $Id$
- */
-
-#include "kmetaprops.h"
-
-#include <kdebug.h>
-#include <kfilemetainfowidget.h>
-#include <kfilemetainfo.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <klocale.h>
-#include <kprotocolinfo.h>
-
-#include <tqvalidator.h>
-#include <tqlayout.h>
-#include <tqlabel.h>
-#include <tqfileinfo.h>
-#include <tqdatetime.h>
-#include <tqstylesheet.h>
-#include <tqvgroupbox.h>
-
-#undef Bool
-
-class MetaPropsScrollView : public TQScrollView
-{
-public:
- MetaPropsScrollView(TQWidget* parent = 0, const char* name = 0)
- : TQScrollView(parent, name)
- {
- setFrameStyle(TQFrame::NoFrame);
- m_frame = new TQFrame(viewport(), "MetaPropsScrollView::m_frame");
- m_frame->setFrameStyle(TQFrame::NoFrame);
- addChild(m_frame, 0, 0);
- };
-
- TQFrame* frame() {return m_frame;};
-
-protected:
- virtual void viewportResizeEvent(TQResizeEvent* ev)
- {
- TQScrollView::viewportResizeEvent(ev);
- m_frame->resize( kMax(m_frame->sizeHint().width(), ev->size().width()),
- kMax(m_frame->sizeHint().height(), ev->size().height()));
- };
-
-private:
- TQFrame* m_frame;
-};
-
-class KFileMetaPropsPlugin::KFileMetaPropsPluginPrivate
-{
-public:
- KFileMetaPropsPluginPrivate() {}
- ~KFileMetaPropsPluginPrivate() {}
-
- TQFrame* m_frame;
- TQGridLayout* m_framelayout;
- KFileMetaInfo m_info;
-// TQPushButton* m_add;
- TQPtrList<KFileMetaInfoWidget> m_editWidgets;
-};
-
-KFileMetaPropsPlugin::KFileMetaPropsPlugin(KPropertiesDialog* props)
- : KPropsDlgPlugin(props)
-{
- d = new KFileMetaPropsPluginPrivate;
-
- KFileItem * fileitem = properties->item();
- kdDebug(250) << "KFileMetaPropsPlugin constructor" << endl;
-
- d->m_info = fileitem->metaInfo();
- if (!d->m_info.isValid())
- {
- d->m_info = KFileMetaInfo(properties->kurl().path(-1));
- fileitem->setMetaInfo(d->m_info);
- }
-
- if ( properties->items().count() > 1 )
- {
- // not yet supported
- // we should allow setting values for a list of files. Itt makes sense
- // in some cases, like the album of a list of mp3s
- return;
- }
-
- createLayout();
-
- setDirty(true);
-}
-
-void KFileMetaPropsPlugin::createLayout()
-{
- TQFileInfo file_info(properties->item()->url().path());
-
- kdDebug(250) << "KFileMetaPropsPlugin::createLayout" << endl;
-
- // is there any valid and non-empty info at all?
- if ( !d->m_info.isValid() || (d->m_info.preferredKeys()).isEmpty() )
- return;
-
- // now get a list of groups
- KFileMetaInfoProvider* prov = KFileMetaInfoProvider::self();
- TQStringList groupList = d->m_info.preferredGroups();
-
- const KFileMimeTypeInfo* mtinfo = prov->mimeTypeInfo(d->m_info.mimeType());
- if (!mtinfo)
- {
- kdDebug(7034) << "no mimetype info there\n";
- return;
- }
-
- // let the dialog create the page frame
- TQFrame* topframe = properties->addPage(i18n("&Meta Info"));
- topframe->setFrameStyle(TQFrame::NoFrame);
- TQVBoxLayout* tmp = new TQVBoxLayout(topframe);
-
- // create a scroll view in the page
- MetaPropsScrollView* view = new MetaPropsScrollView(topframe);
-
- tmp->addWidget(view);
-
- d->m_frame = view->frame();
-
- TQVBoxLayout *toplayout = new TQVBoxLayout(d->m_frame);
- toplayout->setSpacing(KDialog::spacingHint());
-
- for (TQStringList::Iterator git=groupList.begin();
- git!=groupList.end(); ++git)
- {
- kdDebug(7033) << *git << endl;
-
- TQStringList itemList = d->m_info.group(*git).preferredKeys();
- if (itemList.isEmpty())
- continue;
-
- TQGroupBox *groupBox = new TQGroupBox(2, Qt::Horizontal,
- TQStyleSheet::escape(mtinfo->groupInfo(*git)->translatedName()),
- d->m_frame);
-
- toplayout->addWidget(groupBox);
-
- TQValueList<KFileMetaInfoItem> readItems;
- TQValueList<KFileMetaInfoItem> editItems;
-
- for (TQStringList::Iterator iit = itemList.begin();
- iit!=itemList.end(); ++iit)
- {
- KFileMetaInfoItem item = d->m_info[*git][*iit];
- if ( !item.isValid() ) continue;
-
- bool editable = file_info.isWritable() && item.isEditable();
-
- if (editable)
- editItems.append( item );
- else
- readItems.append( item );
- }
-
- KFileMetaInfoWidget* w = 0L;
- // then first add the editable items to the layout
- for (TQValueList<KFileMetaInfoItem>::Iterator iit= editItems.begin();
- iit!=editItems.end(); ++iit)
- {
- TQLabel* l = new TQLabel((*iit).translatedKey() + ":", groupBox);
- l->setAlignment( AlignAuto | AlignTop | ExpandTabs );
- TQValidator* val = mtinfo->createValidator(*git, (*iit).key());
- if (!val) kdDebug(7033) << "didn't get a validator for " << *git << "/" << (*iit).key() << endl;
- w = new KFileMetaInfoWidget(*iit, val, groupBox);
- d->m_editWidgets.append( w );
- connect(w, TQT_SIGNAL(valueChanged(const TQVariant&)), this, TQT_SIGNAL(changed()));
- }
-
- // and then the read only items
- for (TQValueList<KFileMetaInfoItem>::Iterator iit= readItems.begin();
- iit!=readItems.end(); ++iit)
- {
- TQLabel* l = new TQLabel((*iit).translatedKey() + ":", groupBox);
- l->setAlignment( AlignAuto | AlignTop | ExpandTabs );
- (new KFileMetaInfoWidget(*iit, KFileMetaInfoWidget::ReadOnly, 0L, groupBox));
- }
- }
-
- toplayout->addStretch(1);
-
- // the add key (disabled until fully implemented)
-/* d->m_add = new TQPushButton(i18n("&Add"), topframe);
- d->m_add->setSizePolicy(TQSizePolicy(TQSizePolicy::Fixed,
- TQSizePolicy::Fixed));
- connect(d->m_add, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotAdd()));
- tmp->addWidget(d->m_add);
-
- // if nothing can be added, deactivate it
- if ( !d->m_info.supportsVariableKeys() )
- {
- // if supportedKeys() does contain anything not in preferredKeys,
- // we have something addable
-
- TQStringList sk = d->m_info.supportedKeys();
- d->m_add->setEnabled(false);
- for (TQStringList::Iterator it = sk.begin(); it!=sk.end(); ++it)
- {
- if ( l.find(*it)==l.end() )
- {
- d->m_add->setEnabled(true);
- kdDebug(250) << "**first addable key is " << (*it).latin1() << "**" <<endl;
- break;
- }
- kdDebug(250) << "**already existing key is " << (*it).latin1() << "**" <<endl;
- }
- } */
-}
-
-/*void KFileMetaPropsPlugin::slotAdd()
-{
- // add a lineedit for the name
-
-
-
- // insert the item in the list
-
-}*/
-
-KFileMetaPropsPlugin::~KFileMetaPropsPlugin()
-{
- delete d;
-}
-
-bool KFileMetaPropsPlugin::supports( KFileItemList _items )
-{
-#ifdef _GNUC
-#warning TODO: Add support for more than one item
-#endif
- if (KExecPropsPlugin::supports(_items) || KURLPropsPlugin::supports(_items))
- return false; // Having both is redundant.
-
- bool metaDataEnabled = TDEGlobalSettings::showFilePreview(_items.first()->url());
- return _items.count() == 1 && metaDataEnabled;
-}
-
-void KFileMetaPropsPlugin::applyChanges()
-{
- kdDebug(250) << "applying changes" << endl;
- // insert the fields that changed into the info object
-
- TQPtrListIterator<KFileMetaInfoWidget> it( d->m_editWidgets );
- KFileMetaInfoWidget* w;
- for (; (w = it.current()); ++it) w->apply();
- d->m_info.applyChanges(properties->kurl().path());
-}
-
-#include "kmetaprops.moc"
diff --git a/kio/kfile/knotifydialog.cpp b/kio/kfile/knotifydialog.cpp
deleted file mode 100644
index 088f9be54..000000000
--- a/kio/kfile/knotifydialog.cpp
+++ /dev/null
@@ -1,1191 +0,0 @@
-/*
- Copyright (C) 2000,2002 Carsten Pfeiffer <pfeiffer@kde.org>
- Copyright (C) 2002 Neil Stevens <neil@qualityassistant.com>
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation;
-
- 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 Library General Public License
- along with this library, If not, write to the Free Software Foundation,
- Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include <dcopclient.h>
-
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kaudioplayer.h>
-#include <kcombobox.h>
-#include <kconfig.h>
-#include <kcursor.h>
-#include <kdebug.h>
-#include <kfiledialog.h>
-#include <kiconloader.h>
-#include <kicontheme.h>
-#include <klineedit.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <knotifyclient.h>
-#include <knotifydialog.h>
-#include <kstandarddirs.h>
-#include <kurlrequester.h>
-#include <kio/netaccess.h>
-
-#include <tqcheckbox.h>
-#include <tqgroupbox.h>
-#include <tqheader.h>
-#include <tqlabel.h>
-#include <tqlistview.h>
-#include <tqlayout.h>
-#include <tqptrlist.h>
-#include <tqpushbutton.h>
-#include <tqstring.h>
-#include <tqtooltip.h>
-#include <tqtimer.h>
-#include <tqvbox.h>
-#include <tqwhatsthis.h>
-
-using namespace KNotify;
-
-enum
-{
- COL_EXECUTE = 0,
- COL_STDERR = 1,
- COL_MESSAGE = 2,
- COL_LOGFILE = 3,
- COL_SOUND = 4,
- COL_TASKBAR = 5,
- COL_EVENT = 6
-};
-
-//
-// I don't feel like subclassing KComboBox and find ways to insert that into
-// the .ui file...
-//
-namespace KNotify
-{
- class SelectionCombo
- {
- public:
- //
- // Mind the order in fill() and type()
- //
- static void fill( KComboBox *combo )
- {
- combo->insertItem( i18n("Sounds") );
- combo->insertItem( i18n("Logging") );
- combo->insertItem( i18n("Program Execution") );
- combo->insertItem( i18n("Message Windows") );
- combo->insertItem( i18n("Passive Windows") );
- combo->insertItem( i18n("Standard Error Output") );
- combo->insertItem( i18n("Taskbar") );
- }
-
- static int type( KComboBox *combo )
- {
- switch( combo->currentItem() )
- {
- case 0:
- return KNotifyClient::Sound;
- case 1:
- return KNotifyClient::Logfile;
- case 2:
- return KNotifyClient::Execute;
- case 3:
- return KNotifyClient::Messagebox;
- case 4:
- return KNotifyClient::PassivePopup;
- case 5:
- return KNotifyClient::Stderr;
- case 6:
- return KNotifyClient::Taskbar;
- }
-
- return KNotifyClient::None;
- }
- };
-
- // Needed for displaying tooltips in the listview's QHeader
- class KNotifyToolTip : public TQToolTip
- {
- public:
- KNotifyToolTip( TQHeader *header )
- : TQToolTip( header )
- {
- m_tips[COL_EXECUTE] = i18n("Execute a program");
- m_tips[COL_STDERR] = i18n("Print to Standard error output");
- m_tips[COL_MESSAGE] = i18n("Display a messagebox");
- m_tips[COL_LOGFILE] = i18n("Log to a file");
- m_tips[COL_SOUND] = i18n("Play a sound");
- m_tips[COL_TASKBAR] = i18n("Flash the taskbar entry");
- }
- virtual ~KNotifyToolTip() {}
-
- protected:
- virtual void maybeTip ( const TQPoint& p )
- {
- TQHeader *header = static_cast<TQHeader*>( parentWidget() );
- int section = 0;
-
- if ( header->orientation() == Qt::Horizontal )
- section= header->sectionAt( p.x() );
- else
- section= header->sectionAt( p.y() );
-
- if ( ( section < 0 ) || ( static_cast<uint>( section ) >= (sizeof(m_tips) / sizeof(TQString)) ) )
- return;
-
- tip( header->sectionRect( section ), m_tips[section] );
- }
-
- private:
- TQString m_tips[6];
- };
-
-}
-
-
-int KNotifyDialog::configure( TQWidget *parent, const char *name,
- const TDEAboutData *aboutData )
-{
- KNotifyDialog dialog( parent, name, true, aboutData );
- return dialog.exec();
-}
-
-KNotifyDialog::KNotifyDialog( TQWidget *parent, const char *name, bool modal,
- const TDEAboutData *aboutData )
- : KDialogBase(parent, name, modal, i18n("Notification Settings"),
- Ok | Apply | Cancel | Default, Ok, true )
-{
- TQVBox *box = makeVBoxMainWidget();
-
- m_notifyWidget = new KNotifyWidget( box, "knotify widget" );
-
- if ( aboutData )
- addApplicationEvents( aboutData->appName() );
-
- connect( this, TQT_SIGNAL( okClicked() ), m_notifyWidget, TQT_SLOT( save() ));
- connect( this, TQT_SIGNAL( applyClicked() ), m_notifyWidget, TQT_SLOT( save() ));
-}
-
-KNotifyDialog::~KNotifyDialog()
-{
-}
-
-void KNotifyDialog::addApplicationEvents( const char *appName )
-{
- addApplicationEvents( TQString::fromUtf8( appName ) +
- TQString::fromLatin1( "/eventsrc" ) );
-}
-
-void KNotifyDialog::addApplicationEvents( const TQString& path )
-{
- Application *app = m_notifyWidget->addApplicationEvents( path );
- if ( app )
- {
- m_notifyWidget->addVisibleApp( app );
- m_notifyWidget->sort();
- }
-}
-
-void KNotifyDialog::clearApplicationEvents()
-{
- m_notifyWidget->clear();
-}
-
-void KNotifyDialog::slotDefault()
-{
- m_notifyWidget->resetDefaults( true ); // ask user
-}
-
-
-//////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////
-
-
-class KNotifyWidget::Private
-{
-public:
- TQPixmap pixmaps[6];
- KNotifyToolTip *toolTip;
-};
-
-// simple access to all knotify-handled applications
-KNotifyWidget::KNotifyWidget( TQWidget *parent, const char *name,
- bool handleAllApps )
- : KNotifyWidgetBase( parent, name ? name : "KNotifyWidget" )
-{
- d = new Private;
-
- m_allApps.setAutoDelete( true );
-
- if ( !handleAllApps )
- {
- m_affectAllApps->hide();
- m_playerButton->hide();
- }
-
- SelectionCombo::fill( m_comboEnable );
- SelectionCombo::fill( m_comboDisable );
-
- m_listview->setFullWidth( true );
- m_listview->setAllColumnsShowFocus( true );
-
- TQPixmap pexec = SmallIcon("exec");
- TQPixmap pstderr = SmallIcon("terminal");
- TQPixmap pmessage = SmallIcon("info");
- TQPixmap plogfile = SmallIcon("log");
- TQPixmap psound = SmallIcon("sound");
- TQPixmap ptaskbar = SmallIcon("kicker");
-
- d->pixmaps[COL_EXECUTE] = pexec;
- d->pixmaps[COL_STDERR] = pstderr;
- d->pixmaps[COL_MESSAGE] = pmessage;
- d->pixmaps[COL_LOGFILE] = plogfile;
- d->pixmaps[COL_SOUND] = psound;
- d->pixmaps[COL_TASKBAR] = ptaskbar;
-
- int w = KIcon::SizeSmall + 6;
-
- TQHeader *header = m_listview->header();
- header->setLabel( COL_EXECUTE, pexec, TQString::null, w );
- header->setLabel( COL_STDERR, pstderr, TQString::null, w );
- header->setLabel( COL_MESSAGE, pmessage, TQString::null, w );
- header->setLabel( COL_LOGFILE, plogfile, TQString::null, w );
- header->setLabel( COL_SOUND, psound, TQString::null, w );
- header->setLabel( COL_TASKBAR, ptaskbar, TQString::null, w );
-
- d->toolTip = new KNotifyToolTip( header );
-
- m_playButton->setIconSet( SmallIconSet( "player_play" ) );
- connect( m_playButton, TQT_SIGNAL( clicked() ), TQT_SLOT( playSound() ));
-
- connect( m_listview, TQT_SIGNAL( currentChanged( TQListViewItem * ) ),
- TQT_SLOT( slotEventChanged( TQListViewItem * ) ));
- connect( m_listview, TQT_SIGNAL(clicked( TQListViewItem *, const TQPoint&, int)),
- TQT_SLOT( slotItemClicked( TQListViewItem *, const TQPoint&, int )));
-
- connect( m_playSound, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( soundToggled( bool )) );
- connect( m_logToFile, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( loggingToggled( bool )) );
- connect( m_execute, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( executeToggled( bool )) );
- connect( m_messageBox, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( messageBoxChanged() ) );
- connect( m_passivePopup, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( messageBoxChanged() ) );
- connect( m_stderr, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( stderrToggled( bool ) ) );
- connect( m_taskbar, TQT_SIGNAL( toggled( bool )),
- TQT_SLOT( taskbarToggled( bool ) ) );
-
- connect( m_soundPath, TQT_SIGNAL( textChanged( const TQString& )),
- TQT_SLOT( soundFileChanged( const TQString& )));
- connect( m_logfilePath, TQT_SIGNAL( textChanged( const TQString& )),
- TQT_SLOT( logfileChanged( const TQString& ) ));
- connect( m_executePath, TQT_SIGNAL( textChanged( const TQString& )),
- TQT_SLOT( commandlineChanged( const TQString& ) ));
-
- connect( m_soundPath, TQT_SIGNAL( openFileDialog( KURLRequester * )),
- TQT_SLOT( openSoundDialog( KURLRequester * )));
- connect( m_logfilePath, TQT_SIGNAL( openFileDialog( KURLRequester * )),
- TQT_SLOT( openLogDialog( KURLRequester * )));
- connect( m_executePath, TQT_SIGNAL( openFileDialog( KURLRequester * )),
- TQT_SLOT( openExecDialog( KURLRequester * )));
-
- connect( m_extension, TQT_SIGNAL( clicked() ),
- TQT_SLOT( toggleAdvanced()) );
-
- connect( m_buttonEnable, TQT_SIGNAL( clicked() ), TQT_SLOT( enableAll() ));
- connect( m_buttonDisable, TQT_SIGNAL( clicked() ), TQT_SLOT( enableAll() ));
-
- TQString whatsThis = i18n("<qt>You may use the following macros<br>"
- "in the commandline:<br>"
- "<b>%e</b>: for the event name,<br>"
- "<b>%a</b>: for the name of the application that sent the event,<br>"
- "<b>%s</b>: for the notification message,<br>"
- "<b>%w</b>: for the numeric window ID where the event originated,<br>"
- "<b>%i</b>: for the numeric event ID.");
- TQWhatsThis::add( m_execute, whatsThis );
- TQWhatsThis::add( m_executePath, whatsThis );
-
- showAdvanced( false );
-
- slotEventChanged( 0L ); // disable widgets by default
-}
-
-KNotifyWidget::~KNotifyWidget()
-{
- delete d->toolTip;
- delete d;
-}
-
-void KNotifyWidget::toggleAdvanced()
-{
- showAdvanced( m_logToFile->isHidden() );
-}
-
-void KNotifyWidget::showAdvanced( bool show )
-{
- if ( show )
- {
- m_extension->setText( i18n("Advanced <<") );
- TQToolTip::add( m_extension, i18n("Hide advanced options") );
-
- m_logToFile->show();
- m_logfilePath->show();
- m_execute->show();
- m_executePath->show();
- m_messageBox->show();
- m_passivePopup->show();
- m_stderr->show();
- m_taskbar->show();
-
- m_passivePopup->setEnabled( m_messageBox->isChecked() );
- m_actionsBoxLayout->setSpacing( KDialog::spacingHint() );
- }
- else
- {
- m_extension->setText( i18n("Advanced >>") );
- TQToolTip::add( m_extension, i18n("Show advanced options") );
-
- m_logToFile->hide();
- m_logfilePath->hide();
- m_execute->hide();
- m_executePath->hide();
- m_messageBox->hide();
- m_passivePopup->hide();
- m_stderr->hide();
- m_taskbar->hide();
-
- m_actionsBoxLayout->setSpacing( 0 );
- }
-}
-
-Application * KNotifyWidget::addApplicationEvents( const TQString& path )
-{
- kdDebug() << "**** knotify: adding path: " << path << endl;
- TQString relativePath = path;
-
- if ( path.at(0) == '/' && KStandardDirs::exists( path ) )
- relativePath = makeRelative( path );
-
- if ( !relativePath.isEmpty() )
- {
- Application *app = new Application( relativePath );
- m_allApps.append( app );
- return app;
- }
-
- return 0L;
-}
-
-void KNotifyWidget::clear()
-{
- clearVisible();
- m_allApps.clear();
-}
-
-void KNotifyWidget::clearVisible()
-{
- m_visibleApps.clear();
- m_listview->clear();
- slotEventChanged( 0L ); // disable widgets
-}
-
-void KNotifyWidget::showEvent( TQShowEvent *e )
-{
- selectItem( m_listview->firstChild() );
- KNotifyWidgetBase::showEvent( e );
-}
-
-void KNotifyWidget::slotEventChanged( TQListViewItem *item )
-{
- bool on = (item != 0L);
-
- m_actionsBox->setEnabled( on );
- m_controlsBox->setEnabled( on );
-
- if ( !on )
- return;
-
- ListViewItem *lit = static_cast<ListViewItem*>( item );
- updateWidgets( lit );
-}
-
-void KNotifyWidget::updateWidgets( ListViewItem *item )
-{
- bool enable;
- bool checked;
-
- blockSignals( true ); // don't emit changed() signals
-
- const Event& event = item->event();
-
- // sound settings
- m_playButton->setEnabled( !event.soundfile.isEmpty() );
- m_soundPath->setURL( event.soundfile );
- enable = (event.dontShow & KNotifyClient::Sound) == 0;
- checked = enable && !event.soundfile.isEmpty() &&
- (event.presentation & KNotifyClient::Sound);
- m_playSound->setEnabled( enable );
- m_playSound->setChecked( checked );
- m_soundPath->setEnabled( checked );
-
-
- // logfile settings
- m_logfilePath->setURL( event.logfile );
- enable = (event.dontShow & KNotifyClient::Logfile) == 0;
- checked = enable && !event.logfile.isEmpty() &&
- (event.presentation & KNotifyClient::Logfile);
- m_logToFile->setEnabled( enable );
- m_logToFile->setChecked( checked );
- m_logfilePath->setEnabled( checked );
-
-
- // execute program settings
- m_executePath->setURL( event.commandline );
- enable = (event.dontShow & KNotifyClient::Execute) == 0;
- checked = enable && !event.commandline.isEmpty() &&
- (event.presentation & KNotifyClient::Execute);
- m_execute->setEnabled( enable );
- m_execute->setChecked( checked );
- m_executePath->setEnabled( checked );
-
-
- // other settings
- m_messageBox->setChecked(event.presentation & (KNotifyClient::Messagebox | KNotifyClient::PassivePopup));
- enable = (event.dontShow & KNotifyClient::Messagebox) == 0;
- m_messageBox->setEnabled( enable );
-
- m_passivePopup->setChecked(event.presentation & KNotifyClient::PassivePopup);
- enable = (event.dontShow & KNotifyClient::PassivePopup) == 0;
- m_passivePopup->setEnabled( enable );
-
- m_stderr->setChecked( event.presentation & KNotifyClient::Stderr );
- enable = (event.dontShow & KNotifyClient::Stderr) == 0;
- m_stderr->setEnabled( enable );
-
- m_taskbar->setChecked(event.presentation & KNotifyClient::Taskbar);
- enable = (event.dontShow & KNotifyClient::Taskbar) == 0;
- m_taskbar->setEnabled( enable );
-
- updatePixmaps( item );
-
- blockSignals( false );
-}
-
-void KNotifyWidget::updatePixmaps( ListViewItem *item )
-{
- TQPixmap emptyPix;
- Event &event = item->event();
-
- bool doIt = (event.presentation & KNotifyClient::Execute) &&
- !event.commandline.isEmpty();
- item->setPixmap( COL_EXECUTE, doIt ? d->pixmaps[COL_EXECUTE] : emptyPix );
-
- doIt = (event.presentation & KNotifyClient::Sound) &&
- !event.soundfile.isEmpty();
- item->setPixmap( COL_SOUND, doIt ? d->pixmaps[COL_SOUND] : emptyPix );
-
- doIt = (event.presentation & KNotifyClient::Logfile) &&
- !event.logfile.isEmpty();
- item->setPixmap( COL_LOGFILE, doIt ? d->pixmaps[COL_LOGFILE] : emptyPix );
-
- item->setPixmap( COL_MESSAGE,
- (event.presentation &
- (KNotifyClient::Messagebox | KNotifyClient::PassivePopup)) ?
- d->pixmaps[COL_MESSAGE] : emptyPix );
-
- item->setPixmap( COL_STDERR,
- (event.presentation & KNotifyClient::Stderr) ?
- d->pixmaps[COL_STDERR] : emptyPix );
- item->setPixmap( COL_TASKBAR,
- (event.presentation & KNotifyClient::Taskbar) ?
- d->pixmaps[COL_TASKBAR] : emptyPix );
-}
-
-void KNotifyWidget::addVisibleApp( Application *app )
-{
- if ( !app || (m_visibleApps.findRef( app ) != -1) )
- return;
-
- m_visibleApps.append( app );
- addToView( app->eventList() );
-
- TQListViewItem *item = m_listview->selectedItem();
- if ( !item )
- item = m_listview->firstChild();
-
- selectItem( item );
-}
-
-void KNotifyWidget::addToView( const EventList& events )
-{
- ListViewItem *item = 0L;
-
- EventListIterator it( events );
-
- for ( ; it.current(); ++it )
- {
- Event *event = it.current();
- item = new ListViewItem( m_listview, event );
-
- if ( (event->presentation & KNotifyClient::Execute) &&
- !event->commandline.isEmpty() )
- item->setPixmap( COL_EXECUTE, d->pixmaps[COL_EXECUTE] );
- if ( (event->presentation & KNotifyClient::Sound) &&
- !event->soundfile.isEmpty() )
- item->setPixmap( COL_SOUND, d->pixmaps[COL_SOUND] );
- if ( (event->presentation & KNotifyClient::Logfile) &&
- !event->logfile.isEmpty() )
- item->setPixmap( COL_LOGFILE, d->pixmaps[COL_LOGFILE] );
- if ( event->presentation & (KNotifyClient::Messagebox|KNotifyClient::PassivePopup) )
- item->setPixmap( COL_MESSAGE, d->pixmaps[COL_MESSAGE] );
- if ( event->presentation & KNotifyClient::Stderr )
- item->setPixmap( COL_STDERR, d->pixmaps[COL_STDERR] );
- if ( event->presentation & KNotifyClient::Taskbar )
- item->setPixmap( COL_TASKBAR, d->pixmaps[COL_TASKBAR] );
- }
-}
-
-void KNotifyWidget::widgetChanged( TQListViewItem *item,
- int what, bool on, TQWidget *buddy )
-{
- if ( signalsBlocked() )
- return;
-
- if ( buddy )
- buddy->setEnabled( on );
-
- Event &e = static_cast<ListViewItem*>( item )->event();
- if ( on )
- {
- e.presentation |= what;
- if ( buddy )
- buddy->setFocus();
- }
- else
- e.presentation &= ~what;
-
- emit changed( true );
-}
-
-void KNotifyWidget::soundToggled( bool on )
-{
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
- bool doIcon = on && !m_soundPath->url().isEmpty();
- item->setPixmap( COL_SOUND, doIcon ? d->pixmaps[COL_SOUND] : TQPixmap() );
- widgetChanged( item, KNotifyClient::Sound, on, m_soundPath );
-}
-
-void KNotifyWidget::loggingToggled( bool on )
-{
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
- bool doIcon = on && !m_logfilePath->url().isEmpty();
- item->setPixmap(COL_LOGFILE, doIcon ? d->pixmaps[COL_LOGFILE] : TQPixmap());
- widgetChanged( item, KNotifyClient::Logfile, on, m_logfilePath );
-}
-
-void KNotifyWidget::executeToggled( bool on )
-{
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
- bool doIcon = on && !m_executePath->url().isEmpty();
- item->setPixmap(COL_EXECUTE, doIcon ? d->pixmaps[COL_EXECUTE] : TQPixmap());
- widgetChanged( item, KNotifyClient::Execute, on, m_executePath );
-}
-
-void KNotifyWidget::messageBoxChanged()
-{
- if ( signalsBlocked() )
- return;
-
- m_passivePopup->setEnabled( m_messageBox->isChecked() );
-
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
-
- bool on = m_passivePopup->isEnabled();
- item->setPixmap( COL_MESSAGE, on ? d->pixmaps[COL_MESSAGE] : TQPixmap() );
-
- Event &e = static_cast<ListViewItem*>( item )->event();
-
- if ( m_messageBox->isChecked() ) {
- if ( m_passivePopup->isChecked() ) {
- e.presentation |= KNotifyClient::PassivePopup;
- e.presentation &= ~KNotifyClient::Messagebox;
- }
- else {
- e.presentation &= ~KNotifyClient::PassivePopup;
- e.presentation |= KNotifyClient::Messagebox;
- }
- }
- else {
- e.presentation &= ~KNotifyClient::Messagebox;
- e.presentation &= ~KNotifyClient::PassivePopup;
- }
-
- emit changed( true );
-}
-
-void KNotifyWidget::stderrToggled( bool on )
-{
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
- item->setPixmap( COL_STDERR, on ? d->pixmaps[COL_STDERR] : TQPixmap() );
- widgetChanged( item, KNotifyClient::Stderr, on );
-}
-
-void KNotifyWidget::taskbarToggled( bool on )
-{
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
- item->setPixmap( COL_TASKBAR, on ? d->pixmaps[COL_TASKBAR] : TQPixmap() );
- widgetChanged( item, KNotifyClient::Taskbar, on );
-}
-
-void KNotifyWidget::soundFileChanged( const TQString& text )
-{
- if ( signalsBlocked() )
- return;
-
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
-
- m_playButton->setEnabled( !text.isEmpty() );
-
- currentEvent()->soundfile = text;
- bool ok = !text.isEmpty() && m_playSound->isChecked();
- item->setPixmap( COL_SOUND, ok ? d->pixmaps[COL_SOUND] : TQPixmap() );
-
- emit changed( true );
-}
-
-void KNotifyWidget::logfileChanged( const TQString& text )
-{
- if ( signalsBlocked() )
- return;
-
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
-
- currentEvent()->logfile = text;
- bool ok = !text.isEmpty() && m_logToFile->isChecked();
- item->setPixmap( COL_LOGFILE, ok ? d->pixmaps[COL_LOGFILE] : TQPixmap() );
-
- emit changed( true );
-}
-
-void KNotifyWidget::commandlineChanged( const TQString& text )
-{
- if ( signalsBlocked() )
- return;
-
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- return;
-
- currentEvent()->commandline = text;
- bool ok = !text.isEmpty() && m_execute->isChecked();
- item->setPixmap( COL_EXECUTE, ok ? d->pixmaps[COL_EXECUTE] : TQPixmap() );
-
- emit changed( true );
-}
-
-void KNotifyWidget::slotItemClicked( TQListViewItem *item, const TQPoint&,
- int col )
-{
- if ( !item || !item->isSelected() )
- return;
-
- Event *event = currentEvent();
- if ( !event )
- return; // very unlikely, but safety first
-
- bool doShowAdvanced = false;
-
- switch( col )
- {
- case COL_EXECUTE:
- m_execute->toggle();
- m_executePath->setFocus();
- doShowAdvanced = true;
- break;
- case COL_STDERR:
- m_stderr->toggle();
- break;
- case COL_TASKBAR:
- m_taskbar->toggle();
- break;
- case COL_MESSAGE:
- m_passivePopup->setChecked( true ); // default to passive popups
- m_messageBox->toggle();
- break;
- case COL_LOGFILE:
- m_logToFile->toggle();
- m_logfilePath->setFocus();
- doShowAdvanced = true;
- break;
- case COL_SOUND:
- m_playSound->toggle();
- break;
- default: // do nothing
- break;
- }
-
- if ( doShowAdvanced && !m_logToFile->isVisible() )
- {
- showAdvanced( true );
- m_listview->ensureItemVisible( m_listview->currentItem() );
- }
-}
-
-void KNotifyWidget::sort( bool ascending )
-{
- m_listview->setSorting( COL_EVENT, ascending );
- m_listview->sort();
-}
-
-void KNotifyWidget::selectItem( TQListViewItem *item )
-{
- if ( item )
- {
- m_listview->setCurrentItem( item );
- item->setSelected( true );
- slotEventChanged( item );
- }
-}
-
-void KNotifyWidget::resetDefaults( bool ask )
-{
- if ( ask )
- {
- if ( KMessageBox::warningContinueCancel(this,
- i18n("This will cause the notifications "
- "to be reset to their defaults."),
- i18n("Are You Sure?"),
- i18n("&Reset"))
- != KMessageBox::Continue)
- return;
- }
-
- reload( true ); // defaults
- emit changed( true );
-}
-
-void KNotifyWidget::reload( bool revertToDefaults )
-{
- m_listview->clear();
- ApplicationListIterator it( m_visibleApps );
- for ( ; it.current(); ++it )
- {
- it.current()->reloadEvents( revertToDefaults );
- addToView( it.current()->eventList() );
- }
-
- m_listview->sort();
- selectItem( m_listview->firstChild() );
-}
-
-void KNotifyWidget::save()
-{
- kdDebug() << "save\n";
-
- ApplicationListIterator it( m_allApps );
- while ( it.current() )
- {
- (*it)->save();
- ++it;
- }
-
- if ( kapp )
- {
- if ( !kapp->dcopClient()->isAttached() )
- kapp->dcopClient()->attach();
- kapp->dcopClient()->send("knotify", "", "reconfigure()", TQString(""));
- }
-
- emit changed( false );
-}
-
-// returns e.g. "twin/eventsrc" from a given path
-// "/opt/trinity/share/apps/twin/eventsrc"
-TQString KNotifyWidget::makeRelative( const TQString& fullPath )
-{
- int slash = fullPath.findRev( '/' ) - 1;
- slash = fullPath.findRev( '/', slash );
-
- if ( slash < 0 )
- return TQString::null;
-
- return fullPath.mid( slash+1 );
-}
-
-Event * KNotifyWidget::currentEvent()
-{
- TQListViewItem *current = m_listview->currentItem();
- if ( !current )
- return 0L;
-
- return &static_cast<ListViewItem*>( current )->event();
-}
-
-void KNotifyWidget::openSoundDialog( KURLRequester *requester )
-{
- // only need to init this once
- requester->disconnect( TQT_SIGNAL( openFileDialog( KURLRequester * )),
- this, TQT_SLOT( openSoundDialog( KURLRequester * )));
-
- KFileDialog *fileDialog = requester->fileDialog();
- fileDialog->setCaption( i18n("Select Sound File") );
- TQStringList filters;
- filters << "audio/x-wav" << "audio/x-mp3" << "application/ogg"
- << "audio/x-adpcm";
- fileDialog->setMimeFilter( filters );
-
- // find the first "sound"-resource that contains files
- const Application *app = currentEvent()->application();
- TQStringList soundDirs =
- TDEGlobal::dirs()->findDirs("data", app->appName() + "/sounds");
- soundDirs += TDEGlobal::dirs()->resourceDirs( "sound" );
-
- if ( !soundDirs.isEmpty() ) {
- KURL soundURL;
- TQDir dir;
- dir.setFilter( TQDir::Files | TQDir::Readable );
- TQStringList::ConstIterator it = soundDirs.begin();
- while ( it != soundDirs.end() ) {
- dir = *it;
- if ( dir.isReadable() && dir.count() > 2 ) {
- soundURL.setPath( *it );
- fileDialog->setURL( soundURL );
- break;
- }
- ++it;
- }
- }
-}
-
-void KNotifyWidget::openLogDialog( KURLRequester *requester )
-{
- // only need to init this once
- requester->disconnect( TQT_SIGNAL( openFileDialog( KURLRequester * )),
- this, TQT_SLOT( openLogDialog( KURLRequester * )));
-
- KFileDialog *fileDialog = requester->fileDialog();
- fileDialog->setCaption( i18n("Select Log File") );
- TQStringList filters;
- filters << "text/x-log" << "text/plain";
- fileDialog->setMimeFilter( filters );
-}
-
-void KNotifyWidget::openExecDialog( KURLRequester *requester )
-{
- // only need to init this once
- requester->disconnect( TQT_SIGNAL( openFileDialog( KURLRequester * )),
- this, TQT_SLOT( openExecDialog( KURLRequester * )));
-
-
- KFileDialog *fileDialog = requester->fileDialog();
- fileDialog->setCaption( i18n("Select File to Execute") );
- TQStringList filters;
- filters << "application/x-executable" << "application/x-shellscript"
- << "application/x-perl" << "application/x-python";
- fileDialog->setMimeFilter( filters );
-}
-
-void KNotifyWidget::playSound()
-{
- TQString soundPath = m_soundPath->url();
- if (!TDEIO::NetAccess::exists( m_soundPath->url(), true, 0 )) {
- bool foundSound=false;
-
- // find the first "sound"-resource that contains files
- const Application *app = currentEvent()->application();
- TQStringList soundDirs = TDEGlobal::dirs()->findDirs("data", app->appName() + "/sounds");
- soundDirs += TDEGlobal::dirs()->resourceDirs( "sound" );
-
- if ( !soundDirs.isEmpty() ) {
- TQDir dir;
- dir.setFilter( TQDir::Files | TQDir::Readable );
- TQStringList::ConstIterator it = soundDirs.begin();
- while ( it != soundDirs.end() ) {
- dir = *it;
- if ( dir.isReadable() && dir.count() > 2 &&
- TDEIO::NetAccess::exists( *it + m_soundPath->url(), true, 0 )) {
- foundSound=true;
- soundPath = *it + m_soundPath->url();
- break;
- }
- ++it;
- }
- }
- if ( !foundSound ) {
- KMessageBox::sorry(this, i18n("The specified file does not exist." ));
- return;
- }
- }
- KAudioPlayer::play( soundPath );
-}
-
-void KNotifyWidget::enableAll()
-{
- bool enable = (sender() == m_buttonEnable);
- enableAll( SelectionCombo::type(enable ? m_comboEnable : m_comboDisable),
- enable );
-}
-
-void KNotifyWidget::enableAll( int what, bool enable )
-{
- if ( m_listview->childCount() == 0 )
- return;
-
- bool affectAll = m_affectAllApps->isChecked(); // multi-apps mode
-
- ApplicationListIterator appIt( affectAll ? m_allApps : m_visibleApps );
- for ( ; appIt.current(); ++appIt )
- {
- const EventList& events = appIt.current()->eventList();
- EventListIterator it( events );
- for ( ; it.current(); ++it )
- {
- if ( enable )
- it.current()->presentation |= what;
- else
- it.current()->presentation &= ~what;
- }
- }
-
- // now make the listview reflect the changes
- TQListViewItemIterator it( m_listview->firstChild() );
- for ( ; it.current(); ++it )
- {
- ListViewItem *item = static_cast<ListViewItem*>( it.current() );
- updatePixmaps( item );
- }
-
- TQListViewItem *item = m_listview->currentItem();
- if ( !item )
- item = m_listview->firstChild();
- selectItem( item );
-
- emit changed( true );
-}
-
-
-//////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////
-
-
-//
-// path must be "appname/eventsrc", i.e. a relative path
-//
-Application::Application( const TQString &path )
-{
- TQString config_file = path;
- config_file[config_file.find('/')] = '.';
- m_events = 0L;
- config = new TDEConfig(config_file, false, false);
- kc = new TDEConfig(path, true, false, "data");
- kc->setGroup( TQString::fromLatin1("!Global!") );
- m_icon = kc->readEntry(TQString::fromLatin1("IconName"),
- TQString::fromLatin1("misc"));
- m_description = kc->readEntry( TQString::fromLatin1("Comment"),
- i18n("No description available") );
-
- int index = path.find( '/' );
- if ( index >= 0 )
- m_appname = path.left( index );
- else
- kdDebug() << "Cannot determine application name from path: " << path << endl;
-}
-
-Application::~Application()
-{
- delete config;
- delete kc;
- delete m_events;
-}
-
-
-const EventList& Application::eventList()
-{
- if ( !m_events ) {
- m_events = new EventList;
- m_events->setAutoDelete( true );
- reloadEvents();
- }
-
- return *m_events;
-}
-
-
-void Application::save()
-{
- if ( !m_events )
- return;
-
- EventListIterator it( *m_events );
- Event *e;
- while ( (e = it.current()) ) {
- config->setGroup( e->configGroup );
- config->writeEntry( "presentation", e->presentation );
- config->writePathEntry( "soundfile", e->soundfile );
- config->writePathEntry( "logfile", e->logfile );
- config->writePathEntry( "commandline", e->commandline );
-
- ++it;
- }
- config->sync();
-}
-
-
-void Application::reloadEvents( bool revertToDefaults )
-{
- if ( m_events )
- m_events->clear();
- else
- {
- m_events = new EventList;
- m_events->setAutoDelete( true );
- }
-
- Event *e = 0L;
-
- TQString global = TQString::fromLatin1("!Global!");
- TQString default_group = TQString::fromLatin1("<default>");
- TQString name = TQString::fromLatin1("Name");
- TQString comment = TQString::fromLatin1("Comment");
-
- TQStringList conflist = kc->groupList();
- TQStringList::ConstIterator it = conflist.begin();
-
- while ( it != conflist.end() ) {
- if ( (*it) != global && (*it) != default_group ) { // event group
- kc->setGroup( *it );
-
- e = new Event( this );
- e->name = kc->readEntry( name );
- e->description = kc->readEntry( comment );
- e->dontShow = kc->readNumEntry("nopresentation", 0 );
- e->configGroup = *it;
- if ( e->name.isEmpty() && e->description.isEmpty() )
- delete e;
- else { // load the event
- if( !e->name.isEmpty() && e->description.isEmpty() )
- e->description = e->name;
- // default to passive popups over plain messageboxes
- int default_rep = kc->readNumEntry("default_presentation",
- 0 | KNotifyClient::PassivePopup);
- TQString default_logfile = kc->readPathEntry("default_logfile");
- TQString default_soundfile = kc->readPathEntry("default_sound");
- TQString default_commandline = kc->readPathEntry("default_commandline");
-
- config->setGroup(*it);
-
- if ( revertToDefaults )
- {
- e->presentation = default_rep;
- e->logfile = default_logfile;
- e->soundfile = default_soundfile;
- e->commandline = default_commandline;
- }
-
- else
- {
- e->presentation = config->readNumEntry("presentation",
- default_rep);
- e->logfile = config->readPathEntry("logfile",
- default_logfile);
- e->soundfile = config->readPathEntry("soundfile",
- default_soundfile);
- e->commandline = config->readPathEntry("commandline",
- default_commandline);
- }
-
- m_events->append( e );
- }
- }
-
- ++it;
- }
-
- return;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-ListViewItem::ListViewItem( TQListView *view, Event *event )
- : TQListViewItem( view ),
- m_event( event )
-{
- setText( COL_EVENT, event->text() );
-}
-
-int ListViewItem::compare ( TQListViewItem * i, int col, bool ascending ) const
-{
- ListViewItem *item = static_cast<ListViewItem*>( i );
- int myPres = m_event->presentation;
- int otherPres = item->event().presentation;
-
- int action = 0;
-
- switch ( col )
- {
- case COL_EVENT: // use default sorting
- return TQListViewItem::compare( i, col, ascending );
-
- case COL_EXECUTE:
- action = KNotifyClient::Execute;
- break;
- case COL_LOGFILE:
- action = KNotifyClient::Logfile;
- break;
- case COL_MESSAGE:
- action = (KNotifyClient::Messagebox | KNotifyClient::PassivePopup);
- break;
- case COL_SOUND:
- action = KNotifyClient::Sound;
- break;
- case COL_STDERR:
- action = KNotifyClient::Stderr;
- break;
- case COL_TASKBAR:
- action = KNotifyClient::Taskbar;
- break;
- }
-
- if ( (myPres & action) == (otherPres & action) )
- {
- // default sorting by event
- return TQListViewItem::compare( i, COL_EVENT, true );
- }
-
- if ( myPres & action )
- return -1;
- if ( otherPres & action )
- return 1;
-
- return 0;
-}
-
-#include "knotifydialog.moc"
diff --git a/kio/kfile/kpreviewprops.cpp b/kio/kfile/kpreviewprops.cpp
deleted file mode 100644
index 3672f4387..000000000
--- a/kio/kfile/kpreviewprops.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2005 Stephan Binner <binner@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
- */
-
-#include "kpreviewprops.h"
-
-#include <tqlayout.h>
-
-#include <kfilemetapreview.h>
-#include <kglobalsettings.h>
-#include <klocale.h>
-
-class KPreviewPropsPlugin::KPreviewPropsPluginPrivate
-{
-public:
- KPreviewPropsPluginPrivate() {}
- ~KPreviewPropsPluginPrivate() {}
-};
-
-KPreviewPropsPlugin::KPreviewPropsPlugin(KPropertiesDialog* props)
- : KPropsDlgPlugin(props)
-{
- d = new KPreviewPropsPluginPrivate;
-
- if (properties->items().count()>1)
- return;
-
- createLayout();
-}
-
-void KPreviewPropsPlugin::createLayout()
-{
- // let the dialog create the page frame
- TQFrame* topframe = properties->addPage(i18n("P&review"));
- topframe->setFrameStyle(TQFrame::NoFrame);
-
- TQVBoxLayout* tmp = new TQVBoxLayout(topframe, 0, 0);
-
- preview = new KFileMetaPreview(topframe);
-
- tmp->addWidget(preview) ;
- connect( properties, TQT_SIGNAL( aboutToShowPage( TQWidget * ) ), TQT_SLOT( aboutToShowPage( TQWidget* ) ) );
-}
-
-KPreviewPropsPlugin::~KPreviewPropsPlugin()
-{
- delete d;
-}
-
-bool KPreviewPropsPlugin::supports( KFileItemList _items )
-{
- if ( _items.count() != 1)
- return false;
- if( !TDEGlobalSettings::showFilePreview(_items.first()->url()))
- return false;
- KMimeType::Ptr mt = KMimeType::findByURL( _items.first()->url() );
- if ( mt->inherits("inode/directory") || mt->name() == "application/octet-stream" )
- return false;
-
- //TODO Copy everything of KFileMetaPreview::previewProviderFor() ?
-
- return true;
-}
-
-void KPreviewPropsPlugin::aboutToShowPage( TQWidget* widget )
-{
- if ( TQT_TQOBJECT(widget) != TQT_TQOBJECT(preview->parent()) )
- return;
-
- disconnect( properties, TQT_SIGNAL( aboutToShowPage( TQWidget * ) ), this, TQT_SLOT( aboutToShowPage( TQWidget* ) ) );
- preview->showPreview(properties->item()->url());
-}
-
-#include "kpreviewprops.moc"
diff --git a/kio/kfile/kpropertiesdialog.cpp b/kio/kfile/kpropertiesdialog.cpp
deleted file mode 100644
index 0b1f6c05b..000000000
--- a/kio/kfile/kpropertiesdialog.cpp
+++ /dev/null
@@ -1,4170 +0,0 @@
-/* This file is part of the KDE project
-
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
- Copyright (c) 1999, 2000 Preston Brown <pbrown@kde.org>
- Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
- Copyright (c) 2000 David Faure <faure@kde.org>
- Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/*
- * kpropertiesdialog.cpp
- * View/Edit Properties of files, locally or remotely
- *
- * some FilePermissionsPropsPlugin-changes by
- * Henner Zeller <zeller@think.de>
- * some layout management by
- * Bertrand Leconte <B.Leconte@mail.dotcom.fr>
- * the rest of the layout management, bug fixes, adaptation to libkio,
- * template feature by
- * David Faure <faure@kde.org>
- * More layout, cleanups, and fixes by
- * Preston Brown <pbrown@kde.org>
- * Plugin capability, cleanups and port to KDialogBase by
- * Simon Hausmann <hausmann@kde.org>
- * KDesktopPropsPlugin by
- * Waldo Bastian <bastian@kde.org>
- */
-
-#include <config.h>
-extern "C" {
-#include <pwd.h>
-#include <grp.h>
-#include <time.h>
-#include <sys/types.h>
-}
-#include <unistd.h>
-#include <errno.h>
-#include <assert.h>
-#include <algorithm>
-#include <functional>
-
-#include <tqfile.h>
-#include <tqdir.h>
-#include <tqlabel.h>
-#include <tqpushbutton.h>
-#include <tqcheckbox.h>
-#include <tqstrlist.h>
-#include <tqstringlist.h>
-#include <tqtextstream.h>
-#include <tqpainter.h>
-#include <tqlayout.h>
-#include <tqcombobox.h>
-#include <tqgroupbox.h>
-#include <tqwhatsthis.h>
-#include <tqtooltip.h>
-#include <tqstyle.h>
-#include <tqprogressbar.h>
-#include <tqvbox.h>
-#include <tqvaluevector.h>
-
-#ifdef USE_POSIX_ACL
-extern "C" {
-#include <sys/param.h>
-#ifdef HAVE_SYS_MOUNT_H
-#include <sys/mount.h>
-#endif
-#ifdef HAVE_SYS_XATTR_H
-#include <sys/xattr.h>
-#endif
-}
-#endif
-
-#include <kapplication.h>
-#include <kdialog.h>
-#include <kdirsize.h>
-#include <kdirwatch.h>
-#include <kdirnotify_stub.h>
-#include <kdiskfreesp.h>
-#include <kdebug.h>
-#include <kdesktopfile.h>
-#include <kicondialog.h>
-#include <kurl.h>
-#include <kurlrequester.h>
-#include <klocale.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <kstandarddirs.h>
-#include <kio/job.h>
-#include <kio/chmodjob.h>
-#include <kio/renamedlg.h>
-#include <kio/netaccess.h>
-#include <kio/kservicetypefactory.h>
-#include <kfiledialog.h>
-#include <kmimetype.h>
-#include <kmountpoint.h>
-#include <kiconloader.h>
-#include <kmessagebox.h>
-#include <kservice.h>
-#include <kcompletion.h>
-#include <klineedit.h>
-#include <kseparator.h>
-#include <ksqueezedtextlabel.h>
-#include <klibloader.h>
-#include <ktrader.h>
-#include <tdeparts/componentfactory.h>
-#include <kmetaprops.h>
-#include <kpreviewprops.h>
-#include <kprocess.h>
-#include <krun.h>
-#include <klistview.h>
-#include <kacl.h>
-#include "kfilesharedlg.h"
-
-#include "kpropertiesdesktopbase.h"
-#include "kpropertiesdesktopadvbase.h"
-#include "kpropertiesmimetypebase.h"
-#ifdef USE_POSIX_ACL
-#include "kacleditwidget.h"
-#endif
-
-#include "kpropertiesdialog.h"
-
-#ifdef Q_WS_WIN
-# include <win32_utils.h>
-#endif
-
-static TQString nameFromFileName(TQString nameStr)
-{
- if ( nameStr.endsWith(".desktop") )
- nameStr.truncate( nameStr.length() - 8 );
- if ( nameStr.endsWith(".kdelnk") )
- nameStr.truncate( nameStr.length() - 7 );
- // Make it human-readable (%2F => '/', ...)
- nameStr = TDEIO::decodeFileName( nameStr );
- return nameStr;
-}
-
-mode_t KFilePermissionsPropsPlugin::fperm[3][4] = {
- {S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID},
- {S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID},
- {S_IROTH, S_IWOTH, S_IXOTH, S_ISVTX}
- };
-
-class KPropertiesDialog::KPropertiesDialogPrivate
-{
-public:
- KPropertiesDialogPrivate()
- {
- m_aborted = false;
- fileSharePage = 0;
- }
- ~KPropertiesDialogPrivate()
- {
- }
- bool m_aborted:1;
- TQWidget* fileSharePage;
-};
-
-KPropertiesDialog::KPropertiesDialog (KFileItem* item,
- TQWidget* parent, const char* name,
- bool modal, bool autoShow)
- : KDialogBase (KDialogBase::Tabbed, i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(item->url().fileName())),
- KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
- parent, name, modal)
-{
- d = new KPropertiesDialogPrivate;
- assert( item );
- m_items.append( new KFileItem(*item) ); // deep copy
-
- m_singleUrl = item->url();
- assert(!m_singleUrl.isEmpty());
-
- init (modal, autoShow);
-}
-
-KPropertiesDialog::KPropertiesDialog (const TQString& title,
- TQWidget* parent, const char* name, bool modal)
- : KDialogBase (KDialogBase::Tabbed, i18n ("Properties for %1").arg(title),
- KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
- parent, name, modal)
-{
- d = new KPropertiesDialogPrivate;
-
- init (modal, false);
-}
-
-KPropertiesDialog::KPropertiesDialog (KFileItemList _items,
- TQWidget* parent, const char* name,
- bool modal, bool autoShow)
- : KDialogBase (KDialogBase::Tabbed,
- // TODO: replace <never used> with "Properties for 1 item". It's very confusing how it has to be translated otherwise
- // (empty translation before the "\n" is not allowed by msgfmt...)
- _items.count()>1 ? i18n( "<never used>","Properties for %n Selected Items",_items.count()) :
- i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_items.first()->url().fileName())),
- KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
- parent, name, modal)
-{
- d = new KPropertiesDialogPrivate;
-
- assert( !_items.isEmpty() );
- m_singleUrl = _items.first()->url();
- assert(!m_singleUrl.isEmpty());
-
- KFileItemListIterator it ( _items );
- // Deep copy
- for ( ; it.current(); ++it )
- m_items.append( new KFileItem( **it ) );
-
- init (modal, autoShow);
-}
-
-#ifndef KDE_NO_COMPAT
-KPropertiesDialog::KPropertiesDialog (const KURL& _url, mode_t /* _mode is now unused */,
- TQWidget* parent, const char* name,
- bool modal, bool autoShow)
- : KDialogBase (KDialogBase::Tabbed,
- i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_url.fileName())),
- KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
- parent, name, modal),
- m_singleUrl( _url )
-{
- d = new KPropertiesDialogPrivate;
-
- TDEIO::UDSEntry entry;
-
- TDEIO::NetAccess::stat(_url, entry, parent);
-
- m_items.append( new KFileItem( entry, _url ) );
- init (modal, autoShow);
-}
-#endif
-
-KPropertiesDialog::KPropertiesDialog (const KURL& _url,
- TQWidget* parent, const char* name,
- bool modal, bool autoShow)
- : KDialogBase (KDialogBase::Tabbed,
- i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_url.fileName())),
- KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
- parent, name, modal),
- m_singleUrl( _url )
-{
- d = new KPropertiesDialogPrivate;
-
- TDEIO::UDSEntry entry;
-
- TDEIO::NetAccess::stat(_url, entry, parent);
-
- m_items.append( new KFileItem( entry, _url ) );
- init (modal, autoShow);
-}
-
-KPropertiesDialog::KPropertiesDialog (const KURL& _tempUrl, const KURL& _currentDir,
- const TQString& _defaultName,
- TQWidget* parent, const char* name,
- bool modal, bool autoShow)
- : KDialogBase (KDialogBase::Tabbed,
- i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_tempUrl.fileName())),
- KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
- parent, name, modal),
-
- m_singleUrl( _tempUrl ),
- m_defaultName( _defaultName ),
- m_currentDir( _currentDir )
-{
- d = new KPropertiesDialogPrivate;
-
- assert(!m_singleUrl.isEmpty());
-
- // Create the KFileItem for the _template_ file, in order to read from it.
- m_items.append( new KFileItem( KFileItem::Unknown, KFileItem::Unknown, m_singleUrl ) );
- init (modal, autoShow);
-}
-
-bool KPropertiesDialog::showDialog(KFileItem* item, TQWidget* parent,
- const char* name, bool modal)
-{
-#ifdef Q_WS_WIN
- TQString localPath = item->localPath();
- if (!localPath.isEmpty())
- return showWin32FilePropertyDialog(localPath);
-#endif
- new KPropertiesDialog(item, parent, name, modal);
- return true;
-}
-
-bool KPropertiesDialog::showDialog(const KURL& _url, TQWidget* parent,
- const char* name, bool modal)
-{
-#ifdef Q_WS_WIN
- if (_url.isLocalFile())
- return showWin32FilePropertyDialog( _url.path() );
-#endif
- new KPropertiesDialog(_url, parent, name, modal);
- return true;
-}
-
-bool KPropertiesDialog::showDialog(const KFileItemList& _items, TQWidget* parent,
- const char* name, bool modal)
-{
- if (_items.count()==1)
- return KPropertiesDialog::showDialog(_items.getFirst(), parent, name, modal);
- new KPropertiesDialog(_items, parent, name, modal);
- return true;
-}
-
-void KPropertiesDialog::init (bool modal, bool autoShow)
-{
- m_pageList.setAutoDelete( true );
- m_items.setAutoDelete( true );
-
- insertPages();
-
- if (autoShow)
- {
- if (!modal)
- show();
- else
- exec();
- }
-}
-
-void KPropertiesDialog::showFileSharingPage()
-{
- if (d->fileSharePage) {
- showPage( pageIndex( d->fileSharePage));
- }
-}
-
-void KPropertiesDialog::setFileSharingPage(TQWidget* page) {
- d->fileSharePage = page;
-}
-
-
-void KPropertiesDialog::setFileNameReadOnly( bool ro )
-{
- KPropsDlgPlugin *it;
-
- for ( it=m_pageList.first(); it != 0L; it=m_pageList.next() )
- {
- KFilePropsPlugin* plugin = dynamic_cast<KFilePropsPlugin*>(it);
- if ( plugin ) {
- plugin->setFileNameReadOnly( ro );
- break;
- }
- }
-}
-
-void KPropertiesDialog::slotStatResult( TDEIO::Job * )
-{
-}
-
-KPropertiesDialog::~KPropertiesDialog()
-{
- m_pageList.clear();
- delete d;
-}
-
-void KPropertiesDialog::insertPlugin (KPropsDlgPlugin* plugin)
-{
- connect (plugin, TQT_SIGNAL (changed ()),
- plugin, TQT_SLOT (setDirty ()));
-
- m_pageList.append (plugin);
-}
-
-bool KPropertiesDialog::canDisplay( KFileItemList _items )
-{
- // TODO: cache the result of those calls. Currently we parse .desktop files far too many times
- return KFilePropsPlugin::supports( _items ) ||
- KFilePermissionsPropsPlugin::supports( _items ) ||
- KDesktopPropsPlugin::supports( _items ) ||
- KBindingPropsPlugin::supports( _items ) ||
- KURLPropsPlugin::supports( _items ) ||
- KDevicePropsPlugin::supports( _items ) ||
- KFileMetaPropsPlugin::supports( _items ) ||
- KPreviewPropsPlugin::supports( _items );
-}
-
-void KPropertiesDialog::slotOk()
-{
- KPropsDlgPlugin *page;
- d->m_aborted = false;
-
- KFilePropsPlugin * filePropsPlugin = 0L;
- if ( m_pageList.first()->isA("KFilePropsPlugin") )
- filePropsPlugin = static_cast<KFilePropsPlugin *>(m_pageList.first());
-
- // If any page is dirty, then set the main one (KFilePropsPlugin) as
- // dirty too. This is what makes it possible to save changes to a global
- // desktop file into a local one. In other cases, it doesn't hurt.
- for ( page = m_pageList.first(); page != 0L; page = m_pageList.next() )
- if ( page->isDirty() && filePropsPlugin )
- {
- filePropsPlugin->setDirty();
- break;
- }
-
- // Apply the changes in the _normal_ order of the tabs now
- // This is because in case of renaming a file, KFilePropsPlugin will call
- // KPropertiesDialog::rename, so other tab will be ok with whatever order
- // BUT for file copied from templates, we need to do the renaming first !
- for ( page = m_pageList.first(); page != 0L && !d->m_aborted; page = m_pageList.next() )
- if ( page->isDirty() )
- {
- kdDebug( 250 ) << "applying changes for " << page->className() << endl;
- page->applyChanges();
- // applyChanges may change d->m_aborted.
- }
- else
- kdDebug( 250 ) << "skipping page " << page->className() << endl;
-
- if ( !d->m_aborted && filePropsPlugin )
- filePropsPlugin->postApplyChanges();
-
- if ( !d->m_aborted )
- {
- emit applied();
- emit propertiesClosed();
- deleteLater();
- accept();
- } // else, keep dialog open for user to fix the problem.
-}
-
-void KPropertiesDialog::slotCancel()
-{
- emit canceled();
- emit propertiesClosed();
-
- deleteLater();
- done( Rejected );
-}
-
-void KPropertiesDialog::insertPages()
-{
- if (m_items.isEmpty())
- return;
-
- if ( KFilePropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KFilePropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( KFilePermissionsPropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KFilePermissionsPropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( KDesktopPropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KDesktopPropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( KBindingPropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KBindingPropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( KURLPropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KURLPropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( KDevicePropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KDevicePropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( KFileMetaPropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KFileMetaPropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( KPreviewPropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KPreviewPropsPlugin( this );
- insertPlugin (p);
- }
-
- if ( kapp->authorizeKAction("sharefile") &&
- KFileSharePropsPlugin::supports( m_items ) )
- {
- KPropsDlgPlugin *p = new KFileSharePropsPlugin( this );
- insertPlugin (p);
- }
-
- //plugins
-
- if ( m_items.count() != 1 )
- return;
-
- KFileItem *item = m_items.first();
- TQString mimetype = item->mimetype();
-
- if ( mimetype.isEmpty() )
- return;
-
- TQString query = TQString::fromLatin1(
- "('KPropsDlg/Plugin' in ServiceTypes) and "
- "((not exist [X-TDE-Protocol]) or "
- " ([X-TDE-Protocol] == '%1' ) )" ).arg(item->url().protocol());
-
- kdDebug( 250 ) << "trader query: " << query << endl;
- KTrader::OfferList offers = KTrader::self()->query( mimetype, query );
- KTrader::OfferList::ConstIterator it = offers.begin();
- KTrader::OfferList::ConstIterator end = offers.end();
- for (; it != end; ++it )
- {
- KPropsDlgPlugin *plugin = KParts::ComponentFactory
- ::createInstanceFromLibrary<KPropsDlgPlugin>( (*it)->library().local8Bit().data(),
- TQT_TQOBJECT(this),
- (*it)->name().latin1() );
- if ( !plugin )
- continue;
-
- insertPlugin( plugin );
- }
-}
-
-void KPropertiesDialog::updateUrl( const KURL& _newUrl )
-{
- Q_ASSERT( m_items.count() == 1 );
- kdDebug(250) << "KPropertiesDialog::updateUrl (pre)" << _newUrl.url() << endl;
- KURL newUrl = _newUrl;
- emit saveAs(m_singleUrl, newUrl);
- kdDebug(250) << "KPropertiesDialog::updateUrl (post)" << newUrl.url() << endl;
-
- m_singleUrl = newUrl;
- m_items.first()->setURL( newUrl );
- assert(!m_singleUrl.isEmpty());
- // If we have an Desktop page, set it dirty, so that a full file is saved locally
- // Same for a URL page (because of the Name= hack)
- for ( TQPtrListIterator<KPropsDlgPlugin> it(m_pageList); it.current(); ++it )
- if ( it.current()->isA("KExecPropsPlugin") || // KDE4 remove me
- it.current()->isA("KURLPropsPlugin") ||
- it.current()->isA("KDesktopPropsPlugin"))
- {
- //kdDebug(250) << "Setting page dirty" << endl;
- it.current()->setDirty();
- break;
- }
-}
-
-void KPropertiesDialog::rename( const TQString& _name )
-{
- Q_ASSERT( m_items.count() == 1 );
- kdDebug(250) << "KPropertiesDialog::rename " << _name << endl;
- KURL newUrl;
- // if we're creating from a template : use currentdir
- if ( !m_currentDir.isEmpty() )
- {
- newUrl = m_currentDir;
- newUrl.addPath( _name );
- }
- else
- {
- TQString tmpurl = m_singleUrl.url();
- if ( tmpurl.at(tmpurl.length() - 1) == '/')
- // It's a directory, so strip the trailing slash first
- tmpurl.truncate( tmpurl.length() - 1);
- newUrl = tmpurl;
- newUrl.setFileName( _name );
- }
- updateUrl( newUrl );
-}
-
-void KPropertiesDialog::abortApplying()
-{
- d->m_aborted = true;
-}
-
-class KPropsDlgPlugin::KPropsDlgPluginPrivate
-{
-public:
- KPropsDlgPluginPrivate()
- {
- }
- ~KPropsDlgPluginPrivate()
- {
- }
-
- bool m_bDirty;
-};
-
-KPropsDlgPlugin::KPropsDlgPlugin( KPropertiesDialog *_props )
-: TQObject( _props, 0L )
-{
- d = new KPropsDlgPluginPrivate;
- properties = _props;
- fontHeight = 2*properties->fontMetrics().height();
- d->m_bDirty = false;
-}
-
-KPropsDlgPlugin::~KPropsDlgPlugin()
-{
- delete d;
-}
-
-bool KPropsDlgPlugin::isDesktopFile( KFileItem * _item )
-{
- // only local files
- bool isLocal;
- KURL url = _item->mostLocalURL( isLocal );
- if ( !isLocal )
- return false;
-
- // only regular files
- if ( !S_ISREG( _item->mode() ) )
- return false;
-
- TQString t( url.path() );
-
- // only if readable
- FILE *f = fopen( TQFile::encodeName(t), "r" );
- if ( f == 0L )
- return false;
- fclose(f);
-
- // return true if desktop file
- return ( (_item->mimetype() == "application/x-desktop")
- || (_item->mimetype() == "media/builtin-mydocuments")
- || (_item->mimetype() == "media/builtin-mycomputer")
- || (_item->mimetype() == "media/builtin-mynetworkplaces")
- || (_item->mimetype() == "media/builtin-printers")
- || (_item->mimetype() == "media/builtin-trash")
- || (_item->mimetype() == "media/builtin-webbrowser") );
-}
-
-void KPropsDlgPlugin::setDirty( bool b )
-{
- d->m_bDirty = b;
-}
-
-void KPropsDlgPlugin::setDirty()
-{
- d->m_bDirty = true;
-}
-
-bool KPropsDlgPlugin::isDirty() const
-{
- return d->m_bDirty;
-}
-
-void KPropsDlgPlugin::applyChanges()
-{
- kdWarning(250) << "applyChanges() not implemented in page !" << endl;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-class KFilePropsPlugin::KFilePropsPluginPrivate
-{
-public:
- KFilePropsPluginPrivate()
- {
- dirSizeJob = 0L;
- dirSizeUpdateTimer = 0L;
- m_lined = 0;
- m_freeSpaceLabel = 0;
- }
- ~KFilePropsPluginPrivate()
- {
- if ( dirSizeJob )
- dirSizeJob->kill();
- }
-
- KDirSize * dirSizeJob;
- TQTimer *dirSizeUpdateTimer;
- TQFrame *m_frame;
- bool bMultiple;
- bool bIconChanged;
- bool bKDesktopMode;
- bool bDesktopFile;
- TQLabel *m_freeSpaceLabel;
- TQString mimeType;
- TQString oldFileName;
- KLineEdit* m_lined;
-};
-
-KFilePropsPlugin::KFilePropsPlugin( KPropertiesDialog *_props )
- : KPropsDlgPlugin( _props )
-{
- d = new KFilePropsPluginPrivate;
- d->bMultiple = (properties->items().count() > 1);
- d->bIconChanged = false;
- d->bKDesktopMode = (TQCString(tqApp->name()) == "kdesktop"); // nasty heh?
- d->bDesktopFile = KDesktopPropsPlugin::supports(properties->items());
- kdDebug(250) << "KFilePropsPlugin::KFilePropsPlugin bMultiple=" << d->bMultiple << endl;
-
- // We set this data from the first item, and we'll
- // check that the other items match against it, resetting when not.
- bool isLocal;
- KFileItem * item = properties->item();
- KURL url = item->mostLocalURL( isLocal );
- bool isReallyLocal = item->url().isLocalFile();
- bool bDesktopFile = isDesktopFile(item);
- kdDebug() << "url=" << url << " bDesktopFile=" << bDesktopFile << " isLocal=" << isLocal << " isReallyLocal=" << isReallyLocal << endl;
- mode_t mode = item->mode();
- bool hasDirs = item->isDir() && !item->isLink();
- bool hasRoot = url.path() == TQString::fromLatin1("/");
- TQString iconStr = KMimeType::iconForURL(url, mode);
- TQString directory = properties->kurl().directory();
- TQString protocol = properties->kurl().protocol();
- TQString mimeComment = item->mimeComment();
- d->mimeType = item->mimetype();
- bool hasTotalSize;
- TDEIO::filesize_t totalSize = item->size(hasTotalSize);
- TQString magicMimeComment;
- if ( isLocal ) {
- KMimeType::Ptr magicMimeType = KMimeType::findByFileContent( url.path() );
- if ( magicMimeType->name() != KMimeType::defaultMimeType() )
- magicMimeComment = magicMimeType->comment();
- }
-
- // Those things only apply to 'single file' mode
- TQString filename = TQString::null;
- bool isTrash = false;
- bool isDevice = false;
- m_bFromTemplate = false;
-
- // And those only to 'multiple' mode
- uint iDirCount = hasDirs ? 1 : 0;
- uint iFileCount = 1-iDirCount;
-
- d->m_frame = properties->addPage (i18n("&General"));
-
- TQVBoxLayout *vbl = new TQVBoxLayout( d->m_frame, 0,
- KDialog::spacingHint(), "vbl");
- TQGridLayout *grid = new TQGridLayout(0, 3); // unknown rows
- grid->setColStretch(0, 0);
- grid->setColStretch(1, 0);
- grid->setColStretch(2, 1);
- grid->addColSpacing(1, KDialog::spacingHint());
- vbl->addLayout(TQT_TQLAYOUT(grid));
- int curRow = 0;
-
- if ( !d->bMultiple )
- {
- TQString path;
- if ( !m_bFromTemplate ) {
- isTrash = ( properties->kurl().protocol().find( "trash", 0, false)==0 );
- if ( properties->kurl().protocol().find("device", 0, false)==0)
- isDevice = true;
- // Extract the full name, but without file: for local files
- if ( isReallyLocal )
- path = properties->kurl().path();
- else
- path = properties->kurl().prettyURL();
- } else {
- path = properties->currentDir().path(1) + properties->defaultName();
- directory = properties->currentDir().prettyURL();
- }
-
- if (KExecPropsPlugin::supports(properties->items()) || // KDE4 remove me
- d->bDesktopFile ||
- KBindingPropsPlugin::supports(properties->items())) {
- determineRelativePath( path );
- }
-
- // Extract the file name only
- filename = properties->defaultName();
- if ( filename.isEmpty() ) { // no template
- filename = item->name(); // this gives support for UDS_NAME, e.g. for kio_trash or kio_system
- } else {
- m_bFromTemplate = true;
- setDirty(); // to enforce that the copy happens
- }
- d->oldFileName = filename;
-
- // Make it human-readable
- filename = nameFromFileName( filename );
-
- if ( d->bKDesktopMode && d->bDesktopFile ) {
- KDesktopFile config( url.path(), true /* readonly */ );
- if ( config.hasKey( "Name" ) ) {
- filename = config.readName();
- }
- }
-
- oldName = filename;
- }
- else
- {
- // Multiple items: see what they have in common
- KFileItemList items = properties->items();
- KFileItemListIterator it( items );
- for ( ++it /*no need to check the first one again*/ ; it.current(); ++it )
- {
- KURL url = (*it)->url();
- kdDebug(250) << "KFilePropsPlugin::KFilePropsPlugin " << url.prettyURL() << endl;
- // The list of things we check here should match the variables defined
- // at the beginning of this method.
- if ( url.isLocalFile() != isLocal )
- isLocal = false; // not all local
- if ( bDesktopFile && isDesktopFile(*it) != bDesktopFile )
- bDesktopFile = false; // not all desktop files
- if ( (*it)->mode() != mode )
- mode = (mode_t)0;
- if ( KMimeType::iconForURL(url, mode) != iconStr )
- iconStr = "tdemultiple";
- if ( url.directory() != directory )
- directory = TQString::null;
- if ( url.protocol() != protocol )
- protocol = TQString::null;
- if ( !mimeComment.isNull() && (*it)->mimeComment() != mimeComment )
- mimeComment = TQString::null;
- if ( isLocal && !magicMimeComment.isNull() ) {
- KMimeType::Ptr magicMimeType = KMimeType::findByFileContent( url.path() );
- if ( magicMimeType->comment() != magicMimeComment )
- magicMimeComment = TQString::null;
- }
-
- if ( url.path() == TQString::fromLatin1("/") )
- hasRoot = true;
- if ( (*it)->isDir() && !(*it)->isLink() )
- {
- iDirCount++;
- hasDirs = true;
- }
- else
- {
- iFileCount++;
- bool hasSize;
- totalSize += (*it)->size(hasSize);
- hasTotalSize = hasTotalSize || hasSize;
- }
- }
- }
-
- if (!isReallyLocal && !protocol.isEmpty())
- {
- directory += ' ';
- directory += '(';
- directory += protocol;
- directory += ')';
- }
-
- if ( !isDevice && !isTrash && (bDesktopFile || S_ISDIR(mode)) && !d->bMultiple /*not implemented for multiple*/ )
- {
- KIconButton *iconButton = new KIconButton( d->m_frame );
- int bsize = 66 + 2 * iconButton->style().pixelMetric(TQStyle::PM_ButtonMargin);
- iconButton->setFixedSize(bsize, bsize);
- iconButton->setIconSize(48);
- iconButton->setStrictIconSize(false);
- // This works for everything except Device icons on unmounted devices
- // So we have to really open .desktop files
- TQString iconStr = KMimeType::findByURL( url, mode )->icon( url, isLocal );
- if ( bDesktopFile && isLocal )
- {
- KDesktopFile config( url.path(), true );
- config.setDesktopGroup();
- iconStr = config.readEntry( "Icon" );
- if ( config.hasDeviceType() )
- iconButton->setIconType( KIcon::Desktop, KIcon::Device );
- else
- iconButton->setIconType( KIcon::Desktop, KIcon::Application );
- } else
- iconButton->setIconType( KIcon::Desktop, KIcon::Place );
- iconButton->setIcon(iconStr);
- iconArea = iconButton;
- connect( iconButton, TQT_SIGNAL( iconChanged(TQString) ),
- this, TQT_SLOT( slotIconChanged() ) );
- } else {
- TQLabel *iconLabel = new TQLabel( d->m_frame );
- int bsize = 66 + 2 * iconLabel->style().pixelMetric(TQStyle::PM_ButtonMargin);
- iconLabel->setFixedSize(bsize, bsize);
- iconLabel->setPixmap( TDEGlobal::iconLoader()->loadIcon( iconStr, KIcon::Desktop, 48) );
- iconArea = iconLabel;
- }
- grid->addWidget(iconArea, curRow, 0, Qt::AlignLeft);
-
- if (d->bMultiple || isTrash || isDevice || hasRoot)
- {
- TQLabel *lab = new TQLabel(d->m_frame );
- if ( d->bMultiple )
- lab->setText( TDEIO::itemsSummaryString( iFileCount + iDirCount, iFileCount, iDirCount, 0, false ) );
- else
- lab->setText( filename );
- nameArea = lab;
- } else
- {
- d->m_lined = new KLineEdit( d->m_frame );
- d->m_lined->setText(filename);
- nameArea = d->m_lined;
- d->m_lined->setFocus();
-
- // Enhanced rename: Don't highlight the file extension.
- TQString pattern;
- KServiceTypeFactory::self()->findFromPattern( filename, &pattern );
- if (!pattern.isEmpty() && pattern.at(0)=='*' && pattern.find('*',1)==-1)
- d->m_lined->setSelection(0, filename.length()-pattern.stripWhiteSpace().length()+1);
- else
- {
- int lastDot = filename.findRev('.');
- if (lastDot > 0)
- d->m_lined->setSelection(0, lastDot);
- }
-
- connect( d->m_lined, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SLOT( nameFileChanged(const TQString & ) ) );
- }
-
- grid->addWidget(nameArea, curRow++, 2);
-
- KSeparator* sep = new KSeparator( KSeparator::HLine, d->m_frame);
- grid->addMultiCellWidget(sep, curRow, curRow, 0, 2);
- ++curRow;
-
- TQLabel *l;
- if ( !mimeComment.isEmpty() && !isDevice && !isTrash)
- {
- l = new TQLabel(i18n("Type:"), d->m_frame );
-
- grid->addWidget(l, curRow, 0);
-
- TQHBox *box = new TQHBox(d->m_frame);
- box->setSpacing(20);
- l = new TQLabel(mimeComment, box );
-
-#ifdef Q_WS_X11
- //TODO: wrap for win32 or mac?
- TQPushButton *button = new TQPushButton(box);
-
- TQIconSet iconSet = SmallIconSet(TQString::fromLatin1("configure"));
- TQPixmap pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
- button->setIconSet( iconSet );
- button->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
- if ( d->mimeType == KMimeType::defaultMimeType() )
- TQToolTip::add(button, i18n("Create new file type"));
- else
- TQToolTip::add(button, i18n("Edit file type"));
-
- connect( button, TQT_SIGNAL( clicked() ), TQT_SLOT( slotEditFileType() ));
-
- if (!kapp->authorizeKAction("editfiletype"))
- button->hide();
-#endif
-
- grid->addWidget(box, curRow++, 2);
- }
-
- if ( !magicMimeComment.isEmpty() && magicMimeComment != mimeComment )
- {
- l = new TQLabel(i18n("Contents:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- l = new TQLabel(magicMimeComment, d->m_frame );
- grid->addWidget(l, curRow++, 2);
- }
-
- if ( !directory.isEmpty() )
- {
- l = new TQLabel( i18n("Location:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- l = new KSqueezedTextLabel( d->m_frame );
- l->setText( directory );
- grid->addWidget(l, curRow++, 2);
- }
-
- if( hasDirs || hasTotalSize ) {
- l = new TQLabel(i18n("Size:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- m_sizeLabel = new TQLabel( d->m_frame );
- grid->addWidget( m_sizeLabel, curRow++, 2 );
- } else {
- m_sizeLabel = 0;
- }
-
- if ( !hasDirs ) // Only files [and symlinks]
- {
- if(hasTotalSize) {
- m_sizeLabel->setText(TDEIO::convertSizeWithBytes(totalSize));
- }
-
- m_sizeDetermineButton = 0L;
- m_sizeStopButton = 0L;
- }
- else // Directory
- {
- TQHBoxLayout * sizelay = new TQHBoxLayout(KDialog::spacingHint());
- grid->addLayout( sizelay, curRow++, 2 );
-
- // buttons
- m_sizeDetermineButton = new TQPushButton( i18n("Calculate"), d->m_frame );
- m_sizeStopButton = new TQPushButton( i18n("Stop"), d->m_frame );
- connect( m_sizeDetermineButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotSizeDetermine() ) );
- connect( m_sizeStopButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotSizeStop() ) );
- sizelay->addWidget(m_sizeDetermineButton, 0);
- sizelay->addWidget(m_sizeStopButton, 0);
- sizelay->addStretch(10); // so that the buttons don't grow horizontally
-
- // auto-launch for local dirs only, and not for '/'
- if ( isLocal && !hasRoot )
- {
- m_sizeDetermineButton->setText( i18n("Refresh") );
- slotSizeDetermine();
- }
- else
- m_sizeStopButton->setEnabled( false );
- }
-
- if (!d->bMultiple && item->isLink()) {
- l = new TQLabel(i18n("Points to:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- l = new KSqueezedTextLabel(item->linkDest(), d->m_frame );
- grid->addWidget(l, curRow++, 2);
- }
-
- if (!d->bMultiple) // Dates for multiple don't make much sense...
- {
- TQDateTime dt;
- bool hasTime;
- time_t tim = item->time(TDEIO::UDS_CREATION_TIME, hasTime);
- if ( hasTime )
- {
- l = new TQLabel(i18n("Created:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- dt.setTime_t( tim );
- l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
- grid->addWidget(l, curRow++, 2);
- }
-
- tim = item->time(TDEIO::UDS_MODIFICATION_TIME, hasTime);
- if ( hasTime )
- {
- l = new TQLabel(i18n("Modified:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- dt.setTime_t( tim );
- l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
- grid->addWidget(l, curRow++, 2);
- }
-
- tim = item->time(TDEIO::UDS_ACCESS_TIME, hasTime);
- if ( hasTime )
- {
- l = new TQLabel(i18n("Accessed:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- dt.setTime_t( tim );
- l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
- grid->addWidget(l, curRow++, 2);
- }
- }
-
- if ( isLocal && hasDirs ) // only for directories
- {
- sep = new KSeparator( KSeparator::HLine, d->m_frame);
- grid->addMultiCellWidget(sep, curRow, curRow, 0, 2);
- ++curRow;
-
- TQString mountPoint = TDEIO::findPathMountPoint( url.path() );
-
- if (mountPoint != "/")
- {
- l = new TQLabel(i18n("Mounted on:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- l = new KSqueezedTextLabel( mountPoint, d->m_frame );
- grid->addWidget( l, curRow++, 2 );
- }
-
- l = new TQLabel(i18n("Free disk space:"), d->m_frame );
- grid->addWidget(l, curRow, 0);
-
- d->m_freeSpaceLabel = new TQLabel( d->m_frame );
- grid->addWidget( d->m_freeSpaceLabel, curRow++, 2 );
-
- KDiskFreeSp * job = new KDiskFreeSp;
- connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
- const unsigned long&, const TQString& ) ),
- this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
- const unsigned long&, const TQString& ) ) );
- job->readDF( mountPoint );
- }
-
- vbl->addStretch(1);
-}
-
-// TQString KFilePropsPlugin::tabName () const
-// {
-// return i18n ("&General");
-// }
-
-void KFilePropsPlugin::setFileNameReadOnly( bool ro )
-{
- if ( d->m_lined )
- {
- d->m_lined->setReadOnly( ro );
- if (ro)
- {
- // Don't put the initial focus on the line edit when it is ro
- TQPushButton *button = properties->actionButton(KDialogBase::Ok);
- if (button)
- button->setFocus();
- }
- }
-}
-
-void KFilePropsPlugin::slotEditFileType()
-{
-#ifdef Q_WS_X11
- TQString mime;
- if ( d->mimeType == KMimeType::defaultMimeType() ) {
- int pos = d->oldFileName.findRev( '.' );
- if ( pos != -1 )
- mime = "*" + d->oldFileName.mid(pos);
- else
- mime = "*";
- }
- else
- mime = d->mimeType;
- //TODO: wrap for win32 or mac?
- TQString keditfiletype = TQString::fromLatin1("keditfiletype");
- KRun::runCommand( keditfiletype
- + " --parent " + TQString::number( (ulong)properties->topLevelWidget()->winId())
- + " " + TDEProcess::quote(mime),
- keditfiletype, keditfiletype /*unused*/);
-#endif
-}
-
-void KFilePropsPlugin::slotIconChanged()
-{
- d->bIconChanged = true;
- emit changed();
-}
-
-void KFilePropsPlugin::nameFileChanged(const TQString &text )
-{
- properties->enableButtonOK(!text.isEmpty());
- emit changed();
-}
-
-void KFilePropsPlugin::determineRelativePath( const TQString & path )
-{
- // now let's make it relative
- TQStringList dirs;
- if (KBindingPropsPlugin::supports(properties->items()))
- {
- m_sRelativePath =TDEGlobal::dirs()->relativeLocation("mime", path);
- if (m_sRelativePath.startsWith("/"))
- m_sRelativePath = TQString::null;
- }
- else
- {
- m_sRelativePath =TDEGlobal::dirs()->relativeLocation("apps", path);
- if (m_sRelativePath.startsWith("/"))
- {
- m_sRelativePath =TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path);
- if (m_sRelativePath.startsWith("/"))
- m_sRelativePath = TQString::null;
- else
- m_sRelativePath = path;
- }
- }
- if ( m_sRelativePath.isEmpty() )
- {
- if (KBindingPropsPlugin::supports(properties->items()))
- kdWarning(250) << "Warning : editing a mimetype file out of the mimetype dirs!" << endl;
- }
-}
-
-void KFilePropsPlugin::slotFoundMountPoint( const TQString&,
- unsigned long kBSize,
- unsigned long /*kBUsed*/,
- unsigned long kBAvail )
-{
- d->m_freeSpaceLabel->setText(
- // xgettext:no-c-format -- Don't warn about translating the %1 out of %2 part.
- i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
- .arg(TDEIO::convertSizeFromKB(kBAvail))
- .arg(TDEIO::convertSizeFromKB(kBSize))
- .arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
-}
-
-// attention: copy&paste below, due to compiler bug
-// it doesn't like those unsigned long parameters -- unsigned long& are ok :-/
-void KFilePropsPlugin::slotFoundMountPoint( const unsigned long& kBSize,
- const unsigned long& /*kBUsed*/,
- const unsigned long& kBAvail,
- const TQString& )
-{
- d->m_freeSpaceLabel->setText(
- // xgettext:no-c-format -- Don't warn about translating the %1 out of %2 part.
- i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
- .arg(TDEIO::convertSizeFromKB(kBAvail))
- .arg(TDEIO::convertSizeFromKB(kBSize))
- .arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
-}
-
-void KFilePropsPlugin::slotDirSizeUpdate()
-{
- TDEIO::filesize_t totalSize = d->dirSizeJob->totalSize();
- TDEIO::filesize_t totalFiles = d->dirSizeJob->totalFiles();
- TDEIO::filesize_t totalSubdirs = d->dirSizeJob->totalSubdirs();
- m_sizeLabel->setText( i18n("Calculating... %1 (%2)\n%3, %4")
- .arg(TDEIO::convertSize(totalSize))
- .arg(TDEGlobal::locale()->formatNumber(totalSize, 0))
- .arg(i18n("1 file","%n files",totalFiles))
- .arg(i18n("1 sub-folder","%n sub-folders",totalSubdirs)));
-}
-
-void KFilePropsPlugin::slotDirSizeFinished( TDEIO::Job * job )
-{
- if (job->error())
- m_sizeLabel->setText( job->errorString() );
- else
- {
- TDEIO::filesize_t totalSize = static_cast<KDirSize*>(job)->totalSize();
- TDEIO::filesize_t totalFiles = static_cast<KDirSize*>(job)->totalFiles();
- TDEIO::filesize_t totalSubdirs = static_cast<KDirSize*>(job)->totalSubdirs();
- m_sizeLabel->setText( TQString::fromLatin1("%1 (%2)\n%3, %4")
- .arg(TDEIO::convertSize(totalSize))
- .arg(TDEGlobal::locale()->formatNumber(totalSize, 0))
- .arg(i18n("1 file","%n files",totalFiles))
- .arg(i18n("1 sub-folder","%n sub-folders",totalSubdirs)));
- }
- m_sizeStopButton->setEnabled(false);
- // just in case you change something and try again :)
- m_sizeDetermineButton->setText( i18n("Refresh") );
- m_sizeDetermineButton->setEnabled(true);
- d->dirSizeJob = 0L;
- delete d->dirSizeUpdateTimer;
- d->dirSizeUpdateTimer = 0L;
-}
-
-void KFilePropsPlugin::slotSizeDetermine()
-{
- m_sizeLabel->setText( i18n("Calculating...") );
- kdDebug(250) << " KFilePropsPlugin::slotSizeDetermine() properties->item()=" << properties->item() << endl;
- kdDebug(250) << " URL=" << properties->item()->url().url() << endl;
- d->dirSizeJob = KDirSize::dirSizeJob( properties->items() );
- d->dirSizeUpdateTimer = new TQTimer(this);
- connect( d->dirSizeUpdateTimer, TQT_SIGNAL( timeout() ),
- TQT_SLOT( slotDirSizeUpdate() ) );
- d->dirSizeUpdateTimer->start(500);
- connect( d->dirSizeJob, TQT_SIGNAL( result( TDEIO::Job * ) ),
- TQT_SLOT( slotDirSizeFinished( TDEIO::Job * ) ) );
- m_sizeStopButton->setEnabled(true);
- m_sizeDetermineButton->setEnabled(false);
-
- // also update the "Free disk space" display
- if ( d->m_freeSpaceLabel )
- {
- bool isLocal;
- KFileItem * item = properties->item();
- KURL url = item->mostLocalURL( isLocal );
- TQString mountPoint = TDEIO::findPathMountPoint( url.path() );
-
- KDiskFreeSp * job = new KDiskFreeSp;
- connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
- const unsigned long&, const TQString& ) ),
- this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
- const unsigned long&, const TQString& ) ) );
- job->readDF( mountPoint );
- }
-}
-
-void KFilePropsPlugin::slotSizeStop()
-{
- if ( d->dirSizeJob )
- {
- m_sizeLabel->setText( i18n("Stopped") );
- d->dirSizeJob->kill();
- d->dirSizeJob = 0;
- }
- if ( d->dirSizeUpdateTimer )
- d->dirSizeUpdateTimer->stop();
-
- m_sizeStopButton->setEnabled(false);
- m_sizeDetermineButton->setEnabled(true);
-}
-
-KFilePropsPlugin::~KFilePropsPlugin()
-{
- delete d;
-}
-
-bool KFilePropsPlugin::supports( KFileItemList /*_items*/ )
-{
- return true;
-}
-
-// Don't do this at home
-void tqt_enter_modal( TQWidget *widget );
-void tqt_leave_modal( TQWidget *widget );
-
-void KFilePropsPlugin::applyChanges()
-{
- if ( d->dirSizeJob )
- slotSizeStop();
-
- kdDebug(250) << "KFilePropsPlugin::applyChanges" << endl;
-
- if (nameArea->inherits(TQLINEEDIT_OBJECT_NAME_STRING))
- {
- TQString n = ((TQLineEdit *) nameArea)->text();
- // Remove trailing spaces (#4345)
- while ( n[n.length()-1].isSpace() )
- n.truncate( n.length() - 1 );
- if ( n.isEmpty() )
- {
- KMessageBox::sorry( properties, i18n("The new file name is empty."));
- properties->abortApplying();
- return;
- }
-
- // Do we need to rename the file ?
- kdDebug(250) << "oldname = " << oldName << endl;
- kdDebug(250) << "newname = " << n << endl;
- if ( oldName != n || m_bFromTemplate ) { // true for any from-template file
- TDEIO::Job * job = 0L;
- KURL oldurl = properties->kurl();
-
- TQString newFileName = TDEIO::encodeFileName(n);
- if (d->bDesktopFile && !newFileName.endsWith(".desktop") && !newFileName.endsWith(".kdelnk"))
- newFileName += ".desktop";
-
- // Tell properties. Warning, this changes the result of properties->kurl() !
- properties->rename( newFileName );
-
- // Update also relative path (for apps and mimetypes)
- if ( !m_sRelativePath.isEmpty() )
- determineRelativePath( properties->kurl().path() );
-
- kdDebug(250) << "New URL = " << properties->kurl().url() << endl;
- kdDebug(250) << "old = " << oldurl.url() << endl;
-
- // Don't remove the template !!
- if ( !m_bFromTemplate ) // (normal renaming)
- job = TDEIO::move( oldurl, properties->kurl() );
- else // Copying a template
- job = TDEIO::copy( oldurl, properties->kurl() );
-
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- TQT_SLOT( slotCopyFinished( TDEIO::Job * ) ) );
- connect( job, TQT_SIGNAL( renamed( TDEIO::Job *, const KURL &, const KURL & ) ),
- TQT_SLOT( slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & ) ) );
- // wait for job
- TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
- tqt_enter_modal(&dummy);
- tqApp->enter_loop();
- tqt_leave_modal(&dummy);
- return;
- }
- properties->updateUrl(properties->kurl());
- // Update also relative path (for apps and mimetypes)
- if ( !m_sRelativePath.isEmpty() )
- determineRelativePath( properties->kurl().path() );
- }
-
- // No job, keep going
- slotCopyFinished( 0L );
-}
-
-void KFilePropsPlugin::slotCopyFinished( TDEIO::Job * job )
-{
- kdDebug(250) << "KFilePropsPlugin::slotCopyFinished" << endl;
- if (job)
- {
- // allow apply() to return
- tqApp->exit_loop();
- if ( job->error() )
- {
- job->showErrorDialog( d->m_frame );
- // Didn't work. Revert the URL to the old one
- properties->updateUrl( static_cast<TDEIO::CopyJob*>(job)->srcURLs().first() );
- properties->abortApplying(); // Don't apply the changes to the wrong file !
- return;
- }
- }
-
- assert( properties->item() );
- assert( !properties->item()->url().isEmpty() );
-
- // Save the file where we can -> usually in ~/.trinity/...
- if (KBindingPropsPlugin::supports(properties->items()) && !m_sRelativePath.isEmpty())
- {
- KURL newURL;
- newURL.setPath( locateLocal("mime", m_sRelativePath) );
- properties->updateUrl( newURL );
- }
- else if (d->bDesktopFile && !m_sRelativePath.isEmpty())
- {
- kdDebug(250) << "KFilePropsPlugin::slotCopyFinished " << m_sRelativePath << endl;
- KURL newURL;
- newURL.setPath( KDesktopFile::locateLocal(m_sRelativePath) );
- kdDebug(250) << "KFilePropsPlugin::slotCopyFinished path=" << newURL.path() << endl;
- properties->updateUrl( newURL );
- }
-
- if ( d->bKDesktopMode && d->bDesktopFile ) {
- // Renamed? Update Name field
- if ( d->oldFileName != properties->kurl().fileName() || m_bFromTemplate ) {
- KDesktopFile config( properties->kurl().path() );
- TQString nameStr = nameFromFileName(properties->kurl().fileName());
- config.writeEntry( "Name", nameStr );
- config.writeEntry( "Name", nameStr, true, false, true );
- }
- }
-}
-
-void KFilePropsPlugin::applyIconChanges()
-{
- KIconButton *iconButton = ::tqqt_cast<KIconButton *>( iconArea );
- if ( !iconButton || !d->bIconChanged )
- return;
- // handle icon changes - only local files (or pseudo-local) for now
- // TODO: Use KTempFile and TDEIO::file_copy with overwrite = true
- KURL url = properties->kurl();
- url = TDEIO::NetAccess::mostLocalURL( url, properties );
- if (url.isLocalFile()) {
- TQString path;
-
- if (S_ISDIR(properties->item()->mode()))
- {
- path = url.path(1) + TQString::fromLatin1(".directory");
- // don't call updateUrl because the other tabs (i.e. permissions)
- // apply to the directory, not the .directory file.
- }
- else
- path = url.path();
-
- // Get the default image
- TQString str = KMimeType::findByURL( url,
- properties->item()->mode(),
- true )->KServiceType::icon();
- // Is it another one than the default ?
- TQString sIcon;
- if ( str != iconButton->icon() )
- sIcon = iconButton->icon();
- // (otherwise write empty value)
-
- kdDebug(250) << "**" << path << "**" << endl;
- TQFile f( path );
-
- // If default icon and no .directory file -> don't create one
- if ( !sIcon.isEmpty() || f.exists() )
- {
- if ( !f.open( IO_ReadWrite ) ) {
- KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not "
- "have sufficient access to write to <b>%1</b>.</qt>").arg(path));
- return;
- }
- f.close();
-
- KDesktopFile cfg(path);
- kdDebug(250) << "sIcon = " << (sIcon) << endl;
- kdDebug(250) << "str = " << (str) << endl;
- cfg.writeEntry( "Icon", sIcon );
- cfg.sync();
- }
- }
-}
-
-void KFilePropsPlugin::slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & newUrl )
-{
- // This is called in case of an existing local file during the copy/move operation,
- // if the user chooses Rename.
- properties->updateUrl( newUrl );
-}
-
-void KFilePropsPlugin::postApplyChanges()
-{
- // Save the icon only after applying the permissions changes (#46192)
- applyIconChanges();
-
- KURL::List lst;
- KFileItemList items = properties->items();
- for ( KFileItemListIterator it( items ); it.current(); ++it )
- lst.append((*it)->url());
- KDirNotify_stub allDirNotify("*", "KDirNotify*");
- allDirNotify.FilesChanged( lst );
-}
-
-class KFilePermissionsPropsPlugin::KFilePermissionsPropsPluginPrivate
-{
-public:
- KFilePermissionsPropsPluginPrivate()
- {
- }
- ~KFilePermissionsPropsPluginPrivate()
- {
- }
-
- TQFrame *m_frame;
- TQCheckBox *cbRecursive;
- TQLabel *explanationLabel;
- TQComboBox *ownerPermCombo, *groupPermCombo, *othersPermCombo;
- TQCheckBox *extraCheckbox;
- mode_t partialPermissions;
- KFilePermissionsPropsPlugin::PermissionsMode pmode;
- bool canChangePermissions;
- bool isIrregular;
- bool hasExtendedACL;
- KACL extendedACL;
- KACL defaultACL;
- bool fileSystemSupportsACLs;
-};
-
-#define UniOwner (S_IRUSR|S_IWUSR|S_IXUSR)
-#define UniGroup (S_IRGRP|S_IWGRP|S_IXGRP)
-#define UniOthers (S_IROTH|S_IWOTH|S_IXOTH)
-#define UniRead (S_IRUSR|S_IRGRP|S_IROTH)
-#define UniWrite (S_IWUSR|S_IWGRP|S_IWOTH)
-#define UniExec (S_IXUSR|S_IXGRP|S_IXOTH)
-#define UniSpecial (S_ISUID|S_ISGID|S_ISVTX)
-
-// synced with PermissionsTarget
-const mode_t KFilePermissionsPropsPlugin::permissionsMasks[3] = {UniOwner, UniGroup, UniOthers};
-const mode_t KFilePermissionsPropsPlugin::standardPermissions[4] = { 0, UniRead, UniRead|UniWrite, (mode_t)-1 };
-
-// synced with PermissionsMode and standardPermissions
-const char *KFilePermissionsPropsPlugin::permissionsTexts[4][4] = {
- { I18N_NOOP("Forbidden"),
- I18N_NOOP("Can Read"),
- I18N_NOOP("Can Read & Write"),
- 0 },
- { I18N_NOOP("Forbidden"),
- I18N_NOOP("Can View Content"),
- I18N_NOOP("Can View & Modify Content"),
- 0 },
- { 0, 0, 0, 0}, // no texts for links
- { I18N_NOOP("Forbidden"),
- I18N_NOOP("Can View Content & Read"),
- I18N_NOOP("Can View/Read & Modify/Write"),
- 0 }
-};
-
-
-KFilePermissionsPropsPlugin::KFilePermissionsPropsPlugin( KPropertiesDialog *_props )
- : KPropsDlgPlugin( _props )
-{
- d = new KFilePermissionsPropsPluginPrivate;
- d->cbRecursive = 0L;
- grpCombo = 0L; grpEdit = 0;
- usrEdit = 0L;
- TQString path = properties->kurl().path(-1);
- TQString fname = properties->kurl().fileName();
- bool isLocal = properties->kurl().isLocalFile();
- bool isTrash = ( properties->kurl().protocol().find("trash", 0, false)==0 );
- bool IamRoot = (geteuid() == 0);
-
- KFileItem * item = properties->item();
- bool isLink = item->isLink();
- bool isDir = item->isDir(); // all dirs
- bool hasDir = item->isDir(); // at least one dir
- permissions = item->permissions(); // common permissions to all files
- d->partialPermissions = permissions; // permissions that only some files have (at first we take everything)
- d->isIrregular = isIrregular(permissions, isDir, isLink);
- strOwner = item->user();
- strGroup = item->group();
- d->hasExtendedACL = item->ACL().isExtended() || item->defaultACL().isValid();
- d->extendedACL = item->ACL();
- d->defaultACL = item->defaultACL();
- d->fileSystemSupportsACLs = false;
-
- if ( properties->items().count() > 1 )
- {
- // Multiple items: see what they have in common
- KFileItemList items = properties->items();
- KFileItemListIterator it( items );
- for ( ++it /*no need to check the first one again*/ ; it.current(); ++it )
- {
- if (!d->isIrregular)
- d->isIrregular |= isIrregular((*it)->permissions(),
- (*it)->isDir() == isDir,
- (*it)->isLink() == isLink);
- d->hasExtendedACL = d->hasExtendedACL || (*it)->hasExtendedACL();
- if ( (*it)->isLink() != isLink )
- isLink = false;
- if ( (*it)->isDir() != isDir )
- isDir = false;
- hasDir |= (*it)->isDir();
- if ( (*it)->permissions() != permissions )
- {
- permissions &= (*it)->permissions();
- d->partialPermissions |= (*it)->permissions();
- }
- if ( (*it)->user() != strOwner )
- strOwner = TQString::null;
- if ( (*it)->group() != strGroup )
- strGroup = TQString::null;
- }
- }
-
- if (isLink)
- d->pmode = PermissionsOnlyLinks;
- else if (isDir)
- d->pmode = PermissionsOnlyDirs;
- else if (hasDir)
- d->pmode = PermissionsMixed;
- else
- d->pmode = PermissionsOnlyFiles;
-
- // keep only what's not in the common permissions
- d->partialPermissions = d->partialPermissions & ~permissions;
-
- bool isMyFile = false;
-
- if (isLocal && !strOwner.isEmpty()) { // local files, and all owned by the same person
- struct passwd *myself = getpwuid( geteuid() );
- if ( myself != 0L )
- {
- isMyFile = (strOwner == TQString::fromLocal8Bit(myself->pw_name));
- } else
- kdWarning() << "I don't exist ?! geteuid=" << geteuid() << endl;
- } else {
- //We don't know, for remote files, if they are ours or not.
- //So we let the user change permissions, and
- //TDEIO::chmod will tell, if he had no right to do it.
- isMyFile = true;
- }
-
- d->canChangePermissions = (isMyFile || IamRoot) && (!isLink);
-
-
- // create GUI
-
- d->m_frame = properties->addPage(i18n("&Permissions"));
-
- TQBoxLayout *box = new TQVBoxLayout( d->m_frame, 0, KDialog::spacingHint() );
-
- TQWidget *l;
- TQLabel *lbl;
- TQGroupBox *gb;
- TQGridLayout *gl;
- TQPushButton* pbAdvancedPerm = 0;
-
- /* Group: Access Permissions */
- gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Access Permissions"), d->m_frame );
- gb->layout()->setSpacing(KDialog::spacingHint());
- gb->layout()->setMargin(KDialog::marginHint());
- box->addWidget (gb);
-
- gl = new TQGridLayout (gb->layout(), 7, 2);
- gl->setColStretch(1, 1);
-
- l = d->explanationLabel = new TQLabel( "", gb );
- if (isLink)
- d->explanationLabel->setText(i18n("This file is a link and does not have permissions.",
- "All files are links and do not have permissions.",
- properties->items().count()));
- else if (!d->canChangePermissions)
- d->explanationLabel->setText(i18n("Only the owner can change permissions."));
- gl->addMultiCellWidget(l, 0, 0, 0, 1);
-
- lbl = new TQLabel( i18n("O&wner:"), gb);
- gl->addWidget(lbl, 1, 0);
- l = d->ownerPermCombo = new TQComboBox(gb);
- lbl->setBuddy(l);
- gl->addWidget(l, 1, 1);
- connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
- TQWhatsThis::add(l, i18n("Specifies the actions that the owner is allowed to do."));
-
- lbl = new TQLabel( i18n("Gro&up:"), gb);
- gl->addWidget(lbl, 2, 0);
- l = d->groupPermCombo = new TQComboBox(gb);
- lbl->setBuddy(l);
- gl->addWidget(l, 2, 1);
- connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
- TQWhatsThis::add(l, i18n("Specifies the actions that the members of the group are allowed to do."));
-
- lbl = new TQLabel( i18n("O&thers:"), gb);
- gl->addWidget(lbl, 3, 0);
- l = d->othersPermCombo = new TQComboBox(gb);
- lbl->setBuddy(l);
- gl->addWidget(l, 3, 1);
- connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
- TQWhatsThis::add(l, i18n("Specifies the actions that all users, who are neither "
- "owner nor in the group, are allowed to do."));
-
- if (!isLink) {
- l = d->extraCheckbox = new TQCheckBox(hasDir ?
- i18n("Only own&er can rename and delete folder content") :
- i18n("Is &executable"),
- gb );
- connect( d->extraCheckbox, TQT_SIGNAL( clicked() ), this, TQT_SIGNAL( changed() ) );
- gl->addWidget(l, 4, 1);
- TQWhatsThis::add(l, hasDir ? i18n("Enable this option to allow only the folder's owner to "
- "delete or rename the contained files and folders. Other "
- "users can only add new files, which requires the 'Modify "
- "Content' permission.")
- : i18n("Enable this option to mark the file as executable. This only makes "
- "sense for programs and scripts. It is required when you want to "
- "execute them."));
-
- TQLayoutItem *spacer = TQT_TQLAYOUTITEM(new TQSpacerItem(0, 20, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
- gl->addMultiCell(spacer, 5, 5, 0, 1);
-
- pbAdvancedPerm = new TQPushButton(i18n("A&dvanced Permissions"), gb);
- gl->addMultiCellWidget(pbAdvancedPerm, 6, 6, 0, 1, Qt::AlignRight);
- connect(pbAdvancedPerm, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotShowAdvancedPermissions() ));
- }
- else
- d->extraCheckbox = 0;
-
-
- /**** Group: Ownership ****/
- gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Ownership"), d->m_frame );
- gb->layout()->setSpacing(KDialog::spacingHint());
- gb->layout()->setMargin(KDialog::marginHint());
- box->addWidget (gb);
-
- gl = new TQGridLayout (gb->layout(), 4, 3);
- gl->addRowSpacing(0, 10);
-
- /*** Set Owner ***/
- l = new TQLabel( i18n("User:"), gb );
- gl->addWidget (l, 1, 0);
-
- /* GJ: Don't autocomplete more than 1000 users. This is a kind of random
- * value. Huge sites having 10.000+ user have a fair chance of using NIS,
- * (possibly) making this unacceptably slow.
- * OTOH, it is nice to offer this functionality for the standard user.
- */
- int i, maxEntries = 1000;
- struct passwd *user;
- struct group *ge;
-
- /* File owner: For root, offer a KLineEdit with autocompletion.
- * For a user, who can never chown() a file, offer a TQLabel.
- */
- if (IamRoot && isLocal)
- {
- usrEdit = new KLineEdit( gb );
- KCompletion *kcom = usrEdit->completionObject();
- kcom->setOrder(KCompletion::Sorted);
- setpwent();
- for (i=0; ((user = getpwent()) != 0L) && (i < maxEntries); i++)
- kcom->addItem(TQString::fromLatin1(user->pw_name));
- endpwent();
- usrEdit->setCompletionMode((i < maxEntries) ? TDEGlobalSettings::CompletionAuto :
- TDEGlobalSettings::CompletionNone);
- usrEdit->setText(strOwner);
- gl->addWidget(usrEdit, 1, 1);
- connect( usrEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- }
- else
- {
- l = new TQLabel(strOwner, gb);
- gl->addWidget(l, 1, 1);
- }
-
- /*** Set Group ***/
-
- TQStringList groupList;
- TQCString strUser;
- user = getpwuid(geteuid());
- if (user != 0L)
- strUser = user->pw_name;
-
-#ifdef Q_OS_UNIX
- setgrent();
- for (i=0; ((ge = getgrent()) != 0L) && (i < maxEntries); i++)
- {
- if (IamRoot)
- groupList += TQString::fromLatin1(ge->gr_name);
- else
- {
- /* pick the groups to which the user belongs */
- char ** members = ge->gr_mem;
- char * member;
- while ((member = *members) != 0L) {
- if (strUser == member) {
- groupList += TQString::fromLocal8Bit(ge->gr_name);
- break;
- }
- ++members;
- }
- }
- }
- endgrent();
-#endif //Q_OS_UNIX
-
- /* add the effective Group to the list .. */
- ge = getgrgid (getegid());
- if (ge) {
- TQString name = TQString::fromLatin1(ge->gr_name);
- if (name.isEmpty())
- name.setNum(ge->gr_gid);
- if (groupList.find(name) == groupList.end())
- groupList += name;
- }
-
- bool isMyGroup = groupList.contains(strGroup);
-
- /* add the group the file currently belongs to ..
- * .. if its not there already
- */
- if (!isMyGroup)
- groupList += strGroup;
-
- l = new TQLabel( i18n("Group:"), gb );
- gl->addWidget (l, 2, 0);
-
- /* Set group: if possible to change:
- * - Offer a KLineEdit for root, since he can change to any group.
- * - Offer a TQComboBox for a normal user, since he can change to a fixed
- * (small) set of groups only.
- * If not changeable: offer a TQLabel.
- */
- if (IamRoot && isLocal)
- {
- grpEdit = new KLineEdit(gb);
- KCompletion *kcom = new KCompletion;
- kcom->setItems(groupList);
- grpEdit->setCompletionObject(kcom, true);
- grpEdit->setAutoDeleteCompletionObject( true );
- grpEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
- grpEdit->setText(strGroup);
- gl->addWidget(grpEdit, 2, 1);
- connect( grpEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- }
- else if ((groupList.count() > 1) && isMyFile && isLocal)
- {
- grpCombo = new TQComboBox(gb, "combogrouplist");
- grpCombo->insertStringList(groupList);
- grpCombo->setCurrentItem(groupList.findIndex(strGroup));
- gl->addWidget(grpCombo, 2, 1);
- connect( grpCombo, TQT_SIGNAL( activated( int ) ),
- this, TQT_SIGNAL( changed() ) );
- }
- else
- {
- l = new TQLabel(strGroup, gb);
- gl->addWidget(l, 2, 1);
- }
-
- gl->setColStretch(2, 10);
-
- // "Apply recursive" checkbox
- if ( hasDir && !isLink && !isTrash )
- {
- d->cbRecursive = new TQCheckBox( i18n("Apply changes to all subfolders and their contents"), d->m_frame );
- connect( d->cbRecursive, TQT_SIGNAL( clicked() ), this, TQT_SIGNAL( changed() ) );
- box->addWidget( d->cbRecursive );
- }
-
- updateAccessControls();
-
-
- if ( isTrash || !d->canChangePermissions )
- {
- //don't allow to change properties for file into trash
- enableAccessControls(false);
- if ( pbAdvancedPerm && !d->hasExtendedACL )
- pbAdvancedPerm->setEnabled(false);
- }
-
- box->addStretch (10);
-}
-
-#ifdef USE_POSIX_ACL
-static bool fileSystemSupportsACL( const TQCString& pathCString )
-{
- bool fileSystemSupportsACLs = false;
-#ifdef Q_OS_FREEBSD
- struct statfs buf;
- fileSystemSupportsACLs = ( statfs( pathCString.data(), &buf ) == 0 ) && ( buf.f_flags & MNT_ACLS );
-#else
- fileSystemSupportsACLs =
- getxattr( pathCString.data(), "system.posix_acl_access", NULL, 0 ) >= 0
-#ifdef ENODATA
- || (errno == ENODATA)
-#endif
-#ifdef ENOATTR
- || (errno == ENOATTR)
-#endif
- ;
-#endif
- return fileSystemSupportsACLs;
-}
-#endif
-
-
-void KFilePermissionsPropsPlugin::slotShowAdvancedPermissions() {
-
- bool isDir = (d->pmode == PermissionsOnlyDirs) || (d->pmode == PermissionsMixed);
- KDialogBase dlg(properties, 0, true, i18n("Advanced Permissions"),
- KDialogBase::Ok|KDialogBase::Cancel);
-
- TQLabel *l, *cl[3];
- TQGroupBox *gb;
- TQGridLayout *gl;
-
- TQVBox *mainVBox = dlg.makeVBoxMainWidget();
-
- // Group: Access Permissions
- gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Access Permissions"), mainVBox );
- gb->layout()->setSpacing(KDialog::spacingHint());
- gb->layout()->setMargin(KDialog::marginHint());
-
- gl = new TQGridLayout (gb->layout(), 6, 6);
- gl->addRowSpacing(0, 10);
-
- TQValueVector<TQWidget*> theNotSpecials;
-
- l = new TQLabel(i18n("Class"), gb );
- gl->addWidget(l, 1, 0);
- theNotSpecials.append( l );
-
- if (isDir)
- l = new TQLabel( i18n("Show\nEntries"), gb );
- else
- l = new TQLabel( i18n("Read"), gb );
- gl->addWidget (l, 1, 1);
- theNotSpecials.append( l );
- TQString readWhatsThis;
- if (isDir)
- readWhatsThis = i18n("This flag allows viewing the content of the folder.");
- else
- readWhatsThis = i18n("The Read flag allows viewing the content of the file.");
- TQWhatsThis::add(l, readWhatsThis);
-
- if (isDir)
- l = new TQLabel( i18n("Write\nEntries"), gb );
- else
- l = new TQLabel( i18n("Write"), gb );
- gl->addWidget (l, 1, 2);
- theNotSpecials.append( l );
- TQString writeWhatsThis;
- if (isDir)
- writeWhatsThis = i18n("This flag allows adding, renaming and deleting of files. "
- "Note that deleting and renaming can be limited using the Sticky flag.");
- else
- writeWhatsThis = i18n("The Write flag allows modifying the content of the file.");
- TQWhatsThis::add(l, writeWhatsThis);
-
- TQString execWhatsThis;
- if (isDir) {
- l = new TQLabel( i18n("Enter folder", "Enter"), gb );
- execWhatsThis = i18n("Enable this flag to allow entering the folder.");
- }
- else {
- l = new TQLabel( i18n("Exec"), gb );
- execWhatsThis = i18n("Enable this flag to allow executing the file as a program.");
- }
- TQWhatsThis::add(l, execWhatsThis);
- theNotSpecials.append( l );
- // GJ: Add space between normal and special modes
- TQSize size = l->sizeHint();
- size.setWidth(size.width() + 15);
- l->setFixedSize(size);
- gl->addWidget (l, 1, 3);
-
- l = new TQLabel( i18n("Special"), gb );
- gl->addMultiCellWidget(l, 1, 1, 4, 5);
- TQString specialWhatsThis;
- if (isDir)
- specialWhatsThis = i18n("Special flag. Valid for the whole folder, the exact "
- "meaning of the flag can be seen in the right hand column.");
- else
- specialWhatsThis = i18n("Special flag. The exact meaning of the flag can be seen "
- "in the right hand column.");
- TQWhatsThis::add(l, specialWhatsThis);
-
- cl[0] = new TQLabel( i18n("User"), gb );
- gl->addWidget (cl[0], 2, 0);
- theNotSpecials.append( cl[0] );
-
- cl[1] = new TQLabel( i18n("Group"), gb );
- gl->addWidget (cl[1], 3, 0);
- theNotSpecials.append( cl[1] );
-
- cl[2] = new TQLabel( i18n("Others"), gb );
- gl->addWidget (cl[2], 4, 0);
- theNotSpecials.append( cl[2] );
-
- l = new TQLabel(i18n("Set UID"), gb);
- gl->addWidget(l, 2, 5);
- TQString setUidWhatsThis;
- if (isDir)
- setUidWhatsThis = i18n("If this flag is set, the owner of this folder will be "
- "the owner of all new files.");
- else
- setUidWhatsThis = i18n("If this file is an executable and the flag is set, it will "
- "be executed with the permissions of the owner.");
- TQWhatsThis::add(l, setUidWhatsThis);
-
- l = new TQLabel(i18n("Set GID"), gb);
- gl->addWidget(l, 3, 5);
- TQString setGidWhatsThis;
- if (isDir)
- setGidWhatsThis = i18n("If this flag is set, the group of this folder will be "
- "set for all new files.");
- else
- setGidWhatsThis = i18n("If this file is an executable and the flag is set, it will "
- "be executed with the permissions of the group.");
- TQWhatsThis::add(l, setGidWhatsThis);
-
- l = new TQLabel(i18n("File permission", "Sticky"), gb);
- gl->addWidget(l, 4, 5);
- TQString stickyWhatsThis;
- if (isDir)
- stickyWhatsThis = i18n("If the Sticky flag is set on a folder, only the owner "
- "and root can delete or rename files. Otherwise everybody "
- "with write permissions can do this.");
- else
- stickyWhatsThis = i18n("The Sticky flag on a file is ignored on Linux, but may "
- "be used on some systems");
- TQWhatsThis::add(l, stickyWhatsThis);
-
- mode_t aPermissions, aPartialPermissions;
- mode_t dummy1, dummy2;
-
- if (!d->isIrregular) {
- switch (d->pmode) {
- case PermissionsOnlyFiles:
- getPermissionMasks(aPartialPermissions,
- dummy1,
- aPermissions,
- dummy2);
- break;
- case PermissionsOnlyDirs:
- case PermissionsMixed:
- getPermissionMasks(dummy1,
- aPartialPermissions,
- dummy2,
- aPermissions);
- break;
- case PermissionsOnlyLinks:
- aPermissions = UniRead | UniWrite | UniExec | UniSpecial;
- aPartialPermissions = 0;
- break;
- }
- }
- else {
- aPermissions = permissions;
- aPartialPermissions = d->partialPermissions;
- }
-
- // Draw Checkboxes
- TQCheckBox *cba[3][4];
- for (int row = 0; row < 3 ; ++row) {
- for (int col = 0; col < 4; ++col) {
- TQCheckBox *cb = new TQCheckBox( gb );
- if ( col != 3 ) theNotSpecials.append( cb );
- cba[row][col] = cb;
- cb->setChecked(aPermissions & fperm[row][col]);
- if ( aPartialPermissions & fperm[row][col] )
- {
- cb->setTristate();
- cb->setNoChange();
- }
- else if (d->cbRecursive && d->cbRecursive->isChecked())
- cb->setTristate();
-
- cb->setEnabled( d->canChangePermissions );
- gl->addWidget (cb, row+2, col+1);
- switch(col) {
- case 0:
- TQWhatsThis::add(cb, readWhatsThis);
- break;
- case 1:
- TQWhatsThis::add(cb, writeWhatsThis);
- break;
- case 2:
- TQWhatsThis::add(cb, execWhatsThis);
- break;
- case 3:
- switch(row) {
- case 0:
- TQWhatsThis::add(cb, setUidWhatsThis);
- break;
- case 1:
- TQWhatsThis::add(cb, setGidWhatsThis);
- break;
- case 2:
- TQWhatsThis::add(cb, stickyWhatsThis);
- break;
- }
- break;
- }
- }
- }
- gl->setColStretch(6, 10);
-
-#ifdef USE_POSIX_ACL
- KACLEditWidget *extendedACLs = 0;
-
- // FIXME make it work with partial entries
- if ( properties->items().count() == 1 ) {
- TQCString pathCString = TQFile::encodeName( properties->item()->url().path() );
- d->fileSystemSupportsACLs = fileSystemSupportsACL( pathCString );
- }
- if ( d->fileSystemSupportsACLs ) {
- std::for_each( theNotSpecials.begin(), theNotSpecials.end(), std::mem_fun( &TQWidget::hide ) );
- extendedACLs = new KACLEditWidget( mainVBox );
- if ( d->extendedACL.isValid() && d->extendedACL.isExtended() )
- extendedACLs->setACL( d->extendedACL );
- else
- extendedACLs->setACL( KACL( aPermissions ) );
-
- if ( d->defaultACL.isValid() )
- extendedACLs->setDefaultACL( d->defaultACL );
-
- if ( properties->items().first()->isDir() )
- extendedACLs->setAllowDefaults( true );
- if ( !d->canChangePermissions )
- extendedACLs->setReadOnly( true );
-
- }
-#endif
- if (dlg.exec() != KDialogBase::Accepted)
- return;
-
- mode_t andPermissions = mode_t(~0);
- mode_t orPermissions = 0;
- for (int row = 0; row < 3; ++row)
- for (int col = 0; col < 4; ++col) {
- switch (cba[row][col]->state())
- {
- case TQCheckBox::On:
- orPermissions |= fperm[row][col];
- //fall through
- case TQCheckBox::Off:
- andPermissions &= ~fperm[row][col];
- break;
- default: // NoChange
- break;
- }
- }
-
- d->isIrregular = false;
- KFileItemList items = properties->items();
- for (KFileItemListIterator it(items); it.current(); ++it) {
- if (isIrregular(((*it)->permissions() & andPermissions) | orPermissions,
- (*it)->isDir(), (*it)->isLink())) {
- d->isIrregular = true;
- break;
- }
- }
-
- permissions = orPermissions;
- d->partialPermissions = andPermissions;
-
-#ifdef USE_POSIX_ACL
- // override with the acls, if present
- if ( extendedACLs ) {
- d->extendedACL = extendedACLs->getACL();
- d->defaultACL = extendedACLs->getDefaultACL();
- d->hasExtendedACL = d->extendedACL.isExtended() || d->defaultACL.isValid();
- permissions = d->extendedACL.basePermissions();
- permissions |= ( andPermissions | orPermissions ) & ( S_ISUID|S_ISGID|S_ISVTX );
- }
-#endif
-
- updateAccessControls();
- emit changed();
-}
-
-// TQString KFilePermissionsPropsPlugin::tabName () const
-// {
-// return i18n ("&Permissions");
-// }
-
-KFilePermissionsPropsPlugin::~KFilePermissionsPropsPlugin()
-{
- delete d;
-}
-
-bool KFilePermissionsPropsPlugin::supports( KFileItemList _items )
-{
- KFileItemList::const_iterator it = _items.constBegin();
- for ( ; it != _items.constEnd(); ++it ) {
- KFileItem *item = *it;
- if( !item->user().isEmpty() || !item->group().isEmpty() )
- return true;
- }
- return false;
-}
-
-// sets a combo box in the Access Control frame
-void KFilePermissionsPropsPlugin::setComboContent(TQComboBox *combo, PermissionsTarget target,
- mode_t permissions, mode_t partial) {
- combo->clear();
- if (d->pmode == PermissionsOnlyLinks) {
- combo->insertItem(i18n("Link"));
- combo->setCurrentItem(0);
- return;
- }
-
- mode_t tMask = permissionsMasks[target];
- int textIndex;
- for (textIndex = 0; standardPermissions[textIndex] != (mode_t)-1; textIndex++)
- if ((standardPermissions[textIndex]&tMask) == (permissions&tMask&(UniRead|UniWrite)))
- break;
- Q_ASSERT(standardPermissions[textIndex] != (mode_t)-1); // must not happen, would be irreglar
-
- for (int i = 0; permissionsTexts[(int)d->pmode][i]; i++)
- combo->insertItem(i18n(permissionsTexts[(int)d->pmode][i]));
-
- if (partial & tMask & ~UniExec) {
- combo->insertItem(i18n("Varying (No Change)"));
- combo->setCurrentItem(3);
- }
- else
- combo->setCurrentItem(textIndex);
-}
-
-// permissions are irregular if they cant be displayed in a combo box.
-bool KFilePermissionsPropsPlugin::isIrregular(mode_t permissions, bool isDir, bool isLink) {
- if (isLink) // links are always ok
- return false;
-
- mode_t p = permissions;
- if (p & (S_ISUID | S_ISGID)) // setuid/setgid -> irregular
- return true;
- if (isDir) {
- p &= ~S_ISVTX; // ignore sticky on dirs
-
- // check supported flag combinations
- mode_t p0 = p & UniOwner;
- if ((p0 != 0) && (p0 != (S_IRUSR | S_IXUSR)) && (p0 != UniOwner))
- return true;
- p0 = p & UniGroup;
- if ((p0 != 0) && (p0 != (S_IRGRP | S_IXGRP)) && (p0 != UniGroup))
- return true;
- p0 = p & UniOthers;
- if ((p0 != 0) && (p0 != (S_IROTH | S_IXOTH)) && (p0 != UniOthers))
- return true;
- return false;
- }
- if (p & S_ISVTX) // sticky on file -> irregular
- return true;
-
- // check supported flag combinations
- mode_t p0 = p & UniOwner;
- bool usrXPossible = !p0; // true if this file could be an executable
- if (p0 & S_IXUSR) {
- if ((p0 == S_IXUSR) || (p0 == (S_IWUSR | S_IXUSR)))
- return true;
- usrXPossible = true;
- }
- else if (p0 == S_IWUSR)
- return true;
-
- p0 = p & UniGroup;
- bool grpXPossible = !p0; // true if this file could be an executable
- if (p0 & S_IXGRP) {
- if ((p0 == S_IXGRP) || (p0 == (S_IWGRP | S_IXGRP)))
- return true;
- grpXPossible = true;
- }
- else if (p0 == S_IWGRP)
- return true;
- if (p0 == 0)
- grpXPossible = true;
-
- p0 = p & UniOthers;
- bool othXPossible = !p0; // true if this file could be an executable
- if (p0 & S_IXOTH) {
- if ((p0 == S_IXOTH) || (p0 == (S_IWOTH | S_IXOTH)))
- return true;
- othXPossible = true;
- }
- else if (p0 == S_IWOTH)
- return true;
-
- // check that there either all targets are executable-compatible, or none
- return (p & UniExec) && !(usrXPossible && grpXPossible && othXPossible);
-}
-
-// enables/disabled the widgets in the Access Control frame
-void KFilePermissionsPropsPlugin::enableAccessControls(bool enable) {
- d->ownerPermCombo->setEnabled(enable);
- d->groupPermCombo->setEnabled(enable);
- d->othersPermCombo->setEnabled(enable);
- if (d->extraCheckbox)
- d->extraCheckbox->setEnabled(enable);
- if ( d->cbRecursive )
- d->cbRecursive->setEnabled(enable);
-}
-
-// updates all widgets in the Access Control frame
-void KFilePermissionsPropsPlugin::updateAccessControls() {
- setComboContent(d->ownerPermCombo, PermissionsOwner,
- permissions, d->partialPermissions);
- setComboContent(d->groupPermCombo, PermissionsGroup,
- permissions, d->partialPermissions);
- setComboContent(d->othersPermCombo, PermissionsOthers,
- permissions, d->partialPermissions);
-
- switch(d->pmode) {
- case PermissionsOnlyLinks:
- enableAccessControls(false);
- break;
- case PermissionsOnlyFiles:
- enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
- if (d->canChangePermissions)
- d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
- i18n("This file uses advanced permissions",
- "These files use advanced permissions.",
- properties->items().count()) : "");
- if (d->partialPermissions & UniExec) {
- d->extraCheckbox->setTristate();
- d->extraCheckbox->setNoChange();
- }
- else {
- d->extraCheckbox->setTristate(false);
- d->extraCheckbox->setChecked(permissions & UniExec);
- }
- break;
- case PermissionsOnlyDirs:
- enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
- // if this is a dir, and we can change permissions, don't dis-allow
- // recursive, we can do that for ACL setting.
- if ( d->cbRecursive )
- d->cbRecursive->setEnabled( d->canChangePermissions && !d->isIrregular );
-
- if (d->canChangePermissions)
- d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
- i18n("This folder uses advanced permissions.",
- "These folders use advanced permissions.",
- properties->items().count()) : "");
- if (d->partialPermissions & S_ISVTX) {
- d->extraCheckbox->setTristate();
- d->extraCheckbox->setNoChange();
- }
- else {
- d->extraCheckbox->setTristate(false);
- d->extraCheckbox->setChecked(permissions & S_ISVTX);
- }
- break;
- case PermissionsMixed:
- enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
- if (d->canChangePermissions)
- d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
- i18n("These files use advanced permissions.") : "");
- break;
- if (d->partialPermissions & S_ISVTX) {
- d->extraCheckbox->setTristate();
- d->extraCheckbox->setNoChange();
- }
- else {
- d->extraCheckbox->setTristate(false);
- d->extraCheckbox->setChecked(permissions & S_ISVTX);
- }
- break;
- }
-}
-
-// gets masks for files and dirs from the Access Control frame widgets
-void KFilePermissionsPropsPlugin::getPermissionMasks(mode_t &andFilePermissions,
- mode_t &andDirPermissions,
- mode_t &orFilePermissions,
- mode_t &orDirPermissions) {
- andFilePermissions = mode_t(~UniSpecial);
- andDirPermissions = mode_t(~(S_ISUID|S_ISGID));
- orFilePermissions = 0;
- orDirPermissions = 0;
- if (d->isIrregular)
- return;
-
- mode_t m = standardPermissions[d->ownerPermCombo->currentItem()];
- if (m != (mode_t) -1) {
- orFilePermissions |= m & UniOwner;
- if ((m & UniOwner) &&
- ((d->pmode == PermissionsMixed) ||
- ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
- andFilePermissions &= ~(S_IRUSR | S_IWUSR);
- else {
- andFilePermissions &= ~(S_IRUSR | S_IWUSR | S_IXUSR);
- if ((m & S_IRUSR) && (d->extraCheckbox->state() == TQButton::On))
- orFilePermissions |= S_IXUSR;
- }
-
- orDirPermissions |= m & UniOwner;
- if (m & S_IRUSR)
- orDirPermissions |= S_IXUSR;
- andDirPermissions &= ~(S_IRUSR | S_IWUSR | S_IXUSR);
- }
-
- m = standardPermissions[d->groupPermCombo->currentItem()];
- if (m != (mode_t) -1) {
- orFilePermissions |= m & UniGroup;
- if ((m & UniGroup) &&
- ((d->pmode == PermissionsMixed) ||
- ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
- andFilePermissions &= ~(S_IRGRP | S_IWGRP);
- else {
- andFilePermissions &= ~(S_IRGRP | S_IWGRP | S_IXGRP);
- if ((m & S_IRGRP) && (d->extraCheckbox->state() == TQButton::On))
- orFilePermissions |= S_IXGRP;
- }
-
- orDirPermissions |= m & UniGroup;
- if (m & S_IRGRP)
- orDirPermissions |= S_IXGRP;
- andDirPermissions &= ~(S_IRGRP | S_IWGRP | S_IXGRP);
- }
-
- m = standardPermissions[d->othersPermCombo->currentItem()];
- if (m != (mode_t) -1) {
- orFilePermissions |= m & UniOthers;
- if ((m & UniOthers) &&
- ((d->pmode == PermissionsMixed) ||
- ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
- andFilePermissions &= ~(S_IROTH | S_IWOTH);
- else {
- andFilePermissions &= ~(S_IROTH | S_IWOTH | S_IXOTH);
- if ((m & S_IROTH) && (d->extraCheckbox->state() == TQButton::On))
- orFilePermissions |= S_IXOTH;
- }
-
- orDirPermissions |= m & UniOthers;
- if (m & S_IROTH)
- orDirPermissions |= S_IXOTH;
- andDirPermissions &= ~(S_IROTH | S_IWOTH | S_IXOTH);
- }
-
- if (((d->pmode == PermissionsMixed) || (d->pmode == PermissionsOnlyDirs)) &&
- (d->extraCheckbox->state() != TQButton::NoChange)) {
- andDirPermissions &= ~S_ISVTX;
- if (d->extraCheckbox->state() == TQButton::On)
- orDirPermissions |= S_ISVTX;
- }
-}
-
-void KFilePermissionsPropsPlugin::applyChanges()
-{
- mode_t orFilePermissions;
- mode_t orDirPermissions;
- mode_t andFilePermissions;
- mode_t andDirPermissions;
-
- if (!d->canChangePermissions)
- return;
-
- if (!d->isIrregular)
- getPermissionMasks(andFilePermissions,
- andDirPermissions,
- orFilePermissions,
- orDirPermissions);
- else {
- orFilePermissions = permissions;
- andFilePermissions = d->partialPermissions;
- orDirPermissions = permissions;
- andDirPermissions = d->partialPermissions;
- }
-
- TQString owner, group;
- if (usrEdit)
- owner = usrEdit->text();
- if (grpEdit)
- group = grpEdit->text();
- else if (grpCombo)
- group = grpCombo->currentText();
-
- if (owner == strOwner)
- owner = TQString::null; // no change
-
- if (group == strGroup)
- group = TQString::null;
-
- bool recursive = d->cbRecursive && d->cbRecursive->isChecked();
- bool permissionChange = false;
-
- KFileItemList files, dirs;
- KFileItemList items = properties->items();
- for (KFileItemListIterator it(items); it.current(); ++it) {
- if ((*it)->isDir()) {
- dirs.append(*it);
- if ((*it)->permissions() != (((*it)->permissions() & andDirPermissions) | orDirPermissions))
- permissionChange = true;
- }
- else if ((*it)->isFile()) {
- files.append(*it);
- if ((*it)->permissions() != (((*it)->permissions() & andFilePermissions) | orFilePermissions))
- permissionChange = true;
- }
- }
-
- const bool ACLChange = ( d->extendedACL != properties->item()->ACL() );
- const bool defaultACLChange = ( d->defaultACL != properties->item()->defaultACL() );
-
- if ( owner.isEmpty() && group.isEmpty() && !recursive
- && !permissionChange && !ACLChange && !defaultACLChange )
- return;
-
- TDEIO::Job * job;
- if (files.count() > 0) {
- job = TDEIO::chmod( files, orFilePermissions, ~andFilePermissions,
- owner, group, false );
- if ( ACLChange && d->fileSystemSupportsACLs )
- job->addMetaData( "ACL_STRING", d->extendedACL.isValid()?d->extendedACL.asString():"ACL_DELETE" );
- if ( defaultACLChange && d->fileSystemSupportsACLs )
- job->addMetaData( "DEFAULT_ACL_STRING", d->defaultACL.isValid()?d->defaultACL.asString():"ACL_DELETE" );
-
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- TQT_SLOT( slotChmodResult( TDEIO::Job * ) ) );
- // Wait for job
- TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
- tqt_enter_modal(&dummy);
- tqApp->enter_loop();
- tqt_leave_modal(&dummy);
- }
- if (dirs.count() > 0) {
- job = TDEIO::chmod( dirs, orDirPermissions, ~andDirPermissions,
- owner, group, recursive );
- if ( ACLChange && d->fileSystemSupportsACLs )
- job->addMetaData( "ACL_STRING", d->extendedACL.isValid()?d->extendedACL.asString():"ACL_DELETE" );
- if ( defaultACLChange && d->fileSystemSupportsACLs )
- job->addMetaData( "DEFAULT_ACL_STRING", d->defaultACL.isValid()?d->defaultACL.asString():"ACL_DELETE" );
-
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- TQT_SLOT( slotChmodResult( TDEIO::Job * ) ) );
- // Wait for job
- TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
- tqt_enter_modal(&dummy);
- tqApp->enter_loop();
- tqt_leave_modal(&dummy);
- }
-}
-
-void KFilePermissionsPropsPlugin::slotChmodResult( TDEIO::Job * job )
-{
- kdDebug(250) << "KFilePermissionsPropsPlugin::slotChmodResult" << endl;
- if (job->error())
- job->showErrorDialog( d->m_frame );
- // allow apply() to return
- tqApp->exit_loop();
-}
-
-
-
-
-class KURLPropsPlugin::KURLPropsPluginPrivate
-{
-public:
- KURLPropsPluginPrivate()
- {
- }
- ~KURLPropsPluginPrivate()
- {
- }
-
- TQFrame *m_frame;
-};
-
-KURLPropsPlugin::KURLPropsPlugin( KPropertiesDialog *_props )
- : KPropsDlgPlugin( _props )
-{
- d = new KURLPropsPluginPrivate;
- d->m_frame = properties->addPage(i18n("U&RL"));
- TQVBoxLayout *layout = new TQVBoxLayout(d->m_frame, 0, KDialog::spacingHint());
-
- TQLabel *l;
- l = new TQLabel( d->m_frame, "Label_1" );
- l->setText( i18n("URL:") );
- layout->addWidget(l);
-
- URLEdit = new KURLRequester( d->m_frame, "URL Requester" );
- layout->addWidget(URLEdit);
-
- TQString path = properties->kurl().path();
-
- TQFile f( path );
- if ( !f.open( IO_ReadOnly ) )
- return;
- f.close();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- URLStr = config.readPathEntry( "URL" );
-
- if ( !URLStr.isNull() )
- URLEdit->setURL( URLStr );
-
- connect( URLEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
-
- layout->addStretch (1);
-}
-
-KURLPropsPlugin::~KURLPropsPlugin()
-{
- delete d;
-}
-
-// TQString KURLPropsPlugin::tabName () const
-// {
-// return i18n ("U&RL");
-// }
-
-bool KURLPropsPlugin::supports( KFileItemList _items )
-{
- if ( _items.count() != 1 )
- return false;
- KFileItem * item = _items.first();
- // check if desktop file
- if ( !KPropsDlgPlugin::isDesktopFile( item ) )
- return false;
-
- // open file and check type
- KDesktopFile config( item->url().path(), true /* readonly */ );
- return config.hasLinkType();
-}
-
-void KURLPropsPlugin::applyChanges()
-{
- TQString path = properties->kurl().path();
-
- TQFile f( path );
- if ( !f.open( IO_ReadWrite ) ) {
- KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
- "sufficient access to write to <b>%1</b>.</qt>").arg(path));
- return;
- }
- f.close();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- config.writeEntry( "Type", TQString::fromLatin1("Link"));
- config.writePathEntry( "URL", URLEdit->url() );
- // Users can't create a Link .desktop file with a Name field,
- // but distributions can. Update the Name field in that case.
- if ( config.hasKey("Name") )
- {
- TQString nameStr = nameFromFileName(properties->kurl().fileName());
- config.writeEntry( "Name", nameStr );
- config.writeEntry( "Name", nameStr, true, false, true );
-
- }
-}
-
-
-/* ----------------------------------------------------
- *
- * KBindingPropsPlugin
- *
- * -------------------------------------------------- */
-
-class KBindingPropsPlugin::KBindingPropsPluginPrivate
-{
-public:
- KBindingPropsPluginPrivate()
- {
- }
- ~KBindingPropsPluginPrivate()
- {
- }
-
- TQFrame *m_frame;
-};
-
-KBindingPropsPlugin::KBindingPropsPlugin( KPropertiesDialog *_props ) : KPropsDlgPlugin( _props )
-{
- d = new KBindingPropsPluginPrivate;
- d->m_frame = properties->addPage(i18n("A&ssociation"));
- patternEdit = new KLineEdit( d->m_frame, "LineEdit_1" );
- commentEdit = new KLineEdit( d->m_frame, "LineEdit_2" );
- mimeEdit = new KLineEdit( d->m_frame, "LineEdit_3" );
-
- TQBoxLayout *mainlayout = new TQVBoxLayout(d->m_frame, 0, KDialog::spacingHint());
- TQLabel* tmpQLabel;
-
- tmpQLabel = new TQLabel( d->m_frame, "Label_1" );
- tmpQLabel->setText( i18n("Pattern ( example: *.html;*.htm )") );
- tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
- mainlayout->addWidget(tmpQLabel, 1);
-
- //patternEdit->setGeometry( 10, 40, 210, 30 );
- //patternEdit->setText( "" );
- patternEdit->setMaxLength( 512 );
- patternEdit->setMinimumSize( patternEdit->sizeHint() );
- patternEdit->setFixedHeight( fontHeight );
- mainlayout->addWidget(patternEdit, 1);
-
- tmpQLabel = new TQLabel( d->m_frame, "Label_2" );
- tmpQLabel->setText( i18n("Mime Type") );
- tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
- mainlayout->addWidget(tmpQLabel, 1);
-
- //mimeEdit->setGeometry( 10, 160, 210, 30 );
- mimeEdit->setMaxLength( 256 );
- mimeEdit->setMinimumSize( mimeEdit->sizeHint() );
- mimeEdit->setFixedHeight( fontHeight );
- mainlayout->addWidget(mimeEdit, 1);
-
- tmpQLabel = new TQLabel( d->m_frame, "Label_3" );
- tmpQLabel->setText( i18n("Comment") );
- tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
- mainlayout->addWidget(tmpQLabel, 1);
-
- //commentEdit->setGeometry( 10, 100, 210, 30 );
- commentEdit->setMaxLength( 256 );
- commentEdit->setMinimumSize( commentEdit->sizeHint() );
- commentEdit->setFixedHeight( fontHeight );
- mainlayout->addWidget(commentEdit, 1);
-
- cbAutoEmbed = new TQCheckBox( i18n("Left click previews"), d->m_frame, "cbAutoEmbed" );
- mainlayout->addWidget(cbAutoEmbed, 1);
-
- mainlayout->addStretch (10);
- mainlayout->activate();
-
- TQFile f( _props->kurl().path() );
- if ( !f.open( IO_ReadOnly ) )
- return;
- f.close();
-
- KSimpleConfig config( _props->kurl().path() );
- config.setDesktopGroup();
- TQString patternStr = config.readEntry( "Patterns" );
- TQString iconStr = config.readEntry( "Icon" );
- TQString commentStr = config.readEntry( "Comment" );
- m_sMimeStr = config.readEntry( "MimeType" );
-
- if ( !patternStr.isEmpty() )
- patternEdit->setText( patternStr );
- if ( !commentStr.isEmpty() )
- commentEdit->setText( commentStr );
- if ( !m_sMimeStr.isEmpty() )
- mimeEdit->setText( m_sMimeStr );
- cbAutoEmbed->setTristate();
- if ( config.hasKey( "X-TDE-AutoEmbed" ) )
- cbAutoEmbed->setChecked( config.readBoolEntry( "X-TDE-AutoEmbed" ) );
- else
- cbAutoEmbed->setNoChange();
-
- connect( patternEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( mimeEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( cbAutoEmbed, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
-}
-
-KBindingPropsPlugin::~KBindingPropsPlugin()
-{
- delete d;
-}
-
-// TQString KBindingPropsPlugin::tabName () const
-// {
-// return i18n ("A&ssociation");
-// }
-
-bool KBindingPropsPlugin::supports( KFileItemList _items )
-{
- if ( _items.count() != 1 )
- return false;
- KFileItem * item = _items.first();
- // check if desktop file
- if ( !KPropsDlgPlugin::isDesktopFile( item ) )
- return false;
-
- // open file and check type
- KDesktopFile config( item->url().path(), true /* readonly */ );
- return config.hasMimeTypeType();
-}
-
-void KBindingPropsPlugin::applyChanges()
-{
- TQString path = properties->kurl().path();
- TQFile f( path );
-
- if ( !f.open( IO_ReadWrite ) )
- {
- KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
- "sufficient access to write to <b>%1</b>.</qt>").arg(path));
- return;
- }
- f.close();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- config.writeEntry( "Type", TQString::fromLatin1("MimeType") );
-
- config.writeEntry( "Patterns", patternEdit->text() );
- config.writeEntry( "Comment", commentEdit->text() );
- config.writeEntry( "Comment",
- commentEdit->text(), true, false, true ); // for compat
- config.writeEntry( "MimeType", mimeEdit->text() );
- if ( cbAutoEmbed->state() == TQButton::NoChange )
- config.deleteEntry( "X-TDE-AutoEmbed", false );
- else
- config.writeEntry( "X-TDE-AutoEmbed", cbAutoEmbed->isChecked() );
- config.sync();
-}
-
-/* ----------------------------------------------------
- *
- * KDevicePropsPlugin
- *
- * -------------------------------------------------- */
-
-class KDevicePropsPlugin::KDevicePropsPluginPrivate
-{
-public:
- KDevicePropsPluginPrivate()
- {
- }
- ~KDevicePropsPluginPrivate()
- {
- }
-
- TQFrame *m_frame;
- TQStringList mountpointlist;
- TQLabel *m_freeSpaceText;
- TQLabel *m_freeSpaceLabel;
- TQProgressBar *m_freeSpaceBar;
-};
-
-KDevicePropsPlugin::KDevicePropsPlugin( KPropertiesDialog *_props ) : KPropsDlgPlugin( _props )
-{
- d = new KDevicePropsPluginPrivate;
- d->m_frame = properties->addPage(i18n("De&vice"));
-
- TQStringList devices;
- KMountPoint::List mountPoints = KMountPoint::possibleMountPoints();
-
- for(KMountPoint::List::ConstIterator it = mountPoints.begin();
- it != mountPoints.end(); ++it)
- {
- KMountPoint *mp = *it;
- TQString mountPoint = mp->mountPoint();
- TQString device = mp->mountedFrom();
- kdDebug()<<"mountPoint :"<<mountPoint<<" device :"<<device<<" mp->mountType() :"<<mp->mountType()<<endl;
-
- if ((mountPoint != "-") && (mountPoint != "none") && !mountPoint.isEmpty()
- && device != "none")
- {
- devices.append( device + TQString::fromLatin1(" (")
- + mountPoint + TQString::fromLatin1(")") );
- m_devicelist.append(device);
- d->mountpointlist.append(mountPoint);
- }
- }
-
- TQGridLayout *layout = new TQGridLayout( d->m_frame, 0, 2, 0,
- KDialog::spacingHint());
- layout->setColStretch(1, 1);
-
- TQLabel* label;
- label = new TQLabel( d->m_frame );
- label->setText( devices.count() == 0 ?
- i18n("Device (/dev/fd0):") : // old style
- i18n("Device:") ); // new style (combobox)
- layout->addWidget(label, 0, 0);
-
- device = new TQComboBox( true, d->m_frame, "ComboBox_device" );
- device->insertStringList( devices );
- layout->addWidget(device, 0, 1);
- connect( device, TQT_SIGNAL( activated( int ) ),
- this, TQT_SLOT( slotActivated( int ) ) );
-
- readonly = new TQCheckBox( d->m_frame, "CheckBox_readonly" );
- readonly->setText( i18n("Read only") );
- layout->addWidget(readonly, 1, 1);
-
- label = new TQLabel( d->m_frame );
- label->setText( i18n("File system:") );
- layout->addWidget(label, 2, 0);
-
- TQLabel *fileSystem = new TQLabel( d->m_frame );
- layout->addWidget(fileSystem, 2, 1);
-
- label = new TQLabel( d->m_frame );
- label->setText( devices.count()==0 ?
- i18n("Mount point (/mnt/floppy):") : // old style
- i18n("Mount point:")); // new style (combobox)
- layout->addWidget(label, 3, 0);
-
- mountpoint = new TQLabel( d->m_frame, "LineEdit_mountpoint" );
-
- layout->addWidget(mountpoint, 3, 1);
-
- // show disk free
- d->m_freeSpaceText = new TQLabel(i18n("Free disk space:"), d->m_frame );
- layout->addWidget(d->m_freeSpaceText, 4, 0);
-
- d->m_freeSpaceLabel = new TQLabel( d->m_frame );
- layout->addWidget( d->m_freeSpaceLabel, 4, 1 );
-
- d->m_freeSpaceBar = new TQProgressBar( d->m_frame, "freeSpaceBar" );
- layout->addMultiCellWidget(d->m_freeSpaceBar, 5, 5, 0, 1);
-
- // we show it in the slot when we know the values
- d->m_freeSpaceText->hide();
- d->m_freeSpaceLabel->hide();
- d->m_freeSpaceBar->hide();
-
- KSeparator* sep = new KSeparator( KSeparator::HLine, d->m_frame);
- layout->addMultiCellWidget(sep, 6, 6, 0, 1);
-
- unmounted = new KIconButton( d->m_frame );
- int bsize = 66 + 2 * unmounted->style().pixelMetric(TQStyle::PM_ButtonMargin);
- unmounted->setFixedSize(bsize, bsize);
- unmounted->setIconType(KIcon::Desktop, KIcon::Device);
- layout->addWidget(unmounted, 7, 0);
-
- label = new TQLabel( i18n("Unmounted Icon"), d->m_frame );
- layout->addWidget(label, 7, 1);
-
- layout->setRowStretch(8, 1);
-
- TQString path( _props->kurl().path() );
-
- TQFile f( path );
- if ( !f.open( IO_ReadOnly ) )
- return;
- f.close();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- TQString deviceStr = config.readEntry( "Dev" );
- TQString mountPointStr = config.readEntry( "MountPoint" );
- bool ro = config.readBoolEntry( "ReadOnly", false );
- TQString unmountedStr = config.readEntry( "UnmountIcon" );
-
- fileSystem->setText( i18n(config.readEntry("FSType").local8Bit()) );
-
- device->setEditText( deviceStr );
- if ( !deviceStr.isEmpty() ) {
- // Set default options for this device (first matching entry)
- int index = m_devicelist.findIndex(deviceStr);
- if (index != -1)
- {
- //kdDebug(250) << "found it " << index << endl;
- slotActivated( index );
- }
- }
-
- if ( !mountPointStr.isEmpty() )
- {
- mountpoint->setText( mountPointStr );
- updateInfo();
- }
-
- readonly->setChecked( ro );
-
- if ( unmountedStr.isEmpty() )
- unmountedStr = KMimeType::defaultMimeTypePtr()->KServiceType::icon(); // default icon
-
- unmounted->setIcon( unmountedStr );
-
- connect( device, TQT_SIGNAL( activated( int ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( device, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( readonly, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( unmounted, TQT_SIGNAL( iconChanged( TQString ) ),
- this, TQT_SIGNAL( changed() ) );
-
- connect( device, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SLOT( slotDeviceChanged() ) );
-}
-
-KDevicePropsPlugin::~KDevicePropsPlugin()
-{
- delete d;
-}
-
-// TQString KDevicePropsPlugin::tabName () const
-// {
-// return i18n ("De&vice");
-// }
-
-void KDevicePropsPlugin::updateInfo()
-{
- // we show it in the slot when we know the values
- d->m_freeSpaceText->hide();
- d->m_freeSpaceLabel->hide();
- d->m_freeSpaceBar->hide();
-
- if ( !mountpoint->text().isEmpty() )
- {
- KDiskFreeSp * job = new KDiskFreeSp;
- connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
- const unsigned long&, const TQString& ) ),
- this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
- const unsigned long&, const TQString& ) ) );
-
- job->readDF( mountpoint->text() );
- }
-}
-
-void KDevicePropsPlugin::slotActivated( int index )
-{
- // Update mountpoint so that it matches the device that was selected in the combo
- device->setEditText( m_devicelist[index] );
- mountpoint->setText( d->mountpointlist[index] );
-
- updateInfo();
-}
-
-void KDevicePropsPlugin::slotDeviceChanged()
-{
- // Update mountpoint so that it matches the typed device
- int index = m_devicelist.findIndex( device->currentText() );
- if ( index != -1 )
- mountpoint->setText( d->mountpointlist[index] );
- else
- mountpoint->setText( TQString::null );
-
- updateInfo();
-}
-
-void KDevicePropsPlugin::slotFoundMountPoint( const unsigned long& kBSize,
- const unsigned long& /*kBUsed*/,
- const unsigned long& kBAvail,
- const TQString& )
-{
- d->m_freeSpaceText->show();
- d->m_freeSpaceLabel->show();
-
- int percUsed = 100 - (int)(100.0 * kBAvail / kBSize);
-
- d->m_freeSpaceLabel->setText(
- // xgettext:no-c-format -- Don't warn about translating the %1 out of %2 part.
- i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
- .arg(TDEIO::convertSizeFromKB(kBAvail))
- .arg(TDEIO::convertSizeFromKB(kBSize))
- .arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
-
- d->m_freeSpaceBar->setProgress(percUsed, 100);
- d->m_freeSpaceBar->show();
-}
-
-bool KDevicePropsPlugin::supports( KFileItemList _items )
-{
- if ( _items.count() != 1 )
- return false;
- KFileItem * item = _items.first();
- // check if desktop file
- if ( !KPropsDlgPlugin::isDesktopFile( item ) )
- return false;
- // open file and check type
- KDesktopFile config( item->url().path(), true /* readonly */ );
- return config.hasDeviceType();
-}
-
-void KDevicePropsPlugin::applyChanges()
-{
- TQString path = properties->kurl().path();
- TQFile f( path );
- if ( !f.open( IO_ReadWrite ) )
- {
- KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have sufficient "
- "access to write to <b>%1</b>.</qt>").arg(path));
- return;
- }
- f.close();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- config.writeEntry( "Type", TQString::fromLatin1("FSDevice") );
-
- config.writeEntry( "Dev", device->currentText() );
- config.writeEntry( "MountPoint", mountpoint->text() );
-
- config.writeEntry( "UnmountIcon", unmounted->icon() );
- kdDebug(250) << "unmounted->icon() = " << unmounted->icon() << endl;
-
- config.writeEntry( "ReadOnly", readonly->isChecked() );
-
- config.sync();
-}
-
-
-/* ----------------------------------------------------
- *
- * KDesktopPropsPlugin
- *
- * -------------------------------------------------- */
-
-
-KDesktopPropsPlugin::KDesktopPropsPlugin( KPropertiesDialog *_props )
- : KPropsDlgPlugin( _props )
-{
- TQFrame *frame = properties->addPage(i18n("&Application"));
- TQVBoxLayout *mainlayout = new TQVBoxLayout( frame, 0, KDialog::spacingHint() );
-
- w = new KPropertiesDesktopBase(frame);
- mainlayout->addWidget(w);
-
- bool bKDesktopMode = (TQCString(tqApp->name()) == "kdesktop"); // nasty heh?
-
- if (bKDesktopMode)
- {
- // Hide Name entry
- w->nameEdit->hide();
- w->nameLabel->hide();
- }
-
- w->pathEdit->setMode(KFile::Directory | KFile::LocalOnly);
- w->pathEdit->lineEdit()->setAcceptDrops(false);
-
- connect( w->nameEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
- connect( w->genNameEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
- connect( w->commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
- connect( w->commandEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
- connect( w->pathEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
-
- connect( w->browseButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotBrowseExec() ) );
- connect( w->addFiletypeButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotAddFiletype() ) );
- connect( w->delFiletypeButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotDelFiletype() ) );
- connect( w->advancedButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotAdvanced() ) );
-
- // now populate the page
- TQString path = _props->kurl().path();
- TQFile f( path );
- if ( !f.open( IO_ReadOnly ) )
- return;
- f.close();
-
- KDesktopFile config( path );
- TQString nameStr = config.readName();
- TQString genNameStr = config.readGenericName();
- TQString commentStr = config.readComment();
- TQString commandStr = config.readPathEntry( "Exec" );
- if (commandStr.left(12) == "ksystraycmd ")
- {
- commandStr.remove(0, 12);
- m_systrayBool = true;
- }
- else
- m_systrayBool = false;
-
- m_origCommandStr = commandStr;
- TQString pathStr = config.readPathEntry( "Path" );
- m_terminalBool = config.readBoolEntry( "Terminal" );
- m_terminalOptionStr = config.readEntry( "TerminalOptions" );
- m_suidBool = config.readBoolEntry( "X-TDE-SubstituteUID" );
- m_suidUserStr = config.readEntry( "X-TDE-Username" );
- if( config.hasKey( "StartupNotify" ))
- m_startupBool = config.readBoolEntry( "StartupNotify", true );
- else
- m_startupBool = config.readBoolEntry( "X-TDE-StartupNotify", true );
- m_dcopServiceType = config.readEntry("X-DCOP-ServiceType").lower();
-
- TQStringList mimeTypes = config.readListEntry( "MimeType", ';' );
-
- if ( nameStr.isEmpty() || bKDesktopMode ) {
- // We'll use the file name if no name is specified
- // because we _need_ a Name for a valid file.
- // But let's do it in apply, not here, so that we pick up the right name.
- setDirty();
- }
- if ( !bKDesktopMode )
- w->nameEdit->setText(nameStr);
-
- w->genNameEdit->setText( genNameStr );
- w->commentEdit->setText( commentStr );
- w->commandEdit->setText( commandStr );
- w->pathEdit->lineEdit()->setText( pathStr );
- w->filetypeList->setAllColumnsShowFocus(true);
-
- KMimeType::Ptr defaultMimetype = KMimeType::defaultMimeTypePtr();
- for(TQStringList::ConstIterator it = mimeTypes.begin();
- it != mimeTypes.end(); )
- {
- KMimeType::Ptr p = KMimeType::mimeType(*it);
- ++it;
- TQString preference;
- if (it != mimeTypes.end())
- {
- bool numeric;
- (*it).toInt(&numeric);
- if (numeric)
- {
- preference = *it;
- ++it;
- }
- }
- if (p && (p != defaultMimetype))
- {
- new TQListViewItem(w->filetypeList, p->name(), p->comment(), preference);
- }
- }
-
-}
-
-KDesktopPropsPlugin::~KDesktopPropsPlugin()
-{
-}
-
-void KDesktopPropsPlugin::slotSelectMimetype()
-{
- TQListView *w = (TQListView*)sender();
- TQListViewItem *item = w->firstChild();
- while(item)
- {
- if (item->isSelected())
- w->setSelected(item, false);
- item = item->nextSibling();
- }
-}
-
-void KDesktopPropsPlugin::slotAddFiletype()
-{
- KDialogBase dlg(w, "KPropertiesMimetypes", true,
- i18n("Add File Type for %1").arg(properties->kurl().fileName()),
- KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);
-
- KGuiItem okItem(i18n("&Add"), TQString::null /* no icon */,
- i18n("Add the selected file types to\nthe list of supported file types."),
- i18n("Add the selected file types to\nthe list of supported file types."));
- dlg.setButtonOK(okItem);
-
- KPropertiesMimetypeBase *mw = new KPropertiesMimetypeBase(&dlg);
-
- dlg.setMainWidget(mw);
-
- {
- mw->listView->setRootIsDecorated(true);
- mw->listView->setSelectionMode(TQListView::Extended);
- mw->listView->setAllColumnsShowFocus(true);
- mw->listView->setFullWidth(true);
- mw->listView->setMinimumSize(500,400);
-
- connect(mw->listView, TQT_SIGNAL(selectionChanged()),
- this, TQT_SLOT(slotSelectMimetype()));
- connect(mw->listView, TQT_SIGNAL(doubleClicked( TQListViewItem *, const TQPoint &, int )),
- &dlg, TQT_SLOT( slotOk()));
-
- TQMap<TQString,TQListViewItem*> majorMap;
- TQListViewItem *majorGroup;
- KMimeType::List mimetypes = KMimeType::allMimeTypes();
- TQValueListIterator<KMimeType::Ptr> it(mimetypes.begin());
- for (; it != mimetypes.end(); ++it) {
- TQString mimetype = (*it)->name();
- if (mimetype == KMimeType::defaultMimeType())
- continue;
- int index = mimetype.find("/");
- TQString maj = mimetype.left(index);
- TQString min = mimetype.mid(index+1);
-
- TQMapIterator<TQString,TQListViewItem*> mit = majorMap.find( maj );
- if ( mit == majorMap.end() ) {
- majorGroup = new TQListViewItem( mw->listView, maj );
- majorGroup->setExpandable(true);
- mw->listView->setOpen(majorGroup, true);
- majorMap.insert( maj, majorGroup );
- }
- else
- {
- majorGroup = mit.data();
- }
-
- TQListViewItem *item = new TQListViewItem(majorGroup, min, (*it)->comment());
- item->setPixmap(0, (*it)->pixmap(KIcon::Small, IconSize(KIcon::Small)));
- }
- TQMapIterator<TQString,TQListViewItem*> mit = majorMap.find( "all" );
- if ( mit != majorMap.end())
- {
- mw->listView->setCurrentItem(mit.data());
- mw->listView->ensureItemVisible(mit.data());
- }
- }
-
- if (dlg.exec() == KDialogBase::Accepted)
- {
- KMimeType::Ptr defaultMimetype = KMimeType::defaultMimeTypePtr();
- TQListViewItem *majorItem = mw->listView->firstChild();
- while(majorItem)
- {
- TQString major = majorItem->text(0);
-
- TQListViewItem *minorItem = majorItem->firstChild();
- while(minorItem)
- {
- if (minorItem->isSelected())
- {
- TQString mimetype = major + "/" + minorItem->text(0);
- KMimeType::Ptr p = KMimeType::mimeType(mimetype);
- if (p && (p != defaultMimetype))
- {
- mimetype = p->name();
- bool found = false;
- TQListViewItem *item = w->filetypeList->firstChild();
- while (item)
- {
- if (mimetype == item->text(0))
- {
- found = true;
- break;
- }
- item = item->nextSibling();
- }
- if (!found) {
- new TQListViewItem(w->filetypeList, p->name(), p->comment());
- emit changed();
- }
- }
- }
- minorItem = minorItem->nextSibling();
- }
-
- majorItem = majorItem->nextSibling();
- }
-
- }
-}
-
-void KDesktopPropsPlugin::slotDelFiletype()
-{
- delete w->filetypeList->currentItem();
- emit changed();
-}
-
-void KDesktopPropsPlugin::checkCommandChanged()
-{
- if (KRun::binaryName(w->commandEdit->text(), true) !=
- KRun::binaryName(m_origCommandStr, true))
- {
- TQString m_origCommandStr = w->commandEdit->text();
- m_dcopServiceType= TQString::null; // Reset
- }
-}
-
-void KDesktopPropsPlugin::applyChanges()
-{
- kdDebug(250) << "KDesktopPropsPlugin::applyChanges" << endl;
- TQString path = properties->kurl().path();
-
- TQFile f( path );
-
- if ( !f.open( IO_ReadWrite ) ) {
- KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
- "sufficient access to write to <b>%1</b>.</qt>").arg(path));
- return;
- }
- f.close();
-
- // If the command is changed we reset certain settings that are strongly
- // coupled to the command.
- checkCommandChanged();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- config.writeEntry( "Type", TQString::fromLatin1("Application"));
- config.writeEntry( "Comment", w->commentEdit->text() );
- config.writeEntry( "Comment", w->commentEdit->text(), true, false, true ); // for compat
- config.writeEntry( "GenericName", w->genNameEdit->text() );
- config.writeEntry( "GenericName", w->genNameEdit->text(), true, false, true ); // for compat
-
- if (m_systrayBool)
- config.writePathEntry( "Exec", w->commandEdit->text().prepend("ksystraycmd ") );
- else
- config.writePathEntry( "Exec", w->commandEdit->text() );
- config.writePathEntry( "Path", w->pathEdit->lineEdit()->text() );
-
- // Write mimeTypes
- TQStringList mimeTypes;
- for( TQListViewItem *item = w->filetypeList->firstChild();
- item; item = item->nextSibling() )
- {
- TQString preference = item->text(2);
- mimeTypes.append(item->text(0));
- if (!preference.isEmpty())
- mimeTypes.append(preference);
- }
-
- config.writeEntry( "MimeType", mimeTypes, ';' );
-
- if ( !w->nameEdit->isHidden() ) {
- TQString nameStr = w->nameEdit->text();
- config.writeEntry( "Name", nameStr );
- config.writeEntry( "Name", nameStr, true, false, true );
- }
-
- config.writeEntry("Terminal", m_terminalBool);
- config.writeEntry("TerminalOptions", m_terminalOptionStr);
- config.writeEntry("X-TDE-SubstituteUID", m_suidBool);
- config.writeEntry("X-TDE-Username", m_suidUserStr);
- config.writeEntry("StartupNotify", m_startupBool);
- config.writeEntry("X-DCOP-ServiceType", m_dcopServiceType);
- config.sync();
-
- // KSycoca update needed?
- TQString sycocaPath = TDEGlobal::dirs()->relativeLocation("apps", path);
- bool updateNeeded = !sycocaPath.startsWith("/");
- if (!updateNeeded)
- {
- sycocaPath = TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path);
- updateNeeded = !sycocaPath.startsWith("/");
- }
- if (updateNeeded)
- KService::rebuildKSycoca(w);
-}
-
-
-void KDesktopPropsPlugin::slotBrowseExec()
-{
- KURL f = KFileDialog::getOpenURL( TQString::null,
- TQString::null, w );
- if ( f.isEmpty() )
- return;
-
- if ( !f.isLocalFile()) {
- KMessageBox::sorry(w, i18n("Only executables on local file systems are supported."));
- return;
- }
-
- TQString path = f.path();
- KRun::shellQuote( path );
- w->commandEdit->setText( path );
-}
-
-void KDesktopPropsPlugin::slotAdvanced()
-{
- KDialogBase dlg(w, "KPropertiesDesktopAdv", true,
- i18n("Advanced Options for %1").arg(properties->kurl().fileName()),
- KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);
- KPropertiesDesktopAdvBase *w = new KPropertiesDesktopAdvBase(&dlg);
-
- dlg.setMainWidget(w);
-
- // If the command is changed we reset certain settings that are strongly
- // coupled to the command.
- checkCommandChanged();
-
- // check to see if we use konsole if not do not add the nocloseonexit
- // because we don't know how to do this on other terminal applications
- TDEConfigGroup confGroup( TDEGlobal::config(), TQString::fromLatin1("General") );
- TQString preferredTerminal = confGroup.readPathEntry("TerminalApplication",
- TQString::fromLatin1("konsole"));
-
- bool terminalCloseBool = false;
-
- if (preferredTerminal == "konsole")
- {
- terminalCloseBool = (m_terminalOptionStr.contains( "--noclose" ) > 0);
- w->terminalCloseCheck->setChecked(terminalCloseBool);
- m_terminalOptionStr.replace( "--noclose", "");
- }
- else
- {
- w->terminalCloseCheck->hide();
- }
-
- w->terminalCheck->setChecked(m_terminalBool);
- w->terminalEdit->setText(m_terminalOptionStr);
- w->terminalCloseCheck->setEnabled(m_terminalBool);
- w->terminalEdit->setEnabled(m_terminalBool);
- w->terminalEditLabel->setEnabled(m_terminalBool);
-
- w->suidCheck->setChecked(m_suidBool);
- w->suidEdit->setText(m_suidUserStr);
- w->suidEdit->setEnabled(m_suidBool);
- w->suidEditLabel->setEnabled(m_suidBool);
-
- w->startupInfoCheck->setChecked(m_startupBool);
- w->systrayCheck->setChecked(m_systrayBool);
-
- if (m_dcopServiceType == "unique")
- w->dcopCombo->setCurrentItem(2);
- else if (m_dcopServiceType == "multi")
- w->dcopCombo->setCurrentItem(1);
- else if (m_dcopServiceType == "wait")
- w->dcopCombo->setCurrentItem(3);
- else
- w->dcopCombo->setCurrentItem(0);
-
- // Provide username completion up to 1000 users.
- KCompletion *kcom = new KCompletion;
- kcom->setOrder(KCompletion::Sorted);
- struct passwd *pw;
- int i, maxEntries = 1000;
- setpwent();
- for (i=0; ((pw = getpwent()) != 0L) && (i < maxEntries); i++)
- kcom->addItem(TQString::fromLatin1(pw->pw_name));
- endpwent();
- if (i < maxEntries)
- {
- w->suidEdit->setCompletionObject(kcom, true);
- w->suidEdit->setAutoDeleteCompletionObject( true );
- w->suidEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
- }
- else
- {
- delete kcom;
- }
-
- connect( w->terminalEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( w->terminalCloseCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( w->terminalCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( w->suidCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( w->suidEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( w->startupInfoCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( w->systrayCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( w->dcopCombo, TQT_SIGNAL( highlighted( int ) ),
- this, TQT_SIGNAL( changed() ) );
-
- if ( dlg.exec() == TQDialog::Accepted )
- {
- m_terminalOptionStr = w->terminalEdit->text().stripWhiteSpace();
- m_terminalBool = w->terminalCheck->isChecked();
- m_suidBool = w->suidCheck->isChecked();
- m_suidUserStr = w->suidEdit->text().stripWhiteSpace();
- m_startupBool = w->startupInfoCheck->isChecked();
- m_systrayBool = w->systrayCheck->isChecked();
-
- if (w->terminalCloseCheck->isChecked())
- {
- m_terminalOptionStr.append(" --noclose");
- }
-
- switch(w->dcopCombo->currentItem())
- {
- case 1: m_dcopServiceType = "multi"; break;
- case 2: m_dcopServiceType = "unique"; break;
- case 3: m_dcopServiceType = "wait"; break;
- default: m_dcopServiceType = "none"; break;
- }
- }
-}
-
-bool KDesktopPropsPlugin::supports( KFileItemList _items )
-{
- if ( _items.count() != 1 )
- return false;
- KFileItem * item = _items.first();
- // check if desktop file
- if ( !KPropsDlgPlugin::isDesktopFile( item ) )
- return false;
- // open file and check type
- KDesktopFile config( item->url().path(), true /* readonly */ );
- return config.hasApplicationType() && kapp->authorize("run_desktop_files") && kapp->authorize("shell_access");
-}
-
-void KPropertiesDialog::virtual_hook( int id, void* data )
-{ KDialogBase::virtual_hook( id, data ); }
-
-void KPropsDlgPlugin::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-
-
-
-
-/**
- * The following code is obsolete and only kept for binary compatibility
- * To be removed in KDE 4
- */
-
-class KExecPropsPlugin::KExecPropsPluginPrivate
-{
-public:
- KExecPropsPluginPrivate()
- {
- }
- ~KExecPropsPluginPrivate()
- {
- }
-
- TQFrame *m_frame;
- TQCheckBox *nocloseonexitCheck;
-};
-
-KExecPropsPlugin::KExecPropsPlugin( KPropertiesDialog *_props )
- : KPropsDlgPlugin( _props )
-{
- d = new KExecPropsPluginPrivate;
- d->m_frame = properties->addPage(i18n("E&xecute"));
- TQVBoxLayout * mainlayout = new TQVBoxLayout( d->m_frame, 0,
- KDialog::spacingHint());
-
- // Now the widgets in the top layout
-
- TQLabel* l;
- l = new TQLabel( i18n( "Comman&d:" ), d->m_frame );
- mainlayout->addWidget(l);
-
- TQHBoxLayout * hlayout;
- hlayout = new TQHBoxLayout(KDialog::spacingHint());
- mainlayout->addLayout(hlayout);
-
- execEdit = new KLineEdit( d->m_frame );
- TQWhatsThis::add(execEdit,i18n(
- "Following the command, you can have several place holders which will be replaced "
- "with the actual values when the actual program is run:\n"
- "%f - a single file name\n"
- "%F - a list of files; use for applications that can open several local files at once\n"
- "%u - a single URL\n"
- "%U - a list of URLs\n"
- "%d - the folder of the file to open\n"
- "%D - a list of folders\n"
- "%i - the icon\n"
- "%m - the mini-icon\n"
- "%c - the caption"));
- hlayout->addWidget(execEdit, 1);
-
- l->setBuddy( execEdit );
-
- execBrowse = new TQPushButton( d->m_frame );
- execBrowse->setText( i18n("&Browse...") );
- hlayout->addWidget(execBrowse);
-
- // The groupbox about swallowing
- TQGroupBox* tmpQGroupBox;
- tmpQGroupBox = new TQGroupBox( i18n("Panel Embedding"), d->m_frame );
- tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );
-
- mainlayout->addWidget(tmpQGroupBox);
-
- TQGridLayout *grid = new TQGridLayout(tmpQGroupBox->layout(), 2, 2);
- grid->setSpacing( KDialog::spacingHint() );
- grid->setColStretch(1, 1);
-
- l = new TQLabel( i18n( "&Execute on click:" ), tmpQGroupBox );
- grid->addWidget(l, 0, 0);
-
- swallowExecEdit = new KLineEdit( tmpQGroupBox );
- grid->addWidget(swallowExecEdit, 0, 1);
-
- l->setBuddy( swallowExecEdit );
-
- l = new TQLabel( i18n( "&Window title:" ), tmpQGroupBox );
- grid->addWidget(l, 1, 0);
-
- swallowTitleEdit = new KLineEdit( tmpQGroupBox );
- grid->addWidget(swallowTitleEdit, 1, 1);
-
- l->setBuddy( swallowTitleEdit );
-
- // The groupbox about run in terminal
-
- tmpQGroupBox = new TQGroupBox( d->m_frame );
- tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );
-
- mainlayout->addWidget(tmpQGroupBox);
-
- grid = new TQGridLayout(tmpQGroupBox->layout(), 3, 2);
- grid->setSpacing( KDialog::spacingHint() );
- grid->setColStretch(1, 1);
-
- terminalCheck = new TQCheckBox( tmpQGroupBox );
- terminalCheck->setText( i18n("&Run in terminal") );
- grid->addMultiCellWidget(terminalCheck, 0, 0, 0, 1);
-
- // check to see if we use konsole if not do not add the nocloseonexit
- // because we don't know how to do this on other terminal applications
- TDEConfigGroup confGroup( TDEGlobal::config(), TQString::fromLatin1("General") );
- TQString preferredTerminal = confGroup.readPathEntry("TerminalApplication",
- TQString::fromLatin1("konsole"));
-
- int posOptions = 1;
- d->nocloseonexitCheck = 0L;
- if (preferredTerminal == "konsole")
- {
- posOptions = 2;
- d->nocloseonexitCheck = new TQCheckBox( tmpQGroupBox );
- d->nocloseonexitCheck->setText( i18n("Do not &close when command exits") );
- grid->addMultiCellWidget(d->nocloseonexitCheck, 1, 1, 0, 1);
- }
-
- terminalLabel = new TQLabel( i18n( "&Terminal options:" ), tmpQGroupBox );
- grid->addWidget(terminalLabel, posOptions, 0);
-
- terminalEdit = new KLineEdit( tmpQGroupBox );
- grid->addWidget(terminalEdit, posOptions, 1);
-
- terminalLabel->setBuddy( terminalEdit );
-
- // The groupbox about run with substituted uid.
-
- tmpQGroupBox = new TQGroupBox( d->m_frame );
- tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );
-
- mainlayout->addWidget(tmpQGroupBox);
-
- grid = new TQGridLayout(tmpQGroupBox->layout(), 2, 2);
- grid->setSpacing(KDialog::spacingHint());
- grid->setColStretch(1, 1);
-
- suidCheck = new TQCheckBox(tmpQGroupBox);
- suidCheck->setText(i18n("Ru&n as a different user"));
- grid->addMultiCellWidget(suidCheck, 0, 0, 0, 1);
-
- suidLabel = new TQLabel(i18n( "&Username:" ), tmpQGroupBox);
- grid->addWidget(suidLabel, 1, 0);
-
- suidEdit = new KLineEdit(tmpQGroupBox);
- grid->addWidget(suidEdit, 1, 1);
-
- suidLabel->setBuddy( suidEdit );
-
- mainlayout->addStretch(1);
-
- // now populate the page
- TQString path = _props->kurl().path();
- TQFile f( path );
- if ( !f.open( IO_ReadOnly ) )
- return;
- f.close();
-
- KSimpleConfig config( path );
- config.setDollarExpansion( false );
- config.setDesktopGroup();
- execStr = config.readPathEntry( "Exec" );
- swallowExecStr = config.readPathEntry( "SwallowExec" );
- swallowTitleStr = config.readEntry( "SwallowTitle" );
- termBool = config.readBoolEntry( "Terminal" );
- termOptionsStr = config.readEntry( "TerminalOptions" );
- suidBool = config.readBoolEntry( "X-TDE-SubstituteUID" );
- suidUserStr = config.readEntry( "X-TDE-Username" );
-
- if ( !swallowExecStr.isNull() )
- swallowExecEdit->setText( swallowExecStr );
- if ( !swallowTitleStr.isNull() )
- swallowTitleEdit->setText( swallowTitleStr );
-
- if ( !execStr.isNull() )
- execEdit->setText( execStr );
-
- if ( d->nocloseonexitCheck )
- {
- d->nocloseonexitCheck->setChecked( (termOptionsStr.contains( "--noclose" ) > 0) );
- termOptionsStr.replace( "--noclose", "");
- }
- if ( !termOptionsStr.isNull() )
- terminalEdit->setText( termOptionsStr );
-
- terminalCheck->setChecked( termBool );
- enableCheckedEdit();
-
- suidCheck->setChecked( suidBool );
- suidEdit->setText( suidUserStr );
- enableSuidEdit();
-
- // Provide username completion up to 1000 users.
- KCompletion *kcom = new KCompletion;
- kcom->setOrder(KCompletion::Sorted);
- struct passwd *pw;
- int i, maxEntries = 1000;
- setpwent();
- for (i=0; ((pw = getpwent()) != 0L) && (i < maxEntries); i++)
- kcom->addItem(TQString::fromLatin1(pw->pw_name));
- endpwent();
- if (i < maxEntries)
- {
- suidEdit->setCompletionObject(kcom, true);
- suidEdit->setAutoDeleteCompletionObject( true );
- suidEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
- }
- else
- {
- delete kcom;
- }
-
- connect( swallowExecEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( swallowTitleEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( execEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( terminalEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- if (d->nocloseonexitCheck)
- connect( d->nocloseonexitCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( terminalCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( suidCheck, TQT_SIGNAL( toggled( bool ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( suidEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
-
- connect( execBrowse, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotBrowseExec() ) );
- connect( terminalCheck, TQT_SIGNAL( clicked() ), this, TQT_SLOT( enableCheckedEdit() ) );
- connect( suidCheck, TQT_SIGNAL( clicked() ), this, TQT_SLOT( enableSuidEdit() ) );
-
-}
-
-KExecPropsPlugin::~KExecPropsPlugin()
-{
- delete d;
-}
-
-void KExecPropsPlugin::enableCheckedEdit()
-{
- bool checked = terminalCheck->isChecked();
- terminalLabel->setEnabled( checked );
- if (d->nocloseonexitCheck)
- d->nocloseonexitCheck->setEnabled( checked );
- terminalEdit->setEnabled( checked );
-}
-
-void KExecPropsPlugin::enableSuidEdit()
-{
- bool checked = suidCheck->isChecked();
- suidLabel->setEnabled( checked );
- suidEdit->setEnabled( checked );
-}
-
-bool KExecPropsPlugin::supports( KFileItemList _items )
-{
- if ( _items.count() != 1 )
- return false;
- KFileItem * item = _items.first();
- // check if desktop file
- if ( !KPropsDlgPlugin::isDesktopFile( item ) )
- return false;
- // open file and check type
- KDesktopFile config( item->url().path(), true /* readonly */ );
- return config.hasApplicationType() && kapp->authorize("run_desktop_files") && kapp->authorize("shell_access");
-}
-
-void KExecPropsPlugin::applyChanges()
-{
- kdDebug(250) << "KExecPropsPlugin::applyChanges" << endl;
- TQString path = properties->kurl().path();
-
- TQFile f( path );
-
- if ( !f.open( IO_ReadWrite ) ) {
- KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
- "sufficient access to write to <b>%1</b>.</qt>").arg(path));
- return;
- }
- f.close();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- config.writeEntry( "Type", TQString::fromLatin1("Application"));
- config.writePathEntry( "Exec", execEdit->text() );
- config.writePathEntry( "SwallowExec", swallowExecEdit->text() );
- config.writeEntry( "SwallowTitle", swallowTitleEdit->text() );
- config.writeEntry( "Terminal", terminalCheck->isChecked() );
- TQString temp = terminalEdit->text();
- if (d->nocloseonexitCheck )
- if ( d->nocloseonexitCheck->isChecked() )
- temp += TQString::fromLatin1("--noclose ");
- temp = temp.stripWhiteSpace();
- config.writeEntry( "TerminalOptions", temp );
- config.writeEntry( "X-TDE-SubstituteUID", suidCheck->isChecked() );
- config.writeEntry( "X-TDE-Username", suidEdit->text() );
-}
-
-
-void KExecPropsPlugin::slotBrowseExec()
-{
- KURL f = KFileDialog::getOpenURL( TQString::null,
- TQString::null, d->m_frame );
- if ( f.isEmpty() )
- return;
-
- if ( !f.isLocalFile()) {
- KMessageBox::sorry(d->m_frame, i18n("Only executables on local file systems are supported."));
- return;
- }
-
- TQString path = f.path();
- KRun::shellQuote( path );
- execEdit->setText( path );
-}
-
-class TDEApplicationPropsPlugin::TDEApplicationPropsPluginPrivate
-{
-public:
- TDEApplicationPropsPluginPrivate()
- {
- m_kdesktopMode = TQCString(tqApp->name()) == "kdesktop"; // nasty heh?
- }
- ~TDEApplicationPropsPluginPrivate()
- {
- }
-
- TQFrame *m_frame;
- bool m_kdesktopMode;
-};
-
-TDEApplicationPropsPlugin::TDEApplicationPropsPlugin( KPropertiesDialog *_props )
- : KPropsDlgPlugin( _props )
-{
- d = new TDEApplicationPropsPluginPrivate;
- d->m_frame = properties->addPage(i18n("&Application"));
- TQVBoxLayout *toplayout = new TQVBoxLayout( d->m_frame, 0, KDialog::spacingHint());
-
- TQIconSet iconSet;
- TQPixmap pixMap;
-
- addExtensionButton = new TQPushButton( TQString::null, d->m_frame );
- iconSet = SmallIconSet( "back" );
- addExtensionButton->setIconSet( iconSet );
- pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
- addExtensionButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
- connect( addExtensionButton, TQT_SIGNAL( clicked() ),
- TQT_SLOT( slotAddExtension() ) );
-
- delExtensionButton = new TQPushButton( TQString::null, d->m_frame );
- iconSet = SmallIconSet( "forward" );
- delExtensionButton->setIconSet( iconSet );
- delExtensionButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
- connect( delExtensionButton, TQT_SIGNAL( clicked() ),
- TQT_SLOT( slotDelExtension() ) );
-
- TQLabel *l;
-
- TQGridLayout *grid = new TQGridLayout(2, 2);
- grid->setColStretch(1, 1);
- toplayout->addLayout(TQT_TQLAYOUT(grid));
-
- if ( d->m_kdesktopMode )
- {
- // in kdesktop the name field comes from the first tab
- nameEdit = 0L;
- }
- else
- {
- l = new TQLabel(i18n("Name:"), d->m_frame, "Label_4" );
- grid->addWidget(l, 0, 0);
-
- nameEdit = new KLineEdit( d->m_frame, "LineEdit_3" );
- grid->addWidget(nameEdit, 0, 1);
- }
-
- l = new TQLabel(i18n("Description:"), d->m_frame, "Label_5" );
- grid->addWidget(l, 1, 0);
-
- genNameEdit = new KLineEdit( d->m_frame, "LineEdit_4" );
- grid->addWidget(genNameEdit, 1, 1);
-
- l = new TQLabel(i18n("Comment:"), d->m_frame, "Label_3" );
- grid->addWidget(l, 2, 0);
-
- commentEdit = new KLineEdit( d->m_frame, "LineEdit_2" );
- grid->addWidget(commentEdit, 2, 1);
-
- l = new TQLabel(i18n("File types:"), d->m_frame);
- toplayout->addWidget(l, 0, AlignLeft);
-
- grid = new TQGridLayout(4, 3);
- grid->setColStretch(0, 1);
- grid->setColStretch(2, 1);
- grid->setRowStretch( 0, 1 );
- grid->setRowStretch( 3, 1 );
- toplayout->addLayout(TQT_TQLAYOUT(grid), 2);
-
- extensionsList = new TQListBox( d->m_frame );
- extensionsList->setSelectionMode( TQListBox::Extended );
- grid->addMultiCellWidget(extensionsList, 0, 3, 0, 0);
-
- grid->addWidget(addExtensionButton, 1, 1);
- grid->addWidget(delExtensionButton, 2, 1);
-
- availableExtensionsList = new TQListBox( d->m_frame );
- availableExtensionsList->setSelectionMode( TQListBox::Extended );
- grid->addMultiCellWidget(availableExtensionsList, 0, 3, 2, 2);
-
- TQString path = properties->kurl().path() ;
- TQFile f( path );
- if ( !f.open( IO_ReadOnly ) )
- return;
- f.close();
-
- KDesktopFile config( path );
- TQString commentStr = config.readComment();
- TQString genNameStr = config.readGenericName();
-
- TQStringList selectedTypes = config.readListEntry( "ServiceTypes" );
- // For compatibility with KDE 1.x
- selectedTypes += config.readListEntry( "MimeType", ';' );
-
- TQString nameStr = config.readName();
- if ( nameStr.isEmpty() || d->m_kdesktopMode ) {
- // We'll use the file name if no name is specified
- // because we _need_ a Name for a valid file.
- // But let's do it in apply, not here, so that we pick up the right name.
- setDirty();
- }
-
- commentEdit->setText( commentStr );
- genNameEdit->setText( genNameStr );
- if ( nameEdit )
- nameEdit->setText( nameStr );
-
- selectedTypes.sort();
- TQStringList::Iterator sit = selectedTypes.begin();
- for( ; sit != selectedTypes.end(); ++sit ) {
- if ( !((*sit).isEmpty()) )
- extensionsList->insertItem( *sit );
- }
-
- KMimeType::List mimeTypes = KMimeType::allMimeTypes();
- TQValueListIterator<KMimeType::Ptr> it2 = mimeTypes.begin();
- for ( ; it2 != mimeTypes.end(); ++it2 )
- addMimeType ( (*it2)->name() );
-
- updateButton();
-
- connect( extensionsList, TQT_SIGNAL( highlighted( int ) ),
- this, TQT_SLOT( updateButton() ) );
- connect( availableExtensionsList, TQT_SIGNAL( highlighted( int ) ),
- this, TQT_SLOT( updateButton() ) );
-
- connect( addExtensionButton, TQT_SIGNAL( clicked() ),
- this, TQT_SIGNAL( changed() ) );
- connect( delExtensionButton, TQT_SIGNAL( clicked() ),
- this, TQT_SIGNAL( changed() ) );
- if ( nameEdit )
- connect( nameEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( genNameEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( availableExtensionsList, TQT_SIGNAL( selected( int ) ),
- this, TQT_SIGNAL( changed() ) );
- connect( extensionsList, TQT_SIGNAL( selected( int ) ),
- this, TQT_SIGNAL( changed() ) );
-}
-
-TDEApplicationPropsPlugin::~TDEApplicationPropsPlugin()
-{
- delete d;
-}
-
-// TQString TDEApplicationPropsPlugin::tabName () const
-// {
-// return i18n ("&Application");
-// }
-
-void TDEApplicationPropsPlugin::updateButton()
-{
- addExtensionButton->setEnabled(availableExtensionsList->currentItem()>-1);
- delExtensionButton->setEnabled(extensionsList->currentItem()>-1);
-}
-
-void TDEApplicationPropsPlugin::addMimeType( const TQString & name )
-{
- // Add a mimetype to the list of available mime types if not in the extensionsList
-
- bool insert = true;
-
- for ( uint i = 0; i < extensionsList->count(); i++ )
- if ( extensionsList->text( i ) == name )
- insert = false;
-
- if ( insert )
- {
- availableExtensionsList->insertItem( name );
- availableExtensionsList->sort();
- }
-}
-
-bool TDEApplicationPropsPlugin::supports( KFileItemList _items )
-{
- // same constraints as KExecPropsPlugin : desktop file with Type = Application
- return KExecPropsPlugin::supports( _items );
-}
-
-void TDEApplicationPropsPlugin::applyChanges()
-{
- TQString path = properties->kurl().path();
-
- TQFile f( path );
-
- if ( !f.open( IO_ReadWrite ) ) {
- KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not "
- "have sufficient access to write to <b>%1</b>.</qt>").arg(path));
- return;
- }
- f.close();
-
- KSimpleConfig config( path );
- config.setDesktopGroup();
- config.writeEntry( "Type", TQString::fromLatin1("Application"));
- config.writeEntry( "Comment", commentEdit->text() );
- config.writeEntry( "Comment", commentEdit->text(), true, false, true ); // for compat
- config.writeEntry( "GenericName", genNameEdit->text() );
- config.writeEntry( "GenericName", genNameEdit->text(), true, false, true ); // for compat
-
- TQStringList selectedTypes;
- for ( uint i = 0; i < extensionsList->count(); i++ )
- selectedTypes.append( extensionsList->text( i ) );
-
- config.writeEntry( "MimeType", selectedTypes, ';' );
- config.writeEntry( "ServiceTypes", "" );
- // hmm, actually it should probably be the contrary (but see also typeslistitem.cpp)
-
- TQString nameStr = nameEdit ? nameEdit->text() : TQString::null;
- if ( nameStr.isEmpty() ) // nothing entered, or widget not existing at all (kdesktop mode)
- nameStr = nameFromFileName(properties->kurl().fileName());
-
- config.writeEntry( "Name", nameStr );
- config.writeEntry( "Name", nameStr, true, false, true );
-
- config.sync();
-}
-
-void TDEApplicationPropsPlugin::slotAddExtension()
-{
- TQListBoxItem *item = availableExtensionsList->firstItem();
- TQListBoxItem *nextItem;
-
- while ( item )
- {
- nextItem = item->next();
-
- if ( item->isSelected() )
- {
- extensionsList->insertItem( item->text() );
- availableExtensionsList->removeItem( availableExtensionsList->index( item ) );
- }
-
- item = nextItem;
- }
-
- extensionsList->sort();
- updateButton();
-}
-
-void TDEApplicationPropsPlugin::slotDelExtension()
-{
- TQListBoxItem *item = extensionsList->firstItem();
- TQListBoxItem *nextItem;
-
- while ( item )
- {
- nextItem = item->next();
-
- if ( item->isSelected() )
- {
- availableExtensionsList->insertItem( item->text() );
- extensionsList->removeItem( extensionsList->index( item ) );
- }
-
- item = nextItem;
- }
-
- availableExtensionsList->sort();
- updateButton();
-}
-
-
-
-#include "kpropertiesdialog.moc"
diff --git a/kio/kfile/kpropertiesdialog.h b/kio/kfile/kpropertiesdialog.h
deleted file mode 100644
index 3f6d48c6a..000000000
--- a/kio/kfile/kpropertiesdialog.h
+++ /dev/null
@@ -1,918 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
- Copyright (c) 1999, 2000 Preston Brown <pbrown@kde.org>
- Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
- Copyright (c) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/*
- * This file holds the definitions for all classes used to
- * display a properties dialog.
- */
-
-#ifndef __propsdlg_h
-#define __propsdlg_h
-
-#include <tqstring.h>
-#include <tqptrlist.h>
-
-#include <kdemacros.h>
-#include <kurl.h>
-#include <kfileitem.h>
-#include <kdialogbase.h>
-
-class TQLineEdit;
-class TQCheckBox;
-class TQPushButton;
-class KLineEdit;
-class KURLRequester;
-class TQButton;
-class KIconButton;
-class KPropsDlgPlugin;
-class TQComboBox;
-
-#define KPropsPage KPropsDlgPlugin
-
-namespace TDEIO { class Job; }
-
-/**
- * The main properties dialog class.
- * A Properties Dialog is a dialog which displays various information
- * about a particular file or URL, or several files or URLs.
- * This main class holds various related classes, which are instantiated in
- * the form of tab entries in the tabbed dialog that this class provides.
- * The various tabs themselves will let the user view, and sometimes change,
- * information about the file or URL.
- *
- * \image html kpropertiesdialog.png "Typical KProperties Dialog"
- *
- * This class must be created with (void)new KPropertiesDialog(...)
- * It will take care of deleting itself.
- *
- * If you are looking for more flexibility, see KFileMetaInfo and
- * KFileMetaInfoWidget.
- */
-class TDEIO_EXPORT KPropertiesDialog : public KDialogBase
-{
- Q_OBJECT
-
-public:
-
- /**
- * Determine whether there are any property pages available for the
- * given file items.
- * @param _items the list of items to check.
- * @return true if there are any property pages, otherwise false.
- */
- static bool canDisplay( KFileItemList _items );
-
- /**
- * Brings up a Properties dialog, as shown above.
- * This is the normal constructor for
- * file-manager type applications, where you have a KFileItem instance
- * to work with. Normally you will use this
- * method rather than the one below.
- *
- * @param item file item whose properties should be displayed.
- * @param parent is the parent of the dialog widget.
- * @param name is the internal name.
- * @param modal tells the dialog whether it should be modal.
- * @param autoShow tells the dialog whether it should show itself automatically.
- */
- KPropertiesDialog( KFileItem * item,
- TQWidget* parent = 0L, const char* name = 0L,
- bool modal = false, bool autoShow = true);
-
- /**
- * \overload
- *
- * You use this constructor for cases where you have a number of items,
- * rather than a single item. Be careful which methods you use
- * when passing a list of files or URLs, since some of them will only
- * work on the first item in a list.
- *
- * @param _items list of file items whose properties should be displayed.
- * @param parent is the parent of the dialog widget.
- * @param name is the internal name.
- * @param modal tells the dialog whether it should be modal.
- * @param autoShow tells the dialog whether it should show itself automatically.
- */
- KPropertiesDialog( KFileItemList _items,
- TQWidget *parent = 0L, const char* name = 0L,
- bool modal = false, bool autoShow = true);
-
-#ifndef KDE_NO_COMPAT
- /**
- * @deprecated You should use the following constructor instead of this one.
- * The only change that is required is to delete the _mode argument.
- *
- * @param _url the URL whose properties should be displayed
- * @param _mode unused.
- * @param parent is the parent of the dialog widget.
- * @param name is the internal name.
- * @param modal tells the dialog whether it should be modal.
- * @param autoShow tells the dialog whether it should show itself automatically. */
- KPropertiesDialog( const KURL& _url, mode_t _mode,
- TQWidget* parent = 0L, const char* name = 0L,
- bool modal = false, bool autoShow = true) KDE_DEPRECATED;
-#endif
-
- /**
- * Brings up a Properties dialog. Convenience constructor for
- * non-file-manager applications, where you have a KURL rather than a
- * KFileItem or KFileItemList.
- *
- * @param _url the URL whose properties should be displayed
- * @param parent is the parent of the dialog widget.
- * @param name is the internal name.
- * @param modal tells the dialog whether it should be modal.
- * IMPORTANT: This constructor, together with modal=true, leads to a grave
- * display bug (due to TDEIO::stat() being run before the dialog has all the
- * necessary information). Do not use this combination for now.
- * For local files with a known mimetype, simply create a KFileItem and pass
- * it to the other constructor.
- *
- * @param autoShow tells the dialog whethr it should show itself automatically.
- */
- KPropertiesDialog( const KURL& _url,
- TQWidget* parent = 0L, const char* name = 0L,
- bool modal = false, bool autoShow = true);
-
- /**
- * Creates a properties dialog for a new .desktop file (whose name
- * is not known yet), based on a template. Special constructor for
- * "File / New" in file-manager type applications.
- *
- * @param _tempUrl template used for reading only
- * @param _currentDir directory where the file will be written to
- * @param _defaultName something to put in the name field,
- * like mimetype.desktop
- * @param parent is the parent of the dialog widget.
- * @param name is the internal name.
- * @param modal tells the dialog whether it should be modal.
- * @param autoShow tells the dialog whethr it should show itself automatically.
- */
- KPropertiesDialog( const KURL& _tempUrl, const KURL& _currentDir,
- const TQString& _defaultName,
- TQWidget* parent = 0L, const char* name = 0L,
- bool modal = false, bool autoShow = true);
-
- /**
- * Creates an empty properties dialog (for applications that want use
- * a standard dialog, but for things not doable via the plugin-mechanism).
- *
- * @param title is the string display as the "filename" in the caption of the dialog.
- * @param parent is the parent of the dialog widget.
- * @param name is the internal name.
- * @param modal tells the dialog whether it should be modal.
- */
- KPropertiesDialog (const TQString& title,
- TQWidget* parent = 0L, const char* name = 0L, bool modal = false);
-
- /**
- * Cleans up the properties dialog and frees any associated resources,
- * including the dialog itself. Note that when a properties dialog is
- * closed it cleans up and deletes itself.
- */
- virtual ~KPropertiesDialog();
-
- /**
- * Immediately displays a Properties dialog using constructor with
- * the same parameters.
- * On MS Windows, if @p item points to a local file, native (non modal) property
- * dialog is displayed (@p parent and @p modal are ignored in this case).
- *
- * @return true on succesfull dialog displaying (can be false on win32).
- * @since 3.4
- */
- static bool showDialog(KFileItem* item, TQWidget* parent = 0,
- const char* name = 0, bool modal = false);
-
- /**
- * Immediately displays a Properties dialog using constructor with
- * the same parameters.
- * On MS Windows, if @p _url points to a local file, native (non modal) property
- * dialog is displayed (@p parent and @p modal are ignored in this case).
- *
- * @return true on succesfull dialog displaying (can be false on win32).
- * @since 3.4
- */
- static bool showDialog(const KURL& _url, TQWidget* parent = 0,
- const char* name = 0, bool modal = false);
-
- /**
- * Immediately displays a Properties dialog using constructor with
- * the same parameters.
- * On MS Windows, if @p _items has one element and this element points
- * to a local file, native (non modal) property dialog is displayed
- * (@p parent and @p modal are ignored in this case).
- *
- * @return true on succesfull dialog displaying (can be false on win32).
- * @since 3.4
- */
- static bool showDialog(const KFileItemList& _items, TQWidget* parent = 0,
- const char* name = 0, bool modal = false);
-
- /**
- * Adds a "3rd party" properties plugin to the dialog. Useful
- * for extending the properties mechanism.
- *
- * To create a new plugin type, inherit from the base class KPropsDlgPlugin
- * and implement all the methods. If you define a service .desktop file
- * for your plugin, you do not need to call insertPlugin().
- *
- * @param plugin is a pointer to the KPropsDlgPlugin. The Properties
- * dialog will do destruction for you. The KPropsDlgPlugin \b must
- * have been created with the KPropertiesDialog as its parent.
- * @see KPropsDlgPlugin
- */
- void insertPlugin (KPropsDlgPlugin *plugin);
-
- /**
- * The URL of the file that has its properties being displayed.
- * This is only valid if the KPropertiesDialog was created/shown
- * for one file or URL.
- *
- * @return a parsed URL.
- */
- const KURL& kurl() const { return m_singleUrl; }
-
- /**
- * @return the file item for which the dialog is shown
- *
- * Warning: this method returns the first item of the list.
- * This means that you should use this only if you are sure the dialog is used
- * for a single item. Otherwise, you probably want items() instead.
- */
- KFileItem *item() { return m_items.first(); }
-
- /**
- * @return the items for which the dialog is shown
- */
- KFileItemList items() const { return m_items; }
-
- /**
- * @return a pointer to the dialog
- * @deprecated KPropertiesDialog directly inherits from KDialogBase, so use \a this instead
- */
- KDE_DEPRECATED KDialogBase* dialog() { return this; }
- /**
- * @return a pointer to the dialog
- * @deprecated KPropertiesDialog directly inherits from KDialogBase, so use \a this instead
- */
- KDE_DEPRECATED const KDialogBase* dialog() const { return this; }
-
- /**
- * If the dialog is being built from a template, this method
- * returns the current directory. If no template, it returns TQString::null.
- * See the template form of the constructor.
- *
- * @return the current directory or TQString::null
- */
- const KURL& currentDir() const { return m_currentDir; }
-
- /**
- * If the dialog is being built from a template, this method
- * returns the default name. If no template, it returns TQString::null.
- * See the template form of the constructor.
- * @return the default name or TQString::null
- */
- const TQString& defaultName() const { return m_defaultName; }
-
- /**
- * Updates the item URL (either called by rename or because
- * a global apps/mimelnk desktop file is being saved)
- * Can only be called if the dialog applies to a single file or URL.
- * @param _newUrl the new URL
- */
- void updateUrl( const KURL& _newUrl );
-
- /**
- * Renames the item to the specified name. This can only be called if
- * the dialog applies to a single file or URL.
- * @param _name new filename, encoded.
- * \see FilePropsDlgPlugin::applyChanges
- */
- void rename( const TQString& _name );
-
- /**
- * To abort applying changes.
- */
- void abortApplying();
-
- /**
- * Shows the page that was previously set by
- * setFileSharingPage(), or does nothing if no page
- * was set yet.
- * \see setFileSharingPage
- * @since 3.1
- */
- void showFileSharingPage();
-
- /**
- * Sets the file sharing page.
- * This page is shown when calling showFileSharingPage().
- *
- * @param page the page to set
- * \see showFileSharingPage
- * @since 3.3
- */
- void setFileSharingPage(TQWidget* page);
-
- /**
- * Call this to make the filename lineedit readonly, to prevent the user
- * from renaming the file.
- * \param ro true if the lineedit should be read only
- * @since 3.2
- */
- void setFileNameReadOnly( bool ro );
-
-public slots:
- /**
- * Called when the user presses 'Ok'.
- */
- virtual void slotOk(); // Deletes the PropertiesDialog instance
- /**
- * Called when the user presses 'Cancel'.
- */
- virtual void slotCancel(); // Deletes the PropertiesDialog instance
-
-signals:
- /**
- * This signal is emitted when the Properties Dialog is closed (for
- * example, with OK or Cancel buttons)
- */
- void propertiesClosed();
-
- /**
- * This signal is emitted when the properties changes are applied (for
- * example, with the OK button)
- */
- void applied();
-
- /**
- * This signal is emitted when the properties changes are aborted (for
- * example, with the Cancel button)
- */
-
- void canceled();
- /**
- * Emitted before changes to @p oldUrl are saved as @p newUrl.
- * The receiver may change @p newUrl to point to an alternative
- * save location.
- */
- void saveAs(const KURL &oldUrl, KURL &newUrl);
-
-private:
-
- /**
- * Common initialization for all constructors
- */
- void init (bool modal = false, bool autoShow = true);
-
- /**
- * Inserts all pages in the dialog.
- */
- void insertPages();
-
- /**
- * The URL of the props dialog (when shown for only one file)
- */
- KURL m_singleUrl;
-
- /**
- * List of items this props dialog is shown for
- */
- KFileItemList m_items;
-
- /**
- * For templates
- */
- TQString m_defaultName;
- KURL m_currentDir;
-
- /**
- * List of all plugins inserted ( first one first )
- */
- TQPtrList<KPropsDlgPlugin> m_pageList;
-
-private slots:
- void slotStatResult( TDEIO::Job * ); // No longer used
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KPropertiesDialogPrivate;
- KPropertiesDialogPrivate *d;
-};
-
-/**
- * A Plugin in the Properties dialog
- * This is an abstract class. You must inherit from this class
- * to build a new kind of tabbed page for the KPropertiesDialog.
- * A plugin in itself is just a library containing code, not a dialog's page.
- * It's up to the plugin to insert pages into the parent dialog.
- *
- * To make a plugin available, define a service that implements the KPropsDlg/Plugin
- * servicetype, as well as the mimetypes for which the plugin should be created.
- * For instance, ServiceTypes=KPropsDlg/Plugin,text/html,application/x-mymimetype.
- *
- * You can also include X-TDE-Protocol=file if you want that plugin
- * to be loaded only for local files, for instance.
- */
-class TDEIO_EXPORT KPropsDlgPlugin : public TQObject
-{
- Q_OBJECT
-public:
- /**
- * Constructor
- * To insert tabs into the properties dialog, use the add methods provided by
- * KDialogBase (the properties dialog is a KDialogBase).
- */
- KPropsDlgPlugin( KPropertiesDialog *_props );
- virtual ~KPropsDlgPlugin();
-
- /**
- * Applies all changes to the file.
- * This function is called when the user presses 'Ok'. The last plugin inserted
- * is called first.
- */
- virtual void applyChanges();
-
- /**
- * Convenience method for most ::supports methods
- * @return true if the file is a local, regular, readable, desktop file
- */
- static bool isDesktopFile( KFileItem * _item );
-
- void setDirty( bool b );
- bool isDirty() const;
-
-public slots:
- void setDirty(); // same as setDirty( true )
-
-signals:
- /**
- * Emit this signal when the user changed anything in the plugin's tabs.
- * The hosting PropertiesDialog will call applyChanges only if the
- * PropsPlugin has emitted this signal before.
- */
- void changed();
-
-protected:
- /**
- * Pointer to the dialog
- */
- KPropertiesDialog *properties;
-
- int fontHeight;
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KPropsDlgPluginPrivate;
- KPropsDlgPluginPrivate *d;
-};
-
-/**
- * 'General' plugin
- * This plugin displays the name of the file, its size and access times.
- * @internal
- */
-class TDEIO_EXPORT KFilePropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- /**
- * Constructor
- */
- KFilePropsPlugin( KPropertiesDialog *_props );
- virtual ~KFilePropsPlugin();
-
- /**
- * Applies all changes made. This plugin must be always the first
- * plugin in the dialog, since this function may rename the file which
- * may confuse other applyChanges functions.
- */
- virtual void applyChanges();
-
- /**
- * Tests whether the files specified by _items need a 'General' plugin.
- */
- static bool supports( KFileItemList _items );
-
- /**
- * Called after all plugins applied their changes
- */
- void postApplyChanges();
-
- void setFileNameReadOnly( bool ro );
-
-protected slots:
- void slotEditFileType();
- void slotCopyFinished( TDEIO::Job * );
- void slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & );
- void slotDirSizeUpdate();
- void slotDirSizeFinished( TDEIO::Job * );
- void slotFoundMountPoint( const TQString& mp, unsigned long kBSize,
- unsigned long kBUsed, unsigned long kBAvail );
- void slotSizeStop();
- void slotSizeDetermine();
-
-private slots:
- // workaround for compiler bug
- void slotFoundMountPoint( const unsigned long& kBSize, const unsigned long&
- kBUsed, const unsigned long& kBAvail, const TQString& mp );
- void nameFileChanged(const TQString &text );
- void slotIconChanged();
-
-private:
- void determineRelativePath( const TQString & path );
- void applyIconChanges();
-
- TQWidget *iconArea;
- TQWidget *nameArea;
-
- TQLabel *m_sizeLabel;
- TQPushButton *m_sizeDetermineButton;
- TQPushButton *m_sizeStopButton;
-
- TQString m_sRelativePath;
- bool m_bFromTemplate;
-
- /**
- * The initial filename
- */
- TQString oldName;
-
- class KFilePropsPluginPrivate;
- KFilePropsPluginPrivate *d;
-};
-
-/**
- * 'Permissions' plugin
- * In this plugin you can modify permissions and change
- * the owner of a file.
- * @internal
- */
-class TDEIO_EXPORT KFilePermissionsPropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- enum PermissionsMode {
- PermissionsOnlyFiles = 0,
- PermissionsOnlyDirs = 1,
- PermissionsOnlyLinks = 2,
- PermissionsMixed = 3
- };
-
- enum PermissionsTarget {
- PermissionsOwner = 0,
- PermissionsGroup = 1,
- PermissionsOthers = 2
- };
-
- /**
- * Constructor
- */
- KFilePermissionsPropsPlugin( KPropertiesDialog *_props );
- virtual ~KFilePermissionsPropsPlugin();
-
- virtual void applyChanges();
-
- /**
- * Tests whether the file specified by _items needs a 'Permissions' plugin.
- */
- static bool supports( KFileItemList _items );
-
-private slots:
-
- void slotChmodResult( TDEIO::Job * );
- void slotShowAdvancedPermissions();
-
-private:
- void setComboContent(TQComboBox *combo, PermissionsTarget target,
- mode_t permissions, mode_t partial);
- bool isIrregular(mode_t permissions, bool isDir, bool isLink);
- void enableAccessControls(bool enable);
- void updateAccessControls();
- void getPermissionMasks(mode_t &andFilePermissions,
- mode_t &andDirPermissions,
- mode_t &orFilePermissions,
- mode_t &orDirPermissions);
-
- static const mode_t permissionsMasks[3];
- static const mode_t standardPermissions[4];
- static const char *permissionsTexts[4][4];
-
- // unused, for binary compatibility!
- TQCheckBox *permBox[3][4];
-
- TQComboBox *grpCombo;
-
- KLineEdit *usrEdit, *grpEdit;
-
- /**
- * Old permissions
- */
- mode_t permissions;
- /**
- * Old group
- */
- TQString strGroup;
- /**
- * Old owner
- */
- TQString strOwner;
-
- // unused, for compatibility
- static mode_t fperm[3][4];
-
- class KFilePermissionsPropsPluginPrivate;
- KFilePermissionsPropsPluginPrivate *d;
-};
-
-
-/**
- * Used to edit the files containing
- * [Desktop Entry]
- * URL=....
- *
- * Such files are used to represent a program in kicker and konqueror.
- * @internal
- */
-class TDEIO_EXPORT KURLPropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- /**
- * Constructor
- */
- KURLPropsPlugin( KPropertiesDialog *_props );
- virtual ~KURLPropsPlugin();
-
- virtual void applyChanges();
-
- static bool supports( KFileItemList _items );
-
-private:
- KURLRequester *URLEdit;
- KIconButton *iconBox;
-
- TQString URLStr;
- TQString iconStr;
-
- TQPixmap pixmap;
- TQString pixmapFile;
-private:
- class KURLPropsPluginPrivate;
- KURLPropsPluginPrivate *d;
-};
-
-
-/**
- * Used to edit the files containing
- * [Desktop Entry]
- * Type=MimeType
- * @internal
- */
-class TDEIO_EXPORT KBindingPropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- /**
- * Constructor
- */
- KBindingPropsPlugin( KPropertiesDialog *_props );
- virtual ~KBindingPropsPlugin();
-
- virtual void applyChanges();
- static bool supports( KFileItemList _items );
-
-private:
-
- TQLineEdit *commentEdit;
- TQLineEdit *patternEdit;
- TQLineEdit *mimeEdit;
- TQString m_sMimeStr;
-
- TQCheckBox * cbAutoEmbed;
-
- class KBindingPropsPluginPrivate;
- KBindingPropsPluginPrivate *d;
-};
-
-/**
- * Properties plugin for device .desktop files
- * @internal
- */
-class TDEIO_EXPORT KDevicePropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- KDevicePropsPlugin( KPropertiesDialog *_props );
- virtual ~KDevicePropsPlugin();
-
- virtual void applyChanges();
-
- static bool supports( KFileItemList _items );
-
-private slots:
- void slotActivated( int );
- void slotDeviceChanged();
- void slotFoundMountPoint( const unsigned long& kBSize,
- const unsigned long& /*kBUsed*/,
- const unsigned long& kBAvail,
- const TQString& );
-
-private:
- void updateInfo();
-
-private:
- TQComboBox* device;
- TQLabel* mountpoint;
- TQCheckBox* readonly;
- void* unused;
- //KIconButton* mounted;
- KIconButton* unmounted;
-
- TQStringList m_devicelist;
- int indexDevice;
- int indexMountPoint;
- int indexFSType;
-
- TQPixmap pixmap;
- TQString pixmapFile;
-
- class KDevicePropsPluginPrivate;
- KDevicePropsPluginPrivate *d;
-};
-
-class KPropertiesDesktopBase;
-
-/**
- * Used to edit the files containing
- * [Desktop Entry]
- * Type=Application
- *
- * Such files are used to represent a program in kicker and konqueror.
- * @internal
- */
-class TDEIO_EXPORT KDesktopPropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- /**
- * Constructor
- */
- KDesktopPropsPlugin( KPropertiesDialog *_props );
- virtual ~KDesktopPropsPlugin();
-
- virtual void applyChanges();
-
- static bool supports( KFileItemList _items );
-
-public slots:
- void slotAddFiletype();
- void slotDelFiletype();
- void slotBrowseExec();
- void slotAdvanced();
- void slotSelectMimetype();
-
-private:
- void checkCommandChanged();
-
-private:
- KPropertiesDesktopBase* w;
-
- TQString m_origCommandStr;
- TQString m_terminalOptionStr;
- TQString m_suidUserStr;
- TQString m_dcopServiceType;
- bool m_terminalBool;
- bool m_terminalCloseBool;
- bool m_suidBool;
- bool m_startupBool;
- bool m_systrayBool;
-
- class KDesktopPropsPluginPrivate;
- KDesktopPropsPluginPrivate *d;
-};
-
-/**
- * Used to edit the files containing
- * [Desktop Entry]
- * Type=Application
- *
- * Such files are used to represent a program in kicker and konqueror.
- * @internal
- * @deprecated replaced with KDesktopPropsPlugin
- */
- /// Remove in KDE4
-class TDEIO_EXPORT_DEPRECATED KExecPropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- /**
- * Constructor
- */
- KExecPropsPlugin( KPropertiesDialog *_props );
- virtual ~KExecPropsPlugin();
-
- virtual void applyChanges();
-
- static bool supports( KFileItemList _items );
-
-public slots:
- void slotBrowseExec();
-
-private slots:
- void enableCheckedEdit();
- void enableSuidEdit();
-
-private:
-
- TQLabel *terminalLabel;
- TQLabel *suidLabel;
- KLineEdit *execEdit;
- TQCheckBox *terminalCheck;
- TQCheckBox *suidCheck;
- KLineEdit *terminalEdit;
- KLineEdit *suidEdit;
- KLineEdit *swallowExecEdit;
- KLineEdit *swallowTitleEdit;
- TQButton *execBrowse;
-
- TQString execStr;
- TQString swallowExecStr;
- TQString swallowTitleStr;
- TQString termOptionsStr;
- bool termBool;
- bool suidBool;
- TQString suidUserStr;
-
- class KExecPropsPluginPrivate;
- KExecPropsPluginPrivate *d;
-};
-
-/**
- * Used to edit the files containing
- * [Desktop Entry]
- * Type=Application
- *
- * Such files are used to represent a program in kicker and konqueror.
- * @internal
- * @deprecated replaced with KDesktopPropsPlugin
- */
- /// Remove in KDE4
-class TDEIO_EXPORT_DEPRECATED TDEApplicationPropsPlugin : public KPropsDlgPlugin
-{
- Q_OBJECT
-public:
- /**
- * Constructor
- */
- TDEApplicationPropsPlugin( KPropertiesDialog *_props );
- virtual ~TDEApplicationPropsPlugin();
-
- virtual void applyChanges();
-
- static bool supports( KFileItemList _items );
-
-public slots:
- void slotDelExtension();
- void slotAddExtension();
-
-private slots:
- void updateButton();
-
-private:
- void addMimeType( const TQString & name );
-
- TQLineEdit *commentEdit;
- TQLineEdit *genNameEdit;
- TQLineEdit *nameEdit;
- TQListBox *extensionsList;
- TQListBox *availableExtensionsList;
- TQPushButton *addExtensionButton;
- TQPushButton *delExtensionButton;
-
- class TDEApplicationPropsPluginPrivate;
- TDEApplicationPropsPluginPrivate *d;
-};
-
-#endif
-
diff --git a/kio/kfile/kurlbar.cpp b/kio/kfile/kurlbar.cpp
deleted file mode 100644
index 95f30ee24..000000000
--- a/kio/kfile/kurlbar.cpp
+++ /dev/null
@@ -1,1049 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation, version 2.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <unistd.h>
-
-#include <tqapplication.h>
-#include <tqcheckbox.h>
-#include <tqdrawutil.h>
-#include <tqfontmetrics.h>
-#include <tqlabel.h>
-#include <tqgrid.h>
-#include <tqpainter.h>
-#include <tqpopupmenu.h>
-#include <tqstyle.h>
-#include <tqvbox.h>
-#include <tqwhatsthis.h>
-
-#include <kaboutdata.h>
-#include <kconfig.h>
-#include <kdebug.h>
-#include <kglobal.h>
-#include <kicondialog.h>
-#include <kiconloader.h>
-#include <kinstance.h>
-#include <klineedit.h>
-#include <klocale.h>
-#include <kmimetype.h>
-#include <kprotocolinfo.h>
-#include <kstringhandler.h>
-#include <kurldrag.h>
-#include <kurlrequester.h>
-#include <kio/global.h>
-#include <kio/netaccess.h>
-
-#include "kurlbar.h"
-
-/**
- * Handles tooltips in the KURLBar
- * @internal
- */
-class KURLBarToolTip : public TQToolTip
-{
-public:
- KURLBarToolTip( TQListBox *view ) : TQToolTip( view ), m_view( view ) {}
-
-protected:
- virtual void maybeTip( const TQPoint& point ) {
- TQListBoxItem *item = m_view->itemAt( point );
- if ( item ) {
- TQString text = static_cast<KURLBarItem*>( item )->toolTip();
- if ( !text.isEmpty() )
- tip( m_view->itemRect( item ), text );
- }
- }
-
-private:
- TQListBox *m_view;
-};
-
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-class KURLBarItem::KURLBarItemPrivate
-{
-public:
- KURLBarItemPrivate()
- {
- isPersistent = true;
- }
-
- bool isPersistent;
-};
-
-KURLBarItem::KURLBarItem( KURLBar *parent,
- const KURL& url, bool persistent, const TQString& description,
- const TQString& icon, KIcon::Group group )
- : TQListBoxPixmap( KIconLoader::unknown() /*, parent->listBox()*/ ),
- m_url( url ),
- m_pixmap( 0L ),
- m_parent( parent ),
- m_appLocal( true )
-{
- init( icon, group, description, persistent );
-}
-
-KURLBarItem::KURLBarItem( KURLBar *parent,
- const KURL& url, const TQString& description,
- const TQString& icon, KIcon::Group group )
- : TQListBoxPixmap( KIconLoader::unknown() /*, parent->listBox()*/ ),
- m_url( url ),
- m_pixmap( 0L ),
- m_parent( parent ),
- m_appLocal( true )
-{
- init( icon, group, description, true /*persistent*/ );
-}
-
-void KURLBarItem::init( const TQString& icon, KIcon::Group group,
- const TQString& description, bool persistent )
-{
- d = new KURLBarItemPrivate;
- d->isPersistent = persistent;
-
- setCustomHighlighting( true );
- setIcon( icon, group );
- setDescription( description );
-}
-
-KURLBarItem::~KURLBarItem()
-{
- delete d;
-}
-
-void KURLBarItem::setURL( const KURL& url )
-{
- m_url = url;
- if ( m_description.isEmpty() )
- setText( url.fileName() );
-}
-
-void KURLBarItem::setIcon( const TQString& icon, KIcon::Group group )
-{
- m_icon = icon;
- m_group = group;
-
- if ( icon.isEmpty() )
- m_pixmap = KMimeType::pixmapForURL( m_url, 0, group, iconSize() );
- else
- m_pixmap = TDEGlobal::iconLoader()->loadIcon( icon, group, iconSize(),
- KIcon::DefaultState );
-}
-
-void KURLBarItem::setDescription( const TQString& desc )
-{
- m_description = desc;
- setText( desc.isEmpty() ? m_url.fileName() : desc );
-}
-
-void KURLBarItem::setApplicationLocal( bool local )
-{
- if ( !local && !isPersistent() )
- {
- kdWarning() << "KURLBar: dynamic (non-persistent) items can not be global." << endl;
- return;
- }
-
- m_appLocal = local;
-}
-
-void KURLBarItem::setToolTip( const TQString& tip )
-{
- m_toolTip = tip;
-}
-
-TQString KURLBarItem::toolTip() const
-{
- return m_toolTip.isEmpty() ? m_url.prettyURL() : m_toolTip;
-}
-
-int KURLBarItem::iconSize() const
-{
- return m_parent->iconSize();
-}
-
-void KURLBarItem::paint( TQPainter *p )
-{
- TQListBox *box = listBox();
- int w = width( box );
- static const int margin = KDialog::spacingHint();
-
- // draw sunken selection
- if ( isCurrent() || isSelected() ) {
- int h = height( box );
-
- TQBrush brush = box->colorGroup().brush( TQColorGroup::Highlight );
- p->fillRect( 0, 0, w, h, brush );
- TQPen pen = p->pen();
- TQPen oldPen = pen;
- pen.setColor( box->colorGroup().mid() );
- p->setPen( pen );
-
- p->drawPoint( 0, 0 );
- p->drawPoint( 0, h - 1 );
- p->drawPoint( w - 1, 0 );
- p->drawPoint( w - 1, h - 1 );
-
- p->setPen( oldPen );
- }
-
- if ( m_parent->iconSize() < KIcon::SizeMedium ) {
- // small icon -> draw icon next to text
-
- // ### mostly cut & paste of TQListBoxPixmap::paint() until Qt 3.1
- // (where it will properly use pixmap() instead of the internal pixmap)
- const TQPixmap *pm = pixmap();
- int yPos = QMAX( 0, (height(box) - pm->height())/2 );
-
- p->drawPixmap( margin, yPos, *pm );
- if ( !text().isEmpty() ) {
- TQFontMetrics fm = p->fontMetrics();
- if ( pm->height() < fm.height() )
- yPos = fm.ascent() + fm.leading()/2;
- else
- yPos = pm->height()/2 - fm.height()/2 + fm.ascent();
-
- yPos += margin;
- int stringWidth = box->width() - pm->width() - 2 - (margin * 2);
- TQString visibleText = KStringHandler::rPixelSqueeze( text(), fm, stringWidth );
- int xPos = pm->width() + margin + 2;
-
- if ( isCurrent() || isSelected() ) {
- p->setPen( box->colorGroup().highlight().dark(115) );
- p->drawText( xPos + ( TQApplication::reverseLayout() ? -1 : 1),
- yPos + 1, visibleText );
- p->setPen( box->colorGroup().highlightedText() );
- }
-
- p->drawText( xPos, yPos, visibleText );
- }
- // end cut & paste (modulo pixmap centering)
- }
-
- else {
- // big icons -> draw text below icon
- int y = margin;
- const TQPixmap *pm = pixmap();
-
- if ( !pm->isNull() ) {
- int x = (w - pm->width()) / 2;
- x = QMAX( x, margin );
- p->drawPixmap( x, y, *pm );
- }
-
- if ( !text().isEmpty() ) {
- TQFontMetrics fm = p->fontMetrics();
- y += pm->height() + fm.height() - fm.descent();
-
- int stringWidth = box->width() - (margin * 2);
- TQString visibleText = KStringHandler::rPixelSqueeze( text(), fm, stringWidth );
- int x = (w - fm.width( visibleText )) / 2;
- x = QMAX( x, margin );
-
- if ( isCurrent() || isSelected() ) {
- p->setPen( box->colorGroup().highlight().dark(115) );
- p->drawText( x + ( TQApplication::reverseLayout() ? -1 : 1),
- y + 1, visibleText );
- p->setPen( box->colorGroup().highlightedText() );
- }
-
- p->drawText( x, y, visibleText );
- }
- }
-}
-
-TQSize KURLBarItem::sizeHint() const
-{
- int wmin = 0;
- int hmin = 0;
- const KURLBarListBox *lb =static_cast<const KURLBarListBox*>(listBox());
-
- if ( m_parent->iconSize() < KIcon::SizeMedium ) {
- wmin = TQListBoxPixmap::width( lb ) + KDialog::spacingHint() * 2;
- hmin = TQListBoxPixmap::height( lb ) + KDialog::spacingHint() * 2;
- }
- else {
- wmin = QMAX(lb->fontMetrics().width(text()), pixmap()->width()) + KDialog::spacingHint() * 2;
- hmin = lb->fontMetrics().lineSpacing() + pixmap()->height() + KDialog::spacingHint() * 2;
- }
-
- if ( lb->isVertical() )
- wmin = QMIN( wmin, lb->viewport()->sizeHint().width() );
- else
- hmin = QMIN( hmin, lb->viewport()->sizeHint().height() );
-
- return TQSize( wmin, hmin );
-}
-
-int KURLBarItem::width( const TQListBox *lb ) const
-{
- if ( static_cast<const KURLBarListBox *>( lb )->isVertical() )
- return QMAX( sizeHint().width(), lb->viewport()->width() );
- else
- return sizeHint().width();
-}
-
-int KURLBarItem::height( const TQListBox *lb ) const
-{
- if ( static_cast<const KURLBarListBox *>( lb )->isVertical() )
- return sizeHint().height();
- else
- return QMAX( sizeHint().height(), lb->viewport()->height() );
-}
-
-bool KURLBarItem::isPersistent() const
-{
- return d->isPersistent;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-class KURLBar::KURLBarPrivate
-{
-public:
- KURLBarPrivate()
- {
- currentURL.setPath( TQDir::homeDirPath() );
- defaultIconSize = 0;
- }
-
- int defaultIconSize;
- KURL currentURL;
-};
-
-
-KURLBar::KURLBar( bool useGlobalItems, TQWidget *parent, const char *name, WFlags f )
- : TQFrame( parent, name, f ),
- m_activeItem( 0L ),
- m_useGlobal( useGlobalItems ),
- m_isModified( false ),
- m_isImmutable( false ),
- m_listBox( 0L ),
- m_iconSize( KIcon::SizeMedium )
-{
- d = new KURLBarPrivate();
-
- setListBox( 0L );
- setSizePolicy( TQSizePolicy( isVertical() ?
- TQSizePolicy::Maximum :
- TQSizePolicy::Preferred,
- isVertical() ?
- TQSizePolicy::Preferred :
- TQSizePolicy::Maximum ));
- TQWhatsThis::add(this, i18n("<qt>The <b>Quick Access</b> panel provides easy access to commonly used file locations.<p>"
- "Clicking on one of the shortcut entries will take you to that location.<p>"
- "By right clicking on an entry you can add, edit and remove shortcuts.</qt>"));
-}
-
-KURLBar::~KURLBar()
-{
- delete d;
-}
-
-KURLBarItem * KURLBar::insertItem(const KURL& url, const TQString& description,
- bool applicationLocal,
- const TQString& icon, KIcon::Group group )
-{
- KURLBarItem *item = new KURLBarItem(this, url, description, icon, group);
- item->setApplicationLocal( applicationLocal );
- m_listBox->insertItem( item );
- return item;
-}
-
-KURLBarItem * KURLBar::insertDynamicItem(const KURL& url, const TQString& description,
- const TQString& icon, KIcon::Group group )
-{
- KURLBarItem *item = new KURLBarItem(this, url, false, description, icon, group);
- m_listBox->insertItem( item );
- return item;
-}
-
-void KURLBar::setOrientation( Qt::Orientation orient )
-{
- m_listBox->setOrientation( orient );
- setSizePolicy( TQSizePolicy( isVertical() ?
- TQSizePolicy::Maximum :
- TQSizePolicy::Preferred,
- isVertical() ?
- TQSizePolicy::Preferred :
- TQSizePolicy::Maximum ));
-}
-
-Qt::Orientation KURLBar::orientation() const
-{
- return m_listBox->orientation();
-}
-
-void KURLBar::setListBox( KURLBarListBox *view )
-{
- delete m_listBox;
-
- if ( !view ) {
- m_listBox = new KURLBarListBox( this, "urlbar listbox" );
- setOrientation( Qt::Vertical );
- }
- else {
- m_listBox = view;
- if ( m_listBox->parentWidget() != this )
- m_listBox->reparent( this, TQPoint(0,0) );
- m_listBox->resize( width(), height() );
- }
-
- m_listBox->setSelectionMode( KListBox::Single );
- paletteChange( palette() );
- m_listBox->setFocusPolicy( TQ_TabFocus );
-
- connect( m_listBox, TQT_SIGNAL( mouseButtonClicked( int, TQListBoxItem *, const TQPoint & ) ),
- TQT_SLOT( slotSelected( int, TQListBoxItem * )));
- connect( m_listBox, TQT_SIGNAL( dropped( TQDropEvent * )),
- this, TQT_SLOT( slotDropped( TQDropEvent * )));
- connect( m_listBox, TQT_SIGNAL( contextMenuRequested( TQListBoxItem *,
- const TQPoint& )),
- TQT_SLOT( slotContextMenuRequested( TQListBoxItem *, const TQPoint& )));
- connect( m_listBox, TQT_SIGNAL( returnPressed( TQListBoxItem * ) ),
- TQT_SLOT( slotSelected( TQListBoxItem * ) ));
-}
-
-void KURLBar::setIconSize( int size )
-{
- if ( size == m_iconSize )
- return;
-
- m_iconSize = size;
-
- // reload the icons with the new size
- KURLBarItem *item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
- while ( item ) {
- item->setIcon( item->icon(), item->iconGroup() );
- item = static_cast<KURLBarItem*>( item->next() );
- }
-
- resize( sizeHint() );
- updateGeometry();
-}
-
-void KURLBar::clear()
-{
- m_listBox->clear();
-}
-
-void KURLBar::resizeEvent( TQResizeEvent *e )
-{
- TQFrame::resizeEvent( e );
- m_listBox->resize( width(), height() );
-}
-
-void KURLBar::paletteChange( const TQPalette & )
-{
- TQPalette pal = palette();
- TQColor gray = pal.color( TQPalette::Normal, TQColorGroup::Background );
- TQColor selectedTextColor = pal.color( TQPalette::Normal, TQColorGroup::BrightText );
- TQColor foreground = pal.color( TQPalette::Normal, TQColorGroup::Foreground );
- pal.setColor( TQPalette::Normal, TQColorGroup::Base, gray );
- pal.setColor( TQPalette::Normal, TQColorGroup::HighlightedText, selectedTextColor );
- pal.setColor( TQPalette::Normal, TQColorGroup::Text, foreground );
- pal.setColor( TQPalette::Inactive, TQColorGroup::Base, gray );
- pal.setColor( TQPalette::Inactive, TQColorGroup::HighlightedText, selectedTextColor );
- pal.setColor( TQPalette::Inactive, TQColorGroup::Text, foreground );
-
- setPalette( pal );
-}
-
-TQSize KURLBar::sizeHint() const
-{
- return m_listBox->sizeHint();
-
-#if 0
- // this code causes vertical and or horizontal scrollbars appearing
- // depending on the text, font, moonphase and earth rotation. Just using
- // m_listBox->sizeHint() fixes this (although the widget can then be
- // resized to a smaller size so that scrollbars appear).
- int w = 0;
- int h = 0;
- KURLBarItem *item;
- bool vertical = isVertical();
-
- for ( item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
- item;
- item = static_cast<KURLBarItem*>( item->next() ) ) {
-
- TQSize sh = item->sizeHint();
-
- if ( vertical ) {
- w = QMAX( w, sh.width() );
- h += sh.height();
- }
- else {
- w += sh.width();
- h = QMAX( h, sh.height() );
- }
- }
-
-// if ( vertical && m_listBox->verticalScrollBar()->isVisible() )
-// w += m_listBox->verticalScrollBar()->width();
-// else if ( !vertical && m_listBox->horizontalScrollBar()->isVisible() )
-// h += m_listBox->horizontalScrollBar()->height();
-
- if ( w == 0 && h == 0 )
- return TQSize( 100, 200 );
- else
- return TQSize( 6 + w, h );
-#endif
-}
-
-TQSize KURLBar::minimumSizeHint() const
-{
- TQSize s = sizeHint(); // ###
- int w = s.width() + m_listBox->verticalScrollBar()->width();
- int h = s.height() + m_listBox->horizontalScrollBar()->height();
- return TQSize( w, h );
-}
-
-void KURLBar::slotSelected( int button, TQListBoxItem *item )
-{
- if ( button != Qt::LeftButton )
- return;
-
- slotSelected( item );
-}
-
-void KURLBar::slotSelected( TQListBoxItem *item )
-{
- if ( item && item != m_activeItem )
- m_activeItem = static_cast<KURLBarItem*>( item );
-
- if ( m_activeItem ) {
- m_listBox->setCurrentItem( m_activeItem );
- emit activated( m_activeItem->url() );
- }
-}
-
-void KURLBar::setCurrentItem( const KURL& url )
-{
- d->currentURL = url;
-
- TQString u = url.url(-1);
-
- if ( m_activeItem && m_activeItem->url().url(-1) == u )
- return;
-
- bool hasURL = false;
- TQListBoxItem *item = m_listBox->firstItem();
- while ( item ) {
- if ( static_cast<KURLBarItem*>( item )->url().url(-1) == u ) {
- m_activeItem = static_cast<KURLBarItem*>( item );
- m_listBox->setCurrentItem( item );
- m_listBox->setSelected( item, true );
- hasURL = true;
- break;
- }
- item = item->next();
- }
-
- if ( !hasURL ) {
- m_activeItem = 0L;
- m_listBox->clearSelection();
- }
-}
-
-KURLBarItem * KURLBar::currentItem() const
-{
- TQListBoxItem *item = m_listBox->item( m_listBox->currentItem() );
- if ( item )
- return static_cast<KURLBarItem *>( item );
- return 0L;
-}
-
-KURL KURLBar::currentURL() const
-{
- KURLBarItem *item = currentItem();
- return item ? item->url() : KURL();
-}
-
-void KURLBar::readConfig( TDEConfig *appConfig, const TQString& itemGroup )
-{
- m_isImmutable = appConfig->groupIsImmutable( itemGroup );
- TDEConfigGroupSaver cs( appConfig, itemGroup );
- d->defaultIconSize = m_iconSize;
- m_iconSize = appConfig->readNumEntry( "Speedbar IconSize", m_iconSize );
-
- if ( m_useGlobal ) { // read global items
- TDEConfig *globalConfig = TDEGlobal::config();
- TDEConfigGroupSaver cs( globalConfig, (TQString)(itemGroup +" (Global)"));
- int num = globalConfig->readNumEntry( "Number of Entries" );
- for ( int i = 0; i < num; i++ ) {
- readItem( i, globalConfig, false );
- }
- }
-
- // read application local items
- int num = appConfig->readNumEntry( "Number of Entries" );
- for ( int i = 0; i < num; i++ ) {
- readItem( i, appConfig, true );
- }
-}
-
-void KURLBar::readItem( int i, TDEConfig *config, bool applicationLocal )
-{
- TQString number = TQString::number( i );
- KURL url = KURL::fromPathOrURL( config->readPathEntry( TQString("URL_") + number ));
- if ( !url.isValid() || !KProtocolInfo::isKnownProtocol( url ))
- return; // nothing we could do.
-
- TQString description = config->readEntry( TQString("Description_") + number );
-
- if (description.isEmpty() && url.protocol()=="beagle") {
- TDEIO::UDSEntry uds;
- const KURL kurl("beagle:?beagled-status");
- if (!TDEIO::NetAccess::stat(kurl, uds))
- return;
-
- description = i18n("Desktop Search");
- }
-
- insertItem( url,
- description,
- applicationLocal,
- config->readEntry( TQString("Icon_") + number ),
- static_cast<KIcon::Group>(
- config->readNumEntry( TQString("IconGroup_") + number )) );
-}
-
-void KURLBar::writeConfig( TDEConfig *config, const TQString& itemGroup )
-{
- TDEConfigGroupSaver cs1( config, itemGroup );
- if(!config->hasDefault("Speedbar IconSize") && m_iconSize == d->defaultIconSize )
- config->revertToDefault("Speedbar IconSize");
- else
- config->writeEntry( "Speedbar IconSize", m_iconSize );
-
- if ( !m_isModified )
- return;
-
- int i = 0;
- int numLocal = 0;
- KURLBarItem *item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
-
- while ( item )
- {
- if ( item->isPersistent() ) // we only save persistent items
- {
- if ( item->applicationLocal() )
- {
- writeItem( item, numLocal, config, false );
- numLocal++;
- }
-
- i++;
- }
- item = static_cast<KURLBarItem*>( item->next() );
- }
- config->writeEntry("Number of Entries", numLocal);
-
-
- // write the global entries to kdeglobals, if any
- bool haveGlobalEntries = (i > numLocal);
- if ( m_useGlobal && haveGlobalEntries ) {
- config->setGroup( itemGroup + " (Global)" );
-
- int numGlobals = 0;
- item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
-
- while ( item )
- {
- if ( item->isPersistent() ) // we only save persistent items
- {
- if ( !item->applicationLocal() )
- {
- writeItem( item, numGlobals, config, true );
- numGlobals++;
- }
- }
-
- item = static_cast<KURLBarItem*>( item->next() );
- }
- config->writeEntry("Number of Entries", numGlobals, true, true);
- }
-
- m_isModified = false;
-}
-
-void KURLBar::writeItem( KURLBarItem *item, int i, TDEConfig *config,
- bool global )
-{
- if ( !item->isPersistent() )
- return;
-
- TQString Description = "Description_";
- TQString URL = "URL_";
- TQString Icon = "Icon_";
- TQString IconGroup = "IconGroup_";
-
- TQString number = TQString::number( i );
- config->writePathEntry( URL + number, item->url().prettyURL(), true, global );
-
- config->writeEntry( Description + number, item->description(),true,global);
- config->writeEntry( Icon + number, item->icon(), true, global );
- config->writeEntry( IconGroup + number, item->iconGroup(), true, global );
-}
-
-
-void KURLBar::slotDropped( TQDropEvent *e )
-{
- KURL::List urls;
- if ( KURLDrag::decode( e, urls ) ) {
- KURL url;
- TQString description;
- TQString icon;
- bool appLocal = false;
-
- KURL::List::Iterator it = urls.begin();
- for ( ; it != urls.end(); ++it ) {
- (void) insertItem( *it, description, appLocal, icon );
- m_isModified = true;
- updateGeometry();
- }
- }
-}
-
-void KURLBar::slotContextMenuRequested( TQListBoxItem *_item, const TQPoint& pos )
-{
- if (m_isImmutable)
- return;
-
- KURLBarItem *item = dynamic_cast<KURLBarItem*>( _item );
-
- static const int IconSize = 10;
- static const int AddItem = 20;
- static const int EditItem = 30;
- static const int RemoveItem = 40;
-
- KURL lastURL = m_activeItem ? m_activeItem->url() : KURL();
-
- bool smallIcons = m_iconSize < KIcon::SizeMedium;
- TQPopupMenu *popup = new TQPopupMenu();
- popup->insertItem( smallIcons ?
- i18n("&Large Icons") : i18n("&Small Icons"),
- IconSize );
- popup->insertSeparator();
-
- if (item != 0L && item->isPersistent())
- {
- popup->insertItem(SmallIconSet("edit"), i18n("&Edit Entry..."), EditItem);
- popup->insertSeparator();
- }
-
- popup->insertItem(SmallIconSet("filenew"), i18n("&Add Entry..."), AddItem);
-
- if (item != 0L && item->isPersistent())
- {
- popup->insertItem( SmallIconSet("editdelete"), i18n("&Remove Entry"),
- RemoveItem );
- }
-
- int result = popup->exec( pos );
- switch ( result ) {
- case IconSize:
- setIconSize( smallIcons ? KIcon::SizeMedium : KIcon::SizeSmallMedium );
- m_listBox->triggerUpdate( true );
- break;
- case AddItem:
- addNewItem();
- break;
- case EditItem:
- editItem( static_cast<KURLBarItem *>( item ) );
- break;
- case RemoveItem:
- delete item;
- m_isModified = true;
- break;
- default: // abort
- break;
- }
-
- // reset current item
- m_activeItem = 0L;
- setCurrentItem( lastURL );
-}
-
-bool KURLBar::addNewItem()
-{
- KURLBarItem *item = new KURLBarItem( this, d->currentURL,
- i18n("Enter a description") );
- if ( editItem( item ) ) {
- m_listBox->insertItem( item );
- return true;
- }
-
- delete item;
- return false;
-}
-
-bool KURLBar::editItem( KURLBarItem *item )
-{
- if ( !item || !item->isPersistent() ) // should never happen tho
- return false;
-
- KURL url = item->url();
- TQString description = item->description();
- TQString icon = item->icon();
- bool appLocal = item->applicationLocal();
-
- if ( KURLBarItemDialog::getInformation( m_useGlobal,
- url, description,
- icon, appLocal,
- m_iconSize, this ))
- {
- item->setURL( url );
- item->setDescription( description );
- item->setIcon( icon );
- item->setApplicationLocal( appLocal );
- m_listBox->triggerUpdate( true );
- m_isModified = true;
- updateGeometry();
- return true;
- }
-
- return false;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-KURLBarListBox::KURLBarListBox( TQWidget *parent, const char *name )
- : KListBox( parent, name )
-{
- m_toolTip = new KURLBarToolTip( this );
- setAcceptDrops( true );
- viewport()->setAcceptDrops( true );
-}
-
-KURLBarListBox::~KURLBarListBox()
-{
- delete m_toolTip;
-}
-
-void KURLBarListBox::paintEvent( TQPaintEvent* )
-{
- TQPainter p(this);
- p.setPen( colorGroup().mid() );
- p.drawRect( 0, 0, width(), height() );
-}
-
-TQDragObject * KURLBarListBox::dragObject()
-{
- KURL::List urls;
- KURLBarItem *item = static_cast<KURLBarItem*>( firstItem() );
-
- while ( item ) {
- if ( item->isSelected() )
- urls.append( item->url() );
- item = static_cast<KURLBarItem*>( item->next() );
- }
-
- if ( !urls.isEmpty() ) // ### use custom drag-object with description etc.?
- return new KURLDrag( urls, this, "urlbar drag" );
-
- return 0L;
-}
-
-void KURLBarListBox::contentsDragEnterEvent( TQDragEnterEvent *e )
-{
- e->accept( KURLDrag::canDecode( e ));
-}
-
-void KURLBarListBox::contentsDropEvent( TQDropEvent *e )
-{
- emit dropped( e );
-}
-
-void KURLBarListBox::contextMenuEvent( TQContextMenuEvent *e )
-{
- if (e)
- {
- emit contextMenuRequested( itemAt( e->globalPos() ), e->globalPos() );
- e->consume(); // Consume the event to avoid multiple contextMenuEvent calls...
- }
-}
-
-void KURLBarListBox::setOrientation( Qt::Orientation orient )
-{
- if ( orient == Qt::Vertical ) {
- setColumnMode( 1 );
- setRowMode( Variable );
- }
- else {
- setRowMode( 1 );
- setColumnMode( Variable );
- }
-
- m_orientation = orient;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-bool KURLBarItemDialog::getInformation( bool allowGlobal, KURL& url,
- TQString& description, TQString& icon,
- bool& appLocal, int iconSize,
- TQWidget *parent )
-{
- KURLBarItemDialog *dialog = new KURLBarItemDialog( allowGlobal, url,
- description, icon,
- appLocal,
- iconSize, parent );
- if ( dialog->exec() == TQDialog::Accepted ) {
- // set the return parameters
- url = dialog->url();
- description = dialog->description();
- icon = dialog->icon();
- appLocal = dialog->applicationLocal();
-
- delete dialog;
- return true;
- }
-
- delete dialog;
- return false;
-}
-
-KURLBarItemDialog::KURLBarItemDialog( bool allowGlobal, const KURL& url,
- const TQString& description,
- TQString icon, bool appLocal,
- int iconSize,
- TQWidget *parent, const char *name )
- : KDialogBase( parent, name, true,
- i18n("Edit Quick Access Entry"), Ok | Cancel, Ok, true )
-{
- TQVBox *box = new TQVBox( this );
- TQString text = i18n("<qt><b>Please provide a description, URL and icon for this Quick Access entry.</b></br></qt>");
- TQLabel *label = new TQLabel( text, box );
- box->setSpacing( spacingHint() );
-
- TQGrid *grid = new TQGrid( 2, box );
- grid->setSpacing( spacingHint() );
-
- TQString whatsThisText = i18n("<qt>This is the text that will appear in the Quick Access panel.<p>"
- "The description should consist of one or two words "
- "that will help you remember what this entry refers to.</qt>");
- label = new TQLabel( i18n("&Description:"), grid );
- m_edit = new KLineEdit( grid, "description edit" );
- m_edit->setText( description.isEmpty() ? url.fileName() : description );
- label->setBuddy( m_edit );
- TQWhatsThis::add( label, whatsThisText );
- TQWhatsThis::add( m_edit, whatsThisText );
-
- whatsThisText = i18n("<qt>This is the location associated with the entry. Any valid URL may be used. For example:<p>"
- "%1<br>http://www.kde.org<br>ftp://ftp.kde.org/pub/kde/stable<p>"
- "By clicking on the button next to the text edit box you can browse to an "
- "appropriate URL.</qt>").arg(TQDir::homeDirPath());
- label = new TQLabel( i18n("&URL:"), grid );
- m_urlEdit = new KURLRequester( url.prettyURL(), grid );
- m_urlEdit->setMode( KFile::Directory );
- label->setBuddy( m_urlEdit );
- TQWhatsThis::add( label, whatsThisText );
- TQWhatsThis::add( m_urlEdit, whatsThisText );
-
- whatsThisText = i18n("<qt>This is the icon that will appear in the Quick Access panel.<p>"
- "Click on the button to select a different icon.</qt>");
- label = new TQLabel( i18n("Choose an &icon:"), grid );
- m_iconButton = new KIconButton( grid, "icon button" );
- m_iconButton->setIconSize( iconSize );
- if ( icon.isEmpty() )
- icon = KMimeType::iconForURL( url );
- m_iconButton->setIcon( icon );
- label->setBuddy( m_iconButton );
- TQWhatsThis::add( label, whatsThisText );
- TQWhatsThis::add( m_iconButton, whatsThisText );
-
- if ( allowGlobal ) {
- TQString appName;
- if ( TDEGlobal::instance()->aboutData() )
- appName = TDEGlobal::instance()->aboutData()->programName();
- if ( appName.isEmpty() )
- appName = TQString::fromLatin1( TDEGlobal::instance()->instanceName() );
- m_appLocal = new TQCheckBox( i18n("&Only show when using this application (%1)").arg( appName ), box );
- m_appLocal->setChecked( appLocal );
- TQWhatsThis::add( m_appLocal,
- i18n("<qt>Select this setting if you want this "
- "entry to show only when using the current application (%1).<p>"
- "If this setting is not selected, the entry will be available in all "
- "applications.</qt>")
- .arg(appName));
- }
- else
- m_appLocal = 0L;
- connect(m_urlEdit->lineEdit(),TQT_SIGNAL(textChanged ( const TQString & )),this,TQT_SLOT(urlChanged(const TQString & )));
- m_edit->setFocus();
- setMainWidget( box );
-}
-
-KURLBarItemDialog::~KURLBarItemDialog()
-{
-}
-
-void KURLBarItemDialog::urlChanged(const TQString & text )
-{
- enableButtonOK( !text.isEmpty() );
-}
-
-KURL KURLBarItemDialog::url() const
-{
- TQString text = m_urlEdit->url();
- KURL u;
- if ( text.at(0) == '/' )
- u.setPath( text );
- else
- u = text;
-
- return u;
-}
-
-TQString KURLBarItemDialog::description() const
-{
- return m_edit->text();
-}
-
-TQString KURLBarItemDialog::icon() const
-{
- return m_iconButton->icon();
-}
-
-bool KURLBarItemDialog::applicationLocal() const
-{
- if ( !m_appLocal )
- return true;
-
- return m_appLocal->isChecked();
-}
-
-void KURLBarItem::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-void KURLBar::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-void KURLBarListBox::virtual_hook( int id, void* data )
-{ KListBox::virtual_hook( id, data ); }
-
-
-#include "kurlbar.moc"
diff --git a/kio/kfile/kurlrequester.cpp b/kio/kfile/kurlrequester.cpp
deleted file mode 100644
index 99e6e96f0..000000000
--- a/kio/kfile/kurlrequester.cpp
+++ /dev/null
@@ -1,430 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1999,2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2, as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <tqstring.h>
-#include <tqtooltip.h>
-#include <tqapplication.h>
-
-#include <kaccel.h>
-#include <kcombobox.h>
-#include <kdebug.h>
-#include <kdialog.h>
-#include <kdirselectdialog.h>
-#include <kfiledialog.h>
-#include <kglobal.h>
-#include <kiconloader.h>
-#include <klineedit.h>
-#include <klocale.h>
-#include <kurlcompletion.h>
-#include <kurldrag.h>
-#include <kprotocolinfo.h>
-
-#include "kurlrequester.h"
-
-
-class KURLDragPushButton : public KPushButton
-{
-public:
- KURLDragPushButton( TQWidget *parent, const char *name=0 )
- : KPushButton( parent, name ) {
- setDragEnabled( true );
- }
- ~KURLDragPushButton() {}
-
- void setURL( const KURL& url ) {
- m_urls.clear();
- m_urls.append( url );
- }
-
- /* not needed so far
- void setURLs( const KURL::List& urls ) {
- m_urls = urls;
- }
- const KURL::List& urls() const { return m_urls; }
- */
-
-protected:
- virtual TQDragObject *dragObject() {
- if ( m_urls.isEmpty() )
- return 0L;
-
- TQDragObject *drag = new KURLDrag( m_urls, this, "url drag" );
- return drag;
- }
-
-private:
- KURL::List m_urls;
-
-};
-
-
-/*
-*************************************************************************
-*/
-
-class KURLRequester::KURLRequesterPrivate
-{
-public:
- KURLRequesterPrivate() {
- edit = 0L;
- combo = 0L;
- fileDialogMode = KFile::File | KFile::ExistingOnly | KFile::LocalOnly;
- }
-
- void setText( const TQString& text ) {
- if ( combo )
- {
- if (combo->editable())
- {
- combo->setEditText( text );
- }
- else
- {
- combo->insertItem( text );
- combo->setCurrentItem( combo->count()-1 );
- }
- }
- else
- {
- edit->setText( text );
- }
- }
-
- void connectSignals( TQObject *receiver ) {
- TQObject *sender;
- if ( combo )
- sender = TQT_TQOBJECT(combo);
- else
- sender = TQT_TQOBJECT(edit);
-
- connect( sender, TQT_SIGNAL( textChanged( const TQString& )),
- receiver, TQT_SIGNAL( textChanged( const TQString& )));
- connect( sender, TQT_SIGNAL( returnPressed() ),
- receiver, TQT_SIGNAL( returnPressed() ));
- connect( sender, TQT_SIGNAL( returnPressed( const TQString& ) ),
- receiver, TQT_SIGNAL( returnPressed( const TQString& ) ));
- }
-
- void setCompletionObject( KCompletion *comp ) {
- if ( combo )
- combo->setCompletionObject( comp );
- else
- edit->setCompletionObject( comp );
- }
-
- /**
- * replaces ~user or $FOO, if necessary
- */
- TQString url() {
- TQString txt = combo ? combo->currentText() : edit->text();
- KURLCompletion *comp;
- if ( combo )
- comp = dynamic_cast<KURLCompletion*>(combo->completionObject());
- else
- comp = dynamic_cast<KURLCompletion*>(edit->completionObject());
-
- if ( comp )
- return comp->replacedPath( txt );
- else
- return txt;
- }
-
- KLineEdit *edit;
- KComboBox *combo;
- int fileDialogMode;
- TQString fileDialogFilter;
-};
-
-
-
-KURLRequester::KURLRequester( TQWidget *editWidget, TQWidget *parent,
- const char *name )
- : TQHBox( parent, name )
-{
- d = new KURLRequesterPrivate;
-
- // must have this as parent
- editWidget->reparent( this, 0, TQPoint(0,0) );
- d->edit = dynamic_cast<KLineEdit*>( editWidget );
- d->combo = dynamic_cast<KComboBox*>( editWidget );
-
- init();
-}
-
-
-KURLRequester::KURLRequester( TQWidget *parent, const char *name )
- : TQHBox( parent, name )
-{
- d = new KURLRequesterPrivate;
- init();
-}
-
-
-KURLRequester::KURLRequester( const TQString& url, TQWidget *parent,
- const char *name )
- : TQHBox( parent, name )
-{
- d = new KURLRequesterPrivate;
- init();
- setKURL( KURL::fromPathOrURL( url ) );
-}
-
-
-KURLRequester::~KURLRequester()
-{
- delete myCompletion;
- delete myFileDialog;
- delete d;
-}
-
-
-void KURLRequester::init()
-{
- myFileDialog = 0L;
- myShowLocalProt = false;
-
- if ( !d->combo && !d->edit )
- d->edit = new KLineEdit( this, "line edit" );
-
- myButton = new KURLDragPushButton( this, "kfile button");
- TQIconSet iconSet = SmallIconSet(TQString::fromLatin1("fileopen"));
- TQPixmap pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
- myButton->setIconSet( iconSet );
- myButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
- TQToolTip::add(myButton, i18n("Open file dialog"));
-
- connect( myButton, TQT_SIGNAL( pressed() ), TQT_SLOT( slotUpdateURL() ));
-
- setSpacing( KDialog::spacingHint() );
-
- TQWidget *widget = d->combo ? (TQWidget*) d->combo : (TQWidget*) d->edit;
- widget->installEventFilter( this );
- setFocusProxy( widget );
-
- d->connectSignals( TQT_TQOBJECT(this) );
- connect( myButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotOpenDialog() ));
-
- myCompletion = new KURLCompletion();
- d->setCompletionObject( myCompletion );
-
- KAccel *accel = new KAccel( this );
- accel->insert( KStdAccel::Open, TQT_TQOBJECT(this), TQT_SLOT( slotOpenDialog() ));
- accel->readSettings();
-}
-
-
-void KURLRequester::setURL( const TQString& url )
-{
- if ( myShowLocalProt )
- {
- d->setText( url );
- }
- else
- {
- // ### This code is broken (e.g. for paths with '#')
- if ( url.startsWith("file://") )
- d->setText( url.mid( 7 ) );
- else if ( url.startsWith("file:") )
- d->setText( url.mid( 5 ) );
- else
- d->setText( url );
- }
-}
-
-void KURLRequester::setKURL( const KURL& url )
-{
- if ( myShowLocalProt )
- d->setText( url.url() );
- else
- d->setText( url.pathOrURL() );
-}
-
-void KURLRequester::setCaption( const TQString& caption )
-{
- TQWidget::setCaption( caption );
- if (myFileDialog)
- myFileDialog->setCaption( caption );
-}
-
-TQString KURLRequester::url() const
-{
- return d->url();
-}
-
-void KURLRequester::slotOpenDialog()
-{
- KURL newurl;
- if ( (d->fileDialogMode & KFile::Directory) && !(d->fileDialogMode & KFile::File) ||
- /* catch possible fileDialog()->setMode( KFile::Directory ) changes */
- (myFileDialog && ( (myFileDialog->mode() & KFile::Directory) &&
- (myFileDialog->mode() & (KFile::File | KFile::Files)) == 0 ) ) )
- {
- newurl = KDirSelectDialog::selectDirectory(url(), d->fileDialogMode & KFile::LocalOnly);
- if ( !newurl.isValid() )
- {
- return;
- }
- }
- else
- {
- emit openFileDialog( this );
-
- KFileDialog *dlg = fileDialog();
- if ( !d->url().isEmpty() ) {
- KURL u( url() );
- // If we won't be able to list it (e.g. http), then don't try :)
- if ( KProtocolInfo::supportsListing( u ) )
- dlg->setSelection( u.url() );
- }
-
- if ( dlg->exec() != TQDialog::Accepted )
- {
- return;
- }
-
- newurl = dlg->selectedURL();
- }
-
- setKURL( newurl );
- emit urlSelected( d->url() );
-}
-
-void KURLRequester::setMode(uint mode)
-{
- Q_ASSERT( (mode & KFile::Files) == 0 );
- d->fileDialogMode = mode;
- if ( (mode & KFile::Directory) && !(mode & KFile::File) )
- myCompletion->setMode( KURLCompletion::DirCompletion );
-
- if (myFileDialog)
- myFileDialog->setMode( d->fileDialogMode );
-}
-
-unsigned int KURLRequester::mode() const
-{
- return d->fileDialogMode;
-}
-
-void KURLRequester::setFilter(const TQString &filter)
-{
- d->fileDialogFilter = filter;
- if (myFileDialog)
- myFileDialog->setFilter( d->fileDialogFilter );
-}
-
-TQString KURLRequester::filter( ) const
-{
- return d->fileDialogFilter;
-}
-
-
-KFileDialog * KURLRequester::fileDialog() const
-{
- if ( !myFileDialog ) {
- TQWidget *p = parentWidget();
- myFileDialog = new KFileDialog( TQString::null, d->fileDialogFilter, p,
- "file dialog", true );
-
- myFileDialog->setMode( d->fileDialogMode );
- myFileDialog->setCaption( caption() );
- }
-
- return myFileDialog;
-}
-
-
-void KURLRequester::setShowLocalProtocol( bool b )
-{
- if ( myShowLocalProt == b )
- return;
-
- myShowLocalProt = b;
- setKURL( url() );
-}
-
-void KURLRequester::clear()
-{
- d->setText( TQString::null );
-}
-
-KLineEdit * KURLRequester::lineEdit() const
-{
- return d->edit;
-}
-
-KComboBox * KURLRequester::comboBox() const
-{
- return d->combo;
-}
-
-void KURLRequester::slotUpdateURL()
-{
- // bin compat, myButton is declared as QPushButton
- KURL u;
- u = KURL( KURL( TQDir::currentDirPath() + '/' ), url() );
- (static_cast<KURLDragPushButton *>( myButton ))->setURL( u );
-}
-
-bool KURLRequester::eventFilter( TQObject *obj, TQEvent *ev )
-{
- if ( ( TQT_BASE_OBJECT(d->edit) == TQT_BASE_OBJECT(obj) ) || ( TQT_BASE_OBJECT(d->combo) == TQT_BASE_OBJECT(obj) ) )
- {
- if (( ev->type() == TQEvent::FocusIn ) || ( ev->type() == TQEvent::FocusOut ))
- // Forward focusin/focusout events to the urlrequester; needed by file form element in tdehtml
- TQApplication::sendEvent( this, ev );
- }
- return TQWidget::eventFilter( obj, ev );
-}
-
-KPushButton * KURLRequester::button() const
-{
- return myButton;
-}
-
-KEditListBox::CustomEditor KURLRequester::customEditor()
-{
- setSizePolicy(TQSizePolicy( TQSizePolicy::Preferred,
- TQSizePolicy::Fixed));
-
- KLineEdit *edit = d->edit;
- if ( !edit && d->combo )
- edit = dynamic_cast<KLineEdit*>( d->combo->lineEdit() );
-
-#ifndef NDEBUG
- if ( !edit )
- kdWarning() << "KURLRequester's lineedit is not a KLineEdit!??\n";
-#endif
-
- KEditListBox::CustomEditor editor( this, edit );
- return editor;
-}
-
-void KURLRequester::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-KURLComboRequester::KURLComboRequester( TQWidget *parent,
- const char *name )
- : KURLRequester( new KComboBox(false), parent, name)
-{
-}
-
-#include "kurlrequester.moc"
diff --git a/kio/kfile/kurlrequester.h b/kio/kfile/kurlrequester.h
deleted file mode 100644
index aa2f6894b..000000000
--- a/kio/kfile/kurlrequester.h
+++ /dev/null
@@ -1,301 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1999,2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2, as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-
-#ifndef KURLREQUESTER_H
-#define KURLREQUESTER_H
-
-#include <tqhbox.h>
-
-#include <keditlistbox.h>
-#include <kfile.h>
-#include <kpushbutton.h>
-#include <kurl.h>
-
-class KComboBox;
-class KFileDialog;
-class KLineEdit;
-class KURLCompletion;
-class KURLDragPushButton;
-
-class TQString;
-class TQTimer;
-
-/**
- * This class is a widget showing a lineedit and a button, which invokes a
- * filedialog. File name completion is available in the lineedit.
- *
- * The defaults for the filedialog are to ask for one existing local file, i.e.
- * KFileDialog::setMode( KFile::File | KFile::ExistingOnly | KFile::LocalOnly )
- * The default filter is "*", i.e. show all files, and the start directory is
- * the current working directory, or the last directory where a file has been
- * selected.
- *
- * You can change this behavior by using setMode() or setFilter().
- *
- * \image html kurlrequester.png "KDE URL Requester"
- *
- * @short A widget to request a filename/url from the user
- * @author Carsten Pfeiffer <pfeiffer@kde.org>
- */
-class TDEIO_EXPORT KURLRequester : public TQHBox
-{
- Q_OBJECT
- TQ_PROPERTY( TQString url READ url WRITE setURL )
- TQ_PROPERTY( bool showLocalProtocol READ showLocalProtocol WRITE setShowLocalProtocol )
- TQ_PROPERTY( TQString filter READ filter WRITE setFilter )
- TQ_PROPERTY( uint mode READ mode WRITE setMode )
-
-public:
- /**
- * Constructs a KURLRequester widget.
- */
- KURLRequester( TQWidget *parent=0, const char *name=0 );
-
- /**
- * Constructs a KURLRequester widget with the initial URL @p url.
- * // TODO KDE4: Use KURL instead
- */
- KURLRequester( const TQString& url, TQWidget *parent=0, const char *name=0 );
-
- /**
- * Special constructor, which creates a KURLRequester widget with a custom
- * edit-widget. The edit-widget can be either a KComboBox or a KLineEdit
- * (or inherited thereof). Note: for geometry management reasons, the
- * edit-widget is reparented to have the KURLRequester as parent.
- */
- KURLRequester( TQWidget *editWidget, TQWidget *parent, const char *name=0 );
- /**
- * Destructs the KURLRequester.
- */
- ~KURLRequester();
-
- /**
- * @returns the current url in the lineedit. May be malformed, if the user
- * entered something weird. ~user or environment variables are substituted
- * for local files.
- * // TODO KDE4: Use KURL so that the result is properly defined
- */
- TQString url() const;
-
- /**
- * Enables/disables showing file:/ in the lineedit, when a local file has
- * been selected in the filedialog or was set via setURL().
- * Default is false, not showing file:/
- * @see showLocalProtocol
- */
- void setShowLocalProtocol( bool b );
-
- /**
- * Sets the mode of the file dialog.
- * Note: you can only select one file with the filedialog,
- * so KFile::Files doesn't make much sense.
- * @see KFileDialog::setMode()
- */
- void setMode( uint m );
-
- /**
- * Returns the current mode
- * @see KFileDialog::mode()
- * @since 3.3
- */
- uint mode() const;
-
-
- /**
- * Sets the filter for the file dialog.
- * @see KFileDialog::setFilter()
- */
- void setFilter( const TQString& filter );
-
- /**
- * Returns the current filter for the file dialog.
- * @see KFileDialog::filter()
- * @since 3.3
- */
- TQString filter() const;
-
- /**
- * @returns whether local files will be prefixed with file:/ in the
- * lineedit
- * @see setShowLocalProtocol
- */
- bool showLocalProtocol() const { return myShowLocalProt; }
- // ## KDE4: there's no reason to keep this, it should always be false
-
- /**
- * @returns a pointer to the filedialog
- * You can use this to customize the dialog, e.g. to specify a filter.
- * Never returns 0L.
- *
- * Remove in KDE4? KURLRequester should use KDirSelectDialog for
- * (mode & KFile::Directory) && !(mode & KFile::File)
- */
- virtual KFileDialog * fileDialog() const;
-
- /**
- * @returns a pointer to the lineedit, either the default one, or the
- * special one, if you used the special constructor.
- *
- * It is provided so that you can e.g. set an own completion object
- * (e.g. KShellCompletion) into it.
- */
- KLineEdit * lineEdit() const;
-
- /**
- * @returns a pointer to the combobox, in case you have set one using the
- * special constructor. Returns 0L otherwise.
- */
- KComboBox * comboBox() const;
-
- /**
- * @returns a pointer to the pushbutton. It is provided so that you can
- * specify an own pixmap or a text, if you really need to.
- */
- KPushButton * button() const;
-
- /**
- * @returns the KURLCompletion object used in the lineedit/combobox.
- */
- KURLCompletion *completionObject() const { return myCompletion; }
-
- /**
- * @returns an object, suitable for use with KEditListBox. It allows you
- * to put this KURLRequester into a KEditListBox.
- * Basically, do it like this:
- * \code
- * KURLRequester *req = new KURLRequester( someWidget );
- * [...]
- * KEditListBox *editListBox = new KEditListBox( i18n("Some Title"), req->customEditor(), someWidget );
- * \endcode
- * @since 3.1
- */
- KEditListBox::CustomEditor customEditor();
-
-public slots:
- /**
- * Sets the url in the lineedit to @p url. Depending on the state of
- * showLocalProtocol(), file:/ on local files will be shown or not.
- * @since 3.1
- * // TODO KDE4: Use KURL instead
- */
- void setURL( const TQString& url );
-
- /**
- * Sets the url in the lineedit to @p url.
- * @since 3.4
- * // TODO KDE4: rename to setURL
- */
- void setKURL( const KURL& url );
-
- /**
- * Sets the caption of the file dialog.
- * @since 3.1
- */
- virtual void setCaption( const TQString& caption );
-
- /**
- * Clears the lineedit/combobox.
- */
- void clear();
-
-signals:
- // forwards from LineEdit
- /**
- * Emitted when the text in the lineedit changes.
- * The parameter contains the contents of the lineedit.
- * @since 3.1
- */
- void textChanged( const TQString& );
-
- /**
- * Emitted when return or enter was pressed in the lineedit.
- */
- void returnPressed();
-
- /**
- * Emitted when return or enter was pressed in the lineedit.
- * The parameter contains the contents of the lineedit.
- */
- void returnPressed( const TQString& );
-
- /**
- * Emitted before the filedialog is going to open. Connect
- * to this signal to "configure" the filedialog, e.g. set the
- * filefilter, the mode, a preview-widget, etc. It's usually
- * not necessary to set a URL for the filedialog, as it will
- * get set properly from the editfield contents.
- *
- * If you use multiple KURLRequesters, you can connect all of them
- * to the same slot and use the given KURLRequester pointer to know
- * which one is going to open.
- */
- void openFileDialog( KURLRequester * );
-
- /**
- * Emitted when the user changed the URL via the file dialog.
- * The parameter contains the contents of the lineedit.
- * // TODO KDE4: Use KURL instead
- */
- void urlSelected( const TQString& );
-
-protected:
- void init();
-
- KURLCompletion * myCompletion;
-
-
-private:
- KURLDragPushButton * myButton;
- bool myShowLocalProt;
- mutable KFileDialog * myFileDialog;
-
-
-protected slots:
- /**
- * Called when the button is pressed to open the filedialog.
- * Also called when KStdAccel::Open (default is Ctrl-O) is pressed.
- */
- void slotOpenDialog();
-
-private slots:
- void slotUpdateURL();
-
-protected:
- virtual void virtual_hook( int id, void* data );
- bool eventFilter( TQObject *obj, TQEvent *ev );
-private:
- class KURLRequesterPrivate;
- KURLRequesterPrivate *d;
-};
-
-/**
- * URL requester with a combo box, for use in Designer
- */
-class TDEIO_EXPORT KURLComboRequester : public KURLRequester
-{
- Q_OBJECT
-public:
- /**
- * Constructs a KURLRequester widget with a combobox.
- */
- KURLComboRequester( TQWidget *parent=0, const char *name=0 );
-};
-
-
-#endif // KURLREQUESTER_H
diff --git a/kio/kfile/kurlrequesterdlg.cpp b/kio/kfile/kurlrequesterdlg.cpp
deleted file mode 100644
index 19409afdc..000000000
--- a/kio/kfile/kurlrequesterdlg.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Wilco Greven <greven@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqstring.h>
-#include <tqtoolbutton.h>
-
-#include <kaccel.h>
-#include <kfiledialog.h>
-#include <kglobal.h>
-#include <kiconloader.h>
-#include <klineedit.h>
-#include <klocale.h>
-#include <krecentdocument.h>
-#include <kurl.h>
-#include <kurlrequester.h>
-
-#include "kurlrequesterdlg.h"
-
-
-KURLRequesterDlg::KURLRequesterDlg( const TQString& urlName, TQWidget *parent,
- const char *name, bool modal )
- : KDialogBase( Plain, TQString::null, Ok|Cancel|User1, Ok, parent, name,
- modal, true, KStdGuiItem::clear() )
-{
- initDialog(i18n( "Location:" ), urlName);
-}
-
-KURLRequesterDlg::KURLRequesterDlg( const TQString& urlName, const TQString& _text, TQWidget *parent, const char *name, bool modal )
- : KDialogBase( Plain, TQString::null, Ok|Cancel|User1, Ok, parent, name,
- modal, true, KStdGuiItem::clear() )
-{
- initDialog(_text, urlName);
-}
-
-KURLRequesterDlg::~KURLRequesterDlg()
-{
-}
-
-void KURLRequesterDlg::initDialog(const TQString &text,const TQString &urlName)
-{
- TQVBoxLayout * topLayout = new TQVBoxLayout( plainPage(), 0,
- spacingHint() );
-
- TQLabel * label = new TQLabel( text , plainPage() );
- topLayout->addWidget( label );
-
- urlRequester_ = new KURLRequester( urlName, plainPage(), "urlRequester" );
- urlRequester_->setMinimumWidth( urlRequester_->sizeHint().width() * 3 );
- topLayout->addWidget( urlRequester_ );
- urlRequester_->setFocus();
- connect( urlRequester_->lineEdit(), TQT_SIGNAL(textChanged(const TQString&)),
- TQT_SLOT(slotTextChanged(const TQString&)) );
- bool state = !urlName.isEmpty();
- enableButtonOK( state );
- enableButton( KDialogBase::User1, state );
- /*
- KFile::Mode mode = static_cast<KFile::Mode>( KFile::File |
- KFile::ExistingOnly );
- urlRequester_->setMode( mode );
- */
- connect( this, TQT_SIGNAL( user1Clicked() ), TQT_SLOT( slotClear() ) );
-}
-
-void KURLRequesterDlg::slotTextChanged(const TQString & text)
-{
- bool state = !text.stripWhiteSpace().isEmpty();
- enableButtonOK( state );
- enableButton( KDialogBase::User1, state );
-}
-
-void KURLRequesterDlg::slotClear()
-{
- urlRequester_->clear();
-}
-
-KURL KURLRequesterDlg::selectedURL() const
-{
- if ( result() == TQDialog::Accepted )
- return KURL::fromPathOrURL( urlRequester_->url() );
- else
- return KURL();
-}
-
-
-KURL KURLRequesterDlg::getURL(const TQString& dir, TQWidget *parent,
- const TQString& caption)
-{
- KURLRequesterDlg dlg(dir, parent, "filedialog", true);
-
- dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
-
- dlg.exec();
-
- const KURL& url = dlg.selectedURL();
- if (url.isValid())
- KRecentDocument::add(url);
-
- return url;
-}
-
-KFileDialog * KURLRequesterDlg::fileDialog()
-{
- return urlRequester_->fileDialog();
-}
-
-KURLRequester * KURLRequesterDlg::urlRequester()
-{
- return urlRequester_;
-}
-
-#include "kurlrequesterdlg.moc"
-
-// vim:ts=4:sw=4:tw=78
diff --git a/kio/kfile/tests/Makefile.am b/kio/kfile/tests/Makefile.am
deleted file mode 100644
index 9689f7a27..000000000
--- a/kio/kfile/tests/Makefile.am
+++ /dev/null
@@ -1,41 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 1996-1997 Matthias Kalle Dalheimer (kalle@kde.org)
-# (C) 1997-1998 Stephan Kulow (coolo@kde.org)
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-INCLUDES = $(all_includes)
-
-AM_LDFLAGS = $(QT_LDFLAGS) $(X_LDFLAGS) $(KDE_RPATH)
-
-check_PROGRAMS = kfstest kurlrequestertest kfiletreeviewtest \
- kopenwithtest kdirselectdialogtest kicondialogtest \
- knotifytest kcustommenueditortest
-
-# noinst_HEADERS =
-
-METASOURCES = AUTO
-
-LDADD = $(LIB_KIO)
-kcustommenueditortest_SOURCES = kcustommenueditortest.cpp
-kurlrequestertest_SOURCES = kurlrequestertest.cpp
-kfstest_SOURCES = kfstest.cpp kfdtest.cpp
-kfiletreeviewtest_SOURCES = kfiletreeviewtest.cpp
-kopenwithtest_SOURCES = kopenwithtest.cpp
-kdirselectdialogtest_SOURCES = kdirselectdialogtest.cpp
-kicondialogtest_SOURCES = kicondialogtest.cpp
-knotifytest_SOURCES = knotifytest.cpp
-
diff --git a/kio/kfile/tests/kcustommenueditortest.cpp b/kio/kfile/tests/kcustommenueditortest.cpp
deleted file mode 100644
index 1fc6da496..000000000
--- a/kio/kfile/tests/kcustommenueditortest.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "kcustommenueditor.h"
-#include <kapplication.h>
-#include <klocale.h>
-#include <kconfig.h>
-
-int main(int argc, char** argv)
-{
- KLocale::setMainCatalogue("tdelibs");
- TDEApplication app(argc, argv, "KCustomMenuEditorTest");
- KCustomMenuEditor editor(0);
- TDEConfig *cfg = new TDEConfig("kdesktop_custom_menu2");
- editor.load(cfg);
- if (editor.exec())
- {
- editor.save(cfg);
- cfg->sync();
- }
-}
-
diff --git a/kio/kfile/tests/kfdtest.cpp b/kio/kfile/tests/kfdtest.cpp
deleted file mode 100644
index 867b9b4a8..000000000
--- a/kio/kfile/tests/kfdtest.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "kfdtest.h"
-
-#include <tqstringlist.h>
-#include <kfiledialog.h>
-#include <kapplication.h>
-#include <kmessagebox.h>
-#include <tqtimer.h>
-
-KFDTest::KFDTest( const TQString& startDir, TQObject *parent, const char *name )
- : TQObject( parent, name ),
- m_startDir( startDir )
-{
- TQTimer::singleShot( 1000, this, TQT_SLOT( doit() ));
-}
-
-void KFDTest::doit()
-{
- KFileDialog *dlg = new KFileDialog( m_startDir, TQString::null, 0L,
- "file dialog", true );
- dlg->setMode( KFile::File);
- dlg->setOperationMode( KFileDialog::Saving );
- TQStringList filter;
- filter << "all/allfiles" << "text/plain";
- dlg->setMimeFilter( filter, "all/allfiles" );
-
- if ( dlg->exec() == KDialog::Accepted )
- {
- KMessageBox::information(0, TQString::fromLatin1("You selected the file: %1").arg( dlg->selectedURL().prettyURL() ));
- }
-
-// tqApp->quit();
-}
-
-#include "kfdtest.moc"
diff --git a/kio/kfile/tests/kfiletreeviewtest.cpp b/kio/kfile/tests/kfiletreeviewtest.cpp
deleted file mode 100644
index cf28557f8..000000000
--- a/kio/kfile/tests/kfiletreeviewtest.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001 Klaas Freitag <freitag@suse.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqdir.h>
-
-#include <kglobal.h>
-#include <kiconloader.h>
-#include <kmainwindow.h>
-#include <kapplication.h>
-#include <kurl.h>
-#include <kdebug.h>
-#include <kstatusbar.h>
-
-#include <kfiletreeview.h>
-#include "kfiletreeviewtest.h"
-
-
-#include "kfiletreeviewtest.moc"
-
-testFrame::testFrame():KMainWindow(0,"Test FileTreeView"),
- dirOnlyMode(false)
-
-{
- treeView = new KFileTreeView( this );
- treeView->setDragEnabled( true );
- treeView->setAcceptDrops( true );
- treeView->setDropVisualizer( true );
-
-
- /* Connect to see the status bar */
- KStatusBar* sta = statusBar();
- connect( treeView, TQT_SIGNAL( onItem( const TQString& )),
- sta, TQT_SLOT( message( const TQString& )));
-
- connect( treeView, TQT_SIGNAL( dropped( TQWidget*, TQDropEvent*, KURL::List& )),
- this, TQT_SLOT( urlsDropped( TQWidget*, TQDropEvent*, KURL::List& )));
-
- connect( treeView, TQT_SIGNAL( dropped( KURL::List&, KURL& )), this,
- TQT_SLOT( copyURLs( KURL::List&, KURL& )));
-
- treeView->addColumn( "File" );
- treeView->addColumn( "ChildCount" );
- setCentralWidget( treeView );
- resize( 600, 400 );
-
- showPath( KURL::fromPathOrURL( TQDir::homeDirPath() ));
-}
-
-void testFrame::showPath( const KURL &url )
-{
- TQString fname = "TestBranch"; // url.fileName ();
- /* try a user icon */
- KIconLoader *loader = TDEGlobal::iconLoader();
- TQPixmap pix = loader->loadIcon( "contents2", KIcon::Small );
- TQPixmap pixOpen = loader->loadIcon( "contents", KIcon::Small );
-
- KFileTreeBranch *nb = treeView->addBranch( url, fname, pix );
-
- if( nb )
- {
- if( dirOnlyMode ) treeView->setDirOnlyMode( nb, true );
- nb->setOpenPixmap( pixOpen );
-
- connect( nb, TQT_SIGNAL(populateFinished(KFileTreeViewItem*)),
- this, TQT_SLOT(slotPopulateFinished(KFileTreeViewItem*)));
- connect( nb, TQT_SIGNAL( directoryChildCount( KFileTreeViewItem *, int )),
- this, TQT_SLOT( slotSetChildCount( KFileTreeViewItem*, int )));
- // nb->setChildRecurse(false );
-
- nb->setOpen(true);
- }
-
-
-}
-
-void testFrame::urlsDropped( TQWidget* , TQDropEvent* , KURL::List& list )
-{
- KURL::List::ConstIterator it = list.begin();
- for ( ; it != list.end(); ++it ) {
- kdDebug() << "Url dropped: " << (*it).prettyURL() << endl;
- }
-}
-
-void testFrame::copyURLs( KURL::List& list, KURL& to )
-{
- KURL::List::ConstIterator it = list.begin();
- kdDebug() << "Copy to " << to.prettyURL() << endl;
- for ( ; it != list.end(); ++it ) {
- kdDebug() << "Url: " << (*it).prettyURL() << endl;
- }
-
-}
-
-
-void testFrame::slotPopulateFinished(KFileTreeViewItem *item )
-{
- if( item )
- {
-#if 0
- int cc = item->childCount();
-
- kdDebug() << "setting column 2 of treeview with count " << cc << endl;
-
- item->setText( 1, TQString::number( cc ));
-#endif
- }
- else
- {
- kdDebug() << "slotPopFinished for uninitalised item" << endl;
- }
-}
-
-void testFrame::slotSetChildCount( KFileTreeViewItem *item, int c )
-{
- if( item )
- item->setText(1, TQString::number( c ));
-}
-
-int main(int argc, char **argv)
-{
- TDEApplication a(argc, argv, "kfiletreeviewtest");
- TQString name1;
- TQStringList names;
-
- TQString argv1;
- testFrame *tf;
-
- tf = new testFrame();
- a.setMainWidget( tf );
-
- if (argc > 1)
- {
- for( int i = 1; i < argc; i++ )
- {
- argv1 = TQString::fromLatin1(argv[i]);
- kdDebug() << "Opening " << argv1 << endl;
- if( argv1 == "-d" )
- tf->setDirOnly();
- else
- {
- KURL u( argv1 );
- tf->showPath( u );
- }
- }
- }
- tf->show();
- int ret = a.exec();
- return( ret );
-}
diff --git a/kio/kfile/tests/kfstest.cpp b/kio/kfile/tests/kfstest.cpp
deleted file mode 100644
index b0ecabcc6..000000000
--- a/kio/kfile/tests/kfstest.cpp
+++ /dev/null
@@ -1,183 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1997, 1998 Richard Moore <rich@kde.org>
- 1998 Stephan Kulow <coolo@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <tqdir.h>
-#include <tqlayout.h>
-#include <tqstringlist.h>
-#include <tqwidget.h>
-
-#include <kfiledialog.h>
-#include <kfileiconview.h>
-#include <kmessagebox.h>
-#include <kconfig.h>
-#include <kapplication.h>
-#include <kurl.h>
-#include <kurlbar.h>
-#include <kdiroperator.h>
-#include <kfile.h>
-#include <kdebug.h>
-#include <kicondialog.h>
-
-#include "kfdtest.h"
-
-int main(int argc, char **argv)
-{
- TDEApplication a(argc, argv, "kfstest");
- TQString name1;
- TQStringList names;
-
- TQString argv1;
- TQString startDir;
- if (argc > 1)
- argv1 = TQString::fromLatin1(argv[1]);
- if ( argc > 2 )
- startDir = TQString::fromLatin1( argv[2]);
-
- if (argv1 == TQString::fromLatin1("diroperator")) {
- KDirOperator *op = new KDirOperator(startDir, 0, "operator");
- op->setViewConfig( TDEGlobal::config(), "TestGroup" );
- op->setView(KFile::Simple);
- op->show();
- a.setMainWidget(op);
- a.exec();
- }
-
- else if (argv1 == TQString::fromLatin1("justone")) {
- TQString name = KFileDialog::getOpenFileName(startDir);
- tqDebug("filename=%s",name.latin1());
- }
-
- else if (argv1 == TQString::fromLatin1("existingURL")) {
- KURL url = KFileDialog::getExistingURL();
- tqDebug("URL=%s",url.url().latin1());
- name1 = url.url();
- }
-
- else if (argv1 == TQString::fromLatin1("preview")) {
- KURL u = KFileDialog::getImageOpenURL();
- tqDebug("filename=%s", u.url().latin1());
- }
-
- else if (argv1 == TQString::fromLatin1("preselect")) {
- names = KFileDialog::getOpenFileNames(TQString::fromLatin1("/etc/passwd"));
- TQStringList::Iterator it = names.begin();
- while ( it != names.end() ) {
- tqDebug("selected file: %s", (*it).latin1());
- ++it;
- }
- }
-
- else if (argv1 == TQString::fromLatin1("dirs"))
- name1 = KFileDialog::getExistingDirectory();
-
- else if (argv1 == TQString::fromLatin1("heap")) {
- KFileDialog *dlg = new KFileDialog( startDir, TQString::null, 0L,
- "file dialog", true );
- dlg->setMode( KFile::File);
- dlg->setOperationMode( KFileDialog::Saving );
- TQStringList filter;
- filter << "all/allfiles" << "text/plain";
- dlg->setMimeFilter( filter, "all/allfiles" );
- KURLBar *urlBar = dlg->speedBar();
- if ( urlBar )
- {
- urlBar->insertDynamicItem( KURL("ftp://ftp.kde.org"),
- TQString::fromLatin1("KDE FTP Server") );
- }
-
- if ( dlg->exec() == KDialog::Accepted )
- name1 = dlg->selectedURL().url();
- }
-
- else if ( argv1 == TQString::fromLatin1("eventloop") )
- {
- KFDTest *test = new KFDTest( startDir );
- return a.exec();
- }
-
- else if (argv1 == TQString::fromLatin1("save")) {
- KURL u = KFileDialog::getSaveURL();
-// TQString(TQDir::homeDirPath() + TQString::fromLatin1("/testfile")),
-// TQString::null, 0L);
- name1 = u.url();
- }
-
- else if (argv1 == TQString::fromLatin1("icon")) {
- KIconDialog dlg;
- TQString icon = dlg.selectIcon();
- kdDebug() << icon << endl;
- }
-
-// else if ( argv1 == TQString::fromLatin1("dirselect") ) {
-// KURL url;
-// url.setPath( "/" );
-// KURL selected = KDirSelectDialog::selectDirectory( url );
-// name1 = selected.url();
-// tqDebug("*** selected: %s", selected.url().latin1());
-// }
-
- else {
- KFileDialog dlg(startDir,
- TQString::fromLatin1("*|All Files\n"
- "*.lo *.o *.la|All libtool Files"),
- 0, 0, true);
-// dlg.setFilter( "*.tdevelop" );
- dlg.setMode( (KFile::Mode) (KFile::Files |
- KFile::Directory |
- KFile::ExistingOnly |
- KFile::LocalOnly) );
-// TQStringList filter;
-// filter << "text/plain" << "text/html" << "image/png";
-// dlg.setMimeFilter( filter );
-// KMimeType::List types;
-// types.append( KMimeType::mimeType( "text/plain" ) );
-// types.append( KMimeType::mimeType( "text/html" ) );
-// dlg.setFilterMimeType( "Filetypes:", types, types.first() );
- if ( dlg.exec() == TQDialog::Accepted ) {
- KURL::List list = dlg.selectedURLs();
- KURL::List::ConstIterator it = list.begin();
- tqDebug("*** selectedURLs(): ");
- while ( it != list.end() ) {
- name1 = (*it).url();
- tqDebug(" -> %s", name1.latin1());
- ++it;
- }
- tqDebug("*** selectedFile: %s", dlg.selectedFile().latin1());
- tqDebug("*** selectedURL: %s", dlg.selectedURL().url().latin1());
- tqDebug("*** selectedFiles: ");
- TQStringList l = dlg.selectedFiles();
- TQStringList::Iterator it2 = l.begin();
- while ( it2 != l.end() ) {
- tqDebug(" -> %s", (*it2).latin1());
- ++it2;
- }
- }
- }
-
- if (!(name1.isNull()))
- KMessageBox::information(0, TQString::fromLatin1("You selected the file " ) + name1,
- TQString::fromLatin1("Your Choice"));
- return 0;
-}
diff --git a/kio/kio/CMakeLists.txt b/kio/kio/CMakeLists.txt
deleted file mode 100644
index 1a2c3a263..000000000
--- a/kio/kio/CMakeLists.txt
+++ /dev/null
@@ -1,138 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/kio/kssl
- ${CMAKE_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore/network
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kssl
- ${CMAKE_SOURCE_DIR}/interfaces
- ${LIBR_INCLUDEDIR}
- ${GAMIN_INCLUDEDIR}
-)
-
-link_directories(
- ${GAMIN_LIBDIR}
-)
-
-##### headers ###################################
-
-install( FILES
- kservicetype.h kmimetype.h kmimemagic.h kservice.h
- krun.h kdirwatch.h kautomount.h kuserprofile.h
- kshred.h kar.h ktar.h kzip.h ktrader.h kurifilter.h
- kurlcompletion.h kshellcompletion.h kfileitem.h
- kfileshare.h ksambashare.h knfsshare.h kdirlister.h
- kservicegroup.h kimageio.h kdirnotify.h kdirnotify_stub.h
- kurlpixmapprovider.h kprotocolinfo.h kprotocolmanager.h
- kfilterbase.h kfilterdev.h kemailsettings.h kscan.h
- kdatatool.h karchive.h kfilefilter.h kfilemetainfo.h
- renamedlgplugin.h kmimetyperesolver.h kdcopservicestarter.h
- kremoteencoding.h kmimetypechooser.h
- DESTINATION ${INCLUDE_INSTALL_DIR} )
-
-# FIXME seems that ACL is no longer optional
-#if( USE_POSIX_ACL )
- install( FILES kacl.h DESTINATION ${INCLUDE_INSTALL_DIR} )
-#endif( USE_POSIX_ACL )
-
-install( FILES
- connection.h slaveinterface.h slave.h slaveconfig.h
- sessiondata.h global.h passdlg.h netaccess.h job.h
- scheduler.h jobclasses.h paste.h slavebase.h
- progressbase.h defaultprogress.h statusbarprogress.h
- tcpslavebase.h forwardingslavebase.h observer.h
- chmodjob.h kmdbase.h authinfo.h ioslave_defaults.h
- http_slave_defaults.h previewjob.h thumbcreator.h
- metainfojob.h davjob.h renamedlg.h skipdlg.h
- ${CMAKE_CURRENT_BINARY_DIR}/uiserver_stub.h
- DESTINATION ${INCLUDE_INSTALL_DIR}/kio )
-
-
-##### kiocore ###################################
-
-set( target kiocore )
-
-set( ${target}_SRCS
- authinfo.cpp kshred.cpp kprotocolmanager.cpp slave.cpp
- slaveinterface.cpp observer.stub sessiondata.cpp
- scheduler.cpp connection.cpp job.cpp global.cpp
- slaveconfig.cpp kurlpixmapprovider.cpp netaccess.cpp
- paste.cpp pastedialog.cpp kmimemagic.cpp tcpslavebase.cpp
- slavebase.cpp passdlg.cpp forwardingslavebase.cpp
- progressbase.cpp defaultprogress.cpp statusbarprogress.cpp
- kdirnotify.cpp kdirnotify.skel kdirnotify_stub.cpp
- observer.cpp ../misc/uiserver.stub observer.skel kemailsettings.cpp
- kprotocolinfo.cpp renamedlg.cpp skipdlg.cpp kremoteencoding.cpp
- kmimetypechooser.cpp
-)
-
-tde_add_library( ${target} STATIC_PIC AUTOMOC
- SOURCES ${${target}_SRCS}
- DEPENDENCIES dcopidl
-)
-
-
-##### tdesycoca ###################################
-
-set( target tdesycoca )
-
-set( ${target}_SRCS
- kdirwatch.cpp kfileshare.cpp ksambashare.cpp
- knfsshare.cpp ktrader.cpp ktraderparse.cpp
- ktraderparsetree.cpp kservicetypefactory.cpp
- kservicetype.cpp kmimetype.cpp kservicegroup.cpp
- kservice.cpp kservicefactory.cpp kuserprofile.cpp
- kservicegroupfactory.cpp kurifilter.cpp kfilterbase.cpp
- kfilterdev.cpp kshellcompletion.cpp kurlcompletion.cpp
- kautomount.cpp krun.cpp kfileitem.cpp kdirlister.cpp
- kimageio.cpp yacc.c lex.c chmodjob.cpp kscan.cpp
- kar.cpp ktar.cpp kzip.cpp previewjob.cpp metainfojob.cpp
- davjob.cpp kdatatool.cpp karchive.cpp kfilefilter.cpp
- kfilemetainfo.cpp kdcopservicestarter.cpp dataslave.cpp
- dataprotocol.cpp
-)
-
-# FIXME seems that ACL is no longer optional
-#if( USE_POSIX_ACL )
- set( ${target}_SRCS ${${target}_SRCS} kacl.cpp posixacladdons.cpp )
-#endif( USE_POSIX_ACL )
-
-tde_add_library( ${target} STATIC_PIC AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK ${GAMIN_LIBRARIES}
-)
-
-
-##### tdelficon ###################################
-
-if( HAVE_ELFICON )
-
- set( target tdelficon )
-
- set( ${target}_SRCS
- tdelficon.cpp
- )
-
- tde_add_library( ${target} STATIC_PIC AUTOMOC
- SOURCES ${${target}_SRCS}
- )
-
-endif( HAVE_ELFICON )
diff --git a/kio/kio/Makefile.am b/kio/kio/Makefile.am
deleted file mode 100644
index 63d5fc5d8..000000000
--- a/kio/kio/Makefile.am
+++ /dev/null
@@ -1,129 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 1997 Torben Weis (weis@kde.org)
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
-
-INCLUDES= -I$(top_srcdir) -I$(srcdir)/.. -I$(top_srcdir)/tdecore/network -I$(srcdir)/../kssl -I../kssl -I$(srcdir)/../../interfaces $(all_includes) $(SSL_INCLUDES)
-
-noinst_LTLIBRARIES = libkiocore.la libtdesycoca.la
-
-# convenience lib - no LDFLAGS or LIBADD !
-
-libtdesycoca_la_SOURCES = \
- kdirwatch.cpp \
- kfileshare.cpp ksambashare.cpp knfsshare.cpp \
- ktrader.cpp ktraderparse.cpp ktraderparsetree.cpp \
- kservicetypefactory.cpp kservicetype.cpp \
- kmimetype.cpp kservicegroup.cpp \
- kservice.cpp kservicefactory.cpp \
- kuserprofile.cpp kservicegroupfactory.cpp \
- kurifilter.cpp \
- kfilterbase.cpp kfilterdev.cpp \
- kshellcompletion.cpp kurlcompletion.cpp \
- kautomount.cpp krun.cpp \
- kfileitem.cpp kdirlister.cpp kimageio.cpp \
- yacc.c lex.c \
- chmodjob.cpp kscan.cpp kar.cpp ktar.cpp kzip.cpp previewjob.cpp metainfojob.cpp davjob.cpp \
- kdatatool.cpp karchive.cpp kfilefilter.cpp \
- kfilemetainfo.cpp kdcopservicestarter.cpp \
- dataslave.cpp dataprotocol.cpp
-#if USE_POSIX_ACL
- libtdesycoca_la_SOURCES += kacl.cpp posixacladdons.cpp
-#endif
-
-include_HEADERS = \
- kservicetype.h kmimetype.h kmimemagic.h kservice.h \
- krun.h kdirwatch.h kautomount.h kuserprofile.h \
- kshred.h kar.h ktar.h kzip.h ktrader.h kurifilter.h kurlcompletion.h \
- kshellcompletion.h kfileitem.h kfileshare.h ksambashare.h knfsshare.h \
- kdirlister.h kservicegroup.h \
- kimageio.h kdirnotify.h kdirnotify_stub.h \
- kurlpixmapprovider.h kprotocolinfo.h kprotocolmanager.h \
- kfilterbase.h kfilterdev.h kemailsettings.h kscan.h kdatatool.h \
- karchive.h kfilefilter.h kfilemetainfo.h renamedlgplugin.h \
- kmimetyperesolver.h kdcopservicestarter.h kremoteencoding.h \
- kmimetypechooser.h
-#if USE_POSIX_ACL
-include_HEADERS += kacl.h
-#endif
-
-#libkiocore_la_LDFLAGS = $(all_libraries)
-#libkiocore_la_LIBADD = ../../tdeui/libtdeui.la ../../tdesu/libtdesu.la $(LIBZ) $(LIBFAM) $(LIBVOLMGT)
-
-libkiocore_la_SOURCES = authinfo.cpp \
- kshred.cpp \
- kprotocolmanager.cpp \
- slave.cpp slaveinterface.cpp observer.stub \
- sessiondata.cpp scheduler.cpp \
- connection.cpp \
- job.cpp global.cpp \
- slaveconfig.cpp kurlpixmapprovider.cpp \
- netaccess.cpp paste.cpp pastedialog.cpp \
- kmimemagic.cpp \
- tcpslavebase.cpp slavebase.cpp passdlg.cpp \
- forwardingslavebase.cpp \
- progressbase.cpp defaultprogress.cpp \
- statusbarprogress.cpp \
- kdirnotify.cpp kdirnotify.skel kdirnotify_stub.cpp \
- observer.cpp uiserver.stub observer.skel \
- kemailsettings.cpp \
- kprotocolinfo.cpp \
- renamedlg.cpp skipdlg.cpp kremoteencoding.cpp \
- kmimetypechooser.cpp
-
-uiserver_DIR = $(top_srcdir)/kio/misc
-
-METASOURCES = AUTO
-
-kioincludedir = $(includedir)/kio
-kioinclude_HEADERS = connection.h \
- slaveinterface.h slave.h slaveconfig.h \
- sessiondata.h global.h passdlg.h \
- netaccess.h job.h scheduler.h \
- jobclasses.h paste.h slavebase.h \
- progressbase.h defaultprogress.h \
- statusbarprogress.h tcpslavebase.h \
- forwardingslavebase.h \
- observer.h chmodjob.h uiserver_stub.h \
- kmdbase.h authinfo.h \
- ioslave_defaults.h http_slave_defaults.h previewjob.h thumbcreator.h \
- metainfojob.h davjob.h renamedlg.h skipdlg.h
-
-# Internal
-noinst_HEADERS = kservicetypefactory.h kservicefactory.h \
- kmessageboxwrapper.h \
- ktraderparse.h ktraderparsetree.h yacc.h \
- kimageiofactory.h kdirwatch_p.h kdirlister_p.h \
- renamedlg.h skipdlg.h dataslave.h dataprotocol.h \
- kservice_p.h
-#if USE_POSIX_ACL
-noinst_HEADERS += posixacladdons.h
-#endif
-
-parserfiles = yacc.y lex.l
-
-EXTRA_DIST = $(parserfiles)
-
-parser: $(parserfiles)
- cd $(srcdir) ;\
- flex -olex.c -Pkiotrader lex.l ;\
- bison -d -p kiotrader yacc.y && mv yacc.tab.c yacc.c; mv yacc.tab.h yacc.h
-
-.PHONY: parser
-
-include ../../admin/Doxyfile.am
diff --git a/kio/kio/authinfo.cpp b/kio/kio/authinfo.cpp
deleted file mode 100644
index 483bc682f..000000000
--- a/kio/kio/authinfo.cpp
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (C) 2000-2001 Dawit Alemayehu <adawit@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include <config.h>
-
-#include <stdio.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#include <tqdir.h>
-#include <tqfile.h>
-
-#include <kdebug.h>
-#include <kstandarddirs.h>
-#include <ksavefile.h>
-#include <kstaticdeleter.h>
-#include <kde_file.h>
-
-#include "kio/authinfo.h"
-
-#define NETRC_READ_BUF_SIZE 4096
-
-using namespace TDEIO;
-
-AuthInfo::AuthInfo()
-{
- modified = false;
- readOnly = false;
- verifyPath = false;
- keepPassword = false;
-}
-
-AuthInfo::AuthInfo( const AuthInfo& info )
-{
- (*this) = info;
-}
-
-AuthInfo& AuthInfo::operator= ( const AuthInfo& info )
-{
- url = info.url;
- username = info.username;
- password = info.password;
- prompt = info.prompt;
- caption = info.caption;
- comment = info.comment;
- commentLabel = info.commentLabel;
- realmValue = info.realmValue;
- digestInfo = info.digestInfo;
- verifyPath = info.verifyPath;
- readOnly = info.readOnly;
- keepPassword = info.keepPassword;
- modified = info.modified;
- return *this;
-}
-
-TQDataStream& TDEIO::operator<< (TQDataStream& s, const AuthInfo& a)
-{
- s << a.url << a.username << a.password << a.prompt << a.caption
- << a.comment << a.commentLabel << a.realmValue << a.digestInfo
- << TQ_UINT8(a.verifyPath ? 1:0) << TQ_UINT8(a.readOnly ? 1:0)
- << TQ_UINT8(a.keepPassword ? 1:0) << TQ_UINT8(a.modified ? 1:0);
- return s;
-}
-
-TQDataStream& TDEIO::operator>> (TQDataStream& s, AuthInfo& a)
-{
- TQ_UINT8 verify = 0;
- TQ_UINT8 ro = 0;
- TQ_UINT8 keep = 0;
- TQ_UINT8 mod = 0;
-
- s >> a.url >> a.username >> a.password >> a.prompt >> a.caption
- >> a.comment >> a.commentLabel >> a.realmValue >> a.digestInfo
- >> verify >> ro >> keep >> mod;
- a.verifyPath = (verify != 0);
- a.readOnly = (ro != 0);
- a.keepPassword = (keep != 0);
- a.modified = (mod != 0);
- return s;
-}
-
-
-NetRC* NetRC::instance = 0L;
-
-NetRC::NetRC()
-{
- isDirty = false;
-}
-
-NetRC::~NetRC()
-{
- delete instance;
- instance = 0L;
-}
-
-NetRC* NetRC::self()
-{
- if ( !instance )
- instance = new NetRC();
- return instance;
-}
-
-bool NetRC::lookup( const KURL& url, AutoLogin& login, bool userealnetrc,
- TQString type, int mode )
-{
- // kdDebug() << "AutoLogin lookup for: " << url.host() << endl;
- if ( !url.isValid() )
- return false;
-
- if ( type.isEmpty() )
- type = url.protocol();
-
- if ( loginMap.isEmpty() || isDirty )
- {
- loginMap.clear();
-
- TQString filename = locateLocal("config", "kionetrc");
- bool status = parse (openf (filename));
-
- if ( userealnetrc )
- {
- filename = TQDir::homeDirPath()+ TQDir::separator() + ".netrc";
- status |= parse (openf(filename));
- }
-
- if ( !status )
- return false;
- }
-
- if ( !loginMap.contains( type ) )
- return false;
-
- LoginList l = loginMap[type];
- if ( l.isEmpty() )
- return false;
-
- for (LoginList::Iterator it = l.begin(); it != l.end(); ++it)
- {
- AutoLogin &log = *it;
-
- if ( (mode & defaultOnly) == defaultOnly &&
- log.machine == TQString::fromLatin1("default") &&
- (login.login.isEmpty() || login.login == log.login) )
- {
- login.type = log.type;
- login.machine = log.machine;
- login.login = log.login;
- login.password = log.password;
- login.macdef = log.macdef;
- }
-
- if ( (mode & presetOnly) == presetOnly &&
- log.machine == TQString::fromLatin1("preset") &&
- (login.login.isEmpty() || login.login == log.login) )
- {
- login.type = log.type;
- login.machine = log.machine;
- login.login = log.login;
- login.password = log.password;
- login.macdef = log.macdef;
- }
-
- if ( (mode & exactOnly) == exactOnly &&
- log.machine == url.host() &&
- (login.login.isEmpty() || login.login == log.login) )
- {
- login.type = log.type;
- login.machine = log.machine;
- login.login = log.login;
- login.password = log.password;
- login.macdef = log.macdef;
- break;
- }
- }
-
- return true;
-}
-
-int NetRC::openf( const TQString& f )
-{
- KDE_struct_stat sbuff;
- TQCString ef = TQFile::encodeName(f);
- if ( KDE_stat(ef, &sbuff) != 0 )
- return -1;
-
- // Security check!!
- if ( sbuff.st_mode != (S_IFREG|S_IRUSR|S_IWUSR) ||
- sbuff.st_uid != geteuid() )
- return -1;
-
- return KDE_open( ef, O_RDONLY );
-}
-
-TQString NetRC::extract( const char* buf, const char* key, int& pos )
-{
- int idx = pos;
- int m_len = strlen(key);
- int b_len = strlen(buf);
-
- while( idx < b_len )
- {
- while( buf[idx] == ' ' || buf[idx] == '\t' )
- idx++;
-
- if ( strncasecmp( buf+idx, key, m_len ) != 0 )
- idx++;
- else
- {
- idx += m_len;
- while( buf[idx] == ' ' || buf[idx] == '\t' )
- idx++;
-
- int start = idx;
- while( buf[idx] != ' ' && buf[idx] != '\t' &&
- buf[idx] != '\n' && buf[idx] != '\r' )
- idx++;
-
- if ( idx > start )
- {
- pos = idx;
- return TQString::fromLatin1( buf+start, idx-start);
- }
- }
- }
-
- return TQString::null;
-}
-
-bool NetRC::parse( int fd )
-{
- if (fd == -1)
- return false;
-
- TQString type;
- TQString macro;
-
- uint index = 0;
- bool isMacro = false;
- char* buf = new char[NETRC_READ_BUF_SIZE];
- FILE* fstream = KDE_fdopen( fd,"rb" );
-
- while ( fgets (buf, NETRC_READ_BUF_SIZE, fstream) != 0L )
- {
- int pos = 0;
-
- while ( buf[pos] == ' ' || buf[pos] == '\t' )
- pos++;
-
- if ( buf[pos] == '#' || buf[pos] == '\n' ||
- buf[pos] == '\r' || buf[pos] == '\0' )
- {
- if ( buf[pos] != '#' && isMacro )
- isMacro = false;
-
- continue;
- }
-
- if ( isMacro )
- {
- int tail = strlen(buf);
- while( buf[tail-1] == '\n' || buf[tail-1] =='\r' )
- tail--;
-
- TQString mac = TQString::fromLatin1(buf, tail).stripWhiteSpace();
- if ( !mac.isEmpty() )
- loginMap[type][index].macdef[macro].append( mac );
-
- continue;
- }
-
- AutoLogin l;
- l.machine = extract( buf, "machine", pos );
- if ( l.machine.isEmpty() )
- {
- if (strncasecmp(buf+pos, "default", 7) == 0 )
- {
- pos += 7;
- l.machine = TQString::fromLatin1("default");
- }
- else if (strncasecmp(buf+pos, "preset", 6) == 0 )
- {
- pos += 6;
- l.machine = TQString::fromLatin1("preset");
- }
- }
- // kdDebug() << "Machine: " << l.machine << endl;
-
- l.login = extract( buf, "login", pos );
- // kdDebug() << "Login: " << l.login << endl;
-
- l.password = extract( buf, "password", pos );
- if ( l.password.isEmpty() )
- l.password = extract( buf, "account", pos );
- // kdDebug() << "Password: " << l.password << endl;
-
- type = l.type = extract( buf, "type", pos );
- if ( l.type.isEmpty() && !l.machine.isEmpty() )
- type = l.type = TQString::fromLatin1("ftp");
- // kdDebug() << "Type: " << l.type << endl;
-
- macro = extract( buf, "macdef", pos );
- isMacro = !macro.isEmpty();
- // kdDebug() << "Macro: " << macro << endl;
-
- loginMap[l.type].append(l);
- index = loginMap[l.type].count()-1;
- }
-
- delete [] buf;
- fclose (fstream);
- close (fd);
- return true;
-}
diff --git a/kio/kio/chmodjob.cpp b/kio/kio/chmodjob.cpp
deleted file mode 100644
index f589da957..000000000
--- a/kio/kio/chmodjob.cpp
+++ /dev/null
@@ -1,258 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- David Faure <faure@kde.org>
- Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <config.h>
-
-#include <pwd.h>
-#include <grp.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <assert.h>
-
-#include <tqtimer.h>
-#include <tqfile.h>
-#include <klocale.h>
-#include <kdebug.h>
-#include <kmessagebox.h>
-
-#include "kio/job.h"
-#include "kio/chmodjob.h"
-
-#include <kdirnotify_stub.h>
-
-using namespace TDEIO;
-
-ChmodJob::ChmodJob( const KFileItemList& lstItems, int permissions, int mask,
- int newOwner, int newGroup,
- bool recursive, bool showProgressInfo )
- : TDEIO::Job( showProgressInfo ), state( STATE_LISTING ),
- m_permissions( permissions ), m_mask( mask ),
- m_newOwner( newOwner ), m_newGroup( newGroup ),
- m_recursive( recursive ), m_lstItems( lstItems )
-{
- TQTimer::singleShot( 0, this, TQT_SLOT(processList()) );
-}
-
-void ChmodJob::processList()
-{
- while ( !m_lstItems.isEmpty() )
- {
- KFileItem * item = m_lstItems.first();
- if ( !item->isLink() ) // don't do anything with symlinks
- {
- // File or directory -> remember to chmod
- ChmodInfo info;
- info.url = item->url();
- // This is a toplevel file, we apply changes directly (no +X emulation here)
- info.permissions = ( m_permissions & m_mask ) | ( item->permissions() & ~m_mask );
- /*kdDebug(7007) << "\n current permissions=" << TQString::number(item->permissions(),8)
- << "\n wanted permission=" << TQString::number(m_permissions,8)
- << "\n with mask=" << TQString::number(m_mask,8)
- << "\n with ~mask (mask bits we keep) =" << TQString::number((uint)~m_mask,8)
- << "\n bits we keep =" << TQString::number(item->permissions() & ~m_mask,8)
- << "\n new permissions = " << TQString::number(info.permissions,8)
- << endl;*/
- m_infos.prepend( info );
- //kdDebug(7007) << "processList : Adding info for " << info.url.prettyURL() << endl;
- // Directory and recursive -> list
- if ( item->isDir() && m_recursive )
- {
- //kdDebug(7007) << "ChmodJob::processList dir -> listing" << endl;
- TDEIO::ListJob * listJob = TDEIO::listRecursive( item->url(), false /* no GUI */ );
- connect( listJob, TQT_SIGNAL(entries( TDEIO::Job *,
- const TDEIO::UDSEntryList& )),
- TQT_SLOT( slotEntries( TDEIO::Job*,
- const TDEIO::UDSEntryList& )));
- addSubjob( listJob );
- return; // we'll come back later, when this one's finished
- }
- }
- m_lstItems.removeFirst();
- }
- kdDebug(7007) << "ChmodJob::processList -> going to STATE_CHMODING" << endl;
- // We have finished, move on
- state = STATE_CHMODING;
- chmodNextFile();
-}
-
-void ChmodJob::slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList & list )
-{
- TDEIO::UDSEntryListConstIterator it = list.begin();
- TDEIO::UDSEntryListConstIterator end = list.end();
- for (; it != end; ++it) {
- TDEIO::UDSEntry::ConstIterator it2 = (*it).begin();
- mode_t permissions = 0;
- bool isDir = false;
- bool isLink = false;
- TQString relativePath;
- for( ; it2 != (*it).end(); it2++ ) {
- switch( (*it2).m_uds ) {
- case TDEIO::UDS_NAME:
- relativePath = (*it2).m_str;
- break;
- case TDEIO::UDS_FILE_TYPE:
- isDir = S_ISDIR((*it2).m_long);
- break;
- case TDEIO::UDS_LINK_DEST:
- isLink = !(*it2).m_str.isEmpty();
- break;
- case TDEIO::UDS_ACCESS:
- permissions = (mode_t)((*it2).m_long);
- break;
- default:
- break;
- }
- }
- if ( !isLink && relativePath != TQString::fromLatin1("..") )
- {
- ChmodInfo info;
- info.url = m_lstItems.first()->url(); // base directory
- info.url.addPath( relativePath );
- int mask = m_mask;
- // Emulate -X: only give +x to files that had a +x bit already
- // So the check is the opposite : if the file had no x bit, don't touch x bits
- // For dirs this doesn't apply
- if ( !isDir )
- {
- int newPerms = m_permissions & mask;
- if ( (newPerms & 0111) && !(permissions & 0111) )
- {
- // don't interfere with mandatory file locking
- if ( newPerms & 02000 )
- mask = mask & ~0101;
- else
- mask = mask & ~0111;
- }
- }
- info.permissions = ( m_permissions & mask ) | ( permissions & ~mask );
- /*kdDebug(7007) << "\n current permissions=" << TQString::number(permissions,8)
- << "\n wanted permission=" << TQString::number(m_permissions,8)
- << "\n with mask=" << TQString::number(mask,8)
- << "\n with ~mask (mask bits we keep) =" << TQString::number((uint)~mask,8)
- << "\n bits we keep =" << TQString::number(permissions & ~mask,8)
- << "\n new permissions = " << TQString::number(info.permissions,8)
- << endl;*/
- // Prepend this info in our todo list.
- // This way, the toplevel dirs are done last.
- m_infos.prepend( info );
- }
- }
-}
-
-void ChmodJob::chmodNextFile()
-{
- if ( !m_infos.isEmpty() )
- {
- ChmodInfo info = m_infos.first();
- m_infos.remove( m_infos.begin() );
- // First update group / owner (if local file)
- // (permissions have to set after, in case of suid and sgid)
- if ( info.url.isLocalFile() && ( m_newOwner != -1 || m_newGroup != -1 ) )
- {
- TQString path = info.url.path();
- if ( chown( TQFile::encodeName(path), m_newOwner, m_newGroup ) != 0 )
- {
- int answer = KMessageBox::warningContinueCancel( 0, i18n( "<qt>Could not modify the ownership of file <b>%1</b>. You have insufficient access to the file to perform the change.</qt>" ).arg(path), TQString::null, i18n("&Skip File") );
- if (answer == KMessageBox::Cancel)
- {
- m_error = ERR_USER_CANCELED;
- emitResult();
- return;
- }
- }
- }
-
- kdDebug(7007) << "ChmodJob::chmodNextFile chmod'ing " << info.url.prettyURL()
- << " to " << TQString::number(info.permissions,8) << endl;
- TDEIO::SimpleJob * job = TDEIO::chmod( info.url, info.permissions );
- // copy the metadata for acl and default acl
- const TQString aclString = queryMetaData( "ACL_STRING" );
- const TQString defaultAclString = queryMetaData( "DEFAULT_ACL_STRING" );
- if ( !aclString.isEmpty() )
- job->addMetaData( "ACL_STRING", aclString );
- if ( !defaultAclString.isEmpty() )
- job->addMetaData( "DEFAULT_ACL_STRING", defaultAclString );
- addSubjob(job);
- }
- else
- // We have finished
- emitResult();
-}
-
-void ChmodJob::slotResult( TDEIO::Job * job )
-{
- if ( job->error() )
- {
- m_error = job->error();
- m_errorText = job->errorText();
- emitResult();
- return;
- }
- //kdDebug(7007) << " ChmodJob::slotResult( TDEIO::Job * job ) m_lstItems:" << m_lstItems.count() << endl;
- switch ( state )
- {
- case STATE_LISTING:
- subjobs.remove(job);
- m_lstItems.removeFirst();
- kdDebug(7007) << "ChmodJob::slotResult -> processList" << endl;
- processList();
- return;
- case STATE_CHMODING:
- subjobs.remove(job);
- kdDebug(7007) << "ChmodJob::slotResult -> chmodNextFile" << endl;
- chmodNextFile();
- return;
- default:
- assert(0);
- return;
- }
-}
-
-// antlarr: KDE 4: Make owner and group be const TQString &
-TDEIO_EXPORT ChmodJob *TDEIO::chmod( const KFileItemList& lstItems, int permissions, int mask,
- TQString owner, TQString group,
- bool recursive, bool showProgressInfo )
-{
- uid_t newOwnerID = (uid_t)-1; // chown(2) : -1 means no change
- if ( !owner.isEmpty() )
- {
- struct passwd* pw = getpwnam(TQFile::encodeName(owner));
- if ( pw == 0L )
- kdError(250) << " ERROR: No user " << owner << endl;
- else
- newOwnerID = pw->pw_uid;
- }
- gid_t newGroupID = (gid_t)-1; // chown(2) : -1 means no change
- if ( !group.isEmpty() )
- {
- struct group* g = getgrnam(TQFile::encodeName(group));
- if ( g == 0L )
- kdError(250) << " ERROR: No group " << group << endl;
- else
- newGroupID = g->gr_gid;
- }
- return new ChmodJob( lstItems, permissions, mask, newOwnerID, newGroupID, recursive, showProgressInfo );
-}
-
-void ChmodJob::virtual_hook( int id, void* data )
-{ TDEIO::Job::virtual_hook( id, data ); }
-
-#include "chmodjob.moc"
diff --git a/kio/kio/chmodjob.h b/kio/kio/chmodjob.h
deleted file mode 100644
index 81b614562..000000000
--- a/kio/kio/chmodjob.h
+++ /dev/null
@@ -1,109 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_chmodjob_h__
-#define __kio_chmodjob_h__
-
-#include <kurl.h>
-#include <tqstring.h>
-
-#include <kio/global.h>
-#include <kio/job.h>
-#include <kfileitem.h>
-
-namespace TDEIO {
-
- /**
- * This job changes permissions on a list of files or directories,
- * optionally in a recursive manner.
- * @see TDEIO::chmod()
- */
- class TDEIO_EXPORT ChmodJob : public TDEIO::Job
- {
- Q_OBJECT
- public:
- /**
- * Create new ChmodJobs using the TDEIO::chmod() function.
- */
- ChmodJob( const KFileItemList & lstItems, int permissions, int mask,
- int newOwner, int newGroup,
- bool recursive, bool showProgressInfo );
-
- protected:
- void chmodNextFile();
-
- protected slots:
-
- virtual void slotResult( TDEIO::Job *job );
- void slotEntries( TDEIO::Job * , const TDEIO::UDSEntryList & );
- void processList();
-
- private:
- struct ChmodInfo
- {
- KURL url;
- int permissions;
- };
- enum { STATE_LISTING, STATE_CHMODING } state;
- int m_permissions;
- int m_mask;
- int m_newOwner;
- int m_newGroup;
- bool m_recursive;
- KFileItemList m_lstItems;
- TQValueList<ChmodInfo> m_infos;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class ChmodJobPrivate* d;
- };
-
-
- /**
- * Creates a job that changes permissions/ownership on several files or directories,
- * optionally recursively.
- * This version of chmod uses a KFileItemList so that it directly knows
- * what to do with the items. TODO: a version that takes a KURL::List,
- * and a general job that stats each url and returns a KFileItemList.
- *
- * Note that change of ownership is only supported for local files.
- *
- * Inside directories, the "x" bits will only be changed for files that had
- * at least one "x" bit before, and for directories.
- * This emulates the behavior of chmod +X.
- *
- * @param lstItems The file items representing several files or directories.
- * @param permissions the permissions we want to set
- * @param mask the bits we are allowed to change.
- * For instance, if mask is 0077, we don't change
- * the "user" bits, only "group" and "others".
- * @param newOwner If non-empty, the new owner for the files
- * @param newGroup If non-empty, the new group for the files
- * @param recursive whether to open directories recursively
- * @param showProgressInfo true to show progess information
- * @return The job handling the operation.
- */
- TDEIO_EXPORT ChmodJob * chmod( const KFileItemList& lstItems, int permissions, int mask,
- TQString newOwner, TQString newGroup,
- bool recursive, bool showProgressInfo = true );
-
-}
-
-#endif
diff --git a/kio/kio/connection.cpp b/kio/kio/connection.cpp
deleted file mode 100644
index d85f4921c..000000000
--- a/kio/kio/connection.cpp
+++ /dev/null
@@ -1,273 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#include <config.h>
-
-#include <kde_file.h>
-#include <ksock.h>
-#include <tqtimer.h>
-
-#include <sys/types.h>
-#include <sys/signal.h>
-#include <sys/time.h>
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <signal.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "kio/connection.h"
-
-#include <kdebug.h>
-#include <tqsocketnotifier.h>
-
-using namespace TDEIO;
-
-Connection::Connection()
-{
- f_out = 0;
- fd_in = -1;
- socket = 0;
- notifier = 0;
- receiver = 0;
- member = 0;
- m_suspended = false;
- tasks.setAutoDelete(true);
-}
-
-Connection::~Connection()
-{
- close();
-}
-
-void Connection::suspend()
-{
- m_suspended = true;
- if (notifier)
- notifier->setEnabled(false);
-}
-
-void Connection::resume()
-{
- m_suspended = false;
- if (notifier)
- notifier->setEnabled(true);
-}
-
-void Connection::close()
-{
- delete notifier;
- notifier = 0;
- delete socket;
- socket = 0;
-
- // TDESocket has already closed the file descriptor, but we need to
- // close the file-stream as well otherwise we leak memory.
- // As a result we close the file descriptor twice, but that should
- // be harmless
- // KDE4: fix this
- if (f_out)
- fclose(f_out);
- f_out = 0;
- fd_in = -1;
- tasks.clear();
-}
-
-void Connection::send(int cmd, const TQByteArray& data)
-{
- if (!inited() || tasks.count() > 0) {
- Task *task = new Task();
- task->cmd = cmd;
- task->data = data;
- tasks.append(task);
- } else {
- sendnow( cmd, data );
- }
-}
-
-void Connection::dequeue()
-{
- if (!inited())
- return;
-
- while (tasks.count())
- {
- tasks.first();
- Task *task = tasks.take();
- sendnow( task->cmd, task->data );
- delete task;
- }
-}
-
-void Connection::init(TDESocket *sock)
-{
- delete notifier;
- notifier = 0;
-#ifdef Q_OS_UNIX //TODO: not yet available on WIN32
- delete socket;
- socket = sock;
- fd_in = socket->socket();
- f_out = KDE_fdopen( socket->socket(), "wb" );
-#endif
- if (receiver && ( fd_in != -1 )) {
- notifier = new TQSocketNotifier(fd_in, TQSocketNotifier::Read);
- if ( m_suspended ) {
- suspend();
- }
- TQObject::connect(notifier, TQT_SIGNAL(activated(int)), receiver, member);
- }
- dequeue();
-}
-
-void Connection::init(int _fd_in, int fd_out)
-{
- delete notifier;
- notifier = 0;
- fd_in = _fd_in;
- f_out = KDE_fdopen( fd_out, "wb" );
- if (receiver && ( fd_in != -1 )) {
- notifier = new TQSocketNotifier(fd_in, TQSocketNotifier::Read);
- if ( m_suspended ) {
- suspend();
- }
- TQObject::connect(notifier, TQT_SIGNAL(activated(int)), receiver, member);
- }
- dequeue();
-}
-
-
-void Connection::connect(TQObject *_receiver, const char *_member)
-{
- receiver = _receiver;
- member = _member;
- delete notifier;
- notifier = 0;
- if (receiver && (fd_in != -1 )) {
- notifier = new TQSocketNotifier(fd_in, TQSocketNotifier::Read);
- if ( m_suspended )
- suspend();
- TQObject::connect(notifier, TQT_SIGNAL(activated(int)), receiver, member);
- }
-}
-
-bool Connection::sendnow( int _cmd, const TQByteArray &data )
-{
- if (f_out == 0) {
- return false;
- }
-
- if (data.size() > 0xffffff)
- return false;
-
- static char buffer[ 64 ];
- sprintf( buffer, "%6x_%2x_", data.size(), _cmd );
-
- size_t n = fwrite( buffer, 1, 10, f_out );
-
- if ( n != 10 ) {
- kdError(7017) << "Could not send header" << endl;
- return false;
- }
-
- n = fwrite( data.data(), 1, data.size(), f_out );
-
- if ( n != data.size() ) {
- kdError(7017) << "Could not write data" << endl;
- return false;
- }
-
- if (fflush( f_out )) {
- kdError(7017) << "Could not write data" << endl;
- return false;
- }
-
- return true;
-}
-
-int Connection::read( int* _cmd, TQByteArray &data )
-{
- if (fd_in == -1 ) {
- kdError(7017) << "read: not yet inited" << endl;
- return -1;
- }
-
- static char buffer[ 10 ];
-
- again1:
- ssize_t n = ::read( fd_in, buffer, 10);
- if ( n == -1 && errno == EINTR )
- goto again1;
-
- if ( n == -1) {
- kdError(7017) << "Header read failed, errno=" << errno << endl;
- }
-
- if ( n != 10 ) {
- if ( n ) // 0 indicates end of file
- kdError(7017) << "Header has invalid size (" << n << ")" << endl;
- return -1;
- }
-
- buffer[ 6 ] = 0;
- buffer[ 9 ] = 0;
-
- char *p = buffer;
- while( *p == ' ' ) p++;
- long int len = strtol( p, 0L, 16 );
-
- p = buffer + 7;
- while( *p == ' ' ) p++;
- long int cmd = strtol( p, 0L, 16 );
-
- data.resize( len );
-
- if ( len > 0L ) {
- size_t bytesToGo = len;
- size_t bytesRead = 0;
- do {
- n = ::read(fd_in, data.data()+bytesRead, bytesToGo);
- if (n == -1) {
- if (errno == EINTR)
- continue;
-
- kdError(7017) << "Data read failed, errno=" << errno << endl;
- return -1;
- }
- if ( !n ) { // 0 indicates end of file
- kdError(7017) << "Connection ended unexpectedly (" << n << "/" << bytesToGo << ")" << endl;
- return -1;
- }
-
- bytesRead += n;
- bytesToGo -= n;
- }
- while(bytesToGo);
- }
-
- *_cmd = cmd;
- return len;
-}
-
-#include "connection.moc"
diff --git a/kio/kio/dataprotocol.cpp b/kio/kio/dataprotocol.cpp
deleted file mode 100644
index 1e3db04d7..000000000
--- a/kio/kio/dataprotocol.cpp
+++ /dev/null
@@ -1,339 +0,0 @@
-// dataprotocol.cpp
-// ==================
-//
-// Implementation of the data protocol (rfc 2397)
-//
-// Author: Leo Savernik
-// Email: l.savernik@aon.at
-// (C) 2002, 2003 by Leo Savernik
-// Created: Sam Dez 28 14:11:18 CET 2002
-
-/***************************************************************************
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU Lesser General Public License as *
- * published by the Free Software Foundation; version 2. *
- * *
- ***************************************************************************/
-
-#include "dataprotocol.h"
-
-#include <kdebug.h>
-#include <kmdcodec.h>
-#include <kurl.h>
-#include <kio/global.h>
-
-#include <tqcstring.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqtextcodec.h>
-
-#ifdef DATAKIOSLAVE
-# include <kinstance.h>
-# include <stdlib.h>
-#endif
-#ifdef TESTKIO
-# include <iostream.h>
-#endif
-
-#if !defined(DATAKIOSLAVE) && !defined(TESTKIO)
-# define DISPATCH(f) dispatch_##f
-#else
-# define DISPATCH(f) f
-#endif
-
-using namespace TDEIO;
-#ifdef DATAKIOSLAVE
-extern "C" {
-
- int kdemain( int argc, char **argv ) {
- TDEInstance instance( "kio_data" );
-
- kdDebug(7101) << "*** Starting kio_data " << endl;
-
- if (argc != 4) {
- kdDebug(7101) << "Usage: kio_data protocol domain-socket1 domain-socket2" << endl;
- exit(-1);
- }
-
- DataProtocol slave(argv[2], argv[3]);
- slave.dispatchLoop();
-
- kdDebug(7101) << "*** kio_data Done" << endl;
- return 0;
- }
-}
-#endif
-
-/** structure containing header information */
-struct DataHeader {
- TQString mime_type; // mime type of content (lowercase)
- MetaData attributes; // attribute/value pairs (attribute lowercase,
- // value unchanged)
- bool is_base64; // true if data is base64 encoded
- TQString url; // reference to decoded url
- int data_offset; // zero-indexed position within url
- // where the real data begins. May point beyond
- // the end to indicate that there is no data
- TQString *charset; // shortcut to charset (it always exists)
-};
-
-// constant string data
-const TQChar text_plain_str[] = { 't','e','x','t','/','p','l','a','i','n' };
-const TQChar charset_str[] = { 'c','h','a','r','s','e','t' };
-const TQChar us_ascii_str[] = { 'u','s','-','a','s','c','i','i' };
-const TQChar base64_str[] = { 'b','a','s','e','6','4' };
-
-/** returns the position of the first occurrence of any of the given characters
- * @p c1 to @p c3 or buf.length() if none is contained.
- * @param buf buffer where to look for c
- * @param begin zero-indexed starting position
- * @param c1 character to find
- * @param c2 alternative character to find or '\0' to ignore
- * @param c3 alternative character to find or '\0' to ignore
- */
-static int find(const TQString &buf, int begin, TQChar c1, TQChar c2 = '\0',
- TQChar c3 = '\0') {
- int pos = begin;
- int size = (int)buf.length();
- while (pos < size) {
- TQChar ch = buf[pos];
- if (ch == c1
- || (c2 != '\0' && ch == c2)
- || (c3 != '\0' && ch == c3))
- break;
- pos++;
- }/*wend*/
- return pos;
-}
-
-/** extracts the string between the current position @p pos and the first
- * occurrence of either @p c1 to @p c3 exclusively and updates @p pos
- * to point at the found delimiter or at the end of the buffer if
- * neither character occurred.
- * @param buf buffer where to look for
- * @param pos zero-indexed position within buffer
- * @param c1 character to find
- * @param c2 alternative character to find or 0 to ignore
- * @param c3 alternative character to find or 0 to ignore
- */
-inline TQString extract(const TQString &buf, int &pos, TQChar c1,
- TQChar c2 = '\0', TQChar c3 = '\0') {
- int oldpos = pos;
- pos = find(buf,oldpos,c1,c2,c3);
- return TQString(buf.unicode() + oldpos, pos - oldpos);
-}
-
-/** ignores all whitespaces
- * @param buf buffer to operate on
- * @param pos position to shift to first non-whitespace character
- * Upon return @p pos will either point to the first non-whitespace
- * character or to the end of the buffer.
- */
-inline void ignoreWS(const TQString &buf, int &pos) {
- int size = (int)buf.length();
- TQChar ch = buf[pos];
- while (pos < size && (ch == ' ' || ch == '\t' || ch == '\n'
- || ch == '\r'))
- ch = buf[++pos];
-}
-
-/** parses a quoted string as per rfc 822.
- *
- * If trailing quote is missing, the whole rest of the buffer is returned.
- * @param buf buffer to operate on
- * @param pos position pointing to the leading quote
- * @return the extracted string. @p pos will be updated to point to the
- * character following the trailing quote.
- */
-static TQString parseQuotedString(const TQString &buf, int &pos) {
- int size = (int)buf.length();
- TQString res;
- pos++; // jump over leading quote
- bool escaped = false; // if true means next character is literal
- bool parsing = true; // true as long as end quote not found
- while (parsing && pos < size) {
- TQChar ch = buf[pos++];
- if (escaped) {
- res += ch;
- escaped = false;
- } else {
- switch (ch) {
- case '"': parsing = false; break;
- case '\\': escaped = true; break;
- default: res += ch; break;
- }/*end switch*/
- }/*end if*/
- }/*wend*/
- return res;
-}
-
-/** parses the header of a data url
- * @param url the data url
- * @param header_info fills the given DataHeader structure with the header
- * information
- */
-static void parseDataHeader(const KURL &url, DataHeader &header_info) {
- TQConstString text_plain(text_plain_str,sizeof text_plain_str/sizeof text_plain_str[0]);
- TQConstString charset(charset_str,sizeof charset_str/sizeof charset_str[0]);
- TQConstString us_ascii(us_ascii_str,sizeof us_ascii_str/sizeof us_ascii_str[0]);
- TQConstString base64(base64_str,sizeof base64_str/sizeof base64_str[0]);
- // initialize header info members
- header_info.mime_type = text_plain.string();
- header_info.charset = &header_info.attributes.insert(
- charset.string(),us_ascii.string())
- .data();
- header_info.is_base64 = false;
-
- // decode url and save it
- TQString &raw_url = header_info.url = TQString::fromLatin1("data:") + url.path();
- int raw_url_len = (int)raw_url.length();
-
- // jump over scheme part (must be "data:", we don't even check that)
- header_info.data_offset = raw_url.find(':');
- header_info.data_offset++; // jump over colon or to begin if scheme was missing
-
- // read mime type
- if (header_info.data_offset >= raw_url_len) return;
- TQString mime_type = extract(raw_url,header_info.data_offset,';',',')
- .stripWhiteSpace();
- if (!mime_type.isEmpty()) header_info.mime_type = mime_type;
-
- if (header_info.data_offset >= raw_url_len) return;
- // jump over delimiter token and return if data reached
- if (raw_url[header_info.data_offset++] == ',') return;
-
- // read all attributes and store them
- bool data_begin_reached = false;
- while (!data_begin_reached && header_info.data_offset < raw_url_len) {
- // read attribute
- TQString attribute = extract(raw_url,header_info.data_offset,'=',';',',')
- .stripWhiteSpace();
- if (header_info.data_offset >= raw_url_len
- || raw_url[header_info.data_offset] != '=') {
- // no assigment, must be base64 option
- if (attribute == base64.string())
- header_info.is_base64 = true;
- } else {
- header_info.data_offset++; // jump over '=' token
-
- // read value
- ignoreWS(raw_url,header_info.data_offset);
- if (header_info.data_offset >= raw_url_len) return;
-
- TQString value;
- if (raw_url[header_info.data_offset] == '"') {
- value = parseQuotedString(raw_url,header_info.data_offset);
- ignoreWS(raw_url,header_info.data_offset);
- } else
- value = extract(raw_url,header_info.data_offset,';',',')
- .stripWhiteSpace();
-
- // add attribute to map
- header_info.attributes[attribute.lower()] = value;
-
- }/*end if*/
- if (header_info.data_offset < raw_url_len
- && raw_url[header_info.data_offset] == ',')
- data_begin_reached = true;
- header_info.data_offset++; // jump over separator token
- }/*wend*/
-}
-
-#ifdef DATAKIOSLAVE
-DataProtocol::DataProtocol(const TQCString &pool_socket, const TQCString &app_socket)
- : SlaveBase("kio_data", pool_socket, app_socket) {
-#else
-DataProtocol::DataProtocol() {
-#endif
- kdDebug() << "DataProtocol::DataProtocol()" << endl;
-}
-
-/* --------------------------------------------------------------------- */
-
-DataProtocol::~DataProtocol() {
- kdDebug() << "DataProtocol::~DataProtocol()" << endl;
-}
-
-/* --------------------------------------------------------------------- */
-
-void DataProtocol::get(const KURL& url) {
- ref();
- //kdDebug() << "===============================================================================================================================================================================" << endl;
- kdDebug() << "kio_data@"<<this<<"::get(const KURL& url)" << endl ;
-
- DataHeader hdr;
- parseDataHeader(url,hdr);
-
- int size = (int)hdr.url.length();
- int data_ofs = QMIN(hdr.data_offset,size);
- // FIXME: string is copied, would be nice if we could have a reference only
- TQString url_data = hdr.url.mid(data_ofs);
- TQCString outData;
-
-#ifdef TESTKIO
-// cout << "current charset: \"" << *hdr.charset << "\"" << endl;
-#endif
- if (hdr.is_base64) {
- // base64 stuff is expected to contain the correct charset, so we just
- // decode it and pass it to the receiver
- KCodecs::base64Decode(url_data.local8Bit(),outData);
- } else {
- // FIXME: This is all flawed, must be reworked thoroughly
- // non encoded data must be converted to the given charset
- TQTextCodec *codec = TQTextCodec::codecForName(hdr.charset->latin1());
- if (codec != 0) {
- outData = codec->fromUnicode(url_data);
- } else {
- // if there is no approprate codec, just use local encoding. This
- // should work for >90% of all cases.
- outData = url_data.local8Bit();
- }/*end if*/
- }/*end if*/
-
- //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
- //kdDebug() << "emit mimeType@"<<this << endl ;
- mimeType(hdr.mime_type);
- //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
- //kdDebug() << "emit totalSize@"<<this << endl ;
- totalSize(outData.size());
-
- //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
- //kdDebug() << "emit setMetaData@"<<this << endl ;
-#if defined(TESTKIO) || defined(DATAKIOSLAVE)
- MetaData::ConstIterator it;
- for (it = hdr.attributes.begin(); it != hdr.attributes.end(); ++it) {
- setMetaData(it.key(),it.data());
- }/*next it*/
-#else
- setAllMetaData(hdr.attributes);
-#endif
-
- //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
- //kdDebug() << "emit sendMetaData@"<<this << endl ;
- sendMetaData();
- //kdDebug() << "^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C" << endl;
-// kdDebug() << "(1) queue size " << dispatchQueue.size() << endl;
- // empiric studies have shown that this shouldn't be queued & dispatched
- /*DISPATCH*/(data(outData));
-// kdDebug() << "(2) queue size " << dispatchQueue.size() << endl;
- DISPATCH(data(TQByteArray()));
-// kdDebug() << "(3) queue size " << dispatchQueue.size() << endl;
- DISPATCH(finished());
-// kdDebug() << "(4) queue size " << dispatchQueue.size() << endl;
- deref();
-}
-
-/* --------------------------------------------------------------------- */
-
-void DataProtocol::mimetype(const KURL &url) {
- ref();
- DataHeader hdr;
- parseDataHeader(url,hdr);
- mimeType(hdr.mime_type);
- finished();
- deref();
-}
-
-/* --------------------------------------------------------------------- */
-
diff --git a/kio/kio/dataprotocol.h b/kio/kio/dataprotocol.h
deleted file mode 100644
index 472b42886..000000000
--- a/kio/kio/dataprotocol.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// dataprotocol.h
-// ================
-//
-// Interface of the KDE data protocol core operations
-//
-// Author: Leo Savernik
-// Email: l.savernik@aon.at
-// (C) 2002 by Leo Savernik
-// Created: Sam Dez 28 14:11:18 CET 2002
-
-/***************************************************************************
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU Lesser General Public License as *
- * published by the Free Software Foundation; version 2. *
- * *
- ***************************************************************************/
-
-#ifndef __dataprotocol_h__
-#define __dataprotocol_h__
-
-// dataprotocol.* interprets the following defines
-// DATAKIOSLAVE: define if you want to compile this into a stand-alone
-// kioslave
-// TESTKIO: define for test-driving
-// Both defines are mutually exclusive. Defining none of them compiles
-// DataProtocol for internal usage within libkiocore.
-
-class TQString;
-class TQCString;
-
-class KURL;
-
-#if defined(DATAKIOSLAVE)
-# include <kio/slavebase.h>
-#elif !defined(TESTKIO)
-# include "kio/dataslave.h"
-#endif
-
-namespace TDEIO {
-
-/** This kioslave provides support of data urls as specified by rfc 2397
- * @see http://www.ietf.org/rfc/rfc2397.txt
- * @author Leo Savernik
- */
-#if defined(DATAKIOSLAVE)
-class DataProtocol : public TDEIO::SlaveBase {
-#elif defined(TESTKIO)
-class DataProtocol : public TestSlave {
-#else
-class DataProtocol : public DataSlave {
-#endif
-
-public:
-#if defined(DATAKIOSLAVE)
- DataProtocol(const TQCString &pool_socket, const TQCString &app_socket);
-#else
- DataProtocol();
-#endif
- virtual ~DataProtocol();
- virtual void mimetype(const KURL &url);
- virtual void get(const KURL &url);
-#if defined(TESTKIO)
- void ref() {}
- void deref() {}
-#endif
-};
-
-}/*end namespace*/
-
-#endif
diff --git a/kio/kio/dataslave.h b/kio/kio/dataslave.h
deleted file mode 100644
index 3567f3faf..000000000
--- a/kio/kio/dataslave.h
+++ /dev/null
@@ -1,126 +0,0 @@
-// -*- c++ -*-
-/*
- * This file is part of the KDE libraries
- * Copyright (c) 2003 Leo Savernik <l.savernik@aon.at>
- * Derived from slave.h
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#ifndef __KIO_DATASLAVE_H__
-#define __KIO_DATASLAVE_H__
-
-#include <kio/global.h>
-#include <kio/slave.h>
-
-class TQTimer;
-
-// don't forget to sync DISPATCH_IMPL in dataslave.h
-#define DISPATCH_DECL(type) \
- void dispatch_##type();
-
-// don't forget to sync DISPATCH_IMPL1 in dataslave.h
-#define DISPATCH_DECL1(type, paramtype, param) \
- void dispatch_##type(paramtype param);
-
-namespace TDEIO {
-
- /**
- * This class provides a high performance implementation for the data
- * url scheme (rfc2397).
- *
- * @internal
- * Do not use this class in external applications. It is an implementation
- * detail of KIO and subject to change without notice.
- * @author Leo Savernik
- */
- class DataSlave : public TDEIO::Slave {
- Q_OBJECT
- public:
- DataSlave();
-
- virtual ~DataSlave();
-
- virtual void setHost(const TQString &host, int port,
- const TQString &user, const TQString &passwd);
- virtual void setConfig(const MetaData &config);
-
- virtual void suspend();
- virtual void resume();
- virtual bool suspended();
- virtual void send(int cmd, const TQByteArray &data = TQByteArray());
-
- virtual void hold(const KURL &url);
-
- // pure virtual methods that are defined by the actual protocol
- virtual void get(const KURL &url) = 0;
- virtual void mimetype(const KURL &url) = 0;
-
- protected:
- /**
- * Sets metadata
- * @internal
- */
- void setAllMetaData(const MetaData &);
- /**
- * Sends metadata set with setAllMetaData
- * @internal
- */
- void sendMetaData();
-
- // queueing methods
- /** identifiers of functions to be queued */
- enum QueueType { Queue_mimeType = 1, Queue_totalSize,
- Queue_sendMetaData, Queue_data, Queue_finished };
- /** structure for queueing. It is very primitive, it doesn't
- * even try to conserve memory.
- */
- struct QueueStruct {
- QueueType type;
- TQString s;
- TDEIO::filesize_t size;
- TQByteArray ba;
-
- QueueStruct() {}
- QueueStruct(QueueType type) : type(type) {}
- };
- typedef TQValueList<QueueStruct> DispatchQueue;
- DispatchQueue dispatchQueue;
-
- DISPATCH_DECL1(mimeType, const TQString &, s)
- DISPATCH_DECL1(totalSize, TDEIO::filesize_t, size)
- DISPATCH_DECL(sendMetaData)
- DISPATCH_DECL1(data, const TQByteArray &, ba)
- DISPATCH_DECL(finished)
-
- protected slots:
- /** dispatches next queued method. Does nothing if there are no
- * queued methods.
- */
- void dispatchNext();
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- MetaData meta_data;
- bool _suspended;
- TQTimer *timer;
- };
-
-}
-
-#undef DISPATCH_DECL
-#undef DISPATCH_DECL1
-
-#endif /*__KIO_DATASLAVE_H__*/
diff --git a/kio/kio/davjob.cpp b/kio/kio/davjob.cpp
deleted file mode 100644
index f1ba2d2d4..000000000
--- a/kio/kio/davjob.cpp
+++ /dev/null
@@ -1,142 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Jan-Pascal van Best <janpascal@vanbest.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kurl.h>
-
-#include <tqobject.h>
-#include <tqptrlist.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqguardedptr.h>
-#include <tqdom.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <kdebug.h>
-#include <kio/jobclasses.h>
-#include <kio/global.h>
-#include <kio/http.h>
-#include <kio/davjob.h>
-#include <kio/job.h>
-#include <kio/slaveinterface.h>
-
-#define KIO_ARGS TQByteArray packedArgs; TQDataStream stream( packedArgs, IO_WriteOnly ); stream
-
-using namespace TDEIO;
-
-class DavJob::DavJobPrivate
-{
-public:
- TQByteArray savedStaticData;
- TQByteArray str_response; // replaces the TQString previously used in DavJob itself
-};
-
-DavJob::DavJob( const KURL& url, int method, const TQString& request, bool showProgressInfo )
- : TransferJob( url, TDEIO::CMD_SPECIAL, TQByteArray(), TQByteArray(), showProgressInfo )
-{
- d = new DavJobPrivate;
- // We couldn't set the args when calling the parent constructor,
- // so do it now.
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << (int) 7 << url << method;
- // Same for static data
- if ( ! request.isEmpty() && ! request.isNull() ) {
- staticData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + request.utf8();
- staticData.truncate( staticData.size() - 1 );
- d->savedStaticData = staticData.copy();
- }
-}
-
-void DavJob::slotData( const TQByteArray& data )
-{
- if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error) {
- unsigned int oldSize = d->str_response.size();
- d->str_response.resize( oldSize + data.size() );
- memcpy( d->str_response.data() + oldSize, data.data(), data.size() );
- }
-}
-
-void DavJob::slotFinished()
-{
- // kdDebug(7113) << "DavJob::slotFinished()" << endl;
- // kdDebug(7113) << d->str_response << endl;
- if (!m_redirectionURL.isEmpty() && m_redirectionURL.isValid() && (m_command == CMD_SPECIAL)) {
- TQDataStream istream( m_packedArgs, IO_ReadOnly );
- int s_cmd, s_method;
- KURL s_url;
- istream >> s_cmd;
- istream >> s_url;
- istream >> s_method;
- // PROPFIND
- if ( (s_cmd == 7) && (s_method == (int)TDEIO::DAV_PROPFIND) ) {
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << (int)7 << m_redirectionURL << (int)TDEIO::DAV_PROPFIND;
- }
- } else if ( ! m_response.setContent( d->str_response, true ) ) {
- // An error occurred parsing the XML response
- TQDomElement root = m_response.createElementNS( "DAV:", "error-report" );
- m_response.appendChild( root );
-
- TQDomElement el = m_response.createElementNS( "DAV:", "offending-response" );
- TQDomText textnode = m_response.createTextNode( d->str_response );
- el.appendChild( textnode );
- root.appendChild( el );
- delete d; // Should be in virtual destructor
- d = 0;
- } else {
- delete d; // Should be in virtual destructor
- d = 0;
- }
- // kdDebug(7113) << m_response.toString() << endl;
- TransferJob::slotFinished();
- if( d ) staticData = d->savedStaticData.copy(); // Need to send DAV request to this host too
-}
-
-/* Convenience methods */
-
-// KDE 4: Make it const TQString &
-DavJob* TDEIO::davPropFind( const KURL& url, const TQDomDocument& properties, TQString depth, bool showProgressInfo )
-{
- DavJob *job = new DavJob( url, (int) TDEIO::DAV_PROPFIND, properties.toString(), showProgressInfo );
- job->addMetaData( "davDepth", depth );
- return job;
-}
-
-
-DavJob* TDEIO::davPropPatch( const KURL& url, const TQDomDocument& properties, bool showProgressInfo )
-{
- return new DavJob( url, (int) TDEIO::DAV_PROPPATCH, properties.toString(), showProgressInfo );
-}
-
-DavJob* TDEIO::davSearch( const KURL& url, const TQString& nsURI, const TQString& qName, const TQString& query, bool showProgressInfo )
-{
- TQDomDocument doc;
- TQDomElement searchrequest = doc.createElementNS( "DAV:", "searchrequest" );
- TQDomElement searchelement = doc.createElementNS( nsURI, qName );
- TQDomText text = doc.createTextNode( query );
- searchelement.appendChild( text );
- searchrequest.appendChild( searchelement );
- doc.appendChild( searchrequest );
- return new DavJob( url, TDEIO::DAV_SEARCH, doc.toString(), showProgressInfo );
-}
-
-#include "davjob.moc"
diff --git a/kio/kio/davjob.h b/kio/kio/davjob.h
deleted file mode 100644
index 02eaa6a78..000000000
--- a/kio/kio/davjob.h
+++ /dev/null
@@ -1,127 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Jan-Pascal van Best <janpascal@vanbest.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_davjob_h__
-#define __kio_davjob_h__
-
-#include <kurl.h>
-
-#include <tqobject.h>
-#include <tqptrlist.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqguardedptr.h>
-#include <tqdom.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <kio/jobclasses.h>
-#include <kio/global.h>
-
-class Observer;
-class TQTimer;
-
-namespace TDEIO {
-
- class Slave;
- class SlaveInterface;
-
- /**
- * The transfer job pumps data into and/or out of a Slave.
- * Data is sent to the slave on request of the slave ( dataReq).
- * If data coming from the slave can not be handled, the
- * reading of data from the slave should be suspended.
- * @see TDEIO::davPropFind()
- * @see TDEIO::davPropPatch()
- * @see TDEIO::davSearch()
- * @since 3.1
- */
- class TDEIO_EXPORT DavJob : public TransferJob {
- Q_OBJECT
-
- public:
- /**
- * Use TDEIO::davPropFind(), TDEIO::davPropPatch() and
- * TDEIO::davSearch() to create a new DavJob.
- */
- DavJob(const KURL& url, int method,
- const TQString& request, bool showProgressInfo);
- /**
- * Returns the response as a TQDomDocument.
- * @return the response document
- */
- TQDomDocument& response() { return m_response; }
-
- protected slots:
- virtual void slotFinished();
- virtual void slotData( const TQByteArray &data);
-
- protected:
- bool m_suspended;
- TransferJob *m_subJob;
- private:
- class DavJobPrivate;
- DavJobPrivate *d;
- TQString dummy; // kept around for BC reasons
- TQDomDocument m_response;
- };
-
- /**
- * Creates a new DavJob that issues a PROPFIND command. PROPFIND retrieves
- * the properties of the resource identified by the given @p url.
- *
- * @param url the URL of the resource
- * @param properties a propfind document that describes the properties that
- * should be retrieved
- * @param depth the depth of the request. Can be "0", "1" or "infinity"
- * @param showProgressInfo true to show progress information
- * @return the new DavJob
- */
- TDEIO_EXPORT DavJob* davPropFind( const KURL& url, const TQDomDocument& properties, TQString depth, bool showProgressInfo=true );
-
- /**
- * Creates a new DavJob that issues a PROPPATCH command. PROPPATCH sets
- * the properties of the resource identified by the given @p url.
- *
- * @param url the URL of the resource
- * @param properties a PROPPACTCH document that describes the properties that
- * should be modified and its new values
- * @param showProgressInfo true to show progress information
- * @return the new DavJob
- */
- TDEIO_EXPORT DavJob* davPropPatch( const KURL& url, const TQDomDocument& properties, bool showProgressInfo=true );
-
- /**
- * Creates a new DavJob that issues a SEARCH command.
- *
- * @param url the URL of the resource
- * @param nsURI the URI of the search method's qualified name
- * @param qName the local part of the search method's qualified name
- * @param query the search string
- * @param showProgressInfo true to show progress information
- * @return the new DavJob
- */
- TDEIO_EXPORT DavJob* davSearch( const KURL &url, const TQString& nsURI, const TQString& qName, const TQString& query, bool showProgressInfo=true );
-
-}
-
-#endif
-
diff --git a/kio/kio/defaultprogress.cpp b/kio/kio/defaultprogress.cpp
deleted file mode 100644
index 72bec0cfc..000000000
--- a/kio/kio/defaultprogress.cpp
+++ /dev/null
@@ -1,507 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Matej Koss <koss@miesto.sk>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqtimer.h>
-#include <tqlayout.h>
-#include <tqtooltip.h>
-#include <tqdatetime.h>
-#include <tqcheckbox.h>
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kdialog.h>
-#include <kstringhandler.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kiconloader.h>
-#include <kprocess.h>
-#include <kpushbutton.h>
-#include <kstandarddirs.h>
-#include <kstdguiitem.h>
-#include <klineedit.h>
-
-#ifdef Q_WS_X11
-#include <twin.h>
-#endif
-
-#include "jobclasses.h"
-#include "defaultprogress.h"
-
-namespace TDEIO {
-
-class DefaultProgress::DefaultProgressPrivate
-{
-public:
- bool keepOpenChecked;
- bool noCaptionYet;
- KPushButton *cancelClose;
- KPushButton *openFile;
- KPushButton *openLocation;
- TQCheckBox *keepOpen;
- KURL location;
- TQTime startTime;
-};
-
-DefaultProgress::DefaultProgress( bool showNow )
- : ProgressBase( 0 ),
- m_iTotalSize(0), m_iTotalFiles(0), m_iTotalDirs(0),
- m_iProcessedSize(0), m_iProcessedDirs(0), m_iProcessedFiles(0)
-{
- init();
-
- if ( showNow ) {
- show();
- }
-}
-
-DefaultProgress::DefaultProgress( TQWidget* parent, const char* /*name*/ )
- : ProgressBase( parent ),
- m_iTotalSize(0), m_iTotalFiles(0), m_iTotalDirs(0),
- m_iProcessedSize(0), m_iProcessedDirs(0), m_iProcessedFiles(0)
-{
- init();
-}
-
-bool DefaultProgress::keepOpen() const
-{
- return d->keepOpenChecked;
-}
-
-void DefaultProgress::init()
-{
- d = new DefaultProgressPrivate;
-
-#ifdef Q_WS_X11 //FIXME(E): Remove once all the KWin::foo calls have been ported to QWS
- // Set a useful icon for this window!
- KWin::setIcons( winId(),
- TDEGlobal::iconLoader()->loadIcon( "filesave", KIcon::NoGroup, 32 ),
- TDEGlobal::iconLoader()->loadIcon( "filesave", KIcon::NoGroup, 16 ) );
-#endif
-
- TQVBoxLayout *topLayout = new TQVBoxLayout( this, KDialog::marginHint(),
- KDialog::spacingHint() );
- topLayout->addStrut( 360 ); // makes dlg at least that wide
-
- TQGridLayout *grid = new TQGridLayout( 2, 3 );
- topLayout->addLayout(TQT_TQLAYOUT(grid));
- grid->addColSpacing(1, KDialog::spacingHint());
- // filenames or action name
- grid->addWidget(new TQLabel(i18n("Source:"), this), 0, 0);
-
- sourceEdit = new KLineEdit(this);
- sourceEdit->setReadOnly(true);
- sourceEdit->setEnableSqueezedText(true);
- grid->addWidget(sourceEdit, 0, 2);
-
- destInvite = new TQLabel(i18n("Destination:"), this);
- grid->addWidget(destInvite, 1, 0);
-
- destEdit = new KLineEdit(this);
- destEdit->setReadOnly (true);
- destEdit->setEnableSqueezedText(true);
- grid->addWidget(destEdit, 1, 2);
-
- m_pProgressBar = new KProgress(this);
- topLayout->addWidget( m_pProgressBar );
-
- // processed info
- TQHBoxLayout *hBox = new TQHBoxLayout();
- topLayout->addLayout(hBox);
-
- sizeLabel = new TQLabel(this);
- hBox->addWidget(sizeLabel);
-
- resumeLabel = new TQLabel(this);
- hBox->addWidget(resumeLabel);
-
- progressLabel = new TQLabel( this );
-/* progressLabel->setSizePolicy( TQSizePolicy( TQSizePolicy::MinimumExpanding,
- TQSizePolicy::Preferred ) );*/
- progressLabel->setAlignment( TQLabel::AlignRight );
- hBox->addWidget( progressLabel );
-
- hBox = new TQHBoxLayout();
- topLayout->addLayout(hBox);
-
- speedLabel = new TQLabel(this);
- hBox->addWidget(speedLabel, 1);
-
- TQFrame *line = new TQFrame( this );
- line->setFrameShape( TQFrame::HLine );
- line->setFrameShadow( TQFrame::Sunken );
- topLayout->addWidget( line );
-
- d->keepOpen = new TQCheckBox( i18n("&Keep this window open after transfer is complete"), this);
- connect( d->keepOpen, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( slotKeepOpenToggled(bool) ) );
- topLayout->addWidget(d->keepOpen);
- d->keepOpen->hide();
-
- hBox = new TQHBoxLayout();
- topLayout->addLayout(hBox);
-
- d->openFile = new KPushButton( i18n("Open &File"), this );
- connect( d->openFile, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOpenFile() ) );
- hBox->addWidget( d->openFile );
- d->openFile->setEnabled(false);
- d->openFile->hide();
-
- d->openLocation = new KPushButton( i18n("Open &Destination"), this );
- connect( d->openLocation, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOpenLocation() ) );
- hBox->addWidget( d->openLocation );
- d->openLocation->hide();
-
- hBox->addStretch(1);
-
- d->cancelClose = new KPushButton( KStdGuiItem::cancel(), this );
- connect( d->cancelClose, TQT_SIGNAL( clicked() ), TQT_SLOT( slotStop() ) );
- hBox->addWidget( d->cancelClose );
-
- resize( sizeHint() );
- setMaximumHeight(sizeHint().height());
-
- d->keepOpenChecked = false;
- d->noCaptionYet = true;
- setCaption(i18n("Progress Dialog")); // show something better than kio_uiserver
-}
-
-DefaultProgress::~DefaultProgress()
-{
- delete d;
-}
-
-void DefaultProgress::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
-{
- // size is measured in bytes
- if ( m_iTotalSize == size )
- return;
- m_iTotalSize = size;
- if (d->startTime.isNull())
- d->startTime.start();
-}
-
-
-void DefaultProgress::slotTotalFiles( TDEIO::Job*, unsigned long files )
-{
- if ( m_iTotalFiles == files )
- return;
- m_iTotalFiles = files;
- showTotals();
-}
-
-
-void DefaultProgress::slotTotalDirs( TDEIO::Job*, unsigned long dirs )
-{
- if ( m_iTotalDirs == dirs )
- return;
- m_iTotalDirs = dirs;
- showTotals();
-}
-
-void DefaultProgress::showTotals()
-{
- // Show the totals in the progress label, if we still haven't
- // processed anything. This is useful when the stat'ing phase
- // of CopyJob takes a long time (e.g. over networks).
- if ( m_iProcessedFiles == 0 && m_iProcessedDirs == 0 )
- {
- TQString tmps;
- if ( m_iTotalDirs > 1 )
- // that we have a singular to translate looks weired but is only logical
- // xgettext: no-c-format
- tmps = i18n("%n folder", "%n folders", m_iTotalDirs) + " ";
- // xgettext: no-c-format
- tmps += i18n("%n file", "%n files", m_iTotalFiles);
- progressLabel->setText( tmps );
- }
-}
-
-//static
-TQString DefaultProgress::makePercentString( unsigned long percent,
- TDEIO::filesize_t totalSize,
- unsigned long totalFiles )
-{
- if ( totalSize )
- return i18n( "%1 % of %2 " ).arg( TQString::number(percent) , TDEIO::convertSize( totalSize ) );
- else if ( totalFiles )
- return i18n( "%1 % of 1 file", "%1 % of %n files", totalFiles ).arg( percent );
- else
- return i18n( "%1 %" ).arg( percent );
-}
-
-void DefaultProgress::slotPercent( TDEIO::Job*, unsigned long percent )
-{
- TQString caption = makePercentString( percent, m_iTotalSize, m_iTotalFiles );
- m_pProgressBar->setValue( percent );
- switch(mode) {
- case Copy:
- caption.append(i18n(" (Copying)"));
- break;
- case Move:
- caption.append(i18n(" (Moving)"));
- break;
- case Delete:
- caption.append(i18n(" (Deleting)"));
- break;
- case Create:
- caption.append(i18n(" (Creating)"));
- break;
- case Done:
- caption.append(i18n(" (Done)"));
- break;
- }
-
- setCaption( caption );
- d->noCaptionYet = false;
-}
-
-
-void DefaultProgress::slotInfoMessage( TDEIO::Job*, const TQString & msg )
-{
- speedLabel->setText( msg );
- speedLabel->setAlignment( speedLabel->alignment() & ~TQt::WordBreak );
-}
-
-
-void DefaultProgress::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t bytes ) {
- if ( m_iProcessedSize == bytes )
- return;
- m_iProcessedSize = bytes;
-
- TQString tmp = i18n( "%1 of %2 complete")
- .arg( TDEIO::convertSize(bytes) )
- .arg( TDEIO::convertSize(m_iTotalSize));
- sizeLabel->setText( tmp );
-}
-
-
-void DefaultProgress::slotProcessedDirs( TDEIO::Job*, unsigned long dirs )
-{
- if ( m_iProcessedDirs == dirs )
- return;
- m_iProcessedDirs = dirs;
-
- TQString tmps;
- tmps = i18n("%1 / %n folder", "%1 / %n folders", m_iTotalDirs).arg( m_iProcessedDirs );
- tmps += " ";
- tmps += i18n("%1 / %n file", "%1 / %n files", m_iTotalFiles).arg( m_iProcessedFiles );
- progressLabel->setText( tmps );
-}
-
-
-void DefaultProgress::slotProcessedFiles( TDEIO::Job*, unsigned long files )
-{
- if ( m_iProcessedFiles == files )
- return;
- m_iProcessedFiles = files;
-
- TQString tmps;
- if ( m_iTotalDirs > 1 ) {
- tmps = i18n("%1 / %n folder", "%1 / %n folders", m_iTotalDirs).arg( m_iProcessedDirs );
- tmps += " ";
- }
- tmps += i18n("%1 / %n file", "%1 / %n files", m_iTotalFiles).arg( m_iProcessedFiles );
- progressLabel->setText( tmps );
-}
-
-
-void DefaultProgress::slotSpeed( TDEIO::Job*, unsigned long speed )
-{
- if ( speed == 0 ) {
- speedLabel->setText( i18n( "Stalled") );
- } else {
- speedLabel->setText( i18n( "%1/s ( %2 remaining )").arg( TDEIO::convertSize( speed ))
- .arg( TDEIO::convertSeconds( TDEIO::calculateRemainingSeconds( m_iTotalSize, m_iProcessedSize, speed ))) );
- }
-}
-
-
-void DefaultProgress::slotCopying( TDEIO::Job*, const KURL& from, const KURL& to )
-{
- if ( d->noCaptionYet ) {
- setCaption(i18n("Copy File(s) Progress"));
- d->noCaptionYet = false;
- }
- mode = Copy;
- sourceEdit->setText(from.prettyURL());
- setDestVisible( true );
- checkDestination( to );
- destEdit->setText(to.prettyURL());
-}
-
-
-void DefaultProgress::slotMoving( TDEIO::Job*, const KURL& from, const KURL& to )
-{
- if ( d->noCaptionYet ) {
- setCaption(i18n("Move File(s) Progress"));
- d->noCaptionYet = false;
- }
- mode = Move;
- sourceEdit->setText(from.prettyURL());
- setDestVisible( true );
- checkDestination( to );
- destEdit->setText(to.prettyURL());
-}
-
-
-void DefaultProgress::slotCreatingDir( TDEIO::Job*, const KURL& dir )
-{
- if ( d->noCaptionYet ) {
- setCaption(i18n("Creating Folder"));
- d->noCaptionYet = false;
- }
- mode = Create;
- sourceEdit->setText(dir.prettyURL());
- setDestVisible( false );
-}
-
-
-void DefaultProgress::slotDeleting( TDEIO::Job*, const KURL& url )
-{
- if ( d->noCaptionYet ) {
- setCaption(i18n("Delete File(s) Progress"));
- d->noCaptionYet = false;
- }
- mode = Delete;
- sourceEdit->setText(url.prettyURL());
- setDestVisible( false );
-}
-
-void DefaultProgress::slotTransferring( TDEIO::Job*, const KURL& url )
-{
- if ( d->noCaptionYet ) {
- setCaption(i18n("Loading Progress"));
- d->noCaptionYet = false;
- }
- sourceEdit->setText(url.prettyURL());
- setDestVisible( false );
-}
-
-void DefaultProgress::slotStating( TDEIO::Job*, const KURL& url )
-{
- setCaption(i18n("Examining File Progress"));
- sourceEdit->setText(url.prettyURL());
- setDestVisible( false );
-}
-
-void DefaultProgress::slotMounting( TDEIO::Job*, const TQString & dev, const TQString & point )
-{
- setCaption(i18n("Mounting %1").arg(dev));
- sourceEdit->setText(point);
- setDestVisible( false );
-}
-
-void DefaultProgress::slotUnmounting( TDEIO::Job*, const TQString & point )
-{
- setCaption(i18n("Unmounting"));
- sourceEdit->setText(point);
- setDestVisible( false );
-}
-
-void DefaultProgress::slotCanResume( TDEIO::Job*, TDEIO::filesize_t resume )
-{
- if ( resume ) {
- resumeLabel->setText( i18n("Resuming from %1").arg(TDEIO::number(resume)) );
- } else {
- resumeLabel->setText( i18n("Not resumable") );
- }
-}
-
-void DefaultProgress::setDestVisible( bool visible )
-{
- // We can't hide the destInvite/destEdit labels,
- // because it screws up the TQGridLayout.
- if (visible)
- {
- destInvite->show();
- destEdit->show();
-
- destInvite->setText( i18n("Destination:") );
- }
- else
- {
- destInvite->hide();
- destEdit->hide();
- destInvite->setText( TQString::null );
- destEdit->setText( TQString::null );
- }
-}
-
-void DefaultProgress::slotClean() {
- if (d->keepOpenChecked) {
- mode = Done;
- slotPercent(0, 100);
- d->cancelClose->setGuiItem( KStdGuiItem::close() );
- d->openFile->setEnabled(true);
- slotProcessedSize(0, m_iTotalSize);
- d->keepOpen->setEnabled(false);
- if (!d->startTime.isNull()) {
- int s = d->startTime.elapsed();
- if (!s)
- s = 1;
- speedLabel->setText(i18n("%1/s (done)").arg(TDEIO::convertSize(1000 * m_iTotalSize / s)));
- }
- setOnlyClean(false);
- }
- else
- hide();
-}
-
-void DefaultProgress::slotKeepOpenToggled(bool keepopen)
-{
- d->keepOpenChecked=keepopen;
-}
-
-void DefaultProgress::checkDestination(const KURL& dest) {
- bool ok = true;
- if ( dest.isLocalFile() ) {
- TQString path = dest.path( -1 );
- TQStringList tmpDirs = TDEGlobal::dirs()->resourceDirs( "tmp" );
- for ( TQStringList::Iterator it = tmpDirs.begin() ; ok && it != tmpDirs.end() ; ++it )
- if ( path.contains( *it ) )
- ok = false; // it's in the tmp resource
- }
-
- if ( ok ) {
- d->openFile->show();
- d->openLocation->show();
- d->keepOpen->show();
- d->location=dest;
- }
-}
-
-void DefaultProgress::slotOpenFile()
-{
- TDEProcess proc;
- proc << "konqueror" << d->location.prettyURL();
- proc.start(TDEProcess::DontCare);
-}
-
-void DefaultProgress::slotOpenLocation()
-{
- TDEProcess proc;
- d->location.setFileName("");
- proc << "konqueror" << d->location.prettyURL();
- proc.start(TDEProcess::DontCare);
-}
-
-void DefaultProgress::virtual_hook( int id, void* data )
-{ ProgressBase::virtual_hook( id, data ); }
-
-} /* namespace */
-
-#include "defaultprogress.moc"
diff --git a/kio/kio/defaultprogress.h b/kio/kio/defaultprogress.h
deleted file mode 100644
index 44ffff6c4..000000000
--- a/kio/kio/defaultprogress.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Matej Koss <koss@miesto.sk>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __defaultprogress_h__
-#define __defaultprogress_h__
-
-#include <tqlabel.h>
-
-#include <kio/global.h>
-
-#include <kprogress.h>
-
-#include "progressbase.h"
-
-class KLineEdit;
-
-namespace TDEIO {
-
-/*
- * A default implementation of the progress dialog ProgressBase.
- * ProgressBase
- */
-class TDEIO_EXPORT DefaultProgress : public ProgressBase {
-
- Q_OBJECT
-
-public:
- /**
- * Creates a new default progress dialog.
- * @param showNow true to show immediately, false to show when
- * needed
- */
- DefaultProgress( bool showNow = true );
- /**
- * Creates a new default progress dialog.
- * @param parent the parent of the dialog (or 0 for top-level)
- * @param name the name of the dialog, can be 0
- * @since 3.1
- */
- DefaultProgress( TQWidget* parent, const char* name = 0 );
- ~DefaultProgress();
-
- bool keepOpen() const;
-
- /// Shared with uiserver.cpp
- static TQString makePercentString( unsigned long percent,
- TDEIO::filesize_t totalSize,
- unsigned long totalFiles );
-
-public slots:
- virtual void slotTotalSize( TDEIO::Job *job, TDEIO::filesize_t size );
- virtual void slotTotalFiles( TDEIO::Job *job, unsigned long files );
- virtual void slotTotalDirs( TDEIO::Job *job, unsigned long dirs );
-
- virtual void slotProcessedSize( TDEIO::Job *job, TDEIO::filesize_t bytes );
- virtual void slotProcessedFiles( TDEIO::Job *job, unsigned long files );
- virtual void slotProcessedDirs( TDEIO::Job *job, unsigned long dirs );
-
- virtual void slotSpeed( TDEIO::Job *job, unsigned long speed );
- virtual void slotPercent( TDEIO::Job *job, unsigned long percent );
- /**
- * Called to set an information message.
- * @param job the TDEIO::Job
- * @param msg the message to set
- */
- virtual void slotInfoMessage( TDEIO::Job *job, const TQString & msg );
-
- virtual void slotCopying( TDEIO::Job* job, const KURL& src, const KURL& dest );
- virtual void slotMoving( TDEIO::Job* job, const KURL& src, const KURL& dest );
- virtual void slotDeleting( TDEIO::Job* job, const KURL& url );
- /**
- * Called when the job is transferring.
- * @param job the TDEIO::Job
- * @param url the url to transfer
- * @since 3.1
- */
- void slotTransferring( TDEIO::Job* job, const KURL& url );
- virtual void slotCreatingDir( TDEIO::Job* job, const KURL& dir );
- /**
- * Called when the job is requesting a stat.
- * @param job the TDEIO::Job
- * @param dir the dir to stat
- * @since 3.1
- */
- virtual void slotStating( TDEIO::Job* job, const KURL& dir );
- /**
- * Called when the job is mounting.
- * @param job the TDEIO::Job
- * @param dev the device to mount
- * @param point the mount point
- */
- virtual void slotMounting( TDEIO::Job* job, const TQString & dev, const TQString & point );
- /**
- * Called when the job is unmounting.
- * @param job the TDEIO::Job
- * @param point the mount point
- */
- virtual void slotUnmounting( TDEIO::Job* job, const TQString & point );
- virtual void slotCanResume( TDEIO::Job* job, TDEIO::filesize_t from);
-
- /**
- * Called when the job is cleaned.
- * @since 3.1
- */
- void slotClean();
-
-protected:
- /// @since 3.1
- void init();
- void showTotals();
- void setDestVisible( bool visible );
- /// @since 3.1
- void checkDestination( const KURL& dest);
-
- KLineEdit* sourceEdit;
- KLineEdit* destEdit;
- TQLabel* progressLabel;
- TQLabel* destInvite;
- TQLabel* speedLabel;
- TQLabel* sizeLabel;
- TQLabel* resumeLabel;
-
- KProgress* m_pProgressBar;
-
- TDEIO::filesize_t m_iTotalSize;
- unsigned long m_iTotalFiles;
- unsigned long m_iTotalDirs;
-
- TDEIO::filesize_t m_iProcessedSize;
- unsigned long m_iProcessedDirs;
- unsigned long m_iProcessedFiles;
-
- enum ModeType { Copy, Move, Delete, Create, Done };
- ModeType mode;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class DefaultProgressPrivate;
- DefaultProgressPrivate* d;
-private slots:
- void slotKeepOpenToggled(bool);
- void slotOpenFile();
- void slotOpenLocation();
-};
-
-} /* namespace */
-
-#endif // __defaultprogress_h__
-
diff --git a/kio/kio/forwardingslavebase.cpp b/kio/kio/forwardingslavebase.cpp
deleted file mode 100644
index 53121986d..000000000
--- a/kio/kio/forwardingslavebase.cpp
+++ /dev/null
@@ -1,475 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2004 Kevin Ottens <ervin ipsquad net>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kdebug.h>
-#include <kio/job.h>
-#include <kmimetype.h>
-#include <kprotocolinfo.h>
-
-#include <tqapplication.h>
-#include <tqeventloop.h>
-
-#include "forwardingslavebase.h"
-
-namespace TDEIO
-{
-
-class ForwardingSlaveBasePrivate
-{
-};
-
-ForwardingSlaveBase::ForwardingSlaveBase(const TQCString &protocol,
- const TQCString &poolSocket,
- const TQCString &appSocket)
- : TQObject(), SlaveBase(protocol, poolSocket, appSocket)
-{
-}
-
-ForwardingSlaveBase::~ForwardingSlaveBase()
-{
-}
-
-bool ForwardingSlaveBase::internalRewriteURL(const KURL &url, KURL &newURL)
-{
- bool result = true;
-
- if ( url.protocol().ascii()==mProtocol )
- {
- result = rewriteURL(url, newURL);
- }
- else
- {
- newURL = url;
- }
-
- m_processedURL = newURL;
- m_requestedURL = url;
- return result;
-}
-
-void ForwardingSlaveBase::prepareUDSEntry(TDEIO::UDSEntry &entry,
- bool listing) const
-{
- kdDebug() << "ForwardingSlaveBase::prepareUDSEntry: listing=="
- << listing << endl;
-
- bool url_found = false;
- TQString name;
- KURL url;
-
- TDEIO::UDSEntry::iterator it = entry.begin();
- TDEIO::UDSEntry::iterator end = entry.end();
-
- for(; it!=end; ++it)
- {
- KURL new_url = m_requestedURL;
-
- switch( (*it).m_uds )
- {
- case TDEIO::UDS_NAME:
- name = (*it).m_str;
- kdDebug() << "Name = " << name << endl;
- break;
- case TDEIO::UDS_URL:
- url_found = true;
- url = (*it).m_str;
- if (listing)
- {
- new_url.addPath(url.fileName());
- }
- (*it).m_str = new_url.url();
- kdDebug() << "URL = " << url << endl;
- kdDebug() << "New URL = " << (*it).m_str << endl;
- break;
- }
- }
-
- if ( m_processedURL.isLocalFile() )
- {
- KURL new_url = m_processedURL;
- if (listing)
- {
- new_url.addPath( name );
- }
-
- TDEIO::UDSAtom atom;
- atom.m_uds = TDEIO::UDS_LOCAL_PATH;
- atom.m_long = 0;
- atom.m_str = new_url.path();
- entry.append(atom);
- }
-}
-
-void ForwardingSlaveBase::get(const KURL &url)
-{
- kdDebug() << "ForwardingSlaveBase::get: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- TDEIO::TransferJob *job = TDEIO::get(new_url, false, false);
- connectTransferJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::put(const KURL &url, int permissions,
- bool overwrite, bool resume )
-{
- kdDebug() << "ForwardingSlaveBase::put: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- TDEIO::TransferJob *job = TDEIO::put(new_url, permissions, overwrite,
- resume, false);
- connectTransferJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::stat(const KURL &url)
-{
- kdDebug() << "ForwardingSlaveBase::stat: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- TDEIO::SimpleJob *job = TDEIO::stat(new_url, false);
- connectSimpleJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::mimetype(const KURL &url)
-{
- kdDebug() << "ForwardingSlaveBase::mimetype: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- TDEIO::TransferJob *job = TDEIO::mimetype(new_url, false);
- connectTransferJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::listDir(const KURL &url)
-{
- kdDebug() << "ForwardingSlaveBase::listDir: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- TDEIO::ListJob *job = TDEIO::listDir(new_url, false);
- connectListJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::mkdir(const KURL &url, int permissions)
-{
- kdDebug() << "ForwardingSlaveBase::mkdir: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- TDEIO::SimpleJob *job = TDEIO::mkdir(new_url, permissions);
- connectSimpleJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::rename(const KURL &src, const KURL &dest,
- bool overwrite)
-{
- kdDebug() << "ForwardingSlaveBase::rename: " << src << ", " << dest << endl;
-
- KURL new_src, new_dest;
- if ( internalRewriteURL(src, new_src) && internalRewriteURL(dest, new_dest) )
- {
- TDEIO::Job *job = TDEIO::rename(new_src, new_dest, overwrite);
- connectJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::symlink(const TQString &target, const KURL &dest,
- bool overwrite)
-{
- kdDebug() << "ForwardingSlaveBase::symlink: " << target << ", " << dest << endl;
-
- KURL new_dest;
- if ( internalRewriteURL(dest, new_dest) )
- {
- TDEIO::SimpleJob *job = TDEIO::symlink(target, new_dest, overwrite, false);
- connectSimpleJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::chmod(const KURL &url, int permissions)
-{
- kdDebug() << "ForwardingSlaveBase::chmod: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- TDEIO::SimpleJob *job = TDEIO::chmod(new_url, permissions);
- connectSimpleJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::copy(const KURL &src, const KURL &dest,
- int permissions, bool overwrite)
-{
- kdDebug() << "ForwardingSlaveBase::copy: " << src << ", " << dest << endl;
-
- KURL new_src, new_dest;
- if ( internalRewriteURL(src, new_src) && internalRewriteURL(dest, new_dest) )
- {
- TDEIO::Job *job = TDEIO::file_copy(new_src, new_dest, permissions,
- overwrite, false);
- connectJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::del(const KURL &url, bool isfile)
-{
- kdDebug() << "ForwardingSlaveBase::del: " << url << endl;
-
- KURL new_url;
- if ( internalRewriteURL(url, new_url) )
- {
- if (isfile)
- {
- TDEIO::DeleteJob *job = TDEIO::del(new_url, false, false);
- connectJob(job);
- }
- else
- {
- TDEIO::SimpleJob *job = TDEIO::rmdir(new_url);
- connectSimpleJob(job);
- }
-
- tqApp->eventLoop()->enterLoop();
- }
-}
-
-void ForwardingSlaveBase::localURL(const KURL& remoteURL)
-{
- kdDebug() << "ForwardingSlaveBase::localURL: " << remoteURL << endl;
-
- KURL new_url;
- if ( internalRewriteURL(remoteURL, new_url) )
- {
- TDEIO::LocalURLJob *job = TDEIO::localURL(new_url);
- connectLocalURLJob(job);
-
- tqApp->eventLoop()->enterLoop();
- }
- else
- {
- // Let the slave base emit the required signals
- SlaveBase::localURL(remoteURL);
- }
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-void ForwardingSlaveBase::connectJob(TDEIO::Job *job)
-{
- // We will forward the warning message, no need to let the job
- // display it itself
- job->setInteractive(false);
-
- // Forward metadata (e.g. modification time for put())
- job->setMetaData( allMetaData() );
-#if 0 // debug code
- kdDebug() << k_funcinfo << "transferring metadata:" << endl;
- const MetaData md = allMetaData();
- for ( MetaData::const_iterator it = md.begin(); it != md.end(); ++it )
- kdDebug() << it.key() << " = " << it.data() << endl;
-#endif
-
- connect( job, TQT_SIGNAL( result(TDEIO::Job *) ),
- this, TQT_SLOT( slotResult(TDEIO::Job *) ) );
- connect( job, TQT_SIGNAL( warning(TDEIO::Job *, const TQString &) ),
- this, TQT_SLOT( slotWarning(TDEIO::Job *, const TQString &) ) );
- connect( job, TQT_SIGNAL( infoMessage(TDEIO::Job *, const TQString &) ),
- this, TQT_SLOT( slotInfoMessage(TDEIO::Job *, const TQString &) ) );
- connect( job, TQT_SIGNAL( totalSize(TDEIO::Job *, TDEIO::filesize_t) ),
- this, TQT_SLOT( slotTotalSize(TDEIO::Job *, TDEIO::filesize_t) ) );
- connect( job, TQT_SIGNAL( processedSize(TDEIO::Job *, TDEIO::filesize_t) ),
- this, TQT_SLOT( slotProcessedSize(TDEIO::Job *, TDEIO::filesize_t) ) );
- connect( job, TQT_SIGNAL( speed(TDEIO::Job *, unsigned long) ),
- this, TQT_SLOT( slotSpeed(TDEIO::Job *, unsigned long) ) );
-}
-
-void ForwardingSlaveBase::connectSimpleJob(TDEIO::SimpleJob *job)
-{
- connectJob(job);
- connect( job, TQT_SIGNAL( redirection(TDEIO::Job *, const KURL &) ),
- this, TQT_SLOT( slotRedirection(TDEIO::Job *, const KURL &) ) );
-}
-
-void ForwardingSlaveBase::connectListJob(TDEIO::ListJob *job)
-{
- connectSimpleJob(job);
- connect( job, TQT_SIGNAL( entries(TDEIO::Job *, const TDEIO::UDSEntryList &) ),
- this, TQT_SLOT( slotEntries(TDEIO::Job *, const TDEIO::UDSEntryList &) ) );
-}
-
-void ForwardingSlaveBase::connectTransferJob(TDEIO::TransferJob *job)
-{
- connectSimpleJob(job);
- connect( job, TQT_SIGNAL( data(TDEIO::Job *, const TQByteArray &) ),
- this, TQT_SLOT( slotData(TDEIO::Job *, const TQByteArray &) ) );
- connect( job, TQT_SIGNAL( dataReq(TDEIO::Job *, TQByteArray &) ),
- this, TQT_SLOT( slotDataReq(TDEIO::Job *, TQByteArray &) ) );
- connect( job, TQT_SIGNAL( mimetype(TDEIO::Job *, const TQString &) ),
- this, TQT_SLOT( slotMimetype(TDEIO::Job *, const TQString &) ) );
- connect( job, TQT_SIGNAL( canResume(TDEIO::Job *, TDEIO::filesize_t) ),
- this, TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t) ) );
-}
-
-void ForwardingSlaveBase::connectLocalURLJob(TDEIO::LocalURLJob *job)
-{
- connectJob(job);
- connect( job, TQT_SIGNAL( localURL(TDEIO::Job *, const KURL&, bool) ),
- this, TQT_SLOT( slotLocalURL(TDEIO::Job *, const KURL&, bool) ) );
-}
-
-//////////////////////////////////////////////////////////////////////////////
-
-void ForwardingSlaveBase::slotResult(TDEIO::Job *job)
-{
- if ( job->error() != 0)
- {
- error( job->error(), job->errorText() );
- }
- else
- {
- TDEIO::StatJob *stat_job = dynamic_cast<TDEIO::StatJob *>(job);
- if ( stat_job!=0L )
- {
- TDEIO::UDSEntry entry = stat_job->statResult();
- prepareUDSEntry(entry);
- statEntry( entry );
- }
- finished();
- }
-
- tqApp->eventLoop()->exitLoop();
-}
-
-void ForwardingSlaveBase::slotWarning(TDEIO::Job* /*job*/, const TQString &msg)
-{
- warning(msg);
-}
-
-void ForwardingSlaveBase::slotInfoMessage(TDEIO::Job* /*job*/, const TQString &msg)
-{
- infoMessage(msg);
-}
-
-void ForwardingSlaveBase::slotTotalSize(TDEIO::Job* /*job*/, TDEIO::filesize_t size)
-{
- totalSize(size);
-}
-
-void ForwardingSlaveBase::slotProcessedSize(TDEIO::Job* /*job*/, TDEIO::filesize_t size)
-{
- processedSize(size);
-}
-
-void ForwardingSlaveBase::slotSpeed(TDEIO::Job* /*job*/, unsigned long bytesPerSecond)
-{
- speed(bytesPerSecond);
-}
-
-void ForwardingSlaveBase::slotRedirection(TDEIO::Job *job, const KURL &url)
-{
- redirection(url);
-
- // We've been redirected stop everything.
- job->kill( true );
- finished();
-
- tqApp->eventLoop()->exitLoop();
-}
-
-void ForwardingSlaveBase::slotEntries(TDEIO::Job* /*job*/,
- const TDEIO::UDSEntryList &entries)
-{
- TDEIO::UDSEntryList final_entries = entries;
-
- TDEIO::UDSEntryList::iterator it = final_entries.begin();
- TDEIO::UDSEntryList::iterator end = final_entries.end();
-
- for(; it!=end; ++it)
- {
- prepareUDSEntry(*it, true);
- }
-
- listEntries( final_entries );
-}
-
-void ForwardingSlaveBase::slotData(TDEIO::Job* /*job*/, const TQByteArray &d)
-{
- data(d);
-}
-
-void ForwardingSlaveBase::slotDataReq(TDEIO::Job* /*job*/, TQByteArray &data)
-{
- dataReq();
- readData(data);
-}
-
-void ForwardingSlaveBase::slotMimetype (TDEIO::Job* /*job*/, const TQString &type)
-{
- mimeType(type);
-}
-
-void ForwardingSlaveBase::slotCanResume (TDEIO::Job* /*job*/, TDEIO::filesize_t offset)
-{
- canResume(offset);
-}
-
-void ForwardingSlaveBase::slotLocalURL(TDEIO::Job *, const KURL& url, bool)
-{
- SlaveBase::localURL(url);
-}
-
-}
-
-#include "forwardingslavebase.moc"
-
diff --git a/kio/kio/forwardingslavebase.h b/kio/kio/forwardingslavebase.h
deleted file mode 100644
index f765e38a6..000000000
--- a/kio/kio/forwardingslavebase.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2004 Kevin Ottens <ervin ipsquad net>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _FORWARDING_SLAVE_BASE_H_
-#define _FORWARDING_SLAVE_BASE_H_
-
-#include <kio/slavebase.h>
-#include <kio/jobclasses.h>
-
-#include <tqobject.h>
-
-namespace TDEIO
-{
-
-class ForwardingSlaveBasePrivate;
-
-/**
- * This class should be used as a base for ioslaves acting as a
- * forwarder to other ioslaves. It has been designed to support only
- * local filesystem like ioslaves.
- *
- * If the resulting ioslave should be a simple proxy, you only need
- * to implement the ForwardingSlaveBase::rewriteURL() method.
- *
- * For more advanced behavior, the classic ioslave methods should
- * be reimplemented, because their default behavior in this class
- * is to forward using the ForwardingSlaveBase::rewriteURL() method.
- *
- * A possible code snippet for an advanced stat() behavior would look
- * like this in the child class:
- *
- * \code
- * void ChildProtocol::stat(const KURL &url)
- * {
- * bool is_special = false;
- *
- * // Process the URL to see if it should have
- * // a special treatment
- *
- * if ( is_special )
- * {
- * // Handle the URL ourselves
- * TDEIO::UDSEntry entry;
- * // Fill entry with UDSAtom instances
- * statEntry(entry);
- * finished();
- * }
- * else
- * {
- * // Setup the ioslave internal state if
- * // required by ChildProtocol::rewriteURL()
- * ForwardingSlaveBase::stat(url);
- * }
- * }
- * \endcode
- *
- * Of course in this case, you surely need to reimplement listDir()
- * and get() accordingly.
- *
- * If you want view on directories to be correctly refreshed when
- * something changes on a forwarded URL, you'll need a companion kded
- * module to emit the KDirNotify Files*() DCOP signals.
- *
- * This class was initially used for media:/ ioslave. This ioslave code
- * and the MediaDirNotify class of its companion kded module can be a
- * good source of inspiration.
- *
- * @see ForwardingSlaveBase::rewriteURL()
- * @since 3.4
- * @author Kevin Ottens <ervin@ipsquad.net>
- */
-class TDEIO_EXPORT ForwardingSlaveBase : public TQObject, public SlaveBase
-{
-Q_OBJECT
-public:
- ForwardingSlaveBase(const TQCString &protocol,
- const TQCString &poolSocket,
- const TQCString &appSocket);
- virtual ~ForwardingSlaveBase();
-
- virtual void get(const KURL &url);
-
- virtual void put(const KURL &url, int permissions,
- bool overwrite, bool resume);
-
- virtual void stat(const KURL &url);
-
- virtual void mimetype(const KURL &url);
-
- virtual void listDir(const KURL &url);
-
- virtual void mkdir(const KURL &url, int permissions);
-
- virtual void rename(const KURL &src, const KURL &dest, bool overwrite);
-
- virtual void symlink(const TQString &target, const KURL &dest,
- bool overwrite);
-
- virtual void chmod(const KURL &url, int permissions);
-
- virtual void copy(const KURL &src, const KURL &dest,
- int permissions, bool overwrite);
-
- virtual void del(const KURL &url, bool isfile);
-
- virtual void localURL(const KURL& remoteURL);
-
-protected:
- /**
- * Rewrite an url to it's forwarded counterpart. It should return
- * true if everything was ok, and false otherwise.
- *
- * If a problem is detected it's up to this method to trigger error()
- * before returning. Returning false silently cancel the current
- * slave operation.
- *
- * @param url The URL as given during the slave call
- * @param newURL The new URL to forward the slave call to
- * @return true if the given url could be correctly rewritten
- */
- virtual bool rewriteURL(const KURL &url, KURL &newURL)=0;
-
- /**
- * Allow to modify a UDSEntry before it's sent to the ioslave enpoint.
- * This is the default implementation working in most case, but sometimes
- * you could make use of more forwarding black magic (for example
- * dynamically transform any desktop file into a fake directory...)
- *
- * @param entry the UDSEntry to post-process
- * @param listing indicate if this entry it created during a listDir
- * operation
- */
- virtual void prepareUDSEntry(TDEIO::UDSEntry &entry,
- bool listing=false) const;
-
- /**
- * Return the URL being processed by the ioslave
- * Only access it inside prepareUDSEntry()
- */
- KURL processedURL() const { return m_processedURL; }
-
- /**
- * Return the URL asked to the ioslave
- * Only access it inside prepareUDSEntry()
- */
- KURL requestedURL() const { return m_requestedURL; }
-
-private:
- KURL m_processedURL;
- KURL m_requestedURL;
- ForwardingSlaveBasePrivate *d;
-
- bool internalRewriteURL(const KURL &url, KURL &newURL);
-
- void connectJob(Job *job);
- void connectSimpleJob(SimpleJob *job);
- void connectListJob(ListJob *job);
- void connectTransferJob(TransferJob *job);
- void connectLocalURLJob(LocalURLJob *job);
-
-private slots:
- // TDEIO::Job
- void slotResult(TDEIO::Job *job);
- void slotWarning(TDEIO::Job *job, const TQString &msg);
- void slotInfoMessage(TDEIO::Job *job, const TQString &msg);
- void slotTotalSize(TDEIO::Job *job, TDEIO::filesize_t size);
- void slotProcessedSize(TDEIO::Job *job, TDEIO::filesize_t size);
- void slotSpeed(TDEIO::Job *job, unsigned long bytesPerSecond);
-
- // TDEIO::SimpleJob subclasses
- void slotRedirection(TDEIO::Job *job, const KURL &url);
-
- // TDEIO::ListJob
- void slotEntries(TDEIO::Job *job, const TDEIO::UDSEntryList &entries);
-
- // TDEIO::TransferJob
- void slotData(TDEIO::Job *job, const TQByteArray &data);
- void slotDataReq(TDEIO::Job *job, TQByteArray &data);
- void slotMimetype (TDEIO::Job *job, const TQString &type);
- void slotCanResume (TDEIO::Job *job, TDEIO::filesize_t offset);
-
- // TDEIO::LocalURLJob
- void slotLocalURL(TDEIO::Job *, const KURL&, bool);
-};
-
-}
-
-#endif
diff --git a/kio/kio/global.cpp b/kio/kio/global.cpp
deleted file mode 100644
index 3a7cadb8f..000000000
--- a/kio/kio/global.cpp
+++ /dev/null
@@ -1,2009 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <config.h>
-
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/uio.h>
-
-#include <assert.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <stdio.h>
-
-#include "kio/global.h"
-#include "kio/job.h"
-
-#include <kdebug.h>
-#include <klocale.h>
-#include <kglobal.h>
-#include <kprotocolmanager.h>
-#include <kde_file.h>
-
-#ifdef HAVE_VOLMGT
-#include <volmgt.h>
-#endif
-
-TDEIO_EXPORT TQString TDEIO::convertSizeWithBytes( TDEIO::filesize_t size )
-{
- if ( size >= 1024 )
- return convertSize( size ) + " (" + i18n( "%1 B" ).arg( TDEGlobal::locale()->formatNumber(size, 0) ) + ")";
- else
- return convertSize( size );
-}
-
-TDEIO_EXPORT TQString TDEIO::convertSize( TDEIO::filesize_t size )
-{
- double fsize = size;
- TQString s;
- // Giga-byte
- if ( size >= 1073741824 )
- {
- fsize /= 1073741824.0;
- if ( fsize > 1024 ) // Tera-byte
- s = i18n( "%1 TB" ).arg( TDEGlobal::locale()->formatNumber(fsize / 1024.0, 1));
- else
- s = i18n( "%1 GB" ).arg( TDEGlobal::locale()->formatNumber(fsize, 1));
- }
- // Mega-byte
- else if ( size >= 1048576 )
- {
- fsize /= 1048576.0;
- s = i18n( "%1 MB" ).arg( TDEGlobal::locale()->formatNumber(fsize, 1));
- }
- // Kilo-byte
- else if ( size >= 1024 )
- {
- fsize /= 1024.0;
- s = i18n( "%1 KB" ).arg( TDEGlobal::locale()->formatNumber(fsize, 1));
- }
- // Just byte
- else if ( size > 0 )
- {
- s = i18n( "%1 B" ).arg( TDEGlobal::locale()->formatNumber(fsize, 0));
- }
- // Nothing
- else
- {
- s = i18n( "0 B" );
- }
- return s;
-}
-
-TDEIO_EXPORT TQString TDEIO::convertSizeFromKB( TDEIO::filesize_t kbSize )
-{
- return convertSize(kbSize * 1024);
-}
-
-TDEIO_EXPORT TQString TDEIO::number( TDEIO::filesize_t size )
-{
- char charbuf[256];
- sprintf(charbuf, "%lld", size);
- return TQString::fromLatin1(charbuf);
-}
-
-TDEIO_EXPORT unsigned int TDEIO::calculateRemainingSeconds( TDEIO::filesize_t totalSize,
- TDEIO::filesize_t processedSize, TDEIO::filesize_t speed )
-{
- if ( (speed != 0) && (totalSize != 0) )
- return ( totalSize - processedSize ) / speed;
- else
- return 0;
-}
-
-TDEIO_EXPORT TQString TDEIO::convertSeconds( unsigned int seconds )
-{
- unsigned int days = seconds / 86400;
- unsigned int hours = (seconds - (days * 86400)) / 3600;
- unsigned int mins = (seconds - (days * 86400) - (hours * 3600)) / 60;
- seconds = (seconds - (days * 86400) - (hours * 3600) - (mins * 60));
-
- const TQTime time(hours, mins, seconds);
- const TQString timeStr( TDEGlobal::locale()->formatTime(time, true /*with seconds*/, true /*duration*/) );
- if ( days > 0 )
- return i18n("1 day %1", "%n days %1", days).arg(timeStr);
- else
- return timeStr;
-}
-
-TDEIO_EXPORT TQTime TDEIO::calculateRemaining( TDEIO::filesize_t totalSize, TDEIO::filesize_t processedSize, TDEIO::filesize_t speed )
-{
- TQTime remainingTime;
-
- if ( speed != 0 ) {
- TDEIO::filesize_t secs;
- if ( totalSize == 0 ) {
- secs = 0;
- } else {
- secs = ( totalSize - processedSize ) / speed;
- }
- if (secs >= (24*60*60)) // Limit to 23:59:59
- secs = (24*60*60)-1;
- int hr = secs / ( 60 * 60 );
- int mn = ( secs - hr * 60 * 60 ) / 60;
- int sc = ( secs - hr * 60 * 60 - mn * 60 );
-
- remainingTime.setHMS( hr, mn, sc );
- }
-
- return remainingTime;
-}
-
-TDEIO_EXPORT TQString TDEIO::itemsSummaryString(uint items, uint files, uint dirs, TDEIO::filesize_t size, bool showSize)
-{
- TQString text = items == 0 ? i18n( "No Items" ) : i18n( "One Item", "%n Items", items );
- text += " - ";
- text += files == 0 ? i18n( "No Files" ) : i18n( "One File", "%n Files", files );
- if ( showSize && files > 0 )
- {
- text += " ";
- text += i18n("(%1 Total)").arg(TDEIO::convertSize( size ) );
- }
- text += " - ";
- text += dirs == 0 ? i18n( "No Folders" ) : i18n("One Folder", "%n Folders", dirs);
- return text;
-}
-
-TDEIO_EXPORT TQString TDEIO::encodeFileName( const TQString & _str )
-{
- TQString str( _str );
-
- int i = 0;
- while ( ( i = str.find( "%", i ) ) != -1 )
- {
- str.replace( i, 1, "%%");
- i += 2;
- }
- while ( ( i = str.find( "/" ) ) != -1 )
- str.replace( i, 1, "%2f");
- return str;
-}
-
-TDEIO_EXPORT TQString TDEIO::decodeFileName( const TQString & _str )
-{
- TQString str;
-
- unsigned int i = 0;
- for ( ; i < _str.length() ; ++i )
- {
- if ( _str[i]=='%' )
- {
- if ( _str[i+1]=='%' ) // %% -> %
- {
- str.append('%');
- ++i;
- }
- else if ( _str[i+1]=='2' && (i+2<_str.length()) && _str[i+2].lower()=='f' ) // %2f -> /
- {
- str.append('/');
- i += 2;
- }
- else
- str.append('%');
- } else
- str.append(_str[i]);
- }
-
- return str;
-}
-
-TDEIO_EXPORT TQString TDEIO::Job::errorString() const
-{
- return TDEIO::buildErrorString(m_error, m_errorText);
-}
-
-TDEIO_EXPORT TQString TDEIO::buildErrorString(int errorCode, const TQString &errorText)
-{
- TQString result;
-
- switch( errorCode )
- {
- case TDEIO::ERR_CANNOT_OPEN_FOR_READING:
- result = i18n( "Could not read %1." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_OPEN_FOR_WRITING:
- result = i18n( "Could not write to %1." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_LAUNCH_PROCESS:
- result = i18n( "Could not start process %1." ).arg( errorText );
- break;
- case TDEIO::ERR_INTERNAL:
- result = i18n( "Internal Error\nPlease send a full bug report at http://bugs.kde.org\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_MALFORMED_URL:
- result = i18n( "Malformed URL %1." ).arg( errorText );
- break;
- case TDEIO::ERR_UNSUPPORTED_PROTOCOL:
- result = i18n( "The protocol %1 is not supported." ).arg( errorText );
- break;
- case TDEIO::ERR_NO_SOURCE_PROTOCOL:
- result = i18n( "The protocol %1 is only a filter protocol.").arg( errorText );
- break;
- case TDEIO::ERR_UNSUPPORTED_ACTION:
- result = errorText;
-// result = i18n( "Unsupported action %1" ).arg( errorText );
- break;
- case TDEIO::ERR_IS_DIRECTORY:
- result = i18n( "%1 is a folder, but a file was expected." ).arg( errorText );
- break;
- case TDEIO::ERR_IS_FILE:
- result = i18n( "%1 is a file, but a folder was expected." ).arg( errorText );
- break;
- case TDEIO::ERR_DOES_NOT_EXIST:
- result = i18n( "The file or folder %1 does not exist." ).arg( errorText );
- break;
- case TDEIO::ERR_FILE_ALREADY_EXIST:
- result = i18n( "A file named %1 already exists." ).arg( errorText );
- break;
- case TDEIO::ERR_DIR_ALREADY_EXIST:
- result = i18n( "A folder named %1 already exists." ).arg( errorText );
- break;
- case TDEIO::ERR_UNKNOWN_HOST:
- result = errorText.isEmpty() ? i18n( "No hostname specified." ) : i18n( "Unknown host %1" ).arg( errorText );
- break;
- case TDEIO::ERR_ACCESS_DENIED:
- result = i18n( "Access denied to %1." ).arg( errorText );
- break;
- case TDEIO::ERR_WRITE_ACCESS_DENIED:
- result = i18n( "Access denied.\nCould not write to %1." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_ENTER_DIRECTORY:
- result = i18n( "Could not enter folder %1." ).arg( errorText );
- break;
- case TDEIO::ERR_PROTOCOL_IS_NOT_A_FILESYSTEM:
- result = i18n( "The protocol %1 does not implement a folder service." ).arg( errorText );
- break;
- case TDEIO::ERR_CYCLIC_LINK:
- result = i18n( "Found a cyclic link in %1." ).arg( errorText );
- break;
- case TDEIO::ERR_USER_CANCELED:
- // Do nothing in this case. The user doesn't need to be told what he just did.
- break;
- case TDEIO::ERR_CYCLIC_COPY:
- result = i18n( "Found a cyclic link while copying %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_CREATE_SOCKET:
- result = i18n( "Could not create socket for accessing %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_CONNECT:
- result = i18n( "Could not connect to host %1." ).arg( errorText.isEmpty() ? TQString::fromLatin1("localhost") : errorText );
- break;
- case TDEIO::ERR_CONNECTION_BROKEN:
- result = i18n( "Connection to host %1 is broken." ).arg( errorText );
- break;
- case TDEIO::ERR_NOT_FILTER_PROTOCOL:
- result = i18n( "The protocol %1 is not a filter protocol." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_MOUNT:
- result = i18n( "Could not mount device.\nThe reported error was:\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_UNMOUNT:
- result = i18n( "Could not unmount device.\nThe reported error was:\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_READ:
- result = i18n( "Could not read file %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_WRITE:
- result = i18n( "Could not write to file %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_BIND:
- result = i18n( "Could not bind %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_LISTEN:
- result = i18n( "Could not listen %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_ACCEPT:
- result = i18n( "Could not accept %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_LOGIN:
- result = errorText;
- break;
- case TDEIO::ERR_COULD_NOT_STAT:
- result = i18n( "Could not access %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_CLOSEDIR:
- result = i18n( "Could not terminate listing %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_MKDIR:
- result = i18n( "Could not make folder %1." ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_RMDIR:
- result = i18n( "Could not remove folder %1." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_RESUME:
- result = i18n( "Could not resume file %1." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_RENAME:
- result = i18n( "Could not rename file %1." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_CHMOD:
- result = i18n( "Could not change permissions for %1." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_DELETE:
- result = i18n( "Could not delete file %1." ).arg( errorText );
- break;
- case TDEIO::ERR_SLAVE_DIED:
- result = i18n( "The process for the %1 protocol died unexpectedly." ).arg( errorText );
- break;
- case TDEIO::ERR_OUT_OF_MEMORY:
- result = i18n( "Error. Out of memory.\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_UNKNOWN_PROXY_HOST:
- result = i18n( "Unknown proxy host\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_COULD_NOT_AUTHENTICATE:
- result = i18n( "Authorization failed, %1 authentication not supported" ).arg( errorText );
- break;
- case TDEIO::ERR_ABORTED:
- result = i18n( "User canceled action\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_INTERNAL_SERVER:
- result = i18n( "Internal error in server\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_SERVER_TIMEOUT:
- result = i18n( "Timeout on server\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_UNKNOWN:
- result = i18n( "Unknown error\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_UNKNOWN_INTERRUPT:
- result = i18n( "Unknown interrupt\n%1" ).arg( errorText );
- break;
-/*
- case TDEIO::ERR_CHECKSUM_MISMATCH:
- if (errorText)
- result = i18n( "Warning: MD5 Checksum for %1 does not match checksum returned from server" ).arg(errorText);
- else
- result = i18n( "Warning: MD5 Checksum for %1 does not match checksum returned from server" ).arg("document");
- break;
-*/
- case TDEIO::ERR_CANNOT_DELETE_ORIGINAL:
- result = i18n( "Could not delete original file %1.\nPlease check permissions." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_DELETE_PARTIAL:
- result = i18n( "Could not delete partial file %1.\nPlease check permissions." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_RENAME_ORIGINAL:
- result = i18n( "Could not rename original file %1.\nPlease check permissions." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_RENAME_PARTIAL:
- result = i18n( "Could not rename partial file %1.\nPlease check permissions." ).arg( errorText );
- break;
- case TDEIO::ERR_CANNOT_SYMLINK:
- result = i18n( "Could not create symlink %1.\nPlease check permissions." ).arg( errorText );
- break;
- case TDEIO::ERR_NO_CONTENT:
- result = errorText;
- break;
- case TDEIO::ERR_DISK_FULL:
- result = i18n( "Could not write file %1.\nDisk full." ).arg( errorText );
- break;
- case TDEIO::ERR_IDENTICAL_FILES:
- result = i18n( "The source and destination are the same file.\n%1" ).arg( errorText );
- break;
- case TDEIO::ERR_SLAVE_DEFINED:
- result = errorText;
- break;
- case TDEIO::ERR_UPGRADE_REQUIRED:
- result = i18n( "%1 is required by the server, but is not available." ).arg(errorText);
- break;
- case TDEIO::ERR_POST_DENIED:
- result = i18n( "Access to restricted port in POST denied.");
- break;
- case TDEIO::ERR_OFFLINE_MODE:
- result = i18n( "Could not access %1.\nOffline mode active.").arg( errorText );
- break;
- default:
- result = i18n( "Unknown error code %1\n%2\nPlease send a full bug report at http://bugs.kde.org." ).arg( errorCode ).arg( errorText );
- break;
- }
-
- return result;
-}
-
-TDEIO_EXPORT TQString TDEIO::unsupportedActionErrorString(const TQString &protocol, int cmd) {
- switch (cmd) {
- case CMD_CONNECT:
- return i18n("Opening connections is not supported with the protocol %1." ).arg(protocol);
- case CMD_DISCONNECT:
- return i18n("Closing connections is not supported with the protocol %1." ).arg(protocol);
- case CMD_STAT:
- return i18n("Accessing files is not supported with the protocol %1.").arg(protocol);
- case CMD_PUT:
- return i18n("Writing to %1 is not supported.").arg(protocol);
- case CMD_SPECIAL:
- return i18n("There are no special actions available for protocol %1.").arg(protocol);
- case CMD_LISTDIR:
- return i18n("Listing folders is not supported for protocol %1.").arg(protocol);
- case CMD_GET:
- return i18n("Retrieving data from %1 is not supported.").arg(protocol);
- case CMD_MIMETYPE:
- return i18n("Retrieving mime type information from %1 is not supported.").arg(protocol);
- case CMD_RENAME:
- return i18n("Renaming or moving files within %1 is not supported.").arg(protocol);
- case CMD_SYMLINK:
- return i18n("Creating symlinks is not supported with protocol %1.").arg(protocol);
- case CMD_COPY:
- return i18n("Copying files within %1 is not supported.").arg(protocol);
- case CMD_DEL:
- return i18n("Deleting files from %1 is not supported.").arg(protocol);
- case CMD_MKDIR:
- return i18n("Creating folders is not supported with protocol %1.").arg(protocol);
- case CMD_CHMOD:
- return i18n("Changing the attributes of files is not supported with protocol %1.").arg(protocol);
- case CMD_SUBURL:
- return i18n("Using sub-URLs with %1 is not supported.").arg(protocol);
- case CMD_MULTI_GET:
- return i18n("Multiple get is not supported with protocol %1.").arg(protocol);
- default:
- return i18n("Protocol %1 does not support action %2.").arg(protocol).arg(cmd);
- }/*end switch*/
-}
-
-TDEIO_EXPORT TQStringList TDEIO::Job::detailedErrorStrings( const KURL *reqUrl /*= 0L*/,
- int method /*= -1*/ ) const
-{
- TQString errorName, techName, description, ret2;
- TQStringList causes, solutions, ret;
-
- TQByteArray raw = rawErrorDetail( m_error, m_errorText, reqUrl, method );
- TQDataStream stream(raw, IO_ReadOnly);
-
- stream >> errorName >> techName >> description >> causes >> solutions;
-
- TQString url, protocol, datetime;
- if ( reqUrl ) {
- url = reqUrl->htmlURL();
- protocol = reqUrl->protocol();
- } else {
- url = i18n( "(unknown)" );
- }
-
- datetime = TDEGlobal::locale()->formatDateTime( TQDateTime::currentDateTime(),
- false );
-
- ret << errorName;
- ret << TQString::fromLatin1( "<qt><p><b>" ) + errorName +
- TQString::fromLatin1( "</b></p><p>" ) + description +
- TQString::fromLatin1( "</p>" );
- ret2 = TQString::fromLatin1( "<qt><p>" );
- if ( !techName.isEmpty() )
- ret2 += i18n( "<b>Technical reason</b>: " ) + techName + TQString::fromLatin1( "</p>" );
- ret2 += i18n( "</p><p><b>Details of the request</b>:" );
- ret2 += i18n( "</p><ul><li>URL: %1</li>" ).arg( url );
- if ( !protocol.isEmpty() ) {
- ret2 += i18n( "<li>Protocol: %1</li>" ).arg( protocol );
- }
- ret2 += i18n( "<li>Date and time: %1</li>" ).arg( datetime );
- ret2 += i18n( "<li>Additional information: %1</li></ul>" ).arg( m_errorText );
- if ( !causes.isEmpty() ) {
- ret2 += i18n( "<p><b>Possible causes</b>:</p><ul><li>" );
- ret2 += causes.join( "</li><li>" );
- ret2 += TQString::fromLatin1( "</li></ul>" );
- }
- if ( !solutions.isEmpty() ) {
- ret2 += i18n( "<p><b>Possible solutions</b>:</p><ul><li>" );
- ret2 += solutions.join( "</li><li>" );
- ret2 += TQString::fromLatin1( "</li></ul>" );
- }
- ret << ret2;
- return ret;
-}
-
-TDEIO_EXPORT TQByteArray TDEIO::rawErrorDetail(int errorCode, const TQString &errorText,
- const KURL *reqUrl /*= 0L*/, int /*method = -1*/ )
-{
- TQString url, host, protocol, datetime, domain, path, dir, filename;
- bool isSlaveNetwork = false;
- if ( reqUrl ) {
- url = reqUrl->prettyURL();
- host = reqUrl->host();
- protocol = reqUrl->protocol();
-
- if ( host.left(4) == "www." )
- domain = host.mid(4);
- else
- domain = host;
-
- path = reqUrl->path(1);
- filename = reqUrl->fileName();
- dir = path + filename;
-
- // detect if protocol is a network protocol...
- // add your hacks here...
- if ( protocol == "http" ||
- protocol == "https" ||
- protocol == "ftp" ||
- protocol == "sftp" ||
- protocol == "webdav" ||
- protocol == "webdavs" ||
- protocol == "finger" ||
- protocol == "fish" ||
- protocol == "gopher" ||
- protocol == "imap" ||
- protocol == "imaps" ||
- protocol == "lan" ||
- protocol == "ldap" ||
- protocol == "mailto" ||
- protocol == "news" ||
- protocol == "nntp" ||
- protocol == "pop3" ||
- protocol == "pop3s" ||
- protocol == "smtp" ||
- protocol == "smtps" ||
- protocol == "telnet"
- ) {
- isSlaveNetwork = false;
- }
- } else {
- // assume that the errorText has the location we are interested in
- url = host = domain = path = filename = dir = errorText;
- protocol = i18n( "(unknown)" );
- }
-
- datetime = TDEGlobal::locale()->formatDateTime( TQDateTime::currentDateTime(),
- false );
-
- TQString errorName, techName, description;
- TQStringList causes, solutions;
-
- // c == cause, s == solution
- TQString sSysadmin = i18n( "Contact your appropriate computer support system, "
- "whether the system administrator, or technical support group for further "
- "assistance." );
- TQString sServeradmin = i18n( "Contact the administrator of the server "
- "for further assistance." );
- // FIXME active link to permissions dialog
- TQString sAccess = i18n( "Check your access permissions on this resource." );
- TQString cAccess = i18n( "Your access permissions may be inadequate to "
- "perform the requested operation on this resource." );
- TQString cLocked = i18n( "The file may be in use (and thus locked) by "
- "another user or application." );
- TQString sQuerylock = i18n( "Check to make sure that no other "
- "application or user is using the file or has locked the file." );
- TQString cHardware = i18n( "Although unlikely, a hardware error may have "
- "occurred." );
- TQString cBug = i18n( "You may have encountered a bug in the program." );
- TQString cBuglikely = i18n( "This is most likely to be caused by a bug in the "
- "program. Please consider submitting a full bug report as detailed below." );
- TQString sUpdate = i18n( "Update your software to the latest version. "
- "Your distribution should provide tools to update your software." );
- TQString sBugreport = i18n( "When all else fails, please consider helping the "
- "TDE team or the third party maintainer of this software by submitting a "
- "high quality bug report. If the software is provided by a third party, "
- "please contact them directly. Otherwise, first look to see if "
- "the same bug has been submitted by someone else by searching at the "
- "<a href=\"http://bugs.pearsoncomputing.net//\">TDE bug reporting website</a>. If not, take "
- "note of the details given above, and include them in your bug report, along "
- "with as many other details as you think might help." );
- TQString cNetwork = i18n( "There may have been a problem with your network "
- "connection." );
- // FIXME netconf kcontrol link
- TQString cNetconf = i18n( "There may have been a problem with your network "
- "configuration. If you have been accessing the Internet with no problems "
- "recently, this is unlikely." );
- TQString cNetpath = i18n( "There may have been a problem at some point along "
- "the network path between the server and this computer." );
- TQString sTryagain = i18n( "Try again, either now or at a later time." );
- TQString cProtocol = i18n( "A protocol error or incompatibility may have occurred." );
- TQString sExists = i18n( "Ensure that the resource exists, and try again." );
- TQString cExists = i18n( "The specified resource may not exist." );
- TQString cTypo = i18n( "You may have incorrectly typed the location." );
- TQString sTypo = i18n( "Double-check that you have entered the correct location "
- "and try again." );
- TQString sNetwork = i18n( "Check your network connection status." );
-
- switch( errorCode ) {
- case TDEIO::ERR_CANNOT_OPEN_FOR_READING:
- errorName = i18n( "Cannot Open Resource For Reading" );
- description = i18n( "This means that the contents of the requested file "
- "or folder <strong>%1</strong> could not be retrieved, as read "
- "access could not be obtained." ).arg( dir );
- causes << i18n( "You may not have permissions to read the file or open "
- "the folder.") << cLocked << cHardware;
- solutions << sAccess << sQuerylock << sSysadmin;
- break;
-
- case TDEIO::ERR_CANNOT_OPEN_FOR_WRITING:
- errorName = i18n( "Cannot Open Resource For Writing" );
- description = i18n( "This means that the file, <strong>%1</strong>, could "
- "not be written to as requested, because access with permission to "
- "write could not be obtained." ).arg( filename );
- causes << cAccess << cLocked << cHardware;
- solutions << sAccess << sQuerylock << sSysadmin;
- break;
-
- case TDEIO::ERR_CANNOT_LAUNCH_PROCESS:
- errorName = i18n( "Cannot Initiate the %1 Protocol" ).arg( protocol );
- techName = i18n( "Unable to Launch Process" );
- description = i18n( "The program on your computer which provides access "
- "to the <strong>%1</strong> protocol could not be started. This is "
- "usually due to technical reasons." ).arg( protocol );
- causes << i18n( "The program which provides compatibility with this "
- "protocol may not have been updated with your last update of TDE. "
- "This can cause the program to be incompatible with the current version "
- "and thus not start." ) << cBug;
- solutions << sUpdate << sSysadmin;
- break;
-
- case TDEIO::ERR_INTERNAL:
- errorName = i18n( "Internal Error" );
- description = i18n( "The program on your computer which provides access "
- "to the <strong>%1</strong> protocol has reported an internal error." )
- .arg( protocol );
- causes << cBuglikely;
- solutions << sUpdate << sBugreport;
- break;
-
- case TDEIO::ERR_MALFORMED_URL:
- errorName = i18n( "Improperly Formatted URL" );
- description = i18n( "The <strong>U</strong>niform <strong>R</strong>esource "
- "<strong>L</strong>ocator (URL) that you entered was not properly "
- "formatted. The format of a URL is generally as follows:"
- "<blockquote><strong>protocol://user:password@www.example.org:port/folder/"
- "filename.extension?query=value</strong></blockquote>" );
- solutions << sTypo;
- break;
-
- case TDEIO::ERR_UNSUPPORTED_PROTOCOL:
- errorName = i18n( "Unsupported Protocol %1" ).arg( protocol );
- description = i18n( "The protocol <strong>%1</strong> is not supported "
- "by the TDE programs currently installed on this computer." )
- .arg( protocol );
- causes << i18n( "The requested protocol may not be supported." )
- << i18n( "The versions of the %1 protocol supported by this computer and "
- "the server may be incompatible." ).arg( protocol );
- solutions << i18n( "You may perform a search on the Internet for a TDE "
- "program (called a kioslave or ioslave) which supports this protocol. "
- "Places to search include <a href=\"http://kde-apps.org/\">"
- "http://kde-apps.org/</a> and <a href=\"http://freshmeat.net/\">"
- "http://freshmeat.net/</a>." )
- << sUpdate << sSysadmin;
- break;
-
- case TDEIO::ERR_NO_SOURCE_PROTOCOL:
- errorName = i18n( "URL Does Not Refer to a Resource." );
- techName = i18n( "Protocol is a Filter Protocol" );
- description = i18n( "The <strong>U</strong>niform <strong>R</strong>esource "
- "<strong>L</strong>ocator (URL) that you entered did not refer to a "
- "specific resource." );
- causes << i18n( "TDE is able to communicate through a protocol within a "
- "protocol; the protocol specified is only for use in such situations, "
- "however this is not one of these situations. This is a rare event, and "
- "is likely to indicate a programming error." );
- solutions << sTypo;
- break;
-
- case TDEIO::ERR_UNSUPPORTED_ACTION:
- errorName = i18n( "Unsupported Action: %1" ).arg( errorText );
- description = i18n( "The requested action is not supported by the TDE "
- "program which is implementing the <strong>%1</strong> protocol." )
- .arg( protocol );
- causes << i18n( "This error is very much dependent on the TDE program. The "
- "additional information should give you more information than is available "
- "to the TDE input/output architecture." );
- solutions << i18n( "Attempt to find another way to accomplish the same "
- "outcome." );
- break;
-
- case TDEIO::ERR_IS_DIRECTORY:
- errorName = i18n( "File Expected" );
- description = i18n( "The request expected a file, however the "
- "folder <strong>%1</strong> was found instead." ).arg( dir );
- causes << i18n( "This may be an error on the server side." ) << cBug;
- solutions << sUpdate << sSysadmin;
- break;
-
- case TDEIO::ERR_IS_FILE:
- errorName = i18n( "Folder Expected" );
- description = i18n( "The request expected a folder, however "
- "the file <strong>%1</strong> was found instead." ).arg( filename );
- causes << cBug;
- solutions << sUpdate << sSysadmin;
- break;
-
- case TDEIO::ERR_DOES_NOT_EXIST:
- errorName = i18n( "File or Folder Does Not Exist" );
- description = i18n( "The specified file or folder <strong>%1</strong> "
- "does not exist." ).arg( dir );
- causes << cBug;
- solutions << sUpdate << sSysadmin;
- break;
-
- case TDEIO::ERR_FILE_ALREADY_EXIST:
- errorName = i18n( "File Already Exists" );
- description = i18n( "The requested file could not be created because a "
- "file with the same name already exists." );
- solutions << i18n ( "Try moving the current file out of the way first, "
- "and then try again." )
- << i18n ( "Delete the current file and try again." )
- << i18n( "Choose an alternate filename for the new file." );
- break;
-
- case TDEIO::ERR_DIR_ALREADY_EXIST:
- errorName = i18n( "Folder Already Exists" );
- description = i18n( "The requested folder could not be created because "
- "a folder with the same name already exists." );
- solutions << i18n( "Try moving the current folder out of the way first, "
- "and then try again." )
- << i18n( "Delete the current folder and try again." )
- << i18n( "Choose an alternate name for the new folder." );
- break;
-
- case TDEIO::ERR_UNKNOWN_HOST:
- errorName = i18n( "Unknown Host" );
- description = i18n( "An unknown host error indicates that the server with "
- "the requested name, <strong>%1</strong>, could not be "
- "located on the Internet." ).arg( host );
- causes << i18n( "The name that you typed, %1, may not exist: it may be "
- "incorrectly typed." ).arg( host )
- << cNetwork << cNetconf;
- solutions << sNetwork << sSysadmin;
- break;
-
- case TDEIO::ERR_ACCESS_DENIED:
- errorName = i18n( "Access Denied" );
- description = i18n( "Access was denied to the specified resource, "
- "<strong>%1</strong>." ).arg( url );
- causes << i18n( "You may have supplied incorrect authentication details or "
- "none at all." )
- << i18n( "Your account may not have permission to access the "
- "specified resource." );
- solutions << i18n( "Retry the request and ensure your authentication details "
- "are entered correctly." ) << sSysadmin;
- if ( !isSlaveNetwork ) solutions << sServeradmin;
- break;
-
- case TDEIO::ERR_WRITE_ACCESS_DENIED:
- errorName = i18n( "Write Access Denied" );
- description = i18n( "This means that an attempt to write to the file "
- "<strong>%1</strong> was rejected." ).arg( filename );
- causes << cAccess << cLocked << cHardware;
- solutions << sAccess << sQuerylock << sSysadmin;
- break;
-
- case TDEIO::ERR_CANNOT_ENTER_DIRECTORY:
- errorName = i18n( "Unable to Enter Folder" );
- description = i18n( "This means that an attempt to enter (in other words, "
- "to open) the requested folder <strong>%1</strong> was rejected." )
- .arg( dir );
- causes << cAccess << cLocked;
- solutions << sAccess << sQuerylock << sSysadmin;
- break;
-
- case TDEIO::ERR_PROTOCOL_IS_NOT_A_FILESYSTEM:
- errorName = i18n( "Folder Listing Unavailable" );
- techName = i18n( "Protocol %1 is not a Filesystem" ).arg( protocol );
- description = i18n( "This means that a request was made which requires "
- "determining the contents of the folder, and the TDE program supporting "
- "this protocol is unable to do so." );
- causes << cBug;
- solutions << sUpdate << sBugreport;
- break;
-
- case TDEIO::ERR_CYCLIC_LINK:
- errorName = i18n( "Cyclic Link Detected" );
- description = i18n( "UNIX environments are commonly able to link a file or "
- "folder to a separate name and/or location. TDE detected a link or "
- "series of links that results in an infinite loop - i.e. the file was "
- "(perhaps in a roundabout way) linked to itself." );
- solutions << i18n( "Delete one part of the loop in order that it does not "
- "cause an infinite loop, and try again." ) << sSysadmin;
- break;
-
- case TDEIO::ERR_USER_CANCELED:
- // Do nothing in this case. The user doesn't need to be told what he just did.
- // rodda: However, if we have been called, an application is about to display
- // this information anyway. If we don't return sensible information, the
- // user sees a blank dialog (I have seen this myself)
- errorName = i18n( "Request Aborted By User" );
- description = i18n( "The request was not completed because it was "
- "aborted." );
- solutions << i18n( "Retry the request." );
- break;
-
- case TDEIO::ERR_CYCLIC_COPY:
- errorName = i18n( "Cyclic Link Detected During Copy" );
- description = i18n( "UNIX environments are commonly able to link a file or "
- "folder to a separate name and/or location. During the requested copy "
- "operation, TDE detected a link or series of links that results in an "
- "infinite loop - i.e. the file was (perhaps in a roundabout way) linked "
- "to itself." );
- solutions << i18n( "Delete one part of the loop in order that it does not "
- "cause an infinite loop, and try again." ) << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_CREATE_SOCKET:
- errorName = i18n( "Could Not Create Network Connection" );
- techName = i18n( "Could Not Create Socket" );
- description = i18n( "This is a fairly technical error in which a required "
- "device for network communications (a socket) could not be created." );
- causes << i18n( "The network connection may be incorrectly configured, or "
- "the network interface may not be enabled." );
- solutions << sNetwork << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_CONNECT:
- errorName = i18n( "Connection to Server Refused" );
- description = i18n( "The server <strong>%1</strong> refused to allow this "
- "computer to make a connection." ).arg( host );
- causes << i18n( "The server, while currently connected to the Internet, "
- "may not be configured to allow requests." )
- << i18n( "The server, while currently connected to the Internet, "
- "may not be running the requested service (%1)." ).arg( protocol )
- << i18n( "A network firewall (a device which restricts Internet "
- "requests), either protecting your network or the network of the server, "
- "may have intervened, preventing this request." );
- solutions << sTryagain << sServeradmin << sSysadmin;
- break;
-
- case TDEIO::ERR_CONNECTION_BROKEN:
- errorName = i18n( "Connection to Server Closed Unexpectedly" );
- description = i18n( "Although a connection was established to "
- "<strong>%1</strong>, the connection was closed at an unexpected point "
- "in the communication." ).arg( host );
- causes << cNetwork << cNetpath << i18n( "A protocol error may have occurred, "
- "causing the server to close the connection as a response to the error." );
- solutions << sTryagain << sServeradmin << sSysadmin;
- break;
-
- case TDEIO::ERR_NOT_FILTER_PROTOCOL:
- errorName = i18n( "URL Resource Invalid" );
- techName = i18n( "Protocol %1 is not a Filter Protocol" ).arg( protocol );
- description = i18n( "The <strong>U</strong>niform <strong>R</strong>esource "
- "<strong>L</strong>ocator (URL) that you entered did not refer to "
- "a valid mechanism of accessing the specific resource, "
- "<strong>%1%2</strong>." )
- .arg( !host.isNull() ? host + '/' : TQString::null ).arg( dir );
- causes << i18n( "TDE is able to communicate through a protocol within a "
- "protocol. This request specified a protocol be used as such, however "
- "this protocol is not capable of such an action. This is a rare event, "
- "and is likely to indicate a programming error." );
- solutions << sTypo << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_MOUNT:
- errorName = i18n( "Unable to Initialize Input/Output Device" );
- techName = i18n( "Could Not Mount Device" );
- description = i18n( "The requested device could not be initialized "
- "(\"mounted\"). The reported error was: <strong>%1</strong>" )
- .arg( errorText );
- causes << i18n( "The device may not be ready, for example there may be "
- "no media in a removable media device (i.e. no CD-ROM in a CD drive), "
- "or in the case of a peripheral/portable device, the device may not "
- "be correctly connected." )
- << i18n( "You may not have permissions to initialize (\"mount\") the "
- "device. On UNIX systems, often system administrator privileges are "
- "required to initialize a device." )
- << cHardware;
- solutions << i18n( "Check that the device is ready; removable drives "
- "must contain media, and portable devices must be connected and powered "
- "on.; and try again." ) << sAccess << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_UNMOUNT:
- errorName = i18n( "Unable to Uninitialize Input/Output Device" );
- techName = i18n( "Could Not Unmount Device" );
- description = i18n( "The requested device could not be uninitialized "
- "(\"unmounted\"). The reported error was: <strong>%1</strong>" )
- .arg( errorText );
- causes << i18n( "The device may be busy, that is, still in use by "
- "another application or user. Even such things as having an open "
- "browser window on a location on this device may cause the device to "
- "remain in use." )
- << i18n( "You may not have permissions to uninitialize (\"unmount\") "
- "the device. On UNIX systems, system administrator privileges are "
- "often required to uninitialize a device." )
- << cHardware;
- solutions << i18n( "Check that no applications are accessing the device, "
- "and try again." ) << sAccess << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_READ:
- errorName = i18n( "Cannot Read From Resource" );
- description = i18n( "This means that although the resource, "
- "<strong>%1</strong>, was able to be opened, an error occurred while "
- "reading the contents of the resource." ).arg( url );
- causes << i18n( "You may not have permissions to read from the resource." );
- if ( !isSlaveNetwork ) causes << cNetwork;
- causes << cHardware;
- solutions << sAccess;
- if ( !isSlaveNetwork ) solutions << sNetwork;
- solutions << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_WRITE:
- errorName = i18n( "Cannot Write to Resource" );
- description = i18n( "This means that although the resource, <strong>%1</strong>"
- ", was able to be opened, an error occurred while writing to the resource." )
- .arg( url );
- causes << i18n( "You may not have permissions to write to the resource." );
- if ( !isSlaveNetwork ) causes << cNetwork;
- causes << cHardware;
- solutions << sAccess;
- if ( !isSlaveNetwork ) solutions << sNetwork;
- solutions << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_BIND:
- errorName = i18n( "Could Not Listen for Network Connections" );
- techName = i18n( "Could Not Bind" );
- description = i18n( "This is a fairly technical error in which a required "
- "device for network communications (a socket) could not be established "
- "to listen for incoming network connections." );
- causes << i18n( "The network connection may be incorrectly configured, or "
- "the network interface may not be enabled." );
- solutions << sNetwork << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_LISTEN:
- errorName = i18n( "Could Not Listen for Network Connections" );
- techName = i18n( "Could Not Listen" );
- description = i18n( "This is a fairly technical error in which a required "
- "device for network communications (a socket) could not be established "
- "to listen for incoming network connections." );
- causes << i18n( "The network connection may be incorrectly configured, or "
- "the network interface may not be enabled." );
- solutions << sNetwork << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_ACCEPT:
- errorName = i18n( "Could Not Accept Network Connection" );
- description = i18n( "This is a fairly technical error in which an error "
- "occurred while attempting to accept an incoming network connection." );
- causes << i18n( "The network connection may be incorrectly configured, or "
- "the network interface may not be enabled." )
- << i18n( "You may not have permissions to accept the connection." );
- solutions << sNetwork << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_LOGIN:
- errorName = i18n( "Could Not Login: %1" ).arg( errorText );
- description = i18n( "An attempt to login to perform the requested "
- "operation was unsuccessful." );
- causes << i18n( "You may have supplied incorrect authentication details or "
- "none at all." )
- << i18n( "Your account may not have permission to access the "
- "specified resource." ) << cProtocol;
- solutions << i18n( "Retry the request and ensure your authentication details "
- "are entered correctly." ) << sServeradmin << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_STAT:
- errorName = i18n( "Could Not Determine Resource Status" );
- techName = i18n( "Could Not Stat Resource" );
- description = i18n( "An attempt to determine information about the status "
- "of the resource <strong>%1</strong>, such as the resource name, type, "
- "size, etc., was unsuccessful." ).arg( url );
- causes << i18n( "The specified resource may not have existed or may "
- "not be accessible." ) << cProtocol << cHardware;
- solutions << i18n( "Retry the request and ensure your authentication details "
- "are entered correctly." ) << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_CLOSEDIR:
- //result = i18n( "Could not terminate listing %1" ).arg( errorText );
- errorName = i18n( "Could Not Cancel Listing" );
- techName = i18n( "FIXME: Document this" );
- break;
-
- case TDEIO::ERR_COULD_NOT_MKDIR:
- errorName = i18n( "Could Not Create Folder" );
- description = i18n( "An attempt to create the requested folder failed." );
- causes << cAccess << i18n( "The location where the folder was to be created "
- "may not exist." );
- if ( !isSlaveNetwork ) causes << cProtocol;
- solutions << i18n( "Retry the request." ) << sAccess;
- break;
-
- case TDEIO::ERR_COULD_NOT_RMDIR:
- errorName = i18n( "Could Not Remove Folder" );
- description = i18n( "An attempt to remove the specified folder, "
- "<strong>%1</strong>, failed." ).arg( dir );
- causes << i18n( "The specified folder may not exist." )
- << i18n( "The specified folder may not be empty." )
- << cAccess;
- if ( !isSlaveNetwork ) causes << cProtocol;
- solutions << i18n( "Ensure that the folder exists and is empty, and try "
- "again." ) << sAccess;
- break;
-
- case TDEIO::ERR_CANNOT_RESUME:
- errorName = i18n( "Could Not Resume File Transfer" );
- description = i18n( "The specified request asked that the transfer of "
- "file <strong>%1</strong> be resumed at a certain point of the "
- "transfer. This was not possible." ).arg( filename );
- causes << i18n( "The protocol, or the server, may not support file "
- "resuming." );
- solutions << i18n( "Retry the request without attempting to resume "
- "transfer." );
- break;
-
- case TDEIO::ERR_CANNOT_RENAME:
- errorName = i18n( "Could Not Rename Resource" );
- description = i18n( "An attempt to rename the specified resource "
- "<strong>%1</strong> failed." ).arg( url );
- causes << cAccess << cExists;
- if ( !isSlaveNetwork ) causes << cProtocol;
- solutions << sAccess << sExists;
- break;
-
- case TDEIO::ERR_CANNOT_CHMOD:
- errorName = i18n( "Could Not Alter Permissions of Resource" );
- description = i18n( "An attempt to alter the permissions on the specified "
- "resource <strong>%1</strong> failed." ).arg( url );
- causes << cAccess << cExists;
- solutions << sAccess << sExists;
- break;
-
- case TDEIO::ERR_CANNOT_DELETE:
- errorName = i18n( "Could Not Delete Resource" );
- description = i18n( "An attempt to delete the specified resource "
- "<strong>%1</strong> failed." ).arg( url );
- causes << cAccess << cExists;
- solutions << sAccess << sExists;
- break;
-
- case TDEIO::ERR_SLAVE_DIED:
- errorName = i18n( "Unexpected Program Termination" );
- description = i18n( "The program on your computer which provides access "
- "to the <strong>%1</strong> protocol has unexpectedly terminated." )
- .arg( url );
- causes << cBuglikely;
- solutions << sUpdate << sBugreport;
- break;
-
- case TDEIO::ERR_OUT_OF_MEMORY:
- errorName = i18n( "Out of Memory" );
- description = i18n( "The program on your computer which provides access "
- "to the <strong>%1</strong> protocol could not obtain the memory "
- "required to continue." ).arg( protocol );
- causes << cBuglikely;
- solutions << sUpdate << sBugreport;
- break;
-
- case TDEIO::ERR_UNKNOWN_PROXY_HOST:
- errorName = i18n( "Unknown Proxy Host" );
- description = i18n( "While retrieving information about the specified "
- "proxy host, <strong>%1</strong>, an Unknown Host error was encountered. "
- "An unknown host error indicates that the requested name could not be "
- "located on the Internet." ).arg( errorText );
- causes << i18n( "There may have been a problem with your network "
- "configuration, specifically your proxy's hostname. If you have been "
- "accessing the Internet with no problems recently, this is unlikely." )
- << cNetwork;
- solutions << i18n( "Double-check your proxy settings and try again." )
- << sSysadmin;
- break;
-
- case TDEIO::ERR_COULD_NOT_AUTHENTICATE:
- errorName = i18n( "Authentication Failed: Method %1 Not Supported" )
- .arg( errorText );
- description = i18n( "Although you may have supplied the correct "
- "authentication details, the authentication failed because the "
- "method that the server is using is not supported by the TDE "
- "program implementing the protocol %1." ).arg( protocol );
- solutions << i18n( "Please file a bug at <a href=\"http://bugs.kde.org/\">"
- "http://bugs.pearsoncomputing.net/</a> to inform the TDE team of the unsupported "
- "authentication method." ) << sSysadmin;
- break;
-
- case TDEIO::ERR_ABORTED:
- errorName = i18n( "Request Aborted" );
- description = i18n( "The request was not completed because it was "
- "aborted." );
- solutions << i18n( "Retry the request." );
- break;
-
- case TDEIO::ERR_INTERNAL_SERVER:
- errorName = i18n( "Internal Error in Server" );
- description = i18n( "The program on the server which provides access "
- "to the <strong>%1</strong> protocol has reported an internal error: "
- "%0." ).arg( protocol );
- causes << i18n( "This is most likely to be caused by a bug in the "
- "server program. Please consider submitting a full bug report as "
- "detailed below." );
- solutions << i18n( "Contact the administrator of the server "
- "to advise them of the problem." )
- << i18n( "If you know who the authors of the server software are, "
- "submit the bug report directly to them." );
- break;
-
- case TDEIO::ERR_SERVER_TIMEOUT:
- errorName = i18n( "Timeout Error" );
- description = i18n( "Although contact was made with the server, a "
- "response was not received within the amount of time allocated for "
- "the request as follows:<ul>"
- "<li>Timeout for establishing a connection: %1 seconds</li>"
- "<li>Timeout for receiving a response: %2 seconds</li>"
- "<li>Timeout for accessing proxy servers: %3 seconds</li></ul>"
- "Please note that you can alter these timeout settings in the TDE "
- "Control Center, by selecting Network -> Preferences." )
- .arg( KProtocolManager::connectTimeout() )
- .arg( KProtocolManager::responseTimeout() )
- .arg( KProtocolManager::proxyConnectTimeout() );
- causes << cNetpath << i18n( "The server was too busy responding to other "
- "requests to respond." );
- solutions << sTryagain << sServeradmin;
- break;
-
- case TDEIO::ERR_UNKNOWN:
- errorName = i18n( "Unknown Error" );
- description = i18n( "The program on your computer which provides access "
- "to the <strong>%1</strong> protocol has reported an unknown error: "
- "%2." ).arg( protocol ).arg( errorText );
- causes << cBug;
- solutions << sUpdate << sBugreport;
- break;
-
- case TDEIO::ERR_UNKNOWN_INTERRUPT:
- errorName = i18n( "Unknown Interruption" );
- description = i18n( "The program on your computer which provides access "
- "to the <strong>%1</strong> protocol has reported an interruption of "
- "an unknown type: %2." ).arg( protocol ).arg( errorText );
- causes << cBug;
- solutions << sUpdate << sBugreport;
- break;
-
- case TDEIO::ERR_CANNOT_DELETE_ORIGINAL:
- errorName = i18n( "Could Not Delete Original File" );
- description = i18n( "The requested operation required the deleting of "
- "the original file, most likely at the end of a file move operation. "
- "The original file <strong>%1</strong> could not be deleted." )
- .arg( errorText );
- causes << cAccess;
- solutions << sAccess;
- break;
-
- case TDEIO::ERR_CANNOT_DELETE_PARTIAL:
- errorName = i18n( "Could Not Delete Temporary File" );
- description = i18n( "The requested operation required the creation of "
- "a temporary file in which to save the new file while being "
- "downloaded. This temporary file <strong>%1</strong> could not be "
- "deleted." ).arg( errorText );
- causes << cAccess;
- solutions << sAccess;
- break;
-
- case TDEIO::ERR_CANNOT_RENAME_ORIGINAL:
- errorName = i18n( "Could Not Rename Original File" );
- description = i18n( "The requested operation required the renaming of "
- "the original file <strong>%1</strong>, however it could not be "
- "renamed." ).arg( errorText );
- causes << cAccess;
- solutions << sAccess;
- break;
-
- case TDEIO::ERR_CANNOT_RENAME_PARTIAL:
- errorName = i18n( "Could Not Rename Temporary File" );
- description = i18n( "The requested operation required the creation of "
- "a temporary file <strong>%1</strong>, however it could not be "
- "created." ).arg( errorText );
- causes << cAccess;
- solutions << sAccess;
- break;
-
- case TDEIO::ERR_CANNOT_SYMLINK:
- errorName = i18n( "Could Not Create Link" );
- techName = i18n( "Could Not Create Symbolic Link" );
- description = i18n( "The requested symbolic link %1 could not be created." )
- .arg( errorText );
- causes << cAccess;
- solutions << sAccess;
- break;
-
- case TDEIO::ERR_NO_CONTENT:
- errorName = i18n( "No Content" );
- description = errorText;
- break;
-
- case TDEIO::ERR_DISK_FULL:
- errorName = i18n( "Disk Full" );
- description = i18n( "The requested file <strong>%1</strong> could not be "
- "written to as there is inadequate disk space." ).arg( errorText );
- solutions << i18n( "Free up enough disk space by 1) deleting unwanted and "
- "temporary files; 2) archiving files to removable media storage such as "
- "CD-Recordable discs; or 3) obtain more storage capacity." )
- << sSysadmin;
- break;
-
- case TDEIO::ERR_IDENTICAL_FILES:
- errorName = i18n( "Source and Destination Files Identical" );
- description = i18n( "The operation could not be completed because the "
- "source and destination files are the same file." );
- solutions << i18n( "Choose a different filename for the destination file." );
- break;
-
- // We assume that the slave has all the details
- case TDEIO::ERR_SLAVE_DEFINED:
- errorName = TQString::null;
- description = errorText;
- break;
-
- default:
- // fall back to the plain error...
- errorName = i18n( "Undocumented Error" );
- description = buildErrorString( errorCode, errorText );
- }
-
- TQByteArray ret;
- TQDataStream stream(ret, IO_WriteOnly);
- stream << errorName << techName << description << causes << solutions;
- return ret;
-}
-
-#ifdef Q_OS_UNIX
-
-#include <limits.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <tqfile.h>
-
-#include <config.h>
-
-#ifdef HAVE_PATHS_H
-#include <paths.h>
-#endif
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#endif
-#include <sys/param.h>
-#ifdef HAVE_LIMITS_H
-#include <limits.h>
-#endif
-#ifdef HAVE_SYS_MNTTAB_H
-#include <sys/mnttab.h>
-#endif
-#ifdef HAVE_MNTENT_H
-#include <mntent.h>
-#elif defined(HAVE_SYS_MNTENT_H)
-#include <sys/mntent.h>
-#endif
-#ifdef HAVE_SYS_UCRED_H
-#include <sys/ucred.h>
-#endif
-#ifdef HAVE_SYS_MOUNT_H
-#include <sys/mount.h>
-#endif
-#ifdef HAVE_FSTAB_H
-#include <fstab.h>
-#endif
-#if defined(_AIX)
-#include <sys/mntctl.h>
-#include <sys/vmount.h>
-#include <sys/vfs.h>
-
-/* AIX does not prototype mntctl anywhere that I can find */
-#ifndef mntctl
-extern "C" {
-int mntctl(int command, int size, void* buffer);
-}
-#endif
-extern "C" struct vfs_ent *getvfsbytype(int vfsType);
-extern "C" void endvfsent( );
-#endif
-
-/***************************************************************
- *
- * Utility functions
- *
- ***************************************************************/
-
-#ifndef HAVE_GETMNTINFO
-
-#ifdef _PATH_MOUNTED
-// On some Linux, MNTTAB points to /etc/fstab !
-# undef MNTTAB
-# define MNTTAB _PATH_MOUNTED
-#else
-# ifndef MNTTAB
-# ifdef MTAB_FILE
-# define MNTTAB MTAB_FILE
-# else
-# define MNTTAB "/etc/mnttab"
-# endif
-# endif
-#endif
-
-#ifndef FSTAB
-# ifdef _PATH_FSTAB
-# define FSTAB _PATH_FSTAB
-# else
-# define FSTAB "/etc/fstab"
-# endif
-#endif
-
-#ifdef __CYGWIN__
-#define hasmntopt(var,opt) (0)
-#endif
-
-// There are (at least) four kind of APIs:
-// setmntent + getmntent + struct mntent (linux...)
-// getmntent + struct mnttab
-// mntctl + struct vmount (AIX)
-// getmntinfo + struct statfs&flags (BSD 4.4 and friends)
-// getfsent + char* (BSD 4.3 and friends)
-
-#ifdef HAVE_SETMNTENT
-#define SETMNTENT setmntent
-#define ENDMNTENT endmntent
-#define STRUCT_MNTENT struct mntent *
-#define STRUCT_SETMNTENT FILE *
-#define GETMNTENT(file, var) ((var = getmntent(file)) != 0)
-#define MOUNTPOINT(var) var->mnt_dir
-#define MOUNTTYPE(var) var->mnt_type
-#define HASMNTOPT(var, opt) hasmntopt(var, opt)
-#define FSNAME(var) var->mnt_fsname
-#elif defined(_AIX)
-/* we don't need this stuff */
-#else
-#define SETMNTENT fopen
-#define ENDMNTENT fclose
-#define STRUCT_MNTENT struct mnttab
-#define STRUCT_SETMNTENT FILE *
-#define GETMNTENT(file, var) (getmntent(file, &var) == 0)
-#define MOUNTPOINT(var) var.mnt_mountp
-#define MOUNTTYPE(var) var.mnt_fstype
-#define HASMNTOPT(var, opt) hasmntopt(&var, opt)
-#define FSNAME(var) var.mnt_special
-#endif
-
-#endif /* HAVE_GETMNTINFO */
-
-TQString TDEIO::findDeviceMountPoint( const TQString& filename )
-{
- TQString result;
-
-#ifdef HAVE_VOLMGT
- /*
- * support for Solaris volume management
- */
- const char *volpath;
- FILE *mnttab;
- struct mnttab mnt;
- int len;
- TQCString devname;
-
- if( (volpath = volmgt_root()) == NULL ) {
- kdDebug( 7007 ) << "findDeviceMountPoint: "
- << "VOLMGT: can't find volmgt root dir" << endl;
- return TQString::null;
- }
-
- if( (mnttab = fopen( MNTTAB, "r" )) == NULL ) {
- kdDebug( 7007 ) << "findDeviceMountPoint: "
- << "VOLMGT: can't open mnttab" << endl;
- return TQString::null;
- }
-
- devname = volpath;
- devname += TQFile::encodeName( filename );
- devname += '/';
- len = devname.length();
-// kdDebug( 7007 ) << "findDeviceMountPoint: "
-// << "VOLMGT: searching mountpoint for \"" << devname << "\""
-// << endl;
-
- /*
- * find the mountpoint
- * floppies:
- * /dev/disketteN => <volpath>/dev/disketteN
- * CDROM, ZIP, and other media:
- * /dev/dsk/cXtYdZs2 => <volpath>/dev/dsk/cXtYdZ (without slice#)
- */
- rewind( mnttab );
- result = TQString::null;
- while( getmntent( mnttab, &mnt ) == 0 ) {
- /*
- * either match the exact device name (floppies),
- * or the device name without the slice#
- */
- if( strncmp( devname.data(), mnt.mnt_special, len ) == 0
- || (strncmp( devname.data(), mnt.mnt_special, len - 3 ) == 0
- && mnt.mnt_special[len - 3] == '/' )
- || (strcmp(TQFile::encodeName(filename).data()
- , mnt.mnt_special)==0)) {
- result = mnt.mnt_mountp;
- break;
- }
- }
- fclose( mnttab );
-#else
-
- char realpath_buffer[MAXPATHLEN];
- TQCString realname;
-
- realname = TQFile::encodeName(filename);
- /* If the path contains symlinks, get the real name */
- if (realpath(realname, realpath_buffer) != 0)
- // succes, use result from realpath
- realname = realpath_buffer;
-
- //kdDebug(7007) << "findDeviceMountPoint realname=" << realname << endl;
-
-#ifdef HAVE_GETMNTINFO
-
-#ifdef GETMNTINFO_USES_STATVFS
- struct statvfs *mounted;
-#else
- struct statfs *mounted;
-#endif
-
- int num_fs = getmntinfo(&mounted, MNT_NOWAIT);
-
- for (int i=0;i<num_fs;i++) {
-
- TQCString device_name = mounted[i].f_mntfromname;
-
- // If the path contains symlinks, get
- // the real name
- if (realpath(device_name, realpath_buffer) != 0)
- // succes, use result from realpath
- device_name = realpath_buffer;
-
- if (realname == device_name) {
- result = mounted[i].f_mntonname;
- break;
- }
- }
-
-#elif defined(_AIX)
-
- struct vmount *mntctl_buffer;
- struct vmount *vm;
- char *mountedfrom;
- char *mountedto;
- int fsname_len, num;
- int buf_sz = 4096;
-
- /* mntctl can be used to query mounted file systems.
- * mntctl takes only the command MCTL_QUERY so far.
- * The buffer is filled with an array of vmount structures, but these
- * vmount structures have variable size.
- * mntctl return values:
- * -1 error
- * 0 look in first word of buffer for required bytes, 4096 may be
- * a good starting size, but if tables grow too large, look here.
- * >0 number of vmount structures
- */
- mntctl_buffer = (struct vmount*)malloc(buf_sz);
- num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
- if (num == 0)
- {
- buf_sz = *(int*)mntctl_buffer;
- free(mntctl_buffer);
- mntctl_buffer = (struct vmount*)malloc(buf_sz);
- num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
- }
-
- if (num > 0)
- {
- /* iterate through items in the vmount structure: */
- vm = mntctl_buffer;
- for ( ; num > 0; num-- )
- {
- /* get the name of the mounted file systems: */
- fsname_len = vmt2datasize(vm, VMT_STUB);
- mountedto = (char*)malloc(fsname_len + 1);
- mountedto[fsname_len] = '\0';
- strncpy(mountedto, (char *)vmt2dataptr(vm, VMT_STUB), fsname_len);
-
- /* get the mount-from information: */
- fsname_len = vmt2datasize(vm, VMT_OBJECT);
- mountedfrom = (char*)malloc(fsname_len + 1);
- mountedfrom[fsname_len] = '\0';
- strncpy(mountedfrom, (char *)vmt2dataptr(vm, VMT_OBJECT), fsname_len);
-
- TQCString device_name = mountedfrom;
-
- if (realpath(device_name, realpath_buffer) != 0)
- // success, use result from realpath
- device_name = realpath_buffer;
-
- free(mountedfrom);
-
- if (realname == device_name) {
- result = mountedto;
- free(mountedto);
- break;
- }
-
- free(mountedto);
-
- /* goto the next vmount structure: */
- vm = (struct vmount *)((char *)vm + vm->vmt_length);
- }
- }
-
- free( mntctl_buffer );
-
-#else
-
- STRUCT_SETMNTENT mtab;
-
- /* Get the list of mounted file systems */
-
- if ((mtab = SETMNTENT(MNTTAB, "r")) == 0) {
- perror("setmntent");
- return TQString::null;
- }
-
- /* Loop over all file systems and see if we can find our
- * mount point.
- * Note that this is the mount point with the longest match.
- * XXX: Fails if me->mnt_dir is not a realpath but goes
- * through a symlink, e.g. /foo/bar where /foo is a symlink
- * pointing to /local/foo.
- *
- * How kinky can you get with a filesystem?
- */
-
- STRUCT_MNTENT me;
-
- while (GETMNTENT(mtab, me))
- {
- // There may be symbolic links into the /etc/mnttab
- // So we have to find the real device name here as well!
- TQCString device_name = FSNAME(me);
- if (device_name.isEmpty() || (device_name == "none"))
- continue;
-
- //kdDebug( 7007 ) << "device_name=" << device_name << endl;
-
- // If the path contains symlinks, get
- // the real name
- if (realpath(device_name, realpath_buffer) != 0)
- // succes, use result from realpath
- device_name = realpath_buffer;
-
- //kdDebug( 7007 ) << "device_name after realpath =" << device_name << endl;
-
- if (realname == device_name)
- {
- result = MOUNTPOINT(me);
- break;
- }
- }
-
- ENDMNTENT(mtab);
-
-#endif /* GET_MNTINFO */
-#endif /* HAVE_VOLMGT */
-
- //kdDebug( 7007 ) << "Returning result " << result << endl;
- return result;
-}
-
-// Don't just trust the return value, keep iterating to check for a better match (bigger max)
-static bool is_my_mountpoint( const char *mountpoint, const char *realname, int &max )
-{
- int length = strlen(mountpoint);
-
- if (!strncmp(mountpoint, realname, length)
- && length > max) {
- max = length;
- if (length == 1 || realname[length] == '/' || realname[length] == '\0')
- return true;
- }
- return false;
-}
-
-typedef enum { Unseen, Right, Wrong } MountState;
-
-/**
- * Idea and code base by Olaf Kirch <okir@caldera.de>
- **/
-static void check_mount_point(const char *mounttype,
- const char *fsname,
- MountState &isslow, MountState &isautofs)
-{
- bool nfs = !strcmp(mounttype, "nfs");
- bool autofs = !strcmp(mounttype, "autofs") || !strcmp(mounttype,"subfs");
- bool pid = (strstr(fsname, ":(pid") != 0);
-
- if (nfs && !pid)
- isslow = Right;
- else if (isslow == Right)
- isslow = Wrong;
-
- /* Does this look like automounted? */
- if (autofs || (nfs && pid)) {
- isautofs = Right;
- isslow = Right;
- }
-}
-
-// returns the mount point, checks the mount state.
-// if ismanual == Wrong this function does not check the manual mount state
-static TQString get_mount_info(const TQString& filename,
- MountState& isautofs, MountState& isslow, MountState& ismanual,
- TQString& fstype)
-{
- static bool gotRoot = false;
- static dev_t rootDevice;
-
- struct cachedDevice_t
- {
- dev_t device;
- TQString mountPoint;
- MountState isautofs;
- MountState isslow;
- MountState ismanual;
- TQString fstype;
- };
- static struct cachedDevice_t *cachedDevice = 0;
-
- if (!gotRoot)
- {
- KDE_struct_stat stat_buf;
- KDE_stat("/", &stat_buf);
- gotRoot = true;
- rootDevice = stat_buf.st_dev;
- }
-
- bool gotDevice = false;
- KDE_struct_stat stat_buf;
- if (KDE_stat(TQFile::encodeName(filename), &stat_buf) == 0)
- {
- gotDevice = true;
- if (stat_buf.st_dev == rootDevice)
- {
- static const TQString &root = TDEGlobal::staticQString("/");
- isautofs = Wrong;
- isslow = Wrong;
- ismanual = Wrong;
- fstype = TQString::null; // ### do we need it?
- return root;
- }
- if (cachedDevice && (stat_buf.st_dev == cachedDevice->device))
- {
- bool interestedInIsManual = ismanual != Wrong;
- isautofs = cachedDevice->isautofs;
- isslow = cachedDevice->isslow;
- ismanual = cachedDevice->ismanual;
- fstype = cachedDevice->fstype;
- // Don't use the cache if it doesn't have the information we're looking for
- if ( !interestedInIsManual || ismanual != Unseen )
- return cachedDevice->mountPoint;
- }
- }
-
- char realname[MAXPATHLEN];
-
- memset(realname, 0, MAXPATHLEN);
-
- /* If the path contains symlinks, get the real name */
- if (realpath(TQFile::encodeName(filename), realname) == 0) {
- if( strlcpy(realname, TQFile::encodeName(filename), MAXPATHLEN)>=MAXPATHLEN)
- return TQString::null;
- }
-
- int max = 0;
- TQString mountPoint;
-
- /* Loop over all file systems and see if we can find our
- * mount point.
- * Note that this is the mount point with the longest match.
- * XXX: Fails if me->mnt_dir is not a realpath but goes
- * through a symlink, e.g. /foo/bar where /foo is a symlink
- * pointing to /local/foo.
- *
- * How kinky can you get with a filesystem?
- */
-
-#ifdef HAVE_GETMNTINFO
-
-#ifdef GETMNTINFO_USES_STATVFS
- struct statvfs *mounted;
-#else
- struct statfs *mounted;
-#endif
-
- char realpath_buffer[MAXPATHLEN];
-
- int num_fs = getmntinfo(&mounted, MNT_NOWAIT);
-
- for (int i=0;i<num_fs;i++) {
-
- TQCString device_name = mounted[i].f_mntfromname;
-
- // If the path contains symlinks, get
- // the real name
- if (realpath(device_name, realpath_buffer) != 0)
- // succes, use result from realpath
- device_name = realpath_buffer;
-#ifdef __osf__
- char * mounttype = mnt_names[mounted[i].f_type];
-#else
- char * mounttype = mounted[i].f_fstypename;
-#endif
- if ( is_my_mountpoint( mounted[i].f_mntonname, realname, max ) )
- {
- mountPoint = TQFile::decodeName(mounted[i].f_mntonname);
- fstype = TQString::fromLatin1(mounttype);
- check_mount_point( mounttype, mounted[i].f_mntfromname,
- isautofs, isslow );
- // keep going, looking for a potentially better one
-
- if (ismanual == Unseen)
- {
- struct fstab *ft = getfsfile(mounted[i].f_mntonname);
- if (!ft || strstr(ft->fs_mntops, "noauto"))
- ismanual = Right;
- }
- }
- }
-
-#elif defined(_AIX)
-
- struct vmount *mntctl_buffer;
- struct vmount *vm;
- char *mountedfrom;
- char *mountedto;
- int fsname_len, num;
- char realpath_buffer[MAXPATHLEN];
- int buf_sz = 4096;
-
- mntctl_buffer = (struct vmount*)malloc(buf_sz);
- num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
- if (num == 0)
- {
- buf_sz = *(int*)mntctl_buffer;
- free(mntctl_buffer);
- mntctl_buffer = (struct vmount*)malloc(buf_sz);
- num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
- }
-
- if (num > 0)
- {
- /* iterate through items in the vmount structure: */
- vm = (struct vmount *)mntctl_buffer;
- for ( ; num > 0; num-- )
- {
- /* get the name of the mounted file systems: */
- fsname_len = vmt2datasize(vm, VMT_STUB);
- mountedto = (char*)malloc(fsname_len + 1);
- mountedto[fsname_len] = '\0';
- strncpy(mountedto, (char *)vmt2dataptr(vm, VMT_STUB), fsname_len);
-
- fsname_len = vmt2datasize(vm, VMT_OBJECT);
- mountedfrom = (char*)malloc(fsname_len + 1);
- mountedfrom[fsname_len] = '\0';
- strncpy(mountedfrom, (char *)vmt2dataptr(vm, VMT_OBJECT), fsname_len);
-
- /* get the mount-from information: */
- TQCString device_name = mountedfrom;
-
- if (realpath(device_name, realpath_buffer) != 0)
- // success, use result from realpath
- device_name = realpath_buffer;
-
- /* Look up the string for the file system type,
- * as listed in /etc/vfs.
- * ex.: nfs,jfs,afs,cdrfs,sfs,cachefs,nfs3,autofs
- */
- struct vfs_ent* ent = getvfsbytype(vm->vmt_gfstype);
-
- if ( is_my_mountpoint( mountedto, realname, max ) )
- {
- mountPoint = TQFile::decodeName(mountedto);
- fstype = TQString::fromLatin1(ent->vfsent_name);
- check_mount_point(ent->vfsent_name, device_name, isautofs, isslow);
-
- if (ismanual == Unseen)
- {
- // TODO: add check for ismanual, I couldn't find any way
- // how to get the mount attribute from /etc/filesystems
- ismanual == Wrong;
- }
- }
-
- free(mountedfrom);
- free(mountedto);
-
- /* goto the next vmount structure: */
- vm = (struct vmount *)((char *)vm + vm->vmt_length);
- }
-
- endvfsent( );
- }
-
- free( mntctl_buffer );
-
-#else
-
- STRUCT_SETMNTENT mtab;
- /* Get the list of mounted file systems */
-
- if ((mtab = SETMNTENT(MNTTAB, "r")) == 0) {
- perror("setmntent");
- return TQString::null;
- }
-
- STRUCT_MNTENT me;
-
- while (true) {
- if (!GETMNTENT(mtab, me))
- break;
-
- if ( is_my_mountpoint( MOUNTPOINT(me), realname, max ) )
- {
- mountPoint = TQFile::decodeName( MOUNTPOINT(me) );
- fstype = MOUNTTYPE(me);
- check_mount_point(MOUNTTYPE(me), FSNAME(me), isautofs, isslow);
- // we don't check if ismanual is Right, if /a/b is manually
- // mounted /a/b/c can't be automounted. At least IMO.
- if (ismanual == Unseen)
- {
- // The next GETMNTENT call may destroy 'me'
- // Copy out the info that we need
- TQCString fsname_me = FSNAME(me);
- TQCString mounttype_me = MOUNTTYPE(me);
-
- STRUCT_SETMNTENT fstab;
- if ((fstab = SETMNTENT(FSTAB, "r")) == 0) {
- continue;
- }
-
- bool found = false;
- STRUCT_MNTENT fe;
- while (GETMNTENT(fstab, fe))
- {
- if (fsname_me == FSNAME(fe))
- {
- found = true;
- if (HASMNTOPT(fe, "noauto") ||
- !strcmp(MOUNTTYPE(fe), "supermount"))
- ismanual = Right;
- break;
- }
- }
- if (!found || (mounttype_me == "supermount"))
- ismanual = Right;
-
- ENDMNTENT(fstab);
- }
- }
- }
-
- ENDMNTENT(mtab);
-
-#endif
-
- if (isautofs == Right && isslow == Unseen)
- isslow = Right;
-
- if (gotDevice)
- {
- if (!cachedDevice)
- cachedDevice = new cachedDevice_t;
-
- cachedDevice->device = stat_buf.st_dev;
- cachedDevice->mountPoint = mountPoint;
- cachedDevice->isautofs = isautofs;
- cachedDevice->isslow = isslow;
- cachedDevice->ismanual = ismanual;
- cachedDevice->fstype = fstype;
- }
-
- return mountPoint;
-}
-
-#else //!Q_OS_UNIX
-//dummy
-TQString TDEIO::findDeviceMountPoint( const TQString& filename )
-{
- return TQString::null;
-}
-#endif
-
-TQString TDEIO::findPathMountPoint(const TQString& filename)
-{
-#ifdef Q_OS_UNIX
- MountState isautofs = Unseen, isslow = Unseen, ismanual = Wrong;
- TQString fstype;
- return get_mount_info(filename, isautofs, isslow, ismanual, fstype);
-#else //!Q_OS_UNIX
- return TQString::null;
-#endif
-}
-
-bool TDEIO::manually_mounted(const TQString& filename)
-{
-#ifdef Q_OS_UNIX
- MountState isautofs = Unseen, isslow = Unseen, ismanual = Unseen;
- TQString fstype;
- TQString mountPoint = get_mount_info(filename, isautofs, isslow, ismanual, fstype);
- return !mountPoint.isNull() && (ismanual == Right);
-#else //!Q_OS_UNIX
- return false;
-#endif
-}
-
-bool TDEIO::probably_slow_mounted(const TQString& filename)
-{
-#ifdef Q_OS_UNIX
- MountState isautofs = Unseen, isslow = Unseen, ismanual = Wrong;
- TQString fstype;
- TQString mountPoint = get_mount_info(filename, isautofs, isslow, ismanual, fstype);
- return !mountPoint.isNull() && (isslow == Right);
-#else //!Q_OS_UNIX
- return false;
-#endif
-}
-
-bool TDEIO::testFileSystemFlag(const TQString& filename, FileSystemFlag flag)
-{
-#ifdef Q_OS_UNIX
- MountState isautofs = Unseen, isslow = Unseen, ismanual = Wrong;
- TQString fstype;
- TQString mountPoint = get_mount_info(filename, isautofs, isslow, ismanual, fstype);
- kdDebug() << "testFileSystemFlag: fstype=" << fstype << endl;
- if (mountPoint.isNull())
- return false;
- bool isMsDos = ( fstype == "msdos" || fstype == "fat" || fstype == "vfat" );
- switch (flag) {
- case SupportsChmod:
- case SupportsChown:
- case SupportsUTime:
- case SupportsSymlinks:
- return !isMsDos; // it's amazing the number of things FAT doesn't support :)
- case CaseInsensitive:
- return isMsDos;
- }
-#endif
- return false;
-}
-
-TDEIO::CacheControl TDEIO::parseCacheControl(const TQString &cacheControl)
-{
- TQString tmp = cacheControl.lower();
-
- if (tmp == "cacheonly")
- return TDEIO::CC_CacheOnly;
- if (tmp == "cache")
- return TDEIO::CC_Cache;
- if (tmp == "verify")
- return TDEIO::CC_Verify;
- if (tmp == "refresh")
- return TDEIO::CC_Refresh;
- if (tmp == "reload")
- return TDEIO::CC_Reload;
-
- kdDebug() << "unrecognized Cache control option:"<<cacheControl<<endl;
- return TDEIO::CC_Verify;
-}
-
-TQString TDEIO::getCacheControlString(TDEIO::CacheControl cacheControl)
-{
- if (cacheControl == TDEIO::CC_CacheOnly)
- return "CacheOnly";
- if (cacheControl == TDEIO::CC_Cache)
- return "Cache";
- if (cacheControl == TDEIO::CC_Verify)
- return "Verify";
- if (cacheControl == TDEIO::CC_Refresh)
- return "Refresh";
- if (cacheControl == TDEIO::CC_Reload)
- return "Reload";
- kdDebug() << "unrecognized Cache control enum value:"<<cacheControl<<endl;
- return TQString::null;
-}
diff --git a/kio/kio/job.cpp b/kio/kio/job.cpp
deleted file mode 100644
index d72eae574..000000000
--- a/kio/kio/job.cpp
+++ /dev/null
@@ -1,4814 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- David Faure <faure@kde.org>
- Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kio/job.h"
-
-#include <config.h>
-
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/stat.h>
-
-#include <assert.h>
-
-#include <signal.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <time.h>
-#include <unistd.h>
-extern "C" {
-#include <pwd.h>
-#include <grp.h>
-}
-#include <tqtimer.h>
-#include <tqfile.h>
-
-#include <kapplication.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <ksimpleconfig.h>
-#include <kdebug.h>
-#include <kdialog.h>
-#include <kmessagebox.h>
-#include <kdatastream.h>
-#include <kmainwindow.h>
-#include <kde_file.h>
-
-#include <errno.h>
-
-#include "kmimetype.h"
-#include "slave.h"
-#include "scheduler.h"
-#include "kdirwatch.h"
-#include "kmimemagic.h"
-#include "kprotocolinfo.h"
-#include "kprotocolmanager.h"
-
-#include "kio/observer.h"
-
-#include "kssl/ksslcsessioncache.h"
-
-#include <kdirnotify_stub.h>
-#include <ktempfile.h>
-#include <dcopclient.h>
-
-#ifdef Q_OS_UNIX
-#include <utime.h>
-#endif
-#if defined Q_WS_X11
-#include <netwm.h>
-#include <fixx11h.h>
-#endif
-
-using namespace TDEIO;
-template class TQPtrList<TDEIO::Job>;
-
-//this will update the report dialog with 5 Hz, I think this is fast enough, aleXXX
-#define REPORT_TIMEOUT 200
-
-#define KIO_ARGS TQByteArray packedArgs; TQDataStream stream( packedArgs, IO_WriteOnly ); stream
-
-class Job::JobPrivate
-{
-public:
- JobPrivate() : m_autoErrorHandling( false ), m_autoWarningHandling( true ),
- m_interactive( true ), m_parentJob( 0L ), m_extraFlags(0),
- m_processedSize(0), m_userTimestamp(0)
- {}
-
- bool m_autoErrorHandling;
- bool m_autoWarningHandling;
- bool m_interactive;
- TQGuardedPtr<TQWidget> m_errorParentWidget;
- // Maybe we could use the TQObject parent/child mechanism instead
- // (requires a new ctor, and moving the ctor code to some init()).
- Job* m_parentJob;
- int m_extraFlags;
- TDEIO::filesize_t m_processedSize;
- unsigned long m_userTimestamp;
-};
-
-Job::Job(bool showProgressInfo) : TQObject(0, "job"), m_error(0), m_percent(0)
- , m_progressId(0), m_speedTimer(0), d( new JobPrivate )
-{
- // All jobs delete themselves after emiting 'result'.
-
- // Notify the UI Server and get a progress id
- if ( showProgressInfo )
- {
- m_progressId = Observer::self()->newJob( this, true );
- addMetaData("progress-id", TQString::number(m_progressId));
- //kdDebug(7007) << "Created job " << this << " with progress info -- m_progressId=" << m_progressId << endl;
- // Connect global progress info signals
- connect( this, TQT_SIGNAL( percent( TDEIO::Job*, unsigned long ) ),
- Observer::self(), TQT_SLOT( slotPercent( TDEIO::Job*, unsigned long ) ) );
- connect( this, TQT_SIGNAL( infoMessage( TDEIO::Job*, const TQString & ) ),
- Observer::self(), TQT_SLOT( slotInfoMessage( TDEIO::Job*, const TQString & ) ) );
- connect( this, TQT_SIGNAL( totalSize( TDEIO::Job*, TDEIO::filesize_t ) ),
- Observer::self(), TQT_SLOT( slotTotalSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
- connect( this, TQT_SIGNAL( processedSize( TDEIO::Job*, TDEIO::filesize_t ) ),
- Observer::self(), TQT_SLOT( slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
- connect( this, TQT_SIGNAL( speed( TDEIO::Job*, unsigned long ) ),
- Observer::self(), TQT_SLOT( slotSpeed( TDEIO::Job*, unsigned long ) ) );
- }
- // Don't exit while this job is running
- if (kapp)
- kapp->ref();
- if (kapp)
- updateUserTimestamp( kapp->userTimestamp());
-}
-
-Job::~Job()
-{
- delete m_speedTimer;
- delete d;
- if (kapp)
- kapp->deref();
-}
-
-int& Job::extraFlags()
-{
- return d->m_extraFlags;
-}
-
-void Job::setProcessedSize(TDEIO::filesize_t size)
-{
- d->m_processedSize = size;
-}
-
-TDEIO::filesize_t Job::getProcessedSize()
-{
- return d->m_processedSize;
-}
-
-void Job::addSubjob(Job *job, bool inheritMetaData)
-{
- //kdDebug(7007) << "addSubjob(" << job << ") this = " << this << endl;
- subjobs.append(job);
-
- connect( job, TQT_SIGNAL(result(TDEIO::Job*)),
- TQT_SLOT(slotResult(TDEIO::Job*)) );
-
- // Forward information from that subjob.
- connect( job, TQT_SIGNAL(speed( TDEIO::Job*, unsigned long )),
- TQT_SLOT(slotSpeed(TDEIO::Job*, unsigned long)) );
-
- connect( job, TQT_SIGNAL(infoMessage( TDEIO::Job*, const TQString & )),
- TQT_SLOT(slotInfoMessage(TDEIO::Job*, const TQString &)) );
-
- if (inheritMetaData)
- job->mergeMetaData(m_outgoingMetaData);
-
- job->setWindow( m_window );
- job->updateUserTimestamp( d->m_userTimestamp );
-}
-
-void Job::removeSubjob( Job *job )
-{
- removeSubjob( job, false, true );
-}
-
-void Job::removeSubjob( Job *job, bool mergeMetaData, bool emitResultIfLast )
-{
- //kdDebug(7007) << "removeSubjob(" << job << ") this = " << this << " subjobs = " << subjobs.count() << endl;
- // Merge metadata from subjob
- if ( mergeMetaData )
- m_incomingMetaData += job->metaData();
- subjobs.remove(job);
- if ( subjobs.isEmpty() && emitResultIfLast )
- emitResult();
-}
-
-void Job::emitPercent( TDEIO::filesize_t processedSize, TDEIO::filesize_t totalSize )
-{
- // calculate percents
- unsigned long ipercent = m_percent;
-
- if ( totalSize == 0 )
- m_percent = 100;
- else
- m_percent = (unsigned long)(( (float)(processedSize) / (float)(totalSize) ) * 100.0);
-
- if ( m_percent != ipercent || m_percent == 100 /* for those buggy total sizes that grow */ ) {
- emit percent( this, m_percent );
- //kdDebug(7007) << "Job::emitPercent - percent = " << (unsigned int) m_percent << endl;
- }
-}
-
-void Job::emitSpeed( unsigned long bytes_per_second )
-{
- //kdDebug(7007) << "Job " << this << " emitSpeed " << bytes_per_second << endl;
- if ( !m_speedTimer )
- {
- m_speedTimer = new TQTimer();
- connect( m_speedTimer, TQT_SIGNAL( timeout() ), TQT_SLOT( slotSpeedTimeout() ) );
- }
- emit speed( this, bytes_per_second );
- m_speedTimer->start( 5000 ); // 5 seconds interval should be enough
-}
-
-void Job::emitResult()
-{
- // If we are displaying a progress dialog, remove it first.
- if ( m_progressId ) // Did we get an ID from the observer ?
- Observer::self()->jobFinished( m_progressId );
- if ( m_error && d->m_interactive && d->m_autoErrorHandling )
- showErrorDialog( d->m_errorParentWidget );
- emit result(this);
- deleteLater();
-}
-
-void Job::kill( bool quietly )
-{
- kdDebug(7007) << "Job::kill this=" << this << " " << className() << " m_progressId=" << m_progressId << " quietly=" << quietly << endl;
- // kill all subjobs, without triggering their result slot
- TQPtrListIterator<Job> it( subjobs );
- for ( ; it.current() ; ++it )
- (*it)->kill( true );
- subjobs.clear();
-
- if ( ! quietly ) {
- m_error = ERR_USER_CANCELED;
- emit canceled( this ); // Not very useful (deprecated)
- emitResult();
- } else
- {
- if ( m_progressId ) // in both cases we want to hide the progress window
- Observer::self()->jobFinished( m_progressId );
- deleteLater();
- }
-}
-
-void Job::slotResult( Job *job )
-{
- // Did job have an error ?
- if ( job->error() && !m_error )
- {
- // Store it in the parent only if first error
- m_error = job->error();
- m_errorText = job->errorText();
- }
- removeSubjob(job);
-}
-
-void Job::slotSpeed( TDEIO::Job*, unsigned long speed )
-{
- //kdDebug(7007) << "Job::slotSpeed " << speed << endl;
- emitSpeed( speed );
-}
-
-void Job::slotInfoMessage( TDEIO::Job*, const TQString & msg )
-{
- emit infoMessage( this, msg );
-}
-
-void Job::slotSpeedTimeout()
-{
- //kdDebug(7007) << "slotSpeedTimeout()" << endl;
- // send 0 and stop the timer
- // timer will be restarted only when we receive another speed event
- emit speed( this, 0 );
- m_speedTimer->stop();
-}
-
-//Job::errorString is implemented in global.cpp
-
-void Job::showErrorDialog( TQWidget * parent )
-{
- //kdDebug(7007) << "Job::showErrorDialog parent=" << parent << endl;
- kapp->enableStyles();
- // Show a message box, except for "user canceled" or "no content"
- if ( (m_error != ERR_USER_CANCELED) && (m_error != ERR_NO_CONTENT) ) {
- //old plain error message
- //kdDebug(7007) << "Default language: " << TDEGlobal::locale()->defaultLanguage() << endl;
- if ( 1 )
- KMessageBox::queuedMessageBox( parent, KMessageBox::Error, errorString() );
-#if 0
- } else {
- TQStringList errors = detailedErrorStrings();
- TQString caption, err, detail;
- TQStringList::const_iterator it = errors.begin();
- if ( it != errors.end() )
- caption = *(it++);
- if ( it != errors.end() )
- err = *(it++);
- if ( it != errors.end() )
- detail = *it;
- KMessageBox::queuedDetailedError( parent, err, detail, caption );
- }
-#endif
- }
-}
-
-void Job::setAutoErrorHandlingEnabled( bool enable, TQWidget *parentWidget )
-{
- d->m_autoErrorHandling = enable;
- d->m_errorParentWidget = parentWidget;
-}
-
-bool Job::isAutoErrorHandlingEnabled() const
-{
- return d->m_autoErrorHandling;
-}
-
-void Job::setAutoWarningHandlingEnabled( bool enable )
-{
- d->m_autoWarningHandling = enable;
-}
-
-bool Job::isAutoWarningHandlingEnabled() const
-{
- return d->m_autoWarningHandling;
-}
-
-void Job::setInteractive(bool enable)
-{
- d->m_interactive = enable;
-}
-
-bool Job::isInteractive() const
-{
- return d->m_interactive;
-}
-
-void Job::setWindow(TQWidget *window)
-{
- m_window = window;
- TDEIO::Scheduler::registerWindow(window);
-}
-
-TQWidget *Job::window() const
-{
- return m_window;
-}
-
-void Job::updateUserTimestamp( unsigned long time )
-{
-#if defined Q_WS_X11
- if( d->m_userTimestamp == 0 || NET::timestampCompare( time, d->m_userTimestamp ) > 0 )
- d->m_userTimestamp = time;
-#endif
-}
-
-unsigned long Job::userTimestamp() const
-{
- return d->m_userTimestamp;
-}
-
-void Job::setParentJob(Job* job)
-{
- Q_ASSERT(d->m_parentJob == 0L);
- Q_ASSERT(job);
- d->m_parentJob = job;
-}
-
-Job* Job::parentJob() const
-{
- return d->m_parentJob;
-}
-
-MetaData Job::metaData() const
-{
- return m_incomingMetaData;
-}
-
-TQString Job::queryMetaData(const TQString &key)
-{
- if (!m_incomingMetaData.contains(key))
- return TQString::null;
- return m_incomingMetaData[key];
-}
-
-void Job::setMetaData( const TDEIO::MetaData &_metaData)
-{
- m_outgoingMetaData = _metaData;
-}
-
-void Job::addMetaData( const TQString &key, const TQString &value)
-{
- m_outgoingMetaData.insert(key, value);
-}
-
-void Job::addMetaData( const TQMap<TQString,TQString> &values)
-{
- TQMapConstIterator<TQString,TQString> it = values.begin();
- for(;it != values.end(); ++it)
- m_outgoingMetaData.insert(it.key(), it.data());
-}
-
-void Job::mergeMetaData( const TQMap<TQString,TQString> &values)
-{
- TQMapConstIterator<TQString,TQString> it = values.begin();
- for(;it != values.end(); ++it)
- m_outgoingMetaData.insert(it.key(), it.data(), false);
-}
-
-MetaData Job::outgoingMetaData() const
-{
- return m_outgoingMetaData;
-}
-
-
-SimpleJob::SimpleJob(const KURL& url, int command, const TQByteArray &packedArgs,
- bool showProgressInfo )
- : Job(showProgressInfo), m_slave(0), m_packedArgs(packedArgs),
- m_url(url), m_command(command), m_totalSize(0)
-{
- if (m_url.hasSubURL())
- {
- KURL::List list = KURL::split(m_url);
- KURL::List::Iterator it = list.fromLast();
- list.remove(it);
- m_subUrl = KURL::join(list);
- //kdDebug(7007) << "New URL = " << m_url.url() << endl;
- //kdDebug(7007) << "Sub URL = " << m_subUrl.url() << endl;
- }
-
- Scheduler::doJob(this);
-
- if (!m_url.isValid())
- {
- kdDebug() << "ERR_MALFORMED_URL" << endl;
- m_error = ERR_MALFORMED_URL;
- m_errorText = m_url.url();
- TQTimer::singleShot(0, this, TQT_SLOT(slotFinished()) );
- return;
- }
-}
-
-void SimpleJob::kill( bool quietly )
-{
- Scheduler::cancelJob( this ); // deletes the slave if not 0
- m_slave = 0; // -> set to 0
- Job::kill( quietly );
-}
-
-void SimpleJob::putOnHold()
-{
- Q_ASSERT( m_slave );
- if ( m_slave )
- {
- Scheduler::putSlaveOnHold(this, m_url);
- m_slave = 0;
- }
- kill(true);
-}
-
-void SimpleJob::removeOnHold()
-{
- Scheduler::removeSlaveOnHold();
-}
-
-SimpleJob::~SimpleJob()
-{
- if (m_slave) // was running
- {
- kdDebug(7007) << "SimpleJob::~SimpleJob: Killing running job in destructor!" << endl;
-#if 0
- m_slave->kill();
- Scheduler::jobFinished( this, m_slave ); // deletes the slave
-#endif
- Scheduler::cancelJob( this );
- m_slave = 0; // -> set to 0
- }
-}
-
-void SimpleJob::start(Slave *slave)
-{
- m_slave = slave;
-
- connect( m_slave, TQT_SIGNAL( error( int , const TQString & ) ),
- TQT_SLOT( slotError( int , const TQString & ) ) );
-
- connect( m_slave, TQT_SIGNAL( warning( const TQString & ) ),
- TQT_SLOT( slotWarning( const TQString & ) ) );
-
- connect( m_slave, TQT_SIGNAL( infoMessage( const TQString & ) ),
- TQT_SLOT( slotInfoMessage( const TQString & ) ) );
-
- connect( m_slave, TQT_SIGNAL( connected() ),
- TQT_SLOT( slotConnected() ) );
-
- connect( m_slave, TQT_SIGNAL( finished() ),
- TQT_SLOT( slotFinished() ) );
-
- if ((extraFlags() & EF_TransferJobDataSent) == 0)
- {
- connect( m_slave, TQT_SIGNAL( totalSize( TDEIO::filesize_t ) ),
- TQT_SLOT( slotTotalSize( TDEIO::filesize_t ) ) );
-
- connect( m_slave, TQT_SIGNAL( processedSize( TDEIO::filesize_t ) ),
- TQT_SLOT( slotProcessedSize( TDEIO::filesize_t ) ) );
-
- connect( m_slave, TQT_SIGNAL( speed( unsigned long ) ),
- TQT_SLOT( slotSpeed( unsigned long ) ) );
- }
-
- connect( slave, TQT_SIGNAL( needProgressId() ),
- TQT_SLOT( slotNeedProgressId() ) );
-
- connect( slave, TQT_SIGNAL(metaData( const TDEIO::MetaData& ) ),
- TQT_SLOT( slotMetaData( const TDEIO::MetaData& ) ) );
-
- if (m_window)
- {
- TQString id;
- addMetaData("window-id", id.setNum((ulong)m_window->winId()));
- }
- if (userTimestamp())
- {
- TQString id;
- addMetaData("user-timestamp", id.setNum(userTimestamp()));
- }
-
- TQString sslSession = KSSLCSessionCache::getSessionForURL(m_url);
- if ( !sslSession.isNull() )
- {
- addMetaData("ssl_session_id", sslSession);
- }
-
- if (!isInteractive())
- {
- addMetaData("no-auth-prompt", "true");
- }
-
- if (!m_outgoingMetaData.isEmpty())
- {
- KIO_ARGS << m_outgoingMetaData;
- slave->send( CMD_META_DATA, packedArgs );
- }
-
- if (!m_subUrl.isEmpty())
- {
- KIO_ARGS << m_subUrl;
- m_slave->send( CMD_SUBURL, packedArgs );
- }
-
- m_slave->send( m_command, m_packedArgs );
-}
-
-void SimpleJob::slaveDone()
-{
- if (!m_slave) return;
- disconnect(m_slave); // Remove all signals between slave and job
- Scheduler::jobFinished( this, m_slave );
- m_slave = 0;
-}
-
-void SimpleJob::slotFinished( )
-{
- // Return slave to the scheduler
- slaveDone();
-
- if (subjobs.isEmpty())
- {
- if ( !m_error && (m_command == CMD_MKDIR || m_command == CMD_RENAME ) )
- {
- KDirNotify_stub allDirNotify( "*", "KDirNotify*" );
- if ( m_command == CMD_MKDIR )
- {
- KURL urlDir( url() );
- urlDir.setPath( urlDir.directory() );
- allDirNotify.FilesAdded( urlDir );
- }
- else /*if ( m_command == CMD_RENAME )*/
- {
- KURL src, dst;
- TQDataStream str( m_packedArgs, IO_ReadOnly );
- str >> src >> dst;
- if ( src.directory() == dst.directory() ) // For the user, moving isn't renaming. Only renaming is.
- allDirNotify.FileRenamed( src, dst );
- }
- }
- emitResult();
- }
-}
-
-void SimpleJob::slotError( int error, const TQString & errorText )
-{
- m_error = error;
- m_errorText = errorText;
- if ((m_error == ERR_UNKNOWN_HOST) && m_url.host().isEmpty())
- m_errorText = TQString::null;
- // error terminates the job
- slotFinished();
-}
-
-void SimpleJob::slotWarning( const TQString & errorText )
-{
- TQGuardedPtr<SimpleJob> guard( this );
- if (isInteractive() && isAutoWarningHandlingEnabled())
- {
- static uint msgBoxDisplayed = 0;
- if ( msgBoxDisplayed == 0 ) // don't bomb the user with message boxes, only one at a time
- {
- msgBoxDisplayed++;
- KMessageBox::information( 0L, errorText );
- msgBoxDisplayed--;
- }
- // otherwise just discard it.
- }
-
- if ( !guard.isNull() )
- emit warning( this, errorText );
-}
-
-void SimpleJob::slotInfoMessage( const TQString & msg )
-{
- emit infoMessage( this, msg );
-}
-
-void SimpleJob::slotConnected()
-{
- emit connected( this );
-}
-
-void SimpleJob::slotNeedProgressId()
-{
- if ( !m_progressId )
- m_progressId = Observer::self()->newJob( this, false );
- m_slave->setProgressId( m_progressId );
-}
-
-void SimpleJob::slotTotalSize( TDEIO::filesize_t size )
-{
- if (size > m_totalSize)
- {
- m_totalSize = size;
- emit totalSize( this, size );
- }
-}
-
-void SimpleJob::slotProcessedSize( TDEIO::filesize_t size )
-{
- //kdDebug(7007) << "SimpleJob::slotProcessedSize " << TDEIO::number(size) << endl;
- setProcessedSize(size);
- emit processedSize( this, size );
- if ( size > m_totalSize ) {
- slotTotalSize(size); // safety
- }
- emitPercent( size, m_totalSize );
-}
-
-void SimpleJob::slotSpeed( unsigned long speed )
-{
- //kdDebug(7007) << "SimpleJob::slotSpeed( " << speed << " )" << endl;
- emitSpeed( speed );
-}
-
-void SimpleJob::slotMetaData( const TDEIO::MetaData &_metaData)
-{
- m_incomingMetaData += _metaData;
-}
-
-void SimpleJob::storeSSLSessionFromJob(const KURL &m_redirectionURL) {
- TQString sslSession = queryMetaData("ssl_session_id");
-
- if ( !sslSession.isNull() ) {
- const KURL &queryURL = m_redirectionURL.isEmpty()?m_url:m_redirectionURL;
- KSSLCSessionCache::putSessionForURL(queryURL, sslSession);
- }
-}
-
-//////////
-MkdirJob::MkdirJob( const KURL& url, int command,
- const TQByteArray &packedArgs, bool showProgressInfo )
- : SimpleJob(url, command, packedArgs, showProgressInfo)
-{
-}
-
-void MkdirJob::start(Slave *slave)
-{
- connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
- TQT_SLOT( slotRedirection(const KURL &) ) );
-
- SimpleJob::start(slave);
-}
-
-// Slave got a redirection request
-void MkdirJob::slotRedirection( const KURL &url)
-{
- kdDebug(7007) << "MkdirJob::slotRedirection(" << url << ")" << endl;
- if (!kapp->authorizeURLAction("redirect", m_url, url))
- {
- kdWarning(7007) << "MkdirJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
- m_error = ERR_ACCESS_DENIED;
- m_errorText = url.prettyURL();
- return;
- }
- m_redirectionURL = url; // We'll remember that when the job finishes
- if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
- m_redirectionURL.setUser(m_url.user()); // Preserve user
- // Tell the user that we haven't finished yet
- emit redirection(this, m_redirectionURL);
-}
-
-void MkdirJob::slotFinished()
-{
- if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
- {
- // Return slave to the scheduler
- SimpleJob::slotFinished();
- } else {
- //kdDebug(7007) << "MkdirJob: Redirection to " << m_redirectionURL << endl;
- if (queryMetaData("permanent-redirect")=="true")
- emit permanentRedirection(this, m_url, m_redirectionURL);
- KURL dummyUrl;
- int permissions;
- TQDataStream istream( m_packedArgs, IO_ReadOnly );
- istream >> dummyUrl >> permissions;
-
- m_url = m_redirectionURL;
- m_redirectionURL = KURL();
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << m_url << permissions;
-
- // Return slave to the scheduler
- slaveDone();
- Scheduler::doJob(this);
- }
-}
-
-SimpleJob *TDEIO::mkdir( const KURL& url, int permissions )
-{
- //kdDebug(7007) << "mkdir " << url << endl;
- KIO_ARGS << url << permissions;
- return new MkdirJob(url, CMD_MKDIR, packedArgs, false);
-}
-
-SimpleJob *TDEIO::rmdir( const KURL& url )
-{
- //kdDebug(7007) << "rmdir " << url << endl;
- KIO_ARGS << url << TQ_INT8(false); // isFile is false
- return new SimpleJob(url, CMD_DEL, packedArgs, false);
-}
-
-SimpleJob *TDEIO::chmod( const KURL& url, int permissions )
-{
- //kdDebug(7007) << "chmod " << url << endl;
- KIO_ARGS << url << permissions;
- return new SimpleJob(url, CMD_CHMOD, packedArgs, false);
-}
-
-SimpleJob *TDEIO::rename( const KURL& src, const KURL & dest, bool overwrite )
-{
- //kdDebug(7007) << "rename " << src << " " << dest << endl;
- KIO_ARGS << src << dest << (TQ_INT8) overwrite;
- return new SimpleJob(src, CMD_RENAME, packedArgs, false);
-}
-
-SimpleJob *TDEIO::symlink( const TQString& target, const KURL & dest, bool overwrite, bool showProgressInfo )
-{
- //kdDebug(7007) << "symlink target=" << target << " " << dest << endl;
- KIO_ARGS << target << dest << (TQ_INT8) overwrite;
- return new SimpleJob(dest, CMD_SYMLINK, packedArgs, showProgressInfo);
-}
-
-SimpleJob *TDEIO::special(const KURL& url, const TQByteArray & data, bool showProgressInfo)
-{
- //kdDebug(7007) << "special " << url << endl;
- return new SimpleJob(url, CMD_SPECIAL, data, showProgressInfo);
-}
-
-SimpleJob *TDEIO::mount( bool ro, const char *fstype, const TQString& dev, const TQString& point, bool showProgressInfo )
-{
- KIO_ARGS << int(1) << TQ_INT8( ro ? 1 : 0 )
- << TQString::fromLatin1(fstype) << dev << point;
- SimpleJob *job = special( KURL("file:/"), packedArgs, showProgressInfo );
- if ( showProgressInfo )
- Observer::self()->mounting( job, dev, point );
- return job;
-}
-
-SimpleJob *TDEIO::unmount( const TQString& point, bool showProgressInfo )
-{
- KIO_ARGS << int(2) << point;
- SimpleJob *job = special( KURL("file:/"), packedArgs, showProgressInfo );
- if ( showProgressInfo )
- Observer::self()->unmounting( job, point );
- return job;
-}
-
-//////////
-LocalURLJob::LocalURLJob( const KURL& url, int command,
- const TQByteArray &packedArgs, bool showProgressInfo )
- : SimpleJob(url, command, packedArgs, showProgressInfo)
-{
-
-}
-
-void LocalURLJob::start(Slave *slave)
-{
- connect( slave, TQT_SIGNAL( localURL(const KURL &, bool) ),
- TQT_SLOT( slotLocalURL(const KURL &, bool) ) );
-
- SimpleJob::start(slave);
-}
-
-// Slave sent a response!
-void LocalURLJob::slotLocalURL(const KURL &url, bool isLocal)
-{
- kdDebug(7007) << "LocalURLJob::slotLocalURL(" << url << ")" << endl;
- emit localURL(this, url, isLocal);
-}
-
-void LocalURLJob::slotFinished()
-{
- // Return slave to the scheduler
- SimpleJob::slotFinished();
-}
-
-LocalURLJob *TDEIO::localURL( const KURL& remoteUrl )
-{
- KIO_ARGS << remoteUrl;
- return new LocalURLJob(remoteUrl, CMD_LOCALURL, packedArgs, false);
-}
-
-
-//////////
-
-StatJob::StatJob( const KURL& url, int command,
- const TQByteArray &packedArgs, bool showProgressInfo )
- : SimpleJob(url, command, packedArgs, showProgressInfo),
- m_bSource(true), m_details(2)
-{
-}
-
-void StatJob::start(Slave *slave)
-{
- m_outgoingMetaData.replace( "statSide", m_bSource ? "source" : "dest" );
- m_outgoingMetaData.replace( "details", TQString::number(m_details) );
-
- connect( slave, TQT_SIGNAL( statEntry( const TDEIO::UDSEntry& ) ),
- TQT_SLOT( slotStatEntry( const TDEIO::UDSEntry & ) ) );
- connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
- TQT_SLOT( slotRedirection(const KURL &) ) );
-
- SimpleJob::start(slave);
-}
-
-void StatJob::slotStatEntry( const TDEIO::UDSEntry & entry )
-{
- //kdDebug(7007) << "StatJob::slotStatEntry" << endl;
- m_statResult = entry;
-}
-
-// Slave got a redirection request
-void StatJob::slotRedirection( const KURL &url)
-{
- kdDebug(7007) << "StatJob::slotRedirection(" << url << ")" << endl;
- if (!kapp->authorizeURLAction("redirect", m_url, url))
- {
- kdWarning(7007) << "StatJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
- m_error = ERR_ACCESS_DENIED;
- m_errorText = url.prettyURL();
- return;
- }
- m_redirectionURL = url; // We'll remember that when the job finishes
- if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
- m_redirectionURL.setUser(m_url.user()); // Preserve user
- // Tell the user that we haven't finished yet
- emit redirection(this, m_redirectionURL);
-}
-
-void StatJob::slotFinished()
-{
- if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
- {
- // Return slave to the scheduler
- SimpleJob::slotFinished();
- } else {
- //kdDebug(7007) << "StatJob: Redirection to " << m_redirectionURL << endl;
- if (queryMetaData("permanent-redirect")=="true")
- emit permanentRedirection(this, m_url, m_redirectionURL);
- m_url = m_redirectionURL;
- m_redirectionURL = KURL();
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << m_url;
-
- // Return slave to the scheduler
- slaveDone();
- Scheduler::doJob(this);
- }
-}
-
-void StatJob::slotMetaData( const TDEIO::MetaData &_metaData) {
- SimpleJob::slotMetaData(_metaData);
- storeSSLSessionFromJob(m_redirectionURL);
-}
-
-StatJob *TDEIO::stat(const KURL& url, bool showProgressInfo)
-{
- // Assume sideIsSource. Gets are more common than puts.
- return stat( url, true, 2, showProgressInfo );
-}
-
-StatJob *TDEIO::stat(const KURL& url, bool sideIsSource, short int details, bool showProgressInfo)
-{
- kdDebug(7007) << "stat " << url << endl;
- KIO_ARGS << url;
- StatJob * job = new StatJob(url, CMD_STAT, packedArgs, showProgressInfo );
- job->setSide( sideIsSource );
- job->setDetails( details );
- if ( showProgressInfo )
- Observer::self()->stating( job, url );
- return job;
-}
-
-SimpleJob *TDEIO::http_update_cache( const KURL& url, bool no_cache, time_t expireDate)
-{
- assert( (url.protocol() == "http") || (url.protocol() == "https") );
- // Send http update_cache command (2)
- KIO_ARGS << (int)2 << url << no_cache << expireDate;
- SimpleJob * job = new SimpleJob( url, CMD_SPECIAL, packedArgs, false );
- Scheduler::scheduleJob(job);
- return job;
-}
-
-//////////
-
-TransferJob::TransferJob( const KURL& url, int command,
- const TQByteArray &packedArgs,
- const TQByteArray &_staticData,
- bool showProgressInfo)
- : SimpleJob(url, command, packedArgs, showProgressInfo), staticData( _staticData)
-{
- m_suspended = false;
- m_errorPage = false;
- m_subJob = 0L;
- if ( showProgressInfo )
- Observer::self()->slotTransferring( this, url );
-}
-
-// Slave sends data
-void TransferJob::slotData( const TQByteArray &_data)
-{
- if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error)
- emit data( this, _data);
-}
-
-// Slave got a redirection request
-void TransferJob::slotRedirection( const KURL &url)
-{
- kdDebug(7007) << "TransferJob::slotRedirection(" << url << ")" << endl;
- if (!kapp->authorizeURLAction("redirect", m_url, url))
- {
- kdWarning(7007) << "TransferJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
- return;
- }
-
- // Some websites keep redirecting to themselves where each redirection
- // acts as the stage in a state-machine. We define "endless redirections"
- // as 5 redirections to the same URL.
- if (m_redirectionList.contains(url) > 5)
- {
- kdDebug(7007) << "TransferJob::slotRedirection: CYCLIC REDIRECTION!" << endl;
- m_error = ERR_CYCLIC_LINK;
- m_errorText = m_url.prettyURL();
- }
- else
- {
- m_redirectionURL = url; // We'll remember that when the job finishes
- if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
- m_redirectionURL.setUser(m_url.user()); // Preserve user
- m_redirectionList.append(url);
- m_outgoingMetaData["ssl_was_in_use"] = m_incomingMetaData["ssl_in_use"];
- // Tell the user that we haven't finished yet
- emit redirection(this, m_redirectionURL);
- }
-}
-
-void TransferJob::slotFinished()
-{
- //kdDebug(7007) << "TransferJob::slotFinished(" << this << ", " << m_url << ")" << endl;
- if (m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
- SimpleJob::slotFinished();
- else {
- //kdDebug(7007) << "TransferJob: Redirection to " << m_redirectionURL << endl;
- if (queryMetaData("permanent-redirect")=="true")
- emit permanentRedirection(this, m_url, m_redirectionURL);
- // Honour the redirection
- // We take the approach of "redirecting this same job"
- // Another solution would be to create a subjob, but the same problem
- // happens (unpacking+repacking)
- staticData.truncate(0);
- m_incomingMetaData.clear();
- if (queryMetaData("cache") != "reload")
- addMetaData("cache","refresh");
- m_suspended = false;
- m_url = m_redirectionURL;
- m_redirectionURL = KURL();
- // The very tricky part is the packed arguments business
- TQString dummyStr;
- KURL dummyUrl;
- TQDataStream istream( m_packedArgs, IO_ReadOnly );
- switch( m_command ) {
- case CMD_GET: {
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << m_url;
- break;
- }
- case CMD_PUT: {
- int permissions;
- TQ_INT8 iOverwrite, iResume;
- istream >> dummyUrl >> iOverwrite >> iResume >> permissions;
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << m_url << iOverwrite << iResume << permissions;
- break;
- }
- case CMD_SPECIAL: {
- int specialcmd;
- istream >> specialcmd;
- if (specialcmd == 1) // HTTP POST
- {
- addMetaData("cache","reload");
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << m_url;
- m_command = CMD_GET;
- }
- break;
- }
- }
-
- // Return slave to the scheduler
- slaveDone();
- Scheduler::doJob(this);
- }
-}
-
-void TransferJob::setAsyncDataEnabled(bool enabled)
-{
- if (enabled)
- extraFlags() |= EF_TransferJobAsync;
- else
- extraFlags() &= ~EF_TransferJobAsync;
-}
-
-void TransferJob::sendAsyncData(const TQByteArray &dataForSlave)
-{
- if (extraFlags() & EF_TransferJobNeedData)
- {
- m_slave->send( MSG_DATA, dataForSlave );
- if (extraFlags() & EF_TransferJobDataSent)
- {
- TDEIO::filesize_t size = getProcessedSize()+dataForSlave.size();
- setProcessedSize(size);
- emit processedSize( this, size );
- if ( size > m_totalSize ) {
- slotTotalSize(size); // safety
- }
- emitPercent( size, m_totalSize );
- }
- }
-
- extraFlags() &= ~EF_TransferJobNeedData;
-}
-
-void TransferJob::setReportDataSent(bool enabled)
-{
- if (enabled)
- extraFlags() |= EF_TransferJobDataSent;
- else
- extraFlags() &= ~EF_TransferJobDataSent;
-}
-
-bool TransferJob::reportDataSent()
-{
- return (extraFlags() & EF_TransferJobDataSent);
-}
-
-
-// Slave requests data
-void TransferJob::slotDataReq()
-{
- TQByteArray dataForSlave;
-
- extraFlags() |= EF_TransferJobNeedData;
-
- if (!staticData.isEmpty())
- {
- dataForSlave = staticData;
- staticData = TQByteArray();
- }
- else
- {
- emit dataReq( this, dataForSlave);
-
- if (extraFlags() & EF_TransferJobAsync)
- return;
- }
-
- static const size_t max_size = 14 * 1024 * 1024;
- if (dataForSlave.size() > max_size)
- {
- kdDebug(7007) << "send " << dataForSlave.size() / 1024 / 1024 << "MB of data in TransferJob::dataReq. This needs to be splitted, which requires a copy. Fix the application.\n";
- staticData.duplicate(dataForSlave.data() + max_size , dataForSlave.size() - max_size);
- dataForSlave.truncate(max_size);
- }
-
- sendAsyncData(dataForSlave);
-
- if (m_subJob)
- {
- // Bitburger protocol in action
- suspend(); // Wait for more data from subJob.
- m_subJob->resume(); // Ask for more!
- }
-}
-
-void TransferJob::slotMimetype( const TQString& type )
-{
- m_mimetype = type;
- emit mimetype( this, m_mimetype);
-}
-
-
-void TransferJob::suspend()
-{
- m_suspended = true;
- if (m_slave)
- m_slave->suspend();
-}
-
-void TransferJob::resume()
-{
- m_suspended = false;
- if (m_slave)
- m_slave->resume();
-}
-
-void TransferJob::start(Slave *slave)
-{
- assert(slave);
- connect( slave, TQT_SIGNAL( data( const TQByteArray & ) ),
- TQT_SLOT( slotData( const TQByteArray & ) ) );
-
- connect( slave, TQT_SIGNAL( dataReq() ),
- TQT_SLOT( slotDataReq() ) );
-
- connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
- TQT_SLOT( slotRedirection(const KURL &) ) );
-
- connect( slave, TQT_SIGNAL(mimeType( const TQString& ) ),
- TQT_SLOT( slotMimetype( const TQString& ) ) );
-
- connect( slave, TQT_SIGNAL(errorPage() ),
- TQT_SLOT( slotErrorPage() ) );
-
- connect( slave, TQT_SIGNAL( needSubURLData() ),
- TQT_SLOT( slotNeedSubURLData() ) );
-
- connect( slave, TQT_SIGNAL(canResume( TDEIO::filesize_t ) ),
- TQT_SLOT( slotCanResume( TDEIO::filesize_t ) ) );
-
- if (slave->suspended())
- {
- m_mimetype = "unknown";
- // WABA: The slave was put on hold. Resume operation.
- slave->resume();
- }
-
- SimpleJob::start(slave);
- if (m_suspended)
- slave->suspend();
-}
-
-void TransferJob::slotNeedSubURLData()
-{
- // Job needs data from subURL.
- m_subJob = TDEIO::get( m_subUrl, false, false);
- suspend(); // Put job on hold until we have some data.
- connect(m_subJob, TQT_SIGNAL( data(TDEIO::Job*,const TQByteArray &)),
- TQT_SLOT( slotSubURLData(TDEIO::Job*,const TQByteArray &)));
- addSubjob(m_subJob);
-}
-
-void TransferJob::slotSubURLData(TDEIO::Job*, const TQByteArray &data)
-{
- // The Alternating Bitburg protocol in action again.
- staticData = data;
- m_subJob->suspend(); // Put job on hold until we have delivered the data.
- resume(); // Activate ourselves again.
-}
-
-void TransferJob::slotMetaData( const TDEIO::MetaData &_metaData) {
- SimpleJob::slotMetaData(_metaData);
- storeSSLSessionFromJob(m_redirectionURL);
-}
-
-void TransferJob::slotErrorPage()
-{
- m_errorPage = true;
-}
-
-void TransferJob::slotCanResume( TDEIO::filesize_t offset )
-{
- emit canResume(this, offset);
-}
-
-void TransferJob::slotResult( TDEIO::Job *job)
-{
- // This can only be our suburl.
- assert(job == m_subJob);
- // Did job have an error ?
- if ( job->error() )
- {
- m_error = job->error();
- m_errorText = job->errorText();
-
- emitResult();
- return;
- }
-
- if (job == m_subJob)
- {
- m_subJob = 0; // No action required
- resume(); // Make sure we get the remaining data.
- }
- removeSubjob( job, false, false ); // Remove job, but don't kill this job.
-}
-
-TransferJob *TDEIO::get( const KURL& url, bool reload, bool showProgressInfo )
-{
- // Send decoded path and encoded query
- KIO_ARGS << url;
- TransferJob * job = new TransferJob( url, CMD_GET, packedArgs, TQByteArray(), showProgressInfo );
- if (reload)
- job->addMetaData("cache", "reload");
- return job;
-}
-
-class PostErrorJob : public TransferJob
-{
-public:
-
- PostErrorJob(int _error, const TQString& url, const TQByteArray &packedArgs, const TQByteArray &postData, bool showProgressInfo)
- : TransferJob(KURL(), CMD_SPECIAL, packedArgs, postData, showProgressInfo)
- {
- m_error = _error;
- m_errorText = url;
- }
-
-};
-
-TransferJob *TDEIO::http_post( const KURL& url, const TQByteArray &postData, bool showProgressInfo )
-{
- int _error = 0;
-
- // filter out some malicious ports
- static const int bad_ports[] = {
- 1, // tcpmux
- 7, // echo
- 9, // discard
- 11, // systat
- 13, // daytime
- 15, // netstat
- 17, // qotd
- 19, // chargen
- 20, // ftp-data
- 21, // ftp-cntl
- 22, // ssh
- 23, // telnet
- 25, // smtp
- 37, // time
- 42, // name
- 43, // nicname
- 53, // domain
- 77, // priv-rjs
- 79, // finger
- 87, // ttylink
- 95, // supdup
- 101, // hostriame
- 102, // iso-tsap
- 103, // gppitnp
- 104, // acr-nema
- 109, // pop2
- 110, // pop3
- 111, // sunrpc
- 113, // auth
- 115, // sftp
- 117, // uucp-path
- 119, // nntp
- 123, // NTP
- 135, // loc-srv / epmap
- 139, // netbios
- 143, // imap2
- 179, // BGP
- 389, // ldap
- 512, // print / exec
- 513, // login
- 514, // shell
- 515, // printer
- 526, // tempo
- 530, // courier
- 531, // Chat
- 532, // netnews
- 540, // uucp
- 556, // remotefs
- 587, // sendmail
- 601, //
- 989, // ftps data
- 990, // ftps
- 992, // telnets
- 993, // imap/SSL
- 995, // pop3/SSL
- 1080, // SOCKS
- 2049, // nfs
- 4045, // lockd
- 6000, // x11
- 6667, // irc
- 0};
- for (int cnt=0; bad_ports[cnt]; ++cnt)
- if (url.port() == bad_ports[cnt])
- {
- _error = TDEIO::ERR_POST_DENIED;
- break;
- }
-
- if( _error )
- {
- static bool override_loaded = false;
- static TQValueList< int >* overriden_ports = NULL;
- if( !override_loaded )
- {
- TDEConfig cfg( "kio_httprc", true );
- overriden_ports = new TQValueList< int >;
- *overriden_ports = cfg.readIntListEntry( "OverriddenPorts" );
- override_loaded = true;
- }
- for( TQValueList< int >::ConstIterator it = overriden_ports->begin();
- it != overriden_ports->end();
- ++it )
- if( overriden_ports->contains( url.port()))
- _error = 0;
- }
-
- // filter out non https? protocols
- if ((url.protocol() != "http") && (url.protocol() != "https" ))
- _error = TDEIO::ERR_POST_DENIED;
-
- bool redirection = false;
- KURL _url(url);
- if (_url.path().isEmpty())
- {
- redirection = true;
- _url.setPath("/");
- }
-
- if (!_error && !kapp->authorizeURLAction("open", KURL(), _url))
- _error = TDEIO::ERR_ACCESS_DENIED;
-
- // if request is not valid, return an invalid transfer job
- if (_error)
- {
- KIO_ARGS << (int)1 << url;
- TransferJob * job = new PostErrorJob(_error, url.prettyURL(), packedArgs, postData, showProgressInfo);
- return job;
- }
-
- // Send http post command (1), decoded path and encoded query
- KIO_ARGS << (int)1 << _url;
- TransferJob * job = new TransferJob( _url, CMD_SPECIAL,
- packedArgs, postData, showProgressInfo );
-
- if (redirection)
- TQTimer::singleShot(0, job, TQT_SLOT(slotPostRedirection()) );
-
- return job;
-}
-
-// http post got redirected from http://host to http://host/ by TransferJob
-// We must do this redirection ourselves because redirections by the
-// slave change post jobs into get jobs.
-void TransferJob::slotPostRedirection()
-{
- kdDebug(7007) << "TransferJob::slotPostRedirection(" << m_url << ")" << endl;
- // Tell the user about the new url.
- emit redirection(this, m_url);
-}
-
-
-TransferJob *TDEIO::put( const KURL& url, int permissions,
- bool overwrite, bool resume, bool showProgressInfo )
-{
- KIO_ARGS << url << TQ_INT8( overwrite ? 1 : 0 ) << TQ_INT8( resume ? 1 : 0 ) << permissions;
- TransferJob * job = new TransferJob( url, CMD_PUT, packedArgs, TQByteArray(), showProgressInfo );
- return job;
-}
-
-//////////
-
-StoredTransferJob::StoredTransferJob(const KURL& url, int command,
- const TQByteArray &packedArgs,
- const TQByteArray &_staticData,
- bool showProgressInfo)
- : TransferJob( url, command, packedArgs, _staticData, showProgressInfo ),
- m_uploadOffset( 0 )
-{
- connect( this, TQT_SIGNAL( data( TDEIO::Job *, const TQByteArray & ) ),
- TQT_SLOT( slotStoredData( TDEIO::Job *, const TQByteArray & ) ) );
- connect( this, TQT_SIGNAL( dataReq( TDEIO::Job *, TQByteArray & ) ),
- TQT_SLOT( slotStoredDataReq( TDEIO::Job *, TQByteArray & ) ) );
-}
-
-void StoredTransferJob::setData( const TQByteArray& arr )
-{
- Q_ASSERT( m_data.isNull() ); // check that we're only called once
- Q_ASSERT( m_uploadOffset == 0 ); // no upload started yet
- m_data = arr;
-}
-
-void StoredTransferJob::slotStoredData( TDEIO::Job *, const TQByteArray &data )
-{
- // check for end-of-data marker:
- if ( data.size() == 0 )
- return;
- unsigned int oldSize = m_data.size();
- m_data.resize( oldSize + data.size(), TQGArray::SpeedOptim );
- memcpy( m_data.data() + oldSize, data.data(), data.size() );
-}
-
-void StoredTransferJob::slotStoredDataReq( TDEIO::Job *, TQByteArray &data )
-{
- // Inspired from kmail's KMKernel::byteArrayToRemoteFile
- // send the data in 64 KB chunks
- const int MAX_CHUNK_SIZE = 64*1024;
- int remainingBytes = m_data.size() - m_uploadOffset;
- if( remainingBytes > MAX_CHUNK_SIZE ) {
- // send MAX_CHUNK_SIZE bytes to the receiver (deep copy)
- data.duplicate( m_data.data() + m_uploadOffset, MAX_CHUNK_SIZE );
- m_uploadOffset += MAX_CHUNK_SIZE;
- //kdDebug() << "Sending " << MAX_CHUNK_SIZE << " bytes ("
- // << remainingBytes - MAX_CHUNK_SIZE << " bytes remain)\n";
- } else {
- // send the remaining bytes to the receiver (deep copy)
- data.duplicate( m_data.data() + m_uploadOffset, remainingBytes );
- m_data = TQByteArray();
- m_uploadOffset = 0;
- //kdDebug() << "Sending " << remainingBytes << " bytes\n";
- }
-}
-
-StoredTransferJob *TDEIO::storedGet( const KURL& url, bool reload, bool showProgressInfo )
-{
- // Send decoded path and encoded query
- KIO_ARGS << url;
- StoredTransferJob * job = new StoredTransferJob( url, CMD_GET, packedArgs, TQByteArray(), showProgressInfo );
- if (reload)
- job->addMetaData("cache", "reload");
- return job;
-}
-
-StoredTransferJob *TDEIO::storedPut( const TQByteArray& arr, const KURL& url, int permissions,
- bool overwrite, bool resume, bool showProgressInfo )
-{
- KIO_ARGS << url << TQ_INT8( overwrite ? 1 : 0 ) << TQ_INT8( resume ? 1 : 0 ) << permissions;
- StoredTransferJob * job = new StoredTransferJob( url, CMD_PUT, packedArgs, TQByteArray(), showProgressInfo );
- job->setData( arr );
- return job;
-}
-
-//////////
-
-MimetypeJob::MimetypeJob( const KURL& url, int command,
- const TQByteArray &packedArgs, bool showProgressInfo )
- : TransferJob(url, command, packedArgs, TQByteArray(), showProgressInfo)
-{
-}
-
-void MimetypeJob::start(Slave *slave)
-{
- TransferJob::start(slave);
-}
-
-
-void MimetypeJob::slotFinished( )
-{
- //kdDebug(7007) << "MimetypeJob::slotFinished()" << endl;
- if ( m_error == TDEIO::ERR_IS_DIRECTORY )
- {
- // It is in fact a directory. This happens when HTTP redirects to FTP.
- // Due to the "protocol doesn't support listing" code in KRun, we
- // assumed it was a file.
- kdDebug(7007) << "It is in fact a directory!" << endl;
- m_mimetype = TQString::fromLatin1("inode/directory");
- emit TransferJob::mimetype( this, m_mimetype );
- m_error = 0;
- }
- if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error )
- {
- // Return slave to the scheduler
- TransferJob::slotFinished();
- } else {
- //kdDebug(7007) << "MimetypeJob: Redirection to " << m_redirectionURL << endl;
- if (queryMetaData("permanent-redirect")=="true")
- emit permanentRedirection(this, m_url, m_redirectionURL);
- staticData.truncate(0);
- m_suspended = false;
- m_url = m_redirectionURL;
- m_redirectionURL = KURL();
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << m_url;
-
- // Return slave to the scheduler
- slaveDone();
- Scheduler::doJob(this);
- }
-}
-
-MimetypeJob *TDEIO::mimetype(const KURL& url, bool showProgressInfo )
-{
- KIO_ARGS << url;
- MimetypeJob * job = new MimetypeJob(url, CMD_MIMETYPE, packedArgs, showProgressInfo);
- if ( showProgressInfo )
- Observer::self()->stating( job, url );
- return job;
-}
-
-//////////////////////////
-
-DirectCopyJob::DirectCopyJob( const KURL& url, int command,
- const TQByteArray &packedArgs, bool showProgressInfo )
- : SimpleJob(url, command, packedArgs, showProgressInfo)
-{
-}
-
-void DirectCopyJob::start( Slave* slave )
-{
- connect( slave, TQT_SIGNAL(canResume( TDEIO::filesize_t ) ),
- TQT_SLOT( slotCanResume( TDEIO::filesize_t ) ) );
- SimpleJob::start(slave);
-}
-
-void DirectCopyJob::slotCanResume( TDEIO::filesize_t offset )
-{
- emit canResume(this, offset);
-}
-
-//////////////////////////
-
-
-class FileCopyJob::FileCopyJobPrivate
-{
-public:
- TDEIO::filesize_t m_sourceSize;
- time_t m_modificationTime;
- SimpleJob *m_delJob;
-};
-
-/*
- * The FileCopyJob works according to the famous Bayern
- * 'Alternating Bitburger Protocol': we either drink a beer or we
- * we order a beer, but never both at the same time.
- * Tranlated to io-slaves: We alternate between receiving a block of data
- * and sending it away.
- */
-FileCopyJob::FileCopyJob( const KURL& src, const KURL& dest, int permissions,
- bool move, bool overwrite, bool resume, bool showProgressInfo)
- : Job(showProgressInfo), m_src(src), m_dest(dest),
- m_permissions(permissions), m_move(move), m_overwrite(overwrite), m_resume(resume),
- m_totalSize(0)
-{
- if (showProgressInfo && !move)
- Observer::self()->slotCopying( this, src, dest );
- else if (showProgressInfo && move)
- Observer::self()->slotMoving( this, src, dest );
-
- //kdDebug(7007) << "FileCopyJob::FileCopyJob()" << endl;
- m_moveJob = 0;
- m_copyJob = 0;
- m_getJob = 0;
- m_putJob = 0;
- d = new FileCopyJobPrivate;
- d->m_delJob = 0;
- d->m_sourceSize = (TDEIO::filesize_t) -1;
- d->m_modificationTime = static_cast<time_t>( -1 );
- TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
-}
-
-void FileCopyJob::slotStart()
-{
- if ( m_move )
- {
- // The if() below must be the same as the one in startBestCopyMethod
- if ((m_src.protocol() == m_dest.protocol()) &&
- (m_src.host() == m_dest.host()) &&
- (m_src.port() == m_dest.port()) &&
- (m_src.user() == m_dest.user()) &&
- (m_src.pass() == m_dest.pass()) &&
- !m_src.hasSubURL() && !m_dest.hasSubURL())
- {
- startRenameJob(m_src);
- return;
- }
- else if (m_src.isLocalFile() && KProtocolInfo::canRenameFromFile(m_dest))
- {
- startRenameJob(m_dest);
- return;
- }
- else if (m_dest.isLocalFile() && KProtocolInfo::canRenameToFile(m_src))
- {
- startRenameJob(m_src);
- return;
- }
- // No fast-move available, use copy + del.
- }
- startBestCopyMethod();
-}
-
-void FileCopyJob::startBestCopyMethod()
-{
- if ((m_src.protocol() == m_dest.protocol()) &&
- (m_src.host() == m_dest.host()) &&
- (m_src.port() == m_dest.port()) &&
- (m_src.user() == m_dest.user()) &&
- (m_src.pass() == m_dest.pass()) &&
- !m_src.hasSubURL() && !m_dest.hasSubURL())
- {
- startCopyJob();
- }
- else if (m_src.isLocalFile() && KProtocolInfo::canCopyFromFile(m_dest))
- {
- startCopyJob(m_dest);
- }
- else if (m_dest.isLocalFile() && KProtocolInfo::canCopyToFile(m_src))
- {
- startCopyJob(m_src);
- }
- else
- {
- startDataPump();
- }
-}
-
-FileCopyJob::~FileCopyJob()
-{
- delete d;
-}
-
-void FileCopyJob::setSourceSize( off_t size )
-{
- d->m_sourceSize = size;
- if (size != (off_t) -1)
- m_totalSize = size;
-}
-
-void FileCopyJob::setSourceSize64( TDEIO::filesize_t size )
-{
- d->m_sourceSize = size;
- if (size != (TDEIO::filesize_t) -1)
- m_totalSize = size;
-}
-
-void FileCopyJob::setModificationTime( time_t mtime )
-{
- d->m_modificationTime = mtime;
-}
-
-void FileCopyJob::startCopyJob()
-{
- startCopyJob(m_src);
-}
-
-void FileCopyJob::startCopyJob(const KURL &slave_url)
-{
- //kdDebug(7007) << "FileCopyJob::startCopyJob()" << endl;
- KIO_ARGS << m_src << m_dest << m_permissions << (TQ_INT8) m_overwrite;
- m_copyJob = new DirectCopyJob(slave_url, CMD_COPY, packedArgs, false);
- addSubjob( m_copyJob );
- connectSubjob( m_copyJob );
- connect( m_copyJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
- TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
-}
-
-void FileCopyJob::startRenameJob(const KURL &slave_url)
-{
- KIO_ARGS << m_src << m_dest << (TQ_INT8) m_overwrite;
- m_moveJob = new SimpleJob(slave_url, CMD_RENAME, packedArgs, false);
- addSubjob( m_moveJob );
- connectSubjob( m_moveJob );
-}
-
-void FileCopyJob::connectSubjob( SimpleJob * job )
-{
- connect( job, TQT_SIGNAL(totalSize( TDEIO::Job*, TDEIO::filesize_t )),
- this, TQT_SLOT( slotTotalSize(TDEIO::Job*, TDEIO::filesize_t)) );
-
- connect( job, TQT_SIGNAL(processedSize( TDEIO::Job*, TDEIO::filesize_t )),
- this, TQT_SLOT( slotProcessedSize(TDEIO::Job*, TDEIO::filesize_t)) );
-
- connect( job, TQT_SIGNAL(percent( TDEIO::Job*, unsigned long )),
- this, TQT_SLOT( slotPercent(TDEIO::Job*, unsigned long)) );
-
-}
-
-void FileCopyJob::slotProcessedSize( TDEIO::Job *, TDEIO::filesize_t size )
-{
- setProcessedSize(size);
- emit processedSize( this, size );
- if ( size > m_totalSize ) {
- slotTotalSize( this, size ); // safety
- }
- emitPercent( size, m_totalSize );
-}
-
-void FileCopyJob::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
-{
- if (size > m_totalSize)
- {
- m_totalSize = size;
- emit totalSize( this, m_totalSize );
- }
-}
-
-void FileCopyJob::slotPercent( TDEIO::Job*, unsigned long pct )
-{
- if ( pct > m_percent )
- {
- m_percent = pct;
- emit percent( this, m_percent );
- }
-}
-
-void FileCopyJob::startDataPump()
-{
- //kdDebug(7007) << "FileCopyJob::startDataPump()" << endl;
-
- m_canResume = false;
- m_resumeAnswerSent = false;
- m_getJob = 0L; // for now
- m_putJob = put( m_dest, m_permissions, m_overwrite, m_resume, false /* no GUI */);
- if ( d->m_modificationTime != static_cast<time_t>( -1 ) ) {
- TQDateTime dt; dt.setTime_t( d->m_modificationTime );
- m_putJob->addMetaData( "modified", dt.toString( Qt::ISODate ) );
- }
- //kdDebug(7007) << "FileCopyJob: m_putJob = " << m_putJob << " m_dest=" << m_dest << endl;
-
- // The first thing the put job will tell us is whether we can
- // resume or not (this is always emitted)
- connect( m_putJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
- TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
- connect( m_putJob, TQT_SIGNAL(dataReq(TDEIO::Job *, TQByteArray&)),
- TQT_SLOT( slotDataReq(TDEIO::Job *, TQByteArray&)));
- addSubjob( m_putJob );
-}
-
-void FileCopyJob::slotCanResume( TDEIO::Job* job, TDEIO::filesize_t offset )
-{
- if ( job == m_putJob || job == m_copyJob )
- {
- //kdDebug(7007) << "FileCopyJob::slotCanResume from PUT job. offset=" << TDEIO::number(offset) << endl;
- if (offset)
- {
- RenameDlg_Result res = R_RESUME;
-
- if (!KProtocolManager::autoResume() && !m_overwrite)
- {
- TQString newPath;
- TDEIO::Job* job = ( !m_progressId && parentJob() ) ? parentJob() : this;
- // Ask confirmation about resuming previous transfer
- res = Observer::self()->open_RenameDlg(
- job, i18n("File Already Exists"),
- m_src.url(),
- m_dest.url(),
- (RenameDlg_Mode) (M_OVERWRITE | M_RESUME | M_NORENAME), newPath,
- d->m_sourceSize, offset );
- }
-
- if ( res == R_OVERWRITE || m_overwrite )
- offset = 0;
- else if ( res == R_CANCEL )
- {
- if ( job == m_putJob )
- m_putJob->kill(true);
- else
- m_copyJob->kill(true);
- m_error = ERR_USER_CANCELED;
- emitResult();
- return;
- }
- }
- else
- m_resumeAnswerSent = true; // No need for an answer
-
- if ( job == m_putJob )
- {
- m_getJob = get( m_src, false, false /* no GUI */ );
- //kdDebug(7007) << "FileCopyJob: m_getJob = " << m_getJob << endl;
- m_getJob->addMetaData( "errorPage", "false" );
- m_getJob->addMetaData( "AllowCompressedPage", "false" );
- // Set size in subjob. This helps if the slave doesn't emit totalSize.
- if ( d->m_sourceSize != (TDEIO::filesize_t)-1 )
- m_getJob->slotTotalSize( d->m_sourceSize );
- if (offset)
- {
- //kdDebug(7007) << "Setting metadata for resume to " << (unsigned long) offset << endl;
- // TODO KDE4: rename to seek or offset and document it
- // This isn't used only for resuming, but potentially also for extracting (#72302).
- m_getJob->addMetaData( "resume", TDEIO::number(offset) );
-
- // Might or might not get emitted
- connect( m_getJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
- TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
- }
- m_putJob->slave()->setOffset( offset );
-
- m_putJob->suspend();
- addSubjob( m_getJob );
- connectSubjob( m_getJob ); // Progress info depends on get
- m_getJob->resume(); // Order a beer
-
- connect( m_getJob, TQT_SIGNAL(data(TDEIO::Job*,const TQByteArray&)),
- TQT_SLOT( slotData(TDEIO::Job*,const TQByteArray&)) );
- connect( m_getJob, TQT_SIGNAL(mimetype(TDEIO::Job*,const TQString&) ),
- TQT_SLOT(slotMimetype(TDEIO::Job*,const TQString&)) );
- }
- else // copyjob
- {
- m_copyJob->slave()->sendResumeAnswer( offset != 0 );
- }
- }
- else if ( job == m_getJob )
- {
- // Cool, the get job said ok, we can resume
- m_canResume = true;
- //kdDebug(7007) << "FileCopyJob::slotCanResume from the GET job -> we can resume" << endl;
-
- m_getJob->slave()->setOffset( m_putJob->slave()->offset() );
- }
- else
- kdWarning(7007) << "FileCopyJob::slotCanResume from unknown job=" << job
- << " m_getJob=" << m_getJob << " m_putJob=" << m_putJob << endl;
-}
-
-void FileCopyJob::slotData( TDEIO::Job * , const TQByteArray &data)
-{
- //kdDebug(7007) << "FileCopyJob::slotData" << endl;
- //kdDebug(7007) << " data size : " << data.size() << endl;
- assert(m_putJob);
- if (!m_putJob) return; // Don't crash
- m_getJob->suspend();
- m_putJob->resume(); // Drink the beer
- m_buffer = data;
-
- // On the first set of data incoming, we tell the "put" slave about our
- // decision about resuming
- if (!m_resumeAnswerSent)
- {
- m_resumeAnswerSent = true;
- //kdDebug(7007) << "FileCopyJob::slotData (first time) -> send resume answer " << m_canResume << endl;
- m_putJob->slave()->sendResumeAnswer( m_canResume );
- }
-}
-
-void FileCopyJob::slotDataReq( TDEIO::Job * , TQByteArray &data)
-{
- //kdDebug(7007) << "FileCopyJob::slotDataReq" << endl;
- if (!m_resumeAnswerSent && !m_getJob)
- {
- // This can't happen (except as a migration bug on 12/10/2000)
- m_error = ERR_INTERNAL;
- m_errorText = "'Put' job didn't send canResume or 'Get' job didn't send data!";
- m_putJob->kill(true);
- emitResult();
- return;
- }
- if (m_getJob)
- {
- m_getJob->resume(); // Order more beer
- m_putJob->suspend();
- }
- data = m_buffer;
- m_buffer = TQByteArray();
-}
-
-void FileCopyJob::slotMimetype( TDEIO::Job*, const TQString& type )
-{
- emit mimetype( this, type );
-}
-
-void FileCopyJob::slotResult( TDEIO::Job *job)
-{
- //kdDebug(7007) << "FileCopyJob this=" << this << " ::slotResult(" << job << ")" << endl;
- // Did job have an error ?
- if ( job->error() )
- {
- if ((job == m_moveJob) && (job->error() == ERR_UNSUPPORTED_ACTION))
- {
- m_moveJob = 0;
- startBestCopyMethod();
- removeSubjob(job);
- return;
- }
- else if ((job == m_copyJob) && (job->error() == ERR_UNSUPPORTED_ACTION))
- {
- m_copyJob = 0;
- startDataPump();
- removeSubjob(job);
- return;
- }
- else if (job == m_getJob)
- {
- m_getJob = 0L;
- if (m_putJob)
- m_putJob->kill(true);
- }
- else if (job == m_putJob)
- {
- m_putJob = 0L;
- if (m_getJob)
- m_getJob->kill(true);
- }
- m_error = job->error();
- m_errorText = job->errorText();
- emitResult();
- return;
- }
-
- if (job == m_moveJob)
- {
- m_moveJob = 0; // Finished
- }
-
- if (job == m_copyJob)
- {
- m_copyJob = 0;
- if (m_move)
- {
- d->m_delJob = file_delete( m_src, false/*no GUI*/ ); // Delete source
- addSubjob(d->m_delJob);
- }
- }
-
- if (job == m_getJob)
- {
- m_getJob = 0; // No action required
- if (m_putJob)
- m_putJob->resume();
- }
-
- if (job == m_putJob)
- {
- //kdDebug(7007) << "FileCopyJob: m_putJob finished " << endl;
- m_putJob = 0;
- if (m_getJob)
- {
- kdWarning(7007) << "WARNING ! Get still going on..." << endl;
- m_getJob->resume();
- }
- if (m_move)
- {
- d->m_delJob = file_delete( m_src, false/*no GUI*/ ); // Delete source
- addSubjob(d->m_delJob);
- }
- }
-
- if (job == d->m_delJob)
- {
- d->m_delJob = 0; // Finished
- }
- removeSubjob(job);
-}
-
-FileCopyJob *TDEIO::file_copy( const KURL& src, const KURL& dest, int permissions,
- bool overwrite, bool resume, bool showProgressInfo)
-{
- return new FileCopyJob( src, dest, permissions, false, overwrite, resume, showProgressInfo );
-}
-
-FileCopyJob *TDEIO::file_move( const KURL& src, const KURL& dest, int permissions,
- bool overwrite, bool resume, bool showProgressInfo)
-{
- return new FileCopyJob( src, dest, permissions, true, overwrite, resume, showProgressInfo );
-}
-
-SimpleJob *TDEIO::file_delete( const KURL& src, bool showProgressInfo)
-{
- KIO_ARGS << src << TQ_INT8(true); // isFile
- return new SimpleJob(src, CMD_DEL, packedArgs, showProgressInfo );
-}
-
-//////////
-
-// KDE 4: Make it const TQString & _prefix
-ListJob::ListJob(const KURL& u, bool showProgressInfo, bool _recursive, TQString _prefix, bool _includeHidden) :
- SimpleJob(u, CMD_LISTDIR, TQByteArray(), showProgressInfo),
- recursive(_recursive), includeHidden(_includeHidden), prefix(_prefix), m_processedEntries(0)
-{
- // We couldn't set the args when calling the parent constructor,
- // so do it now.
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << u;
-}
-
-void ListJob::slotListEntries( const TDEIO::UDSEntryList& list )
-{
- // Emit progress info (takes care of emit processedSize and percent)
- m_processedEntries += list.count();
- slotProcessedSize( m_processedEntries );
-
- if (recursive) {
- UDSEntryListConstIterator it = list.begin();
- UDSEntryListConstIterator end = list.end();
-
- for (; it != end; ++it) {
- bool isDir = false;
- bool isLink = false;
- KURL itemURL;
-
- UDSEntry::ConstIterator it2 = (*it).begin();
- UDSEntry::ConstIterator end2 = (*it).end();
- for( ; it2 != end2; it2++ ) {
- switch( (*it2).m_uds ) {
- case UDS_FILE_TYPE:
- isDir = S_ISDIR((*it2).m_long);
- break;
- case UDS_NAME:
- if( itemURL.isEmpty() ) {
- itemURL = url();
- itemURL.addPath( (*it2).m_str );
- }
- break;
- case UDS_URL:
- itemURL = (*it2).m_str;
- break;
- case UDS_LINK_DEST:
- // This is a link !!! Don't follow !
- isLink = !(*it2).m_str.isEmpty();
- break;
- default:
- break;
- }
- }
- if (isDir && !isLink) {
- const TQString filename = itemURL.fileName();
- // skip hidden dirs when listing if requested
- if (filename != ".." && filename != "." && (includeHidden || filename[0] != '.')) {
- ListJob *job = new ListJob(itemURL,
- false /*no progress info!*/,
- true /*recursive*/,
- prefix + filename + "/",
- includeHidden);
- Scheduler::scheduleJob(job);
- connect(job, TQT_SIGNAL(entries( TDEIO::Job *,
- const TDEIO::UDSEntryList& )),
- TQT_SLOT( gotEntries( TDEIO::Job*,
- const TDEIO::UDSEntryList& )));
- addSubjob(job);
- }
- }
- }
- }
-
- // Not recursive, or top-level of recursive listing : return now (send . and .. as well)
- // exclusion of hidden files also requires the full sweep, but the case for full-listing
- // a single dir is probably common enough to justify the shortcut
- if (prefix.isNull() && includeHidden) {
- emit entries(this, list);
- } else {
- // cull the unwanted hidden dirs and/or parent dir references from the listing, then emit that
- UDSEntryList newlist;
-
- UDSEntryListConstIterator it = list.begin();
- UDSEntryListConstIterator end = list.end();
- for (; it != end; ++it) {
-
- UDSEntry newone = *it;
- UDSEntry::Iterator it2 = newone.begin();
- TQString filename;
- for( ; it2 != newone.end(); it2++ ) {
- if ((*it2).m_uds == UDS_NAME) {
- filename = (*it2).m_str;
- (*it2).m_str = prefix + filename;
- }
- }
- // Avoid returning entries like subdir/. and subdir/.., but include . and .. for
- // the toplevel dir, and skip hidden files/dirs if that was requested
- if ( (prefix.isNull() || (filename != ".." && filename != ".") )
- && (includeHidden || (filename[0] != '.') ) )
- newlist.append(newone);
- }
-
- emit entries(this, newlist);
- }
-}
-
-void ListJob::gotEntries(TDEIO::Job *, const TDEIO::UDSEntryList& list )
-{
- // Forward entries received by subjob - faking we received them ourselves
- emit entries(this, list);
-}
-
-void ListJob::slotResult( TDEIO::Job * job )
-{
- // If we can't list a subdir, the result is still ok
- // This is why we override Job::slotResult() - to skip error checking
- removeSubjob( job );
-}
-
-void ListJob::slotRedirection( const KURL & url )
-{
- if (!kapp->authorizeURLAction("redirect", m_url, url))
- {
- kdWarning(7007) << "ListJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
- return;
- }
- m_redirectionURL = url; // We'll remember that when the job finishes
- if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
- m_redirectionURL.setUser(m_url.user()); // Preserve user
- emit redirection( this, m_redirectionURL );
-}
-
-void ListJob::slotFinished()
-{
- // Support for listing archives as directories
- if ( m_error == TDEIO::ERR_IS_FILE && m_url.isLocalFile() ) {
- KMimeType::Ptr ptr = KMimeType::findByURL( m_url, 0, true, true );
- if ( ptr ) {
- TQString proto = ptr->property("X-TDE-LocalProtocol").toString();
- if ( !proto.isEmpty() && KProtocolInfo::isKnownProtocol(proto) ) {
- m_redirectionURL = m_url;
- m_redirectionURL.setProtocol( proto );
- m_error = 0;
- emit redirection(this,m_redirectionURL);
- }
- }
- }
- if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error ) {
- // Return slave to the scheduler
- SimpleJob::slotFinished();
- } else {
-
- //kdDebug(7007) << "ListJob: Redirection to " << m_redirectionURL << endl;
- if (queryMetaData("permanent-redirect")=="true")
- emit permanentRedirection(this, m_url, m_redirectionURL);
- m_url = m_redirectionURL;
- m_redirectionURL = KURL();
- m_packedArgs.truncate(0);
- TQDataStream stream( m_packedArgs, IO_WriteOnly );
- stream << m_url;
-
- // Return slave to the scheduler
- slaveDone();
- Scheduler::doJob(this);
- }
-}
-
-void ListJob::slotMetaData( const TDEIO::MetaData &_metaData) {
- SimpleJob::slotMetaData(_metaData);
- storeSSLSessionFromJob(m_redirectionURL);
-}
-
-ListJob *TDEIO::listDir( const KURL& url, bool showProgressInfo, bool includeHidden )
-{
- ListJob * job = new ListJob(url, showProgressInfo,false,TQString::null,includeHidden);
- return job;
-}
-
-ListJob *TDEIO::listRecursive( const KURL& url, bool showProgressInfo, bool includeHidden )
-{
- ListJob * job = new ListJob(url, showProgressInfo, true,TQString::null,includeHidden);
- return job;
-}
-
-void ListJob::setUnrestricted(bool unrestricted)
-{
- if (unrestricted)
- extraFlags() |= EF_ListJobUnrestricted;
- else
- extraFlags() &= ~EF_ListJobUnrestricted;
-}
-
-void ListJob::start(Slave *slave)
-{
- if (kapp && !kapp->authorizeURLAction("list", m_url, m_url) && !(extraFlags() & EF_ListJobUnrestricted))
- {
- m_error = ERR_ACCESS_DENIED;
- m_errorText = m_url.url();
- TQTimer::singleShot(0, this, TQT_SLOT(slotFinished()) );
- return;
- }
- connect( slave, TQT_SIGNAL( listEntries( const TDEIO::UDSEntryList& )),
- TQT_SLOT( slotListEntries( const TDEIO::UDSEntryList& )));
- connect( slave, TQT_SIGNAL( totalSize( TDEIO::filesize_t ) ),
- TQT_SLOT( slotTotalSize( TDEIO::filesize_t ) ) );
- connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
- TQT_SLOT( slotRedirection(const KURL &) ) );
-
- SimpleJob::start(slave);
-}
-
-class CopyJob::CopyJobPrivate
-{
-public:
- CopyJobPrivate() {
- m_defaultPermissions = false;
- m_bURLDirty = false;
- }
- // This is the dest URL that was initially given to CopyJob
- // It is copied into m_dest, which can be changed for a given src URL
- // (when using the RENAME dialog in slotResult),
- // and which will be reset for the next src URL.
- KURL m_globalDest;
- // The state info about that global dest
- CopyJob::DestinationState m_globalDestinationState;
- // See setDefaultPermissions
- bool m_defaultPermissions;
- // Whether URLs changed (and need to be emitted by the next slotReport call)
- bool m_bURLDirty;
- // Used after copying all the files into the dirs, to set mtime (TODO: and permissions?)
- // after the copy is done
- TQValueList<CopyInfo> m_directoriesCopied;
-};
-
-CopyJob::CopyJob( const KURL::List& src, const KURL& dest, CopyMode mode, bool asMethod, bool showProgressInfo )
- : Job(showProgressInfo), m_mode(mode), m_asMethod(asMethod),
- destinationState(DEST_NOT_STATED), state(STATE_STATING),
- m_totalSize(0), m_processedSize(0), m_fileProcessedSize(0),
- m_processedFiles(0), m_processedDirs(0),
- m_srcList(src), m_currentStatSrc(m_srcList.begin()),
- m_bCurrentOperationIsLink(false), m_bSingleFileCopy(false), m_bOnlyRenames(mode==Move),
- m_dest(dest), m_bAutoSkip( false ), m_bOverwriteAll( false ),
- m_conflictError(0), m_reportTimer(0)
-{
- d = new CopyJobPrivate;
- d->m_globalDest = dest;
- d->m_globalDestinationState = destinationState;
-
- if ( showProgressInfo ) {
- connect( this, TQT_SIGNAL( totalFiles( TDEIO::Job*, unsigned long ) ),
- Observer::self(), TQT_SLOT( slotTotalFiles( TDEIO::Job*, unsigned long ) ) );
-
- connect( this, TQT_SIGNAL( totalDirs( TDEIO::Job*, unsigned long ) ),
- Observer::self(), TQT_SLOT( slotTotalDirs( TDEIO::Job*, unsigned long ) ) );
- }
- TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
- /**
- States:
- STATE_STATING for the dest
- STATE_STATING for each src url (statNextSrc)
- for each: if dir -> STATE_LISTING (filling 'dirs' and 'files')
- but if direct rename possible: STATE_RENAMING instead.
- STATE_CREATING_DIRS (createNextDir, iterating over 'dirs')
- if conflict: STATE_CONFLICT_CREATING_DIRS
- STATE_COPYING_FILES (copyNextFile, iterating over 'files')
- if conflict: STATE_CONFLICT_COPYING_FILES
- STATE_DELETING_DIRS (deleteNextDir) (if moving)
- STATE_SETTING_DIR_ATTRIBUTES (setNextDirAttribute, iterating over d->m_directoriesCopied)
- done.
- */
-}
-
-CopyJob::~CopyJob()
-{
- delete d;
-}
-
-void CopyJob::slotStart()
-{
- /**
- We call the functions directly instead of using signals.
- Calling a function via a signal takes approx. 65 times the time
- compared to calling it directly (at least on my machine). aleXXX
- */
- m_reportTimer = new TQTimer(this);
-
- connect(m_reportTimer,TQT_SIGNAL(timeout()),this,TQT_SLOT(slotReport()));
- m_reportTimer->start(REPORT_TIMEOUT,false);
-
- // Stat the dest
- TDEIO::Job * job = TDEIO::stat( m_dest, false, 2, false );
- //kdDebug(7007) << "CopyJob:stating the dest " << m_dest << endl;
- addSubjob(job);
-}
-
-// For unit test purposes
-TDEIO_EXPORT bool kio_resolve_local_urls = true;
-
-void CopyJob::slotResultStating( Job *job )
-{
- //kdDebug(7007) << "CopyJob::slotResultStating" << endl;
- // Was there an error while stating the src ?
- if (job->error() && destinationState != DEST_NOT_STATED )
- {
- KURL srcurl = ((SimpleJob*)job)->url();
- if ( !srcurl.isLocalFile() )
- {
- // Probably : src doesn't exist. Well, over some protocols (e.g. FTP)
- // this info isn't really reliable (thanks to MS FTP servers).
- // We'll assume a file, and try to download anyway.
- kdDebug(7007) << "Error while stating source. Activating hack" << endl;
- subjobs.remove( job );
- assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
- struct CopyInfo info;
- info.permissions = (mode_t) -1;
- info.mtime = (time_t) -1;
- info.ctime = (time_t) -1;
- info.size = (TDEIO::filesize_t)-1;
- info.uSource = srcurl;
- info.uDest = m_dest;
- // Append filename or dirname to destination URL, if allowed
- if ( destinationState == DEST_IS_DIR && !m_asMethod )
- info.uDest.addPath( srcurl.fileName() );
-
- files.append( info );
- statNextSrc();
- return;
- }
- // Local file. If stat fails, the file definitely doesn't exist.
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
-
- // Is it a file or a dir ? Does it have a local path?
- UDSEntry entry = ((StatJob*)job)->statResult();
- bool bDir = false;
- bool bLink = false;
- TQString sName;
- TQString sLocalPath;
- UDSEntry::ConstIterator it2 = entry.begin();
- for( ; it2 != entry.end(); it2++ ) {
- if ( ((*it2).m_uds) == UDS_FILE_TYPE )
- bDir = S_ISDIR( (mode_t)(*it2).m_long );
- else if ( ((*it2).m_uds) == UDS_LINK_DEST )
- bLink = !((*it2).m_str.isEmpty());
- else if ( ((*it2).m_uds) == UDS_NAME )
- sName = (*it2).m_str;
- else if ( ((*it2).m_uds) == UDS_LOCAL_PATH )
- sLocalPath = (*it2).m_str;
- }
-
- if ( destinationState == DEST_NOT_STATED )
- // we were stating the dest
- {
- if (job->error())
- destinationState = DEST_DOESNT_EXIST;
- else {
- // Treat symlinks to dirs as dirs here, so no test on bLink
- destinationState = bDir ? DEST_IS_DIR : DEST_IS_FILE;
- //kdDebug(7007) << "CopyJob::slotResultStating dest is dir:" << bDir << endl;
- }
- const bool isGlobalDest = m_dest == d->m_globalDest;
- if ( isGlobalDest )
- d->m_globalDestinationState = destinationState;
-
- if ( !sLocalPath.isEmpty() && kio_resolve_local_urls ) {
- m_dest = KURL();
- m_dest.setPath(sLocalPath);
- if ( isGlobalDest )
- d->m_globalDest = m_dest;
- }
-
- subjobs.remove( job );
- assert ( subjobs.isEmpty() );
-
- // After knowing what the dest is, we can start stat'ing the first src.
- statCurrentSrc();
- return;
- }
- // We were stating the current source URL
- m_currentDest = m_dest; // used by slotEntries
- // Create a dummy list with it, for slotEntries
- UDSEntryList lst;
- lst.append(entry);
-
- // There 6 cases, and all end up calling slotEntries(job, lst) first :
- // 1 - src is a dir, destination is a directory,
- // slotEntries will append the source-dir-name to the destination
- // 2 - src is a dir, destination is a file, ERROR (done later on)
- // 3 - src is a dir, destination doesn't exist, then it's the destination dirname,
- // so slotEntries will use it as destination.
-
- // 4 - src is a file, destination is a directory,
- // slotEntries will append the filename to the destination.
- // 5 - src is a file, destination is a file, m_dest is the exact destination name
- // 6 - src is a file, destination doesn't exist, m_dest is the exact destination name
- // Tell slotEntries not to alter the src url
- m_bCurrentSrcIsDir = false;
- slotEntries(job, lst);
-
- KURL srcurl;
- if (!sLocalPath.isEmpty())
- srcurl.setPath(sLocalPath);
- else
- srcurl = ((SimpleJob*)job)->url();
-
- subjobs.remove( job );
- assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
-
- if ( bDir
- && !bLink // treat symlinks as files (no recursion)
- && m_mode != Link ) // No recursion in Link mode either.
- {
- //kdDebug(7007) << " Source is a directory " << endl;
-
- m_bCurrentSrcIsDir = true; // used by slotEntries
- if ( destinationState == DEST_IS_DIR ) // (case 1)
- {
- if ( !m_asMethod )
- {
- // Use <desturl>/<directory_copied> as destination, from now on
- TQString directory = srcurl.fileName();
- if ( !sName.isEmpty() && KProtocolInfo::fileNameUsedForCopying( srcurl ) == KProtocolInfo::Name )
- {
- directory = sName;
- }
- m_currentDest.addPath( directory );
- }
- }
- else if ( destinationState == DEST_IS_FILE ) // (case 2)
- {
- m_error = ERR_IS_FILE;
- m_errorText = m_dest.prettyURL();
- emitResult();
- return;
- }
- else // (case 3)
- {
- // otherwise dest is new name for toplevel dir
- // so the destination exists, in fact, from now on.
- // (This even works with other src urls in the list, since the
- // dir has effectively been created)
- destinationState = DEST_IS_DIR;
- if ( m_dest == d->m_globalDest )
- d->m_globalDestinationState = destinationState;
- }
-
- startListing( srcurl );
- }
- else
- {
- //kdDebug(7007) << " Source is a file (or a symlink), or we are linking -> no recursive listing " << endl;
- statNextSrc();
- }
-}
-
-void CopyJob::slotReport()
-{
- // If showProgressInfo was set, m_progressId is > 0.
- Observer * observer = m_progressId ? Observer::self() : 0L;
- switch (state) {
- case STATE_COPYING_FILES:
- emit processedFiles( this, m_processedFiles );
- if (observer) observer->slotProcessedFiles(this, m_processedFiles);
- if (d->m_bURLDirty)
- {
- // Only emit urls when they changed. This saves time, and fixes #66281
- d->m_bURLDirty = false;
- if (m_mode==Move)
- {
- if (observer) observer->slotMoving( this, m_currentSrcURL, m_currentDestURL);
- emit moving( this, m_currentSrcURL, m_currentDestURL);
- }
- else if (m_mode==Link)
- {
- if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL ); // we don't have a slotLinking
- emit linking( this, m_currentSrcURL.path(), m_currentDestURL );
- }
- else
- {
- if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL );
- emit copying( this, m_currentSrcURL, m_currentDestURL );
- }
- }
- break;
-
- case STATE_CREATING_DIRS:
- if (observer) observer->slotProcessedDirs( this, m_processedDirs );
- emit processedDirs( this, m_processedDirs );
- if (d->m_bURLDirty)
- {
- d->m_bURLDirty = false;
- emit creatingDir( this, m_currentDestURL );
- if (observer) observer->slotCreatingDir( this, m_currentDestURL);
- }
- break;
-
- case STATE_STATING:
- case STATE_LISTING:
- if (d->m_bURLDirty)
- {
- d->m_bURLDirty = false;
- if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL );
- }
- emit totalSize( this, m_totalSize );
- emit totalFiles( this, files.count() );
- emit totalDirs( this, dirs.count() );
- break;
-
- default:
- break;
- }
-}
-
-void CopyJob::slotEntries(TDEIO::Job* job, const UDSEntryList& list)
-{
- UDSEntryListConstIterator it = list.begin();
- UDSEntryListConstIterator end = list.end();
- for (; it != end; ++it) {
- UDSEntry::ConstIterator it2 = (*it).begin();
- struct CopyInfo info;
- info.permissions = -1;
- info.mtime = (time_t) -1;
- info.ctime = (time_t) -1;
- info.size = (TDEIO::filesize_t)-1;
- TQString displayName;
- KURL url;
- TQString localPath;
- bool isDir = false;
- for( ; it2 != (*it).end(); it2++ ) {
- switch ((*it2).m_uds) {
- case UDS_FILE_TYPE:
- //info.type = (mode_t)((*it2).m_long);
- isDir = S_ISDIR( (mode_t)((*it2).m_long) );
- break;
- case UDS_NAME: // recursive listing, displayName can be a/b/c/d
- displayName = (*it2).m_str;
- break;
- case UDS_URL: // optional
- url = KURL((*it2).m_str);
- break;
- case UDS_LOCAL_PATH:
- localPath = (*it2).m_str;
- break;
- case UDS_LINK_DEST:
- info.linkDest = (*it2).m_str;
- break;
- case UDS_ACCESS:
- info.permissions = ((*it2).m_long);
- break;
- case UDS_SIZE:
- info.size = (TDEIO::filesize_t)((*it2).m_long);
- m_totalSize += info.size;
- break;
- case UDS_MODIFICATION_TIME:
- info.mtime = (time_t)((*it2).m_long);
- break;
- case UDS_CREATION_TIME:
- info.ctime = (time_t)((*it2).m_long);
- default:
- break;
- }
- }
- if (displayName != ".." && displayName != ".")
- {
- bool hasCustomURL = !url.isEmpty() || !localPath.isEmpty();
- if( !hasCustomURL ) {
- // Make URL from displayName
- url = ((SimpleJob *)job)->url();
- if ( m_bCurrentSrcIsDir ) { // Only if src is a directory. Otherwise uSource is fine as is
- //kdDebug(7007) << "adding path " << displayName << endl;
- url.addPath( displayName );
- }
- }
- //kdDebug(7007) << "displayName=" << displayName << " url=" << url << endl;
- if (!localPath.isEmpty() && kio_resolve_local_urls) {
- url = KURL();
- url.setPath(localPath);
- }
-
- info.uSource = url;
- info.uDest = m_currentDest;
- //kdDebug(7007) << " uSource=" << info.uSource << " uDest(1)=" << info.uDest << endl;
- // Append filename or dirname to destination URL, if allowed
- if ( destinationState == DEST_IS_DIR &&
- // "copy/move as <foo>" means 'foo' is the dest for the base srcurl
- // (passed here during stating) but not its children (during listing)
- ( ! ( m_asMethod && state == STATE_STATING ) ) )
- {
- TQString destFileName;
- if ( hasCustomURL &&
- KProtocolInfo::fileNameUsedForCopying( url ) == KProtocolInfo::FromURL ) {
- //destFileName = url.fileName(); // Doesn't work for recursive listing
- // Count the number of prefixes used by the recursive listjob
- int numberOfSlashes = displayName.contains( '/' ); // don't make this a find()!
- TQString path = url.path();
- int pos = 0;
- for ( int n = 0; n < numberOfSlashes + 1; ++n ) {
- pos = path.findRev( '/', pos - 1 );
- if ( pos == -1 ) { // error
- kdWarning(7007) << "kioslave bug: not enough slashes in UDS_URL " << path << " - looking for " << numberOfSlashes << " slashes" << endl;
- break;
- }
- }
- if ( pos >= 0 ) {
- destFileName = path.mid( pos + 1 );
- }
-
- } else { // destination filename taken from UDS_NAME
- destFileName = displayName;
- }
-
- // Here we _really_ have to add some filename to the dest.
- // Otherwise, we end up with e.g. dest=..../Desktop/ itself.
- // (This can happen when dropping a link to a webpage with no path)
- if ( destFileName.isEmpty() )
- destFileName = TDEIO::encodeFileName( info.uSource.prettyURL() );
-
- //kdDebug(7007) << " adding destFileName=" << destFileName << endl;
- info.uDest.addPath( destFileName );
- }
- //kdDebug(7007) << " uDest(2)=" << info.uDest << endl;
- //kdDebug(7007) << " " << info.uSource << " -> " << info.uDest << endl;
- if ( info.linkDest.isEmpty() && isDir && m_mode != Link ) // Dir
- {
- dirs.append( info ); // Directories
- if (m_mode == Move)
- dirsToRemove.append( info.uSource );
- }
- else {
- files.append( info ); // Files and any symlinks
- }
- }
- }
-}
-
-void CopyJob::skipSrc()
-{
- m_dest = d->m_globalDest;
- destinationState = d->m_globalDestinationState;
- ++m_currentStatSrc;
- skip( m_currentSrcURL );
- statCurrentSrc();
-}
-
-void CopyJob::statNextSrc()
-{
- /* Revert to the global destination, the one that applies to all source urls.
- * Imagine you copy the items a b and c into /d, but /d/b exists so the user uses "Rename" to put it in /foo/b instead.
- * m_dest is /foo/b for b, but we have to revert to /d for item c and following.
- */
- m_dest = d->m_globalDest;
- destinationState = d->m_globalDestinationState;
- ++m_currentStatSrc;
- statCurrentSrc();
-}
-
-void CopyJob::statCurrentSrc()
-{
- if ( m_currentStatSrc != m_srcList.end() )
- {
- m_currentSrcURL = (*m_currentStatSrc);
- d->m_bURLDirty = true;
- if ( m_mode == Link )
- {
- // Skip the "stating the source" stage, we don't need it for linking
- m_currentDest = m_dest;
- struct CopyInfo info;
- info.permissions = -1;
- info.mtime = (time_t) -1;
- info.ctime = (time_t) -1;
- info.size = (TDEIO::filesize_t)-1;
- info.uSource = m_currentSrcURL;
- info.uDest = m_currentDest;
- // Append filename or dirname to destination URL, if allowed
- if ( destinationState == DEST_IS_DIR && !m_asMethod )
- {
- if (
- (m_currentSrcURL.protocol() == info.uDest.protocol()) &&
- (m_currentSrcURL.host() == info.uDest.host()) &&
- (m_currentSrcURL.port() == info.uDest.port()) &&
- (m_currentSrcURL.user() == info.uDest.user()) &&
- (m_currentSrcURL.pass() == info.uDest.pass()) )
- {
- // This is the case of creating a real symlink
- info.uDest.addPath( m_currentSrcURL.fileName() );
- }
- else
- {
- // Different protocols, we'll create a .desktop file
- // We have to change the extension anyway, so while we're at it,
- // name the file like the URL
- info.uDest.addPath( TDEIO::encodeFileName( m_currentSrcURL.prettyURL() )+".desktop" );
- }
- }
- files.append( info ); // Files and any symlinks
- statNextSrc(); // we could use a loop instead of a recursive call :)
- return;
- }
- else if ( m_mode == Move && (
- // Don't go renaming right away if we need a stat() to find out the destination filename
- KProtocolInfo::fileNameUsedForCopying( m_currentSrcURL ) == KProtocolInfo::FromURL ||
- destinationState != DEST_IS_DIR || m_asMethod )
- )
- {
- // If moving, before going for the full stat+[list+]copy+del thing, try to rename
- // The logic is pretty similar to FileCopyJob::slotStart()
- if ( (m_currentSrcURL.protocol() == m_dest.protocol()) &&
- (m_currentSrcURL.host() == m_dest.host()) &&
- (m_currentSrcURL.port() == m_dest.port()) &&
- (m_currentSrcURL.user() == m_dest.user()) &&
- (m_currentSrcURL.pass() == m_dest.pass()) )
- {
- startRenameJob( m_currentSrcURL );
- return;
- }
- else if ( m_currentSrcURL.isLocalFile() && KProtocolInfo::canRenameFromFile( m_dest ) )
- {
- startRenameJob( m_dest );
- return;
- }
- else if ( m_dest.isLocalFile() && KProtocolInfo::canRenameToFile( m_currentSrcURL ) )
- {
- startRenameJob( m_currentSrcURL );
- return;
- }
- }
-
- // if the file system doesn't support deleting, we do not even stat
- if (m_mode == Move && !KProtocolInfo::supportsDeleting(m_currentSrcURL)) {
- TQGuardedPtr<CopyJob> that = this;
- if (isInteractive())
- KMessageBox::information( 0, buildErrorString(ERR_CANNOT_DELETE, m_currentSrcURL.prettyURL()));
- if (that)
- statNextSrc(); // we could use a loop instead of a recursive call :)
- return;
- }
-
- // Stat the next src url
- Job * job = TDEIO::stat( m_currentSrcURL, true, 2, false );
- //kdDebug(7007) << "TDEIO::stat on " << m_currentSrcURL << endl;
- state = STATE_STATING;
- addSubjob(job);
- m_currentDestURL=m_dest;
- m_bOnlyRenames = false;
- d->m_bURLDirty = true;
- }
- else
- {
- // Finished the stat'ing phase
- // First make sure that the totals were correctly emitted
- state = STATE_STATING;
- d->m_bURLDirty = true;
- slotReport();
- if (!dirs.isEmpty())
- emit aboutToCreate( this, dirs );
- if (!files.isEmpty())
- emit aboutToCreate( this, files );
- // Check if we are copying a single file
- m_bSingleFileCopy = ( files.count() == 1 && dirs.isEmpty() );
- // Then start copying things
- state = STATE_CREATING_DIRS;
- createNextDir();
- }
-}
-
-void CopyJob::startRenameJob( const KURL& slave_url )
-{
- KURL dest = m_dest;
- // Append filename or dirname to destination URL, if allowed
- if ( destinationState == DEST_IS_DIR && !m_asMethod )
- dest.addPath( m_currentSrcURL.fileName() );
- kdDebug(7007) << "This seems to be a suitable case for trying to rename before stat+[list+]copy+del" << endl;
- state = STATE_RENAMING;
-
- struct CopyInfo info;
- info.permissions = -1;
- info.mtime = (time_t) -1;
- info.ctime = (time_t) -1;
- info.size = (TDEIO::filesize_t)-1;
- info.uSource = m_currentSrcURL;
- info.uDest = dest;
- TQValueList<CopyInfo> files;
- files.append(info);
- emit aboutToCreate( this, files );
-
- KIO_ARGS << m_currentSrcURL << dest << (TQ_INT8) false /*no overwrite*/;
- SimpleJob * newJob = new SimpleJob(slave_url, CMD_RENAME, packedArgs, false);
- Scheduler::scheduleJob(newJob);
- addSubjob( newJob );
- if ( m_currentSrcURL.directory() != dest.directory() ) // For the user, moving isn't renaming. Only renaming is.
- m_bOnlyRenames = false;
-}
-
-void CopyJob::startListing( const KURL & src )
-{
- state = STATE_LISTING;
- d->m_bURLDirty = true;
- ListJob * newjob = listRecursive( src, false );
- newjob->setUnrestricted(true);
- connect(newjob, TQT_SIGNAL(entries( TDEIO::Job *,
- const TDEIO::UDSEntryList& )),
- TQT_SLOT( slotEntries( TDEIO::Job*,
- const TDEIO::UDSEntryList& )));
- addSubjob( newjob );
-}
-
-void CopyJob::skip( const KURL & sourceUrl )
-{
- // Check if this is one if toplevel sources
- // If yes, remove it from m_srcList, for a correct FilesRemoved() signal
- //kdDebug(7007) << "CopyJob::skip: looking for " << sourceUrl << endl;
- KURL::List::Iterator sit = m_srcList.find( sourceUrl );
- if ( sit != m_srcList.end() )
- {
- //kdDebug(7007) << "CopyJob::skip: removing " << sourceUrl << " from list" << endl;
- m_srcList.remove( sit );
- }
- dirsToRemove.remove( sourceUrl );
-}
-
-bool CopyJob::shouldOverwrite( const TQString& path ) const
-{
- if ( m_bOverwriteAll )
- return true;
- TQStringList::ConstIterator sit = m_overwriteList.begin();
- for( ; sit != m_overwriteList.end(); ++sit )
- if ( path.startsWith( *sit ) )
- return true;
- return false;
-}
-
-bool CopyJob::shouldSkip( const TQString& path ) const
-{
- TQStringList::ConstIterator sit = m_skipList.begin();
- for( ; sit != m_skipList.end(); ++sit )
- if ( path.startsWith( *sit ) )
- return true;
- return false;
-}
-
-void CopyJob::slotResultCreatingDirs( Job * job )
-{
- // The dir we are trying to create:
- TQValueList<CopyInfo>::Iterator it = dirs.begin();
- // Was there an error creating a dir ?
- if ( job->error() )
- {
- m_conflictError = job->error();
- if ( (m_conflictError == ERR_DIR_ALREADY_EXIST)
- || (m_conflictError == ERR_FILE_ALREADY_EXIST) ) // can't happen?
- {
- KURL oldURL = ((SimpleJob*)job)->url();
- // Should we skip automatically ?
- if ( m_bAutoSkip ) {
- // We don't want to copy files in this directory, so we put it on the skip list
- m_skipList.append( oldURL.path( 1 ) );
- skip( oldURL );
- dirs.remove( it ); // Move on to next dir
- } else {
- // Did the user choose to overwrite already?
- const TQString destFile = (*it).uDest.path();
- if ( shouldOverwrite( destFile ) ) { // overwrite => just skip
- emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
- dirs.remove( it ); // Move on to next dir
- } else {
- if ( !isInteractive() ) {
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
-
- assert( ((SimpleJob*)job)->url().url() == (*it).uDest.url() );
- subjobs.remove( job );
- assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
-
- // We need to stat the existing dir, to get its last-modification time
- KURL existingDest( (*it).uDest );
- SimpleJob * newJob = TDEIO::stat( existingDest, false, 2, false );
- Scheduler::scheduleJob(newJob);
- kdDebug(7007) << "TDEIO::stat for resolving conflict on " << existingDest << endl;
- state = STATE_CONFLICT_CREATING_DIRS;
- addSubjob(newJob);
- return; // Don't move to next dir yet !
- }
- }
- }
- else
- {
- // Severe error, abort
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
- }
- else // no error : remove from list, to move on to next dir
- {
- //this is required for the undo feature
- emit copyingDone( this, (*it).uSource, (*it).uDest, true, false );
- d->m_directoriesCopied.append( *it );
- dirs.remove( it );
- }
-
- m_processedDirs++;
- //emit processedDirs( this, m_processedDirs );
- subjobs.remove( job );
- assert( subjobs.isEmpty() ); // We should have only one job at a time ...
- createNextDir();
-}
-
-void CopyJob::slotResultConflictCreatingDirs( TDEIO::Job * job )
-{
- // We come here after a conflict has been detected and we've stated the existing dir
-
- // The dir we were trying to create:
- TQValueList<CopyInfo>::Iterator it = dirs.begin();
- // Its modification time:
- time_t destmtime = (time_t)-1;
- time_t destctime = (time_t)-1;
- TDEIO::filesize_t destsize = 0;
- TQString linkDest;
-
- UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
- TDEIO::UDSEntry::ConstIterator it2 = entry.begin();
- for( ; it2 != entry.end(); it2++ ) {
- switch ((*it2).m_uds) {
- case UDS_MODIFICATION_TIME:
- destmtime = (time_t)((*it2).m_long);
- break;
- case UDS_CREATION_TIME:
- destctime = (time_t)((*it2).m_long);
- break;
- case UDS_SIZE:
- destsize = (*it2).m_long;
- break;
- case UDS_LINK_DEST:
- linkDest = (*it2).m_str;
- break;
- }
- }
- subjobs.remove( job );
- assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
-
- // Always multi and skip (since there are files after that)
- RenameDlg_Mode mode = (RenameDlg_Mode)( M_MULTI | M_SKIP );
- // Overwrite only if the existing thing is a dir (no chance with a file)
- if ( m_conflictError == ERR_DIR_ALREADY_EXIST )
- {
- if( (*it).uSource == (*it).uDest ||
- ((*it).uSource.protocol() == (*it).uDest.protocol() &&
- (*it).uSource.path(-1) == linkDest) )
- mode = (RenameDlg_Mode)( mode | M_OVERWRITE_ITSELF);
- else
- mode = (RenameDlg_Mode)( mode | M_OVERWRITE );
- }
-
- TQString existingDest = (*it).uDest.path();
- TQString newPath;
- if (m_reportTimer)
- m_reportTimer->stop();
- RenameDlg_Result r = Observer::self()->open_RenameDlg( this, i18n("Folder Already Exists"),
- (*it).uSource.url(),
- (*it).uDest.url(),
- mode, newPath,
- (*it).size, destsize,
- (*it).ctime, destctime,
- (*it).mtime, destmtime );
- if (m_reportTimer)
- m_reportTimer->start(REPORT_TIMEOUT,false);
- switch ( r ) {
- case R_CANCEL:
- m_error = ERR_USER_CANCELED;
- emitResult();
- return;
- case R_RENAME:
- {
- TQString oldPath = (*it).uDest.path( 1 );
- KURL newUrl( (*it).uDest );
- newUrl.setPath( newPath );
- emit renamed( this, (*it).uDest, newUrl ); // for e.g. kpropsdlg
-
- // Change the current one and strip the trailing '/'
- (*it).uDest.setPath( newUrl.path( -1 ) );
- newPath = newUrl.path( 1 ); // With trailing slash
- TQValueList<CopyInfo>::Iterator renamedirit = it;
- ++renamedirit;
- // Change the name of subdirectories inside the directory
- for( ; renamedirit != dirs.end() ; ++renamedirit )
- {
- TQString path = (*renamedirit).uDest.path();
- if ( path.left(oldPath.length()) == oldPath ) {
- TQString n = path;
- n.replace( 0, oldPath.length(), newPath );
- kdDebug(7007) << "dirs list: " << (*renamedirit).uSource.path()
- << " was going to be " << path
- << ", changed into " << n << endl;
- (*renamedirit).uDest.setPath( n );
- }
- }
- // Change filenames inside the directory
- TQValueList<CopyInfo>::Iterator renamefileit = files.begin();
- for( ; renamefileit != files.end() ; ++renamefileit )
- {
- TQString path = (*renamefileit).uDest.path();
- if ( path.left(oldPath.length()) == oldPath ) {
- TQString n = path;
- n.replace( 0, oldPath.length(), newPath );
- kdDebug(7007) << "files list: " << (*renamefileit).uSource.path()
- << " was going to be " << path
- << ", changed into " << n << endl;
- (*renamefileit).uDest.setPath( n );
- }
- }
- if (!dirs.isEmpty())
- emit aboutToCreate( this, dirs );
- if (!files.isEmpty())
- emit aboutToCreate( this, files );
- }
- break;
- case R_AUTO_SKIP:
- m_bAutoSkip = true;
- // fall through
- case R_SKIP:
- m_skipList.append( existingDest );
- skip( (*it).uSource );
- // Move on to next dir
- dirs.remove( it );
- m_processedDirs++;
- break;
- case R_OVERWRITE:
- m_overwriteList.append( existingDest );
- emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
- // Move on to next dir
- dirs.remove( it );
- m_processedDirs++;
- break;
- case R_OVERWRITE_ALL:
- m_bOverwriteAll = true;
- emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
- // Move on to next dir
- dirs.remove( it );
- m_processedDirs++;
- break;
- default:
- assert( 0 );
- }
- state = STATE_CREATING_DIRS;
- //emit processedDirs( this, m_processedDirs );
- createNextDir();
-}
-
-void CopyJob::createNextDir()
-{
- KURL udir;
- if ( !dirs.isEmpty() )
- {
- // Take first dir to create out of list
- TQValueList<CopyInfo>::Iterator it = dirs.begin();
- // Is this URL on the skip list or the overwrite list ?
- while( it != dirs.end() && udir.isEmpty() )
- {
- const TQString dir = (*it).uDest.path();
- if ( shouldSkip( dir ) ) {
- dirs.remove( it );
- it = dirs.begin();
- } else
- udir = (*it).uDest;
- }
- }
- if ( !udir.isEmpty() ) // any dir to create, finally ?
- {
- // Create the directory - with default permissions so that we can put files into it
- // TODO : change permissions once all is finished; but for stuff coming from CDROM it sucks...
- TDEIO::SimpleJob *newjob = TDEIO::mkdir( udir, -1 );
- Scheduler::scheduleJob(newjob);
-
- m_currentDestURL = udir;
- d->m_bURLDirty = true;
-
- addSubjob(newjob);
- return;
- }
- else // we have finished creating dirs
- {
- emit processedDirs( this, m_processedDirs ); // make sure final number appears
- if (m_progressId) Observer::self()->slotProcessedDirs( this, m_processedDirs );
-
- state = STATE_COPYING_FILES;
- m_processedFiles++; // Ralf wants it to start at 1, not 0
- copyNextFile();
- }
-}
-
-void CopyJob::slotResultCopyingFiles( Job * job )
-{
- // The file we were trying to copy:
- TQValueList<CopyInfo>::Iterator it = files.begin();
- if ( job->error() )
- {
- // Should we skip automatically ?
- if ( m_bAutoSkip )
- {
- skip( (*it).uSource );
- m_fileProcessedSize = (*it).size;
- files.remove( it ); // Move on to next file
- }
- else
- {
- if ( !isInteractive() ) {
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
-
- m_conflictError = job->error(); // save for later
- // Existing dest ?
- if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
- || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
- || ( m_conflictError == ERR_IDENTICAL_FILES ) )
- {
- subjobs.remove( job );
- assert ( subjobs.isEmpty() );
- // We need to stat the existing file, to get its last-modification time
- KURL existingFile( (*it).uDest );
- SimpleJob * newJob = TDEIO::stat( existingFile, false, 2, false );
- Scheduler::scheduleJob(newJob);
- kdDebug(7007) << "TDEIO::stat for resolving conflict on " << existingFile << endl;
- state = STATE_CONFLICT_COPYING_FILES;
- addSubjob(newJob);
- return; // Don't move to next file yet !
- }
- else
- {
- if ( m_bCurrentOperationIsLink && ::tqqt_cast<TDEIO::DeleteJob*>( job ) )
- {
- // Very special case, see a few lines below
- // We are deleting the source of a symlink we successfully moved... ignore error
- m_fileProcessedSize = (*it).size;
- files.remove( it );
- } else {
- // Go directly to the conflict resolution, there is nothing to stat
- slotResultConflictCopyingFiles( job );
- return;
- }
- }
- }
- } else // no error
- {
- // Special case for moving links. That operation needs two jobs, unlike others.
- if ( m_bCurrentOperationIsLink && m_mode == Move
- && !::tqqt_cast<TDEIO::DeleteJob *>( job ) // Deleting source not already done
- )
- {
- subjobs.remove( job );
- assert ( subjobs.isEmpty() );
- // The only problem with this trick is that the error handling for this del operation
- // is not going to be right... see 'Very special case' above.
- TDEIO::Job * newjob = TDEIO::del( (*it).uSource, false /*don't shred*/, false /*no GUI*/ );
- addSubjob( newjob );
- return; // Don't move to next file yet !
- }
-
- if ( m_bCurrentOperationIsLink )
- {
- TQString target = ( m_mode == Link ? (*it).uSource.path() : (*it).linkDest );
- //required for the undo feature
- emit copyingLinkDone( this, (*it).uSource, target, (*it).uDest );
- }
- else
- //required for the undo feature
- emit copyingDone( this, (*it).uSource, (*it).uDest, false, false );
- // remove from list, to move on to next file
- files.remove( it );
- }
- m_processedFiles++;
-
- // clear processed size for last file and add it to overall processed size
- m_processedSize += m_fileProcessedSize;
- m_fileProcessedSize = 0;
-
- //kdDebug(7007) << files.count() << " files remaining" << endl;
-
- removeSubjob( job, true, false ); // merge metadata
- assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
- copyNextFile();
-}
-
-void CopyJob::slotResultConflictCopyingFiles( TDEIO::Job * job )
-{
- // We come here after a conflict has been detected and we've stated the existing file
- // The file we were trying to create:
- TQValueList<CopyInfo>::Iterator it = files.begin();
-
- RenameDlg_Result res;
- TQString newPath;
-
- if (m_reportTimer)
- m_reportTimer->stop();
-
- if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
- || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
- || ( m_conflictError == ERR_IDENTICAL_FILES ) )
- {
- // Its modification time:
- time_t destmtime = (time_t)-1;
- time_t destctime = (time_t)-1;
- TDEIO::filesize_t destsize = 0;
- TQString linkDest;
- UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
- TDEIO::UDSEntry::ConstIterator it2 = entry.begin();
- for( ; it2 != entry.end(); it2++ ) {
- switch ((*it2).m_uds) {
- case UDS_MODIFICATION_TIME:
- destmtime = (time_t)((*it2).m_long);
- break;
- case UDS_CREATION_TIME:
- destctime = (time_t)((*it2).m_long);
- break;
- case UDS_SIZE:
- destsize = (*it2).m_long;
- break;
- case UDS_LINK_DEST:
- linkDest = (*it2).m_str;
- break;
- }
- }
-
- // Offer overwrite only if the existing thing is a file
- // If src==dest, use "overwrite-itself"
- RenameDlg_Mode mode;
- bool isDir = true;
-
- if( m_conflictError == ERR_DIR_ALREADY_EXIST )
- mode = (RenameDlg_Mode) 0;
- else
- {
- if ( (*it).uSource == (*it).uDest ||
- ((*it).uSource.protocol() == (*it).uDest.protocol() &&
- (*it).uSource.path(-1) == linkDest) )
- mode = M_OVERWRITE_ITSELF;
- else
- mode = M_OVERWRITE;
- isDir = false;
- }
-
- if ( m_bSingleFileCopy )
- mode = (RenameDlg_Mode) ( mode | M_SINGLE );
- else
- mode = (RenameDlg_Mode) ( mode | M_MULTI | M_SKIP );
-
- res = Observer::self()->open_RenameDlg( this, !isDir ?
- i18n("File Already Exists") : i18n("Already Exists as Folder"),
- (*it).uSource.url(),
- (*it).uDest.url(),
- mode, newPath,
- (*it).size, destsize,
- (*it).ctime, destctime,
- (*it).mtime, destmtime );
-
- }
- else
- {
- if ( job->error() == ERR_USER_CANCELED )
- res = R_CANCEL;
- else if ( !isInteractive() ) {
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
- else
- {
- SkipDlg_Result skipResult = Observer::self()->open_SkipDlg( this, files.count() > 1,
- job->errorString() );
-
- // Convert the return code from SkipDlg into a RenameDlg code
- res = ( skipResult == S_SKIP ) ? R_SKIP :
- ( skipResult == S_AUTO_SKIP ) ? R_AUTO_SKIP :
- R_CANCEL;
- }
- }
-
- if (m_reportTimer)
- m_reportTimer->start(REPORT_TIMEOUT,false);
-
- subjobs.remove( job );
- assert ( subjobs.isEmpty() );
- switch ( res ) {
- case R_CANCEL:
- m_error = ERR_USER_CANCELED;
- emitResult();
- return;
- case R_RENAME:
- {
- KURL newUrl( (*it).uDest );
- newUrl.setPath( newPath );
- emit renamed( this, (*it).uDest, newUrl ); // for e.g. kpropsdlg
- (*it).uDest = newUrl;
-
- TQValueList<CopyInfo> files;
- files.append(*it);
- emit aboutToCreate( this, files );
- }
- break;
- case R_AUTO_SKIP:
- m_bAutoSkip = true;
- // fall through
- case R_SKIP:
- // Move on to next file
- skip( (*it).uSource );
- m_processedSize += (*it).size;
- files.remove( it );
- m_processedFiles++;
- break;
- case R_OVERWRITE_ALL:
- m_bOverwriteAll = true;
- break;
- case R_OVERWRITE:
- // Add to overwrite list, so that copyNextFile knows to overwrite
- m_overwriteList.append( (*it).uDest.path() );
- break;
- default:
- assert( 0 );
- }
- state = STATE_COPYING_FILES;
- //emit processedFiles( this, m_processedFiles );
- copyNextFile();
-}
-
-void CopyJob::copyNextFile()
-{
- bool bCopyFile = false;
- //kdDebug(7007) << "CopyJob::copyNextFile()" << endl;
- // Take the first file in the list
- TQValueList<CopyInfo>::Iterator it = files.begin();
- // Is this URL on the skip list ?
- while (it != files.end() && !bCopyFile)
- {
- const TQString destFile = (*it).uDest.path();
- bCopyFile = !shouldSkip( destFile );
- if ( !bCopyFile ) {
- files.remove( it );
- it = files.begin();
- }
- }
-
- if (bCopyFile) // any file to create, finally ?
- {
- // Do we set overwrite ?
- bool bOverwrite;
- const TQString destFile = (*it).uDest.path();
- kdDebug(7007) << "copying " << destFile << endl;
- if ( (*it).uDest == (*it).uSource )
- bOverwrite = false;
- else
- bOverwrite = shouldOverwrite( destFile );
-
- m_bCurrentOperationIsLink = false;
- TDEIO::Job * newjob = 0L;
- if ( m_mode == Link )
- {
- //kdDebug(7007) << "Linking" << endl;
- if (
- ((*it).uSource.protocol() == (*it).uDest.protocol()) &&
- ((*it).uSource.host() == (*it).uDest.host()) &&
- ((*it).uSource.port() == (*it).uDest.port()) &&
- ((*it).uSource.user() == (*it).uDest.user()) &&
- ((*it).uSource.pass() == (*it).uDest.pass()) )
- {
- // This is the case of creating a real symlink
- TDEIO::SimpleJob *newJob = TDEIO::symlink( (*it).uSource.path(), (*it).uDest, bOverwrite, false /*no GUI*/ );
- newjob = newJob;
- Scheduler::scheduleJob(newJob);
- //kdDebug(7007) << "CopyJob::copyNextFile : Linking target=" << (*it).uSource.path() << " link=" << (*it).uDest << endl;
- //emit linking( this, (*it).uSource.path(), (*it).uDest );
- m_bCurrentOperationIsLink = true;
- m_currentSrcURL=(*it).uSource;
- m_currentDestURL=(*it).uDest;
- d->m_bURLDirty = true;
- //Observer::self()->slotCopying( this, (*it).uSource, (*it).uDest ); // should be slotLinking perhaps
- } else {
- //kdDebug(7007) << "CopyJob::copyNextFile : Linking URL=" << (*it).uSource << " link=" << (*it).uDest << endl;
- if ( (*it).uDest.isLocalFile() )
- {
- bool devicesOk=false;
-
- // if the source is a devices url, handle it a littlebit special
- if ((*it).uSource.protocol()==TQString::fromLatin1("devices"))
- {
- TQByteArray data;
- TQByteArray param;
- TQCString retType;
- TQDataStream streamout(param,IO_WriteOnly);
- streamout<<(*it).uSource;
- streamout<<(*it).uDest;
- if ( kapp && kapp->dcopClient()->call( "kded",
- "mountwatcher", "createLink(KURL, KURL)", param,retType,data,false ) )
- {
- TQDataStream streamin(data,IO_ReadOnly);
- streamin>>devicesOk;
- }
- if (devicesOk)
- {
- files.remove( it );
- m_processedFiles++;
- //emit processedFiles( this, m_processedFiles );
- copyNextFile();
- return;
- }
- }
-
- if (!devicesOk)
- {
- TQString path = (*it).uDest.path();
- //kdDebug(7007) << "CopyJob::copyNextFile path=" << path << endl;
- TQFile f( path );
- if ( f.open( IO_ReadWrite ) )
- {
- f.close();
- KSimpleConfig config( path );
- config.setDesktopGroup();
- KURL url = (*it).uSource;
- url.setPass( "" );
- config.writePathEntry( TQString::fromLatin1("URL"), url.url() );
- config.writeEntry( TQString::fromLatin1("Name"), url.url() );
- config.writeEntry( TQString::fromLatin1("Type"), TQString::fromLatin1("Link") );
- TQString protocol = (*it).uSource.protocol();
- if ( protocol == TQString::fromLatin1("ftp") )
- config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("ftp") );
- else if ( protocol == TQString::fromLatin1("http") )
- config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("www") );
- else if ( protocol == TQString::fromLatin1("info") )
- config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("info") );
- else if ( protocol == TQString::fromLatin1("mailto") ) // sven:
- config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("kmail") ); // added mailto: support
- else
- config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("unknown") );
- config.sync();
- files.remove( it );
- m_processedFiles++;
- //emit processedFiles( this, m_processedFiles );
- copyNextFile();
- return;
- }
- else
- {
- kdDebug(7007) << "CopyJob::copyNextFile ERR_CANNOT_OPEN_FOR_WRITING" << endl;
- m_error = ERR_CANNOT_OPEN_FOR_WRITING;
- m_errorText = (*it).uDest.path();
- emitResult();
- return;
- }
- }
- } else {
- // Todo: not show "link" on remote dirs if the src urls are not from the same protocol+host+...
- m_error = ERR_CANNOT_SYMLINK;
- m_errorText = (*it).uDest.prettyURL();
- emitResult();
- return;
- }
- }
- }
- else if ( !(*it).linkDest.isEmpty() &&
- ((*it).uSource.protocol() == (*it).uDest.protocol()) &&
- ((*it).uSource.host() == (*it).uDest.host()) &&
- ((*it).uSource.port() == (*it).uDest.port()) &&
- ((*it).uSource.user() == (*it).uDest.user()) &&
- ((*it).uSource.pass() == (*it).uDest.pass()))
- // Copying a symlink - only on the same protocol/host/etc. (#5601, downloading an FTP file through its link),
- {
- TDEIO::SimpleJob *newJob = TDEIO::symlink( (*it).linkDest, (*it).uDest, bOverwrite, false /*no GUI*/ );
- Scheduler::scheduleJob(newJob);
- newjob = newJob;
- //kdDebug(7007) << "CopyJob::copyNextFile : Linking target=" << (*it).linkDest << " link=" << (*it).uDest << endl;
- //emit linking( this, (*it).linkDest, (*it).uDest );
- m_currentSrcURL=(*it).linkDest;
- m_currentDestURL=(*it).uDest;
- d->m_bURLDirty = true;
- //Observer::self()->slotCopying( this, (*it).linkDest, (*it).uDest ); // should be slotLinking perhaps
- m_bCurrentOperationIsLink = true;
- // NOTE: if we are moving stuff, the deletion of the source will be done in slotResultCopyingFiles
- } else if (m_mode == Move) // Moving a file
- {
- TDEIO::FileCopyJob * moveJob = TDEIO::file_move( (*it).uSource, (*it).uDest, (*it).permissions, bOverwrite, false, false/*no GUI*/ );
- moveJob->setSourceSize64( (*it).size );
- newjob = moveJob;
- //kdDebug(7007) << "CopyJob::copyNextFile : Moving " << (*it).uSource << " to " << (*it).uDest << endl;
- //emit moving( this, (*it).uSource, (*it).uDest );
- m_currentSrcURL=(*it).uSource;
- m_currentDestURL=(*it).uDest;
- d->m_bURLDirty = true;
- //Observer::self()->slotMoving( this, (*it).uSource, (*it).uDest );
- }
- else // Copying a file
- {
- // If source isn't local and target is local, we ignore the original permissions
- // Otherwise, files downloaded from HTTP end up with -r--r--r--
- bool remoteSource = !KProtocolInfo::supportsListing((*it).uSource);
- int permissions = (*it).permissions;
- if ( d->m_defaultPermissions || ( remoteSource && (*it).uDest.isLocalFile() ) )
- permissions = -1;
- TDEIO::FileCopyJob * copyJob = TDEIO::file_copy( (*it).uSource, (*it).uDest, permissions, bOverwrite, false, false/*no GUI*/ );
- copyJob->setParentJob( this ); // in case of rename dialog
- copyJob->setSourceSize64( (*it).size );
- copyJob->setModificationTime( (*it).mtime );
- newjob = copyJob;
- //kdDebug(7007) << "CopyJob::copyNextFile : Copying " << (*it).uSource << " to " << (*it).uDest << endl;
- m_currentSrcURL=(*it).uSource;
- m_currentDestURL=(*it).uDest;
- d->m_bURLDirty = true;
- }
- addSubjob(newjob);
- connect( newjob, TQT_SIGNAL( processedSize( TDEIO::Job*, TDEIO::filesize_t ) ),
- this, TQT_SLOT( slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
- connect( newjob, TQT_SIGNAL( totalSize( TDEIO::Job*, TDEIO::filesize_t ) ),
- this, TQT_SLOT( slotTotalSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
- }
- else
- {
- // We're done
- //kdDebug(7007) << "copyNextFile finished" << endl;
- deleteNextDir();
- }
-}
-
-void CopyJob::deleteNextDir()
-{
- if ( m_mode == Move && !dirsToRemove.isEmpty() ) // some dirs to delete ?
- {
- state = STATE_DELETING_DIRS;
- d->m_bURLDirty = true;
- // Take first dir to delete out of list - last ones first !
- KURL::List::Iterator it = dirsToRemove.fromLast();
- SimpleJob *job = TDEIO::rmdir( *it );
- Scheduler::scheduleJob(job);
- dirsToRemove.remove(it);
- addSubjob( job );
- }
- else
- {
- // This step is done, move on
- setNextDirAttribute();
- }
-}
-
-void CopyJob::setNextDirAttribute()
-{
- if ( !d->m_directoriesCopied.isEmpty() )
- {
- state = STATE_SETTING_DIR_ATTRIBUTES;
-#ifdef Q_OS_UNIX
- // TODO KDE4: this should use a SlaveBase method, but we have none yet in KDE3.
- TQValueList<CopyInfo>::Iterator it = d->m_directoriesCopied.begin();
- for ( ; it != d->m_directoriesCopied.end() ; ++it ) {
- const KURL& url = (*it).uDest;
- if ( url.isLocalFile() && (*it).mtime != (time_t)-1 ) {
- const TQCString path = TQFile::encodeName( url.path() );
- KDE_struct_stat statbuf;
- if (KDE_lstat(path, &statbuf) == 0) {
- struct utimbuf utbuf;
- utbuf.actime = statbuf.st_atime; // access time, unchanged
- utbuf.modtime = (*it).mtime; // modification time
- utime( path, &utbuf );
- }
-
- }
- }
-#endif
- d->m_directoriesCopied.clear();
- }
-
- // No "else" here, since the above is a simple sync loop
-
- {
- // Finished - tell the world
- if ( !m_bOnlyRenames )
- {
- KDirNotify_stub allDirNotify("*", "KDirNotify*");
- KURL url( d->m_globalDest );
- if ( d->m_globalDestinationState != DEST_IS_DIR || m_asMethod )
- url.setPath( url.directory() );
- //kdDebug(7007) << "KDirNotify'ing FilesAdded " << url << endl;
- allDirNotify.FilesAdded( url );
-
- if ( m_mode == Move && !m_srcList.isEmpty() ) {
- //kdDebug(7007) << "KDirNotify'ing FilesRemoved " << m_srcList.toStringList() << endl;
- allDirNotify.FilesRemoved( m_srcList );
- }
- }
- if (m_reportTimer)
- m_reportTimer->stop();
- --m_processedFiles; // undo the "start at 1" hack
- slotReport(); // display final numbers, important if progress dialog stays up
-
- emitResult();
- }
-}
-
-void CopyJob::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size )
-{
- //kdDebug(7007) << "CopyJob::slotProcessedSize " << data_size << endl;
- m_fileProcessedSize = data_size;
- setProcessedSize(m_processedSize + m_fileProcessedSize);
-
- if ( m_processedSize + m_fileProcessedSize > m_totalSize )
- {
- m_totalSize = m_processedSize + m_fileProcessedSize;
- //kdDebug(7007) << "Adjusting m_totalSize to " << m_totalSize << endl;
- emit totalSize( this, m_totalSize ); // safety
- }
- //kdDebug(7007) << "emit processedSize " << (unsigned long) (m_processedSize + m_fileProcessedSize) << endl;
- emit processedSize( this, m_processedSize + m_fileProcessedSize );
- emitPercent( m_processedSize + m_fileProcessedSize, m_totalSize );
-}
-
-void CopyJob::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
-{
- //kdDebug(7007) << "slotTotalSize: " << size << endl;
- // Special case for copying a single file
- // This is because some protocols don't implement stat properly
- // (e.g. HTTP), and don't give us a size in some cases (redirection)
- // so we'd rather rely on the size given for the transfer
- if ( m_bSingleFileCopy && size > m_totalSize)
- {
- //kdDebug(7007) << "slotTotalSize: updating totalsize to " << size << endl;
- m_totalSize = size;
- emit totalSize( this, size );
- }
-}
-
-void CopyJob::slotResultDeletingDirs( Job * job )
-{
- if (job->error())
- {
- // Couldn't remove directory. Well, perhaps it's not empty
- // because the user pressed Skip for a given file in it.
- // Let's not display "Could not remove dir ..." for each of those dir !
- }
- subjobs.remove( job );
- assert ( subjobs.isEmpty() );
- deleteNextDir();
-}
-
-#if 0 // TODO KDE4
-void CopyJob::slotResultSettingDirAttributes( Job * job )
-{
- if (job->error())
- {
- // Couldn't set directory attributes. Ignore the error, it can happen
- // with inferior file systems like VFAT.
- // Let's not display warnings for each dir like "cp -a" does.
- }
- subjobs.remove( job );
- assert ( subjobs.isEmpty() );
- setNextDirAttribute();
-}
-#endif
-
-void CopyJob::slotResultRenaming( Job* job )
-{
- int err = job->error();
- const TQString errText = job->errorText();
- removeSubjob( job, true, false ); // merge metadata
- assert ( subjobs.isEmpty() );
- // Determine dest again
- KURL dest = m_dest;
- if ( destinationState == DEST_IS_DIR && !m_asMethod )
- dest.addPath( m_currentSrcURL.fileName() );
- if ( err )
- {
- // Direct renaming didn't work. Try renaming to a temp name,
- // this can help e.g. when renaming 'a' to 'A' on a VFAT partition.
- // In that case it's the _same_ dir, we don't want to copy+del (data loss!)
- if ( m_currentSrcURL.isLocalFile() && m_currentSrcURL.url(-1) != dest.url(-1) &&
- m_currentSrcURL.url(-1).lower() == dest.url(-1).lower() &&
- ( err == ERR_FILE_ALREADY_EXIST ||
- err == ERR_DIR_ALREADY_EXIST ||
- err == ERR_IDENTICAL_FILES ) )
- {
- kdDebug(7007) << "Couldn't rename directly, dest already exists. Detected special case of lower/uppercase renaming in same dir, try with 2 rename calls" << endl;
- TQCString _src( TQFile::encodeName(m_currentSrcURL.path()) );
- TQCString _dest( TQFile::encodeName(dest.path()) );
- KTempFile tmpFile( m_currentSrcURL.directory(false) );
- TQCString _tmp( TQFile::encodeName(tmpFile.name()) );
- kdDebug(7007) << "CopyJob::slotResult KTempFile status:" << tmpFile.status() << " using " << _tmp << " as intermediary" << endl;
- tmpFile.unlink();
- if ( ::rename( _src, _tmp ) == 0 )
- {
- if ( !TQFile::exists( _dest ) && ::rename( _tmp, _dest ) == 0 )
- {
- kdDebug(7007) << "Success." << endl;
- err = 0;
- }
- else
- {
- // Revert back to original name!
- if ( ::rename( _tmp, _src ) != 0 ) {
- kdError(7007) << "Couldn't rename " << tmpFile.name() << " back to " << _src << " !" << endl;
- // Severe error, abort
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
- }
- }
- }
- }
- if ( err )
- {
- // This code is similar to CopyJob::slotResultConflictCopyingFiles
- // but here it's about the base src url being moved/renamed
- // (*m_currentStatSrc) and its dest (m_dest), not about a single file.
- // It also means we already stated the dest, here.
- // On the other hand we haven't stated the src yet (we skipped doing it
- // to save time, since it's not necessary to rename directly!)...
-
- Q_ASSERT( m_currentSrcURL == *m_currentStatSrc );
-
- // Existing dest?
- if ( ( err == ERR_DIR_ALREADY_EXIST ||
- err == ERR_FILE_ALREADY_EXIST ||
- err == ERR_IDENTICAL_FILES )
- && isInteractive() )
- {
- if (m_reportTimer)
- m_reportTimer->stop();
-
- // Should we skip automatically ?
- if ( m_bAutoSkip ) {
- // Move on to next file
- skipSrc();
- return;
- } else if ( m_bOverwriteAll ) {
- ; // nothing to do, stat+copy+del will overwrite
- } else {
- TQString newPath;
- // If src==dest, use "overwrite-itself"
- RenameDlg_Mode mode = (RenameDlg_Mode)
- ( ( m_currentSrcURL == dest ) ? M_OVERWRITE_ITSELF : M_OVERWRITE );
-
- if ( m_srcList.count() > 1 )
- mode = (RenameDlg_Mode) ( mode | M_MULTI | M_SKIP );
- else
- mode = (RenameDlg_Mode) ( mode | M_SINGLE );
-
- // we lack mtime info for both the src (not stated)
- // and the dest (stated but this info wasn't stored)
- // Let's do it for local files, at least
- TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1;
- TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1;
- time_t ctimeSrc = (time_t) -1;
- time_t ctimeDest = (time_t) -1;
- time_t mtimeSrc = (time_t) -1;
- time_t mtimeDest = (time_t) -1;
-
- KDE_struct_stat stat_buf;
- if ( m_currentSrcURL.isLocalFile() &&
- KDE_stat(TQFile::encodeName(m_currentSrcURL.path()), &stat_buf) == 0 ) {
- sizeSrc = stat_buf.st_size;
- ctimeSrc = stat_buf.st_ctime;
- mtimeSrc = stat_buf.st_mtime;
- }
- if ( dest.isLocalFile() &&
- KDE_stat(TQFile::encodeName(dest.path()), &stat_buf) == 0 ) {
- sizeDest = stat_buf.st_size;
- ctimeDest = stat_buf.st_ctime;
- mtimeDest = stat_buf.st_mtime;
- }
-
- RenameDlg_Result r = Observer::self()->open_RenameDlg(
- this,
- err != ERR_DIR_ALREADY_EXIST ? i18n("File Already Exists") : i18n("Already Exists as Folder"),
- m_currentSrcURL.url(),
- dest.url(),
- mode, newPath,
- sizeSrc, sizeDest,
- ctimeSrc, ctimeDest,
- mtimeSrc, mtimeDest );
- if (m_reportTimer)
- m_reportTimer->start(REPORT_TIMEOUT,false);
-
- switch ( r )
- {
- case R_CANCEL:
- {
- m_error = ERR_USER_CANCELED;
- emitResult();
- return;
- }
- case R_RENAME:
- {
- // Set m_dest to the chosen destination
- // This is only for this src url; the next one will revert to d->m_globalDest
- m_dest.setPath( newPath );
- TDEIO::Job* job = TDEIO::stat( m_dest, false, 2, false );
- state = STATE_STATING;
- destinationState = DEST_NOT_STATED;
- addSubjob(job);
- return;
- }
- case R_AUTO_SKIP:
- m_bAutoSkip = true;
- // fall through
- case R_SKIP:
- // Move on to next file
- skipSrc();
- return;
- case R_OVERWRITE_ALL:
- m_bOverwriteAll = true;
- break;
- case R_OVERWRITE:
- // Add to overwrite list
- // Note that we add dest, not m_dest.
- // This ensures that when moving several urls into a dir (m_dest),
- // we only overwrite for the current one, not for all.
- // When renaming a single file (m_asMethod), it makes no difference.
- kdDebug(7007) << "adding to overwrite list: " << dest.path() << endl;
- m_overwriteList.append( dest.path() );
- break;
- default:
- //assert( 0 );
- break;
- }
- }
- } else if ( err != TDEIO::ERR_UNSUPPORTED_ACTION ) {
- kdDebug(7007) << "Couldn't rename " << m_currentSrcURL << " to " << dest << ", aborting" << endl;
- m_error = err;
- m_errorText = errText;
- emitResult();
- return;
- }
- kdDebug(7007) << "Couldn't rename " << m_currentSrcURL << " to " << dest << ", reverting to normal way, starting with stat" << endl;
- //kdDebug(7007) << "TDEIO::stat on " << m_currentSrcURL << endl;
- TDEIO::Job* job = TDEIO::stat( m_currentSrcURL, true, 2, false );
- state = STATE_STATING;
- addSubjob(job);
- m_bOnlyRenames = false;
- }
- else
- {
- //kdDebug(7007) << "Renaming succeeded, move on" << endl;
- emit copyingDone( this, *m_currentStatSrc, dest, true, true );
- statNextSrc();
- }
-}
-
-void CopyJob::slotResult( Job *job )
-{
- //kdDebug(7007) << "CopyJob::slotResult() state=" << (int) state << endl;
- // In each case, what we have to do is :
- // 1 - check for errors and treat them
- // 2 - subjobs.remove(job);
- // 3 - decide what to do next
-
- switch ( state ) {
- case STATE_STATING: // We were trying to stat a src url or the dest
- slotResultStating( job );
- break;
- case STATE_RENAMING: // We were trying to do a direct renaming, before even stat'ing
- {
- slotResultRenaming( job );
- break;
- }
- case STATE_LISTING: // recursive listing finished
- //kdDebug(7007) << "totalSize: " << (unsigned int) m_totalSize << " files: " << files.count() << " dirs: " << dirs.count() << endl;
- // Was there an error ?
- if (job->error())
- {
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
-
- subjobs.remove( job );
- assert ( subjobs.isEmpty() );
-
- statNextSrc();
- break;
- case STATE_CREATING_DIRS:
- slotResultCreatingDirs( job );
- break;
- case STATE_CONFLICT_CREATING_DIRS:
- slotResultConflictCreatingDirs( job );
- break;
- case STATE_COPYING_FILES:
- slotResultCopyingFiles( job );
- break;
- case STATE_CONFLICT_COPYING_FILES:
- slotResultConflictCopyingFiles( job );
- break;
- case STATE_DELETING_DIRS:
- slotResultDeletingDirs( job );
- break;
- case STATE_SETTING_DIR_ATTRIBUTES: // TODO KDE4
- assert( 0 );
- //slotResultSettingDirAttributes( job );
- break;
- default:
- assert( 0 );
- }
-}
-
-void TDEIO::CopyJob::setDefaultPermissions( bool b )
-{
- d->m_defaultPermissions = b;
-}
-
-// KDE4: remove
-void TDEIO::CopyJob::setInteractive( bool b )
-{
- Job::setInteractive( b );
-}
-
-CopyJob *TDEIO::copy(const KURL& src, const KURL& dest, bool showProgressInfo )
-{
- //kdDebug(7007) << "TDEIO::copy src=" << src << " dest=" << dest << endl;
- KURL::List srcList;
- srcList.append( src );
- return new CopyJob( srcList, dest, CopyJob::Copy, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::copyAs(const KURL& src, const KURL& dest, bool showProgressInfo )
-{
- //kdDebug(7007) << "TDEIO::copyAs src=" << src << " dest=" << dest << endl;
- KURL::List srcList;
- srcList.append( src );
- return new CopyJob( srcList, dest, CopyJob::Copy, true, showProgressInfo );
-}
-
-CopyJob *TDEIO::copy( const KURL::List& src, const KURL& dest, bool showProgressInfo )
-{
- //kdDebug(7007) << src << " " << dest << endl;
- return new CopyJob( src, dest, CopyJob::Copy, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::move(const KURL& src, const KURL& dest, bool showProgressInfo )
-{
- //kdDebug(7007) << src << " " << dest << endl;
- KURL::List srcList;
- srcList.append( src );
- return new CopyJob( srcList, dest, CopyJob::Move, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::moveAs(const KURL& src, const KURL& dest, bool showProgressInfo )
-{
- //kdDebug(7007) << src << " " << dest << endl;
- KURL::List srcList;
- srcList.append( src );
- return new CopyJob( srcList, dest, CopyJob::Move, true, showProgressInfo );
-}
-
-CopyJob *TDEIO::move( const KURL::List& src, const KURL& dest, bool showProgressInfo )
-{
- //kdDebug(7007) << src << " " << dest << endl;
- return new CopyJob( src, dest, CopyJob::Move, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::link(const KURL& src, const KURL& destDir, bool showProgressInfo )
-{
- KURL::List srcList;
- srcList.append( src );
- return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::link(const KURL::List& srcList, const KURL& destDir, bool showProgressInfo )
-{
- return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::linkAs(const KURL& src, const KURL& destDir, bool showProgressInfo )
-{
- KURL::List srcList;
- srcList.append( src );
- return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::trash(const KURL& src, bool showProgressInfo )
-{
- KURL::List srcList;
- srcList.append( src );
- return new CopyJob( srcList, KURL( "trash:/" ), CopyJob::Move, false, showProgressInfo );
-}
-
-CopyJob *TDEIO::trash(const KURL::List& srcList, bool showProgressInfo )
-{
- return new CopyJob( srcList, KURL( "trash:/" ), CopyJob::Move, false, showProgressInfo );
-}
-
-//////////
-
-DeleteJob::DeleteJob( const KURL::List& src, bool /*shred*/, bool showProgressInfo )
-: Job(showProgressInfo), m_totalSize( 0 ), m_processedSize( 0 ), m_fileProcessedSize( 0 ),
- m_processedFiles( 0 ), m_processedDirs( 0 ), m_totalFilesDirs( 0 ),
- m_srcList(src), m_currentStat(m_srcList.begin()), m_reportTimer(0)
-{
- if ( showProgressInfo ) {
-
- connect( this, TQT_SIGNAL( totalFiles( TDEIO::Job*, unsigned long ) ),
- Observer::self(), TQT_SLOT( slotTotalFiles( TDEIO::Job*, unsigned long ) ) );
-
- connect( this, TQT_SIGNAL( totalDirs( TDEIO::Job*, unsigned long ) ),
- Observer::self(), TQT_SLOT( slotTotalDirs( TDEIO::Job*, unsigned long ) ) );
-
- // See slotReport
- /*connect( this, TQT_SIGNAL( processedFiles( TDEIO::Job*, unsigned long ) ),
- m_observer, TQT_SLOT( slotProcessedFiles( TDEIO::Job*, unsigned long ) ) );
-
- connect( this, TQT_SIGNAL( processedDirs( TDEIO::Job*, unsigned long ) ),
- m_observer, TQT_SLOT( slotProcessedDirs( TDEIO::Job*, unsigned long ) ) );
-
- connect( this, TQT_SIGNAL( deleting( TDEIO::Job*, const KURL& ) ),
- m_observer, TQT_SLOT( slotDeleting( TDEIO::Job*, const KURL& ) ) );*/
-
- m_reportTimer=new TQTimer(this);
- connect(m_reportTimer,TQT_SIGNAL(timeout()),this,TQT_SLOT(slotReport()));
- //this will update the report dialog with 5 Hz, I think this is fast enough, aleXXX
- m_reportTimer->start(REPORT_TIMEOUT,false);
- }
-
- TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
-}
-
-void DeleteJob::slotStart()
-{
- statNextSrc();
-}
-
-//this is called often, so calling the functions
-//from Observer here directly might improve the performance a little bit
-//aleXXX
-void DeleteJob::slotReport()
-{
- if (m_progressId==0)
- return;
-
- Observer * observer = Observer::self();
-
- emit deleting( this, m_currentURL );
- observer->slotDeleting(this,m_currentURL);
-
- switch( state ) {
- case STATE_STATING:
- case STATE_LISTING:
- emit totalSize( this, m_totalSize );
- emit totalFiles( this, files.count() );
- emit totalDirs( this, dirs.count() );
- break;
- case STATE_DELETING_DIRS:
- emit processedDirs( this, m_processedDirs );
- observer->slotProcessedDirs(this,m_processedDirs);
- emitPercent( m_processedFiles + m_processedDirs, m_totalFilesDirs );
- break;
- case STATE_DELETING_FILES:
- observer->slotProcessedFiles(this,m_processedFiles);
- emit processedFiles( this, m_processedFiles );
- emitPercent( m_processedFiles, m_totalFilesDirs );
- break;
- }
-}
-
-
-void DeleteJob::slotEntries(TDEIO::Job* job, const UDSEntryList& list)
-{
- UDSEntryListConstIterator it = list.begin();
- UDSEntryListConstIterator end = list.end();
- for (; it != end; ++it)
- {
- UDSEntry::ConstIterator it2 = (*it).begin();
- bool bDir = false;
- bool bLink = false;
- TQString displayName;
- KURL url;
- int atomsFound(0);
- for( ; it2 != (*it).end(); it2++ )
- {
- switch ((*it2).m_uds)
- {
- case UDS_FILE_TYPE:
- bDir = S_ISDIR((*it2).m_long);
- atomsFound++;
- break;
- case UDS_NAME:
- displayName = (*it2).m_str;
- atomsFound++;
- break;
- case UDS_URL:
- url = KURL((*it2).m_str);
- atomsFound++;
- break;
- case UDS_LINK_DEST:
- bLink = !(*it2).m_str.isEmpty();
- atomsFound++;
- break;
- case UDS_SIZE:
- m_totalSize += (TDEIO::filesize_t)((*it2).m_long);
- atomsFound++;
- break;
- default:
- break;
- }
- if (atomsFound==5) break;
- }
- assert(!displayName.isEmpty());
- if (displayName != ".." && displayName != ".")
- {
- if( url.isEmpty() ) {
- url = ((SimpleJob *)job)->url(); // assumed to be a dir
- url.addPath( displayName );
- }
- //kdDebug(7007) << "DeleteJob::slotEntries " << displayName << " (" << url << ")" << endl;
- if ( bLink )
- symlinks.append( url );
- else if ( bDir )
- dirs.append( url );
- else
- files.append( url );
- }
- }
-}
-
-
-void DeleteJob::statNextSrc()
-{
- //kdDebug(7007) << "statNextSrc" << endl;
- if ( m_currentStat != m_srcList.end() )
- {
- m_currentURL = (*m_currentStat);
-
- // if the file system doesn't support deleting, we do not even stat
- if (!KProtocolInfo::supportsDeleting(m_currentURL)) {
- TQGuardedPtr<DeleteJob> that = this;
- ++m_currentStat;
- if (isInteractive())
- KMessageBox::information( 0, buildErrorString(ERR_CANNOT_DELETE, m_currentURL.prettyURL()));
- if (that)
- statNextSrc();
- return;
- }
- // Stat it
- state = STATE_STATING;
- TDEIO::SimpleJob * job = TDEIO::stat( m_currentURL, true, 1, false );
- Scheduler::scheduleJob(job);
- //kdDebug(7007) << "TDEIO::stat (DeleteJob) " << m_currentURL << endl;
- addSubjob(job);
- //if ( m_progressId ) // Did we get an ID from the observer ?
- // Observer::self()->slotDeleting( this, *it ); // show asap
- } else
- {
- m_totalFilesDirs = files.count()+symlinks.count() + dirs.count();
- slotReport();
- // Now we know which dirs hold the files we're going to delete.
- // To speed things up and prevent double-notification, we disable KDirWatch
- // on those dirs temporarily (using KDirWatch::self, that's the instanced
- // used by e.g. kdirlister).
- for ( TQStringList::Iterator it = m_parentDirs.begin() ; it != m_parentDirs.end() ; ++it )
- KDirWatch::self()->stopDirScan( *it );
- state = STATE_DELETING_FILES;
- deleteNextFile();
- }
-}
-
-void DeleteJob::deleteNextFile()
-{
- //kdDebug(7007) << "deleteNextFile" << endl;
- if ( !files.isEmpty() || !symlinks.isEmpty() )
- {
- SimpleJob *job;
- do {
- // Take first file to delete out of list
- KURL::List::Iterator it = files.begin();
- bool isLink = false;
- if ( it == files.end() ) // No more files
- {
- it = symlinks.begin(); // Pick up a symlink to delete
- isLink = true;
- }
- // Normal deletion
- // If local file, try do it directly
- if ( (*it).isLocalFile() && unlink( TQFile::encodeName((*it).path()) ) == 0 ) {
- //kdDebug(7007) << "DeleteJob deleted " << (*it).path() << endl;
- job = 0;
- m_processedFiles++;
- if ( m_processedFiles % 300 == 0 || m_totalFilesDirs < 300) { // update progress info every 300 files
- m_currentURL = *it;
- slotReport();
- }
- } else
- { // if remote - or if unlink() failed (we'll use the job's error handling in that case)
- job = TDEIO::file_delete( *it, false /*no GUI*/);
- Scheduler::scheduleJob(job);
- m_currentURL=(*it);
- }
- if ( isLink )
- symlinks.remove(it);
- else
- files.remove(it);
- if ( job ) {
- addSubjob(job);
- return;
- }
- // loop only if direct deletion worked (job=0) and there is something else to delete
- } while (!job && (!files.isEmpty() || !symlinks.isEmpty()));
- }
- state = STATE_DELETING_DIRS;
- deleteNextDir();
-}
-
-void DeleteJob::deleteNextDir()
-{
- if ( !dirs.isEmpty() ) // some dirs to delete ?
- {
- do {
- // Take first dir to delete out of list - last ones first !
- KURL::List::Iterator it = dirs.fromLast();
- // If local dir, try to rmdir it directly
- if ( (*it).isLocalFile() && ::rmdir( TQFile::encodeName((*it).path()) ) == 0 ) {
-
- m_processedDirs++;
- if ( m_processedDirs % 100 == 0 ) { // update progress info every 100 dirs
- m_currentURL = *it;
- slotReport();
- }
- } else {
- SimpleJob* job;
- if ( KProtocolInfo::canDeleteRecursive( *it ) ) {
- // If the ioslave supports recursive deletion of a directory, then
- // we only need to send a single CMD_DEL command, so we use file_delete :)
- job = TDEIO::file_delete( *it, false /*no gui*/ );
- } else {
- job = TDEIO::rmdir( *it );
- }
- Scheduler::scheduleJob(job);
- dirs.remove(it);
- addSubjob( job );
- return;
- }
- dirs.remove(it);
- } while ( !dirs.isEmpty() );
- }
-
- // Re-enable watching on the dirs that held the deleted files
- for ( TQStringList::Iterator it = m_parentDirs.begin() ; it != m_parentDirs.end() ; ++it )
- KDirWatch::self()->restartDirScan( *it );
-
- // Finished - tell the world
- if ( !m_srcList.isEmpty() )
- {
- KDirNotify_stub allDirNotify("*", "KDirNotify*");
- //kdDebug(7007) << "KDirNotify'ing FilesRemoved " << m_srcList.toStringList() << endl;
- allDirNotify.FilesRemoved( m_srcList );
- }
- if (m_reportTimer!=0)
- m_reportTimer->stop();
- emitResult();
-}
-
-void DeleteJob::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size )
-{
- // Note: this is the same implementation as CopyJob::slotProcessedSize but
- // it's different from FileCopyJob::slotProcessedSize - which is why this
- // is not in Job.
-
- m_fileProcessedSize = data_size;
- setProcessedSize(m_processedSize + m_fileProcessedSize);
-
- //kdDebug(7007) << "DeleteJob::slotProcessedSize " << (unsigned int) (m_processedSize + m_fileProcessedSize) << endl;
-
- emit processedSize( this, m_processedSize + m_fileProcessedSize );
-
- // calculate percents
- unsigned long ipercent = m_percent;
-
- if ( m_totalSize == 0 )
- m_percent = 100;
- else
- m_percent = (unsigned long)(( (float)(m_processedSize + m_fileProcessedSize) / (float)m_totalSize ) * 100.0);
-
- if ( m_percent > ipercent )
- {
- emit percent( this, m_percent );
- //kdDebug(7007) << "DeleteJob::slotProcessedSize - percent = " << (unsigned int) m_percent << endl;
- }
-
-}
-
-void DeleteJob::slotResult( Job *job )
-{
- switch ( state )
- {
- case STATE_STATING:
- {
- // Was there an error while stating ?
- if (job->error() )
- {
- // Probably : doesn't exist
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
-
- // Is it a file or a dir ?
- UDSEntry entry = ((StatJob*)job)->statResult();
- bool bDir = false;
- bool bLink = false;
- TDEIO::filesize_t size = (TDEIO::filesize_t)-1;
- UDSEntry::ConstIterator it2 = entry.begin();
- int atomsFound(0);
- for( ; it2 != entry.end(); it2++ )
- {
- if ( ((*it2).m_uds) == UDS_FILE_TYPE )
- {
- bDir = S_ISDIR( (mode_t)(*it2).m_long );
- atomsFound++;
- }
- else if ( ((*it2).m_uds) == UDS_LINK_DEST )
- {
- bLink = !((*it2).m_str.isEmpty());
- atomsFound++;
- }
- else if ( ((*it2).m_uds) == UDS_SIZE )
- {
- size = (*it2).m_long;
- atomsFound++;
- }
- if (atomsFound==3) break;
- }
-
- KURL url = ((SimpleJob*)job)->url();
-
- subjobs.remove( job );
- assert( subjobs.isEmpty() );
-
- if (bDir && !bLink)
- {
- // Add toplevel dir in list of dirs
- dirs.append( url );
- if ( url.isLocalFile() && !m_parentDirs.contains( url.path(-1) ) )
- m_parentDirs.append( url.path(-1) );
-
- if ( !KProtocolInfo::canDeleteRecursive( url ) ) {
- //kdDebug(7007) << " Target is a directory " << endl;
- // List it
- state = STATE_LISTING;
- ListJob *newjob = listRecursive( url, false );
- newjob->setUnrestricted(true); // No KIOSK restrictions
- Scheduler::scheduleJob(newjob);
- connect(newjob, TQT_SIGNAL(entries( TDEIO::Job *,
- const TDEIO::UDSEntryList& )),
- TQT_SLOT( slotEntries( TDEIO::Job*,
- const TDEIO::UDSEntryList& )));
- addSubjob(newjob);
- } else {
- ++m_currentStat;
- statNextSrc();
- }
- }
- else
- {
- if ( bLink ) {
- //kdDebug(7007) << " Target is a symlink" << endl;
- symlinks.append( url );
- } else {
- //kdDebug(7007) << " Target is a file" << endl;
- files.append( url );
- }
- if ( url.isLocalFile() && !m_parentDirs.contains( url.directory(false) ) )
- m_parentDirs.append( url.directory(false) );
- ++m_currentStat;
- statNextSrc();
- }
- }
- break;
- case STATE_LISTING:
- if ( job->error() )
- {
- // Try deleting nonetheless, it may be empty (and non-listable)
- }
- subjobs.remove( job );
- assert( subjobs.isEmpty() );
- ++m_currentStat;
- statNextSrc();
- break;
- case STATE_DELETING_FILES:
- if ( job->error() )
- {
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
- subjobs.remove( job );
- assert( subjobs.isEmpty() );
- m_processedFiles++;
-
- deleteNextFile();
- break;
- case STATE_DELETING_DIRS:
- if ( job->error() )
- {
- Job::slotResult( job ); // will set the error and emit result(this)
- return;
- }
- subjobs.remove( job );
- assert( subjobs.isEmpty() );
- m_processedDirs++;
- //emit processedDirs( this, m_processedDirs );
- //if (!m_shred)
- //emitPercent( m_processedFiles + m_processedDirs, m_totalFilesDirs );
-
- deleteNextDir();
- break;
- default:
- assert(0);
- }
-}
-
-DeleteJob *TDEIO::del( const KURL& src, bool shred, bool showProgressInfo )
-{
- KURL::List srcList;
- srcList.append( src );
- DeleteJob *job = new DeleteJob( srcList, shred, showProgressInfo );
- return job;
-}
-
-DeleteJob *TDEIO::del( const KURL::List& src, bool shred, bool showProgressInfo )
-{
- DeleteJob *job = new DeleteJob( src, shred, showProgressInfo );
- return job;
-}
-
-MultiGetJob::MultiGetJob(const KURL& url,
- bool showProgressInfo)
- : TransferJob(url, 0, TQByteArray(), TQByteArray(), showProgressInfo)
-{
- m_waitQueue.setAutoDelete(true);
- m_activeQueue.setAutoDelete(true);
- m_currentEntry = 0;
-}
-
-void MultiGetJob::get(long id, const KURL &url, const MetaData &metaData)
-{
- GetRequest *entry = new GetRequest(id, url, metaData);
- entry->metaData["request-id"] = TQString("%1").arg(id);
- m_waitQueue.append(entry);
-}
-
-void MultiGetJob::flushQueue(TQPtrList<GetRequest> &queue)
-{
- GetRequest *entry;
- // Use multi-get
- // Scan all jobs in m_waitQueue
- for(entry = m_waitQueue.first(); entry; )
- {
- if ((m_url.protocol() == entry->url.protocol()) &&
- (m_url.host() == entry->url.host()) &&
- (m_url.port() == entry->url.port()) &&
- (m_url.user() == entry->url.user()))
- {
- m_waitQueue.take();
- queue.append(entry);
- entry = m_waitQueue.current();
- }
- else
- {
- entry = m_waitQueue.next();
- }
- }
- // Send number of URLs, (URL, metadata)*
- KIO_ARGS << (TQ_INT32) queue.count();
- for(entry = queue.first(); entry; entry = queue.next())
- {
- stream << entry->url << entry->metaData;
- }
- m_packedArgs = packedArgs;
- m_command = CMD_MULTI_GET;
- m_outgoingMetaData.clear();
-}
-
-void MultiGetJob::start(Slave *slave)
-{
- // Add first job from m_waitQueue and add it to m_activeQueue
- GetRequest *entry = m_waitQueue.take(0);
- m_activeQueue.append(entry);
-
- m_url = entry->url;
-
- if (!entry->url.protocol().startsWith("http"))
- {
- // Use normal get
- KIO_ARGS << entry->url;
- m_packedArgs = packedArgs;
- m_outgoingMetaData = entry->metaData;
- m_command = CMD_GET;
- b_multiGetActive = false;
- }
- else
- {
- flushQueue(m_activeQueue);
- b_multiGetActive = true;
- }
-
- TransferJob::start(slave); // Anything else to do??
-}
-
-bool MultiGetJob::findCurrentEntry()
-{
- if (b_multiGetActive)
- {
- long id = m_incomingMetaData["request-id"].toLong();
- for(GetRequest *entry = m_activeQueue.first(); entry; entry = m_activeQueue.next())
- {
- if (entry->id == id)
- {
- m_currentEntry = entry;
- return true;
- }
- }
- m_currentEntry = 0;
- return false;
- }
- else
- {
- m_currentEntry = m_activeQueue.first();
- return (m_currentEntry != 0);
- }
-}
-
-void MultiGetJob::slotRedirection( const KURL &url)
-{
- if (!findCurrentEntry()) return; // Error
- if (kapp && !kapp->authorizeURLAction("redirect", m_url, url))
- {
- kdWarning(7007) << "MultiGetJob: Redirection from " << m_currentEntry->url << " to " << url << " REJECTED!" << endl;
- return;
- }
- m_redirectionURL = url;
- if (m_currentEntry->url.hasUser() && !url.hasUser() && (m_currentEntry->url.host().lower() == url.host().lower()))
- m_redirectionURL.setUser(m_currentEntry->url.user()); // Preserve user
- get(m_currentEntry->id, m_redirectionURL, m_currentEntry->metaData); // Try again
-}
-
-
-void MultiGetJob::slotFinished()
-{
- if (!findCurrentEntry()) return;
- if (m_redirectionURL.isEmpty())
- {
- // No redirection, tell the world that we are finished.
- emit result(m_currentEntry->id);
- }
- m_redirectionURL = KURL();
- m_error = 0;
- m_incomingMetaData.clear();
- m_activeQueue.removeRef(m_currentEntry);
- if (m_activeQueue.count() == 0)
- {
- if (m_waitQueue.count() == 0)
- {
- // All done
- TransferJob::slotFinished();
- }
- else
- {
- // return slave to pool
- // fetch new slave for first entry in m_waitQueue and call start
- // again.
- GetRequest *entry = m_waitQueue.at(0);
- m_url = entry->url;
- slaveDone();
- Scheduler::doJob(this);
- }
- }
-}
-
-void MultiGetJob::slotData( const TQByteArray &_data)
-{
- if(!m_currentEntry) return;// Error, unknown request!
- if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error)
- emit data(m_currentEntry->id, _data);
-}
-
-void MultiGetJob::slotMimetype( const TQString &_mimetype )
-{
- if (b_multiGetActive)
- {
- TQPtrList<GetRequest> newQueue;
- flushQueue(newQueue);
- if (!newQueue.isEmpty())
- {
- while(!newQueue.isEmpty())
- m_activeQueue.append(newQueue.take(0));
- m_slave->send( m_command, m_packedArgs );
- }
- }
- if (!findCurrentEntry()) return; // Error, unknown request!
- emit mimetype(m_currentEntry->id, _mimetype);
-}
-
-MultiGetJob *TDEIO::multi_get(long id, const KURL &url, const MetaData &metaData)
-{
- MultiGetJob * job = new MultiGetJob( url, false );
- job->get(id, url, metaData);
- return job;
-}
-
-
-#ifdef CACHE_INFO
-CacheInfo::CacheInfo(const KURL &url)
-{
- m_url = url;
-}
-
-TQString CacheInfo::cachedFileName()
-{
- const TQChar separator = '_';
-
- TQString CEF = m_url.path();
-
- int p = CEF.find('/');
-
- while(p != -1)
- {
- CEF[p] = separator;
- p = CEF.find('/', p);
- }
-
- TQString host = m_url.host().lower();
- CEF = host + CEF + '_';
-
- TQString dir = KProtocolManager::cacheDir();
- if (dir[dir.length()-1] != '/')
- dir += "/";
-
- int l = m_url.host().length();
- for(int i = 0; i < l; i++)
- {
- if (host[i].isLetter() && (host[i] != 'w'))
- {
- dir += host[i];
- break;
- }
- }
- if (dir[dir.length()-1] == '/')
- dir += "0";
-
- unsigned long hash = 0x00000000;
- TQCString u = m_url.url().latin1();
- for(int i = u.length(); i--;)
- {
- hash = (hash * 12211 + u[i]) % 2147483563;
- }
-
- TQString hashString;
- hashString.sprintf("%08lx", hash);
-
- CEF = CEF + hashString;
-
- CEF = dir + "/" + CEF;
-
- return CEF;
-}
-
-TQFile *CacheInfo::cachedFile()
-{
-#ifdef Q_WS_WIN
- const char *mode = (readWrite ? "rb+" : "rb");
-#else
- const char *mode = (readWrite ? "r+" : "r");
-#endif
-
- FILE *fs = fopen(TQFile::encodeName(CEF), mode); // Open for reading and writing
- if (!fs)
- return 0;
-
- char buffer[401];
- bool ok = true;
-
- // CacheRevision
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
- ok = false;
-
- time_t date;
- time_t currentDate = time(0);
-
- // URL
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- int l = strlen(buffer);
- if (l>0)
- buffer[l-1] = 0; // Strip newline
- if (m_.url.url() != buffer)
- {
- ok = false; // Hash collision
- }
- }
-
- // Creation Date
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- date = (time_t) strtoul(buffer, 0, 10);
- if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
- {
- m_bMustRevalidate = true;
- m_expireDate = currentDate;
- }
- }
-
- // Expiration Date
- m_cacheExpireDateOffset = ftell(fs);
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- if (m_request.cache == CC_Verify)
- {
- date = (time_t) strtoul(buffer, 0, 10);
- // After the expire date we need to revalidate.
- if (!date || difftime(currentDate, date) >= 0)
- m_bMustRevalidate = true;
- m_expireDate = date;
- }
- }
-
- // ETag
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- m_etag = TQString(buffer).stripWhiteSpace();
- }
-
- // Last-Modified
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- m_lastModified = TQString(buffer).stripWhiteSpace();
- }
-
- fclose(fs);
-
- if (ok)
- return fs;
-
- unlink( TQFile::encodeName(CEF) );
- return 0;
-
-}
-
-void CacheInfo::flush()
-{
- cachedFile().remove();
-}
-
-void CacheInfo::touch()
-{
-
-}
-void CacheInfo::setExpireDate(int);
-void CacheInfo::setExpireTimeout(int);
-
-
-int CacheInfo::creationDate();
-int CacheInfo::expireDate();
-int CacheInfo::expireTimeout();
-#endif
-
-void Job::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-void SimpleJob::virtual_hook( int id, void* data )
-{ TDEIO::Job::virtual_hook( id, data ); }
-
-void MkdirJob::virtual_hook( int id, void* data )
-{ SimpleJob::virtual_hook( id, data ); }
-
-void StatJob::virtual_hook( int id, void* data )
-{ SimpleJob::virtual_hook( id, data ); }
-
-void TransferJob::virtual_hook( int id, void* data )
-{ SimpleJob::virtual_hook( id, data ); }
-
-void MultiGetJob::virtual_hook( int id, void* data )
-{ TransferJob::virtual_hook( id, data ); }
-
-void MimetypeJob::virtual_hook( int id, void* data )
-{ TransferJob::virtual_hook( id, data ); }
-
-void FileCopyJob::virtual_hook( int id, void* data )
-{ Job::virtual_hook( id, data ); }
-
-void ListJob::virtual_hook( int id, void* data )
-{ SimpleJob::virtual_hook( id, data ); }
-
-void CopyJob::virtual_hook( int id, void* data )
-{ Job::virtual_hook( id, data ); }
-
-void DeleteJob::virtual_hook( int id, void* data )
-{ Job::virtual_hook( id, data ); }
-
-void LocalURLJob::virtual_hook( int id, void* data )
-{ Job::virtual_hook( id, data ); }
-
-
-#include "jobclasses.moc"
diff --git a/kio/kio/job.h b/kio/kio/job.h
deleted file mode 100644
index f5254df39..000000000
--- a/kio/kio/job.h
+++ /dev/null
@@ -1,532 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_job_h__
-#define __kio_job_h__
-
-#include <kio/jobclasses.h>
-
-namespace TDEIO {
-
-
- /**
- * Creates a single directory.
- *
- *
- *
- *
- * @param url The URL of the directory to create.
- * @param permissions The permissions to set after creating the
- * directory (unix-style), -1 for default permissions.
- * @return A pointer to the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob * mkdir( const KURL& url, int permissions = -1 );
-
- /**
- * Removes a single directory.
- *
- * The directory is assumed to be empty.
- *
- *
- *
- * @param url The URL of the directory to remove.
- * @return A pointer to the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob * rmdir( const KURL& url );
-
- /**
- * Changes permissions on a file or directory.
- * See the other chmod below for changing many files
- * or directories.
- *
- * @param url The URL of file or directory.
- * @param permissions The permissions to set.
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob * chmod( const KURL& url, int permissions );
-
- /**
- * Rename a file or directory.
- * Warning: this operation fails if a direct renaming is not
- * possible (like with files or dirs on separate partitions)
- * Use move or file_move in this case.
- *
- * @param src The original URL
- * @param dest The final URL
- * @param overwrite whether to automatically overwrite if the dest exists
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob * rename( const KURL& src, const KURL & dest, bool overwrite );
-
- /**
- * Create or move a symlink.
- * This is the lowlevel operation, similar to file_copy and file_move.
- * It doesn't do any check (other than those the slave does)
- * and it doesn't show rename and skip dialogs - use TDEIO::link for that.
- * @param target The string that will become the "target" of the link (can be relative)
- * @param dest The symlink to create.
- * @param overwrite whether to automatically overwrite if the dest exists
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob * symlink( const TQString & target, const KURL& dest, bool overwrite, bool showProgressInfo = true );
-
- /**
- * Execute any command that is specific to one slave (protocol).
- *
- * Examples are : HTTP POST, mount and unmount (kio_file)
- *
- * @param url The URL isn't passed to the slave, but is used to know
- * which slave to send it to :-)
- * @param data Packed data. The meaning is completely dependent on the
- * slave, but usually starts with an int for the command number.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob * special( const KURL& url, const TQByteArray & data, bool showProgressInfo = true );
-
- /**
- * Mount filesystem.
- *
- * Special job for @p kio_file.
- *
- * @param ro Mount read-only if @p true.
- * @param fstype File system type (e.g. "ext2", can be 0L).
- * @param dev Device (e.g. /dev/sda0).
- * @param point Mount point, can be @p null.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob *mount( bool ro, const char *fstype, const TQString& dev, const TQString& point, bool showProgressInfo = true );
-
- /**
- * Unmount filesystem.
- *
- * Special job for @p kio_file.
- *
- * @param point Point to unmount.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob *unmount( const TQString & point, bool showProgressInfo = true );
-
- /**
- * Retrieve local URL if available
- *
- * @param remoteURL the remote URL to get the local URL for
- * @return the job handling the operation.
- */
- TDEIO_EXPORT LocalURLJob *localURL( const KURL& remoteUrl );
-
- /**
- * HTTP cache update
- *
- * @param url Url to update, protocol must be "http".
- * @param no_cache If true, cache entry for @p url is deleted.
- * @param expireDate Local machine time indicating when the entry is
- * supposed to expire.
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob *http_update_cache( const KURL& url, bool no_cache, time_t expireDate);
-
- /**
- * Find all details for one file or directory.
- *
- * @param url the URL of the file
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT StatJob * stat( const KURL& url, bool showProgressInfo = true );
- /**
- * Find all details for one file or directory.
- * This version of the call includes two additional booleans, @p sideIsSource and @p details.
- *
- * @param url the URL of the file
- * @param sideIsSource is true when stating a source file (we will do a get on it if
- * the stat works) and false when stating a destination file (target of a copy).
- * The reason for this parameter is that in some cases the kioslave might not
- * be able to determine a file's existence (e.g. HTTP doesn't allow it, FTP
- * has issues with case-sensitivity on some systems).
- * When the slave can't reliably determine the existence of a file, it will:
- * @li be optimistic if sideIsSource=true, i.e. it will assume the file exists,
- * and if it doesn't this will appear when actually trying to download it
- * @li be pessimistic if sideIsSource=false, i.e. it will assume the file
- * doesn't exist, to prevent showing "about to overwrite" errors to the user.
- * If you simply want to check for existence without downloading/uploading afterwards,
- * then you should use sideIsSource=false.
- *
- * @param details selects the level of details we want.
- * By default this is 2 (all details wanted, including modification time, size, etc.),
- * setDetails(1) is used when deleting: we don't need all the information if it takes
- * too much time, no need to follow symlinks etc.
- * setDetails(0) is used for very simple probing: we'll only get the answer
- * "it's a file or a directory, or it doesn't exist". This is used by KRun.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT StatJob * stat( const KURL& url, bool sideIsSource, short int details, bool showProgressInfo = true );
-
- /**
- * Get (a.k.a. read).
- *
- * The slave emits the data through data().
- * @param url the URL of the file
- * @param reload true to reload the file, false if it can be taken from the cache
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT TransferJob *get( const KURL& url, bool reload=false, bool showProgressInfo = true );
-
- /**
- * Put (a.k.a. write)
- *
- * @param url Where to write data.
- * @param permissions May be -1. In this case no special permission mode is set.
- * @param overwrite If true, any existing file will be overwritten.
- * @param resume true to resume an operation. Warning, setting this to true means
- * that the data will be appended to @p dest if @p dest exists.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- * @see multi_get()
- */
- TDEIO_EXPORT TransferJob *put( const KURL& url, int permissions,
- bool overwrite, bool resume, bool showProgressInfo = true );
-
- /**
- * HTTP POST (for form data).
- *
- * Example:
- * \code
- * job = TDEIO::http_post( url, postData, false );
- * job->addMetaData("content-type", contentType );
- * job->addMetaData("referrer", referrerURL);
- * \endcode
- *
- * @p postData is the data that you want to send and
- * @p contentType is the complete HTTP header line that
- * specifies the content's MIME type, for example
- * "Content-Type: text/xml".
- *
- * You MUST specify content-type!
- *
- * Often @p contentType is
- * "Content-Type: application/x-www-form-urlencoded" and
- * the @p postData is then an ASCII string (without null-termination!)
- * with characters like space, linefeed and percent escaped like %20,
- * %0A and %25.
- *
- * @param url Where to write the data.
- * @param postData Encoded data to post.
- * @param showProgressInfo true to display
- * @return the job handling the operation.
- */
- TDEIO_EXPORT TransferJob *http_post( const KURL& url, const TQByteArray &postData,
- bool showProgressInfo = true );
-
- /**
- * Get (a.k.a. read), into a single TQByteArray.
- * @see StoredTransferJob
- *
- * @param url the URL of the file
- * @param reload true to reload the file, false if it can be taken from the cache
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- * @since 3.3
- */
- TDEIO_EXPORT StoredTransferJob *storedGet( const KURL& url, bool reload=false, bool showProgressInfo = true );
-
- /**
- * Put (a.k.a. write) data from a single TQByteArray.
- * @see StoredTransferJob
- *
- * @param arr The data to write
- * @param url Where to write data.
- * @param permissions May be -1. In this case no special permission mode is set.
- * @param overwrite If true, any existing file will be overwritten.
- * @param resume true to resume an operation. Warning, setting this to true means
- * that the data will be appended to @p dest if @p dest exists.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- * @since 3.3
- */
- TDEIO_EXPORT StoredTransferJob *storedPut( const TQByteArray& arr, const KURL& url, int permissions,
- bool overwrite, bool resume, bool showProgressInfo = true );
-
- /**
- * Creates a new multiple get job.
- *
- * @param id the id of the get operation
- * @param url the URL of the file
- * @param metaData the MetaData associated with the file
- *
- * @return the job handling the operation.
- * @see get()
- */
- TDEIO_EXPORT MultiGetJob *multi_get( long id, const KURL &url, const MetaData &metaData);
-
- /**
- * Find mimetype for one file or directory.
- *
- * @param url the URL of the file
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT MimetypeJob * mimetype( const KURL& url,
- bool showProgressInfo = true );
-
- /**
- * Copy a single file.
- *
- * Uses either SlaveBase::copy() if the slave supports that
- * or get() and put() otherwise.
- * @param src Where to get the file.
- * @param dest Where to put the file.
- * @param permissions May be -1. In this case no special permission mode is set.
- * @param overwrite If true, any existing file will be overwritten.
- * @param resume true to resume an operation. Warning, setting this to true means
- * that @p src will be appended to @p dest if @p dest exists.
- * You probably don't want that, so leave it to false :)
- *
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT FileCopyJob *file_copy( const KURL& src, const KURL& dest, int permissions=-1,
- bool overwrite=false, bool resume=false,
- bool showProgressInfo = true);
-
- /**
- * Move a single file.
- *
- * Use either SlaveBase::rename() if the slave supports that,
- * or copy() and del() otherwise, or eventually get() & put() & del()
- * @param src Where to get the file.
- * @param dest Where to put the file.
- * @param permissions May be -1. In this case no special permission mode is set.
- * @param overwrite If @p true, any existing file will be overwritten.
- * @param resume true to resume an operation. Warning, setting this to true means
- * that @p src will be appended to @p dest if @p dest exists.
- * You probably don't want that, so leave it to false :)
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT FileCopyJob *file_move( const KURL& src, const KURL& dest, int permissions=-1,
- bool overwrite=false, bool resume=false,
- bool showProgressInfo = true);
-
- /**
- * Delete a single file.
- *
- * @param src File to delete.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation.
- */
- TDEIO_EXPORT SimpleJob *file_delete( const KURL& src, bool showProgressInfo = true);
-
- /**
- * List the contents of @p url, which is assumed to be a directory.
- *
- * "." and ".." are returned, filter them out if you don't want them.
- *
- *
- * @param url the url of the directory
- * @param showProgressInfo true to show progress information
- * @param includeHidden true for all files, false to cull out UNIX hidden
- * files/dirs (whose names start with dot)
- * @return the job handling the operation.
- */
- TDEIO_EXPORT ListJob *listDir( const KURL& url, bool showProgressInfo = true,
- bool includeHidden = true );
-
- /**
- * The same as the previous method, but recurses subdirectories.
- * Directory links are not followed.
- *
- * "." and ".." are returned but only for the toplevel directory.
- * Filter them out if you don't want them.
- *
- * @param url the url of the directory
- * @param showProgressInfo true to show progress information
- * @param includeHidden true for all files, false to cull out UNIX hidden
- * files/dirs (whose names start with dot)
- * @return the job handling the operation.
- */
- TDEIO_EXPORT ListJob *listRecursive( const KURL& url, bool showProgressInfo = true,
- bool includeHidden = true );
-
- /**
- * Copy a file or directory @p src into the destination @p dest,
- * which can be a file (including the final filename) or a directory
- * (into which @p src will be copied).
- *
- * This emulates the cp command completely.
- *
- * @param src the file or directory to copy
- * @param dest the destination
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @see copyAs()
- */
- TDEIO_EXPORT CopyJob *copy( const KURL& src, const KURL& dest, bool showProgressInfo = true );
-
- /**
- * Copy a file or directory @p src into the destination @p dest,
- * which is the destination name in any case, even for a directory.
- *
- * As opposed to copy(), this doesn't emulate cp, but is the only
- * way to copy a directory, giving it a new name and getting an error
- * box if a directory already exists with the same name.
- *
- * @param src the file or directory to copy
- * @param dest the destination
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- */
- TDEIO_EXPORT CopyJob *copyAs( const KURL& src, const KURL& dest, bool showProgressInfo = true );
-
- /**
- * Copy a list of file/dirs @p src into a destination directory @p dest.
- *
- * @param src the list of files and/or directories
- * @param dest the destination
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- */
- TDEIO_EXPORT CopyJob *copy( const KURL::List& src, const KURL& dest, bool showProgressInfo = true );
-
- /**
- * Moves a file or directory @p src to the given destination @p dest.
- *
- * @param src the file or directory to copy
- * @param dest the destination
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @see copy()
- * @see moveAs()
- */
- TDEIO_EXPORT CopyJob *move( const KURL& src, const KURL& dest, bool showProgressInfo = true );
- /**
- * Moves a file or directory @p src to the given destination @p dest. Unlike move()
- * this operation will fail when the directory already exists.
- *
- * @param src the file or directory to copy
- * @param dest the destination
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @see copyAs()
- */
- TDEIO_EXPORT CopyJob *moveAs( const KURL& src, const KURL& dest, bool showProgressInfo = true );
- /**
- * Moves a list of files or directories @p src to the given destination @p dest.
- *
- * @param src the list of files or directories to copy
- * @param dest the destination
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @see copy()
- */
- TDEIO_EXPORT CopyJob *move( const KURL::List& src, const KURL& dest, bool showProgressInfo = true );
-
- /**
- * Create a link.
- * If the protocols and hosts are the same, a Unix symlink will be created.
- * Otherwise, a .desktop file of Type Link and pointing to the src URL will be created.
- *
- * @param src The existing file or directory, 'target' of the link.
- * @param destDir Destination directory where the link will be created.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- */
- TDEIO_EXPORT CopyJob *link( const KURL& src, const KURL& destDir, bool showProgressInfo = true );
-
- /**
- * Create several links
- * If the protocols and hosts are the same, a Unix symlink will be created.
- * Otherwise, a .desktop file of Type Link and pointing to the src URL will be created.
- *
- * @param src The existing files or directories, 'targets' of the link.
- * @param destDir Destination directory where the links will be created.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @see link()
- */
- TDEIO_EXPORT CopyJob *link( const KURL::List& src, const KURL& destDir, bool showProgressInfo = true );
-
- /**
- * Create a link. Unlike link() this operation will fail when the directory already
- * exists.
- * If the protocols and hosts are the same, a Unix symlink will be created.
- * Otherwise, a .desktop file of Type Link and pointing to the src URL will be created.
- *
- * @param src The existing file or directory, 'target' of the link.
- * @param dest Destination directory where the link will be created.
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @see link ()
- * @see copyAs()
- */
- TDEIO_EXPORT CopyJob *linkAs( const KURL& src, const KURL& dest, bool showProgressInfo = true );
-
- /**
- * Trash a file or directory.
- * This is currently only supported for local files and directories.
- * Use "KURL src; src.setPath( path );" to create a URL from a path.
- *
- * @param src file to delete
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @since 3.4
- */
- TDEIO_EXPORT CopyJob *trash( const KURL& src, bool showProgressInfo = true );
-
- /**
- * Trash a list of files or directories.
- * This is currently only supported for local files and directories.
- *
- * @param src the files to delete
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- * @since 3.4
- */
- TDEIO_EXPORT CopyJob *trash( const KURL::List& src, bool showProgressInfo = true );
-
- /**
- * Delete a file or directory.
- *
- * @param src file to delete
- * @param shred obsolete (TODO remove in KDE4)
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- */
- TDEIO_EXPORT DeleteJob *del( const KURL& src, bool shred = false, bool showProgressInfo = true );
-
- /**
- * Deletes a list of files or directories.
- *
- * @param src the files to delete
- * @param shred obsolete (TODO remove in KDE4)
- * @param showProgressInfo true to show progress information
- * @return the job handling the operation
- */
- TDEIO_EXPORT DeleteJob *del( const KURL::List& src, bool shred = false, bool showProgressInfo = true );
-}
-
-#endif
-
diff --git a/kio/kio/jobclasses.h b/kio/kio/jobclasses.h
deleted file mode 100644
index 3438406fa..000000000
--- a/kio/kio/jobclasses.h
+++ /dev/null
@@ -1,1909 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_jobclasses_h__
-#define __kio_jobclasses_h__
-
-#include <tqobject.h>
-#include <tqptrlist.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqguardedptr.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <kurl.h>
-#include <kio/global.h>
-
-class Observer;
-class TQTimer;
-
-#define KIO_COPYJOB_HAS_SETINTERACTIVE // new in 3.4. Used by kio_trash.
-
-namespace TDEIO {
-
- class Slave;
- class SlaveInterface;
-
-
- /**
- * The base class for all jobs.
- * For all jobs created in an application, the code looks like
- *
- * \code
- * TDEIO::Job * job = TDEIO::someoperation( some parameters );
- * connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- * this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
- * \endcode
- * (other connects, specific to the job)
- *
- * And slotResult is usually at least:
- *
- * \code
- * if ( job->error() )
- * job->showErrorDialog( this or 0L );
- * \endcode
- * @see TDEIO::Scheduler
- * @see TDEIO::Slave
- */
- class TDEIO_EXPORT Job : public TQObject {
- Q_OBJECT
-
- protected:
- Job( bool showProgressInfo );
-
- public:
- virtual ~Job();
-
- /**
- * Abort this job.
- * This kills all subjobs and deletes the job.
- *
- * @param quietly if false, Job will emit signal result
- * and ask kio_uiserver to close the progress window.
- * @p quietly is set to true for subjobs. Whether applications
- * should call with true or false depends on whether they rely
- * on result being emitted or not.
- */
- virtual void kill( bool quietly = true );
-
- /**
- * Returns the error code, if there has been an error.
- * Only call this method from the slot connected to result().
- * @return the error code for this job, 0 if no error.
- * Error codes are defined in TDEIO::Error.
- */
- int error() const { return m_error; }
-
- /**
- * Returns the progress id for this job.
- * @return the progress id for this job, as returned by uiserver
- */
- int progressId() const { return m_progressId; }
-
- /**
- * Returns the error text if there has been an error.
- * Only call if error is not 0.
- * This is really internal, better use errorString() or errorDialog().
- *
- * @return a string to help understand the error, usually the url
- * related to the error. Only valid if error() is not 0.
- */
- const TQString & errorText() const { return m_errorText; }
-
- /**
- * Converts an error code and a non-i18n error message into an
- * error message in the current language. The low level (non-i18n)
- * error message (usually a url) is put into the translated error
- * message using %1.
- *
- * Example for errid == ERR_CANNOT_OPEN_FOR_READING:
- * \code
- * i18n( "Could not read\n%1" ).arg( errortext );
- * \endcode
- * Use this to display the error yourself, but for a dialog box
- * use Job::showErrorDialog. Do not call it if error()
- * is not 0.
- * @return the error message and if there is no error, a message
- * telling the user that the app is broken, so check with
- * error() whether there is an error
- */
- TQString errorString() const;
-
- /**
- * Converts an error code and a non-i18n error message into i18n
- * strings suitable for presentation in a detailed error message box.
- *
- * @param reqUrl the request URL that generated this error message
- * @param method the method that generated this error message
- * (unimplemented)
- * @return the following strings: caption, error + description,
- * causes+solutions
- */
- TQStringList detailedErrorStrings(const KURL *reqUrl = 0L,
- int method = -1) const;
-
- /**
- * Display a dialog box to inform the user of the error given by
- * this job.
- * Only call if error is not 0, and only in the slot connected
- * to result.
- * @param parent the parent widget for the dialog box, can be 0 for
- * top-level
- */
- void showErrorDialog( TQWidget * parent = 0L );
-
- /**
- * Enable or disable the automatic error handling. When automatic
- * error handling is enabled and an error occurs, then showErrorDialog()
- * is called with the specified @p parentWidget (if supplied) , right before
- * the emission of the result signal.
- *
- * The default is false.
- *
- * @param enable enable or disable automatic error handling
- * @param parentWidget the parent widget, passed to showErrorDialog.
- * Can be 0 for top-level
- * @see isAutoErrorHandlingEnabled(), showErrorDialog()
- */
- void setAutoErrorHandlingEnabled( bool enable, TQWidget *parentWidget = 0 );
-
- /**
- * Returns whether automatic error handling is enabled or disabled.
- * @return true if automatic error handling is enabled
- * @see setAutoErrorHandlingEnabled()
- */
- bool isAutoErrorHandlingEnabled() const;
-
- /**
- * Enable or disable the automatic warning handling. When automatic
- * warning handling is enabled and an error occurs, then a message box
- * is displayed with the warning message
- *
- * The default is true.
- *
- * See also isAutoWarningHandlingEnabled , showErrorDialog
- *
- * @param enable enable or disable automatic warning handling
- * @see isAutoWarningHandlingEnabled()
- * @since 3.5
- */
- void setAutoWarningHandlingEnabled( bool enable );
-
- /**
- * Returns whether automatic warning handling is enabled or disabled.
- * See also setAutoWarningHandlingEnabled .
- * @return true if automatic warning handling is enabled
- * @see setAutoWarningHandlingEnabled()
- * @since 3.5
- */
- bool isAutoWarningHandlingEnabled() const;
-
- /**
- * Enable or disable the message display from the job.
- *
- * The default is true.
- * @param enable enable or disable message display
- * @since 3.4.1
- */
- void setInteractive(bool enable);
-
- /**
- * Returns whether message display is enabled or disabled.
- * @return true if message display is enabled
- * @see setInteractive()
- * @since 3.4.1
- */
- bool isInteractive() const;
- /**
- * Associate this job with a window given by @p window.
- * @param window the window to associate to
- * @see window()
- */
- void setWindow(TQWidget *window);
-
- /**
- * Returns the window this job is associated with.
- * @return the associated window
- * @see setWindow()
- */
- TQWidget *window() const;
-
- /**
- * Updates the last user action timestamp to the given time.
- * See TDEApplication::updateUserTimestamp() .
- * @since 3.5.6
- */
- void updateUserTimestamp( unsigned long time );
-
- /**
- * Set the parent Job.
- * One example use of this is when FileCopyJob calls open_RenameDlg,
- * it must pass the correct progress ID of the parent CopyJob
- * (to hide the progress dialog).
- * You can set the parent job only once. By default a job does not
- * have a parent job.
- * @param parentJob the new parent job
- * @since 3.1
- */
- void setParentJob( Job* parentJob );
-
- /**
- * Returns the parent job, if there is one.
- * @return the parent job, or 0 if there is none
- * @see setParentJob
- * @since 3.1
- */
- Job* parentJob() const;
-
- /**
- * Set meta data to be sent to the slave, replacing existing
- * meta data.
- * @param metaData the meta data to set
- * @see addMetaData()
- * @see mergeMetaData()
- */
- void setMetaData( const TDEIO::MetaData &metaData);
-
- /**
- * Add key/value pair to the meta data that is sent to the slave.
- * @param key the key of the meta data
- * @param value the value of the meta data
- * @see setMetaData()
- * @see mergeMetaData()
- */
- void addMetaData(const TQString &key, const TQString &value);
-
- /**
- * Add key/value pairs to the meta data that is sent to the slave.
- * If a certain key already existed, it will be overridden.
- * @param values the meta data to add
- * @see setMetaData()
- * @see mergeMetaData()
- */
- void addMetaData(const TQMap<TQString,TQString> &values);
-
- /**
- * Add key/value pairs to the meta data that is sent to the slave.
- * If a certain key already existed, it will remain unchanged.
- * @param values the meta data to merge
- * @see setMetaData()
- * @see addMetaData()
- */
- void mergeMetaData(const TQMap<TQString,TQString> &values);
-
- /**
- * @internal. For the scheduler. Do not use.
- */
- MetaData outgoingMetaData() const;
-
- /**
- * Get meta data received from the slave.
- * (Valid when first data is received and/or slave is finished)
- * @return the job's meta data
- */
- MetaData metaData() const;
-
- /**
- * Query meta data received from the slave.
- * (Valid when first data is received and/or slave is finished)
- * @param key the key of the meta data to retrieve
- * @return the value of the meta data, or TQString::null if the
- * @p key does not exist
- */
- TQString queryMetaData(const TQString &key);
-
- /**
- * Returns the processed size for this job.
- * @see processedSize
- * @since 3.2
- */
- TDEIO::filesize_t getProcessedSize();
-
- signals:
- /**
- * Emitted when the job is finished, in any case (completed, canceled,
- * failed...). Use error to know the result.
- * @param job the job that emitted this signal
- */
- void result( TDEIO::Job *job );
-
- /**
- * @deprecated. Don't use !
- * Emitted when the job is canceled.
- * Signal result() is emitted as well, and error() is,
- * in this case, ERR_USER_CANCELED.
- * @param job the job that emitted this signal
- */
- void canceled( TDEIO::Job *job );
-
- /**
- * Emitted to display information about this job, as sent by the slave.
- * Examples of message are "Resolving host", "Connecting to host...", etc.
- * @param job the job that emitted this signal
- * @param msg the info message
- */
- void infoMessage( TDEIO::Job *job, const TQString & msg );
- // KDE4: Separate rich-text string from plain-text string, for different widgets.
-
- /**
- * Emitted to display a warning about this job, as sent by the slave.
- * @param job the job that emitted this signal
- * @param msg the info message
- * @since 3.5
- */
- void warning( TDEIO::Job *job, const TQString & msg );
- // KDE4: Separate rich-text string from plain-text string, for different widgets.
-
- /**
- * Emitted when the slave successfully connected to the host.
- * There is no guarantee the slave will send this, and this is
- * currently unused (in the applications).
- * @param job the job that emitted this signal
- */
- void connected( TDEIO::Job *job );
-
- /**
- * Progress signal showing the overall progress of the job
- * This is valid for any kind of job, and allows using a
- * a progress bar very easily. (see KProgress).
- * Note that this signal is not emitted for finished jobs.
- * @param job the job that emitted this signal
- * @param percent the percentage
- */
- void percent( TDEIO::Job *job, unsigned long percent );
-
- /**
- * Emitted when we know the size of this job (data size for transfers,
- * number of entries for listings).
- * @param job the job that emitted this signal
- * @param size the total size in bytes
- */
- void totalSize( TDEIO::Job *job, TDEIO::filesize_t size );
-
- /**
- * Regularly emitted to show the progress of this job
- * (current data size for transfers, entries listed).
- * @param job the job that emitted this signal
- * @param size the processed size in bytes
- */
- void processedSize( TDEIO::Job *job, TDEIO::filesize_t size );
-
- /**
- * Emitted to display information about the speed of this job.
- * @param job the job that emitted this signal
- * @param speed the speed in bytes/s
- */
- void speed( TDEIO::Job *job, unsigned long speed );
-
- protected slots:
- /**
- * Called whenever a subjob finishes.
- * Default implementation checks for errors and propagates
- * to parent job, then calls removeSubjob.
- * Override if you don't want subjobs errors to be propagated.
- * @param job the subjob
- * @see result()
- */
- virtual void slotResult( TDEIO::Job *job );
-
- /**
- * Forward signal from subjob.
- * @param job the subjob
- * @param speed the speed in bytes/s
- * @see speed()
- */
- void slotSpeed( TDEIO::Job *job, unsigned long speed );
- /**
- * Forward signal from subjob.
- * @param job the subjob
- * @param msg the info message
- * @see infoMessage()
- */
- void slotInfoMessage( TDEIO::Job *job, const TQString &msg );
-
- /**
- * Remove speed information.
- */
- void slotSpeedTimeout();
-
- protected:
- /**
- * Add a job that has to be finished before a result
- * is emitted. This has obviously to be called before
- * the finish signal is emitted by the slave.
- *
- * @param job the subjob to add
- * @param inheritMetaData if true, the subjob will
- * inherit the meta data from this job.
- */
- virtual void addSubjob( Job *job, bool inheritMetaData=true );
-
- /**
- * Mark a sub job as being done. If it's the last to
- * wait on the job will emit a result - jobs with
- * two steps might want to override slotResult
- * in order to avoid calling this method.
- *
- * @param job the subjob to add
- */
- virtual void removeSubjob( Job *job );
- /**
- * Overloaded version of removeSubjob
- * @param job the subjob to remove
- * @param mergeMetaData if set, the metadata received by the subjob is
- * merged into this job.
- * @param emitResultIfLast if this was the last subjob, emit result,
- * i.e. terminate this job.
- */
- void removeSubjob( Job *job, bool mergeMetaData, bool emitResultIfLast ); // KDE4: merge with above, with =true to both
-
- /**
- * Utility function for inherited jobs.
- * Emits the percent signal if bigger than m_percent,
- * after calculating it from the parameters.
- *
- * @param processedSize the processed size in bytes
- * @param totalSize the total size in bytes
- */
- void emitPercent( TDEIO::filesize_t processedSize, TDEIO::filesize_t totalSize );
-
- /**
- * Utility function for inherited jobs.
- * Emits the speed signal and starts the timer for removing that info
- *
- * @param speed the speed in bytes/s
- */
- void emitSpeed( unsigned long speed );
-
- /**
- * Utility function to emit the result signal, and suicide this job.
- * It first tells the observer to hide the progress dialog for this job.
- */
- void emitResult();
-
- /**
- * Set the processed size, does not emit processedSize
- * @since 3.2
- */
- void setProcessedSize(TDEIO::filesize_t size);
-
- /**
- * @internal
- */
- unsigned long userTimestamp() const;
-
- /**
- * @internal
- * Some extra storage space for jobs that don't have their own
- * private d pointer.
- */
- enum { EF_TransferJobAsync = (1 << 0),
- EF_TransferJobNeedData = (1 << 1),
- EF_TransferJobDataSent = (1 << 2),
- EF_ListJobUnrestricted = (1 << 3) };
- int &extraFlags();
-
- TQPtrList<Job> subjobs;
- int m_error;
- TQString m_errorText;
- unsigned long m_percent;
- int m_progressId; // for uiserver
- TQTimer *m_speedTimer;
- TQGuardedPtr<TQWidget> m_window;
- MetaData m_outgoingMetaData;
- MetaData m_incomingMetaData;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class JobPrivate;
- JobPrivate *d;
- };
-
- /**
- * A simple job (one url and one command).
- * This is the base class for all jobs that are scheduled.
- * Other jobs are high-level jobs (CopyJob, DeleteJob, FileCopyJob...)
- * that manage subjobs but aren't scheduled directly.
- */
- class TDEIO_EXPORT SimpleJob : public TDEIO::Job {
- Q_OBJECT
-
- public:
- /**
- * Creates a new simple job. You don't need to use this constructor,
- * unless you create a new job that inherits from SimpleJob.
- * @param url the url of the job
- * @param command the command of the job
- * @param packedArgs the arguments
- * @param showProgressInfo true to show progress information to the user
- */
- SimpleJob(const KURL& url, int command, const TQByteArray &packedArgs,
- bool showProgressInfo);
-
- ~SimpleJob();
-
- /**
- * Returns the SimpleJob's URL
- * @return the url
- */
- const KURL& url() const { return m_url; }
-
- /**
- * Abort job.
- * This kills all subjobs and deletes the job.
- * @param quietly if true, Job will emit signal result
- * Should only be set to false when the user kills the job
- * (from kio_uiserver), not when you want to abort a job.
- */
- virtual void kill( bool quietly = true );
-
- /**
- * Abort job.
- * Suspends slave to be reused by another job for the same request.
- */
- virtual void putOnHold();
-
- /**
- * Discard suspended slave.
- */
- static void removeOnHold();
-
- /**
- * @internal
- * Called by the scheduler when a slave gets to
- * work on this job.
- **/
- virtual void start( Slave *slave );
-
- /**
- * @internal
- * Called to detach a slave from a job.
- **/
- void slaveDone();
-
- /**
- * @internal
- * Slave in use by this job.
- */
- Slave *slave() const { return m_slave; }
-
- /**
- * @internal
- */
- int command() const { return m_command; }
-
- public slots:
- /**
- * Forward signal from the slave
- * Can also be called by the parent job, when it knows the size.
- * @param data_size the total size
- */
- void slotTotalSize( TDEIO::filesize_t data_size );
-
- protected slots:
- /**
- * Called when the slave marks the job
- * as finished.
- */
- virtual void slotFinished( );
-
- /**
- * @internal
- * Called on a slave's warning.
- */
- void slotWarning( const TQString & ); // KDE4: make virtual
-
- /**
- * Called on a slave's info message.
- * @param s the info message
- * @see infoMessage()
- */
- void slotInfoMessage( const TQString &s ); // KDE4: make virtual
-
- /**
- * Called on a slave's connected signal.
- * @see connected()
- */
- void slotConnected();
-
- /**
- * Forward signal from the slave.
- * @param data_size the processed size in bytes
- * @see processedSize()
- */
- void slotProcessedSize( TDEIO::filesize_t data_size );
- /**
- * Forward signal from the slave.
- * @param speed the speed in bytes/s
- * @see speed()
- */
- void slotSpeed( unsigned long speed );
-
- /**
- * MetaData from the slave is received.
- * @param _metaData the meta data
- * @see metaData()
- */
- virtual void slotMetaData( const TDEIO::MetaData &_metaData);
-
- public slots:
- /**
- * @internal
- * Called on a slave's error.
- * Made public for the scheduler.
- */
- virtual void slotError( int , const TQString & );
-
- protected slots:
- /**
- * @internal
- */
- void slotNeedProgressId();
-
- protected:
- Slave * m_slave;
- TQByteArray m_packedArgs;
- KURL m_url;
- KURL m_subUrl;
- int m_command;
- TDEIO::filesize_t m_totalSize;
- protected:
- virtual void virtual_hook( int id, void* data );
- /*
- * Allow jobs that inherit SimpleJob and are aware
- * of redirections to store the SSL session used.
- * Retrieval is handled by SimpleJob::start
- * @param m_redirectionURL Reference to redirection URL,
- * used instead of m_url if not empty
- */
- void storeSSLSessionFromJob(const KURL &m_redirectionURL);
- private:
- class SimpleJobPrivate* d;
- };
-
- /**
- * A KIO job that retrieves information about a file or directory.
- * @see TDEIO::stat()
- */
- class TDEIO_EXPORT StatJob : public SimpleJob {
-
- Q_OBJECT
-
- public:
- /**
- * Do not use this constructor to create a StatJob, use TDEIO::stat() instead.
- * @param url the url of the file or directory to check
- * @param command the command to issue
- * @param packedArgs the arguments
- * @param showProgressInfo true to show progress information to the user
- */
- StatJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
-
- /**
- * A stat() can have two meanings. Either we want to read from this URL,
- * or to check if we can write to it. First case is "source", second is "dest".
- * It is necessary to know what the StatJob is for, to tune the kioslave's behavior
- * (e.g. with FTP).
- * @param source true for "source" mode, false for "dest" mode
- */
- void setSide( bool source ) { m_bSource = source; }
-
- /**
- * Selects the level of @p details we want.
- * By default this is 2 (all details wanted, including modification time, size, etc.),
- * setDetails(1) is used when deleting: we don't need all the information if it takes
- * too much time, no need to follow symlinks etc.
- * setDetails(0) is used for very simple probing: we'll only get the answer
- * "it's a file or a directory, or it doesn't exist". This is used by KRun.
- * @param details 2 for all details, 1 for simple, 0 for very simple
- */
- void setDetails( short int details ) { m_details = details; }
-
- /**
- * Call this in the slot connected to result,
- * and only after making sure no error happened.
- * @return the result of the stat
- */
- const UDSEntry & statResult() const { return m_statResult; }
-
- /**
- * @internal
- * Called by the scheduler when a @p slave gets to
- * work on this job.
- * @param slave the slave that starts working on this job
- */
- virtual void start( Slave *slave );
-
- signals:
- /**
- * Signals a redirection.
- * Use to update the URL shown to the user.
- * The redirection itself is handled internally.
- * @param job the job that is redirected
- * @param url the new url
- */
- void redirection( TDEIO::Job *job, const KURL &url );
-
- /**
- * Signals a permanent redirection.
- * The redirection itself is handled internally.
- * @param job the job that is redirected
- * @param fromUrl the original URL
- * @param toUrl the new URL
- * @since 3.1
- */
- void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
-
- protected slots:
- void slotStatEntry( const TDEIO::UDSEntry & entry );
- void slotRedirection( const KURL &url);
- virtual void slotFinished();
- virtual void slotMetaData( const TDEIO::MetaData &_metaData);
-
- protected:
- UDSEntry m_statResult;
- KURL m_redirectionURL;
- bool m_bSource;
- short int m_details;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class StatJobPrivate;
- StatJobPrivate *d;
- };
-
- /**
- * A KIO job that creates a directory
- * @see TDEIO::mkdir()
- * @since 3.3
- */
- class TDEIO_EXPORT MkdirJob : public SimpleJob {
-
- Q_OBJECT
-
- public:
- /**
- * Do not use this constructor to create a MkdirJob, use TDEIO::mkdir() instead.
- * @param url the url of the file or directory to check
- * @param command the command to issue
- * @param packedArgs the arguments
- * @param showProgressInfo true to show progress information to the user
- */
- MkdirJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
-
- /**
- * @internal
- * Called by the scheduler when a @p slave gets to
- * work on this job.
- * @param slave the slave that starts working on this job
- */
- virtual void start( Slave *slave );
-
- signals:
- /**
- * Signals a redirection.
- * Use to update the URL shown to the user.
- * The redirection itself is handled internally.
- * @param job the job that is redirected
- * @param url the new url
- */
- void redirection( TDEIO::Job *job, const KURL &url );
-
- /**
- * Signals a permanent redirection.
- * The redirection itself is handled internally.
- * @param job the job that is redirected
- * @param fromUrl the original URL
- * @param toUrl the new URL
- */
- void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
-
- protected slots:
- void slotRedirection( const KURL &url);
- virtual void slotFinished();
-
- protected:
- KURL m_redirectionURL;
-
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class MkdirJobPrivate;
- MkdirJobPrivate *d;
- };
-
- /**
- * @internal
- * Used for direct copy from or to the local filesystem (i.e. SlaveBase::copy())
- */
- class TDEIO_EXPORT DirectCopyJob : public SimpleJob {
- Q_OBJECT
-
- public:
- /**
- * Do not create a DirectCopyJob. Use TDEIO::copy() or TDEIO::file_copy() instead.
- */
- DirectCopyJob(const KURL& url, int command, const TQByteArray &packedArgs,
- bool showProgressInfo);
- /**
- * @internal
- * Called by the scheduler when a @p slave gets to
- * work on this job.
- * @param slave the slave that starts working on this job
- */
- virtual void start(Slave *slave);
-
- signals:
- /**
- * @internal
- * Emitted if the job found an existing partial file
- * and supports resuming. Used by FileCopyJob.
- */
- void canResume( TDEIO::Job *job, TDEIO::filesize_t offset );
-
- private slots:
- void slotCanResume( TDEIO::filesize_t offset );
- };
-
-
- /**
- * The transfer job pumps data into and/or out of a Slave.
- * Data is sent to the slave on request of the slave ( dataReq).
- * If data coming from the slave can not be handled, the
- * reading of data from the slave should be suspended.
- */
- class TDEIO_EXPORT TransferJob : public SimpleJob {
- Q_OBJECT
-
- public:
- /**
- * Do not create a TransferJob. Use TDEIO::get() or TDEIO::put()
- * instead.
- * @param url the url to get or put
- * @param command the command to issue
- * @param packedArgs the arguments
- * @param _staticData additional data to transmit (e.g. in a HTTP Post)
- * @param showProgressInfo true to show progress information to the user
- */
- TransferJob(const KURL& url, int command,
- const TQByteArray &packedArgs,
- const TQByteArray &_staticData,
- bool showProgressInfo);
-
- /**
- * @internal
- * Called by the scheduler when a @p slave gets to
- * work on this job.
- * @param slave the slave that starts working on this job
- */
- virtual void start(Slave *slave);
-
- /**
- * Called when m_subJob finishes.
- * @param job the job that finished
- */
- virtual void slotResult( TDEIO::Job *job );
-
- /**
- * Flow control. Suspend data processing from the slave.
- */
- void suspend();
-
- /**
- * Flow control. Resume data processing from the slave.
- */
- void resume();
-
- /**
- * Flow control.
- * @return true if the job is suspended
- */
- bool isSuspended() const { return m_suspended; }
-
-
- /**
- * Checks whether we got an error page. This currently only happens
- * with HTTP urls. Call this from your slot connected to result().
- *
- * @return true if we got an (HTML) error page from the server
- * instead of what we asked for.
- */
- bool isErrorPage() const { return m_errorPage; }
-
- /**
- * Enable the async data mode.
- * When async data is enabled, data should be provided to the job by
- * calling sendAsyncData() instead of returning data in the
- * dataReq() signal.
- * @since 3.2
- */
- void setAsyncDataEnabled(bool enabled);
-
- /**
- * Provide data to the job when async data is enabled.
- * Should be called exactly once after receiving a dataReq signal
- * Sending an empty block indicates end of data.
- * @since 3.2
- */
- void sendAsyncData(const TQByteArray &data);
-
- /**
- * When enabled, the job reports the amount of data that has been sent,
- * instead of the amount of data that that has been received.
- * @see slotProcessedSize
- * @see slotSpeed
- * @since 3.2
- */
- void setReportDataSent(bool enabled);
-
- /**
- * Returns whether the job reports the amount of data that has been
- * sent (true), or whether the job reports the amount of data that
- * has been received (false)
- * @since 3.2
- */
- bool reportDataSent();
-
- signals:
- /**
- * Data from the slave has arrived.
- * @param job the job that emitted this signal
- * @param data data received from the slave.
- *
- * End of data (EOD) has been reached if data.size() == 0, however, you
- * should not be certain of data.size() == 0 ever happening (e.g. in case
- * of an error), so you should rely on result() instead.
- */
- void data( TDEIO::Job *job, const TQByteArray &data );
-
- /**
- * Request for data.
- * Please note, that you shouldn't put too large chunks
- * of data in it as this requires copies within the frame
- * work, so you should rather split the data you want
- * to pass here in reasonable chunks (about 1MB maximum)
- *
- * @param job the job that emitted this signal
- * @param data buffer to fill with data to send to the
- * slave. An empty buffer indicates end of data. (EOD)
- */
- void dataReq( TDEIO::Job *job, TQByteArray &data );
-
- /**
- * Signals a redirection.
- * Use to update the URL shown to the user.
- * The redirection itself is handled internally.
- * @param job the job that emitted this signal
- * @param url the new URL
- */
- void redirection( TDEIO::Job *job, const KURL &url );
-
- /**
- * Signals a permanent redirection.
- * The redirection itself is handled internally.
- * @param job the job that emitted this signal
- * @param fromUrl the original URL
- * @param toUrl the new URL
- * @since 3.1
- */
- void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
-
- /**
- * Mimetype determined.
- * @param job the job that emitted this signal
- * @param type the mime type
- */
- void mimetype( TDEIO::Job *job, const TQString &type );
-
- /**
- * @internal
- * Emitted if the "put" job found an existing partial file
- * (in which case offset is the size of that file)
- * and emitted by the "get" job if it supports resuming to
- * the given offset - in this case @p offset is unused)
- */
- void canResume( TDEIO::Job *job, TDEIO::filesize_t offset );
-
-
- protected slots:
- virtual void slotRedirection( const KURL &url);
- virtual void slotFinished();
- virtual void slotData( const TQByteArray &data);
- virtual void slotDataReq();
- virtual void slotMimetype( const TQString &mimetype );
- virtual void slotNeedSubURLData();
- virtual void slotSubURLData(TDEIO::Job*, const TQByteArray &);
- virtual void slotMetaData( const TDEIO::MetaData &_metaData);
- void slotErrorPage();
- void slotCanResume( TDEIO::filesize_t offset );
- void slotPostRedirection();
-
- protected:
- bool m_suspended;
- bool m_errorPage;
- TQByteArray staticData;
- KURL m_redirectionURL;
- KURL::List m_redirectionList;
- TQString m_mimetype;
- TransferJob *m_subJob;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class TransferJobPrivate *d;
- };
-
- /**
- * StoredTransferJob is a TransferJob (for downloading or uploading data) that
- * also stores a TQByteArray with the data, making it simpler to use than the
- * standard TransferJob.
- *
- * For TDEIO::storedGet it puts the data into the member TQByteArray, so the user
- * of this class can get hold of the whole data at once by calling data()
- * when the result signal is emitted.
- * You should only use StoredTransferJob to download data if you cannot
- * process the data by chunks while it's being downloaded, since storing
- * everything in a TQByteArray can potentially require a lot of memory.
- *
- * For TDEIO::storedPut the user of this class simply provides the bytearray from
- * the start, and the job takes care of uploading it.
- * You should only use StoredTransferJob to upload data if you cannot
- * provide the in chunks while it's being uploaded, since storing
- * everything in a TQByteArray can potentially require a lot of memory.
- *
- * @since 3.3
- */
- class TDEIO_EXPORT StoredTransferJob : public TDEIO::TransferJob {
- Q_OBJECT
-
- public:
- /**
- * Do not create a StoredTransferJob. Use storedGet() or storedPut()
- * instead.
- * @param url the url to get or put
- * @param command the command to issue
- * @param packedArgs the arguments
- * @param _staticData additional data to transmit (e.g. in a HTTP Post)
- * @param showProgressInfo true to show progress information to the user
- */
- StoredTransferJob(const KURL& url, int command,
- const TQByteArray &packedArgs,
- const TQByteArray &_staticData,
- bool showProgressInfo);
-
- /**
- * Set data to be uploaded. This is for put jobs.
- * Automatically called by TDEIO::storedPut(const TQByteArray &, ...),
- * do not call this yourself.
- */
- void setData( const TQByteArray& arr );
-
- /**
- * Get hold of the downloaded data. This is for get jobs.
- * You're supposed to call this only from the slot connected to the result() signal.
- */
- TQByteArray data() const { return m_data; }
-
- private slots:
- void slotStoredData( TDEIO::Job *job, const TQByteArray &data );
- void slotStoredDataReq( TDEIO::Job *job, TQByteArray &data );
- private:
- TQByteArray m_data;
- int m_uploadOffset;
- };
-
- /**
- * The MultiGetJob is a TransferJob that allows you to get
- * several files from a single server. Don't create directly,
- * but use TDEIO::multi_get() instead.
- * @see TDEIO::multi_get()
- */
- class TDEIO_EXPORT MultiGetJob : public TransferJob {
- Q_OBJECT
-
- public:
- /**
- * Do not create a MultiGetJob directly, use TDEIO::multi_get()
- * instead.
- *
- * @param url the first url to get
- * @param showProgressInfo true to show progress information to the user
- */
- MultiGetJob(const KURL& url, bool showProgressInfo);
-
- /**
- * @internal
- * Called by the scheduler when a @p slave gets to
- * work on this job.
- * @param slave the slave that starts working on this job
- */
- virtual void start(Slave *slave);
-
- /**
- * Get an additional file.
- *
- * @param id the id of the file
- * @param url the url of the file to get
- * @param metaData the meta data for this request
- */
- void get(long id, const KURL &url, const MetaData &metaData);
-
- signals:
- /**
- * Data from the slave has arrived.
- * @param id the id of the request
- * @param data data received from the slave.
- * End of data (EOD) has been reached if data.size() == 0
- */
- void data( long id, const TQByteArray &data);
-
- /**
- * Mimetype determined
- * @param id the id of the request
- * @param type the mime type
- */
- void mimetype( long id, const TQString &type );
-
- /**
- * File transfer completed.
- *
- * When all files have been processed, result(TDEIO::Job *) gets
- * emitted.
- * @param id the id of the request
- */
- void result( long id);
-
- protected slots:
- virtual void slotRedirection( const KURL &url);
- virtual void slotFinished();
- virtual void slotData( const TQByteArray &data);
- virtual void slotMimetype( const TQString &mimetype );
- private:
- struct GetRequest {
- public:
- GetRequest(long _id, const KURL &_url, const MetaData &_metaData)
- : id(_id), url(_url), metaData(_metaData) { }
- long id;
- KURL url;
- MetaData metaData;
- };
- bool findCurrentEntry();
- void flushQueue(TQPtrList<GetRequest> &queue);
-
- TQPtrList<GetRequest> m_waitQueue;
- TQPtrList<GetRequest> m_activeQueue;
- bool b_multiGetActive;
- GetRequest *m_currentEntry;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class MultiGetJobPrivate* d;
- };
-
- /**
- * A MimetypeJob is a TransferJob that allows you to get
- * the mime type of an URL. Don't create directly,
- * but use TDEIO::mimetype() instead.
- * @see TDEIO::mimetype()
- */
- class TDEIO_EXPORT MimetypeJob : public TransferJob {
- Q_OBJECT
-
- public:
- /**
- * Do not create a MimetypeJob directly. Use TDEIO::mimetype()
- * instead.
- * @param url the url to get
- * @param command the command to issue
- * @param packedArgs the arguments
- * @param showProgressInfo true to show progress information to the user
- */
- MimetypeJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
-
- /**
- * Call this in the slot connected to result,
- * and only after making sure no error happened.
- * @return the mimetype of the URL
- */
- TQString mimetype() const { return m_mimetype; }
-
- /**
- * @internal
- * Called by the scheduler when a slave gets to
- * work on this job.
- * @param slave the slave that works on the job
- */
- virtual void start( Slave *slave );
-
- protected slots:
- virtual void slotFinished( );
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class MimetypeJobPrivate* d;
- };
-
- /**
- * The FileCopyJob copies data from one place to another.
- * @see TDEIO::file_copy()
- * @see TDEIO::file_move()
- */
- class TDEIO_EXPORT FileCopyJob : public Job {
- Q_OBJECT
-
- public:
- /**
- * Do not create a FileCopyJob directly. Use TDEIO::file_move()
- * or TDEIO::file_copy() instead.
- * @param src the source URL
- * @param dest the destination URL
- * @param permissions the permissions of the resulting resource
- * @param move true to move, false to copy
- * @param overwrite true to allow overwriting, false otherwise
- * @param resume true to resume an operation, false otherwise
- * @param showProgressInfo true to show progress information to the user
- */
- FileCopyJob( const KURL& src, const KURL& dest, int permissions,
- bool move, bool overwrite, bool resume, bool showProgressInfo);
-
- ~FileCopyJob();
- /**
- * If you know the size of the source file, call this method
- * to inform this job. It will be displayed in the "resume" dialog.
- * @param size the size of the source file
- * @since 3.2
- */
- void setSourceSize64(TDEIO::filesize_t size);
-
- /**
- * Sets the modification time of the file
- *
- * Note that this is ignored if a direct copy (SlaveBase::copy) can be done,
- * in which case the mtime of the source is applied to the destination (if the protocol
- * supports the concept).
- */
- void setModificationTime( time_t mtime );
-
- /**
- * @deprecated
- */
- void setSourceSize( off_t size ) KDE_DEPRECATED;
-
- /**
- * Returns the source URL.
- * @return the source URL
- */
- KURL srcURL() const { return m_src; }
-
- /**
- * Returns the destination URL.
- * @return the destination URL
- */
- KURL destURL() const { return m_dest; }
-
- signals:
- /**
- * Mimetype determined during a file copy.
- * This is never emitted during a move, and might not be emitted during
- * a copy, depending on the slave.
- * @param job the job that emitted this signal
- * @param type the mime type
- *
- * @since 3.5.7
- */
- void mimetype( TDEIO::Job *job, const TQString &type );
-
- public slots:
- void slotStart();
- void slotData( TDEIO::Job *, const TQByteArray &data);
- void slotDataReq( TDEIO::Job *, TQByteArray &data);
- void slotMimetype( TDEIO::Job *, const TQString& type );
-
- protected slots:
- /**
- * Called whenever a subjob finishes.
- * @param job the job that emitted this signal
- */
- virtual void slotResult( TDEIO::Job *job );
-
- /**
- * Forward signal from subjob
- * @param job the job that emitted this signal
- * @param size the processed size in bytes
- */
- void slotProcessedSize( TDEIO::Job *job, TDEIO::filesize_t size );
- /**
- * Forward signal from subjob
- * @param job the job that emitted this signal
- * @param size the total size
- */
- void slotTotalSize( TDEIO::Job *job, TDEIO::filesize_t size );
- /**
- * Forward signal from subjob
- * @param job the job that emitted this signal
- * @param pct the percentage
- */
- void slotPercent( TDEIO::Job *job, unsigned long pct );
- /**
- * Forward signal from subjob
- * @param job the job that emitted this signal
- * @param offset the offset to resume from
- */
- void slotCanResume( TDEIO::Job *job, TDEIO::filesize_t offset );
-
- protected:
- void startCopyJob();
- void startCopyJob(const KURL &slave_url);
- void startRenameJob(const KURL &slave_url);
- void startDataPump();
- void connectSubjob( SimpleJob * job );
-
- private:
- void startBestCopyMethod();
-
- protected:
- KURL m_src;
- KURL m_dest;
- int m_permissions;
- bool m_move:1;
- bool m_overwrite:1;
- bool m_resume:1;
- bool m_canResume:1;
- bool m_resumeAnswerSent:1;
- TQByteArray m_buffer;
- SimpleJob *m_moveJob;
- SimpleJob *m_copyJob;
- TransferJob *m_getJob;
- TransferJob *m_putJob;
- TDEIO::filesize_t m_totalSize;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class FileCopyJobPrivate;
- FileCopyJobPrivate* d;
- };
-
- /**
- * A ListJob is allows you to get the get the content of a directory.
- * Don't create the job directly, but use TDEIO::listRecursive() or
- * TDEIO::listDir() instead.
- * @see TDEIO::listRecursive()
- * @see TDEIO::listDir()
- */
- class TDEIO_EXPORT ListJob : public SimpleJob {
- Q_OBJECT
-
- public:
- /**
- * Do not create a ListJob directly. Use TDEIO::listDir() or
- * TDEIO::listRecursive() instead.
- * @param url the url of the directory
- * @param showProgressInfo true to show progress information to the user
- * @param recursive true to get the data recursively from child directories,
- * false to get only the content of the specified dir
- * @param prefix the prefix of the files, or TQString::null for no prefix
- * @param includeHidden true to include hidden files (those starting with '.')
- */
- ListJob(const KURL& url, bool showProgressInfo,
- bool recursive = false, TQString prefix = TQString::null,
- bool includeHidden = true);
-
- /**
- * @internal
- * Called by the scheduler when a @p slave gets to
- * work on this job.
- * @param slave the slave that starts working on this job
- */
- virtual void start( Slave *slave );
-
- /**
- * Returns the ListJob's redirection URL. This will be invalid if there
- * was no redirection.
- * @return the redirection url
- * @since 3.4.1
- */
- const KURL& redirectionURL() const { return m_redirectionURL; }
-
- /**
- * Do not apply any KIOSK restrictions to this job.
- * @since 3.2
- */
- void setUnrestricted(bool unrestricted);
-
- signals:
- /**
- * This signal emits the entry found by the job while listing.
- * The progress signals aren't specific to ListJob. It simply
- * uses SimpleJob's processedSize (number of entries listed) and
- * totalSize (total number of entries, if known),
- * as well as percent.
- * @param job the job that emitted this signal
- * @param list the list of UDSEntries
- */
- void entries( TDEIO::Job *job, const TDEIO::UDSEntryList& list);
-
- /**
- * Signals a redirection.
- * Use to update the URL shown to the user.
- * The redirection itself is handled internally.
- * @param job the job that is redirected
- * @param url the new url
- */
- void redirection( TDEIO::Job *job, const KURL &url );
-
- /**
- * Signals a permanent redirection.
- * The redirection itself is handled internally.
- * @param job the job that emitted this signal
- * @param fromUrl the original URL
- * @param toUrl the new URL
- * @since 3.1
- */
- void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
-
- protected slots:
- virtual void slotFinished( );
- virtual void slotMetaData( const TDEIO::MetaData &_metaData);
- virtual void slotResult( TDEIO::Job *job );
- void slotListEntries( const TDEIO::UDSEntryList& list );
- void slotRedirection( const KURL &url );
- void gotEntries( TDEIO::Job * subjob, const TDEIO::UDSEntryList& list );
-
- private:
- bool recursive;
- bool includeHidden;
- TQString prefix;
- unsigned long m_processedEntries;
- KURL m_redirectionURL;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class ListJobPrivate* d;
- };
-
- /// @internal
- struct TDEIO_EXPORT CopyInfo
- {
- KURL uSource;
- KURL uDest;
- TQString linkDest; // for symlinks only
- int permissions;
- //mode_t type;
- time_t ctime;
- time_t mtime;
- TDEIO::filesize_t size; // 0 for dirs
- };
-
- /**
- * CopyJob is used to move, copy or symlink files and directories.
- * Don't create the job directly, but use TDEIO::copy(),
- * TDEIO::move(), TDEIO::link() and friends.
- *
- * @see TDEIO::copy()
- * @see TDEIO::copyAs()
- * @see TDEIO::move()
- * @see TDEIO::moveAs()
- * @see TDEIO::link()
- * @see TDEIO::linkAs()
- */
- class TDEIO_EXPORT CopyJob : public Job {
- Q_OBJECT
-
- public:
- /**
- * Defines the mode of the operation
- */
- enum CopyMode{ Copy, Move, Link };
-
- /**
- * Do not create a CopyJob directly. Use TDEIO::copy(),
- * TDEIO::move(), TDEIO::link() and friends instead.
- *
- * @param src the list of source URLs
- * @param dest the destination URL
- * @param mode specifies whether the job should copy, move or link
- * @param asMethod if true, behaves like TDEIO::copyAs(),
- * TDEIO::moveAs() or TDEIO::linkAs()
- * @param showProgressInfo true to show progress information to the user
- * @see TDEIO::copy()
- * @see TDEIO::copyAs()
- * @see TDEIO::move()
- * @see TDEIO::moveAs()
- * @see TDEIO::link()
- * @see TDEIO::linkAs()
- */
- CopyJob( const KURL::List& src, const KURL& dest, CopyMode mode, bool asMethod, bool showProgressInfo );
-
- virtual ~CopyJob();
-
- /**
- * Returns the list of source URLs.
- * @return the list of source URLs.
- */
- KURL::List srcURLs() const { return m_srcList; }
-
- /**
- * Returns the destination URL.
- * @return the destination URL
- */
- KURL destURL() const { return m_dest; }
-
- /**
- * By default the permissions of the copied files will be those of the source files.
- *
- * But when copying "template" files to "new" files, people prefer the umask
- * to apply, rather than the template's permissions.
- * For that case, call setDefaultPermissions(true)
- *
- * TODO KDE4: consider adding this as bool to copy/copyAs?
- * @since 3.2.3
- */
- void setDefaultPermissions( bool b );
-
- /**
- * When an error happens while copying/moving a file, the user will be presented with
- * a dialog for skipping the file that can't be copied/moved.
- * Or if the error is that the destination file already exists, the standard
- * rename dialog is shown.
- * If the program doesn't want CopyJob to show dialogs, but to simply fail on error,
- * call setInteractive( false ).
- *
- * KDE4: remove, already in Job
- * @since 3.4
- */
- void setInteractive( bool b );
-
- signals:
-
- /**
- * Emitted when the total number of files is known.
- * @param job the job that emitted this signal
- * @param files the total number of files
- */
- void totalFiles( TDEIO::Job *job, unsigned long files );
- /**
- * Emitted when the toal number of direcotries is known.
- * @param job the job that emitted this signal
- * @param dirs the total number of directories
- */
- void totalDirs( TDEIO::Job *job, unsigned long dirs );
-
- /**
- * Emitted when it is known which files / directories are going
- * to be created. Note that this may still change e.g. when
- * existing files with the same name are discovered.
- * @param job the job that emitted this signal
- * @param files a list of items that are about to be created.
- */
- void aboutToCreate( TDEIO::Job *job, const TQValueList<TDEIO::CopyInfo> &files);
-
- /**
- * Sends the number of processed files.
- * @param job the job that emitted this signal
- * @param files the number of processed files
- */
- void processedFiles( TDEIO::Job *job, unsigned long files );
- /**
- * Sends the number of processed directories.
- * @param job the job that emitted this signal
- * @param dirs the number of processed dirs
- */
- void processedDirs( TDEIO::Job *job, unsigned long dirs );
-
- /**
- * The job is copying a file or directory.
- * @param job the job that emitted this signal
- * @param from the URl of the file or directory that is currently
- * being copied
- * @param to the destination of the current operation
- */
- void copying( TDEIO::Job *job, const KURL& from, const KURL& to );
- /**
- * The job is creating a symbolic link.
- * @param job the job that emitted this signal
- * @param target the URl of the file or directory that is currently
- * being linked
- * @param to the destination of the current operation
- */
- void linking( TDEIO::Job *job, const TQString& target, const KURL& to );
- /**
- * The job is moving a file or directory.
- * @param job the job that emitted this signal
- * @param from the URl of the file or directory that is currently
- * being moved
- * @param to the destination of the current operation
- */
- void moving( TDEIO::Job *job, const KURL& from, const KURL& to );
- /**
- * The job is creating the directory @p dir.
- * @param job the job that emitted this signal
- * @param dir the directory that is currently being created
- */
- void creatingDir( TDEIO::Job *job, const KURL& dir );
- /**
- * The user chose to rename @p from to @p to.
- * @param job the job that emitted this signal
- * @param from the original name
- * @param to the new name
- */
- void renamed( TDEIO::Job *job, const KURL& from, const KURL& to );
-
- /**
- * The job emits this signal when copying or moving a file or directory successfully finished.
- * This signal is mainly for the Undo feature.
- *
- * @param job the job that emitted this signal
- * @param from the source URL
- * @param to the destination URL
- * @param directory indicates whether a file or directory was successfully copied/moved.
- * true for a directoy, false for file
- * @param renamed indicates that the destination URL was created using a
- * rename operation (i.e. fast directory moving). true if is has been renamed
- */
- void copyingDone( TDEIO::Job *job, const KURL &from, const KURL &to, bool directory, bool renamed );
- /**
- * The job is copying or moving a symbolic link, that points to target.
- * The new link is created in @p to. The existing one is/was in @p from.
- * This signal is mainly for the Undo feature.
- * @param job the job that emitted this signal
- * @param from the source URL
- * @param target the target
- * @param to the destination URL
- */
- void copyingLinkDone( TDEIO::Job *job, const KURL &from, const TQString& target, const KURL& to );
-
- protected:
- void statCurrentSrc();
- void statNextSrc();
-
- // Those aren't slots but submethods for slotResult.
- void slotResultStating( TDEIO::Job * job );
- void startListing( const KURL & src );
- void slotResultCreatingDirs( TDEIO::Job * job );
- void slotResultConflictCreatingDirs( TDEIO::Job * job );
- void createNextDir();
- void slotResultCopyingFiles( TDEIO::Job * job );
- void slotResultConflictCopyingFiles( TDEIO::Job * job );
- void copyNextFile();
- void slotResultDeletingDirs( TDEIO::Job * job );
- void deleteNextDir();
- void skip( const KURL & sourceURL );
- void slotResultRenaming( TDEIO::Job * job );
- //void slotResultSettingDirAttributes( TDEIO::Job * job );
- void setNextDirAttribute();
- private:
- void startRenameJob(const KURL &slave_url);
- bool shouldOverwrite( const TQString& path ) const;
- bool shouldSkip( const TQString& path ) const;
- void skipSrc();
-
- protected slots:
- void slotStart();
- void slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& list );
- virtual void slotResult( TDEIO::Job *job );
- /**
- * Forward signal from subjob
- */
- void slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size );
- /**
- * Forward signal from subjob
- * @param size the total size
- */
- void slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size );
-
- void slotReport();
- private:
- CopyMode m_mode;
- bool m_asMethod;
- enum DestinationState { DEST_NOT_STATED, DEST_IS_DIR, DEST_IS_FILE, DEST_DOESNT_EXIST };
- DestinationState destinationState;
- enum { STATE_STATING, STATE_RENAMING, STATE_LISTING, STATE_CREATING_DIRS,
- STATE_CONFLICT_CREATING_DIRS, STATE_COPYING_FILES, STATE_CONFLICT_COPYING_FILES,
- STATE_DELETING_DIRS, STATE_SETTING_DIR_ATTRIBUTES } state;
- TDEIO::filesize_t m_totalSize;
- TDEIO::filesize_t m_processedSize;
- TDEIO::filesize_t m_fileProcessedSize;
- int m_processedFiles;
- int m_processedDirs;
- TQValueList<CopyInfo> files;
- TQValueList<CopyInfo> dirs;
- KURL::List dirsToRemove;
- KURL::List m_srcList;
- KURL::List::Iterator m_currentStatSrc;
- bool m_bCurrentSrcIsDir;
- bool m_bCurrentOperationIsLink;
- bool m_bSingleFileCopy;
- bool m_bOnlyRenames;
- KURL m_dest;
- KURL m_currentDest;
- //
- TQStringList m_skipList;
- TQStringList m_overwriteList;
- bool m_bAutoSkip;
- bool m_bOverwriteAll;
- int m_conflictError;
-
- TQTimer *m_reportTimer;
- //these both are used for progress dialog reporting
- KURL m_currentSrcURL;
- KURL m_currentDestURL;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class CopyJobPrivate;
- CopyJobPrivate* d;
- friend class CopyJobPrivate; // for DestinationState
- };
-
- /**
- * A more complex Job to delete files and directories.
- * Don't create the job directly, but use TDEIO::del() instead.
- *
- * @see TDEIO::del()
- */
- class TDEIO_EXPORT DeleteJob : public Job {
- Q_OBJECT
-
- public:
- /**
- * Do not create a DeleteJob directly. Use TDEIO::del()
- * instead.
- *
- * @param src the list of URLs to delete
- * @param shred true to shred (make sure that data is not recoverable)a
- * @param showProgressInfo true to show progress information to the user
- * @see TDEIO::del()
- */
- DeleteJob( const KURL::List& src, bool shred, bool showProgressInfo );
-
- /**
- * Returns the list of URLs.
- * @return the list of URLs.
- */
- KURL::List urls() const { return m_srcList; }
-
- signals:
-
- /**
- * Emitted when the total number of files is known.
- * @param job the job that emitted this signal
- * @param files the total number of files
- */
- void totalFiles( TDEIO::Job *job, unsigned long files );
- /**
- * Emitted when the toal number of direcotries is known.
- * @param job the job that emitted this signal
- * @param dirs the total number of directories
- */
- void totalDirs( TDEIO::Job *job, unsigned long dirs );
-
- /**
- * Sends the number of processed files.
- * @param job the job that emitted this signal
- * @param files the number of processed files
- */
- void processedFiles( TDEIO::Job *job, unsigned long files );
- /**
- * Sends the number of processed directories.
- * @param job the job that emitted this signal
- * @param dirs the number of processed dirs
- */
- void processedDirs( TDEIO::Job *job, unsigned long dirs );
-
- /**
- * Sends the URL of the file that is currently being deleted.
- * @param job the job that emitted this signal
- * @param file the URL of the file or directory that is being
- * deleted
- */
- void deleting( TDEIO::Job *job, const KURL& file );
-
- protected slots:
- void slotStart();
- void slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& list );
- virtual void slotResult( TDEIO::Job *job );
-
- /**
- * Forward signal from subjob
- */
- void slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size );
- void slotReport();
-
- private:
- void statNextSrc();
- void deleteNextFile();
- void deleteNextDir();
-
- private:
- enum { STATE_STATING, STATE_LISTING,
- STATE_DELETING_FILES, STATE_DELETING_DIRS } state;
- TDEIO::filesize_t m_totalSize;
- TDEIO::filesize_t m_processedSize;
- TDEIO::filesize_t m_fileProcessedSize;
- int m_processedFiles;
- int m_processedDirs;
- int m_totalFilesDirs;
- KURL m_currentURL;
- KURL::List files;
- KURL::List symlinks;
- KURL::List dirs;
- KURL::List m_srcList;
- KURL::List::Iterator m_currentStat;
- TQStringList m_parentDirs;
- bool m_shred; // BIC: remove in KDE4
- TQTimer *m_reportTimer;
- protected:
- /** \internal */
- virtual void virtual_hook( int id, void* data );
- private:
- class DeleteJobPrivate* d;
- };
-
- /**
- * A KIO job that finds a local URL
- * @see TDEIO::localURL()
- * @since R14.0.0
- */
- class TDEIO_EXPORT LocalURLJob : public SimpleJob {
-
- Q_OBJECT
-
- public:
- /**
- * Do not use this constructor to create a LocalURLJob, use TDEIO::localURL() instead.
- * @param url the url of the file or directory to check
- * @param command the command to issue
- * @param packedArgs the arguments
- * @param showProgressInfo true to show progress information to the user
- */
- LocalURLJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
-
- /**
- * @internal
- * Called by the scheduler when a @p slave gets to
- * work on this job.
- * @param slave the slave that starts working on this job
- */
- virtual void start( Slave *slave );
-
- signals:
- /**
- * @param job the job that emitted this signal
- * @param url the local url
- * @param isLocal true if the returned URL is local, false if not
- */
- void localURL( TDEIO::Job *job, const KURL &url, bool isLocal );
-
- protected slots:
- void slotLocalURL( const KURL &url, bool isLocal );
- virtual void slotFinished();
-
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class LocalURLJobPrivate;
- LocalURLJobPrivate *d;
- };
-
-}
-
-#endif
diff --git a/kio/kio/kacl.h b/kio/kio/kacl.h
deleted file mode 100644
index 1f60fde60..000000000
--- a/kio/kio/kacl.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2005 Till Adam <adam@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kacl_h__
-#define __kacl_h__
-
-#include <sys/types.h>
-#include <kio/global.h>
-
-typedef QPair<TQString, unsigned short> ACLUserPermissions;
-typedef TQValueList<ACLUserPermissions> ACLUserPermissionsList;
-typedef TQValueListIterator<ACLUserPermissions> ACLUserPermissionsIterator;
-typedef TQValueListConstIterator<ACLUserPermissions> ACLUserPermissionsConstIterator;
-
-typedef QPair<TQString, unsigned short> ACLGroupPermissions;
-typedef TQValueList<ACLGroupPermissions> ACLGroupPermissionsList;
-typedef TQValueListIterator<ACLGroupPermissions> ACLGroupPermissionsIterator;
-typedef TQValueListConstIterator<ACLGroupPermissions> ACLGroupPermissionsConstIterator;
-
-/**
- * The KCAL class encapsulates a POSIX Access Control List. It follows the
- * little standard that couldn't, 1003.1e/1003.2c, which died in draft status.
- * @short a POSIX ACL encapsulation
- * @author Till Adam <adam@kde.org>
- */
-class TDEIO_EXPORT KACL
-{
-public:
- /**
- * Creates a new KACL from @p aclString. If the string is a valid acl
- * string, isValid() will afterwards return true.
- */
- KACL( const TQString & aclString );
-
- /** Copy ctor */
- KACL( const KACL& rhs );
-
- /**
- * Creates a new KACL from the basic permissions passed in @p basicPermissions.
- * isValid() will return true, afterwards.
- */
- KACL( mode_t basicPermissions );
-
- /**
- * Creates an empty KACL. Until a valid acl string is set via setACL,
- * isValid() will return false.
- */
- KACL();
-
- virtual ~KACL();
-
- KACL& operator=( const KACL& rhs ) {
- if ( this != &rhs )
- setACL( rhs.asString() );
- return *this;
- }
-
- bool operator==( const KACL& rhs ) const;
-
- bool operator!=( const KACL& rhs ) const {
- return !operator==( rhs );
- }
-
- /**
- * Returns whether the KACL object represents a valid acl.
- * @return whether the KACL object represents a valid acl.
- */
- bool isValid() const;
-
- /** The standard (non-extended) part of an ACL. These map directly to
- * standard unix file permissions. Setting them will never make a valid
- * ACL invalid. */
-
- /** @return the owner's premissions entry */
- unsigned short ownerPermissions() const;
-
- /** Set the owner's permissions entry.
- * @return success or failure */
- bool setOwnerPermissions( unsigned short );
-
- /** @return the owning group's premissions entry */
- unsigned short owningGroupPermissions() const;
-
- /** Set the owning group's permissions entry.
- * @return success or failure */
- bool setOwningGroupPermissions( unsigned short );
-
- /** @return the premissions entry for others */
- unsigned short othersPermissions() const;
-
- /** Set the permissions entry for others.
- * @return success or failure */
- bool setOthersPermissions( unsigned short );
-
- /** @return the basic (owner/group/others) part of the ACL as a mode_t */
- mode_t basePermissions() const;
-
- /** The interface to the extended ACL. This is a mask, permissions for
- * n named users and permissions for m named groups. */
-
- /**
- * Return whether the ACL contains extended entries or can be expressed
- * using only basic file permissions.
- * @return whether the ACL contains extended entries */
- bool isExtended() const;
-
- /**
- * Return the entry for the permissions mask if there is one and sets
- * @p exists to true. If there is no such entry, @p exists is set to false.
- * @return the permissions mask entry */
- unsigned short maskPermissions( bool &exists ) const;
-
- /** Set the permissions mask for the ACL. Permissions set for individual
- * entries will be masked with this, such that their effective permissions
- * are the result of the logical and of their entry and the mask.
- * @return success or failure */
- bool setMaskPermissions( unsigned short );
-
- /**
- * Access to the permissions entry for a named user, if such an entry
- * exists. @p exists is set to true if a matching entry exists and
- * to false otherwise.
- * @return the permissions for a user entry with the name in @p name */
- unsigned short namedUserPermissions( const TQString& name, bool *exists ) const;
-
-
- /** Set the permissions for a user with the name @p name. Will fail
- * if the user doesn't exist, in which case the ACL will be unchanged.
- * @return success or failure. */
- bool setNamedUserPermissions( const TQString& name, unsigned short );
-
- /** Returns the list of all group permission entries. Each entry consists
- * of a name/permissions pair. This is a QPair, therefore access is provided
- * via the .first and .next members.
- * @return the list of all group permission entries. */
- ACLUserPermissionsList allUserPermissions() const;
-
- /** Replace the list of all user permissions with @p list. If one
- * of the entries in the list does not exists, or setting of the ACL
- * entry fails for any reason, the ACL will be left unchanged.
- * @return success or failure */
- bool setAllUserPermissions( const ACLUserPermissionsList &list );
-
- /**
- * Access to the permissions entry for a named group, if such an entry
- * exists. @p exists is set to true if a matching entry exists and
- * to false otherwise.
- * @return the permissions for a group with the name in @p name */
- unsigned short namedGroupPermissions( const TQString& name, bool *exists ) const;
-
- /** Set the permissions for a group with the name @p name. Will fail
- * if the group doesn't exist, in which case the ACL be unchanged.
- * @return success or failure. */
- bool setNamedGroupPermissions( const TQString& name, unsigned short );
-
- /** Returns the list of all group permission entries. Each entry consists
- * of a name/permissions pair. This is a QPair, therefor access is provided
- * via the .first and .next members.
- * @return the list of all group permission entries. */
-
- ACLGroupPermissionsList allGroupPermissions() const;
- /** Replace the list of all user permissions with @p list. If one
- * of the entries in the list does not exists, or setting of the ACL
- * entry fails for any reason, the ACL will be left unchanged.
- * @return success or failure */
- bool setAllGroupPermissions( const ACLGroupPermissionsList & );
-
- /** Sets the whole list from a string. If the string in @p aclStr represents
- * a valid ACL, it will be set, otherwise the ACL remains unchanged.
- * @return whether setting the ACL was successful. */
- bool setACL( const TQString &aclStr );
-
- /** Return a string representation of the ACL.
- * @return a string version of the ACL in the format compatible with libacl and
- * POSIX 1003.1e. Implementations conforming to that standard should be able
- * to take such strings as input. */
- TQString asString() const;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KACLPrivate;
- KACLPrivate * d;
- TDEIO_EXPORT friend TQDataStream & operator<< ( TQDataStream & s, const KACL & a );
- TDEIO_EXPORT friend TQDataStream & operator>> ( TQDataStream & s, KACL & a );
-};
-
-TDEIO_EXPORT TQDataStream & operator<< ( TQDataStream & s, const KACL & a );
-TDEIO_EXPORT TQDataStream & operator>> ( TQDataStream & s, KACL & a );
-
-#endif
diff --git a/kio/kio/kautomount.cpp b/kio/kio/kautomount.cpp
deleted file mode 100644
index e8b1d2af0..000000000
--- a/kio/kio/kautomount.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kautomount.h"
-#include "krun.h"
-#include "kdirwatch.h"
-#include "kio/job.h"
-#include <kdirnotify_stub.h>
-#include <kdebug.h>
-
-/***********************************************************************
- *
- * Utility classes
- *
- ***********************************************************************/
-
-KAutoMount::KAutoMount( bool _readonly, const TQString& _format, const TQString& _device,
- const TQString& _mountpoint, const TQString & _desktopFile,
- bool _show_filemanager_window )
- : m_strDevice( _device ),
- m_desktopFile( _desktopFile )
-{
- //kdDebug(7015) << "KAutoMount device=" << _device << " mountpoint=" << _mountpoint << endl;
- m_bShowFilemanagerWindow = _show_filemanager_window;
-
- TDEIO::Job* job = TDEIO::mount( _readonly, _format.ascii(), _device, _mountpoint );
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
-}
-
-void KAutoMount::slotResult( TDEIO::Job * job )
-{
- if ( job->error() ) {
- emit error();
- job->showErrorDialog();
- }
- else
- {
- KURL mountpoint;
- mountpoint.setPath( TDEIO::findDeviceMountPoint( m_strDevice ) );
- //kdDebug(7015) << "KAutoMount: m_strDevice=" << m_strDevice << " -> mountpoint=" << mountpoint << endl;
- Q_ASSERT( mountpoint.isValid() );
-
- if ( mountpoint.path().isEmpty() )
- kdWarning(7015) << m_strDevice << " was correctly mounted, but TDEIO::findDeviceMountPoint didn't find it. "
- << "This looks like a bug, please report it on http://bugs.kde.org, together with your /etc/fstab line" << endl;
- else if ( m_bShowFilemanagerWindow )
- KRun::runURL( mountpoint, "inode/directory" );
-
- // Notify about the new stuff in that dir, in case of opened windows showing it
- KDirNotify_stub allDirNotify("*", "KDirNotify*");
- allDirNotify.FilesAdded( mountpoint );
-
- // Update the desktop file which is used for mount/unmount (icon change)
- kdDebug(7015) << " mount finished : updating " << m_desktopFile << endl;
- KURL dfURL;
- dfURL.setPath( m_desktopFile );
- allDirNotify.FilesChanged( dfURL );
- //KDirWatch::self()->setFileDirty( m_desktopFile );
-
- emit finished();
- }
- delete this;
-}
-
-KAutoUnmount::KAutoUnmount( const TQString & _mountpoint, const TQString & _desktopFile )
- : m_desktopFile( _desktopFile ), m_mountpoint( _mountpoint )
-{
- TDEIO::Job * job = TDEIO::unmount( m_mountpoint );
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
-}
-
-void KAutoUnmount::slotResult( TDEIO::Job * job )
-{
- if ( job->error() ) {
- emit error();
- job->showErrorDialog();
- }
- else
- {
- KDirNotify_stub allDirNotify("*", "KDirNotify*");
- // Update the desktop file which is used for mount/unmount (icon change)
- kdDebug(7015) << "unmount finished : updating " << m_desktopFile << endl;
- KURL dfURL;
- dfURL.setPath( m_desktopFile );
- allDirNotify.FilesChanged( dfURL );
- //KDirWatch::self()->setFileDirty( m_desktopFile );
-
- // Notify about the new stuff in that dir, in case of opened windows showing it
- // You may think we removed files, but this may have also readded some
- // (if the mountpoint wasn't empty). The only possible behavior on FilesAdded
- // is to relist the directory anyway.
- KURL mp;
- mp.setPath( m_mountpoint );
- allDirNotify.FilesAdded( mp );
-
- emit finished();
- }
-
- delete this;
-}
-
-#include "kautomount.moc"
diff --git a/kio/kio/kdirlister.cpp b/kio/kio/kdirlister.cpp
deleted file mode 100644
index 90cfca041..000000000
--- a/kio/kio/kdirlister.cpp
+++ /dev/null
@@ -1,2538 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
- 2001-2005 Michael Brade <brade@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kdirlister.h"
-
-#include <tqregexp.h>
-#include <tqptrlist.h>
-#include <tqtimer.h>
-#include <tqeventloop.h>
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kio/job.h>
-#include <kmessagebox.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <kstaticdeleter.h>
-#include <kprotocolinfo.h>
-
-#include "kdirlister_p.h"
-
-#include <assert.h>
-#include <unistd.h>
-
-KDirListerCache* KDirListerCache::s_pSelf = 0;
-static KStaticDeleter<KDirListerCache> sd_KDirListerCache;
-
-// Enable this to get printDebug() called often, to see the contents of the cache
-//#define DEBUG_CACHE
-
-// Make really sure it doesn't get activated in the final build
-#ifdef NDEBUG
-#undef DEBUG_CACHE
-#endif
-
-KDirListerCache::KDirListerCache( int maxCount )
- : itemsCached( maxCount )
-{
- kdDebug(7004) << "+KDirListerCache" << endl;
-
- itemsInUse.setAutoDelete( false );
- itemsCached.setAutoDelete( true );
- urlsCurrentlyListed.setAutoDelete( true );
- urlsCurrentlyHeld.setAutoDelete( true );
- pendingUpdates.setAutoDelete( true );
-
- connect( kdirwatch, TQT_SIGNAL( dirty( const TQString& ) ),
- this, TQT_SLOT( slotFileDirty( const TQString& ) ) );
- connect( kdirwatch, TQT_SIGNAL( created( const TQString& ) ),
- this, TQT_SLOT( slotFileCreated( const TQString& ) ) );
- connect( kdirwatch, TQT_SIGNAL( deleted( const TQString& ) ),
- this, TQT_SLOT( slotFileDeleted( const TQString& ) ) );
-}
-
-KDirListerCache::~KDirListerCache()
-{
- kdDebug(7004) << "-KDirListerCache" << endl;
-
- itemsInUse.setAutoDelete( true );
- itemsInUse.clear();
- itemsCached.clear();
- urlsCurrentlyListed.clear();
- urlsCurrentlyHeld.clear();
-
- if ( KDirWatch::exists() )
- kdirwatch->disconnect( this );
-}
-
-// setting _reload to true will emit the old files and
-// call updateDirectory
-bool KDirListerCache::listDir( KDirLister *lister, const KURL& _u,
- bool _keep, bool _reload )
-{
- // like this we don't have to worry about trailing slashes any further
- KURL _url = _u;
- _url.cleanPath(); // kill consecutive slashes
- _url.adjustPath(-1);
- TQString urlStr = _url.url();
-
- if ( !lister->validURL( _url ) )
- return false;
-
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
- kdDebug(7004) << k_funcinfo << lister << " url=" << _url
- << " keep=" << _keep << " reload=" << _reload << endl;
-
- if ( !_keep )
- {
- // stop any running jobs for lister
- stop( lister );
-
- // clear our internal list for lister
- forgetDirs( lister );
-
- lister->d->rootFileItem = 0;
- }
- else if ( lister->d->lstDirs.find( _url ) != lister->d->lstDirs.end() )
- {
- // stop the job listing _url for this lister
- stop( lister, _url );
-
- // clear _url for lister
- forgetDirs( lister, _url, true );
-
- if ( lister->d->url == _url )
- lister->d->rootFileItem = 0;
- }
-
- lister->d->lstDirs.append( _url );
-
- if ( lister->d->url.isEmpty() || !_keep ) // set toplevel URL only if not set yet
- lister->d->url = _url;
-
- DirItem *itemU = itemsInUse[urlStr];
- DirItem *itemC;
-
- if ( !urlsCurrentlyListed[urlStr] )
- {
- // if there is an update running for _url already we get into
- // the following case - it will just be restarted by updateDirectory().
-
- if ( itemU )
- {
- kdDebug(7004) << "listDir: Entry already in use: " << _url << endl;
-
- bool oldState = lister->d->complete;
- lister->d->complete = false;
-
- emit lister->started( _url );
-
- if ( !lister->d->rootFileItem && lister->d->url == _url )
- lister->d->rootFileItem = itemU->rootItem;
-
- lister->addNewItems( *(itemU->lstItems) );
- lister->emitItems();
-
- // _url is already in use, so there is already an entry in urlsCurrentlyHeld
- assert( urlsCurrentlyHeld[urlStr] );
- urlsCurrentlyHeld[urlStr]->append( lister );
-
- lister->d->complete = oldState;
-
- emit lister->completed( _url );
- if ( lister->d->complete )
- emit lister->completed();
-
- if ( _reload || !itemU->complete )
- updateDirectory( _url );
- }
- else if ( !_reload && (itemC = itemsCached.take( urlStr )) )
- {
- kdDebug(7004) << "listDir: Entry in cache: " << _url << endl;
-
- itemC->decAutoUpdate();
- itemsInUse.insert( urlStr, itemC );
- itemU = itemC;
-
- bool oldState = lister->d->complete;
- lister->d->complete = false;
-
- emit lister->started( _url );
-
- if ( !lister->d->rootFileItem && lister->d->url == _url )
- lister->d->rootFileItem = itemC->rootItem;
-
- lister->addNewItems( *(itemC->lstItems) );
- lister->emitItems();
-
- Q_ASSERT( !urlsCurrentlyHeld[urlStr] );
- TQPtrList<KDirLister> *list = new TQPtrList<KDirLister>;
- list->append( lister );
- urlsCurrentlyHeld.insert( urlStr, list );
-
- lister->d->complete = oldState;
-
- emit lister->completed( _url );
- if ( lister->d->complete )
- emit lister->completed();
-
- if ( !itemC->complete )
- updateDirectory( _url );
- }
- else // dir not in cache or _reload is true
- {
- kdDebug(7004) << "listDir: Entry not in cache or reloaded: " << _url << endl;
-
- TQPtrList<KDirLister> *list = new TQPtrList<KDirLister>;
- list->append( lister );
- urlsCurrentlyListed.insert( urlStr, list );
-
- itemsCached.remove( urlStr );
- itemU = new DirItem( _url );
- itemsInUse.insert( urlStr, itemU );
-
-// // we have a limit of MAX_JOBS_PER_LISTER concurrently running jobs
-// if ( lister->numJobs() >= MAX_JOBS_PER_LISTER )
-// {
-// lstPendingUpdates.append( _url );
-// }
-// else
-// {
-
- if ( lister->d->url == _url )
- lister->d->rootFileItem = 0;
-
- TDEIO::ListJob* job = TDEIO::listDir( _url, false /* no default GUI */ );
- jobs.insert( job, TQValueList<TDEIO::UDSEntry>() );
-
- lister->jobStarted( job );
- lister->connectJob( job );
-
- if ( lister->d->window )
- job->setWindow( lister->d->window );
-
- connect( job, TQT_SIGNAL( entries( TDEIO::Job *, const TDEIO::UDSEntryList & ) ),
- this, TQT_SLOT( slotEntries( TDEIO::Job *, const TDEIO::UDSEntryList & ) ) );
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
- connect( job, TQT_SIGNAL( redirection( TDEIO::Job *, const KURL & ) ),
- this, TQT_SLOT( slotRedirection( TDEIO::Job *, const KURL & ) ) );
-
- emit lister->started( _url );
-
-// }
- }
- }
- else
- {
- kdDebug(7004) << "listDir: Entry currently being listed: " << _url << endl;
-
- emit lister->started( _url );
-
- urlsCurrentlyListed[urlStr]->append( lister );
-
- TDEIO::ListJob *job = jobForUrl( urlStr );
- Q_ASSERT( job );
-
- lister->jobStarted( job );
- lister->connectJob( job );
-
- Q_ASSERT( itemU );
-
- if ( !lister->d->rootFileItem && lister->d->url == _url )
- lister->d->rootFileItem = itemU->rootItem;
-
- lister->addNewItems( *(itemU->lstItems) );
- lister->emitItems();
- }
-
- // automatic updating of directories
- if ( lister->d->autoUpdate )
- itemU->incAutoUpdate();
-
- return true;
-}
-
-bool KDirListerCache::validURL( const KDirLister *lister, const KURL& url ) const
-{
- if ( !url.isValid() )
- {
- if ( lister->d->autoErrorHandling )
- {
- TQString tmp = i18n("Malformed URL\n%1").arg( url.prettyURL() );
- KMessageBox::error( lister->d->errorParent, tmp );
- }
- return false;
- }
-
- if ( !KProtocolInfo::supportsListing( url ) )
- {
- if ( lister->d->autoErrorHandling )
- {
- // TODO: this message should be changed during next string unfreeze!
- TQString tmp = i18n("Malformed URL\n%1").arg( url.prettyURL() );
- KMessageBox::error( lister->d->errorParent, tmp );
- }
- return false;
- }
-
- return true;
-}
-
-void KDirListerCache::stop( KDirLister *lister )
-{
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
- kdDebug(7004) << k_funcinfo << "lister: " << lister << endl;
- bool stopped = false;
-
- TQDictIterator< TQPtrList<KDirLister> > it( urlsCurrentlyListed );
- TQPtrList<KDirLister> *listers;
- while ( (listers = it.current()) )
- {
- if ( listers->findRef( lister ) > -1 )
- {
- // lister is listing url
- TQString url = it.currentKey();
-
- //kdDebug(7004) << k_funcinfo << " found lister in list - for " << url << endl;
- bool ret = listers->removeRef( lister );
- Q_ASSERT( ret );
-
- TDEIO::ListJob *job = jobForUrl( url );
- if ( job )
- lister->jobDone( job );
-
- // move lister to urlsCurrentlyHeld
- TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[url];
- if ( !holders )
- {
- holders = new TQPtrList<KDirLister>;
- urlsCurrentlyHeld.insert( url, holders );
- }
-
- holders->append( lister );
-
- emit lister->canceled( KURL( url ) );
-
- //kdDebug(7004) << k_funcinfo << "remaining list: " << listers->count() << " listers" << endl;
-
- if ( listers->isEmpty() )
- {
- // kill the job since it isn't used any more
- if ( job )
- killJob( job );
-
- urlsCurrentlyListed.remove( url );
- }
-
- stopped = true;
- }
- else
- ++it;
- }
-
- if ( stopped )
- {
- emit lister->canceled();
- lister->d->complete = true;
- }
-
- // this is wrong if there is still an update running!
- //Q_ASSERT( lister->d->complete );
-}
-
-void KDirListerCache::stop( KDirLister *lister, const KURL& _u )
-{
- TQString urlStr( _u.url(-1) );
- KURL _url( urlStr );
-
- // TODO: consider to stop all the "child jobs" of _url as well
- kdDebug(7004) << k_funcinfo << lister << " url=" << _url << endl;
-
- TQPtrList<KDirLister> *listers = urlsCurrentlyListed[urlStr];
- if ( !listers || !listers->removeRef( lister ) )
- return;
-
- // move lister to urlsCurrentlyHeld
- TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[urlStr];
- if ( !holders )
- {
- holders = new TQPtrList<KDirLister>;
- urlsCurrentlyHeld.insert( urlStr, holders );
- }
-
- holders->append( lister );
-
-
- TDEIO::ListJob *job = jobForUrl( urlStr );
- if ( job )
- lister->jobDone( job );
-
- emit lister->canceled( _url );
-
- if ( listers->isEmpty() )
- {
- // kill the job since it isn't used any more
- if ( job )
- killJob( job );
-
- urlsCurrentlyListed.remove( urlStr );
- }
-
- if ( lister->numJobs() == 0 )
- {
- lister->d->complete = true;
-
- // we killed the last job for lister
- emit lister->canceled();
- }
-}
-
-void KDirListerCache::setAutoUpdate( KDirLister *lister, bool enable )
-{
- // IMPORTANT: this method does not check for the current autoUpdate state!
-
- for ( KURL::List::Iterator it = lister->d->lstDirs.begin();
- it != lister->d->lstDirs.end(); ++it )
- {
- if ( enable )
- itemsInUse[(*it).url()]->incAutoUpdate();
- else
- itemsInUse[(*it).url()]->decAutoUpdate();
- }
-}
-
-void KDirListerCache::forgetDirs( KDirLister *lister )
-{
- kdDebug(7004) << k_funcinfo << lister << endl;
-
- emit lister->clear();
-
- // forgetDirs() will modify lstDirs, make a copy first
- KURL::List lstDirsCopy = lister->d->lstDirs;
- for ( KURL::List::Iterator it = lstDirsCopy.begin();
- it != lstDirsCopy.end(); ++it )
- {
- forgetDirs( lister, *it, false );
- }
-}
-
-void KDirListerCache::forgetDirs( KDirLister *lister, const KURL& _url, bool notify )
-{
- kdDebug(7004) << k_funcinfo << lister << " _url: " << _url << endl;
-
- KURL url( _url );
- url.adjustPath( -1 );
- TQString urlStr = url.url();
- TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[urlStr];
- //Q_ASSERT( holders );
- if ( holders )
- {
- holders->removeRef( lister );
- }
-
- // remove the dir from lister->d->lstDirs so that it doesn't contain things
- // that itemsInUse doesn't. When emitting the canceled signals lstDirs must
- // not contain anything that itemsInUse does not contain. (otherwise it
- // might crash in findByName()).
- lister->d->lstDirs.remove( lister->d->lstDirs.find( url ) );
-
- DirItem *item = itemsInUse[urlStr];
-
- if ( holders && holders->isEmpty() )
- {
- urlsCurrentlyHeld.remove( urlStr ); // this deletes the (empty) holders list
- if ( !urlsCurrentlyListed[urlStr] )
- {
- // item not in use anymore -> move into cache if complete
- itemsInUse.remove( urlStr );
-
- // this job is a running update
- TDEIO::ListJob *job = jobForUrl( urlStr );
- if ( job )
- {
- lister->jobDone( job );
- killJob( job );
- kdDebug(7004) << k_funcinfo << "Killing update job for " << urlStr << endl;
-
- emit lister->canceled( url );
- if ( lister->numJobs() == 0 )
- {
- lister->d->complete = true;
- emit lister->canceled();
- }
- }
-
- if ( notify )
- emit lister->clear( url );
-
- if ( item && item->complete )
- {
- kdDebug(7004) << k_funcinfo << lister << " item moved into cache: " << url << endl;
- itemsCached.insert( urlStr, item ); // TODO: may return false!!
-
- // Should we forget the dir for good, or keep a watch on it?
- // Generally keep a watch, except when it would prevent
- // unmounting a removable device (#37780)
- const bool isLocal = item->url.isLocalFile();
- const bool isManuallyMounted = isLocal && TDEIO::manually_mounted( item->url.path() );
- bool containsManuallyMounted = false;
- if ( !isManuallyMounted && item->lstItems && isLocal )
- {
- // Look for a manually-mounted directory inside
- // If there's one, we can't keep a watch either, FAM would prevent unmounting the CDROM
- // I hope this isn't too slow (manually_mounted caches the last device so most
- // of the time this is just a stat per subdir)
- KFileItemListIterator kit( *item->lstItems );
- for ( ; kit.current() && !containsManuallyMounted; ++kit )
- if ( (*kit)->isDir() && TDEIO::manually_mounted( (*kit)->url().path() ) )
- containsManuallyMounted = true;
- }
-
- if ( isManuallyMounted || containsManuallyMounted )
- {
- kdDebug(7004) << "Not adding a watch on " << item->url << " because it " <<
- ( isManuallyMounted ? "is manually mounted" : "contains a manually mounted subdir" ) << endl;
- item->complete = false; // set to "dirty"
- }
- else
- item->incAutoUpdate(); // keep watch
- }
- else
- {
- delete item;
- item = 0;
- }
- }
- }
-
- if ( item && lister->d->autoUpdate )
- item->decAutoUpdate();
-}
-
-void KDirListerCache::updateDirectory( const KURL& _dir )
-{
- kdDebug(7004) << k_funcinfo << _dir << endl;
-
- TQString urlStr = _dir.url(-1);
- if ( !checkUpdate( urlStr ) )
- return;
-
- // A job can be running to
- // - only list a new directory: the listers are in urlsCurrentlyListed
- // - only update a directory: the listers are in urlsCurrentlyHeld
- // - update a currently running listing: the listers are in urlsCurrentlyListed
- // and urlsCurrentlyHeld
-
- TQPtrList<KDirLister> *listers = urlsCurrentlyListed[urlStr];
- TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[urlStr];
-
- // restart the job for _dir if it is running already
- bool killed = false;
- TQWidget *window = 0;
- TDEIO::ListJob *job = jobForUrl( urlStr );
- if ( job )
- {
- window = job->window();
-
- killJob( job );
- killed = true;
-
- if ( listers )
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->jobDone( job );
-
- if ( holders )
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- kdl->jobDone( job );
- }
- kdDebug(7004) << k_funcinfo << "Killed = " << killed << endl;
-
- // we don't need to emit canceled signals since we only replaced the job,
- // the listing is continuing.
-
- Q_ASSERT( !listers || (listers && killed) );
-
- job = TDEIO::listDir( _dir, false /* no default GUI */ );
- jobs.insert( job, TQValueList<TDEIO::UDSEntry>() );
-
- connect( job, TQT_SIGNAL(entries( TDEIO::Job *, const TDEIO::UDSEntryList & )),
- this, TQT_SLOT(slotUpdateEntries( TDEIO::Job *, const TDEIO::UDSEntryList & )) );
- connect( job, TQT_SIGNAL(result( TDEIO::Job * )),
- this, TQT_SLOT(slotUpdateResult( TDEIO::Job * )) );
-
- kdDebug(7004) << k_funcinfo << "update started in " << _dir << endl;
-
- if ( listers )
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->jobStarted( job );
-
- if ( holders )
- {
- if ( !killed )
- {
- bool first = true;
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- {
- kdl->jobStarted( job );
- if ( first && kdl->d->window )
- {
- first = false;
- job->setWindow( kdl->d->window );
- }
- emit kdl->started( _dir );
- }
- }
- else
- {
- job->setWindow( window );
-
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- kdl->jobStarted( job );
- }
- }
-}
-
-bool KDirListerCache::checkUpdate( const TQString& _dir )
-{
- if ( !itemsInUse[_dir] )
- {
- DirItem *item = itemsCached[_dir];
- if ( item && item->complete )
- {
- item->complete = false;
- item->decAutoUpdate();
- // Hmm, this debug output might include login/password from the _dir URL.
- //kdDebug(7004) << k_funcinfo << "directory " << _dir << " not in use, marked dirty." << endl;
- }
- //else
- //kdDebug(7004) << k_funcinfo << "aborted, directory " << _dir << " not in cache." << endl;
-
- return false;
- }
- else
- return true;
-}
-
-KFileItemList *KDirListerCache::itemsForDir( const KURL &_dir ) const
-{
- TQString urlStr = _dir.url(-1);
- DirItem *item = itemsInUse[ urlStr ];
- if ( !item )
- item = itemsCached[ urlStr ];
- return item ? item->lstItems : 0;
-}
-
-KFileItem *KDirListerCache::findByName( const KDirLister *lister, const TQString& _name ) const
-{
- Q_ASSERT( lister );
-
- for ( KURL::List::Iterator it = lister->d->lstDirs.begin();
- it != lister->d->lstDirs.end(); ++it )
- {
- KFileItemListIterator kit( *itemsInUse[(*it).url()]->lstItems );
- for ( ; kit.current(); ++kit )
- if ( (*kit)->name() == _name )
- return (*kit);
- }
-
- return 0L;
-}
-
-KFileItem *KDirListerCache::findByURL( const KDirLister *lister, const KURL& _u ) const
-{
- KURL _url = _u;
- _url.adjustPath(-1);
-
- KURL parentDir( _url );
- parentDir.setPath( parentDir.directory() );
-
- // If lister is set, check that it contains this dir
- if ( lister && !lister->d->lstDirs.contains( parentDir ) )
- return 0L;
-
- KFileItemList *itemList = itemsForDir( parentDir );
- if ( itemList )
- {
- KFileItemListIterator kit( *itemList );
- for ( ; kit.current(); ++kit )
- if ( (*kit)->url() == _url )
- return (*kit);
- }
- return 0L;
-}
-
-void KDirListerCache::FilesAdded( const KURL &dir )
-{
- kdDebug(7004) << k_funcinfo << dir << endl;
- updateDirectory( dir );
-}
-
-void KDirListerCache::FilesRemoved( const KURL::List &fileList )
-{
- kdDebug(7004) << k_funcinfo << endl;
- KURL::List::ConstIterator it = fileList.begin();
- for ( ; it != fileList.end() ; ++it )
- {
- // emit the deleteItem signal if this file was shown in any view
- KFileItem *fileitem = 0L;
- KURL parentDir( *it );
- parentDir.setPath( parentDir.directory() );
- KFileItemList *lstItems = itemsForDir( parentDir );
- if ( lstItems )
- {
- KFileItem *fit = lstItems->first();
- for ( ; fit; fit = lstItems->next() )
- if ( fit->url() == *it ) {
- fileitem = fit;
- lstItems->take(); // remove fileitem from list
- break;
- }
- }
-
- // Tell the views about it before deleting the KFileItems. They might need the subdirs'
- // file items (see the dirtree).
- if ( fileitem )
- {
- TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[parentDir.url()];
- if ( listers )
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->emitDeleteItem( fileitem );
- }
-
- // If we found a fileitem, we can test if it's a dir. If not, we'll go to deleteDir just in case.
- if ( !fileitem || fileitem->isDir() )
- {
- // in case of a dir, check if we have any known children, there's much to do in that case
- // (stopping jobs, removing dirs from cache etc.)
- deleteDir( *it );
- }
-
- // now remove the item itself
- delete fileitem;
- }
-}
-
-void KDirListerCache::FilesChanged( const KURL::List &fileList )
-{
- KURL::List dirsToUpdate;
- kdDebug(7004) << k_funcinfo << "only half implemented" << endl;
- KURL::List::ConstIterator it = fileList.begin();
- for ( ; it != fileList.end() ; ++it )
- {
- if ( ( *it ).isLocalFile() )
- {
- kdDebug(7004) << "KDirListerCache::FilesChanged " << *it << endl;
- KFileItem *fileitem = findByURL( 0, *it );
- if ( fileitem )
- {
- // we need to refresh the item, because e.g. the permissions can have changed.
- aboutToRefreshItem( fileitem );
- fileitem->refresh();
- emitRefreshItem( fileitem );
- }
- else
- kdDebug(7004) << "item not found" << endl;
- } else {
- // For remote files, refresh() won't be able to figure out the new information.
- // Let's update the dir.
- KURL dir( *it );
- dir.setPath( dir.directory( true ) );
- if ( dirsToUpdate.find( dir ) == dirsToUpdate.end() )
- dirsToUpdate.prepend( dir );
- }
- }
-
- KURL::List::ConstIterator itdir = dirsToUpdate.begin();
- for ( ; itdir != dirsToUpdate.end() ; ++itdir )
- updateDirectory( *itdir );
- // ## TODO problems with current jobs listing/updating that dir
- // ( see kde-2.2.2's kdirlister )
-}
-
-void KDirListerCache::FileRenamed( const KURL &src, const KURL &dst )
-{
- kdDebug(7004) << k_funcinfo << src.prettyURL() << " -> " << dst.prettyURL() << endl;
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
-
- // Somehow this should only be called if src is a dir. But how could we know if it is?
- // (Note that looking into itemsInUse isn't good enough. One could rename a subdir in a view.)
- renameDir( src, dst );
-
- // Now update the KFileItem representing that file or dir (not exclusive with the above!)
- KURL oldurl( src );
- oldurl.adjustPath( -1 );
- KFileItem *fileitem = findByURL( 0, oldurl );
- if ( fileitem )
- {
- if ( !fileitem->isLocalFile() && !fileitem->localPath().isEmpty() ) // it uses UDS_LOCAL_PATH? ouch, needs an update then
- FilesChanged( src );
- else
- {
- aboutToRefreshItem( fileitem );
- fileitem->setURL( dst );
- fileitem->refreshMimeType();
- emitRefreshItem( fileitem );
- }
- }
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
-}
-
-void KDirListerCache::aboutToRefreshItem( KFileItem *fileitem )
-{
- // Look whether this item was shown in any view, i.e. held by any dirlister
- KURL parentDir( fileitem->url() );
- parentDir.setPath( parentDir.directory() );
- TQString parentDirURL = parentDir.url();
- TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[parentDirURL];
- if ( listers )
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->aboutToRefreshItem( fileitem );
-
- // Also look in urlsCurrentlyListed, in case the user manages to rename during a listing
- listers = urlsCurrentlyListed[parentDirURL];
- if ( listers )
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->aboutToRefreshItem( fileitem );
-}
-
-void KDirListerCache::emitRefreshItem( KFileItem *fileitem )
-{
- // Look whether this item was shown in any view, i.e. held by any dirlister
- KURL parentDir( fileitem->url() );
- parentDir.setPath( parentDir.directory() );
- TQString parentDirURL = parentDir.url();
- TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[parentDirURL];
- if ( listers )
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- {
- kdl->addRefreshItem( fileitem );
- kdl->emitItems();
- }
-
- // Also look in urlsCurrentlyListed, in case the user manages to rename during a listing
- listers = urlsCurrentlyListed[parentDirURL];
- if ( listers )
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- {
- kdl->addRefreshItem( fileitem );
- kdl->emitItems();
- }
-}
-
-KDirListerCache* KDirListerCache::self()
-{
- if ( !s_pSelf )
- s_pSelf = sd_KDirListerCache.setObject( s_pSelf, new KDirListerCache );
-
- return s_pSelf;
-}
-
-bool KDirListerCache::exists()
-{
- return s_pSelf != 0;
-}
-
-
-// private slots
-
-// _file can also be a directory being currently held!
-void KDirListerCache::slotFileDirty( const TQString& _file )
-{
- kdDebug(7004) << k_funcinfo << _file << endl;
-
- if ( !pendingUpdates[_file] )
- {
- KURL dir;
- dir.setPath( _file );
- if ( checkUpdate( dir.url(-1) ) )
- updateDirectory( dir );
-
- // the parent directory of _file
- dir.setPath( dir.directory() );
- if ( checkUpdate( dir.url() ) )
- {
- // Nice hack to save memory: use the qt object name to store the filename
- TQTimer *timer = new TQTimer( this, _file.utf8() );
- connect( timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotFileDirtyDelayed()) );
- pendingUpdates.insert( _file, timer );
- timer->start( 500, true );
- }
- }
-}
-
-// delayed updating of files, FAM is flooding us with events
-void KDirListerCache::slotFileDirtyDelayed()
-{
- TQString file = TQString::fromUtf8( TQT_TQOBJECT_CONST(sender())->name() );
-
- kdDebug(7004) << k_funcinfo << file << endl;
-
- // TODO: do it better: don't always create/delete the TQTimer but reuse it.
- // Delete the timer after the parent directory is removed from the cache.
- pendingUpdates.remove( file );
-
- KURL u;
- u.setPath( file );
- KFileItem *item = findByURL( 0, u ); // search all items
- if ( item )
- {
- // we need to refresh the item, because e.g. the permissions can have changed.
- aboutToRefreshItem( item );
- item->refresh();
- emitRefreshItem( item );
- }
-}
-
-void KDirListerCache::slotFileCreated( const TQString& _file )
-{
- kdDebug(7004) << k_funcinfo << _file << endl;
- // XXX: how to avoid a complete rescan here?
- KURL u;
- u.setPath( _file );
- u.setPath( u.directory() );
- FilesAdded( u );
-}
-
-void KDirListerCache::slotFileDeleted( const TQString& _file )
-{
- kdDebug(7004) << k_funcinfo << _file << endl;
- KURL u;
- u.setPath( _file );
- FilesRemoved( u );
-}
-
-void KDirListerCache::slotEntries( TDEIO::Job *job, const TDEIO::UDSEntryList &entries )
-{
- KURL url = joburl( static_cast<TDEIO::ListJob *>(job) );
- url.adjustPath(-1);
- TQString urlStr = url.url();
-
- kdDebug(7004) << k_funcinfo << "new entries for " << url << endl;
-
- DirItem *dir = itemsInUse[urlStr];
- Q_ASSERT( dir );
-
- TQPtrList<KDirLister> *listers = urlsCurrentlyListed[urlStr];
- Q_ASSERT( listers );
- Q_ASSERT( !listers->isEmpty() );
-
- // check if anyone wants the mimetypes immediately
- bool delayedMimeTypes = true;
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- delayedMimeTypes = delayedMimeTypes && kdl->d->delayedMimeTypes;
-
- // avoid creating these QStrings again and again
- static const TQString& dot = TDEGlobal::staticQString(".");
- static const TQString& dotdot = TDEGlobal::staticQString("..");
-
- TDEIO::UDSEntryListConstIterator it = entries.begin();
- TDEIO::UDSEntryListConstIterator end = entries.end();
-
- for ( ; it != end; ++it )
- {
- TQString name;
-
- // find out about the name
- TDEIO::UDSEntry::ConstIterator entit = (*it).begin();
- for( ; entit != (*it).end(); ++entit )
- if ( (*entit).m_uds == TDEIO::UDS_NAME )
- {
- name = (*entit).m_str;
- break;
- }
-
- Q_ASSERT( !name.isEmpty() );
- if ( name.isEmpty() )
- continue;
-
- if ( name == dot )
- {
- Q_ASSERT( !dir->rootItem );
- dir->rootItem = new KFileItem( *it, url, delayedMimeTypes, true );
-
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- if ( !kdl->d->rootFileItem && kdl->d->url == url )
- kdl->d->rootFileItem = dir->rootItem;
- }
- else if ( name != dotdot )
- {
- KFileItem* item = new KFileItem( *it, url, delayedMimeTypes, true );
- Q_ASSERT( item );
-
- //kdDebug(7004)<< "Adding item: " << item->url() << endl;
- dir->lstItems->append( item );
-
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->addNewItem( item );
- }
- }
-
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->emitItems();
-}
-
-void KDirListerCache::slotResult( TDEIO::Job *j )
-{
- Q_ASSERT( j );
- TDEIO::ListJob *job = static_cast<TDEIO::ListJob *>( j );
- jobs.remove( job );
-
- KURL jobUrl = joburl( job );
- jobUrl.adjustPath(-1); // need remove trailing slashes again, in case of redirections
- TQString jobUrlStr = jobUrl.url();
-
- kdDebug(7004) << k_funcinfo << "finished listing " << jobUrl << endl;
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
-
- TQPtrList<KDirLister> *listers = urlsCurrentlyListed.take( jobUrlStr );
- Q_ASSERT( listers );
-
- // move the directory to the held directories, do it before emitting
- // the signals to make sure it exists in KDirListerCache in case someone
- // calls listDir during the signal emission
- Q_ASSERT( !urlsCurrentlyHeld[jobUrlStr] );
- urlsCurrentlyHeld.insert( jobUrlStr, listers );
-
- KDirLister *kdl;
-
- if ( job->error() )
- {
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- {
- kdl->jobDone( job );
- kdl->handleError( job );
- emit kdl->canceled( jobUrl );
- if ( kdl->numJobs() == 0 )
- {
- kdl->d->complete = true;
- emit kdl->canceled();
- }
- }
- }
- else
- {
- DirItem *dir = itemsInUse[jobUrlStr];
- Q_ASSERT( dir );
- dir->complete = true;
-
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- {
- kdl->jobDone( job );
- emit kdl->completed( jobUrl );
- if ( kdl->numJobs() == 0 )
- {
- kdl->d->complete = true;
- emit kdl->completed();
- }
- }
- }
-
- // TODO: hmm, if there was an error and job is a parent of one or more
- // of the pending urls we should cancel it/them as well
- processPendingUpdates();
-
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
-}
-
-void KDirListerCache::slotRedirection( TDEIO::Job *j, const KURL& url )
-{
- Q_ASSERT( j );
- TDEIO::ListJob *job = static_cast<TDEIO::ListJob *>( j );
-
- KURL oldUrl = job->url(); // here we really need the old url!
- KURL newUrl = url;
-
- // strip trailing slashes
- oldUrl.adjustPath(-1);
- newUrl.adjustPath(-1);
-
- if ( oldUrl == newUrl )
- {
- kdDebug(7004) << k_funcinfo << "New redirection url same as old, giving up." << endl;
- return;
- }
-
- kdDebug(7004) << k_funcinfo << oldUrl.prettyURL() << " -> " << newUrl.prettyURL() << endl;
-
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
-
- // I don't think there can be dirItems that are childs of oldUrl.
- // Am I wrong here? And even if so, we don't need to delete them, right?
- // DF: redirection happens before listDir emits any item. Makes little sense otherwise.
-
- // oldUrl cannot be in itemsCached because only completed items are moved there
- DirItem *dir = itemsInUse.take( oldUrl.url() );
- Q_ASSERT( dir );
-
- TQPtrList<KDirLister> *listers = urlsCurrentlyListed.take( oldUrl.url() );
- Q_ASSERT( listers );
- Q_ASSERT( !listers->isEmpty() );
-
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- {
- // TODO: put in own method?
- if ( kdl->d->url.equals( oldUrl, true ) )
- {
- kdl->d->rootFileItem = 0;
- kdl->d->url = newUrl;
- }
-
- *kdl->d->lstDirs.find( oldUrl ) = newUrl;
-
- if ( kdl->d->lstDirs.count() == 1 )
- {
- emit kdl->clear();
- emit kdl->redirection( newUrl );
- emit kdl->redirection( oldUrl, newUrl );
- }
- else
- {
- emit kdl->clear( oldUrl );
- emit kdl->redirection( oldUrl, newUrl );
- }
- }
-
- // when a lister was stopped before the job emits the redirection signal, the old url will
- // also be in urlsCurrentlyHeld
- TQPtrList<KDirLister> *holders = urlsCurrentlyHeld.take( oldUrl.url() );
- if ( holders )
- {
- Q_ASSERT( !holders->isEmpty() );
-
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- {
- kdl->jobStarted( job );
-
- // do it like when starting a new list-job that will redirect later
- emit kdl->started( oldUrl );
-
- // TODO: maybe don't emit started if there's an update running for newUrl already?
-
- if ( kdl->d->url.equals( oldUrl, true ) )
- {
- kdl->d->rootFileItem = 0;
- kdl->d->url = newUrl;
- }
-
- *kdl->d->lstDirs.find( oldUrl ) = newUrl;
-
- if ( kdl->d->lstDirs.count() == 1 )
- {
- emit kdl->clear();
- emit kdl->redirection( newUrl );
- emit kdl->redirection( oldUrl, newUrl );
- }
- else
- {
- emit kdl->clear( oldUrl );
- emit kdl->redirection( oldUrl, newUrl );
- }
- }
- }
-
- DirItem *newDir = itemsInUse[newUrl.url()];
- if ( newDir )
- {
- kdDebug(7004) << "slotRedirection: " << newUrl.url() << " already in use" << endl;
-
- // only in this case there can newUrl already be in urlsCurrentlyListed or urlsCurrentlyHeld
- delete dir;
-
- // get the job if one's running for newUrl already (can be a list-job or an update-job), but
- // do not return this 'job', which would happen because of the use of redirectionURL()
- TDEIO::ListJob *oldJob = jobForUrl( newUrl.url(), job );
-
- // listers of newUrl with oldJob: forget about the oldJob and use the already running one
- // which will be converted to an updateJob
- TQPtrList<KDirLister> *curListers = urlsCurrentlyListed[newUrl.url()];
- if ( curListers )
- {
- kdDebug(7004) << "slotRedirection: and it is currently listed" << endl;
-
- Q_ASSERT( oldJob ); // ?!
-
- for ( KDirLister *kdl = curListers->first(); kdl; kdl = curListers->next() ) // listers of newUrl
- {
- kdl->jobDone( oldJob );
-
- kdl->jobStarted( job );
- kdl->connectJob( job );
- }
-
- // append listers of oldUrl with newJob to listers of newUrl with oldJob
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- curListers->append( kdl );
- }
- else
- urlsCurrentlyListed.insert( newUrl.url(), listers );
-
- if ( oldJob ) // kill the old job, be it a list-job or an update-job
- killJob( oldJob );
-
- // holders of newUrl: use the already running job which will be converted to an updateJob
- TQPtrList<KDirLister> *curHolders = urlsCurrentlyHeld[newUrl.url()];
- if ( curHolders )
- {
- kdDebug(7004) << "slotRedirection: and it is currently held." << endl;
-
- for ( KDirLister *kdl = curHolders->first(); kdl; kdl = curHolders->next() ) // holders of newUrl
- {
- kdl->jobStarted( job );
- emit kdl->started( newUrl );
- }
-
- // append holders of oldUrl to holders of newUrl
- if ( holders )
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- curHolders->append( kdl );
- }
- else if ( holders )
- urlsCurrentlyHeld.insert( newUrl.url(), holders );
-
-
- // emit old items: listers, holders. NOT: newUrlListers/newUrlHolders, they already have them listed
- // TODO: make this a separate method?
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- {
- if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
- kdl->d->rootFileItem = newDir->rootItem;
-
- kdl->addNewItems( *(newDir->lstItems) );
- kdl->emitItems();
- }
-
- if ( holders )
- {
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- {
- if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
- kdl->d->rootFileItem = newDir->rootItem;
-
- kdl->addNewItems( *(newDir->lstItems) );
- kdl->emitItems();
- }
- }
- }
- else if ( (newDir = itemsCached.take( newUrl.url() )) )
- {
- kdDebug(7004) << "slotRedirection: " << newUrl.url() << " is unused, but already in the cache." << endl;
-
- delete dir;
- itemsInUse.insert( newUrl.url(), newDir );
- urlsCurrentlyListed.insert( newUrl.url(), listers );
- if ( holders )
- urlsCurrentlyHeld.insert( newUrl.url(), holders );
-
- // emit old items: listers, holders
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- {
- if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
- kdl->d->rootFileItem = newDir->rootItem;
-
- kdl->addNewItems( *(newDir->lstItems) );
- kdl->emitItems();
- }
-
- if ( holders )
- {
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- {
- if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
- kdl->d->rootFileItem = newDir->rootItem;
-
- kdl->addNewItems( *(newDir->lstItems) );
- kdl->emitItems();
- }
- }
- }
- else
- {
- kdDebug(7004) << "slotRedirection: " << newUrl.url() << " has not been listed yet." << endl;
-
- delete dir->rootItem;
- dir->rootItem = 0;
- dir->lstItems->clear();
- dir->redirect( newUrl );
- itemsInUse.insert( newUrl.url(), dir );
- urlsCurrentlyListed.insert( newUrl.url(), listers );
-
- if ( holders )
- urlsCurrentlyHeld.insert( newUrl.url(), holders );
- else
- {
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
- return; // only in this case the job doesn't need to be converted,
- }
- }
-
- // make the job an update job
- job->disconnect( this );
-
- connect( job, TQT_SIGNAL(entries( TDEIO::Job *, const TDEIO::UDSEntryList & )),
- this, TQT_SLOT(slotUpdateEntries( TDEIO::Job *, const TDEIO::UDSEntryList & )) );
- connect( job, TQT_SIGNAL(result( TDEIO::Job * )),
- this, TQT_SLOT(slotUpdateResult( TDEIO::Job * )) );
-
- // FIXME: autoUpdate-Counts!!
-
-#ifdef DEBUG_CACHE
- printDebug();
-#endif
-}
-
-void KDirListerCache::renameDir( const KURL &oldUrl, const KURL &newUrl )
-{
- kdDebug(7004) << k_funcinfo << oldUrl.prettyURL() << " -> " << newUrl.prettyURL() << endl;
- TQString oldUrlStr = oldUrl.url(-1);
- TQString newUrlStr = newUrl.url(-1);
-
- // Not enough. Also need to look at any child dir, even sub-sub-sub-dir.
- //DirItem *dir = itemsInUse.take( oldUrlStr );
- //emitRedirections( oldUrl, url );
-
- // Look at all dirs being listed/shown
- TQDictIterator<DirItem> itu( itemsInUse );
- bool goNext;
- while ( itu.current() )
- {
- goNext = true;
- DirItem *dir = itu.current();
- KURL oldDirUrl ( itu.currentKey() );
- //kdDebug(7004) << "itemInUse: " << oldDirUrl.prettyURL() << endl;
- // Check if this dir is oldUrl, or a subfolder of it
- if ( oldUrl.isParentOf( oldDirUrl ) )
- {
- // TODO should use KURL::cleanpath like isParentOf does
- TQString relPath = oldDirUrl.path().mid( oldUrl.path().length() );
-
- KURL newDirUrl( newUrl ); // take new base
- if ( !relPath.isEmpty() )
- newDirUrl.addPath( relPath ); // add unchanged relative path
- //kdDebug(7004) << "KDirListerCache::renameDir new url=" << newDirUrl.prettyURL() << endl;
-
- // Update URL in dir item and in itemsInUse
- dir->redirect( newDirUrl );
- itemsInUse.remove( itu.currentKey() ); // implies ++itu
- itemsInUse.insert( newDirUrl.url(-1), dir );
- goNext = false; // because of the implied ++itu above
- if ( dir->lstItems )
- {
- // Rename all items under that dir
- KFileItemListIterator kit( *dir->lstItems );
- for ( ; kit.current(); ++kit )
- {
- KURL oldItemUrl = (*kit)->url();
- TQString oldItemUrlStr( oldItemUrl.url(-1) );
- KURL newItemUrl( oldItemUrl );
- newItemUrl.setPath( newDirUrl.path() );
- newItemUrl.addPath( oldItemUrl.fileName() );
- kdDebug(7004) << "KDirListerCache::renameDir renaming " << oldItemUrlStr << " to " << newItemUrl.url() << endl;
- (*kit)->setURL( newItemUrl );
- }
- }
- emitRedirections( oldDirUrl, newDirUrl );
- }
- if ( goNext )
- ++itu;
- }
-
- // Is oldUrl a directory in the cache?
- // Remove any child of oldUrl from the cache - even if the renamed dir itself isn't in it!
- removeDirFromCache( oldUrl );
- // TODO rename, instead.
-}
-
-void KDirListerCache::emitRedirections( const KURL &oldUrl, const KURL &url )
-{
- kdDebug(7004) << k_funcinfo << oldUrl.prettyURL() << " -> " << url.prettyURL() << endl;
- TQString oldUrlStr = oldUrl.url(-1);
- TQString urlStr = url.url(-1);
-
- TDEIO::ListJob *job = jobForUrl( oldUrlStr );
- if ( job )
- killJob( job );
-
- // Check if we were listing this dir. Need to abort and restart with new name in that case.
- TQPtrList<KDirLister> *listers = urlsCurrentlyListed.take( oldUrlStr );
- if ( listers )
- {
- // Tell the world that the job listing the old url is dead.
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- {
- if ( job )
- kdl->jobDone( job );
-
- emit kdl->canceled( oldUrl );
- }
-
- urlsCurrentlyListed.insert( urlStr, listers );
- }
-
- // Check if we are currently displaying this directory (odds opposite wrt above)
- // Update urlsCurrentlyHeld dict with new URL
- TQPtrList<KDirLister> *holders = urlsCurrentlyHeld.take( oldUrlStr );
- if ( holders )
- {
- if ( job )
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- kdl->jobDone( job );
-
- urlsCurrentlyHeld.insert( urlStr, holders );
- }
-
- if ( listers )
- {
- updateDirectory( url );
-
- // Tell the world about the new url
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- emit kdl->started( url );
- }
-
- if ( holders )
- {
- // And notify the dirlisters of the redirection
- for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
- {
- *kdl->d->lstDirs.find( oldUrl ) = url;
-
- if ( kdl->d->lstDirs.count() == 1 )
- emit kdl->redirection( url );
-
- emit kdl->redirection( oldUrl, url );
- }
- }
-}
-
-void KDirListerCache::removeDirFromCache( const KURL& dir )
-{
- kdDebug(7004) << "KDirListerCache::removeDirFromCache " << dir.prettyURL() << endl;
- TQCacheIterator<DirItem> itc( itemsCached );
- while ( itc.current() )
- {
- if ( dir.isParentOf( KURL( itc.currentKey() ) ) )
- itemsCached.remove( itc.currentKey() );
- else
- ++itc;
- }
-}
-
-void KDirListerCache::slotUpdateEntries( TDEIO::Job* job, const TDEIO::UDSEntryList& list )
-{
- jobs[static_cast<TDEIO::ListJob*>(job)] += list;
-}
-
-void KDirListerCache::slotUpdateResult( TDEIO::Job * j )
-{
- Q_ASSERT( j );
- TDEIO::ListJob *job = static_cast<TDEIO::ListJob *>( j );
-
- KURL jobUrl = joburl( job );
- jobUrl.adjustPath(-1); // need remove trailing slashes again, in case of redirections
- TQString jobUrlStr = jobUrl.url();
-
- kdDebug(7004) << k_funcinfo << "finished update " << jobUrl << endl;
-
- KDirLister *kdl;
-
- TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[jobUrlStr];
- TQPtrList<KDirLister> *tmpLst = urlsCurrentlyListed.take( jobUrlStr );
-
- if ( tmpLst )
- {
- if ( listers )
- for ( kdl = tmpLst->first(); kdl; kdl = tmpLst->next() )
- {
- Q_ASSERT( listers->containsRef( kdl ) == 0 );
- listers->append( kdl );
- }
- else
- {
- listers = tmpLst;
- urlsCurrentlyHeld.insert( jobUrlStr, listers );
- }
- }
-
- // once we are updating dirs that are only in the cache this will fail!
- Q_ASSERT( listers );
-
- if ( job->error() )
- {
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- {
- kdl->jobDone( job );
-
- //don't bother the user
- //kdl->handleError( job );
-
- emit kdl->canceled( jobUrl );
- if ( kdl->numJobs() == 0 )
- {
- kdl->d->complete = true;
- emit kdl->canceled();
- }
- }
-
- jobs.remove( job );
-
- // TODO: if job is a parent of one or more
- // of the pending urls we should cancel them
- processPendingUpdates();
- return;
- }
-
- DirItem *dir = itemsInUse[jobUrlStr];
- dir->complete = true;
-
-
- // check if anyone wants the mimetypes immediately
- bool delayedMimeTypes = true;
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- delayedMimeTypes = delayedMimeTypes && kdl->d->delayedMimeTypes;
-
- // should be enough to get reasonable speed in most cases
- TQDict<KFileItem> fileItems( 9973 );
-
- KFileItemListIterator kit ( *(dir->lstItems) );
-
- // Unmark all items in url
- for ( ; kit.current(); ++kit )
- {
- (*kit)->unmark();
- fileItems.insert( (*kit)->url().url(), *kit );
- }
-
- static const TQString& dot = TDEGlobal::staticQString(".");
- static const TQString& dotdot = TDEGlobal::staticQString("..");
-
- KFileItem *item = 0, *tmp;
-
- TQValueList<TDEIO::UDSEntry> buf = jobs[job];
- TQValueListIterator<TDEIO::UDSEntry> it = buf.begin();
- for ( ; it != buf.end(); ++it )
- {
- // Form the complete url
- if ( !item )
- item = new KFileItem( *it, jobUrl, delayedMimeTypes, true );
- else
- item->setUDSEntry( *it, jobUrl, delayedMimeTypes, true );
-
- // Find out about the name
- TQString name = item->name();
- Q_ASSERT( !name.isEmpty() );
-
- // we duplicate the check for dotdot here, to avoid iterating over
- // all items again and checking in matchesFilter() that way.
- if ( name.isEmpty() || name == dotdot )
- continue;
-
- if ( name == dot )
- {
- // if the update was started before finishing the original listing
- // there is no root item yet
- if ( !dir->rootItem )
- {
- dir->rootItem = item;
- item = 0;
-
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- if ( !kdl->d->rootFileItem && kdl->d->url == jobUrl )
- kdl->d->rootFileItem = dir->rootItem;
- }
-
- continue;
- }
-
- // Find this item
- if ( (tmp = fileItems[item->url().url()]) )
- {
- tmp->mark();
-
- // check if something changed for this file
- if ( !tmp->cmp( *item ) )
- {
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->aboutToRefreshItem( tmp );
-
- //kdDebug(7004) << "slotUpdateResult: file changed: " << tmp->name() << endl;
- tmp->assign( *item );
-
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->addRefreshItem( tmp );
- }
- }
- else // this is a new file
- {
- //kdDebug(7004) << "slotUpdateResult: new file: " << name << endl;
-
- item->mark();
- dir->lstItems->append( item );
-
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->addNewItem( item );
-
- // item used, we need a new one for the next iteration
- item = 0;
- }
- }
-
- if ( item )
- delete item;
-
- jobs.remove( job );
-
- deleteUnmarkedItems( listers, dir->lstItems );
-
- for ( kdl = listers->first(); kdl; kdl = listers->next() )
- {
- kdl->emitItems();
-
- kdl->jobDone( job );
-
- emit kdl->completed( jobUrl );
- if ( kdl->numJobs() == 0 )
- {
- kdl->d->complete = true;
- emit kdl->completed();
- }
- }
-
- // TODO: hmm, if there was an error and job is a parent of one or more
- // of the pending urls we should cancel it/them as well
- processPendingUpdates();
-}
-
-// private
-
-TDEIO::ListJob *KDirListerCache::jobForUrl( const TQString& url, TDEIO::ListJob *not_job )
-{
- TDEIO::ListJob *job;
- TQMap< TDEIO::ListJob *, TQValueList<TDEIO::UDSEntry> >::Iterator it = jobs.begin();
- while ( it != jobs.end() )
- {
- job = it.key();
- if ( joburl( job ).url(-1) == url && job != not_job )
- return job;
- ++it;
- }
- return 0;
-}
-
-const KURL& KDirListerCache::joburl( TDEIO::ListJob *job )
-{
- if ( job->redirectionURL().isValid() )
- return job->redirectionURL();
- else
- return job->url();
-}
-
-void KDirListerCache::killJob( TDEIO::ListJob *job )
-{
- jobs.remove( job );
- job->disconnect( this );
- job->kill();
-}
-
-void KDirListerCache::deleteUnmarkedItems( TQPtrList<KDirLister> *listers, KFileItemList *lstItems )
-{
- // Find all unmarked items and delete them
- KFileItem* item;
- lstItems->first();
- while ( (item = lstItems->current()) )
- if ( !item->isMarked() )
- {
- //kdDebug() << k_funcinfo << item->name() << endl;
- for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
- kdl->emitDeleteItem( item );
-
- if ( item->isDir() )
- deleteDir( item->url() );
-
- // finally actually delete the item
- lstItems->take();
- delete item;
- }
- else
- lstItems->next();
-}
-
-void KDirListerCache::deleteDir( const KURL& dirUrl )
-{
- //kdDebug() << k_funcinfo << dirUrl.prettyURL() << endl;
- // unregister and remove the childs of the deleted item.
- // Idea: tell all the KDirListers that they should forget the dir
- // and then remove it from the cache.
-
- TQDictIterator<DirItem> itu( itemsInUse );
- while ( itu.current() )
- {
- KURL deletedUrl( itu.currentKey() );
- if ( dirUrl.isParentOf( deletedUrl ) )
- {
- // stop all jobs for deletedUrl
-
- TQPtrList<KDirLister> *kdls = urlsCurrentlyListed[deletedUrl.url()];
- if ( kdls ) // yeah, I lack good names
- {
- // we need a copy because stop modifies the list
- kdls = new TQPtrList<KDirLister>( *kdls );
- for ( KDirLister *kdl = kdls->first(); kdl; kdl = kdls->next() )
- stop( kdl, deletedUrl );
-
- delete kdls;
- }
-
- // tell listers holding deletedUrl to forget about it
- // this will stop running updates for deletedUrl as well
-
- kdls = urlsCurrentlyHeld[deletedUrl.url()];
- if ( kdls )
- {
- // we need a copy because forgetDirs modifies the list
- kdls = new TQPtrList<KDirLister>( *kdls );
-
- for ( KDirLister *kdl = kdls->first(); kdl; kdl = kdls->next() )
- {
- // lister's root is the deleted item
- if ( kdl->d->url == deletedUrl )
- {
- // tell the view first. It might need the subdirs' items (which forgetDirs will delete)
- if ( kdl->d->rootFileItem )
- emit kdl->deleteItem( kdl->d->rootFileItem );
- forgetDirs( kdl );
- kdl->d->rootFileItem = 0;
- }
- else
- {
- bool treeview = kdl->d->lstDirs.count() > 1;
- if ( !treeview )
- emit kdl->clear();
-
- forgetDirs( kdl, deletedUrl, treeview );
- }
- }
-
- delete kdls;
- }
-
- // delete the entry for deletedUrl - should not be needed, it's in
- // items cached now
-
- DirItem *dir = itemsInUse.take( deletedUrl.url() );
- Q_ASSERT( !dir );
- if ( !dir ) // take didn't find it - move on
- ++itu;
- }
- else
- ++itu;
- }
-
- // remove the children from the cache
- removeDirFromCache( dirUrl );
-}
-
-void KDirListerCache::processPendingUpdates()
-{
- // TODO
-}
-
-#ifndef NDEBUG
-void KDirListerCache::printDebug()
-{
- kdDebug(7004) << "Items in use: " << endl;
- TQDictIterator<DirItem> itu( itemsInUse );
- for ( ; itu.current() ; ++itu ) {
- kdDebug(7004) << " " << itu.currentKey() << " URL: " << itu.current()->url
- << " rootItem: " << ( itu.current()->rootItem ? itu.current()->rootItem->url() : KURL() )
- << " autoUpdates refcount: " << itu.current()->autoUpdates
- << " complete: " << itu.current()->complete
- << ( itu.current()->lstItems ? TQString(" with %1 items.").arg(itu.current()->lstItems->count()) : TQString(" lstItems=NULL") ) << endl;
- }
-
- kdDebug(7004) << "urlsCurrentlyHeld: " << endl;
- TQDictIterator< TQPtrList<KDirLister> > it( urlsCurrentlyHeld );
- for ( ; it.current() ; ++it )
- {
- TQString list;
- for ( TQPtrListIterator<KDirLister> listit( *it.current() ); listit.current(); ++listit )
- list += " 0x" + TQString::number( (long)listit.current(), 16 );
- kdDebug(7004) << " " << it.currentKey() << " " << it.current()->count() << " listers: " << list << endl;
- }
-
- kdDebug(7004) << "urlsCurrentlyListed: " << endl;
- TQDictIterator< TQPtrList<KDirLister> > it2( urlsCurrentlyListed );
- for ( ; it2.current() ; ++it2 )
- {
- TQString list;
- for ( TQPtrListIterator<KDirLister> listit( *it2.current() ); listit.current(); ++listit )
- list += " 0x" + TQString::number( (long)listit.current(), 16 );
- kdDebug(7004) << " " << it2.currentKey() << " " << it2.current()->count() << " listers: " << list << endl;
- }
-
- TQMap< TDEIO::ListJob *, TQValueList<TDEIO::UDSEntry> >::Iterator jit = jobs.begin();
- kdDebug(7004) << "Jobs: " << endl;
- for ( ; jit != jobs.end() ; ++jit )
- kdDebug(7004) << " " << jit.key() << " listing " << joburl( jit.key() ).prettyURL() << ": " << (*jit).count() << " entries." << endl;
-
- kdDebug(7004) << "Items in cache: " << endl;
- TQCacheIterator<DirItem> itc( itemsCached );
- for ( ; itc.current() ; ++itc )
- kdDebug(7004) << " " << itc.currentKey() << " rootItem: "
- << ( itc.current()->rootItem ? itc.current()->rootItem->url().prettyURL() : TQString("NULL") )
- << ( itc.current()->lstItems ? TQString(" with %1 items.").arg(itc.current()->lstItems->count()) : TQString(" lstItems=NULL") ) << endl;
-}
-#endif
-
-/*********************** -- The new KDirLister -- ************************/
-
-
-KDirLister::KDirLister( bool _delayedMimeTypes )
-{
- kdDebug(7003) << "+KDirLister" << endl;
-
- d = new KDirListerPrivate;
-
- d->complete = true;
- d->delayedMimeTypes = _delayedMimeTypes;
-
- setAutoUpdate( true );
- setDirOnlyMode( false );
- setShowingDotFiles( false );
-
- setAutoErrorHandlingEnabled( true, 0 );
-}
-
-KDirLister::~KDirLister()
-{
- kdDebug(7003) << "-KDirLister" << endl;
-
- if ( KDirListerCache::exists() )
- {
- // Stop all running jobs
- stop();
- s_pCache->forgetDirs( this );
- }
-
- delete d;
-}
-
-bool KDirLister::openURL( const KURL& _url, bool _keep, bool _reload )
-{
- kdDebug(7003) << k_funcinfo << _url.prettyURL()
- << " keep=" << _keep << " reload=" << _reload << endl;
-
- // emit the current changes made to avoid an inconsistent treeview
- if ( d->changes != NONE && _keep )
- emitChanges();
-
- d->changes = NONE;
-
- // If a local path is available, monitor that instead of the given remote URL...
- KURL realURL = _url;
- if (!realURL.isLocalFile()) {
- TDEIO::LocalURLJob* localURLJob = TDEIO::localURL(_url);
- if (localURLJob) {
- connect(localURLJob, TQT_SIGNAL(localURL(TDEIO::Job*, const KURL&, bool)), this, TQT_SLOT(slotLocalURL(TDEIO::Job*, const KURL&, bool)));
- connect(localURLJob, TQT_SIGNAL(destroyed()), this, TQT_SLOT(slotLocalURLKIODestroyed()));
- d->localURLSlotFired = false;
- while (!d->localURLSlotFired) {
- tqApp->eventLoop()->processEvents(TQEventLoop::ExcludeUserInput);
- usleep(1000);
- }
- if (d->localURLResultIsLocal) {
- realURL = d->localURLResultURL;
- }
- }
- }
-
- return s_pCache->listDir( this, realURL, _keep, _reload );
-}
-
-void KDirLister::slotLocalURL(TDEIO::Job *job, const KURL& url, bool isLocal) {
- d->localURLSlotFired = true;
- d->localURLResultURL = url;
- d->localURLResultIsLocal = isLocal;
-}
-
-void KDirLister::slotLocalURLKIODestroyed() {
- if (!d->localURLSlotFired) {
- d->localURLSlotFired = true;
- d->localURLResultURL = KURL();
- d->localURLResultIsLocal = false;
- }
-}
-
-void KDirLister::stop()
-{
- kdDebug(7003) << k_funcinfo << endl;
- s_pCache->stop( this );
-}
-
-void KDirLister::stop( const KURL& _url )
-{
- kdDebug(7003) << k_funcinfo << _url.prettyURL() << endl;
- s_pCache->stop( this, _url );
-}
-
-bool KDirLister::autoUpdate() const
-{
- return d->autoUpdate;
-}
-
-void KDirLister::setAutoUpdate( bool _enable )
-{
- if ( d->autoUpdate == _enable )
- return;
-
- d->autoUpdate = _enable;
- s_pCache->setAutoUpdate( this, _enable );
-}
-
-bool KDirLister::showingDotFiles() const
-{
- return d->isShowingDotFiles;
-}
-
-void KDirLister::setShowingDotFiles( bool _showDotFiles )
-{
- if ( d->isShowingDotFiles == _showDotFiles )
- return;
-
- d->isShowingDotFiles = _showDotFiles;
- d->changes ^= DOT_FILES;
-}
-
-bool KDirLister::dirOnlyMode() const
-{
- return d->dirOnlyMode;
-}
-
-void KDirLister::setDirOnlyMode( bool _dirsOnly )
-{
- if ( d->dirOnlyMode == _dirsOnly )
- return;
-
- d->dirOnlyMode = _dirsOnly;
- d->changes ^= DIR_ONLY_MODE;
-}
-
-bool KDirLister::autoErrorHandlingEnabled() const
-{
- return d->autoErrorHandling;
-}
-
-void KDirLister::setAutoErrorHandlingEnabled( bool enable, TQWidget* parent )
-{
- d->autoErrorHandling = enable;
- d->errorParent = parent;
-}
-
-const KURL& KDirLister::url() const
-{
- return d->url;
-}
-
-const KURL::List& KDirLister::directories() const
-{
- return d->lstDirs;
-}
-
-void KDirLister::emitChanges()
-{
- if ( d->changes == NONE )
- return;
-
- static const TQString& dot = TDEGlobal::staticQString(".");
- static const TQString& dotdot = TDEGlobal::staticQString("..");
-
- for ( KURL::List::Iterator it = d->lstDirs.begin();
- it != d->lstDirs.end(); ++it )
- {
- KFileItemListIterator kit( *s_pCache->itemsForDir( *it ) );
- for ( ; kit.current(); ++kit )
- {
- if ( (*kit)->text() == dot || (*kit)->text() == dotdot )
- continue;
-
- bool oldMime = true, newMime = true;
-
- if ( d->changes & MIME_FILTER )
- {
- oldMime = doMimeFilter( (*kit)->mimetype(), d->oldMimeFilter )
- && doMimeExcludeFilter( (*kit)->mimetype(), d->oldMimeExcludeFilter );
- newMime = doMimeFilter( (*kit)->mimetype(), d->mimeFilter )
- && doMimeExcludeFilter( (*kit)->mimetype(), d->mimeExcludeFilter );
-
- if ( oldMime && !newMime )
- {
- emit deleteItem( *kit );
- continue;
- }
- }
-
- if ( d->changes & DIR_ONLY_MODE )
- {
- // the lister switched to dirOnlyMode
- if ( d->dirOnlyMode )
- {
- if ( !(*kit)->isDir() )
- emit deleteItem( *kit );
- }
- else if ( !(*kit)->isDir() )
- addNewItem( *kit );
-
- continue;
- }
-
- if ( (*kit)->isHidden() )
- {
- if ( d->changes & DOT_FILES )
- {
- // the lister switched to dot files mode
- if ( d->isShowingDotFiles )
- addNewItem( *kit );
- else
- emit deleteItem( *kit );
-
- continue;
- }
- }
- else if ( d->changes & NAME_FILTER )
- {
- bool oldName = (*kit)->isDir() ||
- d->oldFilters.isEmpty() ||
- doNameFilter( (*kit)->text(), d->oldFilters );
-
- bool newName = (*kit)->isDir() ||
- d->lstFilters.isEmpty() ||
- doNameFilter( (*kit)->text(), d->lstFilters );
-
- if ( oldName && !newName )
- {
- emit deleteItem( *kit );
- continue;
- }
- else if ( !oldName && newName )
- addNewItem( *kit );
- }
-
- if ( (d->changes & MIME_FILTER) && !oldMime && newMime )
- addNewItem( *kit );
- }
-
- emitItems();
- }
-
- d->changes = NONE;
-}
-
-void KDirLister::updateDirectory( const KURL& _u )
-{
- s_pCache->updateDirectory( _u );
-}
-
-bool KDirLister::isFinished() const
-{
- return d->complete;
-}
-
-KFileItem *KDirLister::rootItem() const
-{
- return d->rootFileItem;
-}
-
-KFileItem *KDirLister::findByURL( const KURL& _url ) const
-{
- return s_pCache->findByURL( this, _url );
-}
-
-KFileItem *KDirLister::findByName( const TQString& _name ) const
-{
- return s_pCache->findByName( this, _name );
-}
-
-#ifndef KDE_NO_COMPAT
-KFileItem *KDirLister::find( const KURL& _url ) const
-{
- return findByURL( _url );
-}
-#endif
-
-
-// ================ public filter methods ================ //
-
-void KDirLister::setNameFilter( const TQString& nameFilter )
-{
- if ( !(d->changes & NAME_FILTER) )
- {
- d->oldFilters = d->lstFilters;
- d->lstFilters.setAutoDelete( false );
- }
-
- d->lstFilters.clear();
- d->lstFilters.setAutoDelete( true );
-
- d->nameFilter = nameFilter;
-
- // Split on white space
- TQStringList list = TQStringList::split( ' ', nameFilter );
- for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it )
- d->lstFilters.append( new TQRegExp(*it, false, true ) );
-
- d->changes |= NAME_FILTER;
-}
-
-const TQString& KDirLister::nameFilter() const
-{
- return d->nameFilter;
-}
-
-void KDirLister::setMimeFilter( const TQStringList& mimeFilter )
-{
- if ( !(d->changes & MIME_FILTER) )
- d->oldMimeFilter = d->mimeFilter;
-
- if ( mimeFilter.find("all/allfiles") != mimeFilter.end() ||
- mimeFilter.find("all/all") != mimeFilter.end() )
- d->mimeFilter.clear();
- else
- d->mimeFilter = mimeFilter;
-
- d->changes |= MIME_FILTER;
-}
-
-void KDirLister::setMimeExcludeFilter( const TQStringList& mimeExcludeFilter )
-{
- if ( !(d->changes & MIME_FILTER) )
- d->oldMimeExcludeFilter = d->mimeExcludeFilter;
-
- d->mimeExcludeFilter = mimeExcludeFilter;
- d->changes |= MIME_FILTER;
-}
-
-
-void KDirLister::clearMimeFilter()
-{
- if ( !(d->changes & MIME_FILTER) )
- {
- d->oldMimeFilter = d->mimeFilter;
- d->oldMimeExcludeFilter = d->mimeExcludeFilter;
- }
- d->mimeFilter.clear();
- d->mimeExcludeFilter.clear();
- d->changes |= MIME_FILTER;
-}
-
-const TQStringList& KDirLister::mimeFilters() const
-{
- return d->mimeFilter;
-}
-
-bool KDirLister::matchesFilter( const TQString& name ) const
-{
- return doNameFilter( name, d->lstFilters );
-}
-
-bool KDirLister::matchesMimeFilter( const TQString& mime ) const
-{
- return doMimeFilter( mime, d->mimeFilter ) && doMimeExcludeFilter(mime,d->mimeExcludeFilter);
-}
-
-// ================ protected methods ================ //
-
-bool KDirLister::matchesFilter( const KFileItem *item ) const
-{
- Q_ASSERT( item );
- static const TQString& dotdot = TDEGlobal::staticQString("..");
-
- if ( item->text() == dotdot )
- return false;
-
- if ( !d->isShowingDotFiles && item->isHidden() )
- return false;
-
- if ( item->isDir() || d->lstFilters.isEmpty() )
- return true;
-
- return matchesFilter( item->text() );
-}
-
-bool KDirLister::matchesMimeFilter( const KFileItem *item ) const
-{
- Q_ASSERT( item );
- // Don't lose time determining the mimetype if there is no filter
- if ( d->mimeFilter.isEmpty() && d->mimeExcludeFilter.isEmpty() )
- return true;
- return matchesMimeFilter( item->mimetype() );
-}
-
-bool KDirLister::doNameFilter( const TQString& name, const TQPtrList<TQRegExp>& filters ) const
-{
- for ( TQPtrListIterator<TQRegExp> it( filters ); it.current(); ++it )
- if ( it.current()->exactMatch( name ) )
- return true;
-
- return false;
-}
-
-bool KDirLister::doMimeFilter( const TQString& mime, const TQStringList& filters ) const
-{
- if ( filters.isEmpty() )
- return true;
-
- KMimeType::Ptr mimeptr = KMimeType::mimeType(mime);
- //kdDebug(7004) << "doMimeFilter: investigating: "<<mimeptr->name()<<endl;
- TQStringList::ConstIterator it = filters.begin();
- for ( ; it != filters.end(); ++it )
- if ( mimeptr->is(*it) )
- return true;
- //else kdDebug(7004) << "doMimeFilter: compared without result to "<<*it<<endl;
-
-
- return false;
-}
-
-bool KDirLister::doMimeExcludeFilter( const TQString& mime, const TQStringList& filters ) const
-{
- if ( filters.isEmpty() )
- return true;
-
- TQStringList::ConstIterator it = filters.begin();
- for ( ; it != filters.end(); ++it )
- if ( (*it) == mime )
- return false;
-
- return true;
-}
-
-
-bool KDirLister::validURL( const KURL& _url ) const
-{
- return s_pCache->validURL( this, _url );
-}
-
-void KDirLister::handleError( TDEIO::Job *job )
-{
- if ( d->autoErrorHandling )
- job->showErrorDialog( d->errorParent );
-}
-
-
-// ================= private methods ================= //
-
-void KDirLister::addNewItem( const KFileItem *item )
-{
- if ( ( d->dirOnlyMode && !item->isDir() ) || !matchesFilter( item ) )
- return; // No reason to continue... bailing out here prevents a mimetype scan.
-
- if ( matchesMimeFilter( item ) )
- {
- if ( !d->lstNewItems )
- d->lstNewItems = new KFileItemList;
-
- d->lstNewItems->append( item ); // items not filtered
- }
- else
- {
- if ( !d->lstMimeFilteredItems )
- d->lstMimeFilteredItems = new KFileItemList;
-
- d->lstMimeFilteredItems->append( item ); // only filtered by mime
- }
-}
-
-void KDirLister::addNewItems( const KFileItemList& items )
-{
- // TODO: make this faster - test if we have a filter at all first
- // DF: was this profiled? The matchesFoo() functions should be fast, w/o filters...
- // Of course if there is no filter and we can do a range-insertion instead of a loop, that might be good.
- // But that's for Qt4, not possible with TQPtrList.
- for ( KFileItemListIterator kit( items ); kit.current(); ++kit )
- addNewItem( *kit );
-}
-
-void KDirLister::aboutToRefreshItem( const KFileItem *item )
-{
- // The code here follows the logic in addNewItem
- if ( ( d->dirOnlyMode && !item->isDir() ) || !matchesFilter( item ) )
- d->refreshItemWasFiltered = true;
- else if ( !matchesMimeFilter( item ) )
- d->refreshItemWasFiltered = true;
- else
- d->refreshItemWasFiltered = false;
-}
-
-void KDirLister::addRefreshItem( const KFileItem *item )
-{
- bool isExcluded = (d->dirOnlyMode && !item->isDir()) || !matchesFilter( item );
-
- if ( !isExcluded && matchesMimeFilter( item ) )
- {
- if ( d->refreshItemWasFiltered )
- {
- if ( !d->lstNewItems )
- d->lstNewItems = new KFileItemList;
-
- d->lstNewItems->append( item );
- }
- else
- {
- if ( !d->lstRefreshItems )
- d->lstRefreshItems = new KFileItemList;
-
- d->lstRefreshItems->append( item );
- }
- }
- else if ( !d->refreshItemWasFiltered )
- {
- if ( !d->lstRemoveItems )
- d->lstRemoveItems = new KFileItemList;
-
- // notify the user that the mimetype of a file changed that doesn't match
- // a filter or does match an exclude filter
- d->lstRemoveItems->append( item );
- }
-}
-
-void KDirLister::emitItems()
-{
- KFileItemList *tmpNew = d->lstNewItems;
- d->lstNewItems = 0;
-
- KFileItemList *tmpMime = d->lstMimeFilteredItems;
- d->lstMimeFilteredItems = 0;
-
- KFileItemList *tmpRefresh = d->lstRefreshItems;
- d->lstRefreshItems = 0;
-
- KFileItemList *tmpRemove = d->lstRemoveItems;
- d->lstRemoveItems = 0;
-
- if ( tmpNew )
- {
- emit newItems( *tmpNew );
- delete tmpNew;
- }
-
- if ( tmpMime )
- {
- emit itemsFilteredByMime( *tmpMime );
- delete tmpMime;
- }
-
- if ( tmpRefresh )
- {
- emit refreshItems( *tmpRefresh );
- delete tmpRefresh;
- }
-
- if ( tmpRemove )
- {
- for ( KFileItem *tmp = tmpRemove->first(); tmp; tmp = tmpRemove->next() )
- emit deleteItem( tmp );
- delete tmpRemove;
- }
-}
-
-void KDirLister::emitDeleteItem( KFileItem *item )
-{
- if ( ( d->dirOnlyMode && !item->isDir() ) || !matchesFilter( item ) )
- return; // No reason to continue... bailing out here prevents a mimetype scan.
- if ( matchesMimeFilter( item ) )
- emit deleteItem( item );
-}
-
-
-// ================ private slots ================ //
-
-void KDirLister::slotInfoMessage( TDEIO::Job *, const TQString& message )
-{
- emit infoMessage( message );
-}
-
-void KDirLister::slotPercent( TDEIO::Job *job, unsigned long pcnt )
-{
- d->jobData[static_cast<TDEIO::ListJob *>(job)].percent = pcnt;
-
- int result = 0;
-
- TDEIO::filesize_t size = 0;
-
- TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
- while ( dataIt != d->jobData.end() )
- {
- result += (*dataIt).percent * (*dataIt).totalSize;
- size += (*dataIt).totalSize;
- ++dataIt;
- }
-
- if ( size != 0 )
- result /= size;
- else
- result = 100;
- emit percent( result );
-}
-
-void KDirLister::slotTotalSize( TDEIO::Job *job, TDEIO::filesize_t size )
-{
- d->jobData[static_cast<TDEIO::ListJob *>(job)].totalSize = size;
-
- TDEIO::filesize_t result = 0;
- TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
- while ( dataIt != d->jobData.end() )
- {
- result += (*dataIt).totalSize;
- ++dataIt;
- }
-
- emit totalSize( result );
-}
-
-void KDirLister::slotProcessedSize( TDEIO::Job *job, TDEIO::filesize_t size )
-{
- d->jobData[static_cast<TDEIO::ListJob *>(job)].processedSize = size;
-
- TDEIO::filesize_t result = 0;
- TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
- while ( dataIt != d->jobData.end() )
- {
- result += (*dataIt).processedSize;
- ++dataIt;
- }
-
- emit processedSize( result );
-}
-
-void KDirLister::slotSpeed( TDEIO::Job *job, unsigned long spd )
-{
- d->jobData[static_cast<TDEIO::ListJob *>(job)].speed = spd;
-
- int result = 0;
- TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
- while ( dataIt != d->jobData.end() )
- {
- result += (*dataIt).speed;
- ++dataIt;
- }
-
- emit speed( result );
-}
-
-uint KDirLister::numJobs()
-{
- return d->jobData.count();
-}
-
-void KDirLister::jobDone( TDEIO::ListJob *job )
-{
- d->jobData.remove( job );
-}
-
-void KDirLister::jobStarted( TDEIO::ListJob *job )
-{
- KDirListerPrivate::JobData jobData;
- jobData.speed = 0;
- jobData.percent = 0;
- jobData.processedSize = 0;
- jobData.totalSize = 0;
-
- d->jobData.insert( job, jobData );
- d->complete = false;
-}
-
-void KDirLister::connectJob( TDEIO::ListJob *job )
-{
- connect( job, TQT_SIGNAL(infoMessage( TDEIO::Job *, const TQString& )),
- this, TQT_SLOT(slotInfoMessage( TDEIO::Job *, const TQString& )) );
- connect( job, TQT_SIGNAL(percent( TDEIO::Job *, unsigned long )),
- this, TQT_SLOT(slotPercent( TDEIO::Job *, unsigned long )) );
- connect( job, TQT_SIGNAL(totalSize( TDEIO::Job *, TDEIO::filesize_t )),
- this, TQT_SLOT(slotTotalSize( TDEIO::Job *, TDEIO::filesize_t )) );
- connect( job, TQT_SIGNAL(processedSize( TDEIO::Job *, TDEIO::filesize_t )),
- this, TQT_SLOT(slotProcessedSize( TDEIO::Job *, TDEIO::filesize_t )) );
- connect( job, TQT_SIGNAL(speed( TDEIO::Job *, unsigned long )),
- this, TQT_SLOT(slotSpeed( TDEIO::Job *, unsigned long )) );
-}
-
-void KDirLister::setMainWindow( TQWidget *window )
-{
- d->window = window;
-}
-
-TQWidget *KDirLister::mainWindow()
-{
- return d->window;
-}
-
-KFileItemList KDirLister::items( WhichItems which ) const
-{
- return itemsForDir( url(), which );
-}
-
-KFileItemList KDirLister::itemsForDir( const KURL& dir, WhichItems which ) const
-{
- KFileItemList result;
- KFileItemList *allItems = s_pCache->itemsForDir( dir );
- if ( !allItems )
- return result;
-
- if ( which == AllItems )
- result = *allItems; // shallow copy
- else // only items passing the filters
- {
- for ( KFileItemListIterator kit( *allItems ); kit.current(); ++kit )
- {
- KFileItem *item = *kit;
- bool isExcluded = (d->dirOnlyMode && !item->isDir()) || !matchesFilter( item );
- if ( !isExcluded && matchesMimeFilter( item ) )
- result.append( item );
- }
- }
-
- return result;
-}
-
-// to keep BC changes
-
-void KDirLister::virtual_hook( int, void * )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-#include "kdirlister.moc"
-#include "kdirlister_p.moc"
diff --git a/kio/kio/kdirlister.h b/kio/kio/kdirlister.h
deleted file mode 100644
index 2688fcd9c..000000000
--- a/kio/kio/kdirlister.h
+++ /dev/null
@@ -1,634 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 1999 David Faure <faure@kde.org>
- 2001, 2002, 2004, 2005 Michael Brade <brade@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef kdirlister_h
-#define kdirlister_h
-
-#include "kfileitem.h"
-#include "kdirnotify.h"
-
-#include <tqstring.h>
-#include <tqstringlist.h>
-
-#include <kurl.h>
-
-namespace TDEIO { class Job; class ListJob; }
-
-/**
- * The dir lister deals with the kiojob used to list and update a directory
- * and has signals for the user of this class (e.g. konqueror view or
- * kdesktop) to create/destroy its items when asked.
- *
- * This class is independent from the graphical representation of the dir
- * (icon container, tree view, ...) and it stores the items (as KFileItems).
- *
- * Typical usage :
- * @li Create an instance.
- * @li Connect to at least update, clear, newItem, and deleteItem.
- * @li Call openURL - the signals will be called.
- * @li Reuse the instance when opening a new url (openURL).
- * @li Destroy the instance when not needed anymore (usually destructor).
- *
- * Advanced usage : call openURL with _keep = true to list directories
- * without forgetting the ones previously read (e.g. for a tree view)
- *
- * @short Helper class for the kiojob used to list and update a directory.
- * @author Michael Brade <brade@kde.org>
- */
-class TDEIO_EXPORT KDirLister : public TQObject
-{
- class KDirListerPrivate;
- friend class KDirListerPrivate;
- friend class KDirListerCache;
-
- Q_OBJECT
- TQ_PROPERTY( bool autoUpdate READ autoUpdate WRITE setAutoUpdate )
- TQ_PROPERTY( bool showingDotFiles READ showingDotFiles WRITE setShowingDotFiles )
- TQ_PROPERTY( bool dirOnlyMode READ dirOnlyMode WRITE setDirOnlyMode )
- TQ_PROPERTY( bool autoErrorHandlingEnabled READ autoErrorHandlingEnabled )
- TQ_PROPERTY( TQString nameFilter READ nameFilter WRITE setNameFilter )
- TQ_PROPERTY( TQStringList mimeFilter READ mimeFilters WRITE setMimeFilter RESET clearMimeFilter )
-
-public:
- /**
- * Create a directory lister.
- * @param _delayedMimeTypes if true, mime types will be fetched on demand. If false,
- * they will always be fetched immediately
- */
- KDirLister( bool _delayedMimeTypes = false );
-
- /**
- * Destroy the directory lister.
- */
- virtual ~KDirLister();
-
- /**
- * Run the directory lister on the given url.
- *
- * This method causes KDirLister to emit _all_ the items of @p _url, in any case.
- * Depending on @p _keep either clear() or clear(const KURL &) will be
- * emitted first.
- *
- * The newItems() signal may be emitted more than once to supply you
- * with KFileItems, up until the signal completed() is emitted
- * (and isFinished() returns true).
- *
- * @param _url the directory URL.
- * @param _keep if true the previous directories aren't forgotten
- * (they are still watched by kdirwatch and their items
- * are kept for this KDirLister). This is useful for e.g.
- * a treeview.
- * @param _reload indicates wether to use the cache (false) or to reread the
- * directory from the disk.
- * Use only when opening a dir not yet listed by this lister
- * without using the cache. Otherwise use updateDirectory.
- * @return true if successful,
- * false otherwise (e.g. invalid @p _url)
- */
- virtual bool openURL( const KURL& _url, bool _keep = false, bool _reload = false );
-
- /**
- * Stop listing all directories currently being listed.
- *
- * Emits canceled() if there was at least one job running.
- * Emits canceled( const KURL& ) for each stopped job if
- * there are at least two dirctories being watched by KDirLister.
- */
- virtual void stop();
-
- /**
- * Stop listing the given directory.
- *
- * Emits canceled() if the killed job was the last running one.
- * Emits canceled( const KURL& ) for the killed job if
- * there are at least two directories being watched by KDirLister.
- * No signal is emitted if there was no job running for @p _url.
- * @param _url the directory URL
- */
- virtual void stop( const KURL& _url );
-
- /**
- * Checks whether KDirWatch will automatically update directories. This is
- * enabled by default.
- * @return true if KDirWatch is used to automatically update directories.
- */
- bool autoUpdate() const;
-
- /**
- * Enable/disable automatic directory updating, when a directory changes
- * (using KDirWatch).
- * @param enable true to enable, false to disable
- */
- virtual void setAutoUpdate( bool enable );
-
- /**
- * Check whether auto error handling is enabled.
- * If enabled, it will show an error dialog to the user when an
- * error occurs. It is turned on by default.
- * @return true if auto error handling is enabled, false otherwise
- * @see setAutoErrorHandlingEnabled()
- */
- bool autoErrorHandlingEnabled() const;
-
- /**
- * Enable or disable auto error handling is enabled.
- * If enabled, it will show an error dialog to the user when an
- * error occurs. It is turned on by default.
- * @param enable true to enable auto error handling, false to disable
- * @param parent the parent widget for the error dialogs, can be 0 for
- * top-level
- * @see autoErrorHandlingEnabled()
- */
- void setAutoErrorHandlingEnabled( bool enable, TQWidget *parent );
-
- /**
- * Checks whether hidden files (files beginning with a dot) will be
- * shown.
- * By default this option is disabled (hidden files will be not shown).
- * @return true if dot files are shown, false otherwise
- * @see setShowingDotFiles()
- */
- bool showingDotFiles() const;
-
- /**
- * Changes the "is viewing dot files" setting.
- * Calls updateDirectory() if setting changed.
- * By default this option is disabled (hidden files will not be shown).
- * @param _showDotFiles true to enable showing hidden files, false to
- * disable
- * @see showingDotFiles()
- */
- virtual void setShowingDotFiles( bool _showDotFiles );
-
- /**
- * Checks whether the KDirLister only lists directories or all
- * files.
- * By default this option is disabled (all files will be shown).
- * @return true if setDirOnlyMode(true) was called
- */
- bool dirOnlyMode() const;
-
- /**
- * Call this to list only directories.
- * By default this option is disabled (all files will be shown).
- * @param dirsOnly true to list only directories
- */
- virtual void setDirOnlyMode( bool dirsOnly );
-
- /**
- * Returns the top level URL that is listed by this KDirLister.
- * It might be different from the one given with openURL() if there was a
- * redirection. If you called openURL() with @p _keep == true this is the
- * first url opened (e.g. in a treeview this is the root).
- *
- * @return the url used by this instance to list the files.
- */
- const KURL& url() const;
-
- /**
- * Returns all URLs that are listed by this KDirLister. This is only
- * useful if you called openURL() with @p _keep == true, as it happens in a
- * treeview, for example. (Note that the base url is included in the list
- * as well, of course.)
- *
- * @return the list of all listed URLs
- * @since 3.4
- */
- const KURL::List& directories() const;
-
- /**
- * Actually emit the changes made with setShowingDotFiles, setDirOnlyMode,
- * setNameFilter and setMimeFilter.
- */
- virtual void emitChanges();
-
- /**
- * Update the directory @p _dir. This method causes KDirLister to _only_ emit
- * the items of @p _dir that actually changed compared to the current state in the
- * cache and updates the cache.
- *
- * The current implementation calls updateDirectory automatically for
- * local files, using KDirWatch (if autoUpdate() is true), but it might be
- * useful to force an update manually.
- *
- * @param _dir the directory URL
- */
- virtual void updateDirectory( const KURL& _dir );
-
- /**
- * Returns true if no io operation is currently in progress.
- * @return true if finished, false otherwise
- */
- bool isFinished() const;
-
- /**
- * Returns the file item of the URL.
- * @return the file item for url() itself (".")
- */
- KFileItem *rootItem() const;
-
- /**
- * Find an item by its URL.
- * @param _url the item URL
- * @return the pointer to the KFileItem
- */
- virtual KFileItem *findByURL( const KURL& _url ) const;
-#ifndef KDE_NO_COMPAT
- KFileItem *find( const KURL& _url ) const;
-#endif
-
- /**
- * Find an item by its name.
- * @param name the item name
- * @return the pointer to the KFileItem
- */
- virtual KFileItem *findByName( const TQString& name ) const;
-
- /**
- * Set a name filter to only list items matching this name, e.g. "*.cpp".
- *
- * You can set more than one filter by separating them with whitespace, e.g
- * "*.cpp *.h".
- * Note: the direcory is not automatically reloaded.
- *
- * @param filter the new filter, TQString::null to disable filtering
- * @see matchesFilter
- */
- virtual void setNameFilter( const TQString &filter );
-
- /**
- * Returns the current name filter, as set via setNameFilter()
- * @return the current name filter, can be TQString::null if filtering
- * is turned off
- */
- const TQString& nameFilter() const;
-
- /**
- * Set mime-based filter to only list items matching the given mimetypes.
- *
- * NOTE: setting the filter does not automatically reload direcory.
- * Also calling this function will not affect any named filter already set.
- *
- * @param mimeList a list of mime-types.
- *
- * @see clearMimeFilter
- * @see matchesMimeFilter
- */
- virtual void setMimeFilter( const TQStringList &mimeList );
-
- /**
- * Filtering should be done with KFileFilter. This will be implemented in a later
- * revision of KDirLister. This method may be removed then.
- *
- * Set mime-based exclude filter to only list items not matching the given mimetypes
- *
- * NOTE: setting the filter does not automatically reload direcory.
- * Also calling this function will not affect any named filter already set.
- *
- * @param mimeList a list of mime-types.
- * @see clearMimeFilter
- * @see matchesMimeFilter
- * @since 3.1
- * @internal
- */
- void setMimeExcludeFilter(const TQStringList &mimeList );
-
-
- /**
- * Clears the mime based filter.
- *
- * @see setMimeFilter
- */
- virtual void clearMimeFilter();
-
- /**
- * Returns the list of mime based filters, as set via setMimeFilter().
- * @return the list of mime based filters. Empty, when no mime filter is set.
- */
- const TQStringList& mimeFilters() const;
-
- /**
- * Checks whether @p name matches a filter in the list of name filters.
- * @return true if @p name matches a filter in the list,
- * otherwise false.
- * @see setNameFilter
- */
- bool matchesFilter( const TQString& name ) const;
-
- /**
- * Checks whether @p mime matches a filter in the list of mime types
- * @param mime the mimetype to find in the filter list.
- * @return true if @p name matches a filter in the list,
- * otherwise false.
- * @see setMimeFilter.
- */
- bool matchesMimeFilter( const TQString& mime ) const;
-
- /**
- * Pass the main window this object is associated with
- * this is used for caching authentication data
- * @param window the window to associate with, 0 to disassociate
- * @since 3.1
- */
- void setMainWindow( TQWidget *window );
-
- /**
- * Returns the main window associated with this object.
- * @return the associated main window, or 0 if there is none
- * @since 3.1
- */
- TQWidget *mainWindow();
-
- /**
- * Used by items() and itemsForDir() to specify whether you want
- * all items for a directory or just the filtered ones.
- */
- enum WhichItems
- {
- AllItems = 0,
- FilteredItems = 1
- };
-
- /**
- * Returns the items listed for the current url().
- * This method will NOT start listing a directory, you should only call
- * this when receiving the finished() signal.
- *
- * The items in the KFileItemList are references to the items used
- * by KDirLister, so e.g. an item gets destroyed when the deleteItem()
- * signal is emitted.
- *
- * @param which specifies whether the returned list will contain all entries
- * or only the ones that passed the nameFilter(), mimeFilter(),
- * etc. Note that the latter causes iteration over all the
- * items, filtering them. If this is too slow for you, use the
- * newItems() signal, sending out filtered items in chunks.
- * @return the items listed for the current url().
- * @since 3.1
- */
- KFileItemList items( WhichItems which = FilteredItems ) const;
-
- /**
- * Returns the items listed for the given @p dir.
- * This method will NOT start listing @p dir, you should only call
- * this when receiving the finished() signal.
- *
- * The items in the KFileItemList are references to the items used
- * by KDirLister, so e.g. an item gets destroyed when the deleteItem()
- * signal is emitted.
- *
- * @param dir specifies the url for which the items should be returned. This
- * is only useful if you use KDirLister with multiple URLs
- * i.e. using bool keep = true in openURL().
- * @param which specifies whether the returned list will contain all entries
- * or only the ones that passed the nameFilter, mimeFilter, etc.
- * Note that the latter causes iteration over all the items,
- * filtering them. If this is too slow for you, use the
- * newItems() signal, sending out filtered items in chunks.
- * @return the items listed for @p dir.
- * @since 3.1
- */
- KFileItemList itemsForDir( const KURL& dir,
- WhichItems which = FilteredItems ) const;
-
-signals:
- /**
- * Tell the view that we started to list @p _url. NOTE: this does _not_ imply that there
- * is really a job running! I.e. KDirLister::jobs() may return an empty list. In this case
- * the items are taken from the cache.
- *
- * The view knows that openURL should start it, so it might seem useless,
- * but the view also needs to know when an automatic update happens.
- * @param _url the URL to list
- */
- void started( const KURL& _url );
-
- /**
- * Tell the view that listing is finished. There are no jobs running anymore.
- */
- void completed();
-
- /**
- * Tell the view that the listing of the directory @p _url is finished.
- * There might be other running jobs left.
- * @param _url the directory URL
- */
- void completed( const KURL& _url );
-
- /**
- * Tell the view that the user canceled the listing. No running jobs are left.
- */
- void canceled();
-
- /**
- * Tell the view that the listing of the directory @p _url was canceled.
- * There might be other running jobs left.
- * @param _url the directory URL
- */
- void canceled( const KURL& _url );
-
- /**
- * Signal a redirection.
- * Only emitted if there's just one directory to list, i.e. most
- * probably openURL() has been called with @p _keep == @p false.
- * @param _url the new URL
- */
- void redirection( const KURL& _url );
-
- /**
- * Signal a redirection.
- * @param oldUrl the original URL
- * @param newUrl the new URL
- */
- void redirection( const KURL& oldUrl, const KURL& newUrl );
-
- /**
- * Signal to clear all items.
- * It must always be connected to this signal to avoid doubled items!
- */
- void clear();
-
- /**
- * Signal to empty the directory @p _url.
- * It is only emitted if the lister is holding more than one directory.
- * @param _url the directory that will be emptied
- */
- void clear( const KURL& _url );
-
- /**
- * Signal new items.
- * @param items a list of new items
- */
- void newItems( const KFileItemList& items );
-
- /**
- * Send a list of items filtered-out by mime-type.
- * @param items the list of filtered items
- */
- void itemsFilteredByMime( const KFileItemList& items );
-
- /**
- * Signal an item to remove.
- *
- * ATTENTION: if @p _fileItem == rootItem() the directory this lister
- * is holding was deleted and you HAVE to release especially the
- * rootItem() of this lister, otherwise your app will CRASH!!
- * The clear() signals have been emitted already.
- * @param _fileItem the fileItem to delete
- */
- void deleteItem( KFileItem *_fileItem );
-
- /**
- * Signal an item to refresh (its mimetype/icon/name has changed).
- * Note: KFileItem::refresh has already been called on those items.
- * @param items the items to refresh
- */
- void refreshItems( const KFileItemList& items );
-
- /**
- * Emitted to display information about running jobs.
- * Examples of message are "Resolving host", "Connecting to host...", etc.
- * @param msg the info message
- */
- void infoMessage( const TQString& msg );
-
- /**
- * Progress signal showing the overall progress of the KDirLister.
- * This allows using a progress bar very easily. (see KProgress)
- * @param percent the progress in percent
- */
- void percent( int percent );
-
- /**
- * Emitted when we know the size of the jobs.
- * @param size the total size in bytes
- */
- void totalSize( TDEIO::filesize_t size );
-
- /**
- * Regularly emitted to show the progress of this KDirLister.
- * @param size the processed size in bytes
- */
- void processedSize( TDEIO::filesize_t size );
-
- /**
- * Emitted to display information about the speed of the jobs.
- * @param bytes_per_second the speed in bytes/s
- */
- void speed( int bytes_per_second );
-
-protected:
- enum Changes {
- NONE=0, NAME_FILTER=1, MIME_FILTER=2, DOT_FILES=4, DIR_ONLY_MODE=8
- };
-
- /**
- * Called for every new item before emitting newItems().
- * You may reimplement this method in a subclass to implement your own
- * filtering.
- * The default implementation filters out ".." and everything not matching
- * the name filter(s)
- * @return true if the item is "ok".
- * false if the item shall not be shown in a view, e.g.
- * files not matching a pattern *.cpp ( KFileItem::isHidden())
- * @see matchesFilter
- * @see setNameFilter
- */
- virtual bool matchesFilter( const KFileItem * ) const;
-
- /**
- * Called for every new item before emitting newItems().
- * You may reimplement this method in a subclass to implement your own
- * filtering.
- * The default implementation filters out ".." and everything not matching
- * the name filter(s)
- * @return true if the item is "ok".
- * false if the item shall not be shown in a view, e.g.
- * files not matching a pattern *.cpp ( KFileItem::isHidden())
- * @see matchesMimeFilter
- * @see setMimeFilter
- */
- virtual bool matchesMimeFilter( const KFileItem * ) const;
-
- /**
- * Called by the public matchesFilter() to do the
- * actual filtering. Those methods may be reimplemented to customize
- * filtering.
- * @param name the name to filter
- * @param filters a list of regular expressions for filtering
- */
- virtual bool doNameFilter( const TQString& name, const TQPtrList<TQRegExp>& filters ) const;
-
- /**
- * Called by the public matchesMimeFilter() to do the
- * actual filtering. Those methods may be reimplemented to customize
- * filtering.
- * @param mime the mime type to filter
- * @param filters the list of mime types to filter
- */
- virtual bool doMimeFilter( const TQString& mime, const TQStringList& filters ) const;
-
- /**
- * @internal
- */
- bool doMimeExcludeFilter( const TQString& mimeExclude, const TQStringList& filters ) const;
-
- /**
- * Checks if an url is malformed or not and displays an error message
- * if it is and autoErrorHandling is set to true.
- * @return true if url is valid, otherwise false.
- */
- virtual bool validURL( const KURL& ) const;
-
- /** Reimplement to customize error handling */
- virtual void handleError( TDEIO::Job * );
-
-protected:
- virtual void virtual_hook( int id, void *data );
-
-private slots:
- void slotInfoMessage( TDEIO::Job *, const TQString& );
- void slotPercent( TDEIO::Job *, unsigned long );
- void slotTotalSize( TDEIO::Job *, TDEIO::filesize_t );
- void slotProcessedSize( TDEIO::Job *, TDEIO::filesize_t );
- void slotSpeed( TDEIO::Job *, unsigned long );
- void slotLocalURL( TDEIO::Job *, const KURL&, bool );
- void slotLocalURLKIODestroyed( );
-
-private:
- void jobStarted( TDEIO::ListJob * );
- void connectJob( TDEIO::ListJob * );
- void jobDone( TDEIO::ListJob * );
-
- uint numJobs();
-
-private:
- virtual void addNewItem( const KFileItem *item );
- virtual void addNewItems( const KFileItemList& items );
- /*virtual*/ void aboutToRefreshItem( const KFileItem *item ); // TODO: KDE 4.0 make virtual
- virtual void addRefreshItem( const KFileItem *item );
- virtual void emitItems();
- virtual void emitDeleteItem( KFileItem *item );
-
- KDirListerPrivate *d;
-};
-
-#endif
-
diff --git a/kio/kio/kdirlister_p.h b/kio/kio/kdirlister_p.h
deleted file mode 100644
index 47bd4d452..000000000
--- a/kio/kio/kdirlister_p.h
+++ /dev/null
@@ -1,358 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2002 Michael Brade <brade@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef kdirlister_p_h
-#define kdirlister_p_h
-
-#include "kfileitem.h"
-
-#include <tqmap.h>
-#include <tqdict.h>
-#include <tqcache.h>
-#include <tqwidget.h>
-
-#include <kurl.h>
-#include <kio/global.h>
-#include <kdirwatch.h>
-#include <dcopclient.h>
-
-class TQTimer;
-class KDirLister;
-namespace TDEIO { class Job; class ListJob; }
-
-
-class KDirLister::KDirListerPrivate
-{
-public:
- KDirListerPrivate()
- {
- complete = false;
-
- autoUpdate = false;
- isShowingDotFiles = false;
- dirOnlyMode = false;
-
- autoErrorHandling = false;
- errorParent = 0;
-
- delayedMimeTypes = false;
-
- rootFileItem = 0;
- lstNewItems = 0;
- lstRefreshItems = 0;
- lstMimeFilteredItems = 0;
- lstRemoveItems = 0;
- refreshItemWasFiltered = false;
-
- changes = NONE;
-
- window = 0;
-
- lstFilters.setAutoDelete( true );
- oldFilters.setAutoDelete( true );
- }
-
- /**
- * List of dirs handled by this dirlister. The first entry is the base URL.
- * For a tree view, it contains all the dirs shown.
- */
- KURL::List lstDirs;
-
- // toplevel URL
- KURL url;
-
- bool complete;
-
- bool autoUpdate;
- bool isShowingDotFiles;
- bool dirOnlyMode;
-
- bool autoErrorHandling;
- TQWidget *errorParent;
-
- bool delayedMimeTypes;
-
- struct JobData {
- long unsigned int percent, speed;
- TDEIO::filesize_t processedSize, totalSize;
- };
-
- TQMap<TDEIO::ListJob *, JobData> jobData;
-
- // file item for the root itself (".")
- KFileItem *rootFileItem;
-
- KFileItemList *lstNewItems, *lstRefreshItems;
- KFileItemList *lstMimeFilteredItems, *lstRemoveItems;
-
- bool refreshItemWasFiltered;
-
- int changes;
-
- TQWidget *window; // Main window ths lister is associated with
-
- TQString nameFilter;
- TQPtrList<TQRegExp> lstFilters, oldFilters;
- TQStringList mimeFilter, oldMimeFilter;
- TQStringList mimeExcludeFilter, oldMimeExcludeFilter;
-
- bool localURLSlotFired;
- KURL localURLResultURL;
- bool localURLResultIsLocal;
-};
-
-/**
- * Design of the cache:
- * There is a single KDirListerCache for the whole process.
- * It holds all the items used by the dir listers (itemsInUse)
- * as well as a cache of the recently used items (itemsCached).
- * Those items are grouped by directory (a DirItem represents a whole directory).
- *
- * KDirListerCache also runs all the jobs for listing directories, whether they are for
- * normal listing or for updates.
- * For faster lookups, it also stores two dicts:
- * a URL -> dirlister holding that URL (urlsCurrentlyHeld)
- * a URL -> dirlister currently listing that URL (urlsCurrentlyListed)
- */
-class KDirListerCache : public TQObject, KDirNotify
-{
- Q_OBJECT
-public:
- KDirListerCache( int maxCount = 10 );
- ~KDirListerCache();
-
- bool listDir( KDirLister *lister, const KURL& _url, bool _keep, bool _reload );
- bool validURL( const KDirLister *lister, const KURL& _url ) const;
-
- // stop all running jobs for lister
- void stop( KDirLister *lister );
- // stop just the job listing url for lister
- void stop( KDirLister *lister, const KURL &_url );
-
- void setAutoUpdate( KDirLister *lister, bool enable );
-
- void forgetDirs( KDirLister *lister );
- void forgetDirs( KDirLister *lister, const KURL &_url, bool notify );
-
- void updateDirectory( const KURL &_dir );
-
- KFileItemList *itemsForDir( const KURL &_dir ) const;
-
- KFileItem *findByName( const KDirLister *lister, const TQString &_name ) const;
- // if lister is set, it is checked that the url is held by the lister
- KFileItem *findByURL( const KDirLister *lister, const KURL &_url ) const;
-
- /**
- * Notify that files have been added in @p directory
- * The receiver will list that directory again to find
- * the new items (since it needs more than just the names anyway).
- * Reimplemented from KDirNotify.
- */
- virtual void FilesAdded( const KURL &directory );
-
- /**
- * Notify that files have been deleted.
- * This call passes the exact urls of the deleted files
- * so that any view showing them can simply remove them
- * or be closed (if its current dir was deleted)
- * Reimplemented from KDirNotify.
- */
- virtual void FilesRemoved( const KURL::List &fileList );
-
- /**
- * Notify that files have been changed.
- * At the moment, this is only used for new icon, but it could be
- * used for size etc. as well.
- * Note: this is ASYNC so that it can be used with a broadcast
- */
- virtual void FilesChanged( const KURL::List &fileList );
- virtual void FileRenamed( const KURL &src, const KURL &dst );
-
- static KDirListerCache *self();
-
- static bool exists();
-
-private slots:
- void slotFileDirty( const TQString &_file );
- void slotFileCreated( const TQString &_file );
- void slotFileDeleted( const TQString &_file );
-
- void slotFileDirtyDelayed();
-
- void slotEntries( TDEIO::Job *job, const TDEIO::UDSEntryList &entries );
- void slotResult( TDEIO::Job *j );
- void slotRedirection( TDEIO::Job *job, const KURL &url );
-
- void slotUpdateEntries( TDEIO::Job *job, const TDEIO::UDSEntryList &entries );
- void slotUpdateResult( TDEIO::Job *job );
-
-private:
- TDEIO::ListJob *jobForUrl( const TQString& url, TDEIO::ListJob *not_job = 0 );
- const KURL& joburl( TDEIO::ListJob *job );
-
- void killJob( TDEIO::ListJob *job );
-
- // check if _url is held by some lister and return true,
- // otherwise schedule a delayed update and return false
- bool checkUpdate( const TQString& _url );
- // when there were items deleted from the filesystem all the listers holding
- // the parent directory need to be notified, the unmarked items have to be deleted
- // and removed from the cache including all the childs.
- void deleteUnmarkedItems( TQPtrList<KDirLister> *, KFileItemList * );
- void processPendingUpdates();
- // common for slotRedirection and FileRenamed
- void renameDir( const KURL &oldUrl, const KURL &url );
- // common for deleteUnmarkedItems and FilesRemoved
- void deleteDir( const KURL& dirUrl );
- // remove directory from cache (itemsCached), including all child dirs
- void removeDirFromCache( const KURL& dir );
- // helper for renameDir
- void emitRedirections( const KURL &oldUrl, const KURL &url );
-
- void aboutToRefreshItem( KFileItem *fileitem );
- void emitRefreshItem( KFileItem *fileitem );
-
-#ifndef NDEBUG
- void printDebug();
-#endif
-
- struct DirItem
- {
- DirItem( const KURL &dir )
- : url(dir), rootItem(0), lstItems(new KFileItemList)
- {
- autoUpdates = 0;
- complete = false;
- lstItems->setAutoDelete( true );
- }
-
- ~DirItem()
- {
- if ( autoUpdates )
- {
- if ( KDirWatch::exists() && url.isLocalFile() )
- kdirwatch->removeDir( url.path() );
- sendSignal( false, url );
- }
- delete rootItem;
- delete lstItems;
- }
-
- void sendSignal( bool entering, const KURL& url )
- {
- DCOPClient *client = DCOPClient::mainClient();
- if ( !client )
- return;
- TQByteArray data;
- TQDataStream arg( data, IO_WriteOnly );
- arg << url;
- client->emitDCOPSignal( "KDirNotify", entering ? "enteredDirectory(KURL)" : "leftDirectory(KURL)", data );
- }
-
- void redirect( const KURL& newUrl )
- {
- if ( autoUpdates )
- {
- if ( url.isLocalFile() )
- kdirwatch->removeDir( url.path() );
- sendSignal( false, url );
-
- if ( newUrl.isLocalFile() )
- kdirwatch->addDir( newUrl.path() );
- sendSignal( true, newUrl );
- }
-
- url = newUrl;
-
- if ( rootItem )
- rootItem->setURL( newUrl );
- }
-
- void incAutoUpdate()
- {
- if ( autoUpdates++ == 0 )
- {
- if ( url.isLocalFile() )
- kdirwatch->addDir( url.path() );
- sendSignal( true, url );
- }
- }
-
- void decAutoUpdate()
- {
- if ( --autoUpdates == 0 )
- {
- if ( url.isLocalFile() )
- kdirwatch->removeDir( url.path() );
- sendSignal( false, url );
- }
-
- else if ( autoUpdates < 0 )
- autoUpdates = 0;
- }
-
- // number of KDirListers using autoUpdate for this dir
- short autoUpdates;
-
- // this directory is up-to-date
- bool complete;
-
- // the complete url of this directory
- KURL url;
-
- // KFileItem representing the root of this directory.
- // Remember that this is optional. FTP sites don't return '.' in
- // the list, so they give no root item
- KFileItem *rootItem;
- KFileItemList *lstItems;
- };
-
- static const unsigned short MAX_JOBS_PER_LISTER;
- TQMap<TDEIO::ListJob *, TDEIO::UDSEntryList> jobs;
-
- // an item is a complete directory
- TQDict<DirItem> itemsInUse;
- TQCache<DirItem> itemsCached;
-
- // A lister can be EITHER in urlsCurrentlyListed OR urlsCurrentlyHeld but NOT
- // in both at the same time.
- // On the other hand there can be some listers in urlsCurrentlyHeld
- // and some in urlsCurrentlyListed for the same url!
- // Or differently said, there can be an entry for url in urlsCurrentlyListed
- // and urlsCurrentlyHeld. This happens if more listers are requesting url at
- // the same time and one lister was stopped during the listing of files.
-
- // saves all urls that are currently being listed and maps them
- // to their KDirListers
- TQDict< TQPtrList<KDirLister> > urlsCurrentlyListed;
-
- // saves all KDirListers that are just holding url
- TQDict< TQPtrList<KDirLister> > urlsCurrentlyHeld;
-
- // running timers for the delayed update
- TQDict<TQTimer> pendingUpdates;
-
- static KDirListerCache *s_pSelf;
-};
-
-const unsigned short KDirListerCache::MAX_JOBS_PER_LISTER = 5;
-
-#define s_pCache KDirListerCache::self()
-
-#endif
diff --git a/kio/kio/kdirwatch.cpp b/kio/kio/kdirwatch.cpp
deleted file mode 100644
index 1ea5805f3..000000000
--- a/kio/kio/kdirwatch.cpp
+++ /dev/null
@@ -1,1774 +0,0 @@
-// -*- c-basic-offset: 2 -*-
-/* This file is part of the KDE libraries
- Copyright (C) 1998 Sven Radej <sven@lisa.exp.univie.ac.at>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-
-// CHANGES:
-// Oct 4, 2005 - Inotify support (Dirk Mueller)
-// Februar 2002 - Add file watching and remote mount check for STAT
-// Mar 30, 2001 - Native support for Linux dir change notification.
-// Jan 28, 2000 - Usage of FAM service on IRIX (Josef.Weidendorfer@in.tum.de)
-// May 24. 1998 - List of times introduced, and some bugs are fixed. (sven)1
-// May 23. 1998 - Removed static pointer - you can have more instances.
-// It was Needed for KRegistry. KDirWatch now emits signals and doesn't
-// call (or need) KFM. No more URL's - just plain paths. (sven)
-// Mar 29. 1998 - added docs, stop/restart for particular Dirs and
-// deep copies for list of dirs. (sven)
-// Mar 28. 1998 - Created. (sven)
-
-
-#include <config.h>
-#include <errno.h>
-
-#ifdef HAVE_DNOTIFY
-#include <unistd.h>
-#include <time.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <errno.h>
-#endif
-
-
-#include <sys/stat.h>
-#include <assert.h>
-#include <tqdir.h>
-#include <tqfile.h>
-#include <tqintdict.h>
-#include <tqptrlist.h>
-#include <tqsocketnotifier.h>
-#include <tqstringlist.h>
-#include <tqtimer.h>
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kconfig.h>
-#include <kglobal.h>
-#include <kstaticdeleter.h>
-#include <kde_file.h>
-
-// debug
-#include <sys/ioctl.h>
-
-#ifdef HAVE_INOTIFY
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/syscall.h>
-#include <linux/types.h>
-// Linux kernel headers are documented to not compile
-#define _S390_BITOPS_H
-#include <sys/inotify.h>
-
-#ifndef __NR_inotify_init
-#if defined(__i386__)
-#define __NR_inotify_init 291
-#define __NR_inotify_add_watch 292
-#define __NR_inotify_rm_watch 293
-#endif
-#if defined(__PPC__)
-#define __NR_inotify_init 275
-#define __NR_inotify_add_watch 276
-#define __NR_inotify_rm_watch 277
-#endif
-#if defined(__x86_64__)
-#define __NR_inotify_init 253
-#define __NR_inotify_add_watch 254
-#define __NR_inotify_rm_watch 255
-#endif
-#endif
-
-#ifndef IN_ONLYDIR
-#define IN_ONLYDIR 0x01000000
-#endif
-
-#ifndef IN_DONT_FOLLOW
-#define IN_DONT_FOLLOW 0x02000000
-#endif
-
-#ifndef IN_MOVE_SELF
-#define IN_MOVE_SELF 0x00000800
-#endif
-
-#endif
-
-#include <sys/utsname.h>
-
-#include "kdirwatch.h"
-#include "kdirwatch_p.h"
-#include "global.h" // TDEIO::probably_slow_mounted
-
-#define NO_NOTIFY (time_t) 0
-
-static KDirWatchPrivate* dwp_self = 0;
-
-#ifdef HAVE_DNOTIFY
-
-static int dnotify_signal = 0;
-
-/* DNOTIFY signal handler
- *
- * As this is called asynchronously, only a flag is set and
- * a rescan is requested.
- * This is done by writing into a pipe to trigger a TQSocketNotifier
- * watching on this pipe: a timer is started and after a timeout,
- * the rescan is done.
- */
-void KDirWatchPrivate::dnotify_handler(int, siginfo_t *si, void *)
-{
- if (!dwp_self) return;
-
- // write might change errno, we have to save it and restore it
- // (Richard Stevens, Advanced programming in the Unix Environment)
- int saved_errno = errno;
-
- Entry* e = dwp_self->fd_Entry.find(si->si_fd);
-
-// kdDebug(7001) << "DNOTIFY Handler: fd " << si->si_fd << " path "
-// << TQString(e ? e->path:"unknown") << endl;
-
- if(e && e->dn_fd == si->si_fd)
- e->dirty = true;
-
- char c = 0;
- write(dwp_self->mPipe[1], &c, 1);
- errno = saved_errno;
-}
-
-static struct sigaction old_sigio_act;
-/* DNOTIFY SIGIO signal handler
- *
- * When the kernel queue for the dnotify_signal overflows, a SIGIO is send.
- */
-void KDirWatchPrivate::dnotify_sigio_handler(int sig, siginfo_t *si, void *p)
-{
- if (dwp_self)
- {
- // write might change errno, we have to save it and restore it
- // (Richard Stevens, Advanced programming in the Unix Environment)
- int saved_errno = errno;
-
- dwp_self->rescan_all = true;
- char c = 0;
- write(dwp_self->mPipe[1], &c, 1);
-
- errno = saved_errno;
- }
-
- // Call previous signal handler
- if (old_sigio_act.sa_flags & SA_SIGINFO)
- {
- if (old_sigio_act.sa_sigaction)
- (*old_sigio_act.sa_sigaction)(sig, si, p);
- }
- else
- {
- if ((old_sigio_act.sa_handler != SIG_DFL) &&
- (old_sigio_act.sa_handler != SIG_IGN))
- (*old_sigio_act.sa_handler)(sig);
- }
-}
-#endif
-
-
-//
-// Class KDirWatchPrivate (singleton)
-//
-
-/* All entries (files/directories) to be watched in the
- * application (coming from multiple KDirWatch instances)
- * are registered in a single KDirWatchPrivate instance.
- *
- * At the moment, the following methods for file watching
- * are supported:
- * - Polling: All files to be watched are polled regularly
- * using stat (more precise: TQFileInfo.lastModified()).
- * The polling frequency is determined from global kconfig
- * settings, defaulting to 500 ms for local directories
- * and 5000 ms for remote mounts
- * - FAM (File Alternation Monitor): first used on IRIX, SGI
- * has ported this method to LINUX. It uses a kernel part
- * (IMON, sending change events to /dev/imon) and a user
- * level damon (fam), to which applications connect for
- * notification of file changes. For NFS, the fam damon
- * on the NFS server machine is used; if IMON is not built
- * into the kernel, fam uses polling for local files.
- * - DNOTIFY: In late LINUX 2.3.x, directory notification was
- * introduced. By opening a directory, you can request for
- * UNIX signals to be sent to the process when a directory
- * is changed.
- * - INOTIFY: In LINUX 2.6.13, inode change notification was
- * introduced. You're now able to watch arbitrary inode's
- * for changes, and even get notification when they're
- * unmounted.
- */
-
-KDirWatchPrivate::KDirWatchPrivate()
- : rescan_timer(0, "KDirWatchPrivate::rescan_timer")
-{
- timer = new TQTimer(this, "KDirWatchPrivate::timer");
- connect (timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotRescan()));
- freq = 3600000; // 1 hour as upper bound
- statEntries = 0;
- delayRemove = false;
- m_ref = 0;
-
- TDEConfigGroup config(TDEGlobal::config(), TQCString("DirWatch"));
- m_nfsPollInterval = config.readNumEntry("NFSPollInterval", 5000);
- m_PollInterval = config.readNumEntry("PollInterval", 500);
-
- TQString available("Stat");
-
- // used for FAM and DNOTIFY
- rescan_all = false;
- connect(&rescan_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotRescan()));
-
-#ifdef HAVE_FAM
- // It's possible that FAM server can't be started
- if (FAMOpen(&fc) ==0) {
- available += ", FAM";
- use_fam=true;
- sn = new TQSocketNotifier( FAMCONNECTION_GETFD(&fc),
- TQSocketNotifier::Read, this);
- connect( sn, TQT_SIGNAL(activated(int)),
- this, TQT_SLOT(famEventReceived()) );
- }
- else {
- kdDebug(7001) << "Can't use FAM (fam daemon not running?)" << endl;
- use_fam=false;
- }
-#endif
-
-#ifdef HAVE_INOTIFY
- supports_inotify = true;
-
- m_inotify_fd = inotify_init();
-
- if ( m_inotify_fd <= 0 ) {
- kdDebug(7001) << "Can't use Inotify, kernel doesn't support it" << endl;
- supports_inotify = false;
- }
-
- {
- struct utsname uts;
- int major, minor, patch;
- if (uname(&uts) < 0)
- supports_inotify = false; // *shrug*
- else if (sscanf(uts.release, "%d.%d.%d", &major, &minor, &patch) != 3)
- supports_inotify = false; // *shrug*
- else if( major * 1000000 + minor * 1000 + patch < 2006014 ) { // <2.6.14
- kdDebug(7001) << "Can't use INotify, Linux kernel too old" << endl;
- supports_inotify = false;
- }
- }
-
- if ( supports_inotify ) {
- available += ", Inotify";
- fcntl(m_inotify_fd, F_SETFD, FD_CLOEXEC);
-
- mSn = new TQSocketNotifier( m_inotify_fd, TQSocketNotifier::Read, this );
- connect( mSn, TQT_SIGNAL(activated( int )), this, TQT_SLOT( slotActivated() ) );
- }
-#endif
-
-#ifdef HAVE_DNOTIFY
-
- // if we have inotify, disable dnotify.
-#ifdef HAVE_INOTIFY
- supports_dnotify = !supports_inotify;
-#else
- // otherwise, not guilty until proven guilty.
- supports_dnotify = true;
-#endif
-
- struct utsname uts;
- int major, minor, patch;
- if (uname(&uts) < 0)
- supports_dnotify = false; // *shrug*
- else if (sscanf(uts.release, "%d.%d.%d", &major, &minor, &patch) != 3)
- supports_dnotify = false; // *shrug*
- else if( major * 1000000 + minor * 1000 + patch < 2004019 ) { // <2.4.19
- kdDebug(7001) << "Can't use DNotify, Linux kernel too old" << endl;
- supports_dnotify = false;
- }
-
- if( supports_dnotify ) {
- available += ", DNotify";
-
- pipe(mPipe);
- fcntl(mPipe[0], F_SETFD, FD_CLOEXEC);
- fcntl(mPipe[1], F_SETFD, FD_CLOEXEC);
- fcntl(mPipe[0], F_SETFL, O_NONBLOCK | fcntl(mPipe[0], F_GETFL));
- fcntl(mPipe[1], F_SETFL, O_NONBLOCK | fcntl(mPipe[1], F_GETFL));
- mSn = new TQSocketNotifier( mPipe[0], TQSocketNotifier::Read, this);
- connect(mSn, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotActivated()));
- // Install the signal handler only once
- if ( dnotify_signal == 0 )
- {
- dnotify_signal = SIGRTMIN + 8;
-
- struct sigaction act;
- act.sa_sigaction = KDirWatchPrivate::dnotify_handler;
- sigemptyset(&act.sa_mask);
- act.sa_flags = SA_SIGINFO;
-#ifdef SA_RESTART
- act.sa_flags |= SA_RESTART;
-#endif
- sigaction(dnotify_signal, &act, NULL);
-
- act.sa_sigaction = KDirWatchPrivate::dnotify_sigio_handler;
- sigaction(SIGIO, &act, &old_sigio_act);
- }
- }
- else
- {
- mPipe[0] = -1;
- mPipe[1] = -1;
- }
-#endif
-
- kdDebug(7001) << "Available methods: " << available << endl;
-}
-
-/* This is called on app exit (KStaticDeleter) */
-KDirWatchPrivate::~KDirWatchPrivate()
-{
- timer->stop();
-
- /* remove all entries being watched */
- removeEntries(0);
-
-#ifdef HAVE_FAM
- if (use_fam) {
- FAMClose(&fc);
- kdDebug(7001) << "KDirWatch deleted (FAM closed)" << endl;
- }
-#endif
-#ifdef HAVE_INOTIFY
- if ( supports_inotify )
- ::close( m_inotify_fd );
-#endif
-#ifdef HAVE_DNOTIFY
- close(mPipe[0]);
- close(mPipe[1]);
-#endif
-}
-
-#include <stdlib.h>
-
-void KDirWatchPrivate::slotActivated()
-{
-#ifdef HAVE_DNOTIFY
- if ( supports_dnotify )
- {
- char dummy_buf[4096];
- read(mPipe[0], &dummy_buf, 4096);
-
- if (!rescan_timer.isActive())
- rescan_timer.start(m_PollInterval, true /* singleshot */);
-
- return;
- }
-#endif
-
-#ifdef HAVE_INOTIFY
- if ( !supports_inotify )
- return;
-
- int pending = -1;
- int offset = 0;
- char buf[4096];
- assert( m_inotify_fd > -1 );
- ioctl( m_inotify_fd, FIONREAD, &pending );
-
- while ( pending > 0 ) {
-
- if ( pending > (int)sizeof( buf ) )
- pending = sizeof( buf );
-
- pending = read( m_inotify_fd, buf, pending);
-
- while ( pending > 0 ) {
- struct inotify_event *event = (struct inotify_event *) &buf[offset];
- pending -= sizeof( struct inotify_event ) + event->len;
- offset += sizeof( struct inotify_event ) + event->len;
-
- TQString path;
- if ( event->len )
- path = TQFile::decodeName( TQCString( event->name, event->len ) );
-
- if ( path.length() && isNoisyFile( path.latin1() ) )
- continue;
-
- kdDebug(7001) << "ev wd: " << event->wd << " mask " << event->mask << " path: " << path << endl;
-
- // now we're in deep trouble of finding the
- // associated entries
- // for now, we suck and iterate
- for ( EntryMap::Iterator it = m_mapEntries.begin();
- it != m_mapEntries.end(); ++it ) {
- Entry* e = &( *it );
- if ( e->wd == event->wd ) {
- e->dirty = true;
-
- if ( 1 || e->isDir) {
- if( event->mask & IN_DELETE_SELF) {
- kdDebug(7001) << "-->got deleteself signal for " << e->path << endl;
- e->m_status = NonExistent;
- if (e->isDir)
- addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
- else
- addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
- }
- if ( event->mask & IN_IGNORED ) {
- e->wd = 0;
- }
- if ( event->mask & (IN_CREATE|IN_MOVED_TO) ) {
- Entry *sub_entry = e->m_entries.first();
- for(;sub_entry; sub_entry = e->m_entries.next())
- if (sub_entry->path == e->path + "/" + path) break;
-
- if (sub_entry /*&& sub_entry->isDir*/) {
- removeEntry(0,e->path, sub_entry);
- KDE_struct_stat stat_buf;
- TQCString tpath = TQFile::encodeName(path);
- KDE_stat(tpath, &stat_buf);
-
- //sub_entry->isDir = S_ISDIR(stat_buf.st_mode);
- //sub_entry->m_ctime = stat_buf.st_ctime;
- //sub_entry->m_status = Normal;
- //sub_entry->m_nlink = stat_buf.st_nlink;
-
- if(!useINotify(sub_entry))
- useStat(sub_entry);
- sub_entry->dirty = true;
- }
- }
- }
-
- if (!rescan_timer.isActive())
- rescan_timer.start(m_PollInterval, true /* singleshot */);
-
- break; // there really should be only one matching wd
- }
- }
-
- }
- }
-#endif
-}
-
-/* In DNOTIFY/FAM mode, only entries which are marked dirty are scanned.
- * We first need to mark all yet nonexistent, but possible created
- * entries as dirty...
- */
-void KDirWatchPrivate::Entry::propagate_dirty()
-{
- for (TQPtrListIterator<Entry> sub_entry (m_entries);
- sub_entry.current(); ++sub_entry)
- {
- if (!sub_entry.current()->dirty)
- {
- sub_entry.current()->dirty = true;
- sub_entry.current()->propagate_dirty();
- }
- }
-}
-
-
-/* A KDirWatch instance is interested in getting events for
- * this file/Dir entry.
- */
-void KDirWatchPrivate::Entry::addClient(KDirWatch* instance)
-{
- Client* client = m_clients.first();
- for(;client; client = m_clients.next())
- if (client->instance == instance) break;
-
- if (client) {
- client->count++;
- return;
- }
-
- client = new Client;
- client->instance = instance;
- client->count = 1;
- client->watchingStopped = instance->isStopped();
- client->pending = NoChange;
-
- m_clients.append(client);
-}
-
-void KDirWatchPrivate::Entry::removeClient(KDirWatch* instance)
-{
- Client* client = m_clients.first();
- for(;client; client = m_clients.next())
- if (client->instance == instance) break;
-
- if (client) {
- client->count--;
- if (client->count == 0) {
- m_clients.removeRef(client);
- delete client;
- }
- }
-}
-
-/* get number of clients */
-int KDirWatchPrivate::Entry::clients()
-{
- int clients = 0;
- Client* client = m_clients.first();
- for(;client; client = m_clients.next())
- clients += client->count;
-
- return clients;
-}
-
-
-KDirWatchPrivate::Entry* KDirWatchPrivate::entry(const TQString& _path)
-{
-// we only support absolute paths
- if (TQDir::isRelativePath(_path)) {
- return 0;
- }
-
- TQString path = _path;
-
- if ( path.length() > 1 && path.right(1) == "/" )
- path.truncate( path.length() - 1 );
-
- EntryMap::Iterator it = m_mapEntries.find( path );
- if ( it == m_mapEntries.end() )
- return 0;
- else
- return &(*it);
-}
-
-// set polling frequency for a entry and adjust global freq if needed
-void KDirWatchPrivate::useFreq(Entry* e, int newFreq)
-{
- e->freq = newFreq;
-
- // a reasonable frequency for the global polling timer
- if (e->freq < freq) {
- freq = e->freq;
- if (timer->isActive()) timer->changeInterval(freq);
- kdDebug(7001) << "Global Poll Freq is now " << freq << " msec" << endl;
- }
-}
-
-
-#ifdef HAVE_FAM
-// setup FAM notification, returns false if not possible
-bool KDirWatchPrivate::useFAM(Entry* e)
-{
- if (!use_fam) return false;
-
- // handle FAM events to avoid deadlock
- // (FAM sends back all files in a directory when monitoring)
- famEventReceived();
-
- e->m_mode = FAMMode;
- e->dirty = false;
-
- if (e->isDir) {
- if (e->m_status == NonExistent) {
- // If the directory does not exist we watch the parent directory
- addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
- }
- else {
- int res =FAMMonitorDirectory(&fc, TQFile::encodeName(e->path),
- &(e->fr), e);
- if (res<0) {
- e->m_mode = UnknownMode;
- use_fam=false;
- return false;
- }
- kdDebug(7001) << " Setup FAM (Req "
- << FAMREQUEST_GETREQNUM(&(e->fr))
- << ") for " << e->path << endl;
- }
- }
- else {
- if (e->m_status == NonExistent) {
- // If the file does not exist we watch the directory
- addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
- }
- else {
- int res = FAMMonitorFile(&fc, TQFile::encodeName(e->path),
- &(e->fr), e);
- if (res<0) {
- e->m_mode = UnknownMode;
- use_fam=false;
- return false;
- }
-
- kdDebug(7001) << " Setup FAM (Req "
- << FAMREQUEST_GETREQNUM(&(e->fr))
- << ") for " << e->path << endl;
- }
- }
-
- // handle FAM events to avoid deadlock
- // (FAM sends back all files in a directory when monitoring)
- famEventReceived();
-
- return true;
-}
-#endif
-
-
-#ifdef HAVE_DNOTIFY
-// setup DNotify notification, returns false if not possible
-bool KDirWatchPrivate::useDNotify(Entry* e)
-{
- e->dn_fd = 0;
- e->dirty = false;
- if (!supports_dnotify) return false;
-
- e->m_mode = DNotifyMode;
-
- if (e->isDir) {
- if (e->m_status == Normal) {
- int fd = KDE_open(TQFile::encodeName(e->path).data(), O_RDONLY);
- // Migrate fd to somewhere above 128. Some libraries have
- // constructs like:
- // fd = socket(...)
- // if (fd > ARBITRARY_LIMIT)
- // return error;
- //
- // Since programs might end up using a lot of KDirWatch objects
- // for a rather long time the above braindamage could get
- // triggered.
- //
- // By moving the kdirwatch fd's to > 128, calls like socket() will keep
- // returning fd's < ARBITRARY_LIMIT for a bit longer.
- int fd2 = fcntl(fd, F_DUPFD, 128);
- if (fd2 >= 0)
- {
- close(fd);
- fd = fd2;
- }
- if (fd<0) {
- e->m_mode = UnknownMode;
- return false;
- }
-
- int mask = DN_DELETE|DN_CREATE|DN_RENAME|DN_MULTISHOT;
- // if dependant is a file watch, we check for MODIFY & ATTRIB too
- for(Entry* dep=e->m_entries.first();dep;dep=e->m_entries.next())
- if (!dep->isDir) { mask |= DN_MODIFY|DN_ATTRIB; break; }
-
- if(fcntl(fd, F_SETSIG, dnotify_signal) < 0 ||
- fcntl(fd, F_NOTIFY, mask) < 0) {
-
- kdDebug(7001) << "Not using Linux Directory Notifications."
- << endl;
- supports_dnotify = false;
- ::close(fd);
- e->m_mode = UnknownMode;
- return false;
- }
-
- fd_Entry.replace(fd, e);
- e->dn_fd = fd;
-
- kdDebug(7001) << " Setup DNotify (fd " << fd
- << ") for " << e->path << endl;
- }
- else { // NotExisting
- addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
- }
- }
- else { // File
- // we always watch the directory (DNOTIFY can't watch files alone)
- // this notifies us about changes of files therein
- addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
- }
-
- return true;
-}
-#endif
-
-#ifdef HAVE_INOTIFY
-// setup INotify notification, returns false if not possible
-bool KDirWatchPrivate::useINotify( Entry* e )
-{
- e->wd = 0;
- e->dirty = false;
- if (!supports_inotify) return false;
-
- e->m_mode = INotifyMode;
-
- int mask = IN_DELETE|IN_DELETE_SELF|IN_CREATE|IN_MOVE|IN_MOVE_SELF|IN_DONT_FOLLOW;
- if(!e->isDir)
- mask |= IN_MODIFY|IN_ATTRIB;
- else
- mask |= IN_ONLYDIR;
-
- // if dependant is a file watch, we check for MODIFY & ATTRIB too
- for(Entry* dep=e->m_entries.first();dep;dep=e->m_entries.next()) {
- if (!dep->isDir) { mask |= IN_MODIFY|IN_ATTRIB; break; }
- }
-
- if ( ( e->wd = inotify_add_watch( m_inotify_fd,
- TQFile::encodeName( e->path ), mask) ) > 0 )
- return true;
-
- if ( e->m_status == NonExistent ) {
- if (e->isDir)
- addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
- else
- addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
- return true;
- }
-
- return false;
-}
-#endif
-
-bool KDirWatchPrivate::useStat(Entry* e)
-{
- if ( e->path.startsWith("/media/") || (e->path == "/media")
- || (TDEIO::probably_slow_mounted(e->path)) )
- useFreq(e, m_nfsPollInterval);
- else
- useFreq(e, m_PollInterval);
-
- if (e->m_mode != StatMode) {
- e->m_mode = StatMode;
- statEntries++;
-
- if ( statEntries == 1 ) {
- // if this was first STAT entry (=timer was stopped)
- timer->start(freq); // then start the timer
- kdDebug(7001) << " Started Polling Timer, freq " << freq << endl;
- }
- }
-
- kdDebug(7001) << " Setup Stat (freq " << e->freq
- << ") for " << e->path << endl;
-
- return true;
-}
-
-
-/* If <instance> !=0, this KDirWatch instance wants to watch at <_path>,
- * providing in <isDir> the type of the entry to be watched.
- * Sometimes, entries are dependant on each other: if <sub_entry> !=0,
- * this entry needs another entry to watch himself (when notExistent).
- */
-void KDirWatchPrivate::addEntry(KDirWatch* instance, const TQString& _path,
- Entry* sub_entry, bool isDir)
-{
- TQString path = _path;
- if (path.startsWith("/dev/") || (path == "/dev"))
- return; // Don't even go there.
-
- if ( path.length() > 1 && path.right(1) == "/" )
- path.truncate( path.length() - 1 );
-
- EntryMap::Iterator it = m_mapEntries.find( path );
- if ( it != m_mapEntries.end() )
- {
- if (sub_entry) {
- (*it).m_entries.append(sub_entry);
- kdDebug(7001) << "Added already watched Entry " << path
- << " (for " << sub_entry->path << ")" << endl;
-
-#ifdef HAVE_DNOTIFY
- {
- Entry* e = &(*it);
- if( (e->m_mode == DNotifyMode) && (e->dn_fd > 0) ) {
- int mask = DN_DELETE|DN_CREATE|DN_RENAME|DN_MULTISHOT;
- // if dependant is a file watch, we check for MODIFY & ATTRIB too
- for(Entry* dep=e->m_entries.first();dep;dep=e->m_entries.next())
- if (!dep->isDir) { mask |= DN_MODIFY|DN_ATTRIB; break; }
- if( fcntl(e->dn_fd, F_NOTIFY, mask) < 0) { // shouldn't happen
- ::close(e->dn_fd);
- e->m_mode = UnknownMode;
- fd_Entry.remove(e->dn_fd);
- e->dn_fd = 0;
- useStat( e );
- }
- }
- }
-#endif
-
-#ifdef HAVE_INOTIFY
- {
- Entry* e = &(*it);
- if( (e->m_mode == INotifyMode) && (e->wd > 0) ) {
- int mask = IN_DELETE|IN_DELETE_SELF|IN_CREATE|IN_MOVE|IN_MOVE_SELF|IN_DONT_FOLLOW;
- if(!e->isDir)
- mask |= IN_MODIFY|IN_ATTRIB;
- else
- mask |= IN_ONLYDIR;
-
- inotify_rm_watch (m_inotify_fd, e->wd);
- e->wd = inotify_add_watch( m_inotify_fd, TQFile::encodeName( e->path ), mask);
- }
- }
-#endif
-
- }
- else {
- (*it).addClient(instance);
- kdDebug(7001) << "Added already watched Entry " << path
- << " (now " << (*it).clients() << " clients)"
- << TQString(TQString(" [%1]").arg(instance->name())) << endl;
- }
- return;
- }
-
- // we have a new path to watch
-
- KDE_struct_stat stat_buf;
- TQCString tpath = TQFile::encodeName(path);
- bool exists = (KDE_stat(tpath, &stat_buf) == 0);
-
- Entry newEntry;
- m_mapEntries.insert( path, newEntry );
- // the insert does a copy, so we have to use <e> now
- Entry* e = &(m_mapEntries[path]);
-
- if (exists) {
- e->isDir = S_ISDIR(stat_buf.st_mode);
-
- if (e->isDir && !isDir)
- kdWarning() << "KDirWatch: " << path << " is a directory. Use addDir!" << endl;
- else if (!e->isDir && isDir)
- kdWarning() << "KDirWatch: " << path << " is a file. Use addFile!" << endl;
-
- e->m_ctime = stat_buf.st_ctime;
- e->m_status = Normal;
- e->m_nlink = stat_buf.st_nlink;
- }
- else {
- e->isDir = isDir;
- e->m_ctime = invalid_ctime;
- e->m_status = NonExistent;
- e->m_nlink = 0;
- }
-
- e->path = path;
- if (sub_entry)
- e->m_entries.append(sub_entry);
- else
- e->addClient(instance);
-
- kdDebug(7001) << "Added " << (e->isDir ? "Dir ":"File ") << path
- << (e->m_status == NonExistent ? " NotExisting" : "")
- << (sub_entry ? TQString(TQString(" for %1").arg(sub_entry->path)) : TQString(""))
- << (instance ? TQString(TQString(" [%1]").arg(instance->name())) : TQString(""))
- << endl;
-
-
- // now setup the notification method
- e->m_mode = UnknownMode;
- e->msecLeft = 0;
-
- if ( isNoisyFile( tpath ) )
- return;
-
-#ifdef HAVE_FAM
- if (useFAM(e)) return;
-#endif
-
-#ifdef HAVE_INOTIFY
- if (useINotify(e)) return;
-#endif
-
-#ifdef HAVE_DNOTIFY
- if (useDNotify(e)) return;
-#endif
-
- useStat(e);
-}
-
-
-void KDirWatchPrivate::removeEntry( KDirWatch* instance,
- const TQString& _path, Entry* sub_entry )
-{
- kdDebug(7001) << "KDirWatchPrivate::removeEntry for '" << _path << "' sub_entry: " << sub_entry << endl;
- Entry* e = entry(_path);
- if (!e) {
- kdDebug(7001) << "KDirWatchPrivate::removeEntry can't handle '" << _path << "'" << endl;
- return;
- }
-
- if (sub_entry)
- e->m_entries.removeRef(sub_entry);
- else
- e->removeClient(instance);
-
- if (e->m_clients.count() || e->m_entries.count()) {
- kdDebug(7001) << "removeEntry: unwatched " << e->path << " " << _path << endl;
- return;
- }
-
- if (delayRemove) {
- // removeList is allowed to contain any entry at most once
- if (removeList.findRef(e)==-1)
- removeList.append(e);
- // now e->isValid() is false
- return;
- }
-
-#ifdef HAVE_FAM
- if (e->m_mode == FAMMode) {
- if ( e->m_status == Normal) {
- FAMCancelMonitor(&fc, &(e->fr) );
- kdDebug(7001) << "Cancelled FAM (Req "
- << FAMREQUEST_GETREQNUM(&(e->fr))
- << ") for " << e->path << endl;
- }
- else {
- if (e->isDir)
- removeEntry(0, TQDir::cleanDirPath(e->path+"/.."), e);
- else
- removeEntry(0, TQFileInfo(e->path).dirPath(true), e);
- }
- }
-#endif
-
-#ifdef HAVE_INOTIFY
- kdDebug(7001) << "inotify remove " << ( e->m_mode == INotifyMode ) << " " << ( e->m_status == Normal ) << endl;
- if (e->m_mode == INotifyMode) {
- if ( e->m_status == Normal ) {
- (void) inotify_rm_watch( m_inotify_fd, e->wd );
- kdDebug(7001) << "Cancelled INotify (fd " <<
- m_inotify_fd << ", " << e->wd <<
- ") for " << e->path << endl;
- }
- else {
- if (e->isDir)
- removeEntry(0, TQDir::cleanDirPath(e->path+"/.."), e);
- else
- removeEntry(0, TQFileInfo(e->path).dirPath(true), e);
- }
- }
-#endif
-
-#ifdef HAVE_DNOTIFY
- if (e->m_mode == DNotifyMode) {
- if (!e->isDir) {
- removeEntry(0, TQFileInfo(e->path).dirPath(true), e);
- }
- else { // isDir
- // must close the FD.
- if ( e->m_status == Normal) {
- if (e->dn_fd) {
- ::close(e->dn_fd);
- fd_Entry.remove(e->dn_fd);
-
- kdDebug(7001) << "Cancelled DNotify (fd " << e->dn_fd
- << ") for " << e->path << endl;
- e->dn_fd = 0;
-
- }
- }
- else {
- removeEntry(0, TQDir::cleanDirPath(e->path+"/.."), e);
- }
- }
- }
-#endif
-
- if (e->m_mode == StatMode) {
- statEntries--;
- if ( statEntries == 0 ) {
- timer->stop(); // stop timer if lists are empty
- kdDebug(7001) << " Stopped Polling Timer" << endl;
- }
- }
-
- kdDebug(7001) << "Removed " << (e->isDir ? "Dir ":"File ") << e->path
- << (sub_entry ? TQString(TQString(" for %1").arg(sub_entry->path)) : TQString(""))
- << (instance ? TQString(TQString(" [%1]").arg(instance->name())) : TQString(""))
- << endl;
- m_mapEntries.remove( e->path ); // <e> not valid any more
-}
-
-
-/* Called from KDirWatch destructor:
- * remove <instance> as client from all entries
- */
-void KDirWatchPrivate::removeEntries( KDirWatch* instance )
-{
- TQPtrList<Entry> list;
- int minfreq = 3600000;
-
- // put all entries where instance is a client in list
- EntryMap::Iterator it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it ) {
- Client* c = (*it).m_clients.first();
- for(;c;c=(*it).m_clients.next())
- if (c->instance == instance) break;
- if (c) {
- c->count = 1; // forces deletion of instance as client
- list.append(&(*it));
- }
- else if ( (*it).m_mode == StatMode && (*it).freq < minfreq )
- minfreq = (*it).freq;
- }
-
- for(Entry* e=list.first();e;e=list.next())
- removeEntry(instance, e->path, 0);
-
- if (minfreq > freq) {
- // we can decrease the global polling frequency
- freq = minfreq;
- if (timer->isActive()) timer->changeInterval(freq);
- kdDebug(7001) << "Poll Freq now " << freq << " msec" << endl;
- }
-}
-
-// instance ==0: stop scanning for all instances
-bool KDirWatchPrivate::stopEntryScan( KDirWatch* instance, Entry* e)
-{
- int stillWatching = 0;
- Client* c = e->m_clients.first();
- for(;c;c=e->m_clients.next()) {
- if (!instance || instance == c->instance)
- c->watchingStopped = true;
- else if (!c->watchingStopped)
- stillWatching += c->count;
- }
-
- kdDebug(7001) << instance->name() << " stopped scanning " << e->path
- << " (now " << stillWatching << " watchers)" << endl;
-
- if (stillWatching == 0) {
- // if nobody is interested, we don't watch
- e->m_ctime = invalid_ctime; // invalid
- e->m_status = NonExistent;
- // e->m_status = Normal;
- }
- return true;
-}
-
-// instance ==0: start scanning for all instances
-bool KDirWatchPrivate::restartEntryScan( KDirWatch* instance, Entry* e,
- bool notify)
-{
- int wasWatching = 0, newWatching = 0;
- Client* c = e->m_clients.first();
- for(;c;c=e->m_clients.next()) {
- if (!c->watchingStopped)
- wasWatching += c->count;
- else if (!instance || instance == c->instance) {
- c->watchingStopped = false;
- newWatching += c->count;
- }
- }
- if (newWatching == 0)
- return false;
-
- kdDebug(7001) << (instance ? instance->name() : "all") << " restarted scanning " << e->path
- << " (now " << wasWatching+newWatching << " watchers)" << endl;
-
- // restart watching and emit pending events
-
- int ev = NoChange;
- if (wasWatching == 0) {
- if (!notify) {
- KDE_struct_stat stat_buf;
- bool exists = (KDE_stat(TQFile::encodeName(e->path), &stat_buf) == 0);
- if (exists) {
- e->m_ctime = stat_buf.st_ctime;
- e->m_status = Normal;
- e->m_nlink = stat_buf.st_nlink;
- }
- else {
- e->m_ctime = invalid_ctime;
- e->m_status = NonExistent;
- e->m_nlink = 0;
- }
- }
- e->msecLeft = 0;
- ev = scanEntry(e);
- }
- emitEvent(e,ev);
-
- return true;
-}
-
-// instance ==0: stop scanning for all instances
-void KDirWatchPrivate::stopScan(KDirWatch* instance)
-{
- EntryMap::Iterator it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it )
- stopEntryScan(instance, &(*it));
-}
-
-
-void KDirWatchPrivate::startScan(KDirWatch* instance,
- bool notify, bool skippedToo )
-{
- if (!notify)
- resetList(instance,skippedToo);
-
- EntryMap::Iterator it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it )
- restartEntryScan(instance, &(*it), notify);
-
- // timer should still be running when in polling mode
-}
-
-
-// clear all pending events, also from stopped
-void KDirWatchPrivate::resetList( KDirWatch* /*instance*/,
- bool skippedToo )
-{
- EntryMap::Iterator it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it ) {
-
- Client* c = (*it).m_clients.first();
- for(;c;c=(*it).m_clients.next())
- if (!c->watchingStopped || skippedToo)
- c->pending = NoChange;
- }
-}
-
-// Return event happened on <e>
-//
-int KDirWatchPrivate::scanEntry(Entry* e)
-{
-#ifdef HAVE_FAM
- if (e->m_mode == FAMMode) {
- // we know nothing has changed, no need to stat
- if(!e->dirty) return NoChange;
- e->dirty = false;
- }
- if (e->isDir) return Changed;
-#endif
-
- // Shouldn't happen: Ignore "unknown" notification method
- if (e->m_mode == UnknownMode) return NoChange;
-
-#if defined ( HAVE_DNOTIFY ) || defined( HAVE_INOTIFY )
- if (e->m_mode == DNotifyMode || e->m_mode == INotifyMode ) {
- // we know nothing has changed, no need to stat
- if(!e->dirty) return NoChange;
- kdDebug(7001) << "scanning " << e->path << " " << e->m_status << " " << e->m_ctime << endl;
- e->dirty = false;
- }
-#endif
-
- if (e->m_mode == StatMode) {
- // only scan if timeout on entry timer happens;
- // e.g. when using 500msec global timer, a entry
- // with freq=5000 is only watched every 10th time
-
- e->msecLeft -= freq;
- if (e->msecLeft>0) return NoChange;
- e->msecLeft += e->freq;
- }
-
- KDE_struct_stat stat_buf;
- bool exists = (KDE_stat(TQFile::encodeName(e->path), &stat_buf) == 0);
- if (exists) {
-
- if (e->m_status == NonExistent) {
- // ctime is the 'creation time' on windows, but with qMax
- // we get the latest change of any kind, on any platform.
- e->m_ctime = stat_buf.st_ctime;
- e->m_status = Normal;
- e->m_nlink = stat_buf.st_nlink;
- return Created;
- }
-
- if ( (e->m_ctime != invalid_ctime) &&
- ((stat_buf.st_ctime != e->m_ctime) ||
- (stat_buf.st_nlink != (nlink_t) e->m_nlink)) ) {
- e->m_ctime = stat_buf.st_ctime;
- e->m_nlink = stat_buf.st_nlink;
- return Changed;
- }
-
- return NoChange;
- }
-
- // dir/file doesn't exist
-
- if (e->m_ctime == invalid_ctime && e->m_status == NonExistent) {
- e->m_nlink = 0;
- e->m_status = NonExistent;
- return NoChange;
- }
-
- e->m_ctime = invalid_ctime;
- e->m_nlink = 0;
- e->m_status = NonExistent;
-
- return Deleted;
-}
-
-/* Notify all interested KDirWatch instances about a given event on an entry
- * and stored pending events. When watching is stopped, the event is
- * added to the pending events.
- */
-void KDirWatchPrivate::emitEvent(Entry* e, int event, const TQString &fileName)
-{
- TQString path = e->path;
- if (!fileName.isEmpty()) {
- if (!TQDir::isRelativePath(fileName))
- path = fileName;
- else
-#ifdef Q_OS_UNIX
- path += "/" + fileName;
-#elif defined(Q_WS_WIN)
- //current drive is passed instead of /
- path += TQDir::currentDirPath().left(2) + "/" + fileName;
-#endif
- }
-
- TQPtrListIterator<Client> cit( e->m_clients );
- for ( ; cit.current(); ++cit )
- {
- Client* c = cit.current();
-
- if (c->instance==0 || c->count==0) continue;
-
- if (c->watchingStopped) {
- // add event to pending...
- if (event == Changed)
- c->pending |= event;
- else if (event == Created || event == Deleted)
- c->pending = event;
- continue;
- }
- // not stopped
- if (event == NoChange || event == Changed)
- event |= c->pending;
- c->pending = NoChange;
- if (event == NoChange) continue;
-
- if (event & Deleted) {
- c->instance->setDeleted(path);
- // emit only Deleted event...
- continue;
- }
-
- if (event & Created) {
- c->instance->setCreated(path);
- // possible emit Change event after creation
- }
-
- if (event & Changed)
- c->instance->setDirty(path);
- }
-}
-
-// Remove entries which were marked to be removed
-void KDirWatchPrivate::slotRemoveDelayed()
-{
- Entry* e;
- delayRemove = false;
- for(e=removeList.first();e;e=removeList.next())
- removeEntry(0, e->path, 0);
- removeList.clear();
-}
-
-/* Scan all entries to be watched for changes. This is done regularly
- * when polling and once after a DNOTIFY signal. This is NOT used by FAM.
- */
-void KDirWatchPrivate::slotRescan()
-{
- EntryMap::Iterator it;
-
- // People can do very long things in the slot connected to dirty(),
- // like showing a message box. We don't want to keep polling during
- // that time, otherwise the value of 'delayRemove' will be reset.
- bool timerRunning = timer->isActive();
- if ( timerRunning )
- timer->stop();
-
- // We delay deletions of entries this way.
- // removeDir(), when called in slotDirty(), can cause a crash otherwise
- delayRemove = true;
-
-#if defined(HAVE_DNOTIFY) || defined(HAVE_INOTIFY)
- TQPtrList<Entry> dList, cList;
-#endif
-
- if (rescan_all)
- {
- // mark all as dirty
- it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it )
- (*it).dirty = true;
- rescan_all = false;
- }
- else
- {
- // progate dirty flag to dependant entries (e.g. file watches)
- it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it )
- if (((*it).m_mode == INotifyMode || (*it).m_mode == DNotifyMode) && (*it).dirty )
- (*it).propagate_dirty();
- }
-
- it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it ) {
- // we don't check invalid entries (i.e. remove delayed)
- if (!(*it).isValid()) continue;
-
- int ev = scanEntry( &(*it) );
-
-
-#ifdef HAVE_INOTIFY
- if ((*it).m_mode == INotifyMode && ev == Created && (*it).wd == 0) {
- cList.append( &(*it) );
- if (! useINotify( &(*it) )) {
- useStat( &(*it) );
- }
- }
-#endif
-
-#ifdef HAVE_DNOTIFY
- if ((*it).m_mode == DNotifyMode) {
- if ((*it).isDir && (ev == Deleted)) {
- dList.append( &(*it) );
-
- // must close the FD.
- if ((*it).dn_fd) {
- ::close((*it).dn_fd);
- fd_Entry.remove((*it).dn_fd);
- (*it).dn_fd = 0;
- }
- }
-
- else if ((*it).isDir && (ev == Created)) {
- // For created, but yet without DNOTIFYing ...
- if ( (*it).dn_fd == 0) {
- cList.append( &(*it) );
- if (! useDNotify( &(*it) )) {
- // if DNotify setup fails...
- useStat( &(*it) );
- }
- }
- }
- }
-#endif
-
- if ( ev != NoChange )
- emitEvent( &(*it), ev);
- }
-
-
-#if defined(HAVE_DNOTIFY) || defined(HAVE_INOTIFY)
- // Scan parent of deleted directories for new creation
- Entry* e;
- for(e=dList.first();e;e=dList.next())
- addEntry(0, TQDir::cleanDirPath( e->path+"/.."), e, true);
-
- // Remove watch of parent of new created directories
- for(e=cList.first();e;e=cList.next())
- removeEntry(0, TQDir::cleanDirPath( e->path+"/.."), e);
-#endif
-
- if ( timerRunning )
- timer->start(freq);
-
- TQTimer::singleShot(0, this, TQT_SLOT(slotRemoveDelayed()));
-}
-
-bool KDirWatchPrivate::isNoisyFile( const char * filename )
-{
- // $HOME/.X.err grows with debug output, so don't notify change
- if ( *filename == '.') {
- if (strncmp(filename, ".X.err", 6) == 0) return true;
- if (strncmp(filename, ".xsession-errors", 16) == 0) return true;
- // fontconfig updates the cache on every KDE app start
- // (inclusive kio_thumbnail slaves)
- if (strncmp(filename, ".fonts.cache", 12) == 0) return true;
- }
-
- return false;
-}
-
-#ifdef HAVE_FAM
-void KDirWatchPrivate::famEventReceived()
-{
- static FAMEvent fe;
-
- delayRemove = true;
-
- while(use_fam && FAMPending(&fc)) {
- if (FAMNextEvent(&fc, &fe) == -1) {
- kdWarning(7001) << "FAM connection problem, switching to polling."
- << endl;
- use_fam = false;
- delete sn; sn = 0;
-
- // Replace all FAMMode entries with DNotify/Stat
- EntryMap::Iterator it;
- it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it )
- if ((*it).m_mode == FAMMode && (*it).m_clients.count()>0) {
-#ifdef HAVE_INOTIFY
- if (useINotify( &(*it) )) continue;
-#endif
-#ifdef HAVE_DNOTIFY
- if (useDNotify( &(*it) )) continue;
-#endif
- useStat( &(*it) );
- }
- }
- else
- checkFAMEvent(&fe);
- }
-
- TQTimer::singleShot(0, this, TQT_SLOT(slotRemoveDelayed()));
-}
-
-void KDirWatchPrivate::checkFAMEvent(FAMEvent* fe)
-{
- // Don't be too verbose ;-)
- if ((fe->code == FAMExists) ||
- (fe->code == FAMEndExist) ||
- (fe->code == FAMAcknowledge)) return;
-
- if ( isNoisyFile( fe->filename ) )
- return;
-
- Entry* e = 0;
- EntryMap::Iterator it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it )
- if (FAMREQUEST_GETREQNUM(&( (*it).fr )) ==
- FAMREQUEST_GETREQNUM(&(fe->fr)) ) {
- e = &(*it);
- break;
- }
-
- // Entry* e = static_cast<Entry*>(fe->userdata);
-
-#if 0 // #88538
- kdDebug(7001) << "Processing FAM event ("
- << ((fe->code == FAMChanged) ? "FAMChanged" :
- (fe->code == FAMDeleted) ? "FAMDeleted" :
- (fe->code == FAMStartExecuting) ? "FAMStartExecuting" :
- (fe->code == FAMStopExecuting) ? "FAMStopExecuting" :
- (fe->code == FAMCreated) ? "FAMCreated" :
- (fe->code == FAMMoved) ? "FAMMoved" :
- (fe->code == FAMAcknowledge) ? "FAMAcknowledge" :
- (fe->code == FAMExists) ? "FAMExists" :
- (fe->code == FAMEndExist) ? "FAMEndExist" : "Unknown Code")
- << ", " << fe->filename
- << ", Req " << FAMREQUEST_GETREQNUM(&(fe->fr))
- << ")" << endl;
-#endif
-
- if (!e) {
- // this happens e.g. for FAMAcknowledge after deleting a dir...
- // kdDebug(7001) << "No entry for FAM event ?!" << endl;
- return;
- }
-
- if (e->m_status == NonExistent) {
- kdDebug(7001) << "FAM event for nonExistent entry " << e->path << endl;
- return;
- }
-
- // Delayed handling. This rechecks changes with own stat calls.
- e->dirty = true;
- if (!rescan_timer.isActive())
- rescan_timer.start(m_PollInterval, true);
-
- // needed FAM control actions on FAM events
- if (e->isDir)
- switch (fe->code)
- {
- case FAMDeleted:
- // file absolute: watched dir
- if (!TQDir::isRelativePath(fe->filename))
- {
- // a watched directory was deleted
-
- e->m_status = NonExistent;
- FAMCancelMonitor(&fc, &(e->fr) ); // needed ?
- kdDebug(7001) << "Cancelled FAMReq "
- << FAMREQUEST_GETREQNUM(&(e->fr))
- << " for " << e->path << endl;
- // Scan parent for a new creation
- addEntry(0, TQDir::cleanDirPath( e->path+"/.."), e, true);
- }
- break;
-
- case FAMCreated: {
- // check for creation of a directory we have to watch
- Entry *sub_entry = e->m_entries.first();
- for(;sub_entry; sub_entry = e->m_entries.next())
- if (sub_entry->path == e->path + "/" + fe->filename) break;
- if (sub_entry && sub_entry->isDir) {
- TQString path = e->path;
- removeEntry(0,e->path,sub_entry); // <e> can be invalid here!!
- sub_entry->m_status = Normal;
- if (!useFAM(sub_entry))
-#ifdef HAVE_INOTIFY
- if (!useINotify(sub_entry ))
-#endif
- useStat(sub_entry);
- }
- break;
- }
-
- default:
- break;
- }
-}
-#else
-void KDirWatchPrivate::famEventReceived() {}
-#endif
-
-
-void KDirWatchPrivate::statistics()
-{
- EntryMap::Iterator it;
-
- kdDebug(7001) << "Entries watched:" << endl;
- if (m_mapEntries.count()==0) {
- kdDebug(7001) << " None." << endl;
- }
- else {
- it = m_mapEntries.begin();
- for( ; it != m_mapEntries.end(); ++it ) {
- Entry* e = &(*it);
- kdDebug(7001) << " " << e->path << " ("
- << ((e->m_status==Normal)?"":"Nonexistent ")
- << (e->isDir ? "Dir":"File") << ", using "
- << ((e->m_mode == FAMMode) ? "FAM" :
- (e->m_mode == INotifyMode) ? "INotify" :
- (e->m_mode == DNotifyMode) ? "DNotify" :
- (e->m_mode == StatMode) ? "Stat" : "Unknown Method")
- << ")" << endl;
-
- Client* c = e->m_clients.first();
- for(;c; c = e->m_clients.next()) {
- TQString pending;
- if (c->watchingStopped) {
- if (c->pending & Deleted) pending += "deleted ";
- if (c->pending & Created) pending += "created ";
- if (c->pending & Changed) pending += "changed ";
- if (!pending.isEmpty()) pending = " (pending: " + pending + ")";
- pending = ", stopped" + pending;
- }
- kdDebug(7001) << " by " << c->instance->name()
- << " (" << c->count << " times)"
- << pending << endl;
- }
- if (e->m_entries.count()>0) {
- kdDebug(7001) << " dependent entries:" << endl;
- Entry* d = e->m_entries.first();
- for(;d; d = e->m_entries.next()) {
- kdDebug(7001) << " " << d << endl;
- kdDebug(7001) << " " << d->path << " (" << d << ") " << endl;
- }
- }
- }
- }
-}
-
-
-//
-// Class KDirWatch
-//
-
-static KStaticDeleter<KDirWatch> sd_dw;
-KDirWatch* KDirWatch::s_pSelf = 0L;
-
-KDirWatch* KDirWatch::self()
-{
- if ( !s_pSelf ) {
- sd_dw.setObject( s_pSelf, new KDirWatch );
- }
-
- return s_pSelf;
-}
-
-bool KDirWatch::exists()
-{
- return s_pSelf != 0;
-}
-
-KDirWatch::KDirWatch (TQObject* parent, const char* name)
- : TQObject(parent,name)
-{
- if (!name) {
- static int nameCounter = 0;
-
- nameCounter++;
- setName(TQString(TQString("KDirWatch-%1").arg(nameCounter)).ascii());
- }
-
- if (!dwp_self)
- dwp_self = new KDirWatchPrivate;
- d = dwp_self;
- d->ref();
-
- _isStopped = false;
-}
-
-KDirWatch::~KDirWatch()
-{
- d->removeEntries(this);
- if ( d->deref() )
- {
- // delete it if it's the last one
- delete d;
- dwp_self = 0L;
- }
-}
-
-
-// TODO: add watchFiles/recursive support
-void KDirWatch::addDir( const TQString& _path,
- bool watchFiles, bool recursive)
-{
- if (watchFiles || recursive) {
- kdDebug(7001) << "addDir - recursive/watchFiles not supported yet in KDE 3.x" << endl;
- }
- if (d) d->addEntry(this, _path, 0, true);
-}
-
-void KDirWatch::addFile( const TQString& _path )
-{
- if (d) d->addEntry(this, _path, 0, false);
-}
-
-TQDateTime KDirWatch::ctime( const TQString &_path )
-{
- KDirWatchPrivate::Entry* e = d->entry(_path);
-
- if (!e)
- return TQDateTime();
-
- TQDateTime result;
- result.setTime_t(e->m_ctime);
- return result;
-}
-
-void KDirWatch::removeDir( const TQString& _path )
-{
- if (d) d->removeEntry(this, _path, 0);
-}
-
-void KDirWatch::removeFile( const TQString& _path )
-{
- if (d) d->removeEntry(this, _path, 0);
-}
-
-bool KDirWatch::stopDirScan( const TQString& _path )
-{
- if (d) {
- KDirWatchPrivate::Entry *e = d->entry(_path);
- if (e && e->isDir) return d->stopEntryScan(this, e);
- }
- return false;
-}
-
-bool KDirWatch::restartDirScan( const TQString& _path )
-{
- if (d) {
- KDirWatchPrivate::Entry *e = d->entry(_path);
- if (e && e->isDir)
- // restart without notifying pending events
- return d->restartEntryScan(this, e, false);
- }
- return false;
-}
-
-void KDirWatch::stopScan()
-{
- if (d) d->stopScan(this);
- _isStopped = true;
-}
-
-void KDirWatch::startScan( bool notify, bool skippedToo )
-{
- _isStopped = false;
- if (d) d->startScan(this, notify, skippedToo);
-}
-
-
-bool KDirWatch::contains( const TQString& _path ) const
-{
- KDirWatchPrivate::Entry* e = d->entry(_path);
- if (!e)
- return false;
-
- KDirWatchPrivate::Client* c = e->m_clients.first();
- for(;c;c=e->m_clients.next())
- if (c->instance == this) return true;
-
- return false;
-}
-
-void KDirWatch::statistics()
-{
- if (!dwp_self) {
- kdDebug(7001) << "KDirWatch not used" << endl;
- return;
- }
- dwp_self->statistics();
-}
-
-
-void KDirWatch::setCreated( const TQString & _file )
-{
- kdDebug(7001) << name() << " emitting created " << _file << endl;
- emit created( _file );
-}
-
-void KDirWatch::setDirty( const TQString & _file )
-{
- kdDebug(7001) << name() << " emitting dirty " << _file << endl;
- emit dirty( _file );
-}
-
-void KDirWatch::setDeleted( const TQString & _file )
-{
- kdDebug(7001) << name() << " emitting deleted " << _file << endl;
- emit deleted( _file );
-}
-
-KDirWatch::Method KDirWatch::internalMethod()
-{
-#ifdef HAVE_FAM
- if (d->use_fam)
- return KDirWatch::FAM;
-#endif
-#ifdef HAVE_INOTIFY
- if (d->supports_inotify)
- return KDirWatch::INotify;
-#endif
-#ifdef HAVE_DNOTIFY
- if (d->supports_dnotify)
- return KDirWatch::DNotify;
-#endif
- return KDirWatch::Stat;
-}
-
-
-#include "kdirwatch.moc"
-#include "kdirwatch_p.moc"
-
-//sven
-
-// vim: sw=2 ts=8 et
diff --git a/kio/kio/kemailsettings.cpp b/kio/kio/kemailsettings.cpp
deleted file mode 100644
index f8ad9f7dd..000000000
--- a/kio/kio/kemailsettings.cpp
+++ /dev/null
@@ -1,272 +0,0 @@
-/*
- * Copyright (c) 2000 Alex Zepeda <zipzippy@sonic.net>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * $Id$
- */
-
-#include "kemailsettings.h"
-
-#include <kconfig.h>
-#include <klocale.h>
-#include <kdebug.h>
-
-class KEMailSettingsPrivate {
-public:
- KEMailSettingsPrivate() : m_pConfig( 0 ) {}
- ~KEMailSettingsPrivate() { delete m_pConfig; }
- TDEConfig *m_pConfig;
- TQStringList profiles;
- TQString m_sDefaultProfile, m_sCurrentProfile;
-};
-
-TQString KEMailSettings::defaultProfileName() const
-{
- return p->m_sDefaultProfile;
-}
-
-TQString KEMailSettings::getSetting(KEMailSettings::Setting s)
-{
- p->m_pConfig->setGroup(TQString("PROFILE_")+p->m_sCurrentProfile);
- switch (s) {
- case ClientProgram: {
- return p->m_pConfig->readEntry("EmailClient");
- break;
- }
- case ClientTerminal: {
- return ((p->m_pConfig->readBoolEntry("TerminalClient")) ? TQString("true") : TQString("false") );
- break;
- }
- case RealName: {
- return p->m_pConfig->readEntry("FullName");
- break;
- }
- case EmailAddress: {
- return p->m_pConfig->readEntry("EmailAddress");
- break;
- }
- case ReplyToAddress: {
- return p->m_pConfig->readEntry("ReplyAddr");
- break;
- }
- case Organization: {
- return p->m_pConfig->readEntry("Organization");
- break;
- }
- case OutServer: {
- return p->m_pConfig->readEntry("OutgoingServer");
- break;
- }
- case OutServerLogin: {
- return p->m_pConfig->readEntry("OutgoingUserName");
- break;
- }
- case OutServerPass: {
- return p->m_pConfig->readEntry("OutgoingPassword");
- break;
- }
- case OutServerType: {
- return p->m_pConfig->readEntry("OutgoingServerType");
- break;
- }
- case OutServerCommand: {
- return p->m_pConfig->readEntry("OutgoingCommand");
- break;
- }
- case OutServerTLS: {
- return ((p->m_pConfig->readBoolEntry("OutgoingServerTLS")) ? TQString("true") : TQString("false") );
- break;
- }
- case InServer: {
- return p->m_pConfig->readEntry("IncomingServer");
- break;
- }
- case InServerLogin: {
- return p->m_pConfig->readEntry("IncomingUserName");
- break;
- }
- case InServerPass: {
- return p->m_pConfig->readEntry("IncomingPassword");
- break;
- }
- case InServerType: {
- return p->m_pConfig->readEntry("IncomingServerType");
- break;
- }
- case InServerMBXType: {
- return p->m_pConfig->readEntry("IncomingServerMBXType");
- break;
- }
- case InServerTLS: {
- return ((p->m_pConfig->readBoolEntry("IncomingServerTLS")) ? TQString("true") : TQString("false") );
- break;
- }
- };
- return TQString::null;
-}
-void KEMailSettings::setSetting(KEMailSettings::Setting s, const TQString &v)
-{
- p->m_pConfig->setGroup(TQString("PROFILE_")+p->m_sCurrentProfile);
- switch (s) {
- case ClientProgram: {
- p->m_pConfig->writePathEntry("EmailClient", v);
- break;
- }
- case ClientTerminal: {
- p->m_pConfig->writeEntry("TerminalClient", (v == "true") ? true : false );
- break;
- }
- case RealName: {
- p->m_pConfig->writeEntry("FullName", v);
- break;
- }
- case EmailAddress: {
- p->m_pConfig->writeEntry("EmailAddress", v);
- break;
- }
- case ReplyToAddress: {
- p->m_pConfig->writeEntry("ReplyAddr", v);
- break;
- }
- case Organization: {
- p->m_pConfig->writeEntry("Organization", v);
- break;
- }
- case OutServer: {
- p->m_pConfig->writeEntry("OutgoingServer", v);
- break;
- }
- case OutServerLogin: {
- p->m_pConfig->writeEntry("OutgoingUserName", v);
- break;
- }
- case OutServerPass: {
- p->m_pConfig->writeEntry("OutgoingPassword", v);
- break;
- }
- case OutServerType: {
- p->m_pConfig->writeEntry("OutgoingServerType", v);
- break;
- }
- case OutServerCommand: {
- p->m_pConfig->writeEntry("OutgoingCommand", v);
- break;
- }
- case OutServerTLS: {
- p->m_pConfig->writeEntry("OutgoingServerTLS", (v == "true") ? true : false );
- break;
- }
- case InServer: {
- p->m_pConfig->writeEntry("IncomingServer", v);
- break;
- }
- case InServerLogin: {
- p->m_pConfig->writeEntry("IncomingUserName", v);
- break;
- }
- case InServerPass: {
- p->m_pConfig->writeEntry("IncomingPassword", v);
- break;
- }
- case InServerType: {
- p->m_pConfig->writeEntry("IncomingServerType", v);
- break;
- }
- case InServerMBXType: {
- p->m_pConfig->writeEntry("IncomingServerMBXType", v);
- break;
- }
- case InServerTLS: {
- p->m_pConfig->writeEntry("IncomingServerTLS", (v == "true") ? true : false );
- break;
- }
- };
- p->m_pConfig->sync();
-}
-
-void KEMailSettings::setDefault(const TQString &s)
-{
- p->m_pConfig->setGroup("Defaults");
- p->m_pConfig->writeEntry("Profile", s);
- p->m_pConfig->sync();
- p->m_sDefaultProfile=s;
-
-}
-
-void KEMailSettings::setProfile (const TQString &s)
-{
- TQString groupname="PROFILE_";
- groupname.append(s);
- p->m_sCurrentProfile=s;
- if (!p->m_pConfig->hasGroup(groupname)) { // Create a group if it doesn't exist
- p->m_pConfig->setGroup(groupname);
- p->m_pConfig->writeEntry("ServerType", TQString::null);
- p->m_pConfig->sync();
- p->profiles+=s;
- }
-}
-
-TQString KEMailSettings::currentProfileName() const
-{
- return p->m_sCurrentProfile;
-}
-
-TQStringList KEMailSettings::profiles() const
-{
- return p->profiles;
-}
-
-KEMailSettings::KEMailSettings()
-{
- p = new KEMailSettingsPrivate();
- p->m_sCurrentProfile=TQString::null;
-
- p->m_pConfig = new TDEConfig("emaildefaults");
-
- TQStringList groups = p->m_pConfig->groupList();
- for (TQStringList::Iterator it = groups.begin(); it != groups.end(); ++it) {
- if ( (*it).left(8) == "PROFILE_" )
- p->profiles+= (*it).mid(8, (*it).length());
- }
-
- p->m_pConfig->setGroup("Defaults");
- p->m_sDefaultProfile=p->m_pConfig->readEntry("Profile", i18n("Default"));
- if (!p->m_sDefaultProfile.isNull()) {
- if (!p->m_pConfig->hasGroup(TQString("PROFILE_")+p->m_sDefaultProfile))
- setDefault(i18n("Default"));
- else
- setDefault(p->m_sDefaultProfile);
- } else {
- if (p->profiles.count()) {
- setDefault(p->profiles[0]);
- } else
- setDefault(i18n("Default"));
- }
- setProfile(defaultProfileName());
-}
-
-KEMailSettings::~KEMailSettings()
-{
- delete p;
-}
diff --git a/kio/kio/kfilefilter.cpp b/kio/kio/kfilefilter.cpp
deleted file mode 100644
index c927804b5..000000000
--- a/kio/kio/kfilefilter.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/* This file is part of the KDE libraries
-
- Copyright (c) 2001,2002 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License (LGPL) as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqregexp.h>
-
-#include <kfileitem.h>
-#include <kglobal.h>
-
-#include "kfilefilter.h"
-
-KSimpleFileFilter::KSimpleFileFilter()
- : m_filterDotFiles( true ),
- m_filterSpecials( true ),
- m_modeFilter( 0 )
-{
- m_nameFilters.setAutoDelete( true );
-}
-
-KSimpleFileFilter::~KSimpleFileFilter()
-{
-}
-
-void KSimpleFileFilter::setFilterDotFiles( bool filter )
-{
- m_filterDotFiles = filter;
-}
-
-void KSimpleFileFilter::setFilterSpecials( bool filter )
-{
- m_filterSpecials = filter;
-}
-
-void KSimpleFileFilter::setNameFilters( const TQString& nameFilters )
-{
- // KDE 3.0 defaults
- setNameFilters( nameFilters, false, ' ' );
-}
-
-void KSimpleFileFilter::setNameFilters( const TQString& nameFilters,
- bool caseSensitive,
- const TQChar& separator )
-{
- m_nameFilters.clear();
-
- // Split on white space
- TQStringList list = TQStringList::split(separator, nameFilters);
-
- TQStringList::ConstIterator it = list.begin();
- for ( ; it != list.end(); ++it )
- m_nameFilters.append(new TQRegExp(*it, caseSensitive, true ));
-}
-
-void KSimpleFileFilter::setMimeFilters( const TQStringList& mimeFilters )
-{
- m_mimeFilters = mimeFilters;
-}
-
-void KSimpleFileFilter::setModeFilter( mode_t mode )
-{
- m_modeFilter = mode;
-}
-
-bool KSimpleFileFilter::passesFilter( const KFileItem *item ) const
-{
- static const TQString& dot = TDEGlobal::staticQString(".");
- static const TQString& dotdot = TDEGlobal::staticQString("..");
-
- const TQString& name = item->name();
-
- if ( m_filterDotFiles && item->isHidden() )
- return false;
-
- if ( m_filterSpecials && (name == dot || name == dotdot) )
- return false;
-
- if ( m_modeFilter && !(m_modeFilter & item->mode()) )
- return false;
-
- if ( !m_mimeFilters.isEmpty() ) {
- // correct or guessed mimetype -- we don't mind
- KMimeType::Ptr mime = item->mimeTypePtr();
- bool ok = false;
-
- TQStringList::ConstIterator it = m_mimeFilters.begin();
- for ( ; it != m_mimeFilters.end(); ++it ) {
- if ( mime->is(*it) ) { // match!
- ok = true;
- break;
- }
- }
- if ( !ok )
- return false;
- }
-
- if ( !m_nameFilters.isEmpty() ) {
- bool ok = false;
-
- TQPtrListIterator<TQRegExp> it( m_nameFilters );
- for ( ; it.current(); ++it ) {
- if ( it.current()->exactMatch( name ) ) { // match!
- ok = true;
- break;
- }
- }
- if ( !ok )
- return false;
- }
-
- return true; // passes the filter!
-}
-
-void KFileFilter::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-void KSimpleFileFilter::virtual_hook( int id, void* data )
-{ KFileFilter::virtual_hook( id, data ); }
-
diff --git a/kio/kio/kfileitem.cpp b/kio/kio/kfileitem.cpp
deleted file mode 100644
index fa08ae961..000000000
--- a/kio/kio/kfileitem.cpp
+++ /dev/null
@@ -1,1202 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 1999 David Faure <faure@kde.org>
- 2001 Carsten Pfeiffer <pfeiffer@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-// $Id$
-
-#include <config.h>
-
-#include <sys/time.h>
-#include <pwd.h>
-#include <grp.h>
-#include <sys/types.h>
-
-#include <assert.h>
-#include <unistd.h>
-
-#include "kfileitem.h"
-
-#include <tqdir.h>
-#include <tqfile.h>
-#include <tqmap.h>
-#include <tqstylesheet.h>
-#include <tqimage.h>
-
-#include <kdebug.h>
-#include <kfilemetainfo.h>
-#include <ksambashare.h>
-#include <knfsshare.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <kiconloader.h>
-#include <klargefile.h>
-#include <klocale.h>
-#include <kmimetype.h>
-#include <krun.h>
-
-#ifdef HAVE_ELFICON
-#include "tdelficon.h"
-#endif // HAVE_ELFICON
-
-class KFileItem::KFileItemPrivate {
- public:
- TQString iconName;
-};
-
-KFileItem::KFileItem( const TDEIO::UDSEntry& _entry, const KURL& _url,
- bool _determineMimeTypeOnDemand, bool _urlIsDirectory ) :
- m_entry( _entry ),
- m_url( _url ),
- m_pMimeType( 0 ),
- m_fileMode( KFileItem::Unknown ),
- m_permissions( KFileItem::Unknown ),
- m_bMarked( false ),
- m_bLink( false ),
- m_bIsLocalURL( _url.isLocalFile() ),
- m_bMimeTypeKnown( false ),
- m_hidden( Auto ),
- d(0)
-{
- readUDSEntry( _urlIsDirectory );
- init( _determineMimeTypeOnDemand );
-}
-
-KFileItem::KFileItem( mode_t _mode, mode_t _permissions, const KURL& _url, bool _determineMimeTypeOnDemand ) :
- m_entry(), // warning !
- m_url( _url ),
- m_strName( _url.fileName() ),
- m_strText( TDEIO::decodeFileName( m_strName ) ),
- m_pMimeType( 0 ),
- m_fileMode ( _mode ),
- m_permissions( _permissions ),
- m_bMarked( false ),
- m_bLink( false ),
- m_bIsLocalURL( _url.isLocalFile() ),
- m_bMimeTypeKnown( false ),
- m_hidden( Auto ),
- d(0)
-{
- init( _determineMimeTypeOnDemand );
-}
-
-KFileItem::KFileItem( const KURL &url, const TQString &mimeType, mode_t mode )
-: m_url( url ),
- m_strName( url.fileName() ),
- m_strText( TDEIO::decodeFileName( m_strName ) ),
- m_pMimeType( 0 ),
- m_fileMode( mode ),
- m_permissions( KFileItem::Unknown ),
- m_bMarked( false ),
- m_bLink( false ),
- m_bIsLocalURL( url.isLocalFile() ),
- m_bMimeTypeKnown( !mimeType.isEmpty() ),
- m_hidden( Auto ),
- d(0)
-{
- if (m_bMimeTypeKnown)
- m_pMimeType = KMimeType::mimeType( mimeType );
-
- init( false );
-}
-
-KFileItem::KFileItem( const KFileItem & item ) :
- d(0)
-{
- assign( item );
-}
-
-KFileItem& KFileItem::operator=( const KFileItem & item )
-{
- assign( item );
- return *this;
-}
-
-KFileItem::~KFileItem()
-{
- delete d;
-}
-
-void KFileItem::init( bool _determineMimeTypeOnDemand )
-{
- m_access = TQString::null;
- m_size = (TDEIO::filesize_t) -1;
- // metaInfo = KFileMetaInfo();
- for ( int i = 0; i < NumFlags; i++ )
- m_time[i] = (time_t) -1;
-
- // determine mode and/or permissions if unknown
- if ( m_fileMode == KFileItem::Unknown || m_permissions == KFileItem::Unknown )
- {
- mode_t mode = 0;
- if ( m_url.isLocalFile() )
- {
- /* directories may not have a slash at the end if
- * we want to stat() them; it requires that we
- * change into it .. which may not be allowed
- * stat("/is/unaccessible") -> rwx------
- * stat("/is/unaccessible/") -> EPERM H.Z.
- * This is the reason for the -1
- */
- KDE_struct_stat buf;
- TQCString path = TQFile::encodeName(m_url.path( -1 ));
- if ( KDE_lstat( path.data(), &buf ) == 0 )
- {
- mode = buf.st_mode;
- if ( S_ISLNK( mode ) )
- {
- m_bLink = true;
- if ( KDE_stat( path.data(), &buf ) == 0 )
- mode = buf.st_mode;
- else // link pointing to nowhere (see kio/file/file.cc)
- mode = (S_IFMT-1) | S_IRWXU | S_IRWXG | S_IRWXO;
- }
- // While we're at it, store the times
- m_time[ Modification ] = buf.st_mtime;
- m_time[ Access ] = buf.st_atime;
- if ( m_fileMode == KFileItem::Unknown )
- m_fileMode = mode & S_IFMT; // extract file type
- if ( m_permissions == KFileItem::Unknown )
- m_permissions = mode & 07777; // extract permissions
- }
- }
- }
-
- // determine the mimetype
- if (!m_pMimeType && !m_url.isEmpty())
- {
- bool accurate = false;
- bool isLocalURL;
- KURL url = mostLocalURL(isLocalURL);
-
- m_pMimeType = KMimeType::findByURL( url, m_fileMode, isLocalURL,
- // use fast mode if not mimetype on demand
- _determineMimeTypeOnDemand, &accurate );
- //kdDebug() << "finding mimetype for " << url.url() << " : " << m_pMimeType->name() << endl;
- // if we didn't use fast mode, or if we got a result, then this is the mimetype
- // otherwise, determineMimeType will be able to do better.
- m_bMimeTypeKnown = (!_determineMimeTypeOnDemand) || accurate;
- }
-}
-
-void KFileItem::readUDSEntry( bool _urlIsDirectory )
-{
- // extract the mode and the filename from the TDEIO::UDS Entry
- bool UDS_URL_seen = false;
-
- if (&m_entry == NULL) return;
-
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- for( ; it != m_entry.end(); ++it ) {
- switch ((*it).m_uds) {
-
- case TDEIO::UDS_FILE_TYPE:
- m_fileMode = (mode_t)((*it).m_long);
- break;
-
- case TDEIO::UDS_ACCESS:
- m_permissions = (mode_t)((*it).m_long);
- break;
-
- case TDEIO::UDS_USER:
- m_user = ((*it).m_str);
- break;
-
- case TDEIO::UDS_GROUP:
- m_group = ((*it).m_str);
- break;
-
- case TDEIO::UDS_NAME:
- m_strName = (*it).m_str;
- m_strText = TDEIO::decodeFileName( m_strName );
- break;
-
- case TDEIO::UDS_URL:
- UDS_URL_seen = true;
- m_url = KURL((*it).m_str);
- if ( m_url.isLocalFile() )
- m_bIsLocalURL = true;
- break;
-
- case TDEIO::UDS_MIME_TYPE:
- m_pMimeType = KMimeType::mimeType((*it).m_str);
- m_bMimeTypeKnown = true;
- break;
-
- case TDEIO::UDS_GUESSED_MIME_TYPE:
- m_guessedMimeType = (*it).m_str;
- break;
-
- case TDEIO::UDS_LINK_DEST:
- m_bLink = !(*it).m_str.isEmpty(); // we don't store the link dest
- break;
-
- case TDEIO::UDS_ICON_NAME:
- if ( !d )
- d = new KFileItemPrivate();
- d->iconName = (*it).m_str;
- break;
-
- case TDEIO::UDS_HIDDEN:
- if ( (*it).m_long )
- m_hidden = Hidden;
- else
- m_hidden = Shown;
- break;
- }
- }
-
- // avoid creating these QStrings again and again
- static const TQString& dot = TDEGlobal::staticQString(".");
- if ( _urlIsDirectory && !UDS_URL_seen && !m_strName.isEmpty() && m_strName != dot )
- m_url.addPath( m_strName );
-}
-
-void KFileItem::refresh()
-{
- m_fileMode = KFileItem::Unknown;
- m_permissions = KFileItem::Unknown;
- m_pMimeType = 0L;
- m_user = TQString::null;
- m_group = TQString::null;
- m_metaInfo = KFileMetaInfo();
- m_hidden = Auto;
-
- // Basically, we can't trust any information we got while listing.
- // Everything could have changed...
- // Clearing m_entry makes it possible to detect changes in the size of the file,
- // the time information, etc.
- m_entry = TDEIO::UDSEntry();
- init( false );
-}
-
-void KFileItem::refreshMimeType()
-{
- m_pMimeType = 0L;
- init( false ); // Will determine the mimetype
-}
-
-void KFileItem::setURL( const KURL &url )
-{
- m_url = url;
- setName( url.fileName() );
-}
-
-void KFileItem::setName( const TQString& name )
-{
- m_strName = name;
- m_strText = TDEIO::decodeFileName( m_strName );
-}
-
-TQString KFileItem::linkDest() const
-{
- if (&m_entry == NULL) return TQString::null;
-
- // Extract it from the TDEIO::UDSEntry
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- for( ; it != m_entry.end(); ++it )
- if ( (*it).m_uds == TDEIO::UDS_LINK_DEST )
- return (*it).m_str;
- // If not in the TDEIO::UDSEntry, or if UDSEntry empty, use readlink() [if local URL]
- if ( m_bIsLocalURL )
- {
- char buf[1000];
- int n = readlink( TQFile::encodeName(m_url.path( -1 )), buf, sizeof(buf)-1 );
- if ( n != -1 )
- {
- buf[ n ] = 0;
- return TQFile::decodeName( buf );
- }
- }
- return TQString::null;
-}
-
-TQString KFileItem::localPath() const
-{
- if ( m_bIsLocalURL )
- {
- return m_url.path();
- }
- else
- {
- if (&m_entry == NULL) return TQString::null;
-
- // Extract the local path from the TDEIO::UDSEntry
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- const TDEIO::UDSEntry::ConstIterator end = m_entry.end();
- for( ; it != end; ++it )
- if ( (*it).m_uds == TDEIO::UDS_LOCAL_PATH )
- return (*it).m_str;
- }
-
- return TQString::null;
-}
-
-TDEIO::filesize_t KFileItem::size(bool &exists) const
-{
- exists = true;
- if ( m_size != (TDEIO::filesize_t) -1 )
- return m_size;
-
- if (&m_entry == NULL) return 0L;
-
- // Extract it from the TDEIO::UDSEntry
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- for( ; it != m_entry.end(); ++it )
- if ( (*it).m_uds == TDEIO::UDS_SIZE ) {
- m_size = (*it).m_long;
- return m_size;
- }
- // If not in the TDEIO::UDSEntry, or if UDSEntry empty, use stat() [if local URL]
- if ( m_bIsLocalURL )
- {
- KDE_struct_stat buf;
- if ( KDE_stat( TQFile::encodeName(m_url.path( -1 )), &buf ) == 0 )
- return buf.st_size;
- }
- exists = false;
- return 0L;
-}
-
-bool KFileItem::hasExtendedACL() const
-{
- if (&m_entry == NULL) return false;
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- for( ; it != m_entry.end(); it++ )
- if ( (*it).m_uds == TDEIO::UDS_EXTENDED_ACL ) {
- return true;
- }
- return false;
-}
-
-KACL KFileItem::ACL() const
-{
- if ( hasExtendedACL() ) {
- if (&m_entry == NULL) return KACL( m_permissions );
-
- // Extract it from the TDEIO::UDSEntry
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- for( ; it != m_entry.end(); ++it )
- if ( (*it).m_uds == TDEIO::UDS_ACL_STRING )
- return KACL((*it).m_str);
- }
- // create one from the basic permissions
- return KACL( m_permissions );
-}
-
-KACL KFileItem::defaultACL() const
-{
- if (&m_entry == NULL) return KACL();
-
- // Extract it from the TDEIO::UDSEntry
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- for( ; it != m_entry.end(); ++it )
- if ( (*it).m_uds == TDEIO::UDS_DEFAULT_ACL_STRING )
- return KACL((*it).m_str);
- return KACL();
-}
-
-TDEIO::filesize_t KFileItem::size() const
-{
- bool exists;
- return size(exists);
-}
-
-time_t KFileItem::time( unsigned int which ) const
-{
- bool hasTime;
- return time(which, hasTime);
-}
-time_t KFileItem::time( unsigned int which, bool &hasTime ) const
-{
- hasTime = true;
- unsigned int mappedWhich = 0;
-
- switch( which ) {
- case TDEIO::UDS_MODIFICATION_TIME:
- mappedWhich = Modification;
- break;
- case TDEIO::UDS_ACCESS_TIME:
- mappedWhich = Access;
- break;
- case TDEIO::UDS_CREATION_TIME:
- mappedWhich = Creation;
- break;
- }
-
- if ( m_time[mappedWhich] != (time_t) -1 )
- return m_time[mappedWhich];
-
- if (&m_entry == NULL) return static_cast<time_t>(0);
-
- // Extract it from the TDEIO::UDSEntry
- TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
- for( ; it != m_entry.end(); ++it )
- if ( (*it).m_uds == which ) {
- m_time[mappedWhich] = static_cast<time_t>((*it).m_long);
- return m_time[mappedWhich];
- }
-
- // If not in the TDEIO::UDSEntry, or if UDSEntry empty, use stat() [if local URL]
- if ( m_bIsLocalURL )
- {
- KDE_struct_stat buf;
- if ( KDE_stat( TQFile::encodeName(m_url.path(-1)), &buf ) == 0 )
- {
- if(which == TDEIO::UDS_CREATION_TIME) {
- // We can't determine creation time for local files
- hasTime = false;
- m_time[mappedWhich] = static_cast<time_t>(0);
- return m_time[mappedWhich];
- }
- m_time[mappedWhich] = (which == TDEIO::UDS_MODIFICATION_TIME) ?
- buf.st_mtime :
- /* which == TDEIO::UDS_ACCESS_TIME)*/
- buf.st_atime;
- return m_time[mappedWhich];
- }
- }
- hasTime = false;
- return static_cast<time_t>(0);
-}
-
-
-TQString KFileItem::user() const
-{
- if ( m_user.isEmpty() && m_bIsLocalURL )
- {
- KDE_struct_stat buff;
- if ( KDE_lstat( TQFile::encodeName(m_url.path( -1 )), &buff ) == 0) // get uid/gid of the link, if it's a link
- {
- struct passwd *user = getpwuid( buff.st_uid );
- if ( user != 0L )
- m_user = TQString::fromLocal8Bit(user->pw_name);
- }
- }
- return m_user;
-}
-
-TQString KFileItem::group() const
-{
-#ifdef Q_OS_UNIX
- if (m_group.isEmpty() && m_bIsLocalURL )
- {
- KDE_struct_stat buff;
- if ( KDE_lstat( TQFile::encodeName(m_url.path( -1 )), &buff ) == 0) // get uid/gid of the link, if it's a link
- {
- struct group *ge = getgrgid( buff.st_gid );
- if ( ge != 0L ) {
- m_group = TQString::fromLocal8Bit(ge->gr_name);
- if (m_group.isEmpty())
- m_group.sprintf("%d",ge->gr_gid);
- } else
- m_group.sprintf("%d",buff.st_gid);
- }
- }
-#endif
- return m_group;
-}
-
-TQString KFileItem::mimetype() const
-{
- KFileItem * that = const_cast<KFileItem *>(this);
- return that->determineMimeType()->name();
-}
-
-KMimeType::Ptr KFileItem::determineMimeType()
-{
- if ( !m_pMimeType || !m_bMimeTypeKnown )
- {
- bool isLocalURL;
- KURL url = mostLocalURL(isLocalURL);
-
- m_pMimeType = KMimeType::findByURL( url, m_fileMode, isLocalURL );
- //kdDebug() << "finding mimetype for " << url.url() << " : " << m_pMimeType->name() << endl;
- m_bMimeTypeKnown = true;
- }
-
- return m_pMimeType;
-}
-
-bool KFileItem::isMimeTypeKnown() const
-{
- // The mimetype isn't known if determineMimeType was never called (on-demand determination)
- // or if this fileitem has a guessed mimetype (e.g. ftp symlink) - in which case
- // it always remains "not fully determined"
- return m_bMimeTypeKnown && m_guessedMimeType.isEmpty();
-}
-
-TQString KFileItem::mimeComment()
-{
- KMimeType::Ptr mType = determineMimeType();
-
- bool isLocalURL;
- KURL url = mostLocalURL(isLocalURL);
-
- TQString comment = mType->comment( url, isLocalURL );
- //kdDebug() << "finding comment for " << url.url() << " : " << m_pMimeType->name() << endl;
- if (!comment.isEmpty())
- return comment;
- else
- return mType->name();
-}
-
-TQString KFileItem::iconName()
-{
- if (d && (!d->iconName.isEmpty())) return d->iconName;
-
- bool isLocalURL;
- KURL url = mostLocalURL(isLocalURL);
-
- //kdDebug() << "finding icon for " << url.url() << " : " << m_pMimeType->name() << endl;
- return determineMimeType()->icon(url, isLocalURL);
-}
-
-int KFileItem::overlays() const
-{
- int _state = 0;
- if ( m_bLink )
- _state |= KIcon::LinkOverlay;
-
- if ( !S_ISDIR( m_fileMode ) // Locked dirs have a special icon, use the overlay for files only
- && !isReadable())
- _state |= KIcon::LockOverlay;
-
- if ( isHidden() )
- _state |= KIcon::HiddenOverlay;
-
- if( S_ISDIR( m_fileMode ) && m_bIsLocalURL)
- {
- if (KSambaShare::instance()->isDirectoryShared( m_url.path() ) ||
- KNFSShare::instance()->isDirectoryShared( m_url.path() ))
- {
- //kdDebug()<<"KFileShare::isDirectoryShared : "<<m_url.path()<<endl;
- _state |= KIcon::ShareOverlay;
- }
- }
-
- if ( m_pMimeType->name() == "application/x-gzip" && m_url.fileName().right(3) == ".gz" )
- _state |= KIcon::ZipOverlay;
- return _state;
-}
-
-TQPixmap KFileItem::pixmap( int _size, int _state ) const
-{
- if (d && (!d->iconName.isEmpty()))
- return DesktopIcon(d->iconName,_size,_state);
-
- if ( !m_pMimeType )
- {
- static const TQString & defaultFolderIcon =
- TDEGlobal::staticQString(KMimeType::mimeType( "inode/directory" )->KServiceType::icon());
-
- if ( S_ISDIR( m_fileMode ) )
- return DesktopIcon( defaultFolderIcon, _size, _state );
-
- return DesktopIcon( "unknown", _size, _state );
- }
-
- _state |= overlays();
-
- KMimeType::Ptr mime;
- // Use guessed mimetype if the main one hasn't been determined for sure
- if ( !m_bMimeTypeKnown && !m_guessedMimeType.isEmpty() )
- mime = KMimeType::mimeType( m_guessedMimeType );
- else
- mime = m_pMimeType;
-
- // Support for gzipped files: extract mimetype of contained file
- // See also the relevant code in overlays, which adds the zip overlay.
- if ( mime->name() == "application/x-gzip" && m_url.fileName().right(3) == ".gz" )
- {
- KURL sf;
- sf.setPath( m_url.path().left( m_url.path().length() - 3 ) );
- //kdDebug() << "KFileItem::pixmap subFileName=" << subFileName << endl;
- mime = KMimeType::findByURL( sf, 0, m_bIsLocalURL );
- }
-
- bool isLocalURL;
- KURL url = mostLocalURL(isLocalURL);
-
- TQPixmap p = mime->pixmap( url, KIcon::Desktop, _size, _state );
- //kdDebug() << "finding pixmap for " << url.url() << " : " << mime->name() << endl;
- if (p.isNull())
- kdWarning() << "Pixmap not found for mimetype " << m_pMimeType->name() << endl;
-
- if ( mime->name() == "application/x-executable" ) {
- // At first glance it might seem to be a good idea to
- // look for .desktop files for this executable before resorting to the embedded icon
- // in the same fashion as the minicli, but on close examination this is NOT A GOOD IDEA.
- // Specifically it allows one executable to mimic another purely based on filename,
- // which could at certain times fool any user regardless of experience level.
-#ifdef HAVE_ELFICON
- // Check for an embedded icon
- unsigned int icon_size;
- libr_icon *icon = NULL;
- libr_file *handle = NULL;
- libr_access_t access = LIBR_READ;
-
- if((handle = libr_open(const_cast<char*>(url.path().ascii()), access)) == NULL)
- {
- kdWarning() << "failed to open file" << url.path() << endl;
- return p;
- }
-
- icon_size = _size;
- icon = libr_icon_geticon_bysize(handle, icon_size);
-
- // See if the embedded icon name matches any icon file names already on the system
- // If it does, use the system icon instead of the embedded one
- int iconresnamefound = 0;
- iconentry *entry = NULL;
- iconlist icons;
- if(!get_iconlist(handle, &icons))
- {
- // Failed to obtain a list of ELF icons
- kdWarning() << "failed to obtain ELF icon: " << libr_errmsg() << endl;
-
- // See if there is a system icon we can use
- TQString sysIconName = elf_get_resource(handle, ".metadata_sysicon");
- if (!sysIconName.isEmpty()) {
- if (TDEGlobal::iconLoader()->iconPath(sysIconName.ascii(), 0, true) != "") {
- p = DesktopIcon( sysIconName.ascii(), _size, _state );
- }
- }
-
- libr_close(handle);
- return p;
- }
- else {
- while((entry = get_nexticon(&icons, entry)) != NULL)
- {
- if(icon == NULL)
- {
- // Try loading this icon as fallback
- icon = libr_icon_geticon_byname(handle, entry->name);
- }
- if (TDEGlobal::iconLoader()->iconPath(entry->name, 0, true) != "") {
- iconresnamefound = 1;
- p = DesktopIcon( entry->name, _size, _state );
- break;
- }
- }
- }
-
- if ((iconresnamefound == 0) && (icon)) {
- // Extract the embedded icon
- size_t icon_data_length;
- char* icondata = libr_icon_malloc(icon, &icon_data_length);
- p.loadFromData(static_cast<uchar*>(static_cast<void*>(icondata)), icon_data_length); // EVIL CAST
- if (icon_size != 0) {
- TQImage ip = p.convertToImage();
- ip = ip.smoothScale(icon_size, icon_size);
- p.convertFromImage(ip);
- }
- free(icondata);
- libr_icon_close(icon);
- }
-
- libr_close(handle);
-#endif // HAVE_ELFICON
- }
-
- return p;
-}
-
-bool KFileItem::isReadable() const
-{
- /*
- struct passwd * user = getpwuid( geteuid() );
- bool isMyFile = (TQString::fromLocal8Bit(user->pw_name) == m_user);
- // This gets ugly for the group....
- // Maybe we want a static TQString for the user and a static QStringList
- // for the groups... then we need to handle the deletion properly...
- */
-
- if ( m_permissions != KFileItem::Unknown ) {
- // No read permission at all
- if ( !(S_IRUSR & m_permissions) && !(S_IRGRP & m_permissions) && !(S_IROTH & m_permissions) )
- return false;
-
- // Read permissions for all: save a stat call
- if ( (S_IRUSR|S_IRGRP|S_IROTH) & m_permissions )
- return true;
- }
-
- // Or if we can't read it [using ::access()] - not network transparent
- if ( m_bIsLocalURL && ::access( TQFile::encodeName(m_url.path()), R_OK ) == -1 )
- return false;
-
- return true;
-}
-
-bool KFileItem::isWritable() const
-{
- /*
- struct passwd * user = getpwuid( geteuid() );
- bool isMyFile = (TQString::fromLocal8Bit(user->pw_name) == m_user);
- // This gets ugly for the group....
- // Maybe we want a static TQString for the user and a static QStringList
- // for the groups... then we need to handle the deletion properly...
- */
-
- if ( m_permissions != KFileItem::Unknown ) {
- // No write permission at all
- if ( !(S_IWUSR & m_permissions) && !(S_IWGRP & m_permissions) && !(S_IWOTH & m_permissions) )
- return false;
- }
-
- // Or if we can't read it [using ::access()] - not network transparent
- if ( m_bIsLocalURL && ::access( TQFile::encodeName(m_url.path()), W_OK ) == -1 )
- return false;
-
- return true;
-}
-
-bool KFileItem::isHidden() const
-{
- if ( m_hidden != Auto )
- return m_hidden == Hidden;
-
- if ( !m_url.isEmpty() )
- return m_url.fileName()[0] == '.';
- else // should never happen
- return m_strName[0] == '.';
-}
-
-bool KFileItem::isDir() const
-{
- if ( m_fileMode == KFileItem::Unknown )
- {
- kdDebug() << " KFileItem::isDir can't say -> false " << endl;
- return false; // can't say for sure, so no
- }
- return (S_ISDIR(m_fileMode));
-/*
- if (!S_ISDIR(m_fileMode)) {
- if (m_url.isLocalFile()) {
- KMimeType::Ptr ptr=KMimeType::findByURL(m_url,0,true,true);
- if ((ptr!=0) && (ptr->is("directory/inode"))) return true;
- }
- return false
- } else return true;*/
-}
-
-bool KFileItem::acceptsDrops()
-{
- // A directory ?
- if ( S_ISDIR( mode() ) ) {
- return isWritable();
- }
-
- // But only local .desktop files and executables
- if ( !m_bIsLocalURL )
- return false;
-
- if (( mimetype() == "application/x-desktop") ||
- ( mimetype() == "media/builtin-mydocuments") ||
- ( mimetype() == "media/builtin-mycomputer") ||
- ( mimetype() == "media/builtin-mynetworkplaces") ||
- ( mimetype() == "media/builtin-printers") ||
- ( mimetype() == "media/builtin-trash") ||
- ( mimetype() == "media/builtin-webbrowser"))
- return true;
-
- // Executable, shell script ... ?
- if ( ::access( TQFile::encodeName(m_url.path()), X_OK ) == 0 )
- return true;
-
- return false;
-}
-
-TQString KFileItem::getStatusBarInfo()
-{
- TQString text = m_strText;
-
- if ( m_bLink )
- {
- TQString comment = determineMimeType()->comment( m_url, m_bIsLocalURL );
- TQString tmp;
- if ( comment.isEmpty() )
- tmp = i18n ( "Symbolic Link" );
- else
- tmp = i18n("%1 (Link)").arg(comment);
- text += "->";
- text += linkDest();
- text += " ";
- text += tmp;
- }
- else if ( S_ISREG( m_fileMode ) )
- {
- bool hasSize;
- TDEIO::filesize_t sizeValue = size(hasSize);
- if(hasSize)
- text += TQString(" (%1) ").arg( TDEIO::convertSize( sizeValue ) );
- text += mimeComment();
- }
- else if ( S_ISDIR ( m_fileMode ) )
- {
- text += "/ ";
- text += mimeComment();
- }
- else
- {
- text += " ";
- text += mimeComment();
- }
- text.replace('\n', " "); // replace any newlines with a space, so the statusbar doesn't get a two-line string which messes the display up, Alex
- return text;
-}
-
-TQString KFileItem::getToolTipText(int maxcount)
-{
- // we can return TQString::null if no tool tip should be shown
- TQString tip;
- KFileMetaInfo info = metaInfo();
-
- // the font tags are a workaround for the fact that the tool tip gets
- // screwed if the color scheme uses white as default text color
- const char* start = "<tr><td><nobr><font color=\"black\">";
- const char* mid = "</font></nobr></td><td><nobr><font color=\"black\">";
- const char* end = "</font></nobr></td></tr>";
-
- tip = "<table cellspacing=0 cellpadding=0>";
-
- tip += start + i18n("Name:") + mid + text() + end;
- tip += start + i18n("Type:") + mid;
-
- TQString type = TQStyleSheet::escape(mimeComment());
- if ( m_bLink ) {
- tip += i18n("Link to %1 (%2)").arg(linkDest(), type) + end;
- } else
- tip += type + end;
-
- if ( !S_ISDIR ( m_fileMode ) ) {
- bool hasSize;
- TDEIO::filesize_t sizeValue = size(hasSize);
- if(hasSize)
- tip += start + i18n("Size:") + mid +
- TDEIO::convertSizeWithBytes(sizeValue) + end;
- }
- TQString timeStr = timeString( TDEIO::UDS_MODIFICATION_TIME);
- if(!timeStr.isEmpty())
- tip += start + i18n("Modified:") + mid +
- timeStr + end;
-#ifndef Q_WS_WIN //TODO: show win32-specific permissions
- TQString userStr = user();
- TQString groupStr = group();
- if(!userStr.isEmpty() || !groupStr.isEmpty())
- tip += start + i18n("Owner:") + mid + userStr + " - " + groupStr + end +
- start + i18n("Permissions:") + mid +
- parsePermissions(m_permissions) + end;
-#endif
-
- if (info.isValid() && !info.isEmpty() )
- {
- tip += "<tr><td colspan=2><center><s>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</s></center></td></tr>";
- TQStringList keys = info.preferredKeys();
-
- // now the rest
- TQStringList::Iterator it = keys.begin();
- for (int count = 0; count<maxcount && it!=keys.end() ; ++it)
- {
- KFileMetaInfoItem item = info.item( *it );
- if ( item.isValid() )
- {
- TQString s = item.string();
- if ( ( item.attributes() & KFileMimeTypeInfo::SqueezeText )
- && s.length() > 50) {
- s.truncate(47);
- s.append("...");
- }
- if ( !s.isEmpty() )
- {
- count++;
- tip += start +
- TQStyleSheet::escape( item.translatedKey() ) + ":" +
- mid +
- TQStyleSheet::escape( s ) +
- end;
- }
-
- }
- }
- }
- tip += "</table>";
-
- //kdDebug() << "making this the tool tip rich text:\n";
- //kdDebug() << tip << endl;
-
- return tip;
-}
-
-void KFileItem::run()
-{
- // It might be faster to pass skip that when we know the mimetype,
- // and just call KRun::runURL. But then we need to use mostLocalURL()
- // for application/x-desktop files, to be able to execute them.
- (void) new KRun( m_url, m_fileMode, m_bIsLocalURL );
-}
-
-bool KFileItem::cmp( const KFileItem & item )
-{
- bool hasSize1,hasSize2,hasTime1,hasTime2;
- hasSize1 = hasSize2 = hasTime1 = hasTime2 = false;
- return ( m_strName == item.m_strName
- && m_bIsLocalURL == item.m_bIsLocalURL
- && m_fileMode == item.m_fileMode
- && m_permissions == item.m_permissions
- && m_user == item.m_user
- && m_group == item.m_group
- && m_bLink == item.m_bLink
- && m_hidden == item.m_hidden
- && size(hasSize1) == item.size(hasSize2)
- && hasSize1 == hasSize2
- && time(TDEIO::UDS_MODIFICATION_TIME, hasTime1) == item.time(TDEIO::UDS_MODIFICATION_TIME, hasTime2)
- && hasTime1 == hasTime2
- && (!d || !item.d || d->iconName == item.d->iconName) );
-
- // Don't compare the mimetypes here. They might not be known, and we don't want to
- // do the slow operation of determining them here.
-}
-
-void KFileItem::assign( const KFileItem & item )
-{
- if ( this == &item )
- return;
- m_entry = item.m_entry;
- m_url = item.m_url;
- m_bIsLocalURL = item.m_bIsLocalURL;
- m_strName = item.m_strName;
- m_strText = item.m_strText;
- m_fileMode = item.m_fileMode;
- m_permissions = item.m_permissions;
- m_user = item.m_user;
- m_group = item.m_group;
- m_bLink = item.m_bLink;
- m_pMimeType = item.m_pMimeType;
- m_strLowerCaseName = item.m_strLowerCaseName;
- m_bMimeTypeKnown = item.m_bMimeTypeKnown;
- m_hidden = item.m_hidden;
- m_guessedMimeType = item.m_guessedMimeType;
- m_access = item.m_access;
- m_metaInfo = item.m_metaInfo;
- for ( int i = 0; i < NumFlags; i++ )
- m_time[i] = item.m_time[i];
- m_size = item.m_size;
- // note: m_extra is NOT copied, as we'd have no control over who is
- // deleting the data or not.
-
- // We had a mimetype previously (probably), so we need to re-determine it
- determineMimeType();
-
- if ( item.d ) {
- if ( !d )
- d = new KFileItemPrivate;
- d->iconName = item.d->iconName;
- } else {
- delete d;
- d = 0;
- }
-}
-
-void KFileItem::setUDSEntry( const TDEIO::UDSEntry& _entry, const KURL& _url,
- bool _determineMimeTypeOnDemand, bool _urlIsDirectory )
-{
- m_entry = _entry;
- m_url = _url;
- m_strName = TQString::null;
- m_strText = TQString::null;
- m_user = TQString::null;
- m_group = TQString::null;
- m_strLowerCaseName = TQString::null;
- m_pMimeType = 0;
- m_fileMode = KFileItem::Unknown;
- m_permissions = KFileItem::Unknown;
- m_bMarked = false;
- m_bLink = false;
- m_bIsLocalURL = _url.isLocalFile();
- m_bMimeTypeKnown = false;
- m_hidden = Auto;
- m_guessedMimeType = TQString::null;
- m_metaInfo = KFileMetaInfo();
-
- if ( d )
- d->iconName = TQString::null;
-
- readUDSEntry( _urlIsDirectory );
- init( _determineMimeTypeOnDemand );
-}
-
-void KFileItem::setFileMode( mode_t m )
-{
- m_fileMode = m;
-}
-
-void KFileItem::setMimeType( const TQString& mimetype )
-{
- m_pMimeType = KMimeType::mimeType( mimetype );
-}
-
-void KFileItem::setExtraData( const void *key, void *value )
-{
- if ( !key )
- return;
-
- m_extra.replace( key, value );
-}
-
-const void * KFileItem::extraData( const void *key ) const
-{
- TQMapConstIterator<const void*,void*> it = m_extra.find( key );
- if ( it != m_extra.end() )
- return it.data();
- return 0L;
-}
-
-void * KFileItem::extraData( const void *key )
-{
- TQMapIterator<const void*,void*> it = m_extra.find( key );
- if ( it != m_extra.end() )
- return it.data();
- return 0L;
-}
-
-void KFileItem::removeExtraData( const void *key )
-{
- m_extra.remove( key );
-}
-
-TQString KFileItem::permissionsString() const
-{
- if (m_access.isNull())
- m_access = parsePermissions( m_permissions );
-
- return m_access;
-}
-
-TQString KFileItem::parsePermissions(mode_t perm) const
-{
- char p[] = "---------- ";
-
- if (isDir())
- p[0]='d';
- else if (isLink())
- p[0]='l';
-
- if (perm & TQFileInfo::ReadUser)
- p[1]='r';
- if (perm & TQFileInfo::WriteUser)
- p[2]='w';
- if ((perm & TQFileInfo::ExeUser) && !(perm & S_ISUID)) p[3]='x';
- else if ((perm & TQFileInfo::ExeUser) && (perm & S_ISUID)) p[3]='s';
- else if (!(perm & TQFileInfo::ExeUser) && (perm & S_ISUID)) p[3]='S';
-
- if (perm & TQFileInfo::ReadGroup)
- p[4]='r';
- if (perm & TQFileInfo::WriteGroup)
- p[5]='w';
- if ((perm & TQFileInfo::ExeGroup) && !(perm & S_ISGID)) p[6]='x';
- else if ((perm & TQFileInfo::ExeGroup) && (perm & S_ISGID)) p[6]='s';
- else if (!(perm & TQFileInfo::ExeGroup) && (perm & S_ISGID)) p[6]='S';
-
- if (perm & TQFileInfo::ReadOther)
- p[7]='r';
- if (perm & TQFileInfo::WriteOther)
- p[8]='w';
- if ((perm & TQFileInfo::ExeOther) && !(perm & S_ISVTX)) p[9]='x';
- else if ((perm & TQFileInfo::ExeOther) && (perm & S_ISVTX)) p[9]='t';
- else if (!(perm & TQFileInfo::ExeOther) && (perm & S_ISVTX)) p[9]='T';
-
- if (hasExtendedACL())
- p[10]='+';
-
- return TQString::fromLatin1(p);
-}
-
-// check if we need to cache this
-TQString KFileItem::timeString( unsigned int which ) const
-{
- bool hasTime;
- time_t time_ = time(which, hasTime);
- if(!hasTime) return TQString::null;
-
- TQDateTime t;
- t.setTime_t( time_);
- return TDEGlobal::locale()->formatDateTime( t );
-}
-
-void KFileItem::setMetaInfo( const KFileMetaInfo & info )
-{
- m_metaInfo = info;
-}
-
-const KFileMetaInfo & KFileItem::metaInfo(bool autoget, int) const
-{
- bool isLocalURL;
- KURL url = mostLocalURL(isLocalURL);
-
- if ( autoget && !m_metaInfo.isValid() &&
- TDEGlobalSettings::showFilePreview(url) )
- {
- m_metaInfo = KFileMetaInfo( url, mimetype() );
- }
-
- return m_metaInfo;
-}
-
-KURL KFileItem::mostLocalURL(bool &local) const
-{
- TQString local_path = localPath();
-
- if ( !local_path.isEmpty() )
- {
- local = true;
- KURL url;
- url.setPath(local_path);
- return url;
- }
- else
- {
- local = m_bIsLocalURL;
- return m_url;
- }
-}
-
-void KFileItem::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-TQDataStream & operator<< ( TQDataStream & s, const KFileItem & a )
-{
- // We don't need to save/restore anything that refresh() invalidates,
- // since that means we can re-determine those by ourselves.
- s << a.m_url;
- s << a.m_strName;
- s << a.m_strText;
- return s;
-}
-
-TQDataStream & operator>> ( TQDataStream & s, KFileItem & a )
-{
- s >> a.m_url;
- s >> a.m_strName;
- s >> a.m_strText;
- a.m_bIsLocalURL = a.m_url.isLocalFile();
- a.m_bMimeTypeKnown = false;
- a.refresh();
- return s;
-}
diff --git a/kio/kio/kfileitem.h b/kio/kio/kfileitem.h
deleted file mode 100644
index 0fcba9f4a..000000000
--- a/kio/kio/kfileitem.h
+++ /dev/null
@@ -1,671 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 1999 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kfileitem_h__
-#define __kfileitem_h__
-
-#include <tqstringlist.h>
-#include <sys/stat.h>
-
-#include <tqptrlist.h>
-#include <kio/global.h>
-#include <kurl.h>
-#include <kacl.h>
-#include <kmimetype.h>
-#include <kfilemetainfo.h>
-
-#define KFILEITEM_HAS_ISWRITABLE // only used in libkonq/konq_iconviewwidget.cc, will be removed for 3.4
-
-/**
- * A KFileItem is a generic class to handle a file, local or remote.
- * In particular, it makes it easier to handle the result of TDEIO::listDir
- * (UDSEntry isn't very friendly to use).
- * It includes many file attributes such as mimetype, icon, text, mode, link...
- */
-class TDEIO_EXPORT KFileItem
-{
-public:
- enum { Unknown = (mode_t) - 1 };
-
- /**
- * Creates an item representing a file, from a UDSEntry.
- * This is the preferred constructor when using TDEIO::listDir().
- *
- * @param _entry the KIO entry used to get the file, contains info about it
- * @param _url the file url
- * @param _determineMimeTypeOnDemand specifies if the mimetype of the given
- * URL should be determined immediately or on demand
- * @param _urlIsDirectory specifies if the url is just the directory of the
- * fileitem and the filename from the UDSEntry should be used.
- */
- KFileItem( const TDEIO::UDSEntry& _entry, const KURL& _url,
- bool _determineMimeTypeOnDemand = false,
- bool _urlIsDirectory = false );
-
- /**
- * Creates an item representing a file, from all the necessary info for it.
- * @param _mode the file mode (according to stat() (e.g. S_IFDIR...)
- * Set to KFileItem::Unknown if unknown. For local files, KFileItem will use stat().
- * @param _permissions the access permissions
- * If you set both the mode and the permissions, you save a ::stat() for
- * local files.
- * Set to KFileItem::Unknown if you don't know the mode or the permission.
- * @param _url the file url
- *
- * @param _determineMimeTypeOnDemand specify if the mimetype of the given URL
- * should be determined immediately or on demand
- */
- KFileItem( mode_t _mode, mode_t _permissions, const KURL& _url,
- bool _determineMimeTypeOnDemand = false );
-
- /**
- * Creates an item representing a file, for which the mimetype is already known.
- * @param url the file url
- * @param mimeType the name of the file's mimetype
- * @param mode the mode (S_IFDIR...)
- */
- KFileItem( const KURL &url, const TQString &mimeType, mode_t mode );
-
- /**
- * Copy constructor. Note that extra-data set via setExtraData() is not
- * deeply copied -- just the pointers are copied.
- */
- KFileItem( const KFileItem &item );
-
- /**
- * Destructs the KFileItem. Extra data set via setExtraData()
- * is not deleted.
- */
- virtual ~KFileItem();
-
- /**
- * Throw away and re-read (for local files) all information about the file.
- * This is called when the _file_ changes.
- */
- void refresh();
-
- /**
- * Re-reads mimetype information.
- * This is called when the mimetype database changes.
- */
- void refreshMimeType();
-
- /**
- * Returns the url of the file.
- * @return the url of the file
- */
- const KURL & url() const { return m_url; }
-
- /**
- * Sets the item's URL. Do not call unless you know what you are doing!
- * (used for example when an item got renamed).
- * @param url the item's URL
- */
- void setURL( const KURL &url );
-
- /**
- * Sets the item's name (i.e. the filename).
- * This is automatically done by setURL, to set the name from the URL's fileName().
- * This method is provided for some special cases like relative paths as names (KFindPart)
- * @param name the item's name
- */
- void setName( const TQString &name );
-
- /**
- * Returns the permissions of the file (stat.st_mode containing only permissions).
- * @return the permissions of the file
- */
- mode_t permissions() const { return m_permissions; }
-
- /**
- * Returns the access permissions for the file as a string.
- * @return the access persmission as string
- */
- TQString permissionsString() const;
-
- /**
- * Tells if the file has extended access level information ( Posix ACL )
- * @return true if the file has extend ACL information or false if it hasn't
- * @since 3.5
- */
- bool hasExtendedACL() const;
-
- /**
- * Returns the access control list for the file.
- * @return the access control list as a KACL
- * @since 3.5
- */
- KACL ACL() const;
-
- /**
- * Returns the default access control list for the directory.
- * @return the default access control list as a KACL
- * @since 3.5
- */
- KACL defaultACL() const;
-
- /**
- * Returns the file type (stat.st_mode containing only S_IFDIR, S_IFLNK, ...).
- * @return the file type
- */
- mode_t mode() const { return m_fileMode; }
-
- /**
- * Returns the owner of the file.
- * @return the file's owner
- */
- TQString user() const;
-
- /**
- * Returns the group of the file.
- * @return the file's group
- */
- TQString group() const;
-
- /**
- * Returns true if this item represents a link in the UNIX sense of
- * a link.
- * @return true if the file is a link
- */
- bool isLink() const { return m_bLink; }
-
- /**
- * Returns true if this item represents a directory.
- * @return true if the item is a directory
- */
- bool isDir() const;
-
- /**
- * Returns true if this item represents a file (and not a a directory)
- * @return true if the item is a file
- */
- bool isFile() const { return !isDir(); }
-
- /**
- * Checks whether the file or directory is readable. In some cases
- * (remote files), we may return true even though it can't be read.
- * @return true if the file can be read - more precisely,
- * false if we know for sure it can't
- */
- bool isReadable() const;
-
- /**
- * Checks whether the file or directory is writable. In some cases
- * (remote files), we may return true even though it can't be written to.
- * @return true if the file or directory can be written to - more precisely,
- * false if we know for sure it can't
- * @since 3.4
- */
- bool isWritable() const;
-
- /**
- * Checks whether the file is hidden.
- * @return true if the file is hidden.
- */
- bool isHidden() const;
-
- /**
- * Returns the link destination if isLink() == true.
- * @return the link destination. TQString::null if the item is not a link
- */
- TQString linkDest() const;
-
- /**
- * Returns the local path if isLocalFile() == true or the KIO item has
- * a UDS_LOCAL_PATH atom.
- * @return the item local path, or TQString::null if not known
- * @since 3.4
- */
- TQString localPath() const;
-
- //FIXME KDE4 deprecate this in favor of size(bool &hasSize)
- /**
- * Returns the size of the file, if known.
- * @return the file size, or 0 if not known
- */
- TDEIO::filesize_t size() const;
-
- /**
- * Returns the size of the file, if known, and sets @p hasSize to false if not known
- * @param @hasSize This is set to true if the size is known, and false if not known
- * @return the file size, or 0 if not known
- */
- TDEIO::filesize_t size(bool &hasSize) const;
-
- //FIXME KDE4 deprecate this in favor of time(unsigned int which, bool &hasSize)
- /**
- * Requests the modification, access or creation time, depending on @p which.
- * @param which UDS_MODIFICATION_TIME, UDS_ACCESS_TIME or UDS_CREATION_TIME
- * @return the time asked for, (time_t)0 if not available
- * @see timeString()
- */
- time_t time( unsigned int which ) const;
-
- /**
- * Requests the modification, access or creation time, depending on @p which.
- * @param which UDS_MODIFICATION_TIME, UDS_ACCESS_TIME or UDS_CREATION_TIME
- * @param hasTime This is set to true is the time is known, and false if not known
- * @return the time asked for, (time_t)0 if not known/available
- * @see timeString()
- */
- time_t time( unsigned int which, bool &hasTime ) const;
-
- /**
- * Requests the modification, access or creation time as a string, depending
- * on @p which.
- * @param which UDS_MODIFICATION_TIME, UDS_ACCESS_TIME or UDS_CREATION_TIME
- * @returns a formatted string of the requested time, TQString::null if time is not known
- * @see time
- */
- TQString timeString( unsigned int which = TDEIO::UDS_MODIFICATION_TIME ) const;
-
- /**
- * Returns true if the file is a local file.
- * @return true if the file is local, false otherwise
- */
- bool isLocalFile() const { return m_bIsLocalURL; }
-
- /**
- * Returns the text of the file item.
- * It's not exactly the filename since some decoding happens ('%2F'->'/').
- * @return the text of the file item
- */
- const TQString& text() const { return m_strText; }
-
- /**
- * Return the name of the file item (without a path).
- * Similar to text(), but unencoded, i.e. the original name.
- * @param lowerCase if true, the name will be returned in lower case,
- * which is useful to speed up sorting by name, case insensitively.
- * @return the file's name
- */
- const TQString& name( bool lowerCase = false ) const {
- if ( !lowerCase )
- return m_strName;
- else
- if ( m_strLowerCaseName.isNull() )
- m_strLowerCaseName = m_strName.lower();
- return m_strLowerCaseName;
- }
-
- /**
- * Returns the mimetype of the file item.
- * If @p _determineMimeTypeOnDemand was used in the constructor, this will determine
- * the mimetype first. Equivalent to determineMimeType()->name()
- * @return the mime type of the file
- */
- TQString mimetype() const;
-
- /**
- * Returns the mimetype of the file item.
- * If _determineMimeTypeOnDemand was used in the constructor, this will determine
- * the mimetype first.
- * @return the mime type
- */
- KMimeType::Ptr determineMimeType();
-
- /**
- * Returns the currently known mimetype of the file item.
- * This will not try to determine the mimetype if unknown.
- * @return the known mime type
- */
- KMimeType::Ptr mimeTypePtr() const { return m_pMimeType; }
-
- bool isMimeTypeKnown() const;
- /**
- * Returns the descriptive comment for this mime type, or
- * the mime type itself if none is present.
- * @return the mime type description, or the mime type itself
- */
- TQString mimeComment();
-
- /**
- * Returns the full path name to the icon that represents
- * this mime type.
- * @return iconName the name of the file's icon
- */
- TQString iconName();
-
- /**
- * Returns a pixmap representing the file.
- * @param _size Size for the pixmap in pixels. Zero will return the
- * globally configured default size.
- * @param _state The state of the icon: KIcon::DefaultState,
- * KIcon::ActiveState or KIcon::DisabledState.
- * @return the pixmap
- */
- TQPixmap pixmap( int _size, int _state=0 ) const;
-
- /**
- * Returns the overlays (bitfield of KIcon::*Overlay flags) that are used
- * for this item's pixmap. Overlays are used to show for example, whether
- * a file can be modified.
- * @return the overlays of the pixmap
- */
- int overlays() const;
-
- /**
- * Returns the string to be displayed in the statusbar,
- * e.g. when the mouse is over this item
- * @return the status bar information
- */
- TQString getStatusBarInfo();
-
- /**
- * Returns the string to be displayed in the tool tip when the mouse
- * is over this item. This may load a plugin to determine additional
- * information specific to the mimetype of the file.
- *
- * @param maxcount the maximum number of entries shown
- * @return the tool tip string
- */
- TQString getToolTipText(int maxcount = 6);
-
- /**
- * Returns true if files can be dropped over this item.
- * Contrary to popular belief, not only dirs will return true :)
- * Executables, .desktop files, will do so as well.
- * @return true if you can drop files over the item
- */
- bool acceptsDrops( );
-
- /**
- * Let's "KRun" this file !
- * (e.g. when file is clicked or double-clicked or return is pressed)
- */
- void run();
-
- /**
- * Returns the UDS entry. Used by the tree view to access all details
- * by position.
- * @return the UDS entry
- */
- const TDEIO::UDSEntry & entry() const { return m_entry; }
-
- /**
- * Used when updating a directory. marked == seen when refreshing.
- * @return true if the file item is marked
- */
- bool isMarked() const { return m_bMarked; }
- /**
- * Marks the item.
- * @see isMarked()
- */
- void mark() { m_bMarked = true; }
- /**
- * Unmarks the item.
- * @see isMarked()
- */
- void unmark() { m_bMarked = false; }
-
- /**
- * Somewhat like a comparison operator, but more explicit.
- * @param item the item to compare
- * @return true if all values are equal
- */
- bool cmp( const KFileItem & item );
-
- /**
- * This allows to associate some "extra" data to a KFileItem. As one
- * KFileItem can be used by several objects (often views) which all need
- * to add some data, you have to use a key to reference your extra data
- * within the KFileItem.
- *
- * That way a KFileItem can hold and provide access to all those views
- * separately.
- *
- * I.e. a KFileIconView that associates a KFileIconViewItem (an item suitable
- * for use with TQIconView) does
- *
- * \code
- * kfileItem->setExtraData( this, iconViewItem );
- * \endcode
- *
- * and can later access the iconViewItem by doing
- *
- * \code
- * KFileIconViewItem *iconViewItem = static_cast<KFileIconViewItem*>( kfileItem->extraData( this ));
- * \endcode
- *
- * This is usually more efficient then having every view associate data to
- * items by using a separate TQDict or TQMap.
- *
- * Note: you have to remove and destroy the data you associated yourself
- * when you don't need it anymore!
- *
- * @param key the key of the extra data
- * @param value the value of the extra data
- * @see extraData
- * @see removeExtraData
- */
- virtual void setExtraData( const void *key, void *value );
-
- /**
- * Retrieves the extra data with the given @p key.
- * @param key the key of the extra data
- * @return the extra data associated to an item with @p key via
- * setExtraData. 0L if nothing was associated with @p key.
- * @see extraData
- */
- virtual const void * extraData( const void *key ) const;
-
- /**
- * Retrieves the extra data with the given @p key.
- * @param key the key of the extra data
- * @return the extra data associated to an item with @p key via
- * setExtraData. 0L if nothing was associated with @p key.
- * @see extraData
- */
- virtual void * extraData( const void *key );
-
- /**
- * Removes the extra data associated with an item via @p key.
- * @param key the key of the extra data to remove
- */
- virtual void removeExtraData( const void *key );
-
- /**
- * Sets the metainfo of this item to @p info.
- * @param info the new meta info
- */
- void setMetaInfo( const KFileMetaInfo & info );
-
- /**
- * Sets the file type (stat.st_mode containing only S_IFDIR, S_IFLNK, ...).
- * @param m the new file type
- * @since 3.5.0
- * @todo Actually explain what this does -- does setting S_IFDIR
- * mean the file type is set to Directory?
- */
- void setFileMode( mode_t m );
-
- /**
- * Sets new mimetype for item
- * @param mimetype the new mimetype
- * @since 3.5.0
- */
- void setMimeType( const TQString& mimetype );
-
- /**
- * Returns the metainfo of this item.
- * @param autoget if true, the metainfo will automatically be created
- * @param what ignored
- */
- const KFileMetaInfo & metaInfo(bool autoget = true,
- int what = KFileMetaInfo::Fastest) const;
-
- /**
- * Somewhat like an assignment operator, but more explicit.
- * Note: extra-data set with setExtraData() is not copied, so be careful
- * what you do!
- *
- * @param item the item to copy
- */
- void assign( const KFileItem & item );
-
- /**
- * Reinitialize KFileItem with a new UDSEntry.
- *
- * Note: extra-data set with setExtraData() is not changed or deleted, so
- * be careful what you do!
- *
- * KDirListerCache uses it to save new/delete calls by updating existing
- * items that are otherwise not needed anymore.
- *
- * @param entry the UDSEntry to assign to this KFileItem
- * @param url the file url
- * @param determineMimeTypeOnDemand specifies if the mimetype of the given
- * URL should be determined immediately or on demand
- * @param urlIsDirectory specifies if the url is just the directory of the
- * fileitem and the filename from the UDSEntry should be used.
- * @since 3.4.1
- */
- void setUDSEntry( const TDEIO::UDSEntry& entry, const KURL& url,
- bool determineMimeTypeOnDemand = false,
- bool urlIsDirectory = false );
-
- /**
- * Assignment operator, calls assign()
- */
- KFileItem& operator=( const KFileItem& );
-
- /**
- * Tries to give a local URL for this file item if possible.
- * The given boolean indicates if the returned url is local or not.
- */
- KURL mostLocalURL(bool &local) const;
-
- /////////////
-
-protected:
- /**
- * Computes the text, mode, and mimetype from the UDSEntry
- * Called by constructor, but can be called again later
- */
- void init( bool _determineMimeTypeOnDemand );
-
- /**
- * Extracts the data from the UDSEntry member and updates the KFileItem
- * accordingly.
- * @since 3.4.1
- */
- void readUDSEntry( bool _urlIsDirectory );
-
- /**
- * Parses the given permission set and provides it for access()
- */
- TQString parsePermissions( mode_t perm ) const;
-
-private:
- /**
- * We keep a copy of the UDSEntry since we need it for getStatusBarInfo
- */
- TDEIO::UDSEntry m_entry;
- /**
- * The url of the file
- */
- KURL m_url;
-
- /**
- * The text for this item, i.e. the file name without path,
- */
- TQString m_strName;
-
- /**
- * The text for this item, i.e. the file name without path, decoded
- * ('%%' becomes '%', '%2F' becomes '/')
- */
- TQString m_strText;
-
- /**
- * the user and group assigned to the file.
- */
- mutable TQString m_user, m_group;
-
- /**
- * The filename in lower case (to speed up sorting)
- */
- mutable TQString m_strLowerCaseName;
-
- /**
- * The mimetype of the file
- */
- KMimeType::Ptr m_pMimeType;
-
- /**
- * The file mode
- */
- mode_t m_fileMode;
- /**
- * The permissions
- */
- mode_t m_permissions;
-
- /**
- * Marked : see mark()
- */
- bool m_bMarked:1;
- /**
- * Whether the file is a link
- */
- bool m_bLink:1;
- /**
- * True if local file
- */
- bool m_bIsLocalURL:1;
-
- bool m_bMimeTypeKnown:1;
-
- // Auto: check leading dot.
- enum { Auto, Hidden, Shown } m_hidden:3;
-
- // For special case like link to dirs over FTP
- TQString m_guessedMimeType;
- mutable TQString m_access;
- TQMap<const void*, void*> m_extra;
- mutable KFileMetaInfo m_metaInfo;
-
- enum { Modification = 0, Access = 1, Creation = 2, NumFlags = 3 };
- mutable time_t m_time[3];
- mutable TDEIO::filesize_t m_size;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KFileItemPrivate;
- KFileItemPrivate * d;
- TDEIO_EXPORT friend TQDataStream & operator<< ( TQDataStream & s, const KFileItem & a );
- TDEIO_EXPORT friend TQDataStream & operator>> ( TQDataStream & s, KFileItem & a );
-};
-
-/**
- * List of KFileItems
- */
-typedef TQPtrList<KFileItem> KFileItemList;
-
-/**
- * Iterator for KFileItemList
- */
-typedef TQPtrListIterator<KFileItem> KFileItemListIterator;
-
-TDEIO_EXPORT TQDataStream & operator<< ( TQDataStream & s, const KFileItem & a );
-TDEIO_EXPORT TQDataStream & operator>> ( TQDataStream & s, KFileItem & a );
-
-
-#endif
diff --git a/kio/kio/kfilemetainfo.cpp b/kio/kio/kfilemetainfo.cpp
deleted file mode 100644
index a5d34fa07..000000000
--- a/kio/kio/kfilemetainfo.cpp
+++ /dev/null
@@ -1,1859 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (C) 2001-2002 Rolf Magnus <ramagnus@kde.org>
- * Copyright (C) 2001-2002 Carsten Pfeiffer <pfeiffer@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation version 2.0.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- * $Id$
- */
-
-#include <assert.h>
-
-#include <tqshared.h>
-#include <tqdict.h>
-
-#include <ktrader.h>
-#include <kstaticdeleter.h>
-#include <tdeparts/componentfactory.h>
-#include <kuserprofile.h>
-#include <kdebug.h>
-#include <kmimetype.h>
-#include <kdatastream.h> // needed for serialization of bool
-#include <klocale.h>
-#include <kio/global.h>
-
-#include "kfilemetainfo.h"
-
-// shared data of a KFileMetaInfoItem
-class KFileMetaInfoItem::Data : public TQShared
-{
-public:
- Data( const KFileMimeTypeInfo::ItemInfo* mti, const TQString& _key,
- const TQVariant& _value )
- : TQShared(),
- mimeTypeInfo( mti ),
- key( _key ),
- value( _value ),
- dirty( false ),
- added( false ),
- removed( false )
- {}
-
- // we use this one for the streaming operators
- Data() : mimeTypeInfo( 0L )
- {}
-
- ~Data()
- {
- if ( this == null ) // only the null item owns its mimeTypeInfo
- delete mimeTypeInfo;
- }
-
- const KFileMimeTypeInfo::ItemInfo* mimeTypeInfo;
- // mimeTypeInfo has the key, too, but only for non-variable ones
- TQString key;
- TQVariant value;
- bool dirty :1;
- bool added :1;
- bool removed :1;
-
- static Data* null;
- static Data* makeNull();
-};
-
-//this is our null data
-KFileMetaInfoItem::Data* KFileMetaInfoItem::Data::null = 0L;
-static KStaticDeleter<KFileMetaInfoItem::Data> sd_KFileMetaInfoItemData;
-
-KFileMetaInfoItem::Data* KFileMetaInfoItem::Data::makeNull()
-{
- if (!null)
- {
- // We deliberately do not reset "null" after it has been destroyed!
- // Otherwise we will run into problems later in ~KFileMetaInfoItem
- // where the d-pointer is compared against null.
-
- KFileMimeTypeInfo::ItemInfo* info = new KFileMimeTypeInfo::ItemInfo();
- null = new Data(info, TQString::null, TQVariant());
- sd_KFileMetaInfoItemData.setObject( null );
- }
- return null;
-}
-
-KFileMetaInfoItem::KFileMetaInfoItem( const KFileMimeTypeInfo::ItemInfo* mti,
- const TQString& key, const TQVariant& value )
- : d( new Data( mti, key, value ) )
-{
-}
-
-KFileMetaInfoItem::KFileMetaInfoItem( const KFileMetaInfoItem& item )
-{
- // operator= does everything that's necessary
- d = Data::makeNull();
- *this = item;
-}
-
-KFileMetaInfoItem::KFileMetaInfoItem()
-{
- d = Data::makeNull();
-}
-
-KFileMetaInfoItem::~KFileMetaInfoItem()
-{
- deref();
-}
-
-const KFileMetaInfoItem& KFileMetaInfoItem::operator=
- (const KFileMetaInfoItem & item )
-{
- if (d != item.d)
- {
- // first deref the old one
- deref();
- d = item.d;
- // and now ref the new one
- ref();
- }
-
- return *this;
-}
-
-bool KFileMetaInfoItem::setValue( const TQVariant& value )
-{
- // We don't call makeNull here since it isn't necassery, see deref()
- if ( d == Data::null ) return false;
-
- if ( ! (d->mimeTypeInfo->attributes() & KFileMimeTypeInfo::Modifiable ) ||
- ! (value.canCast(d->mimeTypeInfo->type())))
- {
- kdDebug(7033) << "setting the value of " << key() << "failed\n";
- return false;
- }
-
-// kdDebug(7033) << key() << ".setValue()\n";
-
- if ( d->value == value )
- return true;
-
- d->dirty = true;
- d->value = value;
- // If we don't cast (and test for canCast in the above if), TQVariant is
- // very picky about types (e.g. TQString vs. TQCString or int vs. uint)
- d->value.cast(d->mimeTypeInfo->type());
-
- return true;
-}
-
-bool KFileMetaInfoItem::isRemoved() const
-{
- return d->removed;
-}
-
-TQString KFileMetaInfoItem::key() const
-{
- return d->key;
-}
-
-TQString KFileMetaInfoItem::translatedKey() const
-{
- // are we a variable key?
- if (d->mimeTypeInfo->key().isNull())
- {
- // then try if we have luck with i18n()
- return i18n(d->key.utf8());
- }
-
- return d->mimeTypeInfo->translatedKey();
-}
-
-const TQVariant& KFileMetaInfoItem::value() const
-{
- return d->value;
-}
-
-TQString KFileMetaInfoItem::string( bool mangle ) const
-{
- return d->mimeTypeInfo->string(d->value, mangle);
-}
-
-TQVariant::Type KFileMetaInfoItem::type() const
-{
- return d->mimeTypeInfo->type();
-}
-
-uint KFileMetaInfoItem::unit() const
-{
- return d->mimeTypeInfo->unit();
-}
-
-bool KFileMetaInfoItem::isModified() const
-{
- return d->dirty;
-}
-
-TQString KFileMetaInfoItem::prefix() const
-{
- return d->mimeTypeInfo->prefix();
-}
-
-TQString KFileMetaInfoItem::suffix() const
-{
- return d->mimeTypeInfo->suffix();
-}
-
-uint KFileMetaInfoItem::hint() const
-{
- return d->mimeTypeInfo->hint();
-}
-
-uint KFileMetaInfoItem::attributes() const
-{
- return d->mimeTypeInfo->attributes();
-}
-
-bool KFileMetaInfoItem::isEditable() const
-{
- return d->mimeTypeInfo->attributes() & KFileMimeTypeInfo::Modifiable;
-}
-
-bool KFileMetaInfoItem::isValid() const
-{
- // We don't call makeNull here since it isn't necassery:
- // If d is equal to null it means that null is initialized already.
- // null is 0L when it hasn't been initialized and d is never 0L.
- return d != Data::null;
-}
-
-void KFileMetaInfoItem::setAdded()
-{
- d->added = true;
-}
-
-void KFileMetaInfoItem::setRemoved()
-{
- d->removed = true;
-}
-
-void KFileMetaInfoItem::ref()
-{
- if (d != Data::null) d->ref();
-}
-
-void KFileMetaInfoItem::deref()
-{
- // We don't call makeNull here since it isn't necassery:
- // If d is equal to null it means that null is initialized already.
- // null is 0L when it hasn't been initialized and d is never 0L.
- if ((d != Data::null) && d->deref())
- {
-// kdDebug(7033) << "item " << d->key
-// << " is finally deleted\n";
- delete d;
- d = 0;
- }
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-// shared data of a KFileMetaInfo
-class KFileMetaInfo::Data : public TQShared
-{
-public:
- Data(const KURL& _url, uint _what)
- : TQShared(),
- url(_url),
- what(_what),
- mimeTypeInfo( 0L )
- {}
-
- // wee use this one for the streaming operators
- Data() {};
-
- KURL url;
- uint what;
- TQMap<TQString, KFileMetaInfoGroup> groups;
- const KFileMimeTypeInfo* mimeTypeInfo;
- TQStringList removedGroups;
-
- static Data* null;
- static Data* makeNull();
-
-};
-
-KFileMetaInfo::KFileMetaInfo( const TQString& path, const TQString& mimeType,
- uint what )
-{
- KURL u;
-
- u.setPath(path);
- init(u, mimeType, what);
-}
-
-KFileMetaInfo::KFileMetaInfo( const KURL& url, const TQString& mimeType,
- uint what )
-{
- init(url, mimeType, what);
-}
-
-void KFileMetaInfo::init( const KURL& url, const TQString& mimeType,
- uint what )
-{
- d = new Data( url, what );
-
- TQString mT;
- if (mimeType.isEmpty())
- mT = KMimeType::findByURL(url)->name();
- else
- mT = mimeType;
-
- // let's "share our property"
- KFileMetaInfo item(*this);
-
- //kdDebug() << k_funcinfo << mT << " " << url << endl;
-
- d->mimeTypeInfo = KFileMetaInfoProvider::self()->mimeTypeInfo( mT, url.protocol() );
- if ( d->mimeTypeInfo )
- {
- //kdDebug(7033) << "Found mimetype info for " << mT /* or protocol*/ << endl;
- KFilePlugin *p = plugin();
- Q_ASSERT( p );
- if ( p && !p->readInfo( item, what) )
- {
- deref();
- d = Data::makeNull();
- }
- }
- else
- {
-// kdDebug(7033) << "No mimetype info for " << mimeType << endl;
- deref();
- d = Data::makeNull();
- }
-}
-
-KFileMetaInfo::KFileMetaInfo( const KFileMetaInfo& original )
-{
- // operator= does everything that's necessary
- d = Data::makeNull();
- *this = original;
-}
-
-KFileMetaInfo::KFileMetaInfo()
-{
- d = Data::makeNull();
-}
-
-KFileMetaInfo::~KFileMetaInfo()
-{
- deref();
-}
-
-TQStringList KFileMetaInfo::supportedGroups() const
-{
- assert(isValid());
- return d->mimeTypeInfo->supportedGroups();
-}
-
-TQStringList KFileMetaInfo::supportedKeys() const
-{
- assert(isValid());
- return d->mimeTypeInfo->supportedKeys();
-}
-
-TQStringList KFileMetaInfo::groups() const
-{
- TQStringList list;
- TQMapConstIterator<TQString, KFileMetaInfoGroup> it = d->groups.begin();
- for ( ; it != d->groups.end(); ++it )
- list += (*it).name();
-
- return list;
-}
-
-TQStringList KFileMetaInfo::editableGroups() const
-{
- TQStringList list;
- TQStringList supported = supportedGroups();
- TQStringList::ConstIterator it = supported.begin();
- for ( ; it != supported.end(); ++it ) {
- const KFileMimeTypeInfo::GroupInfo * groupInfo = d->mimeTypeInfo->groupInfo( *it );
- if ( groupInfo && groupInfo->attributes() &
- (KFileMimeTypeInfo::Addable | KFileMimeTypeInfo::Removable) )
- list.append( *it );
- }
-
- return list;
-}
-
-TQStringList KFileMetaInfo::preferredGroups() const
-{
- assert(isValid());
- TQStringList list = groups();
- TQStringList newlist;
- TQStringList preferred = d->mimeTypeInfo->preferredGroups();
- TQStringList::Iterator pref;
-
- // move all keys from the preferred groups that are in our list to a new list
- for ( pref = preferred.begin(); pref != preferred.end(); ++pref )
- {
- TQStringList::Iterator group = list.find(*pref);
- if ( group != list.end() )
- {
- newlist.append( *group );
- list.remove(group);
- }
- }
-
- // now the old list only contains the non-preferred items, so we
- // add the remaining ones to newlist
- newlist += list;
-
- return newlist;
-}
-
-TQStringList KFileMetaInfo::preferredKeys() const
-{
- TQStringList newlist;
-
- TQStringList list = preferredGroups();
- for (TQStringList::Iterator git = list.begin(); git != list.end(); ++git)
- {
- newlist += d->groups[*git].preferredKeys();
- }
-
- return newlist;
-}
-
-KFileMetaInfoGroup KFileMetaInfo::group(const TQString& key) const
-{
- TQMapIterator<TQString,KFileMetaInfoGroup> it = d->groups.find( key );
- if ( it != d->groups.end() )
- return it.data();
- else
- return KFileMetaInfoGroup();
-}
-
-bool KFileMetaInfo::addGroup( const TQString& name )
-{
- assert(isValid());
- if ( d->mimeTypeInfo->supportedGroups().contains(name) &&
- ! d->groups.contains(name) )
- {
- KFileMetaInfoGroup group( name, d->mimeTypeInfo );
-
- // add all the items that can't be added by the user later
- const KFileMimeTypeInfo::GroupInfo* ginfo = d->mimeTypeInfo->groupInfo(name);
- Q_ASSERT(ginfo);
- if (!ginfo) return false;
-
- TQStringList keys = ginfo->supportedKeys();
- for (TQStringList::Iterator it = keys.begin(); it != keys.end(); ++it)
- {
- const KFileMimeTypeInfo::ItemInfo* iteminfo = ginfo->itemInfo(*it);
- Q_ASSERT(ginfo);
- if (!iteminfo) return false;
-
- if ( !(iteminfo->attributes() & KFileMimeTypeInfo::Addable) &&
- (iteminfo->attributes() & KFileMimeTypeInfo::Modifiable))
- {
- // append it now or never
- group.appendItem(iteminfo->key(), TQVariant());
- }
-
- }
-
- d->groups.insert(name, group);
- group.setAdded();
- return true;
- }
-
- return false;
-}
-
-bool KFileMetaInfo::removeGroup( const TQString& name )
-{
- TQMapIterator<TQString, KFileMetaInfoGroup> it = d->groups.find(name);
- if ( (it==d->groups.end()) ||
- !((*it).attributes() & KFileMimeTypeInfo::Removable))
- return false;
-
- d->groups.remove(it);
- d->removedGroups.append(name);
- return true;
-}
-
-TQStringList KFileMetaInfo::removedGroups()
-{
- return d->removedGroups;
-}
-
-const KFileMetaInfo& KFileMetaInfo::operator= (const KFileMetaInfo& info )
-{
- if (d != info.d)
- {
- deref();
- // first deref the old one
- d = info.d;
- // and now ref the new one
- ref();
- }
- return *this;
-}
-
-bool KFileMetaInfo::isValid() const
-{
- // We don't call makeNull here since it isn't necassery, see deref()
- return d != Data::null;
-}
-
-bool KFileMetaInfo::isEmpty() const
-{
- for (TQMapIterator<TQString, KFileMetaInfoGroup> it = d->groups.begin();
- it!=d->groups.end(); ++it)
- if (!(*it).isEmpty())
- return false;
- return true;
-}
-
-bool KFileMetaInfo::applyChanges()
-{
- return applyChanges( path() );
-}
-
-bool KFileMetaInfo::applyChanges( const TQString& path )
-{
- bool doit = false;
-
-// kdDebug(7033) << "KFileMetaInfo::applyChanges()\n";
-
- // look up if we need to write to the file
- TQMapConstIterator<TQString, KFileMetaInfoGroup> it;
- for (it = d->groups.begin(); it!=d->groups.end() && !doit; ++it)
- {
- if ( (*it).isModified() )
- doit = true;
-
- else
- {
- TQStringList keys = it.data().keys();
- for (TQStringList::Iterator it2 = keys.begin(); it2!=keys.end(); ++it2)
- {
- if ( (*it)[*it2].isModified() )
- {
- doit = true;
- break;
- }
- }
- }
- }
-
- if (!doit)
- {
- kdDebug(7033) << "Don't need to write, nothing changed\n";
- return true;
- }
-
- KFilePlugin* p = plugin();
- if (!p) return false;
-
-// kdDebug(7033) << "Ok, trying to write the info\n";
-
- KURL savedURL = url();
- d->url = KURL();
- d->url.setPath( path );
-
- bool ret = p->writeInfo(*this);
-
- d->url = savedURL;
- return ret;
-}
-
-KFilePlugin * KFileMetaInfo::plugin() const
-{
- assert(isValid());
- KFileMetaInfoProvider* prov = KFileMetaInfoProvider::self();
- return prov->plugin( d->mimeTypeInfo->mimeType(), d->url.protocol() );
-}
-
-TQString KFileMetaInfo::mimeType() const
-{
- assert(isValid());
- return d->mimeTypeInfo->mimeType();
-}
-
-bool KFileMetaInfo::contains(const TQString& key) const
-{
- TQStringList glist = groups();
- for (TQStringList::Iterator it = glist.begin(); it != glist.end(); ++it)
- {
- KFileMetaInfoGroup g = d->groups[*it];
- if (g.contains(key)) return true;
- }
- return false;
-}
-
-bool KFileMetaInfo::containsGroup(const TQString& key) const
-{
- return groups().contains(key);
-}
-
-KFileMetaInfoItem KFileMetaInfo::item( const TQString& key) const
-{
- TQStringList groups = preferredGroups();
- for (TQStringList::Iterator it = groups.begin(); it != groups.end(); ++it)
- {
- KFileMetaInfoItem i = d->groups[*it][key];
- if (i.isValid()) return i;
- }
- return KFileMetaInfoItem();
-}
-
-KFileMetaInfoItem KFileMetaInfo::item(const KFileMetaInfoItem::Hint hint) const
-{
- TQStringList groups = preferredGroups();
- TQStringList::ConstIterator it;
- for (it = groups.begin(); it != groups.end(); ++it)
- {
- KFileMetaInfoItem i = d->groups[*it].item(hint);
- if (i.isValid()) return i;
- }
- return KFileMetaInfoItem();
-}
-
-KFileMetaInfoItem KFileMetaInfo::saveItem( const TQString& key,
- const TQString& preferredGroup,
- bool createGroup )
-{
- assert(isValid());
- // try the preferred groups first
- if ( !preferredGroup.isEmpty() ) {
- TQMapIterator<TQString,KFileMetaInfoGroup> it =
- d->groups.find( preferredGroup );
-
- // try to create the preferred group, if necessary
- if ( it == d->groups.end() && createGroup ) {
- const KFileMimeTypeInfo::GroupInfo *groupInfo =
- d->mimeTypeInfo->groupInfo( preferredGroup );
- if ( groupInfo && groupInfo->supportedKeys().contains( key ) ) {
- if ( addGroup( preferredGroup ) )
- it = d->groups.find( preferredGroup );
- }
- }
-
- if ( it != d->groups.end() ) {
- KFileMetaInfoItem item = it.data().addItem( key );
- if ( item.isValid() )
- return item;
- }
- }
-
- TQStringList groups = preferredGroups();
-
- KFileMetaInfoItem item;
-
- TQStringList::ConstIterator groupIt = groups.begin();
- for ( ; groupIt != groups.end(); ++groupIt )
- {
- TQMapIterator<TQString,KFileMetaInfoGroup> it = d->groups.find( *groupIt );
- if ( it != d->groups.end() )
- {
- KFileMetaInfoGroup group = it.data();
- item = findEditableItem( group, key );
- if ( item.isValid() )
- return item;
- }
- else // not existant -- try to create the group
- {
- const KFileMimeTypeInfo::GroupInfo *groupInfo =
- d->mimeTypeInfo->groupInfo( *groupIt );
- if ( groupInfo && groupInfo->supportedKeys().contains( key ) )
- {
- if ( addGroup( *groupIt ) )
- {
- KFileMetaInfoGroup group = d->groups[*groupIt];
- KFileMetaInfoItem item = group.addItem( key );
- if ( item.isValid() )
- return item;
-// else ### add when removeGroup() is implemented :)
-// removeGroup( *groupIt ); // couldn't add item -> remove
- }
- }
- }
- }
-
- // finally check for variable items
-
- return item;
-}
-
-KFileMetaInfoItem KFileMetaInfo::findEditableItem( KFileMetaInfoGroup& group,
- const TQString& key )
-{
- assert(isValid());
- KFileMetaInfoItem item = group.addItem( key );
- if ( item.isValid() && item.isEditable() )
- return item;
-
- if ( (d->mimeTypeInfo->groupInfo( group.name() )->attributes() & KFileMimeTypeInfo::Addable) )
- return item;
-
- return KFileMetaInfoItem();
-}
-
-KFileMetaInfoGroup KFileMetaInfo::appendGroup(const TQString& name)
-{
- assert(isValid());
- if ( d->mimeTypeInfo->supportedGroups().contains(name) &&
- ! d->groups.contains(name) )
- {
- KFileMetaInfoGroup group( name, d->mimeTypeInfo );
- d->groups.insert(name, group);
- return group;
- }
-
- else {
- kdWarning(7033) << "Someone's trying to add a KFileMetaInfoGroup which is not supported or already existing: " << name << endl;
- return KFileMetaInfoGroup();
- }
-}
-
-TQString KFileMetaInfo::path() const
-{
- return d->url.isLocalFile() ? d->url.path() : TQString::null;
-}
-
-KURL KFileMetaInfo::url() const
-{
- return d->url;
-}
-
-void KFileMetaInfo::ref()
-{
- if (d != Data::null) d->ref();
-
-}
-
-void KFileMetaInfo::deref()
-{
- // We don't call makeNull here since it isn't necassery:
- // If d is equal to null it means that null is initialized already.
- // null is 0L when it hasn't been initialized and d is never 0L.
- if ((d != Data::null) && d->deref())
- {
-// kdDebug(7033) << "metainfo object for " << d->url.path << " is finally deleted\n";
- delete d;
- d = 0;
- }
-
-}
-
-
-KFileMetaInfo::Data* KFileMetaInfo::Data::null = 0L;
-static KStaticDeleter<KFileMetaInfo::Data> sd_KFileMetaInfoData;
-
-KFileMetaInfo::Data* KFileMetaInfo::Data::makeNull()
-{
- if (!null)
- // We deliberately do not reset "null" after it has been destroyed!
- // Otherwise we will run into problems later in ~KFileMetaInfoItem
- // where the d-pointer is compared against null.
- null = sd_KFileMetaInfoData.setObject( new KFileMetaInfo::Data(KURL(), 0) );
- return null;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-KFilePlugin::KFilePlugin( TQObject *parent, const char *name,
- const TQStringList& /*args*/)
- : TQObject( parent, name )
-{
-// kdDebug(7033) << "loaded a plugin for " << name << endl;
-}
-
-KFilePlugin::~KFilePlugin()
-{
-// kdDebug(7033) << "unloaded a plugin for " << name() << endl;
-}
-
-KFileMimeTypeInfo * KFilePlugin::addMimeTypeInfo( const TQString& mimeType )
-{
- return KFileMetaInfoProvider::self()->addMimeTypeInfo( mimeType );
-}
-
-void KFilePlugin::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-
-KFileMimeTypeInfo::GroupInfo* KFilePlugin::addGroupInfo(KFileMimeTypeInfo* info,
- const TQString& key, const TQString& translatedKey) const
-{
- return info->addGroupInfo(key, translatedKey);
-}
-
-void KFilePlugin::setAttributes(KFileMimeTypeInfo::GroupInfo* gi, uint attr) const
-{
- gi->m_attr = attr;
-}
-
-void KFilePlugin::addVariableInfo(KFileMimeTypeInfo::GroupInfo* gi,
- TQVariant::Type type, uint attr) const
-{
- gi->addVariableInfo(type, attr);
-}
-
-KFileMimeTypeInfo::ItemInfo* KFilePlugin::addItemInfo(KFileMimeTypeInfo::GroupInfo* gi,
- const TQString& key,
- const TQString& translatedKey,
- TQVariant::Type type)
-{
- return gi->addItemInfo(key, translatedKey, type);
-}
-
-void KFilePlugin::setAttributes(KFileMimeTypeInfo::ItemInfo* item, uint attr)
-{
- item->m_attr = attr;
-}
-
-void KFilePlugin::setHint(KFileMimeTypeInfo::ItemInfo* item, uint hint)
-{
- item->m_hint = hint;
-}
-
-void KFilePlugin::setUnit(KFileMimeTypeInfo::ItemInfo* item, uint unit)
-{
- item->m_unit = unit;
- // set prefix and suffix
- switch (unit)
- {
- case KFileMimeTypeInfo::Seconds:
- item->m_suffix = i18n("s"); break;
-
- case KFileMimeTypeInfo::MilliSeconds:
- item->m_suffix = i18n("ms"); break;
-
- case KFileMimeTypeInfo::BitsPerSecond:
- item->m_suffix = i18n("bps"); break;
-
- case KFileMimeTypeInfo::Pixels:
- item->m_suffix = i18n("pixels"); break;
-
- case KFileMimeTypeInfo::Inches:
- item->m_suffix = i18n("in"); break;
-
- case KFileMimeTypeInfo::Centimeters:
- item->m_suffix = i18n("cm"); break;
-
- case KFileMimeTypeInfo::Bytes:
- item->m_suffix = i18n("B"); break;
-
- case KFileMimeTypeInfo::KiloBytes:
- item->m_suffix = i18n("KB"); break;
-
- case KFileMimeTypeInfo::FramesPerSecond:
- item->m_suffix = i18n("fps"); break;
-
- case KFileMimeTypeInfo::DotsPerInch:
- item->m_suffix = i18n("dpi"); break;
-
- case KFileMimeTypeInfo::BitsPerPixel:
- item->m_suffix = i18n("bpp"); break;
-
- case KFileMimeTypeInfo::Hertz:
- item->m_suffix = i18n("Hz"); break;
-
- case KFileMimeTypeInfo::Millimeters:
- item->m_suffix = i18n("mm");
- }
-}
-
-void KFilePlugin::setPrefix(KFileMimeTypeInfo::ItemInfo* item, const TQString& prefix)
-{
- item->m_prefix = prefix;
-}
-
-void KFilePlugin::setSuffix(KFileMimeTypeInfo::ItemInfo* item, const TQString& suffix)
-{
- item->m_suffix = suffix;
-}
-
-KFileMetaInfoGroup KFilePlugin::appendGroup(KFileMetaInfo& info, const TQString& key)
-{
- return info.appendGroup(key);
-}
-
-void KFilePlugin::appendItem(KFileMetaInfoGroup& group, const TQString& key, TQVariant value)
-{
- group.appendItem(key, value);
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-KFileMetaInfoProvider * KFileMetaInfoProvider::s_self;
-static KStaticDeleter<KFileMetaInfoProvider> sd;
-
-KFileMetaInfoProvider * KFileMetaInfoProvider::self()
-{
- if ( !s_self )
- s_self = sd.setObject( s_self, new KFileMetaInfoProvider() );
-
- return s_self;
-}
-
-KFileMetaInfoProvider::KFileMetaInfoProvider()
-{
- m_plugins.setAutoDelete( true );
-}
-
-KFileMetaInfoProvider::~KFileMetaInfoProvider()
-{
- m_plugins.clear();
- sd.setObject( 0 );
-}
-
-KFilePlugin* KFileMetaInfoProvider::loadPlugin( const TQString& mimeType, const TQString& protocol )
-{
- //kdDebug() << "loadPlugin: mimeType=" << mimeType << " protocol=" << protocol << endl;
- // Currently the idea is: either the mimetype is set or the protocol, but not both.
- // We need PNG fileinfo, and trash: fileinfo, but not "PNG in the trash".
- TQString queryMimeType, query;
- if ( !mimeType.isEmpty() ) {
- query = "(not exist [X-TDE-Protocol])";
- queryMimeType = mimeType;
- } else {
- query = TQString::fromLatin1( "[X-TDE-Protocol] == '%1'" ).arg(protocol);
- // querying for a protocol: we have no mimetype, so we need to use KFilePlugin as one
- queryMimeType = "KFilePlugin";
- // hopefully using KFilePlugin as genericMimeType too isn't a problem
- }
- const KTrader::OfferList offers = KTrader::self()->query( queryMimeType, "KFilePlugin", query, TQString::null );
- if ( offers.isEmpty() )
- return 0;
- KService::Ptr service = *(offers.begin());
- Q_ASSERT( service && service->isValid() );
- if ( !service || !service->isValid() )
- return 0;
-
- KFilePlugin* plugin = KParts::ComponentFactory::createInstanceFromService<KFilePlugin>
- ( service, TQT_TQOBJECT(this), mimeType.local8Bit() );
- if (!plugin)
- kdWarning(7033) << "error loading the plugin from " << service->desktopEntryPath() << endl;
-
- return plugin;
-}
-
-KFilePlugin* KFileMetaInfoProvider::loadAndRegisterPlugin( const TQString& mimeType, const TQString& protocol )
-{
- Q_ASSERT( m_pendingMimetypeInfos.isEmpty() );
- m_pendingMimetypeInfos.clear();
-
- KFilePlugin* plugin = loadPlugin( mimeType, protocol );
- if ( !plugin ) {
- // No plugin found. Remember that, to save time.
- m_plugins.insert( protocol.isEmpty() ? mimeType : protocol, new CachedPluginInfo );
- return 0;
- }
-
- if ( !protocol.isEmpty() ) {
- // Protocol-metainfo: only one entry
- Q_ASSERT( m_pendingMimetypeInfos.count() == 1 );
- KFileMimeTypeInfo* info = m_pendingMimetypeInfos[ protocol ];
- Q_ASSERT( info );
- m_plugins.insert( protocol, new CachedPluginInfo( plugin, info, true ) );
- } else {
- // Mimetype-metainfo: the plugin can register itself for multiple mimetypes, remember them all
- bool first = true;
- TQDictIterator<KFileMimeTypeInfo> it( m_pendingMimetypeInfos );
- for( ; it.current(); ++it ) {
- KFileMimeTypeInfo* info = it.current();
- m_plugins.insert( it.currentKey(), new CachedPluginInfo( plugin, info, first ) );
- first = false;
- }
- // Hopefully the above includes the mimetype we asked for!
- if ( m_pendingMimetypeInfos.find( mimeType ) == 0 )
- kdWarning(7033) << plugin->className() << " was created for " << mimeType << " but doesn't call addMimeTypeInfo for it!" << endl;
- }
- m_pendingMimetypeInfos.clear();
- return plugin;
-}
-
-KFilePlugin * KFileMetaInfoProvider::plugin(const TQString& mimeType)
-{
- return plugin( mimeType, TQString::null );
-}
-
-KFilePlugin * KFileMetaInfoProvider::plugin(const TQString& mimeType, const TQString& protocol)
-{
- //kdDebug(7033) << "plugin() : looking for plugin for protocol=" << protocol << " mimeType=" << mimeType << endl;
-
- if ( !protocol.isEmpty() ) {
- CachedPluginInfo *cache = m_plugins.find( protocol );
- if ( cache && cache->plugin ) {
- return cache->plugin;
- }
- if ( !cache ) {
- KFilePlugin* plugin = loadAndRegisterPlugin( TQString::null, protocol );
- if ( plugin )
- return plugin;
- }
- }
-
- CachedPluginInfo *cache = m_plugins.find( mimeType );
- if ( cache ) {
- return cache->plugin;
- }
-
- KFilePlugin* plugin = loadAndRegisterPlugin( mimeType, TQString::null );
-
-#if 0
- kdDebug(7033) << "currently loaded plugins:\n";
-
- TQDictIterator<CachedPluginInfo> it( m_plugins );
- for( ; it.current(); ++it ) {
- CachedPluginInfo* cache = it.current();
- kdDebug(7033)
- << it.currentKey() // mimetype or protocol
- << " : " << (cache->plugin ? cache->plugin->className() : "(no plugin)") << endl; // plugin
- // TODO print cache->mimeTypeInfo
- }
-#endif
-
- return plugin;
-}
-
-TQStringList KFileMetaInfoProvider::preferredKeys( const TQString& mimeType ) const
-{
- KService::Ptr service =
- KServiceTypeProfile::preferredService( mimeType, "KFilePlugin");
-
- if ( !service || !service->isValid() )
- {
-// kdDebug(7033) << "no valid service found\n";
- return TQStringList();
- }
- return service->property("PreferredItems").toStringList();
-}
-
-TQStringList KFileMetaInfoProvider::preferredGroups( const TQString& mimeType ) const
-{
- KService::Ptr service =
- KServiceTypeProfile::preferredService( mimeType, "KFilePlugin");
-
- if ( !service || !service->isValid() )
- {
-// kdDebug(7033) << "no valid service found\n";
- return TQStringList();
- }
- return service->property("PreferredGroups").toStringList();
-}
-
-const KFileMimeTypeInfo * KFileMetaInfoProvider::mimeTypeInfo( const TQString& mimeType )
-{
- return mimeTypeInfo( mimeType, TQString::null );
-}
-
-const KFileMimeTypeInfo * KFileMetaInfoProvider::mimeTypeInfo( const TQString& mimeType, const TQString& protocol )
-{
- //kdDebug(7033) << "mimeTypeInfo() : looking for plugin for protocol=" << protocol << " mimeType=" << mimeType << endl;
- if ( !protocol.isEmpty() ) {
- CachedPluginInfo *cache = m_plugins.find( protocol );
- if ( cache && cache->mimeTypeInfo ) {
- return cache->mimeTypeInfo;
- }
-
- if ( !cache ) {
- loadAndRegisterPlugin( TQString::null, protocol );
- cache = m_plugins.find( protocol );
- if ( cache && cache->mimeTypeInfo ) {
- return cache->mimeTypeInfo;
- }
- }
- }
-
- CachedPluginInfo *cache = m_plugins.find( mimeType );
- if ( cache ) {
- return cache->mimeTypeInfo;
- }
-
- loadAndRegisterPlugin( mimeType, TQString::null );
- cache = m_plugins.find( mimeType );
- if ( cache ) {
- return cache->mimeTypeInfo;
- }
- return 0;
-}
-
-KFileMimeTypeInfo * KFileMetaInfoProvider::addMimeTypeInfo(
- const TQString& mimeType )
-{
-
- KFileMimeTypeInfo *info = m_pendingMimetypeInfos.find( mimeType );
- Q_ASSERT( !info );
- if ( !info )
- {
- info = new KFileMimeTypeInfo( mimeType );
- m_pendingMimetypeInfos.insert( mimeType, info );
- }
-
- info->m_preferredKeys = preferredKeys( mimeType );
- info->m_preferredGroups = preferredGroups( mimeType );
-
- return info;
-}
-
-TQStringList KFileMetaInfoProvider::supportedMimeTypes() const
-{
- TQStringList allMimeTypes;
- TQString kfilePlugin = "KFilePlugin";
-
- KTrader::OfferList offers = KTrader::self()->query( "KFilePlugin" );
- KTrader::OfferListIterator it = offers.begin();
- for ( ; it != offers.end(); ++it )
- {
- const TQStringList mimeTypes = (*it)->serviceTypes();
- TQStringList::ConstIterator it2 = mimeTypes.begin();
- for ( ; it2 != mimeTypes.end(); ++it2 )
- if ( allMimeTypes.find( *it2 ) == allMimeTypes.end() &&
- *it2 != kfilePlugin ) // also in serviceTypes()
- allMimeTypes.append( *it2 );
- }
-
- return allMimeTypes;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-// shared data of a KFileMetaInfoGroup
-class KFileMetaInfoGroup::Data : public TQShared
-{
-public:
- Data(const TQString& _name)
- : TQShared(),
- name(_name),
- mimeTypeInfo(0L),
- dirty( false ),
- added( false )
- {}
-
- // we use this one for the streaming operators
- Data() : mimeTypeInfo(0L) {}
- ~Data() {
- if ( this == null )
- delete mimeTypeInfo;
- };
-
- TQString name;
- TQMap<TQString, KFileMetaInfoItem> items;
- const KFileMimeTypeInfo* mimeTypeInfo;
- TQStringList removedItems;
- bool dirty :1;
- bool added :1;
-
- static Data* null;
- static Data* makeNull();
-
-};
-
-KFileMetaInfoGroup::KFileMetaInfoGroup( const TQString& name,
- const KFileMimeTypeInfo* info )
- : d(new Data( name ) )
-{
- d->mimeTypeInfo = info;
-}
-
-KFileMetaInfoGroup::KFileMetaInfoGroup( const KFileMetaInfoGroup& original )
-{
- // operator= does everything that's necessary
- d = Data::makeNull();
- *this = original;
-}
-
-KFileMetaInfoGroup::KFileMetaInfoGroup()
-{
- d = Data::makeNull();
-}
-
-KFileMetaInfoGroup::~KFileMetaInfoGroup()
-{
- deref();
-}
-
-const KFileMetaInfoGroup& KFileMetaInfoGroup::operator= (const KFileMetaInfoGroup& info )
-{
- if (d != info.d)
- {
- deref();
- // first deref the old one
- d = info.d;
- // and now ref the new one
- ref();
- }
- return *this;
-}
-
-bool KFileMetaInfoGroup::isValid() const
-{
- // We don't call makeNull here since it isn't necassery, see deref()
- return d != Data::null;
-}
-
-bool KFileMetaInfoGroup::isEmpty() const
-{
- return d->items.isEmpty();
-}
-
-TQStringList KFileMetaInfoGroup::preferredKeys() const
-{
- assert(isValid());
- TQStringList list = keys();
- TQStringList newlist;
- TQStringList preferredKeys = d->mimeTypeInfo->preferredKeys();
- TQStringList::Iterator pref;
- TQStringList::Iterator begin = preferredKeys.begin();
- TQStringList::Iterator end = preferredKeys.end();
-
- // move all keys from the preferred keys that are in our list to a new list
- for ( pref = begin; pref!=end; ++pref )
- {
- TQStringList::Iterator item = list.find(*pref);
- if ( item != list.end() )
- {
- newlist.append( *item );
- list.remove(item);
- }
- }
-
- // now the old list only contains the non-preferred items, so we
- // add the remaining ones to newlist
- newlist += list;
-
- return newlist;
-}
-
-TQStringList KFileMetaInfoGroup::keys() const
-{
- if (d == Data::makeNull())
- kdWarning(7033) << "attempt to get the keys of "
- "an invalid metainfo group";
-
- TQStringList list;
-
- // make a TQStringList with all available keys
- TQMapConstIterator<TQString, KFileMetaInfoItem> it;
- for (it = d->items.begin(); it!=d->items.end(); ++it)
- {
- list.append(it.data().key());
-// kdDebug(7033) << "Item " << it.data().key() << endl;
- }
- return list;
-}
-
-TQString KFileMetaInfoGroup::translatedName() const
-{
- assert(isValid());
- return d->mimeTypeInfo->groupInfo(d->name)->translatedName();
-}
-
-TQStringList KFileMetaInfoGroup::supportedKeys() const
-{
- assert(isValid());
- return d->mimeTypeInfo->groupInfo(d->name)->supportedKeys();
-}
-
-bool KFileMetaInfoGroup::supportsVariableKeys() const
-{
- assert(isValid());
- return d->mimeTypeInfo->groupInfo(d->name)->supportsVariableKeys();
-}
-
-bool KFileMetaInfoGroup::contains( const TQString& key ) const
-{
- return d->items.contains(key);
-}
-
-KFileMetaInfoItem KFileMetaInfoGroup::item( const TQString& key) const
-{
- TQMapIterator<TQString,KFileMetaInfoItem> it = d->items.find( key );
- if ( it != d->items.end() )
- return it.data();
-
- return KFileMetaInfoItem();
-}
-
-KFileMetaInfoItem KFileMetaInfoGroup::item(uint hint) const
-{
- TQMapIterator<TQString, KFileMetaInfoItem> it;
-
- for (it = d->items.begin(); it!=d->items.end(); ++it)
- if (it.data().hint() == hint)
- return it.data();
-
- return KFileMetaInfoItem();
-}
-
-TQString KFileMetaInfoGroup::name() const
-{
- return d->name;
-}
-
-uint KFileMetaInfoGroup::attributes() const
-{
- assert(isValid());
- return d->mimeTypeInfo->groupInfo(d->name)->attributes();
-}
-
-void KFileMetaInfoGroup::setAdded()
-{
- d->added = true;
-}
-
-bool KFileMetaInfoGroup::isModified() const
-{
- return d->dirty;
-}
-
-void KFileMetaInfoGroup::ref()
-{
- if (d != Data::null) d->ref();
-
-}
-
-void KFileMetaInfoGroup::deref()
-{
- // We don't call makeNull here since it isn't necassery:
- // If d is equal to null it means that null is initialized already.
- // null is 0L when it hasn't been initialized and d is never 0L.
- if ((d != Data::null) && d->deref())
- {
-// kdDebug(7033) << "metainfo group " << d->name
-// << " is finally deleted\n";
- delete d;
- d = 0;
- }
-
-}
-
-KFileMetaInfoItem KFileMetaInfoGroup::addItem( const TQString& key )
-{
- assert(isValid());
- TQMapIterator<TQString,KFileMetaInfoItem> it = d->items.find( key );
- if ( it != d->items.end() )
- return it.data();
-
- const KFileMimeTypeInfo::GroupInfo* ginfo = d->mimeTypeInfo->groupInfo(d->name);
-
- if ( !ginfo ) {
- Q_ASSERT( ginfo );
- return KFileMetaInfoItem();
- }
-
- const KFileMimeTypeInfo::ItemInfo* info = ginfo->itemInfo(key);
-
- if ( !info ) {
- Q_ASSERT( info );
- return KFileMetaInfoItem();
- }
-
- KFileMetaInfoItem item;
-
- if (info->isVariableItem())
- item = KFileMetaInfoItem(ginfo->variableItemInfo(), key, TQVariant());
- else
- item = KFileMetaInfoItem(info, key, TQVariant());
-
- d->items.insert(key, item);
- item.setAdded(); // mark as added
- d->dirty = true; // mark ourself as dirty, too
- return item;
-}
-
-bool KFileMetaInfoGroup::removeItem( const TQString& key )
-{
- if (!isValid())
- {
- kdDebug(7033) << "trying to remove an item from an invalid group\n";
- return false;
- }
-
- TQMapIterator<TQString, KFileMetaInfoItem> it = d->items.find(key);
- if ( it==d->items.end() )
- {
- kdDebug(7033) << "trying to remove the non existant item " << key << "\n";
- return false;
- }
-
- if (!((*it).attributes() & KFileMimeTypeInfo::Removable))
- {
- kdDebug(7033) << "trying to remove a non removable item\n";
- return false;
- }
-
- (*it).setRemoved();
- d->items.remove(it);
- d->removedItems.append(key);
- d->dirty = true;
- return true;
-}
-
-TQStringList KFileMetaInfoGroup::removedItems()
-{
- return d->removedItems;
-}
-
-KFileMetaInfoItem KFileMetaInfoGroup::appendItem(const TQString& key,
- const TQVariant& value)
-{
- //KDE4 enforce (value.type() == d->mimeTypeInfo->type())
- assert(isValid());
- const KFileMimeTypeInfo::GroupInfo* ginfo = d->mimeTypeInfo->groupInfo(d->name);
- if ( !ginfo ) {
- kdWarning() << "Trying to append a Metadata item for a non-existant group:" << d->name << endl;
- return KFileMetaInfoItem();
- }
- const KFileMimeTypeInfo::ItemInfo* info = ginfo->itemInfo(key);
- if ( !info ) {
- kdWarning() << "Trying to append a Metadata item for an unknown key (no ItemInfo): " << key << endl;
- return KFileMetaInfoItem();
- }
-
- KFileMetaInfoItem item;
-
- if (info->key().isNull())
- item = KFileMetaInfoItem(ginfo->variableItemInfo(), key, value);
- else
- item = KFileMetaInfoItem(info, key, value);
-
- kdDebug(7033) << "KFileMetaInfogroup inserting a " << key << endl;
-
- d->items.insert(key, item);
- return item;
-}
-
-KFileMetaInfoGroup::Data* KFileMetaInfoGroup::Data::null = 0L;
-static KStaticDeleter<KFileMetaInfoGroup::Data> sd_KFileMetaInfoGroupData;
-
-KFileMetaInfoGroup::Data* KFileMetaInfoGroup::Data::makeNull()
-{
- if (!null)
- {
- // We deliberately do not reset "null" after it has been destroyed!
- // Otherwise we will run into problems later in ~KFileMetaInfoItem
- // where the d-pointer is compared against null.
- null = new Data(TQString::null);
- null->mimeTypeInfo = new KFileMimeTypeInfo();
- sd_KFileMetaInfoGroupData.setObject( null );
- }
- return null;
-}
-
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-KFileMimeTypeInfo::KFileMimeTypeInfo( const TQString& mimeType )
- : m_mimeType( mimeType )
-{
- m_groups.setAutoDelete( true );
-}
-
-KFileMimeTypeInfo::~KFileMimeTypeInfo()
-{
-}
-
-const KFileMimeTypeInfo::GroupInfo * KFileMimeTypeInfo::groupInfo( const TQString& group ) const
-{
- return m_groups.find( group );
-}
-
-KFileMimeTypeInfo::GroupInfo * KFileMimeTypeInfo::addGroupInfo(
- const TQString& name, const TQString& translatedName )
-{
- GroupInfo* group = new GroupInfo( name, translatedName );
- m_groups.insert(name, group);
- return group;
-}
-
-TQStringList KFileMimeTypeInfo::supportedGroups() const
-{
- TQStringList list;
- TQDictIterator<GroupInfo> it( m_groups );
- for ( ; it.current(); ++it )
- list.append( it.current()->name() );
-
- return list;
-}
-
-TQStringList KFileMimeTypeInfo::translatedGroups() const
-{
- TQStringList list;
- TQDictIterator<GroupInfo> it( m_groups );
- for ( ; it.current(); ++it )
- list.append( it.current()->translatedName() );
-
- return list;
-}
-
-TQStringList KFileMimeTypeInfo::supportedKeys() const
-{
- // not really efficient, but not those are not large lists, probably.
- // maybe cache the result?
- TQStringList keys;
- TQStringList::ConstIterator lit;
- TQDictIterator<GroupInfo> it( m_groups );
- for ( ; it.current(); ++it ) { // need to nuke dupes
- TQStringList list = it.current()->supportedKeys();
- for ( lit = list.begin(); lit != list.end(); ++lit ) {
- if ( keys.find( *lit ) == keys.end() )
- keys.append( *lit );
- }
- }
-
- return keys;
-}
-
-TQValidator * KFileMimeTypeInfo::createValidator(const TQString& group,
- const TQString& key,
- TQObject *parent,
- const char *name) const
-{
- KFilePlugin* plugin = KFileMetaInfoProvider::self()->plugin(m_mimeType);
- if (plugin) return plugin->createValidator(mimeType(), group, key,
- parent, name);
- return 0;
-}
-
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-KFileMimeTypeInfo::GroupInfo::GroupInfo( const TQString& name,
- const TQString& translatedName )
- : m_name( name ),
- m_translatedName( translatedName ),
- m_attr( 0 ),
- m_variableItemInfo( 0 )
-
-{
- m_itemDict.setAutoDelete( true );
-}
-
-KFileMimeTypeInfo::GroupInfo::~GroupInfo()
-{
- delete m_variableItemInfo;
-}
-
-const KFileMimeTypeInfo::ItemInfo * KFileMimeTypeInfo::GroupInfo::itemInfo( const TQString& key ) const
-{
- ItemInfo* item = m_itemDict.find( key );
-
- // if we the item isn't found and variable keys are supported, we need to
- // return the default variable key iteminfo.
- if (!item && m_variableItemInfo)
- {
- return m_variableItemInfo;
- }
- return item;
-}
-
-KFileMimeTypeInfo::ItemInfo* KFileMimeTypeInfo::GroupInfo::addItemInfo(
- const TQString& key, const TQString& translatedKey,
- TQVariant::Type type)
-{
-// kdDebug(7034) << key << "(" << translatedKey << ") -> " << TQVariant::typeToName(type) << endl;
-
- ItemInfo* item = new ItemInfo(key, translatedKey, type);
- m_supportedKeys.append(key);
- m_itemDict.insert(key, item);
- return item;
-}
-
-
-void KFileMimeTypeInfo::GroupInfo::addVariableInfo( TQVariant::Type type,
- uint attr )
-{
- // just make sure that it's not already there
- delete m_variableItemInfo;
- m_variableItemInfo = new ItemInfo(TQString::null, TQString::null, type);
- m_variableItemInfo->m_attr = attr;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-TQString KFileMimeTypeInfo::ItemInfo::string(const TQVariant& value, bool mangle) const
-{
- TQString s;
-
- switch (value.type())
- {
- case TQVariant::Invalid :
- return "---";
-
- case TQVariant::Bool :
- s = value.toBool() ? i18n("Yes") : i18n("No");
- break;
-
- case TQVariant::Int :
- if (unit() == KFileMimeTypeInfo::Seconds)
- {
- int seconds = value.toInt() % 60;
- int minutes = value.toInt() / 60 % 60;
- int hours = value.toInt() / 3600;
- s = hours ? TQString().sprintf("%d:%02d:%02d",hours, minutes, seconds)
- : TQString().sprintf("%02d:%02d", minutes, seconds);
- return s; // no suffix wanted
- }
- else if (unit() == KFileMimeTypeInfo::Bytes)
- {
- // convertSize already adds the correct suffix
- return TDEIO::convertSize(value.toInt());
- }
- else if (unit() == KFileMimeTypeInfo::KiloBytes)
- {
- // convertSizeFromKB already adds the correct suffix
- return TDEIO::convertSizeFromKB(value.toInt());
- }
- else
- s = TDEGlobal::locale()->formatNumber( value.toInt() , 0);
- break;
-
- case TQVariant::LongLong :
- s = TDEGlobal::locale()->formatNumber( value.toLongLong(), 0 );
- break;
-
- case TQVariant::ULongLong :
- if ( unit() == KFileMimeTypeInfo::Bytes )
- return TDEIO::convertSize( value.toULongLong() );
- else if ( unit() == KFileMimeTypeInfo::KiloBytes )
- return TDEIO::convertSizeFromKB( value.toULongLong() );
- else
- s = TDEGlobal::locale()->formatNumber( value.toULongLong(), 0 );
- break;
-
- case TQVariant::UInt :
- s = TDEGlobal::locale()->formatNumber( value.toUInt() , 0);
- break;
-
- case TQVariant::Double :
- s = TDEGlobal::locale()->formatNumber( value.toDouble(), 3);
- break;
-
- case TQVariant::Date :
- s = TDEGlobal::locale()->formatDate( value.toDate(), true );
- break;
-
- case TQVariant::Time :
- s = TDEGlobal::locale()->formatTime( value.toTime(), true );
- break;
-
- case TQVariant::DateTime :
- s = TDEGlobal::locale()->formatDateTime( value.toDateTime(),
- true, true );
- break;
-
- case TQVariant::Size :
- s = TQString("%1 x %2").arg(value.toSize().width())
- .arg(value.toSize().height());
- break;
-
- case TQVariant::Point :
- s = TQString("%1/%2").arg(value.toSize().width())
- .arg(value.toSize().height());
- break;
-
- default:
- s = value.toString();
- }
-
- if (mangle && !s.isNull())
- {
- s.prepend(prefix());
- s.append(" " + suffix());
- }
- return s;
-}
-
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-
-// stream operators
-
-/* serialization of a KFileMetaInfoItem:
- first a bool that says if the items is valid, and if yes,
- all the elements of the Data
-*/
-TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoItem& item )
-{
-
- KFileMetaInfoItem::Data* d = item.d;
-
- // if the object is invalid, put only a char in the stream
- bool isValid = item.isValid();
- s << isValid;
- // ### what do about mimetypeInfo ?
- if (isValid)
- s << d->key
- << d->value
- << d->dirty
- << d->added
- << d->removed;
-
- return s;
-}
-
-
-TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoItem& item )
-{
- bool isValid;
- s >> isValid;
-
- if (!isValid)
- {
- item = KFileMetaInfoItem();
- return s;
- }
-
- // we need a new object for our data
- item.deref();
- item.d = new KFileMetaInfoItem::Data();
-
- // ### what do about mimetypeInfo ?
- bool dirty, added, removed;
- s >> item.d->key
- >> item.d->value
- >> dirty
- >> added
- >> removed;
- item.d->dirty = dirty;
- item.d->added = added;
- item.d->removed = removed;
-
- return s;
-}
-
-
-// serialization of a KFileMetaInfoGroup
-// we serialize the name of the mimetype here instead of the mimetype info
-// on the other side, we can simply use this to ask the provider for the info
-TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoGroup& group )
-{
- KFileMetaInfoGroup::Data* d = group.d;
-
- // if the object is invalid, put only a byte in the stream
- bool isValid = group.isValid();
-
- s << isValid;
- if (isValid)
- {
- s << d->name
- << d->items
- << d->mimeTypeInfo->mimeType();
- }
- return s;
-}
-
-TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& group )
-{
- TQString mimeType;
- bool isValid;
- s >> isValid;
-
- // if it's invalid, there is not much to do
- if (!isValid)
- {
- group = KFileMetaInfoGroup();
- return s;
- }
-
- // we need a new object for our data
- group.deref();
- group.d = new KFileMetaInfoGroup::Data();
-
- s >> group.d->name
- >> group.d->items
- >> mimeType;
-
- group.d->mimeTypeInfo = KFileMetaInfoProvider::self()->mimeTypeInfo(mimeType);
-
- // we need to set the item info for the items here
- TQMapIterator<TQString, KFileMetaInfoItem> it = group.d->items.begin();
- for ( ; it != group.d->items.end(); ++it)
- {
- (*it).d->mimeTypeInfo = group.d->mimeTypeInfo->groupInfo(group.d->name)
- ->itemInfo((*it).key());
- }
-
- return s;
-}
-
-// serialization of a KFileMetaInfo object
-// we serialize the name of the mimetype here instead of the mimetype info
-// on the other side, we can simply use this to ask the provider for the info
-TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfo& info )
-{
- KFileMetaInfo::Data* d = info.d;
-
- // if the object is invalid, put only a byte that tells this
- bool isValid = info.isValid();
-
- s << isValid;
- if (isValid)
- {
- s << d->url
- << d->what
- << d->groups
- << d->mimeTypeInfo->mimeType();
- }
- return s;
-}
-
-TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfo& info )
-{
- TQString mimeType;
- bool isValid;
- s >> isValid;
-
- // if it's invalid, there is not much to do
- if (!isValid)
- {
- info = KFileMetaInfo();
- return s;
- }
-
- // we need a new object for our data
- info.deref();
- info.d = new KFileMetaInfo::Data();
-
- s >> info.d->url
- >> info.d->what
- >> info.d->groups
- >> mimeType;
- info.d->mimeTypeInfo = KFileMetaInfoProvider::self()->mimeTypeInfo(mimeType);
-
- return s;
-}
-
-#include "kfilemetainfo.moc"
diff --git a/kio/kio/kfilemetainfo.h b/kio/kio/kfilemetainfo.h
deleted file mode 100644
index ea843a5f3..000000000
--- a/kio/kio/kfilemetainfo.h
+++ /dev/null
@@ -1,1738 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (C) 2001-2002 Rolf Magnus <ramagnus@kde.org>
- * Copyright (C) 2001-2002 Carsten Pfeiffer <pfeiffer@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation version 2.0.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-#ifndef KILEMETAINFO_H
-#define KILEMETAINFO_H
-
-/* Hack for HPUX: Namespace pollution
- m_unit is a define in <sys/sysmacros.h> */
-#define m_unit outouftheway_m_unit
-
-#include <tqdict.h>
-#include <tqvariant.h>
-#include <tqobject.h>
-#include <tqstring.h>
-#include <kurl.h>
-
-#undef m_unit
-
-class TQValidator;
-class KFilePlugin;
-class KFileMetaInfoGroup;
-
-/**
- * @brief Represents the capabilities of a KFilePlugin for a given mimetype
- *
- * This class provides information about the capabilities that a
- * KFilePlugin for a given mimetype has. It includes a list of metainfo
- * groups and items together with their type, a prefix, suffix and some other
- * information about how to use, display or edit the items.
- *
- * @author Rolf Magnus
- * @author Carsten Pfeiffer
- */
-class TDEIO_EXPORT KFileMimeTypeInfo
-{
- // the plugin needs to be a friend because it puts the data into the object,
- // and it should be the only one allowed to do this.
- friend class KFilePlugin;
- friend class KFileMetaInfoProvider;
-
-public:
- KFileMimeTypeInfo() {}
-
- /**
- * This enum is used to specify some attributes that an item can have,
- * which fit neither in the Hint nor in the Unit enum.
- */
- enum Attributes
- {
- Addable = 1, ///< The item or group can be added by a user
- Removable = 2, ///< It can be removed
- Modifiable = 4, ///< The value can be edited (no meaning for a group)
- Cumulative = 8, /**< If an application wants to display information
- for more than one file, it may add up the values
- for this item (e.g. play time of an mp3 file) */
- Cummulative = Cumulative, ///< @deprecated Use Cumulative instead
- Averaged = 16, /**< Similar to Cumulative, but the average should
- be calculated instead of the sum */
- MultiLine = 32, /**< This attribute says that a string item is likely
- to be more than one line long, so for editing, a
- widget capable for multline text should be used
- @since 3.1 */
- SqueezeText = 64 /**< If the text for this item is very long, it
- should be squeezed to the size of the widget
- where it's displayed
- @since 3.1 */
- };
-
- /**
- * This enum is mainly for items that have a special meaning for some
- * applications.
- */
- enum Hint {
- NoHint = 0, ///< No hint
- Name = 1, ///< The name or title of the document
- Author = 2, ///< The one who created the contents of it
- Description = 3, ///< Description Some information about the document
- Width = 4, ///< The width in pixels
- Height = 5, ///< The height in pixels
- Size = 6, ///< The size in pixels (width and height)
- Bitrate = 7, ///< For media files
- Length = 8, ///< The length of the file, also for media files
- Hidden = 9, ///< The item is usually not shown to the user
- Thumbnail = 10 ///< The item is a thumbnail picture of the file
-
- };
-
- /**
- * This enum exists so that you can specify units for items, which you
- * can usually use for integer items, so an application knows how to
- * display it (e.g. a time in seconds in a hh:mm:ss form). You can either
- * use one of those units, or if you don't find one that fits, you can
- * add it yourself using a prefix and/or suffix.
- */
- enum Unit {
- NoUnit = 0, ///< None of the listed units
- Seconds = 1, ///< The item represents a time in seconds
- MilliSeconds = 2, ///< The item represents a time in milliseconds
- BitsPerSecond = 3, ///< A bit rate
- Pixels = 4, ///< For image dimensions and similar
- Inches = 5, ///< Sizes
- Centimeters = 6, ///< Sizes
- Bytes = 7, ///< Some data/file size in bytes
- FramesPerSecond = 8, ///< A frame rate @since 3.1
- DotsPerInch = 9, ///< Resolution in DPI @since 3.1
- BitsPerPixel = 10, ///< A bit depth @since 3.1
- Hertz = 11, ///< Sample rates and similar @since 3.1
- KiloBytes = 12, ///< Some data/file size in kilobytes @since 3.1
- Millimeters = 13 ///< Sizes @since 3.3
- };
-
-
- class ItemInfo;
-
- /**
- * @brief Information about a meta information group
- *
- * This is the class for one group of items of a KFileMimeTypeInfo.
- * It contains, among other things, the information about the group's name
- * and a list of supported items.
- */
- class TDEIO_EXPORT GroupInfo
- {
-
- friend class KFilePlugin;
- friend class KFileMimeTypeInfo;
- public:
- /**
- * Use this method to get a list of keys in the specified group that
- * the plugin knows about. No variable keys.
- * For a group that doesn't support variable keys, all keys that this
- * group may have are returned. For a group that does support them, the
- * non-variable ones are returned. See KFileMetaInfo about variable
- * keys
- *
- * @return the list of keys supported for this mimetype
- **/
- TQStringList supportedKeys() const
- {
- return m_supportedKeys;
- }
-
- /**
- * Use this method to get the name of the group. This string doesn't
- * depend on the user's locale settings
- *
- * @return the group name
- */
- const TQString& name() const
- {
- return m_name;
- }
-
- /**
- * Use this method to get the string to display to the user as group
- * name. This may be different to name() and it returns the
- * name in the user's language
- *
- * @return the translated group name
- */
- const TQString& translatedName() const
- {
- return m_translatedName;
- }
-
- /**
- * A group object can contain several item objects (of which you can
- * get the names with supportedKeys() . With this method, you can
- * get one of those item objects. See ItemInfo
- *
- * @return a pointer to the item info. Don't delete this object!
- */
- const ItemInfo * itemInfo( const TQString& key ) const;
-
- /**
- * Get the attributes of this group (see Attributes)
- *
- * @return the attributes
- */
- uint attributes() const
- {
- return m_attr;
- }
-
- /**
- * @return true if this group supports adding or removing arbitrary
- * keys, false if not.
- **/
- bool supportsVariableKeys() const
- {
- return m_variableItemInfo;
- }
-
- /**
- * If the group supports variable keys, you can query their item
- * info with this method. The main reason for this is that you can
- * get the type and attributes of variable keys.
- *
- * @return a pointer to the item info. Don't delete this object!
- **/
- const ItemInfo* variableItemInfo( ) const
- {
- return m_variableItemInfo;
- }
-
- /** @internal */
- ~GroupInfo();
- private:
- /** @internal */
- GroupInfo( const TQString& name, const TQString& translatedName);
-
- /** @internal */
- KFileMimeTypeInfo::ItemInfo* addItemInfo( const TQString& key,
- const TQString& translatedKey,
- TQVariant::Type type);
-
- /** @internal */
- void addVariableInfo( TQVariant::Type type, uint attr );
-
- TQString m_name;
- TQString m_translatedName;
- TQStringList m_supportedKeys;
- uint m_attr;
- ItemInfo* m_variableItemInfo;
- TQDict<ItemInfo> m_itemDict;
-
- };
-
- /**
- * This is the class for one item of a KFileMimeTypeInfo.
- * It contains every information about a KFileMetaInfoItem that this
- * item has in common for each file of a specific mimetype.
- **/
- class TDEIO_EXPORT ItemInfo
- {
- friend class KFilePlugin;
- friend class GroupInfo;
- public:
- /** @internal */
- ItemInfo() {} // ### should be private?
-
- /**
- *
- * This method returns a translated prefix to be displayed before the
- * value. Think e.g. of the $ in $30
- *
- * @return the prefix
- */
- const TQString& prefix() const
- {
- return m_prefix;
- }
-
- /**
- * This method returns a translated suffix to be displayed after the
- * value. Think of the kbps in 128kbps
- *
- * @return the prefix
- */
- const TQString& suffix() const
- {
- return m_suffix;
- }
-
- /**
- * The items for a file are stored as a TQVariant and this method
- * can be used to get the data type of this item.
- *
- * @return the TQVariant type
- */
- TQVariant::Type type() const
- {
- return m_type;
- }
-
- /**
- * Returns the name of the item.
- * @return the name of the item
- */
- const TQString& key() const
- {
- return m_key;
- }
-
- /**
- * Returns a string for the specified @p value, if possible. If not,
- * TQString::null is returned. This can be used by programs if they want
- * to display a sum or an average of some item for a list of files.
- *
- * @param value the value to convert
- * @param mangle if true, the string will already contain prefix and
- * suffix
- * @return the converted string, or TQString::null if not possible
- * @since 3.1
- */
- TQString string( const TQVariant& value, bool mangle = true ) const;
-
- /**
- * Is this item the variable item?
- *
- * @return true if it is, false if not
- */
- bool isVariableItem() const
- {
- // every valid item is supposed to have a non-null key
- return key().isNull();
- }
-
- /**
- * Returns a translation of the key for displaying to the user. If the
- * plugin provides translation to the key, it's also in the user's
- * language.
- * @return the translated key
- */
- const TQString& translatedKey() const
- {
- return m_translatedKey;
- }
-
- /**
- * Return the attributes of the item. See
- * KFileMimeTypeInfo::Attributes.
- * @return the attributes
- */
- uint attributes() const
- {
- return m_attr;
- }
-
- /**
- * Return the hints for the item. See
- * KFileMimeTypeInfo::Hint
- * @return the hint
- */
- uint hint() const
- {
- return m_hint;
- }
-
- /**
- * Return the unit of the item. See
- * KFileMimeTypeInfo::Unit
- * @return the unit
- */
- uint unit() const
- {
- return m_unit;
- }
-
- private:
- /** @internal */
- ItemInfo(const TQString& key, const TQString& translatedKey,
- TQVariant::Type type)
- : m_key(key), m_translatedKey(translatedKey),
- m_type(type),
- m_attr(0), m_unit(NoUnit), m_hint(NoHint),
- m_prefix(TQString::null), m_suffix(TQString::null)
- {}
-
- TQString m_key;
- TQString m_translatedKey;
- TQVariant::Type m_type;
- uint m_attr;
- uint m_unit;
- uint m_hint;
- TQString m_prefix;
- TQString m_suffix;
- };
-
- // ### could it be made private? Would this be BC?
- ~KFileMimeTypeInfo();
-
- /**
- * Creates a validator for this item. Make sure to supply a proper
- * @p parent argument or delete the validator yourself.
- *
- * @param group the group of the item
- * @param key the key of the item
- * @param parent the parent of the TQObject, or 0 for a parent-less object
- * @param name the name of the TQObject, can be 0
- * @return the validator. You are responsible for deleting it. 0 if
- * creation failed
- */
- TQValidator * createValidator(const TQString& group, const TQString& key,
- TQObject *parent = 0, const char *name = 0) const;
-
- /**
- * Returns the list of all groups that the plugin for this mimetype
- * supports.
- *
- * @return the list of groups
- */
- TQStringList supportedGroups() const;
-
- /**
- * Same as the above function, but returns the strings to display to the
- * user.
- *
- * @return the list of groups
- */
- TQStringList translatedGroups() const;
-
- /**
- * This returns the list of groups in the preferred order that's specified
- * in the .desktop file.
- *
- * @return the list of groups
- */
- TQStringList preferredGroups() const
- {
- return m_preferredGroups;
- }
-
- /**
- * Returns the mimetype to which this info belongs.
- *
- * @return the mimetype of this info
- */
- TQString mimeType() const {return m_mimeType;}
-
- /**
- * Get the group info for a specific group.
- *
- * @param group the group whose group info should be retrieved
- * @return a pointer to the info. 0 if it does not
- * exist. Don't delete this object!
- */
- const GroupInfo * groupInfo( const TQString& group ) const;
-
- // always returning stringlists which the user has to iterate and use them
- // to look up the real items sounds strange to me. I think we should add
- // our own iterators some time (somewhere in the future ;)
-
- /**
- * Return a list of all supported keys without looking for a specific
- * group
- *
- * @return the list of keys
- */
- TQStringList supportedKeys() const;
-
- /**
- * Return a list of all supported keys in preference order
- *
- * @return the list of keys
- */
- TQStringList preferredKeys() const
- {
- return m_preferredKeys;
- }
-
- // ### shouldn't this be private? BC?
- GroupInfo * addGroupInfo( const TQString& name,
- const TQString& translatedName);
-
- TQString m_translatedName;
- TQStringList m_supportedKeys;
- uint m_attr;
- // bool m_supportsVariableKeys : 1;
- TQDict<ItemInfo> m_itemDict;
-
-// ### this should be made private instead, but this would be BIC
-protected:
- /** @internal */
- KFileMimeTypeInfo( const TQString& mimeType );
-
- TQDict<GroupInfo> m_groups;
- TQString m_mimeType;
- TQStringList m_preferredKeys; // same as KFileMetaInfoProvider::preferredKeys()
- TQStringList m_preferredGroups; // same as KFileMetaInfoProvider::preferredKeys()
-};
-
-
-/**
- * @brief A meta information item about a file
- *
- * This is one item of the meta information about a file (see
- * KFileMetaInfo).
- */
-class TDEIO_EXPORT KFileMetaInfoItem
-{
-public:
- class Data;
- typedef KFileMimeTypeInfo::Hint Hint;
- typedef KFileMimeTypeInfo::Unit Unit;
- typedef KFileMimeTypeInfo::Attributes Attributes;
-
- /**
- * @internal
- * You usually don't need to use this constructor yourself. Let
- * KFileMetaInfo do it for you.
- **/
- // ### hmm, then it should be private
- KFileMetaInfoItem( const KFileMimeTypeInfo::ItemInfo* mti,
- const TQString& key, const TQVariant& value);
-
- /**
- * Copy constructor
- **/
- KFileMetaInfoItem( const KFileMetaInfoItem & item );
-
- /**
- * The assignment operator, so you can do:
- * @code
- * KFileMetaInfoItem item = info.item("Title");
- * @endcode
- *
- * This will create a shared copy of the object. The actual data
- * is automatically deleted if all copies go out of scope
- **/
- const KFileMetaInfoItem& operator= (const KFileMetaInfoItem & item );
-
- /**
- * Default constructor. This creates an "invalid" item
- */
- KFileMetaInfoItem();
-
- ~KFileMetaInfoItem();
-
- /**
- * Returns the key of the item.
- *
- * @return the key of this item
- */
- TQString key() const;
-
- /**
- * Returns a translation of the key for displaying to the user. If the
- * plugin provides translation to the key, it's also in the user's language
- *
- * @return the translated key
- */
- TQString translatedKey() const;
-
- /**
- * Returns the value of the item.
- *
- * @return the value of the item.
- */
- const TQVariant& value() const;
-
- /**
- * Returns a string containing the value, if possible. If not,
- * TQString::null is returned.
- *
- * @param mangle if true, the string will already contain prefix and
- * suffix
- * @return the value string, or TQString::null if not possible
- */
- TQString string( bool mangle = true ) const;
-
- /**
- * Changes the value of the item.
- *
- * @param value the new value
- * @return true if successful, false otherwise
- */
- bool setValue( const TQVariant& value );
-
- /**
- * Return the type of the item.
- *
- * @return the type of the item
- */
- TQVariant::Type type() const;
-
- /**
- * You can query if the application can edit the item and write it back to
- * the file with this method.
- *
- * @note This doesn't ensure that you have write access to the file and
- * that enough space is available.
- *
- * @return true if the item's value can be changed, false if not
- */
- bool isEditable() const;
-
- /**
- * If you remove an item, it is only marked for removal for the file. On
- * the next KFileMetaInfo::applyChanges() , it will be removed from
- * the file. With this method, you can ask if the item is marked for
- * removal.
- *
- * @return true if the item was removed, false if not
- */
- bool isRemoved() const;
-
- /**
- * If you change an item, it is marked as "dirty". On the next
- * KFileMetaInfo::applyChanges() , the change will be written to the
- * file. With this method, you can ask if this item is dirty.
- *
- * @return true if the item contains changes that have not yet been written
- * back into the file. Removing or adding an item counts as such a change
- */
- bool isModified() const;
-
- /**
- * This method returns a translated prefix to be displayed before the
- * value. Think e.g. of the $ in $30
- *
- * @return the prefix
- */
- TQString prefix() const;
-
- /**
- * This method returns a translated suffix to be displayed after the
- * value. Think of the kbps in 128kbps
- *
- * @return the suffix
- */
- TQString suffix() const;
-
- /**
- * Returns the hint for this item. See KFileMimeTypeInfo::Hint.
- *
- * @return the hint
- **/
- uint hint() const;
-
- /**
- * Returns the unit for this item. See KFileMimeTypeInfo::Unit.
- *
- * @return the unit
- * @since 3.2
- **/
- uint unit() const;
-
- /**
- * Returns the attributes for this item. See
- * KFileMimeTypeInfo::Attributes.
- *
- * @return the attributes
- **/
- uint attributes() const;
-
- /**
- * Return true if the item is valid, i.e. if it contains data, false
- * if it's invalid (created with the default constructor and not been
- * assigned anything), or if KFileMetaInfoGroup::item() didn't find
- * your requested item).
- *
- * @return true if valid, false if invalid
- */
- bool isValid() const;
-
- TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoItem& );
- TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& );
- TDEIO_EXPORT friend TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoItem& );
- friend class KFileMetaInfoGroup;
-
-protected:
- void setAdded();
- void setRemoved();
-
- void ref();
- void deref();
-
- Data *d;
-};
-
-/**
- * @brief A group of meta information items about a file
- *
- * This is one group of meta information items about a file (see
- * KFileMetaInfo).
- */
-class TDEIO_EXPORT KFileMetaInfoGroup
-{
- friend class KFilePlugin;
- friend class KFileMetaInfo;
- TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& );
- TDEIO_EXPORT friend TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoGroup& );
-
-public:
- class Data;
- /**
- * @internal
- * You usually don't need to use this constructor yourself. Let
- * KFileMetaInfo do it for you.
- **/
- // ### hmm, then it should be private
- KFileMetaInfoGroup( const TQString& name, const KFileMimeTypeInfo* info );
-
- /**
- * Copy constructor
- **/
- KFileMetaInfoGroup( const KFileMetaInfoGroup& original );
-
- /**
- * The assignment operator, so you can do:
- * @code
- * KFileMetaInfoGroup group = info.group("Technical");
- * @endcode
- *
- * This will create a shared copy of the object. The actual data
- * is automatically deleted if all copies go out of scope
- **/
- const KFileMetaInfoGroup& operator= (const KFileMetaInfoGroup& info );
-
- /**
- * Default constructor. This creates an "invalid" item
- *
- * @since 3.1
- */
- KFileMetaInfoGroup();
-
- ~KFileMetaInfoGroup();
-
- /**
- * Returns true if the item is valid, i.e. if it contains data, false
- * if it's invalid (created with the default constructor and not been
- * assigned anything), or if KFileMetaInfoGroup::item() didn't find
- * your requested item).
- *
- * @return true if valid, false if invalid
- */
- bool isValid() const;
-
- /**
- * Returns false if the object contains data, true if it's empty. An
- * empty group is a group with no items (amazing, isn't it?).
- *
- * @return true if empty, false otherwise
- */
- bool isEmpty() const;
-
- /**
- * Returns true if an item as added or removed from the group.
- *
- * @return true if an item was added or removed from the group, otherwise
- * false.
- *
- * @since 3.1
- */
- bool isModified() const;
-
- /**
- * Operator for convenience. It does the same as item(),
- * but you cannot specify a group to search in
- */
- KFileMetaInfoItem operator[]( const TQString& key ) const
- { return item( key ); }
-
- /**
- * This method searches for the specified item.
- *
- * @param key the key of the item to search
- * @return the specified item if found, an invalid item, if not
- **/
- KFileMetaInfoItem item( const TQString& key ) const;
-
- /**
- * Returns the item with the given @p hint.
- *
- * @param hint the hint of the item
- * @return the item with the specified @p hint
- **/
- KFileMetaInfoItem item( uint hint ) const;
-
- /**
- * Convenience function. Returns the value of the specified key.
- * It does the same as item(key).value().
- *
- * @param key the key of the item to search
- * @return the value with the given key
- */
- const TQVariant value( const TQString& key ) const
- {
- const KFileMetaInfoItem &i = item( key );
- return i.value();
- }
-
- /**
- * Use this method to get a list of keys in the specified group that
- * the plugin knows about. No variable keys.
- * For a group that doesn't support variable keys, all keys that this
- * group may have are returned. For a group that does support them, the
- * non-variable ones are returned. See KFileMetaInfo about variable
- * keys
- *
- * @return the list of keys supported for this mimetype
- **/
- TQStringList supportedKeys() const;
-
- /**
- * Returns true if this group supports adding or removing arbitrary
- * keys, false if not.
- *
- * @return true is variable keys are supported, false otherwise
- **/
- bool supportsVariableKeys() const;
-
- /**
- * Checks whether an item with the given @p key exists.
- *
- * @return true if an item for this @p key exists.
- */
- bool contains( const TQString& key ) const;
-
- /**
- * Returns a list of all keys.
- *
- * @return a list of all keys in the order they were inserted.
- **/
- TQStringList keys() const;
-
- /**
- * Returns a list of all keys in preference order.
- *
- * @return a list of all keys in preference order.
- **/
- TQStringList preferredKeys() const;
-
- /**
- * @return the list of possible types that the value for the specified key
- * can be. You can use this to determine the possible types for new
- * keys before you add them.
- *
- **/
- // ### do we really want to support that?
- // let's not waste time on thinking about it. Let's just kick it for now
- // and add it in 4.0 if needed ;)
-// const TQMemArray<TQVariant::Type>& types( const TQString& key ) const;
-
- /**
- * Add an item to the info. This is only possible if the specified @p key
- * is in the supportedKeys list and not yet defined or if
- * the group supports variable keys.
- *
- * @param key the key of the item
- * @return the KFileMetaInfoItem for the given @p key
- **/
- KFileMetaInfoItem addItem( const TQString& key );
-
- /**
- * Remove this item from the meta info of the file. You cannot query
- * KFileMetaInfo for a removed object, but you can query for a list of
- * removed items with removedItems() if you need to.
- * If you re-add it, its value will be cleared.
- *
- * @param key the key of the removed item
- * @return true if successful, false otherwise
- */
- bool removeItem(const TQString& key);
-
- /**
- * Returns a list of all removed items.
- *
- * @return a list of all removed items
- */
- TQStringList removedItems();
-
- /**
- * The name of this group.
- *
- * @return the name of this group
- */
- TQString name() const;
-
- /**
- * The translated name of this group.
- *
- * @return the translated name of this group
- *
- * @since 3.2
- */
- TQString translatedName() const;
-
- /**
- * Returns the attributes of this item.
- *
- * @return the attributes
- */
- uint attributes() const;
-
-protected:
- void setAdded();
- KFileMetaInfoItem appendItem( const TQString& key, const TQVariant& value);
-
- Data* d;
- void ref();
- void deref();
-
-};
-
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-/**
- * @brief Meta Information about a file
- *
- * This is the class for objects that hold meta information about a file.
- * The information is kept in form of a system of key/value pairs. See also
- * KFileMetaInfoItem.
- * This information is retrieved from the file through a plugin system, and
- * this class is the main interface to it.
- * If you want to write your own plugin, have a look at KFilePlugin.
- * There are basically two different kinds of meta information: Fixed ones
- * that the plugin knows about (e.g. an mp3 id3v1 tag has a well defined
- * fixed list of fields), and variable keys that exist in mimetypes that
- * support their own key/value system (comments in png files are of this type).
- * Almost every file has fixed keys, but some also have variable keys.
- *
- * The groups and the What enum are not yet supported, but already added to
- * the interface so that adding support doesn't break compatibility.
- */
-class TDEIO_EXPORT KFileMetaInfo
-{
-public:
- typedef KFileMimeTypeInfo::Hint Hint;
- typedef KFileMimeTypeInfo::Unit Unit;
- typedef KFileMimeTypeInfo::Attributes Attributes;
- class Data;
-
- /**
- * This is used to specify what a KFileMetaInfo object should read, so
- * you can specify if you want to read "expensive" items or not.
- */
- enum What
- {
- Fastest = 0x1, /**< do the fastest possible read and omit all items
- that might need a significantly longer time
- than the others */
- DontCare = 0x2, ///< let the plugin decide what to read
-
- TechnicalInfo = 0x4, /**< extract technical details about the file, like
- e.g. play time, resolution or a compressioni
- type */
- ContentInfo = 0x8, /**< read information about the content of the file,
- like comments or id3 tags */
- ExtenedAttr = 0x10, /**< read filesystem based extended attributes if
- they are supported for the filesystem */
- Thumbnail = 0x20, /**< only read the file's thumbnail, if it contains
- one */
- Preferred = 0x40, ///< get at least the preferred items
- Everything = 0xffff ///< read everything, even if it might take a while
-
- };
-
- /**
- * The constructor.
- *
- * creating a KFileMetaInfo item through this will autoload the plugin
- * belonging to the mimetype and try to get meta information about
- * the specified file.
- *
- * If no info is available, you'll get an empty (not invalid) object.
- * You can test for it with the isEmpty() method.
- *
- * @param path The file name. This must be the path to a local file.
- * @param mimeType The name of the file's mimetype. If ommited, the
- * mimetype is autodetected
- * @param what one or more of the What enum values. It gives some
- * hint to the plugin what information is desired. The plugin
- * may still return more items.
- *
- * @note This version will @b only work for @b local (file:/) files.
- *
- **/
- KFileMetaInfo( const TQString& path,
- const TQString& mimeType = TQString::null,
- uint what = Fastest);
-
- /**
- * Another constructor
- *
- * Similar to the above, but takes a URL so that meta-data may be retrieved
- * over other protocols (ftp, etc.)
- *
- **/
- KFileMetaInfo( const KURL& url,
- const TQString& mimeType = TQString::null,
- uint what = Fastest);
-
- /**
- * Default constructor. This will create an invalid object (see
- * isValid().
- **/
- KFileMetaInfo();
-
- /**
- * Copy constructor. This creates a copy of the original object, but
- * that copy will point to the same data, so if you change the original,
- * the copy will be changed, too. After all, they are referring to the same
- * file.
- **/
- KFileMetaInfo( const KFileMetaInfo& original);
-
- ~KFileMetaInfo();
-
- /**
- * The assignment operator, so you can do e.g.:
- * @code
- * KFileMetaInfo info;
- * if (something) info = KFileMetaInfo("/the/file");
- * @endcode
- *
- * This will create a shared copy of the object. The actual data
- * is automatically deleted if all copies go out of scope.
- **/
- const KFileMetaInfo& operator= (const KFileMetaInfo& info );
-
-
- /**
- * Returns a list of all groups.
- *
- * @return the keys of the groups that the file has.
- */
- TQStringList groups() const;
-
- /**
- * Returns a list of all supported groups.
- *
- * @return the supported keys of the groups that the file has.
- */
- TQStringList supportedGroups() const;
-
- /**
- * Returns a list of the preferred groups.
- *
- * @return the keys of the preferred groups that the file has.
- */
- TQStringList preferredGroups() const;
-
- /**
- * Returns a list of all preferred keys.
- *
- * @return a list of all preferred keys.
- */
- TQStringList preferredKeys() const;
-
- /**
- * Returns a list of supported keys.
- *
- * @return a list of supported keys
- */
- TQStringList supportedKeys() const;
-
- /**
- * Returns the list of groups that you can add or remove from the file.
- *
- * @return the groups can be added or removed
- */
- TQStringList editableGroups() const;
-
- // I'd like to keep those for lookup without group, at least the hint
- // version
- /**
- * Returns the KFileMetaInfoItem with the given @p key.
- *
- * @param key the key of the item
- * @return the item. Invalid if there is no item with the given @p key.
- */
- KFileMetaInfoItem item(const TQString& key) const;
- /**
- * Returns the KFileMetaInfoItem with the given @p hint.
- *
- * @param hint the hint of the item
- * @return the item. Invalid if there is no item with the given @p hint.
- */
- KFileMetaInfoItem item(const KFileMetaInfoItem::Hint hint) const;
-
- /**
- * Saves the item with the given @p key.
- *
- * @param key the key of the item
- * @param preferredGroup the preferred group, or TQString::null
- * @param createGroup true to create the group if necessary
- * @return the saved item
- */
- KFileMetaInfoItem saveItem( const TQString& key,
- const TQString& preferredGroup = TQString::null,
- bool createGroup = true );
-
- /**
- * Returns the KFileMetaInfoGroup with the given @p key.
- *
- * @param key the key of the item
- * @return the group. Invalid if there is no group with the given @p key.
- */
- KFileMetaInfoGroup group(const TQString& key) const;
-
- /**
- * Returns the KFileMetaInfoGroup with the given @p key.
- *
- * @param key the key of the item
- * @return the group. Invalid if there is no group with the given @p key.
- */
- KFileMetaInfoGroup operator[] (const TQString& key) const
- {
- return group(key);
- }
-
- /**
- * Try to add the specified group. This will only succeed if it is
- * in the list of editableGroups().
- *
- * @note that all non-variable items that belong to this group are
- * automatically added as empty item.
- *
- * @param name the name of the group to add
- * @return true if successful, false if not
- */
- bool addGroup( const TQString& name );
-
- /**
- * Remove the specified group. This will only succeed if it is
- * in the list of editableGroups(). Beware that this also
- * removes all the items in that group, so always ask the user
- * before removing it!
- *
- * @param name the name of the group to remove
- * @return true if successful, false if not
- */
- bool removeGroup( const TQString& name );
-
- /**
- * Returns a list of removed groups.
- *
- * @return a list of removed groups.
- */
- TQStringList removedGroups();
-
- /**
- * This method writes all pending changes of the meta info back to the file.
- * If any items are marked as removed, they are really removed from the
- * list. The info object as well as all items are updated.
- *
- * @return true if successful, false if not
- */
- bool applyChanges();
-
- /**
- * This method writes all pending changes of the meta info to the file @p path.
- * If any items are marked as removed, they are really removed from the
- * list. The info object as well as all items are updated.
- *
- * @return true if successful, false if not
- */
- bool applyChanges(const TQString& path);
-
- /**
- * Checks whether an item with the given @p key exists.
- *
- * @param key the key to check
- * @return whether an item for this @p key exists.
- */
- bool contains( const TQString& key ) const;
-
- /**
- * Checks whether a group with the given @p key exists.
- *
- * @param key the key to check
- * @return whether a group with this name exists.
- */
- bool containsGroup( const TQString& key ) const;
-
- /**
- * Returns the value with the given @p key.
- *
- * @param key the key to retrieve
- * @return the value. Invalid if it does not exist
- */
- const TQVariant value( const TQString& key ) const
- {
- return item(key).value();
- }
-
-
- /**
- * Returns true if the item is valid, i.e. if actually represents the info
- * about a file, false if the object is uninitialized.
- *
- * @return true if valid, false otherwise
- */
- bool isValid() const;
-
- /**
- * Returns false if the object contains data, true if it's empty. You'll
- * get an empty object if no plugin for the file could be found.
- *
- * @return true if empty, false otherwise
- */
- bool isEmpty() const;
-
- /**
- * Returns the mime type of file.
- *
- * @return the file's mime type
- */
- TQString mimeType() const;
-
- /**
- * Returns the path of file - or TQString::null if file is non-local
- *
- * @return the file's path - or TQString::null if file is non-local
- */
- TQString path() const;
-
- /**
- * Returns the url of file
- *
- * @return the file's url
- */
- KURL url() const;
-
- TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfo& );
- TDEIO_EXPORT friend TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfo& );
- friend class KFilePlugin;
-
-protected:
- KFileMetaInfoGroup appendGroup(const TQString& name);
-
- /**
- * @return a pointer to the plugin that belogs to this object's mimetype.
- * It will be auto-loaded if it's currently not loaded
- **/
- KFilePlugin * plugin() const;
-
- void ref();
- void deref();
-
- Data* d;
-
-private:
- KFileMetaInfoItem findEditableItem( KFileMetaInfoGroup& group,
- const TQString& key );
-
- void init( const KURL& url,
- const TQString& mimeType = TQString::null,
- uint what = Fastest);
-};
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-/**
- * @brief Base class for a meta information plugin
- *
- * Meta information plugins are used to extract useful information from files
- * of a given type. These plugins are used in Konqueror's file properties
- * dialog, for example.
- *
- * If you want to write your own plugin, you need to derive from this class.
- *
- * In the constructor of your class, you need to call addMimeTypeInfo() to tell
- * the KFile framework which mimetype(s) your plugin supports. For each
- * mimetype, use the addGroupInfo() and addItemInfo() methods to declare the
- * meta information items the plugin calculates and to group them accordingly.
- * For groups, use setAttributes() to customize your group (see
- * KFileMimeTypeInfo::Attributes). For items, use setAttributes() to define the
- * behaviour of the item; use setHint() to define the meaning of the item; use
- * setUnit() to define the Unit, such as KFileMimeTypeInfo::Seconds or
- * KFileMimeTypeInfo::KiloBytes. In short, the constructor defines the data
- * structure of the meta information supported by your plugin.
- *
- * Example:
- * @code
- * FooPlugin::FooPlugin(TQObject *parent, const char *name,
- * const TQStringList &args)
- * : KFilePlugin(parent, name, args)
- * {
- * KFileMimeTypeInfo* info = addMimeTypeInfo( "application/x-foo" );
- *
- * // our new group
- * KFileMimeTypeInfo::GroupInfo* group = 0L;
- * group = addGroupInfo(info, "FooInfo", i18n("Foo Information"));
- *
- * KFileMimeTypeInfo::ItemInfo* item;
- *
- * // our new items in the group
- * item = addItemInfo(group, "Items", i18n("Items"), TQVariant::Int);
- * item = addItemInfo(group, "Size", i18n("Size"), TQVariant::Int);
- * setUnit(item, KFileMimeTypeInfo::KiloBytes);
- *
- * // strings are possible, too:
- * //addItemInfo(group, "Document Type", i18n("Document type"), TQVariant::String);
- * }
- * @endcode
- *
- * Some meta information items are likely to be available in several different
- * file formats, such as @c "Author", @c "Title" (for documents), and
- * @c "Length" (for multimedia files). Be sure to use the naming scheme from
- * existing plugins for your meta information items if possible. If, for
- * example, the meta information of a group of files is shown in a table view,
- * this will allow two files to share the same column (say "Length") even if
- * they are of a different file type.
- *
- * You must overwrite the readInfo() method. In this method you need to extract
- * the meta information of the given file. You can use a third-party library to
- * achieve this task. This might be the best way for binary files, since a
- * change in the file format is likely to be supported by subsequent releases
- * of that library. Alternatively, for text-based file formats, you can use
- * TQTextStream to parse the file. For simple file formats, TQRegExp can be of
- * great help, too.
- *
- * After you extracted the relevant information, use appendGroup() and
- * appendItem() to fill the meta information data structure (as defined in the
- * constructor) with values. Note that you can leave out groups or items
- * which are not appropriate for a particular file.
- *
- * Example:
- * @code
- * bool FooPlugin::readInfo( KFileMetaInfo& info, uint what)
- * {
- * int numItems = 0;
- * int size = 0;
- *
- * // do your calculations here, e.g. using a third-party
- * // library or by writing an own parser using e.g. QTextStream
- *
- * // calculate numItems and size ...
- *
- * // note: use the same key strings as in the constructor
- * KFileMetaInfoGroup group = appendGroup(info, "FooInfo");
- *
- * appendItem(group, "Items", numItems);
- * appendItem(group, "Size", size);
- *
- * return true;
- * }
- * @endcode
- *
- * If you want to define mutable meta information items, you need to overwrite
- * the writeInfo() method. In this method, you can use third-party library
- * (appropriate mostly for binary files, see above) or TQTextStream to write the
- * information back to the file. If you use TQTextStream, be sure to write all
- * file contents back.
- *
- * For some items, it might be that not all possible values are allowed. You
- * can overwrite the createValidator() method to define constraints for a meta
- * information item. For example, the @c "Year" field for an MP3 file could
- * reject values outside the range 1500 - 2050 (at least for now). The
- * validator is used to check values before the writeInfo() method is called so
- * that writeInfo() is only provided correct values.
- *
- * In your plugin, you need to create a factory for the KFilePlugin
- *
- * Example:
- * @code
- * typedef KGenericFactory<FooPlugin> FooFactory;
- * K_EXPORT_COMPONENT_FACTORY(kfile_foo, FooFactory("kfile_foo"));
- * @endcode
- *
- * To make your plugin available within KDE, you also need to provide a
- * @c .desktop file which describes your plugin. The required fields in the
- * file are:
- *
- * - @c Type: must be @c "Service"
- * - @c Name: the name of the plugin
- * - @c ServiceTypes: must contain @c "KFilePlugin"
- * - @c X-TDE-Library: the name of the library containing the KFile plugin
- * - @c MimeType: the mimetype(s) which are supported by the plugin
- * - @c PreferredGroups: a comma-separated list of the most important groups.
- * This list defines the order in which the meta information groups should be
- * displayed
- * - @c PreferredItems: a comma-separated list of the most important items.
- * This list defines the order in which the meta information items should be
- * displayed
- *
- * Example:
- * @code
- * [Desktop Entry]
- * Encoding=UTF-8
- * Type=Service
- * Name=Foo Info
- * ServiceTypes=KFilePlugin
- * X-TDE-Library=kfile_foo
- * MimeType=application/x-foo
- * PreferredGroups=FooInfo
- * PreferredItems=Items,Size
- * @endcode
- **/
-class TDEIO_EXPORT KFilePlugin : public TQObject
-{
- Q_OBJECT
-
-public:
- /**
- * Creates a new KFilePlugin instance. You need to implement a constructor
- * with the same argument list as this is required by KGenericFactory
- *
- * @param parent the parent of the TQObject, can be @c 0
- * @param name the name of the TQObject, can be @c 0
- * @param args currently ignored
- *
- * @see addMimeTypeInfo()
- * @see addGroupInfo()
- * @see addItemInfo()
- * @see TQObject()
- **/
- KFilePlugin( TQObject *parent, const char *name,
- const TQStringList& args );
-
- /**
- * Destructor
- */
- virtual ~KFilePlugin();
-
- /**
- * Read the info from the file in this method and insert it into the
- * provided KFileMetaInfo object. You can get the path to the file with
- * KFileMetaInfo::path(). Use appendGroup() and appendItem() to fill
- * @p info with the extracted values
- *
- * @param info the information will be written here
- * @param what defines what to read, see KFileMetaInfo::What
- * @return @c true if successful, @c false if it failed
- *
- * @see writeInfo()
- **/
- virtual bool readInfo( KFileMetaInfo& info,
- uint what = KFileMetaInfo::Fastest ) = 0;
-
- /**
- * Similar to the readInfo() but for writing the info back to the file.
- * If you don't have any writable keys, don't implement this method
- *
- * @param info the information that will be written
- * @return @c true if successful, @c false if it failed
- **/
- virtual bool writeInfo( const KFileMetaInfo& info ) const
- {
- Q_UNUSED(info);
- return true;
- }
-
- /**
- * This method should create an appropriate validator for the specified
- * item if it's editable or return a null pointer if not. If you don't have
- * any editable items, you don't need to implement this method.
- *
- * If you you don't need any validation, e.g. you accept any input, you can
- * simply return @c 0L, or not reimplement this method at all.
- *
- * @param mimeType the mime type
- * @param group the group name of the validator item
- * @param key the key name of the validator item
- * @param parent the TQObject parent, can be @c 0
- * @param name the name of the TQObject, can be @c 0
- **/
- virtual TQValidator* createValidator( const TQString& mimeType,
- const TQString& group,
- const TQString& key,
- TQObject* parent,
- const char* name) const
- {
- Q_UNUSED(mimeType); Q_UNUSED(group);Q_UNUSED(key);
- Q_UNUSED(parent);Q_UNUSED(name);
- return 0;
- }
-
-protected:
-
- /**
- * Call this from within your constructor to tell the KFile framework what
- * mimetypes your plugin supports.
- *
- * @param mimeType a string containing the mimetype, e.g. @c "text/html"
- * @return a KFileMimeTypeInfo object, to be used with addGroupInfo()
- **/
- KFileMimeTypeInfo * addMimeTypeInfo( const TQString& mimeType );
- // ### do we need this, if it only calls the provider?
- // IMHO the Plugin shouldn't call its provider.
- // DF: yes we need this. A plugin can create more than one mimetypeinfo.
- // What sucks though, is to let plugins do that in their ctor.
- // Would be much simpler to have a virtual init method for that,
- // so that the provider can set up stuff with the plugin pointer first!
-
- /**
- * Creates a meta information group for KFileMimeTypeInfo object returned
- * by addMimeTypeInfo().
- *
- * @param info the object returned by addMimeTypeInfo()
- * @param key a unique string identifiing this group. For simplicity it is
- * recommended to use the same string as for the translatedKey
- * parameter
- * @param translatedKey the translated version of the key string for
- * displaying in user interfaces. Use i18n() to translate the string
- * @return a GroupInfo object. Pass this object to addItemInfo to add meta
- * information attributed to this group.
- *
- * @see setAttributes()
- * @see addItemInfo()
- **/
- KFileMimeTypeInfo::GroupInfo* addGroupInfo(KFileMimeTypeInfo* info,
- const TQString& key, const TQString& translatedKey) const;
-
- /**
- * Sets attributes of the GroupInfo object returned by addGroupInfo().
- *
- * @param gi the object returned by addGroupInfo()
- * @param attr the attributes for this group; these are values of type
- * KFileMimeTypeInfo::Attributes, or'ed together
- **/
- void setAttributes(KFileMimeTypeInfo::GroupInfo* gi, uint attr) const;
-
- void addVariableInfo(KFileMimeTypeInfo::GroupInfo* gi, TQVariant::Type type,
- uint attr) const;
-
- /**
- * Adds a meta information item to a GroupInfo object as returned by
- * addGroupInfo().
- *
- * @param gi the GroupInfo object to add a new item to
- * @param key a unique string to identify this item. For simplicity it is
- * recommended to use the same string as for the translatedKey
- * parameter
- * @param translatedKey the translated version of the key string for
- * displaying in user interfaces. Use i18n() to translate the string
- * @param type the type of the meta information item, e.g. TQVariant::Int
- * or TQVariant::String.
- * @return an ItemInfo object. Pass this object to setAttributes()
- **/
- KFileMimeTypeInfo::ItemInfo* addItemInfo(KFileMimeTypeInfo::GroupInfo* gi,
- const TQString& key,
- const TQString& translatedKey,
- TQVariant::Type type);
-
- /**
- * Sets some attributes for a meta information item. The attributes
- * describe if the item is mutable, how it should be computed for a list of
- * files, and how it should be displayed
- *
- * @param item the ItemInfo object as returned by addItemInfo()
- * @param attr the attributes for this item; these are values of type
- * KFileMimeTypeInfo::Attributes, or'ed together
- **/
- void setAttributes(KFileMimeTypeInfo::ItemInfo* item, uint attr);
-
- /**
- * Defines the meaning of the meta information item. Some applications make
- * use of this information, so be sure to check KFileMimeTypeInfo::Hint to
- * see if an item's meaning is in the list.
- *
- * @param item the ItemInfo object as returned by addItemInfo()
- * @param hint the item's meaning. See KFileMimeTypeInfo::Hint for a list
- * of available meanings
- **/
- void setHint(KFileMimeTypeInfo::ItemInfo* item, uint hint);
-
- /**
- * Sets the unit used in the meta information item. This unit is used to
- * format the value and to make large values human-readable. For example,
- * if the item's unit is KFileMimeTypeInfo::Seconds and the value is 276,
- * it will be displayed as 4:36.
- *
- * @param item the ItemInfo object as returned by addItemInfo()
- * @param unit the item's unit. See KFileMimeTypeInfo::Unit for a list of
- * available units
- **/
- void setUnit(KFileMimeTypeInfo::ItemInfo* item, uint unit);
-
- /**
- * Sets a prefix string which is displayed before the item's value. Use
- * this string if no predefined unit fits the item's unit. Be sure to
- * translate the string with i18n()
- *
- * @param item the ItemInfo object as returned by addItemInfo()
- * @param prefix the prefix string to display
- **/
- void setPrefix(KFileMimeTypeInfo::ItemInfo* item, const TQString& prefix);
-
- /**
- * Sets a suffix string which is displayed before the item's value. Use
- * this string if no predefined unit fits the item's unit. Be sure to
- * translate the string with i18n()
- *
- * @param item the ItemInfo object as returned by addItemInfo()
- * @param suffix the suffix string to display
- **/
- void setSuffix(KFileMimeTypeInfo::ItemInfo* item, const TQString& suffix);
-
- /**
- * Call this method from within readInfo() to indicate that you wish to
- * fill meta information items of the group identified by @p key with
- * values.
- *
- * @param info the KFileMetaInfo object. Use the parameter of the
- * readInfo() method
- * @param key the key string to identify the group. Use the string that you
- * defined in your class' constructor
- * @return a KFileMetaInfoGroup object, to be used in appendItem()
- **/
- KFileMetaInfoGroup appendGroup(KFileMetaInfo& info, const TQString& key);
-
- /**
- * Call this method from within readInfo() to fill the meta information item
- * identified by @p key with a @p value
- *
- * @param group the KFileMetaInfoGroup object, as returned by appendGroup()
- * @param key the key string to identify the item.
- * @param value the value of the meta information item
- **/
- void appendItem(KFileMetaInfoGroup& group, const TQString& key, TQVariant value);
-
- TQStringList m_preferredKeys;
- TQStringList m_preferredGroups;
-
-protected:
- /**
- * Helper method to allow binary compatible extensions when needing
- * "new virtual methods"
- *
- * @param id the identifier of the new "virtual" method
- * @param data any parameter data the new "virtual" method needs
- */
- virtual void virtual_hook( int id, void* data );
-private:
- class KFilePluginPrivate;
- KFilePluginPrivate *d;
-};
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-/**
- * @internal
- * Synchronous access to metadata of a local file. Usually, you don't want
- * to use this class for getting metainfo from a file. Use KFileMetaInfo
- * directly. However, if you want to find out if a specific mimetype is
- * supported and which groups and items are provided for it, you can ask
- * the KFileMetainfoProvider for it.
- **/
-class TDEIO_EXPORT KFileMetaInfoProvider: private QObject
-{
- friend class KFilePlugin;
-
- Q_OBJECT
-public:
- virtual ~KFileMetaInfoProvider();
-
- static KFileMetaInfoProvider * self();
-
- /**
- * @return a pointer to the plugin that belongs to the specified mimetype,
- * which means also load the plugin if it's not in memory
- */
- KFilePlugin * plugin( const TQString& mimeType ); // KDE4: merge with method below
-
- /**
- * @return a pointer to the plugin that belongs to the specified mimetype,
- * for the given protocol.
- * This loads the plugin if it's not in memory yet.
- */
- KFilePlugin * plugin( const TQString& mimeType, const TQString& protocol );
-
- const KFileMimeTypeInfo * mimeTypeInfo( const TQString& mimeType ); // KDE4: merge with below
- const KFileMimeTypeInfo * mimeTypeInfo( const TQString& mimeType, const TQString& protocol );
-
- TQStringList preferredKeys( const TQString& mimeType ) const;
- TQStringList preferredGroups( const TQString& mimeType ) const;
-
- /// @since 3.1
- TQStringList supportedMimeTypes() const;
-
-protected: // ## should be private, right?
- KFileMetaInfoProvider();
-
-private:
-
- // Data structure:
- // Mimetype or Protocol -> { Plugin and MimeTypeInfo }
- // The {} struct is CachedPluginInfo
- struct CachedPluginInfo
- {
- CachedPluginInfo() : plugin( 0 ), mimeTypeInfo( 0 ), ownsPlugin( false ) {}
- CachedPluginInfo( KFilePlugin* p, KFileMimeTypeInfo* i, bool owns )
- : plugin( p ), mimeTypeInfo( i ), ownsPlugin( owns ) {}
- // auto-delete behavior
- ~CachedPluginInfo() {
- if ( ownsPlugin ) delete plugin;
- delete mimeTypeInfo;
- }
-
- // If plugin and mimeTypeInfo are 0, means that no plugin is available.
- KFilePlugin* plugin;
- KFileMimeTypeInfo* mimeTypeInfo;
- // The problem here is that plugin can be shared in multiple instances,
- // so the memory management isn't easy. KDE4 solution: use KSharedPtr?
- // For now we flag one copy of the KFilePlugin pointer as being "owned".
- bool ownsPlugin;
- };
-
- // The key is either a mimetype or a protocol. Those things don't look the same
- // so there's no need for two QDicts.
- TQDict<CachedPluginInfo> m_plugins;
-
- // This data is aggregated during the creation of a plugin,
- // before being moved to the appropriate CachedPluginInfo(s)
- // At any other time than during the loading of a plugin, this dict is EMPTY.
- // Same key as in m_plugins: mimetype or protocol
- TQDict<KFileMimeTypeInfo> m_pendingMimetypeInfos;
-
-private:
- static KFileMetaInfoProvider * s_self;
-
- KFilePlugin* loadPlugin( const TQString& mimeType, const TQString& protocol );
- KFilePlugin* loadAndRegisterPlugin( const TQString& mimeType, const TQString& protocol );
- KFileMimeTypeInfo * addMimeTypeInfo( const TQString& mimeType );
-
- class KFileMetaInfoProviderPrivate;
- KFileMetaInfoProviderPrivate *d;
-
-};
-
-TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoItem& );
-TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoItem& );
-
-TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoGroup& );
-TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& );
-
-TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfo& );
-TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfo& );
-
-
-#endif // KILEMETAINFO_H
diff --git a/kio/kio/kfileshare.cpp b/kio/kio/kfileshare.cpp
deleted file mode 100644
index bf8cdca1d..000000000
--- a/kio/kio/kfileshare.cpp
+++ /dev/null
@@ -1,346 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2001 David Faure <david@mandrakesoft.com>
- Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kfileshare.h"
-#include <tqdir.h>
-#include <tqfile.h>
-#include <tqregexp.h>
-#include <kprocess.h>
-#include <kprocio.h>
-#include <klocale.h>
-#include <kstaticdeleter.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kdirwatch.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <kdirnotify_stub.h>
-#include <ksimpleconfig.h>
-#include <kuser.h>
-
-KFileShare::Authorization KFileShare::s_authorization = NotInitialized;
-//TQStringList* KFileShare::s_shareList = 0L;
-//static KStaticDeleter<TQStringList> sdShareList;
-TQMap<TQString,TQString>* KFileShare::s_shareMap = 0L;
-static KStaticDeleter<TQMap<TQString,TQString> > sdShareMap;
-
-KFileShare::ShareMode KFileShare::s_shareMode;
-bool KFileShare::s_sambaEnabled;
-bool KFileShare::s_nfsEnabled;
-bool KFileShare::s_restricted;
-TQString KFileShare::s_fileShareGroup;
-bool KFileShare::s_sharingEnabled;
-
-
-#define FILESHARECONF "/etc/security/fileshare.conf"
-
-KFileSharePrivate::KFileSharePrivate()
-{
- KDirWatch::self()->addFile(FILESHARECONF);
- connect(KDirWatch::self(), TQT_SIGNAL(dirty (const TQString&)),this,
- TQT_SLOT(slotFileChange(const TQString &)));
- connect(KDirWatch::self(), TQT_SIGNAL(created(const TQString&)),this,
- TQT_SLOT(slotFileChange(const TQString &)));
- connect(KDirWatch::self(), TQT_SIGNAL(deleted(const TQString&)),this,
- TQT_SLOT(slotFileChange(const TQString &)));
-}
-
-KFileSharePrivate::~KFileSharePrivate()
-{
- KDirWatch::self()->removeFile(FILESHARECONF);
-}
-
-KFileSharePrivate *KFileSharePrivate::_self=0L;
-
-static KStaticDeleter<KFileSharePrivate> kstFileShare;
-
-KFileSharePrivate* KFileSharePrivate::self()
-{
- if (!_self)
- _self = kstFileShare.setObject(_self, new KFileSharePrivate());
- return _self;
-}
-
-void KFileSharePrivate::slotFileChange(const TQString &file)
-{
- if(file==FILESHARECONF) {
- KFileShare::readConfig();
- KFileShare::readShareList();
- }
-}
-
-void KFileShare::readConfig() // static
-{
- // Create KFileSharePrivate instance
- KFileSharePrivate::self();
- KSimpleConfig config(TQString::fromLatin1(FILESHARECONF),true);
-
- s_sharingEnabled = config.readEntry("FILESHARING", "yes") == "yes";
- s_restricted = config.readEntry("RESTRICT", "yes") == "yes";
- s_fileShareGroup = config.readEntry("FILESHAREGROUP", "fileshare");
-
-
- if (!s_sharingEnabled)
- s_authorization = UserNotAllowed;
- else
- if (!s_restricted )
- s_authorization = Authorized;
- else {
- // check if current user is in fileshare group
- KUserGroup shareGroup(s_fileShareGroup);
- if (shareGroup.users().findIndex(KUser()) > -1 )
- s_authorization = Authorized;
- else
- s_authorization = UserNotAllowed;
- }
-
- if (config.readEntry("SHARINGMODE", "simple") == "simple")
- s_shareMode = Simple;
- else
- s_shareMode = Advanced;
-
-
- s_sambaEnabled = config.readEntry("SAMBA", "yes") == "yes";
- s_nfsEnabled = config.readEntry("NFS", "yes") == "yes";
-}
-
-KFileShare::ShareMode KFileShare::shareMode() {
- if ( s_authorization == NotInitialized )
- readConfig();
-
- return s_shareMode;
-}
-
-bool KFileShare::sharingEnabled() {
- if ( s_authorization == NotInitialized )
- readConfig();
-
- return s_sharingEnabled;
-}
-
-bool KFileShare::isRestricted() {
- if ( s_authorization == NotInitialized )
- readConfig();
-
- return s_restricted;
-}
-
-TQString KFileShare::fileShareGroup() {
- if ( s_authorization == NotInitialized )
- readConfig();
-
- return s_fileShareGroup;
-}
-
-
-bool KFileShare::sambaEnabled() {
- if ( s_authorization == NotInitialized )
- readConfig();
-
- return s_sambaEnabled;
-}
-
-bool KFileShare::nfsEnabled() {
- if ( s_authorization == NotInitialized )
- readConfig();
-
- return s_nfsEnabled;
-}
-
-
-void KFileShare::readShareList()
-{
- KFileSharePrivate::self();
- if ( !s_shareMap )
- sdShareMap.setObject( s_shareMap, new TQMap<TQString,TQString> );
- else
- s_shareMap->clear();
-
- // /usr/sbin on Mandrake, $PATH allows flexibility for other distributions
- TQString exe = findExe( "filesharelist" );
- if (exe.isEmpty()) {
- s_authorization = ErrorNotFound;
- return;
- }
- KProcIO proc;
- proc << exe;
- if ( !proc.start( TDEProcess::Block ) ) {
- kdError() << "Can't run " << exe << endl;
- s_authorization = ErrorNotFound;
- return;
- }
-
- // Reading code shamelessly stolen from khostname.cpp ;)
- TQString line;
- TQString options;
- TQString path;
- int length;
- TQRegExp rx_line("([^\\s]+)\\s+(.*)");
- do {
- length = proc.readln(line, true);
- if ( length > 0 )
- {
- if ( line[length-1] != '/' )
- line += '/';
- if( rx_line.search( line ) != -1 ) {
- options = rx_line.cap(1);
- path = rx_line.cap(2);
- (*s_shareMap)[path] = options;
- }
- kdDebug(7000) << "Shared dir:" << line << endl;
- }
- } while (length > -1);
-}
-
-
-int KFileShare::isDirectoryShared( const TQString& _path )
-{
- int ret(0);
-
- if ( ! s_shareMap )
- readShareList();
-
- TQString path( _path );
- if ( path[path.length()-1] != '/' )
- path += '/';
- //return s_shareList && s_shareList->contains( path );
- if( (*s_shareMap).contains(path) && !((*s_shareMap)[path].isEmpty()) ) {
- ret+=1;
- if( (*s_shareMap)[path].find("readwrite") != -1 )
- ret+=2;
- }
-
- return ret;
-}
-
-KFileShare::Authorization KFileShare::authorization()
-{
- // The app should do this on startup, but if it doesn't, let's do here.
- if ( s_authorization == NotInitialized )
- readConfig();
- return s_authorization;
-}
-
-TQString KFileShare::findExe( const char* exeName )
-{
- // /usr/sbin on Mandrake, $PATH allows flexibility for other distributions
- TQString path = TQString::fromLocal8Bit(getenv("PATH")) + TQString::fromLatin1(":/usr/sbin");
- TQString exe = KStandardDirs::findExe( exeName, path );
- if (exe.isEmpty())
- kdError() << exeName << " not found in " << path << endl;
- return exe;
-}
-
-bool KFileShare::setShared( const TQString& path, bool shared )
-{
- return SuSEsetShared( path, shared, false );
-}
-
-bool KFileShare::SuSEsetShared( const TQString& path, bool shared, bool rw )
-{
- if (! KFileShare::sharingEnabled() ||
- KFileShare::shareMode() == Advanced)
- return false;
-
- TQString exe = KFileShare::findExe( "fileshareset" );
- if (exe.isEmpty())
- return false;
-
- // we want to share, so we kick it first - just to be sure
- TDEProcess proc;
- proc << exe;
- proc << "--remove";
- proc << path;
- proc.start( TDEProcess::Block );
- proc.clearArguments();
-
- proc << exe;
- if( rw )
- proc << "--rw";
- if ( shared )
- proc << "--add";
- else
- proc << "--remove";
- proc << path;
- proc.start( TDEProcess::Block ); // should be ok, the perl script terminates fast
- bool ok = proc.normalExit() && (proc.exitStatus() == 0);
- kdDebug(7000) << "KFileSharePropsPlugin::setShared normalExit="
- << proc.normalExit() << endl;
- kdDebug(7000) << "KFileSharePropsPlugin::setShared exitStatus="
- << proc.exitStatus() << endl;
- if ( proc.normalExit() ) {
- switch( proc.exitStatus() ) {
- case 1:
- // User is not authorized
- break;
- case 3:
- // Called script with --add, but path was already shared before.
- // Result is nevertheless what the client wanted, so
- // this is alright.
- ok = true;
- break;
- case 4:
- // Invalid mount point
- break;
- case 5:
- // Called script with --remove, but path was not shared before.
- // Result is nevertheless what the client wanted, so
- // this is alright.
- ok = true;
- break;
- case 6:
- // There is no export method
- break;
- case 7:
- // file sharing is disabled
- break;
- case 8:
- // advanced sharing is enabled
- break;
- case 255:
- // Abitrary error
- break;
- }
- }
-
- return ok;
-}
-
-bool KFileShare::sambaActive()
-{
- // rcsmb is not executable by users, try ourselves
- int status = system( "/sbin/checkproc -p /var/run/samba/smbd.pid /usr/sbin/smbd" );
- return status != -1 && WIFEXITED( status ) && WEXITSTATUS( status ) == 0;
-}
-
-bool KFileShare::nfsActive()
-{
- // rcnfsserver is not executable by users, try ourselves
- int status = system( "/sbin/checkproc /usr/sbin/rpc.mountd" );
- if( status != -1 && WIFEXITED( status ) && WEXITSTATUS( status ) == 0 )
- {
- status = system( "/sbin/checkproc -n nfsd" );
- if( status != -1 && WIFEXITED( status ) && WEXITSTATUS( status ) == 0 )
- return true;
- }
- return false;
-}
-
-#include "kfileshare.moc"
diff --git a/kio/kio/kfileshare.h b/kio/kio/kfileshare.h
deleted file mode 100644
index ff473c122..000000000
--- a/kio/kio/kfileshare.h
+++ /dev/null
@@ -1,165 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2001 David Faure <david@mandrakesoft.com>
- Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef kfileshare_h
-#define kfileshare_h
-#include <tqobject.h>
-
-#include <tdelibs_export.h>
-
-class KDirWatch;
-
-/**
- * @internal
- * Do not use, ever.
- */
-class KFileSharePrivate : public TQObject
-{
- Q_OBJECT
-
-public:
- KFileSharePrivate();
- ~KFileSharePrivate();
- KDirWatch* m_watchFile;
- static KFileSharePrivate *self();
- static KFileSharePrivate *_self;
-protected slots: // this is why this class needs to be in the .h
- void slotFileChange(const TQString &);
-};
-
-/**
- * Common functionality for the file sharing
- * (communication with the backend)
- * @since 3.1
- */
-class TDEIO_EXPORT KFileShare
-{
-
-
-public:
- /**
- * Reads the file share configuration file
- */
- static void readConfig();
-
- /**
- * Reads the list of shared folders
- */
- static void readShareList();
-
-
- /**
- * Call this to know if a directory is currently shared
- */
- static int isDirectoryShared( const TQString& path );
-
- enum Authorization { NotInitialized, ErrorNotFound, Authorized, UserNotAllowed };
- /**
- * Call this to know if the current user is authorized to share directories
- */
- static Authorization authorization();
-
- static TQString findExe( const char* exeName );
-
- /**
- * Uses a suid perl script to share the given path
- * with NFS and Samba
- * @param path the path to share
- * @param shared whether the path should be shared or not
- * @returns whether the perl script was successful
- */
- static bool setShared( const TQString& path, bool shared );
-
- /*
- * SuSE only enhancement for now
- */
- static bool SuSEsetShared( const TQString& path, bool shared, bool ro );
-
- /**
- * The used share mode.
- * Simple means that the simple sharing dialog is used and
- * users can share only folders from there HOME folder.
- * Advanced means that the advanced sharing dialog is used and
- * users can share any folder.
- */
- enum ShareMode { Simple, Advanced };
-
- /**
- * Returns whether sharing is enabled
- * If this is false, file sharing is disabled and
- * nobody can share files.
- */
- static bool sharingEnabled();
-
- /**
- * Returns whether file sharing is restricted.
- * If it is not restricted every user can shar files.
- * If it is restricted only users in the configured
- * file share group can share files.
- */
- static bool isRestricted();
-
- /**
- * Returns the group that is used for file sharing.
- * That is, all users in that group are allowed to
- * share files if file sharing is restricted.
- */
- static TQString fileShareGroup();
-
- /**
- * Returns the configured share mode
- */
- static ShareMode shareMode();
-
- /**
- * Returns whether Samba is enabled
- */
- static bool sambaEnabled();
-
- /**
- * Returns whether NFS is enabled
- */
- static bool nfsEnabled();
-
- /**
- * Returns whether Samba is active (service is running)
- * @internal
- */
- static bool sambaActive();
-
- /**
- * Returns whether NFS is active (service is running)
- * @internal
- */
- static bool nfsActive();
-
-private:
- static Authorization s_authorization;
-// static TQStringList* s_shareList;
- static TQMap<TQString,TQString>* s_shareMap;
- static ShareMode s_shareMode;
- static bool s_sambaEnabled;
- static bool s_nfsEnabled;
- static bool s_restricted;
- static TQString s_fileShareGroup;
- static bool s_sharingEnabled;
-
-};
-
-#endif
diff --git a/kio/kio/kmimetype.cpp b/kio/kio/kmimetype.cpp
deleted file mode 100644
index c6f879a73..000000000
--- a/kio/kio/kmimetype.cpp
+++ /dev/null
@@ -1,1172 +0,0 @@
-/* This file is part of the KDE libraries
- * Copyright (C) 1999 Waldo Bastian <bastian@kde.org>
- * David Faure <faure@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-// $Id$
-
-#include <config.h>
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <assert.h>
-#include <dirent.h>
-#include <errno.h>
-#include <stddef.h>
-#include <unistd.h>
-#include <stdlib.h>
-
-#include <kprotocolinfo.h>
-#include <kio/global.h>
-#include "kmimetype.h"
-#include "kservicetypefactory.h"
-#include "kmimemagic.h"
-#include "kservice.h"
-#include "krun.h"
-#include "kautomount.h"
-#include <kdirnotify_stub.h>
-
-#include <tqstring.h>
-#include <tqfile.h>
-#include <kmessageboxwrapper.h>
-
-#include <dcopclient.h>
-#include <dcopref.h>
-#include <kapplication.h>
-#include <kprocess.h>
-#include <kdebug.h>
-#include <kdesktopfile.h>
-#include <kdirwatch.h>
-#include <kiconloader.h>
-#include <klocale.h>
-#include <ksimpleconfig.h>
-#include <kstandarddirs.h>
-#include <kurl.h>
-#include <tdesycoca.h>
-#include <kde_file.h>
-
-template class KSharedPtr<KMimeType>;
-template class TQValueList<KMimeType::Ptr>;
-
-KMimeType::Ptr KMimeType::s_pDefaultType = 0L;
-bool KMimeType::s_bChecked = false;
-
-void KMimeType::buildDefaultType()
-{
- assert ( !s_pDefaultType );
- // Try to find the default type
- KServiceType * mime = KServiceTypeFactory::self()->
- findServiceTypeByName( defaultMimeType() );
-
- if (mime && mime->isType( KST_KMimeType ))
- {
- s_pDefaultType = KMimeType::Ptr((KMimeType *) mime);
- }
- else
- {
- errorMissingMimeType( defaultMimeType() );
- KStandardDirs stdDirs;
- TQString sDefaultMimeType = stdDirs.resourceDirs("mime").first()+defaultMimeType()+".desktop";
- s_pDefaultType = new KMimeType( sDefaultMimeType, defaultMimeType(),
- "unknown", "mime", TQStringList() );
- }
-}
-
-KMimeType::Ptr KMimeType::defaultMimeTypePtr()
-{
- if ( !s_pDefaultType ) // we need a default type first
- buildDefaultType();
- return s_pDefaultType;
-}
-
-// Check for essential mimetypes
-void KMimeType::checkEssentialMimeTypes()
-{
- if ( s_bChecked ) // already done
- return;
- if ( !s_pDefaultType ) // we need a default type first
- buildDefaultType();
-
- s_bChecked = true; // must be done before building mimetypes
-
- // No Mime-Types installed ?
- // Lets do some rescue here.
- if ( !KServiceTypeFactory::self()->checkMimeTypes() )
- {
- KMessageBoxWrapper::error( 0L, i18n( "No mime types installed." ) );
- return; // no point in going any further
- }
-
- if ( KMimeType::mimeType( "inode/directory" ) == s_pDefaultType )
- errorMissingMimeType( "inode/directory" );
- if ( KMimeType::mimeType( "inode/directory-locked" ) == s_pDefaultType )
- errorMissingMimeType( "inode/directory-locked" );
- if ( KMimeType::mimeType( "inode/blockdevice" ) == s_pDefaultType )
- errorMissingMimeType( "inode/blockdevice" );
- if ( KMimeType::mimeType( "inode/chardevice" ) == s_pDefaultType )
- errorMissingMimeType( "inode/chardevice" );
- if ( KMimeType::mimeType( "inode/socket" ) == s_pDefaultType )
- errorMissingMimeType( "inode/socket" );
- if ( KMimeType::mimeType( "inode/fifo" ) == s_pDefaultType )
- errorMissingMimeType( "inode/fifo" );
- if ( KMimeType::mimeType( "application/x-shellscript" ) == s_pDefaultType )
- errorMissingMimeType( "application/x-shellscript" );
- if ( KMimeType::mimeType( "application/x-executable" ) == s_pDefaultType )
- errorMissingMimeType( "application/x-executable" );
- if ( KMimeType::mimeType( "application/x-desktop" ) == s_pDefaultType )
- errorMissingMimeType( "application/x-desktop" );
-}
-
-void KMimeType::errorMissingMimeType( const TQString& _type )
-{
- TQString tmp = i18n( "Could not find mime type\n%1" ).arg( _type );
-
- KMessageBoxWrapper::sorry( 0, tmp );
-}
-
-KMimeType::Ptr KMimeType::mimeType( const TQString& _name )
-{
- KServiceType * mime = KServiceTypeFactory::self()->findServiceTypeByName( _name );
-
- if ( !mime || !mime->isType( KST_KMimeType ) )
- {
- // When building tdesycoca, findServiceTypeByName doesn't create an object
- // but returns one from a dict.
- if ( !KSycoca::self()->isBuilding() )
- delete mime;
- if ( !s_pDefaultType )
- buildDefaultType();
- return s_pDefaultType;
- }
-
- // We got a mimetype
- return KMimeType::Ptr((KMimeType *) mime);
-}
-
-KMimeType::List KMimeType::allMimeTypes()
-{
- return KServiceTypeFactory::self()->allMimeTypes();
-}
-
-KMimeType::Ptr KMimeType::findByURL( const KURL& _url, mode_t _mode,
- bool _is_local_file, bool _fast_mode )
-{
- checkEssentialMimeTypes();
- TQString path = _url.path();
-
- if ( !_fast_mode && !_is_local_file && _url.isLocalFile() )
- _is_local_file = true;
-
- if ( !_fast_mode && _is_local_file && (_mode == 0 || _mode == (mode_t)-1) )
- {
- KDE_struct_stat buff;
- if ( KDE_stat( TQFile::encodeName(path), &buff ) != -1 )
- _mode = buff.st_mode;
- }
-
- // Look at mode_t first
- if ( S_ISDIR( _mode ) )
- {
- // Special hack for local files. We want to see whether we
- // are allowed to enter the directory
- if ( _is_local_file )
- {
- if ( access( TQFile::encodeName(path), R_OK ) == -1 )
- return mimeType( "inode/directory-locked" );
- }
- return mimeType( "inode/directory" );
- }
- if ( S_ISCHR( _mode ) )
- return mimeType( "inode/chardevice" );
- if ( S_ISBLK( _mode ) )
- return mimeType( "inode/blockdevice" );
- if ( S_ISFIFO( _mode ) )
- return mimeType( "inode/fifo" );
- if ( S_ISSOCK( _mode ) )
- return mimeType( "inode/socket" );
- // KMimeMagic can do that better for local files
- if ( !_is_local_file && S_ISREG( _mode ) && ( _mode & ( S_IXUSR | S_IXGRP | S_IXOTH ) ) )
- return mimeType( "application/x-executable" );
-
- TQString fileName ( _url.fileName() );
-
- static const TQString& slash = TDEGlobal::staticQString("/");
- if ( ! fileName.isNull() && !path.endsWith( slash ) )
- {
- // Try to find it out by looking at the filename
- KMimeType::Ptr mime = KServiceTypeFactory::self()->findFromPattern( fileName );
- if ( mime )
- {
- // Found something - can we trust it ? (e.g. don't trust *.pl over HTTP, could be anything)
- if ( _is_local_file || _url.hasSubURL() || // Explicitly trust suburls
- KProtocolInfo::determineMimetypeFromExtension( _url.protocol() ) )
- {
- if ( _is_local_file && !_fast_mode ) {
- if ( mime->patternsAccuracy()<100 )
- {
- KMimeMagicResult* result =
- KMimeMagic::self()->findFileType( path );
-
- if ( result && result->isValid() && result->accuracy() > 0 )
- return mimeType( result->mimeType() );
- }
- }
-
- return mime;
- }
- }
-
- static const TQString& dotdesktop = TDEGlobal::staticQString(".desktop");
- static const TQString& dotkdelnk = TDEGlobal::staticQString(".kdelnk");
- static const TQString& dotdirectory = TDEGlobal::staticQString(".directory");
-
- // Another filename binding, hardcoded, is .desktop:
- if ( fileName.endsWith( dotdesktop ) )
- return mimeType( "application/x-desktop" );
- // Another filename binding, hardcoded, is .kdelnk;
- // this is preserved for backwards compatibility
- if ( fileName.endsWith( dotkdelnk ) )
- return mimeType( "application/x-desktop" );
- // .directory files are detected as x-desktop by mimemagic
- // but don't have a Type= entry. Better cheat and say they are text files
- if ( fileName == dotdirectory )
- return mimeType( "text/plain" );
- }
-
- if ( !_is_local_file || _fast_mode )
- {
- TQString def = KProtocolInfo::defaultMimetype( _url );
- if ( !def.isEmpty() && def != defaultMimeType() )
- {
- // The protocol says it always returns a given mimetype (e.g. text/html for "man:")
- return mimeType( def );
- }
- if ( path.endsWith( slash ) || path.isEmpty() )
- {
- // We have no filename at all. Maybe the protocol has a setting for
- // which mimetype this means (e.g. directory).
- // For HTTP (def==defaultMimeType()) we don't assume anything,
- // because of redirections (e.g. freshmeat downloads).
- if ( def.isEmpty() )
- {
- // Assume inode/directory, if the protocol supports listing.
- if ( KProtocolInfo::supportsListing( _url ) )
- return mimeType( TQString::fromLatin1("inode/directory") );
- else
- return defaultMimeTypePtr(); // == 'no idea', e.g. for "data:,foo/"
- }
- }
-
- // No more chances for non local URLs
- return defaultMimeTypePtr();
- }
-
- // Do some magic for local files
- //kdDebug(7009) << TQString("Mime Type finding for '%1'").arg(path) << endl;
- KMimeMagicResult* result = KMimeMagic::self()->findFileType( path );
-
- // If we still did not find it, we must assume the default mime type
- if ( !result || !result->isValid() )
- return defaultMimeTypePtr();
-
- // The mimemagic stuff was successful
- return mimeType( result->mimeType() );
-}
-
-KMimeType::Ptr KMimeType::findByURL( const KURL& _url, mode_t _mode,
- bool _is_local_file, bool _fast_mode,
- bool *accurate)
-{
- KMimeType::Ptr mime = findByURL(_url, _mode, _is_local_file, _fast_mode);
- if (accurate) *accurate = !(_fast_mode) || ((mime->patternsAccuracy() == 100) && mime != defaultMimeTypePtr());
- return mime;
-}
-
-KMimeType::Ptr KMimeType::diagnoseFileName(const TQString &fileName, TQString &pattern)
-{
- return KServiceTypeFactory::self()->findFromPattern( fileName, &pattern );
-}
-
-KMimeType::Ptr KMimeType::findByPath( const TQString& path, mode_t mode, bool fast_mode )
-{
- KURL u;
- u.setPath(path);
- return findByURL( u, mode, true, fast_mode );
-}
-
-KMimeType::Ptr KMimeType::findByContent( const TQByteArray &data, int *accuracy )
-{
- KMimeMagicResult *result = KMimeMagic::self()->findBufferType(data);
- if (accuracy)
- *accuracy = result->accuracy();
- return mimeType( result->mimeType() );
-}
-
-KMimeType::Ptr KMimeType::findByFileContent( const TQString &fileName, int *accuracy )
-{
- KMimeMagicResult *result = KMimeMagic::self()->findFileType(fileName);
- if (accuracy)
- *accuracy = result->accuracy();
- return mimeType( result->mimeType() );
-}
-
-#define GZIP_MAGIC1 0x1f
-#define GZIP_MAGIC2 0x8b
-
-KMimeType::Format KMimeType::findFormatByFileContent( const TQString &fileName )
-{
- KMimeType::Format result;
- result.compression = Format::NoCompression;
- KMimeType::Ptr mime = findByPath(fileName);
-
- result.text = mime->name().startsWith("text/");
- TQVariant v = mime->property("X-TDE-text");
- if (v.isValid())
- result.text = v.toBool();
-
- if (mime->name().startsWith("inode/"))
- return result;
-
- TQFile f(fileName);
- if (f.open(IO_ReadOnly))
- {
- unsigned char buf[10+1];
- int l = f.readBlock((char *)buf, 10);
- if ((l > 2) && (buf[0] == GZIP_MAGIC1) && (buf[1] == GZIP_MAGIC2))
- result.compression = Format::GZipCompression;
- }
- return result;
-}
-
-KMimeType::KMimeType( const TQString & _fullpath, const TQString& _type, const TQString& _icon,
- const TQString& _comment, const TQStringList& _patterns )
- : KServiceType( _fullpath, _type, _icon, _comment )
-{
- m_lstPatterns = _patterns;
-}
-
-KMimeType::KMimeType( const TQString & _fullpath ) : KServiceType( _fullpath )
-{
- KDesktopFile _cfg( _fullpath, true );
- init ( &_cfg );
-
- if ( !isValid() )
- kdWarning(7009) << "mimetype not valid '" << m_strName << "' (missing entry in the file ?)" << endl;
-}
-
-KMimeType::KMimeType( KDesktopFile *config ) : KServiceType( config )
-{
- init( config );
-
- if ( !isValid() )
- kdWarning(7009) << "mimetype not valid '" << m_strName << "' (missing entry in the file ?)" << endl;
-}
-
-void KMimeType::init( KDesktopFile * config )
-{
- config->setDesktopGroup();
- m_lstPatterns = config->readListEntry( "Patterns", ';' );
-
- // Read the X-TDE-AutoEmbed setting and store it in the properties map
- TQString XKDEAutoEmbed = TQString::fromLatin1("X-TDE-AutoEmbed");
- if ( config->hasKey( XKDEAutoEmbed ) )
- m_mapProps.insert( XKDEAutoEmbed, TQVariant( config->readBoolEntry( XKDEAutoEmbed ), 0 ) );
-
- TQString XKDEText = TQString::fromLatin1("X-TDE-text");
- if ( config->hasKey( XKDEText ) )
- m_mapProps.insert( XKDEText, config->readBoolEntry( XKDEText ) );
-
- TQString XKDEIsAlso = TQString::fromLatin1("X-TDE-IsAlso");
- if ( config->hasKey( XKDEIsAlso ) ) {
- TQString inherits = config->readEntry( XKDEIsAlso );
- if ( inherits != name() )
- m_mapProps.insert( XKDEIsAlso, inherits );
- else
- kdWarning(7009) << "Error: " << inherits << " inherits from itself!!!!" << endl;
- }
-
- TQString XKDEPatternsAccuracy = TQString::fromLatin1("X-TDE-PatternsAccuracy");
- if ( config->hasKey( XKDEPatternsAccuracy ) )
- m_mapProps.insert( XKDEPatternsAccuracy, config->readEntry( XKDEPatternsAccuracy ) );
-
-}
-
-KMimeType::KMimeType( TQDataStream& _str, int offset ) : KServiceType( _str, offset )
-{
- loadInternal( _str ); // load our specific stuff
-}
-
-void KMimeType::load( TQDataStream& _str )
-{
- KServiceType::load( _str );
- loadInternal( _str );
-}
-
-void KMimeType::loadInternal( TQDataStream& _str )
-{
- // kdDebug(7009) << "KMimeType::load( TQDataStream& ) : loading list of patterns" << endl;
- _str >> m_lstPatterns;
-}
-
-void KMimeType::save( TQDataStream& _str )
-{
- KServiceType::save( _str );
- // Warning adding/removing fields here involves a binary incompatible change - update version
- // number in tdesycoca.h
- _str << m_lstPatterns;
-}
-
-TQVariant KMimeType::property( const TQString& _name ) const
-{
- if ( _name == "Patterns" )
- return TQVariant( m_lstPatterns );
-
- return KServiceType::property( _name );
-}
-
-TQStringList KMimeType::propertyNames() const
-{
- TQStringList res = KServiceType::propertyNames();
- res.append( "Patterns" );
-
- return res;
-}
-
-KMimeType::~KMimeType()
-{
-}
-
-TQPixmap KMimeType::pixmap( KIcon::Group _group, int _force_size, int _state,
- TQString * _path ) const
-{
- KIconLoader *iconLoader=TDEGlobal::iconLoader();
- TQString iconName=icon( TQString::null, false );
- if (!iconLoader->extraDesktopThemesAdded())
- {
- TQPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
- if (!pixmap.isNull() ) return pixmap;
-
- iconLoader->addExtraDesktopThemes();
- }
-
- return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
-}
-
-TQPixmap KMimeType::pixmap( const KURL& _url, KIcon::Group _group, int _force_size,
- int _state, TQString * _path ) const
-{
- KIconLoader *iconLoader=TDEGlobal::iconLoader();
- TQString iconName=icon( _url, _url.isLocalFile() );
- if (!iconLoader->extraDesktopThemesAdded())
- {
- TQPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
- if (!pixmap.isNull() ) return pixmap;
-
- iconLoader->addExtraDesktopThemes();
- }
-
- return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
-}
-
-TQPixmap KMimeType::pixmapForURL( const KURL & _url, mode_t _mode, KIcon::Group _group,
- int _force_size, int _state, TQString * _path )
-{
- KIconLoader *iconLoader=TDEGlobal::iconLoader();
- TQString iconName = iconForURL( _url, _mode );
-
- if (!iconLoader->extraDesktopThemesAdded())
- {
- TQPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
- if (!pixmap.isNull() ) return pixmap;
-
- iconLoader->addExtraDesktopThemes();
- }
-
- return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
-
-}
-
-TQString KMimeType::iconForURL( const KURL & _url, mode_t _mode )
-{
- const KMimeType::Ptr mt = findByURL( _url, _mode, _url.isLocalFile(),
- false /*HACK*/);
- static const TQString& unknown = TDEGlobal::staticQString("unknown");
- const TQString mimeTypeIcon = mt->icon( _url, _url.isLocalFile() );
- TQString i = mimeTypeIcon;
-
- // if we don't find an icon, maybe we can use the one for the protocol
- if ( i == unknown || i.isEmpty() || mt == defaultMimeTypePtr()
- // and for the root of the protocol (e.g. trash:/) the protocol icon has priority over the mimetype icon
- || _url.path().length() <= 1 )
- {
- i = favIconForURL( _url ); // maybe there is a favicon?
-
- if ( i.isEmpty() )
- i = KProtocolInfo::icon( _url.protocol() );
-
- // root of protocol: if we found nothing, revert to mimeTypeIcon (which is usually "folder")
- if ( _url.path().length() <= 1 && ( i == unknown || i.isEmpty() ) )
- i = mimeTypeIcon;
- }
- return i;
-}
-
-TQString KMimeType::favIconForURL( const KURL& url )
-{
- // this method will be called quite often, so better not read the config
- // again and again.
- static bool useFavIcons = true;
- static bool check = true;
- if ( check ) {
- check = false;
- TDEConfig *config = TDEGlobal::config();
- TDEConfigGroupSaver cs( config, "HTML Settings" );
- useFavIcons = config->readBoolEntry( "EnableFavicon", true );
- }
-
- if ( url.isLocalFile() || !url.protocol().startsWith("http")
- || !useFavIcons )
- return TQString::null;
-
- DCOPRef kded( "kded", "favicons" );
- DCOPReply result = kded.call( "iconForURL(KURL)", url );
- if ( result.isValid() )
- return result;
-
- return TQString::null;
-}
-
-TQString KMimeType::parentMimeType() const
-{
- TQVariant v = property("X-TDE-IsAlso");
- return v.toString();
-}
-
-bool KMimeType::is( const TQString& mimeTypeName ) const
-{
- if ( name() == mimeTypeName )
- return true;
- TQString st = parentMimeType();
- //if (st.isEmpty()) kdDebug(7009)<<"Parent mimetype is empty"<<endl;
- while ( !st.isEmpty() )
- {
- //kdDebug(7009)<<"Checking parent mime type: "<<st<<endl;
- KMimeType::Ptr ptr = KMimeType::mimeType( st );
- if (!ptr) return false; //error
- if ( ptr->name() == mimeTypeName )
- return true;
- st = ptr->parentMimeType();
- }
- return false;
-}
-
-int KMimeType::patternsAccuracy() const {
- TQVariant v = property("X-TDE-PatternsAccuracy");
- if (!v.isValid()) return 100;
- else
- return v.toInt();
-}
-
-
-/*******************************************************
- *
- * KFolderType
- *
- ******************************************************/
-
-TQString KFolderType::icon( const TQString& _url, bool _is_local ) const
-{
- if ( !_is_local || _url.isEmpty() )
- return KMimeType::icon( _url, _is_local );
-
- return KFolderType::icon( KURL(_url), _is_local );
-}
-
-TQString KFolderType::icon( const KURL& _url, bool _is_local ) const
-{
- if ( !_is_local )
- return KMimeType::icon( _url, _is_local );
-
- KURL u( _url );
- u.addPath( ".directory" );
-
- TQString icon;
- // using KStandardDirs as this one checks for path being
- // a file instead of a directory
- if ( KStandardDirs::exists( u.path() ) )
- {
- KSimpleConfig cfg( u.path(), true );
- cfg.setDesktopGroup();
- icon = cfg.readEntry( "Icon" );
- TQString empty_icon = cfg.readEntry( "EmptyIcon" );
-
- if ( !empty_icon.isEmpty() )
- {
- bool isempty = false;
- DIR *dp = 0L;
- struct dirent *ep;
- dp = opendir( TQFile::encodeName(_url.path()) );
- if ( dp )
- {
- TQValueList<TQCString> entries;
- // Note that readdir isn't guaranteed to return "." and ".." first (#79826)
- ep=readdir( dp ); if ( ep ) entries.append( ep->d_name );
- ep=readdir( dp ); if ( ep ) entries.append( ep->d_name );
- if ( (ep=readdir( dp )) == 0L ) // third file is NULL entry -> empty directory
- isempty = true;
- else {
- entries.append( ep->d_name );
- if ( readdir( dp ) == 0 ) { // only three
- // check if we got "." ".." and ".directory"
- isempty = entries.find( "." ) != entries.end() &&
- entries.find( ".." ) != entries.end() &&
- entries.find( ".directory" ) != entries.end();
- }
- }
- if (!isempty && !strcmp(ep->d_name, ".directory"))
- isempty = (readdir(dp) == 0L);
- closedir( dp );
- }
-
- if ( isempty )
- return empty_icon;
- }
- }
-
- if ( icon.isEmpty() )
- return KMimeType::icon( _url, _is_local );
-
- if ( icon.startsWith( "./" ) ) {
- // path is relative with respect to the location
- // of the .directory file (#73463)
- KURL v( _url );
- v.addPath( icon.mid( 2 ) );
- icon = v.path();
- }
-
- return icon;
-}
-
-TQString KFolderType::comment( const TQString& _url, bool _is_local ) const
-{
- if ( !_is_local || _url.isEmpty() )
- return KMimeType::comment( _url, _is_local );
-
- return KFolderType::comment( KURL(_url), _is_local );
-}
-
-TQString KFolderType::comment( const KURL& _url, bool _is_local ) const
-{
- if ( !_is_local )
- return KMimeType::comment( _url, _is_local );
-
- KURL u( _url );
- u.addPath( ".directory" );
-
- KDesktopFile cfg( u.path(), true );
- TQString comment = cfg.readComment();
- if ( comment.isEmpty() )
- return KMimeType::comment( _url, _is_local );
-
- return comment;
-}
-
-/*******************************************************
- *
- * KDEDesktopMimeType
- *
- ******************************************************/
-
-TQString KDEDesktopMimeType::icon( const TQString& _url, bool _is_local ) const
-{
- if ( !_is_local || _url.isEmpty() )
- return KMimeType::icon( _url, _is_local );
-
- KURL u( _url );
- return icon( u, _is_local );
-}
-
-TQString KDEDesktopMimeType::icon( const KURL& _url, bool _is_local ) const
-{
- if ( !_is_local )
- return KMimeType::icon( _url, _is_local );
-
- KSimpleConfig cfg( _url.path(), true );
- cfg.setDesktopGroup();
- TQString icon = cfg.readEntry( "Icon" );
- TQString type = cfg.readEntry( "Type" );
-
- if ( type == "FSDevice" || type == "FSDev") // need to provide FSDev for
- // backwards compatibility
- {
- TQString unmount_icon = cfg.readEntry( "UnmountIcon" );
- TQString dev = cfg.readEntry( "Dev" );
- if ( !icon.isEmpty() && !unmount_icon.isEmpty() && !dev.isEmpty() )
- {
- TQString mp = TDEIO::findDeviceMountPoint( dev );
- // Is the device not mounted ?
- if ( mp.isNull() )
- return unmount_icon;
- }
- } else if ( type == "Link" ) {
- const TQString emptyIcon = cfg.readEntry( "EmptyIcon" );
- if ( !emptyIcon.isEmpty() ) {
- const TQString u = cfg.readPathEntry( "URL" );
- const KURL url( u );
- if ( url.protocol() == "trash" ) {
- // We need to find if the trash is empty, preferrably without using a KIO job.
- // So instead kio_trash leaves an entry in its config file for us.
- KSimpleConfig trashConfig( "trashrc", true );
- trashConfig.setGroup( "Status" );
- if ( trashConfig.readBoolEntry( "Empty", true ) ) {
- return emptyIcon;
- }
- }
- }
- }
-
- if ( icon.isEmpty() )
- return KMimeType::icon( _url, _is_local );
-
- return icon;
-}
-
-TQPixmap KDEDesktopMimeType::pixmap( const KURL& _url, KIcon::Group _group, int _force_size,
- int _state, TQString * _path ) const
-{
- TQString _icon = icon( _url, _url.isLocalFile() );
- TQPixmap pix = TDEGlobal::iconLoader()->loadIcon( _icon, _group,
- _force_size, _state, _path, false );
- if ( pix.isNull() )
- pix = TDEGlobal::iconLoader()->loadIcon( "unknown", _group,
- _force_size, _state, _path, false );
- return pix;
-}
-
-TQString KDEDesktopMimeType::comment( const TQString& _url, bool _is_local ) const
-{
- if ( !_is_local || _url.isEmpty() )
- return KMimeType::comment( _url, _is_local );
-
- KURL u( _url );
- return comment( u, _is_local );
-}
-
-TQString KDEDesktopMimeType::comment( const KURL& _url, bool _is_local ) const
-{
- if ( !_is_local )
- return KMimeType::comment( _url, _is_local );
-
- KDesktopFile cfg( _url.path(), true );
- TQString comment = cfg.readComment();
- if ( comment.isEmpty() )
- return KMimeType::comment( _url, _is_local );
-
- return comment;
-}
-
-pid_t KDEDesktopMimeType::run( const KURL& u, bool _is_local )
-{
- // It might be a security problem to run external untrusted desktop
- // entry files
- if ( !_is_local )
- return 0;
-
- KSimpleConfig cfg( u.path(), true );
- cfg.setDesktopGroup();
- TQString type = cfg.readEntry( "Type" );
- if ( type.isEmpty() )
- {
- TQString tmp = i18n("The desktop entry file %1 "
- "has no Type=... entry.").arg(u.path() );
- KMessageBoxWrapper::error( 0, tmp);
- return 0;
- }
-
- //kdDebug(7009) << "TYPE = " << type.data() << endl;
-
- if ( type == "FSDevice" )
- return runFSDevice( u, cfg );
- else if ( type == "Application" )
- return runApplication( u, u.path() );
- else if ( type == "Link" )
- {
- cfg.setDollarExpansion( true ); // for URL=file:$HOME (Simon)
- return runLink( u, cfg );
- }
- else if ( type == "MimeType" )
- return runMimeType( u, cfg );
-
-
- TQString tmp = i18n("The desktop entry of type\n%1\nis unknown.").arg( type );
- KMessageBoxWrapper::error( 0, tmp);
-
- return 0;
-}
-
-pid_t KDEDesktopMimeType::runFSDevice( const KURL& _url, const KSimpleConfig &cfg )
-{
- pid_t retval = 0;
-
- TQString dev = cfg.readEntry( "Dev" );
-
- if ( dev.isEmpty() )
- {
- TQString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( _url.path() );
- KMessageBoxWrapper::error( 0, tmp);
- return retval;
- }
-
- TQString mp = TDEIO::findDeviceMountPoint( dev );
- // Is the device already mounted ?
- if ( !mp.isNull() )
- {
- KURL mpURL;
- mpURL.setPath( mp );
- // Open a new window
- retval = KRun::runURL( mpURL, TQString::fromLatin1("inode/directory") );
- }
- else
- {
- bool ro = cfg.readBoolEntry( "ReadOnly", false );
- TQString fstype = cfg.readEntry( "FSType" );
- if ( fstype == "Default" ) // KDE-1 thing
- fstype = TQString::null;
- TQString point = cfg.readEntry( "MountPoint" );
-#ifndef Q_WS_WIN
- (void) new KAutoMount( ro, fstype, dev, point, _url.path() );
-#endif
- retval = -1; // we don't want to return 0, but we don't want to return a pid
- }
-
- return retval;
-}
-
-pid_t KDEDesktopMimeType::runApplication( const KURL& , const TQString & _serviceFile )
-{
- KService s( _serviceFile );
- if ( !s.isValid() )
- // The error message was already displayed, so we can just quit here
- return 0;
-
- KURL::List lst;
- return KRun::run( s, lst );
-}
-
-pid_t KDEDesktopMimeType::runLink( const KURL& _url, const KSimpleConfig &cfg )
-{
- TQString u = cfg.readPathEntry( "URL" );
- if ( u.isEmpty() )
- {
- TQString tmp = i18n("The desktop entry file\n%1\nis of type Link but has no URL=... entry.").arg( _url.prettyURL() );
- KMessageBoxWrapper::error( 0, tmp );
- return 0;
- }
-
- KURL url ( u );
- KRun* run = new KRun(url);
-
- // X-TDE-LastOpenedWith holds the service desktop entry name that
- // was should be preferred for opening this URL if possible.
- // This is used by the Recent Documents menu for instance.
- TQString lastOpenedWidth = cfg.readEntry( "X-TDE-LastOpenedWith" );
- if ( !lastOpenedWidth.isEmpty() )
- run->setPreferredService( lastOpenedWidth );
-
- return -1; // we don't want to return 0, but we don't want to return a pid
-}
-
-pid_t KDEDesktopMimeType::runMimeType( const KURL& url , const KSimpleConfig & )
-{
- // Hmm, can't really use keditfiletype since we might be looking
- // at the global file, or at a file not in share/mimelnk...
-
- TQStringList args;
- args << "openProperties";
- args << url.path();
-
- int pid;
- if ( !TDEApplication::tdeinitExec("kfmclient", args, 0, &pid) )
- return pid;
-
- TDEProcess p;
- p << "kfmclient" << args;
- p.start(TDEProcess::DontCare);
- return p.pid();
-}
-
-TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::builtinServices( const KURL& _url )
-{
- TQValueList<Service> result;
-
- if ( !_url.isLocalFile() )
- return result;
-
- KSimpleConfig cfg( _url.path(), true );
- cfg.setDesktopGroup();
- TQString type = cfg.readEntry( "Type" );
-
- if ( type.isEmpty() )
- return result;
-
- if ( type == "FSDevice" )
- {
- TQString dev = cfg.readEntry( "Dev" );
- if ( dev.isEmpty() )
- {
- TQString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( _url.path() );
- KMessageBoxWrapper::error( 0, tmp);
- }
- else
- {
- TQString mp = TDEIO::findDeviceMountPoint( dev );
- // not mounted ?
- if ( mp.isEmpty() )
- {
- Service mount;
- mount.m_strName = i18n("Mount");
- mount.m_type = ST_MOUNT;
- result.append( mount );
- }
- else
- {
- Service unmount;
-#ifdef HAVE_VOLMGT
- /*
- * Solaris' volume management can only umount+eject
- */
- unmount.m_strName = i18n("Eject");
-#else
- unmount.m_strName = i18n("Unmount");
-#endif
- unmount.m_type = ST_UNMOUNT;
- result.append( unmount );
- }
- }
- }
-
- return result;
-}
-
-TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const TQString& path, bool bLocalFiles )
-{
- KSimpleConfig cfg( path, true );
- return userDefinedServices( path, cfg, bLocalFiles );
-}
-
-TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const TQString& path, TDEConfig& cfg, bool bLocalFiles )
-{
- return userDefinedServices( path, cfg, bLocalFiles, KURL::List() );
-}
-
-TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const TQString& path, TDEConfig& cfg, bool bLocalFiles, const KURL::List & file_list )
-{
- TQValueList<Service> result;
-
- cfg.setDesktopGroup();
-
- if ( !cfg.hasKey( "Actions" ) && !cfg.hasKey( "X-TDE-GetActionMenu") )
- return result;
-
- if ( cfg.hasKey( "TryExec" ) )
- {
- TQString tryexec = cfg.readPathEntry( "TryExec" );
- TQString exe = KStandardDirs::findExe( tryexec );
- if (exe.isEmpty()) {
- return result;
- }
- }
-
- TQStringList keys;
-
- if( cfg.hasKey( "X-TDE-GetActionMenu" )) {
- TQString dcopcall = cfg.readEntry( "X-TDE-GetActionMenu" );
- const TQCString app = TQString(dcopcall.section(' ', 0,0)).utf8();
-
- TQByteArray dataToSend;
- TQDataStream dataStream(dataToSend, IO_WriteOnly);
- dataStream << file_list;
- TQCString replyType;
- TQByteArray replyData;
- TQCString object = TQString(dcopcall.section(' ', 1,-2)).utf8();
- TQString function = dcopcall.section(' ', -1);
- if(!function.endsWith("(KURL::List)")) {
- kdWarning() << "Desktop file " << path << " contains an invalid X-TDE-ShowIfDcopCall - the function must take the exact parameter (KURL::List) and must be specified." << endl;
- } else {
- if(kapp->dcopClient()->call( app, object,
- function.utf8(),
- dataToSend, replyType, replyData, true, -1)
- && replyType == "TQStringList" ) {
-
- TQDataStream dataStreamIn(replyData, IO_ReadOnly);
- dataStreamIn >> keys;
- }
- }
- }
-
- keys += cfg.readListEntry( "Actions", ';' ); //the desktop standard defines ";" as separator!
-
- if ( keys.count() == 0 )
- return result;
-
- TQStringList::ConstIterator it = keys.begin();
- TQStringList::ConstIterator end = keys.end();
- for ( ; it != end; ++it )
- {
- //kdDebug(7009) << "CURRENT KEY = " << (*it) << endl;
-
- TQString group = *it;
-
- if (group == "_SEPARATOR_")
- {
- Service s;
- result.append(s);
- continue;
- }
-
- group.prepend( "Desktop Action " );
-
- bool bInvalidMenu = false;
-
- if ( cfg.hasGroup( group ) )
- {
- cfg.setGroup( group );
-
- if ( !cfg.hasKey( "Name" ) || !cfg.hasKey( "Exec" ) )
- bInvalidMenu = true;
- else
- {
- TQString exec = cfg.readPathEntry( "Exec" );
- if ( bLocalFiles || exec.contains("%U") || exec.contains("%u") )
- {
- Service s;
- s.m_strName = cfg.readEntry( "Name" );
- s.m_strIcon = cfg.readEntry( "Icon" );
- s.m_strExec = exec;
- s.m_type = ST_USER_DEFINED;
- s.m_display = !cfg.readBoolEntry( "NoDisplay" );
- result.append( s );
- }
- }
- }
- else
- bInvalidMenu = true;
-
- if ( bInvalidMenu )
- {
- TQString tmp = i18n("The desktop entry file\n%1\n has an invalid menu entry\n%2.").arg( path ).arg( *it );
- KMessageBoxWrapper::error( 0, tmp );
- }
- }
-
- return result;
-}
-
-void KDEDesktopMimeType::executeService( const TQString& _url, KDEDesktopMimeType::Service& _service )
-{
- KURL u;
- u.setPath(_url);
- KURL::List lst;
- lst.append( u );
- executeService( lst, _service );
-}
-
-void KDEDesktopMimeType::executeService( const KURL::List& urls, KDEDesktopMimeType::Service& _service )
-{
- //kdDebug(7009) << "EXECUTING Service " << _service.m_strName << endl;
-
- if ( _service.m_type == ST_USER_DEFINED )
- {
- kdDebug() << "KDEDesktopMimeType::executeService " << _service.m_strName
- << " first url's path=" << urls.first().path() << " exec=" << _service.m_strExec << endl;
- KRun::run( _service.m_strExec, urls, _service.m_strName, _service.m_strIcon, _service.m_strIcon );
- // The action may update the desktop file. Example: eject unmounts (#5129).
- KDirNotify_stub allDirNotify("*", "KDirNotify*");
- allDirNotify.FilesChanged( urls );
- return;
- }
- else if ( _service.m_type == ST_MOUNT || _service.m_type == ST_UNMOUNT )
- {
- Q_ASSERT( urls.count() == 1 );
- TQString path = urls.first().path();
- //kdDebug(7009) << "MOUNT&UNMOUNT" << endl;
-
- KSimpleConfig cfg( path, true );
- cfg.setDesktopGroup();
- TQString dev = cfg.readEntry( "Dev" );
- if ( dev.isEmpty() )
- {
- TQString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( path );
- KMessageBoxWrapper::error( 0, tmp );
- return;
- }
- TQString mp = TDEIO::findDeviceMountPoint( dev );
-
- if ( _service.m_type == ST_MOUNT )
- {
- // Already mounted? Strange, but who knows ...
- if ( !mp.isEmpty() )
- {
- kdDebug(7009) << "ALREADY Mounted" << endl;
- return;
- }
-
- bool ro = cfg.readBoolEntry( "ReadOnly", false );
- TQString fstype = cfg.readEntry( "FSType" );
- if ( fstype == "Default" ) // KDE-1 thing
- fstype = TQString::null;
- TQString point = cfg.readEntry( "MountPoint" );
-#ifndef Q_WS_WIN
- (void)new KAutoMount( ro, fstype, dev, point, path, false );
-#endif
- }
- else if ( _service.m_type == ST_UNMOUNT )
- {
- // Not mounted? Strange, but who knows ...
- if ( mp.isEmpty() )
- return;
-
-#ifndef Q_WS_WIN
- (void)new KAutoUnmount( mp, path );
-#endif
- }
- }
- else
- assert( 0 );
-}
-
-const TQString & KMimeType::defaultMimeType()
-{
- static const TQString & s_strDefaultMimeType =
- TDEGlobal::staticQString( "application/octet-stream" );
- return s_strDefaultMimeType;
-}
-
-void KMimeType::virtual_hook( int id, void* data )
-{ KServiceType::virtual_hook( id, data ); }
-
-void KFolderType::virtual_hook( int id, void* data )
-{ KMimeType::virtual_hook( id, data ); }
-
-void KDEDesktopMimeType::virtual_hook( int id, void* data )
-{ KMimeType::virtual_hook( id, data ); }
-
-void KExecMimeType::virtual_hook( int id, void* data )
-{ KMimeType::virtual_hook( id, data ); }
-
-#include "kmimetyperesolver.moc"
-
diff --git a/kio/kio/kmimetypechooser.cpp b/kio/kio/kmimetypechooser.cpp
deleted file mode 100644
index 8ab3a69ee..000000000
--- a/kio/kio/kmimetypechooser.cpp
+++ /dev/null
@@ -1,298 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001 - 2004 Anders Lund <anders@alweb.dk>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kmimetypechooser.h"
-
-#include <kconfig.h>
-#include <kiconloader.h>
-#include <klistview.h>
-#include <klocale.h>
-#include <kmimetype.h>
-#include <kprocess.h>
-#include <krun.h>
-#include <tdesycoca.h>
-
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqlineedit.h>
-#include <tqpushbutton.h>
-#include <tqwhatsthis.h>
-
-//BEGIN KMimeTypeChooserPrivate
-class KMimeTypeChooserPrivate
-{
- public:
- KListView *lvMimeTypes;
- TQPushButton *btnEditMimeType;
-
- TQString defaultgroup;
- TQStringList groups;
- int visuals;
-};
-//END
-
-//BEGIN KMimeTypeChooser
-KMimeTypeChooser::KMimeTypeChooser( const TQString &text,
- const TQStringList &selMimeTypes,
- const TQString &defaultGroup,
- const TQStringList &groupsToShow,
- int visuals,
- TQWidget *parent,
- const char *name )
- : TQVBox( parent, name )
-{
- d = new KMimeTypeChooserPrivate();
- d->lvMimeTypes = 0;
- d->btnEditMimeType = 0;
- d->defaultgroup = defaultGroup;
- d->groups = groupsToShow;
- d->visuals = visuals;
-
- setSpacing( KDialogBase::spacingHint() );
-
- if ( !text.isEmpty() )
- {
- new TQLabel( text, this );
- }
-
- d->lvMimeTypes = new KListView( this );
-
- d->lvMimeTypes->addColumn( i18n("Mime Type") );
-// d->lvMimeTypes->setColumnWidthMode( 0, TQListView::Manual );
-
- if ( visuals & Comments )
- {
- d->lvMimeTypes->addColumn( i18n("Comment") );
- d->lvMimeTypes->setColumnWidthMode( 1, TQListView::Manual );
- }
- if ( visuals & Patterns )
- d->lvMimeTypes->addColumn( i18n("Patterns") );
-
- d->lvMimeTypes->setRootIsDecorated( true );
-
- loadMimeTypes( selMimeTypes );
-
- if (visuals & KMimeTypeChooser::EditButton)
- {
- TQHBox *btns = new TQHBox( this );
- ((TQBoxLayout*)btns->layout())->addStretch(1);
- d->btnEditMimeType = new TQPushButton( i18n("&Edit..."), btns );
-
- connect( d->btnEditMimeType, TQT_SIGNAL(clicked()), this, TQT_SLOT(editMimeType()) );
- d->btnEditMimeType->setEnabled( false );
- connect( d->lvMimeTypes, TQT_SIGNAL( doubleClicked ( TQListViewItem * )),
- this, TQT_SLOT( editMimeType()));
- connect( d->lvMimeTypes, TQT_SIGNAL(currentChanged(TQListViewItem*)),
- this, TQT_SLOT(slotCurrentChanged(TQListViewItem*)) );
-
- TQWhatsThis::add( d->btnEditMimeType, i18n(
- "Click this button to display the familiar TDE mime type editor.") );
- }
-}
-
-KMimeTypeChooser::~KMimeTypeChooser()
-{
- delete d;
-}
-
-void KMimeTypeChooser::loadMimeTypes( const TQStringList &_selectedMimeTypes )
-{
- TQStringList selMimeTypes;
-
- if ( !_selectedMimeTypes.isEmpty() )
- selMimeTypes = _selectedMimeTypes;
- else
- selMimeTypes = mimeTypes();
-
- d->lvMimeTypes->clear();
-
- TQMap<TQString,TQListViewItem*> groups;
- // thanks to tdebase/kcontrol/filetypes/filetypesview
- KMimeType::List mimetypes = KMimeType::allMimeTypes();
- TQValueListIterator<KMimeType::Ptr> it(mimetypes.begin());
-
- TQListViewItem *groupItem;
- bool agroupisopen = false;
- TQListViewItem *idefault = 0; //open this, if all other fails
- TQListViewItem *firstChecked = 0; // make this one visible after the loop
-
- for (; it != mimetypes.end(); ++it)
- {
- TQString mimetype = (*it)->name();
- int index = mimetype.find("/");
- TQString maj = mimetype.left(index);
-
- if ( d->groups.count() && !d->groups.contains( maj ) )
- continue;
-
- TQString min = mimetype.right(mimetype.length() - (index+1));
-
- TQMapIterator<TQString,TQListViewItem*> mit = groups.find( maj );
- if ( mit == groups.end() )
- {
- groupItem = new TQListViewItem( d->lvMimeTypes, maj );
- groups.insert( maj, groupItem );
- if ( maj == d->defaultgroup )
- idefault = groupItem;
- }
- else
- groupItem = mit.data();
-
- TQCheckListItem *item = new TQCheckListItem( groupItem, min, TQCheckListItem::CheckBox );
- item->setPixmap( 0, SmallIcon( (*it)->icon(TQString::null,false) ) );
-
- int cl = 1;
-
- if ( d->visuals & Comments )
- {
- item->setText( cl, (*it)->comment(TQString::null, false) );
- cl++;
- }
-
- if ( d->visuals & Patterns )
- item->setText( cl, (*it)->patterns().join("; ") );
-
- if ( selMimeTypes.contains(mimetype) )
- {
- item->setOn( true );
- groupItem->setOpen( true );
- agroupisopen = true;
- if ( !firstChecked )
- firstChecked = item;
- }
- }
-
- if ( firstChecked )
- d->lvMimeTypes->ensureItemVisible( firstChecked );
-
- if ( !agroupisopen && idefault )
- {
- idefault->setOpen( true );
- d->lvMimeTypes->ensureItemVisible( idefault );
- }
-}
-
-void KMimeTypeChooser::editMimeType()
-{
- if ( !(d->lvMimeTypes->currentItem() && (d->lvMimeTypes->currentItem())->parent()) )
- return;
- TQString mt = (d->lvMimeTypes->currentItem()->parent())->text( 0 ) + "/" + (d->lvMimeTypes->currentItem())->text( 0 );
- // thanks to libkonq/konq_operations.cc
- connect( KSycoca::self(), TQT_SIGNAL(databaseChanged()),
- this, TQT_SLOT(slotSycocaDatabaseChanged()) );
- TQString keditfiletype = TQString::fromLatin1("keditfiletype");
- KRun::runCommand( keditfiletype
- + " --parent " + TQString::number( (ulong)topLevelWidget()->winId())
- + " " + TDEProcess::quote(mt),
- keditfiletype, keditfiletype /*unused*/);
-}
-
-void KMimeTypeChooser::slotCurrentChanged(TQListViewItem* i)
-{
- if ( d->btnEditMimeType )
- d->btnEditMimeType->setEnabled( i->parent() );
-}
-
-void KMimeTypeChooser::slotSycocaDatabaseChanged()
-{
- if ( KSycoca::self()->isChanged("mime") )
- loadMimeTypes();
-}
-
-TQStringList KMimeTypeChooser::mimeTypes() const
-{
- TQStringList l;
- TQListViewItemIterator it( d->lvMimeTypes );
- for (; it.current(); ++it)
- {
- if ( it.current()->parent() && ((TQCheckListItem*)it.current())->isOn() )
- l << it.current()->parent()->text(0) + "/" + it.current()->text(0); // FIXME uncecked, should be Ok unless someone changes mimetypes during this!
- }
- return l;
-}
-
-TQStringList KMimeTypeChooser::patterns() const
-{
- TQStringList l;
- KMimeType::Ptr p;
- TQString defMT = KMimeType::defaultMimeType();
- TQListViewItemIterator it( d->lvMimeTypes );
- for (; it.current(); ++it)
- {
- if ( it.current()->parent() && ((TQCheckListItem*)it.current())->isOn() )
- {
- p = KMimeType::mimeType( it.current()->parent()->text(0) + "/" + it.current()->text(0) );
- if ( p->name() != defMT )
- l += p->patterns();
- }
- }
- return l;
-}
-//END
-
-//BEGIN KMimeTypeChooserDialog
-KMimeTypeChooserDialog::KMimeTypeChooserDialog(
- const TQString &caption,
- const TQString& text,
- const TQStringList &selMimeTypes,
- const TQString &defaultGroup,
- const TQStringList &groupsToShow,
- int visuals,
- TQWidget *parent, const char *name )
- : KDialogBase(parent, name, true, caption, Cancel|Ok, Ok)
-{
- m_chooser = new KMimeTypeChooser( text, selMimeTypes,
- defaultGroup, groupsToShow, visuals,
- this, "chooser" );
- setMainWidget(m_chooser);
-
- TDEConfigGroup group( TDEGlobal::config(), "KMimeTypeChooserDialog");
- TQSize defaultSize( 400, 300 );
- resize( group.readSizeEntry("size", &defaultSize) );
-}
-
-KMimeTypeChooserDialog::KMimeTypeChooserDialog(
- const TQString &caption,
- const TQString& text,
- const TQStringList &selMimeTypes,
- const TQString &defaultGroup,
- TQWidget *parent, const char *name )
- : KDialogBase(parent, name, true, caption, Cancel|Ok, Ok)
-{
- m_chooser = new KMimeTypeChooser( text, selMimeTypes,
- defaultGroup, TQStringList(),
- KMimeTypeChooser::Comments|KMimeTypeChooser::Patterns|KMimeTypeChooser::EditButton,
- this, "chooser" );
- setMainWidget(m_chooser);
-
- TDEConfigGroup group( TDEGlobal::config(), "KMimeTypeChooserDialog");
- TQSize defaultSize( 400, 300 );
- resize( group.readSizeEntry("size", &defaultSize) );
-}
-
-
-KMimeTypeChooserDialog::~KMimeTypeChooserDialog()
-{
- TDEConfigGroup group( TDEGlobal::config(), "KMimeTypeChooserDialog");
- group.writeEntry("size", size());
-}
-
-//END KMimeTypeChooserDialog
-
-// kate: space-indent on; indent-width 2; replace-tabs on;
-#include "kmimetypechooser.moc"
diff --git a/kio/kio/knfsshare.cpp b/kio/kio/knfsshare.cpp
deleted file mode 100644
index 394120009..000000000
--- a/kio/kio/knfsshare.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2004 Jan Schaefer <j_schaef@informatik.uni-kl.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqdict.h>
-#include <tqfile.h>
-#include <tqtextstream.h>
-
-#include <kdirwatch.h>
-#include <kstaticdeleter.h>
-#include <kdebug.h>
-#include <kconfig.h>
-
-#include "knfsshare.h"
-
-class KNFSSharePrivate
-{
-public:
- KNFSSharePrivate();
-
- bool readExportsFile();
- bool findExportsFile();
-
- TQDict<bool> sharedPaths;
- TQString exportsFile;
-};
-
-KNFSSharePrivate::KNFSSharePrivate()
-{
- if (findExportsFile())
- readExportsFile();
-}
-
-/**
- * Try to find the nfs config file path
- * First tries the kconfig, then checks
- * several well-known paths
- * @return wether an 'exports' file was found.
- **/
-bool KNFSSharePrivate::findExportsFile() {
- TDEConfig config("knfsshare");
- config.setGroup("General");
- exportsFile = config.readPathEntry("exportsFile");
-
- if ( TQFile::exists(exportsFile) )
- return true;
-
- if ( TQFile::exists("/etc/exports") )
- exportsFile = "/etc/exports";
- else {
- kdDebug(7000) << "KNFSShare: Could not found exports file!" << endl;
- return false;
- }
-
- config.writeEntry("exportsFile",exportsFile);
- return true;
-}
-
-/**
- * Reads all paths from the exports file
- * and fills the sharedPaths dict with the values
- */
-bool KNFSSharePrivate::readExportsFile() {
- TQFile f(exportsFile);
-
- kdDebug(7000) << "KNFSShare::readExportsFile " << exportsFile << endl;
-
- if (!f.open(IO_ReadOnly)) {
- kdError() << "KNFSShare: Could not open " << exportsFile << endl;
- return false;
- }
-
-
- sharedPaths.clear();
-
- TQTextStream s( &f );
-
- bool continuedLine = false; // is true if the line before ended with a backslash
- TQString completeLine;
-
- while ( !s.eof() )
- {
- TQString currentLine = s.readLine().stripWhiteSpace();
-
- if (continuedLine) {
- completeLine += currentLine;
- continuedLine = false;
- }
- else
- completeLine = currentLine;
-
- // is the line continued in the next line ?
- if ( completeLine[completeLine.length()-1] == '\\' )
- {
- continuedLine = true;
- // remove the ending backslash
- completeLine.truncate( completeLine.length()-1 );
- continue;
- }
-
- // comments or empty lines
- if (completeLine.isEmpty() ||
- '#' == completeLine[0])
- {
- continue;
- }
-
- TQString path;
-
- // Handle quotation marks
- if ( completeLine[0] == '"' ) {
- int i = completeLine.find('"',1);
- if (i == -1) {
- kdError() << "KNFSShare: Parse error: Missing quotation mark: " << completeLine << endl;
- continue;
- }
- path = completeLine.mid(1,i-1);
-
- } else { // no quotation marks
- int i = completeLine.find(' ');
- if (i == -1)
- i = completeLine.find('\t');
-
- if (i == -1)
- path = completeLine;
- else
- path = completeLine.left(i);
-
- }
-
- kdDebug(7000) << "KNFSShare: Found path: " << path << endl;
-
- // normalize path
- if ( path[path.length()-1] != '/' )
- path += '/';
-
- bool b = true;
- sharedPaths.insert(path,&b);
- }
-
- f.close();
-
- return true;
-
-}
-
-KNFSShare::KNFSShare() {
- d = new KNFSSharePrivate();
- if (TQFile::exists(d->exportsFile)) {
- KDirWatch::self()->addFile(d->exportsFile);
- connect(KDirWatch::self(), TQT_SIGNAL(dirty (const TQString&)),this,
- TQT_SLOT(slotFileChange(const TQString&)));
- }
-}
-
-KNFSShare::~KNFSShare() {
- if (TQFile::exists(d->exportsFile)) {
- KDirWatch::self()->removeFile(d->exportsFile);
- }
- delete d;
-}
-
-
-bool KNFSShare::isDirectoryShared( const TQString & path ) const {
- TQString fixedPath = path;
- if ( path[path.length()-1] != '/' )
- fixedPath += '/';
-
- return d->sharedPaths.find(fixedPath) != 0;
-}
-
-TQStringList KNFSShare::sharedDirectories() const {
- TQStringList result;
- TQDictIterator<bool> it(d->sharedPaths);
- for( ; it.current(); ++it )
- result << it.currentKey();
-
- return result;
-}
-
-TQString KNFSShare::exportsPath() const {
- return d->exportsFile;
-}
-
-
-
-void KNFSShare::slotFileChange( const TQString & path ) {
- if (path == d->exportsFile)
- d->readExportsFile();
-
- emit changed();
-}
-
-KNFSShare* KNFSShare::_instance = 0L;
-static KStaticDeleter<KNFSShare> ksdNFSShare;
-
-KNFSShare* KNFSShare::instance() {
- if (! _instance )
- _instance = ksdNFSShare.setObject(_instance, new KNFSShare());
-
- return _instance;
-}
-
-#include "knfsshare.moc"
-
diff --git a/kio/kio/kprotocolinfo.h b/kio/kio/kprotocolinfo.h
deleted file mode 100644
index 10addc610..000000000
--- a/kio/kio/kprotocolinfo.h
+++ /dev/null
@@ -1,688 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1999 Torben Weis <weis@kde.org>
- Copyright (C) 2000-2001 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __kprotocolinfo_h__
-#define __kprotocolinfo_h__
-
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqdatastream.h>
-
-#include <kurl.h>
-#include <tdesycocaentry.h>
-#include <tdesycocatype.h>
-
-/**
- * Information about I/O (Internet, etc.) protocols supported by KDE.
-
- * This class is useful if you want to know which protocols
- * KDE supports. In addition you can find out lots of information
- * about a certain protocol. A KProtocolInfo instance represents a
- * single protocol. Most of the functionality is provided by the static
- * methods that scan the *.protocol files of all installed kioslaves to get
- * this information.
- *
- * *.protocol files are installed in the "services" resource.
- *
- * @author Torben Weis <weis@kde.org>
- */
-class TDEIO_EXPORT KProtocolInfo : public KSycocaEntry
-{
- friend class KProtocolInfoFactory;
- K_SYCOCATYPE( KST_KProtocolInfo, KSycocaEntry )
-
-public:
- typedef KSharedPtr<KProtocolInfo> Ptr;
-
-public:
- /**
- * Read a protocol description file
- * @param path the path of the description file
- */
- KProtocolInfo( const TQString & path); // KDE4: make private and add friend class KProtocolInfoBuildFactory
- // Then we can get rid of the d pointer
-
- /**
- * Returns whether the protocol description file is valid.
- * @return true if valid, false otherwise
- */
- virtual bool isValid() const { return !m_name.isEmpty(); }
-
- /**
- * Returns the name of the protocol.
- *
- * This corresponds to the "protocol=" field in the protocol description file.
- *
- * @return the name of the protocol
- * @see KURL::protocol()
- */
- virtual TQString name() const { return m_name; }
-
- //
- // Static functions:
- //
-
- /**
- * Returns list of all known protocols.
- * @return a list of all known protocols
- */
- static TQStringList protocols();
-
- /**
- * Returns whether a protocol is installed that is able to handle @p url.
- *
- * @param url the url to check
- * @return true if the protocol is known
- * @see name()
- */
- static bool isKnownProtocol( const KURL &url );
-
- /**
- * Same as above except you can supply just the protocol instead of
- * the whole URL.
- */
- static bool isKnownProtocol( const TQString& protocol )
-#ifdef KPROTOCOLINFO_TDECORE
- KDE_WEAK_SYMBOL
-#endif
- ;
-
- /**
- * Returns the library / executable to open for the protocol @p protocol
- * Example : "kio_ftp", meaning either the executable "kio_ftp" or
- * the library "kio_ftp.la" (recommended), whichever is available.
- *
- * This corresponds to the "exec=" field in the protocol description file.
- * @param protocol the protocol to check
- * @return the executable of library to open, or TQString::null for
- * unsupported protocols
- * @see KURL::protocol()
- */
- static TQString exec( const TQString& protocol );
-
- /**
- * Describes the type of a protocol.
- */
- enum Type { T_STREAM, ///< protocol returns a stream
- T_FILESYSTEM, ///<protocol describes location in a file system
- T_NONE, ///< no information about the tyope available
- T_ERROR ///< used to signal an error
- };
-
- /**
- * Returns whether the protocol should be treated as a filesystem
- * or as a stream when reading from it.
- *
- * This corresponds to the "input=" field in the protocol description file.
- * Valid values for this field are "filesystem", "stream" or "none" (default).
- *
- * @param url the url to check
- * @return the input type of the given @p url
- */
- static Type inputType( const KURL &url );
-
- /**
- * Returns whether the protocol should be treated as a filesystem
- * or as a stream when writing to it.
- *
- * This corresponds to the "output=" field in the protocol description file.
- * Valid values for this field are "filesystem", "stream" or "none" (default).
- *
- * @param url the url to check
- * @return the output type of the given @p url
- */
- static Type outputType( const KURL &url );
-
- /**
- * Returns the list of fields this protocol returns when listing
- * The current possibilities are
- * Name, Type, Size, Date, AccessDate, Access, Owner, Group, Link, URL, MimeType
- * as well as Extra1, Extra2 etc. for extra fields (see extraFields).
- *
- * This corresponds to the "listing=" field in the protocol description file.
- * The supported fields should be separated with ',' in the protocol description file.
- *
- * @param url the url to check
- * @return a list of field names
- */
- static TQStringList listing( const KURL &url );
-
- /**
- * Definition of an extra field in the UDS entries, returned by a listDir operation.
- *
- * The name is the name of the column, translated.
- *
- * The type name comes from TQVariant::typeName()
- * Currently supported types: "TQString", "TQDateTime" (ISO-8601 format)
- *
- * @since 3.2
- */
- struct ExtraField {
- ExtraField() {} // for QValueList
- ExtraField(const TQString& _name, const TQString& _type )
- : name(_name), type(_type) {
- }
- TQString name;
- TQString type; // KDE4: make it TQVariant::Type
- };
- typedef TQValueList<ExtraField > ExtraFieldList;
- /**
- * Definition of extra fields in the UDS entries, returned by a listDir operation.
- *
- * This corresponds to the "ExtraNames=" and "ExtraTypes=" fields in the protocol description file.
- * Those two lists should be separated with ',' in the protocol description file.
- * See ExtraField for details about names and types
- *
- * @since 3.2
- */
- static ExtraFieldList extraFields( const KURL& url );
-
- /**
- * Returns whether the protocol can act as a source protocol.
- *
- * A source protocol retrieves data from or stores data to the
- * location specified by a URL.
- * A source protocol is the opposite of a filter protocol.
- *
- * The "source=" field in the protocol description file determines
- * whether a protocol is a source protocol or a filter protocol.
- * @param url the url to check
- * @return true if the protocol is a source of data (e.g. http), false if the
- * protocol is a filter (e.g. gzip)
- */
- static bool isSourceProtocol( const KURL &url );
-
- /**
- * Returns whether the protocol can act as a helper protocol.
- * A helper protocol invokes an external application and does not return
- * a file or stream.
- *
- * This corresponds to the "helper=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol is a helper protocol (e.g. vnc), false
- * if not (e.g. http)
- */
- static bool isHelperProtocol( const KURL &url );
-
- /**
- * Same as above except you can supply just the protocol instead of
- * the whole URL.
- */
- static bool isHelperProtocol( const TQString& protocol )
-#ifdef KPROTOCOLINFO_TDECORE
- KDE_WEAK_SYMBOL
-#endif
- ;
-
- /**
- * Returns whether the protocol can act as a filter protocol.
- *
- * A filter protocol can operate on data that is passed to it
- * but does not retrieve/store data itself, like gzip.
- * A filter protocol is the opposite of a source protocol.
- *
- * The "source=" field in the protocol description file determines
- * whether a protocol is a source protocol or a filter protocol.
- * Valid values for this field are "true" (default) for source protocol or
- * "false" for filter protocol.
- *
- * @param url the url to check
- * @return true if the protocol is a filter (e.g. gzip), false if the
- * protocol is a helper or source
- */
- static bool isFilterProtocol( const KURL &url );
-
- /**
- * Same as above except you can supply just the protocol instead of
- * the whole URL.
- */
- static bool isFilterProtocol( const TQString& protocol )
-#ifdef KPROTOCOLINFO_TDECORE
- KDE_WEAK_SYMBOL
-#endif
- ;
-
- /**
- * Returns whether the protocol can list files/objects.
- * If a protocol supports listing it can be browsed in e.g. file-dialogs
- * and konqueror.
- *
- * Whether a protocol supports listing is determined by the "listing="
- * field in the protocol description file.
- * If the protocol support listing it should list the fields it provides in
- * this field. If the protocol does not support listing this field should
- * remain empty (default.)
- *
- * @param url the url to check
- * @return true if the protocol support listing
- * @see listing()
- */
- static bool supportsListing( const KURL &url );
-
- /**
- * Returns whether the protocol can retrieve data from URLs.
- *
- * This corresponds to the "reading=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if it is possible to read from the URL
- */
- static bool supportsReading( const KURL &url );
-
- /**
- * Returns whether the protocol can store data to URLs.
- *
- * This corresponds to the "writing=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol supports writing
- */
- static bool supportsWriting( const KURL &url );
-
- /**
- * Returns whether the protocol can create directories/folders.
- *
- * This corresponds to the "makedir=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol can create directories
- */
- static bool supportsMakeDir( const KURL &url );
-
- /**
- * Returns whether the protocol can delete files/objects.
- *
- * This corresponds to the "deleting=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol supports deleting
- */
- static bool supportsDeleting( const KURL &url );
-
- /**
- * Returns whether the protocol can create links between files/objects.
- *
- * This corresponds to the "linking=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol supports linking
- */
- static bool supportsLinking( const KURL &url );
-
- /**
- * Returns whether the protocol can move files/objects between different
- * locations.
- *
- * This corresponds to the "moving=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol supports moving
- */
- static bool supportsMoving( const KURL &url );
-
- /**
- * Returns whether the protocol can copy files/objects directly from the
- * filesystem itself. If not, the application will read files from the
- * filesystem using the file-protocol and pass the data on to the destination
- * protocol.
- *
- * This corresponds to the "copyFromFile=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol can copy files from the local file system
- */
- static bool canCopyFromFile( const KURL &url );
-
- /**
- * Returns whether the protocol can copy files/objects directly to the
- * filesystem itself. If not, the application will receive the data from
- * the source protocol and store it in the filesystem using the
- * file-protocol.
- *
- * This corresponds to the "copyToFile=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol can copy files to the local file system
- */
- static bool canCopyToFile( const KURL &url );
-
- /**
- * Returns whether the protocol can rename (i.e. move fast) files/objects
- * directly from the filesystem itself. If not, the application will read
- * files from the filesystem using the file-protocol and pass the data on
- * to the destination protocol.
- *
- * This corresponds to the "renameFromFile=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol can rename/move files from the local file system
- * @since 3.4
- */
- static bool canRenameFromFile( const KURL &url );
-
- /**
- * Returns whether the protocol can rename (i.e. move fast) files/objects
- * directly to the filesystem itself. If not, the application will receive
- * the data from the source protocol and store it in the filesystem using the
- * file-protocol.
- *
- * This corresponds to the "renameToFile=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol can rename files to the local file system
- * @since 3.4
- */
- static bool canRenameToFile( const KURL &url );
-
- /**
- * Returns whether the protocol can recursively delete directories by itself.
- * If not (the usual case) then KIO will list the directory and delete files
- * and empty directories one by one.
- *
- * This corresponds to the "deleteRecursive=" field in the protocol description file.
- * Valid values for this field are "true" or "false" (default).
- *
- * @param url the url to check
- * @return true if the protocol can delete non-empty directories by itself.
- * @since 3.4
- */
- static bool canDeleteRecursive( const KURL &url );
-
- typedef enum { Name, FromURL } FileNameUsedForCopying;
-
- /**
- * This setting defines the strategy to use for generating a filename, when
- * copying a file or directory to another directory. By default the destination
- * filename is made out of the filename in the source URL. However if the
- * ioslave displays names that are different from the filename of the URL
- * (e.g. kio_fonts shows Arial for arial.ttf, or kio_trash shows foo.txt and
- * uses some internal URL), using Name means that the display name (UDS_NAME)
- * will be used to as the filename in the destination directory.
- *
- * This corresponds to the "fileNameUsedForCopying=" field in the protocol description file.
- * Valid values for this field are "Name" or "FromURL" (default).
- *
- * @param url the url to check
- * @return how to generate the filename in the destination directory when copying/moving
- * @since 3.4
- */
- static FileNameUsedForCopying fileNameUsedForCopying( const KURL &url );
-
- /**
- * Returns default mimetype for this URL based on the protocol.
- *
- * This corresponds to the "defaultMimetype=" field in the protocol description file.
- *
- * @param url the url to check
- * @return the default mime type of the protocol, or null if unknown
- */
- static TQString defaultMimetype( const KURL& url );
-
- /**
- * Returns the name of the icon, associated with the specified protocol.
- *
- * This corresponds to the "Icon=" field in the protocol description file.
- *
- * @param protocol the protocol to check
- * @return the icon of the protocol, or null if unknown
- */
- static TQString icon( const TQString& protocol );
-
- /**
- * Returns the name of the config file associated with the
- * specified protocol. This is useful if two similar protocols
- * need to share a single config file, e.g. http and https.
- *
- * This corresponds to the "config=" field in the protocol description file.
- * The default is the protocol name, see name()
- *
- * @param protocol the protocol to check
- * @return the config file, or null if unknown
- */
- static TQString config( const TQString& protocol );
-
- /**
- * Returns the soft limit on the number of slaves for this protocol.
- * This limits the number of slaves used for a single operation, note
- * that multiple operations may result in a number of instances that
- * exceeds this soft limit.
- *
- * This corresponds to the "maxInstances=" field in the protocol description file.
- * The default is 1.
- *
- * @param protocol the protocol to check
- * @return the maximum number of slaves, or 1 if unknown
- */
- static int maxSlaves( const TQString& protocol );
-
- /**
- * Returns whether mimetypes can be determined based on extension for this
- * protocol. For some protocols, e.g. http, the filename extension in the URL
- * can not be trusted to truly reflect the file type.
- *
- * This corresponds to the "determineMimetypeFromExtension=" field in the protocol description file.
- * Valid values for this field are "true" (default) or "false".
- *
- * @param protocol the protocol to check
- * @return true if the mime types can be determined by extension
- */
- static bool determineMimetypeFromExtension( const TQString &protocol );
-
- /**
- * Returns the documentation path for the specified protocol.
- *
- * This corresponds to the "DocPath=" field in the protocol description file.
- *
- * @param protocol the protocol to check
- * @return the docpath of the protocol, or null if unknown
- * @since 3.2
- */
- static TQString docPath( const TQString& protocol );
-
- /**
- * Returns the protocol class for the specified protocol.
- *
- * This corresponds to the "Class=" field in the protocol description file.
- *
- * The following classes are defined:
- * @li ":internet" for common internet protocols
- * @li ":local" for protocols that access local resources
- *
- * Protocol classes always start with a ':' so that they can not be confused with
- * the protocols themselves.
- *
- * @param protocol the protocol to check
- * @return the class of the protocol, or null if unknown
- * @since 3.2
- */
- static TQString protocolClass( const TQString& protocol );
-
- /**
- * Returns whether file previews should be shown for the specified protocol.
- *
- * This corresponds to the "ShowPreviews=" field in the protocol description file.
- *
- * By default previews are shown if protocolClass is :local.
- *
- * @param protocol the protocol to check
- * @return true if previews should be shown by default, false otherwise
- * @since 3.2
- */
- static bool showFilePreview( const TQString& protocol );
-
- /**
- * Returns the suggested URI parsing mode for the KURL parser.
- *
- * This corresponds to the "URIMode=" field in the protocol description file.
- *
- * The following parsing modes are defined:
- * @li "url" for a standards compliant URL
- * @li "rawuri" for a non-conformant URI for which URL parsing would be meaningless
- * @li "mailto" for a mailto style URI (the path part contains only an email address)
- *
- * @param protocol the protocol to check
- * @return the suggested parsing mode, or KURL::Auto if unspecified
- *
- * @since 3.2
- */
- static KURL::URIMode uriParseMode( const TQString& protocol );
-
- /**
- * Returns the list of capabilities provided by the kioslave implementing
- * this protocol.
- *
- * This corresponds to the "Capabilities=" field in the protocol description file.
- *
- * The capability names are not defined globally, they are up to each
- * slave implementation. For example when adding support for a new
- * special command for mounting, one would add the string "Mount" to the
- * capabilities list, and applications could check for that string
- * before sending a special() command that would otherwise do nothing
- * on older kioslave implementations.
- *
- * @param protocol the protocol to check
- * @return the list of capabilities.
- *
- * @since 3.3
- */
- static TQStringList capabilities( const TQString& protocol );
-
- /**
- * Returns the name of the protocol through which the request
- * will be routed if proxy support is enabled.
- *
- * A good example of this is the ftp protocol for which proxy
- * support is commonly handled by the http protocol.
- *
- * This corresponds to the "ProxiedBy=" in the protocol description file.
- *
- * @since 3.3
- */
- static TQString proxiedBy( const TQString& protocol );
-
-public:
- // Internal functions:
- /**
- * @internal construct a KProtocolInfo from a stream
- */
- KProtocolInfo( TQDataStream& _str, int offset);
-
- virtual ~KProtocolInfo();
-
- /**
- * @internal
- * Load the protocol info from a stream.
- */
- virtual void load(TQDataStream& );
-
- /**
- * @internal
- * Save the protocol info to a stream.
- */
- virtual void save(TQDataStream& );
-
- ////////////////////////// DEPRECATED /////////////////////////
- // The following methods are deprecated:
-
- /// @deprecated
- static Type inputType( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static Type outputType( const TQString& protocol ) KDE_DEPRECATED;
- /**
- * @deprecated
- * Returns the list of fields this protocol returns when listing
- * The current possibilities are
- * Name, Type, Size, Date, AccessDate, Access, Owner, Group, Link, URL, MimeType
- */
- static TQStringList listing( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool isSourceProtocol( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool supportsListing( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool supportsReading( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool supportsWriting( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool supportsMakeDir( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool supportsDeleting( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool supportsLinking( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool supportsMoving( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool canCopyFromFile( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static bool canCopyToFile( const TQString& protocol ) KDE_DEPRECATED;
- /// @deprecated
- static TQString defaultMimetype( const TQString& protocol) KDE_DEPRECATED;
- //////////////////////// END DEPRECATED ///////////////////////
-
-protected:
- TQString m_name;
- TQString m_exec;
- Type m_inputType;
- Type m_outputType;
- TQStringList m_listing;
- bool m_isSourceProtocol;
- bool m_isHelperProtocol;
- bool m_supportsListing;
- bool m_supportsReading;
- bool m_supportsWriting;
- bool m_supportsMakeDir;
- bool m_supportsDeleting;
- bool m_supportsLinking;
- bool m_supportsMoving;
- TQString m_defaultMimetype;
- bool m_determineMimetypeFromExtension;
- TQString m_icon;
- bool m_canCopyFromFile;
- bool m_canCopyToFile;
- TQString m_config;
- int m_maxSlaves;
-
- bool canRenameFromFile() const; // for kprotocolinfo_tdecore
- bool canRenameToFile() const; // for kprotocolinfo_tdecore
- bool canDeleteRecursive() const; // for kprotocolinfo_tdecore
- FileNameUsedForCopying fileNameUsedForCopying() const; // for kprotocolinfo_tdecore
- static KProtocolInfo* findProtocol(const KURL &url); // for kprotocolinfo_tdecore
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class KProtocolInfoPrivate;
- KProtocolInfoPrivate* d;
-};
-
-TDEIO_EXPORT TQDataStream& operator>>( TQDataStream& s, KProtocolInfo::ExtraField& field );
-TDEIO_EXPORT TQDataStream& operator<<( TQDataStream& s, const KProtocolInfo::ExtraField& field );
-
-#endif
diff --git a/kio/kio/kprotocolmanager.cpp b/kio/kio/kprotocolmanager.cpp
deleted file mode 100644
index a4f8169f5..000000000
--- a/kio/kio/kprotocolmanager.cpp
+++ /dev/null
@@ -1,534 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1999 Torben Weis <weis@kde.org>
- Copyright (C) 2000- Waldo Bastain <bastain@kde.org>
- Copyright (C) 2000- Dawit Alemayehu <adawit@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <string.h>
-#include <sys/utsname.h>
-
-#include <dcopref.h>
-#include <kdebug.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kconfig.h>
-#include <kstandarddirs.h>
-#include <klibloader.h>
-#include <kstringhandler.h>
-#include <kstaticdeleter.h>
-#include <kio/slaveconfig.h>
-#include <kio/ioslave_defaults.h>
-#include <kio/http_slave_defaults.h>
-
-#include "kprotocolmanager.h"
-
-class
-KProtocolManagerPrivate
-{
-public:
- KProtocolManagerPrivate();
-
- ~KProtocolManagerPrivate();
-
- TDEConfig *config;
- TDEConfig *http_config;
- bool init_busy;
- KURL url;
- TQString protocol;
- TQString proxy;
- TQString modifiers;
- TQString useragent;
-};
-
-static KProtocolManagerPrivate* d = 0;
-static KStaticDeleter<KProtocolManagerPrivate> kpmpksd;
-
-KProtocolManagerPrivate::KProtocolManagerPrivate()
- :config(0), http_config(0), init_busy(false)
-{
- kpmpksd.setObject(d, this);
-}
-
-KProtocolManagerPrivate::~KProtocolManagerPrivate()
-{
- delete config;
- delete http_config;
-}
-
-
-// DEFAULT USERAGENT STRING
-#define CFG_DEFAULT_UAGENT(X) \
-TQString("Mozilla/5.0 (compatible; Konqueror/%1.%2%3) KHTML/%4.%5.%6 (like Gecko)") \
- .arg(TDE_VERSION_MAJOR).arg(TDE_VERSION_MINOR).arg(X).arg(TDE_VERSION_MAJOR).arg(TDE_VERSION_MINOR).arg(TDE_VERSION_RELEASE)
-
-void KProtocolManager::reparseConfiguration()
-{
- kpmpksd.destructObject();
-
- // Force the slave config to re-read its config...
- TDEIO::SlaveConfig::self()->reset ();
-}
-
-TDEConfig *KProtocolManager::config()
-{
- if (!d)
- d = new KProtocolManagerPrivate;
-
- if (!d->config)
- {
- d->config = new TDEConfig("kioslaverc", true, false);
- }
- return d->config;
-}
-
-TDEConfig *KProtocolManager::http_config()
-{
- if (!d)
- d = new KProtocolManagerPrivate;
-
- if (!d->http_config)
- {
- d->http_config = new TDEConfig("kio_httprc", false, false);
- }
- return d->http_config;
-}
-
-/*=============================== TIMEOUT SETTINGS ==========================*/
-
-int KProtocolManager::readTimeout()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- int val = cfg->readNumEntry( "ReadTimeout", DEFAULT_READ_TIMEOUT );
- return QMAX(MIN_TIMEOUT_VALUE, val);
-}
-
-int KProtocolManager::connectTimeout()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- int val = cfg->readNumEntry( "ConnectTimeout", DEFAULT_CONNECT_TIMEOUT );
- return QMAX(MIN_TIMEOUT_VALUE, val);
-}
-
-int KProtocolManager::proxyConnectTimeout()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- int val = cfg->readNumEntry( "ProxyConnectTimeout", DEFAULT_PROXY_CONNECT_TIMEOUT );
- return QMAX(MIN_TIMEOUT_VALUE, val);
-}
-
-int KProtocolManager::responseTimeout()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- int val = cfg->readNumEntry( "ResponseTimeout", DEFAULT_RESPONSE_TIMEOUT );
- return QMAX(MIN_TIMEOUT_VALUE, val);
-}
-
-/*========================== PROXY SETTINGS =================================*/
-
-bool KProtocolManager::useProxy()
-{
- return proxyType() != NoProxy;
-}
-
-bool KProtocolManager::useReverseProxy()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( "Proxy Settings" );
- return cfg->readBoolEntry("ReversedException", false);
-}
-
-KProtocolManager::ProxyType KProtocolManager::proxyType()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( "Proxy Settings" );
- return static_cast<ProxyType>(cfg->readNumEntry( "ProxyType" ));
-}
-
-KProtocolManager::ProxyAuthMode KProtocolManager::proxyAuthMode()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( "Proxy Settings" );
- return static_cast<ProxyAuthMode>(cfg->readNumEntry( "AuthMode" ));
-}
-
-/*========================== CACHING =====================================*/
-
-bool KProtocolManager::useCache()
-{
- TDEConfig *cfg = http_config();
- return cfg->readBoolEntry( "UseCache", true );
-}
-
-TDEIO::CacheControl KProtocolManager::cacheControl()
-{
- TDEConfig *cfg = http_config();
- TQString tmp = cfg->readEntry("cache");
- if (tmp.isEmpty())
- return DEFAULT_CACHE_CONTROL;
- return TDEIO::parseCacheControl(tmp);
-}
-
-TQString KProtocolManager::cacheDir()
-{
- TDEConfig *cfg = http_config();
- return cfg->readPathEntry("CacheDir", TDEGlobal::dirs()->saveLocation("cache","http"));
-}
-
-int KProtocolManager::maxCacheAge()
-{
- TDEConfig *cfg = http_config();
- return cfg->readNumEntry( "MaxCacheAge", DEFAULT_MAX_CACHE_AGE ); // 14 days
-}
-
-int KProtocolManager::maxCacheSize()
-{
- TDEConfig *cfg = http_config();
- return cfg->readNumEntry( "MaxCacheSize", DEFAULT_MAX_CACHE_SIZE ); // 5 MB
-}
-
-TQString KProtocolManager::noProxyForRaw()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( "Proxy Settings" );
-
- return cfg->readEntry( "NoProxyFor" );
-}
-
-TQString KProtocolManager::noProxyFor()
-{
- TQString noProxy = noProxyForRaw();
- if (proxyType() == EnvVarProxy)
- noProxy = TQString::fromLocal8Bit(getenv(noProxy.local8Bit()));
-
- return noProxy;
-}
-
-TQString KProtocolManager::proxyFor( const TQString& protocol )
-{
- TQString scheme = protocol.lower();
-
- if (scheme == "webdav")
- scheme = "http";
- else if (scheme == "webdavs")
- scheme = "https";
-
- TDEConfig *cfg = config();
- cfg->setGroup( "Proxy Settings" );
- return cfg->readEntry( scheme + "Proxy" );
-}
-
-TQString KProtocolManager::proxyForURL( const KURL &url )
-{
- TQString proxy;
- ProxyType pt = proxyType();
-
- switch (pt)
- {
- case PACProxy:
- case WPADProxy:
- if (!url.host().isEmpty())
- {
- KURL u (url);
- TQString p = u.protocol().lower();
-
- // webdav is a KDE specific protocol. Look up proxy
- // information using HTTP instead...
- if ( p == "webdav" )
- {
- p = "http";
- u.setProtocol( p );
- }
- else if ( p == "webdavs" )
- {
- p = "https";
- u.setProtocol( p );
- }
-
- if ( p.startsWith("http") || p == "ftp" || p == "gopher" )
- DCOPRef( "kded", "proxyscout" ).call( "proxyForURL", u ).get( proxy );
- }
- break;
- case EnvVarProxy:
- proxy = TQString(TQString::fromLocal8Bit(getenv(proxyFor(url.protocol()).local8Bit()))).stripWhiteSpace();
- break;
- case ManualProxy:
- proxy = proxyFor( url.protocol() );
- break;
- case NoProxy:
- default:
- break;
- }
-
- return (proxy.isEmpty() ? TQString::fromLatin1("DIRECT") : proxy);
-}
-
-void KProtocolManager::badProxy( const TQString &proxy )
-{
- DCOPRef( "kded", "proxyscout" ).send( "blackListProxy", proxy );
-}
-
-/*
- Domain suffix match. E.g. return true if host is "cuzco.inka.de" and
- nplist is "inka.de,hadiko.de" or if host is "localhost" and nplist is
- "localhost".
-*/
-static bool revmatch(const char *host, const char *nplist)
-{
- if (host == 0)
- return false;
-
- const char *hptr = host + strlen( host ) - 1;
- const char *nptr = nplist + strlen( nplist ) - 1;
- const char *shptr = hptr;
-
- while ( nptr >= nplist )
- {
- if ( *hptr != *nptr )
- {
- hptr = shptr;
-
- // Try to find another domain or host in the list
- while(--nptr>=nplist && *nptr!=',' && *nptr!=' ') ;
-
- // Strip out multiple spaces and commas
- while(--nptr>=nplist && (*nptr==',' || *nptr==' ')) ;
- }
- else
- {
- if ( nptr==nplist || nptr[-1]==',' || nptr[-1]==' ')
- return true;
- if ( hptr == host ) // e.g. revmatch("bugs.kde.org","mybugs.kde.org")
- return false;
-
- hptr--;
- nptr--;
- }
- }
-
- return false;
-}
-
-TQString KProtocolManager::slaveProtocol(const KURL &url, TQString &proxy)
-{
- if (url.hasSubURL()) // We don't want the suburl's protocol
- {
- KURL::List list = KURL::split(url);
- KURL::List::Iterator it = list.fromLast();
- return slaveProtocol(*it, proxy);
- }
-
- if (!d)
- d = new KProtocolManagerPrivate;
-
- if (d->url == url)
- {
- proxy = d->proxy;
- return d->protocol;
- }
-
- if (useProxy())
- {
- proxy = proxyForURL(url);
- if ((proxy != "DIRECT") && (!proxy.isEmpty()))
- {
- bool isRevMatch = false;
- KProtocolManager::ProxyType type = proxyType();
- bool useRevProxy = ((type == ManualProxy) && useReverseProxy());
-
- TQString noProxy;
- // Check no proxy information iff the proxy type is either
- // ManualProxy or EnvVarProxy
- if ( (type == ManualProxy) || (type == EnvVarProxy) )
- noProxy = noProxyFor();
-
- if (!noProxy.isEmpty())
- {
- TQString qhost = url.host().lower();
- const char *host = qhost.latin1();
- TQString qno_proxy = noProxy.stripWhiteSpace().lower();
- const char *no_proxy = qno_proxy.latin1();
- isRevMatch = revmatch(host, no_proxy);
-
- // If no match is found and the request url has a port
- // number, try the combination of "host:port". This allows
- // users to enter host:port in the No-proxy-For list.
- if (!isRevMatch && url.port() > 0)
- {
- qhost += ':' + TQString::number (url.port());
- host = qhost.latin1();
- isRevMatch = revmatch (host, no_proxy);
- }
-
- // If the hostname does not contain a dot, check if
- // <local> is part of noProxy.
- if (!isRevMatch && host && (strchr(host, '.') == NULL))
- isRevMatch = revmatch("<local>", no_proxy);
- }
-
- if ( (!useRevProxy && !isRevMatch) || (useRevProxy && isRevMatch) )
- {
- d->url = proxy;
- if ( d->url.isValid() )
- {
- // The idea behind slave protocols is not applicable to http
- // and webdav protocols.
- TQString protocol = url.protocol().lower();
- if (protocol.startsWith("http") || protocol.startsWith("webdav"))
- d->protocol = protocol;
- else
- {
- d->protocol = d->url.protocol();
- kdDebug () << "slaveProtocol: " << d->protocol << endl;
- }
-
- d->url = url;
- d->proxy = proxy;
- return d->protocol;
- }
- }
- }
- }
-
- d->url = url;
- d->proxy = proxy = TQString::null;
- d->protocol = url.protocol();
- return d->protocol;
-}
-
-/*================================= USER-AGENT SETTINGS =====================*/
-
-TQString KProtocolManager::userAgentForHost( const TQString& hostname )
-{
- TQString sendUserAgent = TDEIO::SlaveConfig::self()->configData("http", hostname.lower(), "SendUserAgent").lower();
- if (sendUserAgent == "false")
- return TQString::null;
-
- TQString useragent = TDEIO::SlaveConfig::self()->configData("http", hostname.lower(), "UserAgent");
-
- // Return the default user-agent if none is specified
- // for the requested host.
- if (useragent.isEmpty())
- return defaultUserAgent();
-
- return useragent;
-}
-
-TQString KProtocolManager::defaultUserAgent( )
-{
- TQString modifiers = TDEIO::SlaveConfig::self()->configData("http", TQString::null, "UserAgentKeys");
- return defaultUserAgent(modifiers);
-}
-
-TQString KProtocolManager::defaultUserAgent( const TQString &_modifiers )
-{
- if (!d)
- d = new KProtocolManagerPrivate;
-
- TQString modifiers = _modifiers.lower();
- if (modifiers.isEmpty())
- modifiers = DEFAULT_USER_AGENT_KEYS;
-
- if (d->modifiers == modifiers)
- return d->useragent;
-
- TQString supp;
- struct utsname nam;
- if( uname(&nam) >= 0 )
- {
- if( modifiers.contains('o') )
- {
- supp += TQString("; %1").arg(nam.sysname);
- if ( modifiers.contains('v') )
- supp += TQString(" %1").arg(nam.release);
- }
- if( modifiers.contains('p') )
- {
- // TODO: determine this value instead of hardcoding it...
- supp += TQString::fromLatin1("; X11");
- }
- if( modifiers.contains('m') )
- {
- supp += TQString("; %1").arg(nam.machine);
- }
- if( modifiers.contains('l') )
- {
- TQStringList languageList = TDEGlobal::locale()->languageList();
- TQStringList::Iterator it = languageList.find( TQString::fromLatin1("C") );
- if( it != languageList.end() )
- {
- if( languageList.contains( TQString::fromLatin1("en") ) > 0 )
- languageList.remove( it );
- else
- (*it) = TQString::fromLatin1("en");
- }
- if( languageList.count() )
- supp += TQString("; %1").arg(languageList.join(", "));
- }
- }
- d->modifiers = modifiers;
- d->useragent = CFG_DEFAULT_UAGENT(supp);
- return d->useragent;
-}
-
-/*==================================== OTHERS ===============================*/
-
-bool KProtocolManager::markPartial()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- return cfg->readBoolEntry( "MarkPartial", true );
-}
-
-int KProtocolManager::minimumKeepSize()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- return cfg->readNumEntry( "MinimumKeepSize",
- DEFAULT_MINIMUM_KEEP_SIZE ); // 5000 byte
-}
-
-bool KProtocolManager::autoResume()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- return cfg->readBoolEntry( "AutoResume", false );
-}
-
-bool KProtocolManager::persistentConnections()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- return cfg->readBoolEntry( "PersistentConnections", true );
-}
-
-bool KProtocolManager::persistentProxyConnection()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( TQString::null );
- return cfg->readBoolEntry( "PersistentProxyConnection", false );
-}
-
-TQString KProtocolManager::proxyConfigScript()
-{
- TDEConfig *cfg = config();
- cfg->setGroup( "Proxy Settings" );
- return cfg->readEntry( "Proxy Config Script" );
-}
diff --git a/kio/kio/kprotocolmanager.h b/kio/kio/kprotocolmanager.h
deleted file mode 100644
index f7e27164b..000000000
--- a/kio/kio/kprotocolmanager.h
+++ /dev/null
@@ -1,389 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1999 Torben Weis <weis@kde.org>
- Copyright (C) 2000- Waldo Bastain <bastain@kde.org>
- Copyright (C) 2000- Dawit Alemayehu <adawit@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __kprotocolmanager_h__
-#define __kprotocolmanager_h__
-
-#include <tqstringlist.h>
-
-#include <kapplication.h>
-#include <kio/global.h>
-
-/** @deprecated Use KProtocolManager::defaultUserAgent() instead. */
-#define DEFAULT_USERAGENT_STRING ""
-
-class TDEConfig;
-
-/**
- * Provides information about I/O (Internet, etc.) settings chosen/set
- * by the end user.
- *
- * KProtocolManager has a heap of static functions that allows only read
- * access to KDE's IO related settings. These include proxy, cache, file
- * transfer resumption, timeout and user-agent related settings.
- *
- * The information provided by this class is generic enough to be applicable
- * to any application that makes use of KDE's IO sub-system. Note that this
- * mean the proxy, timeout etc. settings are saved in a separate user-specific
- * config file and not in the config file of the application.
- *
- * Original author:
- * @author Torben Weis <weis@kde.org>
- *
- * Revised by:
- * @author Waldo Bastain <bastain@kde.org>
- * @author Dawit Alemayehu <adawit@kde.org>
- * @see KPAC
- */
-class TDEIO_EXPORT KProtocolManager
-{
-public:
-
-
-/*=========================== USER-AGENT SETTINGS ===========================*/
-
-
- /**
- * Returns the default user-agent string.
- *
- * @return the default user-agent string
- */
- static TQString defaultUserAgent();
-
- /**
- * Returns the default user-agent value.
- *
- * @param keys can be any of the following:
- * @li 'o' Show OS
- * @li 'v' Show OS Version
- * @li 'p' Show platform
- * @li 'm' Show machine architecture
- * @li 'l' Show language
- * @return the default user-agent value with the given @p keys
- */
- static TQString defaultUserAgent(const TQString &keys);
-
- /**
- * Returns the userAgent string configured for the
- * specified host.
- *
- * If hostname is not found or is empty (i.e. "" or
- * TQString::null) this function will return the default
- * user agent.
- *
- * @param hostname name of the host
- * @return specified userAgent string
- */
- static TQString userAgentForHost( const TQString &hostname );
-
-
-/*=========================== TIMEOUT CONFIG ================================*/
-
-
- /**
- * Returns the preferred timeout value for reading from
- * remote connections in seconds.
- *
- * @return timeout value for remote connection in secs.
- */
- static int readTimeout();
-
- /**
- * Returns the preferred timeout value for remote connections
- * in seconds.
- *
- * @return timeout value for remote connection in secs.
- */
- static int connectTimeout();
-
- /**
- * Returns the preferred timeout value for proxy connections
- * in seconds.
- *
- * @return timeout value for proxy connection in secs.
- */
- static int proxyConnectTimeout();
-
- /**
- * Returns the preferred response timeout value for
- * remote connecting in seconds.
- *
- * @return timeout value for remote connection in seconds.
- */
- static int responseTimeout();
-
-
-/*=============================== PROXY CONFIG ==============================*/
-
-
- /**
- * Returns true if the user specified a proxy server to make connections.
- *
- * @see slaveProtocol, proxyForURL, proxyFor
- */
- static bool useProxy();
-
- /**
- * Returns true if the proxy settings should apply to the list
- * returned by @ref noProxyFor.
- *
- * Normally addresses listed in the noProxyFor list are not routed
- * through a proxy server. However, if this function returns true,
- * then all addresses listed in the noProxyFor list are to be routed
- * through a proxy server where as those that are not should bypass it.
- *
- * This function as well as @ref noProxyFor only apply when @ref proxyType
- * is @p ManualProxy.
- *
- * @see proxyForURL, proxyFor, slaveProtocol
- */
- static bool useReverseProxy();
-
- /**
- * Types of proxy configuration
- * @li NoProxy - No proxy is used
- * @li ManualProxy - Proxies are manually configured
- * @li PACProxy - A Proxy configuration URL has been given
- * @li WPADProxy - A proxy should be automatically discovered
- * @li EnvVarProxy - Use the proxy values set through environment variables.
- */
- enum ProxyType
- {
- NoProxy,
- ManualProxy,
- PACProxy,
- WPADProxy,
- EnvVarProxy
- };
-
- /**
- * Returns the type of proxy configuration that is used.
- *
- * @see ProxyType
- */
- static ProxyType proxyType();
-
- /**
- * Proxy authorization modes.
- *
- * @li Prompt - Ask for authorization as needed
- * @li Automatic - Use auto login as defined in .kionetrc files.
- *
- * NOTE: .kionetrc files have the same format as ftp .netrc files.
- * Please note the use of .kionetrc files is highly discouraged since
- * password is stored in clear text. For future releases the ability
- * to store preset password for proxy servers will probably be supported
- * through KWallet integration.
- */
- enum ProxyAuthMode
- {
- Prompt,
- Automatic
- };
-
- /**
- * Returns the way proxy authorization should be handled.
- *
- * @see ProxyAuthMode
- */
- static ProxyAuthMode proxyAuthMode();
-
- /**
- * Returns a comma-separated list of hostnames or partial
- * host-names that should bypass any proxy settings.
- *
- * This function as well as @ref useReverseProxy only apply
- * when @ref proxyType is @p ManualProxy.
- *
- * @see useReverseProxy, proxyFor, proxyForURL, slaveProtocol
- */
- static TQString noProxyFor();
-
- /**
- * Same as above except the environment variable name
- * is returned instead of the variable value when
- * @ref proxyType is @p EnvVarProxy.
- *
- * @see noProxyFor
- * @since 3.5.x
- */
- static TQString noProxyForRaw();
-
- /**
- * Returns the proxy server address for a given protocol.
- *
- * NOTE: This function does not take the @ref useReverseProxy()
- * settings into account.
- *
- * @see useReverseProxy, slaveProtocol
- * @param protocol the protocol whose proxy info is needed
- * @returns the proxy server address if one is available,
- * or TQString::null if not available
- */
- static TQString proxyFor( const TQString& protocol );
-
- /**
- * Returns the proxy server address for a given URL.
- *
- * If @ref proxyType returns Automatic, an external service
- * called KPAC (a kded module) is used to determine the proxy
- * server. Otherwise, @ref proxyFor is invoked to determine
- * whether the URL needs to be routed through a proxy server.
- *
- * NOTE: This function does not take the @ref useReverseProxy()
- * or the @ref noProxyFor() settings into account.
- *
- * @see useReverseProxy, slaveProtocol, noProxyFor
- * @param url the URL whose proxy info is needed
- * @returns the proxy server address or the text "DIRECT"
- * if no proxying is needed for the given address.
- */
- static TQString proxyForURL( const KURL& url );
-
- /**
- * Marks this proxy as bad (down). It will not be used for the
- * next 30 minutes. (The script may supply an alternate proxy)
- * @param proxy the proxy to mark as bad (as URL)
- */
- static void badProxy( const TQString & proxy );
-
- /**
- * Returns the URL of the script for automatic proxy configuration.
- * @return the proxy configuration script
- */
- static TQString proxyConfigScript();
-
-
-/*========================== CACHE CONFIG ===================================*/
-
-
- /**
- * Returns true/false to indicate whether a cache
- * should be used
- *
- * @return true to use the cache, false otherwisea
- */
- static bool useCache();
-
- /**
- * Returns the maximum age in seconds cached files should be
- * kept before they are deleted as necessary.
- *
- * @return the maximum cache age in seconds
- */
- static int maxCacheAge();
-
- /**
- * Returns the maximum size that can be used for caching.
- *
- * By default this function returns the DEFAULT_MAX_CACHE_SIZE
- * value as defined in http_slave_defaults.h. Not that the
- * value returned is in bytes, hence a value of 5120 would mean
- * 5 Kb.
- *
- * @return the maximum cache size in bytes
- */
- static int maxCacheSize(); // Maximum cache size in Kb.
-
- /**
- * The directory which contains the cache files.
- * @return the directory that contains the cache files
- */
- static TQString cacheDir();
-
- /**
- * Returns the Cache control directive to be used.
- * @return the cache control value
- */
- static TDEIO::CacheControl cacheControl();
-
-
-/*============================ DOWNLOAD CONFIG ==============================*/
-
- /**
- * Returns true if partial downloads should be
- * automatically resumed.
- * @return true to resume partial downloads
- */
- static bool autoResume();
-
- /**
- * Returns true if partial downloads should be marked
- * with a ".part" extension.
- * @return true if partial downloads should get an ".part" extension
- */
- static bool markPartial();
-
- /**
- * Returns the minimum file size for keeping aborted
- * downloads.
- *
- * Any data downloaded that does not meet this minimum
- * requirement will simply be discarded. The default size
- * is 5 KB.
- *
- * @return the minimum keep size for aborted downloads in bytes
- */
- static int minimumKeepSize();
-
-
- /*============================ NETWORK CONNECTIONS ==========================*/
- /**
- * Returns true if proxy connections should be persistent.
- * @return true if proxy connections should be persistent
- * @since 3.1
- */
- static bool persistentProxyConnection();
-
- /**
- * Returns true if connections should be persistent
- * @return true if the connections should be persistent
- */
- static bool persistentConnections();
-
-/*=============================== OTHERS ====================================*/
-
-
- /**
- * Force a reload of the general config file of
- * io-slaves ( kioslaverc).
- */
- static void reparseConfiguration();
-
- /**
- * Return the protocol to use in order to handle the given @p url
- * It's usually the same, except that FTP, when handled by a proxy,
- * needs an HTTP ioslave.
- *
- * When a proxy is to be used, proxy contains the URL for the proxy.
- * @param url the url to check
- * @param proxy the URL of the proxy to use
- * @return the slave protocol (e.g. 'http'), can be null if unknown
- */
- static TQString slaveProtocol(const KURL &url, TQString &proxy);
-
- /**
- * @internal
- * (Shared with SlaveConfig)
- */
- static TDEConfig *config();
-private:
- static TDEConfig *http_config();
-};
-#endif
diff --git a/kio/kio/krun.cpp b/kio/kio/krun.cpp
deleted file mode 100644
index f99f636db..000000000
--- a/kio/kio/krun.cpp
+++ /dev/null
@@ -1,1574 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Torben Weis <weis@kde.org>
- Copyright (C) 2006 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "krun.h"
-
-#include <assert.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <typeinfo>
-
-#include <tqwidget.h>
-#include <tqguardedptr.h>
-
-#include "kuserprofile.h"
-#include "kmimetype.h"
-#include "kmimemagic.h"
-#include "kio/job.h"
-#include "kio/global.h"
-#include "kio/scheduler.h"
-#include "kio/netaccess.h"
-#include "kfile/kopenwith.h"
-#include "kfile/krecentdocument.h"
-
-#include <kdatastream.h>
-#include <kmessageboxwrapper.h>
-#include <kurl.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kprotocolinfo.h>
-#include <kstandarddirs.h>
-#include <kprocess.h>
-#include <dcopclient.h>
-#include <tqfile.h>
-#include <tqfileinfo.h>
-#include <tqtextstream.h>
-#include <tqdatetime.h>
-#include <tqregexp.h>
-#include <kdesktopfile.h>
-#include <kstartupinfo.h>
-#include <kmacroexpander.h>
-#include <kshell.h>
-#include <kde_file.h>
-#include <kstringhandler.h>
-
-#ifdef Q_WS_X11
-#include <twin.h>
-#endif
-
-class KRun::KRunPrivate
-{
-public:
- KRunPrivate() { m_showingError = false; }
-
- bool m_showingError;
- bool m_runExecutables;
-
- TQString m_preferredService;
- TQString m_externalBrowser;
- TQString m_localPath;
- TQString m_suggestedFileName;
- TQGuardedPtr <TQWidget> m_window;
- TQCString m_asn;
-};
-
-pid_t KRun::runURL( const KURL& u, const TQString& _mimetype )
-{
- return runURL( u, _mimetype, false, true, TQString::null );
-}
-
-pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile )
-{
- return runURL( u, _mimetype, tempFile, true, TQString::null );
-}
-
-pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile, bool runExecutables )
-{
- return runURL( u, _mimetype, tempFile, runExecutables, TQString::null );
-}
-
-bool KRun::isExecutableFile( const KURL& url, const TQString &mimetype )
-{
- if ( !url.isLocalFile() )
- return false;
- TQFileInfo file( url.path() );
- if ( file.isExecutable() ) // Got a prospective file to run
- {
- KMimeType::Ptr mimeType = KMimeType::mimeType( mimetype );
-
- if ( mimeType->is("application/x-executable") || mimeType->is("application/x-executable-script") )
- return true;
- }
- return false;
-}
-
-pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile, bool runExecutables, const TQString& suggestedFileName )
-{
- return runURL( u, _mimetype, NULL, "", tempFile, runExecutables, suggestedFileName );
-}
-
-// This is called by foundMimeType, since it knows the mimetype of the URL
-pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, TQWidget* window, const TQCString& asn,
- bool tempFile, bool runExecutables, const TQString& suggestedFileName )
-{
- bool noRun = false;
- bool noAuth = false;
- if ( _mimetype == "inode/directory-locked" )
- {
- KMessageBoxWrapper::error( window,
- i18n("<qt>Unable to enter <b>%1</b>.\nYou do not have access rights to this location.</qt>").arg(u.htmlURL()) );
- return 0;
- }
- else if ( (_mimetype == "application/x-desktop") ||
- (_mimetype == "media/builtin-mydocuments") ||
- (_mimetype == "media/builtin-mycomputer") ||
- (_mimetype == "media/builtin-mynetworkplaces") ||
- (_mimetype == "media/builtin-printers") ||
- (_mimetype == "media/builtin-trash") ||
- (_mimetype == "media/builtin-webbrowser") )
- {
- if ( u.isLocalFile() && runExecutables )
- return KDEDesktopMimeType::run( u, true );
- }
- else if ( isExecutableFile(u, _mimetype) )
- {
- if ( u.isLocalFile() && runExecutables)
- {
- if (kapp->authorize("shell_access"))
- {
- TQString path = u.path();
- shellQuote( path );
- return (KRun::runCommand(path, TQString::null, TQString::null, window, asn)); // just execute the url as a command
- // ## TODO implement deleting the file if tempFile==true
- }
- else
- {
- noAuth = true;
- }
- }
- else if (_mimetype == "application/x-executable")
- noRun = true;
- }
- else if ( isExecutable(_mimetype) )
- {
- if (!runExecutables)
- noRun = true;
-
- if (!kapp->authorize("shell_access"))
- noAuth = true;
- }
-
- if ( noRun )
- {
- KMessageBox::sorry( window,
- i18n("<qt>The file <b>%1</b> is an executable program. "
- "For safety it will not be started.</qt>").arg(u.htmlURL()));
- return 0;
- }
- if ( noAuth )
- {
- KMessageBoxWrapper::error( window,
- i18n("<qt>You do not have permission to run <b>%1</b>.</qt>").arg(u.htmlURL()) );
- return 0;
- }
-
- KURL::List lst;
- lst.append( u );
-
- static const TQString& app_str = TDEGlobal::staticQString("Application");
-
- KService::Ptr offer = KServiceTypeProfile::preferredService( _mimetype, app_str );
-
- if ( !offer )
- {
- // Open-with dialog
- // TODO : pass the mimetype as a parameter, to show it (comment field) in the dialog !
- // Hmm, in fact KOpenWithDlg::setServiceType already guesses the mimetype from the first URL of the list...
- return displayOpenWithDialog( lst, tempFile, suggestedFileName );
- }
-
- return KRun::run( *offer, lst, window, asn, tempFile, suggestedFileName );
-}
-
-bool KRun::displayOpenWithDialog( const KURL::List& lst )
-{
- return displayOpenWithDialog( lst, false, TQString::null );
-}
-
-bool KRun::displayOpenWithDialog( const KURL::List& lst, bool tempFiles )
-{
- return displayOpenWithDialog( lst, tempFiles, TQString::null );
-}
-
-bool KRun::displayOpenWithDialog( const KURL::List& lst, bool tempFiles, const TQString& suggestedFileName )
-{
- if (kapp && !kapp->authorizeKAction("openwith"))
- {
- // TODO: Better message, i18n freeze :-(
- KMessageBox::sorry(0L, i18n("You are not authorized to open this file."));
- return false;
- }
-
- KOpenWithDlg l( lst, i18n("Open with:"), TQString::null, 0L );
- if ( l.exec() )
- {
- KService::Ptr service = l.service();
- if ( !!service )
- return KRun::run( *service, lst, 0 /*window*/, tempFiles, suggestedFileName );
-
- kdDebug(7010) << "No service set, running " << l.text() << endl;
- return KRun::run( l.text(), lst, suggestedFileName ); // TODO handle tempFiles
- }
- return false;
-}
-
-void KRun::shellQuote( TQString &_str )
-{
- // Credits to Walter, says Bernd G. :)
- if (_str.isEmpty()) // Don't create an explicit empty parameter
- return;
- TQChar q('\'');
- _str.replace(q, "'\\''").prepend(q).append(q);
-}
-
-
-class KRunMX1 : public KMacroExpanderBase {
-public:
- KRunMX1( const KService &_service ) :
- KMacroExpanderBase( '%' ), hasUrls( false ), hasSpec( false ), service( _service ) {}
- bool hasUrls:1, hasSpec:1;
-
-protected:
- virtual int expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret );
-
-private:
- const KService &service;
-};
-
-int
-KRunMX1::expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret )
-{
- uint option = str[pos + 1];
- switch( option ) {
- case 'c':
- ret << service.name().replace( '%', "%%" );
- break;
- case 'k':
- ret << service.desktopEntryPath().replace( '%', "%%" );
- break;
- case 'i':
- ret << "-icon" << service.icon().replace( '%', "%%" );
- break;
- case 'm':
- ret << "-miniicon" << service.icon().replace( '%', "%%" );
- break;
- case 'u':
- case 'U':
- hasUrls = true;
- /* fallthrough */
- case 'f':
- case 'F':
- case 'n':
- case 'N':
- case 'd':
- case 'D':
- case 'v':
- hasSpec = true;
- /* fallthrough */
- default:
- return -2; // subst with same and skip
- }
- return 2;
-}
-
-class KRunMX2 : public KMacroExpanderBase {
-public:
- KRunMX2( const KURL::List &_urls ) :
- KMacroExpanderBase( '%' ), ignFile( false ), urls( _urls ) {}
- bool ignFile:1;
-
-protected:
- virtual int expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret );
-
-private:
- void subst( int option, const KURL &url, TQStringList &ret );
-
- const KURL::List &urls;
-};
-
-void
-KRunMX2::subst( int option, const KURL &url, TQStringList &ret )
-{
- switch( option ) {
- case 'u':
- ret << url.pathOrURL();
- break;
- case 'd':
- ret << url.directory();
- break;
- case 'f':
- ret << url.path();
- break;
- case 'n':
- ret << url.fileName();
- break;
- case 'v':
- if (url.isLocalFile() && TQFile::exists( url.path() ) )
- ret << KDesktopFile( url.path(), true ).readEntry( "Dev" );
- break;
- }
- return;
-}
-
-int
-KRunMX2::expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret )
-{
- uint option = str[pos + 1];
- switch( option ) {
- case 'f':
- case 'u':
- case 'n':
- case 'd':
- case 'v':
- if( urls.isEmpty() ) {
- if (!ignFile)
- kdDebug() << "KRun::processDesktopExec: No URLs supplied to single-URL service " << str << endl;
- } else if( urls.count() > 1 )
- kdWarning() << "KRun::processDesktopExec: " << urls.count() << " URLs supplied to single-URL service " << str << endl;
- else
- subst( option, urls.first(), ret );
- break;
- case 'F':
- case 'U':
- case 'N':
- case 'D':
- option += 'a' - 'A';
- for( KURL::List::ConstIterator it = urls.begin(); it != urls.end(); ++it )
- subst( option, *it, ret );
- break;
- case '%':
- ret = "%";
- break;
- default:
- return -2; // subst with same and skip
- }
- return 2;
-}
-
-// BIC: merge methods below
-TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell) {
- return processDesktopExec( _service, _urls, has_shell, false, TQString::null );
-}
-
-TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell /* KDE4: remove */, bool tempFiles)
-{
- return processDesktopExec( _service, _urls, has_shell, tempFiles, TQString::null );
-}
-
-TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell /* KDE4: remove */, bool tempFiles, const TQString& suggestedFileName)
-{
- TQString exec = _service.exec();
- TQStringList result;
- bool appHasTempFileOption;
-
- KRunMX1 mx1( _service );
- KRunMX2 mx2( _urls );
-
- /// compatibility hack -- KDE 4: remove
- TQRegExp re("^\\s*(?:/bin/)?sh\\s+-c\\s+(.*)$");
- if (!re.search( exec )) {
- exec = TQString(re.cap( 1 )).stripWhiteSpace();
- for (uint pos = 0; pos < exec.length(); ) {
- TQChar c = exec.unicode()[pos];
- if (c != '\'' && c != '"')
- goto synerr; // what else can we do? after normal parsing the substs would be insecure
- int pos2 = exec.find( c, pos + 1 ) - 1;
- if (pos2 < 0)
- goto synerr; // quoting error
- memcpy( (void *)(exec.unicode() + pos), exec.unicode() + pos + 1, (pos2 - pos) * sizeof(TQChar));
- pos = pos2;
- exec.remove( pos, 2 );
- }
- }
-
- if( !mx1.expandMacrosShellQuote( exec ) )
- goto synerr; // error in shell syntax
-
- // FIXME: the current way of invoking kioexec disables term and su use
-
- // Check if we need "tempexec" (kioexec in fact)
- appHasTempFileOption = tempFiles && _service.property("X-TDE-HasTempFileOption").toBool();
- if( tempFiles && !appHasTempFileOption && _urls.size() ) {
- result << "kioexec" << "--tempfiles" << exec;
- result += _urls.toStringList();
- if (has_shell)
- result = KShell::joinArgs( result );
- return result;
- }
-
- // Check if we need kioexec
- if( !mx1.hasUrls ) {
- for( KURL::List::ConstIterator it = _urls.begin(); it != _urls.end(); ++it )
- if ( !(*it).isLocalFile() && !KProtocolInfo::isHelperProtocol(*it) ) {
- // We need to run the app through kioexec
- result << "kioexec";
- if ( tempFiles )
- result << "--tempfiles";
- if ( !suggestedFileName.isEmpty() ) {
- result << "--suggestedfilename";
- result << suggestedFileName;
- }
- result << exec;
- result += _urls.toStringList();
- if (has_shell)
- result = KShell::joinArgs( result );
- return result;
- }
- }
-
- if ( appHasTempFileOption )
- exec += " --tempfile";
-
- // Did the user forget to append something like '%f'?
- // If so, then assume that '%f' is the right choice => the application
- // accepts only local files.
- if( !mx1.hasSpec ) {
- exec += " %f";
- mx2.ignFile = true;
- }
-
- mx2.expandMacrosShellQuote( exec ); // syntax was already checked, so don't check return value
-
-/*
- 1 = need_shell, 2 = terminal, 4 = su, 8 = has_shell
-
- 0 << split(cmd)
- 1 << "sh" << "-c" << cmd
- 2 << split(term) << "-e" << split(cmd)
- 3 << split(term) << "-e" << "sh" << "-c" << cmd
-
- 4 << "tdesu" << "-u" << user << "-c" << cmd
- 5 << "tdesu" << "-u" << user << "-c" << ("sh -c " + quote(cmd))
- 6 << split(term) << "-e" << "su" << user << "-c" << cmd
- 7 << split(term) << "-e" << "su" << user << "-c" << ("sh -c " + quote(cmd))
-
- 8 << cmd
- 9 << cmd
- a << term << "-e" << cmd
- b << term << "-e" << ("sh -c " + quote(cmd))
-
- c << "tdesu" << "-u" << user << "-c" << quote(cmd)
- d << "tdesu" << "-u" << user << "-c" << quote("sh -c " + quote(cmd))
- e << term << "-e" << "su" << user << "-c" << quote(cmd)
- f << term << "-e" << "su" << user << "-c" << quote("sh -c " + quote(cmd))
-
- "sh -c" is needed in the "su" case, too, as su uses the user's login shell, not sh.
- this could be optimized with the -s switch of some su versions (e.g., debian linux).
-*/
-
- if (_service.terminal()) {
- TDEConfigGroupSaver gs(TDEGlobal::config(), "General");
- TQString terminal = TDEGlobal::config()->readPathEntry("TerminalApplication", "konsole");
- if (terminal == "konsole")
- terminal += " -caption=%c %i %m";
- terminal += " ";
- terminal += _service.terminalOptions();
- if( !mx1.expandMacrosShellQuote( terminal ) ) {
- kdWarning() << "KRun: syntax error in command `" << terminal << "', service `" << _service.name() << "'" << endl;
- return TQStringList();
- }
- mx2.expandMacrosShellQuote( terminal );
- if (has_shell)
- result << terminal;
- else
- result = KShell::splitArgs( terminal ); // assuming that the term spec never needs a shell!
- result << "-e";
- }
-
- int err;
- if (_service.substituteUid()) {
- if (_service.terminal())
- result << "su";
- else
- result << "tdesu" << "-u";
- result << _service.username() << "-c";
- KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
- if (err == KShell::FoundMeta) {
- shellQuote( exec );
- exec.prepend( "/bin/sh -c " );
- } else if (err != KShell::NoError)
- goto synerr;
- if (has_shell)
- shellQuote( exec );
- result << exec;
- } else {
- if (has_shell) {
- if (_service.terminal()) {
- KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
- if (err == KShell::FoundMeta) {
- shellQuote( exec );
- exec.prepend( "/bin/sh -c " );
- } else if (err != KShell::NoError)
- goto synerr;
- }
- result << exec;
- } else {
- result += KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
- if (err == KShell::FoundMeta)
- result << "/bin/sh" << "-c" << exec;
- else if (err != KShell::NoError)
- goto synerr;
- }
- }
-
- return result;
-
- synerr:
- kdWarning() << "KRun: syntax error in command `" << _service.exec() << "', service `" << _service.name() << "'" << endl;
- return TQStringList();
-}
-
-//static
-TQString KRun::binaryName( const TQString & execLine, bool removePath )
-{
- // Remove parameters and/or trailing spaces.
- TQStringList args = KShell::splitArgs( execLine );
- for (TQStringList::ConstIterator it = args.begin(); it != args.end(); ++it)
- if (!(*it).contains('='))
- // Remove path if wanted
- return removePath ? (*it).mid(TQString(*it).findRev('/') + 1) : *it;
- return TQString();
-}
-
-static pid_t runCommandInternal( TDEProcess* proc, const KService* service, const TQString& binName,
- const TQString &execName, const TQString & iconName, TQWidget* window, TQCString asn )
-{
- if (service && !service->desktopEntryPath().isEmpty()
- && !KDesktopFile::isAuthorizedDesktopFile( service->desktopEntryPath() ))
- {
- kdWarning() << "No authorization to execute " << service->desktopEntryPath() << endl;
- KMessageBox::sorry(window, i18n("You are not authorized to execute this file."));
- return 0;
- }
- TQString bin = KRun::binaryName( binName, true );
-#ifdef Q_WS_X11 // Startup notification doesn't work with QT/E, service isn't needed without Startup notification
- bool silent;
- TQCString wmclass;
- KStartupInfoId id;
- bool startup_notify = ( asn != "0" && KRun::checkStartupNotify( binName, service, &silent, &wmclass ));
- if( startup_notify )
- {
- id.initId( asn );
- id.setupStartupEnv();
- KStartupInfoData data;
- data.setHostname();
- data.setBin( bin );
- if( !execName.isEmpty())
- data.setName( execName );
- else if( service && !service->name().isEmpty())
- data.setName( service->name());
- data.setDescription( i18n( "Launching %1" ).arg( data.name()));
- if( !iconName.isEmpty())
- data.setIcon( iconName );
- else if( service && !service->icon().isEmpty())
- data.setIcon( service->icon());
- if( !wmclass.isEmpty())
- data.setWMClass( wmclass );
- if( silent )
- data.setSilent( KStartupInfoData::Yes );
- data.setDesktop( KWin::currentDesktop());
- if( window )
- data.setLaunchedBy( window->winId());
- KStartupInfo::sendStartup( id, data );
- }
- pid_t pid = TDEProcessRunner::run( proc, binName, id );
- if( startup_notify && pid )
- {
- KStartupInfoData data;
- data.addPid( pid );
- KStartupInfo::sendChange( id, data );
- KStartupInfo::resetStartupEnv();
- }
- return pid;
-#else
- Q_UNUSED( execName );
- Q_UNUSED( iconName );
- return TDEProcessRunner::run( proc, bin );
-#endif
-}
-
-// This code is also used in klauncher.
-bool KRun::checkStartupNotify( const TQString& /*binName*/, const KService* service, bool* silent_arg, TQCString* wmclass_arg )
-{
- bool silent = false;
- TQCString wmclass;
- if( service && service->property( "StartupNotify" ).isValid())
- {
- silent = !service->property( "StartupNotify" ).toBool();
- wmclass = service->property( "StartupWMClass" ).toString().latin1();
- }
- else if( service && service->property( "X-TDE-StartupNotify" ).isValid())
- {
- silent = !service->property( "X-TDE-StartupNotify" ).toBool();
- wmclass = service->property( "X-TDE-WMClass" ).toString().latin1();
- }
- else // non-compliant app
- {
- if( service )
- {
- if( service->type() == "Application" )
- wmclass = "0"; // doesn't have .desktop entries needed, start as non-compliant
- else
- return false; // no startup notification at all
- }
- else
- {
-#if 0
- // Create startup notification even for apps for which there shouldn't be any,
- // just without any visual feedback. This will ensure they'll be positioned on the proper
- // virtual desktop, and will get user timestamp from the ASN ID.
- wmclass = "0";
- silent = true;
-#else // That unfortunately doesn't work, when the launched non-compliant application
- // launches another one that is compliant and there is any delay inbetween (bnc:#343359)
- return false;
-#endif
- }
- }
- if( silent_arg != NULL )
- *silent_arg = silent;
- if( wmclass_arg != NULL )
- *wmclass_arg = wmclass;
- return true;
-}
-
-static pid_t runTempService( const KService& _service, const KURL::List& _urls, TQWidget* window,
- const TQCString& asn, bool tempFiles, const TQString& suggestedFileName )
-{
- if (!_urls.isEmpty()) {
- kdDebug(7010) << "runTempService: first url " << _urls.first().url() << endl;
- }
-
- TQStringList args;
- if ((_urls.count() > 1) && !_service.allowMultipleFiles())
- {
- // We need to launch the application N times. That sucks.
- // We ignore the result for application 2 to N.
- // For the first file we launch the application in the
- // usual way. The reported result is based on this
- // application.
- KURL::List::ConstIterator it = _urls.begin();
- while(++it != _urls.end())
- {
- KURL::List singleUrl;
- singleUrl.append(*it);
- runTempService( _service, singleUrl, window, "", tempFiles, suggestedFileName );
- }
- KURL::List singleUrl;
- singleUrl.append(_urls.first());
- args = KRun::processDesktopExec(_service, singleUrl, false, tempFiles, suggestedFileName);
- }
- else
- {
- args = KRun::processDesktopExec(_service, _urls, false, tempFiles, suggestedFileName);
- }
- kdDebug(7010) << "runTempService: TDEProcess args=" << args << endl;
-
- TDEProcess * proc = new TDEProcess;
- *proc << args;
-
- if (!_service.path().isEmpty())
- proc->setWorkingDirectory(_service.path());
-
- return runCommandInternal( proc, &_service, KRun::binaryName( _service.exec(), false ),
- _service.name(), _service.icon(), window, asn );
-}
-
-// WARNING: don't call this from processDesktopExec, since klauncher uses that too...
-static KURL::List resolveURLs( const KURL::List& _urls, const KService& _service )
-{
- // Check which protocols the application supports.
- // This can be a list of actual protocol names, or just KIO for KDE apps.
- TQStringList supportedProtocols = _service.property("X-TDE-Protocols").toStringList();
- KRunMX1 mx1( _service );
- TQString exec = _service.exec();
- if ( mx1.expandMacrosShellQuote( exec ) && !mx1.hasUrls ) {
- Q_ASSERT( supportedProtocols.isEmpty() ); // huh? If you support protocols you need %u or %U...
- } else {
- if ( supportedProtocols.isEmpty() )
- {
- // compat mode: assume KIO if not set and it's a KDE app
- TQStringList categories = _service.property("Categories").toStringList();
- if (( categories.find("TDE") != categories.end() ) && ( categories.find("KDE") != categories.end() ))
- supportedProtocols.append( "KIO" );
- else { // if no KDE app, be a bit over-generic
- supportedProtocols.append( "http");
- supportedProtocols.append( "ftp");
- }
- }
- }
- kdDebug(7010) << "supportedProtocols:" << supportedProtocols << endl;
-
- KURL::List urls( _urls );
- if ( supportedProtocols.find( "KIO" ) == supportedProtocols.end() ) {
- for( KURL::List::Iterator it = urls.begin(); it != urls.end(); ++it ) {
- const KURL url = *it;
- bool supported = url.isLocalFile() || supportedProtocols.find( url.protocol().lower() ) != supportedProtocols.end();
- kdDebug(7010) << "Looking at url=" << url << " supported=" << supported << endl;
- if ( !supported && KProtocolInfo::protocolClass(url.protocol()) == ":local" )
- {
- // Maybe we can resolve to a local URL?
- KURL localURL = TDEIO::NetAccess::mostLocalURL( url, 0 );
- if ( localURL != url ) {
- *it = localURL;
- kdDebug(7010) << "Changed to " << localURL << endl;
- }
- }
- }
- }
- return urls;
-}
-
-// BIC merge methods below
-pid_t KRun::run( const KService& _service, const KURL::List& _urls )
-{
- return run( _service, _urls, 0, false, TQString::null );
-}
-
-pid_t KRun::run( const KService& _service, const KURL::List& _urls, bool tempFiles )
-{
- return run( _service, _urls, 0, tempFiles, TQString::null );
-}
-
-pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, bool tempFiles )
-{
- return run( _service, _urls, window, "", tempFiles, TQString::null );
-}
-
-pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, const TQCString& asn, bool tempFiles )
-{
- return run( _service, _urls, window, asn, tempFiles, TQString::null );
-}
-
-pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, bool tempFiles, const TQString& suggestedFileName )
-{
- return run( _service, _urls, window, "", tempFiles, suggestedFileName );
-}
-
-pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, const TQCString& asn,
- bool tempFiles, const TQString& suggestedFileName )
-{
- if (!_service.desktopEntryPath().isEmpty() &&
- !KDesktopFile::isAuthorizedDesktopFile( _service.desktopEntryPath()))
- {
- kdWarning() << "No authorization to execute " << _service.desktopEntryPath() << endl;
- KMessageBox::sorry(window, i18n("You are not authorized to execute this service."));
- return 0;
- }
-
- if ( !tempFiles )
- {
- // Remember we opened those urls, for the "recent documents" menu in kicker
- KURL::List::ConstIterator it = _urls.begin();
- for(; it != _urls.end(); ++it) {
- //kdDebug(7010) << "KRecentDocument::adding " << (*it).url() << endl;
- KRecentDocument::add( *it, _service.desktopEntryName() );
- }
- }
-
- if ( tempFiles || _service.desktopEntryPath().isEmpty() || !suggestedFileName.isEmpty() )
- {
- return runTempService(_service, _urls, window, asn, tempFiles, suggestedFileName);
- }
-
- kdDebug(7010) << "KRun::run " << _service.desktopEntryPath() << endl;
-
- if (!_urls.isEmpty()) {
- kdDebug(7010) << "First url " << _urls.first().url() << endl;
- }
-
- // Resolve urls if needed, depending on what the app supports
- const KURL::List urls = resolveURLs( _urls, _service );
-
- TQString error;
- int pid = 0;
-
- TQCString myasn = asn;
- // startServiceByDesktopPath() doesn't take TQWidget*, add it to the startup info now
- if( window != NULL )
- {
- if( myasn.isEmpty())
- myasn = KStartupInfo::createNewStartupId();
- if( myasn != "0" )
- {
- KStartupInfoId id;
- id.initId( myasn );
- KStartupInfoData data;
- data.setLaunchedBy( window->winId());
- KStartupInfo::sendChange( id, data );
- }
- }
-
- int i = TDEApplication::startServiceByDesktopPath(
- _service.desktopEntryPath(), urls.toStringList(), &error, 0L, &pid, myasn
- );
-
- if (i != 0)
- {
- kdDebug(7010) << error << endl;
- KMessageBox::sorry( window, error );
- return 0;
- }
-
- kdDebug(7010) << "startServiceByDesktopPath worked fine" << endl;
- return (pid_t) pid;
-}
-
-
-pid_t KRun::run( const TQString& _exec, const KURL::List& _urls, const TQString& _name,
- const TQString& _icon, const TQString&, const TQString&)
-{
- KService::Ptr service = new KService(_name, _exec, _icon);
-
- return run(*service, _urls);
-}
-
-pid_t KRun::runCommand( TQString cmd )
-{
- return KRun::runCommand( cmd, TQString::null, TQString::null, NULL, "" );
-}
-
-pid_t KRun::runCommand( const TQString& cmd, const TQString &execName, const TQString & iconName )
-{
- return KRun::runCommand( cmd, execName, iconName, NULL, "" );
-}
-
-pid_t KRun::runCommand( const TQString& cmd, const TQString &execName, const TQString & iconName,
- TQWidget* window, const TQCString& asn )
-{
- kdDebug(7010) << "runCommand " << cmd << "," << execName << endl;
- TDEProcess * proc = new TDEProcess;
- proc->setUseShell(true);
- *proc << cmd;
- KService::Ptr service = KService::serviceByDesktopName( binaryName( execName, true ) );
- TQString bin = binaryName( cmd, false );
- int pos = bin.findRev( '/' );
- if (pos != -1) {
- proc->setWorkingDirectory( bin.mid(0, pos) );
- }
- return runCommandInternal( proc, service.data(), binaryName( execName, false ), execName, iconName, window, asn );
-}
-
-KRun::KRun( const KURL& url, mode_t mode, bool isLocalFile, bool showProgressInfo )
- :m_timer(0,"KRun::timer")
-{
- init (url, 0, "", mode, isLocalFile, showProgressInfo);
-}
-
-KRun::KRun( const KURL& url, TQWidget* window, mode_t mode, bool isLocalFile,
- bool showProgressInfo )
- :m_timer(0,"KRun::timer")
-{
- init (url, window, "", mode, isLocalFile, showProgressInfo);
-}
-
-KRun::KRun( const KURL& url, TQWidget* window, const TQCString& asn, mode_t mode, bool isLocalFile,
- bool showProgressInfo )
- :m_timer(0,"KRun::timer")
-{
- init (url, window, asn, mode, isLocalFile, showProgressInfo);
-}
-
-void KRun::init ( const KURL& url, TQWidget* window, const TQCString& asn, mode_t mode, bool isLocalFile,
- bool showProgressInfo )
-{
- m_bFault = false;
- m_bAutoDelete = true;
- m_bProgressInfo = showProgressInfo;
- m_bFinished = false;
- m_job = 0L;
- m_strURL = url;
- m_bScanFile = false;
- m_bIsDirectory = false;
- m_bIsLocalFile = isLocalFile;
- m_mode = mode;
- d = new KRunPrivate;
- d->m_runExecutables = true;
- d->m_window = window;
- d->m_asn = asn;
- setEnableExternalBrowser(true);
-
- // Start the timer. This means we will return to the event
- // loop and do initialization afterwards.
- // Reason: We must complete the constructor before we do anything else.
- m_bInit = true;
- connect( &m_timer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotTimeout() ) );
- m_timer.start( 0, true );
- kdDebug(7010) << " new KRun " << this << " " << url.prettyURL() << " timer=" << &m_timer << endl;
-
- kapp->ref();
-}
-
-void KRun::init()
-{
- kdDebug(7010) << "INIT called" << endl;
-
- bool bypassErrorMessage = false;
-
- if (m_strURL.url().startsWith("$(")) {
- // check for environment variables and make necessary translations
- TQString aValue = m_strURL.url();
- int nDollarPos = aValue.find( '$' );
-
- while( nDollarPos != -1 && nDollarPos+1 < static_cast<int>(aValue.length())) {
- // there is at least one $
- if( (aValue)[nDollarPos+1] == '(' ) {
- uint nEndPos = nDollarPos+1;
- // the next character is no $
- while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!=')') )
- nEndPos++;
- nEndPos++;
- TQString cmd = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
-
- TQString result;
- FILE *fs = popen(TQFile::encodeName(cmd).data(), "r");
- if (fs)
- {
- {
- TQTextStream ts(fs, IO_ReadOnly);
- result = ts.read().stripWhiteSpace();
- }
- pclose(fs);
- }
- aValue.replace( nDollarPos, nEndPos-nDollarPos, result );
- } else if( (aValue)[nDollarPos+1] != '$' ) {
- uint nEndPos = nDollarPos+1;
- // the next character is no $
- TQString aVarName;
- if (aValue[nEndPos]=='{')
- {
- while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') )
- nEndPos++;
- nEndPos++;
- aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
- }
- else
- {
- while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber()
- || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' ) )
- nEndPos++;
- aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 );
- }
- const char* pEnv = 0;
- if (!aVarName.isEmpty())
- pEnv = getenv( aVarName.ascii() );
- if( pEnv ) {
- // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
- // A environment variables may contain values in 8bit
- // locale cpecified encoding or in UTF8 encoding.
- aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) );
- } else
- aValue.remove( nDollarPos, nEndPos-nDollarPos );
- } else {
- // remove one of the dollar signs
- aValue.remove( nDollarPos, 1 );
- nDollarPos++;
- }
- nDollarPos = aValue.find( '$', nDollarPos );
- }
- m_strURL = KURL(aValue);
- bypassErrorMessage = true;
- }
-
- if ( !m_strURL.isValid() )
- {
- if (bypassErrorMessage == false) {
- d->m_showingError = true;
- KMessageBoxWrapper::error( d->m_window, i18n( "Malformed URL\n%1" ).arg( m_strURL.url() ) );
- d->m_showingError = false;
- }
- m_bFault = true;
- m_bFinished = true;
- m_timer.start( 0, true );
- return;
- }
- if ( !kapp->authorizeURLAction( "open", KURL(), m_strURL))
- {
- TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, m_strURL.prettyURL());
- d->m_showingError = true;
- KMessageBoxWrapper::error( d->m_window, msg );
- d->m_showingError = false;
- m_bFault = true;
- m_bFinished = true;
- m_timer.start( 0, true );
- return;
- }
-
- if ( !m_bIsLocalFile && m_strURL.isLocalFile() )
- m_bIsLocalFile = true;
-
- TQString exec;
- if (m_strURL.protocol().startsWith("http"))
- {
- exec = d->m_externalBrowser;
- }
-
- if ( m_bIsLocalFile )
- {
- if ( m_mode == 0 )
- {
- KDE_struct_stat buff;
- if ( KDE_stat( TQFile::encodeName(m_strURL.path()), &buff ) == -1 )
- {
- d->m_showingError = true;
- KMessageBoxWrapper::error( d->m_window, i18n( "<qt>Unable to run the command specified. The file or folder <b>%1</b> does not exist.</qt>" ).arg( m_strURL.htmlURL() ) );
- d->m_showingError = false;
- m_bFault = true;
- m_bFinished = true;
- m_timer.start( 0, true );
- return;
- }
- m_mode = buff.st_mode;
- }
-
- KMimeType::Ptr mime = KMimeType::findByURL( m_strURL, m_mode, m_bIsLocalFile );
- assert( mime != 0L );
- kdDebug(7010) << "MIME TYPE is " << mime->name() << endl;
- foundMimeType( mime->name() );
- return;
- }
- else if ( !exec.isEmpty() || KProtocolInfo::isHelperProtocol( m_strURL ) ) {
- kdDebug(7010) << "Helper protocol" << endl;
-
- bool ok = false;
- KURL::List urls;
- if (!((m_strURL.protocol().startsWith("http")) && (m_strURL.url() == "http://default.browser")))
- urls.append( m_strURL );
- if (exec.isEmpty())
- {
- exec = KProtocolInfo::exec( m_strURL.protocol() );
- if (exec.isEmpty())
- {
- foundMimeType(KProtocolInfo::defaultMimetype(m_strURL));
- return;
- }
- run( exec, urls );
- ok = true;
- }
- else if (exec.startsWith("!"))
- {
- exec = exec.mid(1); // Literal command
- exec += " %u";
- run( exec, urls );
- ok = true;
- }
- else
- {
- KService::Ptr service = KService::serviceByStorageId( exec );
- if (service)
- {
- run( *service, urls, d->m_window, d->m_asn );
- ok = true;
- }
- }
-
- if (ok)
- {
- m_bFinished = true;
- // will emit the error and autodelete this
- m_timer.start( 0, true );
- return;
- }
- }
-
- if ((m_strURL.protocol().startsWith("http")) && (m_strURL.url() == "http://default.browser")) {
- KURL::List urls;
- run( "kfmclient openProfile webbrowsing", urls );
- m_bFinished = true;
- // will emit the error and autodelete this
- m_timer.start( 0, true );
- return;
- }
-
- // Did we already get the information that it is a directory ?
- if ( S_ISDIR( m_mode ) )
- {
- foundMimeType( "inode/directory" );
- return;
- }
-
- // Let's see whether it is a directory
-
- if ( !KProtocolInfo::supportsListing( m_strURL ) )
- {
- //kdDebug(7010) << "Protocol has no support for listing" << endl;
- // No support for listing => it can't be a directory (example: http)
- scanFile();
- return;
- }
-
- kdDebug(7010) << "Testing directory (stating)" << endl;
-
- // It may be a directory or a file, let's stat
- TDEIO::StatJob *job = TDEIO::stat( m_strURL, true, 0 /* no details */, m_bProgressInfo );
- job->setWindow (d->m_window);
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- this, TQT_SLOT( slotStatResult( TDEIO::Job * ) ) );
- m_job = job;
- kdDebug(7010) << " Job " << job << " is about stating " << m_strURL.url() << endl;
-}
-
-KRun::~KRun()
-{
- kdDebug(7010) << "KRun::~KRun() " << this << endl;
- m_timer.stop();
- killJob();
- kapp->deref();
- kdDebug(7010) << "KRun::~KRun() done " << this << endl;
- delete d;
-}
-
-void KRun::scanFile()
-{
- kdDebug(7010) << "###### KRun::scanFile " << m_strURL.url() << endl;
- // First, let's check for well-known extensions
- // Not when there is a query in the URL, in any case.
- if ( m_strURL.query().isEmpty() )
- {
- KMimeType::Ptr mime = KMimeType::findByURL( m_strURL );
- assert( mime != 0L );
- if ( mime->name() != "application/octet-stream" || m_bIsLocalFile )
- {
- kdDebug(7010) << "Scanfile: MIME TYPE is " << mime->name() << endl;
- foundMimeType( mime->name() );
- return;
- }
- }
-
- // No mimetype found, and the URL is not local (or fast mode not allowed).
- // We need to apply the 'KIO' method, i.e. either asking the server or
- // getting some data out of the file, to know what mimetype it is.
-
- if ( !KProtocolInfo::supportsReading( m_strURL ) )
- {
- kdError(7010) << "#### NO SUPPORT FOR READING!" << endl;
- m_bFault = true;
- m_bFinished = true;
- m_timer.start( 0, true );
- return;
- }
- kdDebug(7010) << this << " Scanning file " << m_strURL.url() << endl;
-
- TDEIO::TransferJob *job = TDEIO::get( m_strURL, false /*reload*/, m_bProgressInfo );
- job->setWindow (d->m_window);
- connect(job, TQT_SIGNAL( result(TDEIO::Job *)),
- this, TQT_SLOT( slotScanFinished(TDEIO::Job *)));
- connect(job, TQT_SIGNAL( mimetype(TDEIO::Job *, const TQString &)),
- this, TQT_SLOT( slotScanMimeType(TDEIO::Job *, const TQString &)));
- m_job = job;
- kdDebug(7010) << " Job " << job << " is about getting from " << m_strURL.url() << endl;
-}
-
-void KRun::slotTimeout()
-{
- kdDebug(7010) << this << " slotTimeout called" << endl;
- if ( m_bInit )
- {
- m_bInit = false;
- init();
- return;
- }
-
- if ( m_bFault ) {
- emit error();
- }
- if ( m_bFinished ) {
- emit finished();
- }
- else
- {
- if ( m_bScanFile )
- {
- m_bScanFile = false;
- scanFile();
- return;
- }
- else if ( m_bIsDirectory )
- {
- m_bIsDirectory = false;
- foundMimeType( "inode/directory" );
- return;
- }
- }
-
- if ( m_bAutoDelete )
- {
- delete this;
- return;
- }
-}
-
-void KRun::slotStatResult( TDEIO::Job * job )
-{
- m_job = 0L;
- if (job->error())
- {
- d->m_showingError = true;
- kdError(7010) << this << " ERROR " << job->error() << " " << job->errorString() << endl;
- job->showErrorDialog();
- //kdDebug(7010) << this << " KRun returning from showErrorDialog, starting timer to delete us" << endl;
- d->m_showingError = false;
-
- m_bFault = true;
- m_bFinished = true;
-
- // will emit the error and autodelete this
- m_timer.start( 0, true );
-
- } else {
-
- kdDebug(7010) << "Finished" << endl;
- if(!dynamic_cast<TDEIO::StatJob*>(job))
- kdFatal() << "job is a " << typeid(*job).name() << " should be a StatJob" << endl;
-
- TQString knownMimeType;
- TDEIO::UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
- TDEIO::UDSEntry::ConstIterator it = entry.begin();
- for( ; it != entry.end(); it++ ) {
- switch( (*it).m_uds ) {
- case TDEIO::UDS_FILE_TYPE:
- if ( S_ISDIR( (mode_t)((*it).m_long) ) )
- m_bIsDirectory = true; // it's a dir
- else
- m_bScanFile = true; // it's a file
- break;
- case TDEIO::UDS_MIME_TYPE: // mimetype already known? (e.g. print:/manager)
- knownMimeType = (*it).m_str;
- break;
- case TDEIO::UDS_LOCAL_PATH:
- d->m_localPath = (*it).m_str;
- break;
- default:
- break;
- }
- }
- if ( !knownMimeType.isEmpty() )
- {
- foundMimeType( knownMimeType );
- m_bFinished = true;
- }
-
- // We should have found something
- assert ( m_bScanFile || m_bIsDirectory );
-
- // Start the timer. Once we get the timer event this
- // protocol server is back in the pool and we can reuse it.
- // This gives better performance than starting a new slave
- m_timer.start( 0, true );
- }
-}
-
-void KRun::slotScanMimeType( TDEIO::Job *, const TQString &mimetype )
-{
- if ( mimetype.isEmpty() )
- kdWarning(7010) << "KRun::slotScanFinished : MimetypeJob didn't find a mimetype! Probably a kioslave bug." << endl;
- foundMimeType( mimetype );
- m_job = 0;
-}
-
-void KRun::slotScanFinished( TDEIO::Job *job )
-{
- m_job = 0;
- if (job->error())
- {
- d->m_showingError = true;
- kdError(7010) << this << " ERROR (stat) : " << job->error() << " " << job->errorString() << endl;
- job->showErrorDialog();
- //kdDebug(7010) << this << " KRun returning from showErrorDialog, starting timer to delete us" << endl;
- d->m_showingError = false;
-
- m_bFault = true;
- m_bFinished = true;
-
- // will emit the error and autodelete this
- m_timer.start( 0, true );
- }
-}
-
-void KRun::foundMimeType( const TQString& type )
-{
- kdDebug(7010) << "Resulting mime type is " << type << endl;
-
-/*
- // Automatically unzip stuff
-
- // Disabled since the new KIO doesn't have filters yet.
-
- if ( type == "application/x-gzip" ||
- type == "application/x-bzip" ||
- type == "application/x-bzip2" )
- {
- KURL::List lst = KURL::split( m_strURL );
- if ( lst.isEmpty() )
- {
- TQString tmp = i18n( "Malformed URL" );
- tmp += "\n";
- tmp += m_strURL.url();
- KMessageBoxWrapper::error( 0L, tmp );
- return;
- }
-
- if ( type == "application/x-gzip" )
- lst.prepend( KURL( "gzip:/decompress" ) );
- else if ( type == "application/x-bzip" )
- lst.prepend( KURL( "bzip:/decompress" ) );
- else if ( type == "application/x-bzip2" )
- lst.prepend( KURL( "bzip2:/decompress" ) );
- else if ( type == "application/x-tar" )
- lst.prepend( KURL( "tar:/" ) );
-
- // Move the HTML style reference to the leftmost URL
- KURL::List::Iterator it = lst.begin();
- ++it;
- (*lst.begin()).setRef( (*it).ref() );
- (*it).setRef( TQString::null );
-
- // Create the new URL
- m_strURL = KURL::join( lst );
-
- kdDebug(7010) << "Now trying with " << debugString(m_strURL.url()) << endl;
-
- killJob();
-
- // We don't know if this is a file or a directory. Let's test this first.
- // (For instance a tar.gz is a directory contained inside a file)
- // It may be a directory or a file, let's stat
- TDEIO::StatJob *job = TDEIO::stat( m_strURL, m_bProgressInfo );
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- this, TQT_SLOT( slotStatResult( TDEIO::Job * ) ) );
- m_job = job;
-
- return;
- }
-*/
- TDEIO::TransferJob *job = ::tqqt_cast<TDEIO::TransferJob *>( m_job );
- if ( job )
- {
- job->putOnHold();
- TDEIO::Scheduler::publishSlaveOnHold();
- m_job = 0;
- }
-
- Q_ASSERT( !m_bFinished );
-
- // Suport for preferred service setting, see setPreferredService
- if ( !d->m_preferredService.isEmpty() ) {
- kdDebug(7010) << "Attempting to open with preferred service: " << d->m_preferredService << endl;
- KService::Ptr serv = KService::serviceByDesktopName( d->m_preferredService );
- if ( serv && serv->hasServiceType( type ) )
- {
- KURL::List lst;
- lst.append( m_strURL );
- m_bFinished = KRun::run( *serv, lst, d->m_window, d->m_asn );
- /// Note: the line above means that if that service failed, we'll
- /// go to runURL to maybe find another service, even though a dialog
- /// box was displayed. That's good if runURL tries another service,
- /// but it's not good if it tries the same one :}
- }
- }
-
- // Resolve .desktop files from media:/, remote:/, applications:/ etc.
- if ( ((type == "application/x-desktop") ||
- (type == "media/builtin-mydocuments") ||
- (type == "media/builtin-mycomputer") ||
- (type == "media/builtin-mynetworkplaces") ||
- (type == "media/builtin-printers") ||
- (type == "media/builtin-trash") ||
- (type == "media/builtin-webbrowser")) /* or inheriting? */ && (!d->m_localPath.isEmpty()) )
- {
- m_strURL = KURL();
- m_strURL.setPath( d->m_localPath );
- }
-
- if (!m_bFinished && KRun::runURL( m_strURL, type, d->m_window, d->m_asn, false, d->m_runExecutables, d->m_suggestedFileName )){
- m_bFinished = true;
- }
- else{
- m_bFinished = true;
- m_bFault = true;
- }
-
- m_timer.start( 0, true );
-}
-
-void KRun::killJob()
-{
- if ( m_job )
- {
- kdDebug(7010) << "KRun::killJob run=" << this << " m_job=" << m_job << endl;
- m_job->kill();
- m_job = 0L;
- }
-}
-
-void KRun::abort()
-{
- kdDebug(7010) << "KRun::abort " << this << " m_showingError=" << d->m_showingError << endl;
- killJob();
- // If we're showing an error message box, the rest will be done
- // after closing the msgbox -> don't autodelete nor emit signals now.
- if ( d->m_showingError )
- return;
- m_bFault = true;
- m_bFinished = true;
- m_bInit = false;
- m_bScanFile = false;
-
- // will emit the error and autodelete this
- m_timer.start( 0, true );
-}
-
-void KRun::setEnableExternalBrowser(bool b)
-{
- if (b)
- d->m_externalBrowser = TDEConfigGroup(TDEGlobal::config(), "General").readEntry("BrowserApplication");
- else
- d->m_externalBrowser = TQString::null;
-}
-
-void KRun::setPreferredService( const TQString& desktopEntryName )
-{
- d->m_preferredService = desktopEntryName;
-}
-
-void KRun::setRunExecutables(bool b)
-{
- d->m_runExecutables = b;
-}
-
-void KRun::setSuggestedFileName( const TQString& fileName )
-{
- d->m_suggestedFileName = fileName;
-}
-
-bool KRun::isExecutable( const TQString& serviceType )
-{
- return ( serviceType == "application/x-desktop" ||
- serviceType == "media/builtin-mydocuments" ||
- serviceType == "media/builtin-mycomputer" ||
- serviceType == "media/builtin-mynetworkplaces" ||
- serviceType == "media/builtin-printers" ||
- serviceType == "media/builtin-trash" ||
- serviceType == "media/builtin-webbrowser" ||
- serviceType == "application/x-executable" ||
- serviceType == "application/x-msdos-program" ||
- serviceType == "application/x-shellscript" );
-}
-
-/****************/
-
-pid_t
-TDEProcessRunner::run(TDEProcess * p, const TQString & binName)
-{
- return (new TDEProcessRunner(p, binName))->pid();
-}
-
-#ifdef Q_WS_X11
-pid_t
-TDEProcessRunner::run(TDEProcess * p, const TQString & binName, const KStartupInfoId& id )
-{
- return (new TDEProcessRunner(p, binName, id))->pid();
-}
-#endif
-
-TDEProcessRunner::TDEProcessRunner(TDEProcess * p, const TQString & _binName )
- : TQObject(),
- process_(p),
- binName( _binName )
-{
- TQObject::connect(
- process_, TQT_SIGNAL(processExited(TDEProcess *)),
- this, TQT_SLOT(slotProcessExited(TDEProcess *)));
-
- process_->start();
- if ( !process_->pid() )
- slotProcessExited( process_ );
-}
-
-#ifdef Q_WS_X11
-TDEProcessRunner::TDEProcessRunner(TDEProcess * p, const TQString & _binName, const KStartupInfoId& id )
- : TQObject(),
- process_(p),
- binName( _binName ),
- id_( id )
-{
- TQObject::connect(
- process_, TQT_SIGNAL(processExited(TDEProcess *)),
- this, TQT_SLOT(slotProcessExited(TDEProcess *)));
-
- process_->start();
- if ( !process_->pid() )
- slotProcessExited( process_ );
-}
-#endif
-
-TDEProcessRunner::~TDEProcessRunner()
-{
- delete process_;
-}
-
- pid_t
-TDEProcessRunner::pid() const
-{
- return process_->pid();
-}
-
- void
-TDEProcessRunner::slotProcessExited(TDEProcess * p)
-{
- if (p != process_)
- return; // Eh ?
-
- kdDebug(7010) << "slotProcessExited " << binName << endl;
- kdDebug(7010) << "normalExit " << process_->normalExit() << endl;
- kdDebug(7010) << "exitStatus " << process_->exitStatus() << endl;
- bool showErr = process_->normalExit()
- && ( process_->exitStatus() == 127 || process_->exitStatus() == 1 );
- if ( !binName.isEmpty() && ( showErr || process_->pid() == 0 ) )
- {
- // Often we get 1 (zsh, csh) or 127 (ksh, bash) because the binary doesn't exist.
- // We can't just rely on that, but it's a good hint.
- // Before assuming its really so, we'll try to find the binName
- // relatively to current directory, and then in the PATH.
- if ( !TQFile( binName ).exists() && KStandardDirs::findExe( binName ).isEmpty() )
- {
- kapp->ref();
- KMessageBox::sorry( 0L, i18n("Could not find the program '%1'").arg( binName ) );
- kapp->deref();
- }
- }
-#ifdef Q_WS_X11
- if( !id_.none())
- {
- KStartupInfoData data;
- data.addPid( pid()); // announce this pid for the startup notification has finished
- data.setHostname();
- KStartupInfo::sendFinish( id_, data );
- }
-#endif
- deleteLater();
-}
-
-void KRun::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-#include "krun.moc"
diff --git a/kio/kio/ksambashare.cpp b/kio/kio/ksambashare.cpp
deleted file mode 100644
index ff5b9c104..000000000
--- a/kio/kio/ksambashare.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/* This file is part of the KDE project
- Copyright (c) 2004 Jan Schaefer <j_schaef@informatik.uni-kl.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqdict.h>
-#include <tqfile.h>
-#include <tqtextstream.h>
-
-#include <kdirwatch.h>
-#include <kstaticdeleter.h>
-#include <kdebug.h>
-#include <ksimpleconfig.h>
-
-#include "ksambashare.h"
-
-class KSambaSharePrivate
-{
-public:
- KSambaSharePrivate();
-
- bool readSmbConf();
- bool findSmbConf();
- bool load();
-
- TQDict<bool> sharedPaths;
- TQString smbConf;
-};
-
-KSambaSharePrivate::KSambaSharePrivate()
-{
- load();
-}
-
-
-#define FILESHARECONF "/etc/security/fileshare.conf"
-
-bool KSambaSharePrivate::load() {
- if (!findSmbConf())
- return false;
-
- return readSmbConf();
-}
-
-/**
- * Try to find the samba config file path
- * First tries the kconfig, then checks
- * several well-known paths
- * @return wether a smb.conf was found.
- **/
-bool KSambaSharePrivate::findSmbConf() {
- KSimpleConfig config(TQString::fromLatin1(FILESHARECONF),true);
- smbConf = config.readEntry("SMBCONF");
-
- if ( TQFile::exists(smbConf) )
- return true;
-
- if ( TQFile::exists("/etc/samba/smb.conf") )
- smbConf = "/etc/samba/smb.conf";
- else
- if ( TQFile::exists("/etc/smb.conf") )
- smbConf = "/etc/smb.conf";
- else
- if ( TQFile::exists("/usr/local/samba/lib/smb.conf") )
- smbConf = "/usr/local/samba/lib/smb.conf";
- else
- if ( TQFile::exists("/usr/samba/lib/smb.conf") )
- smbConf = "/usr/samba/lib/smb.conf";
- else
- if ( TQFile::exists("/usr/lib/smb.conf") )
- smbConf = "/usr/lib/smb.conf";
- else
- if ( TQFile::exists("/usr/local/lib/smb.conf") )
- smbConf = "/usr/local/lib/smb.conf";
- else {
- kdDebug(7000) << "KSambaShare: Could not found smb.conf!" << endl;
- return false;
- }
-
- return true;
-}
-
-
-/**
- * Reads all path= entries from the smb.conf file
- * and fills the sharedPaths dict with the values
- */
-bool KSambaSharePrivate::readSmbConf() {
- TQFile f(smbConf);
-
- kdDebug(7000) << "KSambaShare::readSmbConf " << smbConf << endl;
-
- if (!f.open(IO_ReadOnly)) {
- kdError() << "KSambaShare: Could not open " << smbConf << endl;
- return false;
- }
-
- sharedPaths.clear();
-
- TQTextStream s(&f);
-
- bool continuedLine = false; // is true if the line before ended with a backslash
- TQString completeLine;
-
- while (!s.eof())
- {
- TQString currentLine = s.readLine().stripWhiteSpace();
-
- if (continuedLine) {
- completeLine += currentLine;
- continuedLine = false;
- }
- else
- completeLine = currentLine;
-
- // is the line continued in the next line ?
- if ( completeLine[completeLine.length()-1] == '\\' )
- {
- continuedLine = true;
- // remove the ending backslash
- completeLine.truncate( completeLine.length()-1 );
- continue;
- }
-
- // comments or empty lines
- if (completeLine.isEmpty() ||
- '#' == completeLine[0] ||
- ';' == completeLine[0])
- {
- continue;
- }
-
- // parameter
- int i = completeLine.find('=');
-
- if (i>-1)
- {
- TQString name = completeLine.left(i).stripWhiteSpace().lower();
- TQString value = completeLine.mid(i+1).stripWhiteSpace();
-
- if (name == TDEGlobal::staticQString("path")) {
- // Handle quotation marks
- if ( value[0] == '"' )
- value.remove(0,1);
-
- if ( value[value.length()-1] == '"' )
- value.truncate(value.length()-1);
-
- // Normalize path
- if ( value[value.length()-1] != '/' )
- value += '/';
-
- bool b = true;
- sharedPaths.insert(value,&b);
- kdDebug(7000) << "KSambaShare: Found path: " << value << endl;
- }
- }
- }
-
- f.close();
-
- return true;
-
-}
-
-KSambaShare::KSambaShare() {
- d = new KSambaSharePrivate();
- if (TQFile::exists(d->smbConf)) {
- KDirWatch::self()->addFile(d->smbConf);
- KDirWatch::self()->addFile(FILESHARECONF);
- connect(KDirWatch::self(), TQT_SIGNAL(dirty (const TQString&)),this,
- TQT_SLOT(slotFileChange(const TQString&)));
- }
-}
-
-KSambaShare::~KSambaShare() {
- if (TQFile::exists(d->smbConf)) {
- KDirWatch::self()->removeFile(d->smbConf);
- KDirWatch::self()->removeFile(FILESHARECONF);
- }
- delete d;
-}
-
-TQString KSambaShare::smbConfPath() const {
- return d->smbConf;
-}
-
-bool KSambaShare::isDirectoryShared( const TQString & path ) const {
- TQString fixedPath = path;
- if ( path[path.length()-1] != '/' )
- fixedPath += '/';
-
- return d->sharedPaths.find(fixedPath) != 0;
-}
-
-TQStringList KSambaShare::sharedDirectories() const {
- TQStringList result;
- TQDictIterator<bool> it(d->sharedPaths);
- for( ; it.current(); ++it )
- result << it.currentKey();
-
- return result;
-}
-
-void KSambaShare::slotFileChange( const TQString & path ) {
- if (path == d->smbConf)
- d->readSmbConf();
- else
- if (path == FILESHARECONF)
- d->load();
-
- emit changed();
-}
-
-KSambaShare* KSambaShare::_instance = 0L;
-static KStaticDeleter<KSambaShare> ksdSambaShare;
-
-KSambaShare* KSambaShare::instance() {
- if (! _instance )
- _instance = ksdSambaShare.setObject(_instance, new KSambaShare());
-
- return _instance;
-}
-
-#include "ksambashare.moc"
-
diff --git a/kio/kio/kservice.cpp b/kio/kio/kservice.cpp
deleted file mode 100644
index 547df4651..000000000
--- a/kio/kio/kservice.cpp
+++ /dev/null
@@ -1,934 +0,0 @@
-/* This file is part of the KDE libraries
- * Copyright (C) 1999 - 2001 Waldo Bastian <bastian@kde.org>
- * Copyright (C) 1999 David Faure <faure@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-// $Id$
-
-#include <config.h>
-
-#include "kservice.h"
-#include "kservice_p.h"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <stddef.h>
-#include <unistd.h>
-#include <stdlib.h>
-
-#include <tqstring.h>
-#include <tqfile.h>
-#include <tqdir.h>
-#include <tqtl.h>
-
-#include <ksimpleconfig.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kdesktopfile.h>
-#include <kglobal.h>
-#include <kiconloader.h>
-#include <klocale.h>
-#include <kconfigbase.h>
-#include <kstandarddirs.h>
-#include <dcopclient.h>
-
-#include "kservicefactory.h"
-#include "kservicetypefactory.h"
-#include "kservicetype.h"
-#include "kuserprofile.h"
-#include "tdesycoca.h"
-
-class KService::KServicePrivate
-{
-public:
- TQStringList categories;
- TQString menuId;
-};
-
-KService::KService( const TQString & _name, const TQString &_exec, const TQString &_icon)
- : KSycocaEntry( TQString::null)
-{
- d = new KServicePrivate;
- m_bValid = true;
- m_bDeleted = false;
- m_strType = "Application";
- m_strName = _name;
- m_strExec = _exec;
- m_strIcon = _icon;
- m_bTerminal = false;
- m_bAllowAsDefault = true;
- m_initialPreference = 10;
-}
-
-
-KService::KService( const TQString & _fullpath )
- : KSycocaEntry( _fullpath)
-{
- KDesktopFile config( _fullpath );
-
- init(&config);
-}
-
-KService::KService( KDesktopFile *config )
- : KSycocaEntry( config->fileName())
-{
- init(config);
-}
-
-void
-KService::init( KDesktopFile *config )
-{
- d = new KServicePrivate;
- m_bValid = true;
-
- bool absPath = !TQDir::isRelativePath(entryPath());
- bool kde4application = config->fileName().startsWith("/usr/share/applications/kde4/");
-
- config->setDesktopGroup();
-
- TQMap<TQString, TQString> entryMap = config->entryMap(config->group());
-
- entryMap.remove("Encoding"); // reserved as part of Desktop Entry Standard
- entryMap.remove("Version"); // reserved as part of Desktop Entry Standard
-
- m_bDeleted = config->readBoolEntry( "Hidden", false );
- entryMap.remove("Hidden");
- if (m_bDeleted)
- {
- //kdDebug() << "Hidden=true for " << entryPath() << endl;
- m_bValid = false;
- return;
- }
-
- m_strName = config->readName();
- entryMap.remove("Name");
- if ( m_strName.isEmpty() )
- {
- if (config->readEntry( "Exec" ).isEmpty())
- {
- //kdWarning(7012) << "The desktop entry file " << entryPath()
- // << " has no Name and no Exec" << endl;
- m_bValid = false;
- return;
- }
- // Try to make up a name.
- m_strName = entryPath();
- int i = m_strName.findRev('/');
- m_strName = m_strName.mid(i+1);
- i = m_strName.findRev('.');
- if (i != -1)
- m_strName = m_strName.left(i);
- }
-
- m_strType = config->readType();
- entryMap.remove("Type");
- if ( m_strType.isEmpty() )
- {
- /*kdWarning(7012) << "The desktop entry file " << entryPath()
- << " has no Type=... entry."
- << " It should be \"Application\" or \"Service\"" << endl;
- m_bValid = false;
- return;*/
- m_strType = "Application";
- } else if ( m_strType != "Application" && m_strType != "Service" )
- {
- kdWarning(7012) << "The desktop entry file " << entryPath()
- << " has Type=" << m_strType
- << " instead of \"Application\" or \"Service\"" << endl;
- m_bValid = false;
- return;
- }
-
- // In case Try Exec is set, check if the application is available
- if (!config->tryExec()) {
- //kdDebug(7012) << "tryExec said false for " << entryPath() << endl;
- m_bDeleted = true;
- m_bValid = false;
- return;
- }
-
- TQString resource = config->resource();
-
- if ( (m_strType == "Application") &&
- (!resource.isEmpty()) &&
- (resource != "apps") &&
- !absPath)
- {
- kdWarning(7012) << "The desktop entry file " << entryPath()
- << " has Type=" << m_strType << " but is located under \"" << resource
- << "\" instead of \"apps\"" << endl;
- m_bValid = false;
- return;
- }
-
- if ( (m_strType == "Service") &&
- (!resource.isEmpty()) &&
- (resource != "services") &&
- !absPath)
- {
- kdWarning(7012) << "The desktop entry file " << entryPath()
- << " has Type=" << m_strType << " but is located under \"" << resource
- << "\" instead of \"services\"" << endl;
- m_bValid = false;
- return;
- }
-
- TQString name = entryPath();
- int pos = name.findRev('/');
- if (pos != -1)
- name = name.mid(pos+1);
- pos = name.find('.');
- if (pos != -1)
- name = name.left(pos);
-
- m_strExec = config->readPathEntry( "Exec" );
- if (kde4application && !m_strExec.startsWith("/")) {
- m_strExec = "XDG_DATA_DIRS=/usr/share XDG_CONFIG_DIRS=/etc/xdg/ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:$PATH "+m_strExec;
- } else if (config->readBoolEntry("X-TDE-SubstituteUID")) {
- int space = m_strExec.find(" ");
- if (space==-1)
- m_strExec = KStandardDirs::findExe(m_strExec);
- else {
- const TQString command = m_strExec.left(space);
- m_strExec.replace(command,KStandardDirs::findExe(command));
- }
- }
-
- entryMap.remove("Exec");
-
- m_strIcon = config->readEntry( "Icon", "unknown" );
- if (kde4application) {
- if (TQFile::exists("/usr/share/icons/oxygen/22x22/apps/" + m_strIcon + ".png")) {
- m_strIcon = "/usr/share/icons/oxygen/22x22/apps/" + m_strIcon + ".png";
- } else if (TQFile::exists("/usr/share/icons/hicolor/22x22/apps/" + m_strIcon + ".png")) {
- m_strIcon = "/usr/share/icons/hicolor/22x22/apps/" + m_strIcon + ".png";
- }
- }
- entryMap.remove("Icon");
- m_bTerminal = (config->readBoolEntry( "Terminal" )); // should be a property IMHO
- entryMap.remove("Terminal");
- m_strTerminalOptions = config->readEntry( "TerminalOptions" ); // should be a property IMHO
- entryMap.remove("TerminalOptions");
- m_strPath = config->readPath();
- entryMap.remove("Path");
- m_strComment = config->readComment();
- entryMap.remove("Comment");
- m_strGenName = config->readGenericName();
- if (kde4application) {
- m_strGenName += " [KDE4]";
- }
- entryMap.remove("GenericName");
- TQString untranslatedGenericName = config->readEntryUntranslated( "GenericName" );
- if (!untranslatedGenericName.isEmpty())
- entryMap.insert("UntranslatedGenericName", untranslatedGenericName);
-
- m_lstKeywords = config->readListEntry("Keywords");
- entryMap.remove("Keywords");
- d->categories = config->readListEntry("Categories", ';');
- entryMap.remove("Categories");
- m_strLibrary = config->readEntry( "X-TDE-Library" );
- entryMap.remove("X-TDE-Library");
- m_strInit = config->readEntry("X-TDE-Init" );
- entryMap.remove("X-TDE-Init");
-
- m_lstServiceTypes = config->readListEntry( "ServiceTypes" );
- entryMap.remove("ServiceTypes");
- // For compatibility with KDE 1.x
- if (!kde4application)
- m_lstServiceTypes += config->readListEntry( "MimeType", ';' );
- entryMap.remove("MimeType");
-
- if ( m_strType == "Application" && !m_lstServiceTypes.contains("Application") )
- // Applications implement the service type "Application" ;-)
- m_lstServiceTypes += "Application";
-
- TQString dcopServiceType = config->readEntry("X-DCOP-ServiceType").lower();
- entryMap.remove("X-DCOP-ServiceType");
- if (dcopServiceType == "unique")
- m_DCOPServiceType = DCOP_Unique;
- else if (dcopServiceType == "multi")
- m_DCOPServiceType = DCOP_Multi;
- else if (dcopServiceType == "wait")
- m_DCOPServiceType = DCOP_Wait;
- else
- m_DCOPServiceType = DCOP_None;
-
- m_strDesktopEntryName = name.lower();
- if (kde4application)
- m_strDesktopEntryName = "kde4-" + m_strDesktopEntryName;
-
- m_bAllowAsDefault = config->readBoolEntry( "AllowDefault", true );
- entryMap.remove("AllowDefault");
-
- m_initialPreference = config->readNumEntry( "X-TDE-InitialPreference", 1 );
- entryMap.remove("X-TDE-InitialPreference");
- if ( m_initialPreference == 1 )
- m_initialPreference = config->readNumEntry( "InitialPreference", 1 );
- entryMap.remove("InitialPreference");
-
- // Store all additional entries in the property map.
- // A TQMap<TQString,TQString> would be easier for this but we can't
- // brake BC, so we have to store it in m_mapProps.
-// tqWarning("Path = %s", entryPath().latin1());
- TQMap<TQString,TQString>::ConstIterator it = entryMap.begin();
- for( ; it != entryMap.end();++it)
- {
- //tqDebug(" Key = %s Data = %s", it.key().latin1(), it.data().latin1());
- TQString key = it.key();
- if (kde4application && key=="OnlyShowIn" && it.data()=="KDE;")
- key = "NotShowIn";
- m_mapProps.insert( key, TQVariant( it.data()));
- }
-}
-
-KService::KService( TQDataStream& _str, int offset ) : KSycocaEntry( _str, offset )
-{
- d = new KServicePrivate;
- load( _str );
-}
-
-KService::~KService()
-{
- //debug("KService::~KService()");
- delete d;
-}
-
-TQPixmap KService::pixmap( KIcon::Group _group, int _force_size, int _state, TQString * _path ) const
-{
- KIconLoader *iconLoader=TDEGlobal::iconLoader();
- if (!iconLoader->extraDesktopThemesAdded())
- {
- TQPixmap pixmap=iconLoader->loadIcon( m_strIcon, _group, _force_size, _state, _path, true );
- if (!pixmap.isNull() ) return pixmap;
-
- iconLoader->addExtraDesktopThemes();
- }
-
- return iconLoader->loadIcon( m_strIcon, _group, _force_size, _state, _path );
-}
-
-void KService::load( TQDataStream& s )
-{
- // dummies are here because of fields that were removed, to keep bin compat.
- // Feel free to re-use, but fields for Applications only (not generic services)
- // should rather be added to application.desktop
- TQ_INT8 def, term, dummy1, dummy2;
- TQ_INT8 dst, initpref;
- TQString dummyStr1, dummyStr2;
- int dummyI1, dummyI2;
- TQ_UINT32 dummyUI32;
-
- // WARNING: IN KDE 3.x THIS NEEDS TO REMAIN COMPATIBLE WITH KDE 2.x!
- // !! This data structure should remain binary compatible at all times !!
- // You may add new fields at the end. Make sure to update the version
- // number in tdesycoca.h
- s >> m_strType >> m_strName >> m_strExec >> m_strIcon
- >> term >> m_strTerminalOptions
- >> m_strPath >> m_strComment >> m_lstServiceTypes >> def >> m_mapProps
- >> m_strLibrary >> dummyI1 >> dummyI2
- >> dst
- >> m_strDesktopEntryName
- >> dummy1 >> dummyStr1 >> initpref >> dummyStr2 >> dummy2
- >> m_lstKeywords >> m_strInit >> dummyUI32 >> m_strGenName
- >> d->categories >> d->menuId;
-
- m_bAllowAsDefault = def;
- m_bTerminal = term;
- m_DCOPServiceType = (DCOPServiceType_t) dst;
- m_initialPreference = initpref;
-
- m_bValid = true;
-}
-
-void KService::save( TQDataStream& s )
-{
- KSycocaEntry::save( s );
- TQ_INT8 def = m_bAllowAsDefault, initpref = m_initialPreference;
- TQ_INT8 term = m_bTerminal;
- TQ_INT8 dst = (TQ_INT8) m_DCOPServiceType;
- TQ_INT8 dummy1 = 0, dummy2 = 0; // see ::load
- TQString dummyStr1, dummyStr2;
- int dummyI1 = 0, dummyI2 = 0;
- TQ_UINT32 dummyUI32 = 0;
-
- // WARNING: IN KDE 3.x THIS NEEDS TO REMAIN COMPATIBLE WITH KDE 2.x!
- // !! This data structure should remain binary compatible at all times !!
- // You may add new fields at the end. Make sure to update the version
- // number in tdesycoca.h
- s << m_strType << m_strName << m_strExec << m_strIcon
- << term << m_strTerminalOptions
- << m_strPath << m_strComment << m_lstServiceTypes << def << m_mapProps
- << m_strLibrary << dummyI1 << dummyI2
- << dst
- << m_strDesktopEntryName
- << dummy1 << dummyStr1 << initpref << dummyStr2 << dummy2
- << m_lstKeywords << m_strInit << dummyUI32 << m_strGenName
- << d->categories << d->menuId;
-}
-
-bool KService::hasServiceType( const TQString& _servicetype ) const
-{
- if (!m_bValid) return false; // safety test
-
- //kdDebug(7012) << "Testing " << m_strDesktopEntryName << " for " << _servicetype << endl;
-
- KMimeType::Ptr mimePtr = KMimeType::mimeType( _servicetype );
- if ( mimePtr && mimePtr == KMimeType::defaultMimeTypePtr() )
- mimePtr = 0;
-
- bool isNumber;
- // For each service type we are associated with, if it doesn't
- // match then we try its parent service types.
- TQStringList::ConstIterator it = m_lstServiceTypes.begin();
- for( ; it != m_lstServiceTypes.end(); ++it )
- {
- (*it).toInt(&isNumber);
- if (isNumber)
- continue;
- //kdDebug(7012) << " has " << (*it) << endl;
- KServiceType::Ptr ptr = KServiceType::serviceType( *it );
- if ( ptr && ptr->inherits( _servicetype ) )
- return true;
-
- // The mimetype inheritance ("is also") works the other way.
- // e.g. if we're looking for a handler for mimePtr==smb-workgroup
- // then a handler for inode/directory is ok.
- if ( mimePtr && mimePtr->is( *it ) )
- return true;
- }
- return false;
-}
-
-int KService::initialPreferenceForMimeType( const TQString& mimeType ) const
-{
- if (!m_bValid) return 0; // safety test
-
- bool isNumber;
-
- // For each service type we are associated with
- TQStringList::ConstIterator it = m_lstServiceTypes.begin();
- for( ; it != m_lstServiceTypes.end(); ++it )
- {
- (*it).toInt(&isNumber);
- if (isNumber)
- continue;
- //kdDebug(7012) << " has " << (*it) << endl;
- KServiceType::Ptr ptr = KServiceType::serviceType( *it );
- if ( !ptr || !ptr->inherits( mimeType ) )
- continue;
-
- int initalPreference = m_initialPreference;
- ++it;
- if (it != m_lstServiceTypes.end())
- {
- int i = (*it).toInt(&isNumber);
- if (isNumber)
- initalPreference = i;
- }
- return initalPreference;
- }
-
- KMimeType::Ptr mimePtr = KMimeType::mimeType( mimeType );
- if ( mimePtr && mimePtr == KMimeType::defaultMimeTypePtr() )
- mimePtr = 0;
-
- // Try its parent service types.
- it = m_lstServiceTypes.begin();
- for( ; it != m_lstServiceTypes.end(); ++it )
- {
- (*it).toInt(&isNumber);
- if (isNumber)
- continue;
-
- // The mimetype inheritance ("is also") works the other way.
- // e.g. if we're looking for a handler for mimePtr==smb-workgroup
- // then a handler for inode/directory is ok.
- if ( !mimePtr || !mimePtr->is( *it ) )
- continue;
-
- int initalPreference = m_initialPreference;
- ++it;
- if (it != m_lstServiceTypes.end())
- {
- int i = (*it).toInt(&isNumber);
- if (isNumber)
- initalPreference = i;
- }
- return initalPreference;
- }
- return 0;
-}
-
-class KServiceReadProperty : public TDEConfigBase
-{
-public:
- KServiceReadProperty(const TQString &_key, const TQCString &_value)
- : key(_key), value(_value) { }
-
- bool internalHasGroup(const TQCString &) const { /*tqDebug("hasGroup(const TQCString &)");*/ return false; }
-
- TQStringList groupList() const { return TQStringList(); }
-
- TQMap<TQString,TQString> entryMap(const TQString &group) const
- { Q_UNUSED(group); return TQMap<TQString,TQString>(); }
-
- void reparseConfiguration() { }
-
- KEntryMap internalEntryMap( const TQString &pGroup) const
- { Q_UNUSED(pGroup); return KEntryMap(); }
-
- KEntryMap internalEntryMap() const { return KEntryMap(); }
-
- void putData(const KEntryKey &_key, const KEntry& _data, bool _checkGroup)
- { Q_UNUSED(_key); Q_UNUSED(_data); Q_UNUSED(_checkGroup); }
-
- KEntry lookupData(const KEntryKey &_key) const
- { Q_UNUSED(_key); KEntry entry; entry.mValue = value; return entry; }
-protected:
- TQString key;
- TQCString value;
-};
-
-TQVariant KService::property( const TQString& _name) const
-{
- return property( _name, TQVariant::Invalid);
-}
-
-// Return a string TQVariant if string isn't null, and invalid variant otherwise
-// (the variant must be invalid if the field isn't in the .desktop file)
-// This allows trader queries like "exist Library" to work.
-static TQVariant makeStringVariant( const TQString& string )
-{
- // Using isEmpty here would be wrong.
- // Empty is "specified but empty", null is "not specified" (in the .desktop file)
- return string.isNull() ? TQVariant() : TQVariant( string );
-}
-
-TQVariant KService::property( const TQString& _name, TQVariant::Type t ) const
-{
- if ( _name == "Type" )
- return TQVariant( m_strType ); // can't be null
- else if ( _name == "Name" )
- return TQVariant( m_strName ); // can't be null
- else if ( _name == "Exec" )
- return makeStringVariant( m_strExec );
- else if ( _name == "Icon" )
- return makeStringVariant( m_strIcon );
- else if ( _name == "Terminal" )
- return TQVariant( static_cast<int>(m_bTerminal) );
- else if ( _name == "TerminalOptions" )
- return makeStringVariant( m_strTerminalOptions );
- else if ( _name == "Path" )
- return makeStringVariant( m_strPath );
- else if ( _name == "Comment" )
- return makeStringVariant( m_strComment );
- else if ( _name == "GenericName" )
- return makeStringVariant( m_strGenName );
- else if ( _name == "ServiceTypes" )
- return TQVariant( m_lstServiceTypes );
- else if ( _name == "AllowAsDefault" )
- return TQVariant( static_cast<int>(m_bAllowAsDefault) );
- else if ( _name == "InitialPreference" )
- return TQVariant( m_initialPreference );
- else if ( _name == "Library" )
- return makeStringVariant( m_strLibrary );
- else if ( _name == "DesktopEntryPath" ) // can't be null
- return TQVariant( entryPath() );
- else if ( _name == "DesktopEntryName")
- return TQVariant( m_strDesktopEntryName ); // can't be null
- else if ( _name == "Categories")
- return TQVariant( d->categories );
- else if ( _name == "Keywords")
- return TQVariant( m_lstKeywords );
-
- // Ok we need to convert the property from a TQString to its real type.
- // Maybe the caller helped us.
- if (t == TQVariant::Invalid)
- {
- // No luck, let's ask KServiceTypeFactory what the type of this property
- // is supposed to be.
- t = KServiceTypeFactory::self()->findPropertyTypeByName(_name);
- if (t == TQVariant::Invalid)
- {
- kdDebug(7012) << "Request for unknown property '" << _name << "'\n";
- return TQVariant(); // Unknown property: Invalid variant.
- }
- }
-
- // Then we use a homebuild class based on TDEConfigBase to convert the TQString.
- // For some often used property types we do the conversion ourselves.
- TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( _name );
- if ( (it == m_mapProps.end()) || (!it.data().isValid()))
- {
- //kdDebug(7012) << "Property not found " << _name << endl;
- return TQVariant(); // No property set.
- }
-
- switch(t)
- {
- case TQVariant::String:
- return it.data();
- case TQVariant::Bool:
- case TQVariant::Int:
- {
- TQString aValue = it.data().toString();
- int val = 0;
- if (aValue == "true" || aValue == "on" || aValue == "yes")
- val = 1;
- else
- {
- bool bOK;
- val = aValue.toInt( &bOK );
- if( !bOK )
- val = 0;
- }
- if (t == TQVariant::Bool)
- {
- return TQVariant((bool)val, 1);
- }
- return TQVariant(val);
- }
- default:
- // All others
- KServiceReadProperty ksrp(_name, it.data().toString().utf8());
- return ksrp.readPropertyEntry(_name, t);
- }
-}
-
-TQStringList KService::propertyNames() const
-{
- TQStringList res;
-
- TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.begin();
- for( ; it != m_mapProps.end(); ++it )
- res.append( it.key() );
-
- res.append( "Type" );
- res.append( "Name" );
- res.append( "Comment" );
- res.append( "GenericName" );
- res.append( "Icon" );
- res.append( "Exec" );
- res.append( "Terminal" );
- res.append( "TerminalOptions" );
- res.append( "Path" );
- res.append( "ServiceTypes" );
- res.append( "AllowAsDefault" );
- res.append( "InitialPreference" );
- res.append( "Library" );
- res.append( "DesktopEntryPath" );
- res.append( "DesktopEntryName" );
- res.append( "Keywords" );
- res.append( "Categories" );
-
- return res;
-}
-
-KService::List KService::allServices()
-{
- return KServiceFactory::self()->allServices();
-}
-
-KService::Ptr KService::serviceByName( const TQString& _name )
-{
- KService * s = KServiceFactory::self()->findServiceByName( _name );
- return KService::Ptr( s );
-}
-
-KService::Ptr KService::serviceByDesktopPath( const TQString& _name )
-{
- KService * s = KServiceFactory::self()->findServiceByDesktopPath( _name );
- return KService::Ptr( s );
-}
-
-KService::Ptr KService::serviceByDesktopName( const TQString& _name )
-{
- KService * s = KServiceFactory::self()->findServiceByDesktopName( _name.lower() );
- if (!s && !_name.startsWith("kde-"))
- s = KServiceFactory::self()->findServiceByDesktopName( "kde-"+_name.lower() );
- return KService::Ptr( s );
-}
-
-KService::Ptr KService::serviceByMenuId( const TQString& _name )
-{
- KService * s = KServiceFactory::self()->findServiceByMenuId( _name );
- return KService::Ptr( s );
-}
-
-KService::Ptr KService::serviceByStorageId( const TQString& _storageId )
-{
- KService::Ptr service = KService::serviceByMenuId( _storageId );
- if (service)
- return service;
-
- service = KService::serviceByDesktopPath(_storageId);
- if (service)
- return service;
-
- if (!TQDir::isRelativePath(_storageId) && TQFile::exists(_storageId))
- return new KService(_storageId);
-
- TQString tmp = _storageId;
- tmp = tmp.mid(tmp.findRev('/')+1); // Strip dir
-
- if (tmp.endsWith(".desktop"))
- tmp.truncate(tmp.length()-8);
-
- if (tmp.endsWith(".kdelnk"))
- tmp.truncate(tmp.length()-7);
-
- service = KService::serviceByDesktopName(tmp);
-
- return service;
-}
-
-KService::List KService::allInitServices()
-{
- return KServiceFactory::self()->allInitServices();
-}
-
-bool KService::substituteUid() const {
- TQVariant v = property("X-TDE-SubstituteUID", TQVariant::Bool);
- return v.isValid() && v.toBool();
-}
-
-TQString KService::username() const {
- // See also KDesktopFile::tryExec()
- TQString user;
- TQVariant v = property("X-TDE-Username", TQVariant::String);
- user = v.isValid() ? v.toString() : TQString::null;
- if (user.isEmpty())
- user = ::getenv("ADMIN_ACCOUNT");
- if (user.isEmpty())
- user = "root";
- return user;
-}
-
-bool KService::noDisplay() const {
- TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( "NoDisplay" );
- if ( (it != m_mapProps.end()) && (it.data().isValid()))
- {
- TQString aValue = it.data().toString().lower();
- if (aValue == "true" || aValue == "on" || aValue == "yes")
- return true;
- }
-
- it = m_mapProps.find( "OnlyShowIn" );
- if ( (it != m_mapProps.end()) && (it.data().isValid()))
- {
- TQString aValue = it.data().toString();
- TQStringList aList = TQStringList::split(';', aValue);
- if ((!aList.contains("TDE")) && (!aList.contains("KDE")))
- return true;
- }
-
- it = m_mapProps.find( "NotShowIn" );
- if ( (it != m_mapProps.end()) && (it.data().isValid()))
- {
- TQString aValue = it.data().toString();
- TQStringList aList = TQStringList::split(';', aValue);
- if ((aList.contains("TDE")) || (aList.contains("KDE")))
- return true;
- }
-
- if (!kapp->authorizeControlModule(d->menuId))
- return true;
-
- return false;
-}
-
-TQString KService::untranslatedGenericName() const {
- TQVariant v = property("UntranslatedGenericName", TQVariant::String);
- return v.isValid() ? v.toString() : TQString::null;
-}
-
-bool KService::SuSEunimportant() const {
- TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( "X-SuSE-Unimportant" );
- if ( (it == m_mapProps.end()) || (!it.data().isValid()))
- {
- return false;
- }
-
- TQString aValue = it.data().toString();
- if (aValue == "true" || aValue == "on" || aValue == "yes")
- return true;
- else
- return false;
-}
-
-TQString KService::parentApp() const {
- TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( "X-TDE-ParentApp" );
- if ( (it == m_mapProps.end()) || (!it.data().isValid()))
- {
- return TQString::null;
- }
-
- return it.data().toString();
-}
-
-bool KService::allowMultipleFiles() const {
- // Can we pass multiple files on the command line or do we have to start the application for every single file ?
- if ( m_strExec.find( "%F" ) != -1 || m_strExec.find( "%U" ) != -1 ||
- m_strExec.find( "%N" ) != -1 || m_strExec.find( "%D" ) != -1 )
- return true;
- else
- return false;
-}
-
-TQStringList KService::categories() const
-{
- return d->categories;
-}
-
-TQString KService::menuId() const
-{
- return d->menuId;
-}
-
-void KService::setMenuId(const TQString &menuId)
-{
- d->menuId = menuId;
-}
-
-TQString KService::storageId() const
-{
- if (!d->menuId.isEmpty())
- return d->menuId;
- return entryPath();
-}
-
-TQString KService::locateLocal()
-{
- if (d->menuId.isEmpty() || desktopEntryPath().startsWith(".hidden") ||
- (TQDir::isRelativePath(desktopEntryPath()) && d->categories.isEmpty()))
- return KDesktopFile::locateLocal(desktopEntryPath());
-
- return ::locateLocal("xdgdata-apps", d->menuId);
-}
-
-TQString KService::newServicePath(bool showInMenu, const TQString &suggestedName,
- TQString *menuId, const TQStringList *reservedMenuIds)
-{
- TQString base = suggestedName;
- if (!showInMenu)
- base.prepend("kde-");
-
- TQString result;
- for(int i = 1; true; i++)
- {
- if (i == 1)
- result = base + ".desktop";
- else
- result = base + TQString("-%1.desktop").arg(i);
-
- if (reservedMenuIds && reservedMenuIds->contains(result))
- continue;
-
- // Lookup service by menu-id
- KService::Ptr s = serviceByMenuId(result);
- if (s)
- continue;
-
- if (showInMenu)
- {
- if (!locate("xdgdata-apps", result).isEmpty())
- continue;
- }
- else
- {
- TQString file = result.mid(4); // Strip "kde-"
- if (!locate("apps", ".hidden/"+file).isEmpty())
- continue;
- }
-
- break;
- }
- if (menuId)
- *menuId = result;
-
- if (showInMenu)
- {
- return ::locateLocal("xdgdata-apps", result);
- }
- else
- {
- TQString file = result.mid(4); // Strip "kde-"
- return ::locateLocal("apps", ".hidden/"+file);
- }
-}
-
-
-void KService::virtual_hook( int id, void* data )
-{ KSycocaEntry::virtual_hook( id, data ); }
-
-
-void KService::rebuildKSycoca(TQWidget *parent)
-{
- KServiceProgressDialog dlg(parent, "tdesycoca_progress",
- i18n("Updating System Configuration"),
- i18n("Updating system configuration."));
-
- TQByteArray data;
- DCOPClient *client = kapp->dcopClient();
-
- int result = client->callAsync("kded", "kbuildsycoca", "recreate()",
- data, TQT_TQOBJECT(&dlg), TQT_SLOT(slotFinished()));
-
- if (result)
- {
- dlg.exec();
- }
-}
-
-KServiceProgressDialog::KServiceProgressDialog(TQWidget *parent, const char *name,
- const TQString &caption, const TQString &text)
- : KProgressDialog(parent, name, caption, text, true)
-{
- connect(&m_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotProgress()));
- progressBar()->setTotalSteps(20);
- m_timeStep = 700;
- m_timer.start(m_timeStep);
- setAutoClose(false);
-}
-
-void
-KServiceProgressDialog::slotProgress()
-{
- int p = progressBar()->progress();
- if (p == 18)
- {
- progressBar()->reset();
- progressBar()->setProgress(1);
- m_timeStep = m_timeStep * 2;
- m_timer.start(m_timeStep);
- }
- else
- {
- progressBar()->setProgress(p+1);
- }
-}
-
-void
-KServiceProgressDialog::slotFinished()
-{
- progressBar()->setProgress(20);
- m_timer.stop();
- TQTimer::singleShot(1000, this, TQT_SLOT(close()));
-}
-
-#include "kservice_p.moc"
diff --git a/kio/kio/kshred.h b/kio/kio/kshred.h
deleted file mode 100644
index 7f817c1ea..000000000
--- a/kio/kio/kshred.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/*--------------------------------------------------------------------------*
- KShred.h Copyright (c) 2000 MieTerra LLC.
- Credits: Andreas F. Pour <bugs@mieterra.com>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-*/
-
-#ifndef kshred_h
-#define kshred_h
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <tqstring.h>
-#include <tqfile.h>
-#include <tqobject.h>
-
-#include <kio/global.h>
-
-/**
- * @deprecated
- * Erase a file in a way that makes recovery impossible -- well, no guarentee
- * of that, but at least as difficult as reasonably possible.
- * For this, KShred write several times over the
- * existing file, using different patterns, before deleting it.
- * @author Andreas F. Pour <bugs@mieterra.com>
- * @author David Faure <faure@kde.org> (integration into KDE and progress signal)
- */
-class TDEIO_EXPORT_DEPRECATED KShred : public TQObject { // KDE4: remove
-
- Q_OBJECT
-
- public:
-
- /**
- * Initialize the class using the name of the file to 'shred'.
- * @param fileName fully qualified name of the file to shred.
- */
- KShred(TQString fileName);
-
- /*
- * Destructor for the class.
- */
- ~KShred();
-
- /**
- * Writes all 1's over the entire file and flushes the file buffers.
- * @return true on success, false on error (invalid filename or write error)
- */
-
- bool fill1s();
- /**
- * Writes all 0's over the entire file and flushes the file buffers.
- * @return true on success, false on error (invalid filename or write error)
- */
- bool fill0s();
-
- /**
- * Writes the specified byte over the entire file and flushes the file buffers.
- * @param byte the value to write over every byte of the file
- * @return true on success, false on error (invalid filename or write error)
- */
- bool fillbyte(unsigned int byte);
-
- /**
- * Writes random bites over the entire file and flushes the file buffers.
- * @return true on success, false on error (invalid filename or write error)
- */
- bool fillrandom();
-
- /**
- * Writes the specified byte array over the entire file and flushes the file buffers.
- * @param pattern the value to write over the entire file
- * @param size the length of the 'pattern' byte array
- * @return true on success, false on error (invalid filename or write error)
- */
- bool fillpattern(unsigned char *pattern, unsigned int size);
-
- /**
- * Shreds a file by writing a series of values over it (uses
- * #fill0s, then fill1s, then fillrandom, then
- * fillbyte with 0101..., then fillbyte with 1010....
- * @return true on success, false on error (invalid filename or write error)
- */
- bool shred();
-
- /**
- * The simplest method to shred a file.
- * No need to create an instance of the class.
- * @param fileName fully qualified name of the file to shred.
- */
- static bool shred(TQString fileName);
-
- signals:
- /**
- * Shows progress of the shredding.
- * @param bytes the number of bytes written to the file
- */
- void processedSize(TDEIO::filesize_t bytes);
-
- /**
- * Shows a message in the progress dialog
- * @param message the message to display
- */
- void infoMessage(const TQString & message);
-
- private:
- /**
- * @internal write the data to the file
- */
- bool writeData(unsigned char *data, unsigned int size);
-
- /**
- * @internal flush the data to the file
- */
- bool flush();
-
- /**
- * @internal structure for the file information
- */
- TQFile *file;
-
- /**
- * @internal for the size of the file
- */
- TDEIO::filesize_t fileSize;
-
- /**
- * @internal for keeping track of progress
- */
- unsigned int totalBytes;
- unsigned int bytesWritten;
- unsigned int lastSignalled;
- unsigned int tbpc;
- unsigned int fspc;
- private:
- class KShredPrivate* d;
-};
-
-#endif
diff --git a/kio/kio/ktrader.h b/kio/kio/ktrader.h
deleted file mode 100644
index 98891b48d..000000000
--- a/kio/kio/ktrader.h
+++ /dev/null
@@ -1,295 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Torben Weis <weis@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __ktrader_h__
-#define __ktrader_h__
-
-#include <tqstring.h>
-#include <tqobject.h>
-#include <kservice.h>
-
-/**
- * A Trader interface, similar to the CORBA Trader.
- *
- * Basically, it provides a way for an application to query
- * all KDE services (that is, applications and components) that match
- * a specific set of requirements. This allows you to find an
- * application in real-time without you having to hard-code the name
- * and/or path of the application.
- *
- * \par Examples
- *
- * A few examples will make this a lot more clear.
- *
- * Say you have an application that will display HTML. In this
- * example, you don't want to link to tdehtml... and furthermore, you
- * really don't care if the HTML browser is ours or not, as long as
- * it works. The way that you formulate your query as well as the way
- * that you execute the browser depends on whether or not you want the
- * browser to run stand-alone or embedded.
- *
- * If you want the browser to run standalone, then you will limit the
- * query to search for all services that handle 'text/html' @em and,
- * furthermore, they must be applications (Type=Application). You
- * then will use KRun::run() to invoke the application. In "trader-speak",
- * this looks like this:
- * \code
- * KTrader::OfferList offers = KTrader::self()->query("text/html", "Type == 'Application'");
- * KService::Ptr ptr = offers.first();
- * KURL::List lst;
- * lst.append("http://www.kde.org/index.html");
- * KRun::run(*ptr, lst);
- * \endcode
- *
- * Now, say that you want to list all KParts component that can handle HTML.
- * \code
- * KTrader::OfferList offers = KTrader::self()->query("text/html", "KParts/ReadOnlyPart");
- * \endcode
- *
- * If you want to get the preferred KParts component for text/html you could use
- * KServiceTypeProfile::preferredService("text/html", "KParts/ReadOnlyPart"), although if this is about
- * loading that component you would rather use KParts::ComponentFactory directly.
- *
- *
- * Please note that when including property names containing arithmetic operators like - or +, then you have
- * to put brackets around the property name, in order to correctly separate arithmetic operations from
- * the name. So for example a constraint expression like
- * X-TDE-Blah < 4
- * needs to be written as
- * [X-TDE-Blah] < 4
- * otherwise it could also be interpreted as
- * Substract the numeric value of the property "KDE" and "Blah" from the property "X" and make sure it
- * is less than 4.
- * Instead of the other meaning, make sure that the numeric value of "X-TDE-Blah" is less than 4.
- *
- * See also the formal syntax defined in @ref tradersyntax .
- *
- * @short Provides a way to query the KDE infrastructure for specific
- * applications or components.
- * @author Torben Weis <weis@kde.org>
- */
-class TDEIO_EXPORT KTrader : public TQObject
-{
- Q_OBJECT
-public:
- /**
- * A list of services.
- */
- typedef TQValueList<KService::Ptr> OfferList;
- typedef TQValueListIterator<KService::Ptr> OfferListIterator;
-
- /**
- * Standard destructor
- */
- virtual ~KTrader();
-
- /**
- * The main function in the KTrader class.
- *
- * It will return a list of services that match your
- * specifications. The only required parameter is the service
- * type. This is something like 'text/plain' or 'text/html'. The
- * constraint parameter is used to limit the possible choices
- * returned based on the constraints you give it.
- *
- * The @p constraint language is rather full. The most common
- * keywords are AND, OR, NOT, IN, and EXIST, all used in an
- * almost spoken-word form. An example is:
- * \code
- * (Type == 'Service') and (('KParts/ReadOnlyPart' in ServiceTypes) or (exist Exec))
- * \endcode
- *
- * The keys used in the query (Type, ServiceType, Exec) are all
- * fields found in the .desktop files.
- *
- * @param servicetype A service type like 'text/plain', 'text/html', or 'KOfficePlugin'.
- * @param constraint A constraint to limit the choices returned, TQString::null to
- * get all services of the given @p servicetype
- * @param preferences Indicates a particular preference to return, TQString::null to ignore.
- * Uses an expression in the constraint language that must return
- * a number
- *
- * @return A list of services that satisfy the query
- * @see http://developer.kde.org/documentation/library/3.5-api/tdelibs-apidocs/kio/kio/html/tradersyntax.html
- */
- virtual OfferList query( const TQString& servicetype,
- const TQString& constraint = TQString::null,
- const TQString& preferences = TQString::null) const;
-
- /**
- * A variant of query(), that takes two service types as an input.
- * It is not exactly the same as adding the second service type
- * in the constraints of the other query call, because this one
- * takes into account user preferences for this combination of service types.
- *
- * Example usage:
- * To get list of applications that can handle a given mimetype,
- * set @p servicetype to the mimetype and @p genericServiceType is "Application".
- * To get list of embeddable components that can handle a given mimetype,
- * set @p servicetype to the mimetype and @p genericServiceType is "KParts/ReadOnlyPart".
- *
- * @param servicetype A service type like 'text/plain', 'text/html', or 'KOfficePlugin'.
- * @param genericServiceType a basic service type, like 'KParts/ReadOnlyPart' or 'Application'
- * @param constraint A constraint to limit the choices returned, TQString::null to
- * get all services of the given @p servicetype
- * @param preferences Indicates a particular preference to return, TQString::null to ignore.
- * Uses an expression in the constraint language that must return
- * a number
- *
- * @return A list of services that satisfy the query
- * @see http://developer.kde.org/documentation/library/kdeqt/tradersyntax.html
- */
- OfferList query( const TQString& servicetype, const TQString& genericServiceType,
- const TQString& constraint /*= TQString::null*/,
- const TQString& preferences /*= TQString::null*/) const;
-
- /**
- * This is a static pointer to a KTrader instance.
- *
- * You will need
- * to use this to access the KTrader functionality since the
- * constuctors are protected.
- *
- * @return Static KTrader instance
- */
- static KTrader* self();
-
-protected:
- /**
- * @internal
- */
- KTrader();
-
-private:
- static KTrader* s_self;
-protected:
- virtual void virtual_hook( int id, void* data );
-};
-
-/** @page tradersyntax Trader Syntax
- *
- *
- * @section Literals
- *
- * As elementary atoms of the constraint language, KTrader supports
- * booleans, integers, floats and strings. Boolean literals are
- * @a TRUE and @a FALSE . Integers can be positive or negative,
- * i.e. @a 42 and @a -10 are legal values. Floating point
- * numbers are @a 3.141592535 or @a -999.999 . Scientific notation
- * like @a 1.5e-2 is not supported. Character literals are delimited
- * by single quotation marks, e.g. @a 'Bernd' .
- *
- *
- * @section Symbols
- *
- * Identifiers in query string are interpreted as property names, which
- * are listed in the service's <tt>.desktop</tt> file. For example,
- * <tt>Name</tt> is the name of the service, <tt>ServiceTypes</tt> is a
- * list of the service types it supports. Note that only properties can
- * be written as-is which start with an alphabetical character and contain
- * only alphanumerical characters. Other properties have to be enclosed in
- * brackets, e.g. <tt>[X-TDE-Init]</tt>. Properties must not contain any
- * special characters other than <tt>-</tt>.
- *
- * Special property names:
- * - <b>DesktopEntryName</b> stands for the filename of the service
- * desktop entry without any extension. This can be useful to
- * exclude some specific services.
- * - <b>DesktopEntryPath</b> stands for the relative or full path
- * to the .desktop file, see KService::desktopEntryPath. Mentionned
- * here for completeness, better not use it (things can be moved
- * around).
- * - <b>Library</b> is the property whose value is set by
- * <tt>X-TDE-Library</tt> in the .desktop file. This renaming
- * happened to conform to the desktop file standard, but the
- * property name didn't change.
- *
- *
- * @section Comparison
- *
- * Supported comparison operators are:
- *
- * - <tt>==</tt>
- * - <tt>!=</tt>
- * - <tt>&lt;</tt>
- * - <tt>&lt;=</tt>
- * - <tt>&gt;</tt>
- * - <tt>&gt;=</tt>
- *
- *
- * @section Arithmetic Arithmetic and boolean expressions
- *
- * - <tt>+</tt>
- * - <tt>-</tt>
- * - <tt>*</tt>
- * - <tt>/</tt>
- * - <tt>and</tt>
- * - <tt>or</tt>
- * - <tt>not</tt>
- *
- * Note that the arithmetic operators are possible for integers and
- * floating point numbers. <tt>-</tt> is both a unary and binary operator,
- * <tt>not</tt> is a unary operator.
- *
- *
- * @section Other Other operators
- *
- * - <tt>~</tt>
- * - <tt>in</tt>
- * - <tt>exist</tt>
- * - <tt>()</tt>
- *
- * The tilde operator stands for a substring match. For example,
- * <tt>KParts ~ 'KParts/ReadOnlyPart'</tt> is TRUE. The membership
- * operator <tt>in</tt> tests whether a value is in a list. A list is a
- * string with semi-colon- or comma-separated entries, depending on the
- * type. An example for the membership operator is
- * <tt>'text/plain' in ServiceTypes</tt>.
- * The <tt>exist</tt> tests whether a certain property is defined in the
- * <tt>.desktop</tt> file. Subexpressions are written in parentheses.
- *
- * Warning, testing the contents of a property only works if the property
- * is specified. There is not support for default values. If the property
- * might be missing, and you still want such services to be included, you
- * have to check for existence before testing it. For instance, to say
- * that MyProp is a boolean that defaults to true, and that you want the
- * services that have it set to true, use:
- * <tt>not exist MyProp or MyProp</tt>
- * Simply testing for <tt>MyProp</tt> would
- * exclude the services without the property at all.
- *
- *
- * @section Examples
- *
- * The following examples show filters for .desktop files.
- * <tt>Type</tt>, <tt>ServiceTypes</tt> and <tt>MimeType</tt> are
- * properties in .desktop files. Be aware that within KTrader MimeType
- * properties are understood as ServiceTypes ones.
- *
- *
- * - <tt>Type == 'Application'</tt>@n
- * All services that are applications.
- * - <tt>'KParts/ReadOnlyPart' in ServiceTypes</tt>@n
- * All read-only KParts.
- * - <tt>('KParts/ReadOnlyPart' in ServiceTypes) and ('text/plain' in ServiceTypes)</tt>@n
- * All read-only KParts that handle the mime type 'text/plain'.
- *
- * @author Bernd Gehrmann <a href="mailto:bernd@tdevelop.org">bernd@tdevelop.org</a>
-*/
-
-
-#endif
diff --git a/kio/kio/kurlcompletion.cpp b/kio/kio/kurlcompletion.cpp
deleted file mode 100644
index 2dc4185cc..000000000
--- a/kio/kio/kurlcompletion.cpp
+++ /dev/null
@@ -1,1604 +0,0 @@
-/* -*- indent-tabs-mode: t; tab-width: 4; c-basic-offset:4 -*-
-
- This file is part of the KDE libraries
- Copyright (C) 2000 David Smith <dsmith@algonet.se>
- Copyright (C) 2004 Scott Wheeler <wheeler@kde.org>
-
- This class was inspired by a previous KURLCompletion by
- Henner Zeller <zeller@think.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <config.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <limits.h>
-
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqvaluelist.h>
-#include <tqregexp.h>
-#include <tqtimer.h>
-#include <tqdir.h>
-#include <tqfile.h>
-#include <tqtextstream.h>
-#include <tqdeepcopy.h>
-#include <tqthread.h>
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kcompletion.h>
-#include <kurl.h>
-#include <kio/jobclasses.h>
-#include <kio/job.h>
-#include <kprotocolinfo.h>
-#include <kconfig.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kde_file.h>
-
-#include <sys/types.h>
-#include <dirent.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include <pwd.h>
-#include <time.h>
-#include <sys/param.h>
-
-#include "kurlcompletion.h"
-
-static bool expandTilde(TQString &);
-static bool expandEnv(TQString &);
-
-static TQString unescape(const TQString &text);
-
-// Permission mask for files that are executable by
-// user, group or other
-#define MODE_EXE (S_IXUSR | S_IXGRP | S_IXOTH)
-
-// Constants for types of completion
-enum ComplType {CTNone=0, CTEnv, CTUser, CTMan, CTExe, CTFile, CTUrl, CTInfo};
-
-class CompletionThread;
-
-/**
- * A custom event type that is used to return a list of completion
- * matches from an asyncrynous lookup.
- */
-
-class CompletionMatchEvent : public TQCustomEvent
-{
-public:
- CompletionMatchEvent( CompletionThread *thread ) :
- TQCustomEvent( uniqueType() ),
- m_completionThread( thread )
- {}
-
- CompletionThread *completionThread() const { return m_completionThread; }
- static int uniqueType() { return User + 61080; }
-
-private:
- CompletionThread *m_completionThread;
-};
-
-class CompletionThread : public TQThread
-{
-protected:
- CompletionThread( KURLCompletion *receiver ) :
- TQThread(),
- m_receiver( receiver ),
- m_terminationRequested( false )
- {}
-
-public:
- void requestTermination() { m_terminationRequested = true; }
- TQDeepCopy<TQStringList> matches() const { return m_matches; }
-
-protected:
- void addMatch( const TQString &match ) { m_matches.append( match ); }
- bool terminationRequested() const { return m_terminationRequested; }
- void done()
- {
- if ( !m_terminationRequested )
- kapp->postEvent( m_receiver, new CompletionMatchEvent( this ) );
- else
- delete this;
- }
-
-private:
- KURLCompletion *m_receiver;
- TQStringList m_matches;
- bool m_terminationRequested;
-};
-
-/**
- * A simple thread that fetches a list of tilde-completions and returns this
- * to the caller via a CompletionMatchEvent.
- */
-
-class UserListThread : public CompletionThread
-{
-public:
- UserListThread( KURLCompletion *receiver ) :
- CompletionThread( receiver )
- {}
-
-protected:
- virtual void run()
- {
- static const TQChar tilde = '~';
-
- struct passwd *pw;
- while ( ( pw = ::getpwent() ) && !terminationRequested() )
- addMatch( tilde + TQString::fromLocal8Bit( pw->pw_name ) );
-
- ::endpwent();
-
- addMatch( tilde );
-
- done();
- }
-};
-
-class DirectoryListThread : public CompletionThread
-{
-public:
- DirectoryListThread( KURLCompletion *receiver,
- const TQStringList &dirList,
- const TQString &filter,
- bool onlyExe,
- bool onlyDir,
- bool noHidden,
- bool appendSlashToDir ) :
- CompletionThread( receiver ),
- m_dirList( TQDeepCopy<TQStringList>( dirList ) ),
- m_filter( TQDeepCopy<TQString>( filter ) ),
- m_onlyExe( onlyExe ),
- m_onlyDir( onlyDir ),
- m_noHidden( noHidden ),
- m_appendSlashToDir( appendSlashToDir )
- {}
-
- virtual void run();
-
-private:
- TQStringList m_dirList;
- TQString m_filter;
- bool m_onlyExe;
- bool m_onlyDir;
- bool m_noHidden;
- bool m_appendSlashToDir;
-};
-
-void DirectoryListThread::run()
-{
- // Thread safety notes:
- //
- // There very possibly may be thread safety issues here, but I've done a check
- // of all of the things that would seem to be problematic. Here are a few
- // things that I have checked to be safe here (some used indirectly):
- //
- // TQDir::currentDirPath(), TQDir::setCurrent(), TQFile::decodeName(), TQFile::encodeName()
- // TQString::fromLocal8Bit(), TQString::local8Bit(), TQTextCodec::codecForLocale()
- //
- // Also see (for POSIX functions):
- // http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html
-
- DIR *dir = 0;
-
- for ( TQStringList::ConstIterator it = m_dirList.begin();
- it != m_dirList.end() && !terminationRequested();
- ++it )
- {
- // Open the next directory
-
- if ( !dir ) {
- dir = ::opendir( TQFile::encodeName( *it ) );
- if ( ! dir ) {
- kdDebug() << "Failed to open dir: " << *it << endl;
- done();
- return;
- }
- }
-
- // A trick from KIO that helps performance by a little bit:
- // chdir to the directroy so we won't have to deal with full paths
- // with stat()
-
- TQString path = TQDir::currentDirPath();
- TQDir::setCurrent( *it );
-
- // Loop through all directory entries
- // Solaris and IRIX dirent structures do not allocate space for d_name. On
- // systems that do (HP-UX, Linux, Tru64 UNIX), we overallocate space but
- // that's ok.
-#ifndef HAVE_READDIR_R
- struct dirent *dirEntry = 0;
- while ( !terminationRequested() &&
- (dirEntry = ::readdir( dir)))
-#else
-#if !defined(MAXPATHLEN) && defined(__GNU__)
-#define MAXPATHLEN UCHAR_MAX
-#endif
- struct dirent *dirPosition = (struct dirent *) malloc( sizeof( struct dirent ) + MAXPATHLEN + 1 );
- struct dirent *dirEntry = 0;
- while ( !terminationRequested() &&
- ::readdir_r( dir, dirPosition, &dirEntry ) == 0 && dirEntry )
-#endif
-
- {
- // Skip hidden files if m_noHidden is true
-
- if ( dirEntry->d_name[0] == '.' && m_noHidden )
- continue;
-
- // Skip "."
-
- if ( dirEntry->d_name[0] == '.' && dirEntry->d_name[1] == '\0' )
- continue;
-
- // Skip ".."
-
- if ( dirEntry->d_name[0] == '.' && dirEntry->d_name[1] == '.' && dirEntry->d_name[2] == '\0' )
- continue;
-
- TQString file = TQFile::decodeName( dirEntry->d_name );
-
- if ( m_filter.isEmpty() || file.startsWith( m_filter ) ) {
-
- if ( m_onlyExe || m_onlyDir || m_appendSlashToDir ) {
- KDE_struct_stat sbuff;
-
- if ( KDE_stat( dirEntry->d_name, &sbuff ) == 0 ) {
-
- // Verify executable
-
- if ( m_onlyExe && ( sbuff.st_mode & MODE_EXE ) == 0 )
- continue;
-
- // Verify directory
-
- if ( m_onlyDir && !S_ISDIR( sbuff.st_mode ) )
- continue;
-
- // Add '/' to directories
-
- if ( m_appendSlashToDir && S_ISDIR( sbuff.st_mode ) )
- file.append( '/' );
-
- }
- else {
- kdDebug() << "Could not stat file " << file << endl;
- continue;
- }
- }
-
- addMatch( file );
- }
- }
-
- // chdir to the original directory
-
- TQDir::setCurrent( path );
-
- ::closedir( dir );
- dir = 0;
-#ifdef HAVE_READDIR_R
- free( dirPosition );
-#endif
- }
-
- done();
-}
-
-///////////////////////////////////////////////////////
-///////////////////////////////////////////////////////
-// MyURL - wrapper for KURL with some different functionality
-//
-
-class KURLCompletion::MyURL
-{
-public:
- MyURL(const TQString &url, const TQString &cwd);
- MyURL(const MyURL &url);
- ~MyURL();
-
- KURL *kurl() const { return m_kurl; }
-
- TQString protocol() const { return m_kurl->protocol(); }
- // The directory with a trailing '/'
- TQString dir() const { return m_kurl->directory(false, false); }
- TQString file() const { return m_kurl->fileName(false); }
-
- // The initial, unparsed, url, as a string.
- TQString url() const { return m_url; }
-
- // Is the initial string a URL, or just a path (whether absolute or relative)
- bool isURL() const { return m_isURL; }
-
- void filter( bool replace_user_dir, bool replace_env );
-
-private:
- void init(const TQString &url, const TQString &cwd);
-
- KURL *m_kurl;
- TQString m_url;
- bool m_isURL;
-};
-
-KURLCompletion::MyURL::MyURL(const TQString &url, const TQString &cwd)
-{
- init(url, cwd);
-}
-
-KURLCompletion::MyURL::MyURL(const MyURL &url)
-{
- m_kurl = new KURL( *(url.m_kurl) );
- m_url = url.m_url;
- m_isURL = url.m_isURL;
-}
-
-void KURLCompletion::MyURL::init(const TQString &url, const TQString &cwd)
-{
- // Save the original text
- m_url = url;
-
- // Non-const copy
- TQString url_copy = url;
-
- // Special shortcuts for "man:" and "info:"
- if ( url_copy[0] == '#' ) {
- if ( url_copy[1] == '#' )
- url_copy.replace( 0, 2, TQString("info:") );
- else
- url_copy.replace( 0, 1, TQString("man:") );
- }
-
- // Look for a protocol in 'url'
- TQRegExp protocol_regex = TQRegExp( "^[^/\\s\\\\]*:" );
-
- // Assume "file:" or whatever is given by 'cwd' if there is
- // no protocol. (KURL does this only for absoute paths)
- if ( protocol_regex.search( url_copy ) == 0 )
- {
- m_kurl = new KURL( url_copy );
- m_isURL = true;
- }
- else // relative path or ~ or $something
- {
- m_isURL = false;
- if ( cwd.isEmpty() )
- {
- m_kurl = new KURL();
- if ( !TQDir::isRelativePath(url_copy) || url_copy[0] == '$' || url_copy[0] == '~' )
- m_kurl->setPath( url_copy );
- else
- *m_kurl = url_copy;
- }
- else
- {
- KURL base = KURL::fromPathOrURL( cwd );
- base.adjustPath(+1);
-
- if ( !TQDir::isRelativePath(url_copy) || url_copy[0] == '~' || url_copy[0] == '$' )
- {
- m_kurl = new KURL();
- m_kurl->setPath( url_copy );
- }
- else // relative path
- {
- //m_kurl = new KURL( base, url_copy );
- m_kurl = new KURL( base );
- m_kurl->addPath( url_copy );
- }
- }
- }
-}
-
-KURLCompletion::MyURL::~MyURL()
-{
- delete m_kurl;
-}
-
-void KURLCompletion::MyURL::filter( bool replace_user_dir, bool replace_env )
-{
- TQString d = dir() + file();
- if ( replace_user_dir ) expandTilde( d );
- if ( replace_env ) expandEnv( d );
- m_kurl->setPath( d );
-}
-
-///////////////////////////////////////////////////////
-///////////////////////////////////////////////////////
-// KURLCompletionPrivate
-//
-class KURLCompletionPrivate
-{
-public:
- KURLCompletionPrivate() : url_auto_completion(true),
- userListThread(0),
- dirListThread(0) {}
- ~KURLCompletionPrivate();
-
- TQValueList<KURL*> list_urls;
-
- bool onlyLocalProto;
-
- // urlCompletion() in Auto/Popup mode?
- bool url_auto_completion;
-
- // Append '/' to directories in Popup mode?
- // Doing that stat's all files and is slower
- bool popup_append_slash;
-
- // Keep track of currently listed files to avoid reading them again
- TQString last_path_listed;
- TQString last_file_listed;
- TQString last_prepend;
- int last_compl_type;
- int last_no_hidden;
-
- TQString cwd; // "current directory" = base dir for completion
-
- KURLCompletion::Mode mode; // ExeCompletion, FileCompletion, DirCompletion
- bool replace_env;
- bool replace_home;
- bool complete_url; // if true completing a URL (i.e. 'prepend' is a URL), otherwise a path
-
- TDEIO::ListJob *list_job; // kio job to list directories
-
- TQString prepend; // text to prepend to listed items
- TQString compl_text; // text to pass on to KCompletion
-
- // Filters for files read with kio
- bool list_urls_only_exe; // true = only list executables
- bool list_urls_no_hidden;
- TQString list_urls_filter; // filter for listed files
-
- CompletionThread *userListThread;
- CompletionThread *dirListThread;
-};
-
-KURLCompletionPrivate::~KURLCompletionPrivate()
-{
- if ( userListThread )
- userListThread->requestTermination();
- if ( dirListThread )
- dirListThread->requestTermination();
-}
-
-///////////////////////////////////////////////////////
-///////////////////////////////////////////////////////
-// KURLCompletion
-//
-
-KURLCompletion::KURLCompletion() : KCompletion()
-{
- init();
-}
-
-
-KURLCompletion::KURLCompletion( Mode mode ) : KCompletion()
-{
- init();
- setMode ( mode );
-}
-
-KURLCompletion::~KURLCompletion()
-{
- stop();
- delete d;
-}
-
-
-void KURLCompletion::init()
-{
- d = new KURLCompletionPrivate;
-
- d->cwd = TQDir::homeDirPath();
-
- d->replace_home = true;
- d->replace_env = true;
- d->last_no_hidden = false;
- d->last_compl_type = 0;
- d->list_job = 0L;
- d->mode = KURLCompletion::FileCompletion;
-
- // Read settings
- TDEConfig *c = TDEGlobal::config();
- TDEConfigGroupSaver cgs( c, "URLCompletion" );
-
- d->url_auto_completion = c->readBoolEntry("alwaysAutoComplete", true);
- d->popup_append_slash = c->readBoolEntry("popupAppendSlash", true);
- d->onlyLocalProto = c->readBoolEntry("LocalProtocolsOnly", false);
-}
-
-void KURLCompletion::setDir(const TQString &dir)
-{
- d->cwd = dir;
-}
-
-TQString KURLCompletion::dir() const
-{
- return d->cwd;
-}
-
-KURLCompletion::Mode KURLCompletion::mode() const
-{
- return d->mode;
-}
-
-void KURLCompletion::setMode( Mode mode )
-{
- d->mode = mode;
-}
-
-bool KURLCompletion::replaceEnv() const
-{
- return d->replace_env;
-}
-
-void KURLCompletion::setReplaceEnv( bool replace )
-{
- d->replace_env = replace;
-}
-
-bool KURLCompletion::replaceHome() const
-{
- return d->replace_home;
-}
-
-void KURLCompletion::setReplaceHome( bool replace )
-{
- d->replace_home = replace;
-}
-
-/*
- * makeCompletion()
- *
- * Entry point for file name completion
- */
-TQString KURLCompletion::makeCompletion(const TQString &text)
-{
- //kdDebug() << "KURLCompletion::makeCompletion: " << text << " d->cwd=" << d->cwd << endl;
-
- MyURL url(text, d->cwd);
-
- d->compl_text = text;
-
- // Set d->prepend to the original URL, with the filename [and ref/query] stripped.
- // This is what gets prepended to the directory-listing matches.
- int toRemove = url.file().length() - url.kurl()->query().length();
- if ( url.kurl()->hasRef() )
- toRemove += url.kurl()->ref().length() + 1;
- d->prepend = text.left( text.length() - toRemove );
- d->complete_url = url.isURL();
-
- TQString match;
-
- // Environment variables
- //
- if ( d->replace_env && envCompletion( url, &match ) )
- return match;
-
- // User directories
- //
- if ( d->replace_home && userCompletion( url, &match ) )
- return match;
-
- // Replace user directories and variables
- url.filter( d->replace_home, d->replace_env );
-
- //kdDebug() << "Filtered: proto=" << url.protocol()
- // << ", dir=" << url.dir()
- // << ", file=" << url.file()
- // << ", kurl url=" << *url.kurl() << endl;
-
- if ( d->mode == ExeCompletion ) {
- // Executables
- //
- if ( exeCompletion( url, &match ) )
- return match;
-
- // KRun can run "man:" and "info:" etc. so why not treat them
- // as executables...
-
- if ( urlCompletion( url, &match ) )
- return match;
- }
- else if ( d->mode == SystemExeCompletion ) {
- // Executables
- //
- if ( systemexeCompletion( url, &match ) )
- return match;
-
- // KRun can run "man:" and "info:" etc. so why not treat them
- // as executables...
-
- if ( urlCompletion( url, &match ) )
- return match;
- }
- else {
- // Local files, directories
- //
- if ( fileCompletion( url, &match ) )
- return match;
-
- // All other...
- //
- if ( urlCompletion( url, &match ) )
- return match;
- }
-
- setListedURL( CTNone );
- stop();
-
- return TQString::null;
-}
-
-/*
- * finished
- *
- * Go on and call KCompletion.
- * Called when all matches have been added
- */
-TQString KURLCompletion::finished()
-{
- if ( d->last_compl_type == CTInfo )
- return KCompletion::makeCompletion( d->compl_text.lower() );
- else
- return KCompletion::makeCompletion( d->compl_text );
-}
-
-/*
- * isRunning
- *
- * Return true if either a KIO job or the DirLister
- * is running
- */
-bool KURLCompletion::isRunning() const
-{
- return d->list_job || (d->dirListThread && !d->dirListThread->finished());
-}
-
-/*
- * stop
- *
- * Stop and delete a running KIO job or the DirLister
- */
-void KURLCompletion::stop()
-{
- if ( d->list_job ) {
- d->list_job->kill();
- d->list_job = 0L;
- }
-
- if ( !d->list_urls.isEmpty() ) {
- TQValueList<KURL*>::Iterator it = d->list_urls.begin();
- for ( ; it != d->list_urls.end(); it++ )
- delete (*it);
- d->list_urls.clear();
- }
-
- if ( d->dirListThread ) {
- d->dirListThread->requestTermination();
- d->dirListThread = 0;
- }
-}
-
-/*
- * Keep track of the last listed directory
- */
-void KURLCompletion::setListedURL( int complType,
- const TQString& dir,
- const TQString& filter,
- bool no_hidden )
-{
- d->last_compl_type = complType;
- d->last_path_listed = dir;
- d->last_file_listed = filter;
- d->last_no_hidden = (int)no_hidden;
- d->last_prepend = d->prepend;
-}
-
-bool KURLCompletion::isListedURL( int complType,
- const TQString& dir,
- const TQString& filter,
- bool no_hidden )
-{
- return d->last_compl_type == complType
- && ( d->last_path_listed == dir
- || (dir.isEmpty() && d->last_path_listed.isEmpty()) )
- && ( filter.startsWith(d->last_file_listed)
- || (filter.isEmpty() && d->last_file_listed.isEmpty()) )
- && d->last_no_hidden == (int)no_hidden
- && d->last_prepend == d->prepend; // e.g. relative path vs absolute
-}
-
-/*
- * isAutoCompletion
- *
- * Returns true if completion mode is Auto or Popup
- */
-bool KURLCompletion::isAutoCompletion()
-{
- return completionMode() == TDEGlobalSettings::CompletionAuto
- || completionMode() == TDEGlobalSettings::CompletionPopup
- || completionMode() == TDEGlobalSettings::CompletionMan
- || completionMode() == TDEGlobalSettings::CompletionPopupAuto;
-}
-//////////////////////////////////////////////////
-//////////////////////////////////////////////////
-// User directories
-//
-
-bool KURLCompletion::userCompletion(const MyURL &url, TQString *match)
-{
- if ( url.protocol() != "file"
- || !url.dir().isEmpty()
- || url.file().at(0) != '~' )
- return false;
-
- if ( !isListedURL( CTUser ) ) {
- stop();
- clear();
-
- if ( !d->userListThread ) {
- d->userListThread = new UserListThread( this );
- d->userListThread->start();
-
- // If the thread finishes quickly make sure that the results
- // are added to the first matching case.
-
- d->userListThread->wait( 200 );
- TQStringList l = d->userListThread->matches();
- addMatches( l );
- }
- }
- *match = finished();
- return true;
-}
-
-/////////////////////////////////////////////////////
-/////////////////////////////////////////////////////
-// Environment variables
-//
-
-extern char **environ; // Array of environment variables
-
-bool KURLCompletion::envCompletion(const MyURL &url, TQString *match)
-{
- if ( url.file().at(0) != '$' )
- return false;
-
- if ( !isListedURL( CTEnv ) ) {
- stop();
- clear();
-
- char **env = environ;
-
- TQString dollar = TQString("$");
-
- TQStringList l;
-
- while ( *env ) {
- TQString s = TQString::fromLocal8Bit( *env );
-
- int pos = s.find('=');
-
- if ( pos == -1 )
- pos = s.length();
-
- if ( pos > 0 )
- l.append( dollar + s.left(pos) );
-
- env++;
- }
-
- addMatches( l );
- }
-
- setListedURL( CTEnv );
-
- *match = finished();
- return true;
-}
-
-//////////////////////////////////////////////////
-//////////////////////////////////////////////////
-// Executables
-//
-
-bool KURLCompletion::exeCompletion(const MyURL &url, TQString *match)
-{
- if ( url.protocol() != "file" )
- return false;
-
- TQString dir = url.dir();
-
- dir = unescape( dir ); // remove escapes
-
- // Find directories to search for completions, either
- //
- // 1. complete path given in url
- // 2. current directory (d->cwd)
- // 3. $PATH
- // 4. no directory at all
-
- TQStringList dirList;
-
- if ( !TQDir::isRelativePath(dir) ) {
- // complete path in url
- dirList.append( dir );
- }
- else if ( !dir.isEmpty() && !d->cwd.isEmpty() ) {
- // current directory
- dirList.append( d->cwd + '/' + dir );
- }
- else if ( !url.file().isEmpty() ) {
- // $PATH
- dirList = TQStringList::split(KPATH_SEPARATOR,
- TQString::fromLocal8Bit(::getenv("PATH")));
-
- TQStringList::Iterator it = dirList.begin();
-
- for ( ; it != dirList.end(); it++ )
- (*it).append('/');
- }
-
- // No hidden files unless the user types "."
- bool no_hidden_files = url.file().at(0) != '.';
-
- // List files if needed
- //
- if ( !isListedURL( CTExe, dir, url.file(), no_hidden_files ) )
- {
- stop();
- clear();
-
- setListedURL( CTExe, dir, url.file(), no_hidden_files );
-
- *match = listDirectories( dirList, url.file(), true, false, no_hidden_files );
- }
- else if ( !isRunning() ) {
- *match = finished();
- }
- else {
- if ( d->dirListThread )
- setListedURL( CTExe, dir, url.file(), no_hidden_files );
- *match = TQString::null;
- }
-
- return true;
-}
-
-//////////////////////////////////////////////////
-//////////////////////////////////////////////////
-// System Executables
-//
-
-bool KURLCompletion::systemexeCompletion(const MyURL &url, TQString *match)
-{
- if ( url.protocol() != "file" )
- return false;
-
- TQString dir = url.dir();
-
- dir = unescape( dir ); // remove escapes
-
- // Find directories to search for completions, either
- //
- // 1. complete path given in url
- // 2. current directory (d->cwd)
- // 3. $PATH
- // 4. no directory at all
-
- TQStringList dirList;
-
- if ( !url.file().isEmpty() ) {
- // $PATH
- dirList = TQStringList::split(KPATH_SEPARATOR,
- TQString::fromLocal8Bit(::getenv("PATH")));
-
- TQStringList::Iterator it = dirList.begin();
-
- for ( ; it != dirList.end(); it++ )
- (*it).append('/');
- }
-
- // No hidden files unless the user types "."
- bool no_hidden_files = url.file().at(0) != '.';
-
- // List files if needed
- //
- if ( !isListedURL( CTExe, dir, url.file(), no_hidden_files ) )
- {
- stop();
- clear();
-
- setListedURL( CTExe, dir, url.file(), no_hidden_files );
-
- *match = listDirectories( dirList, url.file(), true, false, no_hidden_files );
- }
- else if ( !isRunning() ) {
- *match = finished();
- }
- else {
- if ( d->dirListThread )
- setListedURL( CTExe, dir, url.file(), no_hidden_files );
- *match = TQString::null;
- }
-
- return true;
-}
-
-//////////////////////////////////////////////////
-//////////////////////////////////////////////////
-// Local files
-//
-
-bool KURLCompletion::fileCompletion(const MyURL &url, TQString *match)
-{
- if ( url.protocol() != "file" )
- return false;
-
- TQString dir = url.dir();
-
- if (url.url()[0] == '.')
- {
- if (url.url().length() == 1)
- {
- *match =
- ( completionMode() == TDEGlobalSettings::CompletionMan )? "." : "..";
- return true;
- }
- if (url.url().length() == 2 && url.url()[1]=='.')
- {
- *match="..";
- return true;
- }
- }
-
- //kdDebug() << "fileCompletion " << url.url() << " dir=" << dir << endl;
-
- dir = unescape( dir ); // remove escapes
-
- // Find directories to search for completions, either
- //
- // 1. complete path given in url
- // 2. current directory (d->cwd)
- // 3. no directory at all
-
- TQStringList dirList;
-
- if ( !TQDir::isRelativePath(dir) ) {
- // complete path in url
- dirList.append( dir );
- }
- else if ( !d->cwd.isEmpty() ) {
- // current directory
- dirList.append( d->cwd + '/' + dir );
- }
-
- // No hidden files unless the user types "."
- bool no_hidden_files = ( url.file().at(0) != '.' );
-
- // List files if needed
- //
- if ( !isListedURL( CTFile, dir, "", no_hidden_files ) )
- {
- stop();
- clear();
-
- setListedURL( CTFile, dir, "", no_hidden_files );
-
- // Append '/' to directories in Popup mode?
- bool append_slash = ( d->popup_append_slash
- && (completionMode() == TDEGlobalSettings::CompletionPopup ||
- completionMode() == TDEGlobalSettings::CompletionPopupAuto ) );
-
- bool only_dir = ( d->mode == DirCompletion );
-
- *match = listDirectories( dirList, "", false, only_dir, no_hidden_files,
- append_slash );
- }
- else if ( !isRunning() ) {
- *match = finished();
- }
- else {
- *match = TQString::null;
- }
-
- return true;
-}
-
-//////////////////////////////////////////////////
-//////////////////////////////////////////////////
-// URLs not handled elsewhere...
-//
-
-bool KURLCompletion::urlCompletion(const MyURL &url, TQString *match)
-{
- //kdDebug() << "urlCompletion: url = " << *url.kurl() << endl;
- if (d->onlyLocalProto && KProtocolInfo::protocolClass(url.protocol()) != ":local")
- return false;
-
- // Use d->cwd as base url in case url is not absolute
- KURL url_cwd = KURL::fromPathOrURL( d->cwd );
-
- // Create an URL with the directory to be listed
- KURL url_dir( url_cwd, url.kurl()->url() );
-
- // Don't try url completion if
- // 1. malformed url
- // 2. protocol that doesn't have listDir()
- // 3. there is no directory (e.g. "ftp://ftp.kd" shouldn't do anything)
- // 4. auto or popup completion mode depending on settings
-
- bool man_or_info = ( url_dir.protocol() == TQString("man")
- || url_dir.protocol() == TQString("info") );
-
- if ( !url_dir.isValid()
- || !KProtocolInfo::supportsListing( url_dir )
- || ( !man_or_info
- && ( url_dir.directory(false,false).isEmpty()
- || ( isAutoCompletion()
- && !d->url_auto_completion ) ) ) ) {
- return false;
- }
-
- url_dir.setFileName(""); // not really nesseccary, but clear the filename anyway...
-
- // Remove escapes
- TQString dir = url_dir.directory( false, false );
-
- dir = unescape( dir );
-
- url_dir.setPath( dir );
-
- // List files if needed
- //
- if ( !isListedURL( CTUrl, url_dir.prettyURL(), url.file() ) )
- {
- stop();
- clear();
-
- setListedURL( CTUrl, url_dir.prettyURL(), "" );
-
- TQValueList<KURL*> url_list;
- url_list.append( new KURL( url_dir ) );
-
- listURLs( url_list, "", false );
-
- *match = TQString::null;
- }
- else if ( !isRunning() ) {
- *match = finished();
- }
- else {
- *match = TQString::null;
- }
-
- return true;
-}
-
-//////////////////////////////////////////////////
-//////////////////////////////////////////////////
-// Directory and URL listing
-//
-
-/*
- * addMatches
- *
- * Called to add matches to KCompletion
- */
-void KURLCompletion::addMatches( const TQStringList &matches )
-{
- TQStringList::ConstIterator it = matches.begin();
- TQStringList::ConstIterator end = matches.end();
-
- if ( d->complete_url )
- for ( ; it != end; it++ )
- addItem( d->prepend + KURL::encode_string(*it));
- else
- for ( ; it != end; it++ )
- addItem( d->prepend + (*it));
-}
-
-/*
- * listDirectories
- *
- * List files starting with 'filter' in the given directories,
- * either using DirLister or listURLs()
- *
- * In either case, addMatches() is called with the listed
- * files, and eventually finished() when the listing is done
- *
- * Returns the match if available, or TQString::null if
- * DirLister timed out or using kio
- */
-TQString KURLCompletion::listDirectories(
- const TQStringList &dirList,
- const TQString &filter,
- bool only_exe,
- bool only_dir,
- bool no_hidden,
- bool append_slash_to_dir)
-{
- assert( !isRunning() );
-
- if ( !::getenv("KURLCOMPLETION_LOCAL_KIO") ) {
-
- //kdDebug() << "Listing (listDirectories): " << dirList << " filter=" << filter << " without KIO" << endl;
-
- // Don't use KIO
-
- if ( d->dirListThread )
- d->dirListThread->requestTermination();
-
- TQStringList dirs;
-
- for ( TQStringList::ConstIterator it = dirList.begin();
- it != dirList.end();
- ++it )
- {
- KURL url;
- url.setPath(*it);
- if ( kapp->authorizeURLAction( "list", KURL(), url ) )
- dirs.append( *it );
- }
-
- d->dirListThread = new DirectoryListThread( this, dirs, filter, only_exe, only_dir,
- no_hidden, append_slash_to_dir );
- d->dirListThread->start();
- d->dirListThread->wait( 200 );
- addMatches( d->dirListThread->matches() );
-
- return finished();
- }
- else {
-
- // Use KIO
- //kdDebug() << "Listing (listDirectories): " << dirList << " with KIO" << endl;
-
- TQValueList<KURL*> url_list;
-
- TQStringList::ConstIterator it = dirList.begin();
-
- for ( ; it != dirList.end(); it++ )
- url_list.append( new KURL(*it) );
-
- listURLs( url_list, filter, only_exe, no_hidden );
- // Will call addMatches() and finished()
-
- return TQString::null;
- }
-}
-
-/*
- * listURLs
- *
- * Use KIO to list the given urls
- *
- * addMatches() is called with the listed files
- * finished() is called when the listing is done
- */
-void KURLCompletion::listURLs(
- const TQValueList<KURL *> &urls,
- const TQString &filter,
- bool only_exe,
- bool no_hidden )
-{
- assert( d->list_urls.isEmpty() );
- assert( d->list_job == 0L );
-
- d->list_urls = urls;
- d->list_urls_filter = filter;
- d->list_urls_only_exe = only_exe;
- d->list_urls_no_hidden = no_hidden;
-
-// kdDebug() << "Listing URLs: " << urls[0]->prettyURL() << ",..." << endl;
-
- // Start it off by calling slotIOFinished
- //
- // This will start a new list job as long as there
- // are urls in d->list_urls
- //
- slotIOFinished(0L);
-}
-
-/*
- * slotEntries
- *
- * Receive files listed by KIO and call addMatches()
- */
-void KURLCompletion::slotEntries(TDEIO::Job*, const TDEIO::UDSEntryList& entries)
-{
- TQStringList matches;
-
- TDEIO::UDSEntryListConstIterator it = entries.begin();
- TDEIO::UDSEntryListConstIterator end = entries.end();
-
- TQString filter = d->list_urls_filter;
-
- int filter_len = filter.length();
-
- // Iterate over all files
- //
- for (; it != end; ++it) {
- TQString name;
- TQString url;
- bool is_exe = false;
- bool is_dir = false;
-
- TDEIO::UDSEntry e = *it;
- TDEIO::UDSEntry::ConstIterator it_2 = e.begin();
-
- for( ; it_2 != e.end(); it_2++ ) {
- switch ( (*it_2).m_uds ) {
- case TDEIO::UDS_NAME:
- name = (*it_2).m_str;
- break;
- case TDEIO::UDS_ACCESS:
- is_exe = ((*it_2).m_long & MODE_EXE) != 0;
- break;
- case TDEIO::UDS_FILE_TYPE:
- is_dir = ((*it_2).m_long & S_IFDIR) != 0;
- break;
- case TDEIO::UDS_URL:
- url = (*it_2).m_str;
- break;
- }
- }
-
- if (!url.isEmpty()) {
- // kdDebug() << "KURLCompletion::slotEntries url: " << url << endl;
- name = KURL(url).fileName();
- }
-
- // kdDebug() << "KURLCompletion::slotEntries name: " << name << endl;
-
- if ( name[0] == '.' &&
- ( d->list_urls_no_hidden ||
- name.length() == 1 ||
- ( name.length() == 2 && name[1] == '.' ) ) )
- continue;
-
- if ( d->mode == DirCompletion && !is_dir )
- continue;
-
- if ( filter_len == 0 || name.left(filter_len) == filter ) {
- if ( is_dir )
- name.append( '/' );
-
- if ( is_exe || !d->list_urls_only_exe )
- matches.append( name );
- }
- }
-
- addMatches( matches );
-}
-
-/*
- * slotIOFinished
- *
- * Called when a KIO job is finished.
- *
- * Start a new list job if there are still urls in
- * d->list_urls, otherwise call finished()
- */
-void KURLCompletion::slotIOFinished( TDEIO::Job * job )
-{
-// kdDebug() << "slotIOFinished() " << endl;
-
- assert( job == d->list_job );
-
- if ( d->list_urls.isEmpty() ) {
-
- d->list_job = 0L;
-
- finished(); // will call KCompletion::makeCompletion()
-
- }
- else {
-
- KURL *kurl = d->list_urls.first();
-
- d->list_urls.remove( kurl );
-
-// kdDebug() << "Start KIO: " << kurl->prettyURL() << endl;
-
- d->list_job = TDEIO::listDir( *kurl, false );
- d->list_job->addMetaData("no-auth-prompt", "true");
-
- assert( d->list_job );
-
- connect( d->list_job,
- TQT_SIGNAL(result(TDEIO::Job*)),
- TQT_SLOT(slotIOFinished(TDEIO::Job*)) );
-
- connect( d->list_job,
- TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
- TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList&)) );
-
- delete kurl;
- }
-}
-
-///////////////////////////////////////////////////
-///////////////////////////////////////////////////
-
-/*
- * postProcessMatch, postProcessMatches
- *
- * Called by KCompletion before emitting match() and matches()
- *
- * Append '/' to directories for file completion. This is
- * done here to avoid stat()'ing a lot of files
- */
-void KURLCompletion::postProcessMatch( TQString *match ) const
-{
-// kdDebug() << "KURLCompletion::postProcess: " << *match << endl;
-
- if ( !match->isEmpty() ) {
-
- // Add '/' to directories in file completion mode
- // unless it has already been done
- if ( d->last_compl_type == CTFile )
- adjustMatch( *match );
- }
-}
-
-void KURLCompletion::adjustMatch( TQString& match ) const
-{
- if ( match.at( match.length()-1 ) != '/' )
- {
- TQString copy;
-
- if ( match.startsWith( TQString("file:") ) )
- copy = KURL(match).path();
- else
- copy = match;
-
- expandTilde( copy );
- expandEnv( copy );
- if ( TQDir::isRelativePath(copy) )
- copy.prepend( d->cwd + '/' );
-
-// kdDebug() << "postProcess: stating " << copy << endl;
-
- KDE_struct_stat sbuff;
-
- TQCString file = TQFile::encodeName( copy );
-
- if ( KDE_stat( (const char*)file, &sbuff ) == 0 ) {
- if ( S_ISDIR ( sbuff.st_mode ) )
- match.append( '/' );
- }
- else {
- kdDebug() << "Could not stat file " << copy << endl;
- }
- }
-}
-
-void KURLCompletion::postProcessMatches( TQStringList * matches ) const
-{
- if ( !matches->isEmpty() && d->last_compl_type == CTFile ) {
- TQStringList::Iterator it = matches->begin();
- for (; it != matches->end(); ++it ) {
- adjustMatch( (*it) );
- }
- }
-}
-
-void KURLCompletion::postProcessMatches( KCompletionMatches * matches ) const
-{
- if ( !matches->isEmpty() && d->last_compl_type == CTFile ) {
- KCompletionMatches::Iterator it = matches->begin();
- for (; it != matches->end(); ++it ) {
- adjustMatch( (*it).value() );
- }
- }
-}
-
-void KURLCompletion::customEvent(TQCustomEvent *e)
-{
- if ( e->type() == CompletionMatchEvent::uniqueType() ) {
-
- CompletionMatchEvent *event = static_cast<CompletionMatchEvent *>( e );
-
- event->completionThread()->wait();
-
- if ( !isListedURL( CTUser ) ) {
- stop();
- clear();
- addMatches( event->completionThread()->matches() );
- }
-
- setListedURL( CTUser );
-
- if ( d->userListThread == event->completionThread() )
- d->userListThread = 0;
-
- if ( d->dirListThread == event->completionThread() )
- d->dirListThread = 0;
-
- delete event->completionThread();
- }
-}
-
-// static
-TQString KURLCompletion::replacedPath( const TQString& text, bool replaceHome, bool replaceEnv )
-{
- if ( text.isEmpty() )
- return text;
-
- MyURL url( text, TQString::null ); // no need to replace something of our current cwd
- if ( !url.kurl()->isLocalFile() )
- return text;
-
- url.filter( replaceHome, replaceEnv );
- return url.dir() + url.file();
-}
-
-
-TQString KURLCompletion::replacedPath( const TQString& text )
-{
- return replacedPath( text, d->replace_home, d->replace_env );
-}
-
-/////////////////////////////////////////////////////////
-/////////////////////////////////////////////////////////
-// Static functions
-
-/*
- * expandEnv
- *
- * Expand environment variables in text. Escaped '$' are ignored.
- * Return true if expansion was made.
- */
-static bool expandEnv( TQString &text )
-{
- // Find all environment variables beginning with '$'
- //
- int pos = 0;
-
- bool expanded = false;
-
- while ( (pos = text.find('$', pos)) != -1 ) {
-
- // Skip escaped '$'
- //
- if ( text[pos-1] == '\\' ) {
- pos++;
- }
- // Variable found => expand
- //
- else {
- // Find the end of the variable = next '/' or ' '
- //
- int pos2 = text.find( ' ', pos+1 );
- int pos_tmp = text.find( '/', pos+1 );
-
- if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) )
- pos2 = pos_tmp;
-
- if ( pos2 == -1 )
- pos2 = text.length();
-
- // Replace if the variable is terminated by '/' or ' '
- // and defined
- //
- if ( pos2 >= 0 ) {
- int len = pos2 - pos;
- TQString key = text.mid( pos+1, len-1);
- TQString value =
- TQString::fromLocal8Bit( ::getenv(key.local8Bit()) );
-
- if ( !value.isEmpty() ) {
- expanded = true;
- text.replace( pos, len, value );
- pos = pos + value.length();
- }
- else {
- pos = pos2;
- }
- }
- }
- }
-
- return expanded;
-}
-
-/*
- * expandTilde
- *
- * Replace "~user" with the users home directory
- * Return true if expansion was made.
- */
-static bool expandTilde(TQString &text)
-{
- if ( text[0] != '~' )
- return false;
-
- bool expanded = false;
-
- // Find the end of the user name = next '/' or ' '
- //
- int pos2 = text.find( ' ', 1 );
- int pos_tmp = text.find( '/', 1 );
-
- if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) )
- pos2 = pos_tmp;
-
- if ( pos2 == -1 )
- pos2 = text.length();
-
- // Replace ~user if the user name is terminated by '/' or ' '
- //
- if ( pos2 >= 0 ) {
-
- TQString user = text.mid( 1, pos2-1 );
- TQString dir;
-
- // A single ~ is replaced with $HOME
- //
- if ( user.isEmpty() ) {
- dir = TQDir::homeDirPath();
- }
- // ~user is replaced with the dir from passwd
- //
- else {
- struct passwd *pw = ::getpwnam( user.local8Bit() );
-
- if ( pw )
- dir = TQFile::decodeName( pw->pw_dir );
-
- ::endpwent();
- }
-
- if ( !dir.isEmpty() ) {
- expanded = true;
- text.replace(0, pos2, dir);
- }
- }
-
- return expanded;
-}
-
-/*
- * unescape
- *
- * Remove escapes and return the result in a new string
- *
- */
-static TQString unescape(const TQString &text)
-{
- TQString result;
-
- for (uint pos = 0; pos < text.length(); pos++)
- if ( text[pos] != '\\' )
- result.insert( result.length(), text[pos] );
-
- return result;
-}
-
-void KURLCompletion::virtual_hook( int id, void* data )
-{ KCompletion::virtual_hook( id, data ); }
-
-#include "kurlcompletion.moc"
-
diff --git a/kio/kio/kurlcompletion.h b/kio/kio/kurlcompletion.h
deleted file mode 100644
index f785696b4..000000000
--- a/kio/kio/kurlcompletion.h
+++ /dev/null
@@ -1,236 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Smith <dsmith@algonet.se>
-
- This class was inspired by a previous KURLCompletion by
- Henner Zeller <zeller@think.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef KURLCOMPLETION_H
-#define KURLCOMPLETION_H
-
-#include <kcompletion.h>
-#include <kio/jobclasses.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-
-class KURL;
-class KURLCompletionPrivate;
-
-/**
- * This class does completion of URLs including user directories (~user)
- * and environment variables. Remote URLs are passed to KIO.
- *
- * @short Completion of a single URL
- * @author David Smith <dsmith@algonet.se>
- */
-class TDEIO_EXPORT KURLCompletion : public KCompletion
-{
- Q_OBJECT
-
-public:
- /**
- * Determines how completion is done.
- * @li ExeCompletion - executables in $PATH or with full path.
- * @li FileCompletion - all files with full path or in dir(), URLs
- * are listed using KIO.
- * @li DirCompletion - Same as FileCompletion but only returns directories.
- */
- enum Mode { ExeCompletion=1, FileCompletion, DirCompletion, SystemExeCompletion };
-
- /**
- * Constructs a KURLCompletion object in FileCompletion mode.
- */
- KURLCompletion();
- /**
- * This overloaded constructor allows you to set the Mode to ExeCompletion
- * or FileCompletion without using setMode. Default is FileCompletion.
- */
- KURLCompletion(Mode);
- /**
- * Destructs the KURLCompletion object.
- */
- virtual ~KURLCompletion();
-
- /**
- * Finds completions to the given text.
- *
- * Remote URLs are listed with KIO. For performance reasons, local files
- * are listed with KIO only if KURLCOMPLETION_LOCAL_KIO is set.
- * The completion is done asyncronously if KIO is used.
- *
- * Returns the first match for user, environment, and local dir completion
- * and TQString::null for asynchronous completion (KIO or threaded).
- *
- * @param text the text to complete
- * @return the first match, or TQString::null if not found
- */
- virtual TQString makeCompletion(const TQString &text); // KDE4: remove return value, it's often null due to threading
-
- /**
- * Sets the current directory (used as base for completion).
- * Default = $HOME.
- * @param dir the current directory, either as a path or URL
- */
- virtual void setDir(const TQString &dir);
-
- /**
- * Returns the current directory, as it was given in setDir
- * @return the current directory (path or URL)
- */
- virtual TQString dir() const;
-
- /**
- * Check whether asynchronous completion is in progress.
- * @return true if asynchronous completion is in progress
- */
- virtual bool isRunning() const;
-
- /**
- * Stops asynchronous completion.
- */
- virtual void stop();
-
- /**
- * Returns the completion mode: exe or file completion (default FileCompletion).
- * @return the completion mode
- */
- virtual Mode mode() const;
-
- /**
- * Changes the completion mode: exe or file completion
- * @param mode the new completion mode
- */
- virtual void setMode( Mode mode );
-
- /**
- * Checks whether environment variables are completed and
- * whether they are replaced internally while finding completions.
- * Default is enabled.
- * @return true if environment vvariables will be replaced
- */
- virtual bool replaceEnv() const;
-
- /**
- * Enables/disables completion and replacement (internally) of
- * environment variables in URLs. Default is enabled.
- * @param replace true to replace environment variables
- */
- virtual void setReplaceEnv( bool replace );
-
- /**
- * Returns whether ~username is completed and whether ~username
- * is replaced internally with the user's home directory while
- * finding completions. Default is enabled.
- * @return true to replace tilde with the home directory
- */
- virtual bool replaceHome() const;
-
- /**
- * Enables/disables completion of ~username and replacement
- * (internally) of ~username with the user's home directory.
- * Default is enabled.
- * @param replace true to replace tilde with the home directory
- */
- virtual void setReplaceHome( bool replace );
-
- /**
- * Replaces username and/or environment variables, depending on the
- * current settings and returns the filtered url. Only works with
- * local files, i.e. returns back the original string for non-local
- * urls.
- * @param text the text to process
- * @return the path or URL resulting from this operation. If you
- * want to convert it to a KURL, use KURL::fromPathOrURL.
- */
- TQString replacedPath( const TQString& text );
-
- /**
- * @internal I'll let ossi add a real one to KShell :)
- * @since 3.2
- */
- static TQString replacedPath( const TQString& text,
- bool replaceHome, bool replaceEnv = true );
-
- class MyURL;
-protected:
- // Called by KCompletion, adds '/' to directories
- void postProcessMatch( TQString *match ) const;
- void postProcessMatches( TQStringList *matches ) const;
- void postProcessMatches( KCompletionMatches* matches ) const;
-
- virtual void customEvent( TQCustomEvent *e );
-
-protected slots:
- void slotEntries( TDEIO::Job *, const TDEIO::UDSEntryList& );
- void slotIOFinished( TDEIO::Job * );
-
-private:
-
- bool isAutoCompletion();
-
- bool userCompletion(const MyURL &url, TQString *match);
- bool envCompletion(const MyURL &url, TQString *match);
- bool exeCompletion(const MyURL &url, TQString *match);
- bool systemexeCompletion(const MyURL &url, TQString *match);
- bool fileCompletion(const MyURL &url, TQString *match);
- bool urlCompletion(const MyURL &url, TQString *match);
-
- // List a directory using readdir()
- void listDir( const TQString& dir,
- TQStringList *matches,
- const TQString& filter,
- bool only_exe,
- bool no_hidden );
-
- // List the next dir in m_dirs
- TQString listDirectories(const TQStringList &,
- const TQString &,
- bool only_exe = false,
- bool only_dir = false,
- bool no_hidden = false,
- bool stat_files = true);
-
- void listURLs( const TQValueList<KURL *> &urls,
- const TQString &filter = TQString::null,
- bool only_exe = false,
- bool no_hidden = false );
-
- void addMatches( const TQStringList & );
- TQString finished();
-
- void init();
-
- void setListedURL(int compl_type /* enum ComplType */,
- const TQString& dir = TQString::null,
- const TQString& filter = TQString::null,
- bool no_hidden = false );
-
- bool isListedURL( int compl_type /* enum ComplType */,
- const TQString& dir = TQString::null,
- const TQString& filter = TQString::null,
- bool no_hidden = false );
-
- void adjustMatch( TQString& match ) const;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- KURLCompletionPrivate *d;
-};
-
-#endif // KURLCOMPLETION_H
diff --git a/kio/kio/kuserprofile.cpp b/kio/kio/kuserprofile.cpp
deleted file mode 100644
index b413b3cd5..000000000
--- a/kio/kio/kuserprofile.cpp
+++ /dev/null
@@ -1,355 +0,0 @@
-/* This file is part of the KDE libraries
- * Copyright (C) 1999 Torben Weis <weis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#include "kuserprofile.h"
-#include "kservice.h"
-#include "kservicetype.h"
-#include "kservicetypefactory.h"
-
-#include <kconfig.h>
-#include <kapplication.h>
-#include <kglobal.h>
-#include <kdebug.h>
-#include <kstaticdeleter.h>
-
-#include <tqtl.h>
-
-template class TQPtrList<KServiceTypeProfile>;
-typedef TQPtrList<KServiceTypeProfile> KServiceTypeProfileList;
-
-/*********************************************
- *
- * KServiceTypeProfile
- *
- *********************************************/
-
-KServiceTypeProfileList* KServiceTypeProfile::s_lstProfiles = 0L;
-static KStaticDeleter< KServiceTypeProfileList > profileDeleter;
-bool KServiceTypeProfile::s_configurationMode = false;
-
-void KServiceTypeProfile::initStatic()
-{
- if ( s_lstProfiles )
- return;
-
- // Make sure that a KServiceTypeFactory gets created.
- (void) KServiceTypeFactory::self();
-
- profileDeleter.setObject(s_lstProfiles, new KServiceTypeProfileList);
- s_lstProfiles->setAutoDelete( true );
-
- TDEConfig config( "profilerc", true, false);
-
- static const TQString & defaultGroup = TDEGlobal::staticQString("<default>");
-
- TQStringList tmpList = config.groupList();
- for (TQStringList::Iterator aIt = tmpList.begin();
- aIt != tmpList.end(); ++aIt) {
- if ( *aIt == defaultGroup )
- continue;
-
- config.setGroup( *aIt );
-
- TQString appId = config.readEntry( "Application" );
-
- KService::Ptr pService = KService::serviceByStorageId(appId);
-
- if ( pService ) {
- TQString application = pService->storageId();
- TQString type = config.readEntry( "ServiceType" );
- TQString type2 = config.readEntry( "GenericServiceType" );
- if (type2.isEmpty()) // compat code
- type2 = (pService->type() == "Application") ? "Application" : "KParts/ReadOnlyPart";
- int pref = config.readNumEntry( "Preference" );
-
- if ( !type.isEmpty() /* && pref >= 0*/ ) // Don't test for pref here. We want those in the list, to mark them as forbidden
- {
- KServiceTypeProfile* p =
- KServiceTypeProfile::serviceTypeProfile( type, type2 );
-
- if ( !p ) {
- p = new KServiceTypeProfile( type, type2 );
- s_lstProfiles->append( p );
- }
-
- bool allow = config.readBoolEntry( "AllowAsDefault" );
- //kdDebug(7014) << "KServiceTypeProfile::initStatic adding service " << application << " to profile for " << type << "," << type2 << " with preference " << pref << endl;
- p->addService( application, pref, allow );
- }
- }
- }
-}
-
-//static
-void KServiceTypeProfile::clear()
-{
- // HACK tdesycoca may open the dummy db, in such case the first call to tdesycoca
- // in initStatic() leads to closing the dummy db and clear() being called
- // in the middle of it, making s_lstProfiles be NULL
- if( s_lstProfiles == NULL || s_lstProfiles->count() == 0 )
- return;
- profileDeleter.destructObject();
-}
-
-//static
-KServiceTypeProfile::OfferList KServiceTypeProfile::offers( const TQString& _servicetype, const TQString& _genericServiceType )
-{
- OfferList offers;
- TQStringList serviceList;
- //kdDebug(7014) << "KServiceTypeProfile::offers( " << _servicetype << "," << _genericServiceType << " )" << endl;
-
- // Note that KServiceTypeProfile::offers() calls KServiceType::offers(),
- // so we _do_ get the new services, that are available but not in the profile.
- if ( _genericServiceType.isEmpty() )
- {
- initStatic();
- // We want all profiles for servicetype, if we have profiles.
- // ## Slow loop, if profilerc is big. We should use a map instead?
- TQPtrListIterator<KServiceTypeProfile> it( *s_lstProfiles );
- for( ; it.current(); ++it )
- if ( it.current()->m_strServiceType == _servicetype )
- {
- offers += it.current()->offers();
- }
- //kdDebug(7014) << "Found profile: " << offers.count() << " offers" << endl;
- }
- else
- {
- KServiceTypeProfile* profile = serviceTypeProfile( _servicetype, _genericServiceType );
- if ( profile )
- {
- //kdDebug(7014) << "Found profile: " << profile->offers().count() << " offers" << endl;
- offers += profile->offers();
- }
- else
- {
- // Try the other way round, order is not like size, it doesn't matter.
- profile = serviceTypeProfile( _genericServiceType, _servicetype );
- if ( profile )
- {
- //kdDebug(7014) << "Found profile after switching: " << profile->offers().count() << " offers" << endl;
- offers += profile->offers();
- }
- }
- }
-
- // Collect services, to make the next loop faster
- OfferList::Iterator itOffers = offers.begin();
- for( ; itOffers != offers.end(); ++itOffers )
- serviceList += (*itOffers).service()->desktopEntryPath(); // this should identify each service uniquely
- //kdDebug(7014) << "serviceList: " << serviceList.join(",") << endl;
-
- // Now complete with any other offers that aren't in the profile
- // This can be because the services have been installed after the profile was written,
- // but it's also the case for any service that's neither App nor ReadOnlyPart, e.g. RenameDlg/Plugin
- KService::List list = KServiceType::offers( _servicetype );
- //kdDebug(7014) << "Using KServiceType::offers, result: " << list.count() << " offers" << endl;
- TQValueListIterator<KService::Ptr> it = list.begin();
- for( ; it != list.end(); ++it )
- {
- if (_genericServiceType.isEmpty() /*no constraint*/ || (*it)->hasServiceType( _genericServiceType ))
- {
- // Check that we don't already have it ;)
- if ( serviceList.find( (*it)->desktopEntryPath() ) == serviceList.end() )
- {
- bool allow = (*it)->allowAsDefault();
- KServiceOffer o( (*it), (*it)->initialPreferenceForMimeType(_servicetype), allow );
- offers.append( o );
- //kdDebug(7014) << "Appending offer " << (*it)->name() << " initial preference=" << (*it)->initialPreference() << " allow-as-default=" << allow << endl;
- }
- //else
- // kdDebug(7014) << "Already having offer " << (*it)->name() << endl;
- }
- }
-
- qBubbleSort( offers );
-
-#if 0
- // debug code, comment if you wish but don't remove.
- kdDebug(7014) << "Sorted list:" << endl;
- OfferList::Iterator itOff = offers.begin();
- for( ; itOff != offers.end(); ++itOff )
- kdDebug(7014) << (*itOff).service()->name() << " allow-as-default=" << (*itOff).allowAsDefault() << endl;
-#endif
-
- //kdDebug(7014) << "Returning " << offers.count() << " offers" << endl;
- return offers;
-}
-
-KServiceTypeProfile::KServiceTypeProfile( const TQString& _servicetype, const TQString& _genericServiceType )
-{
- initStatic();
-
- m_strServiceType = _servicetype;
- m_strGenericServiceType = _genericServiceType;
-}
-
-KServiceTypeProfile::~KServiceTypeProfile()
-{
-}
-
-void KServiceTypeProfile::addService( const TQString& _service,
- int _preference, bool _allow_as_default )
-{
- m_mapServices[ _service ].m_iPreference = _preference;
- m_mapServices[ _service ].m_bAllowAsDefault = _allow_as_default;
-}
-
-int KServiceTypeProfile::preference( const TQString& _service ) const
-{
- KService::Ptr service = KService::serviceByName( _service );
- if (!service)
- return 0;
- TQMap<TQString,Service>::ConstIterator it = m_mapServices.find( service->storageId() );
- if ( it == m_mapServices.end() )
- return 0;
-
- return it.data().m_iPreference;
-}
-
-bool KServiceTypeProfile::allowAsDefault( const TQString& _service ) const
-{
- KService::Ptr service = KService::serviceByName( _service );
- if (!service)
- return false;
-
- // Does the service itself not allow that ?
- if ( !service->allowAsDefault() )
- return false;
-
- // Look what the user says ...
- TQMap<TQString,Service>::ConstIterator it = m_mapServices.find( service->storageId() );
- if ( it == m_mapServices.end() )
- return 0;
-
- return it.data().m_bAllowAsDefault;
-}
-
-KServiceTypeProfile* KServiceTypeProfile::serviceTypeProfile( const TQString& _servicetype, const TQString& _genericServiceType )
-{
- initStatic();
- static const TQString& app_str = TDEGlobal::staticQString("Application");
-
- const TQString &_genservicetype = ((!_genericServiceType.isEmpty()) ? _genericServiceType : app_str);
-
- TQPtrListIterator<KServiceTypeProfile> it( *s_lstProfiles );
- for( ; it.current(); ++it )
- if (( it.current()->m_strServiceType == _servicetype ) &&
- ( it.current()->m_strGenericServiceType == _genservicetype))
- return it.current();
-
- return 0;
-}
-
-
-KServiceTypeProfile::OfferList KServiceTypeProfile::offers() const
-{
- OfferList offers;
-
- kdDebug(7014) << "KServiceTypeProfile::offers serviceType=" << m_strServiceType << " genericServiceType=" << m_strGenericServiceType << endl;
- KService::List list = KServiceType::offers( m_strServiceType );
- TQValueListIterator<KService::Ptr> it = list.begin();
- for( ; it != list.end(); ++it )
- {
- //kdDebug(7014) << "KServiceTypeProfile::offers considering " << (*it)->name() << endl;
- if ( m_strGenericServiceType.isEmpty() || (*it)->hasServiceType( m_strGenericServiceType ) )
- {
- // Now look into the profile, to find this service's preference.
- TQMap<TQString,Service>::ConstIterator it2 = m_mapServices.find( (*it)->storageId() );
-
- if( it2 != m_mapServices.end() )
- {
- //kdDebug(7014) << "found in mapServices pref=" << it2.data().m_iPreference << endl;
- if ( it2.data().m_iPreference > 0 ) {
- bool allow = (*it)->allowAsDefault();
- if ( allow )
- allow = it2.data().m_bAllowAsDefault;
- KServiceOffer o( (*it), it2.data().m_iPreference, allow );
- offers.append( o );
- }
- }
- else
- {
- //kdDebug(7014) << "not found in mapServices. Appending." << endl;
- // We use 0 as the preference to ensure new apps don't take over existing apps (which default to 1)
- KServiceOffer o( (*it), 0, (*it)->allowAsDefault() );
- offers.append( o );
- }
- }/* else
- kdDebug(7014) << "Doesn't have " << m_strGenericServiceType << endl;*/
- }
-
- qBubbleSort( offers );
-
- //kdDebug(7014) << "KServiceTypeProfile::offers returning " << offers.count() << " offers" << endl;
- return offers;
-}
-
-KService::Ptr KServiceTypeProfile::preferredService( const TQString & _serviceType, const TQString & _genericServiceType )
-{
- OfferList lst = offers( _serviceType, _genericServiceType );
-
- OfferList::Iterator itOff = lst.begin();
- // Look for the first one that is allowed as default.
- // Since the allowed-as-default are first anyway, we only have
- // to look at the first one to know.
- if( itOff != lst.end() && (*itOff).allowAsDefault() )
- return (*itOff).service();
-
- //kdDebug(7014) << "No offers, or none allowed as default" << endl;
- return 0L;
-}
-
-/*********************************************
- *
- * KServiceOffer
- *
- *********************************************/
-
-KServiceOffer::KServiceOffer()
-{
- m_iPreference = -1;
-}
-
-KServiceOffer::KServiceOffer( const KServiceOffer& _o )
-{
- m_pService = _o.m_pService;
- m_iPreference = _o.m_iPreference;
- m_bAllowAsDefault = _o.m_bAllowAsDefault;
-}
-
-KServiceOffer::KServiceOffer( KService::Ptr _service, int _pref, bool _default )
-{
- m_pService = _service;
- m_iPreference = _pref;
- m_bAllowAsDefault = _default;
-}
-
-
-bool KServiceOffer::operator< ( const KServiceOffer& _o ) const
-{
- // Put offers allowed as default FIRST.
- if ( _o.m_bAllowAsDefault && !m_bAllowAsDefault )
- return false; // _o is default and not 'this'.
- if ( !_o.m_bAllowAsDefault && m_bAllowAsDefault )
- return true; // 'this' is default but not _o.
- // Both offers are allowed or not allowed as default
- // -> use preferences to sort them
- // The bigger the better, but we want the better FIRST
- return _o.m_iPreference < m_iPreference;
-}
diff --git a/kio/kio/kzip.cpp b/kio/kio/kzip.cpp
deleted file mode 100644
index 6241cc1ca..000000000
--- a/kio/kio/kzip.cpp
+++ /dev/null
@@ -1,1460 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
- Copyright (C) 2002 Holger Schroeder <holger-kde@holgis.net>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-/*
- This class implements a kioslave to access ZIP files from KDE.
- you can use it in IO_ReadOnly or in IO_WriteOnly mode, and it
- behaves just as expected (i hope ;-) ).
- It can also be used in IO_ReadWrite mode, in this case one can
- append files to an existing zip archive. when you append new files, which
- are not yet in the zip, it works as expected, they are appended at the end.
- when you append a file, which is already in the file, the reference to the
- old file is dropped and the new one is added to the zip. but the
- old data from the file itself is not deleted, it is still in the
- zipfile. so when you want to have a small and garbagefree zipfile,
- just read the contents of the appended zipfile and write it to a new one
- in IO_WriteOnly mode. especially take care of this, when you don't want
- to leak information of how intermediate versions of files in the zip
- were looking.
- For more information on the zip fileformat go to
- http://www.pkware.com/support/appnote.html .
-
-*/
-
-#include "kzip.h"
-#include "kfilterdev.h"
-#include "klimitediodevice.h"
-#include <kmimetype.h>
-#include <ksavefile.h>
-#include <kdebug.h>
-
-#include <tqasciidict.h>
-#include <tqfile.h>
-#include <tqdir.h>
-#include <tqdatetime.h>
-#include <tqptrlist.h>
-
-#include <zlib.h>
-#include <time.h>
-#include <string.h>
-
-const int max_path_len = 4095; // maximum number of character a path may contain
-
-static void transformToMsDos(const TQDateTime& dt, char* buffer)
-{
- if ( dt.isValid() )
- {
- const TQ_UINT16 time =
- ( dt.time().hour() << 11 ) // 5 bit hour
- | ( dt.time().minute() << 5 ) // 6 bit minute
- | ( dt.time().second() >> 1 ); // 5 bit double seconds
-
- buffer[0] = char(time);
- buffer[1] = char(time >> 8);
-
- const TQ_UINT16 date =
- ( ( dt.date().year() - 1980 ) << 9 ) // 7 bit year 1980-based
- | ( dt.date().month() << 5 ) // 4 bit month
- | ( dt.date().day() ); // 5 bit day
-
- buffer[2] = char(date);
- buffer[3] = char(date >> 8);
- }
- else // !dt.isValid(), assume 1980-01-01 midnight
- {
- buffer[0] = 0;
- buffer[1] = 0;
- buffer[2] = 33;
- buffer[3] = 0;
- }
-}
-
-static time_t transformFromMsDos(const char* buffer)
-{
- TQ_UINT16 time = (uchar)buffer[0] | ( (uchar)buffer[1] << 8 );
- int h = time >> 11;
- int m = ( time & 0x7ff ) >> 5;
- int s = ( time & 0x1f ) * 2 ;
- TQTime qt(h, m, s);
-
- TQ_UINT16 date = (uchar)buffer[2] | ( (uchar)buffer[3] << 8 );
- int y = ( date >> 9 ) + 1980;
- int o = ( date & 0x1ff ) >> 5;
- int d = ( date & 0x1f );
- TQDate qd(y, o, d);
-
- TQDateTime dt( qd, qt );
- return dt.toTime_t();
-}
-
-// == parsing routines for zip headers
-
-/** all relevant information about parsing file information */
-struct ParseFileInfo {
- // file related info
-// TQCString name; // filename
- mode_t perm; // permissions of this file
- time_t atime; // last access time (UNIX format)
- time_t mtime; // modification time (UNIX format)
- time_t ctime; // creation time (UNIX format)
- int uid; // user id (-1 if not specified)
- int gid; // group id (-1 if not specified)
- TQCString guessed_symlink; // guessed symlink target
- int extralen; // length of extra field
-
- // parsing related info
- bool exttimestamp_seen; // true if extended timestamp extra field
- // has been parsed
- bool newinfounix_seen; // true if Info-ZIP Unix New extra field has
- // been parsed
-
- ParseFileInfo() : perm(0100644), uid(-1), gid(-1), extralen(0),
- exttimestamp_seen(false), newinfounix_seen(false) {
- ctime = mtime = atime = time(0);
- }
-};
-
-/** updates the parse information with the given extended timestamp extra field.
- * @param buffer start content of buffer known to contain an extended
- * timestamp extra field (without magic & size)
- * @param size size of field content (must not count magic and size entries)
- * @param islocal true if this is a local field, false if central
- * @param pfi ParseFileInfo object to be updated
- * @return true if processing was successful
- */
-static bool parseExtTimestamp(const char *buffer, int size, bool islocal,
- ParseFileInfo &pfi) {
- if (size < 1) {
- kdDebug(7040) << "premature end of extended timestamp (#1)" << endl;
- return false;
- }/*end if*/
- int flags = *buffer; // read flags
- buffer += 1;
- size -= 1;
-
- if (flags & 1) { // contains modification time
- if (size < 4) {
- kdDebug(7040) << "premature end of extended timestamp (#2)" << endl;
- return false;
- }/*end if*/
- pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
- | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
- buffer += 4;
- size -= 4;
- }/*end if*/
- // central extended field cannot contain more than the modification time
- // even if other flags are set
- if (!islocal) {
- pfi.exttimestamp_seen = true;
- return true;
- }/*end if*/
-
- if (flags & 2) { // contains last access time
- if (size < 4) {
- kdDebug(7040) << "premature end of extended timestamp (#3)" << endl;
- return true;
- }/*end if*/
- pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
- | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
- buffer += 4;
- size -= 4;
- }/*end if*/
-
- if (flags & 4) { // contains creation time
- if (size < 4) {
- kdDebug(7040) << "premature end of extended timestamp (#4)" << endl;
- return true;
- }/*end if*/
- pfi.ctime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
- | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
- buffer += 4;
- }/*end if*/
-
- pfi.exttimestamp_seen = true;
- return true;
-}
-
-/** updates the parse information with the given Info-ZIP Unix old extra field.
- * @param buffer start of content of buffer known to contain an Info-ZIP
- * Unix old extra field (without magic & size)
- * @param size size of field content (must not count magic and size entries)
- * @param islocal true if this is a local field, false if central
- * @param pfi ParseFileInfo object to be updated
- * @return true if processing was successful
- */
-static bool parseInfoZipUnixOld(const char *buffer, int size, bool islocal,
- ParseFileInfo &pfi) {
- // spec mandates to omit this field if one of the newer fields are available
- if (pfi.exttimestamp_seen || pfi.newinfounix_seen) return true;
-
- if (size < 8) {
- kdDebug(7040) << "premature end of Info-ZIP unix extra field old" << endl;
- return false;
- }/*end if*/
-
- pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
- | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
- buffer += 4;
- pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
- | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
- buffer += 4;
- if (islocal && size >= 12) {
- pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
- buffer += 2;
- pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
- buffer += 2;
- }/*end if*/
- return true;
-}
-
-#if 0 // not needed yet
-/** updates the parse information with the given Info-ZIP Unix new extra field.
- * @param buffer start of content of buffer known to contain an Info-ZIP
- * Unix new extra field (without magic & size)
- * @param size size of field content (must not count magic and size entries)
- * @param islocal true if this is a local field, false if central
- * @param pfi ParseFileInfo object to be updated
- * @return true if processing was successful
- */
-static bool parseInfoZipUnixNew(const char *buffer, int size, bool islocal,
- ParseFileInfo &pfi) {
- if (!islocal) { // contains nothing in central field
- pfi.newinfounix = true;
- return true;
- }/*end if*/
-
- if (size < 4) {
- kdDebug(7040) << "premature end of Info-ZIP unix extra field new" << endl;
- return false;
- }/*end if*/
-
- pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
- buffer += 2;
- pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
- buffer += 2;
-
- pfi.newinfounix = true;
- return true;
-}
-#endif
-
-/**
- * parses the extra field
- * @param buffer start of buffer where the extra field is to be found
- * @param size size of the extra field
- * @param islocal true if this is part of a local header, false if of central
- * @param pfi ParseFileInfo object which to write the results into
- * @return true if parsing was successful
- */
-static bool parseExtraField(const char *buffer, int size, bool islocal,
- ParseFileInfo &pfi) {
- // extra field in central directory doesn't contain useful data, so we
- // don't bother parsing it
- if (!islocal) return true;
-
- while (size >= 4) { // as long as a potential extra field can be read
- int magic = (uchar)buffer[0] | (uchar)buffer[1] << 8;
- buffer += 2;
- int fieldsize = (uchar)buffer[0] | (uchar)buffer[1] << 8;
- buffer += 2;
- size -= 4;
-
- if (fieldsize > size) {
- //kdDebug(7040) << "fieldsize: " << fieldsize << " size: " << size << endl;
- kdDebug(7040) << "premature end of extra fields reached" << endl;
- break;
- }/*end if*/
-
- switch (magic) {
- case 0x5455: // extended timestamp
- if (!parseExtTimestamp(buffer, fieldsize, islocal, pfi)) return false;
- break;
- case 0x5855: // old Info-ZIP unix extra field
- if (!parseInfoZipUnixOld(buffer, fieldsize, islocal, pfi)) return false;
- break;
-#if 0 // not needed yet
- case 0x7855: // new Info-ZIP unix extra field
- if (!parseInfoZipUnixNew(buffer, fieldsize, islocal, pfi)) return false;
- break;
-#endif
- default:
- /* ignore everything else */;
- }/*end switch*/
-
- buffer += fieldsize;
- size -= fieldsize;
- }/*wend*/
- return true;
-}
-
-////////////////////////////////////////////////////////////////////////
-/////////////////////////// KZip ///////////////////////////////////////
-////////////////////////////////////////////////////////////////////////
-
-class KZip::KZipPrivate
-{
-public:
- KZipPrivate()
- : m_crc( 0 ),
- m_currentFile( 0L ),
- m_currentDev( 0L ),
- m_compression( 8 ),
- m_extraField( KZip::NoExtraField ),
- m_offset( 0L ),
- m_saveFile( 0 ) {}
-
- unsigned long m_crc; // checksum
- KZipFileEntry* m_currentFile; // file currently being written
- TQIODevice* m_currentDev; // filterdev used to write to the above file
- TQPtrList<KZipFileEntry> m_fileList; // flat list of all files, for the index (saves a recursive method ;)
- int m_compression;
- KZip::ExtraField m_extraField;
- unsigned int m_offset; // holds the offset of the place in the zip,
- // where new data can be appended. after openarchive it points to 0, when in
- // writeonly mode, or it points to the beginning of the central directory.
- // each call to writefile updates this value.
- KSaveFile* m_saveFile;
-};
-
-KZip::KZip( const TQString& filename )
- : KArchive( 0L )
-{
- //kdDebug(7040) << "KZip(filename) reached." << endl;
- Q_ASSERT( !filename.isEmpty() );
- m_filename = filename;
- d = new KZipPrivate;
- // unusual: this ctor leaves the device set to 0.
- // This is for the use of KSaveFile, see openArchive.
- // KDE4: move KSaveFile support to base class, KArchive.
-}
-
-KZip::KZip( TQIODevice * dev )
- : KArchive( dev )
-{
- //kdDebug(7040) << "KZip::KZip( TQIODevice * dev) reached." << endl;
- d = new KZipPrivate;
-}
-
-KZip::~KZip()
-{
- // mjarrett: Closes to prevent ~KArchive from aborting w/o device
- //kdDebug(7040) << "~KZip reached." << endl;
- if( isOpened() )
- close();
- if ( !m_filename.isEmpty() ) { // we created the device ourselves
- if ( d->m_saveFile ) // writing mode
- delete d->m_saveFile;
- else // reading mode
- delete device(); // (the TQFile)
- }
- delete d;
-}
-
-bool KZip::openArchive( int mode )
-{
- //kdDebug(7040) << "openarchive reached." << endl;
- d->m_fileList.clear();
-
- switch ( mode ) {
- case IO_WriteOnly:
- // The use of KSaveFile can't be done in the ctor (no mode known yet)
- // Ideally we would reimplement open() and do it there (BIC)
- if ( !m_filename.isEmpty() ) {
- kdDebug(7040) << "Writing to a file using KSaveFile" << endl;
- d->m_saveFile = new KSaveFile( m_filename );
- if ( d->m_saveFile->status() != 0 ) {
- kdWarning(7040) << "KSaveFile creation for " << m_filename << " failed, " << strerror( d->m_saveFile->status() ) << endl;
- delete d->m_saveFile;
- d->m_saveFile = 0;
- return false;
- }
- Q_ASSERT( d->m_saveFile->file() );
- setDevice( TQT_TQIODEVICE(d->m_saveFile->file()) );
- }
- return true;
- case IO_ReadOnly:
- case IO_ReadWrite:
- {
- // ReadWrite mode still uses TQFile for now; we'd need to copy to the tempfile, in fact.
- if ( !m_filename.isEmpty() ) {
- setDevice( TQT_TQIODEVICE(new TQFile( m_filename )) );
- if ( !device()->open( mode ) )
- return false;
- }
- break; // continued below
- }
- default:
- kdWarning(7040) << "Unsupported mode " << mode << endl;
- return false;
- }
-
- char buffer[47];
-
- // Check that it's a valid ZIP file
- // the above code opened the underlying device already.
- TQIODevice* dev = device();
-
- if (!dev) {
- return false;
- }
-
- uint offset = 0; // holds offset, where we read
- int n;
-
- // contains information gathered from the local file headers
- TQAsciiDict<ParseFileInfo> pfi_map(1009, true /*case sensitive */, true /*copy keys*/);
- pfi_map.setAutoDelete(true);
-
- // We set a bool for knowing if we are allowed to skip the start of the file
- bool startOfFile = true;
-
- for (;;) // repeat until 'end of entries' signature is reached
- {
-kdDebug(7040) << "loop starts" << endl;
-kdDebug(7040) << "dev->at() now : " << dev->at() << endl;
- n = dev->readBlock( buffer, 4 );
-
- if (n < 4)
- {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#1)" << endl;
-
- return false;
- }
-
- if ( !memcmp( buffer, "PK\5\6", 4 ) ) // 'end of entries'
- {
- kdDebug(7040) << "PK56 found end of archive" << endl;
- startOfFile = false;
- break;
- }
-
- if ( !memcmp( buffer, "PK\3\4", 4 ) ) // local file header
- {
- kdDebug(7040) << "PK34 found local file header" << endl;
- startOfFile = false;
- // can this fail ???
- dev->at( dev->at() + 2 ); // skip 'version needed to extract'
-
- // read static header stuff
- n = dev->readBlock( buffer, 24 );
- if (n < 24) {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#4)" << endl;
- return false;
- }
-
- int gpf = (uchar)buffer[0]; // "general purpose flag" not "general protection fault" ;-)
- int compression_mode = (uchar)buffer[2] | (uchar)buffer[3] << 8;
- time_t mtime = transformFromMsDos( buffer+4 );
-
- TQ_LONG compr_size = (uchar)buffer[12] | (uchar)buffer[13] << 8
- | (uchar)buffer[14] << 16 | (uchar)buffer[15] << 24;
- TQ_LONG uncomp_size = (uchar)buffer[16] | (uchar)buffer[17] << 8
- | (uchar)buffer[18] << 16 | (uchar)buffer[19] << 24;
- int namelen = (uchar)buffer[20] | (uchar)buffer[21] << 8;
- int extralen = (uchar)buffer[22] | (uchar)buffer[23] << 8;
-
- kdDebug(7040) << "general purpose bit flag: " << gpf << endl;
- kdDebug(7040) << "compressed size: " << compr_size << endl;
- kdDebug(7040) << "uncompressed size: " << uncomp_size << endl;
- kdDebug(7040) << "namelen: " << namelen << endl;
- kdDebug(7040) << "extralen: " << extralen << endl;
- kdDebug(7040) << "archive size: " << dev->size() << endl;
-
- // read filename
- TQCString filename(namelen + 1);
- n = dev->readBlock(filename.data(), namelen);
- if ( n < namelen ) {
- kdWarning(7040) << "Invalid ZIP file. Name not completely read (#2)" << endl;
- return false;
- }
-
- ParseFileInfo *pfi = new ParseFileInfo();
- pfi->mtime = mtime;
- pfi_map.insert(filename.data(), pfi);
-
- // read and parse the beginning of the extra field,
- // skip rest of extra field in case it is too long
- unsigned int extraFieldEnd = dev->at() + extralen;
- pfi->extralen = extralen;
- int handledextralen = QMIN(extralen, (int)sizeof buffer);
-
- kdDebug(7040) << "handledextralen: " << handledextralen << endl;
-
- n = dev->readBlock(buffer, handledextralen);
- // no error msg necessary as we deliberately truncate the extra field
- if (!parseExtraField(buffer, handledextralen, true, *pfi))
- {
- kdWarning(7040) << "Invalid ZIP File. Broken ExtraField." << endl;
- return false;
- }
-
- // jump to end of extra field
- dev->at( extraFieldEnd );
-
- // we have to take care of the 'general purpose bit flag'.
- // if bit 3 is set, the header doesn't contain the length of
- // the file and we look for the signature 'PK\7\8'.
- if ( gpf & 8 )
- {
- // here we have to read through the compressed data to find
- // the next PKxx
- kdDebug(7040) << "trying to seek for next PK78" << endl;
- bool foundSignature = false;
-
- while (!foundSignature)
- {
- n = dev->readBlock( buffer, 1 );
- if (n < 1)
- {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#2)" << endl;
- return false;
- }
-
- if ( buffer[0] != 'P' )
- continue;
-
- n = dev->readBlock( buffer, 3 );
- if (n < 3)
- {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#3)" << endl;
- return false;
- }
-
- // we have to detect three magic tokens here:
- // PK34 for the next local header in case there is no data descriptor
- // PK12 for the central header in case there is no data descriptor
- // PK78 for the data descriptor in case it is following the compressed data
-
- if ( buffer[0] == 'K' && buffer[1] == 7 && buffer[2] == 8 )
- {
- foundSignature = true;
- dev->at( dev->at() + 12 ); // skip the 'data_descriptor'
- }
- else if ( ( buffer[0] == 'K' && buffer[1] == 1 && buffer[2] == 2 )
- || ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2] == 4 ) )
- {
- foundSignature = true;
- dev->at( dev->at() - 4 ); // go back 4 bytes, so that the magic bytes can be found...
- }
- else if ( buffer[0] == 'P' || buffer[1] == 'P' || buffer[2] == 'P' )
- {
- // We have another P character so we must go back a little to check if it is a magic
- dev->at( dev->at() - 3 );
- }
-
- }
- }
- else
- {
- // here we skip the compressed data and jump to the next header
- kdDebug(7040) << "general purpose bit flag indicates, that local file header contains valid size" << endl;
- // check if this could be a symbolic link
- if (compression_mode == NoCompression
- && uncomp_size <= max_path_len
- && uncomp_size > 0) {
- // read content and store it
- pfi->guessed_symlink.resize(uncomp_size + 1);
- kdDebug(7040) << "guessed symlink size: " << uncomp_size << endl;
- n = dev->readBlock(pfi->guessed_symlink.data(), uncomp_size);
- if (n < uncomp_size) {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#5)" << endl;
- return false;
- }
- } else {
-
- if ( compr_size > (TQ_LONG)dev->size() )
- {
- // here we cannot trust the compressed size, so scan through the compressed
- // data to find the next header
- bool foundSignature = false;
-
- while (!foundSignature)
- {
- n = dev->readBlock( buffer, 1 );
- if (n < 1)
- {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#2)" << endl;
- return false;
- }
-
- if ( buffer[0] != 'P' )
- continue;
-
- n = dev->readBlock( buffer, 3 );
- if (n < 3)
- {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#3)" << endl;
- return false;
- }
-
- // we have to detect three magic tokens here:
- // PK34 for the next local header in case there is no data descriptor
- // PK12 for the central header in case there is no data descriptor
- // PK78 for the data descriptor in case it is following the compressed data
-
- if ( buffer[0] == 'K' && buffer[1] == 7 && buffer[2] == 8 )
- {
- foundSignature = true;
- dev->at( dev->at() + 12 ); // skip the 'data_descriptor'
- }
-
- if ( ( buffer[0] == 'K' && buffer[1] == 1 && buffer[2] == 2 )
- || ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2] == 4 ) )
- {
- foundSignature = true;
- dev->at( dev->at() - 4 );
- // go back 4 bytes, so that the magic bytes can be found
- // in the next cycle...
- }
- }
- }
- else
- {
-// kdDebug(7040) << "before interesting dev->at(): " << dev->at() << endl;
- bool success;
- success = dev->at( dev->at() + compr_size ); // can this fail ???
-/* kdDebug(7040) << "after interesting dev->at(): " << dev->at() << endl;
- if ( success )
- kdDebug(7040) << "dev->at was successful... " << endl;
- else
- kdDebug(7040) << "dev->at failed... " << endl;*/
- }
-
- }
-
-// not needed any more
-/* // here we calculate the length of the file in the zip
- // with headers and jump to the next header.
- uint skip = compr_size + namelen + extralen;
- offset += 30 + skip;*/
- }
- }
- else if ( !memcmp( buffer, "PK\1\2", 4 ) ) // central block
- {
- kdDebug(7040) << "PK12 found central block" << endl;
- startOfFile = false;
-
- // so we reached the central header at the end of the zip file
- // here we get all interesting data out of the central header
- // of a file
- offset = dev->at() - 4;
-
- //set offset for appending new files
- if ( d->m_offset == 0L ) d->m_offset = offset;
-
- n = dev->readBlock( buffer + 4, 42 );
- if (n < 42) {
- kdWarning(7040) << "Invalid ZIP file, central entry too short" << endl; // not long enough for valid entry
- return false;
- }
-
- //int gpf = (uchar)buffer[9] << 8 | (uchar)buffer[10];
- //kdDebug() << "general purpose flag=" << gpf << endl;
- // length of the filename (well, pathname indeed)
- int namelen = (uchar)buffer[29] << 8 | (uchar)buffer[28];
- TQCString bufferName( namelen + 1 );
- n = dev->readBlock( bufferName.data(), namelen );
- if ( n < namelen )
- kdWarning(7040) << "Invalid ZIP file. Name not completely read" << endl;
-
- ParseFileInfo *pfi = pfi_map[bufferName];
- if (!pfi) { // can that happen?
- pfi_map.insert(bufferName.data(), pfi = new ParseFileInfo());
- }
- TQString name( TQFile::decodeName(bufferName) );
-
- //kdDebug(7040) << "name: " << name << endl;
- // only in central header ! see below.
- // length of extra attributes
- int extralen = (uchar)buffer[31] << 8 | (uchar)buffer[30];
- // length of comment for this file
- int commlen = (uchar)buffer[33] << 8 | (uchar)buffer[32];
- // compression method of this file
- int cmethod = (uchar)buffer[11] << 8 | (uchar)buffer[10];
-
- //kdDebug(7040) << "cmethod: " << cmethod << endl;
- //kdDebug(7040) << "extralen: " << extralen << endl;
-
- // uncompressed file size
- uint ucsize = (uchar)buffer[27] << 24 | (uchar)buffer[26] << 16 |
- (uchar)buffer[25] << 8 | (uchar)buffer[24];
- // compressed file size
- uint csize = (uchar)buffer[23] << 24 | (uchar)buffer[22] << 16 |
- (uchar)buffer[21] << 8 | (uchar)buffer[20];
-
- // offset of local header
- uint localheaderoffset = (uchar)buffer[45] << 24 | (uchar)buffer[44] << 16 |
- (uchar)buffer[43] << 8 | (uchar)buffer[42];
-
- // some clever people use different extra field lengths
- // in the central header and in the local header... funny.
- // so we need to get the localextralen to calculate the offset
- // from localheaderstart to dataoffset
- int localextralen = pfi->extralen; // FIXME: this will not work if
- // no local header exists
-
- //kdDebug(7040) << "localextralen: " << localextralen << endl;
-
- // offset, where the real data for uncompression starts
- uint dataoffset = localheaderoffset + 30 + localextralen + namelen; //comment only in central header
-
- //kdDebug(7040) << "esize: " << esize << endl;
- //kdDebug(7040) << "eoffset: " << eoffset << endl;
- //kdDebug(7040) << "csize: " << csize << endl;
-
- int os_madeby = (uchar)buffer[5];
- bool isdir = false;
- int access = 0100644;
-
- if (os_madeby == 3) { // good ole unix
- access = (uchar)buffer[40] | (uchar)buffer[41] << 8;
- }
-
- TQString entryName;
-
- if ( name.endsWith( "/" ) ) // Entries with a trailing slash are directories
- {
- isdir = true;
- name = name.left( name.length() - 1 );
- if (os_madeby != 3) access = S_IFDIR | 0755;
- else Q_ASSERT(access & S_IFDIR);
- }
-
- int pos = name.findRev( '/' );
- if ( pos == -1 )
- entryName = name;
- else
- entryName = name.mid( pos + 1 );
- Q_ASSERT( !entryName.isEmpty() );
-
- KArchiveEntry* entry;
- if ( isdir )
- {
- TQString path = TQDir::cleanDirPath( name );
- KArchiveEntry* ent = rootDir()->entry( path );
- if ( ent && ent->isDirectory() )
- {
- //kdDebug(7040) << "Directory already exists, NOT going to add it again" << endl;
- entry = 0L;
- }
- else
- {
- entry = new KArchiveDirectory( this, entryName, access, (int)pfi->mtime, rootDir()->user(), rootDir()->group(), TQString::null );
- //kdDebug(7040) << "KArchiveDirectory created, entryName= " << entryName << ", name=" << name << endl;
- }
- }
- else
- {
- TQString symlink;
- if (S_ISLNK(access)) {
- symlink = TQFile::decodeName(pfi->guessed_symlink);
- }
- entry = new KZipFileEntry( this, entryName, access, pfi->mtime,
- rootDir()->user(), rootDir()->group(),
- symlink, name, dataoffset,
- ucsize, cmethod, csize );
- static_cast<KZipFileEntry *>(entry)->setHeaderStart( localheaderoffset );
- //kdDebug(7040) << "KZipFileEntry created, entryName= " << entryName << ", name=" << name << endl;
- d->m_fileList.append( static_cast<KZipFileEntry *>( entry ) );
- }
-
- if ( entry )
- {
- if ( pos == -1 )
- {
- rootDir()->addEntry(entry);
- }
- else
- {
- // In some tar files we can find dir/./file => call cleanDirPath
- TQString path = TQDir::cleanDirPath( name.left( pos ) );
- // Ensure container directory exists, create otherwise
- KArchiveDirectory * tdir = findOrCreate( path );
- tdir->addEntry(entry);
- }
- }
-
- //calculate offset to next entry
- offset += 46 + commlen + extralen + namelen;
- bool b = dev->at(offset);
- Q_ASSERT( b );
- if ( !b )
- return false;
- }
- else if ( startOfFile )
- {
- // The file does not start with any ZIP header (e.g. self-extractable ZIP files)
- // Therefore we need to find the first PK\003\004 (local header)
- kdDebug(7040) << "Try to skip start of file" << endl;
- startOfFile = false;
- bool foundSignature = false;
-
- while (!foundSignature)
- {
- n = dev->readBlock( buffer, 1 );
- if (n < 1)
- {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. " << k_funcinfo << endl;
- return false;
- }
-
- if ( buffer[0] != 'P' )
- continue;
-
- n = dev->readBlock( buffer, 3 );
- if (n < 3)
- {
- kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. " << k_funcinfo << endl;
- return false;
- }
-
- // We have to detect the magic token for a local header: PK\003\004
- /*
- * Note: we do not need to check the other magics, if the ZIP file has no
- * local header, then it has not any files!
- */
- if ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2] == 4 )
- {
- foundSignature = true;
- dev->at( dev->at() - 4 ); // go back 4 bytes, so that the magic bytes can be found...
- }
- else if ( buffer[0] == 'P' || buffer[1] == 'P' || buffer[2] == 'P' )
- {
- // We have another P character so we must go back a little to check if it is a magic
- dev->at( dev->at() - 3 );
- }
- }
- }
- else
- {
- kdWarning(7040) << "Invalid ZIP file. Unrecognized header at offset " << offset << endl;
-
- return false;
- }
- }
- //kdDebug(7040) << "*** done *** " << endl;
- return true;
-}
-
-bool KZip::closeArchive()
-{
- if ( ! ( mode() & IO_WriteOnly ) )
- {
- //kdDebug(7040) << "closearchive readonly reached." << endl;
- return true;
- }
-
- kdDebug() << k_funcinfo << "device=" << device() << endl;
- //ReadWrite or WriteOnly
- //write all central dir file entries
-
- if ( !device() ) // saving aborted
- return false;
-
- // to be written at the end of the file...
- char buffer[ 22 ]; // first used for 12, then for 22 at the end
- uLong crc = crc32(0L, Z_NULL, 0);
-
- TQ_LONG centraldiroffset = device()->at();
- //kdDebug(7040) << "closearchive: centraldiroffset: " << centraldiroffset << endl;
- TQ_LONG atbackup = centraldiroffset;
- TQPtrListIterator<KZipFileEntry> it( d->m_fileList );
-
- for ( ; it.current() ; ++it )
- { //set crc and compressed size in each local file header
- if ( !device()->at( it.current()->headerStart() + 14 ) )
- return false;
- //kdDebug(7040) << "closearchive setcrcandcsize: filename: "
- // << it.current()->path()
- // << " encoding: "<< it.current()->encoding() << endl;
-
- uLong mycrc = it.current()->crc32();
- buffer[0] = char(mycrc); // crc checksum, at headerStart+14
- buffer[1] = char(mycrc >> 8);
- buffer[2] = char(mycrc >> 16);
- buffer[3] = char(mycrc >> 24);
-
- int mysize1 = it.current()->compressedSize();
- buffer[4] = char(mysize1); // compressed file size, at headerStart+18
- buffer[5] = char(mysize1 >> 8);
- buffer[6] = char(mysize1 >> 16);
- buffer[7] = char(mysize1 >> 24);
-
- int myusize = it.current()->size();
- buffer[8] = char(myusize); // uncompressed file size, at headerStart+22
- buffer[9] = char(myusize >> 8);
- buffer[10] = char(myusize >> 16);
- buffer[11] = char(myusize >> 24);
-
- if ( device()->writeBlock( buffer, 12 ) != 12 )
- return false;
- }
- device()->at( atbackup );
-
- for ( it.toFirst(); it.current() ; ++it )
- {
- //kdDebug(7040) << "closearchive: filename: " << it.current()->path()
- // << " encoding: "<< it.current()->encoding() << endl;
-
- TQCString path = TQFile::encodeName(it.current()->path());
-
- const int extra_field_len = 9;
- int bufferSize = extra_field_len + path.length() + 46;
- char* buffer = new char[ bufferSize ];
-
- memset(buffer, 0, 46); // zero is a nice default for most header fields
-
- const char head[] =
- {
- 'P', 'K', 1, 2, // central file header signature
- 0x14, 3, // version made by (3 == UNIX)
- 0x14, 0 // version needed to extract
- };
-
- // I do not know why memcpy is not working here
- //memcpy(buffer, head, sizeof(head));
- tqmemmove(buffer, head, sizeof(head));
-
- buffer[ 10 ] = char(it.current()->encoding()); // compression method
- buffer[ 11 ] = char(it.current()->encoding() >> 8);
-
- transformToMsDos( it.current()->datetime(), &buffer[ 12 ] );
-
- uLong mycrc = it.current()->crc32();
- buffer[ 16 ] = char(mycrc); // crc checksum
- buffer[ 17 ] = char(mycrc >> 8);
- buffer[ 18 ] = char(mycrc >> 16);
- buffer[ 19 ] = char(mycrc >> 24);
-
- int mysize1 = it.current()->compressedSize();
- buffer[ 20 ] = char(mysize1); // compressed file size
- buffer[ 21 ] = char(mysize1 >> 8);
- buffer[ 22 ] = char(mysize1 >> 16);
- buffer[ 23 ] = char(mysize1 >> 24);
-
- int mysize = it.current()->size();
- buffer[ 24 ] = char(mysize); // uncompressed file size
- buffer[ 25 ] = char(mysize >> 8);
- buffer[ 26 ] = char(mysize >> 16);
- buffer[ 27 ] = char(mysize >> 24);
-
- buffer[ 28 ] = char(it.current()->path().length()); // filename length
- buffer[ 29 ] = char(it.current()->path().length() >> 8);
-
- buffer[ 30 ] = char(extra_field_len);
- buffer[ 31 ] = char(extra_field_len >> 8);
-
- buffer[ 40 ] = char(it.current()->permissions());
- buffer[ 41 ] = char(it.current()->permissions() >> 8);
-
- int myhst = it.current()->headerStart();
- buffer[ 42 ] = char(myhst); //relative offset of local header
- buffer[ 43 ] = char(myhst >> 8);
- buffer[ 44 ] = char(myhst >> 16);
- buffer[ 45 ] = char(myhst >> 24);
-
- // file name
- strncpy( buffer + 46, path, path.length() );
- //kdDebug(7040) << "closearchive length to write: " << bufferSize << endl;
-
- // extra field
- char *extfield = buffer + 46 + path.length();
- extfield[0] = 'U';
- extfield[1] = 'T';
- extfield[2] = 5;
- extfield[3] = 0;
- extfield[4] = 1 | 2 | 4; // specify flags from local field
- // (unless I misread the spec)
- // provide only modification time
- unsigned long time = (unsigned long)it.current()->date();
- extfield[5] = char(time);
- extfield[6] = char(time >> 8);
- extfield[7] = char(time >> 16);
- extfield[8] = char(time >> 24);
-
- crc = crc32(crc, (Bytef *)buffer, bufferSize );
- bool ok = ( device()->writeBlock( buffer, bufferSize ) == bufferSize );
- delete[] buffer;
- if ( !ok )
- return false;
- }
- TQ_LONG centraldirendoffset = device()->at();
- //kdDebug(7040) << "closearchive: centraldirendoffset: " << centraldirendoffset << endl;
- //kdDebug(7040) << "closearchive: device()->at(): " << device()->at() << endl;
-
- //write end of central dir record.
- buffer[ 0 ] = 'P'; //end of central dir signature
- buffer[ 1 ] = 'K';
- buffer[ 2 ] = 5;
- buffer[ 3 ] = 6;
-
- buffer[ 4 ] = 0; // number of this disk
- buffer[ 5 ] = 0;
-
- buffer[ 6 ] = 0; // number of disk with start of central dir
- buffer[ 7 ] = 0;
-
- int count = d->m_fileList.count();
- //kdDebug(7040) << "number of files (count): " << count << endl;
-
-
- buffer[ 8 ] = char(count); // total number of entries in central dir of
- buffer[ 9 ] = char(count >> 8); // this disk
-
- buffer[ 10 ] = buffer[ 8 ]; // total number of entries in the central dir
- buffer[ 11 ] = buffer[ 9 ];
-
- int cdsize = centraldirendoffset - centraldiroffset;
- buffer[ 12 ] = char(cdsize); // size of the central dir
- buffer[ 13 ] = char(cdsize >> 8);
- buffer[ 14 ] = char(cdsize >> 16);
- buffer[ 15 ] = char(cdsize >> 24);
-
- //kdDebug(7040) << "end : centraldiroffset: " << centraldiroffset << endl;
- //kdDebug(7040) << "end : centraldirsize: " << cdsize << endl;
-
- buffer[ 16 ] = char(centraldiroffset); // central dir offset
- buffer[ 17 ] = char(centraldiroffset >> 8);
- buffer[ 18 ] = char(centraldiroffset >> 16);
- buffer[ 19 ] = char(centraldiroffset >> 24);
-
- buffer[ 20 ] = 0; //zipfile comment length
- buffer[ 21 ] = 0;
-
- if ( device()->writeBlock( buffer, 22 ) != 22 )
- return false;
-
- if ( d->m_saveFile ) {
- d->m_saveFile->close();
- setDevice( 0 );
- delete d->m_saveFile;
- d->m_saveFile = 0;
- }
-
- //kdDebug(7040) << __FILE__" reached." << endl;
- return true;
-}
-
-// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
-bool KZip::writeFile( const TQString& name, const TQString& user, const TQString& group, uint size, const char* data )
-{
- mode_t mode = 0100644;
- time_t the_time = time(0);
- return KArchive::writeFile( name, user, group, size, mode, the_time,
- the_time, the_time, data );
-}
-
-// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
-bool KZip::writeFile( const TQString& name, const TQString& user,
- const TQString& group, uint size, mode_t perm,
- time_t atime, time_t mtime, time_t ctime,
- const char* data ) {
- return KArchive::writeFile(name, user, group, size, perm, atime, mtime,
- ctime, data);
-}
-
-// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
-bool KZip::prepareWriting( const TQString& name, const TQString& user, const TQString& group, uint size )
-{
- mode_t dflt_perm = 0100644;
- time_t the_time = time(0);
- return prepareWriting(name,user,group,size,dflt_perm,
- the_time,the_time,the_time);
-}
-
-// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
-bool KZip::prepareWriting(const TQString& name, const TQString& user,
- const TQString& group, uint size, mode_t perm,
- time_t atime, time_t mtime, time_t ctime) {
- return KArchive::prepareWriting(name,user,group,size,perm,atime,mtime,ctime);
-}
-
-bool KZip::prepareWriting_impl(const TQString &name, const TQString &user,
- const TQString &group, uint /*size*/, mode_t perm,
- time_t atime, time_t mtime, time_t ctime) {
- //kdDebug(7040) << "prepareWriting reached." << endl;
- if ( !isOpened() )
- {
- tqWarning( "KZip::writeFile: You must open the zip file before writing to it\n");
- return false;
- }
-
- if ( ! ( mode() & IO_WriteOnly ) ) // accept WriteOnly and ReadWrite
- {
- tqWarning( "KZip::writeFile: You must open the zip file for writing\n");
- return false;
- }
-
- if ( !device() ) { // aborted
- //kdWarning(7040) << "prepareWriting_impl: no device" << endl;
- return false;
- }
-
- // set right offset in zip.
- if ( !device()->at( d->m_offset ) ) {
- kdWarning(7040) << "prepareWriting_impl: cannot seek in ZIP file. Disk full?" << endl;
- abort();
- return false;
- }
-
- // delete entries in the filelist with the same filename as the one we want
- // to save, so that we don�t have duplicate file entries when viewing the zip
- // with konqi...
- // CAUTION: the old file itself is still in the zip and won't be removed !!!
- TQPtrListIterator<KZipFileEntry> it( d->m_fileList );
-
- //kdDebug(7040) << "filename to write: " << name <<endl;
- for ( ; it.current() ; ++it )
- {
- //kdDebug(7040) << "prepfilename: " << it.current()->path() <<endl;
- if (name == it.current()->path() )
- {
- //kdDebug(7040) << "removing following entry: " << it.current()->path() <<endl;
- d->m_fileList.remove();
- }
-
- }
- // Find or create parent dir
- KArchiveDirectory* parentDir = rootDir();
- TQString fileName( name );
- int i = name.findRev( '/' );
- if ( i != -1 )
- {
- TQString dir = name.left( i );
- fileName = name.mid( i + 1 );
- //kdDebug(7040) << "KZip::prepareWriting ensuring " << dir << " exists. fileName=" << fileName << endl;
- parentDir = findOrCreate( dir );
- }
-
- // construct a KZipFileEntry and add it to list
- KZipFileEntry * e = new KZipFileEntry( this, fileName, perm, mtime, user, group, TQString::null,
- name, device()->at() + 30 + name.length(), // start
- 0 /*size unknown yet*/, d->m_compression, 0 /*csize unknown yet*/ );
- e->setHeaderStart( device()->at() );
- //kdDebug(7040) << "wrote file start: " << e->position() << " name: " << name << endl;
- parentDir->addEntry( e );
-
- d->m_currentFile = e;
- d->m_fileList.append( e );
-
- int extra_field_len = 0;
- if ( d->m_extraField == ModificationTime )
- extra_field_len = 17; // value also used in doneWriting()
-
- // write out zip header
- TQCString encodedName = TQFile::encodeName(name);
- int bufferSize = extra_field_len + encodedName.length() + 30;
- //kdDebug(7040) << "KZip::prepareWriting bufferSize=" << bufferSize << endl;
- char* buffer = new char[ bufferSize ];
-
- buffer[ 0 ] = 'P'; //local file header signature
- buffer[ 1 ] = 'K';
- buffer[ 2 ] = 3;
- buffer[ 3 ] = 4;
-
- buffer[ 4 ] = 0x14; // version needed to extract
- buffer[ 5 ] = 0;
-
- buffer[ 6 ] = 0; // general purpose bit flag
- buffer[ 7 ] = 0;
-
- buffer[ 8 ] = char(e->encoding()); // compression method
- buffer[ 9 ] = char(e->encoding() >> 8);
-
- transformToMsDos( e->datetime(), &buffer[ 10 ] );
-
- buffer[ 14 ] = 'C'; //dummy crc
- buffer[ 15 ] = 'R';
- buffer[ 16 ] = 'C';
- buffer[ 17 ] = 'q';
-
- buffer[ 18 ] = 'C'; //compressed file size
- buffer[ 19 ] = 'S';
- buffer[ 20 ] = 'I';
- buffer[ 21 ] = 'Z';
-
- buffer[ 22 ] = 'U'; //uncompressed file size
- buffer[ 23 ] = 'S';
- buffer[ 24 ] = 'I';
- buffer[ 25 ] = 'Z';
-
- buffer[ 26 ] = (uchar)(encodedName.length()); //filename length
- buffer[ 27 ] = (uchar)(encodedName.length() >> 8);
-
- buffer[ 28 ] = (uchar)(extra_field_len); // extra field length
- buffer[ 29 ] = (uchar)(extra_field_len >> 8);
-
- // file name
- strncpy( buffer + 30, encodedName, encodedName.length() );
-
- // extra field
- if ( d->m_extraField == ModificationTime )
- {
- char *extfield = buffer + 30 + encodedName.length();
- // "Extended timestamp" header (0x5455)
- extfield[0] = 'U';
- extfield[1] = 'T';
- extfield[2] = 13; // data size
- extfield[3] = 0;
- extfield[4] = 1 | 2 | 4; // contains mtime, atime, ctime
-
- extfield[5] = char(mtime);
- extfield[6] = char(mtime >> 8);
- extfield[7] = char(mtime >> 16);
- extfield[8] = char(mtime >> 24);
-
- extfield[9] = char(atime);
- extfield[10] = char(atime >> 8);
- extfield[11] = char(atime >> 16);
- extfield[12] = char(atime >> 24);
-
- extfield[13] = char(ctime);
- extfield[14] = char(ctime >> 8);
- extfield[15] = char(ctime >> 16);
- extfield[16] = char(ctime >> 24);
- }
-
- // Write header
- bool b = (device()->writeBlock( buffer, bufferSize ) == bufferSize );
- d->m_crc = 0L;
- delete[] buffer;
-
- Q_ASSERT( b );
- if (!b) {
- abort();
- return false;
- }
-
- // Prepare device for writing the data
- // Either device() if no compression, or a KFilterDev to compress
- if ( d->m_compression == 0 ) {
- d->m_currentDev = device();
- return true;
- }
-
- d->m_currentDev = KFilterDev::device( device(), "application/x-gzip", false );
- Q_ASSERT( d->m_currentDev );
- if ( !d->m_currentDev ) {
- abort();
- return false; // ouch
- }
- static_cast<KFilterDev *>(d->m_currentDev)->setSkipHeaders(); // Just zlib, not gzip
-
- b = d->m_currentDev->open( IO_WriteOnly );
- Q_ASSERT( b );
- return b;
-}
-
-bool KZip::doneWriting( uint size )
-{
- if ( d->m_currentFile->encoding() == 8 ) {
- // Finish
- (void)d->m_currentDev->writeBlock( 0, 0 );
- delete d->m_currentDev;
- }
- // If 0, d->m_currentDev was device() - don't delete ;)
- d->m_currentDev = 0L;
-
- Q_ASSERT( d->m_currentFile );
- //kdDebug(7040) << "donewriting reached." << endl;
- //kdDebug(7040) << "filename: " << d->m_currentFile->path() << endl;
- //kdDebug(7040) << "getpos (at): " << device()->at() << endl;
- d->m_currentFile->setSize(size);
- int extra_field_len = 0;
- if ( d->m_extraField == ModificationTime )
- extra_field_len = 17; // value also used in doneWriting()
-
- int csize = device()->at() -
- d->m_currentFile->headerStart() - 30 -
- d->m_currentFile->path().length() - extra_field_len;
- d->m_currentFile->setCompressedSize(csize);
- //kdDebug(7040) << "usize: " << d->m_currentFile->size() << endl;
- //kdDebug(7040) << "csize: " << d->m_currentFile->compressedSize() << endl;
- //kdDebug(7040) << "headerstart: " << d->m_currentFile->headerStart() << endl;
-
- //kdDebug(7040) << "crc: " << d->m_crc << endl;
- d->m_currentFile->setCRC32( d->m_crc );
-
- d->m_currentFile = 0L;
-
- // update saved offset for appending new files
- d->m_offset = device()->at();
- return true;
-}
-
-bool KZip::writeSymLink(const TQString &name, const TQString &target,
- const TQString &user, const TQString &group,
- mode_t perm, time_t atime, time_t mtime, time_t ctime) {
- return KArchive::writeSymLink(name,target,user,group,perm,atime,mtime,ctime);
-}
-
-bool KZip::writeSymLink_impl(const TQString &name, const TQString &target,
- const TQString &user, const TQString &group,
- mode_t perm, time_t atime, time_t mtime, time_t ctime) {
-
- // reassure that symlink flag is set, otherwise strange things happen on
- // extraction
- perm |= S_IFLNK;
- Compression c = compression();
- setCompression(NoCompression); // link targets are never compressed
-
- if (!prepareWriting(name, user, group, 0, perm, atime, mtime, ctime)) {
- kdWarning() << "KZip::writeFile prepareWriting failed" << endl;
- setCompression(c);
- return false;
- }
-
- TQCString symlink_target = TQFile::encodeName(target);
- if (!writeData(symlink_target, symlink_target.length())) {
- kdWarning() << "KZip::writeFile writeData failed" << endl;
- setCompression(c);
- return false;
- }
-
- if (!doneWriting(symlink_target.length())) {
- kdWarning() << "KZip::writeFile doneWriting failed" << endl;
- setCompression(c);
- return false;
- }
-
- setCompression(c);
- return true;
-}
-
-void KZip::virtual_hook( int id, void* data )
-{
- switch (id) {
- case VIRTUAL_WRITE_DATA: {
- WriteDataParams* params = reinterpret_cast<WriteDataParams *>(data);
- params->retval = writeData_impl( params->data, params->size );
- break;
- }
- case VIRTUAL_WRITE_SYMLINK: {
- WriteSymlinkParams *params = reinterpret_cast<WriteSymlinkParams *>(data);
- params->retval = writeSymLink_impl(*params->name,*params->target,
- *params->user,*params->group,params->perm,
- params->atime,params->mtime,params->ctime);
- break;
- }
- case VIRTUAL_PREPARE_WRITING: {
- PrepareWritingParams *params = reinterpret_cast<PrepareWritingParams *>(data);
- params->retval = prepareWriting_impl(*params->name,*params->user,
- *params->group,params->size,params->perm,
- params->atime,params->mtime,params->ctime);
- break;
- }
- default:
- KArchive::virtual_hook( id, data );
- }/*end switch*/
-}
-
-// made virtual using virtual_hook
-bool KZip::writeData(const char * c, uint i)
-{
- return KArchive::writeData( c, i );
-}
-
-bool KZip::writeData_impl(const char * c, uint i)
-{
- Q_ASSERT( d->m_currentFile );
- Q_ASSERT( d->m_currentDev );
- if (!d->m_currentFile || !d->m_currentDev) {
- abort();
- return false;
- }
-
- // crc to be calculated over uncompressed stuff...
- // and they didn't mention it in their docs...
- d->m_crc = crc32(d->m_crc, (const Bytef *) c , i);
-
- TQ_LONG written = d->m_currentDev->writeBlock( c, i );
- //kdDebug(7040) << "KZip::writeData wrote " << i << " bytes." << endl;
- bool ok = written == (TQ_LONG)i;
- if ( !ok )
- abort();
- return ok;
-}
-
-void KZip::setCompression( Compression c )
-{
- d->m_compression = ( c == NoCompression ) ? 0 : 8;
-}
-
-KZip::Compression KZip::compression() const
-{
- return ( d->m_compression == 8 ) ? DeflateCompression : NoCompression;
-}
-
-void KZip::setExtraField( ExtraField ef )
-{
- d->m_extraField = ef;
-}
-
-KZip::ExtraField KZip::extraField() const
-{
- return d->m_extraField;
-}
-
-void KZip::abort()
-{
- if ( d->m_saveFile ) {
- d->m_saveFile->abort();
- setDevice( 0 );
- }
-}
-
-
-///////////////
-
-TQByteArray KZipFileEntry::data() const
-{
- TQIODevice* dev = device();
- TQByteArray arr;
- if ( dev ) {
- arr = dev->readAll();
- delete dev;
- }
- return arr;
-}
-
-TQIODevice* KZipFileEntry::device() const
-{
- //kdDebug(7040) << "KZipFileEntry::device creating iodevice limited to pos=" << position() << ", csize=" << compressedSize() << endl;
- // Limit the reading to the appropriate part of the underlying device (e.g. file)
- KLimitedIODevice* limitedDev = new KLimitedIODevice( archive()->device(), position(), compressedSize() );
- if ( encoding() == 0 || compressedSize() == 0 ) // no compression (or even no data)
- return limitedDev;
-
- if ( encoding() == 8 )
- {
- // On top of that, create a device that uncompresses the zlib data
- TQIODevice* filterDev = KFilterDev::device( limitedDev, "application/x-gzip" );
- if ( !filterDev )
- return 0L; // ouch
- static_cast<KFilterDev *>(filterDev)->setSkipHeaders(); // Just zlib, not gzip
- bool b = filterDev->open( IO_ReadOnly );
- Q_ASSERT( b );
- return filterDev;
- }
-
- kdError() << "This zip file contains files compressed with method "
- << encoding() <<", this method is currently not supported by KZip,"
- <<" please use a command-line tool to handle this file." << endl;
- return 0L;
-}
diff --git a/kio/kio/kzip.h b/kio/kio/kzip.h
deleted file mode 100644
index 9e4d24eeb..000000000
--- a/kio/kio/kzip.h
+++ /dev/null
@@ -1,284 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Holger Schroeder <holger-kde@holgis.net>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __kzip_h
-#define __kzip_h
-
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#include <tqdatetime.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-#include <tqdict.h>
-#include <tqvaluelist.h>
-#include <karchive.h>
-
-class KZipFileEntry;
-/**
- * This class implements a kioslave to access zip files from KDE.
- * You can use it in IO_ReadOnly or in IO_WriteOnly mode, and it
- * behaves just as expected.
- * It can also be used in IO_ReadWrite mode, in this case one can
- * append files to an existing zip archive. When you append new files, which
- * are not yet in the zip, it works as expected, i.e. the files are appended at the end.
- * When you append a file, which is already in the file, the reference to the
- * old file is dropped and the new one is added to the zip - but the
- * old data from the file itself is not deleted, it is still in the
- * zipfile. so when you want to have a small and garbage-free zipfile,
- * just read the contents of the appended zip file and write it to a new one
- * in IO_WriteOnly mode. This is especially important when you don't want
- * to leak information of how intermediate versions of files in the zip
- * were looking.
- * For more information on the zip fileformat go to
- * http://www.pkware.com/products/enterprise/white_papers/appnote.html
- * @short A class for reading/writing zip archives.
- * @author Holger Schroeder <holger-kde@holgis.net>
- * @since 3.1
- */
-class TDEIO_EXPORT KZip : public KArchive
-{
-public:
- /**
- * Creates an instance that operates on the given filename.
- * using the compression filter associated to given mimetype.
- *
- * @param filename is a local path (e.g. "/home/holger/myfile.zip")
- */
- KZip( const TQString& filename );
-
- /**
- * Creates an instance that operates on the given device.
- * The device can be compressed (KFilterDev) or not (TQFile, etc.).
- * @warning Do not assume that giving a TQFile here will decompress the file,
- * in case it's compressed!
- * @param dev the device to access
- */
- KZip( TQIODevice * dev );
-
- /**
- * If the zip file is still opened, then it will be
- * closed automatically by the destructor.
- */
- virtual ~KZip();
-
- /**
- * The name of the zip file, as passed to the constructor.
- * Null if you used the TQIODevice constructor.
- * @return the zip's file name, or null if a TQIODevice is used
- */
- TQString fileName() { return m_filename; }
-
- /**
- * Describes the contents of the "extra field" for a given file in the Zip archive.
- */
- enum ExtraField { NoExtraField = 0, ///< No extra field
- ModificationTime = 1, ///< Modification time ("extended timestamp" header)
- DefaultExtraField = 1
- };
-
- /**
- * Call this before writeFile or prepareWriting, to define what the next
- * file to be written should have in its extra field.
- * @param ef the type of "extra field"
- * @see extraField()
- */
- void setExtraField( ExtraField ef );
-
- /**
- * The current type of "extra field" that will be used for new files.
- * @return the current type of "extra field"
- * @see setExtraField()
- */
- ExtraField extraField() const;
-
- /**
- * Describes the compression type for a given file in the Zip archive.
- */
- enum Compression { NoCompression = 0, ///< Uncompressed.
- DeflateCompression = 1 ///< Deflate compression method.
- };
-
-
- /**
- * Call this before writeFile or prepareWriting, to define whether the next
- * files to be written should be compressed or not.
- * @param c the new compression mode
- * @see compression()
- */
- void setCompression( Compression c );
-
- /**
- * The current compression mode that will be used for new files.
- * @return the current compression mode
- * @see setCompression()
- */
- Compression compression() const;
-
- /**
- * If an archive is opened for writing then you can add a new file
- * using this function.
- * This method takes the whole data at once.
- * @param name can include subdirs e.g. path/to/the/file
- * @param user the user owning the file
- * @param group the group owning the file
- * @param size the size of the file
- * @param data a pointer to the data
- * @return true if successful, false otherwise
- */
- virtual bool writeFile( const TQString& name, const TQString& user, const TQString& group, uint size, const char* data ); // BC: remove reimplementation for KDE-4.0
-
- /**
- * Alternative method for writing: call prepareWriting(), then feed the data
- * in small chunks using writeData(), and call doneWriting() when done.
- * @param name can include subdirs e.g. path/to/the/file
- * @param user the user owning the file
- * @param group the group owning the file
- * @param size unused argument
- * @return true if successful, false otherwise
- */
- virtual bool prepareWriting( const TQString& name, const TQString& user, const TQString& group, uint size );
-
- // TODO(BIC) make virtual. For now it must be implemented by virtual_hook.
- bool writeSymLink(const TQString &name, const TQString &target,
- const TQString &user, const TQString &group,
- mode_t perm, time_t atime, time_t mtime, time_t ctime);
- // TODO(BIC) make virtual. For now it must be implemented by virtual_hook.
- bool prepareWriting( const TQString& name, const TQString& user,
- const TQString& group, uint size, mode_t perm,
- time_t atime, time_t mtime, time_t ctime );
- // TODO(BIC) make virtual. For now it must be implemented by virtual_hook.
- bool writeFile( const TQString& name, const TQString& user, const TQString& group,
- uint size, mode_t perm, time_t atime, time_t mtime,
- time_t ctime, const char* data );
- /**
- * Write data to a file that has been created using prepareWriting().
- * @param data a pointer to the data
- * @param size the size of the chunk
- * @return true if successful, false otherwise
- */
- bool writeData( const char* data, uint size ); // TODO make virtual
-
- /**
- * Write data to a file that has been created using prepareWriting().
- * @param size the size of the file
- * @return true if successful, false otherwise
- */
- virtual bool doneWriting( uint size );
-
-protected:
- /**
- * Opens the archive for reading.
- * Parses the directory listing of the archive
- * and creates the KArchiveDirectory/KArchiveFile entries.
- * @param mode the mode of the file
- */
- virtual bool openArchive( int mode );
- /// Closes the archive
- virtual bool closeArchive();
-
- /**
- * @internal Not needed for zip
- */
- virtual bool writeDir( const TQString& name, const TQString& user, const TQString& group) { Q_UNUSED(name); Q_UNUSED(user); Q_UNUSED(group); return true; }
- // TODO(BIC) uncomment and make virtual for KDE 4.
-// bool writeDir( const TQString& name, const TQString& user, const TQString& group,
-// mode_t perm, time_t atime, time_t mtime, time_t ctime );
-
-protected:
- virtual void virtual_hook( int id, void* data );
- /** @internal for virtual_hook */
- // from KArchive
- bool writeData_impl( const char* data, uint size );
- bool prepareWriting_impl(const TQString& name, const TQString& user,
- const TQString& group, uint size, mode_t perm,
- time_t atime, time_t mtime, time_t ctime);
- bool writeSymLink_impl(const TQString &name, const TQString &target,
- const TQString &user, const TQString &group,
- mode_t perm, time_t atime, time_t mtime, time_t ctime);
-private:
- void abort();
-
-private:
- TQString m_filename;
- class KZipPrivate;
- KZipPrivate * d;
-};
-
-
-/**
- * @internal
- */
-class TDEIO_EXPORT KZipFileEntry : public KArchiveFile
-{
-public:
- /*KZipFileEntry() : st(-1)
- {}*/
- KZipFileEntry( KZip* zip, const TQString& name, int access, int date,
- const TQString& user, const TQString& group, const TQString& symlink,
- const TQString& path, TQ_LONG start, TQ_LONG uncompressedSize,
- int encoding, TQ_LONG compressedSize) :
- KArchiveFile( zip, name, access, date, user, group, symlink,
- start, uncompressedSize ),
- m_crc(0),
- m_compressedSize(compressedSize),
- m_headerStart(0),
- m_encoding(encoding),
- m_path( path )
- {}
- int encoding() const { return m_encoding; }
- TQ_LONG compressedSize() const { return m_compressedSize; }
-
- /// Only used when writing
- void setCompressedSize(TQ_LONG compressedSize) { m_compressedSize = compressedSize; }
-
- /// Header start: only used when writing
- void setHeaderStart(TQ_LONG headerstart) { m_headerStart = headerstart; }
- TQ_LONG headerStart() const {return m_headerStart; }
-
- /// CRC: only used when writing
- unsigned long crc32() const { return m_crc; }
- void setCRC32(unsigned long crc32) { m_crc=crc32; }
-
- /// Name with complete path - KArchiveFile::name() is the filename only (no path)
- TQString path() const { return m_path; }
-
- /**
- * @return the content of this file.
- * Call data() with care (only once per file), this data isn't cached.
- */
- virtual TQByteArray data() const;
-
- /**
- * This method returns a TQIODevice to read the file contents.
- * This is obviously for reading only.
- * Note that the ownership of the device is being transferred to the caller,
- * who will have to delete it.
- * The returned device auto-opens (in readonly mode), no need to open it.
- */
- TQIODevice* device() const; // WARNING, not virtual!
-
-private:
- unsigned long m_crc;
- TQ_LONG m_compressedSize;
- TQ_LONG m_headerStart;
- int m_encoding;
- TQString m_path;
- // KDE4: d pointer or at least some int for future extensions
-};
-
-#endif
diff --git a/kio/kio/metainfojob.cpp b/kio/kio/metainfojob.cpp
deleted file mode 100644
index d28914f20..000000000
--- a/kio/kio/metainfojob.cpp
+++ /dev/null
@@ -1,184 +0,0 @@
-// -*- c++ -*-
-// vim: ts=4 sw=4 et
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Rolf Magnus <ramagnus@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation version 2.0.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
- $Id$
-*/
-
-#include <kdatastream.h> // Do not remove, needed for correct bool serialization
-#include <kfileitem.h>
-#include <kdebug.h>
-#include <kfilemetainfo.h>
-#include <kio/kservice.h>
-#include <tdeparts/componentfactory.h>
-
-#include <tqtimer.h>
-
-#include "metainfojob.moc"
-
-using namespace TDEIO;
-
-struct TDEIO::MetaInfoJobPrivate
-{
- KFileItemList items; // all the items we got
- KFileItemListIterator* currentItem; // argh! No default constructor
- bool deleteItems; // Delete the KFileItems when done?
- bool succeeded; // if the current item is ok
-};
-
-MetaInfoJob::MetaInfoJob(const KFileItemList &items, bool deleteItems)
- : TDEIO::Job(false /* no GUI */)
-{
- d = new MetaInfoJobPrivate;
- d->deleteItems = deleteItems;
- d->succeeded = false;
- d->items = items;
- d->currentItem = new KFileItemListIterator(d->items);
-
- d->items.setAutoDelete(deleteItems);
-
- if (d->currentItem->isEmpty())
- {
- kdDebug(7007) << "nothing to do for the MetaInfoJob\n";
- emitResult();
- return;
- }
-
- kdDebug(7007) << "starting MetaInfoJob\n";
-
- // Return to event loop first, determineNextFile() might delete this;
- // (no idea what that means, it comes from previewjob)
- TQTimer::singleShot(0, this, TQT_SLOT(start()));
-}
-
-MetaInfoJob::~MetaInfoJob()
-{
- delete d->currentItem;
- delete d;
-}
-
-void MetaInfoJob::start()
-{
- getMetaInfo();
-}
-
-void MetaInfoJob::removeItem(const KFileItem* item)
-{
- if (d->currentItem->current() == item)
- {
- subjobs.first()->kill();
- subjobs.removeFirst();
- determineNextFile();
- }
-
- d->items.remove(d->items.find(item));
-}
-
-void MetaInfoJob::determineNextFile()
-{
- if (d->currentItem->atLast())
- {
- kdDebug(7007) << "finished MetaInfoJob\n";
- emitResult();
- return;
- }
-
- ++(*d->currentItem);
- d->succeeded = false;
-
- // does the file item already have the needed info? Then shortcut
- if (d->currentItem->current()->metaInfo(false).isValid())
- {
-// kdDebug(7007) << "Is already valid *************************\n";
- emit gotMetaInfo(d->currentItem->current());
- determineNextFile();
- return;
- }
-
- getMetaInfo();
-}
-
-void MetaInfoJob::slotResult( TDEIO::Job *job )
-{
- subjobs.remove(job);
- Q_ASSERT(subjobs.isEmpty()); // We should have only one job at a time ...
-
- determineNextFile();
-}
-
-void MetaInfoJob::getMetaInfo()
-{
- Q_ASSERT(!d->currentItem->isEmpty());
-
- KURL URL;
- URL.setProtocol("metainfo");
- URL.setPath(d->currentItem->current()->url().path());
-
- TDEIO::TransferJob* job = TDEIO::get(URL, false, false);
- addSubjob(job);
-
- connect(job, TQT_SIGNAL(data(TDEIO::Job *, const TQByteArray &)),
- this, TQT_SLOT(slotMetaInfo(TDEIO::Job *, const TQByteArray &)));
-
- job->addMetaData("mimeType", d->currentItem->current()->mimetype());
-}
-
-
-void MetaInfoJob::slotMetaInfo(TDEIO::Job*, const TQByteArray &data)
-{
- KFileMetaInfo info;
- TQDataStream s(data, IO_ReadOnly);
-
- s >> info;
-
- d->currentItem->current()->setMetaInfo(info);
- emit gotMetaInfo(d->currentItem->current());
- d->succeeded = true;
-}
-
-TQStringList MetaInfoJob::availablePlugins()
-{
- TQStringList result;
- KTrader::OfferList plugins = KTrader::self()->query("KFilePlugin");
- for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
- result.append((*it)->desktopEntryName());
- return result;
-}
-
-TQStringList MetaInfoJob::supportedMimeTypes()
-{
- TQStringList result;
- KTrader::OfferList plugins = KTrader::self()->query("KFilePlugin");
- for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
- result += (*it)->property("MimeTypes").toStringList();
- return result;
-}
-
-TDEIO_EXPORT MetaInfoJob *TDEIO::fileMetaInfo( const KFileItemList &items)
-{
- return new MetaInfoJob(items, false);
-}
-
-TDEIO_EXPORT MetaInfoJob *TDEIO::fileMetaInfo( const KURL::List &items)
-{
- KFileItemList fileItems;
- for (KURL::List::ConstIterator it = items.begin(); it != items.end(); ++it)
- fileItems.append(new KFileItem(KFileItem::Unknown, KFileItem::Unknown, *it, true));
- return new MetaInfoJob(fileItems, true);
-}
-
diff --git a/kio/kio/metainfojob.h b/kio/kio/metainfojob.h
deleted file mode 100644
index e2152bded..000000000
--- a/kio/kio/metainfojob.h
+++ /dev/null
@@ -1,119 +0,0 @@
-// -*- c++ -*-
-// vim: ts=4 sw=4 et
-/* This file is part of the KDE libraries
- Copyright (C) 2001 Rolf Magnus <ramagnus@kde.org>
- parts of this taken from previewjob.h
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation version 2.0.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_metainfojob_h__
-#define __kio_metainfojob_h__
-
-#include <kio/job.h>
-#include <kfileitem.h>
-
-namespace TDEIO {
- /**
- * MetaInfoJob is a KIO Job to retrieve meta information from files.
- *
- * @short KIO Job to retrieve meta information from files.
- * @since 3.1
- */
- class TDEIO_EXPORT MetaInfoJob : public TDEIO::Job
- {
- Q_OBJECT
- public:
- /**
- * Creates a new MetaInfoJob.
- * @param items A list of KFileItems to get the metainfo for
- * @param deleteItems If true, the finished KFileItems are deleted
- */
- MetaInfoJob(const KFileItemList &items, bool deleteItems = false);
- virtual ~MetaInfoJob();
-
- /**
- * Removes an item from metainfo extraction.
- *
- * @param item the item that should be removed from the queue
- */
- void removeItem( const KFileItem *item );
-
- /**
- * Returns a list of all available metainfo plugins. The list
- * contains the basenames of the plugins' .desktop files (no path,
- * no .desktop).
- * @return the list of available meta info plugins
- */
- static TQStringList availablePlugins();
-
- /**
- * Returns a list of all supported MIME types. The list can
- * contain entries like text/ * (without the space).
- * @return the list of MIME types that are supported
- */
- static TQStringList supportedMimeTypes();
-
- signals:
- /**
- * Emitted when the meta info for @p item has been successfully
- * retrieved.
- * @param item the KFileItem describing the fetched item
- */
- void gotMetaInfo( const KFileItem *item );
- /**
- * Emitted when metainfo for @p item could not be extracted,
- * either because a plugin for its MIME type does not
- * exist, or because something went wrong.
- * @param item the KFileItem of the file that failed
- */
- void failed( const KFileItem *item );
-
- protected:
- void getMetaInfo();
-
- protected slots:
- virtual void slotResult( TDEIO::Job *job );
-
- private slots:
- void start();
- void slotMetaInfo(TDEIO::Job *, const TQByteArray &);
-
- private:
- void determineNextFile();
-// void saveMetaInfo(const TQByteArray info);
-
- private:
- struct MetaInfoJobPrivate *d;
- };
-
- /**
- * Retrieves meta information for the given items.
- *
- * @param items files to get metainfo for
- * @return the MetaInfoJob to retrieve the items
- */
- TDEIO_EXPORT MetaInfoJob* fileMetaInfo(const KFileItemList& items);
-
- /**
- * Retrieves meta information for the given items.
- *
- * @param items files to get metainfo for
- * @return the MetaInfoJob to retrieve the items
- */
- TDEIO_EXPORT MetaInfoJob* fileMetaInfo(const KURL::List& items);
-}
-
-#endif
diff --git a/kio/kio/netaccess.cpp b/kio/kio/netaccess.cpp
deleted file mode 100644
index 11c20be49..000000000
--- a/kio/kio/netaccess.cpp
+++ /dev/null
@@ -1,536 +0,0 @@
-/* $Id$
-
- This file is part of the KDE libraries
- Copyright (C) 1997 Torben Weis (weis@kde.org)
- Copyright (C) 1998 Matthias Ettrich (ettrich@kde.org)
- Copyright (C) 1999 David Faure (faure@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <signal.h>
-#include <unistd.h>
-
-#include <cstring>
-
-#include <tqstring.h>
-#include <tqapplication.h>
-#include <tqfile.h>
-#include <tqmetaobject.h>
-
-#include <kapplication.h>
-#include <klocale.h>
-#include <ktempfile.h>
-#include <kdebug.h>
-#include <kurl.h>
-#include <kio/job.h>
-#include <kio/scheduler.h>
-
-#include "kio/netaccess.h"
-
-using namespace TDEIO;
-
-TQString * NetAccess::lastErrorMsg;
-int NetAccess::lastErrorCode = 0;
-TQStringList* NetAccess::tmpfiles;
-
-bool NetAccess::download(const KURL& u, TQString & target)
-{
- return NetAccess::download (u, target, 0);
-}
-
-bool NetAccess::download(const KURL& u, TQString & target, TQWidget* window)
-{
- if (u.isLocalFile()) {
- // file protocol. We do not need the network
- target = u.path();
- bool accessible = checkAccess(target, R_OK);
- if(!accessible)
- {
- if(!lastErrorMsg)
- lastErrorMsg = new TQString;
- *lastErrorMsg = i18n("File '%1' is not readable").arg(target);
- lastErrorCode = ERR_COULD_NOT_READ;
- }
- return accessible;
- }
-
- if (target.isEmpty())
- {
- KTempFile tmpFile;
- target = tmpFile.name();
- if (!tmpfiles)
- tmpfiles = new TQStringList;
- tmpfiles->append(target);
- }
-
- NetAccess kioNet;
- KURL dest;
- dest.setPath( target );
- return kioNet.filecopyInternal( u, dest, -1, true /*overwrite*/,
- false, window, false /*copy*/);
-}
-
-bool NetAccess::upload(const TQString& src, const KURL& target)
-{
- return NetAccess::upload(src, target, 0);
-}
-
-bool NetAccess::upload(const TQString& src, const KURL& target, TQWidget* window)
-{
- if (target.isEmpty())
- return false;
-
- // If target is local... well, just copy. This can be useful
- // when the client code uses a temp file no matter what.
- // Let's make sure it's not the exact same file though
- if (target.isLocalFile() && target.path() == src)
- return true;
-
- NetAccess kioNet;
- KURL s;
- s.setPath(src);
- return kioNet.filecopyInternal( s, target, -1, true /*overwrite*/,
- false, window, false /*copy*/ );
-}
-
-bool NetAccess::copy( const KURL & src, const KURL & target )
-{
- return NetAccess::file_copy( src, target, -1, false /*not overwrite*/, false, 0L );
-}
-
-bool NetAccess::copy( const KURL & src, const KURL & target, TQWidget* window )
-{
- return NetAccess::file_copy( src, target, -1, false /*not overwrite*/, false, window );
-}
-
-bool NetAccess::file_copy( const KURL& src, const KURL& target, int permissions,
- bool overwrite, bool resume, TQWidget* window )
-{
- NetAccess kioNet;
- return kioNet.filecopyInternal( src, target, permissions, overwrite, resume,
- window, false /*copy*/ );
-}
-
-
-bool NetAccess::file_move( const KURL& src, const KURL& target, int permissions,
- bool overwrite, bool resume, TQWidget* window )
-{
- NetAccess kioNet;
- return kioNet.filecopyInternal( src, target, permissions, overwrite, resume,
- window, true /*move*/ );
-}
-
-bool NetAccess::dircopy( const KURL & src, const KURL & target )
-{
- return NetAccess::dircopy( src, target, 0 );
-}
-
-bool NetAccess::dircopy( const KURL & src, const KURL & target, TQWidget* window )
-{
- KURL::List srcList;
- srcList.append( src );
- return NetAccess::dircopy( srcList, target, window );
-}
-
-bool NetAccess::dircopy( const KURL::List & srcList, const KURL & target, TQWidget* window )
-{
- NetAccess kioNet;
- return kioNet.dircopyInternal( srcList, target, window, false /*copy*/ );
-}
-
-bool NetAccess::move( const KURL& src, const KURL& target, TQWidget* window )
-{
- KURL::List srcList;
- srcList.append( src );
- return NetAccess::move( srcList, target, window );
-}
-
-bool NetAccess::move( const KURL::List& srcList, const KURL& target, TQWidget* window )
-{
- NetAccess kioNet;
- return kioNet.dircopyInternal( srcList, target, window, true /*move*/ );
-}
-
-bool NetAccess::exists( const KURL & url )
-{
- return NetAccess::exists( url, false, 0 );
-}
-
-bool NetAccess::exists( const KURL & url, TQWidget* window )
-{
- return NetAccess::exists( url, false, window );
-}
-
-bool NetAccess::exists( const KURL & url, bool source )
-{
- return NetAccess::exists( url, source, 0 );
-}
-
-bool NetAccess::exists( const KURL & url, bool source, TQWidget* window )
-{
- if ( url.isLocalFile() )
- return TQFile::exists( url.path() );
- NetAccess kioNet;
- return kioNet.statInternal( url, 0 /*no details*/, source, window );
-}
-
-bool NetAccess::stat( const KURL & url, TDEIO::UDSEntry & entry )
-{
- return NetAccess::stat( url, entry, 0 );
-}
-
-bool NetAccess::stat( const KURL & url, TDEIO::UDSEntry & entry, TQWidget* window )
-{
- NetAccess kioNet;
- bool ret = kioNet.statInternal( url, 2 /*all details*/, true /*source*/, window );
- if (ret)
- entry = kioNet.m_entry;
- return ret;
-}
-
-KURL NetAccess::mostLocalURL(const KURL & url, TQWidget* window)
-{
- if ( url.isLocalFile() )
- {
- return url;
- }
-
- TDEIO::UDSEntry entry;
- if (!stat(url, entry, window))
- {
- return url;
- }
-
- TQString path;
-
- // Extract the local path from the TDEIO::UDSEntry
- TDEIO::UDSEntry::ConstIterator it = entry.begin();
- const TDEIO::UDSEntry::ConstIterator end = entry.end();
- for ( ; it != end; ++it )
- {
- if ( (*it).m_uds == TDEIO::UDS_LOCAL_PATH )
- {
- path = (*it).m_str;
- break;
- }
- }
-
- if ( !path.isEmpty() )
- {
- KURL new_url;
- new_url.setPath(path);
- return new_url;
- }
-
- return url;
-}
-
-
-bool NetAccess::del( const KURL & url )
-{
- return NetAccess::del( url, 0 );
-}
-
-bool NetAccess::del( const KURL & url, TQWidget* window )
-{
- NetAccess kioNet;
- return kioNet.delInternal( url, window );
-}
-
-bool NetAccess::mkdir( const KURL & url, int permissions )
-{
- return NetAccess::mkdir( url, 0, permissions );
-}
-
-bool NetAccess::mkdir( const KURL & url, TQWidget* window, int permissions )
-{
- NetAccess kioNet;
- return kioNet.mkdirInternal( url, permissions, window );
-}
-
-TQString NetAccess::fish_execute( const KURL & url, const TQString command, TQWidget* window )
-{
- NetAccess kioNet;
- return kioNet.fish_executeInternal( url, command, window );
-}
-
-bool NetAccess::synchronousRun( Job* job, TQWidget* window, TQByteArray* data,
- KURL* finalURL, TQMap<TQString, TQString>* metaData )
-{
- NetAccess kioNet;
- return kioNet.synchronousRunInternal( job, window, data, finalURL, metaData );
-}
-
-TQString NetAccess::mimetype( const KURL& url )
-{
- NetAccess kioNet;
- return kioNet.mimetypeInternal( url, 0 );
-}
-
-TQString NetAccess::mimetype( const KURL& url, TQWidget* window )
-{
- NetAccess kioNet;
- return kioNet.mimetypeInternal( url, window );
-}
-
-void NetAccess::removeTempFile(const TQString& name)
-{
- if (!tmpfiles)
- return;
- if (tmpfiles->contains(name))
- {
- unlink(TQFile::encodeName(name));
- tmpfiles->remove(name);
- }
-}
-
-bool NetAccess::filecopyInternal(const KURL& src, const KURL& target, int permissions,
- bool overwrite, bool resume, TQWidget* window, bool move)
-{
- bJobOK = true; // success unless further error occurs
-
- TDEIO::Scheduler::checkSlaveOnHold(true);
- TDEIO::Job * job = move
- ? TDEIO::file_move( src, target, permissions, overwrite, resume )
- : TDEIO::file_copy( src, target, permissions, overwrite, resume );
- job->setWindow (window);
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
-
- enter_loop();
- return bJobOK;
-}
-
-bool NetAccess::dircopyInternal(const KURL::List& src, const KURL& target,
- TQWidget* window, bool move)
-{
- bJobOK = true; // success unless further error occurs
-
- TDEIO::Job * job = move
- ? TDEIO::move( src, target )
- : TDEIO::copy( src, target );
- job->setWindow (window);
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
-
- enter_loop();
- return bJobOK;
-}
-
-bool NetAccess::statInternal( const KURL & url, int details, bool source,
- TQWidget* window )
-{
- bJobOK = true; // success unless further error occurs
- TDEIO::StatJob * job = TDEIO::stat( url, !url.isLocalFile() && !url.url().startsWith("beagle:?") );
- job->setWindow (window);
- job->setDetails( details );
- job->setSide( source );
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
- enter_loop();
- return bJobOK;
-}
-
-bool NetAccess::delInternal( const KURL & url, TQWidget* window )
-{
- bJobOK = true; // success unless further error occurs
- TDEIO::Job * job = TDEIO::del( url );
- job->setWindow (window);
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
- enter_loop();
- return bJobOK;
-}
-
-bool NetAccess::mkdirInternal( const KURL & url, int permissions,
- TQWidget* window )
-{
- bJobOK = true; // success unless further error occurs
- TDEIO::Job * job = TDEIO::mkdir( url, permissions );
- job->setWindow (window);
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
- enter_loop();
- return bJobOK;
-}
-
-TQString NetAccess::mimetypeInternal( const KURL & url, TQWidget* window )
-{
- bJobOK = true; // success unless further error occurs
- m_mimetype = TQString::fromLatin1("unknown");
- TDEIO::Job * job = TDEIO::mimetype( url );
- job->setWindow (window);
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
- connect( job, TQT_SIGNAL( mimetype (TDEIO::Job *, const TQString &) ),
- this, TQT_SLOT( slotMimetype (TDEIO::Job *, const TQString &) ) );
- enter_loop();
- return m_mimetype;
-}
-
-void NetAccess::slotMimetype( TDEIO::Job *, const TQString & type )
-{
- m_mimetype = type;
-}
-
-TQString NetAccess::fish_executeInternal(const KURL & url, const TQString command, TQWidget* window)
-{
- TQString target, remoteTempFileName, resultData;
- KURL tempPathUrl;
- KTempFile tmpFile;
- tmpFile.setAutoDelete( true );
-
- if( url.protocol() == "fish" )
- {
- // construct remote temp filename
- tempPathUrl = url;
- remoteTempFileName = tmpFile.name();
- // only need the filename KTempFile adds some KDE specific dirs
- // that probably does not exist on the remote side
- int pos = remoteTempFileName.findRev('/');
- remoteTempFileName = "/tmp/fishexec_" + remoteTempFileName.mid(pos + 1);
- tempPathUrl.setPath( remoteTempFileName );
- bJobOK = true; // success unless further error occurs
- TQByteArray packedArgs;
- TQDataStream stream( packedArgs, IO_WriteOnly );
-
- stream << int('X') << tempPathUrl << command;
-
- TDEIO::Job * job = TDEIO::special( tempPathUrl, packedArgs, true );
- job->setWindow( window );
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
- enter_loop();
-
- // since the TDEIO::special does not provide feedback we need to download the result
- if( NetAccess::download( tempPathUrl, target, window ) )
- {
- TQFile resultFile( target );
-
- if (resultFile.open( IO_ReadOnly ))
- {
- TQTextStream ts( &resultFile );
- ts.setEncoding( TQTextStream::Locale ); // Locale??
- resultData = ts.read();
- resultFile.close();
- NetAccess::del( tempPathUrl, window );
- }
- }
- }
- else
- {
- resultData = i18n( "ERROR: Unknown protocol '%1'" ).arg( url.protocol() );
- }
- return resultData;
-}
-
-bool NetAccess::synchronousRunInternal( Job* job, TQWidget* window, TQByteArray* data,
- KURL* finalURL, TQMap<TQString,TQString>* metaData )
-{
- job->setWindow( window );
-
- m_metaData = metaData;
- if ( m_metaData ) {
- for ( TQMap<TQString, TQString>::iterator it = m_metaData->begin(); it != m_metaData->end(); ++it ) {
- job->addMetaData( it.key(), it.data() );
- }
- }
-
- if ( finalURL ) {
- SimpleJob *sj = dynamic_cast<SimpleJob*>( job );
- if ( sj ) {
- m_url = sj->url();
- }
- }
-
- connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
- this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
-
- TQMetaObject *meta = job->metaObject();
-
- static const char dataSignal[] = "data(TDEIO::Job*,const " TQBYTEARRAY_OBJECT_NAME_STRING "&)";
- if ( meta->findSignal( dataSignal ) != -1 ) {
- connect( job, TQT_SIGNAL(data(TDEIO::Job*,const TQByteArray&)),
- this, TQT_SLOT(slotData(TDEIO::Job*,const TQByteArray&)) );
- }
-
- static const char redirSignal[] = "redirection(TDEIO::Job*,const KURL&)";
- if ( meta->findSignal( redirSignal ) != -1 ) {
- connect( job, TQT_SIGNAL(redirection(TDEIO::Job*,const KURL&)),
- this, TQT_SLOT(slotRedirection(TDEIO::Job*, const KURL&)) );
- }
-
- enter_loop();
-
- if ( finalURL )
- *finalURL = m_url;
- if ( data )
- *data = m_data;
-
- return bJobOK;
-}
-
-// If a troll sees this, he kills me
-void tqt_enter_modal( TQWidget *widget );
-void tqt_leave_modal( TQWidget *widget );
-
-void NetAccess::enter_loop()
-{
- TQWidget dummy(0,0,(WFlags)(WType_Dialog | WShowModal));
- dummy.setFocusPolicy( TQ_NoFocus );
- tqt_enter_modal(&dummy);
- tqApp->enter_loop();
- tqt_leave_modal(&dummy);
-}
-
-void NetAccess::slotResult( TDEIO::Job * job )
-{
- lastErrorCode = job->error();
- bJobOK = !job->error();
- if ( !bJobOK )
- {
- if ( !lastErrorMsg )
- lastErrorMsg = new TQString;
- *lastErrorMsg = job->errorString();
- }
- if ( job->isA("TDEIO::StatJob") )
- m_entry = static_cast<TDEIO::StatJob *>(job)->statResult();
-
- if ( m_metaData )
- *m_metaData = job->metaData();
-
- tqApp->exit_loop();
-}
-
-void NetAccess::slotData( TDEIO::Job*, const TQByteArray& data )
-{
- if ( data.isEmpty() )
- return;
-
- unsigned offset = m_data.size();
- m_data.resize( offset + data.size() );
- std::memcpy( m_data.data() + offset, data.data(), data.size() );
-}
-
-void NetAccess::slotRedirection( TDEIO::Job*, const KURL& url )
-{
- m_url = url;
-}
-
-#include "netaccess.moc"
diff --git a/kio/kio/netaccess.h b/kio/kio/netaccess.h
deleted file mode 100644
index 54dd02974..000000000
--- a/kio/kio/netaccess.h
+++ /dev/null
@@ -1,540 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (C) 1997 Torben Weis (weis@kde.org)
- Copyright (C) 1998 Matthias Ettrich (ettrich@kde.org)
- Copyright (C) 1999-2004 David Faure (faure@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_netaccess_h
-#define __kio_netaccess_h
-
-#include <tqobject.h>
-#include <tqstring.h>
-#include <kio/global.h>
-
-class TQStringList;
-class TQWidget;
-class KURL;
-template<typename T, typename K> class TQMap;
-
-namespace TDEIO {
-
- class Job;
-
- /**
- * Net Transparency.
- *
- * NetAccess allows you to do simple file operation (load, save,
- * copy, delete...) without working with TDEIO::Job directly.
- * Whereas a TDEIO::Job is asynchronous, meaning that the
- * developer has to connect slots for it, TDEIO::NetAccess provides
- * synchronous downloads and uploads, as well as temporary file
- * creation and removal. The functions appear to be blocking,
- * but the Qt event loop continues running while the operations
- * are handled. This means that the GUI will not freeze.
- *
- * This class isn't meant to be used as a class but only as a simple
- * namespace for static functions, though an instance of the class
- * is built for internal purposes.
- *
- * Port to kio done by David Faure, faure@kde.org
- *
- * @short Provides an easy, synchronous interface to KIO file operations.
- */
-class TDEIO_EXPORT NetAccess : public TQObject
-{
- Q_OBJECT
-
-public:
- /**
- * Downloads a file from an arbitrary URL (@p src) to a
- * temporary file on the local filesystem (@p target).
- *
- * If the argument
- * for @p target is an empty string, download will generate a
- * unique temporary filename in /tmp. Since @p target is a reference
- * to TQString you can access this filename easily. Download will
- * return true if the download was successful, otherwise false.
- *
- * Special case:
- * If the URL is of kind file:, then no downloading is
- * processed but the full filename is returned in @p target.
- * That means you @em have to take care about the @p target argument.
- * (This is very easy to do, please see the example below.)
- *
- * Download is synchronous. That means you can use it like
- * this, (assuming @p u is a string which represents a URL and your
- * application has a loadFile() function):
- *
- * \code
- * TQString tmpFile;
- * if( TDEIO::NetAccess::download( u, tmpFile, window ) )
- * {
- * loadFile( tmpFile );
- * TDEIO::NetAccess::removeTempFile( tmpFile );
- * } else {
- * KMessageBox::error(this, TDEIO::NetAccess::lastErrorString() );
- * }
- * \endcode
- *
- * Of course, your user interface will still process exposure/repaint
- * events during the download.
- *
- * If the download fails, lastError() and lastErrorString() will be set.
- *
- * @param src URL Reference to the file to download.
- * @param target String containing the final local location of the
- * file. If you insert an empty string, it will
- * return a location in a temporary spot. <B>Note:</B>
- * you are responsible for the removal of this file when
- * you are finished reading it using removeTempFile.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @return true if successful, false for failure. Use lastErrorString() to
- * get the reason it failed.
- *
- * @see lastErrorString()
- * @since 3.2
- */
- static bool download(const KURL& src, TQString & target, TQWidget* window);
-
- /**
- * @deprecated. Use the function above instead.
- */
- static bool download(const KURL& src, TQString & target) KDE_DEPRECATED;
-
- /**
- * Removes the specified file if and only if it was created
- * by TDEIO::NetAccess as a temporary file for a former download.
- *
- * Note: This means that if you created your temporary with KTempFile,
- * use KTempFile::unlink() or KTempFile::setAutoDelete() to have
- * it removed.
- *
- * @param name Path to temporary file to remove. May not be
- * empty.
- */
- static void removeTempFile(const TQString& name);
-
- /**
- * Uploads file @p src to URL @p target.
- *
- * Both must be specified, unlike download.
- * Note that this is assumed to be used for saving a file over
- * the network, so overwriting is set to true. This is not the
- * case with copy.
- *
- * @param src URL Referencing the file to upload.
- * @param target URL containing the final location of the file.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be cached
- * only for a short duration after which the user will again be
- * prompted for passwords as needed.
- *
- * @return true if successful, false for failure
- * @since 3.2
- */
- static bool upload(const TQString& src, const KURL& target, TQWidget* window);
-
- /**
- * @deprecated. Use the function above instead.
- */
- static bool upload(const TQString& src, const KURL& target) KDE_DEPRECATED;
-
- /**
- * Alternative to upload for copying over the network.
- * Overwrite is false, so this will fail if @p target exists.
- *
- * This one takes two URLs and is a direct equivalent
- * of TDEIO::file_copy (not TDEIO::copy!).
- * It will be renamed file_copy in KDE4, so better use file_copy.
- *
- * @param src URL Referencing the file to upload.
- * @param target URL containing the final location of the file.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be cached
- * only for a short duration after which the user will again be
- * prompted for passwords as needed.
- *
- * @return true if successful, false for failure
- */
- static bool copy( const KURL& src, const KURL& target, TQWidget* window );
- // KDE4: rename to file_copy
-
- /**
- * @deprecated. Use the function above instead.
- */
- static bool copy( const KURL& src, const KURL& target ) KDE_DEPRECATED;
- // KDE4: merge with above
-
- /**
- * Full-fledged equivalent of TDEIO::file_copy
- */
- static bool file_copy( const KURL& src, const KURL& dest, int permissions=-1,
- bool overwrite=false, bool resume=false, TQWidget* window = 0L );
-
- /**
- * Full-fledged equivalent of TDEIO::file_move.
- * Moves or renames *one file*.
- * @since 3.2
- */
- static bool file_move( const KURL& src, const KURL& target, int permissions=-1,
- bool overwrite=false, bool resume=false, TQWidget* window = 0L );
-
-
- /**
- * Alternative method for copying over the network.
- * Overwrite is false, so this will fail if @p target exists.
- *
- * This one takes two URLs and is a direct equivalent
- * of TDEIO::copy!.
- * This means that it can copy files and directories alike
- * (it should have been named copy()).
- *
- * @param src URL Referencing the file to upload.
- * @param target URL containing the final location of the
- * file.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be cached
- * only for a short duration after which the user will again be
- * prompted for passwords as needed.
- * @return true if successful, false for failure
- */
- static bool dircopy( const KURL& src, const KURL& target, TQWidget* window );
-
- /**
- * @deprecated. Use the function above instead.
- */
- static bool dircopy( const KURL& src, const KURL& target ) KDE_DEPRECATED; // KDE4: merge
-
- /**
- * Overloaded method, which takes a list of source URLs
- */
- static bool dircopy( const KURL::List& src, const KURL& target, TQWidget* window = 0L );
-
- /**
- * Full-fledged equivalent of TDEIO::move.
- * Moves or renames one file or directory.
- * @since 3.2
- */
- static bool move( const KURL& src, const KURL& target, TQWidget* window = 0L );
-
- /**
- * Full-fledged equivalent of TDEIO::move.
- * Moves or renames a list of files or directories.
- * @since 3.2
- */
- static bool move( const KURL::List& src, const KURL& target, TQWidget* window = 0L );
-
- /**
- * Tests whether a URL exists.
- *
- * @param url the URL we are testing
- * @param source if true, we want to read from that URL.
- * If false, we want to write to it.
- * IMPORTANT: see documentation for TDEIO::stat for more details about this.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @return true if the URL exists and we can do the operation specified by
- * @p source, false otherwise
- * @since 3.2
- */
- static bool exists(const KURL& url, bool source, TQWidget* window);
-
- /**
- * @deprecated. Use the function above instead.
- * @since 3.2
- */
- static bool exists(const KURL& url, TQWidget* window) KDE_DEPRECATED;
-
- /**
- * @deprecated. Use the function above instead.
- */
- static bool exists(const KURL& url) KDE_DEPRECATED;
-
- /**
- * @deprecated. Use the function above instead.
- */
- static bool exists(const KURL& url, bool source) KDE_DEPRECATED; // KDE4: merge
-
- /**
- * Tests whether a URL exists and return information on it.
- *
- * This is a convenience function for TDEIO::stat
- * (it saves creating a slot and testing for the job result).
- *
- * @param url The URL we are testing.
- * @param entry The result of the stat. Iterate over the list
- * of atoms to get hold of name, type, size, etc., or use KFileItem.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @return true if successful, false for failure
- */
- static bool stat(const KURL& url, TDEIO::UDSEntry & entry, TQWidget* window);
-
- /**
- * @deprecated. Use the function above instead.
- */
- static bool stat(const KURL& url, TDEIO::UDSEntry & entry) KDE_DEPRECATED;
-
- /**
- * Tries to map a local URL for the given URL.
- *
- * This is a convenience function for TDEIO::stat + parsing the
- * resulting UDSEntry.
- *
- * @param url The URL we are testing.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @return a local URL corresponding to the same ressource than the
- * original URL, or the original URL if no local URL can be mapped
- * @since 3.5
- */
- static KURL mostLocalURL(const KURL& url, TQWidget* window);
-
- /**
- * Deletes a file or a directory in a synchronous way.
- *
- * This is a convenience function for TDEIO::del
- * (it saves creating a slot and testing for the job result).
- *
- * @param url The file or directory to delete.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @return true on success, false on failure.
- */
- static bool del( const KURL & url, TQWidget* window );
-
- /**
- * @deprecated. Use the function above instead. Passing NULL as the
- * additional argument will give the same behaviour, but
- * you should try to identify a suitable parent widget
- * if at all possible.
- */
- static bool del( const KURL & url ) KDE_DEPRECATED;
-
- /**
- * Creates a directory in a synchronous way.
- *
- * This is a convenience function for @p TDEIO::mkdir
- * (it saves creating a slot and testing for the job result).
- *
- * @param url The directory to create.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @param permissions directory permissions.
- * @return true on success, false on failure.
- */
- static bool mkdir( const KURL & url, TQWidget* window, int permissions = -1 );
-
- /**
- * @deprecated. Use the function above instead. Passing NULL as the
- * additional argument will give the same behaviour, but
- * you should try to identify a suitable parent widget
- * if at all possible.
- */
- static bool mkdir( const KURL & url, int permissions = -1 ) KDE_DEPRECATED;
-
- /**
- * Executes a remote process via the fish ioslave in a synchronous way.
- *
- * @param url The remote machine where the command should be executed.
- * e.g. fish://someuser\@somehost:sshport/
- * some special cases exist.
- * fish://someuser\@localhost/
- * will use su instead of ssh to connect and execute the command.
- * fish://someuser\@localhost:port/
- * will use ssh to connect and execute the command.
- * @param command The command to be executed.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @return The resulting output of the @p command that is executed.
- */
- static TQString fish_execute( const KURL & url, const TQString command, TQWidget* window );
-
- /**
- * This function executes a job in a synchronous way.
- * If a job fetches some data, pass a TQByteArray pointer as data parameter to this function
- * and after the function returns it will contain all the data fetched by this job.
- *
- * <code>
- * TDEIO::Job *job = TDEIO::get( url, false, false );
- * TQMap<TQString, TQString> metaData;
- * metaData.insert( "PropagateHttpHeader", "true" );
- * if ( NetAccess::synchronousRun( job, 0, &data, &url, &metaData ) ) {
- * TQString responseHeaders = metaData[ "HTTP-Headers" ];
- * kdDebug()<<"Response header = "<< responseHeaders << endl;
- * }
- * </code>
- *
- * @param job job which the function will run. Note that after this function
- * finishes running, job is deleted and you can't access it anymore!
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @param data if passed and relevant to this job then it will contain the data
- * that was fetched by the job
- * @param finalURL if passed will contain the final url of this job (it might differ
- * from the one it was created with if there was a redirection)
- * @param metaData you can pass a pointer to the map with meta data you wish to
- * set on the job. After the job finishes this map will hold all the
- * meta data from the job.
- *
- * @return true on success, false on failure.
- *
- * @since 3.4
- */
- static bool synchronousRun( Job* job, TQWidget* window, TQByteArray* data=0,
- KURL* finalURL=0, TQMap<TQString,TQString>* metaData=0 );
-
- /**
- * @internal
- * This function is not implemented!?
- * (only mimetypeInternal)
- *
- * Determines the mimetype of a given URL.
- *
- * This is a convenience function for TDEIO::mimetype. You
- * should call this only when really necessary.
- * KMimeType::findByURL can determine extension a lot faster, but
- * less reliably for remote files. Only when findByURL() returns
- * unknown (application/octet-stream) then this one should be
- * used.
- *
- * @param url The URL whose mimetype we are interested in.
- * @param window main window associated with this job. This is used to
- * automatically cache and discard authentication information
- * as needed. If NULL, authentication information will be
- * cached only for a short duration after which the user will
- * again be prompted for passwords as needed.
- * @return The mimetype name.
- */
- static TQString mimetype( const KURL & url, TQWidget* window );
-
- /**
- * @deprecated. Use the function above instead. Passing NULL as the
- * additional argument will give the same behaviour, but
- * you should try to identify a suitable parent widget
- * if at all possible.
- */
- static TQString mimetype( const KURL & url ) KDE_DEPRECATED;
-
- /**
- * Returns the error string for the last job, in case it failed.
- * Note that this is already translated.
- * @return the last error string, or TQString::null
- */
- static TQString lastErrorString() { return lastErrorMsg ? *lastErrorMsg : TQString::null; }
-
- /**
- * Returns the error code for the last job, in case it failed.
- * @return the last error code
- * @since 3.3
- */
- static int lastError() { return lastErrorCode; }
-
-private:
- /**
- * Private constructor
- */
- NetAccess() : m_metaData(0), d(0) {}
-
- /**
- * Private destructor
- */
- ~NetAccess() {}
-
- /**
- * Internal methods
- */
- bool filecopyInternal(const KURL& src, const KURL& target, int permissions,
- bool overwrite, bool resume, TQWidget* window, bool move);
- bool dircopyInternal(const KURL::List& src, const KURL& target,
- TQWidget* window, bool move);
- bool statInternal(const KURL & url, int details, bool source, TQWidget* window = 0);
-
- bool delInternal(const KURL & url, TQWidget* window = 0);
- bool mkdirInternal(const KURL & url, int permissions, TQWidget* window = 0);
- TQString fish_executeInternal(const KURL & url, const TQString command, TQWidget* window = 0);
- bool synchronousRunInternal( Job* job, TQWidget* window, TQByteArray* data,
- KURL* finalURL, TQMap<TQString,TQString>* metaData );
-
- TQString mimetypeInternal(const KURL & url, TQWidget* window = 0);
- void enter_loop();
-
- /**
- * List of temporary files
- */
- static TQStringList* tmpfiles;
-
- static TQString* lastErrorMsg;
- static int lastErrorCode;
-
- friend class I_like_this_class;
-
-private slots:
- void slotResult( TDEIO::Job * job );
- void slotMimetype( TDEIO::Job * job, const TQString & type );
- void slotData( TDEIO::Job*, const TQByteArray& );
- void slotRedirection( TDEIO::Job*, const KURL& );
-
-private:
- UDSEntry m_entry;
- TQString m_mimetype;
- TQByteArray m_data;
- KURL m_url;
- TQMap<TQString, TQString> *m_metaData;
-
- /**
- * Whether the download succeeded or not
- */
- bool bJobOK;
-
-private:
- class NetAccessPrivate* d; // not really needed, the ctor is private already.
-};
-
-}
-
-#endif
diff --git a/kio/kio/observer.cpp b/kio/kio/observer.cpp
deleted file mode 100644
index 347db9df9..000000000
--- a/kio/kio/observer.cpp
+++ /dev/null
@@ -1,417 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Matej Koss <koss@miesto.sk>
- David Faure <faure@kde.org>
-
- $Id$
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <assert.h>
-
-#include <kdebug.h>
-#include <kapplication.h>
-#include <dcopclient.h>
-#include <kurl.h>
-
-#include "jobclasses.h"
-#include "observer.h"
-
-#include "uiserver_stub.h"
-
-#include "passdlg.h"
-#include "slavebase.h"
-#include "observer_stub.h"
-#include <kmessagebox.h>
-#include <ksslinfodlg.h>
-#include <ksslcertdlg.h>
-#include <ksslcertificate.h>
-#include <ksslcertchain.h>
-#include <klocale.h>
-
-using namespace TDEIO;
-
-template class TQIntDict<TDEIO::Job>;
-
-Observer * Observer::s_pObserver = 0L;
-
-const int KDEBUG_OBSERVER = 7007; // Should be 7028
-
-Observer::Observer() : DCOPObject("TDEIO::Observer")
-{
- // Register app as able to receive DCOP messages
- if (kapp && !kapp->dcopClient()->isAttached())
- {
- kapp->dcopClient()->attach();
- }
-
- if ( !kapp->dcopClient()->isApplicationRegistered( "kio_uiserver" ) )
- {
- kdDebug(KDEBUG_OBSERVER) << "Starting kio_uiserver" << endl;
- TQString error;
- int ret = TDEApplication::startServiceByDesktopPath( "kio_uiserver.desktop",
- TQStringList(), &error );
- if ( ret > 0 )
- {
- kdError() << "Couldn't start kio_uiserver from kio_uiserver.desktop: " << error << endl;
- } else
- kdDebug(KDEBUG_OBSERVER) << "startServiceByDesktopPath returned " << ret << endl;
-
- }
- if ( !kapp->dcopClient()->isApplicationRegistered( "kio_uiserver" ) )
- kdDebug(KDEBUG_OBSERVER) << "The application kio_uiserver is STILL NOT REGISTERED" << endl;
- else
- kdDebug(KDEBUG_OBSERVER) << "kio_uiserver registered" << endl;
-
- m_uiserver = new UIServer_stub( "kio_uiserver", "UIServer" );
-}
-
-int Observer::newJob( TDEIO::Job * job, bool showProgress )
-{
- // Tell the UI Server about this new job, and give it the application id
- // at the same time
- int progressId = m_uiserver->newJob( kapp->dcopClient()->appId(), showProgress );
-
- // Keep the result in a dict
- m_dctJobs.insert( progressId, job );
-
- return progressId;
-}
-
-void Observer::jobFinished( int progressId )
-{
- m_uiserver->jobFinished( progressId );
- m_dctJobs.remove( progressId );
-}
-
-void Observer::killJob( int progressId )
-{
- TDEIO::Job * job = m_dctJobs[ progressId ];
- if (!job)
- {
- kdWarning() << "Can't find job to kill ! There is no job with progressId=" << progressId << " in this process" << endl;
- return;
- }
- job->kill( false /* not quietly */ );
-}
-
-MetaData Observer::metadata( int progressId )
-{
- TDEIO::Job * job = m_dctJobs[ progressId ];
- assert(job);
- return job->metaData();
-}
-
-void Observer::slotTotalSize( TDEIO::Job* job, TDEIO::filesize_t size )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTotalSize " << job << " " << TDEIO::number(size) << endl;
- m_uiserver->totalSize64( job->progressId(), size );
-}
-
-void Observer::slotTotalFiles( TDEIO::Job* job, unsigned long files )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTotalFiles " << job << " " << files << endl;
- m_uiserver->totalFiles( job->progressId(), files );
-}
-
-void Observer::slotTotalDirs( TDEIO::Job* job, unsigned long dirs )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTotalDirs " << job << " " << dirs << endl;
- m_uiserver->totalDirs( job->progressId(), dirs );
-}
-
-void Observer::slotProcessedSize( TDEIO::Job* job, TDEIO::filesize_t size )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotProcessedSize " << job << " " << job->progressId() << " " << TDEIO::number(size) << endl;
- m_uiserver->processedSize64( job->progressId(), size );
-}
-
-void Observer::slotProcessedFiles( TDEIO::Job* job, unsigned long files )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotProcessedFiles " << job << " " << files << endl;
- m_uiserver->processedFiles( job->progressId(), files );
-}
-
-void Observer::slotProcessedDirs( TDEIO::Job* job, unsigned long dirs )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotProcessedDirs " << job << " " << dirs << endl;
- m_uiserver->processedDirs( job->progressId(), dirs );
-}
-
-void Observer::slotSpeed( TDEIO::Job* job, unsigned long speed )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotSpeed " << job << " " << speed << endl;
- m_uiserver->speed( job->progressId(), speed );
-}
-
-void Observer::slotPercent( TDEIO::Job* job, unsigned long percent )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotPercent " << job << " " << percent << endl;
- m_uiserver->percent( job->progressId(), percent );
-}
-
-void Observer::slotInfoMessage( TDEIO::Job* job, const TQString & msg )
-{
- m_uiserver->infoMessage( job->progressId(), msg );
-}
-
-void Observer::slotCopying( TDEIO::Job* job, const KURL& from, const KURL& to )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotCopying " << job << " " << from.url() << " " << to.url() << endl;
- m_uiserver->copying( job->progressId(), from, to );
-}
-
-void Observer::slotMoving( TDEIO::Job* job, const KURL& from, const KURL& to )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotMoving " << job << " " << from.url() << " " << to.url() << endl;
- m_uiserver->moving( job->progressId(), from, to );
-}
-
-void Observer::slotDeleting( TDEIO::Job* job, const KURL& url )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotDeleting " << job << " " << url.url() << endl;
- m_uiserver->deleting( job->progressId(), url );
-}
-
-void Observer::slotTransferring( TDEIO::Job* job, const KURL& url )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTransferring " << job << " " << url.url() << endl;
- m_uiserver->transferring( job->progressId(), url );
-}
-
-void Observer::slotCreatingDir( TDEIO::Job* job, const KURL& dir )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotCreatingDir " << job << " " << dir.url() << endl;
- m_uiserver->creatingDir( job->progressId(), dir );
-}
-
-void Observer::slotCanResume( TDEIO::Job* job, TDEIO::filesize_t offset )
-{
- //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotCanResume " << job << " " << TDEIO::number(offset) << endl;
- m_uiserver->canResume64( job->progressId(), offset );
-}
-
-void Observer::stating( TDEIO::Job* job, const KURL& url )
-{
- m_uiserver->stating( job->progressId(), url );
-}
-
-void Observer::mounting( TDEIO::Job* job, const TQString & dev, const TQString & point )
-{
- m_uiserver->mounting( job->progressId(), dev, point );
-}
-
-void Observer::unmounting( TDEIO::Job* job, const TQString & point )
-{
- m_uiserver->unmounting( job->progressId(), point );
-}
-
-bool Observer::openPassDlg( const TQString& prompt, TQString& user,
- TQString& pass, bool readOnly )
-{
- AuthInfo info;
- info.prompt = prompt;
- info.username = user;
- info.password = pass;
- info.readOnly = readOnly;
- bool result = openPassDlg ( info );
- if ( result )
- {
- user = info.username;
- pass = info.password;
- }
- return result;
-}
-
-bool Observer::openPassDlg( TDEIO::AuthInfo& info )
-{
- kdDebug(KDEBUG_OBSERVER) << "Observer::openPassDlg: User= " << info.username
- << ", Message= " << info.prompt << endl;
- int result = TDEIO::PasswordDialog::getNameAndPassword( info.username, info.password,
- &info.keepPassword, info.prompt,
- info.readOnly, info.caption,
- info.comment, info.commentLabel );
- if ( result == TQDialog::Accepted )
- {
- info.setModified( true );
- return true;
- }
- return false;
-}
-
-int Observer::messageBox( int progressId, int type, const TQString &text,
- const TQString &caption, const TQString &buttonYes,
- const TQString &buttonNo )
-{
- return messageBox( progressId, type, text, caption, buttonYes, buttonNo, TQString::null );
-}
-
-int Observer::messageBox( int progressId, int type, const TQString &text,
- const TQString &caption, const TQString &buttonYes,
- const TQString &buttonNo, const TQString &dontAskAgainName )
-{
- kdDebug() << "Observer::messageBox " << type << " " << text << " - " << caption << endl;
- int result = -1;
- TDEConfig *config = new TDEConfig("kioslaverc");
- KMessageBox::setDontShowAskAgainConfig(config);
-
- switch (type) {
- case TDEIO::SlaveBase::QuestionYesNo:
- result = KMessageBox::questionYesNo( 0L, // parent ?
- text, caption, buttonYes, buttonNo, dontAskAgainName );
- break;
- case TDEIO::SlaveBase::WarningYesNo:
- result = KMessageBox::warningYesNo( 0L, // parent ?
- text, caption, buttonYes, buttonNo, dontAskAgainName );
- break;
- case TDEIO::SlaveBase::WarningContinueCancel:
- result = KMessageBox::warningContinueCancel( 0L, // parent ?
- text, caption, buttonYes, dontAskAgainName );
- break;
- case TDEIO::SlaveBase::WarningYesNoCancel:
- result = KMessageBox::warningYesNoCancel( 0L, // parent ?
- text, caption, buttonYes, buttonNo, dontAskAgainName );
- break;
- case TDEIO::SlaveBase::Information:
- KMessageBox::information( 0L, // parent ?
- text, caption, dontAskAgainName );
- result = 1; // whatever
- break;
- case TDEIO::SlaveBase::SSLMessageBox:
- {
- TQCString observerAppId = caption.utf8(); // hack, see slaveinterface.cpp
- // Contact the object "TDEIO::Observer" in the application <appId>
- // Yes, this could be the same application we are, but not necessarily.
- Observer_stub observer( observerAppId, "TDEIO::Observer" );
-
- TDEIO::MetaData meta = observer.metadata( progressId );
- KSSLInfoDlg *kid = new KSSLInfoDlg(meta["ssl_in_use"].upper()=="TRUE", 0L /*parent?*/, 0L, true);
- KSSLCertificate *x = KSSLCertificate::fromString(meta["ssl_peer_certificate"].local8Bit());
- if (x) {
- // Set the chain back onto the certificate
- TQStringList cl =
- TQStringList::split(TQString("\n"), meta["ssl_peer_chain"]);
- TQPtrList<KSSLCertificate> ncl;
-
- ncl.setAutoDelete(true);
- for (TQStringList::Iterator it = cl.begin(); it != cl.end(); ++it) {
- KSSLCertificate *y = KSSLCertificate::fromString((*it).local8Bit());
- if (y) ncl.append(y);
- }
-
- if (ncl.count() > 0)
- x->chain().setChain(ncl);
-
- kid->setup( x,
- meta["ssl_peer_ip"],
- text, // the URL
- meta["ssl_cipher"],
- meta["ssl_cipher_desc"],
- meta["ssl_cipher_version"],
- meta["ssl_cipher_used_bits"].toInt(),
- meta["ssl_cipher_bits"].toInt(),
- KSSLCertificate::KSSLValidation(meta["ssl_cert_state"].toInt()));
- kdDebug(7024) << "Showing SSL Info dialog" << endl;
- kid->exec();
- delete x;
- kdDebug(7024) << "SSL Info dialog closed" << endl;
- } else {
- KMessageBox::information( 0L, // parent ?
- i18n("The peer SSL certificate appears to be corrupt."), i18n("SSL") );
- }
- // This doesn't have to get deleted. It deletes on it's own.
- result = 1; // whatever
- break;
- }
- default:
- kdWarning() << "Observer::messageBox: unknown type " << type << endl;
- result = 0;
- break;
- }
- KMessageBox::setDontShowAskAgainConfig(0);
- delete config;
- return result;
-#if 0
- TQByteArray data, replyData;
- TQCString replyType;
- TQDataStream arg( data, IO_WriteOnly );
- arg << progressId;
- arg << type;
- arg << text;
- arg << caption;
- arg << buttonYes;
- arg << buttonNo;
- if ( kapp->dcopClient()->call( "kio_uiserver", "UIServer", "messageBox(int,int,TQString,TQString,TQString,TQString)", data, replyType, replyData, true )
- && replyType == "int" )
- {
- int result;
- TQDataStream _reply_stream( replyData, IO_ReadOnly );
- _reply_stream >> result;
- kdDebug(KDEBUG_OBSERVER) << "Observer::messageBox got result " << result << endl;
- return result;
- }
- kdDebug(KDEBUG_OBSERVER) << "Observer::messageBox call failed" << endl;
- return 0;
-#endif
-}
-
-RenameDlg_Result Observer::open_RenameDlg( TDEIO::Job* job,
- const TQString & caption,
- const TQString& src, const TQString & dest,
- RenameDlg_Mode mode, TQString& newDest,
- TDEIO::filesize_t sizeSrc,
- TDEIO::filesize_t sizeDest,
- time_t ctimeSrc,
- time_t ctimeDest,
- time_t mtimeSrc,
- time_t mtimeDest
- )
-{
- kdDebug(KDEBUG_OBSERVER) << "Observer::open_RenameDlg job=" << job << endl;
- if (job)
- kdDebug(KDEBUG_OBSERVER) << " progressId=" << job->progressId() << endl;
- // Hide existing dialog box if any
- if (job && job->progressId())
- m_uiserver->setJobVisible( job->progressId(), false );
- // We now do it in process => KDE4: move this code out of Observer (back to job.cpp), so that
- // opening the rename dialog doesn't start uiserver for nothing if progressId=0 (e.g. F2 in konq)
- RenameDlg_Result res = TDEIO::open_RenameDlg( caption, src, dest, mode,
- newDest, sizeSrc, sizeDest,
- ctimeSrc, ctimeDest, mtimeSrc,
- mtimeDest );
- if (job && job->progressId())
- m_uiserver->setJobVisible( job->progressId(), true );
- return res;
-}
-
-SkipDlg_Result Observer::open_SkipDlg( TDEIO::Job* job,
- bool _multi,
- const TQString& _error_text )
-{
- kdDebug(KDEBUG_OBSERVER) << "Observer::open_SkipDlg job=" << job << " progressId=" << job->progressId() << endl;
- // Hide existing dialog box if any
- if (job && job->progressId())
- m_uiserver->setJobVisible( job->progressId(), false );
- // We now do it in process. So this method is a useless wrapper around TDEIO::open_RenameDlg.
- SkipDlg_Result res = TDEIO::open_SkipDlg( _multi, _error_text );
- if (job && job->progressId())
- m_uiserver->setJobVisible( job->progressId(), true );
- return res;
-}
-
-void Observer::virtual_hook( int id, void* data )
-{ DCOPObject::virtual_hook( id, data ); }
-
-#include "observer.moc"
diff --git a/kio/kio/observer.h b/kio/kio/observer.h
deleted file mode 100644
index 1869e5638..000000000
--- a/kio/kio/observer.h
+++ /dev/null
@@ -1,213 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Matej Koss <koss@miesto.sk>
- David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __kio_observer_h__
-#define __kio_observer_h__
-
-#include <tqobject.h>
-#include <dcopobject.h>
-#include <tqintdict.h>
-
-#include <kio/global.h>
-#include <kio/authinfo.h>
-#include "kio/job.h"
-#include "kio/skipdlg.h"
-#include "kio/renamedlg.h"
-
-class UIServer_stub;
-class KURL;
-
-namespace TDEIO {
- class Job;
-}
-
-/**
- * Observer for TDEIO::Job progress information.
- *
- * This class, of which there is always only one instance,
- * "observes" what jobs do and forwards this information
- * to the progress-info server.
- *
- * It is a DCOP object so that the UI server can call the
- * kill method when the user presses Cancel.
- *
- * Usually jobs are automatically registered by the
- * TDEIO::Scheduler, so you do not have to care about that.
- *
- * @short Observer for TDEIO::Job progress information
- * @author David Faure <faure@kde.org>
- */
-class TDEIO_EXPORT Observer : public TQObject, public DCOPObject {
-
- K_DCOP
- Q_OBJECT
-
-public:
-
- /**
- * Returns the unique observer object.
- * @return the observer object
- */
- static Observer * self() {
- if (!s_pObserver) s_pObserver = new Observer;
- return s_pObserver;
- }
-
- /**
- * Called by the job constructor, to signal its presence to the
- * UI Server.
- * @param job the new job
- * @param showProgress true to show progress, false otherwise
- * @return the progress ID assigned by the UI Server to the Job.
- */
- int newJob( TDEIO::Job * job, bool showProgress );
-
- /**
- * Called by the job destructor, to tell the UI Server that
- * the job ended.
- * @param progressId the progress ID of the job, as returned by newJob()
- */
- void jobFinished( int progressId );
-
- /**
- * @deprecated use TDEIO::AutoInfo
- */
- bool openPassDlg( const TQString& prompt, TQString& user, TQString& pass,
- bool readOnly );
-
- /**
- * Opens a password dialog.
- * @param info the authentication information
- * @return true if successful ("ok" clicked), false otherwise
- */
- bool openPassDlg( TDEIO::AuthInfo& info );
-
- /**
- * Popup a message box. See TDEIO::SlaveBase.
- * This doesn't use DCOP anymore, it shows the dialog in the application's process.
- * Otherwise, other apps would block when trying to communicate with UIServer.
- * @param progressId the progress ID of the job, as returned by newJob()
- * @param type the type of the message box
- * @param text the text to show
- * @param caption the window caption
- * @param buttonYes the text of the "Yes" button
- * @param buttonNo the text of the "No button
- */
- static int messageBox( int progressId, int type, const TQString &text, const TQString &caption,
- const TQString &buttonYes, const TQString &buttonNo );
-
- /**
- * Popup a message box. See TDEIO::SlaveBase.
- * This doesn't use DCOP anymore, it shows the dialog in the application's process.
- * Otherwise, other apps would block when trying to communicate with UIServer.
- * @param progressId the progress ID of the job, as returned by newJob()
- * @param type the type of the message box
- * @param text the text to show
- * @param caption the window caption
- * @param buttonYes the text of the "Yes" button
- * @param buttonNo the text of the "No button
- * @param dontAskAgainName A checkbox is added with which further confirmation can be turned off.
- * The string is used to lookup and store the setting in kioslaverc.
- * @since 3.3
- */
- static int messageBox( int progressId, int type, const TQString &text, const TQString &caption,
- const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName );
-
- /**
- * @internal
- * See renamedlg.h
- */
- TDEIO::RenameDlg_Result open_RenameDlg( TDEIO::Job * job,
- const TQString & caption,
- const TQString& src, const TQString & dest,
- TDEIO::RenameDlg_Mode mode,
- TQString& newDest,
- TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1,
- TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1,
- time_t ctimeSrc = (time_t) -1,
- time_t ctimeDest = (time_t) -1,
- time_t mtimeSrc = (time_t) -1,
- time_t mtimeDest = (time_t) -1
- );
-
- /**
- * @internal
- * See skipdlg.h
- */
- TDEIO::SkipDlg_Result open_SkipDlg( TDEIO::Job * job,
- bool multi,
- const TQString & error_text );
-
-k_dcop:
- /**
- * Called by the UI Server (using DCOP) if the user presses cancel.
- * @param progressId the progress ID of the job, as returned by newJob()
- */
- void killJob( int progressId );
-
- /**
- * Called by the UI Server (using DCOP) to get all the metadata of the job
- * @param progressId the progress IDof the job, as returned by newJob()
- */
- TDEIO::MetaData metadata( int progressId );
-
-protected:
-
- static Observer * s_pObserver;
- Observer();
- ~Observer() {}
-
- UIServer_stub * m_uiserver;
-
- TQIntDict< TDEIO::Job > m_dctJobs;
-
-public slots:
-
- void slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size );
- void slotTotalFiles( TDEIO::Job*, unsigned long files );
- void slotTotalDirs( TDEIO::Job*, unsigned long dirs );
-
- void slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t size );
- void slotProcessedFiles( TDEIO::Job*, unsigned long files );
- void slotProcessedDirs( TDEIO::Job*, unsigned long dirs );
-
- void slotSpeed( TDEIO::Job*, unsigned long speed );
- void slotPercent( TDEIO::Job*, unsigned long percent );
- void slotInfoMessage( TDEIO::Job*, const TQString & msg );
-
- void slotCopying( TDEIO::Job*, const KURL& from, const KURL& to );
- void slotMoving( TDEIO::Job*, const KURL& from, const KURL& to );
- void slotDeleting( TDEIO::Job*, const KURL& url );
- /// @since 3.1
- void slotTransferring( TDEIO::Job*, const KURL& url );
- void slotCreatingDir( TDEIO::Job*, const KURL& dir );
- // currently unused
- void slotCanResume( TDEIO::Job*, TDEIO::filesize_t offset );
-
-public:
- void stating( TDEIO::Job*, const KURL& url );
- void mounting( TDEIO::Job*, const TQString & dev, const TQString & point );
- void unmounting( TDEIO::Job*, const TQString & point );
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class ObserverPrivate* d;
-};
-
-// -*- mode: c++; c-basic-offset: 2 -*-
-#endif
diff --git a/kio/kio/passdlg.cpp b/kio/kio/passdlg.cpp
deleted file mode 100644
index 1b5679028..000000000
--- a/kio/kio/passdlg.cpp
+++ /dev/null
@@ -1,367 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "passdlg.h"
-
-#include <tqapplication.h>
-#include <tqcheckbox.h>
-#include <tqhbox.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqsimplerichtext.h>
-#include <tqstylesheet.h>
-
-#include <kcombobox.h>
-#include <kconfig.h>
-#include <kiconloader.h>
-#include <klineedit.h>
-#include <klocale.h>
-#include <kstandarddirs.h>
-
-using namespace TDEIO;
-
-struct PasswordDialog::PasswordDialogPrivate
-{
- TQGridLayout *layout;
- TQLineEdit* userEdit;
- KLineEdit* passEdit;
- TQLabel* userNameLabel;
- TQLabel* prompt;
- TQCheckBox* keepCheckBox;
- TQMap<TQString,TQString> knownLogins;
- KComboBox* userEditCombo;
- TQHBox* userNameHBox;
-
- bool keep;
- short unsigned int nRow;
-};
-
-PasswordDialog::PasswordDialog( const TQString& prompt, const TQString& user,
- bool enableKeep, bool modal, TQWidget* parent,
- const char* name )
- :KDialogBase( parent, name, modal, i18n("Password"), Ok|Cancel, Ok, true)
-{
- init ( prompt, user, enableKeep );
-}
-
-PasswordDialog::~PasswordDialog()
-{
- delete d;
-}
-
-void PasswordDialog::init( const TQString& prompt, const TQString& user,
- bool enableKeep )
-{
- TQWidget *main = makeMainWidget();
-
- d = new PasswordDialogPrivate;
- d->keep = false;
- d->nRow = 0;
- d->keepCheckBox = 0;
-
- TDEConfig* cfg = TDEGlobal::config();
- TDEConfigGroupSaver saver( cfg, "Passwords" );
-
- d->layout = new TQGridLayout( main, 9, 3, spacingHint(), marginHint());
- d->layout->addColSpacing(1, 5);
-
- // Row 0: pixmap prompt
- TQLabel* lbl;
- TQPixmap pix( TDEGlobal::iconLoader()->loadIcon( "password", KIcon::NoGroup, KIcon::SizeHuge, 0, 0, true));
- if ( !pix.isNull() )
- {
- lbl = new TQLabel( main );
- lbl->setPixmap( pix );
- lbl->setAlignment( Qt::AlignLeft|Qt::AlignVCenter );
- lbl->setFixedSize( lbl->sizeHint() );
- d->layout->addWidget( lbl, 0, 0, Qt::AlignLeft );
- }
- d->prompt = new TQLabel( main );
- d->prompt->setAlignment( Qt::AlignLeft|Qt::AlignVCenter|TQt::WordBreak );
- d->layout->addWidget( d->prompt, 0, 2, Qt::AlignLeft );
- if ( prompt.isEmpty() )
- setPrompt( i18n( "You need to supply a username and a password" ) );
- else
- setPrompt( prompt );
-
- // Row 1: Row Spacer
- d->layout->addRowSpacing( 1, 7 );
-
- // Row 2-3: Reserved for an additional comment
-
- // Row 4: Username field
- d->userNameLabel = new TQLabel( i18n("&Username:"), main );
- d->userNameLabel->setAlignment( Qt::AlignVCenter | Qt::AlignLeft );
- d->userNameLabel->setFixedSize( d->userNameLabel->sizeHint() );
- d->userNameHBox = new TQHBox( main );
-
- d->userEdit = new KLineEdit( d->userNameHBox );
- TQSize s = d->userEdit->sizeHint();
- d->userEdit->setFixedHeight( s.height() );
- d->userEdit->setMinimumWidth( s.width() );
- d->userNameLabel->setBuddy( d->userEdit );
- d->layout->addWidget( d->userNameLabel, 4, 0 );
- d->layout->addWidget( d->userNameHBox, 4, 2 );
-
- // Row 5: Row spacer
- d->layout->addRowSpacing( 5, 4 );
-
- // Row 6: Password field
- lbl = new TQLabel( i18n("&Password:"), main );
- lbl->setAlignment( Qt::AlignVCenter | Qt::AlignLeft );
- lbl->setFixedSize( lbl->sizeHint() );
- TQHBox* hbox = new TQHBox( main );
- d->passEdit = new KLineEdit( hbox );
- if ( cfg->readEntry("EchoMode", "OneStar") == "NoEcho" )
- d->passEdit->setEchoMode( TQLineEdit::NoEcho );
- else
- d->passEdit->setEchoMode( TQLineEdit::Password );
- s = d->passEdit->sizeHint();
- d->passEdit->setFixedHeight( s.height() );
- d->passEdit->setMinimumWidth( s.width() );
- lbl->setBuddy( d->passEdit );
- d->layout->addWidget( lbl, 6, 0 );
- d->layout->addWidget( hbox, 6, 2 );
-
- if ( enableKeep )
- {
- // Row 7: Add spacer
- d->layout->addRowSpacing( 7, 4 );
- // Row 8: Keep Password
- hbox = new TQHBox( main );
- d->keepCheckBox = new TQCheckBox( i18n("&Keep password"), hbox );
- d->keepCheckBox->setFixedSize( d->keepCheckBox->sizeHint() );
- d->keep = cfg->readBoolEntry("Keep", false );
- d->keepCheckBox->setChecked( d->keep );
- connect(d->keepCheckBox, TQT_SIGNAL(toggled( bool )), TQT_SLOT(slotKeep( bool )));
- d->layout->addWidget( hbox, 8, 2 );
- }
-
- // Configure necessary key-bindings and connect necessar slots and signals
- connect( d->userEdit, TQT_SIGNAL(returnPressed()), d->passEdit, TQT_SLOT(setFocus()) );
- connect( d->passEdit, TQT_SIGNAL(returnPressed()), TQT_SLOT(slotOk()) );
-
- if ( !user.isEmpty() )
- {
- d->userEdit->setText( user );
- d->passEdit->setFocus();
- }
- else
- d->userEdit->setFocus();
-
- d->userEditCombo = 0;
-// setFixedSize( sizeHint() );
-}
-
-TQString PasswordDialog::username() const
-{
- return d->userEdit->text();
-}
-
-TQString PasswordDialog::password() const
-{
- return d->passEdit->text();
-}
-
-void PasswordDialog::setKeepPassword( bool b )
-{
- if ( d->keepCheckBox )
- d->keepCheckBox->setChecked( b );
-}
-
-bool PasswordDialog::keepPassword() const
-{
- return d->keep;
-}
-
-static void calculateLabelSize(TQLabel *label)
-{
- TQString qt_text = label->text();
-
- int pref_width = 0;
- int pref_height = 0;
- // Calculate a proper size for the text.
- {
- TQSimpleRichText rt(qt_text, label->font());
- TQRect d = TDEGlobalSettings::desktopGeometry(label->topLevelWidget());
-
- pref_width = d.width() / 4;
- rt.setWidth(pref_width-10);
- int used_width = rt.widthUsed();
- pref_height = rt.height();
- if (used_width <= pref_width)
- {
- while(true)
- {
- int new_width = (used_width * 9) / 10;
- rt.setWidth(new_width-10);
- int new_height = rt.height();
- if (new_height > pref_height)
- break;
- used_width = rt.widthUsed();
- if (used_width > new_width)
- break;
- }
- pref_width = used_width;
- }
- else
- {
- if (used_width > (pref_width *2))
- pref_width = pref_width *2;
- else
- pref_width = used_width;
- }
- }
- label->setFixedSize(TQSize(pref_width+10, pref_height));
-}
-
-void PasswordDialog::addCommentLine( const TQString& label,
- const TQString comment )
-{
- if (d->nRow > 0)
- return;
-
- TQWidget *main = mainWidget();
-
- TQLabel* lbl = new TQLabel( label, main);
- lbl->setAlignment( Qt::AlignVCenter|Qt::AlignRight );
- lbl->setFixedSize( lbl->sizeHint() );
- d->layout->addWidget( lbl, d->nRow+2, 0, Qt::AlignLeft );
- lbl = new TQLabel( comment, main);
- lbl->setAlignment( Qt::AlignVCenter|Qt::AlignLeft|TQt::WordBreak );
- calculateLabelSize(lbl);
- d->layout->addWidget( lbl, d->nRow+2, 2, Qt::AlignLeft );
- d->layout->addRowSpacing( 3, 10 ); // Add a spacer
- d->nRow++;
-}
-
-void PasswordDialog::slotKeep( bool keep )
-{
- d->keep = keep;
-}
-
-static TQString qrichtextify( const TQString& text )
-{
- if ( text.isEmpty() || text[0] == '<' )
- return text;
-
- TQStringList lines = TQStringList::split('\n', text);
- for(TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it)
- {
- *it = TQStyleSheet::convertFromPlainText( *it, TQStyleSheetItem::WhiteSpaceNormal );
- }
-
- return lines.join(TQString::null);
-}
-
-void PasswordDialog::setPrompt(const TQString& prompt)
-{
- TQString text = qrichtextify(prompt);
- d->prompt->setText(text);
- calculateLabelSize(d->prompt);
-}
-
-void PasswordDialog::setPassword(const TQString &p)
-{
- d->passEdit->setText(p);
-}
-
-void PasswordDialog::setUserReadOnly( bool readOnly )
-{
- d->userEdit->setReadOnly( readOnly );
- if ( readOnly && d->userEdit->hasFocus() )
- d->passEdit->setFocus();
-}
-
-void PasswordDialog::setKnownLogins( const TQMap<TQString, TQString>& knownLogins )
-{
- const int nr = knownLogins.count();
- if ( nr == 0 )
- return;
- if ( nr == 1 ) {
- d->userEdit->setText( knownLogins.begin().key() );
- setPassword( knownLogins.begin().data() );
- return;
- }
-
- Q_ASSERT( !d->userEdit->isReadOnly() );
- if ( !d->userEditCombo ) {
- delete d->userEdit;
- d->userEditCombo = new KComboBox( true, d->userNameHBox );
- d->userEdit = d->userEditCombo->lineEdit();
- TQSize s = d->userEditCombo->sizeHint();
- d->userEditCombo->setFixedHeight( s.height() );
- d->userEditCombo->setMinimumWidth( s.width() );
- d->userNameLabel->setBuddy( d->userEditCombo );
- d->layout->addWidget( d->userNameHBox, 4, 2 );
- }
-
- d->knownLogins = knownLogins;
- d->userEditCombo->insertStringList( knownLogins.keys() );
- d->userEditCombo->setFocus();
-
- connect( d->userEditCombo, TQT_SIGNAL( activated( const TQString& ) ),
- this, TQT_SLOT( slotActivated( const TQString& ) ) );
-}
-
-void PasswordDialog::slotActivated( const TQString& userName )
-{
- TQMap<TQString, TQString>::ConstIterator it = d->knownLogins.find( userName );
- if ( it != d->knownLogins.end() )
- setPassword( it.data() );
-}
-
-
-int PasswordDialog::getNameAndPassword( TQString& user, TQString& pass, bool* keep,
- const TQString& prompt, bool readOnly,
- const TQString& caption,
- const TQString& comment,
- const TQString& label )
-{
- PasswordDialog* dlg;
- if( keep )
- dlg = new PasswordDialog( prompt, user, (*keep) );
- else
- dlg = new PasswordDialog( prompt, user );
-
- if ( !caption.isEmpty() )
- dlg->setPlainCaption( caption );
- else
- dlg->setPlainCaption( i18n("Authorization Dialog") );
-
- if ( !comment.isEmpty() )
- dlg->addCommentLine( label, comment );
-
- if ( readOnly )
- dlg->setUserReadOnly( readOnly );
-
- int ret = dlg->exec();
- if ( ret == Accepted )
- {
- user = dlg->username();
- pass = dlg->password();
- if ( keep ) { (*keep) = dlg->keepPassword(); }
- }
- delete dlg;
- return ret;
- }
-
-void PasswordDialog::virtual_hook( int id, void* data )
-{ KDialogBase::virtual_hook( id, data ); }
-
-#include "passdlg.moc"
diff --git a/kio/kio/paste.cpp b/kio/kio/paste.cpp
deleted file mode 100644
index 472f4e313..000000000
--- a/kio/kio/paste.cpp
+++ /dev/null
@@ -1,308 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "paste.h"
-#include "pastedialog.h"
-
-#include "kio/job.h"
-#include "kio/global.h"
-#include "kio/netaccess.h"
-#include "kio/observer.h"
-#include "kio/renamedlg.h"
-#include "kio/kprotocolmanager.h"
-
-#include <kurl.h>
-#include <kurldrag.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kinputdialog.h>
-#include <kmessagebox.h>
-#include <kmimetype.h>
-#include <ktempfile.h>
-
-#include <tqapplication.h>
-#include <tqclipboard.h>
-#include <tqdragobject.h>
-#include <tqtextstream.h>
-#include <tqvaluevector.h>
-
-static KURL getNewFileName( const KURL &u, const TQString& text )
-{
- bool ok;
- TQString dialogText( text );
- if ( dialogText.isEmpty() )
- dialogText = i18n( "Filename for clipboard content:" );
- TQString file = KInputDialog::getText( TQString::null, dialogText, TQString::null, &ok );
- if ( !ok )
- return KURL();
-
- KURL myurl(u);
- myurl.addPath( file );
-
- if (TDEIO::NetAccess::exists(myurl, false, 0))
- {
- kdDebug(7007) << "Paste will overwrite file. Prompting..." << endl;
- TDEIO::RenameDlg_Result res = TDEIO::R_OVERWRITE;
-
- TQString newPath;
- // Ask confirmation about resuming previous transfer
- res = Observer::self()->open_RenameDlg(
- 0L, i18n("File Already Exists"),
- u.pathOrURL(),
- myurl.pathOrURL(),
- (TDEIO::RenameDlg_Mode) (TDEIO::M_OVERWRITE | TDEIO::M_SINGLE), newPath);
-
- if ( res == TDEIO::R_RENAME )
- {
- myurl = newPath;
- }
- else if ( res == TDEIO::R_CANCEL )
- {
- return KURL();
- }
- }
-
- return myurl;
-}
-
-// The finaly step: write _data to tempfile and move it to neW_url
-static TDEIO::CopyJob* pasteDataAsyncTo( const KURL& new_url, const TQByteArray& _data )
-{
- KTempFile tempFile;
- tempFile.dataStream()->writeRawBytes( _data.data(), _data.size() );
- tempFile.close();
-
- KURL orig_url;
- orig_url.setPath(tempFile.name());
-
- return TDEIO::move( orig_url, new_url );
-}
-
-#ifndef QT_NO_MIMECLIPBOARD
-static TDEIO::CopyJob* chooseAndPaste( const KURL& u, TQMimeSource* data,
- const TQValueVector<TQCString>& formats,
- const TQString& text,
- TQWidget* widget,
- bool clipboard )
-{
- TQStringList formatLabels;
- for ( uint i = 0; i < formats.size(); ++i ) {
- const TQCString& fmt = formats[i];
- KMimeType::Ptr mime = KMimeType::mimeType( fmt );
- if ( mime != KMimeType::defaultMimeTypePtr() )
- formatLabels.append( i18n( "%1 (%2)" ).arg( mime->comment() ).arg( fmt.data() ) );
- else
- formatLabels.append( fmt );
- }
-
- TQString dialogText( text );
- if ( dialogText.isEmpty() )
- dialogText = i18n( "Filename for clipboard content:" );
- TDEIO::PasteDialog dlg( TQString::null, dialogText, TQString::null, formatLabels, widget, clipboard );
-
- if ( dlg.exec() != KDialogBase::Accepted )
- return 0;
-
- if ( clipboard && dlg.clipboardChanged() ) {
- KMessageBox::sorry( widget,
- i18n( "The clipboard has changed since you used 'paste': "
- "the chosen data format is no longer applicable. "
- "Please copy again what you wanted to paste." ) );
- return 0;
- }
-
- const TQString result = dlg.lineEditText();
- const TQCString chosenFormat = formats[ dlg.comboItem() ];
-
- kdDebug() << " result=" << result << " chosenFormat=" << chosenFormat << endl;
- KURL new_url( u );
- new_url.addPath( result );
- // if "data" came from TQClipboard, then it was deleted already - by a nice 0-seconds timer
- // In that case, get it again. Let's hope the user didn't copy something else meanwhile :/
- if ( clipboard ) {
- data = TQApplication::clipboard()->data();
- }
- const TQByteArray ba = data->encodedData( chosenFormat );
- return pasteDataAsyncTo( new_url, ba );
-}
-#endif
-
-// KDE4: remove
-TDEIO_EXPORT bool TDEIO::isClipboardEmpty()
-{
-#ifndef QT_NO_MIMECLIPBOARD
- TQMimeSource *data = TQApplication::clipboard()->data();
- if ( data->provides( "text/uri-list" ) && data->encodedData( "text/uri-list" ).size() > 0 )
- return false;
-#else
- // Happens with some versions of Qt Embedded... :/
- // Guess.
- TQString data = TQApplication::clipboard()->text();
- if(data.contains("://"))
- return false;
-#endif
- return true;
-}
-
-#ifndef QT_NO_MIMECLIPBOARD
-// The main method for dropping
-TDEIO::CopyJob* TDEIO::pasteMimeSource( TQMimeSource* data, const KURL& dest_url,
- const TQString& dialogText, TQWidget* widget, bool clipboard )
-{
- TQByteArray ba;
-
- // Now check for plain text
- // We don't want to display a mimetype choice for a TQTextDrag, those mimetypes look ugly.
- TQString text;
- if ( TQTextDrag::canDecode( data ) && TQTextDrag::decode( data, text ) )
- {
- TQTextStream txtStream( ba, IO_WriteOnly );
- txtStream << text;
- }
- else
- {
- TQValueVector<TQCString> formats;
- const char* fmt;
- for ( int i = 0; ( fmt = data->format( i ) ); ++i ) {
- if ( qstrcmp( fmt, "application/x-qiconlist" ) == 0 ) // see QIconDrag
- continue;
- if ( qstrcmp( fmt, "application/x-kde-cutselection" ) == 0 ) // see KonqDrag
- continue;
- if ( strchr( fmt, '/' ) == 0 ) // e.g. TARGETS, MULTIPLE, TIMESTAMP
- continue;
- formats.append( fmt );
- }
-
- if ( formats.size() == 0 )
- return 0;
-
- if ( formats.size() > 1 ) {
- return chooseAndPaste( dest_url, data, formats, dialogText, widget, clipboard );
- }
- ba = data->encodedData( formats.first() );
- }
- if ( ba.size() == 0 )
- {
- KMessageBox::sorry(0, i18n("The clipboard is empty"));
- return 0;
- }
-
- return pasteDataAsync( dest_url, ba, dialogText );
-}
-#endif
-
-// The main method for pasting
-TDEIO_EXPORT TDEIO::Job *TDEIO::pasteClipboard( const KURL& dest_url, bool move )
-{
- if ( !dest_url.isValid() ) {
- KMessageBox::error( 0L, i18n( "Malformed URL\n%1" ).arg( dest_url.url() ) );
- return 0;
- }
-
-#ifndef QT_NO_MIMECLIPBOARD
- TQMimeSource *data = TQApplication::clipboard()->data();
-
- // First check for URLs.
- KURL::List urls;
- if ( KURLDrag::canDecode( data ) && KURLDrag::decode( data, urls ) ) {
- if ( urls.count() == 0 ) {
- KMessageBox::error( 0L, i18n("The clipboard is empty"));
- return 0;
- }
-
- TDEIO::Job *res = 0;
- if ( move )
- res = TDEIO::move( urls, dest_url );
- else
- res = TDEIO::copy( urls, dest_url );
-
- // If moving, erase the clipboard contents, the original files don't exist anymore
- if ( move )
- TQApplication::clipboard()->clear();
- return res;
- }
- return pasteMimeSource( data, dest_url, TQString::null, 0 /*TODO parent widget*/, true /*clipboard*/ );
-#else
- TQByteArray ba;
- TQTextStream txtStream( ba, IO_WriteOnly );
- TQStringList data = TQStringList::split("\n", TQApplication::clipboard()->text());
- KURL::List urls;
- KURLDrag::decode(data, urls);
- TQStringList::Iterator end(data.end());
- for(TQStringList::Iterator it=data.begin(); it!=end; ++it)
- txtStream << *it;
- if ( ba.size() == 0 )
- {
- KMessageBox::sorry(0, i18n("The clipboard is empty"));
- return 0;
- }
- return pasteDataAsync( dest_url, ba );
-#endif
-}
-
-
-TDEIO_EXPORT void TDEIO::pasteData( const KURL& u, const TQByteArray& _data )
-{
- KURL new_url = getNewFileName( u, TQString::null );
- // We could use TDEIO::put here, but that would require a class
- // for the slotData call. With NetAccess, we can do a synchronous call.
-
- if (new_url.isEmpty())
- return;
-
- KTempFile tempFile;
- tempFile.setAutoDelete( true );
- tempFile.dataStream()->writeRawBytes( _data.data(), _data.size() );
- tempFile.close();
-
- (void) TDEIO::NetAccess::upload( tempFile.name(), new_url, 0 );
-}
-
-TDEIO_EXPORT TDEIO::CopyJob* TDEIO::pasteDataAsync( const KURL& u, const TQByteArray& _data )
-{
- return pasteDataAsync( u, _data, TQString::null );
-}
-
-TDEIO_EXPORT TDEIO::CopyJob* TDEIO::pasteDataAsync( const KURL& u, const TQByteArray& _data, const TQString& text )
-{
- KURL new_url = getNewFileName( u, text );
-
- if (new_url.isEmpty())
- return 0;
-
- return pasteDataAsyncTo( new_url, _data );
-}
-
-TDEIO_EXPORT TQString TDEIO::pasteActionText()
-{
- TQMimeSource *data = TQApplication::clipboard()->data();
- KURL::List urls;
- if ( KURLDrag::canDecode( data ) && KURLDrag::decode( data, urls ) ) {
- if ( urls.isEmpty() )
- return TQString::null; // nothing to paste
- else if ( urls.first().isLocalFile() )
- return i18n( "&Paste File", "&Paste %n Files", urls.count() );
- else
- return i18n( "&Paste URL", "&Paste %n URLs", urls.count() );
- } else if ( data->format(0) != 0 ) {
- return i18n( "&Paste Clipboard Contents" );
- } else {
- return TQString::null;
- }
-}
-
diff --git a/kio/kio/previewjob.cpp b/kio/kio/previewjob.cpp
deleted file mode 100644
index de4800ab1..000000000
--- a/kio/kio/previewjob.cpp
+++ /dev/null
@@ -1,597 +0,0 @@
-// -*- c++ -*-
-// vim: ts=4 sw=4 et
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
- 2001 Malte Starostik <malte.starostik@t-online.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "previewjob.h"
-
-#include <sys/stat.h>
-#ifdef __FreeBSD__
- #include <machine/param.h>
-#endif
-#include <sys/types.h>
-
-#ifdef Q_OS_UNIX
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#endif
-
-#include <tqdir.h>
-#include <tqfile.h>
-#include <tqimage.h>
-#include <tqtimer.h>
-#include <tqregexp.h>
-
-#include <kdatastream.h> // Do not remove, needed for correct bool serialization
-#include <kfileitem.h>
-#include <kapplication.h>
-#include <ktempfile.h>
-#include <ktrader.h>
-#include <kmdcodec.h>
-#include <kglobal.h>
-#include <kstandarddirs.h>
-
-#include <kio/kservice.h>
-
-#include "previewjob.moc"
-
-namespace TDEIO { struct PreviewItem; }
-using namespace TDEIO;
-
-struct TDEIO::PreviewItem
-{
- KFileItem *item;
- KService::Ptr plugin;
-};
-
-struct TDEIO::PreviewJobPrivate
-{
- enum { STATE_STATORIG, // if the thumbnail exists
- STATE_GETORIG, // if we create it
- STATE_CREATETHUMB // thumbnail:/ slave
- } state;
- KFileItemList initialItems;
- const TQStringList *enabledPlugins;
- // Our todo list :)
- TQValueList<PreviewItem> items;
- // The current item
- PreviewItem currentItem;
- // The modification time of that URL
- time_t tOrig;
- // Path to thumbnail cache for the current size
- TQString thumbPath;
- // Original URL of current item in TMS format
- // (file:///path/to/file instead of file:/path/to/file)
- TQString origName;
- // Thumbnail file name for current item
- TQString thumbName;
- // Size of thumbnail
- int width;
- int height;
- // Unscaled size of thumbnail (128 or 256 if cache is enabled)
- int cacheWidth;
- int cacheHeight;
- // Whether the thumbnail should be scaled
- bool bScale;
- // Whether we should save the thumbnail
- bool bSave;
- // If the file to create a thumb for was a temp file, this is its name
- TQString tempName;
- // Over that, it's too much
- unsigned long maximumSize;
- // the size for the icon overlay
- int iconSize;
- // the transparency of the blended mimetype icon
- int iconAlpha;
- // Shared memory segment Id. The segment is allocated to a size
- // of extent x extent x 4 (32 bit image) on first need.
- int shmid;
- // And the data area
- uchar *shmaddr;
- // Delete the KFileItems when done?
- bool deleteItems;
- bool succeeded;
- // Root of thumbnail cache
- TQString thumbRoot;
- bool ignoreMaximumSize;
- TQTimer startPreviewTimer;
-};
-
-PreviewJob::PreviewJob( const KFileItemList &items, int width, int height,
- int iconSize, int iconAlpha, bool scale, bool save,
- const TQStringList *enabledPlugins, bool deleteItems )
- : TDEIO::Job( false /* no GUI */ )
-{
- d = new PreviewJobPrivate;
- d->tOrig = 0;
- d->shmid = -1;
- d->shmaddr = 0;
- d->initialItems = items;
- d->enabledPlugins = enabledPlugins;
- d->width = width;
- d->height = height ? height : width;
- d->cacheWidth = d->width;
- d->cacheHeight = d->height;
- d->iconSize = iconSize;
- d->iconAlpha = iconAlpha;
- d->deleteItems = deleteItems;
- d->bScale = scale;
- d->bSave = save && scale;
- d->succeeded = false;
- d->currentItem.item = 0;
- d->thumbRoot = TQDir::homeDirPath() + "/.thumbnails/";
- d->ignoreMaximumSize = false;
-
- // Return to event loop first, determineNextFile() might delete this;
- connect(&d->startPreviewTimer, TQT_SIGNAL(timeout()), TQT_SLOT(startPreview()) );
- d->startPreviewTimer.start(0, true);
-}
-
-PreviewJob::~PreviewJob()
-{
-#ifdef Q_OS_UNIX
- if (d->shmaddr) {
- shmdt((char*)d->shmaddr);
- shmctl(d->shmid, IPC_RMID, 0);
- }
-#endif
- delete d;
-}
-
-void PreviewJob::startPreview()
-{
- // Load the list of plugins to determine which mimetypes are supported
- KTrader::OfferList plugins = KTrader::self()->query("ThumbCreator");
- TQMap<TQString, KService::Ptr> mimeMap;
-
- for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
- if (!d->enabledPlugins || d->enabledPlugins->contains((*it)->desktopEntryName()))
- {
- TQStringList mimeTypes = (*it)->property("MimeTypes").toStringList();
- for (TQStringList::ConstIterator mt = mimeTypes.begin(); mt != mimeTypes.end(); ++mt)
- mimeMap.insert(*mt, *it);
- }
-
- // Look for images and store the items in our todo list :)
- bool bNeedCache = false;
- for (KFileItemListIterator it(d->initialItems); it.current(); ++it )
- {
- PreviewItem item;
- item.item = it.current();
- TQMap<TQString, KService::Ptr>::ConstIterator plugin = mimeMap.find(it.current()->mimetype());
- if (plugin == mimeMap.end()
- && (it.current()->mimetype() != "application/x-desktop")
- && (it.current()->mimetype() != "media/builtin-mydocuments")
- && (it.current()->mimetype() != "media/builtin-mycomputer")
- && (it.current()->mimetype() != "media/builtin-mynetworkplaces")
- && (it.current()->mimetype() != "media/builtin-printers")
- && (it.current()->mimetype() != "media/builtin-trash")
- && (it.current()->mimetype() != "media/builtin-webbrowser"))
- {
- TQString mimeType = it.current()->mimetype();
- plugin = mimeMap.find(mimeType.replace(TQRegExp("/.*"), "/*"));
-
- if (plugin == mimeMap.end())
- {
- // check mime type inheritance
- KMimeType::Ptr mimeInfo = KMimeType::mimeType(it.current()->mimetype());
- TQString parentMimeType = mimeInfo->parentMimeType();
- while (!parentMimeType.isEmpty())
- {
- plugin = mimeMap.find(parentMimeType);
- if (plugin != mimeMap.end()) break;
-
- KMimeType::Ptr parentMimeInfo = KMimeType::mimeType(parentMimeType);
- if (!parentMimeInfo) break;
-
- parentMimeType = parentMimeInfo->parentMimeType();
- }
- }
-
- if (plugin == mimeMap.end())
- {
- // check X-TDE-Text property
- KMimeType::Ptr mimeInfo = KMimeType::mimeType(it.current()->mimetype());
- TQVariant textProperty = mimeInfo->property("X-TDE-text");
- if (textProperty.isValid() && textProperty.type() == TQVariant::Bool)
- {
- if (textProperty.toBool())
- {
- plugin = mimeMap.find("text/plain");
- if (plugin == mimeMap.end())
- {
- plugin = mimeMap.find( "text/*" );
- }
- }
- }
- }
- }
-
- if (plugin != mimeMap.end())
- {
- item.plugin = *plugin;
- d->items.append(item);
- if (!bNeedCache && d->bSave &&
- (it.current()->url().protocol() != "file" ||
- !it.current()->url().directory( false ).startsWith(d->thumbRoot)) &&
- (*plugin)->property("CacheThumbnail").toBool())
- bNeedCache = true;
- }
- else
- {
- emitFailed(it.current());
- if (d->deleteItems)
- delete it.current();
- }
- }
-
- // Read configuration value for the maximum allowed size
- TDEConfig * config = TDEGlobal::config();
- TDEConfigGroupSaver cgs( config, "PreviewSettings" );
- d->maximumSize = config->readNumEntry( "MaximumSize", 1024*1024 /* 1MB */ );
-
- if (bNeedCache)
- {
- if (d->width <= 128 && d->height <= 128) d->cacheWidth = d->cacheHeight = 128;
- else d->cacheWidth = d->cacheHeight = 256;
- d->thumbPath = d->thumbRoot + (d->cacheWidth == 128 ? "normal/" : "large/");
- KStandardDirs::makeDir(d->thumbPath, 0700);
- }
- else
- d->bSave = false;
- determineNextFile();
-}
-
-void PreviewJob::removeItem( const KFileItem *item )
-{
- for (TQValueList<PreviewItem>::Iterator it = d->items.begin(); it != d->items.end(); ++it)
- if ((*it).item == item)
- {
- d->items.remove(it);
- break;
- }
-
- if (d->currentItem.item == item)
- {
- subjobs.first()->kill();
- subjobs.removeFirst();
- determineNextFile();
- }
-}
-
-void PreviewJob::setIgnoreMaximumSize(bool ignoreSize)
-{
- d->ignoreMaximumSize = ignoreSize;
-}
-
-void PreviewJob::determineNextFile()
-{
- if (d->currentItem.item)
- {
- if (!d->succeeded)
- emitFailed();
- if (d->deleteItems) {
- delete d->currentItem.item;
- d->currentItem.item = 0L;
- }
- }
- // No more items ?
- if ( d->items.isEmpty() )
- {
- emitResult();
- return;
- }
- else
- {
- // First, stat the orig file
- d->state = PreviewJobPrivate::STATE_STATORIG;
- d->currentItem = d->items.first();
- d->succeeded = false;
- d->items.remove(d->items.begin());
- TDEIO::Job *job = TDEIO::stat( d->currentItem.item->url(), false );
- job->addMetaData( "no-auth-prompt", "true" );
- addSubjob(job);
- }
-}
-
-void PreviewJob::slotResult( TDEIO::Job *job )
-{
- subjobs.remove( job );
- Q_ASSERT ( subjobs.isEmpty() ); // We should have only one job at a time ...
- switch ( d->state )
- {
- case PreviewJobPrivate::STATE_STATORIG:
- {
- if (job->error()) // that's no good news...
- {
- // Drop this one and move on to the next one
- determineNextFile();
- return;
- }
- TDEIO::UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
- TDEIO::UDSEntry::ConstIterator it = entry.begin();
- d->tOrig = 0;
- int found = 0;
- for( ; it != entry.end() && found < 2; it++ )
- {
- if ( (*it).m_uds == TDEIO::UDS_MODIFICATION_TIME )
- {
- d->tOrig = (time_t)((*it).m_long);
- found++;
- }
- else if ( (*it).m_uds == TDEIO::UDS_SIZE )
- {
- if ( filesize_t((*it).m_long) > d->maximumSize &&
- !d->ignoreMaximumSize &&
- !d->currentItem.plugin->property("IgnoreMaximumSize").toBool() )
- {
- determineNextFile();
- return;
- }
- found++;
- }
- }
-
- if ( !d->currentItem.plugin->property( "CacheThumbnail" ).toBool() )
- {
- // This preview will not be cached, no need to look for a saved thumbnail
- // Just create it, and be done
- getOrCreateThumbnail();
- return;
- }
-
- if ( statResultThumbnail() )
- return;
-
- getOrCreateThumbnail();
- return;
- }
- case PreviewJobPrivate::STATE_GETORIG:
- {
- if (job->error())
- {
- determineNextFile();
- return;
- }
-
- createThumbnail( static_cast<TDEIO::FileCopyJob*>(job)->destURL().path() );
- return;
- }
- case PreviewJobPrivate::STATE_CREATETHUMB:
- {
- if (!d->tempName.isEmpty())
- {
- TQFile::remove(d->tempName);
- d->tempName = TQString::null;
- }
- determineNextFile();
- return;
- }
- }
-}
-
-bool PreviewJob::statResultThumbnail()
-{
- if ( d->thumbPath.isEmpty() )
- return false;
-
- KURL url = d->currentItem.item->url();
- // Don't include the password if any
- url.setPass(TQString::null);
- // The TMS defines local files as file:///path/to/file instead of KDE's
- // way (file:/path/to/file)
-#ifdef KURL_TRIPLE_SLASH_FILE_PROT
- d->origName = url.url();
-#else
- if (url.protocol() == "file") d->origName = "file://" + url.path();
- else d->origName = url.url();
-#endif
-
- KMD5 md5( TQFile::encodeName( d->origName ).data() );
- d->thumbName = TQFile::encodeName( md5.hexDigest() ) + ".png";
-
- TQImage thumb;
- if ( !thumb.load( d->thumbPath + d->thumbName ) ) return false;
-
- if ( thumb.text( "Thumb::URI", 0 ) != d->origName ||
- thumb.text( "Thumb::MTime", 0 ).toInt() != d->tOrig ) return false;
-
- // Found it, use it
- emitPreview( thumb );
- d->succeeded = true;
- determineNextFile();
- return true;
-}
-
-
-void PreviewJob::getOrCreateThumbnail()
-{
- // We still need to load the orig file ! (This is getting tedious) :)
- const KFileItem* item = d->currentItem.item;
- const TQString localPath = item->localPath();
- if ( !localPath.isEmpty() )
- createThumbnail( localPath );
- else
- {
- d->state = PreviewJobPrivate::STATE_GETORIG;
- KTempFile localFile;
- KURL localURL;
- localURL.setPath( d->tempName = localFile.name() );
- const KURL currentURL = item->url();
- TDEIO::Job * job = TDEIO::file_copy( currentURL, localURL, -1, true,
- false, false /* No GUI */ );
- job->addMetaData("thumbnail","1");
- addSubjob(job);
- }
-}
-
-// KDE 4: Make it const TQString &
-void PreviewJob::createThumbnail( TQString pixPath )
-{
- d->state = PreviewJobPrivate::STATE_CREATETHUMB;
- KURL thumbURL;
- thumbURL.setProtocol("thumbnail");
- thumbURL.setPath(pixPath);
- TDEIO::TransferJob *job = TDEIO::get(thumbURL, false, false);
- addSubjob(job);
- connect(job, TQT_SIGNAL(data(TDEIO::Job *, const TQByteArray &)), TQT_SLOT(slotThumbData(TDEIO::Job *, const TQByteArray &)));
- bool save = d->bSave && d->currentItem.plugin->property("CacheThumbnail").toBool();
- job->addMetaData("mimeType", d->currentItem.item->mimetype());
- job->addMetaData("width", TQString().setNum(save ? d->cacheWidth : d->width));
- job->addMetaData("height", TQString().setNum(save ? d->cacheHeight : d->height));
- job->addMetaData("iconSize", TQString().setNum(save ? 64 : d->iconSize));
- job->addMetaData("iconAlpha", TQString().setNum(d->iconAlpha));
- job->addMetaData("plugin", d->currentItem.plugin->library());
-#ifdef Q_OS_UNIX
- if (d->shmid == -1)
- {
- if (d->shmaddr) {
- shmdt((char*)d->shmaddr);
- shmctl(d->shmid, IPC_RMID, 0);
- }
- d->shmid = shmget(IPC_PRIVATE, d->cacheWidth * d->cacheHeight * 4, IPC_CREAT|0600);
- if (d->shmid != -1)
- {
- d->shmaddr = (uchar *)(shmat(d->shmid, 0, SHM_RDONLY));
- if (d->shmaddr == (uchar *)-1)
- {
- shmctl(d->shmid, IPC_RMID, 0);
- d->shmaddr = 0;
- d->shmid = -1;
- }
- }
- else
- d->shmaddr = 0;
- }
- if (d->shmid != -1)
- job->addMetaData("shmid", TQString().setNum(d->shmid));
-#endif
-}
-
-void PreviewJob::slotThumbData(TDEIO::Job *, const TQByteArray &data)
-{
- bool save = d->bSave &&
- d->currentItem.plugin->property("CacheThumbnail").toBool() &&
- (d->currentItem.item->url().protocol() != "file" ||
- !d->currentItem.item->url().directory( false ).startsWith(d->thumbRoot));
- TQImage thumb;
-#ifdef Q_OS_UNIX
- if (d->shmaddr)
- {
- TQDataStream str(data, IO_ReadOnly);
- int width, height, depth;
- bool alpha;
- str >> width >> height >> depth >> alpha;
- thumb = TQImage(d->shmaddr, width, height, depth, 0, 0, TQImage::IgnoreEndian);
- thumb.setAlphaBuffer(alpha);
- }
- else
-#endif
- thumb.loadFromData(data);
-
- if (save)
- {
- thumb.setText("Thumb::URI", 0, d->origName);
- thumb.setText("Thumb::MTime", 0, TQString::number(d->tOrig));
- thumb.setText("Thumb::Size", 0, number(d->currentItem.item->size()));
- thumb.setText("Thumb::Mimetype", 0, d->currentItem.item->mimetype());
- thumb.setText("Software", 0, "KDE Thumbnail Generator");
- KTempFile temp(d->thumbPath + "kde-tmp-", ".png");
- if (temp.status() == 0) //Only try to write out the thumbnail if we
- { //actually created the temp file.
- thumb.save(temp.name(), "PNG");
- rename(TQFile::encodeName(temp.name()), TQFile::encodeName(d->thumbPath + d->thumbName));
- }
- }
- emitPreview( thumb );
- d->succeeded = true;
-}
-
-void PreviewJob::emitPreview(const TQImage &thumb)
-{
- TQPixmap pix;
- if (thumb.width() > d->width || thumb.height() > d->height)
- {
- double imgRatio = (double)thumb.height() / (double)thumb.width();
- if (imgRatio > (double)d->height / (double)d->width)
- pix.convertFromImage(
- thumb.smoothScale((int)TQMAX((double)d->height / imgRatio, 1), d->height));
- else pix.convertFromImage(
- thumb.smoothScale(d->width, (int)TQMAX((double)d->width * imgRatio, 1)));
- }
- else pix.convertFromImage(thumb);
- emit gotPreview(d->currentItem.item, pix);
-}
-
-void PreviewJob::emitFailed(const KFileItem *item)
-{
- if (!item)
- item = d->currentItem.item;
- emit failed(item);
-}
-
-TQStringList PreviewJob::availablePlugins()
-{
- TQStringList result;
- KTrader::OfferList plugins = KTrader::self()->query("ThumbCreator");
- for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
- if (!result.contains((*it)->desktopEntryName()))
- result.append((*it)->desktopEntryName());
- return result;
-}
-
-TQStringList PreviewJob::supportedMimeTypes()
-{
- TQStringList result;
- KTrader::OfferList plugins = KTrader::self()->query("ThumbCreator");
- for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
- result += (*it)->property("MimeTypes").toStringList();
- return result;
-}
-
-void PreviewJob::kill( bool quietly )
-{
- d->startPreviewTimer.stop();
- Job::kill( quietly );
-}
-
-PreviewJob *TDEIO::filePreview( const KFileItemList &items, int width, int height,
- int iconSize, int iconAlpha, bool scale, bool save,
- const TQStringList *enabledPlugins )
-{
- return new PreviewJob(items, width, height, iconSize, iconAlpha,
- scale, save, enabledPlugins);
-}
-
-PreviewJob *TDEIO::filePreview( const KURL::List &items, int width, int height,
- int iconSize, int iconAlpha, bool scale, bool save,
- const TQStringList *enabledPlugins )
-{
- KFileItemList fileItems;
- for (KURL::List::ConstIterator it = items.begin(); it != items.end(); ++it)
- fileItems.append(new KFileItem(KFileItem::Unknown, KFileItem::Unknown, *it, true));
- return new PreviewJob(fileItems, width, height, iconSize, iconAlpha,
- scale, save, enabledPlugins, true);
-}
-
-void PreviewJob::virtual_hook( int id, void* data )
-{ TDEIO::Job::virtual_hook( id, data ); }
-
diff --git a/kio/kio/previewjob.h b/kio/kio/previewjob.h
deleted file mode 100644
index fe8e16c0f..000000000
--- a/kio/kio/previewjob.h
+++ /dev/null
@@ -1,182 +0,0 @@
-// -*- c++ -*-
-// vim: ts=4 sw=4 et
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
- 2000 Carsten Pfeiffer <pfeiffer@kde.org>
- 2001 Malte Starostik <malte.starostik@t-online.de>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_previewjob_h__
-#define __kio_previewjob_h__
-
-#include <kfileitem.h>
-#include <kio/job.h>
-
-class TQPixmap;
-
-namespace TDEIO {
- /*!
- * This class catches a preview (thumbnail) for files.
- * @short KIO Job to get a thumbnail picture
- */
- class TDEIO_EXPORT PreviewJob : public TDEIO::Job
- {
- Q_OBJECT
- public:
- /**
- * Creates a new PreviewJob.
- * @param items a list of files to create previews for
- * @param width the desired width
- * @param height the desired height, 0 to use the @p width
- * @param iconSize the size of the mimetype icon to overlay over the
- * preview or zero to not overlay an icon. This has no effect if the
- * preview plugin that will be used doesn't use icon overlays.
- * @param iconAlpha transparency to use for the icon overlay
- * @param scale if the image is to be scaled to the requested size or
- * returned in its original size
- * @param save if the image should be cached for later use
- * @param enabledPlugins if non-zero, this points to a list containing
- * the names of the plugins that may be used.
- * @param deleteItems true to delete the items when done
- */
- PreviewJob( const KFileItemList &items, int width, int height,
- int iconSize, int iconAlpha, bool scale, bool save,
- const TQStringList *enabledPlugins, bool deleteItems = false );
- virtual ~PreviewJob();
-
- /**
- * Removes an item from preview processing. Use this if you passed
- * an item to filePreview and want to delete it now.
- *
- * @param item the item that should be removed from the preview queue
- */
- void removeItem( const KFileItem *item );
-
- /**
- * If @p ignoreSize is true, then the preview is always
- * generated regardless of the settings
- *
- * @since KDE 3.4
- **/
- void setIgnoreMaximumSize(bool ignoreSize = true);
-
- /**
- * Returns a list of all available preview plugins. The list
- * contains the basenames of the plugins' .desktop files (no path,
- * no .desktop).
- * @return the list of plugins
- */
- static TQStringList availablePlugins();
-
- /**
- * Returns a list of all supported MIME types. The list can
- * contain entries like text/ * (without the space).
- * @return the list of mime types
- */
- static TQStringList supportedMimeTypes();
-
- /**
- * Reimplemented for internal reasons
- */
- virtual void kill( bool quietly = true );
-
- signals:
- /**
- * Emitted when a thumbnail picture for @p item has been successfully
- * retrieved.
- * @param item the file of the preview
- * @param preview the preview image
- */
- void gotPreview( const KFileItem *item, const TQPixmap &preview );
- /**
- * Emitted when a thumbnail for @p item could not be created,
- * either because a ThumbCreator for its MIME type does not
- * exist, or because something went wrong.
- * @param item the file that failed
- */
- void failed( const KFileItem *item );
-
- protected:
- void getOrCreateThumbnail();
- bool statResultThumbnail();
- void createThumbnail( TQString );
-
- protected slots:
- virtual void slotResult( TDEIO::Job *job );
-
- private slots:
- void startPreview();
- void slotThumbData(TDEIO::Job *, const TQByteArray &);
-
- private:
- void determineNextFile();
- void emitPreview(const TQImage &thumb);
- void emitFailed(const KFileItem *item = 0);
-
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- struct PreviewJobPrivate *d;
- };
-
- /**
- * Creates a PreviewJob to generate or retrieve a preview image
- * for the given URL.
- *
- * @param items files to get previews for
- * @param width the maximum width to use
- * @param height the maximum height to use, if this is 0, the same
- * value as width is used.
- * @param iconSize the size of the mimetype icon to overlay over the
- * preview or zero to not overlay an icon. This has no effect if the
- * preview plugin that will be used doesn't use icon overlays.
- * @param iconAlpha transparency to use for the icon overlay
- * @param scale if the image is to be scaled to the requested size or
- * returned in its original size
- * @param save if the image should be cached for later use
- * @param enabledPlugins if non-zero, this points to a list containing
- * the names of the plugins that may be used.
- * @return the new PreviewJob
- * @see PreviewJob::availablePlugins()
- */
- TDEIO_EXPORT PreviewJob *filePreview( const KFileItemList &items, int width, int height = 0, int iconSize = 0, int iconAlpha = 70, bool scale = true, bool save = true, const TQStringList *enabledPlugins = 0 );
-
- /**
- * Creates a PreviewJob to generate or retrieve a preview image
- * for the given URL.
- *
- * @param items files to get previews for
- * @param width the maximum width to use
- * @param height the maximum height to use, if this is 0, the same
- * value as width is used.
- * @param iconSize the size of the mimetype icon to overlay over the
- * preview or zero to not overlay an icon. This has no effect if the
- * preview plugin that will be used doesn't use icon overlays.
- * @param iconAlpha transparency to use for the icon overlay
- * @param scale if the image is to be scaled to the requested size or
- * returned in its original size
- * @param save if the image should be cached for later use
- * @param enabledPlugins if non-zero, this points to a list containing
- * the names of the plugins that may be used.
- * @return the new PreviewJob
- * @see PreviewJob::availablePlugins()
- */
- TDEIO_EXPORT PreviewJob *filePreview( const KURL::List &items, int width, int height = 0, int iconSize = 0, int iconAlpha = 70, bool scale = true, bool save = true, const TQStringList *enabledPlugins = 0 );
-}
-
-#endif
diff --git a/kio/kio/progressbase.h b/kio/kio/progressbase.h
deleted file mode 100644
index 2be545621..000000000
--- a/kio/kio/progressbase.h
+++ /dev/null
@@ -1,271 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Matej Koss <koss@miesto.sk>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __progressbase_h__
-#define __progressbase_h__
-
-
-#include <tqwidget.h>
-
-#include <kio/global.h>
-
-class KURL;
-namespace TDEIO {
- class Job;
- class CopyJob;
- class DeleteJob;
-}
-
-namespace TDEIO
-{
- enum Progress {
- DEFAULT = 1,
- STATUSBAR = 2,
- LIST = 3
- };
-
-/**
-* This class does all initialization stuff for progress,
-* like connecting signals to slots.
-* All slots are implemented as pure virtual methods.
-*
-* All custom IO progress dialog should inherit this class.
-* Add your GUI code to the constructor and implemement those virtual
-* methods which you need in order to display progress.
-*
-* E.g. StatusbarProgress only implements slotTotalSize(),
-* slotPercent() and slotSpeed().
-*
-* Custom progress dialog will be used like this :
-* \code
-* // create job
-* CopyJob* job = TDEIO::copy(...);
-* // create a dialog
-* MyCustomProgress *customProgress;
-* customProgress = new MyCustomProgress();
-* // connect progress with job
-* customProgress->setJob( job );
-* ...
-* \endcode
-*
-* There is a special method setStopOnClose() that controls the behavior of
-* the dialog.
-* @short Base class for IO progress dialogs.
-* @author Matej Koss <koss@miesto.sk>
-*/
-class TDEIO_EXPORT ProgressBase : public TQWidget {
-
- Q_OBJECT
-
-public:
-
- /**
- * Creates a new progress dialog.
- * @param parent the parent of this dialog window, or 0
- */
- ProgressBase( TQWidget *parent );
- ~ProgressBase() {}
-
- /**
- * Assign a TDEIO::Job to this progress dialog.
- * @param job the job to assign
- */
- void setJob( TDEIO::Job *job );
- /**
- * Assign a TDEIO::Job to this progress dialog.
- * @param job the job to assign
- */
- void setJob( TDEIO::CopyJob *job );
- /**
- * Assign a TDEIO::Job to this progress dialog.
- * @param job the job to assign
- */
- void setJob( TDEIO::DeleteJob *job );
-
- // should we stop the job when the dialog is closed ?
- void setStopOnClose( bool stopOnClose ) { m_bStopOnClose = stopOnClose; }
- bool stopOnClose() const { return m_bStopOnClose; }
-
- // should we delete the dialog or just clean it when the job is finished ?
- /**
- * This controls whether the dialog should be deleted or only cleaned when
- * the TDEIO::Job is finished (or canceled).
- *
- * If your dialog is an embedded widget and not a separate window, you should
- * setOnlyClean(true) in the constructor of your custom dialog.
- *
- * @param onlyClean If true the dialog will only call method slotClean.
- * If false the dialog will be deleted.
- * @see onlyClean()
- */
- void setOnlyClean( bool onlyClean ) { m_bOnlyClean = onlyClean; }
-
- /**
- * Checks whether the dialog should be deleted or cleaned.
- * @return true if the dialog only calls slotClean, false if it will be
- * deleted
- * @see setOnlyClean()
- */
- bool onlyClean() const { return m_bOnlyClean; }
-
- /**
- * Call when the operation finished.
- * @since 3.1
- */
- void finished();
-
-public slots:
- /**
- * This method should be called for correct cancellation of IO operation
- * Connect this to the progress widgets buttons etc.
- */
- void slotStop();
- /**
- * This method is called when the widget should be cleaned (after job is finished).
- * redefine this for custom behavior.
- */
- virtual void slotClean();
-
- // progress slots
- /**
- * Called to set the total size.
- * @param job the TDEIO::Job
- * @param size the total size in bytes
- */
- virtual void slotTotalSize( TDEIO::Job* job, TDEIO::filesize_t size ) {
- Q_UNUSED(job);Q_UNUSED(size);}
- /**
- * Called to set the total number of files.
- * @param job the TDEIO::Job
- * @param files the number of files
- */
- virtual void slotTotalFiles( TDEIO::Job* job, unsigned long files ) {
- Q_UNUSED(job);Q_UNUSED(files);}
- /**
- * Called to set the total number of directories.
- * @param job the TDEIO::Job
- * @param dirs the number of directories
- */
- virtual void slotTotalDirs( TDEIO::Job* job, unsigned long dirs ) {
- Q_UNUSED(job);Q_UNUSED(dirs);}
-
- /**
- * Called to set the processed size.
- * @param job the TDEIO::Job
- * @param bytes the processed size in bytes
- */
- virtual void slotProcessedSize( TDEIO::Job* job, TDEIO::filesize_t bytes ) {
- Q_UNUSED(job);Q_UNUSED(bytes);}
- /**
- * Called to set the number of processed files.
- * @param job the TDEIO::Job
- * @param files the number of files
- */
- virtual void slotProcessedFiles( TDEIO::Job* job, unsigned long files ) {
- Q_UNUSED(job);Q_UNUSED(files);}
- /**
- * Called to set the number of processed directories.
- * @param job the TDEIO::Job
- * @param dirs the number of directories
- */
- virtual void slotProcessedDirs( TDEIO::Job* job, unsigned long dirs ) {
- Q_UNUSED(job);Q_UNUSED(dirs);}
-
- /**
- * Called to set the speed.
- * @param job the TDEIO::Job
- * @param speed the speed in bytes/second
- */
- virtual void slotSpeed( TDEIO::Job* job, unsigned long speed ) {
- Q_UNUSED(job);Q_UNUSED(speed);}
-
- /**
- * Called to set the percentage.
- * @param job the TDEIO::Job
- * @param percent the percentage
- */
- virtual void slotPercent( TDEIO::Job* job, unsigned long percent ) {
- Q_UNUSED(job);Q_UNUSED(percent);}
-
- /**
- * Called when the job is copying.
- * @param job the TDEIO::Job
- * @param src the source of the operation
- * @param dest the destination of the operation
- */
- virtual void slotCopying( TDEIO::Job* job, const KURL& src, const KURL& dest ) {
- Q_UNUSED(job);Q_UNUSED(src);Q_UNUSED(dest);}
- /**
- * Called when the job is moving.
- * @param job the TDEIO::Job
- * @param src the source of the operation
- * @param dest the destination of the operation
- */
- virtual void slotMoving( TDEIO::Job* job, const KURL& src, const KURL& dest ) {
- Q_UNUSED(job);Q_UNUSED(src);Q_UNUSED(dest);}
- /**
- * Called when the job is deleting.
- * @param job the TDEIO::Job
- * @param url the URL to delete
- */
- virtual void slotDeleting( TDEIO::Job* job, const KURL& url) {
- Q_UNUSED(job);Q_UNUSED(url);}
- /**
- * Called when the job is creating a directory.
- * @param job the TDEIO::Job
- * @param dir the URL of the directory to create
- */
- virtual void slotCreatingDir( TDEIO::Job* job, const KURL& dir ) {
- Q_UNUSED(job);Q_UNUSED(dir);}
-
- /**
- * Called when the job is resuming..
- * @param job the TDEIO::Job
- * @param from the position to resume from in bytes
- */
- virtual void slotCanResume( TDEIO::Job* job, TDEIO::filesize_t from) {
- Q_UNUSED(job);Q_UNUSED(from);}
-
-signals:
- /**
- * Called when the operation stopped.
- */
- void stopped();
-
-protected slots:
- void slotFinished( TDEIO::Job* );
-
-protected:
-
- virtual void closeEvent( TQCloseEvent * );
-
- TDEIO::Job* m_pJob;
-
-private:
- bool m_bOnlyClean;
- bool m_bStopOnClose;
-
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class ProgressBasePrivate* d;
-};
-
-} /* namespace */
-
-#endif // __progressbase_h__
diff --git a/kio/kio/renamedlg.cpp b/kio/kio/renamedlg.cpp
deleted file mode 100644
index 7bba95460..000000000
--- a/kio/kio/renamedlg.cpp
+++ /dev/null
@@ -1,574 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- David Faure <faure@kde.org>
- 2001 Holger Freyther <freyther@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kio/renamedlg.h"
-#include "kio/renamedlgplugin.h"
-#include <stdio.h>
-#include <assert.h>
-
-#include <tqfileinfo.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqlineedit.h>
-#include <tqdir.h>
-
-#include <kmessagebox.h>
-#include <kpushbutton.h>
-#include <kapplication.h>
-#include <kio/global.h>
-#include <ktrader.h>
-#include <klibloader.h>
-#include <kdialog.h>
-#include <klocale.h>
-#include <kglobal.h>
-#include <kdebug.h>
-#include <kurl.h>
-#include <kmimetype.h>
-#include <kseparator.h>
-#include <kstringhandler.h>
-#include <kstdguiitem.h>
-#include <kguiitem.h>
-#include <ksqueezedtextlabel.h>
-
-#ifdef Q_WS_X11
-#include <twin.h>
-#endif
-
-using namespace TDEIO;
-
-class RenameDlg::RenameDlgPrivate
-{
- public:
- RenameDlgPrivate(){
- bCancel = 0;
- bRename = bSkip = bAutoSkip = bOverwrite = bOverwriteAll = 0;
- bResume = bResumeAll = bSuggestNewName = 0;
- m_pLineEdit = 0;
- }
- KPushButton *bCancel;
- TQPushButton *bRename;
- TQPushButton *bSkip;
- TQPushButton *bAutoSkip;
- TQPushButton *bOverwrite;
- TQPushButton *bOverwriteAll;
- TQPushButton *bResume;
- TQPushButton *bResumeAll;
- TQPushButton *bSuggestNewName;
- TQLineEdit* m_pLineEdit;
- KURL src;
- KURL dest;
- TQString mimeSrc;
- TQString mimeDest;
- bool modal;
- bool plugin;
-};
-
-RenameDlg::RenameDlg(TQWidget *parent, const TQString & _caption,
- const TQString &_src, const TQString &_dest,
- RenameDlg_Mode _mode,
- TDEIO::filesize_t sizeSrc,
- TDEIO::filesize_t sizeDest,
- time_t ctimeSrc,
- time_t ctimeDest,
- time_t mtimeSrc,
- time_t mtimeDest,
- bool _modal)
- : TQDialog ( parent, "TDEIO::RenameDialog" , _modal )
-{
- d = new RenameDlgPrivate( );
- d->modal = _modal;
-#if 0
- // Set "StaysOnTop", because this dialog is typically used in kio_uiserver,
- // i.e. in a separate process.
- // ####### This isn't the case anymore - remove?
-#if !defined(Q_WS_QWS) && !defined(Q_WS_WIN) //FIXME(E): Implement for QT Embedded & win32
- if (d->modal)
- KWin::setState( winId(), NET::StaysOnTop );
-#endif
-#endif
-
- d->src = _src;
- d->dest = _dest;
- d->plugin = false;
-
-
- setCaption( _caption );
-
- d->bCancel = new KPushButton( KStdGuiItem::cancel(), this );
- connect(d->bCancel, TQT_SIGNAL(clicked()), this, TQT_SLOT(b0Pressed()));
-
- if ( ! (_mode & M_NORENAME ) ) {
- d->bRename = new TQPushButton( i18n( "&Rename" ), this );
- d->bRename->setEnabled(false);
- d->bSuggestNewName = new TQPushButton( i18n( "Suggest New &Name" ), this );
- connect(d->bSuggestNewName, TQT_SIGNAL(clicked()), this, TQT_SLOT(b8Pressed()));
- connect(d->bRename, TQT_SIGNAL(clicked()), this, TQT_SLOT(b1Pressed()));
- }
-
- if ( ( _mode & M_MULTI ) && ( _mode & M_SKIP ) ) {
- d->bSkip = new TQPushButton( i18n( "&Skip" ), this );
- connect(d->bSkip, TQT_SIGNAL(clicked()), this, TQT_SLOT(b2Pressed()));
-
- d->bAutoSkip = new TQPushButton( i18n( "&Auto Skip" ), this );
- connect(d->bAutoSkip, TQT_SIGNAL(clicked()), this, TQT_SLOT(b3Pressed()));
- }
-
- if ( _mode & M_OVERWRITE ) {
- d->bOverwrite = new TQPushButton( i18n( "&Overwrite" ), this );
- connect(d->bOverwrite, TQT_SIGNAL(clicked()), this, TQT_SLOT(b4Pressed()));
-
- if ( _mode & M_MULTI ) {
- d->bOverwriteAll = new TQPushButton( i18n( "O&verwrite All" ), this );
- connect(d->bOverwriteAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(b5Pressed()));
- }
- }
-
- if ( _mode & M_RESUME ) {
- d->bResume = new TQPushButton( i18n( "&Resume" ), this );
- connect(d->bResume, TQT_SIGNAL(clicked()), this, TQT_SLOT(b6Pressed()));
-
- if ( _mode & M_MULTI )
- {
- d->bResumeAll = new TQPushButton( i18n( "R&esume All" ), this );
- connect(d->bResumeAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(b7Pressed()));
- }
- }
-
- TQVBoxLayout* pLayout = new TQVBoxLayout( this, KDialog::marginHint(),
- KDialog::spacingHint() );
- pLayout->addStrut( 360 ); // makes dlg at least that wide
-
- // User tries to overwrite a file with itself ?
- if ( _mode & M_OVERWRITE_ITSELF ) {
- TQLabel *lb = new TQLabel( i18n( "This action would overwrite '%1' with itself.\n"
- "Please enter a new file name:" ).arg( KStringHandler::csqueeze( d->src.pathOrURL(),100 ) ), this );
- d->bRename->setText(i18n("C&ontinue"));
- pLayout->addWidget( lb );
- }
- else if ( _mode & M_OVERWRITE ) {
-
- // Figure out the mimetype and load one plugin
- // (This is the only mode that is handled by plugins)
- pluginHandling();
- KTrader::OfferList plugin_offers;
- if( d->mimeSrc != KMimeType::defaultMimeType() ){
- plugin_offers = KTrader::self()->query(d->mimeSrc, "'RenameDlg/Plugin' in ServiceTypes");
-
- }else if(d->mimeDest != KMimeType::defaultMimeType() ) {
- plugin_offers = KTrader::self()->query(d->mimeDest, "'RenameDlg/Plugin' in ServiceTypes");
- }
- if(!plugin_offers.isEmpty() ){
- kdDebug(7024) << "Offers" << endl;
- KTrader::OfferList::ConstIterator it = plugin_offers.begin();
- KTrader::OfferList::ConstIterator end = plugin_offers.end();
- for( ; it != end; ++it ){
- TQString libName = (*it)->library();
- if( libName.isEmpty() ){
- kdDebug(7024) << "lib is empty" << endl;
- continue;
- }
- KLibrary *lib = KLibLoader::self()->library(libName.local8Bit() );
- if(!lib) {
- continue;
- }
- KLibFactory *factory = lib->factory();
- if(!factory){
- lib->unload();
- continue;
- }
- TQObject *obj = factory->create( TQT_TQOBJECT(this), (*it)->name().latin1() );
- if(!obj) {
- lib->unload();
- continue;
- }
- RenameDlgPlugin *plugin = static_cast<RenameDlgPlugin *>(TQT_TQWIDGET(obj));
- if(!plugin ){
- delete obj;
- continue;
- }
- if( plugin->initialize( _mode, _src, _dest, d->mimeSrc,
- d->mimeDest, sizeSrc, sizeDest,
- ctimeSrc, ctimeDest,
- mtimeSrc, mtimeDest ) ) {
- d->plugin = true;
- pLayout->addWidget(plugin );
- kdDebug(7024) << "RenameDlgPlugin" << endl;
- break;
- } else {
- delete obj;
- }
- }
-
- }
-
- if( !d->plugin ){
- // No plugin found, build default dialog
- TQGridLayout * gridLayout = new TQGridLayout( 0L, 9, 2, KDialog::marginHint(),
- KDialog::spacingHint() );
- pLayout->addLayout(TQT_TQLAYOUT(gridLayout));
- gridLayout->setColStretch(0,0);
- gridLayout->setColStretch(1,10);
-
- TQString sentence1;
- if (mtimeDest < mtimeSrc)
- sentence1 = i18n("An older item named '%1' already exists.");
- else if (mtimeDest == mtimeSrc)
- sentence1 = i18n("A similar file named '%1' already exists.");
- else
- sentence1 = i18n("A newer item named '%1' already exists.");
-
- TQLabel * lb1 = new KSqueezedTextLabel( sentence1.arg(d->dest.pathOrURL() ), this );
- gridLayout->addMultiCellWidget( lb1, 0, 0, 0, 1 ); // takes the complete first line
-
- lb1 = new TQLabel( this );
- lb1->setPixmap( KMimeType::pixmapForURL( d->dest ) );
- gridLayout->addMultiCellWidget( lb1, 1, 3, 0, 0 ); // takes the first column on rows 1-3
-
- int row = 1;
- if ( sizeDest != (TDEIO::filesize_t)-1 )
- {
- TQLabel * lb = new TQLabel( i18n("size %1").arg( TDEIO::convertSize(sizeDest) ), this );
- gridLayout->addWidget( lb, row, 1 );
- row++;
-
- }
- if ( ctimeDest != (time_t)-1 )
- {
- TQDateTime dctime; dctime.setTime_t( ctimeDest );
- TQLabel * lb = new TQLabel( i18n("created on %1").arg( TDEGlobal::locale()->formatDateTime(dctime) ), this );
- gridLayout->addWidget( lb, row, 1 );
- row++;
- }
- if ( mtimeDest != (time_t)-1 )
- {
- TQDateTime dmtime; dmtime.setTime_t( mtimeDest );
- TQLabel * lb = new TQLabel( i18n("modified on %1").arg( TDEGlobal::locale()->formatDateTime(dmtime) ), this );
- gridLayout->addWidget( lb, row, 1 );
- row++;
- }
-
- if ( !d->src.isEmpty() )
- {
- // rows 1 to 3 are the details (size/ctime/mtime), row 4 is empty
- gridLayout->addRowSpacing( 4, 20 );
-
- TQLabel * lb2 = new KSqueezedTextLabel( i18n("The source file is '%1'").arg(d->src.pathOrURL()), this );
- gridLayout->addMultiCellWidget( lb2, 5, 5, 0, 1 ); // takes the complete first line
-
- lb2 = new TQLabel( this );
- lb2->setPixmap( KMimeType::pixmapForURL( d->src ) );
- gridLayout->addMultiCellWidget( lb2, 6, 8, 0, 0 ); // takes the first column on rows 6-8
-
- row = 6;
-
- if ( sizeSrc != (TDEIO::filesize_t)-1 )
- {
- TQLabel * lb = new TQLabel( i18n("size %1").arg( TDEIO::convertSize(sizeSrc) ), this );
- gridLayout->addWidget( lb, row, 1 );
- row++;
- }
- if ( ctimeSrc != (time_t)-1 )
- {
- TQDateTime dctime; dctime.setTime_t( ctimeSrc );
- TQLabel * lb = new TQLabel( i18n("created on %1").arg( TDEGlobal::locale()->formatDateTime(dctime) ), this );
- gridLayout->addWidget( lb, row, 1 );
- row++;
- }
- if ( mtimeSrc != (time_t)-1 )
- {
- TQDateTime dmtime; dmtime.setTime_t( mtimeSrc );
- TQLabel * lb = new TQLabel( i18n("modified on %1").arg( TDEGlobal::locale()->formatDateTime(dmtime) ), this );
- gridLayout->addWidget( lb, row, 1 );
- row++;
- }
- }
- }
- }
- else
- {
- // This is the case where we don't want to allow overwriting, the existing
- // file must be preserved (e.g. when renaming).
- TQString sentence1;
- if (mtimeDest < mtimeSrc)
- sentence1 = i18n("An older item named '%1' already exists.");
- else if (mtimeDest == mtimeSrc)
- sentence1 = i18n("A similar file named '%1' already exists.");
- else
- sentence1 = i18n("A newer item named '%1' already exists.");
-
- TQLabel *lb = new KSqueezedTextLabel( sentence1.arg(d->dest.pathOrURL()), this );
- pLayout->addWidget(lb);
- }
- TQHBoxLayout* layout2 = new TQHBoxLayout();
- pLayout->addLayout( layout2 );
-
- d->m_pLineEdit = new TQLineEdit( this );
- layout2->addWidget( d->m_pLineEdit );
- TQString fileName = d->dest.fileName();
- d->m_pLineEdit->setText( TDEIO::decodeFileName( fileName ) );
- if ( d->bRename || d->bOverwrite )
- connect(d->m_pLineEdit, TQT_SIGNAL(textChanged(const TQString &)),
- TQT_SLOT(enableRenameButton(const TQString &)));
- if ( d->bSuggestNewName )
- {
- layout2->addWidget( d->bSuggestNewName );
- setTabOrder( d->m_pLineEdit, d->bSuggestNewName );
- }
-
- KSeparator* separator = new KSeparator( this );
- pLayout->addWidget( separator );
-
- TQHBoxLayout* layout = new TQHBoxLayout();
- pLayout->addLayout( layout );
-
- layout->addStretch(1);
-
- if ( d->bRename )
- {
- layout->addWidget( d->bRename );
- setTabOrder( d->bRename, d->bCancel );
- }
- if ( d->bSkip )
- {
- layout->addWidget( d->bSkip );
- setTabOrder( d->bSkip, d->bCancel );
- }
- if ( d->bAutoSkip )
- {
- layout->addWidget( d->bAutoSkip );
- setTabOrder( d->bAutoSkip, d->bCancel );
- }
- if ( d->bOverwrite )
- {
- layout->addWidget( d->bOverwrite );
- setTabOrder( d->bOverwrite, d->bCancel );
- }
- if ( d->bOverwriteAll )
- {
- layout->addWidget( d->bOverwriteAll );
- setTabOrder( d->bOverwriteAll, d->bCancel );
- }
- if ( d->bResume )
- {
- layout->addWidget( d->bResume );
- setTabOrder( d->bResume, d->bCancel );
- }
- if ( d->bResumeAll )
- {
- layout->addWidget( d->bResumeAll );
- setTabOrder( d->bResumeAll, d->bCancel );
- }
-
- d->bCancel->setDefault( true );
- layout->addWidget( d->bCancel );
-
- resize( sizeHint() );
-}
-
-RenameDlg::~RenameDlg()
-{
- delete d;
- // no need to delete Pushbuttons,... qt will do this
-}
-
-void RenameDlg::enableRenameButton(const TQString &newDest)
-{
- if ( newDest != TDEIO::decodeFileName( d->dest.fileName() ) && !newDest.isEmpty() )
- {
- d->bRename->setEnabled( true );
- d->bRename->setDefault( true );
- if ( d->bOverwrite )
- d->bOverwrite->setEnabled( false ); // prevent confusion (#83114)
- }
- else
- {
- d->bRename->setEnabled( false );
- if ( d->bOverwrite )
- d->bOverwrite->setEnabled( true );
- }
-}
-
-KURL RenameDlg::newDestURL()
-{
- KURL newDest( d->dest );
- TQString fileName = d->m_pLineEdit->text();
- newDest.setFileName( TDEIO::encodeFileName( fileName ) );
- return newDest;
-}
-
-void RenameDlg::b0Pressed()
-{
- done( 0 );
-}
-
-// Rename
-void RenameDlg::b1Pressed()
-{
- if ( d->m_pLineEdit->text().isEmpty() )
- return;
-
- KURL u = newDestURL();
- if ( !u.isValid() )
- {
- KMessageBox::error( this, i18n( "Malformed URL\n%1" ).arg( u.url() ) );
- return;
- }
-
- done( 1 );
-}
-
-TQString RenameDlg::suggestName(const KURL& baseURL, const TQString& oldName)
-{
- TQString dotSuffix, suggestedName;
- TQString basename = oldName;
-
- int index = basename.find( '.' );
- if ( index != -1 ) {
- dotSuffix = basename.mid( index );
- basename.truncate( index );
- }
-
- int pos = basename.findRev( '_' );
- if(pos != -1 ){
- TQString tmp = basename.mid( pos+1 );
- bool ok;
- int number = tmp.toInt( &ok );
- if ( !ok ) {// ok there is no number
- suggestedName = basename + "1" + dotSuffix;
- }
- else {
- // yes there's already a number behind the _ so increment it by one
- basename.replace( pos+1, tmp.length(), TQString::number(number+1) );
- suggestedName = basename + dotSuffix;
- }
- }
- else // no underscore yet
- suggestedName = basename + "_1" + dotSuffix ;
-
- // Check if suggested name already exists
- bool exists = false;
- // TODO: network transparency. However, using NetAccess from a modal dialog
- // could be a problem, no? (given that it uses a modal widget itself....)
- if ( baseURL.isLocalFile() )
- exists = TQFileInfo( baseURL.path(+1) + suggestedName ).exists();
-
- if ( !exists )
- return suggestedName;
- else // already exists -> recurse
- return suggestName( baseURL, suggestedName );
-}
-
-// Propose button clicked
-void RenameDlg::b8Pressed()
-{
- /* no name to play with */
- if ( d->m_pLineEdit->text().isEmpty() )
- return;
-
- KURL destDirectory( d->dest );
- destDirectory.setPath( destDirectory.directory() );
- d->m_pLineEdit->setText( suggestName( destDirectory, d->m_pLineEdit->text() ) );
- return;
-}
-
-void RenameDlg::b2Pressed()
-{
- done( 2 );
-}
-
-void RenameDlg::b3Pressed()
-{
- done( 3 );
-}
-
-void RenameDlg::b4Pressed()
-{
- done( 4 );
-}
-
-void RenameDlg::b5Pressed()
-{
- done( 5 );
-}
-
-void RenameDlg::b6Pressed()
-{
- done( 6 );
-}
-
-void RenameDlg::b7Pressed()
-{
- done( 7 );
-}
-
-static TQString mime( const KURL& src )
-{
- KMimeType::Ptr type = KMimeType::findByURL( src );
- //if( type->name() == KMimeType::defaultMimeType() ){ // ok no mimetype
- // TQString ty = TDEIO::NetAccess::mimetype(d->src );
- // return ty;
- return type->name();
-}
-
-/** This will figure out the mimetypes and query for a plugin
- * Loads it then and asks the plugin if it wants to do the job
- * We'll take the first available mimetype
- * The scanning for a mimetype will be done in 2 ways
- *
- */
-void RenameDlg::pluginHandling()
-{
- d->mimeSrc = mime( d->src );
- d->mimeDest = mime(d->dest );
-
- kdDebug(7024) << "Source Mimetype: "<< d->mimeSrc << endl;
- kdDebug(7024) << "Dest Mimetype: "<< d->mimeDest << endl;
-}
-
-
-RenameDlg_Result TDEIO::open_RenameDlg( const TQString & _caption,
- const TQString & _src, const TQString & _dest,
- RenameDlg_Mode _mode,
- TQString& _new,
- TDEIO::filesize_t sizeSrc,
- TDEIO::filesize_t sizeDest,
- time_t ctimeSrc,
- time_t ctimeDest,
- time_t mtimeSrc,
- time_t mtimeDest)
-{
- Q_ASSERT(kapp);
-
- RenameDlg dlg( 0L, _caption, _src, _dest, _mode,
- sizeSrc, sizeDest, ctimeSrc, ctimeDest, mtimeSrc, mtimeDest,
- true /*modal*/ );
- int i = dlg.exec();
- _new = dlg.newDestURL().path();
-
- return (RenameDlg_Result)i;
-}
-
-#include "renamedlg.moc"
-
-
-
-
-
diff --git a/kio/kio/renamedlg.h b/kio/kio/renamedlg.h
deleted file mode 100644
index 38dcac925..000000000
--- a/kio/kio/renamedlg.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- David Faure <faure@kde.org>
- 2001 Holger Freyther <freyther@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_rename_dlg__
-#define __kio_rename_dlg__
-
-#include <kurl.h>
-#include <tqdialog.h>
-#include <tqstring.h>
-#include <sys/types.h>
-
-#include <kio/global.h>
-
-namespace TDEIO {
-
-// KDE4: get rid of M_OVERWRITE_ITSELF, trigger it internally if src==dest
-enum RenameDlg_Mode { M_OVERWRITE = 1, M_OVERWRITE_ITSELF = 2, M_SKIP = 4, M_SINGLE = 8, M_MULTI = 16, M_RESUME = 32, M_NORENAME = 64 };
-
-/**
- * The result of open_RenameDlg().
- */
-enum RenameDlg_Result { R_RESUME = 6, R_RESUME_ALL = 7, R_OVERWRITE = 4, R_OVERWRITE_ALL = 5, R_SKIP = 2, R_AUTO_SKIP = 3, R_RENAME = 1, R_CANCEL = 0 };
-
-
-/**
- * A dialog for the options to rename two files.
- * @short A dialog for renaming files.
- * @since 3.1
- */
-class TDEIO_EXPORT RenameDlg : public TQDialog
-{
- Q_OBJECT
-public:
- /**
- * Construct a "rename" dialog.
- * @param parent parent widget (often 0)
- * @param caption the caption for the dialog box
- * @param src the url to the file/dir we're trying to copy, as it's part of the text message
- * @param dest the path to destination file/dir, i.e. the one that already exists
- * @param mode parameters for the dialog (which buttons to show...),
- * @param sizeSrc size of source file
- * @param sizeDest size of destination file
- * @param ctimeSrc creation time of source file
- * @param ctimeDest creation time of destination file
- * @param mtimeSrc modification time of source file
- * @param mtimeDest modification time of destination file
- * @param modal set to true for a modal dialog
- * @see RenameDlg_Mode
- */
- RenameDlg( TQWidget *parent, const TQString & caption,
- // KDE4: make those KURLs, and use pathOrURL() internally.
- const TQString & src, const TQString & dest,
- RenameDlg_Mode mode,
- TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1,
- TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1,
- time_t ctimeSrc = (time_t) -1,
- time_t ctimeDest = (time_t) -1,
- time_t mtimeSrc = (time_t) -1,
- time_t mtimeDest = (time_t) -1,
- bool modal = false );
- ~RenameDlg();
-
- /**
- * @return the new destination
- * valid only if RENAME was chosen
- */
- KURL newDestURL();
-
- /**
- * Given a directory path and a filename (which usually exists already),
- * this function returns a suggested name for a file that doesn't exist
- * in that directory. The existence is only checked for local urls though.
- * The suggested file name is of the form foo_1 foo_2 etc.
- * @since 3.4
- */
- static TQString suggestName(const KURL& baseURL, const TQString& oldName);
-
-public slots:
- /// KDE4: rename to cancelPressed(), renamePressed() etc.
- void b0Pressed();
- void b1Pressed();
- void b2Pressed();
- void b3Pressed();
- void b4Pressed();
- void b5Pressed();
- void b6Pressed();
- void b7Pressed();
- void b8Pressed();
-
-protected slots:
- void enableRenameButton(const TQString &);
-private:
- class RenameDlgPrivate;
- RenameDlgPrivate *d;
- void pluginHandling( );
-};
-
- /**
- * \addtogroup renamedlg "RenameDlg related Functions"
- * @{
- * \relates TDEIO::RenameDlg
- * Construct a modal, parent-less "rename" dialog, and return
- * a result code, as well as the new dest. Much easier to use than the
- * class RenameDlg directly.
-
- * @param caption the caption for the dialog box
- * @param src the URL of the file/dir we're trying to copy, as it's part of the text message
- * @param dest the URL of the destination file/dir, i.e. the one that already exists
- * @param mode parameters for the dialog (which buttons to show...),
- * see RenameDlg_Mode
- * @param newDest the new destination path, valid if R_RENAME was returned.
- * @param sizeSrc size of source file
- * @param sizeDest size of destination file
- * @param ctimeSrc creation time of source file
- * @param ctimeDest creation time of destination file
- * @param mtimeSrc modification time of source file
- * @param mtimeDest modification time of destination file
- * @return the result
- */
-TDEIO_EXPORT RenameDlg_Result open_RenameDlg( const TQString & caption,
- // KDE4: make those KURLs
- const TQString& src, const TQString & dest,
- RenameDlg_Mode mode, TQString& newDestPath,
- TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1,
- TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1,
- time_t ctimeSrc = (time_t) -1,
- time_t ctimeDest = (time_t) -1,
- time_t mtimeSrc = (time_t) -1,
- time_t mtimeDest = (time_t) -1
- );
-
-/*! @} */
-
-}
-#endif
diff --git a/kio/kio/renamedlgplugin.h b/kio/kio/renamedlgplugin.h
deleted file mode 100644
index b3604b084..000000000
--- a/kio/kio/renamedlgplugin.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001 Holger Freyther <freyther@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef renamedlgplugin_h
-#define renamedlgplugin_h
-
-#include <kio/renamedlg.h>
-#include <tqdialog.h>
-#include <sys/types.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-
-/**
- * This is the base class for all RenameDlg plugins.
- * @short Base class for RenameDlg plugins.
- * @since 3.1
- */
-class TDEIO_EXPORT RenameDlgPlugin : public TQWidget
-{
-public:
- /**
- * This is the c'tor.
- */
- RenameDlgPlugin(TQDialog *dialog, const char *name, const TQStringList &/*list*/ = TQStringList() ): TQWidget(dialog, name ) {};
-
- /**
- * This function will be called by RenameDlg. The params are infos about the files.
- * @return If the plugin want's to display it return true, if not return false
- */
- virtual bool initialize(TDEIO::RenameDlg_Mode /*mod*/ , const TQString &/*_src*/, const TQString &/*_dest*/,
- const TQString &/*mimeSrc*/,
- const TQString &/*mimeDest*/,
- TDEIO::filesize_t /*sizeSrc*/,
- TDEIO::filesize_t /*sizeDest*/,
- time_t /*ctimeSrc*/,
- time_t /*ctimeDest*/,
- time_t /*mtimeSrc*/,
- time_t /*mtimeDest*/ ) {return false;};
-
-};
-
-#endif
-
diff --git a/kio/kio/scheduler.cpp b/kio/kio/scheduler.cpp
deleted file mode 100644
index 09560cb8b..000000000
--- a/kio/kio/scheduler.cpp
+++ /dev/null
@@ -1,922 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kio/sessiondata.h"
-#include "kio/slaveconfig.h"
-#include "kio/scheduler.h"
-#include "kio/authinfo.h"
-#include "kio/slave.h"
-#include <tqptrlist.h>
-#include <tqdict.h>
-
-#include <dcopclient.h>
-
-#include <kdebug.h>
-#include <kglobal.h>
-#include <kprotocolmanager.h>
-#include <kprotocolinfo.h>
-#include <assert.h>
-#include <kstaticdeleter.h>
-#include <tdesu/client.h>
-
-
-// Slaves may be idle for MAX_SLAVE_IDLE time before they are being returned
-// to the system wide slave pool. (3 minutes)
-#define MAX_SLAVE_IDLE (3*60)
-
-using namespace TDEIO;
-
-template class TQDict<TDEIO::Scheduler::ProtocolInfo>;
-
-Scheduler *Scheduler::instance = 0;
-
-class TDEIO::SlaveList: public TQPtrList<Slave>
-{
- public:
- SlaveList() { }
-};
-
-//
-// There are two kinds of protocol:
-// (1) The protocol of the url
-// (2) The actual protocol that the io-slave uses.
-//
-// These two often match, but not necasserily. Most notably, they don't
-// match when doing ftp via a proxy.
-// In that case (1) is ftp, but (2) is http.
-//
-// JobData::protocol stores (2) while Job::url().protocol() returns (1).
-// The ProtocolInfoDict is indexed with (2).
-//
-// We schedule slaves based on (2) but tell the slave about (1) via
-// Slave::setProtocol().
-
-class TDEIO::Scheduler::JobData
-{
-public:
- JobData() : checkOnHold(false) { }
-
-public:
- TQString protocol;
- TQString proxy;
- bool checkOnHold;
-};
-
-class TDEIO::Scheduler::ExtraJobData: public TQPtrDict<TDEIO::Scheduler::JobData>
-{
-public:
- ExtraJobData() { setAutoDelete(true); }
-};
-
-class TDEIO::Scheduler::ProtocolInfo
-{
-public:
- ProtocolInfo() : maxSlaves(1), skipCount(0)
- {
- joblist.setAutoDelete(false);
- }
-
- TQPtrList<SimpleJob> joblist;
- SlaveList activeSlaves;
- int maxSlaves;
- int skipCount;
- TQString protocol;
-};
-
-class TDEIO::Scheduler::ProtocolInfoDict : public TQDict<TDEIO::Scheduler::ProtocolInfo>
-{
- public:
- ProtocolInfoDict() { }
-
- TDEIO::Scheduler::ProtocolInfo *get( const TQString &protocol);
-};
-
-TDEIO::Scheduler::ProtocolInfo *
-TDEIO::Scheduler::ProtocolInfoDict::get(const TQString &protocol)
-{
- ProtocolInfo *info = find(protocol);
- if (!info)
- {
- info = new ProtocolInfo;
- info->protocol = protocol;
- info->maxSlaves = KProtocolInfo::maxSlaves( protocol );
-
- insert(protocol, info);
- }
- return info;
-}
-
-
-Scheduler::Scheduler()
- : DCOPObject( "TDEIO::Scheduler" ),
- TQObject(kapp, "scheduler"),
- slaveTimer(0, "Scheduler::slaveTimer"),
- coSlaveTimer(0, "Scheduler::coSlaveTimer"),
- cleanupTimer(0, "Scheduler::cleanupTimer")
-{
- checkOnHold = true; // !! Always check with KLauncher for the first request.
- slaveOnHold = 0;
- protInfoDict = new ProtocolInfoDict;
- slaveList = new SlaveList;
- idleSlaves = new SlaveList;
- coIdleSlaves = new SlaveList;
- extraJobData = new ExtraJobData;
- sessionData = new SessionData;
- slaveConfig = SlaveConfig::self();
- connect(&slaveTimer, TQT_SIGNAL(timeout()), TQT_SLOT(startStep()));
- connect(&coSlaveTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotScheduleCoSlave()));
- connect(&cleanupTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotCleanIdleSlaves()));
- busy = false;
-}
-
-Scheduler::~Scheduler()
-{
- protInfoDict->setAutoDelete(true);
- delete protInfoDict; protInfoDict = 0;
- delete idleSlaves; idleSlaves = 0;
- delete coIdleSlaves; coIdleSlaves = 0;
- slaveList->setAutoDelete(true);
- delete slaveList; slaveList = 0;
- delete extraJobData; extraJobData = 0;
- delete sessionData; sessionData = 0;
- instance = 0;
-}
-
-void
-Scheduler::debug_info()
-{
-}
-
-bool Scheduler::process(const TQCString &fun, const TQByteArray &data, TQCString &replyType, TQByteArray &replyData )
-{
- if ( fun != "reparseSlaveConfiguration(TQString)" )
- return DCOPObject::process( fun, data, replyType, replyData );
-
- slaveConfig = SlaveConfig::self();
- replyType = "void";
- TQDataStream stream( data, IO_ReadOnly );
- TQString proto;
- stream >> proto;
-
- kdDebug( 7006 ) << "reparseConfiguration( " << proto << " )" << endl;
- KProtocolManager::reparseConfiguration();
- slaveConfig->reset();
- sessionData->reset();
- NetRC::self()->reload();
-
- Slave *slave = slaveList->first();
- for (; slave; slave = slaveList->next() )
- if ( slave->slaveProtocol() == proto || proto.isEmpty() )
- {
- slave->send( CMD_REPARSECONFIGURATION );
- slave->resetHost();
- }
- return true;
-}
-
-QCStringList Scheduler::functions()
-{
- QCStringList funcs = DCOPObject::functions();
- funcs << "void reparseSlaveConfiguration(TQString)";
- return funcs;
-}
-
-void Scheduler::_doJob(SimpleJob *job) {
- JobData *jobData = new JobData;
- jobData->protocol = KProtocolManager::slaveProtocol(job->url(), jobData->proxy);
-// kdDebug(7006) << "Scheduler::_doJob protocol=" << jobData->protocol << endl;
- if (job->command() == CMD_GET)
- {
- jobData->checkOnHold = checkOnHold;
- checkOnHold = false;
- }
- extraJobData->replace(job, jobData);
- newJobs.append(job);
- slaveTimer.start(0, true);
-#ifndef NDEBUG
- if (newJobs.count() > 150)
- kdDebug() << "WARNING - TDEIO::Scheduler got more than 150 jobs! This shows a misuse in your app (yes, a job is a TQObject)." << endl;
-#endif
-}
-
-void Scheduler::_scheduleJob(SimpleJob *job) {
- newJobs.removeRef(job);
- JobData *jobData = extraJobData->find(job);
- if (!jobData)
-{
- kdFatal(7006) << "BUG! _ScheduleJob(): No extraJobData for job!" << endl;
- return;
-}
- TQString protocol = jobData->protocol;
-// kdDebug(7006) << "Scheduler::_scheduleJob protocol=" << protocol << endl;
- ProtocolInfo *protInfo = protInfoDict->get(protocol);
- protInfo->joblist.append(job);
-
- slaveTimer.start(0, true);
-}
-
-void Scheduler::_cancelJob(SimpleJob *job) {
-// kdDebug(7006) << "Scheduler: canceling job " << job << endl;
- Slave *slave = job->slave();
- if ( !slave )
- {
- // was not yet running (don't call this on a finished job!)
- JobData *jobData = extraJobData->find(job);
- if (!jobData)
- return; // I said: "Don't call this on a finished job!"
-
- newJobs.removeRef(job);
- ProtocolInfo *protInfo = protInfoDict->get(jobData->protocol);
- protInfo->joblist.removeRef(job);
-
- // Search all slaves to see if job is in the queue of a coSlave
- slave = slaveList->first();
- for(; slave; slave = slaveList->next())
- {
- JobList *list = coSlaves.find(slave);
- if (list && list->removeRef(job))
- break; // Job was found and removed.
- // Fall through to kill the slave as well!
- }
- if (!slave)
- {
- extraJobData->remove(job);
- return; // Job was not yet running and not in a coSlave queue.
- }
- }
- kdDebug(7006) << "Scheduler: killing slave " << slave->slave_pid() << endl;
- slave->kill();
- _jobFinished( job, slave );
- slotSlaveDied( slave);
-}
-
-void Scheduler::startStep()
-{
- while(newJobs.count())
- {
- (void) startJobDirect();
- }
- TQDictIterator<TDEIO::Scheduler::ProtocolInfo> it(*protInfoDict);
- while(it.current())
- {
- if (startJobScheduled(it.current())) return;
- ++it;
- }
-}
-
-void Scheduler::setupSlave(TDEIO::Slave *slave, const KURL &url, const TQString &protocol, const TQString &proxy , bool newSlave, const TDEIO::MetaData *config)
-{
- TQString host = url.host();
- int port = url.port();
- TQString user = url.user();
- TQString passwd = url.pass();
-
- if ((newSlave) ||
- (slave->host() != host) ||
- (slave->port() != port) ||
- (slave->user() != user) ||
- (slave->passwd() != passwd))
- {
- slaveConfig = SlaveConfig::self();
-
- MetaData configData = slaveConfig->configData(protocol, host);
- sessionData->configDataFor( configData, protocol, host );
-
- configData["UseProxy"] = proxy;
-
- TQString autoLogin = configData["EnableAutoLogin"].lower();
- if ( autoLogin == "true" )
- {
- NetRC::AutoLogin l;
- l.login = user;
- bool usern = (protocol == "ftp");
- if ( NetRC::self()->lookup( url, l, usern) )
- {
- configData["autoLoginUser"] = l.login;
- configData["autoLoginPass"] = l.password;
- if ( usern )
- {
- TQString macdef;
- TQMap<TQString, TQStringList>::ConstIterator it = l.macdef.begin();
- for ( ; it != l.macdef.end(); ++it )
- macdef += it.key() + '\\' + it.data().join( "\\" ) + '\n';
- configData["autoLoginMacro"] = macdef;
- }
- }
- }
- if (config)
- configData += *config;
- slave->setConfig(configData);
- slave->setProtocol(url.protocol());
- slave->setHost(host, port, user, passwd);
- }
-}
-
-bool Scheduler::startJobScheduled(ProtocolInfo *protInfo)
-{
- if (protInfo->joblist.isEmpty())
- return false;
-
-// kdDebug(7006) << "Scheduling job" << endl;
- debug_info();
- bool newSlave = false;
-
- SimpleJob *job = 0;
- Slave *slave = 0;
-
- if (protInfo->skipCount > 2)
- {
- bool dummy;
- // Prevent starvation. We skip the first entry in the queue at most
- // 2 times in a row. The
- protInfo->skipCount = 0;
- job = protInfo->joblist.at(0);
- slave = findIdleSlave(protInfo, job, dummy );
- }
- else
- {
- bool exact=false;
- SimpleJob *firstJob = 0;
- Slave *firstSlave = 0;
- for(uint i = 0; (i < protInfo->joblist.count()) && (i < 10); i++)
- {
- job = protInfo->joblist.at(i);
- slave = findIdleSlave(protInfo, job, exact);
- if (!firstSlave)
- {
- firstJob = job;
- firstSlave = slave;
- }
- if (!slave) break;
- if (exact) break;
- }
-
- if (!exact)
- {
- slave = firstSlave;
- job = firstJob;
- }
- if (job == firstJob)
- protInfo->skipCount = 0;
- else
- protInfo->skipCount++;
- }
-
- if (!slave)
- {
- if ( protInfo->maxSlaves > static_cast<int>(protInfo->activeSlaves.count()) )
- {
- newSlave = true;
- slave = createSlave(protInfo, job, job->url());
- if (!slave)
- slaveTimer.start(0, true);
- }
- }
-
- if (!slave)
- {
-// kdDebug(7006) << "No slaves available" << endl;
-// kdDebug(7006) << " -- active: " << protInfo->activeSlaves.count() << endl;
- return false;
- }
-
- protInfo->activeSlaves.append(slave);
- idleSlaves->removeRef(slave);
- protInfo->joblist.removeRef(job);
-// kdDebug(7006) << "scheduler: job started " << job << endl;
-
-
- JobData *jobData = extraJobData->find(job);
- setupSlave(slave, job->url(), jobData->protocol, jobData->proxy, newSlave);
- job->start(slave);
-
- slaveTimer.start(0, true);
- return true;
-}
-
-bool Scheduler::startJobDirect()
-{
- debug_info();
- SimpleJob *job = newJobs.take(0);
- JobData *jobData = extraJobData->find(job);
- if (!jobData)
- {
- kdFatal(7006) << "BUG! startjobDirect(): No extraJobData for job!"
- << endl;
- return false;
- }
- TQString protocol = jobData->protocol;
- ProtocolInfo *protInfo = protInfoDict->get(protocol);
-
- bool newSlave = false;
- bool dummy;
-
- // Look for matching slave
- Slave *slave = findIdleSlave(protInfo, job, dummy);
-
- if (!slave)
- {
- newSlave = true;
- slave = createSlave(protInfo, job, job->url());
- }
-
- if (!slave)
- return false;
-
- idleSlaves->removeRef(slave);
-// kdDebug(7006) << "scheduler: job started " << job << endl;
-
- setupSlave(slave, job->url(), protocol, jobData->proxy, newSlave);
- job->start(slave);
- return true;
-}
-
-static Slave *searchIdleList(SlaveList *idleSlaves, const KURL &url, const TQString &protocol, bool &exact)
-{
- TQString host = url.host();
- int port = url.port();
- TQString user = url.user();
- exact = true;
-
- for( Slave *slave = idleSlaves->first();
- slave;
- slave = idleSlaves->next())
- {
- if ((protocol == slave->slaveProtocol()) &&
- (host == slave->host()) &&
- (port == slave->port()) &&
- (user == slave->user()))
- return slave;
- }
-
- exact = false;
-
- // Look for slightly matching slave
- for( Slave *slave = idleSlaves->first();
- slave;
- slave = idleSlaves->next())
- {
- if (protocol == slave->slaveProtocol())
- return slave;
- }
- return 0;
-}
-
-Slave *Scheduler::findIdleSlave(ProtocolInfo *, SimpleJob *job, bool &exact)
-{
- Slave *slave = 0;
- JobData *jobData = extraJobData->find(job);
- if (!jobData)
- {
- kdFatal(7006) << "BUG! findIdleSlave(): No extraJobData for job!" << endl;
- return 0;
- }
- if (jobData->checkOnHold)
- {
- slave = Slave::holdSlave(jobData->protocol, job->url());
- if (slave)
- return slave;
- }
- if (slaveOnHold)
- {
- // Make sure that the job wants to do a GET or a POST, and with no offset
- bool bCanReuse = (job->command() == CMD_GET);
- TDEIO::TransferJob * tJob = dynamic_cast<TDEIO::TransferJob *>(job);
- if ( tJob )
- {
- bCanReuse = (job->command() == CMD_GET || job->command() == CMD_SPECIAL);
- if ( bCanReuse )
- {
- TDEIO::MetaData outgoing = tJob->outgoingMetaData();
- TQString resume = (!outgoing.contains("resume")) ? TQString() : outgoing["resume"];
- kdDebug(7006) << "Resume metadata is '" << resume << "'" << endl;
- bCanReuse = (resume.isEmpty() || resume == "0");
- }
- }
-// kdDebug(7006) << "bCanReuse = " << bCanReuse << endl;
- if (bCanReuse)
- {
- if (job->url() == urlOnHold)
- {
- kdDebug(7006) << "HOLD: Reusing held slave for " << urlOnHold.prettyURL() << endl;
- slave = slaveOnHold;
- }
- else
- {
- kdDebug(7006) << "HOLD: Discarding held slave (" << urlOnHold.prettyURL() << ")" << endl;
- slaveOnHold->kill();
- }
- slaveOnHold = 0;
- urlOnHold = KURL();
- }
- if (slave)
- return slave;
- }
-
- return searchIdleList(idleSlaves, job->url(), jobData->protocol, exact);
-}
-
-Slave *Scheduler::createSlave(ProtocolInfo *protInfo, SimpleJob *job, const KURL &url)
-{
- int error;
- TQString errortext;
- Slave *slave = Slave::createSlave(protInfo->protocol, url, error, errortext);
- if (slave)
- {
- slaveList->append(slave);
- idleSlaves->append(slave);
- connect(slave, TQT_SIGNAL(slaveDied(TDEIO::Slave *)),
- TQT_SLOT(slotSlaveDied(TDEIO::Slave *)));
- connect(slave, TQT_SIGNAL(slaveStatus(pid_t,const TQCString &,const TQString &, bool)),
- TQT_SLOT(slotSlaveStatus(pid_t,const TQCString &, const TQString &, bool)));
-
- connect(slave,TQT_SIGNAL(authorizationKey(const TQCString&, const TQCString&, bool)),
- sessionData,TQT_SLOT(slotAuthData(const TQCString&, const TQCString&, bool)));
- connect(slave,TQT_SIGNAL(delAuthorization(const TQCString&)), sessionData,
- TQT_SLOT(slotDelAuthData(const TQCString&)));
- }
- else
- {
- kdError() <<": couldn't create slave : " << errortext << endl;
- if (job)
- {
- protInfo->joblist.removeRef(job);
- extraJobData->remove(job);
- job->slotError( error, errortext );
- }
- }
- return slave;
-}
-
-void Scheduler::slotSlaveStatus(pid_t, const TQCString &, const TQString &, bool)
-{
-}
-
-void Scheduler::_jobFinished(SimpleJob *job, Slave *slave)
-{
- JobData *jobData = extraJobData->take(job);
- if (!jobData)
- {
- kdFatal(7006) << "BUG! _jobFinished(): No extraJobData for job!" << endl;
- return;
- }
- ProtocolInfo *protInfo = protInfoDict->get(jobData->protocol);
- delete jobData;
- slave->disconnect(job);
- protInfo->activeSlaves.removeRef(slave);
- if (slave->isAlive())
- {
- JobList *list = coSlaves.find(slave);
- if (list)
- {
- assert(slave->isConnected());
- assert(!coIdleSlaves->contains(slave));
- coIdleSlaves->append(slave);
- if (!list->isEmpty())
- coSlaveTimer.start(0, true);
- return;
- }
- else
- {
- assert(!slave->isConnected());
- idleSlaves->append(slave);
- slave->setIdle();
- _scheduleCleanup();
-// slave->send( CMD_SLAVE_STATUS );
- }
- }
- if (protInfo->joblist.count())
- {
- slaveTimer.start(0, true);
- }
-}
-
-void Scheduler::slotSlaveDied(TDEIO::Slave *slave)
-{
- assert(!slave->isAlive());
- ProtocolInfo *protInfo = protInfoDict->get(slave->slaveProtocol());
- protInfo->activeSlaves.removeRef(slave);
- if (slave == slaveOnHold)
- {
- slaveOnHold = 0;
- urlOnHold = KURL();
- }
- idleSlaves->removeRef(slave);
- JobList *list = coSlaves.find(slave);
- if (list)
- {
- // coSlave dies, kill jobs waiting in queue
- disconnectSlave(slave);
- }
-
- if (!slaveList->removeRef(slave))
- kdDebug(7006) << "Scheduler: BUG!! Slave " << slave << "/" << slave->slave_pid() << " died, but is NOT in slaveList!!!\n" << endl;
- else
- slave->deref(); // Delete slave
-}
-
-void Scheduler::slotCleanIdleSlaves()
-{
- for(Slave *slave = idleSlaves->first();slave;)
- {
- if (slave->idleTime() >= MAX_SLAVE_IDLE)
- {
- // kdDebug(7006) << "Removing idle slave: " << slave->slaveProtocol() << " " << slave->host() << endl;
- Slave *removeSlave = slave;
- slave = idleSlaves->next();
- idleSlaves->removeRef(removeSlave);
- slaveList->removeRef(removeSlave);
- removeSlave->connection()->close();
- removeSlave->deref();
- }
- else
- {
- slave = idleSlaves->next();
- }
- }
- _scheduleCleanup();
-}
-
-void Scheduler::_scheduleCleanup()
-{
- if (idleSlaves->count())
- {
- if (!cleanupTimer.isActive())
- cleanupTimer.start( MAX_SLAVE_IDLE*1000, true );
- }
-}
-
-void Scheduler::_putSlaveOnHold(TDEIO::SimpleJob *job, const KURL &url)
-{
- Slave *slave = job->slave();
- slave->disconnect(job);
-
- if (slaveOnHold)
- {
- slaveOnHold->kill();
- }
- slaveOnHold = slave;
- urlOnHold = url;
- slaveOnHold->suspend();
-}
-
-void Scheduler::_publishSlaveOnHold()
-{
- if (!slaveOnHold)
- return;
-
- slaveOnHold->hold(urlOnHold);
-}
-
-void Scheduler::_removeSlaveOnHold()
-{
- if (slaveOnHold)
- {
- slaveOnHold->kill();
- }
- slaveOnHold = 0;
- urlOnHold = KURL();
-}
-
-Slave *
-Scheduler::_getConnectedSlave(const KURL &url, const TDEIO::MetaData &config )
-{
- TQString proxy;
- TQString protocol = KProtocolManager::slaveProtocol(url, proxy);
- bool dummy;
- Slave *slave = searchIdleList(idleSlaves, url, protocol, dummy);
- if (!slave)
- {
- ProtocolInfo *protInfo = protInfoDict->get(protocol);
- slave = createSlave(protInfo, 0, url);
- }
- if (!slave)
- return 0; // Error
- idleSlaves->removeRef(slave);
-
- setupSlave(slave, url, protocol, proxy, true, &config);
-
- slave->send( CMD_CONNECT );
- connect(slave, TQT_SIGNAL(connected()),
- TQT_SLOT(slotSlaveConnected()));
- connect(slave, TQT_SIGNAL(error(int, const TQString &)),
- TQT_SLOT(slotSlaveError(int, const TQString &)));
-
- coSlaves.insert(slave, new TQPtrList<SimpleJob>());
-// kdDebug(7006) << "_getConnectedSlave( " << slave << ")" << endl;
- return slave;
-}
-
-void
-Scheduler::slotScheduleCoSlave()
-{
- Slave *nextSlave;
- slaveConfig = SlaveConfig::self();
- for(Slave *slave = coIdleSlaves->first();
- slave;
- slave = nextSlave)
- {
- nextSlave = coIdleSlaves->next();
- JobList *list = coSlaves.find(slave);
- assert(list);
- if (list && !list->isEmpty())
- {
- SimpleJob *job = list->take(0);
- coIdleSlaves->removeRef(slave);
-// kdDebug(7006) << "scheduler: job started " << job << endl;
-
- assert(!coIdleSlaves->contains(slave));
-
- KURL url =job->url();
- TQString host = url.host();
- int port = url.port();
-
- if (slave->host() == "<reset>")
- {
- TQString user = url.user();
- TQString passwd = url.pass();
-
- MetaData configData = slaveConfig->configData(url.protocol(), url.host());
- slave->setConfig(configData);
- slave->setProtocol(url.protocol());
- slave->setHost(host, port, user, passwd);
- }
-
- assert(slave->protocol() == url.protocol());
- assert(slave->host() == host);
- assert(slave->port() == port);
- job->start(slave);
- }
- }
-}
-
-void
-Scheduler::slotSlaveConnected()
-{
- Slave *slave = (Slave *)sender();
-// kdDebug(7006) << "slotSlaveConnected( " << slave << ")" << endl;
- slave->setConnected(true);
- disconnect(slave, TQT_SIGNAL(connected()),
- this, TQT_SLOT(slotSlaveConnected()));
- emit slaveConnected(slave);
- assert(!coIdleSlaves->contains(slave));
- coIdleSlaves->append(slave);
- coSlaveTimer.start(0, true);
-}
-
-void
-Scheduler::slotSlaveError(int errorNr, const TQString &errorMsg)
-{
- Slave *slave = (Slave *)sender();
- if (!slave->isConnected() || (coIdleSlaves->find(slave) != -1))
- {
- // Only forward to application if slave is idle or still connecting.
- emit slaveError(slave, errorNr, errorMsg);
- }
-}
-
-bool
-Scheduler::_assignJobToSlave(TDEIO::Slave *slave, SimpleJob *job)
-{
-// kdDebug(7006) << "_assignJobToSlave( " << job << ", " << slave << ")" << endl;
- TQString dummy;
- if ((slave->slaveProtocol() != KProtocolManager::slaveProtocol( job->url(), dummy ))
- ||
- (!newJobs.removeRef(job)))
- {
- kdDebug(7006) << "_assignJobToSlave(): ERROR, nonmatching or unknown job." << endl;
- job->kill();
- return false;
- }
-
- JobList *list = coSlaves.find(slave);
- assert(list);
- if (!list)
- {
- kdDebug(7006) << "_assignJobToSlave(): ERROR, unknown slave." << endl;
- job->kill();
- return false;
- }
-
- assert(list->contains(job) == 0);
- list->append(job);
- coSlaveTimer.start(0, true); // Start job on timer event
-
- return true;
-}
-
-bool
-Scheduler::_disconnectSlave(TDEIO::Slave *slave)
-{
-// kdDebug(7006) << "_disconnectSlave( " << slave << ")" << endl;
- JobList *list = coSlaves.take(slave);
- assert(list);
- if (!list)
- return false;
- // Kill jobs still in queue.
- while(!list->isEmpty())
- {
- Job *job = list->take(0);
- job->kill();
- }
- delete list;
- coIdleSlaves->removeRef(slave);
- assert(!coIdleSlaves->contains(slave));
- disconnect(slave, TQT_SIGNAL(connected()),
- this, TQT_SLOT(slotSlaveConnected()));
- disconnect(slave, TQT_SIGNAL(error(int, const TQString &)),
- this, TQT_SLOT(slotSlaveError(int, const TQString &)));
- if (slave->isAlive())
- {
- idleSlaves->append(slave);
- slave->send( CMD_DISCONNECT );
- slave->setIdle();
- slave->setConnected(false);
- _scheduleCleanup();
- }
- return true;
-}
-
-void
-Scheduler::_checkSlaveOnHold(bool b)
-{
- checkOnHold = b;
-}
-
-void
-Scheduler::_registerWindow(TQWidget *wid)
-{
- if (!wid)
- return;
-
- TQObject *obj = TQT_TQOBJECT(wid);
- if (!m_windowList.contains(obj))
- {
- // We must store the window Id because by the time
- // the destroyed signal is emitted we can no longer
- // access TQWidget::winId() (already destructed)
- WId windowId = wid->winId();
- m_windowList.insert(obj, windowId);
- connect(TQT_TQOBJECT(wid), TQT_SIGNAL(destroyed(TQObject *)),
- this, TQT_SLOT(slotUnregisterWindow(TQObject*)));
- TQByteArray params;
- TQDataStream stream(params, IO_WriteOnly);
- stream << windowId;
- if( !kapp->dcopClient()->send( "kded", "kded",
- "registerWindowId(long int)", params ) )
- kdDebug(7006) << "Could not register window with kded!" << endl;
- }
-}
-
-void
-Scheduler::slotUnregisterWindow(TQObject *obj)
-{
- if (!obj)
- return;
-
- TQMap<TQObject *, WId>::Iterator it = m_windowList.find(obj);
- if (it == m_windowList.end())
- return;
- WId windowId = it.data();
- disconnect( it.key(), TQT_SIGNAL(destroyed(TQObject *)),
- this, TQT_SLOT(slotUnregisterWindow(TQObject*)));
- m_windowList.remove( it );
- if (kapp)
- {
- TQByteArray params;
- TQDataStream stream(params, IO_WriteOnly);
- stream << windowId;
- kapp->dcopClient()->send( "kded", "kded",
- "unregisterWindowId(long int)", params );
- }
-}
-
-Scheduler* Scheduler::self() {
- if ( !instance ) {
- instance = new Scheduler;
- }
- return instance;
-}
-
-void Scheduler::virtual_hook( int id, void* data )
-{ DCOPObject::virtual_hook( id, data ); }
-
-
-
-#include "scheduler.moc"
diff --git a/kio/kio/scheduler.h b/kio/kio/scheduler.h
deleted file mode 100644
index ac0764dc4..000000000
--- a/kio/kio/scheduler.h
+++ /dev/null
@@ -1,364 +0,0 @@
-// -*- c++ -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
- Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _kio_scheduler_h
-#define _kio_scheduler_h
-
-#include "kio/job.h"
-#include "kio/jobclasses.h"
-#include <tqtimer.h>
-#include <tqptrdict.h>
-#include <tqmap.h>
-
-#include <dcopobject.h>
-
-namespace TDEIO {
-
- class Slave;
- class SlaveList;
- class SlaveConfig;
- class SessionData;
-
- /**
- * The TDEIO::Scheduler manages io-slaves for the application.
- * It also queues jobs and assigns the job to a slave when one
- * becomes available.
- *
- * There are 3 possible ways for a job to get a slave:
- *
- * <h3>1. Direct</h3>
- * This is the default. When you create a job the
- * TDEIO::Scheduler will be notified and will find either an existing
- * slave that is idle or it will create a new slave for the job.
- *
- * Example:
- * \code
- * TransferJob *job = TDEIO::get(KURL("http://www.kde.org"));
- * \endcode
- *
- *
- * <h3>2. Scheduled</h3>
- * If you create a lot of jobs, you might want not want to have a
- * slave for each job. If you schedule a job, a maximum number
- * of slaves will be created. When more jobs arrive, they will be
- * queued. When a slave is finished with a job, it will be assigned
- * a job from the queue.
- *
- * Example:
- * \code
- * TransferJob *job = TDEIO::get(KURL("http://www.kde.org"));
- * TDEIO::Scheduler::scheduleJob(job);
- * \endcode
- *
- * <h3>3. Connection Oriented</h3>
- * For some operations it is important that multiple jobs use
- * the same connection. This can only be ensured if all these jobs
- * use the same slave.
- *
- * You can ask the scheduler to open a slave for connection oriented
- * operations. You can then use the scheduler to assign jobs to this
- * slave. The jobs will be queued and the slave will handle these jobs
- * one after the other.
- *
- * Example:
- * \code
- * Slave *slave = TDEIO::Scheduler::getConnectedSlave(
- * KURL("pop3://bastian:password@mail.kde.org"));
- * TransferJob *job1 = TDEIO::get(
- * KURL("pop3://bastian:password@mail.kde.org/msg1"));
- * TDEIO::Scheduler::assignJobToSlave(slave, job1);
- * TransferJob *job2 = TDEIO::get(
- * KURL("pop3://bastian:password@mail.kde.org/msg2"));
- * TDEIO::Scheduler::assignJobToSlave(slave, job2);
- * TransferJob *job3 = TDEIO::get(
- * KURL("pop3://bastian:password@mail.kde.org/msg3"));
- * TDEIO::Scheduler::assignJobToSlave(slave, job3);
- *
- * // ... Wait for jobs to finish...
- *
- * TDEIO::Scheduler::disconnectSlave(slave);
- * \endcode
- *
- * Note that you need to explicitly disconnect the slave when the
- * connection goes down, so your error handler should contain:
- * \code
- * if (error == TDEIO::ERR_CONNECTION_BROKEN)
- * TDEIO::Scheduler::disconnectSlave(slave);
- * \endcode
- *
- * @see TDEIO::Slave
- * @see TDEIO::Job
- **/
-
- class TDEIO_EXPORT Scheduler : public TQObject, virtual public DCOPObject {
- Q_OBJECT
-
- public:
- typedef TQPtrList<SimpleJob> JobList;
-
- // InfoDict needs Info, so we can't declare it private
- class ProtocolInfo;
- class JobData;
-
- ~Scheduler();
-
- /**
- * Register @p job with the scheduler.
- * The default is to create a new slave for the job if no slave
- * is available. This can be changed by calling scheduleJob.
- * @param job the job to register
- */
- static void doJob(SimpleJob *job)
- { self()->_doJob(job); }
-
- /**
- * Calling ths function makes that @p job gets scheduled for later
- * execution, if multiple jobs are registered it might wait for
- * other jobs to finish.
- * @param job the job to schedule
- */
- static void scheduleJob(SimpleJob *job)
- { self()->_scheduleJob(job); }
-
- /**
- * Stop the execution of a job.
- * @param job the job to cancel
- */
- static void cancelJob(SimpleJob *job)
- { self()->_cancelJob(job); }
-
- /**
- * Called when a job is done.
- * @param job the finished job
- * @param slave the slave that executed the @p job
- */
- static void jobFinished(TDEIO::SimpleJob *job, TDEIO::Slave *slave)
- { self()->_jobFinished(job, slave); }
-
- /**
- * Puts a slave on notice. A next job may reuse this slave if it
- * requests the same URL.
- *
- * A job can be put on hold after it has emit'ed its mimetype.
- * Based on the mimetype, the program can give control to another
- * component in the same process which can then resume the job
- * by simply asking for the same URL again.
- * @param job the job that should be stopped
- * @param url the URL that is handled by the @p url
- */
- static void putSlaveOnHold(TDEIO::SimpleJob *job, const KURL &url)
- { self()->_putSlaveOnHold(job, url); }
-
- /**
- * Removes any slave that might have been put on hold. If a slave
- * was put on hold it will be killed.
- */
- static void removeSlaveOnHold()
- { self()->_removeSlaveOnHold(); }
-
- /**
- * Send the slave that was put on hold back to KLauncher. This
- * allows another process to take over the slave and resume the job
- * that was started.
- */
- static void publishSlaveOnHold()
- { self()->_publishSlaveOnHold(); }
-
- /**
- * Requests a slave for use in connection-oriented mode.
- *
- * @param url This defines the username,password,host & port to
- * connect with.
- * @param config Configuration data for the slave.
- *
- * @return A pointer to a connected slave or 0 if an error occurred.
- * @see assignJobToSlave()
- * @see disconnectSlave()
- */
- static TDEIO::Slave *getConnectedSlave(const KURL &url, const TDEIO::MetaData &config = MetaData() )
- { return self()->_getConnectedSlave(url, config); }
-
- /*
- * Uses @p slave to do @p job.
- * This function should be called immediately after creating a Job.
- *
- * @param slave The slave to use. The slave must have been obtained
- * with a call to getConnectedSlave and must not
- * be currently assigned to any other job.
- * @param job The job to do.
- *
- * @return true is successful, false otherwise.
- *
- * @see getConnectedSlave()
- * @see disconnectSlave()
- * @see slaveConnected()
- * @see slaveError()
- */
- static bool assignJobToSlave(TDEIO::Slave *slave, TDEIO::SimpleJob *job)
- { return self()->_assignJobToSlave(slave, job); }
-
- /*
- * Disconnects @p slave.
- *
- * @param slave The slave to disconnect. The slave must have been
- * obtained with a call to getConnectedSlave
- * and must not be assigned to any job.
- *
- * @return true is successful, false otherwise.
- *
- * @see getConnectedSlave
- * @see assignJobToSlave
- */
- static bool disconnectSlave(TDEIO::Slave *slave)
- { return self()->_disconnectSlave(slave); }
-
- /**
- * Send the slave that was put on hold back to KLauncher. This
- * allows another process to take over the slave and resume the job
- * the that was started.
- * Register the mainwindow @p wid with the KIO subsystem
- * Do not call this, it is called automatically from
- * void TDEIO::Job::setWindow(TQWidget*).
- * @param wid the window to register
- * @since 3.1
- */
- static void registerWindow(TQWidget *wid)
- { self()->_registerWindow(wid); }
-
- /**
- * @internal
- * Unregisters the window registered by registerWindow().
- */
- static void unregisterWindow(TQObject *wid)
- { self()->slotUnregisterWindow(wid); }
-
- /**
- * Function to connect signals emitted by the scheduler.
- *
- * @see slaveConnected()
- * @see slaveError()
- */
- static bool connect( const char *signal, const TQObject *receiver,
- const char *member)
- { return TQObject::connect(self(), signal, receiver, member); }
-
- static bool connect( const TQObject* sender, const char* signal,
- const TQObject* receiver, const char* member )
- { return TQObject::connect(sender, signal, receiver, member); }
-
- static bool disconnect( const TQObject* sender, const char* signal,
- const TQObject* receiver, const char* member )
- { return TQObject::disconnect(sender, signal, receiver, member); }
-
- bool connect( const TQObject *sender, const char *signal,
- const char *member )
- { return TQObject::connect(sender, signal, member); }
-
- /**
- * When true, the next job will check whether KLauncher has a slave
- * on hold that is suitable for the job.
- * @param b true when KLauncher has a job on hold
- */
- static void checkSlaveOnHold(bool b) { self()->_checkSlaveOnHold(b); }
-
- void debug_info();
-
- virtual bool process(const TQCString &fun, const TQByteArray &data,
- TQCString& replyType, TQByteArray &replyData);
-
- virtual QCStringList functions();
-
- public slots:
- void slotSlaveDied(TDEIO::Slave *slave);
- void slotSlaveStatus(pid_t pid, const TQCString &protocol,
- const TQString &host, bool connected);
- signals:
- void slaveConnected(TDEIO::Slave *slave);
- void slaveError(TDEIO::Slave *slave, int error, const TQString &errorMsg);
-
- protected:
- void setupSlave(TDEIO::Slave *slave, const KURL &url, const TQString &protocol, const TQString &proxy , bool newSlave, const TDEIO::MetaData *config=0);
- bool startJobScheduled(ProtocolInfo *protInfo);
- bool startJobDirect();
- Scheduler();
-
- protected slots:
- void startStep();
- void slotCleanIdleSlaves();
- void slotSlaveConnected();
- void slotSlaveError(int error, const TQString &errorMsg);
- void slotScheduleCoSlave();
- /// @since 3.1
- void slotUnregisterWindow(TQObject *);
-
- private:
- class ProtocolInfoDict;
- class ExtraJobData;
-
- Scheduler(const Scheduler&);
- static Scheduler *self();
- static Scheduler *instance;
- void _doJob(SimpleJob *job);
- void _scheduleJob(SimpleJob *job);
- void _cancelJob(SimpleJob *job);
- void _jobFinished(TDEIO::SimpleJob *job, TDEIO::Slave *slave);
- void _scheduleCleanup();
- void _putSlaveOnHold(TDEIO::SimpleJob *job, const KURL &url);
- void _removeSlaveOnHold();
- Slave *_getConnectedSlave(const KURL &url, const TDEIO::MetaData &metaData );
- bool _assignJobToSlave(TDEIO::Slave *slave, TDEIO::SimpleJob *job);
- bool _disconnectSlave(TDEIO::Slave *slave);
- void _checkSlaveOnHold(bool b);
- void _publishSlaveOnHold();
- void _registerWindow(TQWidget *wid);
-
- Slave *findIdleSlave(ProtocolInfo *protInfo, SimpleJob *job, bool &exact);
- Slave *createSlave(ProtocolInfo *protInfo, SimpleJob *job, const KURL &url);
-
-
- TQTimer slaveTimer;
- TQTimer coSlaveTimer;
- TQTimer cleanupTimer;
- bool busy;
-
- SlaveList *slaveList;
- SlaveList *idleSlaves;
- SlaveList *coIdleSlaves;
-
- ProtocolInfoDict *protInfoDict;
- Slave *slaveOnHold;
- KURL urlOnHold;
- JobList newJobs;
-
- TQPtrDict<JobList> coSlaves;
- ExtraJobData *extraJobData;
- SlaveConfig *slaveConfig;
- SessionData *sessionData;
- bool checkOnHold;
- TQMap<TQObject *,WId> m_windowList;
- protected:
- virtual void virtual_hook( int id, void* data );
- private:
- class SchedulerPrivate* d;
-};
-
-}
-#endif
diff --git a/kio/kio/sessiondata.cpp b/kio/kio/sessiondata.cpp
deleted file mode 100644
index e2517cc73..000000000
--- a/kio/kio/sessiondata.cpp
+++ /dev/null
@@ -1,311 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2000 Dawit Alemayehu <adawit@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License (LGPL) as published by the Free Software Foundation;
- either version 2 of the License, or (at your option) any
- later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; see the file COPYING.LIB. If not,
- write to the Free Software Foundation, Inc., 51 Franklin Street,
- Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#include <tqptrlist.h>
-#include <tqtextcodec.h>
-
-#include <kdebug.h>
-#include <kconfig.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kcharsets.h>
-#include <dcopclient.h>
-#include <kprotocolmanager.h>
-#include <kstandarddirs.h>
-
-#include <tdesu/client.h>
-#include <kio/slaveconfig.h>
-#include <kio/http_slave_defaults.h>
-
-#include "sessiondata.h"
-#include "sessiondata.moc"
-
-namespace TDEIO {
-
-/***************************** SessionData::AuthData ************************/
-struct SessionData::AuthData
-{
-
-public:
- AuthData() {}
-
- AuthData(const TQCString& k, const TQCString& g, bool p) {
- key = k;
- group = g;
- persist = p;
- }
-
- bool isKeyMatch( const TQCString& val ) const {
- return (val==key);
- }
-
- bool isGroupMatch( const TQCString& val ) const {
- return (val==group);
- }
-
- TQCString key;
- TQCString group;
- bool persist;
-};
-
-/************************* SessionData::AuthDataList ****************************/
-class SessionData::AuthDataList : public TQPtrList<SessionData::AuthData>
-{
-public:
- AuthDataList();
- ~AuthDataList();
-
- void addData( SessionData::AuthData* );
- void removeData( const TQCString& );
-
- bool pingCacheDaemon();
- void registerAuthData( SessionData::AuthData* );
- void unregisterAuthData( SessionData::AuthData* );
- void purgeCachedData();
-
-private:
-#ifdef Q_OS_UNIX
- KDEsuClient * m_tdesuClient;
-#endif
-};
-
-SessionData::AuthDataList::AuthDataList()
-{
-#ifdef Q_OS_UNIX
- m_tdesuClient = new KDEsuClient;
-#endif
- setAutoDelete(true);
-}
-
-SessionData::AuthDataList::~AuthDataList()
-{
- purgeCachedData();
-#ifdef Q_OS_UNIX
- delete m_tdesuClient;
- m_tdesuClient = 0;
-#endif
-}
-
-void SessionData::AuthDataList::addData( SessionData::AuthData* d )
-{
- TQPtrListIterator<SessionData::AuthData> it ( *this );
- for ( ; it.current(); ++it )
- {
- if ( it.current()->isKeyMatch( d->key ) )
- return;
- }
- registerAuthData( d );
- append( d );
-}
-
-void SessionData::AuthDataList::removeData( const TQCString& gkey )
-{
- TQPtrListIterator<SessionData::AuthData> it( *this );
- for( ; it.current(); ++it )
- {
- if ( it.current()->isGroupMatch(gkey) && pingCacheDaemon() )
- {
- unregisterAuthData( it.current() );
- remove( it.current() );
- }
- }
-}
-
-bool SessionData::AuthDataList::pingCacheDaemon()
-{
-#ifdef Q_OS_UNIX
- Q_ASSERT(m_tdesuClient);
-
- int success = m_tdesuClient->ping();
- if( success == -1 )
- {
- success = m_tdesuClient->startServer();
- if( success == -1 )
- return false;
- }
- return true;
-#else
- return false;
-#endif
-}
-
-void SessionData::AuthDataList::registerAuthData( SessionData::AuthData* d )
-{
- if( !pingCacheDaemon() )
- return;
-
-#ifdef Q_OS_UNIX
- bool ok;
- TQCString ref_key = d->key + "-refcount";
- int count = m_tdesuClient->getVar(ref_key).toInt( &ok );
- if( ok )
- {
- TQCString val;
- val.setNum( count+1 );
- m_tdesuClient->setVar( ref_key, val, 0, d->group );
- }
- else
- m_tdesuClient->setVar( ref_key, "1", 0, d->group );
-#endif
-}
-
-void SessionData::AuthDataList::unregisterAuthData( SessionData::AuthData* d )
-{
- if ( !d || d->persist )
- return;
-
- bool ok;
- int count;
- TQCString ref_key = d->key + "-refcount";
-
-#ifdef Q_OS_UNIX
- count = m_tdesuClient->getVar( ref_key ).toInt( &ok );
- if ( ok )
- {
- if ( count > 1 )
- {
- TQCString val;
- val.setNum(count-1);
- m_tdesuClient->setVar( ref_key, val, 0, d->group );
- }
- else
- {
- m_tdesuClient->delVars(d->key);
- }
- }
-#endif
-}
-
-void SessionData::AuthDataList::purgeCachedData()
-{
- if ( !isEmpty() && pingCacheDaemon() )
- {
- TQPtrListIterator<SessionData::AuthData> it( *this );
- for ( ; it.current(); ++it )
- unregisterAuthData( it.current() );
- }
-}
-
-/********************************* SessionData ****************************/
-
-class SessionData::SessionDataPrivate
-{
-public:
- SessionDataPrivate() {
- useCookie = true;
- initDone = false;
- }
-
- bool initDone;
- bool useCookie;
- TQString charsets;
- TQString language;
-};
-
-SessionData::SessionData()
-{
- authData = 0;
- d = new SessionDataPrivate;
-}
-
-SessionData::~SessionData()
-{
- delete d;
- delete authData;
- d = 0L;
- authData = 0L;
-}
-
-void SessionData::configDataFor( MetaData &configData, const TQString &proto,
- const TQString & )
-{
- if ( (proto.find("http", 0, false) == 0 ) ||
- (proto.find("webdav", 0, false) == 0) )
- {
- if (!d->initDone)
- reset();
-
- // These might have already been set so check first
- // to make sure that we do not trumpt settings sent
- // by apps or end-user.
- if ( configData["Cookies"].isEmpty() )
- configData["Cookies"] = d->useCookie ? "true" : "false";
- if ( configData["Languages"].isEmpty() )
- configData["Languages"] = d->language;
- if ( configData["Charsets"].isEmpty() )
- configData["Charsets"] = d->charsets;
- if ( configData["CacheDir"].isEmpty() )
- configData["CacheDir"] = TDEGlobal::dirs()->saveLocation("cache", "http");
- if ( configData["UserAgent"].isEmpty() )
- {
- configData["UserAgent"] = KProtocolManager::defaultUserAgent();
- }
- }
-}
-
-void SessionData::reset()
-{
- d->initDone = true;
- // Get Cookie settings...
- TDEConfig* cfg = new TDEConfig("kcookiejarrc", true, false);
- cfg->setGroup( "Cookie Policy" );
- d->useCookie = cfg->readBoolEntry( "Cookies", true );
- delete cfg;
-
- static const TQString & english = TDEGlobal::staticQString( "en" );
-
- // Get language settings...
- TQStringList languageList = TDEGlobal::locale()->languagesTwoAlpha();
- TQStringList::Iterator it = languageList.find( TQString::fromLatin1("C") );
- if ( it != languageList.end() )
- {
- if ( languageList.contains( english ) > 0 )
- languageList.remove( it );
- else
- (*it) = english;
- }
- if ( !languageList.contains( english ) )
- languageList.append( english );
-
- d->language = languageList.join( ", " );
-
- d->charsets = TQString::fromLatin1(TQTextCodec::codecForLocale()->mimeName()).lower();
- KProtocolManager::reparseConfiguration();
-}
-
-void SessionData::slotAuthData( const TQCString& key, const TQCString& gkey,
- bool keep )
-{
- if (!authData)
- authData = new AuthDataList;
- authData->addData( new SessionData::AuthData(key, gkey, keep) );
-}
-
-void SessionData::slotDelAuthData( const TQCString& gkey )
-{
- if (!authData)
- return;
- authData->removeData( gkey );
-}
-
-void SessionData::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-}
diff --git a/kio/kio/sessiondata.h b/kio/kio/sessiondata.h
deleted file mode 100644
index 4fef02161..000000000
--- a/kio/kio/sessiondata.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2000 Dawit Alemayehu <adawit@kde.org
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License (LGPL) as published by the Free Software Foundation;
- either version 2 of the License, or (at your option) any
- later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; see the file COPYING.LIB. If not,
- write to the Free Software Foundation, Inc., 51 Franklin Street,
- Fifth Floor, Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __KIO_SESSIONDATA_H
-#define __KIO_SESSIONDATA_H
-
-#include <tqobject.h>
-#include <kio/global.h>
-
-namespace TDEIO {
-
-class SlaveConfig;
-
-
-/**
- * @internal
- */
-class TDEIO_EXPORT SessionData : public TQObject
-{
- Q_OBJECT
-
-public:
- SessionData();
- ~SessionData();
-
- virtual void configDataFor( TDEIO::MetaData &configData, const TQString &proto,
- const TQString &host );
- virtual void reset();
-
- /// @since 3.1
- struct AuthData;
-public slots:
- void slotAuthData( const TQCString&, const TQCString&, bool );
- void slotDelAuthData( const TQCString& );
-
-private:
- class AuthDataList;
- friend class AuthDataList;
- AuthDataList* authData;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class SessionDataPrivate;
- SessionDataPrivate* d;
-};
-
-} // namespace
-
-#endif
diff --git a/kio/kio/skipdlg.cpp b/kio/kio/skipdlg.cpp
deleted file mode 100644
index f4a14a229..000000000
--- a/kio/kio/skipdlg.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kio/skipdlg.h"
-
-#include <stdio.h>
-#include <assert.h>
-
-#include <tqmessagebox.h>
-#include <tqwidget.h>
-#include <tqlayout.h>
-#include <tqlabel.h>
-
-#include <kapplication.h>
-#include <klocale.h>
-#include <kurl.h>
-#include <kpushbutton.h>
-#include <kstdguiitem.h>
-
-#ifdef Q_WS_X11
-#include <twin.h>
-#endif
-
-using namespace TDEIO;
-
-SkipDlg::SkipDlg(TQWidget *parent, bool _multi, const TQString& _error_text, bool _modal ) :
- KDialog ( parent, "" , _modal )
-{
- // TODO : port to KDialogBase
- modal = _modal;
-
- // Set "StaysOnTop", because this dialog is typically used in kio_uiserver,
- // i.e. in a separate process.
-#ifdef Q_WS_X11 //FIXME(E): Implement for QT Embedded, mac & win32
- if (modal)
- KWin::setState( winId(), NET::StaysOnTop );
-#endif
-
- b0 = b1 = b2 = 0L;
-
- setCaption( i18n( "Information" ) );
-
- b0 = new KPushButton( KStdGuiItem::cancel(), this );
- connect(b0, TQT_SIGNAL(clicked()), this, TQT_SLOT(b0Pressed()));
-
- if ( _multi )
- {
- b1 = new TQPushButton( i18n( "Skip" ), this );
- connect(b1, TQT_SIGNAL(clicked()), this, TQT_SLOT(b1Pressed()));
-
- b2 = new TQPushButton( i18n( "Auto Skip" ), this );
- connect(b2, TQT_SIGNAL(clicked()), this, TQT_SLOT(b2Pressed()));
- }
-
- TQVBoxLayout *vlayout = new TQVBoxLayout( this, 10, 0 );
- // vlayout->addStrut( 360 ); makes dlg at least that wide
-
- TQLabel * lb = new TQLabel( _error_text, this );
- lb->setFixedHeight( lb->sizeHint().height() );
- lb->setMinimumWidth( lb->sizeHint().width() );
- vlayout->addWidget( lb );
-
- vlayout->addSpacing( 10 );
-
- TQHBoxLayout* layout = new TQHBoxLayout();
- vlayout->addLayout( layout );
- if ( b0 )
- {
- b0->setDefault( true );
- b0->setFixedSize( b0->sizeHint() );
- layout->addWidget( b0 );
- layout->addSpacing( 5 );
- }
- if ( b1 )
- {
- b1->setFixedSize( b1->sizeHint() );
- layout->addWidget( b1 );
- layout->addSpacing( 5 );
- }
- if ( b2 )
- {
- b2->setFixedSize( b2->sizeHint() );
- layout->addWidget( b2 );
- layout->addSpacing( 5 );
- }
-
- vlayout->addStretch( 10 );
- vlayout->activate();
- resize( sizeHint() );
-}
-
-SkipDlg::~SkipDlg()
-{
-}
-
-void SkipDlg::b0Pressed()
-{
- if ( modal )
- done( 0 );
- else
- emit result( this, 0 );
-}
-
-void SkipDlg::b1Pressed()
-{
- if ( modal )
- done( 1 );
- else
- emit result( this, 1 );
-}
-
-void SkipDlg::b2Pressed()
-{
- if ( modal )
- done( 2 );
- else
- emit result( this, 2 );
-}
-
-SkipDlg_Result TDEIO::open_SkipDlg( bool _multi, const TQString& _error_text )
-{
- Q_ASSERT(kapp);
-
- SkipDlg dlg( 0L, _multi, _error_text, true );
- return (SkipDlg_Result) dlg.exec();
-}
-
-#include "skipdlg.moc"
diff --git a/kio/kio/slave.cpp b/kio/kio/slave.cpp
deleted file mode 100644
index 6e834f5fa..000000000
--- a/kio/kio/slave.cpp
+++ /dev/null
@@ -1,519 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (c) 2000 Waldo Bastian <bastian@kde.org>
- * 2000 Stephan Kulow <coolo@kde.org>
- *
- * $Id$
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#include <config.h>
-
-#include <time.h>
-#include <errno.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <signal.h>
-#include <sys/types.h>
-
-#include <tqfile.h>
-#include <tqtimer.h>
-
-#include <dcopclient.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kglobal.h>
-#include <kstandarddirs.h>
-#include <kapplication.h>
-#include <ktempfile.h>
-#include <ksock.h>
-#include <kprocess.h>
-#include <klibloader.h>
-
-#include "kio/dataprotocol.h"
-#include "kio/slave.h"
-#include "kio/kservice.h"
-#include <kio/global.h>
-#include <kprotocolmanager.h>
-#include <kprotocolinfo.h>
-
-#ifdef HAVE_PATHS_H
-#include <paths.h>
-#endif
-
-#ifndef _PATH_TMP
-#define _PATH_TMP "/tmp"
-#endif
-
-using namespace TDEIO;
-
-#define SLAVE_CONNECTION_TIMEOUT_MIN 2
-
-// Without debug info we consider it an error if the slave doesn't connect
-// within 10 seconds.
-// With debug info we give the slave an hour so that developers have a chance
-// to debug their slave.
-#ifdef NDEBUG
-#define SLAVE_CONNECTION_TIMEOUT_MAX 10
-#else
-#define SLAVE_CONNECTION_TIMEOUT_MAX 3600
-#endif
-
-namespace TDEIO {
-
- /**
- * @internal
- */
- class SlavePrivate {
- public:
- bool derived; // true if this instance of Slave is actually an
- // instance of a derived class.
-
- SlavePrivate(bool derived) : derived(derived) {}
- };
-}
-
-void Slave::accept(TDESocket *socket)
-{
-#ifndef Q_WS_WIN
- slaveconn.init(socket);
-#endif
- delete serv;
- serv = 0;
- slaveconn.connect(this, TQT_SLOT(gotInput()));
- unlinkSocket();
-}
-
-void Slave::unlinkSocket()
-{
- if (m_socket.isEmpty()) return;
- TQCString filename = TQFile::encodeName(m_socket);
- unlink(filename.data());
- m_socket = TQString::null;
-}
-
-void Slave::timeout()
-{
- if (!serv) return;
- kdDebug(7002) << "slave failed to connect to application pid=" << m_pid << " protocol=" << m_protocol << endl;
- if (m_pid && (::kill(m_pid, 0) == 0))
- {
- int delta_t = (int) difftime(time(0), contact_started);
- kdDebug(7002) << "slave is slow... pid=" << m_pid << " t=" << delta_t << endl;
- if (delta_t < SLAVE_CONNECTION_TIMEOUT_MAX)
- {
- TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, this, TQT_SLOT(timeout()));
- return;
- }
- }
- kdDebug(7002) << "Houston, we lost our slave, pid=" << m_pid << endl;
- delete serv;
- serv = 0;
- unlinkSocket();
- dead = true;
- TQString arg = m_protocol;
- if (!m_host.isEmpty())
- arg += "://"+m_host;
- kdDebug(7002) << "slave died pid = " << m_pid << endl;
- ref();
- // Tell the job about the problem.
- emit error(ERR_SLAVE_DIED, arg);
- // Tell the scheduler about the problem.
- emit slaveDied(this);
- // After the above signal we're dead!!
- deref();
-}
-
-Slave::Slave(TDEServerSocket *socket, const TQString &protocol, const TQString &socketname)
- : SlaveInterface(&slaveconn), serv(socket), contacted(false),
- d(new SlavePrivate(false))
-{
- m_refCount = 1;
- m_protocol = protocol;
- m_slaveProtocol = protocol;
- m_socket = socketname;
- dead = false;
- contact_started = time(0);
- idle_since = contact_started;
- m_pid = 0;
- m_port = 0;
-#ifndef Q_WS_WIN
- connect(serv, TQT_SIGNAL(accepted( TDESocket* )),
- TQT_SLOT(accept(TDESocket*) ) );
-#endif
-}
-
-Slave::Slave(bool /*derived*/, TDEServerSocket *socket, const TQString &protocol,
- const TQString &socketname)
- : SlaveInterface(&slaveconn), serv(socket), contacted(false),
- d(new SlavePrivate(true))
-{
- // FIXME: hmm, duplicating code here from public ctor, no good (LS)
- m_refCount = 1;
- m_protocol = protocol;
- m_slaveProtocol = protocol;
- m_socket = socketname;
- dead = false;
- contact_started = time(0);
- idle_since = contact_started;
- m_pid = 0;
- m_port = 0;
- if (serv != 0) {
-#ifndef Q_WS_WIN
- connect(serv, TQT_SIGNAL(accepted( TDESocket* )),
- TQT_SLOT(accept(TDESocket*) ) );
-#endif
- }
-}
-
-Slave::~Slave()
-{
- // kdDebug(7002) << "destructing slave object pid = " << m_pid << endl;
- if (serv != 0) {
- delete serv;
- serv = 0;
- }
- unlinkSocket();
- m_pid = 99999;
- delete d;
- d = 0;
-}
-
-void Slave::setProtocol(const TQString & protocol)
-{
- m_protocol = protocol;
-}
-
-void Slave::setIdle()
-{
- idle_since = time(0);
-}
-
-time_t Slave::idleTime()
-{
- return (time_t) difftime(time(0), idle_since);
-}
-
-void Slave::setPID(pid_t pid)
-{
- m_pid = pid;
-}
-
-void Slave::hold(const KURL &url)
-{
- if (d->derived) { // TODO: clean up before KDE 4
- HoldParams params;
- params.url = &url;
- virtual_hook(VIRTUAL_HOLD, &params);
- return;
- }/*end if*/
-
- ref();
- {
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly );
- stream << url;
- slaveconn.send( CMD_SLAVE_HOLD, data );
- slaveconn.close();
- dead = true;
- emit slaveDied(this);
- }
- deref();
- // Call KLauncher::waitForSlave(pid);
- {
- DCOPClient *client = kapp->dcopClient();
- if (!client->isAttached())
- client->attach();
-
- TQByteArray params, reply;
- TQCString replyType;
- TQDataStream stream(params, IO_WriteOnly);
- pid_t pid = m_pid;
- stream << pid;
-
- TQCString launcher = TDEApplication::launcher();
- client->call(launcher, launcher, "waitForSlave(pid_t)",
- params, replyType, reply);
- }
-}
-
-void Slave::suspend()
-{
- if (d->derived) { // TODO: clean up before KDE 4
- virtual_hook(VIRTUAL_SUSPEND, 0);
- return;
- }/*end if*/
-
- slaveconn.suspend();
-}
-
-void Slave::resume()
-{
- if (d->derived) { // TODO: clean up before KDE 4
- virtual_hook(VIRTUAL_RESUME, 0);
- return;
- }/*end if*/
-
- slaveconn.resume();
-}
-
-bool Slave::suspended()
-{
- if (d->derived) { // TODO: clean up before KDE 4
- SuspendedParams params;
- virtual_hook(VIRTUAL_SUSPENDED, &params);
- return params.retval;
- }/*end if*/
-
- return slaveconn.suspended();
-}
-
-void Slave::send(int cmd, const TQByteArray &arr) {
- if (d->derived) { // TODO: clean up before KDE 4
- SendParams params;
- params.cmd = cmd;
- params.arr = &arr;
- virtual_hook(VIRTUAL_SEND, &params);
- return;
- }/*end if*/
-
- slaveconn.send(cmd, arr);
-}
-
-void Slave::gotInput()
-{
- ref();
- if (!dispatch())
- {
- slaveconn.close();
- dead = true;
- TQString arg = m_protocol;
- if (!m_host.isEmpty())
- arg += "://"+m_host;
- kdDebug(7002) << "slave died pid = " << m_pid << endl;
- // Tell the job about the problem.
- emit error(ERR_SLAVE_DIED, arg);
- // Tell the scheduler about the problem.
- emit slaveDied(this);
- }
- deref();
- // Here we might be dead!!
-}
-
-void Slave::kill()
-{
- dead = true; // OO can be such simple.
- kdDebug(7002) << "killing slave pid=" << m_pid << " (" << m_protocol << "://"
- << m_host << ")" << endl;
- if (m_pid)
- {
- ::kill(m_pid, SIGTERM);
- }
-}
-
-void Slave::setHost( const TQString &host, int port,
- const TQString &user, const TQString &passwd)
-{
- m_host = host;
- m_port = port;
- m_user = user;
- m_passwd = passwd;
-
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly );
- stream << m_host << m_port << m_user << m_passwd;
- slaveconn.send( CMD_HOST, data );
-}
-
-void Slave::resetHost()
-{
- m_host = "<reset>";
-}
-
-void Slave::setConfig(const MetaData &config)
-{
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly );
- stream << config;
- slaveconn.send( CMD_CONFIG, data );
-}
-
-Slave* Slave::createSlave( const TQString &protocol, const KURL& url, int& error, TQString& error_text )
-{
- //kdDebug(7002) << "createSlave '" << protocol << "' for " << url.prettyURL() << endl;
- // Firstly take into account all special slaves
- if (protocol == "data")
- return new DataProtocol();
-
- DCOPClient *client = kapp->dcopClient();
- if (!client->isAttached())
- client->attach();
-
- TQString prefix = locateLocal("socket", TDEGlobal::instance()->instanceName());
- KTempFile socketfile(prefix, TQString::fromLatin1(".slave-socket"));
- if ( socketfile.status() != 0 )
- {
- error_text = i18n("Unable to create io-slave: %1").arg(strerror(errno));
- error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
- return 0;
- }
-
-#ifdef __CYGWIN__
- socketfile.close();
-#endif
-
-#ifndef Q_WS_WIN
- TDEServerSocket *kss = new TDEServerSocket(TQFile::encodeName(socketfile.name()).data());
-
- Slave *slave = new Slave(kss, protocol, socketfile.name());
-#else
- Slave *slave = 0;
-#endif
-
- // WABA: if the dcopserver is running under another uid we don't ask
- // klauncher for a slave, because the slave might have that other uid
- // as well, which might either be a) undesired or b) make it impossible
- // for the slave to connect to the application.
- // In such case we start the slave via TDEProcess.
- // It's possible to force this by setting the env. variable
- // TDE_FORK_SLAVES, Clearcase seems to require this.
- static bool bForkSlaves = !TQCString(getenv("TDE_FORK_SLAVES")).isEmpty();
-
- if (bForkSlaves || !client->isAttached() || client->isAttachedToForeignServer())
- {
- TQString _name = KProtocolInfo::exec(protocol);
- if (_name.isEmpty())
- {
- error_text = i18n("Unknown protocol '%1'.").arg(protocol);
- error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
- delete slave;
- return 0;
- }
- TQString lib_path = KLibLoader::findLibrary(_name.latin1());
- if (lib_path.isEmpty())
- {
- error_text = i18n("Can not find io-slave for protocol '%1'.").arg(protocol);
- error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
- return 0;
- }
-
- TDEProcess proc;
-
- proc << locate("exe", "kioslave") << lib_path << protocol << "" << socketfile.name();
- kdDebug(7002) << "kioslave" << ", " << lib_path << ", " << protocol << ", " << TQString::null << ", " << socketfile.name() << endl;
-
- proc.start(TDEProcess::DontCare);
-
-#ifndef Q_WS_WIN
- slave->setPID(proc.pid());
- TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, slave, TQT_SLOT(timeout()));
-#endif
- return slave;
- }
-
-
- TQByteArray params, reply;
- TQCString replyType;
- TQDataStream stream(params, IO_WriteOnly);
- stream << protocol << url.host() << socketfile.name();
-
- TQCString launcher = TDEApplication::launcher();
- if (!client->call(launcher, launcher, "requestSlave(TQString,TQString,TQString)",
- params, replyType, reply)) {
- error_text = i18n("Cannot talk to klauncher");
- error = TDEIO::ERR_SLAVE_DEFINED;
- delete slave;
- return 0;
- }
- TQDataStream stream2(reply, IO_ReadOnly);
- TQString errorStr;
- pid_t pid;
- stream2 >> pid >> errorStr;
- if (!pid)
- {
- error_text = i18n("Unable to create io-slave:\nklauncher said: %1").arg(errorStr);
- error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
- delete slave;
- return 0;
- }
-#ifndef Q_WS_WIN
- slave->setPID(pid);
- TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, slave, TQT_SLOT(timeout()));
-#endif
- return slave;
-}
-
-Slave* Slave::holdSlave( const TQString &protocol, const KURL& url )
-{
- //kdDebug(7002) << "holdSlave '" << protocol << "' for " << url.prettyURL() << endl;
- // Firstly take into account all special slaves
- if (protocol == "data")
- return 0;
-
- DCOPClient *client = kapp->dcopClient();
- if (!client->isAttached())
- client->attach();
-
- TQString prefix = locateLocal("socket", TDEGlobal::instance()->instanceName());
- KTempFile socketfile(prefix, TQString::fromLatin1(".slave-socket"));
- if ( socketfile.status() != 0 )
- return 0;
-
-#ifdef __CYGWIN__
- socketfile.close();
- socketfile.unlink();
-#endif
-
-#ifndef Q_WS_WIN
- TDEServerSocket *kss = new TDEServerSocket(TQFile::encodeName(socketfile.name()).data());
-
- Slave *slave = new Slave(kss, protocol, socketfile.name());
-#else
- Slave *slave = 0;
-#endif
-
- TQByteArray params, reply;
- TQCString replyType;
- TQDataStream stream(params, IO_WriteOnly);
- stream << url << socketfile.name();
-
- TQCString launcher = TDEApplication::launcher();
- if (!client->call(launcher, launcher, "requestHoldSlave(KURL,TQString)",
- params, replyType, reply)) {
- delete slave;
- return 0;
- }
- TQDataStream stream2(reply, IO_ReadOnly);
- pid_t pid;
- stream2 >> pid;
- if (!pid)
- {
- delete slave;
- return 0;
- }
-#ifndef Q_WS_WIN
- slave->setPID(pid);
- TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, slave, TQT_SLOT(timeout()));
-#endif
- return slave;
-}
-
-void Slave::virtual_hook( int id, void* data ) {
- TDEIO::SlaveInterface::virtual_hook( id, data );
-}
-
-#include "slave.moc"
diff --git a/kio/kio/slave.h b/kio/kio/slave.h
deleted file mode 100644
index 6f9f02a2f..000000000
--- a/kio/kio/slave.h
+++ /dev/null
@@ -1,270 +0,0 @@
-// -*- c++ -*-
-/*
- * This file is part of the KDE libraries
- * Copyright (c) 2000 Waldo Bastian <bastian@kde.org>
- * 2000 Stephan Kulow <coolo@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#ifndef KIO_SLAVE_H
-#define KIO_SLAVE_H
-
-#include <time.h>
-#include <unistd.h>
-
-#include <tqobject.h>
-
-#include <kurl.h>
-
-#include "kio/slaveinterface.h"
-#include "kio/connection.h"
-
-class TDEServerSocket;
-class TDESocket;
-
-namespace TDEIO {
-
- /** Attention developers: If you change the implementation of TDEIO::Slave,
- * do *not* use connection() or slaveconn but the respective TDEIO::Slave
- * accessor methods. Otherwise classes derived from Slave might break. (LS)
- */
- class TDEIO_EXPORT Slave : public TDEIO::SlaveInterface
- {
- Q_OBJECT
-
-
- protected:
- /**
- * Use this constructor if you derive your own class from Slave
- * @p derived must be true in any case
- * @internal
- * @since 3.2
- */
- Slave(bool derived, TDEServerSocket *unixdomain, const TQString &protocol,
- const TQString &socketname); // TODO(BIC): Remove in KDE 4
-
- public:
- Slave(TDEServerSocket *unixdomain,
- const TQString &protocol, const TQString &socketname);
-
- virtual ~Slave();
-
- void setPID(pid_t);
-
- int slave_pid() { return m_pid; }
-
- /**
- * Force termination
- */
- void kill();
-
- /**
- * @return true if the slave survived the last mission.
- */
- bool isAlive() { return !dead; }
-
- /**
- * Set host for url
- * @param host to connect to.
- * @param port to connect to.
- * @param user to login as
- * @param passwd to login with
- */
- void setHost( const TQString &host, int port,
- const TQString &user, const TQString &passwd); // TODO(BIC): make virtual
-
- /**
- * Clear host info.
- */
- void resetHost();
-
- /**
- * Configure slave
- */
- void setConfig(const MetaData &config); // TODO(BIC): make virtual
-
- /**
- * The protocol this slave handles.
- *
- * @return name of protocol handled by this slave, as seen by the user
- */
- TQString protocol() { return m_protocol; }
-
- void setProtocol(const TQString & protocol);
- /**
- * The actual protocol used to handle the request.
- *
- * This method will return a different protocol than
- * the one obtained by using protocol() if a
- * proxy-server is used for the given protocol. This
- * usually means that this method will return "http"
- * when the actuall request was to retrieve a resource
- * from an "ftp" server by going through a proxy server.
- *
- * @return the actual protocol (io-slave) that handled the request
- */
- TQString slaveProtocol() { return m_slaveProtocol; }
-
- /**
- * @return Host this slave is (was?) connected to
- */
- TQString host() { return m_host; }
-
- /**
- * @return port this slave is (was?) connected to
- */
- int port() { return m_port; }
-
- /**
- * @return User this slave is (was?) logged in as
- */
- TQString user() { return m_user; }
-
- /**
- * @return Passwd used to log in
- */
- TQString passwd() { return m_passwd; }
-
- /**
- * Creates a new slave.
- *
- * @param protocol protocol the slave is for.
- * @param url URL the slave should operate on.
- * @param error is the error code on failure and undefined else.
- * @param error_text is the error text on failure and undefined else.
- *
- * @return 0 on failure, or a pointer to a slave otherwise.
- * @todo What are legal @p protocol values?
- */
- static Slave* createSlave( const TQString &protocol, const KURL& url, int& error, TQString& error_text );
-
- static Slave* holdSlave( const TQString &protocol, const KURL& url );
-
- // == communication with connected kioslave ==
- // whenever possible prefer these methods over the respective
- // methods in connection()
- /**
- * Suspends the operation of the attached kioslave.
- */
- void suspend(); // TODO(BIC): make virtual
- /**
- * Resumes the operation of the attached kioslave.
- */
- void resume(); // TODO(BIC): make virtual
- /**
- * Tells wether the kioslave is suspended.
- * @return true if the kioslave is suspended.
- * @since 3.2
- */
- bool suspended(); // TODO(BIC): make virtual
- /**
- * Sends the given command to the kioslave.
- * @param cmd command id
- * @param data byte array containing data
- * @since 3.2
- */
- void send(int cmd, const TQByteArray &data = TQByteArray());// TODO(BIC): make virtual
- // == end communication with connected kioslave ==
-
- /**
- * Puts the kioslave associated with @p url at halt.
- */
- void hold(const KURL &url); // TODO(BIC): make virtual
-
- /**
- * @return The time this slave has been idle.
- */
- time_t idleTime();
-
- /**
- * Marks this slave as idle.
- */
- void setIdle();
-
- /*
- * @returns Whether the slave is connected
- * (Connection oriented slaves only)
- */
- bool isConnected() { return contacted; }
- void setConnected(bool c) { contacted = c; }
-
- /** @deprecated This method is obsolete, use the accessor methods
- * within TDEIO::Slave instead. Old code directly accessing connection()
- * will not be able to access special protocols.
- */
- KDE_DEPRECATED Connection *connection() { return &slaveconn; } // TODO(BIC): remove before KDE 4
-
- void ref() { m_refCount++; }
- void deref() { m_refCount--; if (!m_refCount) delete this; }
-
- public slots:
- void accept(TDESocket *socket);
- void gotInput();
- void timeout();
- signals:
- void slaveDied(TDEIO::Slave *slave);
-
- protected:
- void unlinkSocket();
-
- private:
- TQString m_protocol;
- TQString m_slaveProtocol;
- TQString m_host;
- int m_port;
- TQString m_user;
- TQString m_passwd;
- TDEServerSocket *serv;
- TQString m_socket;
- pid_t m_pid;
- bool contacted;
- bool dead;
- time_t contact_started;
- time_t idle_since;
- TDEIO::Connection slaveconn;
- int m_refCount;
- protected:
- virtual void virtual_hook( int id, void* data );
- // grant SlaveInterface all IDs < 0x200
- enum { VIRTUAL_SUSPEND = 0x200, VIRTUAL_RESUME, VIRTUAL_SEND,
- VIRTUAL_HOLD, VIRTUAL_SUSPENDED,
- VIRTUAL_SET_HOST, VIRTUAL_SET_CONFIG };
- struct SendParams {
- int cmd;
- const TQByteArray *arr;
- };
- struct HoldParams {
- const KURL *url;
- };
- struct SuspendedParams {
- bool retval;
- };
- struct SetHostParams {
- const TQString *host;
- int port;
- const TQString *user;
- const TQString *passwd;
- };
- struct SetConfigParams {
- const MetaData *config;
- };
- private:
- class SlavePrivate* d;
- };
-
-}
-
-#endif
diff --git a/kio/kio/slavebase.cpp b/kio/kio/slavebase.cpp
deleted file mode 100644
index 07d784527..000000000
--- a/kio/kio/slavebase.cpp
+++ /dev/null
@@ -1,1315 +0,0 @@
-/*
- *
- * This file is part of the KDE libraries
- * Copyright (c) 2000 Waldo Bastian <bastian@kde.org>
- * Copyright (c) 2000 David Faure <faure@kde.org>
- * Copyright (c) 2000 Stephan Kulow <coolo@kde.org>
- *
- * $Id$
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- **/
-
-#include "slavebase.h"
-
-#include <config.h>
-
-#include <sys/time.h>
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h> // Needed on some systems.
-#endif
-
-#include <assert.h>
-#include <kdebug.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <unistd.h>
-#include <signal.h>
-#include <time.h>
-
-#include <tqfile.h>
-
-#include <dcopclient.h>
-
-#include <kapplication.h>
-#include <ksock.h>
-#include <kcrash.h>
-#include <tdesu/client.h>
-#include <klocale.h>
-#include <ksocks.h>
-
-#include "kremoteencoding.h"
-
-#include "kio/slavebase.h"
-#include "kio/connection.h"
-#include "kio/ioslave_defaults.h"
-#include "kio/slaveinterface.h"
-
-#include "uiserver_stub.h"
-
-#ifndef NDEBUG
-#ifdef HAVE_BACKTRACE
-#include <execinfo.h>
-#endif
-#endif
-
-using namespace TDEIO;
-
-template class TQPtrList<TQValueList<UDSAtom> >;
-typedef TQValueList<TQCString> AuthKeysList;
-typedef TQMap<TQString,TQCString> AuthKeysMap;
-#define KIO_DATA TQByteArray data; TQDataStream stream( data, IO_WriteOnly ); stream
-#define KIO_FILESIZE_T(x) (unsigned long)(x & 0xffffffff) << (unsigned long)(x >> 32)
-
-namespace TDEIO {
-
-class SlaveBaseConfig : public TDEConfigBase
-{
-public:
- SlaveBaseConfig(SlaveBase *_slave)
- : slave(_slave) { }
-
- bool internalHasGroup(const TQCString &) const { tqWarning("hasGroup(const TQCString &)");
-return false; }
-
- TQStringList groupList() const { return TQStringList(); }
-
- TQMap<TQString,TQString> entryMap(const TQString &group) const
- { Q_UNUSED(group); return TQMap<TQString,TQString>(); }
-
- void reparseConfiguration() { }
-
- KEntryMap internalEntryMap( const TQString &pGroup) const { Q_UNUSED(pGroup); return KEntryMap(); }
-
- KEntryMap internalEntryMap() const { return KEntryMap(); }
-
- void putData(const KEntryKey &_key, const KEntry&_data, bool _checkGroup)
- { Q_UNUSED(_key); Q_UNUSED(_data); Q_UNUSED(_checkGroup); }
-
- KEntry lookupData(const KEntryKey &_key) const
- {
- KEntry entry;
- TQString value = slave->metaData(_key.c_key);
- if (!value.isNull())
- entry.mValue = value.utf8();
- return entry;
- }
-protected:
- SlaveBase *slave;
-};
-
-
-class SlaveBasePrivate {
-public:
- TQString slaveid;
- bool resume:1;
- bool needSendCanResume:1;
- bool onHold:1;
- bool wasKilled:1;
- MetaData configData;
- SlaveBaseConfig *config;
- KURL onHoldUrl;
-
- struct timeval last_tv;
- TDEIO::filesize_t totalSize;
- TDEIO::filesize_t sentListEntries;
- DCOPClient *dcopClient;
- KRemoteEncoding *remotefile;
- time_t timeout;
- TQByteArray timeoutData;
-};
-
-}
-
-static SlaveBase *globalSlave;
-long SlaveBase::s_seqNr;
-
-static volatile bool slaveWriteError = false;
-
-static const char *s_protocol;
-
-#ifdef Q_OS_UNIX
-static void genericsig_handler(int sigNumber)
-{
- signal(sigNumber,SIG_IGN);
- //WABA: Don't do anything that requires malloc, we can deadlock on it since
- //a SIGTERM signal can come in while we are in malloc/free.
- //kdDebug()<<"kioslave : exiting due to signal "<<sigNumber<<endl;
- //set the flag which will be checked in dispatchLoop() and which *should* be checked
- //in lengthy operations in the various slaves
- if (globalSlave!=0)
- globalSlave->setKillFlag();
- signal(SIGALRM,SIG_DFL);
- alarm(5); //generate an alarm signal in 5 seconds, in this time the slave has to exit
-}
-#endif
-
-//////////////
-
-SlaveBase::SlaveBase( const TQCString &protocol,
- const TQCString &pool_socket,
- const TQCString &app_socket )
- : mProtocol(protocol), m_pConnection(0),
- mPoolSocket( TQFile::decodeName(pool_socket)),
- mAppSocket( TQFile::decodeName(app_socket))
-{
- s_protocol = protocol.data();
-#ifdef Q_OS_UNIX
- if (!getenv("TDE_DEBUG"))
- {
- KCrash::setCrashHandler( sigsegv_handler );
- signal(SIGILL,&sigsegv_handler);
- signal(SIGTRAP,&sigsegv_handler);
- signal(SIGABRT,&sigsegv_handler);
- signal(SIGBUS,&sigsegv_handler);
- signal(SIGALRM,&sigsegv_handler);
- signal(SIGFPE,&sigsegv_handler);
-#ifdef SIGPOLL
- signal(SIGPOLL, &sigsegv_handler);
-#endif
-#ifdef SIGSYS
- signal(SIGSYS, &sigsegv_handler);
-#endif
-#ifdef SIGVTALRM
- signal(SIGVTALRM, &sigsegv_handler);
-#endif
-#ifdef SIGXCPU
- signal(SIGXCPU, &sigsegv_handler);
-#endif
-#ifdef SIGXFSZ
- signal(SIGXFSZ, &sigsegv_handler);
-#endif
- }
-
- struct sigaction act;
- act.sa_handler = sigpipe_handler;
- sigemptyset( &act.sa_mask );
- act.sa_flags = 0;
- sigaction( SIGPIPE, &act, 0 );
-
- signal(SIGINT,&genericsig_handler);
- signal(SIGQUIT,&genericsig_handler);
- signal(SIGTERM,&genericsig_handler);
-#endif
-
- globalSlave=this;
-
- appconn = new Connection();
- listEntryCurrentSize = 100;
- struct timeval tp;
- gettimeofday(&tp, 0);
- listEntry_sec = tp.tv_sec;
- listEntry_usec = tp.tv_usec;
- mConnectedToApp = true;
-
- d = new SlaveBasePrivate;
- // by kahl for netmgr (need a way to identify slaves)
- d->slaveid = protocol;
- d->slaveid += TQString::number(getpid());
- d->resume = false;
- d->needSendCanResume = false;
- d->config = new SlaveBaseConfig(this);
- d->onHold = false;
- d->wasKilled=false;
- d->last_tv.tv_sec = 0;
- d->last_tv.tv_usec = 0;
-// d->processed_size = 0;
- d->totalSize=0;
- d->sentListEntries=0;
- d->timeout = 0;
- connectSlave(mAppSocket);
-
- d->dcopClient = 0;
- d->remotefile = 0;
-}
-
-SlaveBase::~SlaveBase()
-{
- delete d;
- s_protocol = "";
-}
-
-DCOPClient *SlaveBase::dcopClient()
-{
- if (!d->dcopClient)
- {
- d->dcopClient = TDEApplication::dcopClient();
- if (!d->dcopClient->isAttached())
- d->dcopClient->attach();
- d->dcopClient->setDaemonMode( true );
- }
- return d->dcopClient;
-}
-
-void SlaveBase::dispatchLoop()
-{
-#ifdef Q_OS_UNIX //TODO: WIN32
- fd_set rfds;
- int retval;
-
- while (true)
- {
- if (d->timeout && (d->timeout < time(0)))
- {
- TQByteArray data = d->timeoutData;
- d->timeout = 0;
- d->timeoutData = TQByteArray();
- special(data);
- }
- FD_ZERO(&rfds);
-
- assert(appconn->inited());
- int maxfd = appconn->fd_from();
- FD_SET(appconn->fd_from(), &rfds);
- if( d->dcopClient )
- {
- FD_SET( d->dcopClient->socket(), &rfds );
- if( d->dcopClient->socket() > maxfd )
- maxfd = d->dcopClient->socket();
- }
-
- if (!d->timeout) // we can wait forever
- {
- retval = select( maxfd + 1, &rfds, NULL, NULL, NULL);
- }
- else
- {
- struct timeval tv;
- tv.tv_sec = kMax(d->timeout-time(0),(time_t) 1);
- tv.tv_usec = 0;
- retval = select( maxfd + 1, &rfds, NULL, NULL, &tv);
- }
- if ((retval>0) && FD_ISSET(appconn->fd_from(), &rfds))
- { // dispatch application messages
- int cmd;
- TQByteArray data;
- if ( appconn->read(&cmd, data) != -1 )
- {
- dispatch(cmd, data);
- }
- else // some error occurred, perhaps no more application
- {
- // When the app exits, should the slave be put back in the pool ?
- if (mConnectedToApp && !mPoolSocket.isEmpty())
- {
- disconnectSlave();
- mConnectedToApp = false;
- closeConnection();
- connectSlave(mPoolSocket);
- }
- else
- {
- return;
- }
- }
- }
- if( retval > 0 && d->dcopClient && FD_ISSET( d->dcopClient->socket(), &rfds ))
- {
- d->dcopClient->processSocketData( d->dcopClient->socket());
- }
- if ((retval<0) && (errno != EINTR))
- {
- kdDebug(7019) << "dispatchLoop(): select returned " << retval << " "
- << (errno==EBADF?"EBADF":errno==EINTR?"EINTR":errno==EINVAL?"EINVAL":errno==ENOMEM?"ENOMEM":"unknown")
- << " (" << errno << ")" << endl;
- return;
- }
- //I think we get here when we were killed in dispatch() and not in select()
- if (wasKilled())
- {
- kdDebug(7019)<<" dispatchLoop() slave was killed, returning"<<endl;
- return;
- }
- }
-#else
-#error The KIO slave system only works under UNIX
-#endif
-}
-
-void SlaveBase::connectSlave(const TQString& path)
-{
-#ifdef Q_OS_UNIX //TODO: TDESocket not yet available on WIN32
- appconn->init(new TDESocket(TQFile::encodeName(path).data()));
- if (!appconn->inited())
- {
- kdDebug(7019) << "SlaveBase: failed to connect to " << path << endl;
- exit();
- }
-
- setConnection(appconn);
-#endif
-}
-
-void SlaveBase::disconnectSlave()
-{
- appconn->close();
-}
-
-void SlaveBase::setMetaData(const TQString &key, const TQString &value)
-{
- mOutgoingMetaData.replace(key, value);
-}
-
-TQString SlaveBase::metaData(const TQString &key) const
-{
- if (mIncomingMetaData.contains(key))
- return mIncomingMetaData[key];
- if (d->configData.contains(key))
- return d->configData[key];
- return TQString::null;
-}
-
-bool SlaveBase::hasMetaData(const TQString &key) const
-{
- if (mIncomingMetaData.contains(key))
- return true;
- if (d->configData.contains(key))
- return true;
- return false;
-}
-
-// ### remove the next two methods for KDE4 (they miss the const)
-TQString SlaveBase::metaData(const TQString &key) {
- return const_cast<const SlaveBase*>(this)->metaData( key );
-}
-bool SlaveBase::hasMetaData(const TQString &key) {
- return const_cast<const SlaveBase*>(this)->hasMetaData( key );
-}
-
-TDEConfigBase *SlaveBase::config()
-{
- return d->config;
-}
-
-void SlaveBase::sendMetaData()
-{
- KIO_DATA << mOutgoingMetaData;
-
- slaveWriteError = false;
- m_pConnection->send( INF_META_DATA, data );
- if (slaveWriteError) exit();
- mOutgoingMetaData.clear(); // Clear
-}
-
-KRemoteEncoding *SlaveBase::remoteEncoding()
-{
- if (d->remotefile != 0)
- return d->remotefile;
-
- return d->remotefile = new KRemoteEncoding(metaData("Charset").latin1());
-}
-
-void SlaveBase::data( const TQByteArray &data )
-{
- if (!mOutgoingMetaData.isEmpty())
- sendMetaData();
- slaveWriteError = false;
- m_pConnection->send( MSG_DATA, data );
- if (slaveWriteError) exit();
-}
-
-void SlaveBase::dataReq( )
-{
-/*
- if (!mOutgoingMetaData.isEmpty())
- sendMetaData();
-*/
- if (d->needSendCanResume)
- canResume(0);
- m_pConnection->send( MSG_DATA_REQ );
-}
-
-void SlaveBase::error( int _errid, const TQString &_text )
-{
- mIncomingMetaData.clear(); // Clear meta data
- mOutgoingMetaData.clear();
- KIO_DATA << (TQ_INT32) _errid << _text;
-
- m_pConnection->send( MSG_ERROR, data );
- //reset
- listEntryCurrentSize = 100;
- d->sentListEntries=0;
- d->totalSize=0;
-}
-
-void SlaveBase::connected()
-{
- slaveWriteError = false;
- m_pConnection->send( MSG_CONNECTED );
- if (slaveWriteError) exit();
-}
-
-void SlaveBase::finished()
-{
- mIncomingMetaData.clear(); // Clear meta data
- if (!mOutgoingMetaData.isEmpty())
- sendMetaData();
- m_pConnection->send( MSG_FINISHED );
-
- // reset
- listEntryCurrentSize = 100;
- d->sentListEntries=0;
- d->totalSize=0;
-}
-
-void SlaveBase::needSubURLData()
-{
- m_pConnection->send( MSG_NEED_SUBURL_DATA );
-}
-
-void SlaveBase::slaveStatus( const TQString &host, bool connected )
-{
- pid_t pid = getpid();
- TQ_INT8 b = connected ? 1 : 0;
- KIO_DATA << pid << mProtocol << host << b;
- if (d->onHold)
- stream << d->onHoldUrl;
- m_pConnection->send( MSG_SLAVE_STATUS, data );
-}
-
-void SlaveBase::canResume()
-{
- m_pConnection->send( MSG_CANRESUME );
-}
-
-void SlaveBase::totalSize( TDEIO::filesize_t _bytes )
-{
- KIO_DATA << KIO_FILESIZE_T(_bytes);
- slaveWriteError = false;
- m_pConnection->send( INF_TOTAL_SIZE, data );
- if (slaveWriteError) exit();
-
- //this one is usually called before the first item is listed in listDir()
- struct timeval tp;
- gettimeofday(&tp, 0);
- listEntry_sec = tp.tv_sec;
- listEntry_usec = tp.tv_usec;
- d->totalSize=_bytes;
- d->sentListEntries=0;
-}
-
-void SlaveBase::processedSize( TDEIO::filesize_t _bytes )
-{
- bool emitSignal=false;
- struct timeval tv;
- int gettimeofday_res=gettimeofday( &tv, 0L );
-
- if( _bytes == d->totalSize )
- emitSignal=true;
- else if ( gettimeofday_res == 0 ) {
- time_t msecdiff = 2000;
- if (d->last_tv.tv_sec) {
- // Compute difference, in ms
- msecdiff = 1000 * ( tv.tv_sec - d->last_tv.tv_sec );
- time_t usecdiff = tv.tv_usec - d->last_tv.tv_usec;
- if ( usecdiff < 0 ) {
- msecdiff--;
- msecdiff += 1000;
- }
- msecdiff += usecdiff / 1000;
- }
- emitSignal=msecdiff >= 100; // emit size 10 times a second
- }
-
- if( emitSignal ) {
- KIO_DATA << KIO_FILESIZE_T(_bytes);
- slaveWriteError = false;
- m_pConnection->send( INF_PROCESSED_SIZE, data );
- if (slaveWriteError) exit();
- if ( gettimeofday_res == 0 ) {
- d->last_tv.tv_sec = tv.tv_sec;
- d->last_tv.tv_usec = tv.tv_usec;
- }
- }
-// d->processed_size = _bytes;
-}
-
-void SlaveBase::processedPercent( float /* percent */ )
-{
- kdDebug(7019) << "SlaveBase::processedPercent: STUB" << endl;
-}
-
-
-void SlaveBase::speed( unsigned long _bytes_per_second )
-{
- KIO_DATA << (TQ_UINT32) _bytes_per_second;
- slaveWriteError = false;
- m_pConnection->send( INF_SPEED, data );
- if (slaveWriteError) exit();
-}
-
-void SlaveBase::redirection( const KURL& _url )
-{
- KIO_DATA << _url;
- m_pConnection->send( INF_REDIRECTION, data );
-}
-
-void SlaveBase::errorPage()
-{
- m_pConnection->send( INF_ERROR_PAGE );
-}
-
-static bool isSubCommand(int cmd)
-{
- return ( (cmd == CMD_REPARSECONFIGURATION) ||
- (cmd == CMD_META_DATA) ||
- (cmd == CMD_CONFIG) ||
- (cmd == CMD_SUBURL) ||
- (cmd == CMD_SLAVE_STATUS) ||
- (cmd == CMD_SLAVE_CONNECT) ||
- (cmd == CMD_SLAVE_HOLD) ||
- (cmd == CMD_MULTI_GET));
-}
-
-void SlaveBase::mimeType( const TQString &_type)
-{
- // kdDebug(7019) << "(" << getpid() << ") SlaveBase::mimeType '" << _type << "'" << endl;
- int cmd;
- do
- {
- // Send the meta-data each time we send the mime-type.
- if (!mOutgoingMetaData.isEmpty())
- {
- // kdDebug(7019) << "(" << getpid() << ") mimeType: emitting meta data" << endl;
- KIO_DATA << mOutgoingMetaData;
- m_pConnection->send( INF_META_DATA, data );
- }
- KIO_DATA << _type;
- m_pConnection->send( INF_MIME_TYPE, data );
- while(true)
- {
- cmd = 0;
- if ( m_pConnection->read( &cmd, data ) == -1 ) {
- kdDebug(7019) << "SlaveBase: mimetype: read error" << endl;
- exit();
- }
- // kdDebug(7019) << "(" << getpid() << ") Slavebase: mimetype got " << cmd << endl;
- if ( cmd == CMD_HOST) // Ignore.
- continue;
- if ( isSubCommand(cmd) )
- {
- dispatch( cmd, data );
- continue; // Disguised goto
- }
- break;
- }
- }
- while (cmd != CMD_NONE);
- mOutgoingMetaData.clear();
-}
-
-void SlaveBase::exit()
-{
- this->~SlaveBase();
- ::exit(255);
-}
-
-void SlaveBase::warning( const TQString &_msg)
-{
- KIO_DATA << _msg;
- m_pConnection->send( INF_WARNING, data );
-}
-
-void SlaveBase::infoMessage( const TQString &_msg)
-{
- KIO_DATA << _msg;
- m_pConnection->send( INF_INFOMESSAGE, data );
-}
-
-bool SlaveBase::requestNetwork(const TQString& host)
-{
- KIO_DATA << host << d->slaveid;
- m_pConnection->send( MSG_NET_REQUEST, data );
-
- if ( waitForAnswer( INF_NETWORK_STATUS, 0, data ) != -1 )
- {
- bool status;
- TQDataStream stream( data, IO_ReadOnly );
- stream >> status;
- return status;
- } else
- return false;
-}
-
-void SlaveBase::dropNetwork(const TQString& host)
-{
- KIO_DATA << host << d->slaveid;
- m_pConnection->send( MSG_NET_DROP, data );
-}
-
-void SlaveBase::statEntry( const UDSEntry& entry )
-{
- KIO_DATA << entry;
- slaveWriteError = false;
- m_pConnection->send( MSG_STAT_ENTRY, data );
- if (slaveWriteError) exit();
-}
-
-void SlaveBase::listEntry( const UDSEntry& entry, bool _ready )
-{
- static struct timeval tp;
- static const int maximum_updatetime = 300;
- static const int minimum_updatetime = 100;
-
- if (!_ready) {
- pendingListEntries.append(entry);
-
- if (pendingListEntries.count() > listEntryCurrentSize) {
- gettimeofday(&tp, 0);
-
- long diff = ((tp.tv_sec - listEntry_sec) * 1000000 +
- tp.tv_usec - listEntry_usec) / 1000;
- if (diff==0) diff=1;
-
- if (diff > maximum_updatetime) {
- listEntryCurrentSize = listEntryCurrentSize * 3 / 4;
- _ready = true;
- }
-//if we can send all list entries of this dir which have not yet been sent
-//within maximum_updatetime, then make listEntryCurrentSize big enough for all of them
- else if (((pendingListEntries.count()*maximum_updatetime)/diff) > (d->totalSize-d->sentListEntries))
- listEntryCurrentSize=d->totalSize-d->sentListEntries+1;
-//if we are below minimum_updatetime, estimate how much we will get within
-//maximum_updatetime
- else if (diff < minimum_updatetime)
- listEntryCurrentSize = (pendingListEntries.count() * maximum_updatetime) / diff;
- else
- _ready=true;
- }
- }
- if (_ready) { // may happen when we started with !ready
- listEntries( pendingListEntries );
- pendingListEntries.clear();
-
- gettimeofday(&tp, 0);
- listEntry_sec = tp.tv_sec;
- listEntry_usec = tp.tv_usec;
- }
-}
-
-void SlaveBase::listEntries( const UDSEntryList& list )
-{
- KIO_DATA << (TQ_UINT32)list.count();
- UDSEntryListConstIterator it = list.begin();
- UDSEntryListConstIterator end = list.end();
- for (; it != end; ++it)
- stream << *it;
- slaveWriteError = false;
- m_pConnection->send( MSG_LIST_ENTRIES, data);
- if (slaveWriteError) exit();
- d->sentListEntries+=(uint)list.count();
-}
-
-void SlaveBase::sendAuthenticationKey( const TQCString& key,
- const TQCString& group,
- bool keepPass )
-{
- KIO_DATA << key << group << keepPass;
- m_pConnection->send( MSG_AUTH_KEY, data );
-}
-
-void SlaveBase::delCachedAuthentication( const TQString& key )
-{
- KIO_DATA << key.utf8() ;
- m_pConnection->send( MSG_DEL_AUTH_KEY, data );
-}
-
-void SlaveBase::sigsegv_handler(int sig)
-{
-#ifdef Q_OS_UNIX
- signal(sig,SIG_DFL); // Next one kills
-
- //Kill us if we deadlock
- signal(SIGALRM,SIG_DFL);
- alarm(5); //generate an alarm signal in 5 seconds, in this time the slave has to exit
-
- // Debug and printf should be avoided because they might
- // call malloc.. and get in a nice recursive malloc loop
- char buffer[120];
- snprintf(buffer, sizeof(buffer), "kioslave: ####### CRASH ###### protocol = %s pid = %d signal = %d\n", s_protocol, getpid(), sig);
- write(2, buffer, strlen(buffer));
-#ifndef NDEBUG
-#ifdef HAVE_BACKTRACE
- void* trace[256];
- int n = backtrace(trace, 256);
- if (n)
- backtrace_symbols_fd(trace, n, 2);
-#endif
-#endif
- ::exit(1);
-#endif
-}
-
-void SlaveBase::sigpipe_handler (int)
-{
- // We ignore a SIGPIPE in slaves.
- // A SIGPIPE can happen in two cases:
- // 1) Communication error with application.
- // 2) Communication error with network.
- slaveWriteError = true;
-
- // Don't add anything else here, especially no debug output
-}
-
-void SlaveBase::setHost(TQString const &, int, TQString const &, TQString const &)
-{
-}
-
-void SlaveBase::openConnection(void)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_CONNECT)); }
-void SlaveBase::closeConnection(void)
-{ } // No response!
-void SlaveBase::stat(KURL const &)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_STAT)); }
-void SlaveBase::put(KURL const &, int, bool, bool)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_PUT)); }
-void SlaveBase::special(const TQByteArray &)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_SPECIAL)); }
-void SlaveBase::listDir(KURL const &)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_LISTDIR)); }
-void SlaveBase::get(KURL const & )
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_GET)); }
-void SlaveBase::mimetype(KURL const &url)
-{ get(url); }
-void SlaveBase::rename(KURL const &, KURL const &, bool)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_RENAME)); }
-void SlaveBase::symlink(TQString const &, KURL const &, bool)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_SYMLINK)); }
-void SlaveBase::copy(KURL const &, KURL const &, int, bool)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_COPY)); }
-void SlaveBase::del(KURL const &, bool)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_DEL)); }
-void SlaveBase::mkdir(KURL const &, int)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_MKDIR)); }
-void SlaveBase::chmod(KURL const &, int)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_CHMOD)); }
-void SlaveBase::setSubURL(KURL const &)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_SUBURL)); }
-void SlaveBase::multiGet(const TQByteArray &)
-{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_MULTI_GET)); }
-
-
-void SlaveBase::slave_status()
-{ slaveStatus( TQString::null, false ); }
-
-void SlaveBase::reparseConfiguration()
-{
-}
-
-void SlaveBase::localURL(const KURL& remoteURL)
-{
- bool local = remoteURL.isLocalFile();
- TQ_INT8 islocal;
- KURL retURL;
- if (local) {
- islocal = true;
- retURL = remoteURL;
- }
- else {
- islocal = false;
- retURL = remoteURL;
- }
- KIO_DATA << islocal << retURL;
- m_pConnection->send( INF_LOCALURL, data );
-}
-
-bool SlaveBase::dispatch()
-{
- assert( m_pConnection );
-
- int cmd;
- TQByteArray data;
- if ( m_pConnection->read( &cmd, data ) == -1 )
- {
- kdDebug(7019) << "SlaveBase::dispatch() has read error." << endl;
- return false;
- }
-
- dispatch( cmd, data );
- return true;
-}
-
-bool SlaveBase::openPassDlg( AuthInfo& info )
-{
- return openPassDlg(info, TQString::null);
-}
-
-bool SlaveBase::openPassDlg( AuthInfo& info, const TQString &errorMsg )
-{
- TQCString replyType;
- TQByteArray params;
- TQByteArray reply;
- AuthInfo authResult;
- long windowId = metaData("window-id").toLong();
- long progressId = metaData("progress-id").toLong();
- unsigned long userTimestamp = metaData("user-timestamp").toULong();
-
- kdDebug(7019) << "SlaveBase::openPassDlg window-id=" << windowId << " progress-id=" << progressId << endl;
-
- (void) dcopClient(); // Make sure to have a dcop client.
-
- UIServer_stub uiserver( "kio_uiserver", "UIServer" );
- if (progressId)
- uiserver.setJobVisible( progressId, false );
-
- TQDataStream stream(params, IO_WriteOnly);
-
- if (metaData("no-auth-prompt").lower() == "true")
- stream << info << TQString("<NoAuthPrompt>") << windowId << s_seqNr << userTimestamp;
- else
- stream << info << errorMsg << windowId << s_seqNr << userTimestamp;
-
- bool callOK = d->dcopClient->call( "kded", "kpasswdserver", "queryAuthInfo(TDEIO::AuthInfo, TQString, long int, long int, unsigned long int)",
- params, replyType, reply );
-
- if (progressId)
- uiserver.setJobVisible( progressId, true );
-
- if (!callOK)
- {
- kdWarning(7019) << "Can't communicate with kded_kpasswdserver!" << endl;
- return false;
- }
-
- if ( replyType == "TDEIO::AuthInfo" )
- {
- TQDataStream stream2( reply, IO_ReadOnly );
- stream2 >> authResult >> s_seqNr;
- }
- else
- {
- kdError(7019) << "DCOP function queryAuthInfo(...) returns "
- << replyType << ", expected TDEIO::AuthInfo" << endl;
- return false;
- }
-
- if (!authResult.isModified())
- return false;
-
- info = authResult;
-
- kdDebug(7019) << "SlaveBase::openPassDlg: username=" << info.username << endl;
- kdDebug(7019) << "SlaveBase::openPassDlg: password=[hidden]" << endl;
-
- return true;
-}
-
-int SlaveBase::messageBox( MessageBoxType type, const TQString &text, const TQString &caption,
- const TQString &buttonYes, const TQString &buttonNo )
-{
- return messageBox( text, type, caption, buttonYes, buttonNo, TQString::null );
-}
-
-int SlaveBase::messageBox( const TQString &text, MessageBoxType type, const TQString &caption,
- const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName )
-{
- kdDebug(7019) << "messageBox " << type << " " << text << " - " << caption << buttonYes << buttonNo << endl;
- KIO_DATA << (TQ_INT32)type << text << caption << buttonYes << buttonNo << dontAskAgainName;
- m_pConnection->send( INF_MESSAGEBOX, data );
- if ( waitForAnswer( CMD_MESSAGEBOXANSWER, 0, data ) != -1 )
- {
- TQDataStream stream( data, IO_ReadOnly );
- int answer;
- stream >> answer;
- kdDebug(7019) << "got messagebox answer" << answer << endl;
- return answer;
- } else
- return 0; // communication failure
-}
-
-bool SlaveBase::canResume( TDEIO::filesize_t offset )
-{
- kdDebug(7019) << "SlaveBase::canResume offset=" << TDEIO::number(offset) << endl;
- d->needSendCanResume = false;
- KIO_DATA << KIO_FILESIZE_T(offset);
- m_pConnection->send( MSG_RESUME, data );
- if ( offset )
- {
- int cmd;
- if ( waitForAnswer( CMD_RESUMEANSWER, CMD_NONE, data, &cmd ) != -1 )
- {
- kdDebug(7019) << "SlaveBase::canResume returning " << (cmd == CMD_RESUMEANSWER) << endl;
- return cmd == CMD_RESUMEANSWER;
- } else
- return false;
- }
- else // No resuming possible -> no answer to wait for
- return true;
-}
-
-
-
-int SlaveBase::waitForAnswer( int expected1, int expected2, TQByteArray & data, int *pCmd )
-{
- int cmd, result;
- for (;;)
- {
- result = m_pConnection->read( &cmd, data );
- if ( result == -1 )
- {
- kdDebug(7019) << "SlaveBase::waitForAnswer has read error." << endl;
- return -1;
- }
- if ( cmd == expected1 || cmd == expected2 )
- {
- if ( pCmd ) *pCmd = cmd;
- return result;
- }
- if ( isSubCommand(cmd) )
- {
- dispatch( cmd, data );
- }
- else
- {
- kdWarning() << "Got cmd " << cmd << " while waiting for an answer!" << endl;
- }
- }
-}
-
-
-int SlaveBase::readData( TQByteArray &buffer)
-{
- int result = waitForAnswer( MSG_DATA, 0, buffer );
- //kdDebug(7019) << "readData: length = " << result << " " << endl;
- return result;
-}
-
-void SlaveBase::setTimeoutSpecialCommand(int timeout, const TQByteArray &data)
-{
- if (timeout > 0)
- d->timeout = time(0)+(time_t)timeout;
- else if (timeout == 0)
- d->timeout = 1; // Immediate timeout
- else
- d->timeout = 0; // Canceled
-
- d->timeoutData = data;
-}
-
-void SlaveBase::dispatch( int command, const TQByteArray &data )
-{
- TQDataStream stream( data, IO_ReadOnly );
-
- KURL url;
- int i;
-
- switch( command ) {
- case CMD_HOST: {
- // Reset s_seqNr, see kpasswdserver/DESIGN
- s_seqNr = 0;
- TQString passwd;
- TQString host, user;
- stream >> host >> i >> user >> passwd;
- setHost( host, i, user, passwd );
- }
- break;
- case CMD_CONNECT:
- openConnection( );
- break;
- case CMD_DISCONNECT:
- closeConnection( );
- break;
- case CMD_SLAVE_STATUS:
- slave_status();
- break;
- case CMD_SLAVE_CONNECT:
- {
- d->onHold = false;
- TQString app_socket;
- TQDataStream stream( data, IO_ReadOnly);
- stream >> app_socket;
- appconn->send( MSG_SLAVE_ACK );
- disconnectSlave();
- mConnectedToApp = true;
- connectSlave(app_socket);
- } break;
- case CMD_SLAVE_HOLD:
- {
- KURL url;
- TQDataStream stream( data, IO_ReadOnly);
- stream >> url;
- d->onHoldUrl = url;
- d->onHold = true;
- disconnectSlave();
- mConnectedToApp = false;
- // Do not close connection!
- connectSlave(mPoolSocket);
- } break;
- case CMD_REPARSECONFIGURATION:
- reparseConfiguration();
- break;
- case CMD_CONFIG:
- stream >> d->configData;
-#ifdef Q_OS_UNIX //TODO: not yet available on WIN32
- KSocks::setConfig(d->config);
-#endif
- delete d->remotefile;
- d->remotefile = 0;
- break;
- case CMD_GET:
- {
- stream >> url;
- get( url );
- } break;
- case CMD_PUT:
- {
- int permissions;
- TQ_INT8 iOverwrite, iResume;
- stream >> url >> iOverwrite >> iResume >> permissions;
- bool overwrite = ( iOverwrite != 0 );
- bool resume = ( iResume != 0 );
-
- // Remember that we need to send canResume(), TransferJob is expecting
- // it. Well, in theory this shouldn't be done if resume is true.
- // (the resume bool is currently unused)
- d->needSendCanResume = true /* !resume */;
-
- put( url, permissions, overwrite, resume);
- } break;
- case CMD_STAT:
- stream >> url;
- stat( url );
- break;
- case CMD_MIMETYPE:
- stream >> url;
- mimetype( url );
- break;
- case CMD_LISTDIR:
- stream >> url;
- listDir( url );
- break;
- case CMD_MKDIR:
- stream >> url >> i;
- mkdir( url, i );
- break;
- case CMD_RENAME:
- {
- TQ_INT8 iOverwrite;
- KURL url2;
- stream >> url >> url2 >> iOverwrite;
- bool overwrite = (iOverwrite != 0);
- rename( url, url2, overwrite );
- } break;
- case CMD_SYMLINK:
- {
- TQ_INT8 iOverwrite;
- TQString target;
- stream >> target >> url >> iOverwrite;
- bool overwrite = (iOverwrite != 0);
- symlink( target, url, overwrite );
- } break;
- case CMD_COPY:
- {
- int permissions;
- TQ_INT8 iOverwrite;
- KURL url2;
- stream >> url >> url2 >> permissions >> iOverwrite;
- bool overwrite = (iOverwrite != 0);
- copy( url, url2, permissions, overwrite );
- } break;
- case CMD_DEL:
- {
- TQ_INT8 isFile;
- stream >> url >> isFile;
- del( url, isFile != 0);
- } break;
- case CMD_CHMOD:
- stream >> url >> i;
- chmod( url, i);
- break;
- case CMD_SPECIAL:
- special( data );
- break;
- case CMD_META_DATA:
- //kdDebug(7019) << "(" << getpid() << ") Incoming meta-data..." << endl;
- stream >> mIncomingMetaData;
- break;
- case CMD_SUBURL:
- stream >> url;
- setSubURL(url);
- break;
- case CMD_NONE:
- fprintf(stderr, "Got unexpected CMD_NONE!\n");
- break;
- case CMD_MULTI_GET:
- multiGet( data );
- break;
- case CMD_LOCALURL:
- {
- stream >> url;
- localURL( url );
- } break;
- default:
- // Some command we don't understand.
- // Just ignore it, it may come from some future version of KDE.
- break;
- }
-}
-
-TQString SlaveBase::createAuthCacheKey( const KURL& url )
-{
- if( !url.isValid() )
- return TQString::null;
-
- // Generate the basic key sequence.
- TQString key = url.protocol();
- key += '-';
- key += url.host();
- int port = url.port();
- if( port )
- {
- key += ':';
- key += TQString::number(port);
- }
-
- return key;
-}
-
-bool SlaveBase::pingCacheDaemon() const
-{
-#ifdef Q_OS_UNIX
- // TODO: Ping kded / kpasswdserver
- KDEsuClient client;
- int success = client.ping();
- if( success == -1 )
- {
- success = client.startServer();
- if( success == -1 )
- {
- kdDebug(7019) << "Cannot start a new deamon!!" << endl;
- return false;
- }
- kdDebug(7019) << "Sucessfully started new cache deamon!!" << endl;
- }
- return true;
-#else
- return false;
-#endif
-}
-
-bool SlaveBase::checkCachedAuthentication( AuthInfo& info )
-{
- TQCString replyType;
- TQByteArray params;
- TQByteArray reply;
- AuthInfo authResult;
- long windowId = metaData("window-id").toLong();
- unsigned long userTimestamp = metaData("user-timestamp").toULong();
-
- kdDebug(7019) << "SlaveBase::checkCachedAuthInfo window = " << windowId << " url = " << info.url.url() << endl;
-
- (void) dcopClient(); // Make sure to have a dcop client.
-
- TQDataStream stream(params, IO_WriteOnly);
- stream << info << windowId << userTimestamp;
-
- if ( !d->dcopClient->call( "kded", "kpasswdserver", "checkAuthInfo(TDEIO::AuthInfo, long int, unsigned long int)",
- params, replyType, reply ) )
- {
- kdWarning(7019) << "Can't communicate with kded_kpasswdserver!" << endl;
- return false;
- }
-
- if ( replyType == "TDEIO::AuthInfo" )
- {
- TQDataStream stream2( reply, IO_ReadOnly );
- stream2 >> authResult;
- }
- else
- {
- kdError(7019) << "DCOP function checkAuthInfo(...) returns "
- << replyType << ", expected TDEIO::AuthInfo" << endl;
- return false;
- }
- if (!authResult.isModified())
- {
- return false;
- }
-
- info = authResult;
- return true;
-}
-
-bool SlaveBase::cacheAuthentication( const AuthInfo& info )
-{
- TQByteArray params;
- long windowId = metaData("window-id").toLong();
-
- (void) dcopClient(); // Make sure to have a dcop client.
-
- TQDataStream stream(params, IO_WriteOnly);
- stream << info << windowId;
-
- d->dcopClient->send( "kded", "kpasswdserver", "addAuthInfo(TDEIO::AuthInfo, long int)", params );
-
- return true;
-}
-
-int SlaveBase::connectTimeout()
-{
- bool ok;
- TQString tmp = metaData("ConnectTimeout");
- int result = tmp.toInt(&ok);
- if (ok)
- return result;
- return DEFAULT_CONNECT_TIMEOUT;
-}
-
-int SlaveBase::proxyConnectTimeout()
-{
- bool ok;
- TQString tmp = metaData("ProxyConnectTimeout");
- int result = tmp.toInt(&ok);
- if (ok)
- return result;
- return DEFAULT_PROXY_CONNECT_TIMEOUT;
-}
-
-
-int SlaveBase::responseTimeout()
-{
- bool ok;
- TQString tmp = metaData("ResponseTimeout");
- int result = tmp.toInt(&ok);
- if (ok)
- return result;
- return DEFAULT_RESPONSE_TIMEOUT;
-}
-
-
-int SlaveBase::readTimeout()
-{
- bool ok;
- TQString tmp = metaData("ReadTimeout");
- int result = tmp.toInt(&ok);
- if (ok)
- return result;
- return DEFAULT_READ_TIMEOUT;
-}
-
-bool SlaveBase::wasKilled() const
-{
- return d->wasKilled;
-}
-
-void SlaveBase::setKillFlag()
-{
- d->wasKilled=true;
-}
-
-void SlaveBase::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
diff --git a/kio/kio/slavebase.h b/kio/kio/slavebase.h
deleted file mode 100644
index a65a1f94f..000000000
--- a/kio/kio/slavebase.h
+++ /dev/null
@@ -1,847 +0,0 @@
-/*
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __slavebase_h
-#define __slavebase_h
-
-#include <kurl.h>
-#include <kconfigbase.h>
-#include <kio/global.h>
-#include <kio/authinfo.h>
-
-class DCOPClient;
-class KRemoteEncoding;
-
-namespace TDEIO {
-
-class Connection;
-class SlaveBasePrivate;
-
-/**
- * There are two classes that specifies the protocol between application (job)
- * and kioslave. SlaveInterface is the class to use on the application end,
- * SlaveBase is the one to use on the slave end.
- *
- * Slave implementations should simply inherit SlaveBase
- *
- * A call to foo() results in a call to slotFoo() on the other end.
- */
-class TDEIO_EXPORT SlaveBase
-{
-public:
- SlaveBase( const TQCString &protocol, const TQCString &pool_socket, const TQCString &app_socket);
- virtual ~SlaveBase();
-
- /**
- * @internal
- * Terminate the slave by calling the destructor and then ::exit()
- */
- void exit();
-
- /**
- * @internal
- */
- void dispatchLoop();
-
- /**
- * @internal
- */
- void setConnection( Connection* connection ) { m_pConnection = connection; }
- /**
- * @internal
- */
- Connection *connection() const { return m_pConnection; }
-
-
- ///////////
- // Message Signals to send to the job
- ///////////
-
- /**
- * Sends data in the slave to the job (i.e. in get).
- *
- * To signal end of data, simply send an empty
- * TQByteArray().
- *
- * @param data the data read by the slave
- */
- void data( const TQByteArray &data );
-
- /**
- * Asks for data from the job.
- * @see readData
- */
- void dataReq( );
-
- /**
- * Call to signal an error.
- * This also finishes the job, no need to call finished.
- *
- * If the Error code is TDEIO::ERR_SLAVE_DEFINED then the
- * _text should contain the complete translated text of
- * of the error message. This message will be displayed
- * in an KTextBrowser which allows rich text complete
- * with hyper links. Email links will call the default
- * mailer, "exec:/command arg1 arg2" will be forked and
- * all other links will call the default browser.
- *
- * @see TDEIO::Error
- * @see KTextBrowser
- * @param _errid the error code from TDEIO::Error
- * @param _text the rich text error message
- */
- void error( int _errid, const TQString &_text );
-
- /**
- * Call in openConnection, if you reimplement it, when you're done.
- */
- void connected();
-
- /**
- * Call to signal successful completion of any command
- * (besides openConnection and closeConnection)
- */
- void finished();
-
- /**
- * Call to signal that data from the sub-URL is needed
- */
- void needSubURLData();
-
- /**
- * Used to report the status of the slave.
- * @param host the slave is currently connected to. (Should be
- * empty if not connected)
- * @param connected Whether an actual network connection exists.
- **/
- void slaveStatus(const TQString &host, bool connected);
-
- /**
- * Call this from stat() to express details about an object, the
- * UDSEntry customarily contains the atoms describing file name, size,
- * mimetype, etc.
- * @param _entry The UDSEntry containing all of the object attributes.
- */
- void statEntry( const UDSEntry& _entry );
-
- /**
- * Call this in listDir, each time you have a bunch of entries
- * to report.
- * @param _entry The UDSEntry containing all of the object attributes.
- */
- void listEntries( const UDSEntryList& _entry );
-
- /**
- * Call this at the beginning of put(), to give the size of the existing
- * partial file, if there is one. The @p offset argument notifies the
- * other job (the one that gets the data) about the offset to use.
- * In this case, the boolean returns whether we can indeed resume or not
- * (we can't if the protocol doing the get() doesn't support setting an offset)
- */
- bool canResume( TDEIO::filesize_t offset );
-
- /*
- * Call this at the beginning of get(), if the "resume" metadata was set
- * and resuming is implemented by this protocol.
- */
- void canResume();
-
- ///////////
- // Info Signals to send to the job
- ///////////
-
- /**
- * Call this in get and copy, to give the total size
- * of the file
- * Call in listDir too, when you know the total number of items.
- */
- void totalSize( TDEIO::filesize_t _bytes );
- /**
- * Call this during get and copy, once in a while,
- * to give some info about the current state.
- * Don't emit it in listDir, listEntries speaks for itself.
- */
- void processedSize( TDEIO::filesize_t _bytes );
-
- /**
- * Only use this if you can't know in advance the size of the
- * copied data. For example, if you're doing variable bitrate
- * compression of the source.
- *
- * STUB ! Currently unimplemented. Here now for binary compatibility.
- *
- * Call this during get and copy, once in a while,
- * to give some info about the current state.
- * Don't emit it in listDir, listEntries speaks for itself.
- */
- void processedPercent( float percent );
-
- /**
- * Call this in get and copy, to give the current transfer
- * speed, but only if it can't be calculated out of the size you
- * passed to processedSize (in most cases you don't want to call it)
- */
- void speed( unsigned long _bytes_per_second );
-
- /**
- * Call this to signal a redirection
- * The job will take care of going to that url.
- */
- void redirection( const KURL &_url );
-
- /**
- * Tell that we will only get an error page here.
- * This means: the data you'll get isn't the data you requested,
- * but an error page (usually HTML) that describes an error.
- */
- void errorPage();
-
- /**
- * Call this in mimetype() and in get(), when you know the mimetype.
- * See mimetype about other ways to implement it.
- */
- void mimeType( const TQString &_type );
-
- /**
- * Call to signal a warning, to be displayed in a dialog box.
- */
- void warning( const TQString &msg );
-
- /**
- * Call to signal a message, to be displayed if the application wants to,
- * for instance in a status bar. Usual examples are "connecting to host xyz", etc.
- */
- void infoMessage( const TQString &msg );
-
- enum MessageBoxType { QuestionYesNo = 1, WarningYesNo = 2, WarningContinueCancel = 3, WarningYesNoCancel = 4, Information = 5, SSLMessageBox = 6 };
-
- /**
- * Call this to show a message box from the slave
- * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
- * @param text Message string. May contain newlines.
- * @param caption Message box title.
- * @param buttonYes The text for the first button.
- * The default is i18n("&Yes").
- * @param buttonNo The text for the second button.
- * The default is i18n("&No").
- * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
- * and for Information, none is used.
- * @return a button code, as defined in KMessageBox, or 0 on communication error.
- */
- int messageBox( MessageBoxType type, const TQString &text,
- const TQString &caption = TQString::null,
- const TQString &buttonYes = TQString::null,
- const TQString &buttonNo = TQString::null );
-
- /**
- * Call this to show a message box from the slave
- * @param text Message string. May contain newlines.
- * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
- * @param caption Message box title.
- * @param buttonYes The text for the first button.
- * The default is i18n("&Yes").
- * @param buttonNo The text for the second button.
- * The default is i18n("&No").
- * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
- * and for Information, none is used.
- * @param dontAskAgainName A checkbox is added with which further confirmation can be turned off.
- * The string is used to lookup and store the setting in kioslaverc.
- * @return a button code, as defined in KMessageBox, or 0 on communication error.
- * @since 3.3
- */
- int messageBox( const TQString &text, MessageBoxType type,
- const TQString &caption = TQString::null,
- const TQString &buttonYes = TQString::null,
- const TQString &buttonNo = TQString::null,
- const TQString &dontAskAgainName = TQString::null );
-
- /**
- * Sets meta-data to be send to the application before the first
- * data() or finished() signal.
- */
- void setMetaData(const TQString &key, const TQString &value);
-
- /**
- * Queries for the existence of a certain config/meta-data entry
- * send by the application to the slave.
- * @since 3.2
- */
- bool hasMetaData(const TQString &key) const;
-
- /**
- * Queries for config/meta-data send by the application to the slave.
- * @since 3.2
- */
- TQString metaData(const TQString &key) const;
-
- /**
- * @obsolete kept for binary compatibility
- * Queries for the existence of a certain config/meta-data entry
- * send by the application to the slave.
- */
- bool hasMetaData(const TQString &key);
-
- /**
- * @obsolete kept for binary compatibility
- * Queries for config/meta-data sent by the application to the slave.
- */
- TQString metaData(const TQString &key);
-
- /**
- * @internal for ForwardingSlaveBase
- * Contains all metadata (but no config) sent by the application to the slave.
- * @since 3.5.2
- */
- MetaData allMetaData() const { return mIncomingMetaData; }
-
- /**
- * Returns a configuration object to query config/meta-data information
- * from.
- *
- * The application provides the slave with all configuration information
- * relevant for the current protocol and host.
- */
- TDEConfigBase* config();
-
- /**
- * Returns an object that can translate remote filenames into proper
- * Unicode forms. This encoding can be set by the user.
- *
- * @since 3.3
- */
- KRemoteEncoding* remoteEncoding();
-
-
- ///////////
- // Commands sent by the job, the slave has to
- // override what it wants to implement
- ///////////
-
- /**
- * Set the host
- * @param host
- * @param port
- * @param user
- * @param pass
- * Called directly by createSlave, this is why there is no equivalent in
- * SlaveInterface, unlike the other methods.
- *
- * This method is called whenever a change in host, port or user occurs.
- */
- virtual void setHost(const TQString& host, int port, const TQString& user, const TQString& pass);
-
- /**
- * Prepare slave for streaming operation
- */
- virtual void setSubURL(const KURL&url);
-
- /**
- * Opens the connection (forced)
- * When this function gets called the slave is operating in
- * connection-oriented mode.
- * When a connection gets lost while the slave operates in
- * connection oriented mode, the slave should report
- * ERR_CONNECTION_BROKEN instead of reconnecting. The user is
- * expected to disconnect the slave in the error handler.
- */
- virtual void openConnection();
-
- /**
- * Closes the connection (forced)
- * Called when the application disconnects the slave to close
- * any open network connections.
- *
- * When the slave was operating in connection-oriented mode,
- * it should reset itself to connectionless (default) mode.
- */
- virtual void closeConnection();
-
- /**
- * get, aka read.
- * @param url the full url for this request. Host, port and user of the URL
- * can be assumed to be the same as in the last setHost() call.
- * The slave emits the data through data
- */
- virtual void get( const KURL& url );
-
- /**
- * put, i.e. write data into a file.
- *
- * @param url where to write the file
- * @param permissions may be -1. In this case no special permission mode is set.
- * @param overwrite if true, any existing file will be overwritten.
- * If the file indeed already exists, the slave should NOT apply the
- * permissions change to it.
- * @param resume currently unused, please ignore.
- * The support for resuming using .part files is done by calling canResume().
- *
- * IMPORTANT: Use the "modified" metadata in order to set the modification time of the file.
- *
- * @see canResume()
- */
- virtual void put( const KURL& url, int permissions, bool overwrite, bool resume );
-
- /**
- * Finds all details for one file or directory.
- * The information returned is the same as what listDir returns,
- * but only for one file or directory.
- */
- virtual void stat( const KURL& url );
-
- /**
- * Finds mimetype for one file or directory.
- *
- * This method should either emit 'mimeType' or it
- * should send a block of data big enough to be able
- * to determine the mimetype.
- *
- * If the slave doesn't reimplement it, a get will
- * be issued, i.e. the whole file will be downloaded before
- * determining the mimetype on it - this is obviously not a
- * good thing in most cases.
- */
- virtual void mimetype( const KURL& url );
-
- /**
- * Lists the contents of @p url.
- * The slave should emit ERR_CANNOT_ENTER_DIRECTORY if it doesn't exist,
- * if we don't have enough permissions, or if it is a file
- * It should also emit totalFiles as soon as it knows how many
- * files it will list.
- */
- virtual void listDir( const KURL& url );
-
- /**
- * Create a directory
- * @param url path to the directory to create
- * @param permissions the permissions to set after creating the directory
- * (-1 if no permissions to be set)
- * The slave emits ERR_COULD_NOT_MKDIR if failure.
- */
- virtual void mkdir( const KURL&url, int permissions );
-
- /**
- * Rename @p oldname into @p newname.
- * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
- * ask for copy + del instead.
- * @param src where to move the file from
- * @param dest where to move the file to
- * @param overwrite if true, any existing file will be overwritten
- */
- virtual void rename( const KURL& src, const KURL& dest, bool overwrite );
-
- /**
- * Creates a symbolic link named @p dest, pointing to @p target, which
- * may be a relative or an absolute path.
- * @param target The string that will become the "target" of the link (can be relative)
- * @param dest The symlink to create.
- * @param overwrite whether to automatically overwrite if the dest exists
- */
- virtual void symlink( const TQString& target, const KURL& dest, bool overwrite );
-
- /**
- * Change permissions on @p path
- * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_CHMOD
- */
- virtual void chmod( const KURL& url, int permissions );
-
- /**
- * Copy @p src into @p dest.
- * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
- * ask for get + put instead.
- * @param src where to copy the file from (decoded)
- * @param dest where to copy the file to (decoded)
- * @param permissions may be -1. In this case no special permission mode is set.
- * @param overwrite if true, any existing file will be overwritten
- *
- */
- virtual void copy( const KURL &src, const KURL &dest, int permissions, bool overwrite );
-
- /**
- * Delete a file or directory.
- * @param url file/directory to delete
- * @param isfile if true, a file should be deleted.
- * if false, a directory should be deleted.
- */
- virtual void del( const KURL &url, bool isfile);
-
- // TODO KDE4: add setLinkDest() or something, to modify symlink targets.
- // Will be used for kio_file but also kio_remote (#97129)
-
- /**
- * Used for any command that is specific to this slave (protocol)
- * Examples are : HTTP POST, mount and unmount (kio_file)
- *
- * @param data packed data; the meaning is completely dependent on the
- * slave, but usually starts with an int for the command number.
- * Document your slave's commands, at least in its header file.
- */
- virtual void special( const TQByteArray & data );
-
- /**
- * Used for multiple get. Currently only used foir HTTP pielining
- * support.
- *
- * @param data packed data; Contains number of URLs to fetch, and for
- * each URL the URL itself and its associated MetaData.
- */
- virtual void multiGet( const TQByteArray & data );
-
- /**
- * Called to get the status of the slave. Slave should respond
- * by calling slaveStatus(...)
- */
- virtual void slave_status();
-
- /**
- * Called by the scheduler to tell the slave that the configuration
- * changed (i.e. proxy settings) .
- */
- virtual void reparseConfiguration();
-
- /**
- * For use with for ForwardingSlaveBase
- * Returns the local URL of the given remote URL if possible
- * @since R14.0.0
- */
- virtual void localURL( const KURL& remoteURL );
-
- /**
- * @return timeout value for connecting to remote host.
- */
- int connectTimeout();
-
- /**
- * @return timeout value for connecting to proxy in secs.
- */
- int proxyConnectTimeout();
-
- /**
- * @return timeout value for read from first data from
- * remote host in seconds.
- */
- int responseTimeout();
-
- /**
- * @return timeout value for read from subsequent data from
- * remote host in secs.
- */
- int readTimeout();
-
- /**
- * This function sets a timeout of @p timeout seconds and calls
- * special(data) when the timeout occurs as if it was called by the
- * application.
- *
- * A timeout can only occur when the slave is waiting for a command
- * from the application.
- *
- * Specifying a negative timeout cancels a pending timeout.
- *
- * Only one timeout at a time is supported, setting a timeout
- * cancels any pending timeout.
- * @since 3.1
- */
- void setTimeoutSpecialCommand(int timeout, const TQByteArray &data=TQByteArray());
-
- /**
- * @internal
- */
- static void sigsegv_handler(int);
- /**
- * @internal
- */
- static void sigpipe_handler(int);
-
- /////////////////
- // Dispatching (internal)
- ////////////////
-
- /**
- * @internal
- */
- virtual bool dispatch();
- /**
- * @internal
- */
- virtual void dispatch( int command, const TQByteArray &data );
-
- /**
- * Read data send by the job, after a dataReq
- *
- * @param buffer buffer where data is stored
- * @return 0 on end of data,
- * > 0 bytes read
- * < 0 error
- **/
- int readData( TQByteArray &buffer );
-
- /**
- * internal function to be called by the slave.
- * It collects entries and emits them via listEntries
- * when enough of them are there or a certain time
- * frame exceeded (to make sure the app gets some
- * items in time but not too many items one by one
- * as this will cause a drastic performance penalty)
- * @param _entry The UDSEntry containing all of the object attributes.
- * @param ready set to true after emitting all items. @p _entry is not
- * used in this case
- */
- void listEntry( const UDSEntry& _entry, bool ready);
-
- /**
- * internal function to connect a slave to/ disconnect from
- * either the slave pool or the application
- */
- void connectSlave(const TQString& path);
- void disconnectSlave();
-
- /**
- * Prompt the user for Authorization info (login & password).
- *
- * Use this function to request authorization information from
- * the end user. You can also pass an error message which explains
- * why a previous authorization attempt failed. Here is a very
- * simple example:
- *
- * \code
- * TDEIO::AuthInfo authInfo;
- * if ( openPassDlg( authInfo ) )
- * {
- * kdDebug() << TQString::fromLatin1("User: ")
- * << authInfo.username << endl;
- * kdDebug() << TQString::fromLatin1("Password: ")
- * << TQString::fromLatin1("Not displayed here!") << endl;
- * }
- * \endcode
- *
- * You can also preset some values like the username, caption or
- * comment as follows:
- *
- * \code
- * TDEIO::AuthInfo authInfo;
- * authInfo.caption= "Acme Password Dialog";
- * authInfo.username= "Wile E. Coyote";
- * TQString errorMsg = "You entered an incorrect password.";
- * if ( openPassDlg( authInfo, errorMsg ) )
- * {
- * kdDebug() << TQString::fromLatin1("User: ")
- * << authInfo.username << endl;
- * kdDebug() << TQString::fromLatin1("Password: ")
- * << TQString::fromLatin1("Not displayed here!") << endl;
- * }
- * \endcode
- *
- * \note You should consider using checkCachedAuthentication() to
- * see if the password is available in kpasswdserver before calling
- * this function.
- *
- * \note A call to this function can fail and return @p false,
- * if the UIServer could not be started for whatever reason.
- *
- * @see checkCachedAuthentication
- * @param info See AuthInfo.
- * @param errorMsg Error message to show
- * @return @p true if user clicks on "OK", @p false otherwsie.
- * @since 3.1
- */
- bool openPassDlg( TDEIO::AuthInfo& info, const TQString &errorMsg );
-
- /**
- * Same as above function except it does not need error message.
- * BIC: Combine this function with the above for KDE4.
- */
- bool openPassDlg( TDEIO::AuthInfo& info );
-
- /**
- * Checks for cached authentication based on parameters
- * given by @p info.
- *
- * Use this function to check if any cached password exists
- * for the URL given by @p info. If @p AuthInfo::realmValue
- * and/or @p AuthInfo::verifyPath flag is specified, then
- * they will also be factored in determining the presence
- * of a cached password. Note that @p Auth::url is a required
- * parameter when attempting to check for cached authorization
- * info. Here is a simple example:
- *
- * \code
- * AuthInfo info;
- * info.url = KURL("http://www.foobar.org/foo/bar");
- * info.username = "somename";
- * info.verifyPath = true;
- * if ( !checkCachedAuthentication( info ) )
- * {
- * if ( !openPassDlg(info) )
- * ....
- * }
- * \endcode
- *
- * @param info See AuthInfo.
- * @return @p true if cached Authorization is found, false otherwise.
- */
- bool checkCachedAuthentication( AuthInfo& info );
-
- /**
- * Explicitly store authentication information. openPassDlg already
- * stores password information automatically, you only need to call
- * this function if you want to store authentication information that
- * is different from the information returned by openPassDlg.
- */
- bool cacheAuthentication( const AuthInfo& info );
-
- /**
- * @obsolete as of 3.1.
- * TODO: Remove before KDE 4.0
- */
- bool pingCacheDaemon() const;
-
- /**
- * @obsolete as of 3.1. Use openPassDlg instead.
- * TODO: Remove before KDE 4.0
- * Creates a basic key to be used to cache the password.
- * @param url the url from which the key is supposed to be generated
- */
- TQString createAuthCacheKey( const KURL& url );
-
- /**
- * @obsolete as of 3.1. Use openPassDlg instead.
- * TODO: Remove before KDE 4.0
- *
- * Cache authentication information is now stored automatically
- * by openPassDlg.
- */
- void sendAuthenticationKey( const TQCString& gKey, const TQCString& key, bool keep );
-
- /**
- * @obsolete as of 3.1. Use openPassDlg instead.
- * TODO: Remove before KDE 4.0
- *
- * Cached authentication information is now session based and
- * removed automatically when a given session ends, i.e. the
- * application is closed.
- */
- void delCachedAuthentication( const TQString& key );
-
- /**
- * @obsolete as of 3.1. Use openPassDlg instead.
- * TODO: Remove before KDE 4.0
- */
- void setMultipleAuthCaching( bool ) {};
-
- /**
- * @obsolete as of 3.1. Use openPassDlg instead.
- * TODO: Remove before KDE 4.0
- */
- bool multipleAuthCaching() const { return false; }
-
- /**
- * Used by the slave to check if it can connect
- * to a given host. This should be called where the slave is ready
- * to do a ::connect() on a socket. For each call to
- * requestNetwork must exist a matching call to
- * dropNetwork, or the system will stay online until
- * KNetMgr gets closed (or the SlaveBase gets destructed)!
- *
- * If KNetMgr is not running, then this is a no-op and returns true
- *
- * @param host tells the netmgr the host the slave wants to connect
- * to. As this could also be a proxy, we can't just take
- * the host currenctly connected to (but that's the default
- * value)
- *
- * @return true in theorie, the host is reachable
- * false the system is offline and the host is in a remote network.
- */
- bool requestNetwork(const TQString& host = TQString::null);
-
- /**
- * Used by the slave to withdraw a connection requested by
- * requestNetwork. This function cancels the last call to
- * requestNetwork. If a client uses more than one internet
- * connection, it must use dropNetwork(host) to
- * stop each request.
- *
- * If KNetMgr is not running, then this is a no-op.
- *
- * @param host the host passed to requestNetwork
- *
- * A slave should call this function every time it disconnect from a host.
- * */
- void dropNetwork(const TQString& host = TQString::null);
-
- /**
- * Return the dcop client used by this slave.
- * @since 3.1
- */
- DCOPClient *dcopClient();
-
- /**
- * Wait for an answer to our request, until we get @p expected1 or @p expected2
- * @return the result from readData, as well as the cmd in *pCmd if set, and the data in @p data
- */
- int waitForAnswer( int expected1, int expected2, TQByteArray & data, int * pCmd = 0 );
-
- /**
- * Internal function to transmit meta data to the application.
- */
- void sendMetaData();
-
- /**
- * Name of the protocol supported by this slave
- */
- TQCString mProtocol;
-
- Connection * m_pConnection;
-
- MetaData mOutgoingMetaData;
- MetaData mIncomingMetaData;
-
- /** If your ioslave was killed by a signal, wasKilled() returns true.
- Check it regularly in lengthy functions (e.g. in get();) and return
- as fast as possible from this function if wasKilled() returns true.
- This will ensure that your slave destructor will be called correctly.
- @since 3.1
- */
- bool wasKilled() const;
-
- /** Internally used.
- * @internal
- * @since 3.1
- */
- void setKillFlag();
-
-protected:
- UDSEntryList pendingListEntries;
- uint listEntryCurrentSize;
- long listEntry_sec, listEntry_usec;
- Connection *appconn;
- TQString mPoolSocket;
- TQString mAppSocket;
- bool mConnectedToApp;
- static long s_seqNr;
- virtual void virtual_hook( int id, void* data );
-
-private:
- SlaveBasePrivate *d;
-};
-
-}
-
-#endif
diff --git a/kio/kio/slaveconfig.cpp b/kio/kio/slaveconfig.cpp
deleted file mode 100644
index c0ec44779..000000000
--- a/kio/kio/slaveconfig.cpp
+++ /dev/null
@@ -1,225 +0,0 @@
-// -*- c++ -*-
-/*
- * This file is part of the KDE libraries
- * Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
- *
- * $Id$
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#include <assert.h>
-
-#include <tqdict.h>
-
-#include <kconfig.h>
-#include <kstaticdeleter.h>
-#include <kprotocolinfo.h>
-#include <kprotocolmanager.h>
-
-#include "slaveconfig.h"
-
-using namespace TDEIO;
-
-namespace TDEIO {
-
-class SlaveConfigProtocol
-{
-public:
- SlaveConfigProtocol() { host.setAutoDelete(true); }
- ~SlaveConfigProtocol()
- {
- delete configFile;
- }
-
-public:
- MetaData global;
- TQDict<MetaData> host;
- TDEConfig *configFile;
-};
-
-static void readConfig(TDEConfig *config, const TQString & group, MetaData *metaData)
-{
- *metaData += config->entryMap(group);
-}
-
-class SlaveConfigPrivate
-{
- public:
- void readGlobalConfig();
- SlaveConfigProtocol *readProtocolConfig(const TQString &_protocol);
- SlaveConfigProtocol *findProtocolConfig(const TQString &_protocol);
- void readConfigProtocolHost(const TQString &_protocol, SlaveConfigProtocol *scp, const TQString &host);
- public:
- MetaData global;
- TQDict<SlaveConfigProtocol> protocol;
-};
-
-void SlaveConfigPrivate::readGlobalConfig()
-{
- global.clear();
- // Read stuff...
- TDEConfig *config = KProtocolManager::config();
- readConfig(TDEGlobal::config(), "Socks", &global); // Socks settings.
- if ( config )
- readConfig(config, "<default>", &global);
-}
-
-SlaveConfigProtocol* SlaveConfigPrivate::readProtocolConfig(const TQString &_protocol)
-{
- SlaveConfigProtocol *scp = protocol.find(_protocol);
- if (!scp)
- {
- TQString filename = KProtocolInfo::config(_protocol);
- scp = new SlaveConfigProtocol;
- scp->configFile = new TDEConfig(filename, true, false);
- protocol.insert(_protocol, scp);
- }
- // Read global stuff...
- readConfig(scp->configFile, "<default>", &(scp->global));
- return scp;
-}
-
-SlaveConfigProtocol* SlaveConfigPrivate::findProtocolConfig(const TQString &_protocol)
-{
- SlaveConfigProtocol *scp = protocol.find(_protocol);
- if (!scp)
- scp = readProtocolConfig(_protocol);
- return scp;
-}
-
-void SlaveConfigPrivate::readConfigProtocolHost(const TQString &, SlaveConfigProtocol *scp, const TQString &host)
-{
- MetaData *metaData = new MetaData;
- scp->host.replace(host, metaData);
-
- // Read stuff
- // Break host into domains
- TQString domain = host;
-
- if (!domain.contains('.'))
- {
- // Host without domain.
- if (scp->configFile->hasGroup("<local>"))
- readConfig(scp->configFile, "<local>", metaData);
- }
-
- int pos = 0;
- do
- {
- pos = host.findRev('.', pos-1);
-
- if (pos < 0)
- domain = host;
- else
- domain = host.mid(pos+1);
-
- if (scp->configFile->hasGroup(domain))
- readConfig(scp->configFile, domain.lower(), metaData);
- }
- while (pos > 0);
-}
-
-
-SlaveConfig *SlaveConfig::_self = 0;
-static KStaticDeleter<SlaveConfig> slaveconfigsd;
-
-SlaveConfig *SlaveConfig::self()
-{
- if (!_self)
- _self = slaveconfigsd.setObject(_self, new SlaveConfig);
- return _self;
-}
-
-SlaveConfig::SlaveConfig()
-{
- d = new SlaveConfigPrivate;
- d->protocol.setAutoDelete(true);
- d->readGlobalConfig();
-}
-
-SlaveConfig::~SlaveConfig()
-{
- delete d; d = 0;
- _self = 0;
-}
-
-void SlaveConfig::setConfigData(const TQString &protocol,
- const TQString &host,
- const TQString &key,
- const TQString &value )
-{
- MetaData config;
- config.insert(key, value);
- setConfigData(protocol, host, config);
-}
-
-void SlaveConfig::setConfigData(const TQString &protocol, const TQString &host, const MetaData &config )
-{
- if (protocol.isEmpty())
- d->global += config;
- else {
- SlaveConfigProtocol *scp = d->findProtocolConfig(protocol);
- if (host.isEmpty())
- {
- scp->global += config;
- }
- else
- {
- MetaData *hostConfig = scp->host.find(host);
- if (!hostConfig)
- {
- d->readConfigProtocolHost(protocol, scp, host);
- hostConfig = scp->host.find(host);
- assert(hostConfig);
- }
- *hostConfig += config;
- }
- }
-}
-
-MetaData SlaveConfig::configData(const TQString &protocol, const TQString &host)
-{
- MetaData config = d->global;
- SlaveConfigProtocol *scp = d->findProtocolConfig(protocol);
- config += scp->global;
- if (host.isEmpty())
- return config;
- MetaData *hostConfig = scp->host.find(host);
- if (!hostConfig)
- {
- d->readConfigProtocolHost(protocol, scp, host);
- emit configNeeded(protocol, host);
- hostConfig = scp->host.find(host);
- assert(hostConfig);
- }
- config += *hostConfig;
- return config;
-}
-
-TQString SlaveConfig::configData(const TQString &protocol, const TQString &host, const TQString &key)
-{
- return configData(protocol, host)[key];
-}
-
-void SlaveConfig::reset()
-{
- d->protocol.clear();
- d->readGlobalConfig();
-}
-
-}
-
-#include "slaveconfig.moc"
diff --git a/kio/kio/slaveconfig.h b/kio/kio/slaveconfig.h
deleted file mode 100644
index 5bdc6cda8..000000000
--- a/kio/kio/slaveconfig.h
+++ /dev/null
@@ -1,106 +0,0 @@
-// -*- c++ -*-
-/*
- * This file is part of the KDE libraries
- * Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#ifndef KIO_SLAVE_CONFIG_H
-#define KIO_SLAVE_CONFIG_H
-
-#include <tqobject.h>
-#include <kio/global.h>
-
-namespace TDEIO {
-
- class SlaveConfigPrivate;
- /**
- * SlaveConfig
- *
- * This class manages the configuration for io-slaves based on protocol
- * and host. The Scheduler makes use of this class to configure the slave
- * whenever it has to connect to a new host.
- *
- * You only need to use this class if you want to override specific
- * configuration items of an io-slave when the io-slave is used by
- * your application.
- *
- * Normally io-slaves are being configured by "kio_<protocol>rc"
- * configuration files. Groups defined in such files are treated as host
- * or domain specification. Configuration items defined in a group are
- * only applied when the slave is connecting with a host that matches with
- * the host and/or domain specified by the group.
- */
- class TDEIO_EXPORT SlaveConfig : public TQObject
- {
- Q_OBJECT
- public:
- static SlaveConfig *self();
- ~SlaveConfig();
- /**
- * Configure slaves of type @p protocol by setting @p key to @p value.
- * If @p host is specified the configuration only applies when dealing
- * with @p host.
- *
- * Changes made to the slave configuration only apply to slaves
- * used by the current process.
- */
- void setConfigData(const TQString &protocol, const TQString &host, const TQString &key, const TQString &value );
-
- /**
- * Configure slaves of type @p protocol with @p config.
- * If @p host is specified the configuration only applies when dealing
- * with @p host.
- *
- * Changes made to the slave configuration only apply to slaves
- * used by the current process.
- */
- void setConfigData(const TQString &protocol, const TQString &host, const MetaData &config );
-
- /**
- * Query slave configuration for slaves of type @p protocol when
- * dealing with @p host.
- */
- MetaData configData(const TQString &protocol, const TQString &host);
-
- /**
- * Query a specific configuration key for slaves of type @p protocol when
- * dealing with @p host.
- */
- TQString configData(const TQString &protocol, const TQString &host, const TQString &key);
-
- /**
- * Undo any changes made by calls to setConfigData.
- */
- void reset();
- signals:
- /**
- * This signal is raised when a slave of type @p protocol deals
- * with @p host for the first time.
- *
- * Your application can use this signal to make some last minute
- * configuration changes with setConfigData based on the
- * host.
- */
- void configNeeded(const TQString &protocol, const TQString &host);
- protected:
- SlaveConfig();
- static SlaveConfig *_self;
- SlaveConfigPrivate *d;
- };
-}
-
-#endif
diff --git a/kio/kio/slaveinterface.cpp b/kio/kio/slaveinterface.cpp
deleted file mode 100644
index 5ba2f6e86..000000000
--- a/kio/kio/slaveinterface.cpp
+++ /dev/null
@@ -1,550 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kio/slaveinterface.h"
-#include "kio/slavebase.h"
-#include "kio/connection.h"
-#include <errno.h>
-#include <assert.h>
-#include <kdebug.h>
-#include <stdlib.h>
-#include <sys/time.h>
-#include <unistd.h>
-#include <signal.h>
-#include <kio/observer.h>
-#include <kapplication.h>
-#include <dcopclient.h>
-#include <time.h>
-#include <tqtimer.h>
-
-using namespace TDEIO;
-
-
-TQDataStream &operator <<(TQDataStream &s, const TDEIO::UDSEntry &e )
-{
- // On 32-bit platforms we send UDS_SIZE with UDS_SIZE_LARGE in front
- // of it to carry the 32 msb. We can't send a 64 bit UDS_SIZE because
- // that would break the compatibility of the wire-protocol with KDE 2.
- // We do the same on 64-bit platforms in case we run in a mixed 32/64bit
- // environment.
-
- TQ_UINT32 size = 0;
- TDEIO::UDSEntry::ConstIterator it = e.begin();
- for( ; it != e.end(); ++it )
- {
- size++;
- if ((*it).m_uds == TDEIO::UDS_SIZE)
- size++;
- }
- s << size;
- it = e.begin();
- for( ; it != e.end(); ++it )
- {
- if ((*it).m_uds == TDEIO::UDS_SIZE)
- {
- TDEIO::UDSAtom a;
- a.m_uds = TDEIO::UDS_SIZE_LARGE;
- a.m_long = (*it).m_long >> 32;
- s << a;
- }
- s << *it;
- }
- return s;
-}
-
-TQDataStream &operator >>(TQDataStream &s, TDEIO::UDSEntry &e )
-{
- e.clear();
- TQ_UINT32 size;
- s >> size;
-
- // On 32-bit platforms we send UDS_SIZE with UDS_SIZE_LARGE in front
- // of it to carry the 32 msb. We can't send a 64 bit UDS_SIZE because
- // that would break the compatibility of the wire-protocol with KDE 2.
- // We do the same on 64-bit platforms in case we run in a mixed 32/64bit
- // environment.
- TQ_LLONG msb = 0;
- for(TQ_UINT32 i = 0; i < size; i++)
- {
- TDEIO::UDSAtom a;
- s >> a;
- if (a.m_uds == TDEIO::UDS_SIZE_LARGE)
- {
- msb = a.m_long;
- }
- else
- {
- if (a.m_uds == TDEIO::UDS_SIZE)
- {
- if (a.m_long < 0)
- a.m_long += (TQ_LLONG) 1 << 32;
- a.m_long += msb << 32;
- }
- e.append(a);
- msb = 0;
- }
- }
- return s;
-}
-
-static const unsigned int max_nums = 8;
-
-class TDEIO::SlaveInterfacePrivate
-{
-public:
- SlaveInterfacePrivate() {
- slave_calcs_speed = false;
- start_time.tv_sec = 0;
- start_time.tv_usec = 0;
- last_time = 0;
- nums = 0;
- filesize = 0;
- offset = 0;
- }
- bool slave_calcs_speed;
- struct timeval start_time;
- uint nums;
- long times[max_nums];
- TDEIO::filesize_t sizes[max_nums];
- size_t last_time;
- TDEIO::filesize_t filesize, offset;
-
- TQTimer speed_timer;
-};
-
-//////////////
-
-SlaveInterface::SlaveInterface( Connection * connection )
-{
- m_pConnection = connection;
- m_progressId = 0;
-
- d = new SlaveInterfacePrivate;
- connect(&d->speed_timer, TQT_SIGNAL(timeout()), TQT_SLOT(calcSpeed()));
-}
-
-SlaveInterface::~SlaveInterface()
-{
- // Note: no kdDebug() here (scheduler is deleted very late)
- m_pConnection = 0; // a bit like the "wasDeleted" of TQObject...
-
- delete d;
-}
-
-static TDEIO::filesize_t readFilesize_t(TQDataStream &stream)
-{
- TDEIO::filesize_t result;
- unsigned long ul;
- stream >> ul;
- result = ul;
- if (stream.atEnd())
- return result;
- stream >> ul;
- result += ((TDEIO::filesize_t)ul) << 32;
- return result;
-}
-
-
-bool SlaveInterface::dispatch()
-{
- assert( m_pConnection );
-
- int cmd;
- TQByteArray data;
-
- if (m_pConnection->read( &cmd, data ) == -1)
- return false;
-
- return dispatch( cmd, data );
-}
-
-void SlaveInterface::calcSpeed()
-{
- if (d->slave_calcs_speed) {
- d->speed_timer.stop();
- return;
- }
-
- struct timeval tv;
- gettimeofday(&tv, 0);
-
- long diff = ((tv.tv_sec - d->start_time.tv_sec) * 1000000 +
- tv.tv_usec - d->start_time.tv_usec) / 1000;
- if (diff - d->last_time >= 900) {
- d->last_time = diff;
- if (d->nums == max_nums) {
- // let's hope gcc can optimize that well enough
- // otherwise I'd try memcpy :)
- for (unsigned int i = 1; i < max_nums; ++i) {
- d->times[i-1] = d->times[i];
- d->sizes[i-1] = d->sizes[i];
- }
- d->nums--;
- }
- d->times[d->nums] = diff;
- d->sizes[d->nums++] = d->filesize - d->offset;
-
- TDEIO::filesize_t lspeed = 1000 * (d->sizes[d->nums-1] - d->sizes[0]) / (d->times[d->nums-1] - d->times[0]);
-
-// kdDebug() << "proceeed " << (long)d->filesize << " " << diff << " "
-// << long(d->sizes[d->nums-1] - d->sizes[0]) << " "
-// << d->times[d->nums-1] - d->times[0] << " "
-// << long(lspeed) << " " << double(d->filesize) / diff
-// << " " << convertSize(lspeed) << " "
-// << convertSize(long(double(d->filesize) / diff) * 1000) << " "
-// << endl ;
-
- if (!lspeed) {
- d->nums = 1;
- d->times[0] = diff;
- d->sizes[0] = d->filesize - d->offset;
- }
- emit speed(lspeed);
- }
-}
-
-bool SlaveInterface::dispatch( int _cmd, const TQByteArray &rawdata )
-{
- //kdDebug(7007) << "dispatch " << _cmd << endl;
-
- TQDataStream stream( rawdata, IO_ReadOnly );
-
- TQString str1;
- TQ_INT32 i;
- TQ_INT8 b;
- TQ_UINT32 ul;
-
- switch( _cmd ) {
- case MSG_DATA:
- emit data( rawdata );
- break;
- case MSG_DATA_REQ:
- emit dataReq();
- break;
- case MSG_FINISHED:
- //kdDebug(7007) << "Finished [this = " << this << "]" << endl;
- d->offset = 0;
- d->speed_timer.stop();
- emit finished();
- break;
- case MSG_STAT_ENTRY:
- {
- UDSEntry entry;
- stream >> entry;
- emit statEntry(entry);
- }
- break;
- case MSG_LIST_ENTRIES:
- {
- TQ_UINT32 count;
- stream >> count;
-
- UDSEntryList list;
- UDSEntry entry;
- for (uint i = 0; i < count; i++) {
- stream >> entry;
- list.append(entry);
- }
- emit listEntries(list);
-
- }
- break;
- case MSG_RESUME: // From the put job
- {
- d->offset = readFilesize_t(stream);
- emit canResume( d->offset );
- }
- break;
- case MSG_CANRESUME: // From the get job
- d->filesize = d->offset;
- emit canResume(0); // the arg doesn't matter
- break;
- case MSG_ERROR:
- stream >> i >> str1;
- kdDebug(7007) << "error " << i << " " << str1 << endl;
- emit error( i, str1 );
- break;
- case MSG_SLAVE_STATUS:
- {
- pid_t pid;
- TQCString protocol;
- stream >> pid >> protocol >> str1 >> b;
- emit slaveStatus(pid, protocol, str1, (b != 0));
- }
- break;
- case MSG_CONNECTED:
- emit connected();
- break;
-
- case INF_TOTAL_SIZE:
- {
- TDEIO::filesize_t size = readFilesize_t(stream);
- gettimeofday(&d->start_time, 0);
- d->last_time = 0;
- d->filesize = d->offset;
- d->sizes[0] = d->filesize - d->offset;
- d->times[0] = 0;
- d->nums = 1;
- d->speed_timer.start(1000);
- d->slave_calcs_speed = false;
- emit totalSize( size );
- }
- break;
- case INF_PROCESSED_SIZE:
- {
- TDEIO::filesize_t size = readFilesize_t(stream);
- emit processedSize( size );
- d->filesize = size;
- }
- break;
- case INF_SPEED:
- stream >> ul;
- d->slave_calcs_speed = true;
- d->speed_timer.stop();
-
- emit speed( ul );
- break;
- case INF_GETTING_FILE:
- break;
- case INF_ERROR_PAGE:
- emit errorPage();
- break;
- case INF_REDIRECTION:
- {
- KURL url;
- stream >> url;
-
- emit redirection( url );
- }
- break;
- case INF_MIME_TYPE:
- stream >> str1;
-
- emit mimeType( str1 );
- if (!m_pConnection->suspended())
- m_pConnection->sendnow( CMD_NONE, TQByteArray() );
- break;
- case INF_WARNING:
- stream >> str1;
-
- emit warning( str1 );
- break;
- case INF_NEED_PASSWD: {
- AuthInfo info;
- stream >> info;
- openPassDlg( info );
- break;
- }
- case INF_MESSAGEBOX: {
- kdDebug(7007) << "needs a msg box" << endl;
- TQString text, caption, buttonYes, buttonNo, dontAskAgainName;
- int type;
- stream >> type >> text >> caption >> buttonYes >> buttonNo;
- if (stream.atEnd())
- messageBox(type, text, caption, buttonYes, buttonNo);
- else {
- stream >> dontAskAgainName;
- messageBox(type, text, caption, buttonYes, buttonNo, dontAskAgainName);
- }
- break;
- }
- case INF_INFOMESSAGE: {
- TQString msg;
- stream >> msg;
- infoMessage(msg);
- break;
- }
- case INF_META_DATA: {
- MetaData meta_data;
- stream >> meta_data;
- metaData(meta_data);
- break;
- }
- case INF_LOCALURL: {
- TQ_INT8 islocal;
- KURL url;
- stream >> islocal >> url;
- emit localURL( url, islocal );
- break;
- }
- case MSG_NET_REQUEST: {
- TQString host;
- TQString slaveid;
- stream >> host >> slaveid;
- requestNetwork(host, slaveid);
- break;
- }
- case MSG_NET_DROP: {
- TQString host;
- TQString slaveid;
- stream >> host >> slaveid;
- dropNetwork(host, slaveid);
- break;
- }
- case MSG_NEED_SUBURL_DATA: {
- emit needSubURLData();
- break;
- }
- case MSG_AUTH_KEY: {
- bool keep;
- TQCString key, group;
- stream >> key >> group >> keep;
- kdDebug(7007) << "Got auth-key: " << key << endl
- << " group-key: " << group << endl
- << " keep password: " << keep << endl;
- emit authorizationKey( key, group, keep );
- break;
- }
- case MSG_DEL_AUTH_KEY: {
- TQCString key;
- stream >> key;
- kdDebug(7007) << "Delete auth-key: " << key << endl;
- emit delAuthorization( key );
- }
- default:
- kdWarning(7007) << "Slave sends unknown command (" << _cmd << "), dropping slave" << endl;
- return false;
- }
- return true;
-}
-
-void SlaveInterface::setOffset( TDEIO::filesize_t o)
-{
- d->offset = o;
-}
-
-TDEIO::filesize_t SlaveInterface::offset() const { return d->offset; }
-
-void SlaveInterface::requestNetwork(const TQString &host, const TQString &slaveid)
-{
- kdDebug(7007) << "requestNetwork " << host << slaveid << endl;
- TQByteArray packedArgs;
- TQDataStream stream( packedArgs, IO_WriteOnly );
- stream << true;
- m_pConnection->sendnow( INF_NETWORK_STATUS, packedArgs );
-}
-
-void SlaveInterface::dropNetwork(const TQString &host, const TQString &slaveid)
-{
- kdDebug(7007) << "dropNetwork " << host << slaveid << endl;
-}
-
-void SlaveInterface::sendResumeAnswer( bool resume )
-{
- kdDebug(7007) << "SlaveInterface::sendResumeAnswer ok for resuming :" << resume << endl;
- m_pConnection->sendnow( resume ? CMD_RESUMEANSWER : CMD_NONE, TQByteArray() );
-}
-
-void SlaveInterface::openPassDlg( const TQString& prompt, const TQString& user, bool readOnly )
-{
- AuthInfo info;
- info.prompt = prompt;
- info.username = user;
- info.readOnly = readOnly;
- openPassDlg( info );
-}
-
-void SlaveInterface::openPassDlg( const TQString& prompt, const TQString& user,
- const TQString& caption, const TQString& comment,
- const TQString& label, bool readOnly )
-{
- AuthInfo info;
- info.prompt = prompt;
- info.username = user;
- info.caption = caption;
- info.comment = comment;
- info.commentLabel = label;
- info.readOnly = readOnly;
- openPassDlg( info );
-}
-
-void SlaveInterface::openPassDlg( AuthInfo& info )
-{
- kdDebug(7007) << "SlaveInterface::openPassDlg: "
- << "User= " << info.username
- << ", Message= " << info.prompt << endl;
- bool result = Observer::self()->openPassDlg( info );
- if ( m_pConnection )
- {
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly );
- if ( result )
- {
- stream << info;
- kdDebug(7007) << "SlaveInterface:::openPassDlg got: "
- << "User= " << info.username
- << ", Password= [hidden]" << endl;
- m_pConnection->sendnow( CMD_USERPASS, data );
- }
- else
- m_pConnection->sendnow( CMD_NONE, data );
- }
-}
-
-void SlaveInterface::messageBox( int type, const TQString &text, const TQString &_caption,
- const TQString &buttonYes, const TQString &buttonNo )
-{
- messageBox( type, text, _caption, buttonYes, buttonNo, TQString::null );
-}
-
-void SlaveInterface::messageBox( int type, const TQString &text, const TQString &_caption,
- const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName )
-{
- kdDebug(7007) << "messageBox " << type << " " << text << " - " << _caption << " " << dontAskAgainName << endl;
- TQByteArray packedArgs;
- TQDataStream stream( packedArgs, IO_WriteOnly );
-
- TQString caption( _caption );
- if ( type == TDEIO::SlaveBase::SSLMessageBox )
- caption = TQString::fromUtf8(kapp->dcopClient()->appId()); // hack, see observer.cpp
-
- emit needProgressId();
- kdDebug(7007) << "SlaveInterface::messageBox m_progressId=" << m_progressId << endl;
- TQGuardedPtr<SlaveInterface> me = this;
- m_pConnection->suspend();
- int result = Observer::/*self()->*/messageBox( m_progressId, type, text, caption, buttonYes, buttonNo, dontAskAgainName );
- if ( me && m_pConnection ) // Don't do anything if deleted meanwhile
- {
- m_pConnection->resume();
- kdDebug(7007) << this << " SlaveInterface result=" << result << endl;
- stream << result;
- m_pConnection->sendnow( CMD_MESSAGEBOXANSWER, packedArgs );
- }
-}
-
-// No longer used.
-// Remove in KDE 4.0
-void SlaveInterface::sigpipe_handler(int)
-{
- int saved_errno = errno;
- // Using kdDebug from a signal handler is not a good idea.
-#ifndef NDEBUG
- char msg[1000];
- sprintf(msg, "*** SIGPIPE *** (ignored, pid = %ld)\n", (long) getpid());
- write(2, msg, strlen(msg));
-#endif
-
- // Do nothing.
- // dispatch will return false and that will trigger ERR_SLAVE_DIED in slave.cpp
- errno = saved_errno;
-}
-
-void SlaveInterface::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-#include "slaveinterface.moc"
diff --git a/kio/kio/slaveinterface.h b/kio/kio/slaveinterface.h
deleted file mode 100644
index 8ac7b683e..000000000
--- a/kio/kio/slaveinterface.h
+++ /dev/null
@@ -1,290 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __kio_slaveinterface_h
-#define __kio_slaveinterface_h
-
-#include <unistd.h>
-#include <sys/types.h>
-
-#include <tqobject.h>
-
-#include <kurl.h>
-#include <kio/global.h>
-#include <kio/authinfo.h>
-#include <kdatastream.h>
-
-namespace TDEIO {
-
-class Connection;
-// better there is one ...
-class SlaveInterfacePrivate;
-
- // Definition of enum Command has been moved to global.h
-
- /**
- * Identifiers for KIO informational messages.
- */
- enum Info {
- INF_TOTAL_SIZE = 10,
- INF_PROCESSED_SIZE = 11,
- INF_SPEED,
- INF_REDIRECTION = 20,
- INF_MIME_TYPE = 21,
- INF_ERROR_PAGE = 22,
- INF_WARNING = 23,
- INF_GETTING_FILE, // Deprecated
- INF_NEED_PASSWD = 25,
- INF_INFOMESSAGE,
- INF_META_DATA,
- INF_NETWORK_STATUS,
- INF_MESSAGEBOX,
- INF_LOCALURL
- // add new ones here once a release is done, to avoid breaking binary compatibility
- };
-
- /**
- * Identifiers for KIO data messages.
- */
- enum Message {
- MSG_DATA = 100,
- MSG_DATA_REQ,
- MSG_ERROR,
- MSG_CONNECTED,
- MSG_FINISHED,
- MSG_STAT_ENTRY,
- MSG_LIST_ENTRIES,
- MSG_RENAMED, // unused
- MSG_RESUME,
- MSG_SLAVE_STATUS,
- MSG_SLAVE_ACK,
- MSG_NET_REQUEST,
- MSG_NET_DROP,
- MSG_NEED_SUBURL_DATA,
- MSG_CANRESUME,
- MSG_AUTH_KEY, // deprecated.
- MSG_DEL_AUTH_KEY // deprecated.
- // add new ones here once a release is done, to avoid breaking binary compatibility
- };
-
-/**
- * There are two classes that specifies the protocol between application
- * (TDEIO::Job) and kioslave. SlaveInterface is the class to use on the application
- * end, SlaveBase is the one to use on the slave end.
- *
- * A call to foo() results in a call to slotFoo() on the other end.
- */
-class TDEIO_EXPORT SlaveInterface : public TQObject
-{
- Q_OBJECT
-
-public:
- SlaveInterface( Connection *connection );
- virtual ~SlaveInterface();
-
- void setConnection( Connection* connection ) { m_pConnection = connection; }
- Connection *connection() const { return m_pConnection; }
-
- void setProgressId( int id ) { m_progressId = id; }
- int progressId() const { return m_progressId; }
-
- /** Send our answer to the MSG_RESUME (canResume) request
- * (to tell the "put" job whether to resume or not)
- */
- void sendResumeAnswer( bool resume );
-
- void setOffset( TDEIO::filesize_t offset );
- TDEIO::filesize_t offset() const;
-
-signals:
- ///////////
- // Messages sent by the slave
- ///////////
-
- void data( const TQByteArray & );
- void dataReq( );
- void error( int , const TQString & );
- void connected();
- void finished();
- void slaveStatus(pid_t, const TQCString &, const TQString &, bool);
- void listEntries( const TDEIO::UDSEntryList& );
- void statEntry( const TDEIO::UDSEntry& );
- void needSubURLData();
- void needProgressId();
-
- void canResume( TDEIO::filesize_t ) ;
-
- ///////////
- // Info sent by the slave
- //////////
- void metaData( const TDEIO::MetaData & );
- void totalSize( TDEIO::filesize_t ) ;
- void processedSize( TDEIO::filesize_t ) ;
- void redirection( const KURL& ) ;
- void localURL( const KURL&, bool ) ;
-
- void speed( unsigned long ) ;
- void errorPage() ;
- void mimeType( const TQString & ) ;
- void warning( const TQString & ) ;
- void infoMessage( const TQString & ) ;
- void connectFinished();
-
- /**
- * @deprecated. Obsolete as of 3.1. Replaced by kpassword, a kded module.
- */
- void authorizationKey( const TQCString&, const TQCString&, bool );
-
- /**
- * @deprecated. Obsolete as of 3.1. Replaced by kpassword, a kded module.
- */
- void delAuthorization( const TQCString& grpkey );
-
-protected:
- /////////////////
- // Dispatching
- ////////////////
-
- virtual bool dispatch();
- virtual bool dispatch( int _cmd, const TQByteArray &data );
-
- /**
- * Prompt the user for authrization info (login & password).
- *
- * Use this function to request authorization info from the
- * the end user. For example to open an empty password dialog
- * using default values:
- *
- * \code
- * TDEIO::AuthInfo authInfo;
- * bool result = openPassDlg( authInfo );
- * if ( result )
- * {
- * printf( "Username: %s", result.username.latin1() );
- * printf( "Username: %s", result.username.latin1() );
- * }
- * \endcode
- *
- * You can also pre-set some values like the username before hand
- * if it is known as well as the comment and caption to be displayed:
- *
- * \code
- * authInfo.comment= "Enter username and password to access acmeone";
- * authInfo.caption= "Acme Password Dialog";
- * authInfo.username= "Wily E. kaiody";
- * bool result = openPassDlg( authInfo );
- * if ( result )
- * {
- * printf( "Username: %s", result.username.latin1() );
- * printf( "Username: %s", result.username.latin1() );
- * }
- * \endcode
- *
- * NOTE: A call to this function can also fail and result
- * in a return value of @p false, if the UIServer could not
- * be started for whatever reason.
- *
- * @param info See AuthInfo.
- * @return true if user clicks on "OK", false otherwsie.
- */
- void openPassDlg( TDEIO::AuthInfo& info );
-
- /**
- * @deprecated. Use openPassDlg( AuthInfo& ) instead.
- */
- void openPassDlg( const TQString& prompt, const TQString& user,
- const TQString& caption, const TQString& comment,
- const TQString& label, bool readOnly ) KDE_DEPRECATED;
-
- /**
- * @deprecated. Use openPassDlg( AuthInfo& ) instead.
- */
- void openPassDlg( const TQString& prompt, const TQString& user, bool readOnly ) KDE_DEPRECATED;
-
- void messageBox( int type, const TQString &text, const TQString &caption,
- const TQString &buttonYes, const TQString &buttonNo );
-
- /**
- * @since 3.3
- */
- void messageBox( int type, const TQString &text, const TQString &caption,
- const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName );
-
- // I need to identify the slaves
- void requestNetwork( const TQString &, const TQString &);
- void dropNetwork( const TQString &, const TQString &);
-
- /**
- * @internal
- * KDE 4.0: Remove
- */
- static void sigpipe_handler(int);
-
-protected slots:
- void calcSpeed();
-
-protected:
- Connection * m_pConnection;
-
-private:
- int m_progressId;
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- SlaveInterfacePrivate *d;
-};
-
-}
-
-inline TQDataStream &operator >>(TQDataStream &s, TDEIO::UDSAtom &a )
-{
- TQ_INT32 l;
- s >> a.m_uds;
-
- if ( a.m_uds & TDEIO::UDS_LONG ) {
- s >> l;
- a.m_long = l;
- a.m_str = TQString::null;
- } else if ( a.m_uds & TDEIO::UDS_STRING ) {
- s >> a.m_str;
- a.m_long = 0;
- } else {} // DIE!
- // assert( 0 );
-
- return s;
-}
-
-inline TQDataStream &operator <<(TQDataStream &s, const TDEIO::UDSAtom &a )
-{
- s << a.m_uds;
-
- if ( a.m_uds & TDEIO::UDS_LONG )
- s << (TQ_INT32) a.m_long;
- else if ( a.m_uds & TDEIO::UDS_STRING )
- s << a.m_str;
- else {} // DIE!
- // assert( 0 );
-
- return s;
-}
-
-TDEIO_EXPORT TQDataStream &operator <<(TQDataStream &s, const TDEIO::UDSEntry &e );
-TDEIO_EXPORT TQDataStream &operator >>(TQDataStream &s, TDEIO::UDSEntry &e );
-
-#endif
diff --git a/kio/kio/tcpslavebase.cpp b/kio/kio/tcpslavebase.cpp
deleted file mode 100644
index 8d3cc49ff..000000000
--- a/kio/kio/tcpslavebase.cpp
+++ /dev/null
@@ -1,1343 +0,0 @@
-/*
- * $Id$
- *
- * Copyright (C) 2000 Alex Zepeda <zipzippy@sonic.net
- * Copyright (C) 2001-2003 George Staikos <staikos@kde.org>
- * Copyright (C) 2001 Dawit Alemayehu <adawit@kde.org>
- *
- * This file is part of the KDE project
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <sys/time.h>
-#include <sys/socket.h>
-
-#include <netinet/in.h>
-
-#include <time.h>
-#include <netdb.h>
-#include <unistd.h>
-#include <errno.h>
-
-#include <ksocks.h>
-#include <kdebug.h>
-#include <ksslall.h>
-#include <ksslcertdlg.h>
-#include <kmessagebox.h>
-#ifndef Q_WS_WIN //temporary
-#include <kresolver.h>
-#endif
-
-#include <klocale.h>
-#include <dcopclient.h>
-#include <tqcstring.h>
-#include <tqdatastream.h>
-
-#include <kapplication.h>
-
-#include <kprotocolmanager.h>
-#include <kde_file.h>
-
-#include "kio/tcpslavebase.h"
-
-using namespace TDEIO;
-
-class TCPSlaveBase::TcpSlaveBasePrivate
-{
-public:
-
- TcpSlaveBasePrivate() : rblockSz(256), militantSSL(false), userAborted(false) {}
- ~TcpSlaveBasePrivate() {}
-
- KSSL *kssl;
- bool usingTLS;
- KSSLCertificateCache *cc;
- TQString host;
- TQString realHost;
- TQString ip;
- DCOPClient *dcc;
- KSSLPKCS12 *pkcs;
-
- int status;
- int timeout;
- int rblockSz; // Size for reading blocks in readLine()
- bool block;
- bool useSSLTunneling;
- bool needSSLHandShake;
- bool militantSSL; // If true, we just drop a connection silently
- // if SSL certificate check fails in any way.
- bool userAborted;
- MetaData savedMetaData;
-};
-
-
-TCPSlaveBase::TCPSlaveBase(unsigned short int defaultPort,
- const TQCString &protocol,
- const TQCString &poolSocket,
- const TQCString &appSocket)
- :SlaveBase (protocol, poolSocket, appSocket),
- m_iSock(-1),
- m_iDefaultPort(defaultPort),
- m_sServiceName(protocol),
- fp(0)
-{
- // We have to have two constructors, so don't add anything
- // else in here. Put it in doConstructorStuff() instead.
- doConstructorStuff();
- m_bIsSSL = false;
-}
-
-TCPSlaveBase::TCPSlaveBase(unsigned short int defaultPort,
- const TQCString &protocol,
- const TQCString &poolSocket,
- const TQCString &appSocket,
- bool useSSL)
- :SlaveBase (protocol, poolSocket, appSocket),
- m_iSock(-1),
- m_bIsSSL(useSSL),
- m_iDefaultPort(defaultPort),
- m_sServiceName(protocol),
- fp(0)
-{
- doConstructorStuff();
- if (useSSL)
- m_bIsSSL = initializeSSL();
-}
-
-// The constructor procedures go here now.
-void TCPSlaveBase::doConstructorStuff()
-{
- d = new TcpSlaveBasePrivate;
- d->kssl = 0L;
- d->ip = "";
- d->cc = 0L;
- d->usingTLS = false;
- d->dcc = 0L;
- d->pkcs = 0L;
- d->status = -1;
- d->timeout = KProtocolManager::connectTimeout();
- d->block = false;
- d->useSSLTunneling = false;
-}
-
-TCPSlaveBase::~TCPSlaveBase()
-{
- cleanSSL();
- if (d->usingTLS) delete d->kssl;
- if (d->dcc) delete d->dcc;
- if (d->pkcs) delete d->pkcs;
- delete d;
-}
-
-ssize_t TCPSlaveBase::write(const void *data, ssize_t len)
-{
-#ifdef Q_OS_UNIX
- if ( (m_bIsSSL || d->usingTLS) && !d->useSSLTunneling )
- {
- if ( d->needSSLHandShake )
- (void) doSSLHandShake( true );
- return d->kssl->write(data, len);
- }
- return KSocks::self()->write(m_iSock, data, len);
-#else
- return 0;
-#endif
-}
-
-ssize_t TCPSlaveBase::read(void *data, ssize_t len)
-{
-#ifdef Q_OS_UNIX
- if ( (m_bIsSSL || d->usingTLS) && !d->useSSLTunneling )
- {
- if ( d->needSSLHandShake )
- (void) doSSLHandShake( true );
- return d->kssl->read(data, len);
- }
- return KSocks::self()->read(m_iSock, data, len);
-#else
- return 0;
-#endif
-}
-
-
-void TCPSlaveBase::setBlockSize(int sz)
-{
- if (sz <= 0)
- sz = 1;
-
- d->rblockSz = sz;
-}
-
-
-ssize_t TCPSlaveBase::readLine(char *data, ssize_t len)
-{
-// Optimization:
-// It's small, but it probably results in a gain on very high
-// speed connections. I moved 3 if statements out of the while loop
-// so that the while loop is as small as possible. (GS)
-
- // let's not segfault!
- if (!data)
- return -1;
-
- char tmpbuf[1024]; // 1kb temporary buffer for peeking
- *data = 0;
- ssize_t clen = 0;
- char *buf = data;
- int rc = 0;
-
-if ((m_bIsSSL || d->usingTLS) && !d->useSSLTunneling) { // SSL CASE
- if ( d->needSSLHandShake )
- (void) doSSLHandShake( true );
-
- while (clen < len-1) {
- rc = d->kssl->pending();
- if (rc > 0) { // Read a chunk
- int bytes = rc;
- if (bytes > d->rblockSz)
- bytes = d->rblockSz;
-
- rc = d->kssl->peek(tmpbuf, bytes);
- if (rc <= 0) {
- // FIXME: this doesn't cover rc == 0 case
- return -1;
- }
-
- bytes = rc; // in case it contains no \n
- for (int i = 0; i < rc; i++) {
- if (tmpbuf[i] == '\n') {
- bytes = i+1;
- break;
- }
- }
-
- if (bytes+clen >= len) // don't read too much!
- bytes = len - clen - 1;
-
- rc = d->kssl->read(buf, bytes);
- if (rc > 0) {
- clen += rc;
- buf += (rc-1);
- if (*buf++ == '\n')
- break;
- } else {
- // FIXME: different case if rc == 0;
- return -1;
- }
- } else { // Read a byte
- rc = d->kssl->read(buf, 1);
- if (rc <= 0) {
- return -1;
- // hm rc = 0 then
- // SSL_read says to call SSL_get_error to see if
- // this was an error. FIXME
- } else {
- clen++;
- if (*buf++ == '\n')
- break;
- }
- }
- }
-} else { // NON SSL CASE
- while (clen < len-1) {
-#ifdef Q_OS_UNIX
- rc = KSocks::self()->read(m_iSock, buf, 1);
-#else
- rc = 0;
-#endif
- if (rc <= 0) {
- // FIXME: this doesn't cover rc == 0 case
- return -1;
- } else {
- clen++;
- if (*buf++ == '\n')
- break;
- }
- }
-}
-
- // Both cases fall through to here
- *buf = 0;
-return clen;
-}
-
-unsigned short int TCPSlaveBase::port(unsigned short int _p)
-{
- unsigned short int p = _p;
-
- if (_p <= 0)
- {
- p = m_iDefaultPort;
- }
-
- return p;
-}
-
-// This function is simply a wrapper to establish the connection
-// to the server. It's a bit more complicated than ::connect
-// because we first have to check to see if the user specified
-// a port, and if so use it, otherwise we check to see if there
-// is a port specified in /etc/services, and if so use that
-// otherwise as a last resort use the supplied default port.
-bool TCPSlaveBase::connectToHost( const TQString &host,
- unsigned int _port,
- bool sendError )
-{
-#ifdef Q_OS_UNIX
- unsigned short int p;
- KExtendedSocket ks;
-
- d->userAborted = false;
-
- // - leaving SSL - warn before we even connect
- if (metaData("main_frame_request") == "TRUE" &&
- metaData("ssl_activate_warnings") == "TRUE" &&
- metaData("ssl_was_in_use") == "TRUE" &&
- !m_bIsSSL) {
- KSSLSettings kss;
- if (kss.warnOnLeave()) {
- int result = messageBox( i18n("You are about to leave secure "
- "mode. Transmissions will no "
- "longer be encrypted.\nThis "
- "means that a third party could "
- "observe your data in transit."),
- WarningContinueCancel,
- i18n("Security Information"),
- i18n("C&ontinue Loading"), TQString::null,
- "WarnOnLeaveSSLMode" );
-
- // Move this setting into KSSL instead
- TDEConfig *config = new TDEConfig("kioslaverc");
- config->setGroup("Notification Messages");
-
- if (!config->readBoolEntry("WarnOnLeaveSSLMode", true)) {
- config->deleteEntry("WarnOnLeaveSSLMode");
- config->sync();
- kss.setWarnOnLeave(false);
- kss.save();
- }
- delete config;
-
- if ( result == KMessageBox::Cancel ) {
- d->userAborted = true;
- return false;
- }
- }
- }
-
- d->status = -1;
- d->host = host;
- d->needSSLHandShake = m_bIsSSL;
- p = port(_port);
- ks.setAddress(host, p);
- if ( d->timeout > -1 )
- ks.setTimeout( d->timeout );
-
- if (ks.connect() < 0)
- {
- d->status = ks.status();
- if ( sendError )
- {
- if (d->status == IO_LookupError)
- error( ERR_UNKNOWN_HOST, host);
- else if ( d->status != -1 )
- error( ERR_COULD_NOT_CONNECT, host);
- }
- return false;
- }
-
- m_iSock = ks.fd();
-
- // store the IP for later
- const TDESocketAddress *sa = ks.peerAddress();
- if (sa)
- d->ip = sa->nodeName();
- else
- d->ip = "";
-
- ks.release(); // KExtendedSocket no longer applicable
-
- if ( d->block != ks.blockingMode() )
- ks.setBlockingMode( d->block );
-
- m_iPort=p;
-
- if (m_bIsSSL && !d->useSSLTunneling) {
- if ( !doSSLHandShake( sendError ) )
- return false;
- }
- else
- setMetaData("ssl_in_use", "FALSE");
-
- // Since we want to use stdio on the socket,
- // we must fdopen it to get a file pointer,
- // if it fails, close everything up
- if ((fp = KDE_fdopen(m_iSock, "w+")) == 0) {
- closeDescriptor();
- return false;
- }
-
- return true;
-#else //!Q_OS_UNIX
- return false;
-#endif //Q_OS_UNIX
-}
-
-void TCPSlaveBase::closeDescriptor()
-{
- stopTLS();
- if (fp) {
- fclose(fp);
- fp=0;
- m_iSock=-1;
- if (m_bIsSSL)
- d->kssl->close();
- }
- if (m_iSock != -1) {
- close(m_iSock);
- m_iSock=-1;
- }
- d->ip = "";
- d->host = "";
-}
-
-bool TCPSlaveBase::initializeSSL()
-{
- if (m_bIsSSL) {
- if (KSSL::doesSSLWork()) {
- d->kssl = new KSSL;
- return true;
- }
- }
-return false;
-}
-
-void TCPSlaveBase::cleanSSL()
-{
- delete d->cc;
-
- if (m_bIsSSL) {
- delete d->kssl;
- d->kssl = 0;
- }
- d->militantSSL = false;
-}
-
-bool TCPSlaveBase::atEnd()
-{
- return feof(fp);
-}
-
-int TCPSlaveBase::startTLS()
-{
- if (d->usingTLS || d->useSSLTunneling || m_bIsSSL || !KSSL::doesSSLWork())
- return false;
-
- d->kssl = new KSSL(false);
- if (!d->kssl->TLSInit()) {
- delete d->kssl;
- return -1;
- }
-
- if ( !d->realHost.isEmpty() )
- {
- kdDebug(7029) << "Setting real hostname: " << d->realHost << endl;
- d->kssl->setPeerHost(d->realHost);
- } else {
- kdDebug(7029) << "Setting real hostname: " << d->host << endl;
- d->kssl->setPeerHost(d->host);
- }
-
- if (hasMetaData("ssl_session_id")) {
- KSSLSession *s = KSSLSession::fromString(metaData("ssl_session_id"));
- if (s) {
- d->kssl->setSession(s);
- delete s;
- }
- }
- certificatePrompt();
-
- int rc = d->kssl->connect(m_iSock);
- if (rc < 0) {
- delete d->kssl;
- return -2;
- }
-
- setMetaData("ssl_session_id", d->kssl->session()->toString());
-
- d->usingTLS = true;
- setMetaData("ssl_in_use", "TRUE");
-
- if (!d->kssl->reusingSession()) {
- rc = verifyCertificate();
- if (rc != 1) {
- setMetaData("ssl_in_use", "FALSE");
- d->usingTLS = false;
- delete d->kssl;
- return -3;
- }
- }
-
- d->savedMetaData = mOutgoingMetaData;
- return (d->usingTLS ? 1 : 0);
-}
-
-
-void TCPSlaveBase::stopTLS()
-{
- if (d->usingTLS) {
- delete d->kssl;
- d->usingTLS = false;
- setMetaData("ssl_in_use", "FALSE");
- }
-}
-
-
-void TCPSlaveBase::setSSLMetaData() {
- if (!(d->usingTLS || d->useSSLTunneling || m_bIsSSL))
- return;
-
- mOutgoingMetaData = d->savedMetaData;
-}
-
-
-bool TCPSlaveBase::canUseTLS()
-{
- if (m_bIsSSL || d->needSSLHandShake || !KSSL::doesSSLWork())
- return false;
-
- KSSLSettings kss;
- return kss.tlsv1();
-}
-
-
-void TCPSlaveBase::certificatePrompt()
-{
-TQString certname; // the cert to use this session
-bool send = false, prompt = false, save = false, forcePrompt = false;
-KSSLCertificateHome::KSSLAuthAction aa;
-
- setMetaData("ssl_using_client_cert", "FALSE"); // we change this if needed
-
- if (metaData("ssl_no_client_cert") == "TRUE") return;
- forcePrompt = (metaData("ssl_force_cert_prompt") == "TRUE");
-
- // Delete the old cert since we're certainly done with it now
- if (d->pkcs) {
- delete d->pkcs;
- d->pkcs = NULL;
- }
-
- if (!d->kssl) return;
-
- // Look for a general certificate
- if (!forcePrompt) {
- certname = KSSLCertificateHome::getDefaultCertificateName(&aa);
- switch(aa) {
- case KSSLCertificateHome::AuthSend:
- send = true; prompt = false;
- break;
- case KSSLCertificateHome::AuthDont:
- send = false; prompt = false;
- certname = TQString::null;
- break;
- case KSSLCertificateHome::AuthPrompt:
- send = false; prompt = true;
- break;
- default:
- break;
- }
- }
-
- TQString ourHost;
- if (!d->realHost.isEmpty()) {
- ourHost = d->realHost;
- } else {
- ourHost = d->host;
- }
-
- // Look for a certificate on a per-host basis as an override
- TQString tmpcn = KSSLCertificateHome::getDefaultCertificateName(ourHost, &aa);
- if (aa != KSSLCertificateHome::AuthNone) { // we must override
- switch (aa) {
- case KSSLCertificateHome::AuthSend:
- send = true;
- prompt = false;
- certname = tmpcn;
- break;
- case KSSLCertificateHome::AuthDont:
- send = false;
- prompt = false;
- certname = TQString::null;
- break;
- case KSSLCertificateHome::AuthPrompt:
- send = false;
- prompt = true;
- certname = tmpcn;
- break;
- default:
- break;
- }
- }
-
- // Finally, we allow the application to override anything.
- if (hasMetaData("ssl_demand_certificate")) {
- certname = metaData("ssl_demand_certificate");
- if (!certname.isEmpty()) {
- forcePrompt = false;
- prompt = false;
- send = true;
- }
- }
-
- if (certname.isEmpty() && !prompt && !forcePrompt) return;
-
- // Ok, we're supposed to prompt the user....
- if (prompt || forcePrompt) {
- TQStringList certs = KSSLCertificateHome::getCertificateList();
-
- for (TQStringList::Iterator it = certs.begin(); it != certs.end(); ++it) {
- KSSLPKCS12 *pkcs = KSSLCertificateHome::getCertificateByName(*it);
- if (pkcs && (!pkcs->getCertificate() ||
- !pkcs->getCertificate()->x509V3Extensions().certTypeSSLClient())) {
- certs.remove(*it);
- }
- delete pkcs;
- }
-
- if (certs.isEmpty()) return; // we had nothing else, and prompt failed
-
- if (!d->dcc) {
- d->dcc = new DCOPClient;
- d->dcc->attach();
- if (!d->dcc->isApplicationRegistered("kio_uiserver")) {
- TDEApplication::startServiceByDesktopPath("kio_uiserver.desktop",
- TQStringList() );
- }
- }
-
- TQByteArray data, retval;
- TQCString rettype;
- TQDataStream arg(data, IO_WriteOnly);
- arg << ourHost;
- arg << certs;
- arg << metaData("window-id").toInt();
- bool rc = d->dcc->call("kio_uiserver", "UIServer",
- "showSSLCertDialog(TQString, TQStringList,int)",
- data, rettype, retval);
-
- if (rc && rettype == "KSSLCertDlgRet") {
- TQDataStream retStream(retval, IO_ReadOnly);
- KSSLCertDlgRet drc;
- retStream >> drc;
- if (drc.ok) {
- send = drc.send;
- save = drc.save;
- certname = drc.choice;
- }
- }
- }
-
- // The user may have said to not send the certificate,
- // but to save the choice
- if (!send) {
- if (save) {
- KSSLCertificateHome::setDefaultCertificate(certname, ourHost,
- false, false);
- }
- return;
- }
-
- // We're almost committed. If we can read the cert, we'll send it now.
- KSSLPKCS12 *pkcs = KSSLCertificateHome::getCertificateByName(certname);
- if (!pkcs && KSSLCertificateHome::hasCertificateByName(certname)) { // We need the password
- TDEIO::AuthInfo ai;
- bool first = true;
- do {
- ai.prompt = i18n("Enter the certificate password:");
- ai.caption = i18n("SSL Certificate Password");
- ai.url.setProtocol("kssl");
- ai.url.setHost(certname);
- ai.username = certname;
- ai.keepPassword = true;
-
- bool showprompt;
- if (first)
- showprompt = !checkCachedAuthentication(ai);
- else
- showprompt = true;
- if (showprompt) {
- if (!openPassDlg(ai, first ? TQString::null :
- i18n("Unable to open the certificate. Try a new password?")))
- break;
- }
-
- first = false;
- pkcs = KSSLCertificateHome::getCertificateByName(certname, ai.password);
- } while (!pkcs);
-
- }
-
- // If we could open the certificate, let's send it
- if (pkcs) {
- if (!d->kssl->setClientCertificate(pkcs)) {
- messageBox(Information, i18n("The procedure to set the "
- "client certificate for the session "
- "failed."), i18n("SSL"));
- delete pkcs; // we don't need this anymore
- pkcs = 0L;
- } else {
- kdDebug(7029) << "Client SSL certificate is being used." << endl;
- setMetaData("ssl_using_client_cert", "TRUE");
- if (save) {
- KSSLCertificateHome::setDefaultCertificate(certname, ourHost,
- true, false);
- }
- }
- d->pkcs = pkcs;
- }
-}
-
-
-
-bool TCPSlaveBase::usingTLS() const
-{
- return d->usingTLS;
-}
-
-// ### remove this for KDE4 (misses const):
-bool TCPSlaveBase::usingTLS()
-{
- return d->usingTLS;
-}
-
-
-// Returns 0 for failed verification, -1 for rejected cert and 1 for ok
-int TCPSlaveBase::verifyCertificate()
-{
- int rc = 0;
- bool permacache = false;
- bool isChild = false;
- bool _IPmatchesCN = false;
- int result;
- bool doAddHost = false;
- TQString ourHost;
-
- if (!d->realHost.isEmpty())
- ourHost = d->realHost;
- else ourHost = d->host;
-
- TQString theurl = TQString(m_sServiceName)+"://"+ourHost+":"+TQString::number(m_iPort);
-
- if (!hasMetaData("ssl_militant") || metaData("ssl_militant") == "FALSE")
- d->militantSSL = false;
- else if (metaData("ssl_militant") == "TRUE")
- d->militantSSL = true;
-
- if (!d->cc) d->cc = new KSSLCertificateCache;
-
- KSSLCertificate& pc = d->kssl->peerInfo().getPeerCertificate();
-
- KSSLCertificate::KSSLValidationList ksvl = pc.validateVerbose(KSSLCertificate::SSLServer);
-
- _IPmatchesCN = d->kssl->peerInfo().certMatchesAddress();
- if (!_IPmatchesCN) {
-#ifndef Q_WS_WIN //temporary
- KNetwork::KResolverResults res = KNetwork::KResolver::resolve(d->kssl->peerInfo().peerHost(), "80", KNetwork::KResolver::CanonName);
- if (!res.isEmpty()) {
- TQString old = d->kssl->peerInfo().peerHost();
- d->kssl->peerInfo().setPeerHost(res[0].canonicalName());
- _IPmatchesCN = d->kssl->peerInfo().certMatchesAddress();
- if (!_IPmatchesCN) {
- d->kssl->peerInfo().setPeerHost(old);
- }
- }
-#endif
- if (!_IPmatchesCN && !d->militantSSL) { // force this if the user wants it
- if (d->cc->getHostList(pc).contains(ourHost)) {
- _IPmatchesCN = true;
- }
- }
- }
-
- if (!_IPmatchesCN) {
- ksvl << KSSLCertificate::InvalidHost;
- }
-
- KSSLCertificate::KSSLValidation ksv = KSSLCertificate::Ok;
- if (!ksvl.isEmpty())
- ksv = ksvl.first();
-
- /* Setting the various bits of meta-info that will be needed. */
- setMetaData("ssl_cipher", d->kssl->connectionInfo().getCipher());
- setMetaData("ssl_cipher_desc",
- d->kssl->connectionInfo().getCipherDescription());
- setMetaData("ssl_cipher_version",
- d->kssl->connectionInfo().getCipherVersion());
- setMetaData("ssl_cipher_used_bits",
- TQString::number(d->kssl->connectionInfo().getCipherUsedBits()));
- setMetaData("ssl_cipher_bits",
- TQString::number(d->kssl->connectionInfo().getCipherBits()));
- setMetaData("ssl_peer_ip", d->ip);
- if (!d->realHost.isEmpty()) {
- setMetaData("ssl_proxied", "true");
- }
-
- TQString errorStr;
- for(KSSLCertificate::KSSLValidationList::ConstIterator it = ksvl.begin();
- it != ksvl.end(); ++it)
- {
- errorStr += TQString::number(*it)+":";
- }
- setMetaData("ssl_cert_errors", errorStr);
- setMetaData("ssl_peer_certificate", pc.toString());
-
- if (pc.chain().isValid() && pc.chain().depth() > 1) {
- TQString theChain;
- TQPtrList<KSSLCertificate> chain = pc.chain().getChain();
- chain.setAutoDelete(true);
- for (KSSLCertificate *c = chain.first(); c; c = chain.next()) {
- theChain += c->toString();
- theChain += "\n";
- }
- setMetaData("ssl_peer_chain", theChain);
- } else setMetaData("ssl_peer_chain", "");
-
- setMetaData("ssl_cert_state", TQString::number(ksv));
-
- if (ksv == KSSLCertificate::Ok) {
- rc = 1;
- setMetaData("ssl_action", "accept");
- }
-
- kdDebug(7029) << "SSL HTTP frame the parent? " << metaData("main_frame_request") << endl;
- if (!hasMetaData("main_frame_request") || metaData("main_frame_request") == "TRUE") {
- // Since we're the parent, we need to teach the child.
- setMetaData("ssl_parent_ip", d->ip);
- setMetaData("ssl_parent_cert", pc.toString());
- // - Read from cache and see if there is a policy for this
- KSSLCertificateCache::KSSLCertificatePolicy cp =
- d->cc->getPolicyByCertificate(pc);
-
- // - validation code
- if (ksv != KSSLCertificate::Ok) {
- if (d->militantSSL) {
- return -1;
- }
-
- if (cp == KSSLCertificateCache::Unknown ||
- cp == KSSLCertificateCache::Ambiguous) {
- cp = KSSLCertificateCache::Prompt;
- } else {
- // A policy was already set so let's honor that.
- permacache = d->cc->isPermanent(pc);
- }
-
- if (!_IPmatchesCN && cp == KSSLCertificateCache::Accept) {
- cp = KSSLCertificateCache::Prompt;
-// ksv = KSSLCertificate::Ok;
- }
-
- // Precondition: cp is one of Reject, Accept or Prompt
- switch (cp) {
- case KSSLCertificateCache::Accept:
- rc = 1;
- setMetaData("ssl_action", "accept");
- break;
- case KSSLCertificateCache::Reject:
- rc = -1;
- setMetaData("ssl_action", "reject");
- break;
- case KSSLCertificateCache::Prompt:
- {
- do {
- if (ksv == KSSLCertificate::InvalidHost) {
- TQString msg = i18n("The IP address of the host %1 "
- "does not match the one the "
- "certificate was issued to.");
- result = messageBox( WarningYesNoCancel,
- msg.arg(ourHost),
- i18n("Server Authentication"),
- i18n("&Details"),
- i18n("Co&ntinue") );
- } else {
- TQString msg = i18n("The server certificate failed the "
- "authenticity test (%1).");
- result = messageBox( WarningYesNoCancel,
- msg.arg(ourHost),
- i18n("Server Authentication"),
- i18n("&Details"),
- i18n("Co&ntinue") );
- }
-
- if (result == KMessageBox::Yes) {
- if (!d->dcc) {
- d->dcc = new DCOPClient;
- d->dcc->attach();
- if (!d->dcc->isApplicationRegistered("kio_uiserver")) {
- TDEApplication::startServiceByDesktopPath("kio_uiserver.desktop",
- TQStringList() );
- }
-
- }
- TQByteArray data, ignore;
- TQCString ignoretype;
- TQDataStream arg(data, IO_WriteOnly);
- arg << theurl << mOutgoingMetaData;
- arg << metaData("window-id").toInt();
- d->dcc->call("kio_uiserver", "UIServer",
- "showSSLInfoDialog(TQString,TDEIO::MetaData,int)",
- data, ignoretype, ignore);
- }
- } while (result == KMessageBox::Yes);
-
- if (result == KMessageBox::No) {
- setMetaData("ssl_action", "accept");
- rc = 1;
- cp = KSSLCertificateCache::Accept;
- doAddHost = true;
- result = messageBox( WarningYesNo,
- i18n("Would you like to accept this "
- "certificate forever without "
- "being prompted?"),
- i18n("Server Authentication"),
- i18n("&Forever"),
- i18n("&Current Sessions Only"));
- if (result == KMessageBox::Yes)
- permacache = true;
- else
- permacache = false;
- } else {
- setMetaData("ssl_action", "reject");
- rc = -1;
- cp = KSSLCertificateCache::Prompt;
- }
- break;
- }
- default:
- kdDebug(7029) << "TCPSlaveBase/SSL error in cert code."
- << "Please report this to kfm-devel@kde.org."
- << endl;
- break;
- }
- }
-
-
- // - cache the results
- d->cc->addCertificate(pc, cp, permacache);
- if (doAddHost) d->cc->addHost(pc, ourHost);
- } else { // Child frame
- // - Read from cache and see if there is a policy for this
- KSSLCertificateCache::KSSLCertificatePolicy cp =
- d->cc->getPolicyByCertificate(pc);
- isChild = true;
-
- // Check the cert and IP to make sure they're the same
- // as the parent frame
- bool certAndIPTheSame = (d->ip == metaData("ssl_parent_ip") &&
- pc.toString() == metaData("ssl_parent_cert"));
-
- if (ksv == KSSLCertificate::Ok) {
- if (certAndIPTheSame) { // success
- rc = 1;
- setMetaData("ssl_action", "accept");
- } else {
- /*
- if (d->militantSSL) {
- return -1;
- }
- result = messageBox(WarningYesNo,
- i18n("The certificate is valid but does not appear to have been assigned to this server. Do you wish to continue loading?"),
- i18n("Server Authentication"));
- if (result == KMessageBox::Yes) { // success
- rc = 1;
- setMetaData("ssl_action", "accept");
- } else { // fail
- rc = -1;
- setMetaData("ssl_action", "reject");
- }
- */
- setMetaData("ssl_action", "accept");
- rc = 1; // Let's accept this now. It's bad, but at least the user
- // will see potential attacks in KDE3 with the pseudo-lock
- // icon on the toolbar, and can investigate with the RMB
- }
- } else {
- if (d->militantSSL) {
- return -1;
- }
-
- if (cp == KSSLCertificateCache::Accept) {
- if (certAndIPTheSame) { // success
- rc = 1;
- setMetaData("ssl_action", "accept");
- } else { // fail
- result = messageBox(WarningYesNo,
- i18n("You have indicated that you wish to accept this certificate, but it is not issued to the server who is presenting it. Do you wish to continue loading?"),
- i18n("Server Authentication"));
- if (result == KMessageBox::Yes) {
- rc = 1;
- setMetaData("ssl_action", "accept");
- d->cc->addHost(pc, ourHost);
- } else {
- rc = -1;
- setMetaData("ssl_action", "reject");
- }
- }
- } else if (cp == KSSLCertificateCache::Reject) { // fail
- messageBox(Information, i18n("SSL certificate is being rejected as requested. You can disable this in the TDE Control Center."),
- i18n("Server Authentication"));
- rc = -1;
- setMetaData("ssl_action", "reject");
- } else {
- do {
- TQString msg = i18n("The server certificate failed the "
- "authenticity test (%1).");
- result = messageBox(WarningYesNoCancel,
- msg.arg(ourHost),
- i18n("Server Authentication"),
- i18n("&Details"),
- i18n("Co&nnect"));
- if (result == KMessageBox::Yes) {
- if (!d->dcc) {
- d->dcc = new DCOPClient;
- d->dcc->attach();
- if (!d->dcc->isApplicationRegistered("kio_uiserver")) {
- TDEApplication::startServiceByDesktopPath("kio_uiserver.desktop",
- TQStringList() );
- }
- }
- TQByteArray data, ignore;
- TQCString ignoretype;
- TQDataStream arg(data, IO_WriteOnly);
- arg << theurl << mOutgoingMetaData;
- arg << metaData("window-id").toInt();
- d->dcc->call("kio_uiserver", "UIServer",
- "showSSLInfoDialog(TQString,TDEIO::MetaData,int)",
- data, ignoretype, ignore);
- }
- } while (result == KMessageBox::Yes);
-
- if (result == KMessageBox::No) {
- setMetaData("ssl_action", "accept");
- rc = 1;
- cp = KSSLCertificateCache::Accept;
- result = messageBox(WarningYesNo,
- i18n("Would you like to accept this "
- "certificate forever without "
- "being prompted?"),
- i18n("Server Authentication"),
- i18n("&Forever"),
- i18n("&Current Sessions Only"));
- permacache = (result == KMessageBox::Yes);
- d->cc->addCertificate(pc, cp, permacache);
- d->cc->addHost(pc, ourHost);
- } else {
- setMetaData("ssl_action", "reject");
- rc = -1;
- cp = KSSLCertificateCache::Prompt;
- d->cc->addCertificate(pc, cp, permacache);
- }
- }
- }
- }
-
-
- if (rc == -1) {
- return rc;
- }
-
- if (metaData("ssl_activate_warnings") == "TRUE") {
- // - entering SSL
- if (!isChild && metaData("ssl_was_in_use") == "FALSE" &&
- d->kssl->settings()->warnOnEnter()) {
- int result;
- do {
- result = messageBox( i18n("You are about to "
- "enter secure mode. "
- "All transmissions "
- "will be encrypted "
- "unless otherwise "
- "noted.\nThis means "
- "that no third party "
- "will be able to "
- "easily observe your "
- "data in transit."),
- WarningYesNo,
- i18n("Security Information"),
- i18n("Display SSL "
- "&Information"),
- i18n("C&onnect"),
- "WarnOnEnterSSLMode" );
- // Move this setting into KSSL instead
- TDEConfig *config = new TDEConfig("kioslaverc");
- config->setGroup("Notification Messages");
-
- if (!config->readBoolEntry("WarnOnEnterSSLMode", true)) {
- config->deleteEntry("WarnOnEnterSSLMode");
- config->sync();
- d->kssl->settings()->setWarnOnEnter(false);
- d->kssl->settings()->save();
- }
- delete config;
-
- if ( result == KMessageBox::Yes )
- {
- if (!d->dcc) {
- d->dcc = new DCOPClient;
- d->dcc->attach();
- if (!d->dcc->isApplicationRegistered("kio_uiserver")) {
- TDEApplication::startServiceByDesktopPath("kio_uiserver.desktop",
- TQStringList() );
- }
- }
- TQByteArray data, ignore;
- TQCString ignoretype;
- TQDataStream arg(data, IO_WriteOnly);
- arg << theurl << mOutgoingMetaData;
- arg << metaData("window-id").toInt();
- d->dcc->call("kio_uiserver", "UIServer",
- "showSSLInfoDialog(TQString,TDEIO::MetaData,int)",
- data, ignoretype, ignore);
- }
- } while (result != KMessageBox::No);
- }
-
- } // if ssl_activate_warnings
-
-
- kdDebug(7029) << "SSL connection information follows:" << endl
- << "+-----------------------------------------------" << endl
- << "| Cipher: " << d->kssl->connectionInfo().getCipher() << endl
- << "| Description: " << d->kssl->connectionInfo().getCipherDescription() << endl
- << "| Version: " << d->kssl->connectionInfo().getCipherVersion() << endl
- << "| Strength: " << d->kssl->connectionInfo().getCipherUsedBits()
- << " of " << d->kssl->connectionInfo().getCipherBits()
- << " bits used." << endl
- << "| PEER:" << endl
- << "| Subject: " << d->kssl->peerInfo().getPeerCertificate().getSubject() << endl
- << "| Issuer: " << d->kssl->peerInfo().getPeerCertificate().getIssuer() << endl
- << "| Validation: " << (int)ksv << endl
- << "| Certificate matches IP: " << _IPmatchesCN << endl
- << "+-----------------------------------------------"
- << endl;
-
- // sendMetaData(); Do not call this function!!
- return rc;
-}
-
-
-bool TCPSlaveBase::isConnectionValid()
-{
- if ( m_iSock == -1 )
- return false;
-
- fd_set rdfs;
- FD_ZERO(&rdfs);
- FD_SET(m_iSock , &rdfs);
-
- struct timeval tv;
- tv.tv_usec = 0;
- tv.tv_sec = 0;
- int retval;
-#ifdef Q_OS_UNIX
- do {
- retval = KSocks::self()->select(m_iSock+1, &rdfs, NULL, NULL, &tv);
- if (wasKilled())
- return false; // Beam us out of here
- } while ((retval == -1) && (errno == EAGAIN));
-#else
- retval = -1;
-#endif
- // retval == -1 ==> Error
- // retval == 0 ==> Connection Idle
- // retval >= 1 ==> Connection Active
- //kdDebug(7029) << "TCPSlaveBase::isConnectionValid: select returned: "
- // << retval << endl;
-
- if (retval == -1)
- return false;
-
- if (retval == 0)
- return true;
-
- // Connection is active, check if it has closed.
- char buffer[100];
-#ifdef Q_OS_UNIX
- do {
- retval = KSocks::self()->recv(m_iSock, buffer, 80, MSG_PEEK);
-
- } while ((retval == -1) && (errno == EAGAIN));
-#else
- retval = -1;
-#endif
- //kdDebug(7029) << "TCPSlaveBase::isConnectionValid: recv returned: "
- // << retval << endl;
- if (retval <= 0)
- return false; // Error or connection closed.
-
- return true; // Connection still valid.
-}
-
-
-bool TCPSlaveBase::waitForResponse( int t )
-{
- fd_set rd;
- struct timeval timeout;
-
- if ( (m_bIsSSL || d->usingTLS) && !d->useSSLTunneling && d->kssl )
- if (d->kssl->pending() > 0)
- return true;
-
- FD_ZERO(&rd);
- FD_SET(m_iSock, &rd);
-
- timeout.tv_usec = 0;
- timeout.tv_sec = t;
- time_t startTime;
-
- int rc;
- int n = t;
-
-reSelect:
- startTime = time(NULL);
-#ifdef Q_OS_UNIX
- rc = KSocks::self()->select(m_iSock+1, &rd, NULL, NULL, &timeout);
-#else
- rc = -1;
-#endif
- if (wasKilled())
- return false; // We're dead.
-
- if (rc == -1)
- return false;
-
- if (FD_ISSET(m_iSock, &rd))
- return true;
-
- // Well it returned but it wasn't set. Let's see if it
- // returned too early (perhaps from an errant signal) and
- // start over with the remaining time
- int timeDone = time(NULL) - startTime;
- if (timeDone < n)
- {
- n -= timeDone;
- timeout.tv_sec = n;
- goto reSelect;
- }
-
- return false; // Timed out!
-}
-
-int TCPSlaveBase::connectResult()
-{
- return d->status;
-}
-
-void TCPSlaveBase::setBlockConnection( bool b )
-{
- d->block = b;
-}
-
-void TCPSlaveBase::setConnectTimeout( int t )
-{
- d->timeout = t;
-}
-
-bool TCPSlaveBase::isSSLTunnelEnabled()
-{
- return d->useSSLTunneling;
-}
-
-void TCPSlaveBase::setEnableSSLTunnel( bool enable )
-{
- d->useSSLTunneling = enable;
-}
-
-void TCPSlaveBase::setRealHost( const TQString& realHost )
-{
- d->realHost = realHost;
-}
-
-bool TCPSlaveBase::doSSLHandShake( bool sendError )
-{
- kdDebug(7029) << "TCPSlaveBase::doSSLHandShake: " << endl;
- TQString msgHost = d->host;
-
- d->kssl->reInitialize();
-
- if (hasMetaData("ssl_session_id")) {
- KSSLSession *s = KSSLSession::fromString(metaData("ssl_session_id"));
- if (s) {
- d->kssl->setSession(s);
- delete s;
- }
- }
- certificatePrompt();
-
- if ( !d->realHost.isEmpty() )
- {
- msgHost = d->realHost;
- }
-
- kdDebug(7029) << "Setting real hostname: " << msgHost << endl;
- d->kssl->setPeerHost(msgHost);
-
- d->status = d->kssl->connect(m_iSock);
- if (d->status < 0)
- {
- closeDescriptor();
- if ( sendError )
- error( ERR_COULD_NOT_CONNECT, msgHost);
- return false;
- }
-
- setMetaData("ssl_session_id", d->kssl->session()->toString());
- setMetaData("ssl_in_use", "TRUE");
-
- if (!d->kssl->reusingSession()) {
- int rc = verifyCertificate();
- if ( rc != 1 ) {
- d->status = -1;
- closeDescriptor();
- if ( sendError )
- error( ERR_COULD_NOT_CONNECT, msgHost);
- return false;
- }
- }
-
- d->needSSLHandShake = false;
-
- d->savedMetaData = mOutgoingMetaData;
- return true;
-}
-
-
-bool TCPSlaveBase::userAborted() const
-{
- return d->userAborted;
-}
-
-void TCPSlaveBase::virtual_hook( int id, void* data )
-{ SlaveBase::virtual_hook( id, data ); }
-
diff --git a/kio/kio/tcpslavebase.h b/kio/kio/tcpslavebase.h
deleted file mode 100644
index 52081c807..000000000
--- a/kio/kio/tcpslavebase.h
+++ /dev/null
@@ -1,389 +0,0 @@
-/*
- * Copyright (C) 2000 Alex Zepeda <zipzippy@sonic.net>
- * Copyright (C) 2001 George Staikos <staikos@kde.org>
- * Copyright (C) 2001 Dawit Alemayehu <adawit@kde.org>
- *
- * This file is part of the KDE project
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef _TCP_SLAVEBASE_H
-#define _TCP_SLAVEBASE_H
-
-#include <sys/types.h>
-#include <stdio.h>
-
-#include <kextsock.h>
-#include <kio/slavebase.h>
-
-
-namespace TDEIO {
-
-/**
- * There are two classes that specifies the protocol between application (job)
- * and kioslave. SlaveInterface is the class to use on the application end,
- * SlaveBase is the one to use on the slave end.
- *
- * Slave implementations should simply inherit SlaveBase
- *
- * A call to foo() results in a call to slotFoo() on the other end.
- */
-class TDEIO_EXPORT TCPSlaveBase : public SlaveBase
-{
-public:
- TCPSlaveBase(unsigned short int defaultPort, const TQCString &protocol,
- const TQCString &poolSocket, const TQCString &appSocket);
-
- TCPSlaveBase(unsigned short int defaultPort, const TQCString &protocol,
- const TQCString &poolSocket, const TQCString &appSocket,
- bool useSSL);
-
- virtual ~TCPSlaveBase();
-
-protected:
-
-#ifndef KDE_NO_COMPAT
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED ssize_t Write(const void *data, ssize_t len) { return write( data, len ); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED ssize_t Read(void *data, ssize_t len) { return read( data, len ); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED ssize_t ReadLine(char *data, ssize_t len) { return readLine( data, len ); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED unsigned short int GetPort(unsigned short int p) { return port(p); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED bool ConnectToHost( const TQString &host, unsigned int port,
- bool sendError ) { return connectToHost( host, port, sendError ); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED void CloseDescriptor() { closeDescriptor(); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED bool AtEOF() { return atEnd(); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED bool InitializeSSL() { return initializeSSL(); }
-
- /**
- * @deprecated Due to inconsistency with KDE naming convention.
- */
- KDE_DEPRECATED void CleanSSL() { cleanSSL(); }
-#endif
-
- /**
- * This function acts like standard write function call
- * except it is also capable of making SSL or SOCKS
- * connections.
- *
- * @param data info to be sent to remote machine
- * @param len the length of the data to be sent
- *
- * @return the actual size of the data that was sent
- */
- ssize_t write(const void *data, ssize_t len);
-
- /**
- * This function acts like standard read function call
- * except it is also capable of deciphering SSL data as
- * well as handling data over SOCKSified connections.
- *
- * @param data storage for the info read from server
- * @param len length of the info to read from the server
- *
- * @return the actual size of data that was obtained
- */
- ssize_t read(void *data, ssize_t len);
-
- /**
- * Same as above except it reads data one line at a time.
- */
- ssize_t readLine(char *data, ssize_t len);
-
- /**
- * Sets the maximum size of blocks read in during calls to readLine().
- * This allows a slave to optimize for the protocol which it implements.
- * Ideally this should be (common_line_length+1) or so.
- * Making this too large will have adverse effects on performance.
- * Initial/default value is 256(bytes)
- */
- void setBlockSize(int sz);
-
- /**
- * Determines the appropriate port to use.
- *
- * This functions attempts to discover the appropriate port.
- *
- * @param _port the port to try, if it works, it is returned
- * @return the default port if the given port doesn't work
- */
- unsigned short int port(unsigned short int _port);
-
- /**
- * Performs the initial TCP connection stuff and/or
- * SSL handshaking as necessary.
- *
- * Please note that unlike its deprecated counterpart, this
- * function allows you to disable any error message from being
- * sent back to the calling application! You can then use the
- * connectResult() function to determine the result of the
- * request for connection.
- *
- * @param host hostname
- * @param port port number to connect to
- * @param sendError if true sends error message to calling app.
- *
- * @return on succes, true is returned.
- * on failure, false is returned and an appropriate
- * error message is send to the application.
- */
- bool connectToHost( const TQString &host, unsigned int port,
- bool sendError = true );
-
- /**
- * Are we using SSL?
- *
- * @return if so, true is returned.
- * if not, true isn't returned.
- * @since 3.2
- */
- bool usingSSL() const { return m_bIsSSL; }
-
- /**
- * Are we using TLS?
- *
- * @return if so, true is returned.
- * if not, true isn't returned.
- * @since 3.2
- */
- bool usingTLS() const;
-
- /**
- * @obsolete kept for binary compatibility
- * Are we using TLS?
- *
- * @return if so, true is returned.
- * if not, true isn't returned.
- */
- bool usingTLS();
-
- /**
- * Can we use TLS?
- *
- * @return if so, true is returned.
- * if not, true isn't returned.
- */
- bool canUseTLS();
-
- /**
- * Start using TLS on the connection.
- *
- * @return on success, 1 is returned.
- * on failure, 0 is returned.
- * on TLS init failure, -1 is returned.
- * on connect failure, -2 is returned.
- * on certificate failure, -3 is returned.
- */
- int startTLS();
-
- /**
- * Stop using TLS on the connection.
- */
- void stopTLS();
-
- /**
- * Closes the current file descriptor.
- *
- * Call this function to properly close up the socket
- * since it also takes care to prroperly close the stdio
- * fstream stuff, as well as sets the socket back to -1
- */
- void closeDescriptor();
-
-
- /**
- * Returns true when end of data is reached
- */
- bool atEnd();
-
-
- /**
- * Call this if you use persistent connections and want all the
- * metadata restored. This is particularly important for SSL
- * sessions since the app needs to know the state of connection,
- * certificates, etc.
- */
- void setSSLMetaData();
-
-
- /**
- * Initializs all SSL variables
- */
- bool initializeSSL();
-
-
- /**
- * Cleans up all SSL settings.
- */
- void cleanSSL();
-
- /**
- * Determines whether or not we are still connected
- * to the remote machine.
- *
- * This method may fail to detect a closed SSL connection.
- *
- * return @p true if the socket is still active or
- * false otherwise.
- */
- bool isConnectionValid();
-
- /**
- * Returns the status of the connection.
- *
- * This function allows you to invoke ConnectToHost
- * with the @p sendError flag set to false so that you
- * can send the appropriate error message back to the
- * calling io-slave.
- *
- * @return the status code as returned by KExtendedSocket.
- */
- int connectResult();
-
- /**
- * Wait for some type of activity on the socket
- * for the period specified by @p t.
- *
- * @param t length of time in seconds that we should monitor the
- * socket before timing out.
- *
- * @return true if any activity was seen on the socket before the
- * timeout value was reached, false otherwise.
- */
- bool waitForResponse( int t );
-
- /**
- * Sets the mode of the connection to blocking or non-blocking.
- *
- * Be sure to call this function before calling connectToHost.
- * Otherwise, this setting will not have any effect until the next
- * @p connectToHost.
- *
- * @param b true to make the connection a blocking one, false otherwise.
- */
- void setBlockConnection( bool b );
-
- /**
- * Sets how long to wait for orignally connecting to
- * the requested before timinig out.
- *
- * Be sure to call this function before calling ConnectToHost,
- * otherwise the setting will not take effect until the next call
- * to @p ConnectToHost.
- *
- * @param t timeout value
- */
- void setConnectTimeout( int t );
-
- /**
- * Returns true if SSL tunneling is enabled.
- *
- * @see setEnableSSlTunnel
- */
- bool isSSLTunnelEnabled();
-
- /**
- * Set up SSL tunneling mode.
- *
- * Calling this function with a @p true argument will allow
- * you to temprarly ignore the @p m_bIsSSL flag setting and
- * make a non-SSL connection. It is mostly useful for making
- * connections to SSL sites through a non-transparent proxy
- * server (i.e. most proxy servers out there).
- *
- * Note that once you have successfully "tunneled" through the
- * proxy server you must call this function with its argument
- * set to false to properly connect to the SSL site.
- *
- * @param enable if true SSL Tunneling will be enabled
- */
- void setEnableSSLTunnel( bool enable );
-
- /**
- * Sets up the the real hostname for an SSL connection
- * that goes through a proxy server.
- *
- * This function is essential in making sure that the
- * real hostname is used for validating certificates from
- * SSL sites!
- *
- * @param realHost the actual host name we are connecting to
- */
- void setRealHost( const TQString& realHost );
-
- // don't use me!
- void doConstructorStuff();
-
- // For the certificate verification code
- int verifyCertificate();
-
- // For prompting for the certificate to use
- void certificatePrompt();
-
- // Did the user abort (as the reason for connectToHost returning false)
- bool userAborted() const;
-
-protected:
- int m_iSock;
- bool m_bIsSSL;
- unsigned short int m_iPort;
- unsigned short int m_iDefaultPort;
- TQCString m_sServiceName;
- FILE *fp;
-
-private:
- bool doSSLHandShake( bool sendError );
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class TcpSlaveBasePrivate;
- TcpSlaveBasePrivate *d;
-};
-
-}
-
-#endif
diff --git a/kio/kio/thumbcreator.h b/kio/kio/thumbcreator.h
deleted file mode 100644
index 79d499e7f..000000000
--- a/kio/kio/thumbcreator.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Malte Starostik <malte@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _THUMBCREATOR_H_
-#define _THUMBCREATOR_H_
-
-#include <tqstring.h>
-
-class TQString;
-class TQImage;
-/**
- * This is the baseclass for "thumbnail-plugins" in KDE. Using the class
- * TDEIO::PreviewJob allows you to generate small images (thumbnails)
- * for any kind of file, where a "ThumbCreator" is available. Have a look
- * at tdebase/kioslave/thumbnail/ for existing ThumbCreators.
- *
- * What you need to do to create and register a ThumbCreator:
- * @li Inherit from this class and reimplement the create() method to
- * generate a thumbnail for the given file-path.
- * @li Provide a factory method in your implementation file to instantiate
- * your plugin, e.g.:
- * \code
- * extern "C"
- * {
- * ThumbCreator *new_creator()
- * {
- * return new YourThumbCreator();
- * }
- * };
- * \endcode
- *
- * Compile your ThumbCreator as a module. The contents of Makefile.am
- * need to look like this:
- * \code
- * INCLUDES = $(all_includes)
- * kde_module_LTLIBRARIES = yourthumbcreator.la
- * yourthumbcreator_la_SOURCES = yourthumbcreator.cpp
- * yourthumbcreator_la_LIBADD = $(LIB_KIO)
- * yourthumbcreator_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
- * kde_services_DATA = yourthumbcreator.desktop
- * \endcode
- *
- * @li Create a file yourthumbcreator.desktop with the following contents:
- * \code
- * [Desktop Entry]
- * Encoding=UTF-8
- * Type=Service
- * Name=Name of the type of files your ThumbCreator supports
- * ServiceTypes=ThumbCreator
- * MimeTypes=application/x-somemimetype
- * CacheThumbnail=true
- * X-TDE-Library=yourthumbcreator
- * \endcode
- *
- * You can supply a comma-separated list of mimetypes to the MimeTypes entry,
- * naming all mimetypes your ThumbCreator supports. You can also use simple
- * wildcards, like (where you see [slash], put a /)
- * \code
- * text[slash]* or image[slash]*.
- * \endcode
- *
- * If your plugin is rather inexpensive (e.g. like the text preview ThumbCreator),
- * you can set CacheThumbnail=false to prevent your thumbnails from being cached
- * on disk.
- *
- * @short Baseclass for thumbnail-generating plugins.
- */
-class ThumbCreator
-{
-public:
- /**
- * The flags of this plugin.
- * @see flags()
- */
- enum Flags { None = 0, DrawFrame = 1, BlendIcon = 2 };
- virtual ~ThumbCreator() {}
-
- /**
- * Creates a thumbnail
- * Note that the width and height parameters should not be used
- * for scaling. Only plugins that create an image "from scratch",
- * like the TextCreator should directly use the specified size.
- * If the resulting preview is larger than width x height, it will be
- * scaled down.
- *
- * @param path the (always local) file path to create a preview for
- * @param width maximum width for the preview
- * @param height maximum height for the preview
- * @param img this image will contain the preview on success
- *
- * @return true if preview generation succeeded
- */
- virtual bool create(const TQString &path, int width, int height, TQImage &img) = 0;
-
- /**
- * The flags of this plugin:
- * @li None nothing special
- * @li DrawFrame a frame should be painted around the preview
- * @li BlendIcon the mimetype icon should be blended over the preview
- *
- * @return flags for this plugin
- */
- virtual Flags flags() const { return None; }
-};
-
-typedef ThumbCreator *(*newCreator)();
-
-#endif
diff --git a/kio/kioexec/CMakeLists.txt b/kio/kioexec/CMakeLists.txt
deleted file mode 100644
index 0ab606643..000000000
--- a/kio/kioexec/CMakeLists.txt
+++ /dev/null
@@ -1,42 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### kioexec ###################################
-
-set( target kioexec )
-
-set( ${target}_SRCS
- main.cpp
-)
-
-tde_add_executable( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${BIN_INSTALL_DIR}
-)
-
-tde_install_symlink( ${target} ${BIN_INSTALL_DIR}/kfmexec )
diff --git a/kio/kioexec/Makefile.am b/kio/kioexec/Makefile.am
deleted file mode 100644
index 5325ce875..000000000
--- a/kio/kioexec/Makefile.am
+++ /dev/null
@@ -1,19 +0,0 @@
-AM_CPPFLAGS = $(all_includes)
-
-bin_PROGRAMS = kioexec
-
-kioexec_SOURCES = main.cpp
-kioexec_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-kioexec_LDADD = $(LIB_KIO)
-
-noinst_HEADERS = main.h
-METASOURCES = AUTO
-
-messages:
- $(XGETTEXT) $(kioexec_SOURCES) -o $(podir)/kioexec.pot
-
-install-exec-local:
- @rm -f $(DESTDIR)$(bindir)/kfmexec
- @$(LN_S) kioexec $(DESTDIR)$(bindir)/kfmexec
-
-include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kio/kioexec/main.cpp b/kio/kioexec/main.cpp
deleted file mode 100644
index 40badcbe0..000000000
--- a/kio/kioexec/main.cpp
+++ /dev/null
@@ -1,294 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
- Copyright (C) 2000 David Faure <faure@kde.org>
- Copyright (C) 2001 Waldo Bastian <bastian@kde.org>
-
- 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; see the file COPYING. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <config.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-
-#include <tqfile.h>
-
-#include <kapplication.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <kmessagebox.h>
-#include <kio/job.h>
-#include <krun.h>
-#include <kio/netaccess.h>
-#include <kprocess.h>
-#include <kservice.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-#include <kaboutdata.h>
-#include <kstartupinfo.h>
-#include <kshell.h>
-#include <kde_file.h>
-
-
-#include "main.h"
-
-
-static const char description[] =
- I18N_NOOP("KIO Exec - Opens remote files, watches modifications, asks for upload");
-
-static KCmdLineOptions options[] =
-{
- { "tempfiles", I18N_NOOP("Treat URLs as local files and delete them afterwards"), 0 },
- { "suggestedfilename <file name>", I18N_NOOP("Suggested file name for the downloaded file"), 0 },
- { "+command", I18N_NOOP("Command to execute"), 0 },
- { "+[URLs]", I18N_NOOP("URL(s) or local file(s) used for 'command'"), 0 },
- KCmdLineLastOption
-};
-
-
-int jobCounter = 0;
-
-TQPtrList<TDEIO::Job>* jobList = 0L;
-
-KIOExec::KIOExec()
-{
- jobList = new TQPtrList<TDEIO::Job>;
- jobList->setAutoDelete( false ); // jobs autodelete themselves
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
- if (args->count() < 1)
- TDECmdLineArgs::usage(i18n("'command' expected.\n"));
-
- tempfiles = args->isSet("tempfiles");
- if ( args->isSet( "suggestedfilename" ) )
- suggestedFileName = TQString::fromLocal8Bit( args->getOption( "suggestedfilename" ) );
- expectedCounter = 0;
- command = args->arg(0);
- kdDebug() << "command=" << command << endl;
-
- for ( int i = 1; i < args->count(); i++ )
- {
- KURL url = args->url(i);
- // we need to map system:/ etc to make sure we get this right
- url = TDEIO::NetAccess::mostLocalURL( url, 0 );
-
- //kdDebug() << "url=" << url.url() << " filename=" << url.fileName() << endl;
- // A local file, not an URL ?
- // => It is not encoded and not shell escaped, too.
- if ( url.isLocalFile() )
- {
- fileInfo file;
- file.path = url.path();
- file.url = url;
- fileList.append(file);
- }
- // It is an URL
- else
- {
- if ( !url.isValid() )
- KMessageBox::error( 0L, i18n( "The URL %1\nis malformed" ).arg( url.url() ) );
- else if ( tempfiles )
- KMessageBox::error( 0L, i18n( "Remote URL %1\nnot allowed with --tempfiles switch" ).arg( url.url() ) );
- else
- // We must fetch the file
- {
- TQString fileName = TDEIO::encodeFileName( url.fileName() );
- if ( !suggestedFileName.isEmpty() )
- fileName = suggestedFileName;
- // Build the destination filename, in ~/.trinity/cache-*/krun/
- // Unlike KDE-1.1, we put the filename at the end so that the extension is kept
- // (Some programs rely on it)
- TQString tmp = TDEGlobal::dirs()->saveLocation( "cache", "krun/" ) +
- TQString("%1.%2.%3").arg(getpid()).arg(jobCounter++).arg(fileName);
- fileInfo file;
- file.path = tmp;
- file.url = url;
- fileList.append(file);
-
- expectedCounter++;
- KURL dest;
- dest.setPath( tmp );
- kdDebug() << "Copying " << url.prettyURL() << " to " << dest << endl;
- TDEIO::Job *job = TDEIO::file_copy( url, dest );
- jobList->append( job );
-
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), TQT_SLOT( slotResult( TDEIO::Job * ) ) );
- }
- }
- }
- args->clear();
-
- if ( tempfiles ) {
- // #113991
- TQTimer::singleShot( 0, this, TQT_SLOT( slotRunApp() ) );
- //slotRunApp(); // does not return
- return;
- }
-
- counter = 0;
- if ( counter == expectedCounter )
- slotResult( 0L );
-}
-
-void KIOExec::slotResult( TDEIO::Job * job )
-{
- if (job && job->error())
- {
- // That error dialog would be queued, i.e. not immediate...
- //job->showErrorDialog();
- if ( (job->error() != TDEIO::ERR_USER_CANCELED) )
- KMessageBox::error( 0L, job->errorString() );
-
- TQString path = static_cast<TDEIO::FileCopyJob*>(job)->destURL().path();
-
- TQValueList<fileInfo>::Iterator it = fileList.begin();
- for(;it != fileList.end(); ++it)
- {
- if ((*it).path == path)
- break;
- }
-
- if ( it != fileList.end() )
- fileList.remove( it );
- else
- kdDebug() << static_cast<TDEIO::FileCopyJob*>(job)->destURL().path() << " not found in list" << endl;
- }
-
- counter++;
-
- if ( counter < expectedCounter )
- return;
-
- kdDebug() << "All files downloaded, will call slotRunApp shortly" << endl;
- // We know we can run the app now - but let's finish the job properly first.
- TQTimer::singleShot( 0, this, TQT_SLOT( slotRunApp() ) );
-
- jobList->clear();
-}
-
-void KIOExec::slotRunApp()
-{
- if ( fileList.isEmpty() ) {
- kdDebug() << k_funcinfo << "No files downloaded -> exiting" << endl;
- exit(1);
- }
-
- KService service("dummy", command, TQString::null);
-
- KURL::List list;
- // Store modification times
- TQValueList<fileInfo>::Iterator it = fileList.begin();
- for ( ; it != fileList.end() ; ++it )
- {
- KDE_struct_stat buff;
- (*it).time = KDE_stat( TQFile::encodeName((*it).path), &buff ) ? 0 : buff.st_mtime;
- KURL url;
- url.setPath((*it).path);
- list << url;
- }
-
- TQStringList params = KRun::processDesktopExec(service, list, false /*no shell*/);
-
- kdDebug() << "EXEC " << KShell::joinArgs( params ) << endl;
-
-#ifdef Q_WS_X11
- // propagate the startup indentification to the started process
- KStartupInfoId id;
- id.initId( kapp->startupId());
- id.setupStartupEnv();
-#endif
-
- TDEProcess proc;
- proc << params;
- proc.start( TDEProcess::Block );
-
-#ifdef Q_WS_X11
- KStartupInfo::resetStartupEnv();
-#endif
-
- kdDebug() << "EXEC done" << endl;
-
- // Test whether one of the files changed
- it = fileList.begin();
- for( ;it != fileList.end(); ++it )
- {
- KDE_struct_stat buff;
- TQString src = (*it).path;
- KURL dest = (*it).url;
- if ( (KDE_stat( TQFile::encodeName(src), &buff ) == 0) &&
- ((*it).time != buff.st_mtime) )
- {
- if ( tempfiles )
- {
- if ( KMessageBox::questionYesNo( 0L,
- i18n( "The supposedly temporary file\n%1\nhas been modified.\nDo you still want to delete it?" ).arg(dest.prettyURL()),
- i18n( "File Changed" ), KStdGuiItem::del(), i18n("Do Not Delete") ) != KMessageBox::Yes )
- continue; // don't delete the temp file
- }
- else if ( ! dest.isLocalFile() ) // no upload when it's already a local file
- {
- if ( KMessageBox::questionYesNo( 0L,
- i18n( "The file\n%1\nhas been modified.\nDo you want to upload the changes?" ).arg(dest.prettyURL()),
- i18n( "File Changed" ), i18n("Upload"), i18n("Do Not Upload") ) == KMessageBox::Yes )
- {
- kdDebug() << TQString(TQString("src='%1' dest='%2'").arg(src).arg(dest.url())).ascii() << endl;
- // Do it the synchronous way.
- if ( !TDEIO::NetAccess::upload( src, dest, 0 ) )
- {
- KMessageBox::error( 0L, TDEIO::NetAccess::lastErrorString() );
- continue; // don't delete the temp file
- }
- }
- }
- }
-
- if ( !dest.isLocalFile() || tempfiles ) {
- // Wait for a reasonable time so that even if the application forks on startup (like OOo or amarok)
- // it will have time to start up and read the file before it gets deleted. #130709.
- kdDebug() << "sleeping..." << endl;
- sleep(180); // 3 mn
- kdDebug() << "about to delete " << src << endl;
- unlink( TQFile::encodeName(src) );
- }
- }
-
- //kapp->quit(); not efficient enough
- exit(0);
-}
-
-int main( int argc, char **argv )
-{
- TDEAboutData aboutData( "kioexec", I18N_NOOP("KIOExec"),
- VERSION, description, TDEAboutData::License_GPL,
- "(c) 1998-2000,2003 The KFM/Konqueror Developers");
- aboutData.addAuthor("David Faure",0, "faure@kde.org");
- aboutData.addAuthor("Stephan Kulow",0, "coolo@kde.org");
- aboutData.addAuthor("Bernhard Rosenkraenzer",0, "bero@arklinux.org");
- aboutData.addAuthor("Waldo Bastian",0, "bastian@kde.org");
- aboutData.addAuthor("Oswald Buddenhagen",0, "ossi@kde.org");
-
- TDECmdLineArgs::init( argc, argv, &aboutData );
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDEApplication app;
-
- KIOExec exec;
-
- kdDebug() << "Constructor returned..." << endl;
- return app.exec();
-}
-
-#include "main.moc"
diff --git a/kio/kioslave.upd b/kio/kioslave.upd
deleted file mode 100644
index f1ad015d3..000000000
--- a/kio/kioslave.upd
+++ /dev/null
@@ -1,18 +0,0 @@
-# Hello world
-Id=kde2.2/r1
-File=kioslaverc,kio_httprc
-Group=Cache Settings,
-Key=MaxCacheSize
-Key=MaxCacheAge
-Key=UseCache
-File=kioslaverc
-Group=Browser Settings/UserAgent,UserAgent
-AllKeys
-Id=kde2.2/r2
-File=kioslaverc,kio_httprc
-Group=UserAgent
-Script=useragent.pl,perl
-Id=kde2.2/r3
-File=kioslaverc
-Group=Proxy Settings
-Script=proxytype.pl,perl
diff --git a/kio/kpasswdserver/CMakeLists.txt b/kio/kpasswdserver/CMakeLists.txt
deleted file mode 100644
index 5209e53c9..000000000
--- a/kio/kpasswdserver/CMakeLists.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/tdewallet/client
- ${CMAKE_SOURCE_DIR}/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-#### kded_kpasswdserver ##############################
-
-set( target kded_kpasswdserver )
-
-set( ${target}_SRCS
- kpasswdserver.cpp kpasswdserver.skel
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK tdeinit_kded-shared
- DEPENDENCIES dcopidl
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kio/kpasswdserver/Makefile.am b/kio/kpasswdserver/Makefile.am
deleted file mode 100644
index 9ba393ef3..000000000
--- a/kio/kpasswdserver/Makefile.am
+++ /dev/null
@@ -1,15 +0,0 @@
-# $Id$
-# Makefile.am of tdebase/kioslave/http
-
-INCLUDES= -I$(top_srcdir)/tdewallet/client $(all_includes)
-
-####### Files
-
-kde_module_LTLIBRARIES = kded_kpasswdserver.la
-
-kded_kpasswdserver_la_SOURCES = kpasswdserver.cpp kpasswdserver.skel
-kded_kpasswdserver_la_METASOURCES = AUTO
-kded_kpasswdserver_la_LDFLAGS = $(all_libraries) -module -avoid-version
-kded_kpasswdserver_la_LIBADD = $(top_builddir)/tdewallet/client/libtdewalletclient.la $(LIB_KIO) $(LIB_KDED) $(LIB_QT) $(LIB_TDEUI) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la $(LIB_X11)
-
-include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kio/kpasswdserver/kpasswdserver.cpp b/kio/kpasswdserver/kpasswdserver.cpp
deleted file mode 100644
index b6a9aa696..000000000
--- a/kio/kpasswdserver/kpasswdserver.cpp
+++ /dev/null
@@ -1,715 +0,0 @@
-/*
- This file is part of the KDE Password Server
-
- Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
- Copyright (C) 2005 David Faure (faure@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- version 2 as published by the Free Software Foundation.
-
- This software 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 library; see the file COPYING. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-//----------------------------------------------------------------------------
-//
-// KDE Password Server
-// $Id$
-
-#include "kpasswdserver.h"
-
-#include <time.h>
-
-#include <tqtimer.h>
-
-#include <kapplication.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <kdebug.h>
-#include <kio/passdlg.h>
-#include <tdewallet.h>
-
-#include "config.h"
-#ifdef Q_WS_X11
-#include <X11/X.h>
-#include <X11/Xlib.h>
-#endif
-
-extern "C" {
- KDE_EXPORT KDEDModule *create_kpasswdserver(const TQCString &name)
- {
- return new KPasswdServer(name);
- }
-}
-
-int
-KPasswdServer::AuthInfoList::compareItems(TQPtrCollection::Item n1, TQPtrCollection::Item n2)
-{
- if (!n1 || !n2)
- return 0;
-
- AuthInfo *i1 = (AuthInfo *) n1;
- AuthInfo *i2 = (AuthInfo *) n2;
-
- int l1 = i1->directory.length();
- int l2 = i2->directory.length();
-
- if (l1 > l2)
- return -1;
- if (l1 < l2)
- return 1;
- return 0;
-}
-
-
-KPasswdServer::KPasswdServer(const TQCString &name)
- : KDEDModule(name)
-{
- m_authDict.setAutoDelete(true);
- m_authPending.setAutoDelete(true);
- m_seqNr = 0;
- m_wallet = 0;
- connect(this, TQT_SIGNAL(windowUnregistered(long)),
- this, TQT_SLOT(removeAuthForWindowId(long)));
-}
-
-KPasswdServer::~KPasswdServer()
-{
- delete m_wallet;
-}
-
-// Helper - returns the wallet key to use for read/store/checking for existence.
-static TQString makeWalletKey( const TQString& key, const TQString& realm )
-{
- return realm.isEmpty() ? key : key + '-' + realm;
-}
-
-// Helper for storeInWallet/readFromWallet
-static TQString makeMapKey( const char* key, int entryNumber )
-{
- TQString str = TQString::fromLatin1( key );
- if ( entryNumber > 1 )
- str += "-" + TQString::number( entryNumber );
- return str;
-}
-
-static bool storeInWallet( KWallet::Wallet* wallet, const TQString& key, const TDEIO::AuthInfo &info )
-{
- if ( !wallet->hasFolder( KWallet::Wallet::PasswordFolder() ) )
- if ( !wallet->createFolder( KWallet::Wallet::PasswordFolder() ) )
- return false;
- wallet->setFolder( KWallet::Wallet::PasswordFolder() );
- // Before saving, check if there's already an entry with this login.
- // If so, replace it (with the new password). Otherwise, add a new entry.
- typedef TQMap<TQString,TQString> Map;
- int entryNumber = 1;
- Map map;
- TQString walletKey = makeWalletKey( key, info.realmValue );
- kdDebug(130) << "storeInWallet: walletKey=" << walletKey << " reading existing map" << endl;
- if ( wallet->readMap( walletKey, map ) == 0 ) {
- Map::ConstIterator end = map.end();
- Map::ConstIterator it = map.find( "login" );
- while ( it != end ) {
- if ( it.data() == info.username ) {
- break; // OK, overwrite this entry
- }
- it = map.find( TQString( "login-" ) + TQString::number( ++entryNumber ) );
- }
- // If no entry was found, create a new entry - entryNumber is set already.
- }
- const TQString loginKey = makeMapKey( "login", entryNumber );
- const TQString passwordKey = makeMapKey( "password", entryNumber );
- kdDebug(130) << "storeInWallet: writing to " << loginKey << "," << passwordKey << endl;
- // note the overwrite=true by default
- map.insert( loginKey, info.username );
- map.insert( passwordKey, info.password );
- wallet->writeMap( walletKey, map );
- return true;
-}
-
-
-static bool readFromWallet( KWallet::Wallet* wallet, const TQString& key, const TQString& realm, TQString& username, TQString& password, bool userReadOnly, TQMap<TQString,TQString>& knownLogins )
-{
- //kdDebug(130) << "readFromWallet: key=" << key << " username=" << username << " password=" /*<< password*/ << " userReadOnly=" << userReadOnly << " realm=" << realm << endl;
- if ( wallet->hasFolder( KWallet::Wallet::PasswordFolder() ) )
- {
- wallet->setFolder( KWallet::Wallet::PasswordFolder() );
-
- TQMap<TQString,TQString> map;
- if ( wallet->readMap( makeWalletKey( key, realm ), map ) == 0 )
- {
- typedef TQMap<TQString,TQString> Map;
- int entryNumber = 1;
- Map::ConstIterator end = map.end();
- Map::ConstIterator it = map.find( "login" );
- while ( it != end ) {
- //kdDebug(130) << "readFromWallet: found " << it.key() << "=" << it.data() << endl;
- Map::ConstIterator pwdIter = map.find( makeMapKey( "password", entryNumber ) );
- if ( pwdIter != end ) {
- if ( it.data() == username )
- password = pwdIter.data();
- knownLogins.insert( it.data(), pwdIter.data() );
- }
-
- it = map.find( TQString( "login-" ) + TQString::number( ++entryNumber ) );
- }
- //kdDebug(130) << knownLogins.count() << " known logins" << endl;
-
- if ( !userReadOnly && !knownLogins.isEmpty() && username.isEmpty() ) {
- // Pick one, any one...
- username = knownLogins.begin().key();
- password = knownLogins.begin().data();
- //kdDebug(130) << "readFromWallet: picked the first one : " << username << endl;
- }
-
- return true;
- }
- }
- return false;
-}
-
-TDEIO::AuthInfo
-KPasswdServer::checkAuthInfo(TDEIO::AuthInfo info, long windowId)
-{
- return checkAuthInfo(info, windowId, 0);
-}
-
-TDEIO::AuthInfo
-KPasswdServer::checkAuthInfo(TDEIO::AuthInfo info, long windowId, unsigned long usertime)
-{
- kdDebug(130) << "KPasswdServer::checkAuthInfo: User= " << info.username
- << ", WindowId = " << windowId << endl;
- if( usertime != 0 )
- kapp->updateUserTimestamp( usertime );
-
- TQString key = createCacheKey(info);
-
- Request *request = m_authPending.first();
- TQString path2 = info.url.directory(false, false);
- for(; request; request = m_authPending.next())
- {
- if (request->key != key)
- continue;
-
- if (info.verifyPath)
- {
- TQString path1 = request->info.url.directory(false, false);
- if (!path2.startsWith(path1))
- continue;
- }
-
- request = new Request;
- request->client = callingDcopClient();
- request->transaction = request->client->beginTransaction();
- request->key = key;
- request->info = info;
- m_authWait.append(request);
- return info;
- }
-
- const AuthInfo *result = findAuthInfoItem(key, info);
- if (!result || result->isCanceled)
- {
- if (!result &&
- (info.username.isEmpty() || info.password.isEmpty()) &&
- !KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(),
- KWallet::Wallet::PasswordFolder(), makeWalletKey(key, info.realmValue)))
- {
- TQMap<TQString, TQString> knownLogins;
- if (openWallet(windowId)) {
- if (readFromWallet(m_wallet, key, info.realmValue, info.username, info.password,
- info.readOnly, knownLogins))
- {
- info.setModified(true);
- return info;
- }
- }
- }
-
- info.setModified(false);
- return info;
- }
-
- updateAuthExpire(key, result, windowId, false);
-
- return copyAuthInfo(result);
-}
-
-TDEIO::AuthInfo
-KPasswdServer::queryAuthInfo(TDEIO::AuthInfo info, TQString errorMsg, long windowId, long seqNr)
-{
- return queryAuthInfo(info, errorMsg, windowId, seqNr, 0 );
-}
-
-TDEIO::AuthInfo
-KPasswdServer::queryAuthInfo(TDEIO::AuthInfo info, TQString errorMsg, long windowId, long seqNr, unsigned long usertime)
-{
- kdDebug(130) << "KPasswdServer::queryAuthInfo: User= " << info.username
- << ", Message= " << info.prompt << ", WindowId = " << windowId << endl;
- if ( !info.password.isEmpty() ) // should we really allow the caller to pre-fill the password?
- kdDebug(130) << "password was set by caller" << endl;
- if( usertime != 0 )
- kapp->updateUserTimestamp( usertime );
-
- TQString key = createCacheKey(info);
- Request *request = new Request;
- request->client = callingDcopClient();
- request->transaction = request->client->beginTransaction();
- request->key = key;
- request->info = info;
- request->windowId = windowId;
- request->seqNr = seqNr;
- if (errorMsg == "<NoAuthPrompt>")
- {
- request->errorMsg = TQString::null;
- request->prompt = false;
- }
- else
- {
- request->errorMsg = errorMsg;
- request->prompt = true;
- }
- m_authPending.append(request);
-
- if (m_authPending.count() == 1)
- TQTimer::singleShot(0, this, TQT_SLOT(processRequest()));
-
- return info;
-}
-
-void
-KPasswdServer::addAuthInfo(TDEIO::AuthInfo info, long windowId)
-{
- kdDebug(130) << "KPasswdServer::addAuthInfo: User= " << info.username
- << ", RealmValue= " << info.realmValue << ", WindowId = " << windowId << endl;
- TQString key = createCacheKey(info);
-
- m_seqNr++;
-
- addAuthInfoItem(key, info, windowId, m_seqNr, false);
-}
-
-bool
-KPasswdServer::openWallet( WId windowId )
-{
- if ( m_wallet && !m_wallet->isOpen() ) { // forced closed
- delete m_wallet;
- m_wallet = 0;
- }
- if ( !m_wallet )
- m_wallet = KWallet::Wallet::openWallet(
- KWallet::Wallet::NetworkWallet(), windowId );
- return m_wallet != 0;
-}
-
-void
-KPasswdServer::processRequest()
-{
- Request *request = m_authPending.first();
- if (!request)
- return;
-
- TDEIO::AuthInfo &info = request->info;
-
- kdDebug(130) << "KPasswdServer::processRequest: User= " << info.username
- << ", Message= " << info.prompt << endl;
- const AuthInfo *result = findAuthInfoItem(request->key, request->info);
-
- if (result && (request->seqNr < result->seqNr))
- {
- kdDebug(130) << "KPasswdServer::processRequest: auto retry!" << endl;
- if (result->isCanceled)
- {
- info.setModified(false);
- }
- else
- {
- updateAuthExpire(request->key, result, request->windowId, false);
- info = copyAuthInfo(result);
- }
- }
- else
- {
- m_seqNr++;
- bool askPw = request->prompt;
- if (result && !info.username.isEmpty() &&
- !request->errorMsg.isEmpty())
- {
- TQString prompt = request->errorMsg;
- prompt += i18n(" Do you want to retry?");
- int dlgResult = KMessageBox::warningContinueCancelWId(request->windowId, prompt,
- i18n("Authentication"), i18n("Retry"));
- if (dlgResult != KMessageBox::Continue)
- askPw = false;
- }
-
- int dlgResult = TQDialog::Rejected;
- if (askPw)
- {
- TQString username = info.username;
- TQString password = info.password;
- bool hasWalletData = false;
- TQMap<TQString, TQString> knownLogins;
-
- if ( ( username.isEmpty() || password.isEmpty() )
- && !KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(), KWallet::Wallet::PasswordFolder(), makeWalletKey( request->key, info.realmValue )) )
- {
- // no login+pass provided, check if tdewallet has one
- if ( openWallet( request->windowId ) )
- hasWalletData = readFromWallet( m_wallet, request->key, info.realmValue, username, password, info.readOnly, knownLogins );
- }
-
- TDEIO::PasswordDialog dlg( info.prompt, username, info.keepPassword );
- if (info.caption.isEmpty())
- dlg.setPlainCaption( i18n("Authorization Dialog") );
- else
- dlg.setPlainCaption( info.caption );
-
- if ( !info.comment.isEmpty() )
- dlg.addCommentLine( info.commentLabel, info.comment );
-
- if ( !password.isEmpty() )
- dlg.setPassword( password );
-
- if (info.readOnly)
- dlg.setUserReadOnly( true );
- else
- dlg.setKnownLogins( knownLogins );
-
- if (hasWalletData)
- dlg.setKeepPassword( true );
-
-#ifdef Q_WS_X11
- XSetTransientForHint( tqt_xdisplay(), dlg.winId(), request->windowId);
-#endif
-
- dlgResult = dlg.exec();
-
- if (dlgResult == TQDialog::Accepted)
- {
- info.username = dlg.username();
- info.password = dlg.password();
- info.keepPassword = dlg.keepPassword();
-
- // When the user checks "keep password", that means:
- // * if the wallet is enabled, store it there for long-term, and in kpasswdserver
- // only for the duration of the window (#92928)
- // * otherwise store in kpasswdserver for the duration of the KDE session.
- if ( info.keepPassword ) {
- if ( openWallet( request->windowId ) ) {
- if ( storeInWallet( m_wallet, request->key, info ) )
- // password is in wallet, don't keep it in memory after window is closed
- info.keepPassword = false;
- }
- }
- }
- }
- if ( dlgResult != TQDialog::Accepted )
- {
- addAuthInfoItem(request->key, info, 0, m_seqNr, true);
- info.setModified( false );
- }
- else
- {
- addAuthInfoItem(request->key, info, request->windowId, m_seqNr, false);
- info.setModified( true );
- }
- }
-
- TQCString replyType;
- TQByteArray replyData;
-
- TQDataStream stream2(replyData, IO_WriteOnly);
- stream2 << info << m_seqNr;
- replyType = "TDEIO::AuthInfo";
- request->client->endTransaction( request->transaction,
- replyType, replyData);
-
- m_authPending.remove((unsigned int) 0);
-
- // Check all requests in the wait queue.
- for(Request *waitRequest = m_authWait.first();
- waitRequest; )
- {
- bool keepQueued = false;
- TQString key = waitRequest->key;
-
- request = m_authPending.first();
- TQString path2 = waitRequest->info.url.directory(false, false);
- for(; request; request = m_authPending.next())
- {
- if (request->key != key)
- continue;
-
- if (info.verifyPath)
- {
- TQString path1 = request->info.url.directory(false, false);
- if (!path2.startsWith(path1))
- continue;
- }
-
- keepQueued = true;
- break;
- }
- if (keepQueued)
- {
- waitRequest = m_authWait.next();
- }
- else
- {
- const AuthInfo *result = findAuthInfoItem(waitRequest->key, waitRequest->info);
-
- TQCString replyType;
- TQByteArray replyData;
-
- TQDataStream stream2(replyData, IO_WriteOnly);
-
- if (!result || result->isCanceled)
- {
- waitRequest->info.setModified(false);
- stream2 << waitRequest->info;
- }
- else
- {
- updateAuthExpire(waitRequest->key, result, waitRequest->windowId, false);
- TDEIO::AuthInfo info = copyAuthInfo(result);
- stream2 << info;
- }
-
- replyType = "TDEIO::AuthInfo";
- waitRequest->client->endTransaction( waitRequest->transaction,
- replyType, replyData);
-
- m_authWait.remove();
- waitRequest = m_authWait.current();
- }
- }
-
- if (m_authPending.count())
- TQTimer::singleShot(0, this, TQT_SLOT(processRequest()));
-
-}
-
-TQString KPasswdServer::createCacheKey( const TDEIO::AuthInfo &info )
-{
- if( !info.url.isValid() ) {
- // Note that a null key will break findAuthInfoItem later on...
- kdWarning(130) << "createCacheKey: invalid URL " << info.url << endl;
- return TQString::null;
- }
-
- // Generate the basic key sequence.
- TQString key = info.url.protocol();
- key += '-';
- if (!info.url.user().isEmpty())
- {
- key += info.url.user();
- key += "@";
- }
- key += info.url.host();
- int port = info.url.port();
- if( port )
- {
- key += ':';
- key += TQString::number(port);
- }
-
- return key;
-}
-
-TDEIO::AuthInfo
-KPasswdServer::copyAuthInfo(const AuthInfo *i)
-{
- TDEIO::AuthInfo result;
- result.url = i->url;
- result.username = i->username;
- result.password = i->password;
- result.realmValue = i->realmValue;
- result.digestInfo = i->digestInfo;
- result.setModified(true);
-
- return result;
-}
-
-const KPasswdServer::AuthInfo *
-KPasswdServer::findAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info)
-{
- AuthInfoList *authList = m_authDict.find(key);
- if (!authList)
- return 0;
-
- TQString path2 = info.url.directory(false, false);
- for(AuthInfo *current = authList->first();
- current; )
- {
- if ((current->expire == AuthInfo::expTime) &&
- (difftime(time(0), current->expireTime) > 0))
- {
- authList->remove();
- current = authList->current();
- continue;
- }
-
- if (info.verifyPath)
- {
- TQString path1 = current->directory;
- if (path2.startsWith(path1) &&
- (info.username.isEmpty() || info.username == current->username))
- return current;
- }
- else
- {
- if (current->realmValue == info.realmValue &&
- (info.username.isEmpty() || info.username == current->username))
- return current; // TODO: Update directory info,
- }
-
- current = authList->next();
- }
- return 0;
-}
-
-void
-KPasswdServer::removeAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info)
-{
- AuthInfoList *authList = m_authDict.find(key);
- if (!authList)
- return;
-
- for(AuthInfo *current = authList->first();
- current; )
- {
- if (current->realmValue == info.realmValue)
- {
- authList->remove();
- current = authList->current();
- }
- else
- {
- current = authList->next();
- }
- }
- if (authList->isEmpty())
- {
- m_authDict.remove(key);
- }
-}
-
-
-void
-KPasswdServer::addAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info, long windowId, long seqNr, bool canceled)
-{
- AuthInfoList *authList = m_authDict.find(key);
- if (!authList)
- {
- authList = new AuthInfoList;
- m_authDict.insert(key, authList);
- }
- AuthInfo *current = authList->first();
- for(; current; current = authList->next())
- {
- if (current->realmValue == info.realmValue)
- {
- authList->take();
- break;
- }
- }
-
- if (!current)
- {
- current = new AuthInfo;
- current->expire = AuthInfo::expTime;
- kdDebug(130) << "Creating AuthInfo" << endl;
- }
- else
- {
- kdDebug(130) << "Updating AuthInfo" << endl;
- }
-
- current->url = info.url;
- current->directory = info.url.directory(false, false);
- current->username = info.username;
- current->password = info.password;
- current->realmValue = info.realmValue;
- current->digestInfo = info.digestInfo;
- current->seqNr = seqNr;
- current->isCanceled = canceled;
-
- updateAuthExpire(key, current, windowId, info.keepPassword && !canceled);
-
- // Insert into list, keep the list sorted "longest path" first.
- authList->inSort(current);
-}
-
-void
-KPasswdServer::updateAuthExpire(const TQString &key, const AuthInfo *auth, long windowId, bool keep)
-{
- AuthInfo *current = const_cast<AuthInfo *>(auth);
- if (keep)
- {
- current->expire = AuthInfo::expNever;
- }
- else if (windowId && (current->expire != AuthInfo::expNever))
- {
- current->expire = AuthInfo::expWindowClose;
- if (!current->windowList.contains(windowId))
- current->windowList.append(windowId);
- }
- else if (current->expire == AuthInfo::expTime)
- {
- current->expireTime = time(0)+10;
- }
-
- // Update mWindowIdList
- if (windowId)
- {
- TQStringList *keysChanged = mWindowIdList.find(windowId);
- if (!keysChanged)
- {
- keysChanged = new TQStringList;
- mWindowIdList.insert(windowId, keysChanged);
- }
- if (!keysChanged->contains(key))
- keysChanged->append(key);
- }
-}
-
-void
-KPasswdServer::removeAuthForWindowId(long windowId)
-{
- TQStringList *keysChanged = mWindowIdList.find(windowId);
- if (!keysChanged) return;
-
- for(TQStringList::ConstIterator it = keysChanged->begin();
- it != keysChanged->end(); ++it)
- {
- TQString key = *it;
- AuthInfoList *authList = m_authDict.find(key);
- if (!authList)
- continue;
-
- AuthInfo *current = authList->first();
- for(; current; )
- {
- if (current->expire == AuthInfo::expWindowClose)
- {
- if (current->windowList.remove(windowId) && current->windowList.isEmpty())
- {
- authList->remove();
- current = authList->current();
- continue;
- }
- }
- current = authList->next();
- }
- }
-}
-
-#include "kpasswdserver.moc"
diff --git a/kio/kpasswdserver/kpasswdserver.h b/kio/kpasswdserver/kpasswdserver.h
deleted file mode 100644
index 46e7191db..000000000
--- a/kio/kpasswdserver/kpasswdserver.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- This file is part of the KDE Password Server
-
- Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- version 2 as published by the Free Software Foundation.
-
- This software 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 library; see the file COPYING. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-//----------------------------------------------------------------------------
-//
-// KDE Password Server
-// $Id$
-
-#ifndef KPASSWDSERVER_H
-#define KPASSWDSERVER_H
-
-#include <tqdict.h>
-#include <tqintdict.h>
-
-#include <dcopclient.h>
-#include <kio/authinfo.h>
-#include <kded/kdedmodule.h>
-
-namespace KWallet {
- class Wallet;
-}
-
-class KPasswdServer : public KDEDModule
-{
- Q_OBJECT
- K_DCOP
-public:
- KPasswdServer(const TQCString &);
- ~KPasswdServer();
-
-k_dcop:
- // KDE4 merge
- TDEIO::AuthInfo checkAuthInfo(TDEIO::AuthInfo, long, unsigned long);
- TDEIO::AuthInfo checkAuthInfo(TDEIO::AuthInfo, long);
- TDEIO::AuthInfo queryAuthInfo(TDEIO::AuthInfo, TQString, long, long, unsigned long);
- TDEIO::AuthInfo queryAuthInfo(TDEIO::AuthInfo, TQString, long, long);
- void addAuthInfo(TDEIO::AuthInfo, long);
-
-public slots:
- void processRequest();
- // Remove all authentication info associated with windowId
- void removeAuthForWindowId(long windowId);
-
-protected:
- struct AuthInfo;
-
- TQString createCacheKey( const TDEIO::AuthInfo &info );
- const AuthInfo *findAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info);
- void removeAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info);
- void addAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info, long windowId, long seqNr, bool canceled);
- TDEIO::AuthInfo copyAuthInfo(const AuthInfo *);
- void updateAuthExpire(const TQString &key, const AuthInfo *, long windowId, bool keep);
- int findWalletEntry( const TQMap<TQString,TQString>& map, const TQString& username );
- bool openWallet( WId windowId );
-
- struct AuthInfo {
- AuthInfo() { expire = expNever; isCanceled = false; seqNr = 0; }
-
- KURL url;
- TQString directory;
- TQString username;
- TQString password;
- TQString realmValue;
- TQString digestInfo;
-
- enum { expNever, expWindowClose, expTime } expire;
- TQValueList<long> windowList;
- unsigned long expireTime;
- long seqNr;
-
- bool isCanceled;
- };
-
- class AuthInfoList : public TQPtrList<AuthInfo>
- {
- public:
- AuthInfoList() { setAutoDelete(true); }
- int compareItems(TQPtrCollection::Item n1, TQPtrCollection::Item n2);
- };
-
- TQDict< AuthInfoList > m_authDict;
-
- struct Request {
- DCOPClient *client;
- DCOPClientTransaction *transaction;
- TQString key;
- TDEIO::AuthInfo info;
- TQString errorMsg;
- long windowId;
- long seqNr;
- bool prompt;
- };
-
- TQPtrList< Request > m_authPending;
- TQPtrList< Request > m_authWait;
- TQIntDict<TQStringList> mWindowIdList;
- DCOPClient *m_dcopClient;
- KWallet::Wallet* m_wallet;
- long m_seqNr;
-};
-
-#endif
diff --git a/kio/kssl/configure.in.in b/kio/kssl/configure.in.in
deleted file mode 100644
index fa256cbdb..000000000
--- a/kio/kssl/configure.in.in
+++ /dev/null
@@ -1,7 +0,0 @@
-KDE_CHECK_SSL
-
-if test "$have_ssl" = yes; then
- AC_DEFINE(KSSL_HAVE_SSL, 1, [Define if we shall use KSSL])
-fi
-
-AM_CONFIG_HEADER([kio/kssl/ksslconfig.h])
diff --git a/kio/kssl/kopenssl.cc b/kio/kssl/kopenssl.cc
deleted file mode 100644
index 9983edceb..000000000
--- a/kio/kssl/kopenssl.cc
+++ /dev/null
@@ -1,1601 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2001-2003 George Staikos <staikos@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#ifdef KSSL_HAVE_SSL
-#include <openssl/opensslv.h>
-#endif
-
-#include <kdebug.h>
-#include <kconfig.h>
-#include <kstaticdeleter.h>
-#include <tqregexp.h>
-#include <tqdir.h>
-
-#include <stdio.h>
-#include <unistd.h>
-#include "kopenssl.h"
-
-extern "C" {
-#ifdef KSSL_HAVE_SSL
-static int (*K_SSL_connect) (SSL *) = 0L;
-static int (*K_SSL_accept) (SSL *) = 0L;
-static int (*K_SSL_read) (SSL *, void *, int) = 0L;
-static int (*K_SSL_write) (SSL *, const void *, int) = 0L;
-static SSL *(*K_SSL_new) (SSL_CTX *) = 0L;
-static void (*K_SSL_free) (SSL *) = 0L;
-static int (*K_SSL_shutdown) (SSL *) = 0L;
-static SSL_CTX *(*K_SSL_CTX_new)(SSL_METHOD *) = 0L;
-static void (*K_SSL_CTX_free) (SSL_CTX *) = 0L;
-static int (*K_SSL_set_fd) (SSL *, int) = 0L;
-static int (*K_SSL_pending) (SSL *) = 0L;
-static int (*K_SSL_peek) (SSL *, void *, int) = 0L;
-static int (*K_SSL_CTX_set_cipher_list)(SSL_CTX *, const char *) = 0L;
-static void (*K_SSL_CTX_set_verify)(SSL_CTX *, int,
- int (*)(int, X509_STORE_CTX *)) = 0L;
-static int (*K_SSL_use_certificate)(SSL *, X509 *) = 0L;
-static SSL_CIPHER *(*K_SSL_get_current_cipher)(SSL *) = 0L;
-static long (*K_SSL_ctrl) (SSL *,int, long, char *) = 0L;
-static int (*K_RAND_egd) (const char *) = 0L;
-static const char* (*K_RAND_file_name) (char *, size_t) = 0L;
-static int (*K_RAND_load_file) (const char *, long) = 0L;
-static int (*K_RAND_write_file) (const char *) = 0L;
-static SSL_METHOD * (*K_TLSv1_client_method) () = 0L;
-static SSL_METHOD * (*K_SSLv2_client_method) () = 0L;
-static SSL_METHOD * (*K_SSLv3_client_method) () = 0L;
-static SSL_METHOD * (*K_SSLv23_client_method) () = 0L;
-static X509 * (*K_SSL_get_peer_certificate) (SSL *) = 0L;
-static int (*K_SSL_CIPHER_get_bits) (SSL_CIPHER *,int *) = 0L;
-static char * (*K_SSL_CIPHER_get_version) (SSL_CIPHER *) = 0L;
-static const char * (*K_SSL_CIPHER_get_name) (SSL_CIPHER *) = 0L;
-static char * (*K_SSL_CIPHER_description) (SSL_CIPHER *, char *, int) = 0L;
-static X509 * (*K_d2i_X509) (X509 **,unsigned char **,long) = 0L;
-static int (*K_i2d_X509) (X509 *,unsigned char **) = 0L;
-static int (*K_X509_cmp) (X509 *, X509 *) = 0L;
-static void (*K_X509_STORE_CTX_free) (X509_STORE_CTX *) = 0L;
-static int (*K_X509_verify_cert) (X509_STORE_CTX *) = 0L;
-static X509_STORE_CTX *(*K_X509_STORE_CTX_new) (void) = 0L;
-static void (*K_X509_STORE_free) (X509_STORE *) = 0L;
-static X509_STORE *(*K_X509_STORE_new) (void) = 0L;
-static void (*K_X509_free) (X509 *) = 0L;
-static char *(*K_X509_NAME_oneline) (X509_NAME *,char *,int) = 0L;
-static X509_NAME *(*K_X509_get_subject_name) (X509 *) = 0L;
-static X509_NAME *(*K_X509_get_issuer_name) (X509 *) = 0L;
-static X509_LOOKUP *(*K_X509_STORE_add_lookup) (X509_STORE *, X509_LOOKUP_METHOD *) = 0L;
-static X509_LOOKUP_METHOD *(*K_X509_LOOKUP_file)(void) = 0L;
-static void (*K_X509_LOOKUP_free)(X509_LOOKUP *) = 0L;
-static int (*K_X509_LOOKUP_ctrl)(X509_LOOKUP *, int, const char *, long, char **) = 0L;
-static void (*K_X509_STORE_CTX_init)(X509_STORE_CTX *, X509_STORE *, X509 *, STACK_OF(X509) *) = 0L;
-static void (*K_CRYPTO_free) (void *) = 0L;
-static X509* (*K_X509_dup) (X509 *) = 0L;
-static BIO_METHOD *(*K_BIO_s_mem) (void) = 0L;
-static BIO* (*K_BIO_new) (BIO_METHOD *) = 0L;
-static BIO* (*K_BIO_new_fp) (FILE *, int) = 0L;
-static BIO* (*K_BIO_new_mem_buf) (void *, int) = 0L;
-static int (*K_BIO_free) (BIO *) = 0L;
-static long (*K_BIO_ctrl) (BIO *,int,long,void *) = 0L;
-static int (*K_BIO_write) (BIO *b, const void *data, int len) = 0L;
-static int (*K_PEM_ASN1_write_bio) (int (*)(),const char *,BIO *,char *,
- const EVP_CIPHER *,unsigned char *,int ,
- pem_password_cb *, void *) = 0L;
-#if OPENSSL_VERSION_NUMBER >= 0x10000000L
-static int (*K_ASN1_item_i2d_fp)(ASN1_ITEM *,FILE *,unsigned char *) = 0L;
-static ASN1_ITEM *K_NETSCAPE_X509_it = 0L;
-#else
-static ASN1_METHOD* (*K_X509_asn1_meth) (void) = 0L;
-static int (*K_ASN1_i2d_fp)(int (*)(),FILE *,unsigned char *) = 0L;
-static int (*K_i2d_ASN1_HEADER)(ASN1_HEADER *, unsigned char **) = 0L;
-#endif
-static int (*K_X509_print_fp) (FILE *, X509*) = 0L;
-static int (*K_i2d_PKCS12) (PKCS12*, unsigned char**) = 0L;
-static int (*K_i2d_PKCS12_fp) (FILE *, PKCS12*) = 0L;
-static int (*K_PKCS12_newpass) (PKCS12*, char*, char*) = 0L;
-static PKCS12* (*K_d2i_PKCS12_fp) (FILE*, PKCS12**) = 0L;
-static PKCS12* (*K_PKCS12_new) (void) = 0L;
-static void (*K_PKCS12_free) (PKCS12 *) = 0L;
-static int (*K_PKCS12_parse) (PKCS12*, const char *, EVP_PKEY**,
- X509**, STACK_OF(X509)**) = 0L;
-static void (*K_EVP_PKEY_free) (EVP_PKEY *) = 0L;
-static EVP_PKEY* (*K_EVP_PKEY_new) () = 0L;
-static void (*K_X509_REQ_free) (X509_REQ *) = 0L;
-static X509_REQ* (*K_X509_REQ_new) () = 0L;
-static int (*K_SSL_CTX_use_PrivateKey) (SSL_CTX*, EVP_PKEY*) = 0L;
-static int (*K_SSL_CTX_use_certificate) (SSL_CTX*, X509*) = 0L;
-static int (*K_SSL_get_error) (SSL*, int) = 0L;
-static STACK_OF(X509)* (*K_SSL_get_peer_cert_chain) (SSL*) = 0L;
-static void (*K_X509_STORE_CTX_set_chain) (X509_STORE_CTX *, STACK_OF(X509)*) = 0L;
-static void (*K_X509_STORE_CTX_set_purpose) (X509_STORE_CTX *, int) = 0L;
-static void (*K_sk_free) (STACK*) = 0L;
-static int (*K_sk_num) (STACK*) = 0L;
-static char* (*K_sk_pop) (STACK*) = 0L;
-static char* (*K_sk_value) (STACK*, int) = 0L;
-static STACK* (*K_sk_new) (int (*)()) = 0L;
-static int (*K_sk_push) (STACK*, char*) = 0L;
-static STACK* (*K_sk_dup) (STACK *) = 0L;
-static char * (*K_i2s_ASN1_INTEGER) (X509V3_EXT_METHOD *, ASN1_INTEGER *) =0L;
-static ASN1_INTEGER * (*K_X509_get_serialNumber) (X509 *) = 0L;
-static EVP_PKEY *(*K_X509_get_pubkey)(X509 *) = 0L;
-static int (*K_i2d_PublicKey)(EVP_PKEY *, unsigned char **) = 0L;
-static int (*K_X509_check_private_key)(X509 *, EVP_PKEY *) = 0L;
-static char * (*K_BN_bn2hex)(const BIGNUM *) = 0L;
-static int (*K_X509_digest)(const X509 *,const EVP_MD *, unsigned char *, unsigned int *) = 0L;
-static EVP_MD* (*K_EVP_md5)() = 0L;
-static void (*K_ASN1_INTEGER_free)(ASN1_INTEGER *) = 0L;
-static int (*K_OBJ_obj2nid)(ASN1_OBJECT *) = 0L;
-static const char * (*K_OBJ_nid2ln)(int) = 0L;
-static int (*K_X509_get_ext_count)(X509*) = 0L;
-static int (*K_X509_get_ext_by_NID)(X509*, int, int) = 0L;
-static int (*K_X509_get_ext_by_OBJ)(X509*,ASN1_OBJECT*,int) = 0L;
-static X509_EXTENSION *(*K_X509_get_ext)(X509*, int loc) = 0L;
-static X509_EXTENSION *(*K_X509_delete_ext)(X509*, int) = 0L;
-static int (*K_X509_add_ext)(X509*, X509_EXTENSION*, int) = 0L;
-static void *(*K_X509_get_ext_d2i)(X509*, int, int*, int*) = 0L;
-static char *(*K_i2s_ASN1_OCTET_STRING)(X509V3_EXT_METHOD*, ASN1_OCTET_STRING*) = 0L;
-static int (*K_ASN1_BIT_STRING_get_bit)(ASN1_BIT_STRING*, int) = 0L;
-static PKCS7 *(*K_PKCS7_new)() = 0L;
-static void (*K_PKCS7_free)(PKCS7*) = 0L;
-static void (*K_PKCS7_content_free)(PKCS7*) = 0L;
-static int (*K_i2d_PKCS7)(PKCS7*, unsigned char**) = 0L;
-static PKCS7 *(*K_d2i_PKCS7)(PKCS7**, unsigned char**,long) = 0L;
-static int (*K_i2d_PKCS7_fp)(FILE*,PKCS7*) = 0L;
-static PKCS7* (*K_d2i_PKCS7_fp)(FILE*,PKCS7**) = 0L;
-static int (*K_i2d_PKCS7_bio)(BIO *bp,PKCS7 *p7) = 0L;
-static PKCS7 *(*K_d2i_PKCS7_bio)(BIO *bp,PKCS7 **p7) = 0L;
-static PKCS7* (*K_PKCS7_dup)(PKCS7*) = 0L;
-static STACK_OF(X509_NAME) *(*K_SSL_load_client_CA_file)(const char*) = 0L;
-static STACK_OF(X509_INFO) *(*K_PEM_X509_INFO_read)(FILE*, STACK_OF(X509_INFO)*, pem_password_cb*, void*) = 0L;
-static char *(*K_ASN1_d2i_fp)(char *(*)(),char *(*)(),FILE*,unsigned char**) = 0L;
-static X509 *(*K_X509_new)() = 0L;
-static int (*K_X509_PURPOSE_get_count)() = 0L;
-static int (*K_X509_PURPOSE_get_id)(X509_PURPOSE *) = 0L;
-static int (*K_X509_check_purpose)(X509*,int,int) = 0L;
-static X509_PURPOSE* (*K_X509_PURPOSE_get0)(int) = 0L;
-static int (*K_EVP_PKEY_assign)(EVP_PKEY*, int, char*) = 0L;
-static int (*K_X509_REQ_set_pubkey)(X509_REQ*, EVP_PKEY*) = 0L;
-static RSA *(*K_RSA_generate_key)(int, unsigned long, void (*)(int,int,void *), void *) = 0L;
-static int (*K_i2d_X509_REQ_fp)(FILE*, X509_REQ*) = 0L;
-static void (*K_ERR_clear_error)() = 0L;
-static unsigned long (*K_ERR_get_error)() = 0L;
-static void (*K_ERR_print_errors_fp)(FILE*) = 0L;
-static PKCS7 *(*K_PKCS7_sign)(X509*, EVP_PKEY*, STACK_OF(X509)*, BIO*, int) = 0L;
-static int (*K_PKCS7_verify)(PKCS7*,STACK_OF(X509)*,X509_STORE*,BIO*,BIO*,int) = 0L;
-static STACK_OF(X509) *(*K_PKCS7_get0_signers)(PKCS7 *, STACK_OF(X509) *, int) = 0L;
-static PKCS7 *(*K_PKCS7_encrypt)(STACK_OF(X509) *, BIO *, EVP_CIPHER *, int) = 0L;
-static int (*K_PKCS7_decrypt)(PKCS7 *, EVP_PKEY *, X509 *, BIO *, int) = 0L;
-static SSL_SESSION* (*K_SSL_get1_session)(SSL*) = 0L;
-static void (*K_SSL_SESSION_free)(SSL_SESSION*) = 0L;
-static int (*K_SSL_set_session)(SSL*,SSL_SESSION*) = 0L;
-static SSL_SESSION* (*K_d2i_SSL_SESSION)(SSL_SESSION**,unsigned char**, long) = 0L;
-static int (*K_i2d_SSL_SESSION)(SSL_SESSION*,unsigned char**) = 0L;
-static STACK *(*K_X509_get1_email)(X509 *x) = 0L;
-static void (*K_X509_email_free)(STACK *sk) = 0L;
-static EVP_CIPHER *(*K_EVP_des_ede3_cbc)() = 0L;
-static EVP_CIPHER *(*K_EVP_des_cbc)() = 0L;
-static EVP_CIPHER *(*K_EVP_rc2_cbc)() = 0L;
-static EVP_CIPHER *(*K_EVP_rc2_64_cbc)() = 0L;
-static EVP_CIPHER *(*K_EVP_rc2_40_cbc)() = 0L;
-static int (*K_i2d_PrivateKey_fp)(FILE*,EVP_PKEY*) = 0L;
-static int (*K_i2d_PKCS8PrivateKey_fp)(FILE*, EVP_PKEY*, const EVP_CIPHER*, char*, int, pem_password_cb*, void*) = 0L;
-static void (*K_RSA_free)(RSA*) = 0L;
-static EVP_CIPHER *(*K_EVP_bf_cbc)() = 0L;
-static int (*K_X509_REQ_sign)(X509_REQ*, EVP_PKEY*, const EVP_MD*) = 0L;
-static int (*K_X509_NAME_add_entry_by_txt)(X509_NAME*, char*, int, unsigned char*, int, int, int) = 0L;
-static X509_NAME *(*K_X509_NAME_new)() = 0L;
-static int (*K_X509_REQ_set_subject_name)(X509_REQ*,X509_NAME*) = 0L;
-static unsigned char *(*K_ASN1_STRING_data)(ASN1_STRING*) = 0L;
-static int (*K_ASN1_STRING_length)(ASN1_STRING*) = 0L;
-static STACK_OF(SSL_CIPHER) *(*K_SSL_get_ciphers)(const SSL *ssl) = 0L;
-
-#endif
-}
-
-
-bool KOpenSSLProxy::hasLibSSL() const {
- return _sslLib != 0L;
-}
-
-
-bool KOpenSSLProxy::hasLibCrypto() const {
- return _cryptoLib != 0L;
-}
-
-
-void KOpenSSLProxy::destroy() {
- delete this;
- _me = 0L;
-}
-
-#ifdef __OpenBSD__
-#include <tqdir.h>
-#include <tqstring.h>
-#include <tqstringlist.h>
-
-static TQString findMostRecentLib(TQString dir, TQString name)
-{
- // Grab all shared libraries in the directory
- TQString filter = "lib"+name+".so.*";
- TQDir d(dir, filter);
- if (!d.exists())
- return 0L;
- TQStringList l = d.entryList();
-
- // Find the best one
- int bestmaj = -1;
- int bestmin = -1;
- TQString best = 0L;
- // where do we start
- uint s = filter.length()-1;
- for (TQStringList::Iterator it = l.begin(); it != l.end(); ++it) {
- TQString numberpart = (*it).mid(s);
- uint endmaj = numberpart.find('.');
- if (endmaj == -1)
- continue;
- bool ok;
- int maj = numberpart.left(endmaj).toInt(&ok);
- if (!ok)
- continue;
- int min = numberpart.mid(endmaj+1).toInt(&ok);
- if (!ok)
- continue;
- if (maj > bestmaj || (maj == bestmaj && min > bestmin)) {
- bestmaj = maj;
- bestmin = min;
- best = (*it);
- }
- }
- if (best.isNull())
- return 0L;
- else
- return dir+"/"+best;
-}
-#endif
-
-
-KOpenSSLProxy::KOpenSSLProxy() {
-KLibLoader *ll = KLibLoader::self();
-_ok = false;
-TQStringList libpaths, libnamesc, libnamess;
-TDEConfig *cfg;
-
- _cryptoLib = 0L;
- _sslLib = 0L;
-
- cfg = new TDEConfig("cryptodefaults", false, false);
- cfg->setGroup("OpenSSL");
- TQString upath = cfg->readPathEntry("Path");
- if (!upath.isEmpty())
- libpaths << upath;
-
- delete cfg;
-
-#ifdef __OpenBSD__
- {
- TQString libname = findMostRecentLib("/usr/lib" KDELIBSUFF, "crypto");
- if (!libname.isNull())
- _cryptoLib = ll->globalLibrary(libname.latin1());
- }
-#elif defined(__CYGWIN__)
- libpaths << "/usr/bin/"
- << "/usr/local/bin"
- << "/usr/local/openssl/bin"
- << "/opt/openssl/bin"
- << "/opt/trinity/bin"
- << "";
-
- libnamess << "cygssl-0.9.7.dll"
- << "cygssl.dll"
- << "libssl.dll"
- << "";
-
- libnamesc << "cygcrypto.dll"
- << "libcrypto.dll"
- << "";
-#else
- libpaths
- #ifdef _AIX
- << "/opt/freeware/lib/"
- #endif
- << "/usr/lib" KDELIBSUFF "/"
- << "/usr/ssl/lib" KDELIBSUFF "/"
- << "/usr/local/lib" KDELIBSUFF "/"
- << "/usr/local/openssl/lib" KDELIBSUFF "/"
- << "/usr/local/ssl/lib" KDELIBSUFF "/"
- << "/opt/openssl/lib" KDELIBSUFF "/"
- << "/lib" KDELIBSUFF "/"
- << "";
-
-// FIXME: #define here for the various OS types to optimize
- libnamess
- #ifdef hpux
- << "libssl.sl"
- #elif defined(_AIX)
- << "libssl.a(libssl.so.0)"
- #elif defined(__APPLE__)
- << "libssl.dylib"
- << "libssl.0.9.dylib"
- #else
- #ifdef SHLIB_VERSION_NUMBER
- << "libssl.so." SHLIB_VERSION_NUMBER
- #endif
- << "libssl.so"
- << "libssl.so.0"
- #endif
- ;
-
- libnamesc
- #ifdef hpux
- << "libcrypto.sl"
- #elif defined(_AIX)
- << "libcrypto.a(libcrypto.so.0)"
- #elif defined(__APPLE__)
- << "libcrypto.dylib"
- << "libcrypto.0.9.dylib"
- #else
- #ifdef SHLIB_VERSION_NUMBER
- << "libcrypto.so." SHLIB_VERSION_NUMBER
- #endif
- << "libcrypto.so"
- << "libcrypto.so.0"
- #endif
- ;
-#endif
-
- for (TQStringList::Iterator it = libpaths.begin();
- it != libpaths.end();
- ++it) {
- for (TQStringList::Iterator shit = libnamesc.begin();
- shit != libnamesc.end();
- ++shit) {
- TQString alib = *it;
- if (!alib.isEmpty() && !alib.endsWith("/"))
- alib += "/";
- alib += *shit;
- TQString tmpStr(alib.latin1());
- tmpStr.replace(TQRegExp("\\(.*\\)"), "");
- if (!access(tmpStr.latin1(), R_OK))
- _cryptoLib = ll->globalLibrary(alib.latin1());
- if (!_cryptoLib) {
- // Multiarch triplet search
- TQDir madir (*it);
- TQStringList multiarchdirs = madir.entryList("*-*-*", TQDir::Dirs);
- for (TQStringList::Iterator mait = multiarchdirs.begin(); mait != multiarchdirs.end(); ++mait ) {
- TQString malib = *it + *mait + "/" + *shit;
- TQString tmpStr(malib.latin1());
- tmpStr.replace(TQRegExp("\\(.*\\)"), "");
- if (!access(tmpStr.latin1(), R_OK))
- _cryptoLib = ll->globalLibrary(malib.latin1());
- }
- }
- if (_cryptoLib) break;
- }
- if (_cryptoLib) break;
- }
-
- if (_cryptoLib) {
-#ifdef KSSL_HAVE_SSL
- K_X509_free = (void (*) (X509 *)) _cryptoLib->symbol("X509_free");
- K_RAND_egd = (int (*)(const char *)) _cryptoLib->symbol("RAND_egd");
- K_RAND_load_file = (int (*)(const char *, long)) _cryptoLib->symbol("RAND_load_file");
- K_RAND_file_name = (const char* (*)(char *, size_t)) _cryptoLib->symbol("RAND_file_name");
- K_RAND_write_file = (int (*)(const char *)) _cryptoLib->symbol("RAND_write_file");
- K_CRYPTO_free = (void (*) (void *)) _cryptoLib->symbol("CRYPTO_free");
- K_d2i_X509 = (X509 * (*)(X509 **,unsigned char **,long)) _cryptoLib->symbol("d2i_X509");
- K_i2d_X509 = (int (*)(X509 *,unsigned char **)) _cryptoLib->symbol("i2d_X509");
- K_X509_cmp = (int (*)(X509 *, X509 *)) _cryptoLib->symbol("X509_cmp");
- K_X509_STORE_CTX_new = (X509_STORE_CTX * (*) (void)) _cryptoLib->symbol("X509_STORE_CTX_new");
- K_X509_STORE_CTX_free = (void (*) (X509_STORE_CTX *)) _cryptoLib->symbol("X509_STORE_CTX_free");
- K_X509_verify_cert = (int (*) (X509_STORE_CTX *)) _cryptoLib->symbol("X509_verify_cert");
- K_X509_STORE_new = (X509_STORE * (*) (void)) _cryptoLib->symbol("X509_STORE_new");
- K_X509_STORE_free = (void (*) (X509_STORE *)) _cryptoLib->symbol("X509_STORE_free");
- K_X509_NAME_oneline = (char * (*) (X509_NAME *,char *,int)) _cryptoLib->symbol("X509_NAME_oneline");
- K_X509_get_subject_name = (X509_NAME * (*) (X509 *)) _cryptoLib->symbol("X509_get_subject_name");
- K_X509_get_issuer_name = (X509_NAME * (*) (X509 *)) _cryptoLib->symbol("X509_get_issuer_name");
- K_X509_STORE_add_lookup = (X509_LOOKUP *(*) (X509_STORE *, X509_LOOKUP_METHOD *)) _cryptoLib->symbol("X509_STORE_add_lookup");
- K_X509_LOOKUP_file = (X509_LOOKUP_METHOD *(*)(void)) _cryptoLib->symbol("X509_LOOKUP_file");
- K_X509_LOOKUP_free = (void (*)(X509_LOOKUP *)) _cryptoLib->symbol("X509_LOOKUP_free");
- K_X509_LOOKUP_ctrl = (int (*)(X509_LOOKUP *, int, const char *, long, char **)) _cryptoLib->symbol("X509_LOOKUP_ctrl");
- K_X509_STORE_CTX_init = (void (*)(X509_STORE_CTX *, X509_STORE *, X509 *, STACK_OF(X509) *)) _cryptoLib->symbol("X509_STORE_CTX_init");
- K_X509_dup = (X509* (*)(X509*)) _cryptoLib->symbol("X509_dup");
- K_BIO_s_mem = (BIO_METHOD *(*) (void)) _cryptoLib->symbol("BIO_s_mem");
- K_BIO_new = (BIO* (*)(BIO_METHOD *)) _cryptoLib->symbol("BIO_new");
- K_BIO_new_fp = (BIO* (*)(FILE*, int)) _cryptoLib->symbol("BIO_new_fp");
- K_BIO_new_mem_buf = (BIO* (*)(void *, int)) _cryptoLib->symbol("BIO_new_mem_buf");
- K_BIO_free = (int (*)(BIO*)) _cryptoLib->symbol("BIO_free");
- K_BIO_ctrl = (long (*) (BIO *,int,long,void *)) _cryptoLib->symbol("BIO_ctrl");
- K_BIO_write = (int (*) (BIO *b, const void *data, int len)) _cryptoLib->symbol("BIO_write");
- K_PEM_ASN1_write_bio = (int (*)(int (*)(), const char *,BIO*, char*, const EVP_CIPHER *, unsigned char *, int, pem_password_cb *, void *)) _cryptoLib->symbol("PEM_ASN1_write_bio");
-#if OPENSSL_VERSION_NUMBER >= 0x10000000L
- K_ASN1_item_i2d_fp = (int (*)(ASN1_ITEM *, FILE*, unsigned char *)) _cryptoLib->symbol("ASN1_item_i2d_fp");
- K_NETSCAPE_X509_it = (ASN1_ITEM *) _cryptoLib->symbol("NETSCAPE_X509_it");
-#else
- K_X509_asn1_meth = (ASN1_METHOD* (*)(void)) _cryptoLib->symbol("X509_asn1_meth");
- K_ASN1_i2d_fp = (int (*)(int (*)(), FILE*, unsigned char *)) _cryptoLib->symbol("ASN1_i2d_fp");
- K_i2d_ASN1_HEADER = (int (*)(ASN1_HEADER *, unsigned char **)) _cryptoLib->symbol("i2d_ASN1_HEADER");
-#endif
- K_X509_print_fp = (int (*)(FILE*, X509*)) _cryptoLib->symbol("X509_print_fp");
- K_i2d_PKCS12 = (int (*)(PKCS12*, unsigned char**)) _cryptoLib->symbol("i2d_PKCS12");
- K_i2d_PKCS12_fp = (int (*)(FILE *, PKCS12*)) _cryptoLib->symbol("i2d_PKCS12_fp");
- K_PKCS12_newpass = (int (*)(PKCS12*, char*, char*)) _cryptoLib->symbol("PKCS12_newpass");
- K_d2i_PKCS12_fp = (PKCS12* (*)(FILE*, PKCS12**)) _cryptoLib->symbol("d2i_PKCS12_fp");
- K_PKCS12_new = (PKCS12* (*)()) _cryptoLib->symbol("PKCS12_new");
- K_PKCS12_free = (void (*)(PKCS12 *)) _cryptoLib->symbol("PKCS12_free");
- K_PKCS12_parse = (int (*)(PKCS12*, const char *, EVP_PKEY**,
- X509**, STACK_OF(X509)**)) _cryptoLib->symbol("PKCS12_parse");
- K_EVP_PKEY_free = (void (*) (EVP_PKEY *)) _cryptoLib->symbol("EVP_PKEY_free");
- K_EVP_PKEY_new = (EVP_PKEY* (*)()) _cryptoLib->symbol("EVP_PKEY_new");
- K_X509_REQ_free = (void (*)(X509_REQ*)) _cryptoLib->symbol("X509_REQ_free");
- K_X509_REQ_new = (X509_REQ* (*)()) _cryptoLib->symbol("X509_REQ_new");
- K_X509_STORE_CTX_set_chain = (void (*)(X509_STORE_CTX *, STACK_OF(X509)*)) _cryptoLib->symbol("X509_STORE_CTX_set_chain");
- K_X509_STORE_CTX_set_purpose = (void (*)(X509_STORE_CTX *, int)) _cryptoLib->symbol("X509_STORE_CTX_set_purpose");
- K_sk_free = (void (*) (STACK *)) _cryptoLib->symbol("sk_free");
- K_sk_num = (int (*) (STACK *)) _cryptoLib->symbol("sk_num");
- K_sk_pop = (char* (*) (STACK *)) _cryptoLib->symbol("sk_pop");
- K_sk_value = (char* (*) (STACK *, int)) _cryptoLib->symbol("sk_value");
- K_sk_new = (STACK* (*) (int (*)())) _cryptoLib->symbol("sk_new");
- K_sk_push = (int (*) (STACK*, char*)) _cryptoLib->symbol("sk_push");
- K_sk_dup = (STACK* (*) (STACK *)) _cryptoLib->symbol("sk_dup");
- K_i2s_ASN1_INTEGER = (char *(*) (X509V3_EXT_METHOD *, ASN1_INTEGER *)) _cryptoLib->symbol("i2s_ASN1_INTEGER");
- K_X509_get_serialNumber = (ASN1_INTEGER * (*) (X509 *)) _cryptoLib->symbol("X509_get_serialNumber");
- K_X509_get_pubkey = (EVP_PKEY *(*)(X509 *)) _cryptoLib->symbol("X509_get_pubkey");
- K_i2d_PublicKey = (int (*)(EVP_PKEY *, unsigned char **)) _cryptoLib->symbol("i2d_PublicKey");
- K_X509_check_private_key = (int (*)(X509 *, EVP_PKEY *)) _cryptoLib->symbol("X509_check_private_key");
- K_BN_bn2hex = (char *(*)(const BIGNUM *)) _cryptoLib->symbol("BN_bn2hex");
- K_X509_digest = (int (*)(const X509 *,const EVP_MD *, unsigned char *, unsigned int *)) _cryptoLib->symbol("X509_digest");
- K_EVP_md5 = (EVP_MD *(*)()) _cryptoLib->symbol("EVP_md5");
- K_ASN1_INTEGER_free = (void (*)(ASN1_INTEGER *)) _cryptoLib->symbol("ASN1_INTEGER_free");
- K_OBJ_obj2nid = (int (*)(ASN1_OBJECT *)) _cryptoLib->symbol("OBJ_obj2nid");
- K_OBJ_nid2ln = (const char *(*)(int)) _cryptoLib->symbol("OBJ_nid2ln");
- K_X509_get_ext_count = (int (*)(X509*)) _cryptoLib->symbol("X509_get_ext_count");
- K_X509_get_ext_by_NID = (int (*)(X509*,int,int)) _cryptoLib->symbol("X509_get_ext_by_NID");
- K_X509_get_ext_by_OBJ = (int (*)(X509*,ASN1_OBJECT*,int)) _cryptoLib->symbol("X509_get_ext_by_OBJ");
- K_X509_get_ext = (X509_EXTENSION* (*)(X509*,int)) _cryptoLib->symbol("X509_get_ext");
- K_X509_delete_ext = (X509_EXTENSION* (*)(X509*,int)) _cryptoLib->symbol("X509_delete_ext");
- K_X509_add_ext = (int (*)(X509*,X509_EXTENSION*,int)) _cryptoLib->symbol("X509_add_ext");
- K_X509_get_ext_d2i = (void* (*)(X509*,int,int*,int*)) _cryptoLib->symbol("X509_get_ext_d2i");
- K_i2s_ASN1_OCTET_STRING = (char *(*)(X509V3_EXT_METHOD*,ASN1_OCTET_STRING*)) _cryptoLib->symbol("i2s_ASN1_OCTET_STRING");
- K_ASN1_BIT_STRING_get_bit = (int (*)(ASN1_BIT_STRING*,int)) _cryptoLib->symbol("ASN1_BIT_STRING_get_bit");
- K_PKCS7_new = (PKCS7 *(*)()) _cryptoLib->symbol("PKCS7_new");
- K_PKCS7_free = (void (*)(PKCS7*)) _cryptoLib->symbol("PKCS7_free");
- K_PKCS7_content_free = (void (*)(PKCS7*)) _cryptoLib->symbol("PKCS7_content_free");
- K_i2d_PKCS7 = (int (*)(PKCS7*, unsigned char**)) _cryptoLib->symbol("i2d_PKCS7");
- K_i2d_PKCS7_fp = (int (*)(FILE*,PKCS7*)) _cryptoLib->symbol("i2d_PKCS7_fp");
- K_i2d_PKCS7_bio = (int (*)(BIO *bp,PKCS7 *p7)) _cryptoLib->symbol("i2d_PKCS7_bio");
- K_d2i_PKCS7 = (PKCS7* (*)(PKCS7**,unsigned char**,long)) _cryptoLib->symbol("d2i_PKCS7");
- K_d2i_PKCS7_fp = (PKCS7 *(*)(FILE *,PKCS7**)) _cryptoLib->symbol("d2i_PKCS7_fp");
- K_d2i_PKCS7_bio = (PKCS7 *(*)(BIO *bp,PKCS7 **p7)) _cryptoLib->symbol("d2i_PKCS7_bio");
- K_PKCS7_dup = (PKCS7* (*)(PKCS7*)) _cryptoLib->symbol("PKCS7_dup");
- K_PKCS7_sign = (PKCS7 *(*)(X509*, EVP_PKEY*, STACK_OF(X509)*, BIO*, int)) _cryptoLib->symbol("PKCS7_sign");
- K_PKCS7_verify = (int (*)(PKCS7*,STACK_OF(X509)*,X509_STORE*,BIO*,BIO*,int)) _cryptoLib->symbol("PKCS7_verify");
- K_PKCS7_get0_signers = (STACK_OF(X509) *(*)(PKCS7 *, STACK_OF(X509) *, int)) _cryptoLib->symbol("PKCS7_get0_signers");
- K_PKCS7_encrypt = (PKCS7* (*)(STACK_OF(X509) *, BIO *, EVP_CIPHER *, int)) _cryptoLib->symbol("PKCS7_encrypt");
- K_PKCS7_decrypt = (int (*)(PKCS7 *, EVP_PKEY *, X509 *, BIO *, int)) _cryptoLib->symbol("PKCS7_decrypt");
- K_PEM_X509_INFO_read = (STACK_OF(X509_INFO) *(*)(FILE*, STACK_OF(X509_INFO)*, pem_password_cb*, void *)) _cryptoLib->symbol("PEM_X509_INFO_read");
- K_ASN1_d2i_fp = (char *(*)(char *(*)(),char *(*)(),FILE*,unsigned char**)) _cryptoLib->symbol("ASN1_d2i_fp");
- K_X509_new = (X509 *(*)()) _cryptoLib->symbol("X509_new");
- K_X509_PURPOSE_get_count = (int (*)()) _cryptoLib->symbol("X509_PURPOSE_get_count");
- K_X509_PURPOSE_get_id = (int (*)(X509_PURPOSE *)) _cryptoLib->symbol("X509_PURPOSE_get_id");
- K_X509_check_purpose = (int (*)(X509*,int,int)) _cryptoLib->symbol("X509_check_purpose");
- K_X509_PURPOSE_get0 = (X509_PURPOSE *(*)(int)) _cryptoLib->symbol("X509_PURPOSE_get0");
- K_EVP_PKEY_assign = (int (*)(EVP_PKEY*, int, char*)) _cryptoLib->symbol("EVP_PKEY_assign");
- K_X509_REQ_set_pubkey = (int (*)(X509_REQ*, EVP_PKEY*)) _cryptoLib->symbol("X509_REQ_set_pubkey");
- K_RSA_generate_key = (RSA* (*)(int, unsigned long, void (*)(int,int,void *), void *)) _cryptoLib->symbol("RSA_generate_key");
- K_i2d_X509_REQ_fp = (int (*)(FILE *, X509_REQ *)) _cryptoLib->symbol("i2d_X509_REQ_fp");
- K_ERR_clear_error = (void (*)()) _cryptoLib->symbol("ERR_clear_error");
- K_ERR_get_error = (unsigned long (*)()) _cryptoLib->symbol("ERR_get_error");
- K_ERR_print_errors_fp = (void (*)(FILE*)) _cryptoLib->symbol("ERR_print_errors_fp");
- K_X509_get1_email = (STACK *(*)(X509 *x)) _cryptoLib->symbol("X509_get1_email");
- K_X509_email_free = (void (*)(STACK *sk)) _cryptoLib->symbol("X509_email_free");
- K_EVP_des_ede3_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_des_ede3_cbc");
- K_EVP_des_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_des_cbc");
- K_EVP_rc2_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_rc2_cbc");
- K_EVP_rc2_64_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_rc2_64_cbc");
- K_EVP_rc2_40_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_rc2_40_cbc");
- K_i2d_PrivateKey_fp = (int (*)(FILE*,EVP_PKEY*)) _cryptoLib->symbol("i2d_PrivateKey_fp");
- K_i2d_PKCS8PrivateKey_fp = (int (*)(FILE*, EVP_PKEY*, const EVP_CIPHER*, char*, int, pem_password_cb*, void*)) _cryptoLib->symbol("i2d_PKCS8PrivateKey_fp");
- K_RSA_free = (void (*)(RSA*)) _cryptoLib->symbol("RSA_free");
- K_EVP_bf_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_bf_cbc");
- K_X509_REQ_sign = (int (*)(X509_REQ*, EVP_PKEY*, const EVP_MD*)) _cryptoLib->symbol("X509_REQ_sign");
- K_X509_NAME_add_entry_by_txt = (int (*)(X509_NAME*, char*, int, unsigned char*, int, int, int)) _cryptoLib->symbol("X509_NAME_add_entry_by_txt");
- K_X509_NAME_new = (X509_NAME *(*)()) _cryptoLib->symbol("X509_NAME_new");
- K_X509_REQ_set_subject_name = (int (*)(X509_REQ*,X509_NAME*)) _cryptoLib->symbol("X509_REQ_set_subject_name");
- K_ASN1_STRING_data = (unsigned char *(*)(ASN1_STRING*)) _cryptoLib->symbol("ASN1_STRING_data");
- K_ASN1_STRING_length = (int (*)(ASN1_STRING*)) _cryptoLib->symbol("ASN1_STRING_length");
-#endif
- }
-
-#ifdef __OpenBSD__
- {
- TQString libname = findMostRecentLib("/usr/lib", "ssl");
- if (!libname.isNull())
- _sslLib = ll->globalLibrary(libname.latin1());
- }
-#else
- for (TQStringList::Iterator it = libpaths.begin();
- it != libpaths.end();
- ++it) {
- for (TQStringList::Iterator shit = libnamess.begin();
- shit != libnamess.end();
- ++shit) {
- TQString alib = *it;
- if (!alib.isEmpty() && !alib.endsWith("/"))
- alib += "/";
- alib += *shit;
- TQString tmpStr(alib.latin1());
- tmpStr.replace(TQRegExp("\\(.*\\)"), "");
- if (!access(tmpStr.latin1(), R_OK))
- _sslLib = ll->globalLibrary(alib.latin1());
- if (!_sslLib) {
- // Multiarch triplet search
- TQDir madir (*it);
- TQStringList multiarchdirs = madir.entryList("*-*-*", TQDir::Dirs);
- for (TQStringList::Iterator mait = multiarchdirs.begin(); mait != multiarchdirs.end(); ++mait ) {
- TQString malib = *it + *mait + "/" + *shit;
- TQString tmpStr(malib.latin1());
- tmpStr.replace(TQRegExp("\\(.*\\)"), "");
- if (!access(tmpStr.latin1(), R_OK))
- _sslLib = ll->globalLibrary(malib.latin1());
- }
- }
- if (_sslLib) break;
- }
- if (_sslLib) break;
- }
-#endif
-
- if (_sslLib) {
-#ifdef KSSL_HAVE_SSL
- // stand back from your monitor and look at this. it's fun! :)
- K_SSL_connect = (int (*)(SSL *)) _sslLib->symbol("SSL_connect");
- K_SSL_accept = (int (*)(SSL *)) _sslLib->symbol("SSL_accept");
- K_SSL_read = (int (*)(SSL *, void *, int)) _sslLib->symbol("SSL_read");
- K_SSL_write = (int (*)(SSL *, const void *, int))
- _sslLib->symbol("SSL_write");
- K_SSL_new = (SSL* (*)(SSL_CTX *)) _sslLib->symbol("SSL_new");
- K_SSL_free = (void (*)(SSL *)) _sslLib->symbol("SSL_free");
- K_SSL_shutdown = (int (*)(SSL *)) _sslLib->symbol("SSL_shutdown");
- K_SSL_CTX_new = (SSL_CTX* (*)(SSL_METHOD*)) _sslLib->symbol("SSL_CTX_new");
- K_SSL_CTX_free = (void (*)(SSL_CTX*)) _sslLib->symbol("SSL_CTX_free");
- K_SSL_set_fd = (int (*)(SSL *, int)) _sslLib->symbol("SSL_set_fd");
- K_SSL_pending = (int (*)(SSL *)) _sslLib->symbol("SSL_pending");
- K_SSL_CTX_set_cipher_list = (int (*)(SSL_CTX *, const char *))
- _sslLib->symbol("SSL_CTX_set_cipher_list");
- K_SSL_CTX_set_verify = (void (*)(SSL_CTX*, int, int (*)(int, X509_STORE_CTX*))) _sslLib->symbol("SSL_CTX_set_verify");
- K_SSL_use_certificate = (int (*)(SSL*, X509*))
- _sslLib->symbol("SSL_CTX_use_certificate");
- K_SSL_get_current_cipher = (SSL_CIPHER *(*)(SSL *))
- _sslLib->symbol("SSL_get_current_cipher");
- K_SSL_ctrl = (long (*)(SSL * ,int, long, char *))
- _sslLib->symbol("SSL_ctrl");
- K_TLSv1_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("TLSv1_client_method");
- K_SSLv2_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("SSLv2_client_method");
- K_SSLv3_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("SSLv3_client_method");
- K_SSLv23_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("SSLv23_client_method");
- K_SSL_get_peer_certificate = (X509 *(*)(SSL *)) _sslLib->symbol("SSL_get_peer_certificate");
- K_SSL_CIPHER_get_bits = (int (*)(SSL_CIPHER *,int *)) _sslLib->symbol("SSL_CIPHER_get_bits");
- K_SSL_CIPHER_get_version = (char * (*)(SSL_CIPHER *)) _sslLib->symbol("SSL_CIPHER_get_version");
- K_SSL_CIPHER_get_name = (const char * (*)(SSL_CIPHER *)) _sslLib->symbol("SSL_CIPHER_get_name");
- K_SSL_CIPHER_description = (char * (*)(SSL_CIPHER *, char *, int)) _sslLib->symbol("SSL_CIPHER_description");
- K_SSL_CTX_use_PrivateKey = (int (*)(SSL_CTX*, EVP_PKEY*)) _sslLib->symbol("SSL_CTX_use_PrivateKey");
- K_SSL_CTX_use_certificate = (int (*)(SSL_CTX*, X509*)) _sslLib->symbol("SSL_CTX_use_certificate");
- K_SSL_get_error = (int (*)(SSL*, int)) _sslLib->symbol("SSL_get_error");
- K_SSL_get_peer_cert_chain = (STACK_OF(X509)* (*)(SSL*)) _sslLib->symbol("SSL_get_peer_cert_chain");
- K_SSL_load_client_CA_file = (STACK_OF(X509_NAME)* (*)(const char *)) _sslLib->symbol("SSL_load_client_CA_file");
- K_SSL_peek = (int (*)(SSL*,void*,int)) _sslLib->symbol("SSL_peek");
- K_SSL_get1_session = (SSL_SESSION* (*)(SSL*)) _sslLib->symbol("SSL_get1_session");
- K_SSL_SESSION_free = (void (*)(SSL_SESSION*)) _sslLib->symbol("SSL_SESSION_free");
- K_SSL_set_session = (int (*)(SSL*,SSL_SESSION*)) _sslLib->symbol("SSL_set_session");
- K_d2i_SSL_SESSION = (SSL_SESSION* (*)(SSL_SESSION**,unsigned char**, long)) _sslLib->symbol("d2i_SSL_SESSION");
- K_i2d_SSL_SESSION = (int (*)(SSL_SESSION*,unsigned char**)) _sslLib->symbol("i2d_SSL_SESSION");
- K_SSL_get_ciphers = (STACK_OF(SSL_CIPHER) *(*)(const SSL*)) _sslLib->symbol("SSL_get_ciphers");
-#endif
-
-
- // Initialize the library (once only!)
- void *x;
- x = _sslLib->symbol("SSL_library_init");
- if (_cryptoLib) {
- if (x) ((int (*)())x)();
- x = _cryptoLib->symbol("OpenSSL_add_all_algorithms");
- if (!x)
- x = _cryptoLib->symbol("OPENSSL_add_all_algorithms");
- if (x) {
- ((void (*)())x)();
- } else {
- x = _cryptoLib->symbol("OpenSSL_add_all_algorithms_conf");
- if (!x)
- x = _cryptoLib->symbol("OPENSSL_add_all_algorithms_conf");
- if (x) {
- ((void (*)())x)();
- } else {
- x = _cryptoLib->symbol("OpenSSL_add_all_algorithms_noconf");
- if (!x)
- x = _cryptoLib->symbol("OPENSSL_add_all_algorithms_noconf");
- if (x)
- ((void (*)())x)();
- }
- }
- x = _cryptoLib->symbol("OpenSSL_add_all_ciphers");
- if (!x)
- x = _cryptoLib->symbol("OPENSSL_add_all_ciphers");
- if (x) ((void (*)())x)();
- x = _cryptoLib->symbol("OpenSSL_add_all_digests");
- if (!x)
- x = _cryptoLib->symbol("OPENSSL_add_all_digests");
- if (x) ((void (*)())x)();
- }
- }
-
-}
-
-
-KOpenSSLProxy* KOpenSSLProxy::_me = 0L;
-static KStaticDeleter<KOpenSSLProxy> medProxy;
-
-
-
-KOpenSSLProxy::~KOpenSSLProxy() {
- if (_sslLib) {
- _sslLib->unload();
- }
- if (_cryptoLib) {
- _cryptoLib->unload();
- }
- medProxy.setObject(0);
-}
-
-
-// FIXME: we should check "ok" and allow this to init the lib if !ok.
-
-KOpenSSLProxy *KOpenSSLProxy::self() {
-#ifdef KSSL_HAVE_SSL
- if (!_me) {
- _me = medProxy.setObject(_me, new KOpenSSLProxy);
- }
-#endif
- return _me;
-}
-
-
-
-
-
-
-
-#ifdef KSSL_HAVE_SSL
-
-
-
-int KOpenSSLProxy::SSL_connect(SSL *ssl) {
- if (K_SSL_connect) return (K_SSL_connect)(ssl);
- return -1;
-}
-
-
-int KOpenSSLProxy::SSL_accept(SSL *ssl) {
- if (K_SSL_accept) return (K_SSL_accept)(ssl);
- return -1;
-}
-
-
-int KOpenSSLProxy::SSL_read(SSL *ssl, void *buf, int num) {
- if (K_SSL_read) return (K_SSL_read)(ssl, buf, num);
- return -1;
-}
-
-
-int KOpenSSLProxy::SSL_write(SSL *ssl, const void *buf, int num) {
- if (K_SSL_write) return (K_SSL_write)(ssl, buf, num);
- return -1;
-}
-
-
-SSL *KOpenSSLProxy::SSL_new(SSL_CTX *ctx) {
- if (K_SSL_new) return (K_SSL_new)(ctx);
- return 0L;
-}
-
-
-void KOpenSSLProxy::SSL_free(SSL *ssl) {
- if (K_SSL_free) (K_SSL_free)(ssl);
-}
-
-
-int KOpenSSLProxy::SSL_shutdown(SSL *ssl) {
- if (K_SSL_shutdown) return (K_SSL_shutdown)(ssl);
- return -1;
-}
-
-
-SSL_CTX *KOpenSSLProxy::SSL_CTX_new(SSL_METHOD *method) {
- if (K_SSL_CTX_new) return (K_SSL_CTX_new)(method);
- return 0L;
-}
-
-
-void KOpenSSLProxy::SSL_CTX_free(SSL_CTX *ctx) {
- if (K_SSL_CTX_free) (K_SSL_CTX_free)(ctx);
-}
-
-
-int KOpenSSLProxy::SSL_set_fd(SSL *ssl, int fd) {
- if (K_SSL_set_fd) return (K_SSL_set_fd)(ssl, fd);
- return -1;
-}
-
-
-int KOpenSSLProxy::SSL_pending(SSL *ssl) {
- if (K_SSL_pending) return (K_SSL_pending)(ssl);
- return -1;
-}
-
-
-int KOpenSSLProxy::SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str) {
- if (K_SSL_CTX_set_cipher_list) return (K_SSL_CTX_set_cipher_list)(ctx, str);
- return -1;
-}
-
-
-void KOpenSSLProxy::SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
- int (*verify_callback)(int, X509_STORE_CTX *)) {
- if (K_SSL_CTX_set_verify) (K_SSL_CTX_set_verify)(ctx, mode, verify_callback);
-}
-
-
-int KOpenSSLProxy::SSL_use_certificate(SSL *ssl, X509 *x) {
- if (K_SSL_use_certificate) return (K_SSL_use_certificate)(ssl, x);
- return -1;
-}
-
-
-SSL_CIPHER *KOpenSSLProxy::SSL_get_current_cipher(SSL *ssl) {
- if (K_SSL_get_current_cipher) return (K_SSL_get_current_cipher)(ssl);
- return 0L;
-}
-
-
-long KOpenSSLProxy::SSL_ctrl(SSL *ssl,int cmd, long larg, char *parg) {
- if (K_SSL_ctrl) return (K_SSL_ctrl)(ssl, cmd, larg, parg);
- return -1;
-}
-
-
-int KOpenSSLProxy::RAND_egd(const char *path) {
- if (K_RAND_egd) return (K_RAND_egd)(path);
- return -1;
-}
-
-
-SSL_METHOD *KOpenSSLProxy::TLSv1_client_method() {
- if (K_TLSv1_client_method) return (K_TLSv1_client_method)();
- return 0L;
-}
-
-
-SSL_METHOD *KOpenSSLProxy::SSLv2_client_method() {
- if (K_SSLv2_client_method) return (K_SSLv2_client_method)();
- return 0L;
-}
-
-
-SSL_METHOD *KOpenSSLProxy::SSLv3_client_method() {
- if (K_SSLv3_client_method) return (K_SSLv3_client_method)();
- return 0L;
-}
-
-
-SSL_METHOD *KOpenSSLProxy::SSLv23_client_method() {
- if (K_SSLv23_client_method) return (K_SSLv23_client_method)();
- return 0L;
-}
-
-
-X509 *KOpenSSLProxy::SSL_get_peer_certificate(SSL *s) {
- if (K_SSL_get_peer_certificate) return (K_SSL_get_peer_certificate)(s);
- return 0L;
-}
-
-
-int KOpenSSLProxy::SSL_CIPHER_get_bits(SSL_CIPHER *c,int *alg_bits) {
- if (K_SSL_CIPHER_get_bits) return (K_SSL_CIPHER_get_bits)(c, alg_bits);
- return -1;
-}
-
-
-char * KOpenSSLProxy::SSL_CIPHER_get_version(SSL_CIPHER *c) {
- if (K_SSL_CIPHER_get_version) return (K_SSL_CIPHER_get_version)(c);
- return 0L;
-}
-
-
-const char * KOpenSSLProxy::SSL_CIPHER_get_name(SSL_CIPHER *c) {
- if (K_SSL_CIPHER_get_name) return (K_SSL_CIPHER_get_name)(c);
- return 0L;
-}
-
-
-char * KOpenSSLProxy::SSL_CIPHER_description(SSL_CIPHER *c,char *buf,int size) {
- if (K_SSL_CIPHER_description) return (K_SSL_CIPHER_description)(c,buf,size);
- return 0L;
-}
-
-
-X509 * KOpenSSLProxy::d2i_X509(X509 **a,unsigned char **pp,long length) {
- if (K_d2i_X509) return (K_d2i_X509)(a,pp,length);
- return 0L;
-}
-
-
-int KOpenSSLProxy::i2d_X509(X509 *a,unsigned char **pp) {
- if (K_i2d_X509) return (K_i2d_X509)(a,pp);
- return -1;
-}
-
-
-int KOpenSSLProxy::X509_cmp(X509 *a, X509 *b) {
- if (K_X509_cmp) return (K_X509_cmp)(a,b);
- return 0;
-}
-
-
-X509_STORE *KOpenSSLProxy::X509_STORE_new(void) {
- if (K_X509_STORE_new) return (K_X509_STORE_new)();
- return 0L;
-}
-
-
-void KOpenSSLProxy::X509_STORE_free(X509_STORE *v) {
- if (K_X509_STORE_free) (K_X509_STORE_free)(v);
-}
-
-
-X509_STORE_CTX *KOpenSSLProxy::X509_STORE_CTX_new(void) {
- if (K_X509_STORE_CTX_new) return (K_X509_STORE_CTX_new)();
- return 0L;
-}
-
-
-void KOpenSSLProxy::X509_STORE_CTX_free(X509_STORE_CTX *ctx) {
- if (K_X509_STORE_CTX_free) (K_X509_STORE_CTX_free)(ctx);
-}
-
-
-int KOpenSSLProxy::X509_verify_cert(X509_STORE_CTX *ctx) {
- if (K_X509_verify_cert) return (K_X509_verify_cert)(ctx);
- return -1;
-}
-
-
-void KOpenSSLProxy::X509_free(X509 *a) {
- if (K_X509_free) (K_X509_free)(a);
-}
-
-
-char *KOpenSSLProxy::X509_NAME_oneline(X509_NAME *a,char *buf,int size) {
- if (K_X509_NAME_oneline) return (K_X509_NAME_oneline)(a,buf,size);
- return 0L;
-}
-
-
-X509_NAME *KOpenSSLProxy::X509_get_subject_name(X509 *a) {
- if (K_X509_get_subject_name) return (K_X509_get_subject_name)(a);
- return 0L;
-}
-
-
-X509_NAME *KOpenSSLProxy::X509_get_issuer_name(X509 *a) {
- if (K_X509_get_issuer_name) return (K_X509_get_issuer_name)(a);
- return 0L;
-}
-
-
-X509_LOOKUP *KOpenSSLProxy::X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m) {
- if (K_X509_STORE_add_lookup) return (K_X509_STORE_add_lookup)(v,m);
- return 0L;
-}
-
-
-X509_LOOKUP_METHOD *KOpenSSLProxy::X509_LOOKUP_file(void) {
- if (K_X509_LOOKUP_file) return (K_X509_LOOKUP_file)();
- return 0L;
-}
-
-
-void KOpenSSLProxy::X509_LOOKUP_free(X509_LOOKUP *x) {
- if (K_X509_LOOKUP_free) (K_X509_LOOKUP_free)(x);
-}
-
-
-int KOpenSSLProxy::X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret) {
- if (K_X509_LOOKUP_ctrl) return (K_X509_LOOKUP_ctrl)(ctx,cmd,argc,argl,ret);
- return -1;
-}
-
-
-void KOpenSSLProxy::X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509, STACK_OF(X509) *chain) {
- if (K_X509_STORE_CTX_init) (K_X509_STORE_CTX_init)(ctx,store,x509,chain);
-}
-
-
-void KOpenSSLProxy::CRYPTO_free(void *x) {
- if (K_CRYPTO_free) (K_CRYPTO_free)(x);
-}
-
-
-X509 *KOpenSSLProxy::X509_dup(X509 *x509) {
- if (K_X509_dup) return (K_X509_dup)(x509);
- return 0L;
-}
-
-
-BIO *KOpenSSLProxy::BIO_new(BIO_METHOD *type) {
- if (K_BIO_new) return (K_BIO_new)(type);
- else return 0L;
-}
-
-
-BIO_METHOD *KOpenSSLProxy::BIO_s_mem(void) {
- if (K_BIO_s_mem) return (K_BIO_s_mem)();
- else return 0L;
-}
-
-
-BIO *KOpenSSLProxy::BIO_new_fp(FILE *stream, int close_flag) {
- if (K_BIO_new_fp) return (K_BIO_new_fp)(stream, close_flag);
- return 0L;
-}
-
-
-BIO *KOpenSSLProxy::BIO_new_mem_buf(void *buf, int len) {
- if (K_BIO_new_mem_buf) return (K_BIO_new_mem_buf)(buf,len);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::BIO_free(BIO *a) {
- if (K_BIO_free) return (K_BIO_free)(a);
- return -1;
-}
-
-
-long KOpenSSLProxy::BIO_ctrl(BIO *bp,int cmd,long larg,void *parg) {
- if (K_BIO_ctrl) return (K_BIO_ctrl)(bp,cmd,larg,parg);
- else return 0; // failure return for BIO_ctrl is quite individual, maybe we should abort() instead
-}
-
-
-int KOpenSSLProxy::BIO_write(BIO *b, const void *data, int len) {
- if (K_BIO_write) return (K_BIO_write)(b, data, len);
- else return -1;
-}
-
-
-int KOpenSSLProxy::PEM_write_bio_X509(BIO *bp, X509 *x) {
- if (K_PEM_ASN1_write_bio) return (K_PEM_ASN1_write_bio) ((int (*)())K_i2d_X509, PEM_STRING_X509, bp, (char *)x, 0L, 0L, 0, 0L, 0L);
- else return -1;
-}
-
-#if OPENSSL_VERSION_NUMBER >= 0x10000000L
-int KOpenSSLProxy::ASN1_i2d_fp(FILE *out,unsigned char *x) {
- if (K_ASN1_item_i2d_fp && K_NETSCAPE_X509_it)
- return (K_ASN1_item_i2d_fp)(K_NETSCAPE_X509_it, out, x);
- else return -1;
-}
-#else
-ASN1_METHOD *KOpenSSLProxy::X509_asn1_meth(void) {
- if (K_X509_asn1_meth) return (K_X509_asn1_meth)();
- else return 0L;
-}
-
-
-int KOpenSSLProxy::ASN1_i2d_fp(FILE *out,unsigned char *x) {
- if (K_ASN1_i2d_fp && K_i2d_ASN1_HEADER)
- return (K_ASN1_i2d_fp)((int (*)())K_i2d_ASN1_HEADER, out, x);
- else return -1;
-}
-#endif
-
-int KOpenSSLProxy::X509_print(FILE *fp, X509 *x) {
- if (K_X509_print_fp) return (K_X509_print_fp)(fp, x);
- return -1;
-}
-
-
-PKCS12 *KOpenSSLProxy::d2i_PKCS12_fp(FILE *fp, PKCS12 **p12) {
- if (K_d2i_PKCS12_fp) return (K_d2i_PKCS12_fp)(fp, p12);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::PKCS12_newpass(PKCS12 *p12, char *oldpass, char *newpass) {
- if (K_PKCS12_newpass) return (K_PKCS12_newpass)(p12, oldpass, newpass);
- else return -1;
-}
-
-
-int KOpenSSLProxy::i2d_PKCS12(PKCS12 *p12, unsigned char **p) {
- if (K_i2d_PKCS12) return (K_i2d_PKCS12)(p12, p);
- else return -1;
-}
-
-
-int KOpenSSLProxy::i2d_PKCS12_fp(FILE *fp, PKCS12 *p12) {
- if (K_i2d_PKCS12_fp) return (K_i2d_PKCS12_fp)(fp, p12);
- else return -1;
-}
-
-
-PKCS12 *KOpenSSLProxy::PKCS12_new(void) {
- if (K_PKCS12_new) return (K_PKCS12_new)();
- else return 0L;
-}
-
-
-void KOpenSSLProxy::PKCS12_free(PKCS12 *a) {
- if (K_PKCS12_free) (K_PKCS12_free)(a);
-}
-
-
-int KOpenSSLProxy::PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey,
- X509 **cert, STACK_OF(X509) **ca) {
- if (K_PKCS12_parse) return (K_PKCS12_parse) (p12, pass, pkey, cert, ca);
- else return -1;
-}
-
-
-void KOpenSSLProxy::EVP_PKEY_free(EVP_PKEY *x) {
- if (K_EVP_PKEY_free) (K_EVP_PKEY_free)(x);
-}
-
-
-EVP_PKEY* KOpenSSLProxy::EVP_PKEY_new() {
- if (K_EVP_PKEY_new) return (K_EVP_PKEY_new)();
- else return 0L;
-}
-
-
-void KOpenSSLProxy::X509_REQ_free(X509_REQ *x) {
- if (K_X509_REQ_free) (K_X509_REQ_free)(x);
-}
-
-
-X509_REQ* KOpenSSLProxy::X509_REQ_new() {
- if (K_X509_REQ_new) return (K_X509_REQ_new)();
- else return 0L;
-}
-
-
-int KOpenSSLProxy::SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey) {
- if (K_SSL_CTX_use_PrivateKey) return (K_SSL_CTX_use_PrivateKey)(ctx,pkey);
- else return -1;
-}
-
-
-int KOpenSSLProxy::SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x) {
- if (K_SSL_CTX_use_certificate) return (K_SSL_CTX_use_certificate)(ctx,x);
- else return -1;
-}
-
-
-int KOpenSSLProxy::SSL_get_error(SSL *ssl, int rc) {
- if (K_SSL_get_error) return (K_SSL_get_error)(ssl,rc);
- else return -1;
-}
-
-
-STACK_OF(X509) *KOpenSSLProxy::SSL_get_peer_cert_chain(SSL *s) {
- if (K_SSL_get_peer_cert_chain) return (K_SSL_get_peer_cert_chain)(s);
- else return 0L;
-}
-
-
-void KOpenSSLProxy::sk_free(STACK *s) {
- if (K_sk_free) (K_sk_free)(s);
-}
-
-
-int KOpenSSLProxy::sk_num(STACK *s) {
- if (K_sk_num) return (K_sk_num)(s);
- else return -1;
-}
-
-
-char *KOpenSSLProxy::sk_pop(STACK *s) {
- if (K_sk_pop) return (K_sk_pop)(s);
- else return 0L;
-}
-
-
-char *KOpenSSLProxy::sk_value(STACK *s, int n) {
- if (K_sk_value) return (K_sk_value)(s, n);
- else return 0L;
-}
-
-
-void KOpenSSLProxy::X509_STORE_CTX_set_chain(X509_STORE_CTX *v, STACK_OF(X509)* x) {
- if (K_X509_STORE_CTX_set_chain) (K_X509_STORE_CTX_set_chain)(v,x);
-}
-
-void KOpenSSLProxy::X509_STORE_CTX_set_purpose(X509_STORE_CTX *v, int purpose) {
- if (K_X509_STORE_CTX_set_purpose) (K_X509_STORE_CTX_set_purpose)(v,purpose);
-}
-
-
-STACK* KOpenSSLProxy::sk_dup(STACK *s) {
- if (K_sk_dup) return (K_sk_dup)(s);
- else return 0L;
-}
-
-
-STACK* KOpenSSLProxy::sk_new(int (*cmp)()) {
- if (K_sk_new) return (K_sk_new)(cmp);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::sk_push(STACK* s, char* d) {
- if (K_sk_push) return (K_sk_push)(s,d);
- else return -1;
-}
-
-
-char *KOpenSSLProxy::i2s_ASN1_INTEGER(X509V3_EXT_METHOD *meth, ASN1_INTEGER *aint) {
- if (K_i2s_ASN1_INTEGER) return (K_i2s_ASN1_INTEGER)(meth, aint);
- else return 0L;
-}
-
-
-ASN1_INTEGER *KOpenSSLProxy::X509_get_serialNumber(X509 *x) {
- if (K_X509_get_serialNumber) return (K_X509_get_serialNumber)(x);
- else return 0L;
-}
-
-
-EVP_PKEY *KOpenSSLProxy::X509_get_pubkey(X509 *x) {
- if (K_X509_get_pubkey) return (K_X509_get_pubkey)(x);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::i2d_PublicKey(EVP_PKEY *a, unsigned char **pp) {
- if (K_i2d_PublicKey) return (K_i2d_PublicKey)(a,pp);
- else return 0;
-}
-
-
-int KOpenSSLProxy::X509_check_private_key(X509 *x, EVP_PKEY *p) {
- if (K_X509_check_private_key) return (K_X509_check_private_key)(x,p);
- return -1;
-}
-
-
-char *KOpenSSLProxy::BN_bn2hex(const BIGNUM *a) {
- if (K_BN_bn2hex) return (K_BN_bn2hex)(a);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::X509_digest(const X509 *x,const EVP_MD *t, unsigned char *md, unsigned int *len) {
- if (K_X509_digest) return (K_X509_digest)(x, t, md, len);
- else return -1;
-}
-
-
-EVP_MD *KOpenSSLProxy::EVP_md5() {
- if (K_EVP_md5) return (K_EVP_md5)();
- return 0L;
-}
-
-
-void KOpenSSLProxy::ASN1_INTEGER_free(ASN1_INTEGER *a) {
- if (K_ASN1_INTEGER_free) (K_ASN1_INTEGER_free)(a);
-}
-
-
-int KOpenSSLProxy::OBJ_obj2nid(ASN1_OBJECT *o) {
- if (K_OBJ_obj2nid) return (K_OBJ_obj2nid)(o);
- else return -1;
-}
-
-
-const char * KOpenSSLProxy::OBJ_nid2ln(int n) {
- if (K_OBJ_nid2ln) return (K_OBJ_nid2ln)(n);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::X509_get_ext_count(X509 *x) {
- if (K_X509_get_ext_count) return (K_X509_get_ext_count)(x);
- else return -1;
-}
-
-
-int KOpenSSLProxy::X509_get_ext_by_NID(X509 *x, int nid, int lastpos) {
- if (K_X509_get_ext_by_NID) return (K_X509_get_ext_by_NID)(x,nid,lastpos);
- else return -1;
-}
-
-
-int KOpenSSLProxy::X509_get_ext_by_OBJ(X509 *x,ASN1_OBJECT *obj,int lastpos) {
- if (K_X509_get_ext_by_OBJ) return (K_X509_get_ext_by_OBJ)(x,obj,lastpos);
- else return -1;
-}
-
-
-X509_EXTENSION *KOpenSSLProxy::X509_get_ext(X509 *x, int loc) {
- if (K_X509_get_ext) return (K_X509_get_ext)(x,loc);
- else return 0L;
-}
-
-
-X509_EXTENSION *KOpenSSLProxy::X509_delete_ext(X509 *x, int loc) {
- if (K_X509_delete_ext) return (K_X509_delete_ext)(x,loc);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc) {
- if (K_X509_add_ext) return (K_X509_add_ext)(x,ex,loc);
- else return -1;
-}
-
-
-void *KOpenSSLProxy::X509_get_ext_d2i(X509 *x, int nid, int *crit, int *idx) {
- if (K_X509_get_ext_d2i) return (K_X509_get_ext_d2i)(x,nid,crit,idx);
- else return 0L;
-}
-
-
-char *KOpenSSLProxy::i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, ASN1_OCTET_STRING *ia5) {
- if (K_i2s_ASN1_OCTET_STRING) return (K_i2s_ASN1_OCTET_STRING)(method,ia5);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n) {
- if (K_ASN1_BIT_STRING_get_bit) return (K_ASN1_BIT_STRING_get_bit)(a,n);
- else return -1;
-}
-
-
-PKCS7 *KOpenSSLProxy::PKCS7_new(void) {
- if (K_PKCS7_new) return (K_PKCS7_new)();
- else return 0L;
-}
-
-
-void KOpenSSLProxy::PKCS7_free(PKCS7 *a) {
- if (K_PKCS7_free) (K_PKCS7_free)(a);
-}
-
-
-void KOpenSSLProxy::PKCS7_content_free(PKCS7 *a) {
- if (K_PKCS7_content_free) (K_PKCS7_content_free)(a);
-}
-
-
-int KOpenSSLProxy::i2d_PKCS7(PKCS7 *a, unsigned char **pp) {
- if (K_i2d_PKCS7) return (K_i2d_PKCS7)(a,pp);
- else return -1;
-}
-
-
-PKCS7 *KOpenSSLProxy::d2i_PKCS7(PKCS7 **a, unsigned char **pp,long length) {
- if (K_d2i_PKCS7) return (K_d2i_PKCS7)(a,pp,length);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::i2d_PKCS7_fp(FILE *fp,PKCS7 *p7) {
- if (K_i2d_PKCS7_fp) return (K_i2d_PKCS7_fp)(fp,p7);
- else return -1;
-}
-
-
-PKCS7 *KOpenSSLProxy::d2i_PKCS7_fp(FILE *fp,PKCS7 **p7) {
- if (K_d2i_PKCS7_fp) return (K_d2i_PKCS7_fp)(fp,p7);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::i2d_PKCS7_bio(BIO *bp,PKCS7 *p7) {
- if (K_i2d_PKCS7_bio) return (K_i2d_PKCS7_bio)(bp, p7);
- else return -1;
-}
-
-
-PKCS7 *KOpenSSLProxy::d2i_PKCS7_bio(BIO *bp,PKCS7 **p7) {
- if (K_d2i_PKCS7_bio) return (K_d2i_PKCS7_bio)(bp, p7);
- else return 0L;
-}
-
-
-PKCS7 *KOpenSSLProxy::PKCS7_dup(PKCS7 *p7) {
- if (K_PKCS7_dup) return (K_PKCS7_dup)(p7);
- else return 0L;
-}
-
-
-PKCS7 *KOpenSSLProxy::PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
- BIO *data, int flags) {
- if (K_PKCS7_sign) return (K_PKCS7_sign)(signcert,pkey,certs,data,flags);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::PKCS7_verify(PKCS7* p, STACK_OF(X509)* st, X509_STORE* s, BIO* in, BIO *out, int flags) {
- if (K_PKCS7_verify) return (K_PKCS7_verify)(p,st,s,in,out,flags);
- else return 0;
-}
-
-
-STACK_OF(X509) *KOpenSSLProxy::PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs, int flags) {
- if (K_PKCS7_get0_signers) return (K_PKCS7_get0_signers)(p7,certs,flags);
- else return 0L;
-}
-
-
-PKCS7 *KOpenSSLProxy::PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, EVP_CIPHER *cipher,
- int flags) {
- if (K_PKCS7_encrypt) return (K_PKCS7_encrypt)(certs,in,cipher,flags);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data, int flags) {
- if (K_PKCS7_decrypt) return (K_PKCS7_decrypt)(p7,pkey,cert,data,flags);
- else return 0;
-}
-
-
-STACK_OF(X509_NAME) *KOpenSSLProxy::SSL_load_client_CA_file(const char *file) {
- if (K_SSL_load_client_CA_file) return (K_SSL_load_client_CA_file)(file);
- else return 0L;
-}
-
-
-STACK_OF(X509_INFO) *KOpenSSLProxy::PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u) {
- if (K_PEM_X509_INFO_read) return (K_PEM_X509_INFO_read)(fp,sk,cb,u);
- else return 0L;
-}
-
-
-X509 *KOpenSSLProxy::X509_d2i_fp(FILE *out, X509** buf) {
- if (K_ASN1_d2i_fp) return reinterpret_cast<X509 *>((K_ASN1_d2i_fp)(reinterpret_cast<char *(*)()>(K_X509_new), reinterpret_cast<char *(*)()>(K_d2i_X509), out, reinterpret_cast<unsigned char **>(buf)));
- else return 0L;
-}
-
-
-int KOpenSSLProxy::SSL_peek(SSL *ssl,void *buf,int num) {
- if (K_SSL_peek) return (K_SSL_peek)(ssl,buf,num);
- else return -1;
-}
-
-
-const char *KOpenSSLProxy::RAND_file_name(char *buf, size_t num) {
- if (K_RAND_file_name) return (K_RAND_file_name)(buf, num);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::RAND_load_file(const char *filename, long max_bytes) {
- if (K_RAND_load_file) return (K_RAND_load_file)(filename, max_bytes);
- else return -1;
-}
-
-
-int KOpenSSLProxy::RAND_write_file(const char *filename) {
- if (K_RAND_write_file) return (K_RAND_write_file)(filename);
- else return -1;
-}
-
-
-int KOpenSSLProxy::X509_PURPOSE_get_count() {
- if (K_X509_PURPOSE_get_count) return (K_X509_PURPOSE_get_count)();
- else return -1;
-}
-
-
-int KOpenSSLProxy::X509_PURPOSE_get_id(X509_PURPOSE *p) {
- if (K_X509_PURPOSE_get_id) return (K_X509_PURPOSE_get_id)(p);
- else return -1;
-}
-
-
-int KOpenSSLProxy::X509_check_purpose(X509 *x, int id, int ca) {
- if (K_X509_check_purpose) return (K_X509_check_purpose)(x, id, ca);
- else return -1;
-}
-
-
-X509_PURPOSE *KOpenSSLProxy::X509_PURPOSE_get0(int idx) {
- if (K_X509_PURPOSE_get0) return (K_X509_PURPOSE_get0)(idx);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::EVP_PKEY_assign(EVP_PKEY *pkey, int type, char *key) {
- if (K_EVP_PKEY_assign) return (K_EVP_PKEY_assign)(pkey, type, key);
- else return -1;
-}
-
-
-int KOpenSSLProxy::X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey) {
- if (K_X509_REQ_set_pubkey) return (K_X509_REQ_set_pubkey)(x, pkey);
- else return -1;
-}
-
-
-RSA* KOpenSSLProxy::RSA_generate_key(int bits, unsigned long e, void
- (*callback)(int,int,void *), void *cb_arg) {
- if (K_RSA_generate_key) return (K_RSA_generate_key)(bits, e, callback, cb_arg);
- else return 0L;
-}
-
-STACK *KOpenSSLProxy::X509_get1_email(X509 *x) {
- if (K_X509_get1_email) return (K_X509_get1_email)(x);
- else return 0L;
-}
-
-void KOpenSSLProxy::X509_email_free(STACK *sk) {
- if (K_X509_email_free) (K_X509_email_free)(sk);
-}
-
-EVP_CIPHER *KOpenSSLProxy::EVP_des_ede3_cbc() {
- if (K_EVP_des_ede3_cbc) return (K_EVP_des_ede3_cbc)();
- else return 0L;
-}
-
-EVP_CIPHER *KOpenSSLProxy::EVP_des_cbc() {
- if (K_EVP_des_cbc) return (K_EVP_des_cbc)();
- else return 0L;
-}
-
-EVP_CIPHER *KOpenSSLProxy::EVP_rc2_cbc() {
- if (K_EVP_rc2_cbc) return (K_EVP_rc2_cbc)();
- else return 0L;
-}
-
-EVP_CIPHER *KOpenSSLProxy::EVP_rc2_64_cbc() {
- if (K_EVP_rc2_64_cbc) return (K_EVP_rc2_64_cbc)();
- else return 0L;
-}
-
-EVP_CIPHER *KOpenSSLProxy::EVP_rc2_40_cbc() {
- if (K_EVP_rc2_40_cbc) return (K_EVP_rc2_40_cbc)();
- else return 0L;
-}
-
-int KOpenSSLProxy::i2d_X509_REQ_fp(FILE *fp, X509_REQ *x) {
- if (K_i2d_X509_REQ_fp) return (K_i2d_X509_REQ_fp)(fp,x);
- else return -1;
-}
-
-
-void KOpenSSLProxy::ERR_clear_error() {
- if (K_ERR_clear_error) (K_ERR_clear_error)();
-}
-
-
-unsigned long KOpenSSLProxy::ERR_get_error() {
- if (K_ERR_get_error) return (K_ERR_get_error)();
- else return 0xffffffff;
-}
-
-
-void KOpenSSLProxy::ERR_print_errors_fp(FILE* fp) {
- if (K_ERR_print_errors_fp) (K_ERR_print_errors_fp)(fp);
-}
-
-
-SSL_SESSION *KOpenSSLProxy::SSL_get1_session(SSL *ssl) {
- if (K_SSL_get1_session) return (K_SSL_get1_session)(ssl);
- else return 0L;
-}
-
-
-void KOpenSSLProxy::SSL_SESSION_free(SSL_SESSION *session) {
- if (K_SSL_SESSION_free) (K_SSL_SESSION_free)(session);
-}
-
-
-int KOpenSSLProxy::SSL_set_session(SSL *ssl, SSL_SESSION *session) {
- if (K_SSL_set_session) return (K_SSL_set_session)(ssl, session);
- else return -1;
-}
-
-
-SSL_SESSION *KOpenSSLProxy::d2i_SSL_SESSION(SSL_SESSION **a, unsigned char **pp, long length) {
- if (K_d2i_SSL_SESSION) return (K_d2i_SSL_SESSION)(a, pp, length);
- else return 0L;
-}
-
-
-int KOpenSSLProxy::i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp) {
- if (K_i2d_SSL_SESSION) return (K_i2d_SSL_SESSION)(in, pp);
- else return -1;
-}
-
-
-int KOpenSSLProxy::i2d_PrivateKey_fp(FILE *fp, EVP_PKEY *p) {
- if (K_i2d_PrivateKey_fp) return (K_i2d_PrivateKey_fp)(fp, p);
- else return -1;
-}
-
-
-int KOpenSSLProxy::i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *p, const EVP_CIPHER *c, char *k, int klen, pem_password_cb *cb, void *u) {
- if (K_i2d_PKCS8PrivateKey_fp) return (K_i2d_PKCS8PrivateKey_fp)(fp, p, c, k, klen, cb, u);
- else return -1;
-}
-
-
-void KOpenSSLProxy::RSA_free(RSA *rsa) {
- if (K_RSA_free) (K_RSA_free)(rsa);
-}
-
-
-EVP_CIPHER *KOpenSSLProxy::EVP_bf_cbc() {
- if (K_EVP_bf_cbc) return (K_EVP_bf_cbc)();
- return 0L;
-}
-
-
-int KOpenSSLProxy::X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md) {
- if (K_X509_REQ_sign) return (K_X509_REQ_sign)(x, pkey, md);
- return -1;
-}
-
-
-int KOpenSSLProxy::X509_NAME_add_entry_by_txt(X509_NAME *name, char *field,
- int type, unsigned char *bytes, int len, int loc, int set) {
- if (K_X509_NAME_add_entry_by_txt) return (K_X509_NAME_add_entry_by_txt)(name, field, type, bytes, len, loc, set);
- return -1;
-}
-
-
-X509_NAME *KOpenSSLProxy::X509_NAME_new() {
- if (K_X509_NAME_new) return (K_X509_NAME_new)();
- return 0L;
-}
-
-
-int KOpenSSLProxy::X509_REQ_set_subject_name(X509_REQ *req,X509_NAME *name) {
- if (K_X509_REQ_set_subject_name) return (K_X509_REQ_set_subject_name)(req, name);
- return -1;
-}
-
-
-unsigned char *KOpenSSLProxy::ASN1_STRING_data(ASN1_STRING *x) {
- if (K_ASN1_STRING_data) return (K_ASN1_STRING_data)(x);
- return 0L;
-}
-
-int KOpenSSLProxy::ASN1_STRING_length(ASN1_STRING *x) {
- if (K_ASN1_STRING_length) return (K_ASN1_STRING_length)(x);
- return 0L;
-}
-
-STACK_OF(SSL_CIPHER) *KOpenSSLProxy::SSL_get_ciphers(const SSL* ssl) {
- if (K_SSL_get_ciphers) return (K_SSL_get_ciphers)(ssl);
- return 0L;
-}
-
-#endif
-
diff --git a/kio/kssl/kssl/HOWTO b/kio/kssl/kssl/HOWTO
deleted file mode 100644
index 9a74e418b..000000000
--- a/kio/kssl/kssl/HOWTO
+++ /dev/null
@@ -1,30 +0,0 @@
-
-NOTE: If you want to add a root file, please contact kde-core-devel and the
-maintainer (currently bradh@kde.org) with full details.
-
-
-1) Build cert_extract
-2) Make a directory 'certtmp'
-3) cd 'certtmp'
-4) Run ../cert_extract /path/to/netscape/cert7.db
- This will create many files and an index
-5) Remove the TrustCenter level 0 certificate.
-6) Merge these files into a bundle with:
- ../cert_bundle /path/to/netscape/cert7.db cert.index ../caroot/ca-bundle.crt
-7) Merge these files into a KDE config file with:
- ../certkde
-8) mv ksslcalist ../
-9) Merge in the local certs that we added ourselves with:
- cd ..
- ./mergelocal
-10) *Do your diffs*! Make *sure* you commit what you think you are committing.
-11) svn commit
-
-
-
-
-To add local files:
-1) Create the .pem file and check it into cvs in tdelibs/kio/kssl/kssl.
-2) List the pem file name as a single line in 'localcerts'.
-
-
diff --git a/kio/kssl/ksslinfodlg.cc b/kio/kssl/ksslinfodlg.cc
deleted file mode 100644
index c6f76a190..000000000
--- a/kio/kssl/ksslinfodlg.cc
+++ /dev/null
@@ -1,463 +0,0 @@
-/* This file is part of the KDE project
- *
- * Copyright (C) 2000,2001 George Staikos <staikos@kde.org>
- * Copyright (C) 2000 Malte Starostik <malte@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "ksslinfodlg.h"
-
-#include <kssl.h>
-
-#include <tqlayout.h>
-#include <kpushbutton.h>
-#include <tqframe.h>
-#include <tqlabel.h>
-#include <tqscrollview.h>
-#include <tqfile.h>
-
-#include <kapplication.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kprocess.h>
-#include <kiconloader.h>
-#include <kglobalsettings.h>
-#include <ksqueezedtextlabel.h>
-#include <kurllabel.h>
-#include <kstdguiitem.h>
-//#include <kstandarddirs.h>
-//#include <krun.h>
-#include <kcombobox.h>
-#include "ksslcertificate.h"
-#include "ksslcertchain.h"
-#include "ksslsigners.h"
-
-
-class KSSLInfoDlg::KSSLInfoDlgPrivate {
- private:
- friend class KSSLInfoDlg;
- bool m_secCon;
- TQGridLayout *m_layout;
- KComboBox *_chain;
- KSSLCertificate *_cert;
- KSSLCertificate::KSSLValidationList _cert_ksvl;
-
- bool inQuestion;
-
- TQLabel *_serialNum;
- TQLabel *_csl;
- TQLabel *_validFrom;
- TQLabel *_validUntil;
- TQLabel *_digest;
-
- TQLabel *pixmap;
- TQLabel *info;
-
- KSSLCertBox *_subject, *_issuer;
-};
-
-
-
-KSSLInfoDlg::KSSLInfoDlg(bool secureConnection, TQWidget *parent, const char *name, bool modal)
- : KDialog(parent, name, modal, (WFlags)TQt::WDestructiveClose), d(new KSSLInfoDlgPrivate) {
- TQVBoxLayout *topLayout = new TQVBoxLayout(this, KDialog::marginHint(), KDialog::spacingHint());
- d->m_secCon = secureConnection;
- d->m_layout = new TQGridLayout(topLayout, 3, 3, KDialog::spacingHint());
- d->m_layout->setColStretch(1, 1);
- d->m_layout->setColStretch(2, 1);
-
- d->pixmap = new TQLabel(this);
- d->m_layout->addWidget(d->pixmap, 0, 0);
-
- d->info = new TQLabel(this);
- d->m_layout->addWidget(d->info, 0, 1);
-
- if (KSSL::doesSSLWork()) {
- if (d->m_secCon) {
- d->pixmap->setPixmap(BarIcon("encrypted"));
- d->info->setText(i18n("Current connection is secured with SSL."));
- } else {
- d->pixmap->setPixmap(BarIcon("decrypted"));
- d->info->setText(i18n("Current connection is not secured with SSL."));
- }
- } else {
- d->pixmap->setPixmap(BarIcon("decrypted"));
- d->info->setText(i18n("SSL support is not available in this build of TDE."));
- }
- d->m_layout->addRowSpacing( 0, 50 ); // give minimum height to look better
-
- TQHBoxLayout *buttonLayout = new TQHBoxLayout(topLayout, KDialog::spacingHint());
- buttonLayout->addStretch( 1 );
-
- KPushButton *button;
-
- if (KSSL::doesSSLWork()) {
- button = new KPushButton(KGuiItem(i18n("C&ryptography Configuration..."),"configure"), this);
- connect(button, TQT_SIGNAL(clicked()), TQT_SLOT(launchConfig()));
- buttonLayout->addWidget( button );
- }
-
- button = new KPushButton(KStdGuiItem::close(), this);
- connect(button, TQT_SIGNAL(clicked()), TQT_SLOT(close()));
- buttonLayout->addWidget( button );
-
- button->setFocus();
-
- setCaption(i18n("TDE SSL Information"));
- d->inQuestion = false;
- }
-
-
-KSSLInfoDlg::~KSSLInfoDlg() {
- delete d;
-}
-
-void KSSLInfoDlg::launchConfig() {
- TDEProcess p;
- p << "kcmshell" << "crypto";
- p.start(TDEProcess::DontCare);
-}
-
-
-void KSSLInfoDlg::setSecurityInQuestion(bool isIt) {
- d->inQuestion = isIt;
- if (KSSL::doesSSLWork())
- if (isIt) {
- d->pixmap->setPixmap(BarIcon("halfencrypted"));
- if (d->m_secCon) {
- d->info->setText(i18n("The main part of this document is secured with SSL, but some parts are not."));
- } else {
- d->info->setText(i18n("Some of this document is secured with SSL, but the main part is not."));
- }
- } else {
- if (d->m_secCon) {
- d->pixmap->setPixmap(BarIcon("encrypted"));
- d->info->setText(i18n("Current connection is secured with SSL."));
- } else {
- d->pixmap->setPixmap(BarIcon("decrypted"));
- d->info->setText(i18n("Current connection is not secured with SSL."));
- }
- }
-}
-
-
-void KSSLInfoDlg::setup( KSSL & ssl, const TQString & ip, const TQString & url )
-{
- setup(
- &ssl.peerInfo().getPeerCertificate(),
- ip,
- url,
- ssl.connectionInfo().getCipher(),
- ssl.connectionInfo().getCipherDescription(),
- ssl.connectionInfo().getCipherVersion(),
- ssl.connectionInfo().getCipherUsedBits(),
- ssl.connectionInfo().getCipherBits(),
- ssl.peerInfo().getPeerCertificate().validate()
- );
-}
-
-void KSSLInfoDlg::setup(KSSLCertificate *cert,
- const TQString& ip, const TQString& url,
- const TQString& cipher, const TQString& cipherdesc,
- const TQString& sslversion, int usedbits, int bits,
- KSSLCertificate::KSSLValidation /*certState*/) {
- // Needed to put the GUI stuff here to get the layouting right
-
- d->_cert = cert;
-
- TQGridLayout *layout = new TQGridLayout(4, 2, KDialog::spacingHint());
-
- layout->addWidget(new TQLabel(i18n("Chain:"), this), 0, 0);
- d->_chain = new KComboBox(this);
- layout->addMultiCellWidget(d->_chain, 1, 1, 0, 1);
- connect(d->_chain, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotChain(int)));
-
- d->_chain->clear();
-
- if (cert->chain().isValid() && cert->chain().depth() > 1) {
- d->_chain->setEnabled(true);
- d->_chain->insertItem(i18n("0 - Site Certificate"));
- int cnt = 0;
- TQPtrList<KSSLCertificate> cl = cert->chain().getChain();
- cl.setAutoDelete(true);
- for (KSSLCertificate *c = cl.first(); c != 0; c = cl.next()) {
- KSSLX509Map map(c->getSubject());
- TQString id;
- id = map.getValue("CN");
- if (id.length() == 0)
- id = map.getValue("O");
- if (id.length() == 0)
- id = map.getValue("OU");
- d->_chain->insertItem(TQString::number(++cnt)+" - "+id);
- }
- d->_chain->setCurrentItem(0);
- } else d->_chain->setEnabled(false);
-
- layout->addWidget(new TQLabel(i18n("Peer certificate:"), this), 2, 0);
- layout->addWidget(d->_subject = static_cast<KSSLCertBox*>(buildCertInfo(cert->getSubject())), 3, 0);
- layout->addWidget(new TQLabel(i18n("Issuer:"), this), 2, 1);
- layout->addWidget(d->_issuer = static_cast<KSSLCertBox*>(buildCertInfo(cert->getIssuer())), 3, 1);
- d->m_layout->addMultiCell(layout, 1, 1, 0, 2);
-
- layout = new TQGridLayout(11, 2, KDialog::spacingHint());
- layout->setColStretch(1, 1);
- TQLabel *ipl = new TQLabel(i18n("IP address:"), this);
- layout->addWidget(ipl, 0, 0);
- if (ip.isEmpty()) {
- ipl->hide();
- }
- layout->addWidget(ipl = new TQLabel(ip, this), 0, 1);
- if (ip.isEmpty()) {
- ipl->hide();
- }
- layout->addWidget(new TQLabel(i18n("URL:"), this), 1, 0);
- KSqueezedTextLabel *urlLabel = new KSqueezedTextLabel(url, this);
- layout->addWidget(urlLabel, 1, 1);
- layout->addWidget(new TQLabel(i18n("Certificate state:"), this), 2, 0);
-
- layout->addWidget(d->_csl = new TQLabel("", this), 2, 1);
-
- update();
-
- layout->addWidget(new TQLabel(i18n("Valid from:"), this), 3, 0);
- layout->addWidget(d->_validFrom = new TQLabel("", this), 3, 1);
- layout->addWidget(new TQLabel(i18n("Valid until:"), this), 4, 0);
- layout->addWidget(d->_validUntil = new TQLabel("", this), 4, 1);
-
- layout->addWidget(new TQLabel(i18n("Serial number:"), this), 5, 0);
- layout->addWidget(d->_serialNum = new TQLabel("", this), 5, 1);
- layout->addWidget(new TQLabel(i18n("MD5 digest:"), this), 6, 0);
- layout->addWidget(d->_digest = new TQLabel("", this), 6, 1);
-
- layout->addWidget(new TQLabel(i18n("Cipher in use:"), this), 7, 0);
- layout->addWidget(new TQLabel(cipher, this), 7, 1);
- layout->addWidget(new TQLabel(i18n("Details:"), this), 8, 0);
- layout->addWidget(new TQLabel(cipherdesc.simplifyWhiteSpace(), this), 8, 1);
- layout->addWidget(new TQLabel(i18n("SSL version:"), this), 9, 0);
- layout->addWidget(new TQLabel(sslversion, this), 9, 1);
- layout->addWidget(new TQLabel(i18n("Cipher strength:"), this), 10, 0);
- layout->addWidget(new TQLabel(i18n("%1 bits used of a %2 bit cipher").arg(usedbits).arg(bits), this), 10, 1);
- d->m_layout->addMultiCell(layout, 2, 2, 0, 2);
-
- displayCert(cert);
-}
-
-void KSSLInfoDlg::setCertState(const TQString &errorNrs)
-{
- d->_cert_ksvl.clear();
- TQStringList errors = TQStringList::split(':', errorNrs);
- for(TQStringList::ConstIterator it = errors.begin();
- it != errors.end(); ++it)
- {
- d->_cert_ksvl << (KSSLCertificate::KSSLValidation) (*it).toInt();
- }
-}
-
-void KSSLInfoDlg::displayCert(KSSLCertificate *x) {
- TQPalette cspl;
-
- d->_serialNum->setText(x->getSerialNumber());
-
- cspl = d->_validFrom->palette();
- if (x->getQDTNotBefore() > TQDateTime::currentDateTime(Qt::UTC))
- cspl.setColor(TQColorGroup::Foreground, TQColor(196,33,21));
- else cspl.setColor(TQColorGroup::Foreground, TQColor(42,153,59));
- d->_validFrom->setPalette(cspl);
- d->_validFrom->setText(x->getNotBefore());
-
- cspl = d->_validUntil->palette();
- if (x->getQDTNotAfter() < TQDateTime::currentDateTime(Qt::UTC))
- cspl.setColor(TQColorGroup::Foreground, TQColor(196,33,21));
- else cspl.setColor(TQColorGroup::Foreground, TQColor(42,153,59));
- d->_validUntil->setPalette(cspl);
- d->_validUntil->setText(x->getNotAfter());
-
- cspl = palette();
-
- KSSLCertificate::KSSLValidation ksv;
- KSSLCertificate::KSSLValidationList ksvl;
- if ((x == d->_cert) && !d->_cert_ksvl.isEmpty()) {
- ksvl = d->_cert_ksvl;
- ksv = ksvl.first();
- } else {
- if (x == d->_cert)
- ksvl = d->_cert->validateVerbose(KSSLCertificate::SSLServer);
- else
- ksvl = d->_cert->validateVerbose(KSSLCertificate::SSLServer, x);
-
- if (ksvl.isEmpty())
- ksvl << KSSLCertificate::Ok;
-
- ksv = ksvl.first();
-
- if (ksv == KSSLCertificate::SelfSigned) {
- if (x->getQDTNotAfter() > TQDateTime::currentDateTime(Qt::UTC) &&
- x->getQDTNotBefore() < TQDateTime::currentDateTime(Qt::UTC)) {
- if (KSSLSigners().useForSSL(*x))
- ksv = KSSLCertificate::Ok;
- } else {
- ksv = KSSLCertificate::Expired;
- }
- }
- }
-
- if (ksv == KSSLCertificate::Ok) {
- cspl.setColor(TQColorGroup::Foreground, TQColor(42,153,59));
- } else if (ksv != KSSLCertificate::Irrelevant) {
- cspl.setColor(TQColorGroup::Foreground, TQColor(196,33,21));
- }
- d->_csl->setPalette(cspl);
-
- TQString errorStr;
- for(KSSLCertificate::KSSLValidationList::ConstIterator it = ksvl.begin();
- it != ksvl.end(); ++it) {
- if (!errorStr.isEmpty())
- errorStr.append('\n');
- errorStr += KSSLCertificate::verifyText(*it);
- }
-
- d->_csl->setText(errorStr);
- d->_csl->setMinimumSize(d->_csl->sizeHint());
-
- d->_subject->setValues(x->getSubject());
- d->_issuer->setValues(x->getIssuer());
-
- d->_digest->setText(x->getMD5DigestText());
-}
-
-
-void KSSLInfoDlg::slotChain(int x) {
- if (x == 0) {
- displayCert(d->_cert);
- } else {
- TQPtrList<KSSLCertificate> cl = d->_cert->chain().getChain();
- cl.setAutoDelete(true);
- for (int i = 0; i < x-1; i++)
- cl.remove((unsigned int)0);
- KSSLCertificate thisCert = *(cl.at(0));
- cl.remove((unsigned int)0);
- thisCert.chain().setChain(cl);
- displayCert(&thisCert);
- }
-}
-
-
-KSSLCertBox *KSSLInfoDlg::certInfoWidget(TQWidget *parent, const TQString &certName, TQWidget *mailCatcher) {
- KSSLCertBox *result = new KSSLCertBox(parent);
- if (!certName.isEmpty()) {
- result->setValues(certName, mailCatcher);
- }
- return result;
-}
-
-
-KSSLCertBox::KSSLCertBox(TQWidget *parent, const char *name, WFlags f)
-: TQScrollView(parent, name, f)
-{
- _frame = 0L;
- setBackgroundMode(TQWidget::PaletteButton);
- setValues(TQString::null, 0L);
-}
-
-
-void KSSLCertBox::setValues(TQString certName, TQWidget *mailCatcher) {
- if (_frame) {
- removeChild(_frame);
- delete _frame;
- }
-
- if (certName.isEmpty()) {
- _frame = new TQFrame(this);
- addChild(_frame);
- viewport()->setBackgroundMode(_frame->backgroundMode());
- _frame->show();
- updateScrollBars();
- show();
- return;
- }
-
- KSSLX509Map cert(certName);
- TQString tmp;
- viewport()->setBackgroundMode(TQWidget::PaletteButton);
- _frame = new TQFrame(this);
- TQGridLayout *grid = new TQGridLayout(_frame, 1, 2, KDialog::marginHint(), KDialog::spacingHint());
- grid->setAutoAdd(true);
- TQLabel *label = 0L;
- if (!(tmp = cert.getValue("O")).isEmpty()) {
- label = new TQLabel(i18n("Organization:"), _frame);
- label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- new TQLabel(tmp, _frame);
- }
- if (!(tmp = cert.getValue("OU")).isEmpty()) {
- label = new TQLabel(i18n("Organizational unit:"), _frame);
- label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- new TQLabel(tmp, _frame);
- }
- if (!(tmp = cert.getValue("L")).isEmpty()) {
- label = new TQLabel(i18n("Locality:"), _frame);
- label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- new TQLabel(tmp, _frame);
- }
- if (!(tmp = cert.getValue("ST")).isEmpty()) {
- label = new TQLabel(i18n("Federal State","State:"), _frame);
- label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- new TQLabel(tmp, _frame);
- }
- if (!(tmp = cert.getValue("C")).isEmpty()) {
- label = new TQLabel(i18n("Country:"), _frame);
- label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- new TQLabel(tmp, _frame);
- }
- if (!(tmp = cert.getValue("CN")).isEmpty()) {
- label = new TQLabel(i18n("Common name:"), _frame);
- label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- new TQLabel(tmp, _frame);
- }
- if (!(tmp = cert.getValue("Email")).isEmpty()) {
- label = new TQLabel(i18n("Email:"), _frame);
- label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- if (mailCatcher) {
- KURLLabel *mail = new KURLLabel(tmp, tmp, _frame);
- connect(mail, TQT_SIGNAL(leftClickedURL(const TQString &)), mailCatcher, TQT_SLOT(mailClicked(const TQString &)));
- } else {
- label = new TQLabel(tmp, _frame);
- }
- }
- if (label && viewport()) {
- viewport()->setBackgroundMode(label->backgroundMode());
- }
- addChild(_frame);
- updateScrollBars();
- _frame->show();
- show();
-}
-
-
-TQScrollView *KSSLInfoDlg::buildCertInfo(const TQString &certName) {
- return KSSLInfoDlg::certInfoWidget(this, certName, this);
-}
-
-void KSSLInfoDlg::urlClicked(const TQString &url) {
- kapp->invokeBrowser(url);
-}
-
-void KSSLInfoDlg::mailClicked(const TQString &url) {
- kapp->invokeMailer(url, TQString::null);
-}
-
-#include "ksslinfodlg.moc"
-// vim: ts=4 sw=4 et
diff --git a/kio/kssl/ksslkeygen.cc b/kio/kssl/ksslkeygen.cc
deleted file mode 100644
index 403632b3a..000000000
--- a/kio/kssl/ksslkeygen.cc
+++ /dev/null
@@ -1,223 +0,0 @@
-/* This file is part of the KDE project
- *
- * Copyright (C) 2001 George Staikos <staikos@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-
-#include "ksslkeygen.h"
-#include "keygenwizard.h"
-#include "keygenwizard2.h"
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <kopenssl.h>
-#include <kprogress.h>
-#include <kstandarddirs.h>
-#include <ktempfile.h>
-#include <tdewallet.h>
-
-#include <tqlineedit.h>
-#include <tqpushbutton.h>
-
-#include <assert.h>
-
-
-KSSLKeyGen::KSSLKeyGen(TQWidget *parent, const char *name, bool modal)
-:KWizard(parent,name,modal) {
- _idx = -1;
-
-#ifdef KSSL_HAVE_SSL
- page1 = new KGWizardPage1(this, "Wizard Page 1");
- addPage(page1, i18n("TDE Certificate Request"));
- page2 = new KGWizardPage2(this, "Wizard Page 2");
- addPage(page2, i18n("TDE Certificate Request - Password"));
- setHelpEnabled(page1, false);
- setHelpEnabled(page2, false);
- setFinishEnabled(page2, false);
- connect(page2->_password1, TQT_SIGNAL(textChanged(const TQString&)), this, TQT_SLOT(slotPassChanged()));
- connect(page2->_password2, TQT_SIGNAL(textChanged(const TQString&)), this, TQT_SLOT(slotPassChanged()));
- connect(finishButton(), TQT_SIGNAL(clicked()), TQT_SLOT(slotGenerate()));
-#else
- // tell him he doesn't have SSL
-#endif
-}
-
-
-KSSLKeyGen::~KSSLKeyGen() {
-
-}
-
-
-void KSSLKeyGen::slotPassChanged() {
- setFinishEnabled(page2, page2->_password1->text() == page2->_password2->text() && page2->_password1->text().length() >= 4);
-}
-
-
-void KSSLKeyGen::slotGenerate() {
- assert(_idx >= 0 && _idx <= 3); // for now
-
-
- // Generate the CSR
- int bits;
- switch (_idx) {
- case 0:
- bits = 2048;
- break;
- case 1:
- bits = 1024;
- break;
- case 2:
- bits = 768;
- break;
- case 3:
- bits = 512;
- break;
- default:
- KMessageBox::sorry(NULL, i18n("Unsupported key size."), i18n("TDE SSL Information"));
- return;
- }
-
- KProgressDialog *kpd = new KProgressDialog(this, "progress dialog", i18n("TDE"), i18n("Please wait while the encryption keys are generated..."));
- kpd->progressBar()->setProgress(0);
- kpd->show();
- // FIXME - progress dialog won't show this way
-
- int rc = generateCSR("This CSR" /*FIXME */, page2->_password1->text(), bits, 0x10001 /* This is the traditional exponent used */);
- kpd->progressBar()->setProgress(100);
-
-#ifndef Q_OS_WIN //TODO: reenable for WIN32
- if (rc == 0 && KWallet::Wallet::isEnabled()) {
- rc = KMessageBox::questionYesNo(this, i18n("Do you wish to store the passphrase in your wallet file?"), TQString::null, i18n("Store"), i18n("Do Not Store"));
- if (rc == KMessageBox::Yes) {
- KWallet::Wallet *w = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), winId());
- if (w) {
- // FIXME: store passphrase in wallet
- delete w;
- }
- }
- }
-#endif
-
- kpd->deleteLater();
-}
-
-
-int KSSLKeyGen::generateCSR(const TQString& name, const TQString& pass, int bits, int e) {
-#ifdef KSSL_HAVE_SSL
- KOSSL *kossl = KOSSL::self();
- int rc;
-
- X509_REQ *req = kossl->X509_REQ_new();
- if (!req) {
- return -2;
- }
-
- EVP_PKEY *pkey = kossl->EVP_PKEY_new();
- if (!pkey) {
- kossl->X509_REQ_free(req);
- return -4;
- }
-
- RSA *rsakey = kossl->RSA_generate_key(bits, e, NULL, NULL);
- if (!rsakey) {
- kossl->X509_REQ_free(req);
- kossl->EVP_PKEY_free(pkey);
- return -3;
- }
-
- rc = kossl->EVP_PKEY_assign(pkey, EVP_PKEY_RSA, (char *)rsakey);
-
- rc = kossl->X509_REQ_set_pubkey(req, pkey);
-
- // Set the subject
- X509_NAME *n = kossl->X509_NAME_new();
-
- kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_countryName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
- kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_organizationName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
- kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_organizationalUnitName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
- kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_localityName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
- kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_stateOrProvinceName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
- kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_commonName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
- kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_pkcs9_emailAddress, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
-
- rc = kossl->X509_REQ_set_subject_name(req, n);
-
-
- rc = kossl->X509_REQ_sign(req, pkey, kossl->EVP_md5());
-
- // We write it to the database and then the caller can obtain it
- // back from there. Yes it's inefficient, but it doesn't happen
- // often and this way things are uniform.
-
- TDEGlobal::dirs()->addResourceType("kssl", KStandardDirs::kde_default("data") + "kssl");
-
- TQString path = TDEGlobal::dirs()->saveLocation("kssl");
- KTempFile csrFile(path + "csr_", ".der");
-
- if (!csrFile.fstream()) {
- kossl->X509_REQ_free(req);
- kossl->EVP_PKEY_free(pkey);
- return -5;
- }
-
- KTempFile p8File(path + "pkey_", ".p8");
-
- if (!p8File.fstream()) {
- kossl->X509_REQ_free(req);
- kossl->EVP_PKEY_free(pkey);
- return -5;
- }
-
- kossl->i2d_X509_REQ_fp(csrFile.fstream(), req);
-
- kossl->i2d_PKCS8PrivateKey_fp(p8File.fstream(), pkey,
- kossl->EVP_bf_cbc(), pass.local8Bit().data(),
- pass.length(), 0L, 0L);
-
- // FIXME Write kconfig entry to store the filenames under the md5 hash
-
- kossl->X509_REQ_free(req);
- kossl->EVP_PKEY_free(pkey);
-
- return 0;
-#else
- return -1;
-#endif
-}
-
-
-TQStringList KSSLKeyGen::supportedKeySizes() {
- TQStringList x;
-
-#ifdef KSSL_HAVE_SSL
- x << i18n("2048 (High Grade)")
- << i18n("1024 (Medium Grade)")
- << i18n("768 (Low Grade)")
- << i18n("512 (Low Grade)");
-#else
- x << i18n("No SSL support.");
-#endif
-
- return x;
-}
-
-
-#include "ksslkeygen.moc"
-
diff --git a/kio/kssl/ksslsettings.h b/kio/kssl/ksslsettings.h
deleted file mode 100644
index 18dd31249..000000000
--- a/kio/kssl/ksslsettings.h
+++ /dev/null
@@ -1,224 +0,0 @@
-/* This file is part of the KDE project
- *
- * Copyright (C) 2000-2003 George Staikos <staikos@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef _KSSLSETTINGS_H
-#define _KSSLSETTINGS_H
-
-#include <tqstring.h>
-#include <tqvaluelist.h>
-#include <kconfig.h>
-
-class KSSLSettingsPrivate;
-
-/**
- * KDE SSL Settings
- *
- * This class contains some of the SSL settings for easy use.
- *
- * @author George Staikos <staikos@kde.org>
- * @see KSSL
- * @short KDE SSL Settings
- */
-class TDEIO_EXPORT KSSLSettings {
-public:
- /**
- * Construct a KSSL Settings object
- *
- * @param readConfig read in the configuration immediately if true
- */
- KSSLSettings(bool readConfig = true);
-
- /**
- * Destroy this KSSL Settings object
- */
- ~KSSLSettings();
-
- /**
- * Does the user allow SSLv2
- * @return true if the user allows SSLv2
- */
- bool sslv2() const;
-
- /**
- * Does the user allow SSLv3
- * @return true if the user allows SSLv3
- */
- bool sslv3() const;
-
- /**
- * Does the user allow TLSv1
- * @return true if the user allows TLSv1
- */
- bool tlsv1() const;
-
- /**
- * Does the user want to be warned on entering SSL mode
- * @return true if the user wants to be warned
- */
- bool warnOnEnter() const;
-
- /**
- * Change the user's warnOnEnter() setting
- * @since 3.3
- * @param x true if the user is to be warned
- * @see warnOnEnter
- */
- void setWarnOnEnter(bool x);
-
- /**
- * Does the user want to be warned on sending unencrypted data
- * @return true if the user wants to be warned
- * @see setWarnOnUnencrypted
- */
- bool warnOnUnencrypted() const;
-
- /**
- * Change the user's warnOnUnencrypted() setting
- * @param x true if the user is to be warned
- * @see warnOnUnencrypted
- */
- void setWarnOnUnencrypted(bool x);
-
- /**
- * Does the user want to be warned on leaving SSL mode
- * @return true if the user wants to be warned
- */
- bool warnOnLeave() const;
-
- /**
- * Change the user's warnOnLeave() setting
- * @since 3.3
- * @param x true if the user is to be warned
- * @see warnOnLeave
- */
- void setWarnOnLeave(bool x);
-
- /**
- * Does the user want to be warned during mixed SSL/non-SSL mode
- * @return true if the user wants to be warned
- */
- bool warnOnMixed() const;
-
- /**
- * Do not use this
- * @deprecated
- */
- bool warnOnSelfSigned() const KDE_DEPRECATED;
-
- /**
- * Do not use this
- * @deprecated
- */
- bool warnOnRevoked() const KDE_DEPRECATED;
-
- /**
- * Do not use this
- * @deprecated
- */
- bool warnOnExpired() const KDE_DEPRECATED;
-
- /**
- * Does the user want to use the Entropy Gathering Daemon?
- * @return true if the user wants to use EGD
- */
- bool useEGD() const;
-
- /**
- * Does the user want to use an entropy file?
- * @return true if the user wants to use an entropy file
- */
- bool useEFile() const;
-
- /**
- * Change the user's TLSv1 preference
- * @param enabled true if TLSv1 is enabled
- */
- void setTLSv1(bool enabled);
-
- /**
- * Change the user's SSLv2 preference
- * @param enabled true if SSLv2 is enabled
- */
- void setSSLv2(bool enabled);
-
- /**
- * Change the user's SSLv3 preference
- * @param enabled true if SSLv3 is enabled
- */
- void setSSLv3(bool enabled);
-
- /**
- * Does the user want X.509 client certificates to always be sent when
- * possible?
- * @return true if the user always wants a certificate sent
- */
- bool autoSendX509() const;
-
- /**
- * Does the user want to be prompted to send X.509 client certificates
- * when possible?
- * @return true if the user wants to be prompted
- */
- bool promptSendX509() const;
-
- /**
- * Get the OpenSSL cipher list for selecting the list of ciphers to
- * use in a connection.
- * @return the cipher list
- */
- TQString getCipherList();
-
- /**
- * Get the configured path to the entropy gathering daemon or entropy
- * file.
- * @return the path
- */
- TQString& getEGDPath();
-
- /**
- * Load the user's settings.
- */
- void load();
-
- /**
- * Revert to default settings.
- */
- void defaults();
-
- /**
- * Save the current settings.
- */
- void save();
-
-private:
- TDEConfig *m_cfg;
- bool m_bUseSSLv2, m_bUseSSLv3, m_bUseTLSv1;
- bool m_bWarnOnEnter, m_bWarnOnUnencrypted, m_bWarnOnLeave, m_bWarnOnMixed;
- bool m_bWarnSelfSigned, m_bWarnRevoked, m_bWarnExpired;
-
- TQValueList<TQString> v2ciphers, v2selectedciphers, v3ciphers, v3selectedciphers;
- TQValueList<int> v2bits, v3bits;
-
- KSSLSettingsPrivate *d;
-};
-
-
-#endif
-
diff --git a/kio/misc/CMakeLists.txt b/kio/misc/CMakeLists.txt
deleted file mode 100644
index 5212444a2..000000000
--- a/kio/misc/CMakeLists.txt
+++ /dev/null
@@ -1,100 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-add_subdirectory( ksendbugmail )
-add_subdirectory( kpac )
-add_subdirectory( tdesasl )
-add_subdirectory( kssld )
-add_subdirectory( kfile )
-add_subdirectory( tdewalletd )
-add_subdirectory( tdentlm )
-
-add_definitions(
- -D_LARGEFILE64_SOURCE
-)
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_BINARY_DIR}/kio
- ${CMAKE_BINARY_DIR}/kio/kio
- ${CMAKE_BINARY_DIR}/kio/kssl
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdefx
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kssl
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### headers ###################################
-
-install( FILES uiserver.h DESTINATION ${INCLUDE_INSTALL_DIR}/kio )
-
-
-##### other data ################################
-
-install(FILES
- kio_uiserver.desktop kmailservice.protocol
- telnet.protocol rlogin.protocol rtsp.protocol
- ssh.protocol mms.protocol mmst.protocol mmsu.protocol
- pnm.protocol rtspt.protocol rtspu.protocol
- DESTINATION ${SERVICES_INSTALL_DIR} )
-
-install( FILES fileshareset DESTINATION ${BIN_INSTALL_DIR}
- PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE SETUID )
-
-
-#### kio_uiserver ###############################
-
-set( target kio_uiserver )
-
-set( ${target}_SRCS
- uiserver.cpp uiserver.skel
-)
-
-tde_add_tdeinit_executable( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DEPENDENCIES dcopidl
-)
-
-
-##### kmailservice ##############################
-
-set( target kmailservice )
-
-tde_add_executable( ${target}
- SOURCES ${target}.cpp
- LINK tdecore-shared
- DESTINATION ${BIN_INSTALL_DIR}
-)
-
-
-##### ktelnetservice ############################
-
-set( target ktelnetservice )
-
-tde_add_executable( ${target}
- SOURCES ${target}.cpp
- LINK tdeui-shared
- DESTINATION ${BIN_INSTALL_DIR}
-)
-
-tde_install_symlink( ${target} ${BIN_INSTALL_DIR}/filesharelist )
diff --git a/kio/misc/Makefile.am b/kio/misc/Makefile.am
deleted file mode 100644
index 0bafce0f5..000000000
--- a/kio/misc/Makefile.am
+++ /dev/null
@@ -1,60 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 1997 Torben Weis (weis@kde.org)
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
-
-INCLUDES= -I$(srcdir)/.. -I$(top_srcdir) -I$(srcdir)/../kssl -I../kssl $(all_includes) $(SSL_INCLUDES)
-
-SUBDIRS = . ksendbugmail kpac tdesasl kssld kfile tdewalletd tdentlm
-
-lib_LTLIBRARIES =
-tdeinit_LTLIBRARIES = kio_uiserver.la
-bin_PROGRAMS = kmailservice ktelnetservice
-
-observer_DIR = $(top_srcdir)/kio/kio
-
-kio_uiserver_la_SOURCES = uiserver.cpp uiserver.skel observer.stub
-kio_uiserver_la_LIBADD = $(LIB_KIO) $(LIB_TDEUI) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE)
-kio_uiserver_la_LDFLAGS = $(all_libraries) -module -avoid-version
-
-METASOURCES = AUTO
-
-kde_services_DATA = kio_uiserver.desktop
-
-kmailservice_SOURCES = kmailservice.cpp
-kmailservice_LDADD = $(LIB_TDECORE)
-kmailservice_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-
-ktelnetservice_SOURCES = ktelnetservice.cpp
-ktelnetservice_LDADD = $(LIB_TDEUI)
-ktelnetservice_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-
-protocol_DATA = kmailservice.protocol telnet.protocol rlogin.protocol rtsp.protocol ssh.protocol \
- mms.protocol mmst.protocol mmsu.protocol pnm.protocol rtspt.protocol rtspu.protocol
-protocoldir = $(kde_servicesdir)
-
-kiomiscdir = $(includedir)/kio
-kiomisc_HEADERS = uiserver.h
-
-
-bin_SCRIPTS = fileshareset
-install-exec-local:
- @-rm -f $(DESTDIR)$(bindir)/filesharelist
- @$(LN_S) fileshareset $(DESTDIR)$(bindir)/filesharelist
- @(chown root $(DESTDIR)$(bindir)/fileshareset && chmod 4755 $(DESTDIR)$(bindir)/fileshareset) || echo "Was not able to make fileshareset setuid root"
-
diff --git a/kio/misc/kfile/CMakeLists.txt b/kio/misc/kfile/CMakeLists.txt
deleted file mode 100644
index 07c2725b2..000000000
--- a/kio/misc/kfile/CMakeLists.txt
+++ /dev/null
@@ -1,39 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### kfile #####################################
-
-set( target kfile )
-
-set( ${target}_SRCS
- fileprops.cpp
-)
-
-tde_add_executable( ${target}
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${BIN_INSTALL_DIR}
-) \ No newline at end of file
diff --git a/kio/misc/kfile/Makefile.am b/kio/misc/kfile/Makefile.am
deleted file mode 100644
index 605fef7d3..000000000
--- a/kio/misc/kfile/Makefile.am
+++ /dev/null
@@ -1,10 +0,0 @@
-METASOURCES = AUTO
-
-noinst_HEADERS = fileprops.h
-INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/kio/kio $(all_includes)
-
-bin_PROGRAMS = kfile
-kfile_SOURCES = fileprops.cpp
-kfile_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-kfile_LDADD = $(LIB_KIO)
-
diff --git a/kio/misc/kfile/fileprops.cpp b/kio/misc/kfile/fileprops.cpp
deleted file mode 100644
index bbd34a2a4..000000000
--- a/kio/misc/kfile/fileprops.cpp
+++ /dev/null
@@ -1,480 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation, version 2.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <iostream>
-
-#include <tqfile.h>
-#include <tqptrlist.h>
-
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kcmdlineargs.h>
-#include <kfilemetainfo.h>
-#include <klocale.h>
-#include <kpropertiesdialog.h>
-
-#include "fileprops.h"
-
-#define KFILEVERSION "0.2"
-#define INDENT "\t"
-
-using namespace std;
-
-static TQString beatifyValue( const TQString& value )
-{
- if ( value.isNull() )
- return TQString("(no value for key available)");
- else if ( value.isEmpty() )
- return TQString("(empty)");
-
- return value;
-}
-
-FileProps::FileProps( const TQString& path, const TQStringList& suppliedGroups )
- : m_dirty( false )
-{
- m_info = new KFileMetaInfo(path, TQString::null, KFileMetaInfo::Everything);
- m_userSuppliedGroups = !suppliedGroups.isEmpty();
- m_groupsToUse = m_userSuppliedGroups ? suppliedGroups : m_info->groups();
-}
-
-FileProps::~FileProps()
-{
- sync();
- delete m_info;
-}
-
-bool FileProps::sync()
-{
- if ( !m_dirty )
- return true;
-
- return m_info->applyChanges();
-}
-
-bool FileProps::isValid() const
-{
- return m_info->isValid();
-}
-
-TQStringList FileProps::supportedGroups() const
-{
- return m_info->supportedGroups();
-}
-
-TQStringList FileProps::availableGroups() const
-{
- return m_info->groups();
-}
-
-TQStringList FileProps::supportedKeys( const TQString& group ) const
-{
- KFileMetaInfoGroup g = m_info->group( group );
- return g.supportedKeys();
-}
-
-TQStringList FileProps::availableKeys( const TQString& group ) const
-{
- KFileMetaInfoGroup g = m_info->group( group );
- TQStringList allKeys = g.keys();
- TQStringList ret;
- TQStringList::ConstIterator it = allKeys.begin();
- for ( ; it != allKeys.end(); ++it )
- {
- if ( g.item( *it ).isValid() )
- ret.append( *it );
- }
-
- return ret;
-}
-
-TQStringList FileProps::preferredKeys( const TQString& group ) const
-{
- KFileMetaInfoGroup g = m_info->group( group );
- return g.preferredKeys();
-}
-
-TQString FileProps::getValue( const TQString& group,
- const TQString& key ) const
-{
- KFileMetaInfoGroup g = m_info->group( group );
- return FileProps::createKeyValue( g, key );
-}
-
-bool FileProps::setValue( const TQString& group,
- const TQString& key, const TQString &value )
-{
- KFileMetaInfoGroup g = m_info->group( group );
- bool wasAdded = false;
- if ( !g.isValid() )
- {
- if ( m_info->addGroup( group ) )
- {
- wasAdded = true;
- g = m_info->group( group );
- }
- else
- return false;
- }
-
- bool ok = g[key].setValue( value );
-
- if ( !ok && wasAdded ) // remove the created group again
- (void) m_info->removeGroup( group );
-
- m_dirty |= ok;
- return ok;
-}
-
-TQStringList FileProps::allValues( const TQString& group ) const
-{
- KFileMetaInfoGroup g = m_info->group( group );
- return FileProps::createKeyValueList( g, g.keys() );
-}
-
-TQStringList FileProps::preferredValues( const TQString& group ) const
-{
- KFileMetaInfoGroup g = m_info->group( group );
- return FileProps::createKeyValueList( g, g.preferredKeys() );
-}
-
-// static helper:
-// creates strings like
-// "group: translatedKey: value"
-TQString FileProps::createKeyValue( const KFileMetaInfoGroup& g,
- const TQString& key )
-{
- static const int MAX_SPACE = 25;
- KFileMetaInfoItem item = g.item( key );
-
- TQString result("%1");
- result = result.arg( (item.isValid() ? item.translatedKey() : key) + ":",
- -MAX_SPACE );
- result.append( beatifyValue( item.string() ) );
-
- TQString group("%1");
- group = group.arg( g.translatedName() + ":", -MAX_SPACE );
- result.prepend( group );
-
- return result;
-}
-
-// static
-TQStringList FileProps::createKeyValueList( const KFileMetaInfoGroup& g,
- const TQStringList& keys )
-{
- TQStringList result;
- TQStringList::ConstIterator it = keys.begin();
-
- for ( ; it != keys.end(); ++it )
- result.append( FileProps::createKeyValue( g, *it ) );
-
- return result;
-}
-
-///////////////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////////////
-
-
-
-// kfile --mimetype --listsupported --listavailable --listpreferred --listwritable --getValue "key" --setValue "key=value" --allValues --preferredValues --dialog --quiet file [file...]
-// "key" may be a list of keys, separated by commas
-static KCmdLineOptions options[] =
-{
- { "m", 0, 0 }, // short option for --mimetype
- { "nomimetype", I18N_NOOP("Do not print the mimetype of the given file(s)"), 0 },
-
- { "ls", 0, 0 }, // short option for --listsupported
- { "listsupported <mimetype>",
- I18N_NOOP("List all supported metadata keys of the given file(s). "
- "If mimetype is not specified, the mimetype of the given "
- "files is used." ), "file" },
-
- { "lp", 0, 0 }, // short option for --listpreferred
- { "listpreferred <mimetype>",
- I18N_NOOP("List all preferred metadata keys of the given file(s). "
- "If mimetype is not specified, the mimetype of the given "
- "files is used." ), "file" },
-
- { "la", 0, 0 }, // short option for --listavailable
- { "listavailable",
- I18N_NOOP("List all metadata keys which have a value in the given "
- "file(s)."), 0 },
-
- { "sm", 0, 0 }, // short option for --supportedMimetypes
- { "supportedMimetypes",
- I18N_NOOP("Prints all mimetypes for which metadata support is "
- "available."), 0 },
-
- { "q", 0, 0 }, // short option for --quiet
- { "quiet",
- I18N_NOOP("Do not print a warning when more than one file was given "
- "and they do not all have the same mimetype."), 0 },
-
- { "av", 0, 0 }, // short option for --allValues
- { "allValues",
- I18N_NOOP("Prints all metadata values, available in the given "
- "file(s)."), 0 },
-
- { "pv", 0, 0 }, // short option for --preferredValues
- { "preferredValues",
- I18N_NOOP("Prints the preferred metadata values, available in the "
- "given file(s)."), 0 },
-
- { "dialog",
- I18N_NOOP("Opens a TDE properties dialog to allow viewing and "
- "modifying of metadata of the given file(s)"), 0 },
-
- { "getValue <key>",
- I18N_NOOP("Prints the value for 'key' of the given file(s). 'key' "
- "may also be a comma-separated list of keys"), 0 },
-
- { "setValue <key=value>",
- I18N_NOOP("Attempts to set the value 'value' for the metadata key "
- "'key' for the given file(s)"), 0 },
-
- { "!groups <arguments>", I18N_NOOP("The group to get values from or set values to"),
- 0 },
-
- { "+[files]",
- I18N_NOOP("The file (or a number of files) to operate on."), 0 },
- KCmdLineLastOption
-};
-
-
-//
-// helper functions
-//
-
-static void printSupportedMimeTypes()
-{
- TQStringList allMimeTypes = KFileMetaInfoProvider::self()->supportedMimeTypes();
- if ( allMimeTypes.isEmpty() )
- {
- cout <<
- i18n("No support for metadata extraction found.").local8Bit().data()
- << endl;
- return;
- }
-
- cout << i18n("Supported MimeTypes:").local8Bit().data() << endl;
-
- TQStringList::ConstIterator it = allMimeTypes.begin();
- for ( ; it != allMimeTypes.end(); it++ )
- cout << (*it).local8Bit().data() << endl;
-}
-
-// caller needs to delete the returned list!
-static KFileItemList * fileItemList( const TDECmdLineArgs *args )
-{
- KFileItemList * items = new KFileItemList();
- items->setAutoDelete( true );
- for ( int i = 0; i < args->count(); i++ )
- items->append( new KFileItem( KFileItem::Unknown,
- KFileItem::Unknown,
- args->url( i ) ));
- return items;
-}
-
-static void showPropertiesDialog( const TDECmdLineArgs *args )
-{
- KFileItemList *items = fileItemList( args );
- new KPropertiesDialog( *items, 0L, "props dialog", true );
- delete items;
-}
-
-static void printMimeTypes( const TDECmdLineArgs *args )
-{
- for ( int i = 0; i < args->count(); i++ )
- {
- KURL url = args->url( i );
- KMimeType::Ptr mt = KMimeType::findByURL( url );
- cout << args->arg(i) << ": " << mt->comment().local8Bit().data() << " ("
- << mt->name().local8Bit().data() << ")" << endl;
- }
-}
-
-static void printList( const TQStringList& list )
-{
- TQStringList::ConstIterator it = list.begin();
- for ( ; it != list.end(); ++it )
- cout << (*it).local8Bit().data() << endl;
- cout << endl;
-}
-
-static void processMetaDataOptions( const TQPtrList<FileProps> propList,
- TDECmdLineArgs *args )
-{
-// kfile --mimetype --supportedMimetypes --listsupported --listavailable --listpreferred --listwritable --getValue "key" --setValue "key=value" --allValues --preferredValues --dialog --quiet file [file...]
-// "key" may be a list of keys, separated by commas
-
- TQString line("-- -------------------------------------------------------");
- FileProps *props;
- TQPtrListIterator<FileProps> it( propList );
- for ( ; (props = it.current()); ++it )
- {
- TQString file = props->fileName() + " ";
- TQString fileString = line.replace( 3, file.length(), file );
- cout << TQFile::encodeName( fileString ).data() << endl;
-
- if ( args->isSet( "listsupported" ) )
- {
- cout << "=Supported Keys=" << endl;
- printList( props->supportedKeys() );
- }
- if ( args->isSet( "listpreferred" ) )
- {
- cout << "=Preferred Keys=" << endl;
- printList( props->preferredKeys() );
- }
- if ( args->isSet( "listavailable" ) )
- {
- cout << "=Available Keys=" << endl;
- TQStringList groups = props->availableGroups();
- TQStringList::ConstIterator git = groups.begin();
- for ( ; git != groups.end(); ++git )
- {
- cout << "Group: " << (*git).local8Bit().data() << endl;
- printList( props->availableKeys( *git ) );
- }
- }
-// if ( args->isSet( "listwritable" ) )
-// {
-// cout << "TODO :)" << endl;
-// }
- if ( args->isSet( "getValue" ) )
- {
- cout << "=Value=" << endl;
- TQString key = TQString::fromLocal8Bit( args->getOption("getValue"));
- TQStringList::ConstIterator git = props->groupsToUse().begin();
- for ( ; git != props->groupsToUse().end(); ++git )
- cout << props->getValue( *git, key ).local8Bit().data() << endl;
- }
-
- if ( args->isSet( "setValue" ) )
- {
- // separate key and value from the line "key=value"
- TQString cmd = TQString::fromLocal8Bit( args->getOption("setValue"));
- TQString key = cmd.section( '=', 0, 0 );
- TQString value = cmd.section( '=', 1 );
-
- // either use supplied groups or all supported groups
- // (not only the available!)
- TQStringList groups = props->userSuppliedGroups() ?
- props->groupsToUse() :
- props->supportedGroups();
-
- TQStringList::ConstIterator git = groups.begin();
- for ( ; git != groups.end(); ++git )
- props->setValue( *git, key, value );
- }
-
- if ( args->isSet( "allValues" ) )
- {
- cout << "=All Values=" << endl;
- TQStringList groups = props->availableGroups();
- TQStringList::ConstIterator group = groups.begin();
- for ( ; group != groups.end(); ++group )
- printList( props->allValues( *group ) );
- }
- if ( args->isSet( "preferredValues" ) && !args->isSet("allValues") )
- {
- cout << "=Preferred Values=" << endl;
- TQStringList groups = props->availableGroups();
- TQStringList::ConstIterator group = groups.begin();
- for ( ; group != groups.end(); ++group )
- printList( props->preferredValues( *group ) );
- }
- }
-
-}
-
-int main( int argc, char **argv )
-{
- TDEAboutData about(
- "kfile", I18N_NOOP( "kfile" ), KFILEVERSION,
- I18N_NOOP("A commandline tool to read and modify metadata of files." ),
- TDEAboutData::License_LGPL, "(c) 2002, Carsten Pfeiffer",
- 0 /*text*/, "http://devel-home.kde.org/~pfeiffer/",
- "pfeiffer@kde.org" );
-
- about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org",
- "http://devel-home.kde.org/~pfeiffer/" );
-
- TDECmdLineArgs::init( argc, argv, &about );
-
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
- bool useGUI = args->isSet( "dialog" );
-
- TDEApplication app( useGUI, useGUI );
-
- TQPtrList<FileProps> m_props;
- m_props.setAutoDelete( true );
-
- bool quiet = args->isSet( "quiet" );
-
- if ( args->isSet( "supportedMimetypes" ) )
- printSupportedMimeTypes();
-
- int files = args->count();
- if ( files == 0 )
- TDECmdLineArgs::usage( i18n("No files specified") ); // exit()s
-
- if ( args->isSet( "dialog" ) )
- {
- showPropertiesDialog( args );
- return true;
- }
-
- TQStringList groupsToUse;
- QCStringList suppliedGroups = args->getOptionList( "groups" );
- QCStringList::ConstIterator it = suppliedGroups.begin();
- for ( ; it != suppliedGroups.end(); ++it )
- groupsToUse.append( TQString::fromLocal8Bit( (*it) ) );
-
- TQString mimeType;
-
- for ( int i = 0; i < files; i++ )
- {
- if ( args->isSet( "mimetype" ) )
- printMimeTypes( args );
-
- FileProps *props = new FileProps( args->url(i).path(), groupsToUse );
- if ( props->isValid() )
- m_props.append( props );
- else
- {
- if ( !quiet )
- {
- cerr << args->arg(i) << ": " <<
- i18n("Cannot determine metadata").local8Bit().data() << endl;
- }
- delete props;
- }
- }
-
-
- processMetaDataOptions( m_props, args );
-
- m_props.clear(); // force destruction/sync of props
- cout.flush();
-
- return 0;
-}
diff --git a/kio/misc/kfile/fileprops.h b/kio/misc/kfile/fileprops.h
deleted file mode 100644
index 41d4f7c86..000000000
--- a/kio/misc/kfile/fileprops.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
-
- library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation, version 2.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef KFILEPROPS_H
-#define KFILEPROPS_H
-
-#include <tqstring.h>
-
-#include <kfilemetainfo.h>
-
-class FileProps
-{
-public:
- FileProps( const TQString& path, const TQStringList& suppliedGroups );
- virtual ~FileProps();
-
- bool isValid() const;
-
- TQString fileName() const { return m_info->path(); }
-
- TQStringList supportedGroups() const;
- TQStringList availableGroups() const;
- TQStringList translatedGroups();
-
- const TQStringList& groupsToUse() const { return m_groupsToUse; }
- bool userSuppliedGroups() const { return m_userSuppliedGroups; }
-
- TQStringList supportedKeys( const TQString& group ) const;
- TQStringList availableKeys( const TQString& group ) const;
- TQStringList preferredKeys( const TQString& group ) const;
-
- TQStringList supportedKeys() const { return m_info->supportedKeys(); }
- TQStringList preferredKeys() const { return m_info->preferredKeys(); }
-
- TQString getValue( const TQString& group, const TQString& key ) const;
- bool setValue( const TQString& group,
- const TQString& key, const TQString &value );
-
- TQStringList allValues( const TQString& group ) const;
- TQStringList preferredValues( const TQString& group ) const;
-
- bool isReadOnly( const TQString& group, const TQString& key );
-
-private:
- static TQString createKeyValue( const KFileMetaInfoGroup& g,
- const TQString& key );
- static TQStringList createKeyValueList( const KFileMetaInfoGroup&,
- const TQStringList& );
- bool sync();
-
- KFileMetaInfo *m_info;
- bool m_dirty;
- bool m_userSuppliedGroups;
-
- TQStringList m_groupsToUse;
-
-};
-
-#endif // KFILEPROPS_H
diff --git a/kio/misc/kio_uiserver.desktop b/kio/misc/kio_uiserver.desktop
deleted file mode 100644
index fd37cd2bd..000000000
--- a/kio/misc/kio_uiserver.desktop
+++ /dev/null
@@ -1,100 +0,0 @@
-[Desktop Entry]
-Type=Service
-Name=kio_uiserver
-Name[de]=Server der graphischen Oberfläche
-Name[fy]=Kio_uiserver
-Name[ja]=kio_uiサーãƒ
-Name[mn]=График гадаргуугийн Ñервер
-Name[nds]=kio_uiserver, Server för de graafsche Böversiet
-Name[nl]=Kio_uiserver
-Name[nso]=kio_uiseabi
-Name[ro]=Kio_uiserver
-Name[sv]=Kio-gränssnittsserver
-Name[ta]=kio_uiசேவையகமà¯
-Name[te]=కేà°à°“_à°¯à±à°à°¸à±†à°°à±à°µà°°à±
-Exec=kio_uiserver
-Comment=TDE's Progress Info UI server
-Comment[af]=TDE se vordering inligting UI bediener
-Comment[ar]=خادم معلومات تقدم واجهة كيدي
-Comment[az]=TDE'nin İrəliləmə Bilgisi İstifadaçi Ara Üz Vericisi
-Comment[be]=Сервер паведамленнÑÑž аб выкананні дзеÑннÑÑž
-Comment[bg]=Сървър за отчитане на прогреÑа (TDE's Progress Info UI server)
-Comment[bn]=কে.ডি.ই. অগà§à¦°à¦—তি তথà§à¦¯ UI সারà§à¦­à¦¾à¦°
-Comment[br]=Servijer stlenn EA Progress TDE
-Comment[bs]=TDEov Progess Info UI server
-Comment[ca]=Servidor d'informació de progrés del TDE
-Comment[cs]=UI server zobrazující informace o průběhu
-Comment[csb]=Serwer wëdowiédzë ò pòkròkù procesë
-Comment[cy]=Gweinydd UI TDE i Ddangos Cynnydd
-Comment[da]=TDE's fremgangsinfo-UI-server
-Comment[de]=Ein UI-Server, der Fortschrittsinformationen darstellt
-Comment[el]=ΕξυπηÏετητής πληÏοφοÏιών Ï€Ïοόδου πεÏιβάλλοντος χÏήσης του TDE
-Comment[eo]=Progresinforma servo
-Comment[es]=Servidor UI de información de progreso de TDE
-Comment[et]=TDE edenemise info UI server
-Comment[eu]=TDEren aurrerapen-informazioen UI zerbitzaria
-Comment[fa]=اطلاعات پیشرÙت کارساز UI TDE
-Comment[fi]=TDE:n edistymispalkin käyttöliittymäpalvelin
-Comment[fr]=Serveur graphique d'infos de progression de TDE
-Comment[fy]=TDE's tsjinner foar ynformaasje oer de fuortgong
-Comment[gl]=Servidor UI de Información de Progreso de TDE
-Comment[he]=שרת ממשק מידע ההתקדמות של TDE
-Comment[hi]=केडीई का पà¥à¤°à¥‹à¤—à¥à¤°à¥‡à¤¸ जानकारी UI सरà¥à¤µà¤°
-Comment[hr]=TDEov Progess Info UI poslužitelj
-Comment[hu]=TDE folyamatinformációs kiszolgáló
-Comment[id]=Perkembangan TDE mengenai info server UI
-Comment[is]=Þjónn sem sýnir framvindu ferla
-Comment[it]=Server informazioni avanzamento di TDE
-Comment[ja]=TDE 進æ—情報 UI サーãƒ
-Comment[ka]=TDE-ს მáƒáƒœáƒáƒªáƒ”მთრგáƒáƒ“áƒáƒªáƒ”მის სერვერი
-Comment[kk]=TDE деректерді алу-беруді бақылау Ñервері
-Comment[km]=ម៉ាស៊ីន​បម្រើ UI នៃ​ពáŸážáŸŒáž˜áž¶áž“​វឌ្ážáž“ភាព​របស់ TDE
-Comment[ko]=TDEì—ì„œ 보다 ë°œì „ëœ ì •ë³´ UI 서버
-Comment[lb]=UI-Server vu TDE, dee Fortschrëttsinformatiounen uweist
-Comment[lt]=TDE eigos informacijos UI serveris
-Comment[lv]=TDE Progresa Info UI serveris
-Comment[mk]=TDE Ñервер за информации за прогреÑот
-Comment[mn]=ПрогреÑÑ Ð¼ÑдÑÑллÑÑÑ€ дүрÑлÑгдÑÑн Ñ…ÑÑ€ÑглÑгчийн харьцах Ñ…ÑÑгийн Ñервер
-Comment[ms]=Pelayan Info UI TDE
-Comment[mt]=Server tal-progress tal-UI TDE
-Comment[nb]=TDE UI-tjener for framgangsinfo
-Comment[nds]=Server för graafsche Vörankamen-Informatschonen
-Comment[ne]=TDE को पà¥à¤°à¤—ति सूचना UI सरà¥à¤­à¤°
-Comment[nl]=TDE's server voor informatie over de voortgang.
-Comment[nn]=TDE UI-tenar for framgangsinfo
-Comment[nso]=Seabi sa UI ya Tshedimoso ya Tswelopele ya TDE
-Comment[oc]=Servor d'informacion de progress TDE
-Comment[pa]=TDE ਦੀ ਤਰੱਕੀ ਜਾਣਕਾਰੀ UI ਸਰਵਰ
-Comment[pl]=Serwer informacji o postępie procesu
-Comment[pt]=Servidor de informações sobre o progresso das operações
-Comment[pt_BR]=Servidor de informação de progresso do TDE
-Comment[ro]=Server informaţii de progres TDE
-Comment[ru]=Сервер монитора передачи данных TDE
-Comment[rw]=Amakuru y'Aho bigeze ya TDE Seriveri UI
-Comment[se]=TDE:a ovdánandieđuid UI-bálvá
-Comment[sk]=TDE Progres Info UI server
-Comment[sl]=Strežnik TDE's Progress Info UI
-Comment[sq]=UI Shërbyesi për Informimin e Progresit të TDEs
-Comment[sr]=TDE-ов UI Ñервер информација о напретку
-Comment[sr@Latn]=TDE-ov UI server informacija o napretku
-Comment[sv]=TDE:s server för förloppsinformation
-Comment[ta]=கேடிஇயின௠மà¯à®©à¯à®©à¯‡à®±à¯à®± தகவல௠மà¯à®•à®ªà¯à®ªà¯à®ªà¯ சேவையகமà¯
-Comment[te]=కెడిఈ యొకà±à°• à°ªà±à°°à°—తి సమాచార యూఠసెరà±à°µà°°à±
-Comment[tg]=Инкишофи TDE's Info UI Сервер
-Comment[th]=เซิร์ฟเวอร์à¹à¸ªà¸”งข้อมูลความคืบหน้าของ TDE
-Comment[tr]=TDE'nin İlerleme Bilgisi arayüz sunucusu
-Comment[tt]=TDE'nıñ Alğakiteşne Küzätü servere
-Comment[uk]=Сервер графічного інтерфейÑу інформації про розвиток TDE
-Comment[uz]=TDE'ning maʼlumot uzatishni nazorat qilish serveri
-Comment[uz@cyrillic]=TDE'нинг маълумот узатишни назорат қилиш Ñервери
-Comment[ven]=UI siva ya mafhungo a mwelaphanda a TDE
-Comment[vi]=Trình phục vụ giao diện ngÆ°á»i dùng cho thông tin tiến hành của TDE.
-Comment[xh]=Umcedisi we UI Wenqubela Yenkcukacha we TDE
-Comment[zh_CN]=TDE 的进度信æ¯ç”¨æˆ·ç•Œé¢æœåŠ¡å™¨
-Comment[zh_HK]=TDE 的進度資訊介é¢ä¼ºæœç¨‹å¼
-Comment[zh_TW]=TDE 的進度資訊使用者介é¢ä¼ºæœå™¨
-Comment[zu]=Umlekeleli we-UI Yolwazi Lwenqubo lwe-TDE
-ServiceTypes=
-# It is a server
-X-DCOP-ServiceType=Unique
-X-TDE-StartupNotify=false
diff --git a/kio/misc/kmailservice.cpp b/kio/misc/kmailservice.cpp
deleted file mode 100644
index 3b2eb8cf7..000000000
--- a/kio/misc/kmailservice.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Simon Hausmann <hausmann@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kapplication.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-
-static const KCmdLineOptions options[] =
-{
- { "+url", 0, 0 },
- KCmdLineLastOption
-};
-
-int main( int argc, char **argv )
-{
- KLocale::setMainCatalogue("tdelibs");
- TDECmdLineArgs::init( argc, argv, "kmailservice", I18N_NOOP("KMailService"), I18N_NOOP("Mail service"), "unknown" );
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDEApplication a( false, false );
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- if ( args->count() != 1 )
- return 1;
-
- a.invokeMailer(KURL(args->arg(0)), a.startupId(), true);
-
- return 0;
-}
diff --git a/kio/misc/kmailservice.protocol b/kio/misc/kmailservice.protocol
deleted file mode 100644
index 46a3054a6..000000000
--- a/kio/misc/kmailservice.protocol
+++ /dev/null
@@ -1,15 +0,0 @@
-[Protocol]
-exec=kmailservice %u
-protocol=mailto
-input=none
-output=none
-helper=true
-listing=
-reading=false
-writing=false
-makedir=false
-deleting=false
-DocPath=kioslave/mailto.html
-Icon=mail_new
-Class=:internet
-URIMode=mailto
diff --git a/kio/misc/kpac/CMakeLists.txt b/kio/misc/kpac/CMakeLists.txt
deleted file mode 100644
index 00ce2d357..000000000
--- a/kio/misc/kpac/CMakeLists.txt
+++ /dev/null
@@ -1,66 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_BINARY_DIR}/kjs
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore/network
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kded
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-##### other data ################################
-
-install(FILES proxyscout.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
-install(FILES eventsrc DESTINATION ${DATA_INSTALL_DIR}/proxyscout )
-
-
-##### kded_proxyscout ###########################
-
-set( target kded_proxyscout )
-
-set( ${target}_SRCS
- proxyscout.cpp proxyscout.skel script.cpp
- downloader.cpp discovery.cpp
-)
-
-set( ${target}_SKELS
- proxyscout.h
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK tdeinit_kded-shared kjs-shared ${RESOLV_LIBRARIES}
- DEPENDENCIES dcopidl
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
-
-
-##### kpac_dhcp_helper ##########################
-
-set( target kpac_dhcp_helper )
-
-# FIXME on Gentoo this binary is not suided
-tde_add_executable( ${target} SETUID
- SOURCES kpac_dhcp_helper.c
- DESTINATION ${BIN_INSTALL_DIR}
-)
diff --git a/kio/misc/kpac/downloader.cpp b/kio/misc/kpac/downloader.cpp
deleted file mode 100644
index c150a732c..000000000
--- a/kio/misc/kpac/downloader.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- Copyright (c) 2003 Malte Starostik <malte@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-
-#include <cstdlib>
-#include <cstring>
-
-#include <tqtextcodec.h>
-
-#include <kcharsets.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kio/job.h>
-
-#include "downloader.moc"
-
-namespace KPAC
-{
- Downloader::Downloader( TQObject* parent )
- : TQObject( parent )
- {
- }
-
- void Downloader::download( const KURL& url )
- {
- m_data.resize( 0 );
- m_script = TQString::null;
- m_scriptURL = url;
-
- TDEIO::TransferJob* job = TDEIO::get( url, false, false );
- connect( job, TQT_SIGNAL( data( TDEIO::Job*, const TQByteArray& ) ),
- TQT_SLOT( data( TDEIO::Job*, const TQByteArray& ) ) );
- connect( job, TQT_SIGNAL( result( TDEIO::Job* ) ), TQT_SLOT( result( TDEIO::Job* ) ) );
- }
-
- void Downloader::failed()
- {
- emit result( false );
- }
-
- void Downloader::setError( const TQString& error )
- {
- m_error = error;
- }
-
- void Downloader::data( TDEIO::Job*, const TQByteArray& data )
- {
- unsigned offset = m_data.size();
- m_data.resize( offset + data.size() );
- std::memcpy( m_data.data() + offset, data.data(), data.size() );
- }
-
- void Downloader::result( TDEIO::Job* job )
- {
- if ( !job->error() && !static_cast< TDEIO::TransferJob* >( job )->isErrorPage() )
- {
- bool dummy;
- m_script = TDEGlobal::charsets()->codecForName(
- job->queryMetaData( "charset" ), dummy )->toUnicode( m_data );
- emit result( true );
- }
- else
- {
- if ( job->error() )
- setError( i18n( "Could not download the proxy configuration script:\n%1" )
- .arg( job->errorString() ) );
- else setError( i18n( "Could not download the proxy configuration script" ) ); // error page
- failed();
- }
- }
-}
-
-// vim: ts=4 sw=4 et
diff --git a/kio/misc/ksendbugmail/CMakeLists.txt b/kio/misc/ksendbugmail/CMakeLists.txt
deleted file mode 100644
index f0e1b99b0..000000000
--- a/kio/misc/ksendbugmail/CMakeLists.txt
+++ /dev/null
@@ -1,37 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### ksendbugmail ##############################
-
-set( target ksendbugmail )
-
-set( ${target}_SRCS
- main.cpp smtp.cpp
-)
-
-tde_add_executable( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${BIN_INSTALL_DIR}
-)
diff --git a/kio/misc/ksendbugmail/Makefile.am b/kio/misc/ksendbugmail/Makefile.am
deleted file mode 100644
index b24e36a26..000000000
--- a/kio/misc/ksendbugmail/Makefile.am
+++ /dev/null
@@ -1,26 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-bin_PROGRAMS = ksendbugmail
-INCLUDES= -I$(srcdir)/.. $(all_includes)
-
-ksendbugmail_SOURCES = main.cpp smtp.cpp
-ksendbugmail_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-ksendbugmail_LDADD = ../../libkio.la
-
-METASOURCES = AUTO
diff --git a/kio/misc/ksendbugmail/main.cpp b/kio/misc/ksendbugmail/main.cpp
deleted file mode 100644
index be1eb8b96..000000000
--- a/kio/misc/ksendbugmail/main.cpp
+++ /dev/null
@@ -1,142 +0,0 @@
-// $Id$
-
-#include <sys/types.h>
-#include "main.h"
-#include <pwd.h>
-#include <stdlib.h>
-#include <unistd.h>
-
-#include <tqtextstream.h>
-
-#include <kapplication.h>
-#include <kemailsettings.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-#include <kaboutdata.h>
-#include <kdebug.h>
-#include <kconfig.h>
-
-#include "smtp.h"
-
-static KCmdLineOptions options[] = {
- { "subject <argument>", I18N_NOOP("Subject line"), 0 },
- { "recipient <argument>", I18N_NOOP("Recipient"), "submit@bugs.kde.org" },
- KCmdLineLastOption
-};
-
-void BugMailer::slotError(int errornum) {
- kdDebug() << "slotError\n";
- TQString str, lstr;
-
- switch(errornum) {
- case SMTP::CONNECTERROR:
- lstr = i18n("Error connecting to server.");
- break;
- case SMTP::NOTCONNECTED:
- lstr = i18n("Not connected.");
- break;
- case SMTP::CONNECTTIMEOUT:
- lstr = i18n("Connection timed out.");
- break;
- case SMTP::INTERACTTIMEOUT:
- lstr = i18n("Time out waiting for server interaction.");
- break;
- default:
- lstr = sm->getLastLine().stripWhiteSpace();
- lstr = i18n("Server said: \"%1\"").arg(lstr);
- }
- fputs(lstr.utf8().data(), stdout);
- fflush(stdout);
-
- ::exit(1);
-}
-
-void BugMailer::slotSend() {
- kdDebug() << "slotSend\n";
- ::exit(0);
-}
-
-int main(int argc, char **argv) {
-
- KLocale::setMainCatalogue("tdelibs");
- TDEAboutData d("ksendbugmail", I18N_NOOP("KSendBugMail"), "1.0",
- I18N_NOOP("Sends a short bug report to submit@bugs.kde.org"),
- TDEAboutData::License_GPL, "(c) 2000 Stephan Kulow");
- d.addAuthor("Stephan Kulow", I18N_NOOP("Author"), "coolo@kde.org");
-
- TDECmdLineArgs::init(argc, argv, &d);
- TDECmdLineArgs::addCmdLineOptions(options);
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- TDEApplication a(false, false);
-
- TQCString recipient = args->getOption("recipient");
- if (recipient.isEmpty())
- recipient = "submit@bugs.kde.org";
- else {
- if (recipient.at(0) == '\'') {
- recipient = recipient.mid(1).left(recipient.length() - 2);
- }
- }
- kdDebug() << "recp \"" << recipient << "\"\n";
-
- TQCString subject = args->getOption("subject");
- if (subject.isEmpty())
- subject = "(no subject)";
- else {
- if (subject.at(0) == '\'')
- subject = subject.mid(1).left(subject.length() - 2);
- }
- TQTextIStream input(stdin);
- TQString text, line;
- while (!input.eof()) {
- line = input.readLine();
- text += line + "\r\n";
- }
- kdDebug() << text << endl;
-
- KEMailSettings emailConfig;
- emailConfig.setProfile(emailConfig.defaultProfileName());
- TQString fromaddr = emailConfig.getSetting(KEMailSettings::EmailAddress);
- if (!fromaddr.isEmpty()) {
- TQString name = emailConfig.getSetting(KEMailSettings::RealName);
- if (!name.isEmpty())
- fromaddr = name + TQString::fromLatin1(" <") + fromaddr + TQString::fromLatin1(">");
- } else {
- struct passwd *p;
- p = getpwuid(getuid());
- fromaddr = TQString::fromLatin1(p->pw_name);
- fromaddr += "@";
- char buffer[256];
- buffer[0] = '\0';
- if(!gethostname(buffer, sizeof(buffer)))
- buffer[sizeof(buffer)-1] = '\0';
- fromaddr += buffer;
- }
- kdDebug() << "fromaddr \"" << fromaddr << "\"" << endl;
-
- TQString server = emailConfig.getSetting(KEMailSettings::OutServer);
- if (server.isEmpty())
- server=TQString::fromLatin1("bugs.kde.org");
-
- SMTP *sm = new SMTP;
- BugMailer bm(sm);
-
- TQObject::connect(sm, TQT_SIGNAL(messageSent()), &bm, TQT_SLOT(slotSend()));
- TQObject::connect(sm, TQT_SIGNAL(error(int)), &bm, TQT_SLOT(slotError(int)));
- sm->setServerHost(server);
- sm->setPort(25);
- sm->setSenderAddress(fromaddr);
- sm->setRecipientAddress(recipient);
- sm->setMessageSubject(subject);
- sm->setMessageHeader(TQString::fromLatin1("From: %1\r\nTo: %2\r\n").arg(fromaddr).arg(recipient.data()));
- sm->setMessageBody(text);
- sm->sendMessage();
-
- int r = a.exec();
- kdDebug() << "execing " << r << endl;
- delete sm;
- return r;
-}
-
-#include "main.moc"
diff --git a/kio/misc/kssld/CMakeLists.txt b/kio/misc/kssld/CMakeLists.txt
deleted file mode 100644
index 14d2de1ac..000000000
--- a/kio/misc/kssld/CMakeLists.txt
+++ /dev/null
@@ -1,47 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/kio/kssl
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio/kssl
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install(FILES kssld.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
-
-
-##### kded_kssld ###########################
-
-set( target kded_kssld )
-
-set( ${target}_SRCS
- kssld.cpp kssld.skel
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK tdeinit_kded-shared
- DEPENDENCIES dcopidl
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kio/misc/kssld/Makefile.am b/kio/misc/kssld/Makefile.am
deleted file mode 100644
index 18193018e..000000000
--- a/kio/misc/kssld/Makefile.am
+++ /dev/null
@@ -1,33 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 2001 George Staikos <staikos@kde.org>
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-INCLUDES= -I$(srcdir)/.. -I$(top_srcdir) $(SSL_INCLUDES) -I$(top_srcdir)/kio/kssl -I$(top_builddir)/kio/kssl $(all_includes)
-
-kde_module_LTLIBRARIES = kded_kssld.la
-
-kded_kssld_la_LDFLAGS = $(all_libraries) -module -avoid-version
-kded_kssld_la_LIBADD = $(LIB_KIO) $(LIB_KDED) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE)
-kded_kssld_la_SOURCES = kssld.cpp kssld.skel
-
-METASOURCES = AUTO
-
-noinst_HEADERS = kssld.h
-
-services_DATA = kssld.desktop
-servicesdir = $(kde_servicesdir)/kded
-
diff --git a/kio/misc/kssld/kssld.cpp b/kio/misc/kssld/kssld.cpp
deleted file mode 100644
index 22bf6ab84..000000000
--- a/kio/misc/kssld/kssld.cpp
+++ /dev/null
@@ -1,1027 +0,0 @@
-/*
- This file is part of the KDE libraries
-
- Copyright (c) 2001-2005 George Staikos <staikos@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
-*/
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <tqtimer.h>
-
-#include "kssld.h"
-#include <kconfig.h>
-#include <ksimpleconfig.h>
-#include <ksslcertchain.h>
-#include <ksslcertificate.h>
-#include <ksslcertificatehome.h>
-#include <ksslpkcs12.h>
-#include <ksslx509map.h>
-#include <tqptrlist.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <stdlib.h>
-#include <pwd.h>
-#include <unistd.h>
-#include <tqfile.h>
-#include <tqsortedlist.h>
-#include <kglobal.h>
-#include <kstandarddirs.h>
-#include <kdebug.h>
-#include <tqdatetime.h>
-
-#include <kmdcodec.h>
-#include <kopenssl.h>
-
-// See design notes at end
-
-extern "C" {
- KDE_EXPORT KDEDModule *create_kssld(const TQCString &name) {
- return new KSSLD(name);
- }
-
- KDE_EXPORT void *__kde_do_unload;
-}
-
-
-static void updatePoliciesConfig(TDEConfig *cfg) {
- TQStringList groups = cfg->groupList();
-
- for (TQStringList::Iterator i = groups.begin(); i != groups.end(); ++i) {
- if ((*i).isEmpty() || *i == "General") {
- continue;
- }
-
- cfg->setGroup(*i);
-
- // remove it if it has expired
- if (!cfg->readBoolEntry("Permanent") && cfg->readDateTimeEntry("Expires") < TQDateTime::currentDateTime()) {
- cfg->deleteGroup(*i);
- continue;
- }
-
- TQString encodedCertStr = cfg->readEntry("Certificate");
- TQCString encodedCert = encodedCertStr.local8Bit();
- KSSLCertificate *newCert = KSSLCertificate::fromString(encodedCert);
- if (!newCert) {
- cfg->deleteGroup(*i);
- continue;
- }
-
- KSSLCertificateCache::KSSLCertificatePolicy policy = (KSSLCertificateCache::KSSLCertificatePolicy) cfg->readNumEntry("Policy");
- bool permanent = cfg->readBoolEntry("Permanent");
- TQDateTime expires = cfg->readDateTimeEntry("Expires");
- TQStringList hosts = cfg->readListEntry("Hosts");
- TQStringList chain = cfg->readListEntry("Chain");
- cfg->deleteGroup(*i);
-
- cfg->setGroup(newCert->getMD5Digest());
- cfg->writeEntry("Certificate", encodedCertStr);
- cfg->writeEntry("Policy", policy);
- cfg->writeEntry("Permanent", permanent);
- cfg->writeEntry("Expires", expires);
- cfg->writeEntry("Hosts", hosts);
- cfg->writeEntry("Chain", chain);
- delete newCert;
- }
-
- cfg->setGroup("General");
- cfg->writeEntry("policies version", 2);
-
- cfg->sync();
-}
-
-
-KSSLD::KSSLD(const TQCString &name) : KDEDModule(name)
-{
-// ----------------------- FOR THE CACHE ------------------------------------
- cfg = new KSimpleConfig("ksslpolicies", false);
- cfg->setGroup("General");
- if (2 != cfg->readNumEntry("policies version", 0)) {
- ::updatePoliciesConfig(cfg);
- }
- TDEGlobal::dirs()->addResourceType("kssl", KStandardDirs::kde_default("data") + "kssl");
- caVerifyUpdate();
- cacheLoadDefaultPolicies();
- certList.setAutoDelete(false);
- kossl = KOSSL::self();
-
-// ----------------------- FOR THE HOME -------------------------------------
-}
-
-
-KSSLD::~KSSLD()
-{
-// ----------------------- FOR THE CACHE ------------------------------------
- cacheClearList();
- delete cfg;
-
-// ----------------------- FOR THE HOME -------------------------------------
-}
-
-
-
-
-// A node in the cache
-class KSSLCNode {
- public:
- KSSLCertificate *cert;
- KSSLCertificateCache::KSSLCertificatePolicy policy;
- bool permanent;
- TQDateTime expires;
- TQStringList hosts;
- KSSLCNode() { cert = 0L;
- policy = KSSLCertificateCache::Unknown;
- permanent = true;
- }
- ~KSSLCNode() { delete cert; }
-};
-
-
-
-void KSSLD::cacheSaveToDisk() {
-KSSLCNode *node;
-
- cfg->setGroup("General");
- cfg->writeEntry("policies version", 2);
-
- for (node = certList.first(); node; node = certList.next()) {
- if (node->permanent ||
- node->expires > TQDateTime::currentDateTime()) {
- // First convert to a binary format and then write the
- // kconfig entry write the (CN, policy, cert) to
- // KSimpleConfig
- cfg->setGroup(node->cert->getMD5Digest());
- cfg->writeEntry("Certificate", node->cert->toString());
- cfg->writeEntry("Policy", node->policy);
- cfg->writeEntry("Expires", node->expires);
- cfg->writeEntry("Permanent", node->permanent);
- cfg->writeEntry("Hosts", node->hosts);
-
- // Also write the chain
- TQStringList qsl;
- TQPtrList<KSSLCertificate> cl =
- node->cert->chain().getChain();
- for (KSSLCertificate *c = cl.first();
- c != 0;
- c = cl.next()) {
- //kdDebug() << "Certificate in chain: "
- // << c->toString() << endl;
- qsl << c->toString();
- }
-
- cl.setAutoDelete(true);
- cfg->writeEntry("Chain", qsl);
- }
- }
-
- cfg->sync();
-
- // insure proper permissions -- contains sensitive data
- TQString cfgName(TDEGlobal::dirs()->findResource("config", "ksslpolicies"));
-
- if (!cfgName.isEmpty()) {
- ::chmod(TQFile::encodeName(cfgName), 0600);
- }
-}
-
-
-void KSSLD::cacheReload() {
- cacheClearList();
- delete cfg;
- cfg = new KSimpleConfig("ksslpolicies", false);
- cacheLoadDefaultPolicies();
-}
-
-
-void KSSLD::cacheClearList() {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- certList.remove(node);
- delete node;
- }
-
- skEmail.clear();
- skMD5Digest.clear();
-}
-
-
-void KSSLD::cacheLoadDefaultPolicies() {
-TQStringList groups = cfg->groupList();
-
- for (TQStringList::Iterator i = groups.begin();
- i != groups.end();
- ++i) {
- if ((*i).isEmpty() || *i == "General") {
- continue;
- }
-
- cfg->setGroup(*i);
-
- // remove it if it has expired
- if (!cfg->readBoolEntry("Permanent") &&
- cfg->readDateTimeEntry("Expires") <
- TQDateTime::currentDateTime()) {
- cfg->deleteGroup(*i);
- continue;
- }
-
- TQCString encodedCert;
- KSSLCertificate *newCert;
-
- encodedCert = cfg->readEntry("Certificate").local8Bit();
- newCert = KSSLCertificate::fromString(encodedCert);
-
- if (!newCert) {
- continue;
- }
-
- KSSLCNode *n = new KSSLCNode;
- n->cert = newCert;
- n->policy = (KSSLCertificateCache::KSSLCertificatePolicy) cfg->readNumEntry("Policy");
- n->permanent = cfg->readBoolEntry("Permanent");
- n->expires = cfg->readDateTimeEntry("Expires");
- n->hosts = cfg->readListEntry("Hosts");
- newCert->chain().setCertChain(cfg->readListEntry("Chain"));
- certList.append(n);
- searchAddCert(newCert);
- }
-}
-
-
-void KSSLD::cacheAddCertificate(KSSLCertificate cert,
- KSSLCertificateCache::KSSLCertificatePolicy policy,
- bool permanent) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- node->policy = policy;
- node->permanent = permanent;
-
- if (!permanent) {
- node->expires = TQDateTime::currentDateTime();
- // FIXME: make this configurable
- node->expires = TQT_TQDATETIME_OBJECT(node->expires.addSecs(3600));
- }
-
- cacheSaveToDisk();
- return;
- }
- }
-
- KSSLCNode *n = new KSSLCNode;
- n->cert = cert.replicate();
- n->policy = policy;
- n->permanent = permanent;
- // remove the old one
- cacheRemoveByCertificate(*(n->cert));
- certList.prepend(n);
-
- if (!permanent) {
- n->expires = TQDateTime::currentDateTime();
- n->expires = TQT_TQDATETIME_OBJECT(n->expires.addSecs(3600));
- }
-
- searchAddCert(n->cert);
- cacheSaveToDisk();
-}
-
-
-KSSLCertificateCache::KSSLCertificatePolicy KSSLD::cacheGetPolicyByCN(TQString cn) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
- if (!node->permanent &&
- node->expires < TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- delete node;
- continue;
- }
-
- certList.remove(node);
- certList.prepend(node);
- cacheSaveToDisk();
- return node->policy;
- }
- }
-
- cacheSaveToDisk();
-
-return KSSLCertificateCache::Unknown;
-}
-
-
-KSSLCertificateCache::KSSLCertificatePolicy KSSLD::cacheGetPolicyByCertificate(KSSLCertificate cert) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- if (!node->permanent &&
- node->expires < TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- delete node;
- cacheSaveToDisk();
- return KSSLCertificateCache::Unknown;
- }
-
- certList.remove(node);
- certList.prepend(node);
- return node->policy;
- }
- }
-
-return KSSLCertificateCache::Unknown;
-}
-
-
-bool KSSLD::cacheSeenCN(TQString cn) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
- if (!node->permanent &&
- node->expires < TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- delete node;
- cacheSaveToDisk();
- continue;
- }
-
- certList.remove(node);
- certList.prepend(node);
- return true;
- }
- }
-
-return false;
-}
-
-
-bool KSSLD::cacheSeenCertificate(KSSLCertificate cert) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- if (!node->permanent &&
- node->expires < TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- delete node;
- cacheSaveToDisk();
- return false;
- }
-
- certList.remove(node);
- certList.prepend(node);
- return true;
- }
- }
-
-return false;
-}
-
-
-bool KSSLD::cacheIsPermanent(KSSLCertificate cert) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- if (!node->permanent && node->expires <
- TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- delete node;
- cacheSaveToDisk();
- return false;
- }
-
- certList.remove(node);
- certList.prepend(node);
- return node->permanent;
- }
- }
-
-return false;
-}
-
-
-bool KSSLD::cacheRemoveBySubject(TQString subject) {
-KSSLCNode *node;
-bool gotOne = false;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (node->cert->getSubject() == subject) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- searchRemoveCert(node->cert);
- delete node;
- gotOne = true;
- }
- }
-
- cacheSaveToDisk();
-
-return gotOne;
-}
-
-
-bool KSSLD::cacheRemoveByCN(TQString cn) {
-KSSLCNode *node;
-bool gotOne = false;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- searchRemoveCert(node->cert);
- delete node;
- gotOne = true;
- }
- }
-
- cacheSaveToDisk();
-
-return gotOne;
-}
-
-
-bool KSSLD::cacheRemoveByCertificate(KSSLCertificate cert) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- searchRemoveCert(node->cert);
- delete node;
- cacheSaveToDisk();
- return true;
- }
- }
-
-return false;
-}
-
-
-bool KSSLD::cacheModifyByCN(TQString cn,
- KSSLCertificateCache::KSSLCertificatePolicy policy, bool permanent,
- TQDateTime expires) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
- node->permanent = permanent;
- node->expires = expires;
- node->policy = policy;
- certList.remove(node);
- certList.prepend(node);
- cacheSaveToDisk();
- return true;
- }
- }
-
-return false;
-}
-
-
-bool KSSLD::cacheModifyByCertificate(KSSLCertificate cert,
- KSSLCertificateCache::KSSLCertificatePolicy policy,
- bool permanent,
- TQDateTime expires) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- node->permanent = permanent;
- node->expires = expires;
- node->policy = policy;
- certList.remove(node);
- certList.prepend(node);
- cacheSaveToDisk();
- return true;
- }
- }
-
-return false;
-}
-
-
-TQStringList KSSLD::cacheGetHostList(KSSLCertificate cert) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- if (!node->permanent && node->expires <
- TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- searchRemoveCert(node->cert);
- delete node;
- cacheSaveToDisk();
- return TQStringList();
- }
-
- certList.remove(node);
- certList.prepend(node);
- return node->hosts;
- }
- }
-
-return TQStringList();
-}
-
-
-bool KSSLD::cacheAddHost(KSSLCertificate cert, TQString host) {
-KSSLCNode *node;
-
- if (host.isEmpty())
- return true;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- if (!node->permanent && node->expires <
- TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- searchRemoveCert(node->cert);
- delete node;
- cacheSaveToDisk();
- return false;
- }
-
- if (!node->hosts.contains(host)) {
- node->hosts << host;
- }
-
- certList.remove(node);
- certList.prepend(node);
- cacheSaveToDisk();
- return true;
- }
- }
-
-return false;
-}
-
-
-bool KSSLD::cacheRemoveHost(KSSLCertificate cert, TQString host) {
-KSSLCNode *node;
-
- for (node = certList.first(); node; node = certList.next()) {
- if (cert == *(node->cert)) {
- if (!node->permanent && node->expires <
- TQDateTime::currentDateTime()) {
- certList.remove(node);
- cfg->deleteGroup(node->cert->getMD5Digest());
- searchRemoveCert(node->cert);
- delete node;
- cacheSaveToDisk();
- return false;
- }
- node->hosts.remove(host);
- certList.remove(node);
- certList.prepend(node);
- cacheSaveToDisk();
- return true;
- }
- }
-
-return false;
-}
-
-
-
-
-///////////////////////////////////////////////////////////////////////////
-
-void KSSLD::caVerifyUpdate() {
- TQString path = TDEGlobal::dirs()->saveLocation("kssl") + "/ca-bundle.crt";
- if (!TQFile::exists(path))
- return;
-
- cfg->setGroup(TQString::null);
- TQ_UINT32 newStamp = TDEGlobal::dirs()->calcResourceHash("config", "ksslcalist", true);
- TQ_UINT32 oldStamp = cfg->readUnsignedNumEntry("ksslcalistStamp");
- if (oldStamp != newStamp)
- {
- caRegenerate();
- cfg->writeEntry("ksslcalistStamp", newStamp);
- cfg->sync();
- }
-}
-
-bool KSSLD::caRegenerate() {
-TQString path = TDEGlobal::dirs()->saveLocation("kssl") + "/ca-bundle.crt";
-
-TQFile out(path);
-
- if (!out.open(IO_WriteOnly))
- return false;
-
-TDEConfig cfg("ksslcalist", true, false);
-
-TQStringList x = cfg.groupList();
-
- for (TQStringList::Iterator i = x.begin();
- i != x.end();
- ++i) {
- if ((*i).isEmpty() || *i == "<default>") continue;
-
- cfg.setGroup(*i);
-
- if (!cfg.readBoolEntry("site", false)) continue;
-
- TQString cert = cfg.readEntry("x509", "");
- if (cert.length() <= 0) continue;
-
- unsigned int xx = cert.length() - 1;
- for (unsigned int j = 0; j < xx/64; j++) {
- cert.insert(64*(j+1)+j, '\n');
- }
- out.writeBlock("-----BEGIN CERTIFICATE-----\n", 28);
- out.writeBlock(cert.latin1(), cert.length());
- out.writeBlock("\n-----END CERTIFICATE-----\n\n", 28);
- out.flush();
- }
-
-return true;
-}
-
-
-
-bool KSSLD::caAdd(TQString certificate, bool ssl, bool email, bool code) {
-KSSLCertificate *x = KSSLCertificate::fromString(certificate.local8Bit());
-
- if (!x) return false;
-
-TDEConfig cfg("ksslcalist", false, false);
-
- cfg.setGroup(x->getSubject());
- cfg.writeEntry("x509", certificate);
- cfg.writeEntry("site", ssl);
- cfg.writeEntry("email", email);
- cfg.writeEntry("code", code);
-
- cfg.sync();
- delete x;
-
-return true;
-}
-
-
-/**
- * @internal
- * Returns a list of certificates as QStrings read from the given file
- */
-static TQStringList caReadCerticatesFromFile(TQString filename) {
-
- TQStringList certificates;
- TQString certificate, temp;
- TQFile file(filename);
-
- if (!file.open(IO_ReadOnly))
- return certificates;
-
- while (!file.atEnd()) {
- file.readLine(temp, 999);
- if (temp.startsWith("-----BEGIN CERTIFICATE-----")) {
- certificate = TQString::null;
- continue;
- }
-
- if (temp.startsWith("-----END CERTIFICATE-----")) {
- certificates.append(certificate);
- certificate = TQString::null;
- continue;
- }
-
- certificate += temp.stripWhiteSpace();
- }
-
- file.close();
-
- return certificates;
-}
-
-bool KSSLD::caAddFromFile(TQString filename, bool ssl, bool email, bool code) {
-
- TQStringList certificates;
- certificates = caReadCerticatesFromFile(filename);
- if (certificates.isEmpty())
- return false;
-
- bool ok = true;
-
- for (TQStringList::Iterator it = certificates.begin();
- it != certificates.end(); ++it ) {
- ok &= caAdd(*it, ssl, email, code);
- }
-
- return ok;
-}
-
-bool KSSLD::caRemoveFromFile(TQString filename) {
-
- TQStringList certificates;
- certificates = caReadCerticatesFromFile(filename);
- if (certificates.isEmpty())
- return false;
-
- bool ok = true;
-
- for (TQStringList::Iterator it = certificates.begin();
- it != certificates.end(); ++it ) {
- TQString certificate = *it;
- KSSLCertificate *x = KSSLCertificate::fromString(certificate.local8Bit());
- ok &= x && caRemove(x->getSubject());
- delete x;
- }
-
- return ok;
-}
-
-
-TQStringList KSSLD::caList() {
-TQStringList x;
-TDEConfig cfg("ksslcalist", true, false);
-
- x = cfg.groupList();
- x.remove("<default>");
-
-return x;
-}
-
-
-bool KSSLD::caUseForSSL(TQString subject) {
-TDEConfig cfg("ksslcalist", true, false);
-
- if (!cfg.hasGroup(subject))
- return false;
-
- cfg.setGroup(subject);
-return cfg.readBoolEntry("site", false);
-}
-
-
-
-bool KSSLD::caUseForEmail(TQString subject) {
-TDEConfig cfg("ksslcalist", true, false);
-
- if (!cfg.hasGroup(subject))
- return false;
-
- cfg.setGroup(subject);
-return cfg.readBoolEntry("email", false);
-}
-
-
-
-bool KSSLD::caUseForCode(TQString subject) {
-TDEConfig cfg("ksslcalist", true, false);
-
- if (!cfg.hasGroup(subject))
- return false;
-
- cfg.setGroup(subject);
-return cfg.readBoolEntry("code", false);
-}
-
-
-bool KSSLD::caRemove(TQString subject) {
-TDEConfig cfg("ksslcalist", false, false);
- if (!cfg.hasGroup(subject))
- return false;
-
- cfg.deleteGroup(subject);
- cfg.sync();
-
-return true;
-}
-
-
-TQString KSSLD::caGetCert(TQString subject) {
-TDEConfig cfg("ksslcalist", true, false);
- if (!cfg.hasGroup(subject))
- return TQString::null;
-
- cfg.setGroup(subject);
-
-return cfg.readEntry("x509", TQString::null);
-}
-
-
-bool KSSLD::caSetUse(TQString subject, bool ssl, bool email, bool code) {
-TDEConfig cfg("ksslcalist", false, false);
- if (!cfg.hasGroup(subject))
- return false;
-
- cfg.setGroup(subject);
-
- cfg.writeEntry("site", ssl);
- cfg.writeEntry("email", email);
- cfg.writeEntry("code", code);
- cfg.sync();
-
-return true;
-}
-
-///////////////////////////////////////////////////////////////////////////
-
-void KSSLD::searchAddCert(KSSLCertificate *cert) {
- skMD5Digest.insert(cert->getMD5Digest(), cert, true);
-
- TQStringList mails;
- cert->getEmails(mails);
- for(TQStringList::const_iterator iter = mails.begin(); iter != mails.end(); ++iter) {
- TQString email = static_cast<const TQString &>(*iter).lower();
- TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(email);
-
- if (it == skEmail.end())
- it = skEmail.insert(email, TQPtrVector<KSSLCertificate>());
-
- TQPtrVector<KSSLCertificate> &elem = *it;
-
- if (elem.findRef(cert) == -1) {
- unsigned int n = 0;
- for(; n < elem.size(); n++) {
- if (!elem.at(n)) {
- elem.insert(n, cert);
- break;
- }
- }
- if (n == elem.size()) {
- elem.resize(n+1);
- elem.insert(n, cert);
- }
- }
- }
-}
-
-
-void KSSLD::searchRemoveCert(KSSLCertificate *cert) {
- skMD5Digest.remove(cert->getMD5Digest());
-
- TQStringList mails;
- cert->getEmails(mails);
- for(TQStringList::const_iterator iter = mails.begin(); iter != mails.end(); ++iter) {
- TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(static_cast<const TQString &>(*iter).lower());
-
- if (it == skEmail.end())
- break;
-
- TQPtrVector<KSSLCertificate> &elem = *it;
-
- int n = elem.findRef(cert);
- if (n != -1)
- elem.remove(n);
- }
-}
-
-
-TQStringList KSSLD::getKDEKeyByEmail(const TQString &email) {
- TQStringList rc;
- TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(email.lower());
-
- kdDebug() << "GETKDEKey " << email.latin1() << endl;
-
- if (it == skEmail.end())
- return rc;
-
- TQPtrVector<KSSLCertificate> &elem = *it;
- for (unsigned int n = 0; n < elem.size(); n++) {
- KSSLCertificate *cert = elem.at(n);
- if (cert) {
- rc.append(cert->getKDEKey());
- }
- }
-
- kdDebug() << "ergebnisse: " << rc.size() << " " << elem.size() << endl;
- return rc;
-}
-
-
-KSSLCertificate KSSLD::getCertByMD5Digest(const TQString &key) {
- TQMap<TQString, KSSLCertificate *>::iterator iter = skMD5Digest.find(key);
-
- kdDebug() << "Searching cert for " << key.latin1() << endl;
-
- if (iter != skMD5Digest.end())
- return **iter;
-
- KSSLCertificate rc; // FIXME: Better way to return a not found condition?
- kdDebug() << "Not found: " << rc.toString().latin1() << endl;
- return rc;
-}
-
-
-///////////////////////////////////////////////////////////////////////////
-
-//
-// Certificate Home methods
-//
-
-TQStringList KSSLD::getHomeCertificateList() {
- return KSSLCertificateHome::getCertificateList();
-}
-
-bool KSSLD::addHomeCertificateFile(TQString filename, TQString password, bool storePass) {
- return KSSLCertificateHome::addCertificate(filename, password, storePass);
-}
-
-bool KSSLD::addHomeCertificatePKCS12(TQString base64cert, TQString passToStore) {
- bool ok;
- KSSLPKCS12 *pkcs12 = KSSLPKCS12::fromString(base64cert, passToStore);
- ok = KSSLCertificateHome::addCertificate(pkcs12, passToStore);
- delete pkcs12;
- return ok;
-}
-
-bool KSSLD::deleteHomeCertificateByFile(TQString filename, TQString password) {
- return KSSLCertificateHome::deleteCertificate(filename, password);
-}
-
-bool KSSLD::deleteHomeCertificateByPKCS12(TQString base64cert, TQString password) {
- bool ok;
- KSSLPKCS12 *pkcs12 = KSSLPKCS12::fromString(base64cert, password);
- ok = KSSLCertificateHome::deleteCertificate(pkcs12);
- delete pkcs12;
- return ok;
-}
-
-bool KSSLD::deleteHomeCertificateByName(TQString name) {
- return KSSLCertificateHome::deleteCertificateByName(name);
-}
-
-
-
-///////////////////////////////////////////////////////////////////////////
-
-#include "kssld.moc"
-
-
-/*
-
- DESIGN - KSSLCertificateCache
- ------
-
- This is the first implementation and I think this cache actually needs
- experimentation to determine which implementation works best. My current
- options are:
-
- (1) Store copies of the X509 certificates in a TQPtrList using a self
- organizing heuristic as described by Munro and Suwanda.
- (2) Store copies of the X509 certificates in a tree structure, perhaps
- a redblack tree, avl tree, or even just a simple binary tree.
- (3) Store the CN's in a tree or list and use them as a hash to retrieve
- the X509 certificates.
- (4) Create "nodes" containing the X509 certificate and place them in
- two structures concurrently, one organized by CN, the other by
- X509 serial number.
-
- This implementation uses (1). (4) is definitely attractive, but I don't
- think it will be necessary to go so crazy with performance, and perhaps
- end up performing poorly in situations where there are very few entries in
- the cache (which is most likely the case most of the time). The style of
- heuristic is move-to-front, not swap-forward. This seems to make more
- sense because the typical user will hit a site at least a few times in a
- row before moving to a new one.
-
- What I worry about most with respect to performance is that cryptographic
- routines are expensive and if we have to perform them on each X509
- certificate until the right one is found, we will perform poorly.
-
- All in all, this code is actually quite crucial for performance on SSL
- website, especially those with many image files loaded via SSL. If a
- site loads 15 images, we will have to run through this code 15 times.
- A heuristic for self organization will make each successive lookup faster.
- Sounds good, doesn't it?
-
- DO NOT ATTEMPT TO GUESS WHICH CERTIFICATES ARE ACCEPTIBLE IN YOUR CODE!!
- ALWAYS USE THE CACHE. IT MAY CHECK THINGS THAT YOU DON'T THINK OF, AND
- ALSO IF THERE IS A BUG IN THE CHECKING CODE, IF IT IS ALL CONTAINED IN
- THIS LIBRARY, A MINOR FIX WILL FIX ALL APPLICATIONS.
- */
-
diff --git a/kio/misc/ktelnetservice.cpp b/kio/misc/ktelnetservice.cpp
deleted file mode 100644
index cf1b5694c..000000000
--- a/kio/misc/ktelnetservice.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- Copyright (c) 2001 Malte Starostik <malte@kde.org>
- based on kmailservice.cpp,
- Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
-
- 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; see the file COPYING. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#include <kapplication.h>
-#include <kmessagebox.h>
-#include <kcmdlineargs.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kprocess.h>
-#include <ksimpleconfig.h>
-
-static const KCmdLineOptions options[] =
-{
- {"+url", 0, 0},
- KCmdLineLastOption
-};
-
-int main(int argc, char **argv)
-{
- KLocale::setMainCatalogue("tdelibs");
- TDECmdLineArgs::init(argc, argv, "ktelnetservice", I18N_NOOP("telnet service"),
- I18N_NOOP("telnet protocol handler"), "unknown");
- TDECmdLineArgs::addCmdLineOptions(options);
-
- TDEApplication app;
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- if (args->count() != 1)
- return 1;
-
- TDEConfig *config = new TDEConfig("kdeglobals", true);
- config->setGroup("General");
- TQString terminal = config->readPathEntry("TerminalApplication", "konsole");
-
- KURL url(args->arg(0));
- TQStringList cmd;
- if (terminal == "konsole")
- cmd << "--noclose";
-
- cmd << "-e";
- if ( url.protocol() == "telnet" )
- cmd << "telnet";
- else if ( url.protocol() == "ssh" )
- cmd << "ssh";
- else if ( url.protocol() == "rlogin" )
- cmd << "rlogin";
- else {
- kdError() << "Invalid protocol " << url.protocol() << endl;
- return 2;
- }
-
- if (!app.authorize("shell_access"))
- {
- KMessageBox::sorry(0,
- i18n("You do not have permission to access the %1 protocol.").arg(url.protocol()));
- return 3;
- }
-
- if (!url.user().isEmpty())
- {
- cmd << "-l";
- cmd << url.user();
- }
-
- TQString host;
- if (!url.host().isEmpty())
- host = url.host(); // telnet://host
- else if (!url.path().isEmpty())
- host = url.path(); // telnet:host
-
- if (host.isEmpty() || host.startsWith("-"))
- {
- kdError() << "Invalid hostname " << host << endl;
- return 2;
- }
-
- cmd << host;
-
- if (url.port()){
- if ( url.protocol() == "ssh" )
- cmd << "-p" << TQString::number(url.port());
- else
- cmd << TQString::number(url.port());
- }
-
- app.tdeinitExec(terminal, cmd);
-
- return 0;
-}
-
-// vim: ts=4 sw=4 noet
diff --git a/kio/misc/rlogin.protocol b/kio/misc/rlogin.protocol
deleted file mode 100644
index 0757e88ab..000000000
--- a/kio/misc/rlogin.protocol
+++ /dev/null
@@ -1,13 +0,0 @@
-[Protocol]
-exec=ktelnetservice %u
-protocol=rlogin
-input=none
-output=none
-helper=true
-listing=
-reading=false
-writing=false
-makedir=false
-deleting=false
-DocPath=kioslave/rlogin.html
-Icon=konsole
diff --git a/kio/misc/ssh.protocol b/kio/misc/ssh.protocol
deleted file mode 100644
index f31a6f4a2..000000000
--- a/kio/misc/ssh.protocol
+++ /dev/null
@@ -1,13 +0,0 @@
-[Protocol]
-exec=ktelnetservice %u
-protocol=ssh
-input=none
-output=none
-helper=true
-listing=false
-reading=false
-writing=false
-makedir=false
-deleting=false
-Icon=konsole
-
diff --git a/kio/misc/tdentlm/CMakeLists.txt b/kio/misc/tdentlm/CMakeLists.txt
deleted file mode 100644
index a846d1dcc..000000000
--- a/kio/misc/tdentlm/CMakeLists.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/tdecore
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### headers ###################################
-
-install(FILES tdentlm.h DESTINATION ${INCLUDE_INSTALL_DIR}/kio )
-
-
-##### tdentlm ###################################
-
-set( target tdentlm )
-
-set( ${target}_SRCS
- tdentlm.cpp des.cpp
-)
-
-tde_add_library( ${target} SHARED
- SOURCES ${${target}_SRCS}
- VERSION 0.0.0
- LINK tdecore-shared
- DESTINATION ${LIB_INSTALL_DIR}
-)
diff --git a/kio/misc/tdentlm/Makefile.am b/kio/misc/tdentlm/Makefile.am
deleted file mode 100644
index 689d0921d..000000000
--- a/kio/misc/tdentlm/Makefile.am
+++ /dev/null
@@ -1,12 +0,0 @@
-INCLUDES=$(all_includes)
-
-lib_LTLIBRARIES = libtdentlm.la
-METASOURCES = AUTO
-
-tdentlmincludedir = $(includedir)/kio
-tdentlminclude_HEADERS = tdentlm.h
-
-libtdentlm_la_SOURCES = tdentlm.cpp des.cpp
-libtdentlm_la_LDFLAGS = $(all_libraries) -version-info 0:0:0 -no-undefined
-libtdentlm_la_LIBADD = $(LIB_TDECORE) $(LIB_QT)
-
diff --git a/kio/misc/tdesasl/CMakeLists.txt b/kio/misc/tdesasl/CMakeLists.txt
deleted file mode 100644
index 27cacfbb9..000000000
--- a/kio/misc/tdesasl/CMakeLists.txt
+++ /dev/null
@@ -1,42 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### headers ###################################
-
-install(FILES tdesasl.h DESTINATION ${INCLUDE_INSTALL_DIR}/kio )
-
-
-##### tdesasl ###################################
-
-set( target tdesasl )
-
-set( ${target}_SRCS
- tdesasl.cpp
-)
-
-tde_add_library( ${target} SHARED
- SOURCES ${${target}_SRCS}
- VERSION 1.2.0
- LINK tdecore-shared
- DESTINATION ${LIB_INSTALL_DIR}
-)
diff --git a/kio/misc/tdesasl/Makefile.am b/kio/misc/tdesasl/Makefile.am
deleted file mode 100644
index 4dd36a6d7..000000000
--- a/kio/misc/tdesasl/Makefile.am
+++ /dev/null
@@ -1,12 +0,0 @@
-INCLUDES=$(all_includes)
-
-lib_LTLIBRARIES = libtdesasl.la
-METASOURCES = AUTO
-
-tdesaslincludedir = $(includedir)/kio
-tdesaslinclude_HEADERS = tdesasl.h
-
-libtdesasl_la_SOURCES = tdesasl.cpp
-libtdesasl_la_LDFLAGS = $(all_libraries) -version-info 3:0:2 -no-undefined
-libtdesasl_la_LIBADD = $(LIB_TDECORE) $(LIB_QT)
-
diff --git a/kio/misc/tdewalletd/CMakeLists.txt b/kio/misc/tdewalletd/CMakeLists.txt
deleted file mode 100644
index 4aaa332aa..000000000
--- a/kio/misc/tdewalletd/CMakeLists.txt
+++ /dev/null
@@ -1,49 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/tdewallet/client
- ${CMAKE_SOURCE_DIR}/tdewallet/backend
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install(FILES tdewalletd.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
-
-
-#### kded_tdewalletd ##############################
-
-set( target kded_tdewalletd )
-
-set( ${target}_SRCS
- tdewalletd.cpp tdewalletd.skel ktimeout.cpp tdewalletwizard.ui
- kbetterthankdialogbase.ui
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK tdeinit_kded-shared tdewalletbackend-shared
- DEPENDENCIES dcopidl
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kio/misc/tdewalletd/tdewalletd.cpp b/kio/misc/tdewalletd/tdewalletd.cpp
deleted file mode 100644
index 3f59f4e91..000000000
--- a/kio/misc/tdewalletd/tdewalletd.cpp
+++ /dev/null
@@ -1,1514 +0,0 @@
-/*
- This file is part of the KDE libraries
-
- Copyright (c) 2002-2004 George Staikos <staikos@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
-*/
-
-#include "kbetterthankdialogbase.h"
-#include "tdewalletwizard.h"
-#include "tdewalletd.h"
-#include "ktimeout.h"
-
-#include <dcopclient.h>
-#include <dcopref.h>
-#include <kactivelabel.h>
-#include <kapplication.h>
-#include <kconfig.h>
-#include <kdebug.h>
-#include <kdirwatch.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kmessagebox.h>
-#include <kpassdlg.h>
-#include <kstandarddirs.h>
-#include <tdewalletentry.h>
-#include <twin.h>
-
-#include <tqdir.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqpushbutton.h>
-#include <tqregexp.h>
-#include <tqstylesheet.h>
-#include <tqvbox.h>
-
-#include <assert.h>
-
-extern "C" {
- KDE_EXPORT KDEDModule *create_tdewalletd(const TQCString &name) {
- return new KWalletD(name);
- }
-}
-
-
-class KWalletTransaction {
- public:
- KWalletTransaction() {
- tType = Unknown;
- transaction = 0L;
- client = 0L;
- modal = false;
- }
-
- ~KWalletTransaction() {
- // Don't delete these!
- transaction = 0L;
- client = 0L;
- }
-
- enum Type { Unknown, Open, ChangePassword, OpenFail };
- DCOPClient *client;
- DCOPClientTransaction *transaction;
- Type tType;
- TQCString rawappid, returnObject;
- TQCString appid;
- uint wId;
- TQString wallet;
- bool modal;
-};
-
-
-KWalletD::KWalletD(const TQCString &name)
-: KDEDModule(name), _failed(0) {
- srand(time(0));
- _showingFailureNotify = false;
- _transactions.setAutoDelete(true);
- _timeouts = new KTimeout(17);
- _closeIdle = false;
- _idleTime = 0;
- connect(_timeouts, TQT_SIGNAL(timedOut(int)), this, TQT_SLOT(timedOut(int)));
- reconfigure();
- TDEGlobal::dirs()->addResourceType("tdewallet", "share/apps/tdewallet");
- connect(TDEApplication::dcopClient(),
- TQT_SIGNAL(applicationRemoved(const TQCString&)),
- this,
- TQT_SLOT(slotAppUnregistered(const TQCString&)));
- _dw = new KDirWatch(this, "KWallet Directory Watcher");
- _dw->addDir(TDEGlobal::dirs()->saveLocation("tdewallet"));
- _dw->startScan(true);
- connect(_dw, TQT_SIGNAL(dirty(const TQString&)), this, TQT_SLOT(emitWalletListDirty()));
-}
-
-
-KWalletD::~KWalletD() {
- delete _timeouts;
- _timeouts = 0;
-
- closeAllWallets();
- _transactions.clear();
-}
-
-
-int KWalletD::generateHandle() {
- int rc;
-
- // ASSUMPTION: RAND_MAX is fairly large.
- do {
- rc = rand();
- } while (_wallets.find(rc) || rc == 0);
-
- return rc;
-}
-
-
-void KWalletD::processTransactions() {
- static bool processing = false;
-
- if (processing) {
- return;
- }
-
- processing = true;
-
- // Process remaining transactions
- KWalletTransaction *xact;
- while (!_transactions.isEmpty()) {
- xact = _transactions.first();
- TQCString replyType;
- int res;
-
- assert(xact->tType != KWalletTransaction::Unknown);
-
- switch (xact->tType) {
- case KWalletTransaction::Open:
- res = doTransactionOpen(xact->appid, xact->wallet, xact->wId, xact->modal);
- replyType = "int";
- if (!xact->returnObject.isEmpty()) {
- DCOPRef(xact->rawappid, xact->returnObject).send("walletOpenResult", res);
- }
-
- // multiple requests from the same client
- // should not produce multiple password
- // dialogs on a failure
- if (res < 0) {
- TQPtrListIterator<KWalletTransaction> it(_transactions);
- KWalletTransaction *x;
- while ((x = it.current()) && x != xact) {
- ++it;
- }
- if (x) {
- ++it;
- }
- while ((x = it.current())) {
- if (xact->appid == x->appid && x->tType == KWalletTransaction::Open && x->wallet == xact->wallet && x->wId == xact->wId) {
- x->tType = KWalletTransaction::OpenFail;
- }
- ++it;
- }
- }
- break;
- case KWalletTransaction::OpenFail:
- res = -1;
- replyType = "int";
- if (!xact->returnObject.isEmpty()) {
- DCOPRef(xact->rawappid, xact->returnObject).send("walletOpenResult", res);
- }
- break;
- case KWalletTransaction::ChangePassword:
- doTransactionChangePassword(xact->appid, xact->wallet, xact->wId);
- // fall through - no return
- default:
- _transactions.removeRef(xact);
- continue;
- }
-
- if (xact->returnObject.isEmpty() && xact->tType != KWalletTransaction::ChangePassword) {
- TQByteArray replyData;
- TQDataStream stream(replyData, IO_WriteOnly);
- stream << res;
- xact->client->endTransaction(xact->transaction, replyType, replyData);
- }
- _transactions.removeRef(xact);
- }
-
- processing = false;
-}
-
-
-void KWalletD::openAsynchronous(const TQString& wallet, const TQCString& returnObject, uint wId) {
- DCOPClient *dc = callingDcopClient();
- if (!dc) {
- return;
- }
-
- TQCString appid = dc->senderId();
- if (!_enabled ||
- !TQRegExp("^[A-Za-z0-9]+[A-Za-z0-9\\s\\-_]*$").exactMatch(wallet)) {
- DCOPRef(appid, returnObject).send("walletOpenResult", -1);
- return;
- }
-
- TQCString peerName = friendlyDCOPPeerName();
-
- KWalletTransaction *xact = new KWalletTransaction;
-
- xact->appid = peerName;
- xact->rawappid = appid;
- xact->client = callingDcopClient();
- xact->wallet = wallet;
- xact->wId = wId;
- xact->tType = KWalletTransaction::Open;
- xact->returnObject = returnObject;
- _transactions.append(xact);
-
- DCOPRef(appid, returnObject).send("walletOpenResult", 0);
-
- TQTimer::singleShot(0, this, TQT_SLOT(processTransactions()));
- checkActiveDialog();
-}
-
-
-int KWalletD::openPath(const TQString& path, uint wId) {
- if (!_enabled) { // guard
- return -1;
- }
-
- // FIXME: setup transaction
- int rc = internalOpen(friendlyDCOPPeerName(), path, true, wId);
- return rc;
-}
-
-
-int KWalletD::open(const TQString& wallet, uint wId) {
- if (!_enabled) { // guard
- return -1;
- }
-
- if (!TQRegExp("^[A-Za-z0-9]+[A-Za-z0-9\\s\\-_]*$").exactMatch(wallet)) {
- return -1;
- }
-
- TQCString appid = friendlyDCOPPeerName();
-
- KWalletTransaction *xact = new KWalletTransaction;
- _transactions.append(xact);
-
- xact->appid = appid;
- xact->client = callingDcopClient();
- xact->transaction = xact->client->beginTransaction();
- xact->wallet = wallet;
- xact->wId = wId;
- xact->tType = KWalletTransaction::Open;
- xact->modal = true; // mark dialogs as modal, the app has blocking wait
- TQTimer::singleShot(0, this, TQT_SLOT(processTransactions()));
- checkActiveDialog();
- return 0; // process later
-}
-
-
-// Sets up a dialog that will be shown by tdewallet.
-void KWalletD::setupDialog( TQWidget* dialog, WId wId, const TQCString& appid, bool modal ) {
- if( wId != 0 )
- KWin::setMainWindow( dialog, wId ); // correct, set dialog parent
- else {
- if( appid.isEmpty())
- kdWarning() << "Using tdewallet without parent window!" << endl;
- else
- kdWarning() << "Application '" << appid << "' using tdewallet without parent window!" << endl;
- // allow dialog activation even if it interrupts, better than trying hacks
- // with keeping the dialog on top or on all desktops
- kapp->updateUserTimestamp();
- }
- if( modal )
- KWin::setState( dialog->winId(), NET::Modal );
- else
- KWin::clearState( dialog->winId(), NET::Modal );
- activeDialog = dialog;
-}
-
-// If there's a dialog already open and another application tries some operation that'd lead to
-// opening a dialog, that application will be blocked by this dialog. A proper solution would
-// be to set the second application's window also as a parent for the active dialog, so that
-// KWin properly handles focus changes and so on, but there's currently no support for multiple
-// dialog parents. Hopefully to be done in KDE4, for now just use all kinds of bad hacks to make
-// sure the user doesn't overlook the active dialog.
-void KWalletD::checkActiveDialog() {
- if( !activeDialog || !activeDialog->isShown())
- return;
- kapp->updateUserTimestamp();
- KWin::setState( activeDialog->winId(), NET::KeepAbove );
- KWin::setOnAllDesktops( activeDialog->winId(), true );
- KWin::forceActiveWindow( activeDialog->winId());
-}
-
-int KWalletD::doTransactionOpen(const TQCString& appid, const TQString& wallet, uint wId, bool modal) {
- if (_firstUse && !wallets().contains(KWallet::Wallet::LocalWallet())) {
- // First use wizard
- KWalletWizard *wiz = new KWalletWizard(0);
- setupDialog( wiz, wId, appid, modal );
- int rc = wiz->exec();
- if (rc == TQDialog::Accepted) {
- TDEConfig cfg("tdewalletrc");
- cfg.setGroup("Wallet");
- cfg.writeEntry("First Use", false);
- cfg.writeEntry("Enabled", wiz->_useWallet->isChecked());
- cfg.writeEntry("Close When Idle", wiz->_closeIdle->isChecked());
- cfg.writeEntry("Use One Wallet", !wiz->_networkWallet->isChecked());
- cfg.sync();
- reconfigure();
-
- if (!wiz->_useWallet->isChecked()) {
- delete wiz;
- return -1;
- }
-
- // Create the wallet
- KWallet::Backend *b = new KWallet::Backend(KWallet::Wallet::LocalWallet());
- TQByteArray p;
- p.duplicate(wiz->_pass1->text().utf8(), wiz->_pass1->text().length());
- b->open(p);
- b->createFolder(KWallet::Wallet::PasswordFolder());
- b->createFolder(KWallet::Wallet::FormDataFolder());
- b->close(p);
- p.fill(0);
- delete b;
- delete wiz;
- } else {
- delete wiz;
- return -1;
- }
- } else if (_firstUse) {
- TDEConfig cfg("tdewalletrc");
- _firstUse = false;
- cfg.setGroup("Wallet");
- cfg.writeEntry("First Use", false);
- cfg.sync();
- }
-
- int rc = internalOpen(appid, wallet, false, wId, modal);
- return rc;
-}
-
-int KWalletD::tryOpen(const TQString& wallet, const TQCString& password)
-{
- if (isOpen(wallet))
- return 0;
-
- if (_tryOpenBlocked.isActive()) {
- kdDebug() << "tryOpen is active.." << endl;
- return -1;
- }
-
- if (!KWallet::Backend::exists(wallet))
- return -2;
-
- KWallet::Backend *b = new KWallet::Backend(wallet, false /*isPath*/);
- int rc = b->open(TQByteArray().duplicate(password, strlen(password)));
- if (rc == 0) {
- _wallets.insert(rc = generateHandle(), b);
- _passwords[wallet] = password;
- b->ref();
- _tryOpenBlocked.stop();
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << wallet;
- emitDCOPSignal("walletOpened(TQString)", data);
- }
- else {
- delete b;
- // make sure that we're not bombed with a dictionary attack
- _tryOpenBlocked.start (30 * 1000, true /*single shot*/);
- if (++_failed > 5) {
- _failed = 0;
- TQTimer::singleShot(0, this, TQT_SLOT(notifyFailures()));
- }
-
- rc = -1;
- }
- return rc;
-}
-
-int KWalletD::internalOpen(const TQCString& appid, const TQString& wallet, bool isPath, WId w, bool modal) {
- int rc = -1;
- bool brandNew = false;
-
- TQCString thisApp;
- if (appid.isEmpty()) {
- thisApp = "TDE System";
- } else {
- thisApp = appid;
- }
-
- if (implicitDeny(wallet, thisApp)) {
- return -1;
- }
-
- for (TQIntDictIterator<KWallet::Backend> i(_wallets); i.current(); ++i) {
- if (i.current()->walletName() == wallet) {
- rc = i.currentKey();
- break;
- }
- }
-
- if (rc == -1) {
- if (_wallets.count() > 20) {
- kdDebug() << "Too many wallets open." << endl;
- return -1;
- }
-
- KWallet::Backend *b = new KWallet::Backend(wallet, isPath);
- KPasswordDialog *kpd = 0L;
- bool emptyPass = false;
- if ((isPath && TQFile::exists(wallet)) || (!isPath && KWallet::Backend::exists(wallet))) {
- int pwless = b->open(TQByteArray());
- if (0 != pwless || !b->isOpen()) {
- if (pwless == 0) {
- // release, start anew
- delete b;
- b = new KWallet::Backend(wallet, isPath);
- }
- kpd = new KPasswordDialog(KPasswordDialog::Password, false, 0);
- if (appid.isEmpty()) {
- kpd->setPrompt(i18n("<qt>TDE has requested to open the wallet '<b>%1</b>'. Please enter the password for this wallet below.").arg(TQStyleSheet::escape(wallet)));
- } else {
- kpd->setPrompt(i18n("<qt>The application '<b>%1</b>' has requested to open the wallet '<b>%2</b>'. Please enter the password for this wallet below.").arg(TQStyleSheet::escape(appid)).arg(TQStyleSheet::escape(wallet)));
- }
- brandNew = false;
- kpd->setButtonOK(KGuiItem(i18n("&Open"),"fileopen"));
- } else {
- emptyPass = true;
- }
- } else if (wallet == KWallet::Wallet::LocalWallet() ||
- wallet == KWallet::Wallet::NetworkWallet()) {
- // Auto create these wallets.
- kpd = new KPasswordDialog(KPasswordDialog::NewPassword, false, 0);
- if (appid.isEmpty()) {
- kpd->setPrompt(i18n("TDE has requested to open the wallet. This is used to store sensitive data in a secure fashion. Please enter a password to use with this wallet or click cancel to deny the application's request."));
- } else {
- kpd->setPrompt(i18n("<qt>The application '<b>%1</b>' has requested to open the TDE wallet. This is used to store sensitive data in a secure fashion. Please enter a password to use with this wallet or click cancel to deny the application's request.").arg(TQStyleSheet::escape(appid)));
- }
- brandNew = true;
- kpd->setButtonOK(KGuiItem(i18n("&Open"),"fileopen"));
- } else {
- kpd = new KPasswordDialog(KPasswordDialog::NewPassword, false, 0);
- if (appid.length() == 0) {
- kpd->setPrompt(i18n("<qt>TDE has requested to create a new wallet named '<b>%1</b>'. Please choose a password for this wallet, or cancel to deny the application's request.").arg(TQStyleSheet::escape(wallet)));
- } else {
- kpd->setPrompt(i18n("<qt>The application '<b>%1</b>' has requested to create a new wallet named '<b>%2</b>'. Please choose a password for this wallet, or cancel to deny the application's request.").arg(TQStyleSheet::escape(appid)).arg(TQStyleSheet::escape(wallet)));
- }
- brandNew = true;
- kpd->setButtonOK(KGuiItem(i18n("C&reate"),"filenew"));
- }
-
- if (kpd) {
- kpd->setCaption(i18n("TDE Wallet Service"));
- kpd->setAllowEmptyPasswords(true);
- }
-
- const char *p = 0L;
- while (!b->isOpen()) {
- assert(kpd); // kpd can't be null if isOpen() is false
- setupDialog( kpd, w, appid, modal );
- if (kpd->exec() == KDialog::Accepted) {
- p = kpd->password();
- int rc = b->open(TQByteArray().duplicate(p, strlen(p)));
- if (!b->isOpen()) {
- kpd->setPrompt(i18n("<qt>Error opening the wallet '<b>%1</b>'. Please try again.<br>(Error code %2: %3)").arg(TQStyleSheet::escape(wallet)).arg(rc).arg(KWallet::Backend::openRCToString(rc)));
- kpd->clearPassword();
- }
- } else {
- break;
- }
- }
-
- if (!emptyPass && (!p || !b->isOpen())) {
- delete b;
- delete kpd;
- return -1;
- }
-
- if (emptyPass && _openPrompt && !isAuthorizedApp(appid, wallet, w)) {
- delete b;
- delete kpd;
- return -1;
- }
-
- _wallets.insert(rc = generateHandle(), b);
- if (emptyPass) {
- _passwords[wallet] = "";
- } else {
- _passwords[wallet] = p;
- }
- _handles[appid].append(rc);
-
- delete kpd; // don't refactor this!! Argh I hate KPassDlg
-
- if (brandNew) {
- createFolder(rc, KWallet::Wallet::PasswordFolder());
- createFolder(rc, KWallet::Wallet::FormDataFolder());
- }
-
- b->ref();
- if (_closeIdle && _timeouts) {
- _timeouts->addTimer(rc, _idleTime);
- }
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << wallet;
- if (brandNew) {
- emitDCOPSignal("walletCreated(TQString)", data);
- }
- emitDCOPSignal("walletOpened(TQString)", data);
- if (_wallets.count() == 1 && _launchManager) {
- TDEApplication::startServiceByDesktopName("tdewalletmanager-tdewalletd");
- }
- } else {
- if (!_handles[appid].contains(rc) && _openPrompt && !isAuthorizedApp(appid, wallet, w)) {
- return -1;
- }
- _handles[appid].append(rc);
- _wallets.find(rc)->ref();
- }
-
- return rc;
-}
-
-
-bool KWalletD::isAuthorizedApp(const TQCString& appid, const TQString& wallet, WId w) {
- int response = 0;
-
- TQCString thisApp;
- if (appid.isEmpty()) {
- thisApp = "TDE System";
- } else {
- thisApp = appid;
- }
-
- if (!implicitAllow(wallet, thisApp)) {
- KBetterThanKDialogBase *dialog = new KBetterThanKDialogBase;
- if (appid.isEmpty()) {
- dialog->setLabel(i18n("<qt>TDE has requested access to the open wallet '<b>%1</b>'.").arg(TQStyleSheet::escape(wallet)));
- } else {
- dialog->setLabel(i18n("<qt>The application '<b>%1</b>' has requested access to the open wallet '<b>%2</b>'.").arg(TQStyleSheet::escape(TQString(appid))).arg(TQStyleSheet::escape(wallet)));
- }
- setupDialog( dialog, w, appid, false );
- response = dialog->exec();
- delete dialog;
- }
-
- if (response == 0 || response == 1) {
- if (response == 1) {
- TDEConfig cfg("tdewalletrc");
- cfg.setGroup("Auto Allow");
- TQStringList apps = cfg.readListEntry(wallet);
- if (!apps.contains(thisApp)) {
- apps += thisApp;
- _implicitAllowMap[wallet] += thisApp;
- cfg.writeEntry(wallet, apps);
- cfg.sync();
- }
- }
- } else if (response == 3) {
- TDEConfig cfg("tdewalletrc");
- cfg.setGroup("Auto Deny");
- TQStringList apps = cfg.readListEntry(wallet);
- if (!apps.contains(thisApp)) {
- apps += thisApp;
- _implicitDenyMap[wallet] += thisApp;
- cfg.writeEntry(wallet, apps);
- cfg.sync();
- }
- return false;
- } else {
- return false;
- }
- return true;
-}
-
-
-int KWalletD::deleteWallet(const TQString& wallet) {
- TQString path = TDEGlobal::dirs()->saveLocation("tdewallet") + TQDir::separator() + wallet + ".kwl";
-
- if (TQFile::exists(path)) {
- close(wallet, true);
- TQFile::remove(path);
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << wallet;
- emitDCOPSignal("walletDeleted(TQString)", data);
- return 0;
- }
-
- return -1;
-}
-
-
-void KWalletD::changePassword(const TQString& wallet, uint wId) {
- TQCString appid = friendlyDCOPPeerName();
-
- KWalletTransaction *xact = new KWalletTransaction;
-
- xact->appid = appid;
- xact->client = callingDcopClient();
- xact->wallet = wallet;
- xact->wId = wId;
- xact->tType = KWalletTransaction::ChangePassword;
-
- _transactions.append(xact);
-
- TQTimer::singleShot(0, this, TQT_SLOT(processTransactions()));
- checkActiveDialog();
-}
-
-
-void KWalletD::doTransactionChangePassword(const TQCString& appid, const TQString& wallet, uint wId) {
- TQIntDictIterator<KWallet::Backend> it(_wallets);
- KWallet::Backend *w = 0L;
- int handle = -1;
- bool reclose = false;
-
- for (; it.current(); ++it) {
- if (it.current()->walletName() == wallet) {
- break;
- }
- }
-
- if (!it.current()) {
- handle = doTransactionOpen(appid, wallet, wId,false);
- if (-1 == handle) {
- KMessageBox::sorryWId(wId, i18n("Unable to open wallet. The wallet must be opened in order to change the password."), i18n("TDE Wallet Service"));
- return;
- }
-
- w = _wallets.find(handle);
- reclose = true;
- } else {
- handle = it.currentKey();
- w = it.current();
- }
-
- assert(w);
-
- KPasswordDialog *kpd;
- kpd = new KPasswordDialog(KPasswordDialog::NewPassword, false, 0);
- kpd->setPrompt(i18n("<qt>Please choose a new password for the wallet '<b>%1</b>'.").arg(TQStyleSheet::escape(wallet)));
- kpd->setCaption(i18n("TDE Wallet Service"));
- kpd->setAllowEmptyPasswords(true);
- setupDialog( kpd, wId, appid, false );
- if (kpd->exec() == KDialog::Accepted) {
- const char *p = kpd->password();
- if (p) {
- _passwords[wallet] = p;
- TQByteArray pa;
- pa.duplicate(p, strlen(p));
- int rc = w->close(pa);
- if (rc < 0) {
- KMessageBox::sorryWId(wId, i18n("Error re-encrypting the wallet. Password was not changed."), i18n("TDE Wallet Service"));
- reclose = true;
- } else {
- rc = w->open(pa);
- if (rc < 0) {
- KMessageBox::sorryWId(wId, i18n("Error reopening the wallet. Data may be lost."), i18n("TDE Wallet Service"));
- reclose = true;
- }
- }
- }
- }
-
- delete kpd;
-
- if (reclose) {
- close(handle, true);
- }
-}
-
-
-int KWalletD::close(const TQString& wallet, bool force) {
- int handle = -1;
- KWallet::Backend *w = 0L;
-
- for (TQIntDictIterator<KWallet::Backend> it(_wallets);
- it.current();
- ++it) {
- if (it.current()->walletName() == wallet) {
- handle = it.currentKey();
- w = it.current();
- break;
- }
- }
-
- return closeWallet(w, handle, force);
-}
-
-
-int KWalletD::closeWallet(KWallet::Backend *w, int handle, bool force) {
- if (w) {
- const TQString& wallet = w->walletName();
- assert(_passwords.contains(wallet));
- if (w->refCount() == 0 || force) {
- invalidateHandle(handle);
- if (_closeIdle && _timeouts) {
- _timeouts->removeTimer(handle);
- }
- _wallets.remove(handle);
- if (_passwords.contains(wallet)) {
- w->close(TQByteArray().duplicate(_passwords[wallet].data(), _passwords[wallet].length()));
- _passwords[wallet].fill(0);
- _passwords.remove(wallet);
- }
- doCloseSignals(handle, wallet);
- delete w;
- return 0;
- }
- return 1;
- }
-
- return -1;
-}
-
-
-int KWalletD::close(int handle, bool force) {
- TQCString appid = friendlyDCOPPeerName();
- KWallet::Backend *w = _wallets.find(handle);
- bool contains = false;
-
- if (w) { // the handle is valid
- if (_handles.contains(appid)) { // we know this app
- if (_handles[appid].contains(handle)) {
- // the app owns this handle
- _handles[appid].remove(_handles[appid].find(handle));
- contains = true;
- if (_handles[appid].isEmpty()) {
- _handles.remove(appid);
- }
- }
- }
-
- // watch the side effect of the deref()
- if ((contains && w->deref() == 0 && !_leaveOpen) || force) {
- if (_closeIdle && _timeouts) {
- _timeouts->removeTimer(handle);
- }
- _wallets.remove(handle);
- if (force) {
- invalidateHandle(handle);
- }
- if (_passwords.contains(w->walletName())) {
- w->close(TQByteArray().duplicate(_passwords[w->walletName()].data(), _passwords[w->walletName()].length()));
- _passwords[w->walletName()].fill(0);
- _passwords.remove(w->walletName());
- }
- doCloseSignals(handle, w->walletName());
- delete w;
- return 0;
- }
- return 1; // not closed
- }
-
- return -1; // not open to begin with, or other error
-}
-
-
-bool KWalletD::isOpen(const TQString& wallet) const {
- for (TQIntDictIterator<KWallet::Backend> it(_wallets);
- it.current();
- ++it) {
- if (it.current()->walletName() == wallet) {
- return true;
- }
- }
- return false;
-}
-
-
-bool KWalletD::isOpen(int handle) {
- if (handle == 0) {
- return false;
- }
-
- KWallet::Backend *rc = _wallets.find(handle);
-
- if (rc == 0 && ++_failed > 5) {
- _failed = 0;
- TQTimer::singleShot(0, this, TQT_SLOT(notifyFailures()));
- } else if (rc != 0) {
- _failed = 0;
- }
-
- return rc != 0;
-}
-
-
-TQStringList KWalletD::wallets() const {
- TQString path = TDEGlobal::dirs()->saveLocation("tdewallet");
- TQDir dir(path, "*.kwl");
- TQStringList rc;
-
- dir.setFilter(TQDir::Files | TQDir::NoSymLinks);
-
- const TQFileInfoList *list = dir.entryInfoList();
- TQFileInfoListIterator it(*list);
- TQFileInfo *fi;
- while ((fi = it.current()) != 0L) {
- TQString fn = fi->fileName();
- if (fn.endsWith(".kwl")) {
- fn.truncate(fn.length()-4);
- }
- rc += fn;
- ++it;
- }
- return rc;
-}
-
-
-void KWalletD::sync(int handle) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- }
-}
-
-
-TQStringList KWalletD::folderList(int handle) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- return b->folderList();
- }
-
- return TQStringList();
-}
-
-
-bool KWalletD::hasFolder(int handle, const TQString& f) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- return b->hasFolder(f);
- }
-
- return false;
-}
-
-
-bool KWalletD::removeFolder(int handle, const TQString& f) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- bool rc = b->removeFolder(f);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << b->walletName();
- emitDCOPSignal("folderListUpdated(TQString)", data);
- return rc;
- }
-
- return false;
-}
-
-
-bool KWalletD::createFolder(int handle, const TQString& f) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- bool rc = b->createFolder(f);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << b->walletName();
- emitDCOPSignal("folderListUpdated(TQString)", data);
- return rc;
- }
-
- return false;
-}
-
-
-TQByteArray KWalletD::readMap(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- KWallet::Entry *e = b->readEntry(key);
- if (e && e->type() == KWallet::Wallet::Map) {
- return e->map();
- }
- }
-
- return TQByteArray();
-}
-
-
-TQMap<TQString,TQByteArray> KWalletD::readMapList(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- TQPtrList<KWallet::Entry> e = b->readEntryList(key);
- TQMap<TQString, TQByteArray> rc;
- TQPtrListIterator<KWallet::Entry> it(e);
- KWallet::Entry *entry;
- while ((entry = it.current())) {
- if (entry->type() == KWallet::Wallet::Map) {
- rc.insert(entry->key(), entry->map());
- }
- ++it;
- }
- return rc;
- }
-
- return TQMap<TQString, TQByteArray>();
-}
-
-
-TQByteArray KWalletD::readEntry(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- KWallet::Entry *e = b->readEntry(key);
- if (e) {
- return e->value();
- }
- }
-
- return TQByteArray();
-}
-
-
-TQMap<TQString, TQByteArray> KWalletD::readEntryList(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- TQPtrList<KWallet::Entry> e = b->readEntryList(key);
- TQMap<TQString, TQByteArray> rc;
- TQPtrListIterator<KWallet::Entry> it(e);
- KWallet::Entry *entry;
- while ((entry = it.current())) {
- rc.insert(entry->key(), entry->value());
- ++it;
- }
- return rc;
- }
-
- return TQMap<TQString, TQByteArray>();
-}
-
-
-TQStringList KWalletD::entryList(int handle, const TQString& folder) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- return b->entryList();
- }
-
- return TQStringList();
-}
-
-
-TQString KWalletD::readPassword(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- KWallet::Entry *e = b->readEntry(key);
- if (e && e->type() == KWallet::Wallet::Password) {
- return e->password();
- }
- }
-
- return TQString::null;
-}
-
-
-TQMap<TQString, TQString> KWalletD::readPasswordList(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- TQPtrList<KWallet::Entry> e = b->readEntryList(key);
- TQMap<TQString, TQString> rc;
- TQPtrListIterator<KWallet::Entry> it(e);
- KWallet::Entry *entry;
- while ((entry = it.current())) {
- if (entry->type() == KWallet::Wallet::Password) {
- rc.insert(entry->key(), entry->password());
- }
- ++it;
- }
- return rc;
- }
-
- return TQMap<TQString, TQString>();
-}
-
-
-int KWalletD::writeMap(int handle, const TQString& folder, const TQString& key, const TQByteArray& value) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- KWallet::Entry e;
- e.setKey(key);
- e.setValue(value);
- e.setType(KWallet::Wallet::Map);
- b->writeEntry(&e);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- emitFolderUpdated(b->walletName(), folder);
- return 0;
- }
-
- return -1;
-}
-
-
-int KWalletD::writeEntry(int handle, const TQString& folder, const TQString& key, const TQByteArray& value, int entryType) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- KWallet::Entry e;
- e.setKey(key);
- e.setValue(value);
- e.setType(KWallet::Wallet::EntryType(entryType));
- b->writeEntry(&e);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- emitFolderUpdated(b->walletName(), folder);
- return 0;
- }
-
- return -1;
-}
-
-
-int KWalletD::writeEntry(int handle, const TQString& folder, const TQString& key, const TQByteArray& value) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- KWallet::Entry e;
- e.setKey(key);
- e.setValue(value);
- e.setType(KWallet::Wallet::Stream);
- b->writeEntry(&e);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- emitFolderUpdated(b->walletName(), folder);
- return 0;
- }
-
- return -1;
-}
-
-
-int KWalletD::writePassword(int handle, const TQString& folder, const TQString& key, const TQString& value) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- KWallet::Entry e;
- e.setKey(key);
- e.setValue(value);
- e.setType(KWallet::Wallet::Password);
- b->writeEntry(&e);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- emitFolderUpdated(b->walletName(), folder);
- return 0;
- }
-
- return -1;
-}
-
-
-int KWalletD::entryType(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- if (!b->hasFolder(folder)) {
- return KWallet::Wallet::Unknown;
- }
- b->setFolder(folder);
- if (b->hasEntry(key)) {
- return b->readEntry(key)->type();
- }
- }
-
- return KWallet::Wallet::Unknown;
-}
-
-
-bool KWalletD::hasEntry(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- if (!b->hasFolder(folder)) {
- return false;
- }
- b->setFolder(folder);
- return b->hasEntry(key);
- }
-
- return false;
-}
-
-
-int KWalletD::removeEntry(int handle, const TQString& folder, const TQString& key) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- if (!b->hasFolder(folder)) {
- return 0;
- }
- b->setFolder(folder);
- bool rc = b->removeEntry(key);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- emitFolderUpdated(b->walletName(), folder);
- return rc ? 0 : -3;
- }
-
- return -1;
-}
-
-
-void KWalletD::slotAppUnregistered(const TQCString& app) {
- if (_handles.contains(app)) {
- TQValueList<int> l = _handles[app];
- for (TQValueList<int>::Iterator i = l.begin(); i != l.end(); ++i) {
- _handles[app].remove(*i);
- KWallet::Backend *w = _wallets.find(*i);
- if (w && !_leaveOpen && 0 == w->deref()) {
- close(w->walletName(), true);
- }
- }
- _handles.remove(app);
- }
-}
-
-
-void KWalletD::invalidateHandle(int handle) {
- for (TQMap<TQCString,TQValueList<int> >::Iterator i = _handles.begin();
- i != _handles.end();
- ++i) {
- i.data().remove(handle);
- }
-}
-
-
-KWallet::Backend *KWalletD::getWallet(const TQCString& appid, int handle) {
- if (handle == 0) {
- return 0L;
- }
-
- KWallet::Backend *w = _wallets.find(handle);
-
- if (w) { // the handle is valid
- if (_handles.contains(appid)) { // we know this app
- if (_handles[appid].contains(handle)) {
- // the app owns this handle
- _failed = 0;
- if (_closeIdle && _timeouts) {
- _timeouts->resetTimer(handle, _idleTime);
- }
- return w;
- }
- }
- }
-
- if (++_failed > 5) {
- _failed = 0;
- TQTimer::singleShot(0, this, TQT_SLOT(notifyFailures()));
- }
-
- return 0L;
-}
-
-
-void KWalletD::notifyFailures() {
- if (!_showingFailureNotify) {
- _showingFailureNotify = true;
- KMessageBox::information(0, i18n("There have been repeated failed attempts to gain access to a wallet. An application may be misbehaving."), i18n("TDE Wallet Service"));
- _showingFailureNotify = false;
- }
-}
-
-
-void KWalletD::doCloseSignals(int handle, const TQString& wallet) {
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << handle;
- emitDCOPSignal("walletClosed(int)", data);
-
- TQByteArray data2;
- TQDataStream ds2(data2, IO_WriteOnly);
- ds2 << wallet;
- emitDCOPSignal("walletClosed(TQString)", data2);
-
- if (_wallets.isEmpty()) {
- emitDCOPSignal("allWalletsClosed()", TQByteArray());
- }
-}
-
-
-int KWalletD::renameEntry(int handle, const TQString& folder, const TQString& oldName, const TQString& newName) {
- KWallet::Backend *b;
-
- if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
- b->setFolder(folder);
- int rc = b->renameEntry(oldName, newName);
- // write changes to disk immediately
- TQByteArray p;
- TQString wallet = b->walletName();
- p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
- b->sync(p);
- p.fill(0);
- emitFolderUpdated(b->walletName(), folder);
- return rc;
- }
-
- return -1;
-}
-
-
-TQStringList KWalletD::users(const TQString& wallet) const {
- TQStringList rc;
-
- for (TQIntDictIterator<KWallet::Backend> it(_wallets);
- it.current();
- ++it) {
- if (it.current()->walletName() == wallet) {
- for (TQMap<TQCString,TQValueList<int> >::ConstIterator hit = _handles.begin(); hit != _handles.end(); ++hit) {
- if (hit.data().contains(it.currentKey())) {
- rc += hit.key();
- }
- }
- break;
- }
- }
-
- return rc;
-}
-
-
-bool KWalletD::disconnectApplication(const TQString& wallet, const TQCString& application) {
- for (TQIntDictIterator<KWallet::Backend> it(_wallets);
- it.current();
- ++it) {
- if (it.current()->walletName() == wallet) {
- if (_handles[application].contains(it.currentKey())) {
- _handles[application].remove(it.currentKey());
-
- if (_handles[application].isEmpty()) {
- _handles.remove(application);
- }
-
- if (it.current()->deref() == 0) {
- close(it.current()->walletName(), true);
- }
-
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << wallet;
- ds << application;
- emitDCOPSignal("applicationDisconnected(TQString,TQCString)", data);
-
- return true;
- }
- }
- }
-
- return false;
-}
-
-
-void KWalletD::emitFolderUpdated(const TQString& wallet, const TQString& folder) {
- TQByteArray data;
- TQDataStream ds(data, IO_WriteOnly);
- ds << wallet;
- ds << folder;
- emitDCOPSignal("folderUpdated(TQString,TQString)", data);
-}
-
-
-void KWalletD::emitWalletListDirty() {
- emitDCOPSignal("walletListDirty()", TQByteArray());
-}
-
-
-void KWalletD::reconfigure() {
- TDEConfig cfg("tdewalletrc");
- cfg.setGroup("Wallet");
- _firstUse = cfg.readBoolEntry("First Use", true);
- _enabled = cfg.readBoolEntry("Enabled", true);
- _launchManager = cfg.readBoolEntry("Launch Manager", true);
- _leaveOpen = cfg.readBoolEntry("Leave Open", false);
- bool idleSave = _closeIdle;
- _closeIdle = cfg.readBoolEntry("Close When Idle", false);
- _openPrompt = cfg.readBoolEntry("Prompt on Open", true);
- int timeSave = _idleTime;
- // in minutes!
- _idleTime = cfg.readNumEntry("Idle Timeout", 10) * 60 * 1000;
-
- if (cfg.readBoolEntry("Close on Screensaver", false)) {
- connectDCOPSignal("kdesktop", "KScreensaverIface", "KDE_start_screensaver()", "closeAllWallets()", false);
- } else {
- disconnectDCOPSignal("kdesktop", "KScreensaverIface", "KDE_start_screensaver()", "closeAllWallets()");
- }
-
- // Handle idle changes
- if (_closeIdle) {
- if (_idleTime != timeSave) { // Timer length changed
- TQIntDictIterator<KWallet::Backend> it(_wallets);
- for (; it.current(); ++it) {
- _timeouts->resetTimer(it.currentKey(), _idleTime);
- }
- }
-
- if (!idleSave) { // add timers for all the wallets
- TQIntDictIterator<KWallet::Backend> it(_wallets);
- for (; it.current(); ++it) {
- _timeouts->addTimer(it.currentKey(), _idleTime);
- }
- }
- } else {
- _timeouts->clear();
- }
-
- // Update the implicit allow stuff
- _implicitAllowMap.clear();
- cfg.setGroup("Auto Allow");
- TQStringList entries = cfg.entryMap("Auto Allow").keys();
- for (TQStringList::Iterator i = entries.begin(); i != entries.end(); ++i) {
- _implicitAllowMap[*i] = cfg.readListEntry(*i);
- }
-
- // Update the implicit allow stuff
- _implicitDenyMap.clear();
- cfg.setGroup("Auto Deny");
- entries = cfg.entryMap("Auto Deny").keys();
- for (TQStringList::Iterator i = entries.begin(); i != entries.end(); ++i) {
- _implicitDenyMap[*i] = cfg.readListEntry(*i);
- }
-
- // Update if wallet was enabled/disabled
- if (!_enabled) { // close all wallets
- while (!_wallets.isEmpty()) {
- TQIntDictIterator<KWallet::Backend> it(_wallets);
- if (!it.current()) { // necessary?
- break;
- }
- closeWallet(it.current(), it.currentKey(), true);
- }
- }
-}
-
-
-bool KWalletD::isEnabled() const {
- return _enabled;
-}
-
-
-bool KWalletD::folderDoesNotExist(const TQString& wallet, const TQString& folder) {
- if (!wallets().contains(wallet)) {
- return true;
- }
-
- for (TQIntDictIterator<KWallet::Backend> it(_wallets); it.current(); ++it) {
- if (it.current()->walletName() == wallet) {
- return it.current()->folderDoesNotExist(folder);
- }
- }
-
- KWallet::Backend *b = new KWallet::Backend(wallet);
- b->open(TQByteArray());
- bool rc = b->folderDoesNotExist(folder);
- delete b;
- return rc;
-}
-
-
-bool KWalletD::keyDoesNotExist(const TQString& wallet, const TQString& folder, const TQString& key) {
- if (!wallets().contains(wallet)) {
- return true;
- }
-
- for (TQIntDictIterator<KWallet::Backend> it(_wallets); it.current(); ++it) {
- if (it.current()->walletName() == wallet) {
- return it.current()->entryDoesNotExist(folder, key);
- }
- }
-
- KWallet::Backend *b = new KWallet::Backend(wallet);
- b->open(TQByteArray());
- bool rc = b->entryDoesNotExist(folder, key);
- delete b;
- return rc;
-}
-
-
-bool KWalletD::implicitAllow(const TQString& wallet, const TQCString& app) {
- return _implicitAllowMap[wallet].contains(TQString::fromLocal8Bit(app));
-}
-
-
-bool KWalletD::implicitDeny(const TQString& wallet, const TQCString& app) {
- return _implicitDenyMap[wallet].contains(TQString::fromLocal8Bit(app));
-}
-
-
-TQCString KWalletD::friendlyDCOPPeerName() {
- DCOPClient *dc = callingDcopClient();
- if (!dc) {
- return "";
- }
- return dc->senderId().replace(TQRegExp("-[0-9]+$"), "");
-}
-
-
-void KWalletD::timedOut(int id) {
- KWallet::Backend *w = _wallets.find(id);
- if (w) {
- closeWallet(w, id, true);
- }
-}
-
-
-void KWalletD::closeAllWallets() {
- TQIntDict<KWallet::Backend> tw = _wallets;
-
- for (TQIntDictIterator<KWallet::Backend> it(tw); it.current(); ++it) {
- closeWallet(it.current(), it.currentKey(), true);
- }
-
- tw.clear();
-
- // All of this should be basically noop. Let's just be safe.
- _wallets.clear();
-
- for (TQMap<TQString,TQCString>::Iterator it = _passwords.begin();
- it != _passwords.end();
- ++it) {
- it.data().fill(0);
- }
- _passwords.clear();
-}
-
-
-TQString KWalletD::networkWallet() {
- return KWallet::Wallet::NetworkWallet();
-}
-
-
-TQString KWalletD::localWallet() {
- return KWallet::Wallet::LocalWallet();
-}
-
-
-#include "tdewalletd.moc"
diff --git a/kio/misc/telnet.protocol b/kio/misc/telnet.protocol
deleted file mode 100644
index 810011594..000000000
--- a/kio/misc/telnet.protocol
+++ /dev/null
@@ -1,13 +0,0 @@
-[Protocol]
-exec=ktelnetservice %u
-protocol=telnet
-input=none
-output=none
-helper=true
-listing=
-reading=false
-writing=false
-makedir=false
-deleting=false
-DocPath=kioslave/telnet.html
-Icon=konsole
diff --git a/kio/misc/uiserver.cpp b/kio/misc/uiserver.cpp
deleted file mode 100644
index e898e5a50..000000000
--- a/kio/misc/uiserver.cpp
+++ /dev/null
@@ -1,1413 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Matej Koss <koss@miesto.sk>
- David Faure <faure@kde.org>
- 2001 George Staikos <staikos@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-// -*- mode: c++; c-basic-offset: 4 -*-
-
-#include <tqtimer.h>
-
-#include <tqregexp.h>
-#include <tqheader.h>
-#include <tqevent.h>
-
-#include <ksqueezedtextlabel.h>
-#include <kconfig.h>
-#include <kstandarddirs.h>
-#include <kuniqueapplication.h>
-#include <kaboutdata.h>
-#include <kcmdlineargs.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <dcopclient.h>
-#include <kstatusbar.h>
-#include <kdebug.h>
-#include <kmessagebox.h>
-#include <tdesu/client.h>
-#include <twin.h>
-#include <kdialog.h>
-#include <ksystemtray.h>
-#include <kpopupmenu.h>
-#include <kaction.h>
-
-#include <tqcheckbox.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqpopupmenu.h>
-#include <tqheader.h>
-
-#include "observer_stub.h"
-#include "observer.h" // for static methods only
-#include "kio/defaultprogress.h"
-#include "kio/jobclasses.h"
-#include "uiserver.h"
-#include "passdlg.h"
-#include "kio/renamedlg.h"
-#include "kio/skipdlg.h"
-#include "slavebase.h" // for QuestionYesNo etc.
-#include <ksslinfodlg.h>
-#include <ksslcertdlg.h>
-#include <ksslcertificate.h>
-#include <ksslcertchain.h>
-
-
-// pointer for main instance of UIServer
-UIServer* uiserver;
-
-// ToolBar field IDs
-enum { TOOL_CANCEL, TOOL_CONFIGURE };
-
-// StatusBar field IDs
-enum { ID_TOTAL_FILES = 1, ID_TOTAL_SIZE, ID_TOTAL_TIME, ID_TOTAL_SPEED };
-
-//static
-int UIServer::s_jobId = 0;
-
-static const int defaultColumnWidth[] = { 70, // SIZE_OPERATION
- 160, // LOCAL_FILENAME
- 40, // RESUME
- 60, // COUNT
- 30, // PROGRESS
- 65, // TOTAL
- 70, // SPEED
- 70, // REMAINING_TIME
- 450 // URL
-};
-
-class UIServerSystemTray:public KSystemTray
-{
- public:
- UIServerSystemTray(UIServer* uis)
- :KSystemTray(uis)
- {
- KPopupMenu* pop= contextMenu();
- pop->insertItem(i18n("Settings..."), uis, TQT_SLOT(slotConfigure()));
- pop->insertItem(i18n("Remove"), uis, TQT_SLOT(slotRemoveSystemTrayIcon()));
- setPixmap(loadIcon("filesave"));
- //actionCollection()->action("file_quit")->setEnabled(true);
- KStdAction::quit(TQT_TQOBJECT(uis), TQT_SLOT(slotQuit()), actionCollection());
- }
-};
-
-class ProgressConfigDialog:public KDialogBase
-{
- public:
- ProgressConfigDialog(TQWidget* parent);
- ~ProgressConfigDialog() {}
- void setChecked(int i, bool on);
- bool isChecked(int i) const;
- friend class UIServer;
- private:
- TQCheckBox *m_showSystemTrayCb;
- TQCheckBox *m_keepOpenCb;
- TQCheckBox *m_toolBarCb;
- TQCheckBox *m_statusBarCb;
- TQCheckBox *m_headerCb;
- TQCheckBox *m_fixedWidthCb;
- KListView *m_columns;
- TQCheckListItem *(m_items[ListProgress::TB_MAX]);
-};
-
-ProgressConfigDialog::ProgressConfigDialog(TQWidget *parent)
-:KDialogBase(KDialogBase::Plain,i18n("Configure Network Operation Window"),KDialogBase::Ok|KDialogBase::Apply|KDialogBase::Cancel,
- KDialogBase::Ok, parent, "configprog", false)
-{
- TQVBoxLayout *layout=new TQVBoxLayout(plainPage(),spacingHint());
- m_showSystemTrayCb=new TQCheckBox(i18n("Show system tray icon"), plainPage());
- m_keepOpenCb=new TQCheckBox(i18n("Keep network operation window always open"), plainPage());
- m_headerCb=new TQCheckBox(i18n("Show column headers"), plainPage());
- m_toolBarCb=new TQCheckBox(i18n("Show toolbar"), plainPage());
- m_statusBarCb=new TQCheckBox(i18n("Show statusbar"), plainPage());
- m_fixedWidthCb=new TQCheckBox(i18n("Column widths are user adjustable"), plainPage());
- TQLabel *label=new TQLabel(i18n("Show information:"), plainPage());
- m_columns=new KListView(plainPage());
-
- m_columns->addColumn("info");
- m_columns->setSorting(-1);
- m_columns->header()->hide();
-
- m_items[ListProgress::TB_ADDRESS] =new TQCheckListItem(m_columns, i18n("URL"), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_REMAINING_TIME] =new TQCheckListItem(m_columns, i18n("Remaining Time", "Rem. Time"), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_SPEED] =new TQCheckListItem(m_columns, i18n("Speed"), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_TOTAL] =new TQCheckListItem(m_columns, i18n("Size"), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_PROGRESS] =new TQCheckListItem(m_columns, i18n("%"), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_COUNT] =new TQCheckListItem(m_columns, i18n("Count"), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_RESUME] =new TQCheckListItem(m_columns, i18n("Resume", "Res."), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_LOCAL_FILENAME] =new TQCheckListItem(m_columns, i18n("Local Filename"), TQCheckListItem::CheckBox);
- m_items[ListProgress::TB_OPERATION] =new TQCheckListItem(m_columns, i18n("Operation"), TQCheckListItem::CheckBox);
-
- layout->addWidget(m_showSystemTrayCb);
- layout->addWidget(m_keepOpenCb);
- layout->addWidget(m_headerCb);
- layout->addWidget(m_toolBarCb);
- layout->addWidget(m_statusBarCb);
- layout->addWidget(m_fixedWidthCb);
- layout->addWidget(label);
- layout->addWidget(m_columns);
-}
-
-void ProgressConfigDialog::setChecked(int i, bool on)
-{
- if (i>=ListProgress::TB_MAX)
- return;
- m_items[i]->setOn(on);
-}
-
-bool ProgressConfigDialog::isChecked(int i) const
-{
- if (i>=ListProgress::TB_MAX)
- return false;
- return m_items[i]->isOn();
-}
-
-ProgressItem::ProgressItem( ListProgress* view, TQListViewItem *after, TQCString app_id, int job_id,
- bool showDefault )
- : TQListViewItem( view, after ) {
-
- listProgress = view;
-
- m_iTotalSize = 0;
- m_iTotalFiles = 0;
- m_iProcessedSize = 0;
- m_iProcessedFiles = 0;
- m_iSpeed = 0;
-
- m_sAppId = app_id;
- m_iJobId = job_id;
- m_visible = true;
- m_defaultProgressVisible = showDefault;
-
- // create dialog, but don't show it
- defaultProgress = new TDEIO::DefaultProgress( false );
- defaultProgress->setOnlyClean( true );
- connect ( defaultProgress, TQT_SIGNAL( stopped() ), this, TQT_SLOT( slotCanceled() ) );
- connect ( &m_showTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT(slotShowDefaultProgress()) );
-
- if ( showDefault ) {
- m_showTimer.start( 500, true );
- }
-}
-
-bool ProgressItem::keepOpen() const
-{
- return defaultProgress->keepOpen();
-}
-
-void ProgressItem::finished()
-{
- defaultProgress->finished();
-}
-
-ProgressItem::~ProgressItem() {
- delete defaultProgress;
-}
-
-
-void ProgressItem::setTotalSize( TDEIO::filesize_t size ) {
- m_iTotalSize = size;
-
- // It's already in the % column...
- //setText( listProgress->lv_total, TDEIO::convertSize( m_iTotalSize ) );
-
- defaultProgress->slotTotalSize( 0, m_iTotalSize );
-}
-
-
-void ProgressItem::setTotalFiles( unsigned long files ) {
- m_iTotalFiles = files;
-
- defaultProgress->slotTotalFiles( 0, m_iTotalFiles );
-}
-
-
-void ProgressItem::setTotalDirs( unsigned long dirs ) {
- defaultProgress->slotTotalDirs( 0, dirs );
-}
-
-
-void ProgressItem::setProcessedSize( TDEIO::filesize_t size ) {
- m_iProcessedSize = size;
-
- setText( ListProgress::TB_TOTAL, TDEIO::convertSize( size ) );
-
- defaultProgress->slotProcessedSize( 0, size );
-}
-
-
-void ProgressItem::setProcessedFiles( unsigned long files ) {
- m_iProcessedFiles = files;
-
- TQString tmps = i18n("%1 / %2").arg( m_iProcessedFiles ).arg( m_iTotalFiles );
- setText( ListProgress::TB_COUNT, tmps );
-
- defaultProgress->slotProcessedFiles( 0, m_iProcessedFiles );
-}
-
-
-void ProgressItem::setProcessedDirs( unsigned long dirs ) {
- defaultProgress->slotProcessedDirs( 0, dirs );
-}
-
-
-void ProgressItem::setPercent( unsigned long percent ) {
- const TQString tmps = TDEIO::DefaultProgress::makePercentString( percent, m_iTotalSize, m_iTotalFiles );
- setText( ListProgress::TB_PROGRESS, tmps );
-
- defaultProgress->slotPercent( 0, percent );
-}
-
-void ProgressItem::setInfoMessage( const TQString & msg ) {
- TQString plainTextMsg(msg);
- plainTextMsg.replace( TQRegExp( "</?b>" ), TQString() );
- plainTextMsg.replace( TQRegExp( "<img.*>" ), TQString() );
- setText( ListProgress::TB_PROGRESS, plainTextMsg );
-
- defaultProgress->slotInfoMessage( 0, msg );
-}
-
-void ProgressItem::setSpeed( unsigned long bytes_per_second ) {
- m_iSpeed = bytes_per_second;
- m_remainingSeconds = TDEIO::calculateRemainingSeconds( m_iTotalSize, m_iProcessedSize, m_iSpeed );
-
- TQString tmps, tmps2;
- if ( m_iSpeed == 0 ) {
- tmps = i18n( "Stalled");
- tmps2 = tmps;
- } else {
- tmps = i18n( "%1/s").arg( TDEIO::convertSize( m_iSpeed ));
- tmps2 = TDEIO::convertSeconds( m_remainingSeconds );
- }
- setText( ListProgress::TB_SPEED, tmps );
- setText( ListProgress::TB_REMAINING_TIME, tmps2 );
-
- defaultProgress->slotSpeed( 0, m_iSpeed );
-}
-
-
-void ProgressItem::setCopying( const KURL& from, const KURL& to ) {
- setText( ListProgress::TB_OPERATION, i18n("Copying") );
- setText( ListProgress::TB_ADDRESS, from.url() );
- setText( ListProgress::TB_LOCAL_FILENAME, to.fileName() );
-
- defaultProgress->slotCopying( 0, from, to );
-}
-
-
-void ProgressItem::setMoving( const KURL& from, const KURL& to ) {
- setText( ListProgress::TB_OPERATION, i18n("Moving") );
- setText( ListProgress::TB_ADDRESS, from.url() );
- setText( ListProgress::TB_LOCAL_FILENAME, to.fileName() );
-
- defaultProgress->slotMoving( 0, from, to );
-}
-
-
-void ProgressItem::setCreatingDir( const KURL& dir ) {
- setText( ListProgress::TB_OPERATION, i18n("Creating") );
- setText( ListProgress::TB_ADDRESS, dir.url() );
- setText( ListProgress::TB_LOCAL_FILENAME, dir.fileName() );
-
- defaultProgress->slotCreatingDir( 0, dir );
-}
-
-
-void ProgressItem::setDeleting( const KURL& url ) {
- setText( ListProgress::TB_OPERATION, i18n("Deleting") );
- setText( ListProgress::TB_ADDRESS, url.url() );
- setText( ListProgress::TB_LOCAL_FILENAME, url.fileName() );
-
- defaultProgress->slotDeleting( 0, url );
-}
-
-void ProgressItem::setTransferring( const KURL& url ) {
- setText( ListProgress::TB_OPERATION, i18n("Loading") );
- setText( ListProgress::TB_ADDRESS, url.url() );
- setText( ListProgress::TB_LOCAL_FILENAME, url.fileName() );
-
- defaultProgress->slotTransferring( 0, url );
-}
-
-void ProgressItem::setText(ListProgress::ListProgressFields field, const TQString& text)
-{
- if (listProgress->m_lpcc[field].enabled)
- {
- TQString t=text;
- if ((field==ListProgress::TB_ADDRESS) && (listProgress->m_fixedColumnWidths))
-// if (((field==ListProgress::TB_LOCAL_FILENAME) || (field==ListProgress::TB_ADDRESS)) && (listProgress->m_fixedColumnWidths))
- {
- m_fullLengthAddress=text;
- listProgress->m_squeezer->resize(listProgress->columnWidth(listProgress->m_lpcc[field].index),50);
- listProgress->m_squeezer->setText(t);
- t=listProgress->m_squeezer->text();
- }
- TQListViewItem::setText(listProgress->m_lpcc[field].index,t);
- }
-}
-
-void ProgressItem::setStating( const KURL& url ) {
- setText( ListProgress::TB_OPERATION, i18n("Examining") );
- setText( ListProgress::TB_ADDRESS, url.url() );
- setText( ListProgress::TB_LOCAL_FILENAME, url.fileName() );
-
- defaultProgress->slotStating( 0, url );
-}
-
-void ProgressItem::setMounting( const TQString& dev, const TQString & point ) {
- setText( ListProgress::TB_OPERATION, i18n("Mounting") );
- setText( ListProgress::TB_ADDRESS, point ); // ?
- setText( ListProgress::TB_LOCAL_FILENAME, dev ); // ?
-
- defaultProgress->slotMounting( 0, dev, point );
-}
-
-void ProgressItem::setUnmounting( const TQString & point ) {
- setText( ListProgress::TB_OPERATION, i18n("Unmounting") );
- setText( ListProgress::TB_ADDRESS, point ); // ?
- setText( ListProgress::TB_LOCAL_FILENAME, "" ); // ?
-
- defaultProgress->slotUnmounting( 0, point );
-}
-
-void ProgressItem::setCanResume( TDEIO::filesize_t offset ) {
- /*
- TQString tmps;
- // set canResume
- if ( _resume ) {
- tmps = i18n("Yes");
- } else {
- tmps = i18n("No");
- }
- setText( listProgress->lv_resume, tmps );
- */
- defaultProgress->slotCanResume( 0, offset );
-}
-
-
-void ProgressItem::slotCanceled() {
- emit jobCanceled( this );
-}
-
-// Called 0.5s after the job has been started
-void ProgressItem::slotShowDefaultProgress() {
- if (defaultProgress)
- {
- if ( m_visible && m_defaultProgressVisible )
- defaultProgress->show();
- else
- defaultProgress->hide();
- }
-}
-
-void ProgressItem::slotToggleDefaultProgress() {
- setDefaultProgressVisible( !m_defaultProgressVisible );
-}
-
-// Called when a rename or skip dialog pops up
-// We want to prevent someone from killing the job in the uiserver then
-void ProgressItem::setVisible( bool visible ) {
- if ( m_visible != visible )
- {
- m_visible = visible;
- updateVisibility();
- }
-}
-
-// Can be toggled by the user
-void ProgressItem::setDefaultProgressVisible( bool visible ) {
- if ( m_defaultProgressVisible != visible )
- {
- m_defaultProgressVisible = visible;
- updateVisibility();
- }
-}
-
-// Update according to state
-void ProgressItem::updateVisibility()
-{
- if (defaultProgress)
- {
- if ( m_visible && m_defaultProgressVisible )
- {
- m_showTimer.start(250, true); // Show delayed
- }
- else
- {
- m_showTimer.stop();
- defaultProgress->hide();
- }
- }
-}
-
-
-//-----------------------------------------------------------------------------
-ListProgress::ListProgress (TQWidget *parent, const char *name)
-: KListView (parent, name)
-{
-
- // enable selection of more than one item
- setMultiSelection( true );
-
- setAllColumnsShowFocus( true );
-
- m_lpcc[TB_OPERATION].title=i18n("Operation");
- m_lpcc[TB_LOCAL_FILENAME].title=i18n("Local Filename");
- m_lpcc[TB_RESUME].title=i18n("Resume", "Res.");
- m_lpcc[TB_COUNT].title=i18n("Count");
- m_lpcc[TB_PROGRESS].title=i18n("%");
- m_lpcc[TB_TOTAL].title=i18n("Size");
- m_lpcc[TB_SPEED].title=i18n("Speed");
- m_lpcc[TB_REMAINING_TIME].title=i18n("Remaining Time", "Rem. Time");
- m_lpcc[TB_ADDRESS].title=i18n("URL");
- readSettings();
-
- applySettings();
-
- //used for squeezing the text in local file name and url
- m_squeezer=new KSqueezedTextLabel(this);
- m_squeezer->hide();
- connect(header(),TQT_SIGNAL(sizeChange(int,int,int)),this,TQT_SLOT(columnWidthChanged(int)));
-}
-
-
-ListProgress::~ListProgress() {
-}
-
-void ListProgress::applySettings()
-{
- int iEnabledCols=0;
-
- // Update listcolumns to show
- for (int i=0; i<TB_MAX; i++)
- {
- if ( !m_lpcc[i].enabled )
- continue;
-
- iEnabledCols++;
-
- // Add new or reuse existing column
- if ( iEnabledCols > columns() )
- m_lpcc[i].index=addColumn(m_lpcc[i].title, m_fixedColumnWidths?m_lpcc[i].width:-1);
- else
- {
- m_lpcc[i].index = iEnabledCols - 1;
- setColumnText(m_lpcc[i].index, m_lpcc[i].title);
- }
-
- setColumnWidth(m_lpcc[i].index, m_lpcc[i].width); //yes, this is required here, alexxx
- if (m_fixedColumnWidths)
- setColumnWidthMode(m_lpcc[i].index, Manual);
- }
-
- // Remove unused columns. However we must keep one column left
- // Otherwise the listview will be emptied
- while( iEnabledCols < columns() && columns() > 1 )
- removeColumn( columns() - 1 );
-
- if ( columns() == 0 )
- addColumn( "" );
-
- if ( !m_showHeader || iEnabledCols == 0 )
- header()->hide();
- else
- header()->show();
-}
-
-void ListProgress::readSettings() {
- TDEConfig config("uiserverrc");
-
- // read listview geometry properties
- config.setGroup( "ProgressList" );
- for ( int i = 0; i < TB_MAX; i++ ) {
- TQString tmps="Col"+TQString::number(i);
- m_lpcc[i].width=config.readNumEntry( tmps, 0);
- if (m_lpcc[i].width==0) m_lpcc[i].width=defaultColumnWidth[i];
-
- tmps="Enabled"+TQString::number(i);
- m_lpcc[i].enabled=config.readBoolEntry(tmps,true);
- }
- m_showHeader=config.readBoolEntry("ShowListHeader",true);
- m_fixedColumnWidths=config.readBoolEntry("FixedColumnWidths",false);
-
- m_lpcc[TB_RESUME].enabled=false;
-}
-
-void ListProgress::columnWidthChanged(int column)
-{
- //resqueeze if necessary
- if ((m_lpcc[TB_ADDRESS].enabled) && (column==m_lpcc[TB_ADDRESS].index))
- {
- for (TQListViewItem* lvi=firstChild(); lvi!=0; lvi=lvi->nextSibling())
- {
- ProgressItem *pi=(ProgressItem*)lvi;
- pi->setText(TB_ADDRESS,pi->fullLengthAddress());
- }
- }
- writeSettings();
-}
-
-void ListProgress::writeSettings() {
- TDEConfig config("uiserverrc");
-
- // write listview geometry properties
- config.setGroup( "ProgressList" );
- for ( int i = 0; i < TB_MAX; i++ ) {
- if (!m_lpcc[i].enabled) {
- TQString tmps= "Enabled" + TQString::number(i);
- config.writeEntry( tmps, false );
- continue;
- }
- m_lpcc[i].width=columnWidth(m_lpcc[i].index);
- TQString tmps="Col"+TQString::number(i);
- config.writeEntry( tmps, m_lpcc[i].width);
- }
- config.writeEntry("ShowListHeader", m_showHeader);
- config.writeEntry("FixedColumnWidths", m_fixedColumnWidths);
- config.sync();
-}
-
-
-//------------------------------------------------------------
-
-
-UIServer::UIServer()
-:KMainWindow(0, "")
-,DCOPObject("UIServer")
-,m_shuttingDown(false)
-,m_configDialog(0)
-,m_contextMenu(0)
-,m_systemTray(0)
-{
-
- readSettings();
-
- // setup toolbar
- toolBar()->insertButton("editdelete", TOOL_CANCEL,
- TQT_SIGNAL(clicked()), TQT_TQOBJECT(this),
- TQT_SLOT(slotCancelCurrent()), FALSE, i18n("Cancel"));
- toolBar()->insertButton("configure", TOOL_CONFIGURE,
- TQT_SIGNAL(clicked()), TQT_TQOBJECT(this),
- TQT_SLOT(slotConfigure()), true, i18n("Settings..."));
-
- toolBar()->setBarPos( KToolBar::Left );
-
- // setup statusbar
- statusBar()->insertItem( i18n(" Files: %1 ").arg( 0 ), ID_TOTAL_FILES);
- statusBar()->insertItem( i18n("Remaining Size", " Rem. Size: %1 kB ").arg( "0" ), ID_TOTAL_SIZE);
- statusBar()->insertItem( i18n("Remaining Time", " Rem. Time: 00:00:00 "), ID_TOTAL_TIME);
- statusBar()->insertItem( i18n(" %1 kB/s ").arg("0"), ID_TOTAL_SPEED);
-
- // setup listview
- listProgress = new ListProgress( this, "progresslist" );
-
- setCentralWidget( listProgress );
-
- connect( listProgress, TQT_SIGNAL( selectionChanged() ),
- TQT_SLOT( slotSelection() ) );
- connect( listProgress, TQT_SIGNAL( executed( TQListViewItem* ) ),
- TQT_SLOT( slotToggleDefaultProgress( TQListViewItem* ) ) );
- connect( listProgress, TQT_SIGNAL( contextMenu( KListView*, TQListViewItem *, const TQPoint &)),
- TQT_SLOT(slotShowContextMenu(KListView*, TQListViewItem *, const TQPoint&)));
-
-
- // setup animation timer
- updateTimer = new TQTimer( this );
- connect( updateTimer, TQT_SIGNAL( timeout() ),
- TQT_SLOT( slotUpdate() ) );
- m_bUpdateNewJob=false;
-
- setCaption(i18n("Progress Dialog"));
- setMinimumSize( 150, 50 );
- resize( m_initWidth, m_initHeight);
-
- applySettings();
-
-/* if ((m_bShowList) && (m_keepListOpen))
- {
- cerr<<"show() !"<<endl;
- show();
- }
- else*/
- hide();
-}
-
-UIServer::~UIServer() {
- updateTimer->stop();
-}
-
-void UIServer::applySettings()
-{
- if ((m_showSystemTray) && (m_systemTray==0))
- {
- m_systemTray=new UIServerSystemTray(this);
- m_systemTray->show();
- }
- else if ((m_showSystemTray==false) && (m_systemTray!=0))
- {
- delete m_systemTray;
- m_systemTray=0;
- }
-
- if (m_showStatusBar==false)
- statusBar()->hide();
- else
- statusBar()->show();
- if (m_showToolBar==false)
- toolBar()->hide();
- else
- toolBar()->show();
-}
-
-void UIServer::slotShowContextMenu(KListView*, TQListViewItem* item, const TQPoint& pos)
-{
- if (m_contextMenu==0)
- {
- m_contextMenu=new TQPopupMenu(this);
- m_idCancelItem = m_contextMenu->insertItem(i18n("Cancel Job"), this, TQT_SLOT(slotCancelCurrent()));
-// m_contextMenu->insertItem(i18n("Toggle Progress"), this, TQT_SLOT(slotToggleDefaultProgress()));
- m_contextMenu->insertSeparator();
- m_contextMenu->insertItem(i18n("Settings..."), this, TQT_SLOT(slotConfigure()));
- }
- if ( item )
- item->setSelected( true );
- bool enabled = false;
- TQListViewItemIterator it( listProgress );
- for ( ; it.current(); ++it ) {
- if ( it.current()->isSelected() ) {
- enabled = true;
- break;
- }
- }
- m_contextMenu->setItemEnabled( m_idCancelItem, enabled);
-
- m_contextMenu->popup(pos);
-}
-
-void UIServer::slotRemoveSystemTrayIcon()
-{
- m_showSystemTray=false;
- applySettings();
- writeSettings();
-}
-
-void UIServer::slotConfigure()
-{
- if (m_configDialog==0)
- {
- m_configDialog=new ProgressConfigDialog(0);
-// connect(m_configDialog,TQT_SIGNAL(cancelClicked()), this, TQT_SLOT(slotCancelConfig()));
- connect(m_configDialog,TQT_SIGNAL(okClicked()), this, TQT_SLOT(slotApplyConfig()));
- connect(m_configDialog,TQT_SIGNAL(applyClicked()), this, TQT_SLOT(slotApplyConfig()));
- }
- m_configDialog->m_showSystemTrayCb->setChecked(m_showSystemTray);
- m_configDialog->m_keepOpenCb->setChecked(m_keepListOpen);
- m_configDialog->m_toolBarCb->setChecked(m_showToolBar);
- m_configDialog->m_statusBarCb->setChecked(m_showStatusBar);
- m_configDialog->m_headerCb->setChecked(listProgress->m_showHeader);
- m_configDialog->m_fixedWidthCb->setChecked(listProgress->m_fixedColumnWidths);
- for (int i=0; i<ListProgress::TB_MAX; i++)
- {
- m_configDialog->setChecked(i, listProgress->m_lpcc[i].enabled);
- }
- m_configDialog->show();
-}
-
-void UIServer::slotApplyConfig()
-{
- m_showSystemTray=m_configDialog->m_showSystemTrayCb->isChecked();
- m_keepListOpen=m_configDialog->m_keepOpenCb->isChecked();
- m_showToolBar=m_configDialog->m_toolBarCb->isChecked();
- m_showStatusBar=m_configDialog->m_statusBarCb->isChecked();
- listProgress->m_showHeader=m_configDialog->m_headerCb->isChecked();
- listProgress->m_fixedColumnWidths=m_configDialog->m_fixedWidthCb->isChecked();
- for (int i=0; i<ListProgress::TB_MAX; i++)
- listProgress->m_lpcc[i].enabled=m_configDialog->isChecked(i);
-
-
- applySettings();
- listProgress->applySettings();
- writeSettings();
- listProgress->writeSettings();
-}
-
-int UIServer::newJob( TQCString observerAppId, bool showProgress )
-{
- kdDebug(7024) << "UIServer::newJob observerAppId=" << observerAppId << ". "
- << "Giving id=" << s_jobId+1 << endl;
-
- TQListViewItemIterator it( listProgress );
- for ( ; it.current(); ++it ) {
- if ( it.current()->itemBelow() == 0L ) { // this will find the end of list
- break;
- }
- }
-
- // increment counter
- s_jobId++;
-
- bool show = !m_bShowList && showProgress;
-
- ProgressItem *item = new ProgressItem( listProgress, it.current(), observerAppId, s_jobId, show );
- connect( item, TQT_SIGNAL( jobCanceled( ProgressItem* ) ),
- TQT_SLOT( slotJobCanceled( ProgressItem* ) ) );
-
- if ( m_bShowList && !updateTimer->isActive() )
- updateTimer->start( 1000 );
-
- m_bUpdateNewJob=true;
-
- return s_jobId;
-}
-
-
-ProgressItem* UIServer::findItem( int id )
-{
- TQListViewItemIterator it( listProgress );
-
- ProgressItem *item;
-
- for ( ; it.current(); ++it ) {
- item = (ProgressItem*) it.current();
- if ( item->jobId() == id ) {
- return item;
- }
- }
-
- return 0L;
-}
-
-
-void UIServer::setItemVisible( ProgressItem * item, bool visible )
-{
- item->setVisible( visible );
- // Check if we were the last one to be visible
- // or the first one -> hide/show the list in that case
- // (Note that the user could have hidden the listview by hand yet, no time)
- if ( m_bShowList ) {
- m_bUpdateNewJob = true;
- slotUpdate();
- }
-}
-
-// Called by Observer when opening a skip or rename dialog
-void UIServer::setJobVisible( int id, bool visible )
-{
- kdDebug(7024) << "UIServer::setJobVisible id=" << id << " visible=" << visible << endl;
- ProgressItem *item = findItem( id );
- Q_ASSERT( item );
- if ( item )
- setItemVisible( item, visible );
-}
-
-void UIServer::jobFinished( int id )
-{
- kdDebug(7024) << "UIServer::jobFinished id=" << id << endl;
- ProgressItem *item = findItem( id );
-
- // remove item from the list and delete the corresponding defaultprogress
- if ( item ) {
- if ( item->keepOpen() )
- item->finished();
- else
- delete item;
- }
-}
-
-
-void UIServer::totalSize( int id, unsigned long size )
-{ totalSize64(id, size); }
-
-void UIServer::totalSize64( int id, TDEIO::filesize_t size )
-{
-// kdDebug(7024) << "UIServer::totalSize " << id << " " << TDEIO::number(size) << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setTotalSize( size );
- }
-}
-
-void UIServer::totalFiles( int id, unsigned long files )
-{
- kdDebug(7024) << "UIServer::totalFiles " << id << " " << (unsigned int) files << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setTotalFiles( files );
- }
-}
-
-void UIServer::totalDirs( int id, unsigned long dirs )
-{
- kdDebug(7024) << "UIServer::totalDirs " << id << " " << (unsigned int) dirs << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setTotalDirs( dirs );
- }
-}
-
-void UIServer::processedSize( int id, unsigned long size )
-{ processedSize64(id, size); }
-
-void UIServer::processedSize64( int id, TDEIO::filesize_t size )
-{
- //kdDebug(7024) << "UIServer::processedSize " << id << " " << TDEIO::number(size) << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setProcessedSize( size );
- }
-}
-
-void UIServer::processedFiles( int id, unsigned long files )
-{
- //kdDebug(7024) << "UIServer::processedFiles " << id << " " << (unsigned int) files << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setProcessedFiles( files );
- }
-}
-
-void UIServer::processedDirs( int id, unsigned long dirs )
-{
- kdDebug(7024) << "UIServer::processedDirs " << id << " " << (unsigned int) dirs << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setProcessedDirs( dirs );
- }
-}
-
-void UIServer::percent( int id, unsigned long ipercent )
-{
- //kdDebug(7024) << "UIServer::percent " << id << " " << (unsigned int) ipercent << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setPercent( ipercent );
- }
-}
-
-void UIServer::speed( int id, unsigned long bytes_per_second )
-{
- //kdDebug(7024) << "UIServer::speed " << id << " " << (unsigned int) bytes_per_second << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setSpeed( bytes_per_second );
- }
-}
-
-void UIServer::infoMessage( int id, const TQString & msg )
-{
- //kdDebug(7024) << "UIServer::infoMessage " << id << " " << msg << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setInfoMessage( msg );
- }
-}
-
-void UIServer::canResume( int id, unsigned long offset )
-{ canResume64(id, offset); }
-
-void UIServer::canResume64( int id, TDEIO::filesize_t offset )
-{
- //kdDebug(7024) << "UIServer::canResume " << id << " " << offset << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setCanResume( offset );
- }
-}
-
-void UIServer::copying( int id, KURL from, KURL to )
-{
- //kdDebug(7024) << "UIServer::copying " << id << " " << from.url() << " " << to.url() << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setCopying( from, to );
- }
-}
-
-void UIServer::moving( int id, KURL from, KURL to )
-{
- //kdDebug(7024) << "UIServer::moving " << id << " " << from.url() << " " << to.url() << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setMoving( from, to );
- }
-}
-
-void UIServer::deleting( int id, KURL url )
-{
- //kdDebug(7024) << "UIServer::deleting " << id << " " << url.url() << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setDeleting( url );
- }
-}
-
-void UIServer::transferring( int id, KURL url )
-{
- //kdDebug(7024) << "UIServer::transferring " << id << " " << url.url() << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setTransferring( url );
- }
-}
-
-void UIServer::creatingDir( int id, KURL dir )
-{
- kdDebug(7024) << "UIServer::creatingDir " << id << " " << dir.url() << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setCreatingDir( dir );
- }
-}
-
-void UIServer::stating( int id, KURL url )
-{
- kdDebug(7024) << "UIServer::stating " << id << " " << url.url() << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setStating( url );
- }
-}
-
-void UIServer::mounting( int id, TQString dev, TQString point )
-{
- kdDebug(7024) << "UIServer::mounting " << id << " " << dev << " " << point << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setMounting( dev, point );
- }
-}
-
-void UIServer::unmounting( int id, TQString point )
-{
- kdDebug(7024) << "UIServer::unmounting " << id << " " << point << endl;
-
- ProgressItem *item = findItem( id );
- if ( item ) {
- item->setUnmounting( point );
- }
-}
-
-void UIServer::killJob( TQCString observerAppId, int progressId )
-{
- // Contact the object "TDEIO::Observer" in the application <appId>
- Observer_stub observer( observerAppId, "TDEIO::Observer" );
- // Tell it to kill the job
- observer.killJob( progressId );
-}
-
-void UIServer::slotJobCanceled( ProgressItem *item ) {
- kdDebug(7024) << "UIServer::slotJobCanceled appid=" << item->appId() << " jobid=" << item->jobId() << endl;
- // kill the corresponding job
- killJob( item->appId(), item->jobId() );
-
- // TDEIO::Job, when killed, should call back jobFinished(), but we can't
- // really rely on that - the app may have crashed
- delete item;
-}
-
-
-void UIServer::slotQuit()
-{
- m_shuttingDown = true;
- kapp->quit();
-}
-
-void UIServer::slotUpdate() {
- // don't do anything if we don't have any inserted progress item
- // or if they're all hidden
- TQListViewItemIterator lvit( listProgress );
- bool visible = false;
- for ( ; lvit.current(); ++lvit )
- if ( ((ProgressItem*)lvit.current())->isVisible() ) {
- visible = true;
- break;
- }
-
- if ( !visible || !m_bShowList ) {
- if (!m_keepListOpen) hide();
- updateTimer->stop();
- return;
- }
-
- // Calling show() is conditional, so that users can close the window
- // and it only pops up back when a new job is started
- if (m_bUpdateNewJob)
- {
- m_bUpdateNewJob=false;
- show();
-
- // Make sure we'll be called back
- if ( m_bShowList && !updateTimer->isActive() )
- updateTimer->start( 1000 );
- }
-
- int iTotalFiles = 0;
- TDEIO::filesize_t iTotalSize = 0;
- int iTotalSpeed = 0;
- unsigned int totalRemTime = 0; // in seconds
-
- ProgressItem *item;
-
- // count totals for statusbar
- TQListViewItemIterator it( listProgress );
-
- for ( ; it.current(); ++it ) {
- item = (ProgressItem*) it.current();
- if ( item->totalSize() != 0 ) {
- iTotalSize += ( item->totalSize() - item->processedSize() );
- }
- iTotalFiles += ( item->totalFiles() - item->processedFiles() );
- iTotalSpeed += item->speed();
-
- if ( item->remainingSeconds() > totalRemTime ) {
- totalRemTime = item->remainingSeconds();
- }
- }
-
- // update statusbar
- statusBar()->changeItem( i18n( " Files: %1 ").arg( iTotalFiles ), ID_TOTAL_FILES);
- statusBar()->changeItem( i18n( "Remaining Size", " Rem. Size: %1 ").arg( TDEIO::convertSize( iTotalSize ) ),
- ID_TOTAL_SIZE);
- statusBar()->changeItem( i18n( "Remaining Time", " Rem. Time: %1 ").arg( TDEIO::convertSeconds( totalRemTime ) ),
- ID_TOTAL_TIME);
- statusBar()->changeItem( i18n( " %1/s ").arg( TDEIO::convertSize( iTotalSpeed ) ),
- ID_TOTAL_SPEED);
-
-}
-
-void UIServer::setListMode( bool list )
-{
- m_bShowList = list;
- TQListViewItemIterator it( listProgress );
- for ( ; it.current(); ++it ) {
- // When going to list mode -> hide all progress dialogs
- // When going back to separate dialogs -> show them all
- ((ProgressItem*) it.current())->setDefaultProgressVisible( !list );
- }
-
- if (m_bShowList)
- {
- show();
- updateTimer->start( 1000 );
- }
- else
- {
- hide();
- updateTimer->stop();
- }
-}
-
-void UIServer::slotToggleDefaultProgress( TQListViewItem *item ) {
- ((ProgressItem*) item )->slotToggleDefaultProgress();
-}
-
-
-void UIServer::slotSelection() {
- TQListViewItemIterator it( listProgress );
-
- for ( ; it.current(); ++it ) {
- if ( it.current()->isSelected() ) {
- toolBar()->setItemEnabled( TOOL_CANCEL, TRUE);
- return;
- }
- }
- toolBar()->setItemEnabled( TOOL_CANCEL, FALSE);
-}
-
-// This code is deprecated, slaves go to Observer::openPassDlg now,
-// but this is kept for compat (DCOP calls to kio_uiserver).
-TQByteArray UIServer::openPassDlg( const TDEIO::AuthInfo &info )
-{
- kdDebug(7024) << "UIServer::openPassDlg: User= " << info.username
- << ", Msg= " << info.prompt << endl;
- TDEIO::AuthInfo inf(info);
- int result = TDEIO::PasswordDialog::getNameAndPassword( inf.username, inf.password,
- &inf.keepPassword, inf.prompt,
- inf.readOnly, inf.caption,
- inf.comment, inf.commentLabel );
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly );
- if ( result == TQDialog::Accepted )
- inf.setModified( true );
- else
- inf.setModified( false );
- stream << inf;
- return data;
-}
-
-int UIServer::messageBox( int progressId, int type, const TQString &text, const TQString &caption, const TQString &buttonYes, const TQString &buttonNo )
-{
- return Observer::messageBox( progressId, type, text, caption, buttonYes, buttonNo );
-}
-
-void UIServer::showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &meta)
-{
- return showSSLInfoDialog(url,meta,0);
-}
-
-void UIServer::showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &meta, int mainwindow)
-{
- KSSLInfoDlg *kid = new KSSLInfoDlg(meta["ssl_in_use"].upper()=="TRUE", 0L /*parent?*/, 0L, true);
- KSSLCertificate *x = KSSLCertificate::fromString(meta["ssl_peer_certificate"].local8Bit());
- if (x) {
- // Set the chain back onto the certificate
- TQStringList cl =
- TQStringList::split(TQString("\n"), meta["ssl_peer_chain"]);
- TQPtrList<KSSLCertificate> ncl;
-
- ncl.setAutoDelete(true);
- for (TQStringList::Iterator it = cl.begin(); it != cl.end(); ++it) {
- KSSLCertificate *y = KSSLCertificate::fromString((*it).local8Bit());
- if (y) ncl.append(y);
- }
-
- if (ncl.count() > 0)
- x->chain().setChain(ncl);
-
- kdDebug(7024) << "ssl_cert_errors=" << meta["ssl_cert_errors"] << endl;
- kid->setCertState(meta["ssl_cert_errors"]);
- TQString ip = meta.contains("ssl_proxied") ? "" : meta["ssl_peer_ip"];
- kid->setup( x,
- ip,
- url, // the URL
- meta["ssl_cipher"],
- meta["ssl_cipher_desc"],
- meta["ssl_cipher_version"],
- meta["ssl_cipher_used_bits"].toInt(),
- meta["ssl_cipher_bits"].toInt(),
- KSSLCertificate::KSSLValidation(meta["ssl_cert_state"].toInt()));
- kdDebug(7024) << "Showing SSL Info dialog" << endl;
-#ifndef Q_WS_WIN
- if( mainwindow != 0 )
- KWin::setMainWindow( kid, mainwindow );
-#endif
- kid->exec();
- delete x;
- kdDebug(7024) << "SSL Info dialog closed" << endl;
- } else {
- KMessageBox::information( 0L, // parent ?
- i18n("The peer SSL certificate appears to be corrupt."), i18n("SSL") );
- }
- // Don't delete kid!!
-}
-
-KSSLCertDlgRet UIServer::showSSLCertDialog(const TQString& host, const TQStringList& certList)
-{
- return showSSLCertDialog( host, certList, 0 );
-}
-
-KSSLCertDlgRet UIServer::showSSLCertDialog(const TQString& host, const TQStringList& certList, int mainwindow)
-{
- KSSLCertDlgRet rc;
- rc.ok = false;
- if (!certList.isEmpty()) {
- KSSLCertDlg *kcd = new KSSLCertDlg(0L, 0L, true);
- kcd->setupDialog(certList);
- kcd->setHost(host);
- kdDebug(7024) << "Showing SSL certificate dialog" << endl;
-#ifndef Q_WS_WIN
- if( mainwindow != 0 )
- KWin::setMainWindow( kcd, mainwindow );
-#endif
- kcd->exec();
- rc.ok = true;
- rc.choice = kcd->getChoice();
- rc.save = kcd->saveChoice();
- rc.send = kcd->wantsToSend();
- kdDebug(7024) << "SSL certificate dialog closed" << endl;
- delete kcd;
- }
- return rc;
-}
-
-
-TQByteArray UIServer::open_RenameDlg( int id,
- const TQString & caption,
- const TQString& src, const TQString & dest,
- int mode,
- unsigned long sizeSrc,
- unsigned long sizeDest,
- unsigned long ctimeSrc,
- unsigned long ctimeDest,
- unsigned long mtimeSrc,
- unsigned long mtimeDest
- )
-{ return open_RenameDlg64(id, caption, src, dest, mode, sizeSrc, sizeDest,
- ctimeSrc, ctimeDest, mtimeSrc, mtimeDest); }
-
-
-TQByteArray UIServer::open_RenameDlg64( int id,
- const TQString & caption,
- const TQString& src, const TQString & dest,
- int mode,
- TDEIO::filesize_t sizeSrc,
- TDEIO::filesize_t sizeDest,
- unsigned long ctimeSrc,
- unsigned long ctimeDest,
- unsigned long mtimeSrc,
- unsigned long mtimeDest
- )
-{
- // Hide existing dialog box if any
- ProgressItem *item = findItem( id );
- if ( item )
- setItemVisible( item, false );
- TQString newDest;
- kdDebug(7024) << "Calling TDEIO::open_RenameDlg" << endl;
- TDEIO::RenameDlg_Result result = TDEIO::open_RenameDlg( caption, src, dest,
- (TDEIO::RenameDlg_Mode) mode, newDest,
- sizeSrc, sizeDest,
- (time_t)ctimeSrc, (time_t)ctimeDest,
- (time_t)mtimeSrc, (time_t)mtimeDest );
- kdDebug(7024) << "TDEIO::open_RenameDlg done" << endl;
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly );
- stream << TQ_UINT8(result) << newDest;
- if ( item && result != TDEIO::R_CANCEL )
- setItemVisible( item, true );
- return data;
-}
-
-int UIServer::open_SkipDlg( int id,
- int /*bool*/ multi,
- const TQString & error_text )
-{
- // Hide existing dialog box if any
- ProgressItem *item = findItem( id );
- if ( item )
- setItemVisible( item, false );
- kdDebug(7024) << "Calling TDEIO::open_SkipDlg" << endl;
- TDEIO::SkipDlg_Result result = TDEIO::open_SkipDlg( (bool)multi, error_text );
- if ( item && result != TDEIO::S_CANCEL )
- setItemVisible( item, true );
- return (TDEIO::SkipDlg_Result) result;
-}
-
-
-void UIServer::readSettings() {
- TDEConfig config("uiserverrc");
- config.setGroup( "UIServer" );
- m_showStatusBar=config.readBoolEntry("ShowStatusBar",false);
- m_showToolBar=config.readBoolEntry("ShowToolBar",true);
- m_keepListOpen=config.readBoolEntry("KeepListOpen",false);
- m_initWidth=config.readNumEntry("InitialWidth",460);
- m_initHeight=config.readNumEntry("InitialHeight",150);
- m_bShowList = config.readBoolEntry( "ShowList", false );
- m_showSystemTray=config.readBoolEntry("ShowSystemTray", false);
-}
-
-void UIServer::writeSettings() {
- TDEConfig config("uiserverrc");
- config.setGroup( "UIServer" );
- config.writeEntry("InitialWidth",width());
- config.writeEntry("InitialHeight",height());
- config.writeEntry("ShowStatusBar", m_showStatusBar);
- config.writeEntry("ShowToolBar", m_showToolBar);
- config.writeEntry("KeepListOpen", m_keepListOpen);
- config.writeEntry("ShowList", m_bShowList);
- config.writeEntry("ShowSystemTray", m_showSystemTray);
-}
-
-
-void UIServer::slotCancelCurrent() {
- TQListViewItemIterator it( listProgress );
- ProgressItem *item;
-
- // kill selected jobs
- for ( ; it.current() ; ++it )
- {
- if ( it.current()->isSelected() ) {
- item = (ProgressItem*) it.current();
- killJob( item->appId(), item->jobId() );
- return;
- }
- }
-}
-
-void UIServer::resizeEvent(TQResizeEvent* e)
-{
- KMainWindow::resizeEvent(e);
- writeSettings();
-}
-
-bool UIServer::queryClose()
-{
- if (( !m_shuttingDown ) && !kapp->sessionSaving()) {
- hide();
- return false;
- }
- return true;
-}
-
-UIServer* UIServer::createInstance()
-{
- return new UIServer;
-}
-
-//------------------------------------------------------------
-
-extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
-{
- KLocale::setMainCatalogue("tdelibs");
- // GS 5/2001 - I changed the name to "TDE" to make it look better
- // in the titles of dialogs which are displayed.
- TDEAboutData aboutdata("kio_uiserver", I18N_NOOP("TDE"),
- "0.8", I18N_NOOP("TDE Progress Information UI Server"),
- TDEAboutData::License_GPL, "(C) 2000, David Faure & Matt Koss");
- // Who's the maintainer ? :)
- aboutdata.addAuthor("David Faure",I18N_NOOP("Developer"),"faure@kde.org");
- aboutdata.addAuthor("Matej Koss",I18N_NOOP("Developer"),"koss@miesto.sk");
-
- TDECmdLineArgs::init( argc, argv, &aboutdata );
- // TDECmdLineArgs::addCmdLineOptions( options );
- KUniqueApplication::addCmdLineOptions();
-
- if (!KUniqueApplication::start())
- {
- kdDebug(7024) << "kio_uiserver is already running!" << endl;
- return (0);
- }
-
- KUniqueApplication app;
-
- // This app is started automatically, no need for session management
- app.disableSessionManagement();
- app.dcopClient()->setDaemonMode( true );
-
- uiserver = UIServer::createInstance();
-
-// app.setMainWidget( uiserver );
-
- return app.exec();
-}
-
-#include "uiserver.moc"
diff --git a/kio/misc/uiserver.h b/kio/misc/uiserver.h
deleted file mode 100644
index abe935ad5..000000000
--- a/kio/misc/uiserver.h
+++ /dev/null
@@ -1,430 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2000 Matej Koss <koss@miesto.sk>
- David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License version 2 as published by the Free Software Foundation.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef __kio_uiserver_h__
-#define __kio_uiserver_h__
-
-#include <tqintdict.h>
-#include <tqdatetime.h>
-#include <tqtimer.h>
-
-#include <dcopobject.h>
-#include <kio/global.h>
-#include <kio/authinfo.h>
-#include <kurl.h>
-#include <kmainwindow.h>
-#include <kdatastream.h>
-#include <klistview.h>
-#include <ksslcertdlg.h>
-
-class ListProgress;
-class KSqueezedTextLabel;
-class ProgressItem;
-class UIServer;
-
-namespace TDEIO {
- class Job;
- class DefaultProgress;
-}
-
-
-struct ListProgressColumnConfig
-{
- TQString title;
- int index;
- int width;
- bool enabled;
-};
-
-/**
-* List view in the UIServer.
-* @internal
-*/
-class TDEIO_EXPORT ListProgress : public KListView {
-
- Q_OBJECT
-
-public:
-
- ListProgress (TQWidget *parent = 0, const char *name = 0 );
-
- virtual ~ListProgress();
-
- /**
- * Field constants
- */
- enum ListProgressFields {
- TB_OPERATION = 0,
- TB_LOCAL_FILENAME = 1,
- TB_RESUME = 2,
- TB_COUNT = 3, //lv_count
- TB_PROGRESS = 4, // lv_progress
- TB_TOTAL = 5,
- TB_SPEED = 6,
- TB_REMAINING_TIME = 7,
- TB_ADDRESS = 8,
- TB_MAX = 9
- };
-
- friend class ProgressItem;
- friend class UIServer;
-protected slots:
- void columnWidthChanged(int column);
-protected:
-
- void writeSettings();
- void readSettings();
- void applySettings();
- void createColumns();
-
- bool m_showHeader;
- bool m_fixedColumnWidths;
- ListProgressColumnConfig m_lpcc[TB_MAX];
- //hack, alexxx
- KSqueezedTextLabel *m_squeezer;
-};
-
-/**
-* One item in the ListProgress
-* @internal
-*/
-class TDEIO_EXPORT ProgressItem : public TQObject, public TQListViewItem {
-
- Q_OBJECT
-
-public:
- ProgressItem( ListProgress* view, TQListViewItem *after, TQCString app_id, int job_id,
- bool showDefault = true );
- ~ProgressItem();
-
- TQCString appId() { return m_sAppId; }
- int jobId() { return m_iJobId; }
-
- bool keepOpen() const;
- void finished();
-
- void setVisible( bool visible );
- void setDefaultProgressVisible( bool visible );
- bool isVisible() const { return m_visible; }
-
- void setTotalSize( TDEIO::filesize_t bytes );
- void setTotalFiles( unsigned long files );
- void setTotalDirs( unsigned long dirs );
-
- void setProcessedSize( TDEIO::filesize_t size );
- void setProcessedFiles( unsigned long files );
- void setProcessedDirs( unsigned long dirs );
-
- void setPercent( unsigned long percent );
- void setSpeed( unsigned long bytes_per_second );
- void setInfoMessage( const TQString & msg );
-
- void setCopying( const KURL& from, const KURL& to );
- void setMoving( const KURL& from, const KURL& to );
- void setDeleting( const KURL& url );
- void setTransferring( const KURL& url );
- void setCreatingDir( const KURL& dir );
- void setStating( const KURL& url );
- void setMounting( const TQString & dev, const TQString & point );
- void setUnmounting( const TQString & point );
-
- void setCanResume( TDEIO::filesize_t offset );
-
- TDEIO::filesize_t totalSize() { return m_iTotalSize; }
- unsigned long totalFiles() { return m_iTotalFiles; }
- TDEIO::filesize_t processedSize() { return m_iProcessedSize; }
- unsigned long processedFiles() { return m_iProcessedFiles; }
- unsigned long speed() { return m_iSpeed; }
- unsigned int remainingSeconds() { return m_remainingSeconds; }
-
- const TQString& fullLengthAddress() const {return m_fullLengthAddress;}
- void setText(ListProgress::ListProgressFields field, const TQString& text);
-public slots:
- void slotShowDefaultProgress();
- void slotToggleDefaultProgress();
-
-protected slots:
- void slotCanceled();
-
-signals:
- void jobCanceled( ProgressItem* );
-
-protected:
- void updateVisibility();
-
- // ids that uniquely identify this progress item
- TQCString m_sAppId;
- int m_iJobId;
-
- // whether shown or not (it is hidden if a rename dialog pops up for the same job)
- bool m_visible;
- bool m_defaultProgressVisible;
-
- // parent listview
- ListProgress *listProgress;
-
- // associated default progress dialog
- TDEIO::DefaultProgress *defaultProgress;
-
- // we store these values for calculation of totals ( for statusbar )
- TDEIO::filesize_t m_iTotalSize;
- unsigned long m_iTotalFiles;
- TDEIO::filesize_t m_iProcessedSize;
- unsigned long m_iProcessedFiles;
- unsigned long m_iSpeed;
- int m_remainingSeconds;
- TQTimer m_showTimer;
- TQString m_fullLengthAddress;
-};
-
-class TQResizeEvent;
-class TQHideEvent;
-class TQShowEvent;
-class ProgressConfigDialog;
-class TQPopupMenu;
-class UIServerSystemTray;
-
-/**
- * It's purpose is to show progress of IO operations.
- * There is only one instance of this window for all jobs.
- *
- * All IO operations ( jobs ) are displayed in this window, one line per operation.
- * User can cancel operations with Cancel button on toolbar.
- *
- * Double clicking an item in the list opens a small download window ( DefaultProgress ).
- *
- * @short Graphical server for progress information with an optional all-in-one progress window.
- * @author David Faure <faure@kde.org>
- * @author Matej Koss <koss@miesto.sk>
- *
- * @internal
- */
-class TDEIO_EXPORT UIServer : public KMainWindow, public DCOPObject {
-
- K_DCOP
- Q_OBJECT
-
- UIServer();
- virtual ~UIServer();
-
-public:
- static UIServer* createInstance();
-
-k_dcop:
-
- /**
- * Signal a new job
- * @param appId the DCOP application id of the job's parent application
- * @see TDEIO::Observer::newJob
- * @param showProgress whether to popup the progress for the job.
- * Usually true, but may be false when we use kio_uiserver for
- * other things, like SSL dialogs.
- * @return the job id
- */
- int newJob( TQCString appId, bool showProgress );
-
- ASYNC jobFinished( int id );
-
- ASYNC totalSize( int id, unsigned long size );
- ASYNC totalSize64( int id, TDEIO::filesize_t size );
- ASYNC totalFiles( int id, unsigned long files );
- ASYNC totalDirs( int id, unsigned long dirs );
-
- ASYNC processedSize( int id, unsigned long bytes );
- ASYNC processedSize64( int id, TDEIO::filesize_t bytes );
- ASYNC processedFiles( int id, unsigned long files );
- ASYNC processedDirs( int id, unsigned long dirs );
-
- ASYNC percent( int id, unsigned long ipercent );
- ASYNC speed( int id, unsigned long bytes_per_second );
- ASYNC infoMessage( int id, const TQString & msg );
-
- ASYNC copying( int id, KURL from, KURL to );
- ASYNC moving( int id, KURL from, KURL to );
- ASYNC deleting( int id, KURL url );
- ASYNC transferring( int id, KURL url );
- ASYNC creatingDir( int id, KURL dir );
- ASYNC stating( int id, KURL url );
-
- ASYNC mounting( int id, TQString dev, TQString point );
- ASYNC unmounting( int id, TQString point );
-
- ASYNC canResume( int id, unsigned long offset );
- ASYNC canResume64( int id, TDEIO::filesize_t offset );
-
- /**
- * @deprecated (it blocks other apps).
- * Use TDEIO::PasswordDialog::getNameAndPassword instead.
- * To be removed in KDE 4.0.
- */
- TQByteArray openPassDlg( const TDEIO::AuthInfo &info );
-
- /**
- * Popup a message box.
- * @param id The message identifier.
- * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
- * This enum is defined in slavebase.h, it currently is:
- * QuestionYesNo = 1, WarningYesNo = 2, WarningContinueCancel = 3,
- * WarningYesNoCancel = 4, Information = 5, SSLMessageBox = 6
- * @param text Message string. May contain newlines.
- * @param caption Message box title.
- * @param buttonYes The text for the first button.
- * The default is i18n("&Yes").
- * @param buttonNo The text for the second button.
- * The default is i18n("&No").
- * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
- * and for Information, none is used.
- * @return a button code, as defined in KMessageBox, or 0 on communication error.
- */
- int messageBox( int id, int type, const TQString &text, const TQString &caption,
- const TQString &buttonYes, const TQString &buttonNo );
-
- /**
- * @deprecated (it blocks other apps).
- * Use TDEIO::open_RenameDlg instead.
- * To be removed in KDE 4.0.
- */
- TQByteArray open_RenameDlg64( int id,
- const TQString & caption,
- const TQString& src, const TQString & dest,
- int /* TDEIO::RenameDlg_Mode */ mode,
- TDEIO::filesize_t sizeSrc,
- TDEIO::filesize_t sizeDest,
- unsigned long /* time_t */ ctimeSrc,
- unsigned long /* time_t */ ctimeDest,
- unsigned long /* time_t */ mtimeSrc,
- unsigned long /* time_t */ mtimeDest
- );
- /**
- * @deprecated (it blocks other apps).
- * Use TDEIO::open_RenameDlg instead.
- * To be removed in KDE 4.0.
- */
- TQByteArray open_RenameDlg( int id,
- const TQString & caption,
- const TQString& src, const TQString & dest,
- int /* TDEIO::RenameDlg_Mode */ mode,
- unsigned long sizeSrc,
- unsigned long sizeDest,
- unsigned long /* time_t */ ctimeSrc,
- unsigned long /* time_t */ ctimeDest,
- unsigned long /* time_t */ mtimeSrc,
- unsigned long /* time_t */ mtimeDest
- );
-
- /**
- * @deprecated (it blocks other apps).
- * Use TDEIO::open_SkipDlg instead.
- * To be removed in KDE 4.0.
- */
- int open_SkipDlg( int id,
- int /*bool*/ multi,
- const TQString & error_text );
-
- /**
- * Switch to or from list mode - called by the kcontrol module
- */
- void setListMode( bool list );
-
- /**
- * Hide or show a job. Typically, we hide a job while a "skip" or "rename" dialog
- * is being shown for this job. This prevents killing it from the uiserver.
- */
- void setJobVisible( int id, bool visible );
-
- /**
- * Show a SSL Information Dialog
- */
- void showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &data, int mainwindow);
-
- /**
- * @deprecated
- */
- void showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &data);
-
- /*
- * Show an SSL Certificate Selection Dialog
- */
- KSSLCertDlgRet showSSLCertDialog(const TQString& host, const TQStringList& certList, int mainwindow);
-
- /*
- * @deprecated
- */
- KSSLCertDlgRet showSSLCertDialog(const TQString& host, const TQStringList& certList);
-
-public slots:
- void slotConfigure();
- void slotRemoveSystemTrayIcon();
-protected slots:
-
- void slotUpdate();
- void slotQuit();
-
- void slotCancelCurrent();
-
- void slotToggleDefaultProgress( TQListViewItem * );
- void slotSelection();
-
- void slotJobCanceled( ProgressItem * );
- void slotApplyConfig();
- void slotShowContextMenu(KListView*, TQListViewItem *item, const TQPoint& pos);
-
-protected:
-
- ProgressItem* findItem( int id );
-
- virtual void resizeEvent(TQResizeEvent* e);
- virtual bool queryClose();
-
- void setItemVisible( ProgressItem * item, bool visible );
-
- TQTimer* updateTimer;
- ListProgress* listProgress;
-
- KToolBar::BarPosition toolbarPos;
- TQString properties;
-
- void applySettings();
- void readSettings();
- void writeSettings();
-private:
-
- void killJob( TQCString observerAppId, int progressId );
-
- int m_initWidth;
- int m_initHeight;
- int m_idCancelItem;
- bool m_bShowList;
- bool m_showStatusBar;
- bool m_showToolBar;
- bool m_keepListOpen;
- bool m_showSystemTray;
- bool m_shuttingDown;
-
- // true if there's a new job that hasn't been shown yet.
- bool m_bUpdateNewJob;
- ProgressConfigDialog *m_configDialog;
- TQPopupMenu* m_contextMenu;
- UIServerSystemTray *m_systemTray;
-
- static int s_jobId;
- friend class no_bogus_warning_from_gcc;
-};
-
-// -*- mode: c++; c-basic-offset: 2 -*-
-#endif
diff --git a/kio/pics/CMakeLists.txt b/kio/pics/CMakeLists.txt
deleted file mode 100644
index 1830674b4..000000000
--- a/kio/pics/CMakeLists.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-##### other data ################################
-
-tde_install_icons( DESTINATION ${DATA_INSTALL_DIR}/kio_uiserver/icons )
diff --git a/kio/pics/Makefile.am b/kio/pics/Makefile.am
deleted file mode 100644
index db5ddb1cc..000000000
--- a/kio/pics/Makefile.am
+++ /dev/null
@@ -1,3 +0,0 @@
-kiouiservericonsdir = $(kde_datadir)/kio_uiserver/icons
-kiouiservericons_ICON = AUTO
-
diff --git a/kio/tests/CMakeLists.txt b/kio/tests/CMakeLists.txt
deleted file mode 100644
index 54378f5c8..000000000
--- a/kio/tests/CMakeLists.txt
+++ /dev/null
@@ -1,36 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### ktradertest ###############################
-
-set( target ktradertest )
-
-set( ${target}_SRCS
- ktradertest.cpp
-)
-
-tde_add_executable( ${target}
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${BIN_INSTALL_DIR}
-)
diff --git a/kio/tests/Makefile.am b/kio/tests/Makefile.am
deleted file mode 100644
index 3a81dfc57..000000000
--- a/kio/tests/Makefile.am
+++ /dev/null
@@ -1,91 +0,0 @@
-# This file is part of the KDE libraries
-# Copyright (C) 1997 David Faure <faure@kde.org>
-
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-
-# This library 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
-# Library General Public License for more details.
-
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/kio $(all_includes)
-LDADD = $(LIB_KIO)
-AM_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-
-check_PROGRAMS = tdesycocatest getalltest kruntest ktartest kziptest\
- kioslavetest kdirwatchtest kshredtest speed kurifiltertest \
- kdefaultprogresstest kmimemagictest \
- kfiltertest kiopassdlgtest kscantest kdirlistertest \
- previewtest kionetrctest kdcopcheck metatest \
- kmimefromext kpropsdlgtest kmfitest dataprotocoltest \
- kprotocolinfotest tdesycocaupdatetest netaccesstest jobtest \
- kurlcompletiontest kmimetypetest kacltest
-
-# Unfortunately some tests depend on the network settings, it seems
-#check: kurifiltertest
-# ./kurifiltertest
-check-local: kziptest
- ./kziptest list $(srcdir)/wronglocalsizes.zip
-
-TESTS = kmimetypetest
-
-bin_PROGRAMS = ktradertest
-
-METASOURCES = AUTO
-
-speed_SOURCES = speed.cpp
-kioslavetest_SOURCES = kioslavetest.cpp
-kshredtest_SOURCES = kshredtest.cpp
-kdefaultprogresstest_SOURCES = kdefaultprogresstest.cpp
-kionetrctest_SOURCES = kionetrctest.cpp
-kiopassdlgtest_SOURCES = kiopassdlgtest.cpp
-kurifiltertest_SOURCES = kurifiltertest.cpp
-tdesycocatest_SOURCES = tdesycocatest.cpp
-kdcopcheck_SOURCES = kdcopcheck.cpp
-getalltest_SOURCES = getalltest.cpp
-kruntest_SOURCES = kruntest.cpp
-kdirwatchtest_SOURCES = kdirwatchtest.cpp
-ktradertest_SOURCES = ktradertest.cpp
-kmimemagictest_SOURCES = kmimemagictest.cpp
-kfiltertest_SOURCES = kfiltertest.cpp
-kscantest_SOURCES = kscantest.cpp
-kdirlistertest_SOURCES = kdirlistertest.cpp
-previewtest_SOURCES = previewtest.cpp
-ktartest_SOURCES = ktartest.cpp
-kziptest_SOURCES = kziptest.cpp
-metatest_SOURCES = metatest.cpp
-kmimefromext_SOURCES = kmimefromext.cpp
-kpropsdlgtest_SOURCES = kpropsdlgtest.cpp
-kmfitest_SOURCES = kmfitest.cpp
-dataprotocoltest_SOURCES = dataprotocoltest.cpp
-kprotocolinfotest_SOURCES = kprotocolinfotest.cpp
-tdesycocaupdatetest_SOURCES = tdesycocaupdatetest.cpp
-netaccesstest_SOURCES = netaccesstest.cpp
-jobtest_SOURCES = jobtest.cpp
-kurlcompletiontest_SOURCES = kurlcompletiontest.cpp
-kmimetypetest_SOURCES = kmimetypetest.cpp
-kacltest_SOURCES = kacltest.cpp
-
-
-check_LTLIBRARIES = tdeunittest_kdirwatch.la
-tdeunittest_kdirwatch_la_SOURCES = kdirwatchunittest.cpp
-tdeunittest_kdirwatch_la_LIBADD = $(LIB_KUNITTEST) $(LIB_KIO)
-tdeunittest_kdirwatch_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN)
-
-# kfile meta stuff. Comment this in, if you want a small
-# metadata plugin test and "make install".
-#kde_module_LTLIBRARIES = dummymeta.la
-#dummymeta_la_SOURCES = dummymeta.cpp
-#dummymeta_la_LIBADD = $(LIB_KIO)
-#dummymeta_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
-
-#services_DATA = dummymeta.desktop
-#servicesdir = $(kde_servicesdir)
diff --git a/kio/tests/dataprotocoltest.cpp b/kio/tests/dataprotocoltest.cpp
deleted file mode 100644
index dfacd92e4..000000000
--- a/kio/tests/dataprotocoltest.cpp
+++ /dev/null
@@ -1,287 +0,0 @@
-// testing the data kioslave
-// (C) 2002, 2003 Leo Savernik
-//
-// invoke "make dataprotocoltest" to generate the binary inside KDE CVS
-// invoke "make test" to generate the binary outside KDE CVS
-
-// fix the symptoms, not the illness ;-)
-#ifdef QT_NO_ASCII_CAST
-# undef QT_NO_ASCII_CAST
-#endif
-
-#ifdef DATAKIOSLAVE
-# undef DATAKIOSLAVE
-#endif
-#ifndef TESTKIO
-# define TESTKIO
-#endif
-
-#include <kio/global.h>
-
-#include <tqcstring.h>
-#include <tqstring.h>
-
-#include <iostream.h>
-
-class KURL;
-
-class TestSlave {
-public:
- TestSlave() {
- }
- virtual ~TestSlave() {
- }
-
- virtual void get(const KURL &) = 0;
- virtual void mimetype(const KURL &) = 0;
-
- void mimeType(const TQString &type) {
- testStrings("MIME Type: ",mime_type_expected,type);
- }
-
- void totalSize(TDEIO::filesize_t bytes) {
-// cout << "content size: " << bytes << " bytes" << endl;
- }
-
- void setMetaData(const TQString &key, const TQString &value) {
-// meta_data[key] = value;
-// cout << "§ " << key << " = " << value << endl;
- TQString prefix = "Metadata[\""+key+"\"]: ";
- TDEIO::MetaData::Iterator it = attributes_expected.find(key);
- if (it != attributes_expected.end()) {
- testStrings(prefix,it.data(),value);
- // remove key from map
- attributes_expected.remove(it);
- } else {
- cout << endl << prefix << " no such key expected";
- total++;
- }
- }
-
- void sendMetaData() {
- // check here if attributes_expected contains any excess keys
- TDEIO::MetaData::ConstIterator it = attributes_expected.begin();
- TDEIO::MetaData::ConstIterator end = attributes_expected.end();
- for (; it != end; ++it) {
- cout << endl << "Metadata[\"" << it.key()
- << "\"] was expected but not defined";
- total++;
- }
- }
-
- void data(const TQByteArray &a) {
- if (a.isEmpty())
-/* cout << "<no more data>" << endl*/;
- else {
- testStrings("Content: ",content_expected,a);
- }/*end if*/
- }
-
- void finished() {
- }
-
- void dispatchLoop() {
- // dummy to make kde_main happy
- }
-
- // == stuff for regression testing
-private:
- int testcaseno; // number of testcase
- bool failure; // true if any testcase failed
- TQMap<int,bool> failed_testcases;
-
- // -- testcase related members
- TQString mime_type_expected; // expected mime type
- /** contains all attributes and values the testcase has to set */
- TDEIO::MetaData attributes_expected;
- /** contains the content as it is expected to be returned */
- TQByteArray content_expected;
- int passed; // # of passed tests
- int total; // # of total tests
-
- /**
- * compares two strings, printing an error message if they don't match.
- * @param prefix prefix string for output in case of mismatch
- * @param templat template string
- * @param s string to compare to template
- * @param casesensitive true if case sensitive compare (currently not used)
- */
- void testStrings(const TQString &prefix, const TQString &templat,
- const TQString &s, bool /*casesensitive*/ = true) {
- if (templat == s)
- passed++;
- else {
- cout << endl << prefix << "expected \"" << templat << "\", found \""
- << s << "\"";
- failure = true;
- }/*end if*/
- total++;
- }
-
-public:
- /** begins a testrun over all testcases */
- void initTestrun() {
- testcaseno = 0;
- failure = false;
- }
-
- /** reuturns true if any testcase failed
- */
- bool hasFailedTestcases() const { return failure; }
-
- /**
- * sets up a new testcase
- * @param name screen name for testcase
- */
- void beginTestcase(const char *name) {
- passed = 0;
- total = 0;
- testcaseno++;
- cout << "Testcase " << testcaseno << ": [" << name << "] ";
- }
-
- /**
- * sets the mime type that this testcase is expected to return
- */
- void setExpectedMimeType(const TQString &mime_type) {
- mime_type_expected = mime_type;
- }
-
- /**
- * sets all attribute-value pairs the testcase must deliver.
- */
- void setExpectedAttributes(const TDEIO::MetaData &attres) {
- attributes_expected = attres;
- }
-
- /**
- * sets content as expected to be delivered by the testcase.
- */
- void setExpectedContent(const TQByteArray &content) {
- content_expected = content;
- }
-
- /**
- * closes testcase, printing out stats
- */
- void endTestcase() {
- bool failed = passed < total;
- if (failed) {
- failure = true;
- failed_testcases[testcaseno] = true;
- cout << endl;
- }
- cout << "(" << passed << " of " << total << ") " << (failed ? "failed"
- : "passed") << endl;
- }
-
- void endTestrun() {
- if (failure) {
- TQMap<int,bool>::ConstIterator it = failed_testcases.begin();
- for (; it != failed_testcases.end(); ++it) {
- cout << "Testcase " << it.key() << " failed" << endl;
- }
- }
- }
-};
-
-#include "dataprotocol.cpp" // we need access to static data & functions
-
-// == general functionality
-const struct {
-const char * const name;
-const char * const exp_mime_type; // 0 means "text/plain"
-const struct {
- const char * const key;
- const char * const value;
-} exp_attrs[10]; // ended with a key==0, value==0 pair
-const char * const exp_content;
-const char * const url;
-} testcases[] = {
- // -----------------------------------------------------------------
- { "escape resolving", 0, {}, "blah blah", "data:,blah%20blah" },
- // --------------------
- { "mime type, escape resolving", "text/html", {},
- "<div style=\"border:thin orange solid;padding:1ex;background-color:"
- "yellow;color:black\">Rich <b>text</b></div>",
- "data:text/html,<div%20style=\"border:thin%20orange%20solid;"
- "padding:1ex;background-color:yellow;color:black\">Rich%20<b>text</b>"
- "</div>" },
- // -------------------- whitespace test I
- { "whitespace test I", "text/css", {
- { "charset", "iso-8859-15" }, { 0,0 } },
- " body { color: yellow; background:darkblue; font-weight:bold }",
- "data:text/css ; charset = iso-8859-15 , body { color: yellow; "
- "background:darkblue; font-weight:bold }" },
- // -------------------- out of spec argument order, base64 decoding,
- // whitespace test II
- { "out of spec argument order, base64 decoding, whitespace test II",
- 0, {
- { "charset", "iso-8859-1" }, { 0,0 } },
- "paaaaaaaasd!!\n",
- "data: ; base64 ; charset = \"iso-8859-1\" ,cGFhYWFhYWFhc2QhIQo=" },
- // -------------------- arbitrary keys, reserved names as keys,
- // whitespace test III
- { "arbitrary keys, reserved names as keys, whitespace test III", 0, {
- { "base64", "nospace" }, { "key", "onespaceinner" },
- { "key2", "onespaceouter" }, { "charset", "utf8" },
- { "<<empty>>", "" }, { 0,0 } },
- "Die, Allied Schweinehund (C) 1990 Wolfenstein 3D",
- "data: ;base64=nospace;key = onespaceinner; key2=onespaceouter ;"
- " charset = utf8 ; <<empty>>= ,Die, Allied Schweinehund "
- "(C) 1990 Wolfenstein 3D" },
- // -------------------- string literal with escaped chars, testing
- // delimiters within string
- { "string literal with escaped chars, testing delimiters within "
- "string", 0, {
- { "fortune-cookie", "Master Leep say: \"Rabbit is humble, "
- "Rabbit is gentle; follow the Rabbit\"" }, { 0,0 } },
- "(C) 1997 Shadow Warrior ;-)",
- "data:;fortune-cookie=\"Master Leep say: \\\"Rabbit is humble, "
- "Rabbit is gentle; follow the Rabbit\\\"\",(C) 1997 Shadow Warrior "
- ";-)" },
-};
-
-#if 0
-// == charset tests
- // -------------------- string
-const QChar
-const TQChar * const charset_urls[] = {
-#endif
-
-int main(int /*argc*/,char* /*argv*/[]) {
- DataProtocol kio_data;
-
- kio_data.initTestrun();
- for (uint i = 0; i < sizeof testcases/sizeof testcases[0]; i++) {
- kio_data.beginTestcase(testcases[i].name);
- kio_data.setExpectedMimeType(testcases[i].exp_mime_type != 0
- ? testcases[i].exp_mime_type : "text/plain");
-
- bool has_charset = false;
- MetaData exp_attrs;
- if (testcases[i].exp_attrs != 0) {
- for (uint j = 0; testcases[i].exp_attrs[j].key != 0; j++) {
- exp_attrs[testcases[i].exp_attrs[j].key] = testcases[i].exp_attrs[j].value;
- if (strcmp(testcases[i].exp_attrs[j].key,"charset") == 0)
- has_charset = true;
- }/*next j*/
- }
- if (!has_charset) exp_attrs["charset"] = "us-ascii";
- kio_data.setExpectedAttributes(exp_attrs);
-
- TQByteArray exp_content;
- uint exp_content_len = strlen(testcases[i].exp_content);
- exp_content.setRawData(testcases[i].exp_content,exp_content_len);
- kio_data.setExpectedContent(exp_content);
-
- kio_data.get(testcases[i].url);
-
- kio_data.endTestcase();
- exp_content.resetRawData(testcases[i].exp_content,exp_content_len);
- }/*next i*/
- kio_data.endTestrun();
-
- return kio_data.hasFailedTestcases() ? 1 : 0;
-}
-
diff --git a/kio/tests/dummymeta.h b/kio/tests/dummymeta.h
deleted file mode 100644
index 053c48ecb..000000000
--- a/kio/tests/dummymeta.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef DUMMYMETA_H
-#define DUMMYMETA_H
-
-#include <kfilemetainfo.h>
-
-class KFileMetaInfo;
-
-class DummyMeta : public KFilePlugin
-{
- Q_OBJECT
-
-public:
- DummyMeta( TQObject *parent, const char *name, const TQStringList &args );
- ~DummyMeta() {}
-
- virtual bool readInfo( KFileMetaInfo::Internal& info );
-
-};
-
-#endif
diff --git a/kio/tests/jobtest.cpp b/kio/tests/jobtest.cpp
deleted file mode 100644
index e811aaec4..000000000
--- a/kio/tests/jobtest.cpp
+++ /dev/null
@@ -1,613 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2004-2006 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "jobtest.h"
-
-#include <config.h>
-
-#include <kurl.h>
-#include <kapplication.h>
-#include <klargefile.h>
-#include <kio/netaccess.h>
-#include <kdebug.h>
-#include <kcmdlineargs.h>
-#include <kprotocolinfo.h>
-
-#include <tqfileinfo.h>
-#include <tqeventloop.h>
-#include <tqdir.h>
-#include <tqfileinfo.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <unistd.h>
-#include <errno.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <time.h>
-#include <utime.h>
-
-// The code comes partly from tdebase/kioslave/trash/testtrash.cpp
-
-static bool check(const TQString& txt, TQString a, TQString b)
-{
- if (a.isEmpty())
- a = TQString::null;
- if (b.isEmpty())
- b = TQString::null;
- if (a == b) {
- kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
- }
- else {
- kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
- exit(1);
- }
- return true;
-}
-
-int main(int argc, char *argv[])
-{
- TDEApplication::disableAutoDcopRegistration();
- TDECmdLineArgs::init(argc,argv,"jobtest", 0, 0, 0, 0);
- TDEApplication app;
-
- JobTest test;
- test.setup();
- test.runAll();
- test.cleanup();
- kdDebug() << "All tests OK." << endl;
- return 0; // success. The exit(1) in check() is what happens in case of failure.
-}
-
-TQString JobTest::homeTmpDir() const
-{
- return TQDir::homeDirPath() + "/.trinity/jobtest/";
-}
-
-TQString JobTest::otherTmpDir() const
-{
- // This one needs to be on another partition
- return "/tmp/jobtest/";
-}
-
-KURL JobTest::systemTmpDir() const
-{
- return "system:/home/.trinity/jobtest-system/";
-}
-
-TQString JobTest::realSystemPath() const
-{
- return TQDir::homeDirPath() + "/.trinity/jobtest-system/";
-}
-
-void JobTest::setup()
-{
- // Start with a clean base dir
- cleanup();
- TQDir dir; // TT: why not a static method?
- bool ok = dir.mkdir( homeTmpDir() );
- if ( !ok )
- kdFatal() << "Couldn't create " << homeTmpDir() << endl;
- ok = dir.mkdir( otherTmpDir() );
- if ( !ok )
- kdFatal() << "Couldn't create " << otherTmpDir() << endl;
- ok = dir.mkdir( realSystemPath() );
- if ( !ok )
- kdFatal() << "Couldn't create " << realSystemPath() << endl;
-}
-
-void JobTest::runAll()
-{
- get();
- copyFileToSamePartition();
- copyDirectoryToSamePartition();
- copyDirectoryToExistingDirectory();
- copyFileToOtherPartition();
- copyDirectoryToOtherPartition();
- listRecursive();
- moveFileToSamePartition();
- moveDirectoryToSamePartition();
- moveFileToOtherPartition();
- moveSymlinkToOtherPartition();
- moveDirectoryToOtherPartition();
- moveFileNoPermissions();
- moveDirectoryNoPermissions();
-
- copyFileToSystem();
-}
-
-void JobTest::cleanup()
-{
- TDEIO::NetAccess::del( homeTmpDir(), 0 );
- TDEIO::NetAccess::del( otherTmpDir(), 0 );
- TDEIO::NetAccess::del( systemTmpDir(), 0 );
-}
-
-static void setTimeStamp( const TQString& path )
-{
-#ifdef Q_OS_UNIX
- // Put timestamp in the past so that we can check that the
- // copy actually preserves it.
- struct timeval tp;
- gettimeofday( &tp, 0 );
- struct utimbuf utbuf;
- utbuf.actime = tp.tv_sec - 30; // 30 seconds ago
- utbuf.modtime = tp.tv_sec - 60; // 60 second ago
- utime( TQFile::encodeName( path ), &utbuf );
- tqDebug( "Time changed for %s", path.latin1() );
-#endif
-}
-
-static void createTestFile( const TQString& path )
-{
- TQFile f( path );
- if ( !f.open( IO_WriteOnly ) )
- kdFatal() << "Can't create " << path << endl;
- f.tqwriteBlock( "Hello world", 11 );
- f.close();
- setTimeStamp( path );
-}
-
-static void createTestSymlink( const TQString& path )
-{
- // Create symlink if it doesn't exist yet
- KDE_struct_stat buf;
- if ( KDE_lstat( TQFile::encodeName( path ), &buf ) != 0 ) {
- bool ok = symlink( "/IDontExist", TQFile::encodeName( path ) ) == 0; // broken symlink
- if ( !ok )
- kdFatal() << "couldn't create symlink: " << strerror( errno ) << endl;
- }
-}
-
-static void createTestDirectory( const TQString& path )
-{
- TQDir dir;
- bool ok = dir.mkdir( path );
- if ( !ok && !dir.exists() )
- kdFatal() << "couldn't create " << path << endl;
- createTestFile( path + "/testfile" );
- createTestSymlink( path + "/testlink" );
- setTimeStamp( path );
-}
-
-void JobTest::get()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString filePath = homeTmpDir() + "fileFromHome";
- createTestFile( filePath );
- KURL u; u.setPath( filePath );
- m_result = -1;
- TDEIO::StoredTransferJob* job = TDEIO::storedGet( u );
- connect( job, TQT_SIGNAL( result( TDEIO::Job* ) ),
- this, TQT_SLOT( slotGetResult( TDEIO::Job* ) ) );
- kapp->eventLoop()->enterLoop();
- assert( m_result == 0 ); // no error
- assert( m_data.size() == 11 );
- assert( TQCString( m_data ) == "Hello world" );
-}
-
-void JobTest::slotGetResult( TDEIO::Job* job )
-{
- m_result = job->error();
- m_data = static_cast<TDEIO::StoredTransferJob *>(job)->data();
- kapp->eventLoop()->exitLoop();
-}
-
-////
-
-void JobTest::copyLocalFile( const TQString& src, const TQString& dest )
-{
- KURL u;
- u.setPath( src );
- KURL d;
- d.setPath( dest );
-
- // copy the file with file_copy
- bool ok = TDEIO::NetAccess::file_copy( u, d );
- assert( ok );
- assert( TQFile::exists( dest ) );
- assert( TQFile::exists( src ) ); // still there
-
- {
- // check that the timestamp is the same (#24443)
- // Note: this only works because of copy() in kio_file.
- // The datapump solution ignores mtime, the app has to call FileCopyJob::setModificationTime()
- TQFileInfo srcInfo( src );
- TQFileInfo destInfo( dest );
- assert( srcInfo.lastModified() == destInfo.lastModified() );
- }
-
- // cleanup and retry with TDEIO::copy()
- TQFile::remove( dest );
- ok = TDEIO::NetAccess::dircopy( u, d, 0 );
- assert( ok );
- assert( TQFile::exists( dest ) );
- assert( TQFile::exists( src ) ); // still there
- {
- // check that the timestamp is the same (#24443)
- TQFileInfo srcInfo( src );
- TQFileInfo destInfo( dest );
- assert( srcInfo.lastModified() == destInfo.lastModified() );
- }
-}
-
-void JobTest::copyLocalDirectory( const TQString& src, const TQString& _dest, int flags )
-{
- assert( TQFileInfo( src ).isDir() );
- assert( TQFileInfo( src + "/testfile" ).isFile() );
- KURL u;
- u.setPath( src );
- TQString dest( _dest );
- KURL d;
- d.setPath( dest );
- if ( flags & AlreadyExists )
- assert( TQFile::exists( dest ) );
- else
- assert( !TQFile::exists( dest ) );
-
- bool ok = TDEIO::NetAccess::dircopy( u, d, 0 );
- assert( ok );
-
- if ( flags & AlreadyExists ) {
- dest += "/" + u.fileName();
- //kdDebug() << "Expecting dest=" << dest << endl;
- }
-
- assert( TQFile::exists( dest ) );
- assert( TQFileInfo( dest ).isDir() );
- assert( TQFileInfo( dest + "/testfile" ).isFile() );
- assert( TQFile::exists( src ) ); // still there
- {
- // check that the timestamp is the same (#24443)
- TQFileInfo srcInfo( src );
- TQFileInfo destInfo( dest );
- assert( srcInfo.lastModified() == destInfo.lastModified() );
- }
-}
-
-void JobTest::copyFileToSamePartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString filePath = homeTmpDir() + "fileFromHome";
- const TQString dest = homeTmpDir() + "fileFromHome_copied";
- createTestFile( filePath );
- copyLocalFile( filePath, dest );
-}
-
-void JobTest::copyDirectoryToSamePartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString src = homeTmpDir() + "dirFromHome";
- const TQString dest = homeTmpDir() + "dirFromHome_copied";
- createTestDirectory( src );
- copyLocalDirectory( src, dest );
-}
-
-void JobTest::copyDirectoryToExistingDirectory()
-{
- kdDebug() << k_funcinfo << endl;
- // just the same as copyDirectoryToSamePartition, but it means that
- // this time dest exists.
- const TQString src = homeTmpDir() + "dirFromHome";
- const TQString dest = homeTmpDir() + "dirFromHome_copied";
- createTestDirectory( src );
- copyLocalDirectory( src, dest, AlreadyExists );
-}
-
-void JobTest::copyFileToOtherPartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString filePath = homeTmpDir() + "fileFromHome";
- const TQString dest = otherTmpDir() + "fileFromHome_copied";
- createTestFile( filePath );
- copyLocalFile( filePath, dest );
-}
-
-void JobTest::copyDirectoryToOtherPartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString src = homeTmpDir() + "dirFromHome";
- const TQString dest = otherTmpDir() + "dirFromHome_copied";
- // src is already created by copyDirectoryToSamePartition()
- // so this is just in case someone calls this method only
- if ( !TQFile::exists( src ) )
- createTestDirectory( src );
- copyLocalDirectory( src, dest );
-}
-
-void JobTest::moveLocalFile( const TQString& src, const TQString& dest )
-{
- assert( TQFile::exists( src ) );
- KURL u;
- u.setPath( src );
- KURL d;
- d.setPath( dest );
-
- // move the file with file_move
- bool ok = TDEIO::NetAccess::file_move( u, d );
- assert( ok );
- assert( TQFile::exists( dest ) );
- assert( !TQFile::exists( src ) ); // not there anymore
-
- // move it back with TDEIO::move()
- ok = TDEIO::NetAccess::move( d, u, 0 );
- assert( ok );
- assert( !TQFile::exists( dest ) );
- assert( TQFile::exists( src ) ); // it's back
-}
-
-static void moveLocalSymlink( const TQString& src, const TQString& dest )
-{
- KDE_struct_stat buf;
- assert ( KDE_lstat( TQFile::encodeName( src ), &buf ) == 0 );
- KURL u;
- u.setPath( src );
- KURL d;
- d.setPath( dest );
-
- // move the symlink with move, NOT with file_move
- bool ok = TDEIO::NetAccess::move( u, d );
- if ( !ok )
- kdWarning() << TDEIO::NetAccess::lastError() << endl;
- assert( ok );
- assert ( KDE_lstat( TQFile::encodeName( dest ), &buf ) == 0 );
- assert( !TQFile::exists( src ) ); // not there anymore
-
- // move it back with TDEIO::move()
- ok = TDEIO::NetAccess::move( d, u, 0 );
- assert( ok );
- assert ( KDE_lstat( TQFile::encodeName( dest ), &buf ) != 0 ); // doesn't exist anymore
- assert ( KDE_lstat( TQFile::encodeName( src ), &buf ) == 0 ); // it's back
-}
-
-void JobTest::moveLocalDirectory( const TQString& src, const TQString& dest )
-{
- assert( TQFile::exists( src ) );
- assert( TQFileInfo( src ).isDir() );
- assert( TQFileInfo( src + "/testfile" ).isFile() );
- assert( TQFileInfo( src + "/testlink" ).isSymLink() );
- KURL u;
- u.setPath( src );
- KURL d;
- d.setPath( dest );
-
- bool ok = TDEIO::NetAccess::move( u, d, 0 );
- assert( ok );
- assert( TQFile::exists( dest ) );
- assert( TQFileInfo( dest ).isDir() );
- assert( TQFileInfo( dest + "/testfile" ).isFile() );
- assert( !TQFile::exists( src ) ); // not there anymore
-
- assert( TQFileInfo( dest + "/testlink" ).isSymLink() );
-}
-
-void JobTest::moveFileToSamePartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString filePath = homeTmpDir() + "fileFromHome";
- const TQString dest = homeTmpDir() + "fileFromHome_moved";
- createTestFile( filePath );
- moveLocalFile( filePath, dest );
-}
-
-void JobTest::moveDirectoryToSamePartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString src = homeTmpDir() + "dirFromHome";
- const TQString dest = homeTmpDir() + "dirFromHome_moved";
- createTestDirectory( src );
- moveLocalDirectory( src, dest );
-}
-
-void JobTest::moveFileToOtherPartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString filePath = homeTmpDir() + "fileFromHome";
- const TQString dest = otherTmpDir() + "fileFromHome_moved";
- createTestFile( filePath );
- moveLocalFile( filePath, dest );
-}
-
-void JobTest::moveSymlinkToOtherPartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString filePath = homeTmpDir() + "testlink";
- const TQString dest = otherTmpDir() + "testlink_moved";
- createTestSymlink( filePath );
- moveLocalSymlink( filePath, dest );
-}
-
-void JobTest::moveDirectoryToOtherPartition()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString src = homeTmpDir() + "dirFromHome";
- const TQString dest = otherTmpDir() + "dirFromHome_moved";
- createTestDirectory( src );
- moveLocalDirectory( src, dest );
-}
-
-void JobTest::moveFileNoPermissions()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString src = "/etc/passwd";
- const TQString dest = homeTmpDir() + "passwd";
- assert( TQFile::exists( src ) );
- assert( TQFileInfo( src ).isFile() );
- KURL u;
- u.setPath( src );
- KURL d;
- d.setPath( dest );
-
- TDEIO::CopyJob* job = TDEIO::move( u, d, 0 );
- job->setInteractive( false ); // no skip dialog, thanks
- TQMap<TQString, TQString> metaData;
- bool ok = TDEIO::NetAccess::synchronousRun( job, 0, 0, 0, &metaData );
- assert( !ok );
- assert( TDEIO::NetAccess::lastError() == TDEIO::ERR_ACCESS_DENIED );
- // OK this is fishy. Just like mv(1), KIO's behavior depends on whether
- // a direct rename(2) was used, or a full copy+del. In the first case
- // there is no destination file created, but in the second case the
- // destination file remains.
- // In fact we assume /home is a separate partition, in this test, so:
- assert( TQFile::exists( dest ) );
- assert( TQFile::exists( src ) );
-}
-
-void JobTest::moveDirectoryNoPermissions()
-{
- kdDebug() << k_funcinfo << endl;
- const TQString src = "/etc/init.d";
- const TQString dest = homeTmpDir() + "init.d";
- assert( TQFile::exists( src ) );
- assert( TQFileInfo( src ).isDir() );
- KURL u;
- u.setPath( src );
- KURL d;
- d.setPath( dest );
-
- TDEIO::CopyJob* job = TDEIO::move( u, d, 0 );
- job->setInteractive( false ); // no skip dialog, thanks
- TQMap<TQString, TQString> metaData;
- bool ok = TDEIO::NetAccess::synchronousRun( job, 0, 0, 0, &metaData );
- assert( !ok );
- assert( TDEIO::NetAccess::lastError() == TDEIO::ERR_ACCESS_DENIED );
- assert( TQFile::exists( dest ) ); // see moveFileNoPermissions
- assert( TQFile::exists( src ) );
-}
-
-void JobTest::listRecursive()
-{
- const TQString src = homeTmpDir();
- KURL u;
- u.setPath( src );
- TDEIO::ListJob* job = TDEIO::listRecursive( u );
- connect( job, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList& ) ),
- TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& ) ) );
- bool ok = TDEIO::NetAccess::synchronousRun( job, 0 );
- assert( ok );
- m_names.sort();
- check( "listRecursive", m_names.join( "," ), ".,..,"
- "dirFromHome,dirFromHome/testfile,dirFromHome/testlink,dirFromHome_copied,"
- "dirFromHome_copied/dirFromHome,dirFromHome_copied/dirFromHome/testfile,dirFromHome_copied/dirFromHome/testlink,"
- "dirFromHome_copied/testfile,dirFromHome_copied/testlink,"
- "fileFromHome,fileFromHome_copied" );
-}
-
-void JobTest::slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& lst )
-{
- for( TDEIO::UDSEntryList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) {
- TDEIO::UDSEntry::ConstIterator it2 = (*it).begin();
- TQString displayName;
- KURL url;
- for( ; it2 != (*it).end(); it2++ ) {
- switch ((*it2).m_uds) {
- case TDEIO::UDS_NAME:
- displayName = (*it2).m_str;
- break;
- case TDEIO::UDS_URL:
- url = (*it2).m_str;
- break;
- }
- }
- m_names.append( displayName );
- }
-}
-
-void JobTest::copyFileToSystem()
-{
- if ( !KProtocolInfo::isKnownProtocol( TQString::fromLatin1( "system" ) ) ) {
- kdDebug() << k_funcinfo << "no kio_system, skipping test" << endl;
- return;
- }
-
- // First test with support for UDS_LOCAL_PATH
- copyFileToSystem( true );
-
- TQString dest = realSystemPath() + "fileFromHome_copied";
- TQFile::remove( dest );
-
- // Then disable support for UDS_LOCAL_PATH, i.e. test what would
- // happen for ftp, smb, http etc.
- copyFileToSystem( false );
-}
-
-void JobTest::copyFileToSystem( bool resolve_local_urls )
-{
- kdDebug() << k_funcinfo << resolve_local_urls << endl;
- extern TDEIO_EXPORT bool kio_resolve_local_urls;
- kio_resolve_local_urls = resolve_local_urls;
-
- const TQString src = homeTmpDir() + "fileFromHome";
- createTestFile( src );
- KURL u;
- u.setPath( src );
- KURL d = systemTmpDir();
- d.addPath( "fileFromHome_copied" );
-
- kdDebug() << "copying " << u << " to " << d << endl;
-
- // copy the file with file_copy
- TDEIO::FileCopyJob* job = TDEIO::file_copy( u, d );
- connect( job, TQT_SIGNAL(mimetype(TDEIO::Job*,const TQString&)),
- this, TQT_SLOT(slotMimetype(TDEIO::Job*,const TQString&)) );
- bool ok = TDEIO::NetAccess::synchronousRun( job, 0 );
- assert( ok );
-
- TQString dest = realSystemPath() + "fileFromHome_copied";
-
- assert( TQFile::exists( dest ) );
- assert( TQFile::exists( src ) ); // still there
-
- {
- // do NOT check that the timestamp is the same.
- // It can't work with file_copy when it uses the datapump,
- // unless we use setModificationTime in the app code.
- }
-
- // Check mimetype
- kdDebug() << m_mimetype << endl;
- // There's no mimemagic determination in kio_file in trinity. Fixing this for kde4...
- assert( m_mimetype == "application/octet-stream" );
- //assert( m_mimetype == "text/plain" );
-
- // cleanup and retry with TDEIO::copy()
- TQFile::remove( dest );
- ok = TDEIO::NetAccess::dircopy( u, d, 0 );
- assert( ok );
- assert( TQFile::exists( dest ) );
- assert( TQFile::exists( src ) ); // still there
- {
- // check that the timestamp is the same (#79937)
- TQFileInfo srcInfo( src );
- TQFileInfo destInfo( dest );
- assert( srcInfo.lastModified() == destInfo.lastModified() );
- }
-
- // restore normal behavior
- kio_resolve_local_urls = true;
-}
-
-void JobTest::slotMimetype(TDEIO::Job* job, const TQString& type)
-{
- assert( job );
- m_mimetype = type;
-}
-
-#include "jobtest.moc"
diff --git a/kio/tests/jobtest.h b/kio/tests/jobtest.h
deleted file mode 100644
index 61051fbaf..000000000
--- a/kio/tests/jobtest.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2004 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef JOBTEST_H
-#define JOBTEST_H
-
-#include <tqstring.h>
-#include <tqobject.h>
-#include <kio/job.h>
-
-class JobTest : public TQObject
-{
- Q_OBJECT
-
-public:
- JobTest() {}
- void setup();
- void runAll();
- void cleanup();
-
- // Local tests (kio_file only)
- void get();
- void copyFileToSamePartition();
- void copyDirectoryToSamePartition();
- void copyDirectoryToExistingDirectory();
- void copyFileToOtherPartition();
- void copyDirectoryToOtherPartition();
- void listRecursive();
- void moveFileToSamePartition();
- void moveDirectoryToSamePartition();
- void moveFileToOtherPartition();
- void moveSymlinkToOtherPartition();
- void moveDirectoryToOtherPartition();
- void moveFileNoPermissions();
- void moveDirectoryNoPermissions();
-
- // Remote tests
- void copyFileToSystem();
-
-private slots:
- void slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& lst );
- void slotGetResult( TDEIO::Job* );
- void slotMimetype(TDEIO::Job*,const TQString&);
-
-private:
- TQString homeTmpDir() const;
- TQString otherTmpDir() const;
- TQString realSystemPath() const;
- KURL systemTmpDir() const;
- enum { AlreadyExists = 1 };
- void copyLocalFile( const TQString& src, const TQString& dest );
- void copyLocalDirectory( const TQString& src, const TQString& dest, int flags = 0 );
- void moveLocalFile( const TQString& src, const TQString& dest );
- void moveLocalDirectory( const TQString& src, const TQString& dest );
- void copyFileToSystem( bool resolve_local_urls );
-
- int m_result;
- TQByteArray m_data;
- TQStringList m_names;
- TQString m_mimetype;
-};
-
-#endif
diff --git a/kio/tests/kacltest.cpp b/kio/tests/kacltest.cpp
deleted file mode 100644
index 45ace585f..000000000
--- a/kio/tests/kacltest.cpp
+++ /dev/null
@@ -1,309 +0,0 @@
-/* This file is part of the KDE project
- Copyright (C) 2005 Till Adam <adam@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kacltest.h"
-
-#include <config.h>
-
-#include <kacl.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kcmdlineargs.h>
-
-#include <tqfileinfo.h>
-#include <tqeventloop.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <tqdir.h>
-
-// The code comes partly from tdebase/kioslave/trash/testtrash.cpp
-
-static bool check(const TQString& txt, TQString a, TQString b)
-{
- if (a.isEmpty())
- a = TQString::null;
- if (b.isEmpty())
- b = TQString::null;
- if (a == b) {
- kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
- }
- else {
- kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
- exit(1);
- }
- return true;
-}
-
-template<typename T>
-static bool check(const TQString& txt, T a, T b)
-{
- if (a == b) {
- kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
- }
- else {
- kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
- exit(1);
- }
- return true;
-}
-
-int main(int argc, char *argv[])
-{
- TDEApplication::disableAutoDcopRegistration();
- TDECmdLineArgs::init(argc,argv,"kacltest", 0, 0, 0, 0);
- TDEApplication app;
-
- KACLTest test;
- test.setup();
- test.runAll();
- test.cleanup();
- kdDebug() << "All tests OK." << endl;
- return 0; // success. The exit(1) in check() is what happens in case of failure.
-}
-
-#ifdef Q_OS_FREEBSD
-static const TQString s_group1 = TQString::fromLatin1("staff");
-static const TQString s_group2 = TQString::fromLatin1("guest");
-#else
-static const TQString s_group1 = TQString::fromLatin1("audio");
-static const TQString s_group2 = TQString::fromLatin1("users");
-#endif
-
-static const TQString s_testACL = TQString::fromLatin1( "user::rw-\nuser:bin:rwx\ngroup::rw-\nmask::rwx\nother::r--\n" );
-static const TQString s_testACL2 = TQString::fromLatin1( "user::rwx\nuser:bin:rwx\ngroup::rw-\n") +
- TQString::fromLatin1( "group:" ) + s_group1 + TQString::fromLatin1( ":--x\n" ) +
- TQString::fromLatin1( "group:" ) + s_group2 + TQString::fromLatin1( ":r--\n" ) +
- TQString::fromLatin1( "mask::r-x\nother::r--\n" );
-static const TQString s_testACLEffective = TQString::fromLatin1( "user::rwx\nuser:bin:rwx #effective:r-x\ngroup::rw- #effective:r--\n" ) +
- TQString::fromLatin1( "group:" ) + s_group1 + TQString::fromLatin1( ":--x\n" ) +
- TQString::fromLatin1( "group:" ) + s_group2 + TQString::fromLatin1( ":r--\n" ) +
- TQString::fromLatin1( "mask::r-x\nother::r--\n" );
-
-KACLTest::KACLTest()
-:m_acl( s_testACL )
-{
-}
-
-void KACLTest::setup()
-{
-}
-
-void KACLTest::runAll()
-{
- testAsString();
- testGetOwnerPermissions();
- testGetOwningGroupPermissions();
- testGetOthersPermissions();
-
- testGetMaskPermissions();
- testGetAllUserPermissions();
-
- testIsExtended();
-
- // from here on we operate with the second test string
- testSetACL();
- testGetAllGroupsPermissions();
-
- testOperators();
- testSettingBasic();
- testSettingExtended();
- testSettingErrorHandling();
-
- testNewMask();
-}
-
-void KACLTest::cleanup()
-{
-}
-
-void KACLTest::testAsString()
-{
- check( "asString: ", m_acl.asString(), s_testACL );
-}
-
-void KACLTest::testSetACL()
-{
- m_acl.setACL( s_testACL2 );
- check( "setACL: ", m_acl.asString().simplifyWhiteSpace().remove(" "), s_testACLEffective.simplifyWhiteSpace().remove(" ") );
-}
-
-void KACLTest::testGetOwnerPermissions()
-{
- check( "Owner permissions: ", TQString::number( m_acl.ownerPermissions() ), "6" );
-}
-
-void KACLTest::testGetOwningGroupPermissions()
-{
- check( "Owning group permissions: ", TQString::number( m_acl.owningGroupPermissions() ), "6" );
-}
-
-void KACLTest::testGetOthersPermissions()
-{
- check( "Others permissions: ", TQString::number( m_acl.othersPermissions() ), "4" );
-}
-
-void KACLTest::testGetMaskPermissions()
-{
- bool exists = false;
- unsigned short mask = m_acl.maskPermissions( exists );
- check( "Mask permissions: ", TQString::number( mask ), "7" );
- check( "Mask permissions: ", exists, true );
-}
-
-void KACLTest::testGetAllUserPermissions()
-{
- ACLUserPermissionsList list = m_acl.allUserPermissions();
- ACLUserPermissionsConstIterator it = list.begin();
- TQString name;
- unsigned short permissions;
- int count = 0;
- while ( it != list.end() ) {
- name = ( *it ).first;
- permissions = ( *it ).second;
- ++it;
- ++count;
- }
- check( "All users count: ", TQString::number( count ), "1" );
- check( "All users name: ", name, "bin" );
- check( "All users permissions: ", TQString::number( permissions ), "7" );
-}
-
-void KACLTest::testGetAllGroupsPermissions()
-{
- ACLGroupPermissionsList list = m_acl.allGroupPermissions();
- ACLGroupPermissionsConstIterator it = list.begin();
- TQString name;
- unsigned short permissions;
- int count = 0;
- while ( it != list.end() ) {
- name = ( *it ).first;
- permissions = ( *it ).second;
- // setACL sorts them alphabetically ...
- if ( count == 0 ) {
- check( "All groups name: ", name, s_group1 );
- check( "All groups permissions: ", TQString::number( permissions ), "1" );
- } else if ( count == 1 ) {
- check( "All groups name: ", name, s_group2 );
- check( "All groups permissions: ", TQString::number( permissions ), "4" );
- }
- ++it;
- ++count;
- }
- check( "All users count: ", TQString::number( count ), "2" );
-}
-
-void KACLTest::testIsExtended()
-{
- KACL dukeOfMonmoth( s_testACL );
- check( "isExtended on an extended one: ", dukeOfMonmoth.isExtended(), true );
- KACL earlOfUpnor( "user::r--\ngroup::r--\nother::r--\n" );
- check( "isExtended on a not extended one: ", earlOfUpnor.isExtended(), false );
-}
-
-void KACLTest::testOperators()
-{
- KACL dukeOfMonmoth( s_testACL );
- KACL JamesScott( s_testACL );
- KACL earlOfUpnor( s_testACL2 );
- check( "operator== on different ones: ", dukeOfMonmoth == earlOfUpnor, false );
- check( "operator== on identical ones: ", dukeOfMonmoth == JamesScott, true );
- check( "operator!= on diffenrent ones: ", dukeOfMonmoth != earlOfUpnor, true );
- check( "operator!=: on identical ones: ", dukeOfMonmoth != JamesScott, false );
-}
-
-void KACLTest::testSettingBasic()
-{
- KACL CharlesII( s_testACL );
- CharlesII.setOwnerPermissions( 7 ); // clearly
- CharlesII.setOwningGroupPermissions( 0 );
- CharlesII.setOthersPermissions( 0 );
- check( "setOwnerPermissions: ", TQString::number( CharlesII.ownerPermissions() ),"7" );
- check( "setOwningGroupPermissions: ", TQString::number( CharlesII.owningGroupPermissions() ),"0" );
- check( "setOthersPermissions: ", TQString::number( CharlesII.othersPermissions() ),"0" );
-}
-
-void KACLTest::testSettingExtended()
-{
- KACL CharlesII( s_testACL );
- CharlesII.setMaskPermissions( 7 ); // clearly
- bool dummy = false;
- check( "setMaskPermissions: ", TQString::number( CharlesII.maskPermissions( dummy ) ),"7" );
-
- const TQString expected( "user::rw-\nuser:root:rwx\nuser:bin:r--\ngroup::rw-\nmask::rwx\nother::r--\n" );
-
- ACLUserPermissionsList users;
- ACLUserPermissions user = qMakePair( TQString( "root" ), ( unsigned short )7 );
- users.append( user );
- user = qMakePair( TQString( "bin" ), ( unsigned short )4 );
- users.append( user );
- CharlesII.setAllUserPermissions( users );
- check( "setAllUserPermissions: ", CharlesII.asString(), expected );
-
- CharlesII.setACL( s_testACL ); // reset
- // it already has an entry for bin, let's change it
- CharlesII.setNamedUserPermissions( TQString("bin"), 4 );
- CharlesII.setNamedUserPermissions( TQString( "root" ), 7 );
- check( "setNamedUserPermissions: ", CharlesII.asString(), expected );
-
- // groups, all and named
-
- const TQString expected2 = TQString::fromLatin1( "user::rw-\nuser:bin:rwx\ngroup::rw-\ngroup:" ) + s_group1 +
- TQString::fromLatin1( ":-wx\ngroup:" ) + s_group2 + TQString::fromLatin1(":r--\nmask::rwx\nother::r--\n" );
- CharlesII.setACL( s_testACL ); // reset
- ACLGroupPermissionsList groups;
- ACLGroupPermissions group = qMakePair( s_group1, ( unsigned short )3 );
- groups.append( group );
- group = qMakePair( s_group2, ( unsigned short )4 );
- groups.append( group );
- CharlesII.setAllGroupPermissions( groups );
- check( "setAllGroupPermissions: ", CharlesII.asString(), expected2 );
-
- CharlesII.setACL( s_testACL ); // reset
- CharlesII.setNamedGroupPermissions( s_group1, 3 );
- CharlesII.setNamedGroupPermissions( s_group2, 4 );
- check( "setNamedGroupPermissions: ", CharlesII.asString(), expected2 );
-}
-
-void KACLTest::testSettingErrorHandling()
-{
- KACL foo( s_testACL );
- bool v = foo.setNamedGroupPermissions( s_group1, 7 ); // existing group
- check( "Existing group: ", v, true );
- v = foo.setNamedGroupPermissions( "jongel", 7 ); // non-existing group
- check( "Non-existing group: ", v, false );
-
- v = foo.setNamedUserPermissions( "bin", 7 ); // existing user
- check( "Existing user: ", v, true );
- v = foo.setNamedUserPermissions( "jongel", 7 ); // non-existing user
- check( "Non-existing user: ", v, false );
-}
-
-void KACLTest::testNewMask()
-{
- KACL CharlesII( "user::rw-\ngroup::rw-\nother::rw\n" );
- bool dummy = false;
- CharlesII.maskPermissions( dummy );
- check( "mask exists: ", dummy, false );
-
- CharlesII.setMaskPermissions( 6 );
- check( "new mask set: ", TQString::number( CharlesII.maskPermissions( dummy ) ), "6" );
- check( "mask exists now: ", dummy, true );
-}
diff --git a/kio/tests/kdefaultprogresstest.cpp b/kio/tests/kdefaultprogresstest.cpp
deleted file mode 100644
index 79ad44e3c..000000000
--- a/kio/tests/kdefaultprogresstest.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-#include <kapplication.h>
-#include <kio/defaultprogress.h>
-#include <kurl.h>
-#include <kdebug.h>
-
-using namespace TDEIO;
-
-int main(int argc, char **argv)
-{
- TDEApplication app(argc, argv, "kdefaultprogresstest");
-
- DefaultProgress* dlg = new DefaultProgress();
- KURL src("http://this.host.doesn't.exist/this/dir/neither/andthisfileneither");
- KURL dest("file:/tmp/dest");
- dlg->slotCopying( 0L, src, dest );
- dlg->slotTotalSize( 0L, 12000 );
- dlg->slotTotalFiles( 0L, 12 );
- dlg->slotTotalDirs( 0L, 1 );
-
- dlg->slotSpeed( 0L, 55 );
- dlg->slotInfoMessage( 0L, TQString::fromLatin1( "Starting..." ) );
-
- int files = 0;
- for ( int size = 0 ; size < 12000 ; size += 1 )
- {
- dlg->slotProcessedSize( 0L, size );
- dlg->slotPercent( 0L, 100 * size / 12000 );
- if ( size % 1000 == 0 )
- {
- dlg->slotProcessedFiles( 0L, ++files );
- }
- kapp->processEvents();
- }
- dlg->slotInfoMessage( 0L, TQString::fromLatin1( "Done." ) );
-
- delete dlg;
- return 0;
-}
-
diff --git a/kio/tests/kdirlistertest.h b/kio/tests/kdirlistertest.h
deleted file mode 100644
index 065f7478d..000000000
--- a/kio/tests/kdirlistertest.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/* This file is part of the KDE desktop environment
-
- Copyright (C) 2001, 2002 Michael Brade <brade@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KDIRLISTERTEST_H_
-#define _KDIRLISTERTEST_H_
-
-#include <tqwidget.h>
-#include <tqstring.h>
-
-#include <kurl.h>
-#include <kfileitem.h>
-
-#include <iostream>
-
-using namespace std;
-
-class PrintSignals : public TQObject
-{
- Q_OBJECT
-public:
- PrintSignals() : TQObject() { }
-
-public slots:
- void started( const KURL &url )
- {
- cout << "*** started( " << url.url().local8Bit() << " )" << endl;
- }
- void canceled() { cout << "canceled()" << endl; }
- void canceled( const KURL& url )
- {
- cout << "*** canceled( " << url.prettyURL().local8Bit() << " )" << endl;
- }
- void completed() { cout << "*** completed()" << endl; }
- void completed( const KURL& url )
- {
- cout << "*** completed( " << url.prettyURL().local8Bit() << " )" << endl;
- }
- void redirection( const KURL& url )
- {
- cout << "*** redirection( " << url.prettyURL().local8Bit() << " )" << endl;
- }
- void redirection( const KURL& src, const KURL& dest )
- {
- cout << "*** redirection( " << src.prettyURL().local8Bit() << ", "
- << dest.prettyURL().local8Bit() << " )" << endl;
- }
- void clear() { cout << "*** clear()" << endl; }
- void newItems( const KFileItemList& items )
- {
- cout << "*** newItems: " << endl;
- for ( KFileItemListIterator it( items ) ; it.current() ; ++it )
- cout << it.current() << " " << it.current()->name().local8Bit() << endl;
- }
- void deleteItem( KFileItem* item )
- {
- cout << "*** deleteItem: " << item->url().prettyURL().local8Bit() << endl;
- }
- void itemsFilteredByMime( const KFileItemList& )
- {
- cout << "*** itemsFilteredByMime: " << endl;
- // TODO
- }
- void refreshItems( const KFileItemList& )
- {
- cout << "*** refreshItems: " << endl;
- // TODO
- }
- void infoMessage( const TQString& msg )
- { cout << "*** infoMessage: " << msg.local8Bit() << endl; }
-
- void percent( int percent )
- { cout << "*** percent: " << percent << endl; }
-
- void totalSize( TDEIO::filesize_t size )
- { cout << "*** totalSize: " << (long)size << endl; }
-
- void processedSize( TDEIO::filesize_t size )
- { cout << "*** processedSize: " << (long)size << endl; }
-
- void speed( int bytes_per_second )
- { cout << "*** speed: " << bytes_per_second << endl; }
-};
-
-class KDirListerTest : public TQWidget
-{
- Q_OBJECT
-public:
- KDirListerTest( TQWidget *parent=0, const char *name=0 );
- ~KDirListerTest();
-
-public slots:
- void startRoot();
- void startHome();
- void startTar();
- void test();
- void completed();
-
-private:
- KDirLister *lister;
- PrintSignals *debug;
-};
-
-#endif
diff --git a/kio/tests/kioslavetest.cpp b/kio/tests/kioslavetest.cpp
deleted file mode 100644
index 27a99eabc..000000000
--- a/kio/tests/kioslavetest.cpp
+++ /dev/null
@@ -1,555 +0,0 @@
- /*
- This file is or will be part of KDE desktop environment
-
- Copyright 1999 Matt Koss <koss@miesto.sk>
-
- It is licensed under GPL version 2.
-
- If it is part of KDE libraries than this file is licensed under
- LGPL version 2.
- */
-
-#include <tqlayout.h>
-#include <tqmessagebox.h>
-#include <tqdir.h>
-
-#include <kacl.h>
-#include <kapplication.h>
-#include <kcmdlineargs.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kurl.h>
-#include <kstatusbar.h>
-#include <kio/job.h>
-#include <kio/scheduler.h>
-#include <kprotocolinfo.h>
-
-#include "kioslavetest.h"
-
-using namespace TDEIO;
-
-KioslaveTest::KioslaveTest( TQString src, TQString dest, uint op, uint pr )
- : KMainWindow(0, "")
-{
-
- job = 0L;
-
- main_widget = new TQWidget( this, "");
- TQBoxLayout *topLayout = new TQVBoxLayout( main_widget, 10, 5 );
-
- TQGridLayout *grid = new TQGridLayout( 2, 2, 10 );
- topLayout->addLayout( grid );
-
- grid->setRowStretch(0,1);
- grid->setRowStretch(1,1);
-
- grid->setColStretch(0,1);
- grid->setColStretch(1,100);
-
- lb_from = new TQLabel( "From:", main_widget );
- grid->addWidget( lb_from, 0, 0 );
-
- le_source = new TQLineEdit( main_widget );
- grid->addWidget( le_source, 0, 1 );
- le_source->setText( src );
-
- lb_to = new TQLabel( "To:", main_widget );
- grid->addWidget( lb_to, 1, 0 );
-
- le_dest = new TQLineEdit( main_widget );
- grid->addWidget( le_dest, 1, 1 );
- le_dest->setText( dest );
-
- // Operation groupbox & buttons
- opButtons = new TQButtonGroup( "Operation", main_widget );
- topLayout->addWidget( opButtons, 10 );
- connect( opButtons, TQT_SIGNAL(clicked(int)), TQT_SLOT(changeOperation(int)) );
-
- TQBoxLayout *hbLayout = new TQHBoxLayout( opButtons, 15 );
-
- rbList = new TQRadioButton( "List", opButtons );
- opButtons->insert( rbList, List );
- hbLayout->addWidget( rbList, 5 );
-
- rbListRecursive = new TQRadioButton( "ListRecursive", opButtons );
- opButtons->insert( rbListRecursive, ListRecursive );
- hbLayout->addWidget( rbListRecursive, 5 );
-
- rbStat = new TQRadioButton( "Stat", opButtons );
- opButtons->insert( rbStat, Stat );
- hbLayout->addWidget( rbStat, 5 );
-
- rbGet = new TQRadioButton( "Get", opButtons );
- opButtons->insert( rbGet, Get );
- hbLayout->addWidget( rbGet, 5 );
-
- rbPut = new TQRadioButton( "Put", opButtons );
- opButtons->insert( rbPut, Put );
- hbLayout->addWidget( rbPut, 5 );
-
- rbCopy = new TQRadioButton( "Copy", opButtons );
- opButtons->insert( rbCopy, Copy );
- hbLayout->addWidget( rbCopy, 5 );
-
- rbMove = new TQRadioButton( "Move", opButtons );
- opButtons->insert( rbMove, Move );
- hbLayout->addWidget( rbMove, 5 );
-
- rbDelete = new TQRadioButton( "Delete", opButtons );
- opButtons->insert( rbDelete, Delete );
- hbLayout->addWidget( rbDelete, 5 );
-
- rbShred = new TQRadioButton( "Shred", opButtons );
- opButtons->insert( rbShred, Shred );
- hbLayout->addWidget( rbShred, 5 );
-
- rbMkdir = new TQRadioButton( "Mkdir", opButtons );
- opButtons->insert( rbMkdir, Mkdir );
- hbLayout->addWidget( rbMkdir, 5 );
-
- rbMimetype = new TQRadioButton( "Mimetype", opButtons );
- opButtons->insert( rbMimetype, Mimetype );
- hbLayout->addWidget( rbMimetype, 5 );
-
- opButtons->setButton( op );
- changeOperation( op );
-
- // Progress groupbox & buttons
- progressButtons = new TQButtonGroup( "Progress dialog mode", main_widget );
- topLayout->addWidget( progressButtons, 10 );
- connect( progressButtons, TQT_SIGNAL(clicked(int)), TQT_SLOT(changeProgressMode(int)) );
-
- hbLayout = new TQHBoxLayout( progressButtons, 15 );
-
- rbProgressNone = new TQRadioButton( "None", progressButtons );
- progressButtons->insert( rbProgressNone, ProgressNone );
- hbLayout->addWidget( rbProgressNone, 5 );
-
- rbProgressDefault = new TQRadioButton( "Default", progressButtons );
- progressButtons->insert( rbProgressDefault, ProgressDefault );
- hbLayout->addWidget( rbProgressDefault, 5 );
-
- rbProgressStatus = new TQRadioButton( "Status", progressButtons );
- progressButtons->insert( rbProgressStatus, ProgressStatus );
- hbLayout->addWidget( rbProgressStatus, 5 );
-
- progressButtons->setButton( pr );
- changeProgressMode( pr );
-
- // statusbar progress widget
- statusProgress = new StatusbarProgress( statusBar() );
- statusBar()->addWidget( statusProgress, 0, true );
-
- // run & stop butons
- hbLayout = new TQHBoxLayout( topLayout, 15 );
-
- pbStart = new TQPushButton( "&Start", main_widget );
- pbStart->setFixedSize( pbStart->sizeHint() );
- connect( pbStart, TQT_SIGNAL(clicked()), TQT_SLOT(startJob()) );
- hbLayout->addWidget( pbStart, 5 );
-
- pbStop = new TQPushButton( "Sto&p", main_widget );
- pbStop->setFixedSize( pbStop->sizeHint() );
- pbStop->setEnabled( false );
- connect( pbStop, TQT_SIGNAL(clicked()), TQT_SLOT(stopJob()) );
- hbLayout->addWidget( pbStop, 5 );
-
- // close button
- close = new TQPushButton( "&Close", main_widget );
- close->setFixedSize( close->sizeHint() );
- connect(close, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotQuit()));
-
- topLayout->addWidget( close, 5 );
-
- main_widget->setMinimumSize( main_widget->sizeHint() );
- setCentralWidget( main_widget );
-
- slave = 0;
-// slave = TDEIO::Scheduler::getConnectedSlave(KURL("ftp://ftp.kde.org"));
- TDEIO::Scheduler::connect(TQT_SIGNAL(slaveConnected(TDEIO::Slave*)),
- this, TQT_SLOT(slotSlaveConnected()));
- TDEIO::Scheduler::connect(TQT_SIGNAL(slaveError(TDEIO::Slave*,int,const TQString&)),
- this, TQT_SLOT(slotSlaveError()));
-}
-
-
-void KioslaveTest::closeEvent( TQCloseEvent * ){
- slotQuit();
-}
-
-
-void KioslaveTest::slotQuit(){
- if ( job ) {
- job->kill( true ); // kill the job quietly
- }
- if (slave)
- TDEIO::Scheduler::disconnectSlave(slave);
- kapp->quit();
-}
-
-
-void KioslaveTest::changeOperation( int id ) {
- // only two urls for copy and move
- bool enab = rbCopy->isChecked() || rbMove->isChecked();
-
- le_dest->setEnabled( enab );
-
- selectedOperation = id;
-}
-
-
-void KioslaveTest::changeProgressMode( int id ) {
- progressMode = id;
-
- if ( progressMode == ProgressStatus ) {
- statusBar()->show();
- } else {
- statusBar()->hide();
- }
-}
-
-
-void KioslaveTest::startJob() {
- TQString sCurrent = TQDir::currentDirPath()+"/";
- KURL::encode_string(sCurrent);
- TQString sSrc( le_source->text() );
- KURL src( sCurrent, sSrc );
-
- if ( !src.isValid() ) {
- TQMessageBox::critical(this, "Kioslave Error Message", "Source URL is malformed" );
- return;
- }
-
- TQString sDest( le_dest->text() );
- KURL dest( sCurrent, sDest );
-
- if ( !dest.isValid() &&
- ( selectedOperation == Copy || selectedOperation == Move ) ) {
- TQMessageBox::critical(this, "Kioslave Error Message",
- "Destination URL is malformed" );
- return;
- }
-
- pbStart->setEnabled( false );
-
- bool observe = true;
- if (progressMode != ProgressDefault) {
- observe = false;
- }
-
- SimpleJob *myJob = 0;
-
- switch ( selectedOperation ) {
- case List:
- myJob = TDEIO::listDir( src );
- connect(myJob, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
- TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList&)));
- break;
-
- case ListRecursive:
- myJob = TDEIO::listRecursive( src );
- connect(myJob, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
- TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList&)));
- break;
-
- case Stat:
- myJob = TDEIO::stat( src, false, 2 );
- break;
-
- case Get:
- myJob = TDEIO::get( src, true );
- connect(myJob, TQT_SIGNAL( data( TDEIO::Job*, const TQByteArray &)),
- TQT_SLOT( slotData( TDEIO::Job*, const TQByteArray &)));
- break;
-
- case Put:
- putBuffer = 0;
- myJob = TDEIO::put( src, -1, true, false);
- connect(myJob, TQT_SIGNAL( dataReq( TDEIO::Job*, TQByteArray &)),
- TQT_SLOT( slotDataReq( TDEIO::Job*, TQByteArray &)));
- break;
-
- case Copy:
- job = TDEIO::copy( src, dest, observe );
- break;
-
- case Move:
- job = TDEIO::move( src, dest, observe );
- break;
-
- case Delete:
- job = TDEIO::del( src, false, observe );
- break;
-
- case Shred:
- job = TDEIO::del(src, true, observe);
- break;
-
- case Mkdir:
- myJob = TDEIO::mkdir( src );
- break;
-
- case Mimetype:
- myJob = TDEIO::mimetype( src );
- break;
- }
- if (myJob)
- {
- if (slave)
- TDEIO::Scheduler::assignJobToSlave(slave, myJob);
- job = myJob;
- }
-
- connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
- TQT_SLOT( slotResult( TDEIO::Job * ) ) );
-
- connect( job, TQT_SIGNAL( canceled( TDEIO::Job * ) ),
- TQT_SLOT( slotResult( TDEIO::Job * ) ) );
-
- if (progressMode == ProgressStatus) {
- statusProgress->setJob( job );
- }
-
- pbStop->setEnabled( true );
-}
-
-
-void KioslaveTest::slotResult( TDEIO::Job * _job )
-{
- if ( _job->error() )
- {
- _job->showErrorDialog();
- }
- else if ( selectedOperation == Stat )
- {
- UDSEntry entry = ((TDEIO::StatJob*)_job)->statResult();
- printUDSEntry( entry );
- }
- else if ( selectedOperation == Mimetype )
- {
- kdDebug() << "mimetype is " << ((TDEIO::MimetypeJob*)_job)->mimetype() << endl;
- }
-
- if (job == _job)
- job = 0L;
- pbStart->setEnabled( true );
- pbStop->setEnabled( false );
-}
-
-void KioslaveTest::slotSlaveConnected()
-{
- kdDebug() << "Slave connected." << endl;
-}
-
-void KioslaveTest::slotSlaveError()
-{
- kdDebug() << "Error connected." << endl;
- slave = 0;
-}
-
-static void printACL( const TQString& acl )
-{
- KACL kacl( acl );
- kdDebug() << "According to KACL: " << endl << kacl.asString() << endl;
- kdDebug() << "Owner: " << kacl.ownerPermissions() << endl;
- kdDebug() << "Owning group: " << kacl.owningGroupPermissions() << endl;
- kdDebug() << "Others: " << kacl.othersPermissions() << endl;
-}
-
-
-void KioslaveTest::printUDSEntry( const TDEIO::UDSEntry & entry )
-{
- TDEIO::UDSEntry::ConstIterator it = entry.begin();
- for( ; it != entry.end(); it++ ) {
- switch ((*it).m_uds) {
- case TDEIO::UDS_FILE_TYPE:
- kdDebug() << "File Type : " << (mode_t)((*it).m_long) << endl;
- if ( S_ISDIR( (mode_t)((*it).m_long) ) )
- {
- kdDebug() << "is a dir" << endl;
- }
- break;
- case TDEIO::UDS_ACCESS:
- kdDebug() << "Access permissions : " << (*it).m_long << endl;
- break;
- case TDEIO::UDS_EXTENDED_ACL:
- if( (*it).m_long == 1 )
- kdDebug() << "Has extended ACL information." << endl;
- break;
- case TDEIO::UDS_ACL_STRING:
- kdDebug() << "ACL: " << ( (*it).m_str.ascii() ) << endl;
- printACL( (*it).m_str );
- break;
- case TDEIO::UDS_DEFAULT_ACL_STRING:
- kdDebug() << "Default ACL: " << ( (*it).m_str.ascii() ) << endl;
- printACL( (*it).m_str );
- break;
- case TDEIO::UDS_USER:
- kdDebug() << "User : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_GROUP:
- kdDebug() << "Group : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_NAME:
- kdDebug() << "Name : " << ((*it).m_str.ascii() ) << endl;
- //m_strText = decodeFileName( (*it).m_str );
- break;
- case TDEIO::UDS_URL:
- kdDebug() << "URL : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_MIME_TYPE:
- kdDebug() << "MimeType : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_LINK_DEST:
- kdDebug() << "LinkDest : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_SIZE:
- kdDebug() << "Size: " << TDEIO::convertSize((*it).m_long) << endl;
- break;
- }
- }
-}
-
-void KioslaveTest::slotEntries(TDEIO::Job* job, const TDEIO::UDSEntryList& list) {
-
- KURL url = static_cast<TDEIO::ListJob*>( job )->url();
- KProtocolInfo::ExtraFieldList extraFields = KProtocolInfo::extraFields(url);
- UDSEntryListConstIterator it=list.begin();
- for (; it != list.end(); ++it) {
- // For each file...
- KProtocolInfo::ExtraFieldList::Iterator extraFieldsIt = extraFields.begin();
- UDSEntry::ConstIterator it2 = (*it).begin();
- for( ; it2 != (*it).end(); it2++ ) {
- if ((*it2).m_uds == UDS_NAME)
- kdDebug() << "" << ( *it2 ).m_str << endl;
- else if ( (*it2).m_uds == UDS_EXTRA) {
- Q_ASSERT( extraFieldsIt != extraFields.end() );
- TQString column = (*extraFieldsIt).name;
- //TQString type = (*extraFieldsIt).type;
- kdDebug() << " Extra data (" << column << ") :" << ( *it2 ).m_str << endl;
- ++extraFieldsIt;
- }
- }
- }
-}
-
-void KioslaveTest::slotData(TDEIO::Job*, const TQByteArray &data)
-{
- if (data.size() == 0)
- {
- kdDebug(0) << "Data: <End>" << endl;
- }
- else
- {
- kdDebug(0) << "Data: \"" << TQCString(data, data.size()+1) << "\"" << endl;
- }
-}
-
-void KioslaveTest::slotDataReq(TDEIO::Job*, TQByteArray &data)
-{
- const char *fileDataArray[] =
- {
- "Hello world\n",
- "This is a test file\n",
- "You can safely delete it.\n",
- "BIG\n",
- 0
- };
- const char *fileData = fileDataArray[putBuffer++];
-
- if (!fileData)
- {
- kdDebug(0) << "DataReq: <End>" << endl;
- return;
- }
- if (!strcmp(fileData, "BIG\n"))
- data.fill(0, 29*1024*1024);
- else
- data.duplicate(fileData, strlen(fileData));
- kdDebug(0) << "DataReq: \"" << fileData << "\"" << endl;
-}
-
-void KioslaveTest::stopJob() {
- kdDebug() << "KioslaveTest::stopJob()" << endl;
- job->kill();
- job = 0L;
-
- pbStop->setEnabled( false );
- pbStart->setEnabled( true );
-}
-
-static const char version[] = "v0.0.0 0000"; // :-)
-static const char description[] = "Test for kioslaves";
-static KCmdLineOptions options[] =
-{
- { "s", 0, 0 },
- { "src <src>", "Source URL", "" },
- { "d", 0, 0 },
- { "dest <dest>", "Destination URL", "" },
- { "o", 0, 0 },
- { "operation <operation>", "Operation (list,listrecursive,stat,get,put,copy,move,del,shred,mkdir)", "copy" },
- { "p", 0, 0 },
- { "progress <progress>", "Progress Type (none,default,status)", "default" },
- KCmdLineLastOption
-};
-
-int main(int argc, char **argv) {
- TDECmdLineArgs::init( argc, argv, "kioslavetest", description, version );
- TDECmdLineArgs::addCmdLineOptions( options );
- TDEApplication app;
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- TQString src = args->getOption("src");
- TQString dest = args->getOption("dest");
-
- uint op = 0;
- uint pr = 0;
-
- TQString tmps;
-
- tmps = args->getOption("operation");
- if ( tmps == "list") {
- op = KioslaveTest::List;
- } else if ( tmps == "listrecursive") {
- op = KioslaveTest::ListRecursive;
- } else if ( tmps == "stat") {
- op = KioslaveTest::Stat;
- } else if ( tmps == "get") {
- op = KioslaveTest::Get;
- } else if ( tmps == "put") {
- op = KioslaveTest::Put;
- } else if ( tmps == "copy") {
- op = KioslaveTest::Copy;
- } else if ( tmps == "move") {
- op = KioslaveTest::Move;
- } else if ( tmps == "del") {
- op = KioslaveTest::Delete;
- } else if ( tmps == "shred") {
- op = KioslaveTest::Shred;
- } else if ( tmps == "mkdir") {
- op = KioslaveTest::Mkdir;
- } else TDECmdLineArgs::usage("unknown operation");
-
- tmps = args->getOption("progress");
- if ( tmps == "none") {
- pr = KioslaveTest::ProgressNone;
- } else if ( tmps == "default") {
- pr = KioslaveTest::ProgressDefault;
- } else if ( tmps == "status") {
- pr = KioslaveTest::ProgressStatus;
- } else TDECmdLineArgs::usage("unknown progress mode");
-
- args->clear(); // Free up memory
-
- KioslaveTest test( src, dest, op, pr );
- test.show();
- // Bug in KTMW / Qt / layouts ?
- test.resize( test.sizeHint() );
-
- app.setMainWidget(&test);
- app.exec();
-}
-
-
-#include "kioslavetest.moc"
diff --git a/kio/tests/kioslavetest.h b/kio/tests/kioslavetest.h
deleted file mode 100644
index 79533bbc5..000000000
--- a/kio/tests/kioslavetest.h
+++ /dev/null
@@ -1,108 +0,0 @@
- /*
- This file is or will be part of KDE desktop environment
-
- Copyright 1999 Matt Koss <koss@miesto.sk>
-
- It is licensed under GPL version 2.
-
- If it is part of KDE libraries than this file is licensed under
- LGPL version 2.
- */
-
-#ifndef _KIOSLAVETEST_H
-#define _KIOSLAVETEST_H
-
-#include <tqlabel.h>
-#include <tqlineedit.h>
-#include <tqradiobutton.h>
-#include <tqpushbutton.h>
-#include <tqbuttongroup.h>
-#include <tqwidget.h>
-
-#include <kmainwindow.h>
-
-#include "kio/job.h"
-#include "kio/global.h"
-#include "kio/statusbarprogress.h"
-#include "kio/slave.h"
-
-class KioslaveTest : public KMainWindow {
- Q_OBJECT
-
-public:
- KioslaveTest( TQString src, TQString dest, uint op, uint pr );
- ~KioslaveTest() {}
-
- enum Operations { List, ListRecursive, Stat, Get, Put, Copy, Move, Delete, Shred, Mkdir, Mimetype };
-
- enum ProgressModes { ProgressNone, ProgressDefault, ProgressStatus };
-
-protected:
-
- void closeEvent( TQCloseEvent * );
-
- void printUDSEntry( const TDEIO::UDSEntry & entry );
-
- // info stuff
- TQLabel *lb_from;
- TQLineEdit *le_source;
-
- TQLabel *lb_to;
- TQLineEdit *le_dest;
-
- // operation stuff
- TQButtonGroup *opButtons;
-
- TQRadioButton *rbList;
- TQRadioButton *rbListRecursive;
- TQRadioButton *rbStat;
- TQRadioButton *rbGet;
- TQRadioButton *rbPut;
- TQRadioButton *rbCopy;
- TQRadioButton *rbMove;
- TQRadioButton *rbDelete;
- TQRadioButton *rbShred;
- TQRadioButton *rbMkdir;
- TQRadioButton *rbMimetype;
-
- // progress stuff
- TQButtonGroup *progressButtons;
-
- TQRadioButton *rbProgressNone;
- TQRadioButton *rbProgressDefault;
- TQRadioButton *rbProgressStatus;
-
- TQPushButton *pbStart;
- TQPushButton *pbStop;
-
- TQPushButton *close;
-
-protected slots:
- void changeOperation( int id );
- void changeProgressMode( int id );
-
- void startJob();
- void stopJob();
-
- void slotResult( TDEIO::Job * );
- void slotEntries( TDEIO::Job *, const TDEIO::UDSEntryList& );
- void slotData( TDEIO::Job *, const TQByteArray &data );
- void slotDataReq( TDEIO::Job *, TQByteArray &data );
-
- void slotQuit();
- void slotSlaveConnected();
- void slotSlaveError();
-
-private:
- TDEIO::Job *job;
- TQWidget *main_widget;
-
- TDEIO::StatusbarProgress *statusProgress;
-
- int selectedOperation;
- int progressMode;
- int putBuffer;
- TDEIO::Slave *slave;
-};
-
-#endif // _KIOSLAVETEST_H
diff --git a/kio/tests/kmfitest.cpp b/kio/tests/kmfitest.cpp
deleted file mode 100644
index 40530184d..000000000
--- a/kio/tests/kmfitest.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-#include <stdio.h>
-#include <tqdir.h>
-#include <tqfile.h>
-#include <kinstance.h>
-#include <kurl.h>
-#include <kfilemetainfo.h>
-#include <kmimetype.h>
-
-int main (int argc, char **argv)
-{
- TDEInstance ins("kmfitest");
-
- if (argc < 2) {
- printf("usage: %s <file>\n", argv[0]);
- return 1;
- }
-
- for (int i = 1; i < argc; i++) {
- TQString file = TQFile::decodeName(argv[i]);
- tqWarning("File: %s", file.local8Bit().data());
- KMimeType::Ptr p;
- p = KMimeType::findByPath(file);
- tqWarning("Mime type (findByPath): %s", p->name().latin1());
- KFileMetaInfo meta(file, TQString::null, KFileMetaInfo::TechnicalInfo | KFileMetaInfo::ContentInfo);
- }
-
- return 0;
-}
diff --git a/kio/tests/ktradertest.cpp b/kio/tests/ktradertest.cpp
deleted file mode 100644
index b05444dfd..000000000
--- a/kio/tests/ktradertest.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2002, 2003 David Faure <faure@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include <kcmdlineargs.h>
-#include <ktrader.h>
-#include <kmimetype.h>
-#include <kapplication.h>
-#include <stdio.h>
-
-static KCmdLineOptions options[] =
-{
- { "+query", "the query", 0 },
- { "+[genericServiceType]", "Application (default), or KParts/ReadOnlyPart", 0 },
- { "+[constraint]", "constraint", 0 },
- { "+[preference]", "preference", 0 },
- KCmdLineLastOption
-};
-
-int main( int argc, char **argv )
-{
- TDECmdLineArgs::init( argc, argv, "ktradertest", "KTradertest", "A KTrader testing tool", "0.0" );
-
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDEApplication app( false, false ); // no GUI
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- if ( args->count() < 1 )
- TDECmdLineArgs::usage();
-
- TQString query = TQString::fromLocal8Bit( args->arg( 0 ) );
-
- TQString genericServiceType, constraint, preference;
-
- if ( args->count() >= 2 )
- genericServiceType = TQString::fromLocal8Bit( args->arg( 1 ) );
-
- if ( args->count() >= 3 )
- constraint = TQString::fromLocal8Bit( args->arg( 2 ) );
-
- if ( args->count() == 4 )
- preference = TQString::fromLocal8Bit( args->arg( 3 ) );
-
- printf( "query is : %s\n", query.local8Bit().data() );
- printf( "genericServiceType is : %s\n", genericServiceType.local8Bit().data() );
- printf( "constraint is : %s\n", constraint.local8Bit().data() );
- printf( "preference is : %s\n", preference.local8Bit().data() );
-
- KTrader::OfferList offers = KTrader::self()->query( query, genericServiceType, constraint, preference );
-
- printf("got %d offers.\n", offers.count());
-
- int i = 0;
- KTrader::OfferList::ConstIterator it = offers.begin();
- KTrader::OfferList::ConstIterator end = offers.end();
- for (; it != end; ++it, ++i )
- {
- printf("---- Offer %d ----\n", i);
- TQStringList props = (*it)->propertyNames();
- TQStringList::ConstIterator propIt = props.begin();
- TQStringList::ConstIterator propEnd = props.end();
- for (; propIt != propEnd; ++propIt )
- {
- TQVariant prop = (*it)->property( *propIt );
-
- if ( !prop.isValid() )
- {
- printf("Invalid property %s\n", (*propIt).local8Bit().data());
- continue;
- }
-
- TQString outp = *propIt;
- outp += " : '";
-
- switch ( prop.type() )
- {
- case TQVariant::StringList:
- outp += prop.toStringList().join(" - ");
- break;
- case TQVariant::Bool:
- outp += prop.toBool() ? "TRUE" : "FALSE";
- break;
- default:
- outp += prop.toString();
- break;
- }
-
- if ( !outp.isEmpty() )
- printf("%s'\n", outp.local8Bit().data());
- }
- }
-}
diff --git a/kio/tests/kurifiltertest.cpp b/kio/tests/kurifiltertest.cpp
deleted file mode 100644
index 820f97403..000000000
--- a/kio/tests/kurifiltertest.cpp
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Copyright (C) 2002, 2003 David Faure <faure@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "kurifilter.h"
-
-#include <config.h>
-#include <iostream>
-#include <stdlib.h>
-
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kcmdlineargs.h>
-#include <kstandarddirs.h>
-#include <ksimpleconfig.h>
-
-#include <tqdir.h>
-#include <tqregexp.h>
-#include <kio/netaccess.h>
-
-static const char * const s_uritypes[] = { "NET_PROTOCOL", "LOCAL_FILE", "LOCAL_DIR", "EXECUTABLE", "HELP", "SHELL", "BLOCKED", "ERROR", "UNKNOWN" };
-#define NO_FILTERING -2
-
-void filter( const char* u, const char * expectedResult = 0, int expectedUriType = -1, TQStringList list = TQStringList(), const char * abs_path = 0, bool checkForExecutables = true )
-{
- TQString a = TQString::fromUtf8( u );
- KURIFilterData * m_filterData = new KURIFilterData;
- m_filterData->setData( a );
- m_filterData->setCheckForExecutables( checkForExecutables );
-
- if( abs_path )
- {
- m_filterData->setAbsolutePath( TQString::fromLatin1( abs_path ) );
- kdDebug() << "Filtering: " << a << " with abs_path=" << abs_path << endl;
- }
- else
- kdDebug() << "Filtering: " << a << endl;
-
- if (KURIFilter::self()->filterURI(*m_filterData, list))
- {
- // Copied from minicli...
- TQString cmd;
- KURL uri = m_filterData->uri();
-
- if ( uri.isLocalFile() && !uri.hasRef() && uri.query().isEmpty() )
- cmd = uri.path();
- else
- cmd = uri.url();
-
- switch( m_filterData->uriType() )
- {
- case KURIFilterData::LOCAL_FILE:
- case KURIFilterData::LOCAL_DIR:
- case KURIFilterData::HELP:
- kdDebug() << "*** Result: Local Resource => '"
- << m_filterData->uri().url() << "'" << endl;
- break;
- case KURIFilterData::NET_PROTOCOL:
- kdDebug() << "*** Result: Network Resource => '"
- << m_filterData->uri().url() << "'" << endl;
- break;
- case KURIFilterData::SHELL:
- case KURIFilterData::EXECUTABLE:
- if( m_filterData->hasArgsAndOptions() )
- cmd += m_filterData->argsAndOptions();
- kdDebug() << "*** Result: Executable/Shell => '" << cmd << "'"<< endl;
- break;
- case KURIFilterData::ERROR:
- kdDebug() << "*** Result: Encountered error. See reason below." << endl;
- break;
- default:
- kdDebug() << "*** Result: Unknown or invalid resource." << endl;
- }
-
- if ( expectedUriType != -1 && expectedUriType != m_filterData->uriType() )
- {
- kdError() << " Got URI type " << s_uritypes[m_filterData->uriType()]
- << " expected " << s_uritypes[expectedUriType] << endl;
- ::exit(1);
- }
-
- if ( expectedResult )
- {
- // Hack for other locales than english, normalize google hosts to google.com
- cmd = cmd.replace( TQRegExp( "www\\.google\\.[^/]*/" ), "www.google.com/" );
- if ( cmd != TQString::fromLatin1( expectedResult ) )
- {
- kdError() << " Got " << cmd << " expected " << expectedResult << endl;
- ::exit(1);
- }
- }
- }
- else
- {
- if ( expectedUriType == NO_FILTERING )
- kdDebug() << "*** No filtering required." << endl;
- else
- {
- kdDebug() << "*** Could not be filtered." << endl;
- if( expectedUriType != m_filterData->uriType() )
- {
- kdError() << " Got URI type " << s_uritypes[m_filterData->uriType()]
- << " expected " << s_uritypes[expectedUriType] << endl;
- ::exit(1);
- }
- }
- }
-
- delete m_filterData;
- kdDebug() << "-----" << endl;
-}
-
-void testLocalFile( const TQString& filename )
-{
- TQFile tmpFile( filename ); // Yeah, I know, security risk blah blah. This is a test prog!
-
- if ( tmpFile.open( IO_ReadWrite ) )
- {
- TQCString fname = TQFile::encodeName( tmpFile.name() );
- filter(fname, fname, KURIFilterData::LOCAL_FILE);
- tmpFile.close();
- tmpFile.remove();
- }
- else
- kdDebug() << "Couldn't create " << tmpFile.name() << ", skipping test" << endl;
-}
-
-static const char appName[] = "kurifiltertest";
-static const char programName[] = I18N_NOOP("kurifiltertest");
-static const char description[] = I18N_NOOP("Unit test for the URI filter plugin framework.");
-static const char version[] = "1.5";
-
-static const KCmdLineOptions options[] =
-{
- { "s", I18N_NOOP("Use space as keyword delimeter for web shortcuts"), 0},
- KCmdLineLastOption
-};
-
-int main(int argc, char **argv)
-{
- // Ensure that user configuration doesn't change the results of those tests
- // TDEHOME needs to be writable though, for a tdesycoca database
- setenv( "TDEHOME", TQFile::encodeName( TQDir::homeDirPath() + "/.tde-kurifiltertest" ), true );
- setenv( "TDE_FORK_SLAVES", "yes", true ); // simpler, for the final cleanup
-
- TDEAboutData aboutData(appName, programName, version, description);
- TDECmdLineArgs::init(argc, argv, &aboutData);
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDEApplication app;
- app.disableAutoDcopRegistration();
-
- // Allow testing of the search engine using both delimiters...
- char delimiter = TDECmdLineArgs::parsedArgs()->isSet("s") ? ' ' : ':';
-
- // Many tests check the "default search engine" feature.
- // There is no default search engine by default (since it was annoying when making typos),
- // so the user has to set it up, which we do here.
- {
- KSimpleConfig cfg( "kuriikwsfilterrc" );
- cfg.setGroup( "General" );
- cfg.writeEntry( "DefaultSearchEngine", "google" );
- cfg.writeEntry( "Verbose", true );
- cfg.writeEntry( "KeywordDelimiter", delimiter );
- cfg.sync();
- }
-
- // Enable verbosity for debugging
- {
- KSimpleConfig cfg( "kshorturifilterrc" );
- cfg.writeEntry( "Verbose", true );
- cfg.sync();
- }
-
- TQStringList minicliFilters;
- minicliFilters << "kshorturifilter" << "kurisearchfilter" << "localdomainurifilter";
-
- // URI that should require no filtering
- filter( "http://www.kde.org", "http://www.kde.org", KURIFilterData::NET_PROTOCOL );
- filter( "http://www.kde.org/developer//index.html", "http://www.kde.org/developer//index.html", KURIFilterData::NET_PROTOCOL );
- // URL with reference
- filter( "http://www.kde.org/index.html#q8", "http://www.kde.org/index.html#q8", KURIFilterData::NET_PROTOCOL );
- // local file with reference
- filter( "file:/etc/passwd#q8", "file:///etc/passwd#q8", KURIFilterData::LOCAL_FILE );
- filter( "file:///etc/passwd#q8", "file:///etc/passwd#q8", KURIFilterData::LOCAL_FILE );
- filter( "/etc/passwd#q8", "file:///etc/passwd#q8", KURIFilterData::LOCAL_FILE );
- // local file with query (can be used by javascript)
- filter( "file:/etc/passwd?foo=bar", "file:///etc/passwd?foo=bar", KURIFilterData::LOCAL_FILE );
- testLocalFile( "/tmp/kurifiltertest?foo" ); // local file with ? in the name (#58990)
- testLocalFile( "/tmp/kurlfiltertest#foo" ); // local file with '#' in the name
- testLocalFile( "/tmp/kurlfiltertest#foo?bar" ); // local file with both
- testLocalFile( "/tmp/kurlfiltertest?foo#bar" ); // local file with both, the other way round
-
- // hostnames are lowercased by KURL
- filter( "http://www.myDomain.commyPort/ViewObjectRes//Default:name=hello",
- "http://www.mydomain.commyport/ViewObjectRes//Default:name=hello", KURIFilterData::NET_PROTOCOL);
- filter( "ftp://ftp.kde.org", "ftp://ftp.kde.org", KURIFilterData::NET_PROTOCOL );
- filter( "ftp://username@ftp.kde.org:500", "ftp://username@ftp.kde.org:500", KURIFilterData::NET_PROTOCOL );
-
- // ShortURI/LocalDomain filter tests. NOTE: any of these tests can fail
- // if you have specified your own patterns in kshorturifilterrc. For
- // examples, see $TDEDIR/share/config/kshorturifilterrc .
- filter( "linuxtoday.com", "http://linuxtoday.com", KURIFilterData::NET_PROTOCOL );
- filter( "LINUXTODAY.COM", "http://linuxtoday.com", KURIFilterData::NET_PROTOCOL );
- filter( "kde.org", "http://kde.org", KURIFilterData::NET_PROTOCOL );
- filter( "ftp.kde.org", "ftp://ftp.kde.org", KURIFilterData::NET_PROTOCOL );
- filter( "ftp.kde.org:21", "ftp://ftp.kde.org:21", KURIFilterData::NET_PROTOCOL );
- filter( "cr.yp.to", "http://cr.yp.to", KURIFilterData::NET_PROTOCOL );
- filter( "user@192.168.1.0:3128", "http://user@192.168.1.0:3128", KURIFilterData::NET_PROTOCOL );
- filter( "127.0.0.1", "http://127.0.0.1", KURIFilterData::NET_PROTOCOL );
- filter( "127.0.0.1:3128", "http://127.0.0.1:3128", KURIFilterData::NET_PROTOCOL );
- filter( "foo@bar.com", "mailto:foo@bar.com", KURIFilterData::NET_PROTOCOL );
- filter( "firstname.lastname@x.foo.bar", "mailto:firstname.lastname@x.foo.bar", KURIFilterData::NET_PROTOCOL );
- filter( "www.123.foo", "http://www.123.foo", KURIFilterData::NET_PROTOCOL );
- filter( "user@www.123.foo:3128", "http://user@www.123.foo:3128", KURIFilterData::NET_PROTOCOL );
-
- // Exotic IPv4 address formats...
- filter( "127.1", "http://127.1", KURIFilterData::NET_PROTOCOL );
- filter( "127.0.1", "http://127.0.1", KURIFilterData::NET_PROTOCOL );
-
- // Local domain filter - If you uncomment these test, make sure you
- // you adjust it based on the localhost entry in your /etc/hosts file.
- // filter( "localhost:3128", "http://localhost.localdomain:3128", KURIFilterData::NET_PROTOCOL );
- // filter( "localhost", "http://localhost.localdomain", KURIFilterData::NET_PROTOCOL );
- // filter( "localhost/~blah", "http://localhost.localdomain/~blah", KURIFilterData::NET_PROTOCOL );
-
- filter( "/", "/", KURIFilterData::LOCAL_DIR );
- filter( "/", "/", KURIFilterData::LOCAL_DIR, "kshorturifilter" );
- filter( "~/.bashrc", TQDir::homeDirPath().local8Bit()+"/.bashrc", KURIFilterData::LOCAL_FILE, "kshorturifilter" );
- filter( "~", TQDir::homeDirPath().local8Bit(), KURIFilterData::LOCAL_DIR, "kshorturifilter", "/tmp" );
- filter( "~foobar", 0, KURIFilterData::ERROR, "kshorturifilter" );
- filter( "user@host.domain", "mailto:user@host.domain", KURIFilterData::NET_PROTOCOL ); // new in KDE-3.2
-
- // Windows style SMB (UNC) URL. Should be converted into the valid smb format...
- filter( "\\\\mainserver\\share\\file", "smb://mainserver/share/file" , KURIFilterData::NET_PROTOCOL );
-
- // Should not be filtered at all. All valid protocols of this form will be ignored.
- filter( "ftp:" , "ftp:", KURIFilterData::UNKNOWN );
- filter( "http:" , "http:", KURIFilterData::UNKNOWN );
-
- /*
- Automatic searching tests. NOTE: If the Default search engine is set to 'None',
- this stuff will fail as the status returned will then be KURIFilterData::UNKNOWN.
- */
- filter( "gg:", 0 , KURIFilterData::NET_PROTOCOL );
- filter( "KDE", 0 , KURIFilterData::NET_PROTOCOL );
- filter( "FTP", 0 , KURIFilterData::NET_PROTOCOL );
-
- // If your default search engine is set to 'Google', you can uncomment the test below.
- filter( "gg:", "http://www.google.com/search?q=gg%3A&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
- filter( "KDE", "http://www.google.com/search?q=KDE&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
- filter( "FTP", "http://www.google.com/search?q=FTP&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
-
- // Typing 'cp' or any other valid unix command in konq's location bar should result in
- // a search using the default search engine
- // 'ls' is a bit of a special case though, due to the toplevel domain called 'ls'
- filter( "cp", "http://www.google.com/search?q=cp&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL,
- TQStringList(), 0, false /* don't check for executables, see konq_misc.cc */ );
-
- // Executable tests - No IKWS in minicli
- filter( "cp", "cp", KURIFilterData::EXECUTABLE, minicliFilters );
- filter( "kfmclient", "kfmclient", KURIFilterData::EXECUTABLE, minicliFilters );
- filter( "xwininfo", "xwininfo", KURIFilterData::EXECUTABLE, minicliFilters );
- filter( "KDE", "KDE", NO_FILTERING, minicliFilters );
- filter( "I/dont/exist", "I/dont/exist", NO_FILTERING, minicliFilters );
- filter( "/I/dont/exist", 0, KURIFilterData::ERROR, minicliFilters );
- filter( "/I/dont/exist#a", 0, KURIFilterData::ERROR, minicliFilters );
- filter( "kfmclient --help", "kfmclient --help", KURIFilterData::EXECUTABLE, minicliFilters ); // the args are in argsAndOptions()
- filter( "/usr/bin/gs", "/usr/bin/gs", KURIFilterData::EXECUTABLE, minicliFilters );
- filter( "/usr/bin/gs -q -option arg1", "/usr/bin/gs -q -option arg1", KURIFilterData::EXECUTABLE, minicliFilters ); // the args are in argsAndOptions()
-
- // ENVIRONMENT variable
- setenv( "SOMEVAR", "/somevar", 0 );
- setenv( "ETC", "/etc", 0 );
-
- TQCString qtdir=getenv("QTDIR");
- TQCString home = getenv("HOME");
- TQCString tdehome = getenv("TDEHOME");
-
- filter( "$SOMEVAR/tdelibs/kio", 0, KURIFilterData::ERROR ); // note: this dir doesn't exist...
- filter( "$ETC/passwd", "/etc/passwd", KURIFilterData::LOCAL_FILE );
- filter( "$QTDIR/doc/html/functions.html#s", TQCString("file://")+qtdir+"/doc/html/functions.html#s", KURIFilterData::LOCAL_FILE );
- filter( "http://www.kde.org/$USER", "http://www.kde.org/$USER", KURIFilterData::NET_PROTOCOL ); // no expansion
-
- // Assume the default (~/.trinity) if
- if (tdehome.isEmpty())
- {
- tdehome += "$HOME/.trinity";
- setenv("TDEHOME", tdehome.data(), 0);
- }
-
- filter( "$TDEHOME/share", tdehome+"/share", KURIFilterData::LOCAL_DIR );
- KStandardDirs::makeDir( tdehome+"/a+plus" );
- filter( "$TDEHOME/a+plus", tdehome+"/a+plus", KURIFilterData::LOCAL_DIR );
-
- // BR 27788
- KStandardDirs::makeDir( tdehome+"/share/Dir With Space" );
- filter( "$TDEHOME/share/Dir With Space", tdehome+"/share/Dir With Space", KURIFilterData::LOCAL_DIR );
-
- // support for name filters (BR 93825)
- filter( "$TDEHOME/*.txt", tdehome+"/*.txt", KURIFilterData::LOCAL_DIR );
- filter( "$TDEHOME/[a-b]*.txt", tdehome+"/[a-b]*.txt", KURIFilterData::LOCAL_DIR );
- filter( "$TDEHOME/a?c.txt", tdehome+"/a?c.txt", KURIFilterData::LOCAL_DIR );
- filter( "$TDEHOME/?c.txt", tdehome+"/?c.txt", KURIFilterData::LOCAL_DIR );
- // but let's check that a directory with * in the name still works
- KStandardDirs::makeDir( tdehome+"/share/Dir*With*Stars" );
- filter( "$TDEHOME/share/Dir*With*Stars", tdehome+"/share/Dir*With*Stars", KURIFilterData::LOCAL_DIR );
- KStandardDirs::makeDir( tdehome+"/share/Dir?QuestionMark" );
- filter( "$TDEHOME/share/Dir?QuestionMark", tdehome+"/share/Dir?QuestionMark", KURIFilterData::LOCAL_DIR );
- KStandardDirs::makeDir( tdehome+"/share/Dir[Bracket" );
- filter( "$TDEHOME/share/Dir[Bracket", tdehome+"/share/Dir[Bracket", KURIFilterData::LOCAL_DIR );
-
- filter( "$HOME/$TDEDIR/tdebase/kcontrol/ebrowsing", 0, KURIFilterData::ERROR );
- filter( "$1/$2/$3", "http://www.google.com/search?q=$1/$2/$3&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL ); // can be used as bogus or valid test. Currently triggers default search, i.e. google
- filter( "$$$$", "http://www.google.com/search?q=$$$$&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL ); // worst case scenarios.
-
- // Replaced the match testing with a 0 since
- // the shortURI filter will return the string
- // itself if the requested environment variable
- // is not already set.
- filter( "$QTDIR", 0, KURIFilterData::LOCAL_DIR, "kshorturifilter" ); //use specific filter.
- filter( "$HOME", home, KURIFilterData::LOCAL_DIR, "kshorturifilter" ); //use specific filter.
-
-
- TQCString sc;
- filter( sc.sprintf("gg%cfoo bar",delimiter), "http://www.google.com/search?q=foo+bar&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
- filter( sc.sprintf("bug%c55798", delimiter), "http://bugs.kde.org/show_bug.cgi?id=55798", KURIFilterData::NET_PROTOCOL );
-
- filter( sc.sprintf("gg%cC++", delimiter), "http://www.google.com/search?q=C%2B%2B&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
- filter( sc.sprintf("ya%cfoo bar was here", delimiter), 0, -1 ); // this triggers default search, i.e. google
- filter( sc.sprintf("gg%cwww.kde.org", delimiter), "http://www.google.com/search?q=www.kde.org&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
- filter( sc.sprintf("av%c+rock +sample", delimiter), "http://www.altavista.com/cgi-bin/query?pg=q&kl=XX&stype=stext&q=%2Brock+%2Bsample", KURIFilterData::NET_PROTOCOL );
- filter( sc.sprintf("gg%cé", delimiter) /*eaccent in utf8*/, "http://www.google.com/search?q=%C3%A9&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
- filter( sc.sprintf("gg%cпрйвет", delimiter) /* greetings in russian utf-8*/, "http://www.google.com/search?q=%D0%BF%D1%80%D0%B9%D0%B2%D0%B5%D1%82&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
-
- // Absolute Path tests for kshorturifilter
- filter( "./", tdehome+"/share", KURIFilterData::LOCAL_DIR, "kshorturifilter", tdehome+"/share/" ); // cleanDirPath removes the trailing slash
- filter( "../", tdehome, KURIFilterData::LOCAL_DIR, "kshorturifilter", tdehome+"/share" );
- filter( "config", tdehome+"/share/config", KURIFilterData::LOCAL_DIR, "kshorturifilter", tdehome+"/share" );
-
- // Clean up
- TDEIO::NetAccess::del( tdehome, 0 );
-
- kdDebug() << "All tests done. Go home..." << endl;
- return 0;
-}
diff --git a/kio/tests/metatest.cpp b/kio/tests/metatest.cpp
deleted file mode 100644
index 034d740ed..000000000
--- a/kio/tests/metatest.cpp
+++ /dev/null
@@ -1,321 +0,0 @@
-#include <kapplication.h>
-#include <kfilemetainfo.h>
-#include <kcmdlineargs.h>
-#include <tqstringlist.h>
-#include <tqimage.h>
-#include <kdebug.h>
-#include <tqlabel.h>
-#include <tqvalidator.h>
-
-#define I18N_NOOP
-
- static KCmdLineOptions options[] =
- {
- { "+file", "File name", 0 },
- { "addgroup ", "Add a group to a file", 0},
- { "removegroup ", "Remove a group from a file", 0},
- { "removeitem ", "Remove the item from --group from a file", 0},
- { "group ", "Specify a group to work on", 0},
- { "validator", "Create a validator for an item and show its class", 0},
- { "item ", "Specify an item to work on", 0},
- { "add ", "Add the --item to the --group and set the value", 0},
- { "autogroupadd", "Automatically add a group if none is found", 0},
- { "set ", "Set the value of --item in --group", 0},
- { "groups", "list the groups of this file", 0 },
- { "mimetypeinfo ", "the mimetype info for a mimetype", 0 },
- KCmdLineLastOption
- };
-
-void printKeyValues(KFileMetaInfo& info)
-{
- TQStringList l = info.preferredKeys();
- kdDebug() << "found " << l.size() << " keys\n";
-
- TQString s;
- TQStringList::Iterator it;
- for (it = l.begin(); it!=l.end(); ++it)
- {
- s +=" - " + *it;
- }
- kdDebug() << "keys: " << s << endl;
-
- for (it = l.begin(); it!=l.end(); ++it)
- {
- KFileMetaInfoItem item = info.item(*it);
- if ( item.isValid() && item.value().canCast(TQVariant::String)) {
- kdDebug() << item.key() << "(" << item.translatedKey() << ") -> "
- << item.string() << endl;
- }
- }
-}
-
-void printMimeTypeInfo(TQString mimetype)
-{
- const KFileMimeTypeInfo* info = KFileMetaInfoProvider::self()->mimeTypeInfo(mimetype);
-
- if (!info) return;
- kdDebug() << "Preferred groups:\n";
- kdDebug() << "=================\n";
- TQStringList groups = info->preferredGroups();
-
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- {
- kdDebug() << *it << endl;
- }
-
- kdDebug() << endl;
- kdDebug() << "Supported groups:\n";
- kdDebug() << "=================\n";
- groups = info->supportedGroups();
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- {
- kdDebug() << *it << endl;
- }
-
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- {
- const KFileMimeTypeInfo::GroupInfo* groupinfo = info->groupInfo(*it);
-
- kdDebug() << endl;
- kdDebug() << "Group \"" << *it << "\"\n";
- kdDebug() << "==================\n";
-
- if (!groupinfo) kdDebug() << "argh! no group info\n";
-
- kdDebug() << endl;
- kdDebug() << " Supported keys:\n";
- TQStringList keys = groupinfo->supportedKeys();
- if (!keys.count()) kdDebug() << " none\n";
- for (TQStringList::Iterator kit=keys.begin(); kit!=keys.end(); ++kit)
- {
- kdDebug() << " " << *kit << endl;
-
- const KFileMimeTypeInfo::ItemInfo* iti = groupinfo->itemInfo(*kit);
- kdDebug() << " Key: " << iti->key() << endl;
- kdDebug() << " Translated: " << iti->key() << endl;
- kdDebug() << " Type: " << TQVariant::typeToName(iti->type()) << endl;
- kdDebug() << " Unit: " << iti->unit() << endl;
- kdDebug() << " Hint: " << iti->hint() << endl;
- kdDebug() << " Attributes: " << iti->attributes() << endl;
- kdDebug() << " Prefix: " << iti->prefix() << endl;
- kdDebug() << " Suffix: " << iti->suffix() << endl;
- }
-
- kdDebug() << " name: " << groupinfo->name() << endl;
- kdDebug() << " translated: " << groupinfo->translatedName() << endl;
- kdDebug() << " attributes: " << groupinfo->attributes() << endl;
- kdDebug() << " variable keys: " << (groupinfo->supportsVariableKeys() ? "Yes" : "No") << endl;
- if (groupinfo->supportsVariableKeys())
- {
- const KFileMimeTypeInfo::ItemInfo* iti = groupinfo->variableItemInfo();
- kdDebug() << " variable key type/attr: " << TQVariant::typeToName(iti->type()) << " / " << iti->attributes() << endl;
- }
- }
-
- kdDebug() << endl;
- kdDebug() << "Preferred keys:\n";
- kdDebug() << "===============\n";
- TQStringList prefKeys = info->preferredKeys();
- if (!prefKeys.count()) kdDebug() << " none\n";
- for (TQStringList::Iterator kit=prefKeys.begin(); kit!=prefKeys.end(); ++kit)
- {
- kdDebug() << *kit << endl;
- }
-
- kdDebug() << endl;
- kdDebug() << "Supported keys:\n";
- kdDebug() << "===============\n";
- TQStringList supKeys = info->supportedKeys();
- if (!supKeys.count()) kdDebug() << " none\n";
- for (TQStringList::Iterator kit=supKeys.begin(); kit!=supKeys.end(); ++kit)
- {
- kdDebug() << *kit << endl;
- }
-}
-
-void addGroup(KFileMetaInfo& info, TQString group)
-{
- kdDebug() << "trying to add group " << group << endl;
-
- kdDebug() << "groups before: \n";
- TQStringList groups = info.groups();
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- kdDebug() << " " << *it << endl;
-
- if (info.addGroup(group))
- kdDebug() << "addGroup succeeded\n";
- else
- kdDebug() << "addGroup failed\n";
-
- kdDebug() << "trying another addGroup to see what happens\n";
-
- if (info.addGroup(group))
- kdDebug() << "addGroup succeeded\n";
- else
- kdDebug() << "addGroup failed\n";
-
-
- kdDebug() << "and afterwards: \n";
- groups = info.groups();
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- kdDebug() << " " << *it << endl;
-}
-
-void removeGroup(KFileMetaInfo& info, TQString group)
-{
- kdDebug() << "trying to remove group " << group << endl;
-
- kdDebug() << "groups before: \n";
- TQStringList groups = info.groups();
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- kdDebug() << " " << *it << endl;
-
- info.removeGroup(group);
-
- kdDebug() << "and afterwards: \n";
- groups = info.groups();
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- kdDebug() << " " << *it << endl;
-}
-
-int main( int argc, char **argv )
-{
- // Initialize command line args
- TDECmdLineArgs::init(argc, argv, "kfilemetatest", "testing kfilmetainfo", "X");
-
- // Tell which options are supported
- TDECmdLineArgs::addCmdLineOptions( options );
-
- // Add options from other components
- TDEApplication::addCmdLineOptions();
-
- TDEApplication app;
-
- TDECmdLineArgs* args = TDECmdLineArgs::parsedArgs();
-
- TQCString ov;
- ov = args->getOption("mimetypeinfo");
- if (ov)
- {
- printMimeTypeInfo(ov);
- return 0;
- }
-
- if (!args->count()) return 1;
-
- KFileMetaInfo info( args->url(0), TQString::null, KFileMetaInfo::Everything);
-
- if (args->isSet("groups"))
- {
- TQStringList groups = info.groups();
- for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
- {
- kdDebug() << "group " << *it << endl;
- }
- return 0;
- }
-
- TQString group, item;
-
- ov = args->getOption("addgroup");
- if (ov) addGroup(info, ov);
-
- ov = args->getOption("removegroup");
- if (ov) removeGroup(info, ov);
-
- ov = args->getOption("group");
- if (ov) group = ov;
-
- ov = args->getOption("item");
- if (ov) item = ov;
-
- ov = args->getOption("add");
- if (ov && !group.isNull() && !item.isNull())
- {
- KFileMetaInfoGroup g = info[group];
- if (!g.isValid() && args->isSet("autogroupadd"))
- {
- kdDebug() << "group is not there, adding it\n";
- info.addGroup(group);
- }
- // add the item
- KFileMetaInfoItem i = info[group].addItem(item);
- if (i.isValid())
- kdDebug() << "additem success\n";
- else
- kdDebug() << "additem failed\n";
-
- if (i.setValue(ov))
- kdDebug() << "setValue success\n";
- else
- kdDebug() << "setValue failed\n";
- }
-
- ov = args->getOption("set");
- if (ov && !group.isNull() && !item.isNull())
- {
- if (info[group][item].setValue(TQString(ov)))
- kdDebug() << "setValue success\n";
- else
- kdDebug() << "setValue failed\n";
- }
-
- ov = args->getOption("removeitem");
- if (ov && !group.isNull())
- {
- if (info[group].removeItem(ov))
- kdDebug() << "removeitem success\n";
- else
- kdDebug() << "removeitem failed\n";
- }
-
- if (args->isSet("validator") && !group.isNull() && !item.isNull())
- {
- const KFileMimeTypeInfo* kfmti = KFileMetaInfoProvider::self()->mimeTypeInfo(info.mimeType());
- TQValidator* v = kfmti->createValidator(group, item);
- if (!v)
- kdDebug() << "got no validator\n";
- else
- {
- kdDebug() << "validator is a " << v->className() << endl;
- delete v;
- }
-
- }
-
- kdDebug() << "is it valid?\n";
-
- if (!info.isValid()) return 1;
-
- kdDebug() << "it is!\n";
-
- printKeyValues(info);
-
-
- kdDebug() << "========= again after applyChanges() =========\n";
-
- info.applyChanges();
-
- printKeyValues(info);
-
- KFileMetaInfoItem thumbitem = info.item(KFileMimeTypeInfo::Thumbnail);
-// KFileMetaInfoItem thumbitem = info.item("Thumbnail");
-
- if (!thumbitem.isValid()) kdDebug() << "no thumbnail\n";
- else
- kdDebug() << "type of thumbnail is " << thumbitem.value().typeName() << endl;
-
-
- if (thumbitem.isValid() && thumbitem.value().canCast(TQVariant::Image))
- {
- TQLabel* label = new TQLabel(0);
- app.setMainWidget(label);
- TQPixmap pix;
- pix.convertFromImage(thumbitem.value().toImage());
- label->setPixmap(pix);
- label->show();
- app.exec();
- }
-
- return 0;
-}
diff --git a/kio/tests/netaccesstest.cpp b/kio/tests/netaccesstest.cpp
deleted file mode 100644
index c83f45aae..000000000
--- a/kio/tests/netaccesstest.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2004 David Faure <faure@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <kurl.h>
-#include <kio/netaccess.h>
-#include <tqfile.h>
-
-int main(int argc, char **argv)
-{
- TDEApplication app( argc, argv, "netaccesstest", true /* it _has_ a GUI ! */);
-
- KURL srcURL( "ftp://ftp.kde.org/pub/kde/README" );
- KURL tmpURL( "file:/tmp/netaccesstest_README" );
-
- for ( uint i = 0; i < 4 ; ++i ) {
- kdDebug() << "file_copy" << endl;
- if ( !TDEIO::NetAccess::file_copy(srcURL, tmpURL, -1, true, false, 0) )
- kdError() << "file_copy failed: " << TDEIO::NetAccess::lastErrorString() << endl;
- else {
- TQFile f( tmpURL.path() );
- if (!f.open(IO_ReadOnly))
- kdFatal() << "Cannot open: " << f.name() << ". The error was: " << f.errorString() << endl;
- else {
- f.close();
- }
- }
- }
-
- return 0;
-}
-
diff --git a/kio/tests/previewtest.cpp b/kio/tests/previewtest.cpp
deleted file mode 100644
index 62f6c3d62..000000000
--- a/kio/tests/previewtest.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqpushbutton.h>
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klineedit.h>
-
-#include <kio/previewjob.h>
-
-#include "previewtest.moc"
-
-PreviewTest::PreviewTest()
- :TQWidget()
-{
- TQGridLayout *layout = new TQGridLayout(this, 2, 2);
- m_url = new KLineEdit(this);
- m_url->setText("/home/malte/gore_bush.jpg");
- layout->addWidget(m_url, 0, 0);
- TQPushButton *btn = new TQPushButton("Generate", this);
- connect(btn, TQT_SIGNAL(clicked()), TQT_SLOT(slotGenerate()));
- layout->addWidget(btn, 0, 1);
- m_preview = new TQLabel(this);
- m_preview->setMinimumSize(400, 300);
- layout->addMultiCellWidget(m_preview, 1, 1, 0, 1);
-}
-
-void PreviewTest::slotGenerate()
-{
- KURL::List urls;
- urls.append(m_url->text());
- TDEIO::PreviewJob *job = TDEIO::filePreview(urls, m_preview->width(), m_preview->height(), true, 48);
- connect(job, TQT_SIGNAL(result(TDEIO::Job*)), TQT_SLOT(slotResult(TDEIO::Job*)));
- connect(job, TQT_SIGNAL(gotPreview(const KFileItem *, const TQPixmap &)), TQT_SLOT(slotPreview(const KFileItem *, const TQPixmap &)));
- connect(job, TQT_SIGNAL(failed(const KFileItem *)), TQT_SLOT(slotFailed()));
-}
-
-void PreviewTest::slotResult(TDEIO::Job*)
-{
- kdDebug() << "PreviewTest::slotResult(...)" << endl;
-}
-
-void PreviewTest::slotPreview(const KFileItem *, const TQPixmap &pix)
-{
- kdDebug() << "PreviewTest::slotPreview()" << endl;
- m_preview->setPixmap(pix);
-}
-
-void PreviewTest::slotFailed()
-{
- kdDebug() << "PreviewTest::slotFailed()" << endl;
- m_preview->setText("failed");
-}
-
-int main(int argc, char **argv)
-{
- TDEApplication app(argc, argv, "previewtest");
- PreviewTest *w = new PreviewTest;
- w->show();
- app.setMainWidget(w);
- return app.exec();
-}
-
diff --git a/kio/tests/previewtest.h b/kio/tests/previewtest.h
deleted file mode 100644
index a749e95a3..000000000
--- a/kio/tests/previewtest.h
+++ /dev/null
@@ -1,25 +0,0 @@
-
-#include <tqwidget.h>
-#include <kio/job.h>
-
-class KLineEdit;
-class TQLabel;
-class KFileItem;
-
-class PreviewTest : public TQWidget
-{
- Q_OBJECT
-public:
- PreviewTest();
-
-private slots:
- void slotGenerate();
- void slotResult(TDEIO::Job *);
- void slotPreview( const KFileItem *, const TQPixmap & );
- void slotFailed();
-
-private:
- KLineEdit *m_url;
- TQLabel *m_preview;
-};
-
diff --git a/kio/tests/speed.cpp b/kio/tests/speed.cpp
deleted file mode 100644
index 44a7d9330..000000000
--- a/kio/tests/speed.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2002, 2003 Stephan Kulow <coolo@kde.org>
- * Copyright (C) 2003 David Faure <faure@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation;
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-#include <kdebug.h>
-#include <kapplication.h>
-#include <time.h>
-#include "speed.h"
-#include <kio/job.h>
-#include <kcmdlineargs.h>
-#include <tqdir.h>
-#include <kio/global.h>
-
-using namespace TDEIO;
-
-SpeedTest::SpeedTest( const KURL & url )
- : TQObject(0, "speed")
-{
- Job *job = listRecursive( url );
- //Job *job = del( KURL("file:" + TQDir::currentDirPath()) ); DANGEROUS !
- connect(job, TQT_SIGNAL( result( TDEIO::Job*)),
- TQT_SLOT( finished( TDEIO::Job* ) ));
- /*connect(job, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
- TQT_SLOT( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)));
- */
-}
-
-void SpeedTest::entries(TDEIO::Job*, const UDSEntryList& list) {
-
- UDSEntryListConstIterator it=list.begin();
- for (; it != list.end(); ++it) {
- UDSEntry::ConstIterator it2 = (*it).begin();
- for( ; it2 != (*it).end(); it2++ ) {
- if ((*it2).m_uds == UDS_NAME)
- kdDebug() << ( *it2 ).m_str << endl;
- }
- }
-}
-
-
-void SpeedTest::finished(Job*) {
- kdDebug() << "job finished" << endl;
- kapp->quit();
-}
-
-static KCmdLineOptions options[] =
-{
- { "+[URL]", "the URL to list", 0 },
- KCmdLineLastOption
-};
-
-int main(int argc, char **argv) {
-
- TDECmdLineArgs::init( argc, argv, "speedapp", "A TDEIO::listRecursive testing tool", "0.0" );
-
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDEApplication app;
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- KURL url;
- if ( args->count() == 1 )
- url = args->url(0);
- else
- url = "file:" + TQDir::currentDirPath();
-
- kdDebug() << url.url() << " is probably " << (TDEIO::probably_slow_mounted(url.path()) ? "slow" : "normal") << " mounted\n";
- kdDebug() << url.url() << " is " << (TDEIO::manually_mounted(url.path()) ? "manually" : "system") << " mounted\n";
- TQString mp = TDEIO::findDeviceMountPoint(url.path());
- if (mp.isEmpty()) {
- kdDebug() << "no mount point for device " << url.url() << " found\n";
- } else
- kdDebug() << mp << " is the mount point for device " << url.url() << endl;
-
- mp = TDEIO::findPathMountPoint(url.path());
- if (mp.isEmpty()) {
- kdDebug() << "no mount point for path " << url.url() << " found\n";
- } else
- kdDebug() << mp << " is the mount point for path " << url.url() << endl;
- // SpeedTest test( url );
- // app.exec();
-
- mp = TDEIO::findPathMountPoint(url.path());
- if (mp.isEmpty()) {
- kdDebug() << "no mount point for path " << url.url() << " found\n";
- } else
- kdDebug() << mp << " is the mount point for path " << url.url() << endl;
- // SpeedTest test( url );
- // app.exec();
-
- url.setPath(TQDir::homeDirPath());
-
- mp = TDEIO::findPathMountPoint(url.path());
- if (mp.isEmpty()) {
- kdDebug() << "no mount point for path " << url.url() << " found\n";
- } else
- kdDebug() << mp << " is the mount point for path " << url.url() << endl;
- // SpeedTest test( url );
- // app.exec();
-
- mp = TDEIO::findPathMountPoint(url.path());
- if (mp.isEmpty()) {
- kdDebug() << "no mount point for path " << url.url() << " found\n";
- } else
- kdDebug() << mp << " is the mount point for path " << url.url() << endl;
- // SpeedTest test( url );
- // app.exec();
-
- if ( args->count() == 1 )
- url = args->url(0);
- else
- url = "file:" + TQDir::currentDirPath();
-
- mp = TDEIO::findPathMountPoint(url.path());
- if (mp.isEmpty()) {
- kdDebug() << "no mount point for path " << url.url() << " found\n";
- } else
- kdDebug() << mp << " is the mount point for path " << url.url() << endl;
- // SpeedTest test( url );
- // app.exec();
-
-}
-
-#include "speed.moc"
diff --git a/kio/tests/speed.h b/kio/tests/speed.h
deleted file mode 100644
index 5b928a18e..000000000
--- a/kio/tests/speed.h
+++ /dev/null
@@ -1,24 +0,0 @@
-// -*- c++ -*-
-#ifndef _SPEED_H
-#define _SPEED_H
-
-#include <kio/global.h>
-#include <kurl.h>
-
-namespace TDEIO {
- class Job;
-}
-
-class SpeedTest : public TQObject {
- Q_OBJECT
-
-public:
- SpeedTest(const KURL & url);
-
-private slots:
- void entries( TDEIO::Job *, const TDEIO::UDSEntryList& );
- void finished( TDEIO::Job *job );
-
-};
-
-#endif
diff --git a/kioslave/bzip2/CMakeLists.txt b/kioslave/bzip2/CMakeLists.txt
deleted file mode 100644
index a2354d6b0..000000000
--- a/kioslave/bzip2/CMakeLists.txt
+++ /dev/null
@@ -1,42 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install( FILES kbzip2filter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-##### kbzip2filter ##############################
-
-set( target kbzip2filter )
-
-set( ${target}_SRCS
- kbzip2filter.cpp
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared ${BZIP2_LIBRARIES}
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kioslave/bzip2/Makefile.am b/kioslave/bzip2/Makefile.am
deleted file mode 100644
index 9353959ab..000000000
--- a/kioslave/bzip2/Makefile.am
+++ /dev/null
@@ -1,11 +0,0 @@
-INCLUDES = -I$(top_srcdir)/kio $(all_includes)
-METASOURCES = AUTO
-
-kde_module_LTLIBRARIES = kbzip2filter.la
-
-kbzip2filter_la_SOURCES = kbzip2filter.cpp
-kbzip2filter_la_LIBADD = $(LIB_KIO) $(LIBBZ2) $(LIB_QT) $(LIB_TDECORE)
-kbzip2filter_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
-
-kde_services_DATA = kbzip2filter.desktop
-
diff --git a/kioslave/file/CMakeLists.txt b/kioslave/file/CMakeLists.txt
deleted file mode 100644
index 2cf415745..000000000
--- a/kioslave/file/CMakeLists.txt
+++ /dev/null
@@ -1,55 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-add_definitions(
- -D_LARGEFILE64_SOURCE
-)
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### headers ###################################
-
-install( FILES file.h DESTINATION ${INCLUDE_INSTALL_DIR}/kio )
-
-
-##### other data ################################
-
-install( FILES file.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-##### kio_file ##################################
-
-set( target kio_file )
-
-set( ${target}_SRCS
- file.cc
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
-
diff --git a/kioslave/file/Makefile.am b/kioslave/file/Makefile.am
deleted file mode 100644
index 3daf0cbcc..000000000
--- a/kioslave/file/Makefile.am
+++ /dev/null
@@ -1,22 +0,0 @@
-## Makefile.am of tdebase/kioslave/file
-
-AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
-
-INCLUDES = $(all_includes)
-
-####### Files
-
-kde_module_LTLIBRARIES = kio_file.la
-
-kio_file_la_SOURCES = file.cc
-kio_file_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE) $(ACL_LIBS)
-kio_file_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(top_builddir)/dcop/libDCOP.la
-noinst_HEADERS = file.h
-
-fileinclude_HEADERS = file.h
-fileincludedir = $(includedir)/kio
-
-METASOURCES = AUTO
-
-kdelnkdir = $(kde_servicesdir)
-kdelnk_DATA = file.protocol
diff --git a/kioslave/file/file.cc b/kioslave/file/file.cc
deleted file mode 100644
index 73a037b91..000000000
--- a/kioslave/file/file.cc
+++ /dev/null
@@ -1,1831 +0,0 @@
-/*
- Copyright (C) 2000-2002 Stephan Kulow <coolo@kde.org>
- Copyright (C) 2000-2002 David Faure <faure@kde.org>
- Copyright (C) 2000-2002 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License (LGPL) as published by the Free Software Foundation;
- either version 2 of the License, or (at your option) any later
- version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#include <config.h>
-
-#include <tqglobal.h> //for Q_OS_XXX
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-
-//sendfile has different semantics in different platforms
-#if defined HAVE_SENDFILE && defined Q_OS_LINUX
-#define USE_SENDFILE 1
-#endif
-
-#ifdef USE_SENDFILE
-#include <sys/sendfile.h>
-#endif
-
-#ifdef USE_POSIX_ACL
-#include <sys/acl.h>
-#ifdef HAVE_NON_POSIX_ACL_EXTENSIONS
-#include <acl/libacl.h>
-#else
-#include <posixacladdons.h>
-#endif
-#endif
-
-#include <assert.h>
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <signal.h>
-#include <time.h>
-#include <utime.h>
-#include <unistd.h>
-#ifdef HAVE_STRING_H
-#include <string.h>
-#endif
-
-#include <tqvaluelist.h>
-#include <tqregexp.h>
-
-#include <dcopref.h>
-#include <kshred.h>
-#include <kdebug.h>
-#include <kurl.h>
-#include <kinstance.h>
-#include <ksimpleconfig.h>
-#include <ktempfile.h>
-#include <klocale.h>
-#include <tqfile.h>
-#include <tqstrlist.h>
-#include "file.h"
-#include <limits.h>
-#include <kprocess.h>
-#include <kmountpoint.h>
-#include <kstandarddirs.h>
-
-#ifdef HAVE_VOLMGT
-#include <volmgt.h>
-#include <sys/mnttab.h>
-#endif
-
-#include <kstandarddirs.h>
-#include <kio/ioslave_defaults.h>
-#include <klargefile.h>
-#include <kglobal.h>
-#include <kmimetype.h>
-
-using namespace TDEIO;
-
-#define MAX_IPC_SIZE (1024*32)
-
-static TQString testLogFile( const char *_filename );
-#ifdef USE_POSIX_ACL
-static TQString aclAsString( acl_t p_acl );
-static bool isExtendedACL( acl_t p_acl );
-static void appendACLAtoms( const TQCString & path, UDSEntry& entry,
- mode_t type, bool withACL );
-#endif
-
-extern "C" { KDE_EXPORT int kdemain(int argc, char **argv); }
-
-int kdemain( int argc, char **argv )
-{
- KLocale::setMainCatalogue("tdelibs");
- TDEInstance instance( "kio_file" );
- ( void ) TDEGlobal::locale();
-
- kdDebug(7101) << "Starting " << getpid() << endl;
-
- if (argc != 4)
- {
- fprintf(stderr, "Usage: kio_file protocol domain-socket1 domain-socket2\n");
- exit(-1);
- }
-
- FileProtocol slave(argv[2], argv[3]);
- slave.dispatchLoop();
-
- kdDebug(7101) << "Done" << endl;
- return 0;
-}
-
-
-FileProtocol::FileProtocol( const TQCString &pool, const TQCString &app ) : SlaveBase( "file", pool, app )
-{
- usercache.setAutoDelete( true );
- groupcache.setAutoDelete( true );
-}
-
-
-int FileProtocol::setACL( const char *path, mode_t perm, bool directoryDefault )
-{
- int ret = 0;
-#ifdef USE_POSIX_ACL
-
- const TQString ACLString = metaData( "ACL_STRING" );
- const TQString defaultACLString = metaData( "DEFAULT_ACL_STRING" );
- // Empty strings mean leave as is
- if ( !ACLString.isEmpty() ) {
- acl_t acl = 0;
- if ( ACLString == "ACL_DELETE" ) {
- // user told us to delete the extended ACL, so let's write only
- // the minimal (UNIX permission bits) part
- acl = acl_from_mode( perm );
- }
- acl = acl_from_text( ACLString.latin1() );
- if ( acl_valid( acl ) == 0 ) { // let's be safe
- ret = acl_set_file( path, ACL_TYPE_ACCESS, acl );
- kdDebug(7101) << "Set ACL on: " << path << " to: " << aclAsString( acl ) << endl;
- }
- acl_free( acl );
- if ( ret != 0 ) return ret; // better stop trying right away
- }
-
- if ( directoryDefault && !defaultACLString.isEmpty() ) {
- if ( defaultACLString == "ACL_DELETE" ) {
- // user told us to delete the default ACL, do so
- ret += acl_delete_def_file( path );
- } else {
- acl_t acl = acl_from_text( defaultACLString.latin1() );
- if ( acl_valid( acl ) == 0 ) { // let's be safe
- ret += acl_set_file( path, ACL_TYPE_DEFAULT, acl );
- kdDebug(7101) << "Set Default ACL on: " << path << " to: " << aclAsString( acl ) << endl;
- }
- acl_free( acl );
- }
- }
-#endif
- return ret;
-}
-
-void FileProtocol::chmod( const KURL& url, int permissions )
-{
- TQCString _path( TQFile::encodeName(url.path()) );
- /* FIXME: Should be atomic */
- if ( ::chmod( _path.data(), permissions ) == -1 ||
- ( setACL( _path.data(), permissions, false ) == -1 ) ||
- /* if not a directory, cannot set default ACLs */
- ( setACL( _path.data(), permissions, true ) == -1 && errno != ENOTDIR ) ) {
-
- switch (errno) {
- case EPERM:
- case EACCES:
- error( TDEIO::ERR_ACCESS_DENIED, url.path() );
- break;
- case ENOTSUP:
- error( TDEIO::ERR_UNSUPPORTED_ACTION, url.path() );
- break;
- case ENOSPC:
- error( TDEIO::ERR_DISK_FULL, url.path() );
- break;
- default:
- error( TDEIO::ERR_CANNOT_CHMOD, url.path() );
- }
- } else
- finished();
-}
-
-void FileProtocol::mkdir( const KURL& url, int permissions )
-{
- TQCString _path( TQFile::encodeName(url.path()));
-
- kdDebug(7101) << "mkdir(): " << _path << ", permission = " << permissions << endl;
-
- KDE_struct_stat buff;
- if ( KDE_stat( _path.data(), &buff ) == -1 ) {
- if ( ::mkdir( _path.data(), 0777 /*umask will be applied*/ ) != 0 ) {
- if ( errno == EACCES ) {
- error( TDEIO::ERR_ACCESS_DENIED, url.path() );
- return;
- } else if ( errno == ENOSPC ) {
- error( TDEIO::ERR_DISK_FULL, url.path() );
- return;
- } else {
- error( TDEIO::ERR_COULD_NOT_MKDIR, url.path() );
- return;
- }
- } else {
- if ( permissions != -1 )
- chmod( url, permissions );
- else
- finished();
- return;
- }
- }
-
- if ( S_ISDIR( buff.st_mode ) ) {
- kdDebug(7101) << "ERR_DIR_ALREADY_EXIST" << endl;
- error( TDEIO::ERR_DIR_ALREADY_EXIST, url.path() );
- return;
- }
- error( TDEIO::ERR_FILE_ALREADY_EXIST, url.path() );
- return;
-}
-
-void FileProtocol::get( const KURL& url )
-{
- if (!url.isLocalFile()) {
- KURL redir(url);
- redir.setProtocol(config()->readEntry("DefaultRemoteProtocol", "smb"));
- redirection(redir);
- finished();
- return;
- }
-
- TQCString _path( TQFile::encodeName(url.path()));
- KDE_struct_stat buff;
- if ( KDE_stat( _path.data(), &buff ) == -1 ) {
- if ( errno == EACCES )
- error( TDEIO::ERR_ACCESS_DENIED, url.path() );
- else
- error( TDEIO::ERR_DOES_NOT_EXIST, url.path() );
- return;
- }
-
- if ( S_ISDIR( buff.st_mode ) ) {
- error( TDEIO::ERR_IS_DIRECTORY, url.path() );
- return;
- }
- if ( !S_ISREG( buff.st_mode ) ) {
- error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, url.path() );
- return;
- }
-
- int fd = KDE_open( _path.data(), O_RDONLY);
- if ( fd < 0 ) {
- error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, url.path() );
- return;
- }
-
-#ifdef HAVE_FADVISE
- posix_fadvise( fd, 0, 0, POSIX_FADV_SEQUENTIAL);
-#endif
-
- // Determine the mimetype of the file to be retrieved, and emit it.
- // This is mandatory in all slaves (for KRun/BrowserRun to work).
- KMimeType::Ptr mt = KMimeType::findByURL( url, buff.st_mode, true /* local URL */ );
- emit mimeType( mt->name() );
-
- TDEIO::filesize_t processed_size = 0;
-
- TQString resumeOffset = metaData("resume");
- if ( !resumeOffset.isEmpty() )
- {
- bool ok;
- TDEIO::fileoffset_t offset = resumeOffset.toLongLong(&ok);
- if (ok && (offset > 0) && (offset < buff.st_size))
- {
- if (KDE_lseek(fd, offset, SEEK_SET) == offset)
- {
- canResume ();
- processed_size = offset;
- kdDebug( 7101 ) << "Resume offset: " << TDEIO::number(offset) << endl;
- }
- }
- }
-
- totalSize( buff.st_size );
-
- char buffer[ MAX_IPC_SIZE ];
- TQByteArray array;
-
- while( 1 )
- {
- int n = ::read( fd, buffer, MAX_IPC_SIZE );
- if (n == -1)
- {
- if (errno == EINTR)
- continue;
- error( TDEIO::ERR_COULD_NOT_READ, url.path());
- close(fd);
- return;
- }
- if (n == 0)
- break; // Finished
-
- array.setRawData(buffer, n);
- data( array );
- array.resetRawData(buffer, n);
-
- processed_size += n;
- processedSize( processed_size );
-
- //kdDebug( 7101 ) << "Processed: " << TDEIO::number (processed_size) << endl;
- }
-
- data( TQByteArray() );
-
- close( fd );
-
- processedSize( buff.st_size );
- finished();
-}
-
-static int
-write_all(int fd, const char *buf, size_t len)
-{
- while (len > 0)
- {
- ssize_t written = write(fd, buf, len);
- if (written < 0)
- {
- if (errno == EINTR)
- continue;
- return -1;
- }
- buf += written;
- len -= written;
- }
- return 0;
-}
-
-static bool
-same_inode(const KDE_struct_stat &src, const KDE_struct_stat &dest)
-{
- if (src.st_ino == dest.st_ino &&
- src.st_dev == dest.st_dev)
- return true;
-
- return false;
-}
-
-void FileProtocol::put( const KURL& url, int _mode, bool _overwrite, bool _resume )
-{
- TQString dest_orig = url.path();
- TQCString _dest_orig( TQFile::encodeName(dest_orig));
-
- kdDebug(7101) << "put(): " << dest_orig << ", mode=" << _mode << endl;
-
- TQString dest_part( dest_orig );
- dest_part += TQString::fromLatin1(".part");
- TQCString _dest_part( TQFile::encodeName(dest_part));
-
- KDE_struct_stat buff_orig;
- bool bOrigExists = (KDE_lstat( _dest_orig.data(), &buff_orig ) != -1);
- bool bPartExists = false;
- bool bMarkPartial = config()->readBoolEntry("MarkPartial", true);
-
- if (bMarkPartial)
- {
- KDE_struct_stat buff_part;
- bPartExists = (KDE_stat( _dest_part.data(), &buff_part ) != -1);
-
- if (bPartExists && !_resume && !_overwrite && buff_part.st_size > 0 && S_ISREG(buff_part.st_mode))
- {
- kdDebug(7101) << "FileProtocol::put : calling canResume with "
- << TDEIO::number(buff_part.st_size) << endl;
-
- // Maybe we can use this partial file for resuming
- // Tell about the size we have, and the app will tell us
- // if it's ok to resume or not.
- _resume = canResume( buff_part.st_size );
-
- kdDebug(7101) << "FileProtocol::put got answer " << _resume << endl;
- }
- }
-
- if ( bOrigExists && !_overwrite && !_resume)
- {
- if (S_ISDIR(buff_orig.st_mode))
- error( TDEIO::ERR_DIR_ALREADY_EXIST, dest_orig );
- else
- error( TDEIO::ERR_FILE_ALREADY_EXIST, dest_orig );
- return;
- }
-
- int result;
- TQString dest;
- TQCString _dest;
-
- int fd = -1;
-
- // Loop until we got 0 (end of data)
- do
- {
- TQByteArray buffer;
- dataReq(); // Request for data
- result = readData( buffer );
-
- if (result >= 0)
- {
- if (dest.isEmpty())
- {
- if (bMarkPartial)
- {
- kdDebug(7101) << "Appending .part extension to " << dest_orig << endl;
- dest = dest_part;
- if ( bPartExists && !_resume )
- {
- kdDebug(7101) << "Deleting partial file " << dest_part << endl;
- remove( _dest_part.data() );
- // Catch errors when we try to open the file.
- }
- }
- else
- {
- dest = dest_orig;
- if ( bOrigExists && !_resume )
- {
- kdDebug(7101) << "Deleting destination file " << dest_orig << endl;
- remove( _dest_orig.data() );
- // Catch errors when we try to open the file.
- }
- }
-
- _dest = TQFile::encodeName(dest);
-
- if ( _resume )
- {
- fd = KDE_open( _dest.data(), O_RDWR ); // append if resuming
- KDE_lseek(fd, 0, SEEK_END); // Seek to end
- }
- else
- {
- // WABA: Make sure that we keep writing permissions ourselves,
- // otherwise we can be in for a surprise on NFS.
- mode_t initialMode;
- if (_mode != -1)
- initialMode = _mode | S_IWUSR | S_IRUSR;
- else
- initialMode = 0666;
-
- fd = KDE_open(_dest.data(), O_CREAT | O_TRUNC | O_WRONLY, initialMode);
- }
-
- if ( fd < 0 )
- {
- kdDebug(7101) << "####################### COULD NOT WRITE " << dest << " _mode=" << _mode << endl;
- kdDebug(7101) << "errno==" << errno << "(" << strerror(errno) << ")" << endl;
- if ( errno == EACCES )
- error( TDEIO::ERR_WRITE_ACCESS_DENIED, dest );
- else
- error( TDEIO::ERR_CANNOT_OPEN_FOR_WRITING, dest );
- return;
- }
- }
-
- if (write_all( fd, buffer.data(), buffer.size()))
- {
- if ( errno == ENOSPC ) // disk full
- {
- error( TDEIO::ERR_DISK_FULL, dest_orig);
- result = -2; // means: remove dest file
- }
- else
- {
- kdWarning(7101) << "Couldn't write. Error:" << strerror(errno) << endl;
- error( TDEIO::ERR_COULD_NOT_WRITE, dest_orig);
- result = -1;
- }
- }
- }
- }
- while ( result > 0 );
-
- // An error occurred deal with it.
- if (result < 0)
- {
- kdDebug(7101) << "Error during 'put'. Aborting." << endl;
-
- if (fd != -1)
- {
- close(fd);
-
- KDE_struct_stat buff;
- if (bMarkPartial && KDE_stat( _dest.data(), &buff ) == 0)
- {
- int size = config()->readNumEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE);
- if (buff.st_size < size)
- remove(_dest.data());
- }
- }
-
- ::exit(255);
- }
-
- if ( fd == -1 ) // we got nothing to write out, so we never opened the file
- {
- finished();
- return;
- }
-
- if ( close(fd) )
- {
- kdWarning(7101) << "Error when closing file descriptor:" << strerror(errno) << endl;
- error( TDEIO::ERR_COULD_NOT_WRITE, dest_orig);
- return;
- }
-
- // after full download rename the file back to original name
- if ( bMarkPartial )
- {
- // If the original URL is a symlink and we were asked to overwrite it,
- // remove the symlink first. This ensures that we do not overwrite the
- // current source if the symlink points to it.
- if( _overwrite && S_ISLNK( buff_orig.st_mode ) )
- remove( _dest_orig.data() );
-
- if ( ::rename( _dest.data(), _dest_orig.data() ) )
- {
- kdWarning(7101) << " Couldn't rename " << _dest << " to " << _dest_orig << endl;
- error( TDEIO::ERR_CANNOT_RENAME_PARTIAL, dest_orig );
- return;
- }
- }
-
- // set final permissions
- if ( _mode != -1 && !_resume )
- {
- if (::chmod(_dest_orig.data(), _mode) != 0)
- {
- // couldn't chmod. Eat the error if the filesystem apparently doesn't support it.
- if ( TDEIO::testFileSystemFlag( _dest_orig, TDEIO::SupportsChmod ) )
- warning( i18n( "Could not change permissions for\n%1" ).arg( dest_orig ) );
- }
- }
-
- // set modification time
- const TQString mtimeStr = metaData( "modified" );
- if ( !mtimeStr.isEmpty() ) {
- TQDateTime dt = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( mtimeStr, Qt::ISODate ));
- if ( dt.isValid() ) {
- KDE_struct_stat dest_statbuf;
- if (KDE_stat( _dest_orig.data(), &dest_statbuf ) == 0) {
- struct utimbuf utbuf;
- utbuf.actime = dest_statbuf.st_atime; // access time, unchanged
- utbuf.modtime = dt.toTime_t(); // modification time
- kdDebug() << k_funcinfo << "setting modtime to " << utbuf.modtime << endl;
- utime( _dest_orig.data(), &utbuf );
- }
- }
-
- }
-
- // We have done our job => finish
- finished();
-}
-
-
-void FileProtocol::copy( const KURL &src, const KURL &dest,
- int _mode, bool _overwrite )
-{
- kdDebug(7101) << "copy(): " << src << " -> " << dest << ", mode=" << _mode << endl;
-
- TQCString _src( TQFile::encodeName(src.path()));
- TQCString _dest( TQFile::encodeName(dest.path()));
- KDE_struct_stat buff_src;
-#ifdef USE_POSIX_ACL
- acl_t acl;
-#endif
-
- if ( KDE_stat( _src.data(), &buff_src ) == -1 ) {
- if ( errno == EACCES )
- error( TDEIO::ERR_ACCESS_DENIED, src.path() );
- else
- error( TDEIO::ERR_DOES_NOT_EXIST, src.path() );
- return;
- }
-
- if ( S_ISDIR( buff_src.st_mode ) ) {
- error( TDEIO::ERR_IS_DIRECTORY, src.path() );
- return;
- }
- if ( S_ISFIFO( buff_src.st_mode ) || S_ISSOCK ( buff_src.st_mode ) ) {
- error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, src.path() );
- return;
- }
-
- KDE_struct_stat buff_dest;
- bool dest_exists = ( KDE_lstat( _dest.data(), &buff_dest ) != -1 );
- if ( dest_exists )
- {
- if (S_ISDIR(buff_dest.st_mode))
- {
- error( TDEIO::ERR_DIR_ALREADY_EXIST, dest.path() );
- return;
- }
-
- if ( same_inode( buff_dest, buff_src) )
- {
- error( TDEIO::ERR_IDENTICAL_FILES, dest.path() );
- return;
- }
-
- if (!_overwrite)
- {
- error( TDEIO::ERR_FILE_ALREADY_EXIST, dest.path() );
- return;
- }
-
- // If the destination is a symlink and overwrite is TRUE,
- // remove the symlink first to prevent the scenario where
- // the symlink actually points to current source!
- if (_overwrite && S_ISLNK(buff_dest.st_mode))
- {
- kdDebug(7101) << "copy(): LINK DESTINATION" << endl;
- remove( _dest.data() );
- }
- }
-
- int src_fd = KDE_open( _src.data(), O_RDONLY);
- if ( src_fd < 0 ) {
- error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, src.path() );
- return;
- }
-
-#ifdef HAVE_FADVISE
- posix_fadvise(src_fd,0,0,POSIX_FADV_SEQUENTIAL);
-#endif
- // WABA: Make sure that we keep writing permissions ourselves,
- // otherwise we can be in for a surprise on NFS.
- mode_t initialMode;
- if (_mode != -1)
- initialMode = _mode | S_IWUSR;
- else
- initialMode = 0666;
-
- int dest_fd = KDE_open(_dest.data(), O_CREAT | O_TRUNC | O_WRONLY, initialMode);
- if ( dest_fd < 0 ) {
- kdDebug(7101) << "###### COULD NOT WRITE " << dest.url() << endl;
- if ( errno == EACCES ) {
- error( TDEIO::ERR_WRITE_ACCESS_DENIED, dest.path() );
- } else {
- error( TDEIO::ERR_CANNOT_OPEN_FOR_WRITING, dest.path() );
- }
- close(src_fd);
- return;
- }
-
-#ifdef HAVE_FADVISE
- posix_fadvise(dest_fd,0,0,POSIX_FADV_SEQUENTIAL);
-#endif
-
-#ifdef USE_POSIX_ACL
- acl = acl_get_fd(src_fd);
- if ( acl && !isExtendedACL( acl ) ) {
- kdDebug(7101) << _dest.data() << " doesn't have extended ACL" << endl;
- acl_free( acl );
- acl = NULL;
- }
-#endif
- totalSize( buff_src.st_size );
-
- TDEIO::filesize_t processed_size = 0;
- char buffer[ MAX_IPC_SIZE ];
- int n;
-#ifdef USE_SENDFILE
- bool use_sendfile=buff_src.st_size < 0x7FFFFFFF;
-#endif
- while( 1 )
- {
-#ifdef USE_SENDFILE
- if (use_sendfile) {
- off_t sf = processed_size;
- n = ::sendfile( dest_fd, src_fd, &sf, MAX_IPC_SIZE );
- processed_size = sf;
- if ( n == -1 && errno == EINVAL ) { //not all filesystems support sendfile()
- kdDebug(7101) << "sendfile() not supported, falling back " << endl;
- use_sendfile = false;
- }
- }
- if (!use_sendfile)
-#endif
- n = ::read( src_fd, buffer, MAX_IPC_SIZE );
-
- if (n == -1)
- {
- if (errno == EINTR)
- continue;
-#ifdef USE_SENDFILE
- if ( use_sendfile ) {
- kdDebug(7101) << "sendfile() error:" << strerror(errno) << endl;
- if ( errno == ENOSPC ) // disk full
- {
- error( TDEIO::ERR_DISK_FULL, dest.path());
- remove( _dest.data() );
- }
- else {
- error( TDEIO::ERR_SLAVE_DEFINED,
- i18n("Cannot copy file from %1 to %2. (Errno: %3)")
- .arg( src.path() ).arg( dest.path() ).arg( errno ) );
- }
- } else
-#endif
- error( TDEIO::ERR_COULD_NOT_READ, src.path());
- close(src_fd);
- close(dest_fd);
-#ifdef USE_POSIX_ACL
- if (acl) acl_free(acl);
-#endif
- return;
- }
- if (n == 0)
- break; // Finished
-#ifdef USE_SENDFILE
- if ( !use_sendfile ) {
-#endif
- if (write_all( dest_fd, buffer, n))
- {
- close(src_fd);
- close(dest_fd);
-
- if ( errno == ENOSPC ) // disk full
- {
- error( TDEIO::ERR_DISK_FULL, dest.path());
- remove( _dest.data() );
- }
- else
- {
- kdWarning(7101) << "Couldn't write[2]. Error:" << strerror(errno) << endl;
- error( TDEIO::ERR_COULD_NOT_WRITE, dest.path());
- }
-#ifdef USE_POSIX_ACL
- if (acl) acl_free(acl);
-#endif
- return;
- }
- processed_size += n;
-#ifdef USE_SENDFILE
- }
-#endif
- processedSize( processed_size );
- }
-
- close( src_fd );
-
- if (close( dest_fd))
- {
- kdWarning(7101) << "Error when closing file descriptor[2]:" << strerror(errno) << endl;
- error( TDEIO::ERR_COULD_NOT_WRITE, dest.path());
-#ifdef USE_POSIX_ACL
- if (acl) acl_free(acl);
-#endif
- return;
- }
-
- // set final permissions
- if ( _mode != -1 )
- {
- if ( (::chmod(_dest.data(), _mode) != 0)
-#ifdef USE_POSIX_ACL
- || (acl && acl_set_file(_dest.data(), ACL_TYPE_ACCESS, acl) != 0)
-#endif
- )
- {
- // Eat the error if the filesystem apparently doesn't support chmod.
- if ( TDEIO::testFileSystemFlag( _dest, TDEIO::SupportsChmod ) )
- warning( i18n( "Could not change permissions for\n%1" ).arg( dest.path() ) );
- }
- }
-#ifdef USE_POSIX_ACL
- if (acl) acl_free(acl);
-#endif
-
- // copy access and modification time
- struct utimbuf ut;
- ut.actime = buff_src.st_atime;
- ut.modtime = buff_src.st_mtime;
- if ( ::utime( _dest.data(), &ut ) != 0 )
- {
- kdWarning() << TQString(TQString::fromLatin1("Couldn't preserve access and modification time for\n%1").arg( dest.path() )) << endl;
- }
-
- processedSize( buff_src.st_size );
- finished();
-}
-
-void FileProtocol::rename( const KURL &src, const KURL &dest,
- bool _overwrite )
-{
- TQCString _src( TQFile::encodeName(src.path()));
- TQCString _dest( TQFile::encodeName(dest.path()));
- KDE_struct_stat buff_src;
- if ( KDE_lstat( _src.data(), &buff_src ) == -1 ) {
- if ( errno == EACCES )
- error( TDEIO::ERR_ACCESS_DENIED, src.path() );
- else
- error( TDEIO::ERR_DOES_NOT_EXIST, src.path() );
- return;
- }
-
- KDE_struct_stat buff_dest;
- bool dest_exists = ( KDE_stat( _dest.data(), &buff_dest ) != -1 );
- if ( dest_exists )
- {
- if (S_ISDIR(buff_dest.st_mode))
- {
- error( TDEIO::ERR_DIR_ALREADY_EXIST, dest.path() );
- return;
- }
-
- if ( same_inode( buff_dest, buff_src) )
- {
- error( TDEIO::ERR_IDENTICAL_FILES, dest.path() );
- return;
- }
-
- if (!_overwrite)
- {
- error( TDEIO::ERR_FILE_ALREADY_EXIST, dest.path() );
- return;
- }
- }
-
- if ( ::rename( _src.data(), _dest.data()))
- {
- if (( errno == EACCES ) || (errno == EPERM)) {
- error( TDEIO::ERR_ACCESS_DENIED, dest.path() );
- }
- else if (errno == EXDEV) {
- error( TDEIO::ERR_UNSUPPORTED_ACTION, TQString::fromLatin1("rename"));
- }
- else if (errno == EROFS) { // The file is on a read-only filesystem
- error( TDEIO::ERR_CANNOT_DELETE, src.path() );
- }
- else {
- error( TDEIO::ERR_CANNOT_RENAME, src.path() );
- }
- return;
- }
-
- finished();
-}
-
-void FileProtocol::symlink( const TQString &target, const KURL &dest, bool overwrite )
-{
- // Assume dest is local too (wouldn't be here otherwise)
- if ( ::symlink( TQFile::encodeName( target ), TQFile::encodeName( dest.path() ) ) == -1 )
- {
- // Does the destination already exist ?
- if ( errno == EEXIST )
- {
- if ( overwrite )
- {
- // Try to delete the destination
- if ( unlink( TQFile::encodeName( dest.path() ) ) != 0 )
- {
- error( TDEIO::ERR_CANNOT_DELETE, dest.path() );
- return;
- }
- // Try again - this won't loop forever since unlink succeeded
- symlink( target, dest, overwrite );
- }
- else
- {
- KDE_struct_stat buff_dest;
- KDE_lstat( TQFile::encodeName( dest.path() ), &buff_dest );
- if (S_ISDIR(buff_dest.st_mode))
- error( TDEIO::ERR_DIR_ALREADY_EXIST, dest.path() );
- else
- error( TDEIO::ERR_FILE_ALREADY_EXIST, dest.path() );
- return;
- }
- }
- else
- {
- // Some error occurred while we tried to symlink
- error( TDEIO::ERR_CANNOT_SYMLINK, dest.path() );
- return;
- }
- }
- finished();
-}
-
-void FileProtocol::del( const KURL& url, bool isfile)
-{
- TQCString _path( TQFile::encodeName(url.path()));
- /*****
- * Delete files
- *****/
-
- if (isfile) {
- kdDebug( 7101 ) << "Deleting file "<< url.url() << endl;
-
- // TODO deletingFile( source );
-
- if ( unlink( _path.data() ) == -1 ) {
- if ((errno == EACCES) || (errno == EPERM))
- error( TDEIO::ERR_ACCESS_DENIED, url.path());
- else if (errno == EISDIR)
- error( TDEIO::ERR_IS_DIRECTORY, url.path());
- else
- error( TDEIO::ERR_CANNOT_DELETE, url.path() );
- return;
- }
- } else {
-
- /*****
- * Delete empty directory
- *****/
-
- kdDebug( 7101 ) << "Deleting directory " << url.url() << endl;
-
- if ( ::rmdir( _path.data() ) == -1 ) {
- if ((errno == EACCES) || (errno == EPERM))
- error( TDEIO::ERR_ACCESS_DENIED, url.path());
- else {
- kdDebug( 7101 ) << "could not rmdir " << perror << endl;
- error( TDEIO::ERR_COULD_NOT_RMDIR, url.path() );
- return;
- }
- }
- }
-
- finished();
-}
-
-
-TQString FileProtocol::getUserName( uid_t uid )
-{
- TQString *temp;
- temp = usercache.find( uid );
- if ( !temp ) {
- struct passwd *user = getpwuid( uid );
- if ( user ) {
- usercache.insert( uid, new TQString(TQString::fromLatin1(user->pw_name)) );
- return TQString::fromLatin1( user->pw_name );
- }
- else
- return TQString::number( uid );
- }
- else
- return *temp;
-}
-
-TQString FileProtocol::getGroupName( gid_t gid )
-{
- TQString *temp;
- temp = groupcache.find( gid );
- if ( !temp ) {
- struct group *grp = getgrgid( gid );
- if ( grp ) {
- groupcache.insert( gid, new TQString(TQString::fromLatin1(grp->gr_name)) );
- return TQString::fromLatin1( grp->gr_name );
- }
- else
- return TQString::number( gid );
- }
- else
- return *temp;
-}
-
-
-
-bool FileProtocol::createUDSEntry( const TQString & filename, const TQCString & path, UDSEntry & entry,
- short int details, bool withACL )
-{
- assert(entry.count() == 0); // by contract :-)
- // Note: details = 0 (only "file or directory or symlink or doesn't exist") isn't implemented
- // because there's no real performance penalty in kio_file for returning the complete
- // details. Please consider doing it in your kioslave if you're using this one as a model :)
- UDSAtom atom;
- atom.m_uds = TDEIO::UDS_NAME;
- atom.m_str = filename;
- entry.append( atom );
-
- mode_t type;
- mode_t access;
- KDE_struct_stat buff;
-
- if ( KDE_lstat( path.data(), &buff ) == 0 ) {
-
- if (S_ISLNK(buff.st_mode)) {
-
- char buffer2[ 1000 ];
- int n = readlink( path.data(), buffer2, 1000 );
- if ( n != -1 ) {
- buffer2[ n ] = 0;
- }
-
- atom.m_uds = TDEIO::UDS_LINK_DEST;
- atom.m_str = TQFile::decodeName( buffer2 );
- entry.append( atom );
-
- // A symlink -> follow it only if details>1
- if ( details > 1 && KDE_stat( path.data(), &buff ) == -1 ) {
- // It is a link pointing to nowhere
- type = S_IFMT - 1;
- access = S_IRWXU | S_IRWXG | S_IRWXO;
-
- atom.m_uds = TDEIO::UDS_FILE_TYPE;
- atom.m_long = type;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = access;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_SIZE;
- atom.m_long = 0L;
- entry.append( atom );
-
- goto notype;
-
- }
- }
- } else {
- // kdWarning() << "lstat didn't work on " << path.data() << endl;
- return false;
- }
-
- type = buff.st_mode & S_IFMT; // extract file type
- access = buff.st_mode & 07777; // extract permissions
-
- atom.m_uds = TDEIO::UDS_FILE_TYPE;
- atom.m_long = type;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = access;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_SIZE;
- atom.m_long = buff.st_size;
- entry.append( atom );
-
-#ifdef USE_POSIX_ACL
- /* Append an atom indicating whether the file has extended acl information
- * and if withACL is specified also one with the acl itself. If it's a directory
- * and it has a default ACL, also append that. */
- appendACLAtoms( path, entry, type, withACL );
-#endif
-
- notype:
- atom.m_uds = TDEIO::UDS_MODIFICATION_TIME;
- atom.m_long = buff.st_mtime;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_USER;
- atom.m_str = getUserName( buff.st_uid );
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_GROUP;
- atom.m_str = getGroupName( buff.st_gid );
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_ACCESS_TIME;
- atom.m_long = buff.st_atime;
- entry.append( atom );
-
- // Note: buff.st_ctime isn't the creation time !
- // We made that mistake for KDE 2.0, but it's in fact the
- // "file status" change time, which we don't care about.
-
- return true;
-}
-
-void FileProtocol::stat( const KURL & url )
-{
- if (!url.isLocalFile()) {
- KURL redir(url);
- redir.setProtocol(config()->readEntry("DefaultRemoteProtocol", "smb"));
- redirection(redir);
- kdDebug(7101) << "redirecting to " << redir.url() << endl;
- finished();
- return;
- }
-
- /* directories may not have a slash at the end if
- * we want to stat() them; it requires that we
- * change into it .. which may not be allowed
- * stat("/is/unaccessible") -> rwx------
- * stat("/is/unaccessible/") -> EPERM H.Z.
- * This is the reason for the -1
- */
- TQCString _path( TQFile::encodeName(url.path(-1)));
-
- TQString sDetails = metaData(TQString::fromLatin1("details"));
- int details = sDetails.isEmpty() ? 2 : sDetails.toInt();
- kdDebug(7101) << "FileProtocol::stat details=" << details << endl;
-
- UDSEntry entry;
- if ( !createUDSEntry( url.fileName(), _path, entry, details, true /*with acls*/ ) )
- {
- error( TDEIO::ERR_DOES_NOT_EXIST, url.path(-1) );
- return;
- }
-#if 0
-///////// debug code
- TDEIO::UDSEntry::ConstIterator it = entry.begin();
- for( ; it != entry.end(); it++ ) {
- switch ((*it).m_uds) {
- case TDEIO::UDS_FILE_TYPE:
- kdDebug(7101) << "File Type : " << (mode_t)((*it).m_long) << endl;
- break;
- case TDEIO::UDS_ACCESS:
- kdDebug(7101) << "Access permissions : " << (mode_t)((*it).m_long) << endl;
- break;
- case TDEIO::UDS_USER:
- kdDebug(7101) << "User : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_GROUP:
- kdDebug(7101) << "Group : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_NAME:
- kdDebug(7101) << "Name : " << ((*it).m_str.ascii() ) << endl;
- //m_strText = decodeFileName( (*it).m_str );
- break;
- case TDEIO::UDS_URL:
- kdDebug(7101) << "URL : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_MIME_TYPE:
- kdDebug(7101) << "MimeType : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_LINK_DEST:
- kdDebug(7101) << "LinkDest : " << ((*it).m_str.ascii() ) << endl;
- break;
- case TDEIO::UDS_EXTENDED_ACL:
- kdDebug(7101) << "Contains extended ACL " << endl;
- break;
- }
- }
- MetaData::iterator it1 = mOutgoingMetaData.begin();
- for ( ; it1 != mOutgoingMetaData.end(); it1++ ) {
- kdDebug(7101) << it1.key() << " = " << it1.data() << endl;
- }
-/////////
-#endif
- statEntry( entry );
-
- finished();
-}
-
-void FileProtocol::listDir( const KURL& url)
-{
- kdDebug(7101) << "========= LIST " << url.url() << " =========" << endl;
- if (!url.isLocalFile()) {
- KURL redir(url);
- redir.setProtocol(config()->readEntry("DefaultRemoteProtocol", "smb"));
- redirection(redir);
- kdDebug(7101) << "redirecting to " << redir.url() << endl;
- finished();
- return;
- }
-
- TQCString _path( TQFile::encodeName(url.path()));
-
- KDE_struct_stat buff;
- if ( KDE_stat( _path.data(), &buff ) == -1 ) {
- error( TDEIO::ERR_DOES_NOT_EXIST, url.path() );
- return;
- }
-
- if ( !S_ISDIR( buff.st_mode ) ) {
- error( TDEIO::ERR_IS_FILE, url.path() );
- return;
- }
-
- DIR *dp = 0L;
- KDE_struct_dirent *ep;
-
- dp = opendir( _path.data() );
- if ( dp == 0 ) {
- switch (errno)
- {
-#ifdef ENOMEDIUM
- case ENOMEDIUM:
- error( ERR_SLAVE_DEFINED,
- i18n( "No media in device for %1" ).arg( url.path() ) );
- break;
-#endif
- default:
- error( TDEIO::ERR_CANNOT_ENTER_DIRECTORY, url.path() );
- break;
- }
- return;
- }
-
- // Don't make this a TQStringList. The locale file name we get here
- // should be passed intact to createUDSEntry to avoid problems with
- // files where TQFile::encodeName(TQFile::decodeName(a)) != a.
- TQStrList entryNames;
-
- while ( ( ep = KDE_readdir( dp ) ) != 0L )
- entryNames.append( ep->d_name );
-
- closedir( dp );
- totalSize( entryNames.count() );
-
- /* set the current dir to the path to speed up
- in not having to pass an absolute path.
- We restore the path later to get out of the
- path - the kernel wouldn't unmount or delete
- directories we keep as active directory. And
- as the slave runs in the background, it's hard
- to see for the user what the problem would be */
-#if !defined(PATH_MAX) && defined(__GLIBC__)
- char *path_buffer;
- path_buffer = getcwd(NULL, 0);
-#else
- char path_buffer[PATH_MAX];
- (void) getcwd(path_buffer, PATH_MAX - 1);
-#endif
- if ( chdir( _path.data() ) ) {
- if (errno == EACCES)
- error(ERR_ACCESS_DENIED, _path);
- else
- error(ERR_CANNOT_ENTER_DIRECTORY, _path);
- finished();
- }
-
- UDSEntry entry;
- TQStrListIterator it(entryNames);
- for (; it.current(); ++it) {
- entry.clear();
- if ( createUDSEntry( TQFile::decodeName(*it),
- *it /* we can use the filename as relative path*/,
- entry, 2, true ) )
- listEntry( entry, false);
- //else
- // ;//Well, this should never happen... but with wrong encoding names
- }
-
- listEntry( entry, true ); // ready
-
- kdDebug(7101) << "============= COMPLETED LIST ============" << endl;
-
- chdir(path_buffer);
-#if !defined(PATH_MAX) && defined(__GLIBC__)
- free(path_buffer);
-#endif
-
- finished();
-}
-
-/*
-void FileProtocol::testDir( const TQString& path )
-{
- TQCString _path( TQFile::encodeName(path));
- KDE_struct_stat buff;
- if ( KDE_stat( _path.data(), &buff ) == -1 ) {
- error( TDEIO::ERR_DOES_NOT_EXIST, path );
- return;
- }
-
- if ( S_ISDIR( buff.st_mode ) )
- isDirectory();
- else
- isFile();
-
- finished();
-}
-*/
-
-void FileProtocol::special( const TQByteArray &data)
-{
- int tmp;
- TQDataStream stream(data, IO_ReadOnly);
-
- stream >> tmp;
- switch (tmp) {
- case 1:
- {
- TQString fstype, dev, point;
- TQ_INT8 iRo;
-
- stream >> iRo >> fstype >> dev >> point;
-
- bool ro = ( iRo != 0 );
-
- kdDebug(7101) << "MOUNTING fstype=" << fstype << " dev=" << dev << " point=" << point << " ro=" << ro << endl;
- bool ok = pmount( dev );
- if (ok)
- finished();
- else
- mount( ro, fstype.ascii(), dev, point );
-
- }
- break;
- case 2:
- {
- TQString point;
- stream >> point;
- bool ok = pumount( point );
- if (ok)
- finished();
- else
- unmount( point );
- }
- break;
-
- case 3:
- {
- TQString filename;
- stream >> filename;
- KShred shred( filename );
- connect( &shred, TQT_SIGNAL( processedSize( TDEIO::filesize_t ) ),
- this, TQT_SLOT( slotProcessedSize( TDEIO::filesize_t ) ) );
- connect( &shred, TQT_SIGNAL( infoMessage( const TQString & ) ),
- this, TQT_SLOT( slotInfoMessage( const TQString & ) ) );
- if (!shred.shred())
- error( TDEIO::ERR_CANNOT_DELETE, filename );
- else
- finished();
- break;
- }
- default:
- break;
- }
-}
-
-// Connected to KShred
-void FileProtocol::slotProcessedSize( TDEIO::filesize_t bytes )
-{
- kdDebug(7101) << "FileProtocol::slotProcessedSize (" << (unsigned int) bytes << ")" << endl;
- processedSize( bytes );
-}
-
-// Connected to KShred
-void FileProtocol::slotInfoMessage( const TQString & msg )
-{
- kdDebug(7101) << "FileProtocol::slotInfoMessage (" << msg << ")" << endl;
- infoMessage( msg );
-}
-
-void FileProtocol::mount( bool _ro, const char *_fstype, const TQString& _dev, const TQString& _point )
-{
- kdDebug(7101) << "FileProtocol::mount _fstype=" << _fstype << endl;
- TQCString buffer;
-
-#ifdef HAVE_VOLMGT
- /*
- * support for Solaris volume management
- */
- TQString err;
- TQCString devname = TQFile::encodeName( _dev );
-
- if( volmgt_running() ) {
-// kdDebug(7101) << "VOLMGT: vold ok." << endl;
- if( volmgt_check( devname.data() ) == 0 ) {
- kdDebug(7101) << "VOLMGT: no media in "
- << devname.data() << endl;
- err = i18n("No Media inserted or Media not recognized.");
- error( TDEIO::ERR_COULD_NOT_MOUNT, err );
- return;
- } else {
- kdDebug(7101) << "VOLMGT: " << devname.data()
- << ": media ok" << endl;
- finished();
- return;
- }
- } else {
- err = i18n("\"vold\" is not running.");
- kdDebug(7101) << "VOLMGT: " << err << endl;
- error( TDEIO::ERR_COULD_NOT_MOUNT, err );
- return;
- }
-#else
-
-
- KTempFile tmpFile;
- TQCString tmpFileC = TQFile::encodeName(tmpFile.name());
- const char *tmp = tmpFileC.data();
- TQCString dev;
- if ( _dev.startsWith( "LABEL=" ) ) { // turn LABEL=foo into -L foo (#71430)
- TQString labelName = _dev.mid( 6 );
- dev = "-L ";
- dev += TQFile::encodeName( TDEProcess::quote( labelName ) ); // is it correct to assume same encoding as filesystem?
- } else if ( _dev.startsWith( "UUID=" ) ) { // and UUID=bar into -U bar
- TQString uuidName = _dev.mid( 5 );
- dev = "-U ";
- dev += TQFile::encodeName( TDEProcess::quote( uuidName ) );
- }
- else
- dev = TQFile::encodeName( TDEProcess::quote(_dev) ); // get those ready to be given to a shell
-
- TQCString point = TQFile::encodeName( TDEProcess::quote(_point) );
- bool fstype_empty = !_fstype || !*_fstype;
- TQCString fstype = TDEProcess::quote(_fstype).latin1(); // good guess
- TQCString readonly = _ro ? "-r" : "";
- TQString epath = TQString::fromLatin1(getenv("PATH"));
- TQString path = TQString::fromLatin1("/sbin:/bin");
- if(!epath.isEmpty())
- path += TQString::fromLatin1(":") + epath;
- TQString mountProg = TDEGlobal::dirs()->findExe("mount", path);
- if (mountProg.isEmpty()){
- error( TDEIO::ERR_COULD_NOT_MOUNT, i18n("Could not find program \"mount\""));
- return;
- }
-
- // Two steps, in case mount doesn't like it when we pass all options
- for ( int step = 0 ; step <= 1 ; step++ )
- {
- // Mount using device only if no fstype nor mountpoint (KDE-1.x like)
- if ( !_dev.isEmpty() && _point.isEmpty() && fstype_empty )
- buffer.sprintf( "%s %s 2>%s", mountProg.latin1(), dev.data(), tmp );
- else
- // Mount using the mountpoint, if no fstype nor device (impossible in first step)
- if ( !_point.isEmpty() && _dev.isEmpty() && fstype_empty )
- buffer.sprintf( "%s %s 2>%s", mountProg.latin1(), point.data(), tmp );
- else
- // mount giving device + mountpoint but no fstype
- if ( !_point.isEmpty() && !_dev.isEmpty() && fstype_empty )
- buffer.sprintf( "%s %s %s %s 2>%s", mountProg.latin1(), readonly.data(), dev.data(), point.data(), tmp );
- else
- // mount giving device + mountpoint + fstype
-#if defined(__svr4__) && defined(__sun__) // MARCO for Solaris 8 and I
- // believe this is true for SVR4 in general
- buffer.sprintf( "%s -F %s %s %s %s 2>%s"
- mountProg.latin1()
- fstype.data()
- _ro ? "-oro" : ""
- dev.data()
- point.data()
- tmp );
-#else
- buffer.sprintf( "%s %s -t %s %s %s 2>%s", mountProg.latin1(), readonly.data(),
- fstype.data(), dev.data(), point.data(), tmp );
-#endif
-
- kdDebug(7101) << buffer << endl;
-
- int mount_ret = system( buffer.data() );
-
- TQString err = testLogFile( tmp );
- if ( err.isEmpty() && mount_ret == 0)
- {
- finished();
- return;
- }
- else
- {
- // Didn't work - or maybe we just got a warning
- TQString mp = TDEIO::findDeviceMountPoint( _dev );
- // Is the device mounted ?
- if ( !mp.isEmpty() && mount_ret == 0)
- {
- kdDebug(7101) << "mount got a warning: " << err << endl;
- warning( err );
- finished();
- return;
- }
- else
- {
- if ( (step == 0) && !_point.isEmpty())
- {
- kdDebug(7101) << err << endl;
- kdDebug(7101) << "Mounting with those options didn't work, trying with only mountpoint" << endl;
- fstype = "";
- fstype_empty = true;
- dev = "";
- // The reason for trying with only mountpoint (instead of
- // only device) is that some people (hi Malte!) have the
- // same device associated with two mountpoints
- // for different fstypes, like /dev/fd0 /mnt/e2floppy and
- // /dev/fd0 /mnt/dosfloppy.
- // If the user has the same mountpoint associated with two
- // different devices, well they shouldn't specify the
- // mountpoint but just the device.
- }
- else
- {
- error( TDEIO::ERR_COULD_NOT_MOUNT, err );
- return;
- }
- }
- }
- }
-#endif /* ! HAVE_VOLMGT */
-}
-
-
-void FileProtocol::unmount( const TQString& _point )
-{
- TQCString buffer;
-
- KTempFile tmpFile;
- TQCString tmpFileC = TQFile::encodeName(tmpFile.name());
- TQString err;
- const char *tmp = tmpFileC.data();
-
-#ifdef HAVE_VOLMGT
- /*
- * support for Solaris volume management
- */
- char *devname;
- char *ptr;
- FILE *mnttab;
- struct mnttab mnt;
-
- if( volmgt_running() ) {
- kdDebug(7101) << "VOLMGT: looking for "
- << _point.local8Bit() << endl;
-
- if( (mnttab = KDE_fopen( MNTTAB, "r" )) == NULL ) {
- err = "couldn't open mnttab";
- kdDebug(7101) << "VOLMGT: " << err << endl;
- error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
- return;
- }
-
- /*
- * since there's no way to derive the device name from
- * the mount point through the volmgt library (and
- * media_findname() won't work in this case), we have to
- * look ourselves...
- */
- devname = NULL;
- rewind( mnttab );
- while( getmntent( mnttab, &mnt ) == 0 ) {
- if( strcmp( _point.local8Bit(), mnt.mnt_mountp ) == 0 ){
- devname = mnt.mnt_special;
- break;
- }
- }
- fclose( mnttab );
-
- if( devname == NULL ) {
- err = "not in mnttab";
- kdDebug(7101) << "VOLMGT: "
- << TQFile::encodeName(_point).data()
- << ": " << err << endl;
- error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
- return;
- }
-
- /*
- * strip off the directory name (volume name)
- * the eject(1) command will handle unmounting and
- * physically eject the media (if possible)
- */
- ptr = strrchr( devname, '/' );
- *ptr = '\0';
- TQCString qdevname(TQFile::encodeName(TDEProcess::quote(TQFile::decodeName(TQCString(devname)))).data());
- buffer.sprintf( "/usr/bin/eject %s 2>%s", qdevname.data(), tmp );
- kdDebug(7101) << "VOLMGT: eject " << qdevname << endl;
-
- /*
- * from eject(1): exit status == 0 => need to manually eject
- * exit status == 4 => media was ejected
- */
-// if( WEXITSTATUS( system( buffer.local8Bit() )) == 4 ) {
- if( WEXITSTATUS( system( buffer.data() )) == 4 ) { // Fix for TQString -> QCString?
- /*
- * this is not an error, so skip "testLogFile()"
- * to avoid wrong/confusing error popup
- */
- unlink( tmp );
- finished();
- return;
- }
- } else {
- /*
- * eject(1) should do its job without vold(1M) running,
- * so we probably could call eject anyway, but since the
- * media is mounted now, vold must've died for some reason
- * during the user's session, so it should be restarted...
- */
- err = i18n("\"vold\" is not running.");
- kdDebug(7101) << "VOLMGT: " << err << endl;
- error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
- return;
- }
-#else
- TQString epath = getenv("PATH");
- TQString path = TQString::fromLatin1("/sbin:/bin");
- if (!epath.isEmpty())
- path += ":" + epath;
- TQString umountProg = TDEGlobal::dirs()->findExe("umount", path);
-
- if (umountProg.isEmpty()) {
- error( TDEIO::ERR_COULD_NOT_UNMOUNT, i18n("Could not find program \"umount\""));
- return;
- }
- buffer.sprintf( "%s %s 2>%s", umountProg.latin1(), TQFile::encodeName(TDEProcess::quote(_point)).data(), tmp );
- system( buffer.data() );
-#endif /* HAVE_VOLMGT */
-
- err = testLogFile( tmp );
-
- if (err.contains("fstab") || err.contains("root")) {
- TQString olderr;
- err = TQString::null;
-
- DCOPRef d("kded", "mediamanager");
- d.setDCOPClient ( dcopClient() );
- DCOPReply reply = d.call("properties", _point);
- TQString udi;
-
- if ( reply.isValid() ) {
- TQStringList list = reply;
- if (list.size())
- udi = list[0];
- }
-
- if (!udi.isEmpty())
- reply = d.call("unmount", udi);
-
- if (udi.isEmpty() || !reply.isValid())
- err = olderr;
- else if (reply.isValid())
- reply.get(err);
- }
-
- if ( err.isEmpty() )
- finished();
- else
- error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
-}
-
-/*************************************
- *
- * pmount handling
- *
- *************************************/
-
-bool FileProtocol::pmount(const TQString &dev)
-{
- TQString epath = getenv("PATH");
- TQString path = TQString::fromLatin1("/sbin:/bin");
- if (!epath.isEmpty())
- path += ":" + epath;
- TQString pmountProg = TDEGlobal::dirs()->findExe("pmount", path);
-
- if (pmountProg.isEmpty())
- return false;
-
- TQCString buffer;
- buffer.sprintf( "%s %s", TQFile::encodeName(pmountProg).data(),
- TQFile::encodeName(TDEProcess::quote(dev)).data() );
-
- int res = system( buffer.data() );
-
- return res==0;
-}
-
-bool FileProtocol::pumount(const TQString &point)
-{
- TQString real_point = KStandardDirs::realPath(point);
-
- KMountPoint::List mtab = KMountPoint::currentMountPoints();
-
- KMountPoint::List::const_iterator it = mtab.begin();
- KMountPoint::List::const_iterator end = mtab.end();
-
- TQString dev;
-
- for (; it!=end; ++it)
- {
- TQString tmp = (*it)->mountedFrom();
- TQString mp = (*it)->mountPoint();
- mp = KStandardDirs::realPath(mp);
-
- if (mp==real_point)
- dev = KStandardDirs::realPath(tmp);
- }
-
- if (dev.isEmpty()) return false;
- if (dev.endsWith("/")) dev.truncate(dev.length()-1);
-
- TQString epath = getenv("PATH");
- TQString path = TQString::fromLatin1("/sbin:/bin");
- if (!epath.isEmpty())
- path += ":" + epath;
- TQString pumountProg = TDEGlobal::dirs()->findExe("pumount", path);
-
- if (pumountProg.isEmpty())
- return false;
-
- TQCString buffer;
- buffer.sprintf( "%s %s", TQFile::encodeName(pumountProg).data(),
- TQFile::encodeName(TDEProcess::quote(dev)).data() );
-
- int res = system( buffer.data() );
-
- return res==0;
-}
-
-/*************************************
- *
- * Utilities
- *
- *************************************/
-
-static TQString testLogFile( const char *_filename )
-{
- char buffer[ 1024 ];
- KDE_struct_stat buff;
-
- TQString result;
-
- KDE_stat( _filename, &buff );
- int size = buff.st_size;
- if ( size == 0 ) {
- unlink( _filename );
- return result;
- }
-
- FILE * f = KDE_fopen( _filename, "rb" );
- if ( f == 0L ) {
- unlink( _filename );
- result = i18n("Could not read %1").arg(TQFile::decodeName(_filename));
- return result;
- }
-
- result = "";
- const char *p = "";
- while ( p != 0L ) {
- p = fgets( buffer, sizeof(buffer)-1, f );
- if ( p != 0L )
- result += TQString::fromLocal8Bit(buffer);
- }
-
- fclose( f );
-
- unlink( _filename );
-
- return result;
-}
-
-/*************************************
- *
- * ACL handling helpers
- *
- *************************************/
-#ifdef USE_POSIX_ACL
-
-static bool isExtendedACL( acl_t acl )
-{
- return ( acl_equiv_mode( acl, 0 ) != 0 );
-}
-
-static TQString aclAsString( acl_t acl )
-{
- char *aclString = acl_to_text( acl, 0 );
- TQString ret = TQString::fromLatin1( aclString );
- acl_free( (void*)aclString );
- return ret;
-}
-
-static void appendACLAtoms( const TQCString & path, UDSEntry& entry, mode_t type, bool withACL )
-{
- // first check for a noop
-#ifdef HAVE_NON_POSIX_ACL_EXTENSIONS
- if ( acl_extended_file( path.data() ) == 0 ) return;
-#endif
-
- acl_t acl = 0;
- acl_t defaultAcl = 0;
- UDSAtom atom;
- bool isDir = S_ISDIR( type );
- // do we have an acl for the file, and/or a default acl for the dir, if it is one?
- if ( ( acl = acl_get_file( path.data(), ACL_TYPE_ACCESS ) ) ) {
- if ( !isExtendedACL( acl ) ) {
- acl_free( acl );
- acl = 0;
- }
- }
-
- /* Sadly libacl does not provided a means of checking for extended ACL and default
- * ACL separately. Since a directory can have both, we need to check again. */
- if ( isDir )
- defaultAcl = acl_get_file( path.data(), ACL_TYPE_DEFAULT );
-
- if ( acl || defaultAcl ) {
- kdDebug(7101) << path.data() << " has extended ACL entries " << endl;
- atom.m_uds = TDEIO::UDS_EXTENDED_ACL;
- atom.m_long = 1;
- entry.append( atom );
- }
- if ( withACL ) {
- if ( acl ) {
- atom.m_uds = TDEIO::UDS_ACL_STRING;
- atom.m_str = aclAsString( acl );
- entry.append( atom );
- kdDebug(7101) << path.data() << "ACL: " << atom.m_str << endl;
- }
- if ( defaultAcl ) {
- atom.m_uds = TDEIO::UDS_DEFAULT_ACL_STRING;
- atom.m_str = aclAsString( defaultAcl );
- entry.append( atom );
- kdDebug(7101) << path.data() << "DEFAULT ACL: " << atom.m_str << endl;
- }
- }
- if ( acl ) acl_free( acl );
- if ( defaultAcl ) acl_free( defaultAcl );
-}
-#endif
-
-#include "file.moc"
diff --git a/kioslave/file/file.h b/kioslave/file/file.h
deleted file mode 100644
index 9f9d98995..000000000
--- a/kioslave/file/file.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- Copyright (C) 2000-2002 Stephan Kulow <coolo@kde.org>
- Copyright (C) 2000-2002 David Faure <faure@kde.org>
- Copyright (C) 2000-2002 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License (LGPL) as published by the Free Software Foundation;
- either version 2 of the License, or (at your option) any later
- version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef __file_h__
-#define __file_h__ "$Id$"
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <stdio.h>
-#include <unistd.h>
-
-#include <tqobject.h>
-#include <tqintdict.h>
-#include <tqstring.h>
-#include <tqvaluelist.h>
-
-#include <kio/global.h>
-#include <kio/slavebase.h>
-
-// Note that this header file is installed, so think twice
-// before breaking binary compatibility (read: it is forbidden :)
-
-class FileProtocol : public TQObject, public TDEIO::SlaveBase
-{
- Q_OBJECT
-public:
- FileProtocol( const TQCString &pool, const TQCString &app);
- virtual ~FileProtocol() { }
-
- virtual void get( const KURL& url );
- virtual void put( const KURL& url, int permissions,
- bool overwrite, bool resume );
- virtual void copy( const KURL &src, const KURL &dest,
- int permissions, bool overwrite );
- virtual void rename( const KURL &src, const KURL &dest,
- bool overwrite );
- virtual void symlink( const TQString &target, const KURL &dest,
- bool overwrite );
-
- virtual void stat( const KURL& url );
- virtual void listDir( const KURL& url );
- virtual void mkdir( const KURL& url, int permissions );
- virtual void chmod( const KURL& url, int permissions );
- virtual void del( const KURL& url, bool isfile);
-
- /**
- * Special commands supported by this slave:
- * 1 - mount
- * 2 - unmount
- * 3 - shred
- */
- virtual void special( const TQByteArray &data);
- void unmount( const TQString& point );
- void mount( bool _ro, const char *_fstype, const TQString& dev, const TQString& point );
- bool pumount( const TQString &point );
- bool pmount( const TQString &dev );
-
-protected slots:
- void slotProcessedSize( TDEIO::filesize_t _bytes );
- void slotInfoMessage( const TQString & msg );
-
-protected:
-
- bool createUDSEntry( const TQString & filename, const TQCString & path, TDEIO::UDSEntry & entry,
- short int details, bool withACL );
- int setACL( const char *path, mode_t perm, bool _directoryDefault );
-
- TQString getUserName( uid_t uid );
- TQString getGroupName( gid_t gid );
-
- TQIntDict<TQString> usercache; // maps long ==> TQString *
- TQIntDict<TQString> groupcache;
-
- class FileProtocolPrivate;
- FileProtocolPrivate *d;
-};
-
-#endif
diff --git a/kioslave/file/file.protocol b/kioslave/file/file.protocol
deleted file mode 100644
index ae3487999..000000000
--- a/kioslave/file/file.protocol
+++ /dev/null
@@ -1,15 +0,0 @@
-[Protocol]
-exec=kio_file
-protocol=file
-input=none
-output=filesystem
-listing=Name,Type,Size,Date,AccessDate,Access,Owner,Group,Link
-reading=true
-writing=true
-makedir=true
-deleting=true
-linking=true
-moving=true
-maxInstances=4
-DocPath=kioslave/file.html
-Class=:local
diff --git a/kioslave/ftp/CMakeLists.txt b/kioslave/ftp/CMakeLists.txt
deleted file mode 100644
index e0287639b..000000000
--- a/kioslave/ftp/CMakeLists.txt
+++ /dev/null
@@ -1,44 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore/network
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install( FILES ftp.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-##### kio_ftp ###################################
-
-set( target kio_ftp )
-
-set( ${target}_SRCS
- ftp.cc
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kioslave/ftp/ftp.cc b/kioslave/ftp/ftp.cc
deleted file mode 100644
index 3d29e2b65..000000000
--- a/kioslave/ftp/ftp.cc
+++ /dev/null
@@ -1,2675 +0,0 @@
-// -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 2; -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-
- Recommended reading explaining FTP details and quirks:
- http://cr.yp.to/ftp.html (by D.J. Bernstein)
-*/
-
-
-#define KIO_FTP_PRIVATE_INCLUDE
-#include "ftp.h"
-
-#include <sys/stat.h>
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
-
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <netdb.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <signal.h>
-
-#if TIME_WITH_SYS_TIME
-#include <time.h>
-#endif
-
-#include <tqdir.h>
-
-#include <kdebug.h>
-#include <klocale.h>
-#include <kinstance.h>
-#include <kmimemagic.h>
-#include <kmimetype.h>
-#include <ksockaddr.h>
-#include <tdesocketaddress.h>
-#include <kio/ioslave_defaults.h>
-#include <kio/slaveconfig.h>
-#include <kremoteencoding.h>
-#include <klargefile.h>
-
-#ifdef HAVE_STRTOLL
- #define charToLongLong(a) strtoll(a, 0, 10)
-#else
- #define charToLongLong(a) strtol(a, 0, 10)
-#endif
-
-// JPF: a remark on coding style (2004-03-06):
-// Some calls to TQString::fromLatin1() were removed from the code. In most places
-// the KDE code relies on implicit creation of QStrings. Also Qt has a lot of
-// const char* overloads, so that using TQString::fromLatin1() can be ineffectient!
-
-#define FTP_LOGIN "anonymous"
-#define FTP_PASSWD "anonymous@"
-
-//#undef kdDebug
-#define ENABLE_CAN_RESUME
-
-// JPF: somebody should find a better solution for this or move this to KIO
-// JPF: anyhow, in KDE 3.2.0 I found diffent MAX_IPC_SIZE definitions!
-namespace TDEIO {
- enum buffersizes
- { /**
- * largest buffer size that should be used to transfer data between
- * KIO slaves using the data() function
- */
- maximumIpcSize = 32 * 1024,
- /**
- * this is a reasonable value for an initial read() that a KIO slave
- * can do to obtain data via a slow network connection.
- */
- initialIpcSize = 2 * 1024,
- /**
- * recommended size of a data block passed to findBufferFileType()
- */
- mimimumMimeSize = 1024
- };
-
- // JPF: this helper was derived from write_all in file.cc (FileProtocol).
- static // JPF: in ftp.cc we make it static
- /**
- * This helper handles some special issues (blocking and interrupted
- * system call) when writing to a file handle.
- *
- * @return 0 on success or an error code on failure (ERR_COULD_NOT_WRITE,
- * ERR_DISK_FULL, ERR_CONNECTION_BROKEN).
- */
- int WriteToFile(int fd, const char *buf, size_t len)
- {
- while (len > 0)
- { // JPF: shouldn't there be a KDE_write?
- ssize_t written = write(fd, buf, len);
- if (written >= 0)
- { buf += written;
- len -= written;
- continue;
- }
- switch(errno)
- { case EINTR: continue;
- case EPIPE: return ERR_CONNECTION_BROKEN;
- case ENOSPC: return ERR_DISK_FULL;
- default: return ERR_COULD_NOT_WRITE;
- }
- }
- return 0;
- }
-}
-
-TDEIO::filesize_t Ftp::UnknownSize = (TDEIO::filesize_t)-1;
-
-using namespace TDEIO;
-
-extern "C" { KDE_EXPORT int kdemain(int argc, char **argv); }
-
-int kdemain( int argc, char **argv )
-{
- KLocale::setMainCatalogue("tdelibs");
- TDEInstance instance( "kio_ftp" );
- ( void ) TDEGlobal::locale();
-
- kdDebug(7102) << "Starting " << getpid() << endl;
-
- if (argc != 4)
- {
- fprintf(stderr, "Usage: kio_ftp protocol domain-socket1 domain-socket2\n");
- exit(-1);
- }
-
- Ftp slave(argv[2], argv[3]);
- slave.dispatchLoop();
-
- kdDebug(7102) << "Done" << endl;
- return 0;
-}
-
-//===============================================================================
-// FtpTextReader Read Text lines from a file (or socket)
-//===============================================================================
-
-void FtpTextReader::textClear()
-{ m_iTextLine = m_iTextBuff = 0;
- m_szText[0] = 0;
- m_bTextEOF = m_bTextTruncated = false;
-}
-
-int FtpTextReader::textRead(FtpSocket *pSock)
-{
- // if we have still buffered data then move it to the left
- char* pEOL;
- if(m_iTextLine < m_iTextBuff)
- { m_iTextBuff -= m_iTextLine;
- memmove(m_szText, m_szText+m_iTextLine, m_iTextBuff);
- pEOL = (char*)memchr(m_szText, '\n', m_iTextBuff); // have a complete line?
- }
- else
- { m_iTextBuff = 0;
- pEOL = NULL;
- }
- m_bTextEOF = m_bTextTruncated = false;
-
- // read data from the control socket until a complete line is read
- int nBytes;
- while(pEOL == NULL)
- {
- if(m_iTextBuff > textReadLimit)
- { m_bTextTruncated = true;
- m_iTextBuff = textReadLimit;
- }
- nBytes = pSock->read(m_szText+m_iTextBuff, sizeof(m_szText)-m_iTextBuff);
- if(nBytes <= 0)
- {
- // This error can occur after the server closed the connection (after a timeout)
- if(nBytes < 0)
- pSock->debugMessage("textRead failed");
- m_bTextEOF = true;
- pEOL = m_szText + m_iTextBuff;
- }
- else
- {
- m_iTextBuff += nBytes;
- pEOL = (char*)memchr(m_szText, '\n', m_iTextBuff);
- }
- }
-
- nBytes = pEOL - m_szText;
- m_iTextLine = nBytes + 1;
-
- if(nBytes > textReadLimit)
- { m_bTextTruncated = true;
- nBytes = textReadLimit;
- }
- if(nBytes && m_szText[nBytes-1] == '\r')
- nBytes--;
- m_szText[nBytes] = 0;
- return nBytes;
-}
-
-//===============================================================================
-// FtpSocket Helper Class for Data or Control Connections
-//===============================================================================
-void FtpSocket::debugMessage(const char* pszMsg) const
-{
- kdDebug(7102) << m_pszName << ": " << pszMsg << endl;
-}
-
-int FtpSocket::errorMessage(int iErrorCode, const char* pszMsg) const
-{
- kdError(7102) << m_pszName << ": " << pszMsg << endl;
- return iErrorCode;
-}
-
-int FtpSocket::connectSocket(int iTimeOutSec, bool bControl)
-{
- closeSocket();
-
- int iOpt = bControl ? KExtendedSocket::inetSocket
- : KExtendedSocket::noResolve;
- setSocketFlags(iOpt | socketFlags());
- setTimeout(iTimeOutSec);
-
- int iCon = KExtendedSocket::connect();
- if(iCon < 0)
- { int iErrorCode = (status() == IO_LookupError)
- ? ERR_UNKNOWN_HOST : ERR_COULD_NOT_CONNECT;
- TQString strMsg = KExtendedSocket::strError(status(), systemError());
- strMsg.prepend("connect failed (code %1): ");
- return errorMessage(iErrorCode, TQString(strMsg.arg(iCon)).latin1());
- }
- if( !setAddressReusable(true) )
- return errorMessage(ERR_COULD_NOT_CREATE_SOCKET, "setAddressReusable failed");
-
- if(!bControl)
- { int on=1;
- if( !setSocketOption(SO_KEEPALIVE, (char *)&on, sizeof(on)) )
- errorMessage(0, "Keepalive not allowed");
-
- struct linger lng = { 1, 120 };
- if( !setSocketOption(SO_LINGER, (char *)&lng, sizeof (lng)) )
- errorMessage(0, "Linger mode was not allowed.");
- }
-
- debugMessage("connected");
- return 0;
-}
-
-void FtpSocket::closeSocket()
-{
- if(m_server != -1 || fd() != -1)
- debugMessage("disconnected");
-
- if(m_server != -1)
- {
- ::shutdown(m_server, SHUT_RDWR);
- ::close(m_server);
- m_server = -1;
- }
- if(socketStatus() > nothing)
- reset();
- textClear();
-}
-
-bool FtpSocket::setSocketOption(int opt, char*arg, socklen_t len) const
-{
- return (setsockopt(sock(), SOL_SOCKET, opt, arg, len) != -1);
-}
-
-//===============================================================================
-// Ftp
-//===============================================================================
-
-Ftp::Ftp( const TQCString &pool, const TQCString &app )
- : SlaveBase( "ftp", pool, app )
-{
- // init the socket data
- m_data = m_control = NULL;
- ftpCloseControlConnection();
-
- // init other members
- m_port = 0;
- kdDebug(7102) << "Ftp::Ftp()" << endl;
-}
-
-
-Ftp::~Ftp()
-{
- kdDebug(7102) << "Ftp::~Ftp()" << endl;
- closeConnection();
-}
-
-/**
- * This closes a data connection opened by ftpOpenDataConnection().
- */
-void Ftp::ftpCloseDataConnection()
-{
- if(m_data != NULL)
- { delete m_data;
- m_data = NULL;
- }
-}
-
-/**
- * This closes a control connection opened by ftpOpenControlConnection() and reinits the
- * related states. This method gets called from the constructor with m_control = NULL.
- */
-void Ftp::ftpCloseControlConnection()
-{
- m_extControl = 0;
- if(m_control)
- delete m_control;
- m_control = NULL;
- m_cDataMode = 0;
- m_bLoggedOn = false; // logon needs control connction
- m_bTextMode = false;
- m_bBusy = false;
-}
-
-/**
- * Returns the last response from the server (iOffset >= 0) -or- reads a new response
- * (iOffset < 0). The result is returned (with iOffset chars skipped for iOffset > 0).
- */
-const char* Ftp::ftpResponse(int iOffset)
-{
- assert(m_control != NULL); // must have control connection socket
- const char *pTxt = m_control->textLine();
-
- // read the next line ...
- if(iOffset < 0)
- {
- int iMore = 0;
- m_iRespCode = 0;
-
- // If the server sends multiline responses "nnn-text" we loop here until
- // a final "nnn text" line is reached. Only data from the final line will
- // be stored. Some servers (OpenBSD) send a single "nnn-" followed by
- // optional lines that start with a space and a final "nnn text" line.
- do {
- int nBytes = m_control->textRead();
- int iCode = atoi(pTxt);
- if(iCode > 0) m_iRespCode = iCode;
-
- // ignore lines starting with a space in multiline response
- if(iMore != 0 && pTxt[0] == 32)
- ;
- // otherwise the line should start with "nnn-" or "nnn "
- else if(nBytes < 4 || iCode < 100)
- iMore = 0;
- // we got a valid line, now check for multiline responses ...
- else if(iMore == 0 && pTxt[3] == '-')
- iMore = iCode;
- // "nnn " ends multiline mode ...
- else if(iMore != 0 && (iMore != iCode || pTxt[3] != '-'))
- iMore = 0;
-
- if(iMore != 0)
- kdDebug(7102) << " > " << pTxt << endl;
- } while(iMore != 0);
- kdDebug(7102) << "resp> " << pTxt << endl;
-
- m_iRespType = (m_iRespCode > 0) ? m_iRespCode / 100 : 0;
- }
-
- // return text with offset ...
- while(iOffset-- > 0 && pTxt[0])
- pTxt++;
- return pTxt;
-}
-
-
-void Ftp::closeConnection()
-{
- if(m_control != NULL || m_data != NULL)
- kdDebug(7102) << "Ftp::closeConnection m_bLoggedOn=" << m_bLoggedOn << " m_bBusy=" << m_bBusy << endl;
-
- if(m_bBusy) // ftpCloseCommand not called
- {
- kdWarning(7102) << "Ftp::closeConnection Abandoned data stream" << endl;
- ftpCloseDataConnection();
- }
-
- if(m_bLoggedOn) // send quit
- {
- if( !ftpSendCmd( "quit", 0 ) || (m_iRespType != 2) )
- kdWarning(7102) << "Ftp::closeConnection QUIT returned error: " << m_iRespCode << endl;
- }
-
- // close the data and control connections ...
- ftpCloseDataConnection();
- ftpCloseControlConnection();
-}
-
-void Ftp::setHost( const TQString& _host, int _port, const TQString& _user,
- const TQString& _pass )
-{
- kdDebug(7102) << "Ftp::setHost (" << getpid() << "): " << _host << endl;
-
- m_proxyURL = metaData("UseProxy");
- m_bUseProxy = (m_proxyURL.isValid() && m_proxyURL.protocol() == "ftp");
-
- if ( m_host != _host || m_port != _port ||
- m_user != _user || m_pass != _pass )
- closeConnection();
-
- m_host = _host;
- m_port = _port;
- m_user = _user;
- m_pass = _pass;
-}
-
-void Ftp::openConnection()
-{
- ftpOpenConnection(loginExplicit);
-}
-
-bool Ftp::ftpOpenConnection (LoginMode loginMode)
-{
- // check for implicit login if we are already logged on ...
- if(loginMode == loginImplicit && m_bLoggedOn)
- {
- assert(m_control != NULL); // must have control connection socket
- return true;
- }
-
- kdDebug(7102) << "ftpOpenConnection " << m_host << ":" << m_port << " "
- << m_user << " [password hidden]" << endl;
-
- infoMessage( i18n("Opening connection to host %1").arg(m_host) );
-
- if ( m_host.isEmpty() )
- {
- error( ERR_UNKNOWN_HOST, TQString::null );
- return false;
- }
-
- assert( !m_bLoggedOn );
-
- m_initialPath = TQString::null;
- m_currentPath = TQString::null;
-
- TQString host = m_bUseProxy ? m_proxyURL.host() : m_host;
- unsigned short int port = m_bUseProxy ? m_proxyURL.port() : m_port;
-
- if (!ftpOpenControlConnection(host, port) )
- return false; // error emitted by ftpOpenControlConnection
- infoMessage( i18n("Connected to host %1").arg(m_host) );
-
- if(loginMode != loginDefered)
- {
- m_bLoggedOn = ftpLogin();
- if( !m_bLoggedOn )
- return false; // error emitted by ftpLogin
- }
-
- m_bTextMode = config()->readBoolEntry("textmode", false);
- connected();
- return true;
-}
-
-
-/**
- * Called by @ref openConnection. It opens the control connection to the ftp server.
- *
- * @return true on success.
- */
-bool Ftp::ftpOpenControlConnection( const TQString &host, unsigned short int port )
-{
- if ( port == 0 ) {
- struct servent *pse;
- if ( ( pse = getservbyname( "ftp", "tcp" ) ) == NULL )
- port = 21;
- else
- port = ntohs(pse->s_port);
- }
-
- // implicitly close, then try to open a new connection ...
- closeConnection();
- int iErrorCode = ERR_OUT_OF_MEMORY;
- TQString sErrorMsg;
- m_control = new FtpSocket("CNTL");
- if(m_control != NULL)
- {
- // now connect to the server and read the login message ...
- m_control->setAddress(host, port);
- iErrorCode = m_control->connectSocket(connectTimeout(), true);
- sErrorMsg = host;
-
- // on connect success try to read the server message...
- if(iErrorCode == 0)
- {
- const char* psz = ftpResponse(-1);
- if(m_iRespType != 2)
- { // login not successful, do we have an message text?
- if(psz[0])
- sErrorMsg = i18n("%1.\n\nReason: %2").arg(host).arg(psz);
- iErrorCode = ERR_COULD_NOT_CONNECT;
- }
- }
- }
-
- // if there was a problem - report it ...
- if(iErrorCode == 0) // OK, return success
- return true;
- closeConnection(); // clean-up on error
- error(iErrorCode, sErrorMsg);
- return false;
-}
-
-/**
- * Called by @ref openConnection. It logs us in.
- * @ref m_initialPath is set to the current working directory
- * if logging on was successful.
- *
- * @return true on success.
- */
-bool Ftp::ftpLogin()
-{
- infoMessage( i18n("Sending login information") );
-
- assert( !m_bLoggedOn );
-
- TQString user = m_user;
- TQString pass = m_pass;
-
- if ( config()->readBoolEntry("EnableAutoLogin") )
- {
- TQString au = config()->readEntry("autoLoginUser");
- if ( !au.isEmpty() )
- {
- user = au;
- pass = config()->readEntry("autoLoginPass");
- }
- }
-
- // Try anonymous login if both username/password
- // information is blank.
- if (user.isEmpty() && pass.isEmpty())
- {
- user = FTP_LOGIN;
- pass = FTP_PASSWD;
- }
-
- AuthInfo info;
- info.url.setProtocol( "ftp" );
- info.url.setHost( m_host );
- info.url.setPort( m_port );
- info.url.setUser( user );
-
- TQCString tempbuf;
- int failedAuth = 0;
-
- do
- {
- // Check the cache and/or prompt user for password if 1st
- // login attempt failed OR the user supplied a login name,
- // but no password.
- if ( failedAuth > 0 || (!user.isEmpty() && pass.isEmpty()) )
- {
- TQString errorMsg;
- kdDebug(7102) << "Prompting user for login info..." << endl;
-
- // Ask user if we should retry after when login fails!
- if( failedAuth > 0 )
- {
- errorMsg = i18n("Message sent:\nLogin using username=%1 and "
- "password=[hidden]\n\nServer replied:\n%2\n\n"
- ).arg(user).arg(ftpResponse(0));
- }
-
- if ( user != FTP_LOGIN )
- info.username = user;
-
- info.prompt = i18n("You need to supply a username and a password "
- "to access this site.");
- info.commentLabel = i18n( "Site:" );
- info.comment = i18n("<b>%1</b>").arg( m_host );
- info.keepPassword = true; // Prompt the user for persistence as well.
- info.readOnly = (!m_user.isEmpty() && m_user != FTP_LOGIN);
-
- bool disablePassDlg = config()->readBoolEntry( "DisablePassDlg", false );
- if ( disablePassDlg || !openPassDlg( info, errorMsg ) )
- {
- error( ERR_USER_CANCELED, m_host );
- return false;
- }
- else
- {
- user = info.username;
- pass = info.password;
- }
- }
-
- tempbuf = "USER ";
- tempbuf += user.latin1();
- if ( m_bUseProxy )
- {
- tempbuf += '@';
- tempbuf += m_host.latin1();
- if ( m_port > 0 && m_port != DEFAULT_FTP_PORT )
- {
- tempbuf += ':';
- tempbuf += TQString::number(m_port).latin1();
- }
- }
-
- kdDebug(7102) << "Sending Login name: " << tempbuf << endl;
-
- bool loggedIn = ( ftpSendCmd(tempbuf) && (m_iRespCode == 230) );
- bool needPass = (m_iRespCode == 331);
- // Prompt user for login info if we do not
- // get back a "230" or "331".
- if ( !loggedIn && !needPass )
- {
- kdDebug(7102) << "Login failed: " << ftpResponse(0) << endl;
- ++failedAuth;
- continue; // Well we failed, prompt the user please!!
- }
-
- if( needPass )
- {
- tempbuf = "pass ";
- tempbuf += pass.latin1();
- kdDebug(7102) << "Sending Login password: " << "[protected]" << endl;
- loggedIn = ( ftpSendCmd(tempbuf) && (m_iRespCode == 230) );
- }
-
- if ( loggedIn )
- {
- // Do not cache the default login!!
- if( user != FTP_LOGIN && pass != FTP_PASSWD )
- cacheAuthentication( info );
- failedAuth = -1;
- }
-
- } while( ++failedAuth );
-
-
- kdDebug(7102) << "Login OK" << endl;
- infoMessage( i18n("Login OK") );
-
- // Okay, we're logged in. If this is IIS 4, switch dir listing style to Unix:
- // Thanks to jk@soegaard.net (Jens Kristian Søgaard) for this hint
- if( ftpSendCmd("SYST") && (m_iRespType == 2) )
- {
- if( !strncmp( ftpResponse(0), "215 Windows_NT", 14 ) ) // should do for any version
- {
- ftpSendCmd( "site dirstyle" );
- // Check if it was already in Unix style
- // Patch from Keith Refson <Keith.Refson@earth.ox.ac.uk>
- if( !strncmp( ftpResponse(0), "200 MSDOS-like directory output is on", 37 ))
- //It was in Unix style already!
- ftpSendCmd( "site dirstyle" );
- // windows won't support chmod before KDE konquers their desktop...
- m_extControl |= chmodUnknown;
- }
- }
- else
- kdWarning(7102) << "SYST failed" << endl;
-
- if ( config()->readBoolEntry ("EnableAutoLoginMacro") )
- ftpAutoLoginMacro ();
-
- // Get the current working directory
- kdDebug(7102) << "Searching for pwd" << endl;
- if( !ftpSendCmd("PWD") || (m_iRespType != 2) )
- {
- kdDebug(7102) << "Couldn't issue pwd command" << endl;
- error( ERR_COULD_NOT_LOGIN, i18n("Could not login to %1.").arg(m_host) ); // or anything better ?
- return false;
- }
-
- TQString sTmp = remoteEncoding()->decode( ftpResponse(3) );
- int iBeg = sTmp.find('"');
- int iEnd = sTmp.findRev('"');
- if(iBeg > 0 && iBeg < iEnd)
- {
- m_initialPath = sTmp.mid(iBeg+1, iEnd-iBeg-1);
- if(m_initialPath[0] != '/') m_initialPath.prepend('/');
- kdDebug(7102) << "Initial path set to: " << m_initialPath << endl;
- m_currentPath = m_initialPath;
- }
- return true;
-}
-
-void Ftp::ftpAutoLoginMacro ()
-{
- TQString macro = metaData( "autoLoginMacro" );
-
- if ( macro.isEmpty() )
- return;
-
- TQStringList list = TQStringList::split('\n', macro);
-
- for(TQStringList::Iterator it = list.begin() ; it != list.end() ; ++it )
- {
- if ( (*it).startsWith("init") )
- {
- list = TQStringList::split( '\\', macro);
- it = list.begin();
- ++it; // ignore the macro name
-
- for( ; it != list.end() ; ++it )
- {
- // TODO: Add support for arbitrary commands
- // besides simply changing directory!!
- if ( (*it).startsWith( "cwd" ) )
- ftpFolder( (*it).mid(4).stripWhiteSpace(), false );
- }
-
- break;
- }
- }
-}
-
-
-/**
- * ftpSendCmd - send a command (@p cmd) and read response
- *
- * @param maxretries number of time it should retry. Since it recursively
- * calls itself if it can't read the answer (this happens especially after
- * timeouts), we need to limit the recursiveness ;-)
- *
- * return true if any response received, false on error
- */
-bool Ftp::ftpSendCmd( const TQCString& cmd, int maxretries )
-{
- assert(m_control != NULL); // must have control connection socket
-
- if ( cmd.find( '\r' ) != -1 || cmd.find( '\n' ) != -1)
- {
- kdWarning(7102) << "Invalid command received (contains CR or LF):"
- << cmd.data() << endl;
- error( ERR_UNSUPPORTED_ACTION, m_host );
- return false;
- }
-
- // Don't print out the password...
- bool isPassCmd = (cmd.left(4).lower() == "pass");
- if ( !isPassCmd )
- kdDebug(7102) << "send> " << cmd.data() << endl;
- else
- kdDebug(7102) << "send> pass [protected]" << endl;
-
- // Send the message...
- TQCString buf = cmd;
- buf += "\r\n"; // Yes, must use CR/LF - see http://cr.yp.to/ftp/request.html
- int num = m_control->write(buf.data(), buf.length());
-
- // If we were able to successfully send the command, then we will
- // attempt to read the response. Otherwise, take action to re-attempt
- // the login based on the maximum number of retires specified...
- if( num > 0 )
- ftpResponse(-1);
- else
- { m_iRespType = m_iRespCode = 0;
- m_control->textClear();
- }
-
- // If respCh is NULL or the response is 421 (Timed-out), we try to re-send
- // the command based on the value of maxretries.
- if( (m_iRespType <= 0) || (m_iRespCode == 421) )
- {
- // We have not yet logged on...
- if (!m_bLoggedOn)
- {
- // The command was sent from the ftpLogin function, i.e. we are actually
- // attempting to login in. NOTE: If we already sent the username, we
- // return false and let the user decide whether (s)he wants to start from
- // the beginning...
- if (maxretries > 0 && !isPassCmd)
- {
- closeConnection ();
- if( ftpOpenConnection(loginDefered) )
- ftpSendCmd ( cmd, maxretries - 1 );
- }
-
- return false;
- }
- else
- {
- if ( maxretries < 1 )
- return false;
- else
- {
- kdDebug(7102) << "Was not able to communicate with " << m_host << endl
- << "Attempting to re-establish connection." << endl;
-
- closeConnection(); // Close the old connection...
- openConnection(); // Attempt to re-establish a new connection...
-
- if (!m_bLoggedOn)
- {
- if (m_control != NULL) // if openConnection succeeded ...
- {
- kdDebug(7102) << "Login failure, aborting" << endl;
- error (ERR_COULD_NOT_LOGIN, m_host);
- closeConnection ();
- }
- return false;
- }
-
- kdDebug(7102) << "Logged back in, re-issuing command" << endl;
-
- // If we were able to login, resend the command...
- if (maxretries)
- maxretries--;
-
- return ftpSendCmd( cmd, maxretries );
- }
- }
- }
-
- return true;
-}
-
-/*
- * ftpOpenPASVDataConnection - set up data connection, using PASV mode
- *
- * return 1 if successful, 0 otherwise
- * doesn't set error message, since non-pasv mode will always be tried if
- * this one fails
- */
-int Ftp::ftpOpenPASVDataConnection()
-{
- assert(m_control != NULL); // must have control connection socket
- assert(m_data == NULL); // ... but no data connection
-
- // Check that we can do PASV
- const TDESocketAddress *sa = m_control->peerAddress();
- if (sa != NULL && sa->family() != PF_INET)
- return ERR_INTERNAL; // no PASV for non-PF_INET connections
-
- const KInetSocketAddress *sin = static_cast<const KInetSocketAddress*>(sa);
-
- if (m_extControl & pasvUnknown)
- return ERR_INTERNAL; // already tried and got "unknown command"
-
- m_bPasv = true;
-
- /* Let's PASsiVe*/
- if( !ftpSendCmd("PASV") || (m_iRespType != 2) )
- {
- kdDebug(7102) << "PASV attempt failed" << endl;
- // unknown command?
- if( m_iRespType == 5 )
- {
- kdDebug(7102) << "disabling use of PASV" << endl;
- m_extControl |= pasvUnknown;
- }
- return ERR_INTERNAL;
- }
-
- // The usual answer is '227 Entering Passive Mode. (160,39,200,55,6,245)'
- // but anonftpd gives '227 =160,39,200,55,6,245'
- int i[6];
- const char *start = strchr(ftpResponse(3), '(');
- if ( !start )
- start = strchr(ftpResponse(3), '=');
- if ( !start ||
- ( sscanf(start, "(%d,%d,%d,%d,%d,%d)",&i[0], &i[1], &i[2], &i[3], &i[4], &i[5]) != 6 &&
- sscanf(start, "=%d,%d,%d,%d,%d,%d", &i[0], &i[1], &i[2], &i[3], &i[4], &i[5]) != 6 ) )
- {
- kdError(7102) << "parsing IP and port numbers failed. String parsed: " << start << endl;
- return ERR_INTERNAL;
- }
-
- // Make hostname and port number ...
- int port = i[4] << 8 | i[5];
-
- // we ignore the host part on purpose for two reasons
- // a) it might be wrong anyway
- // b) it would make us being suceptible to a port scanning attack
-
- // now connect the data socket ...
- m_data = new FtpSocket("PASV");
- m_data->setAddress(sin->nodeName(), port);
-
- kdDebug(7102) << "Connecting to " << sin->nodeName() << " on port " << port << endl;
- return m_data->connectSocket(connectTimeout(), false);
-}
-
-/*
- * ftpOpenEPSVDataConnection - opens a data connection via EPSV
- */
-int Ftp::ftpOpenEPSVDataConnection()
-{
- assert(m_control != NULL); // must have control connection socket
- assert(m_data == NULL); // ... but no data connection
-
- const TDESocketAddress *sa = m_control->peerAddress();
- int portnum;
- // we are sure sa is a KInetSocketAddress, because we asked for KExtendedSocket::inetSocket
- // when we connected
- const KInetSocketAddress *sin = static_cast<const KInetSocketAddress*>(sa);
-
- if (m_extControl & epsvUnknown || sa == NULL)
- return ERR_INTERNAL;
-
- m_bPasv = true;
- if( !ftpSendCmd("EPSV") || (m_iRespType != 2) )
- {
- // unknown command?
- if( m_iRespType == 5 )
- {
- kdDebug(7102) << "disabling use of EPSV" << endl;
- m_extControl |= epsvUnknown;
- }
- return ERR_INTERNAL;
- }
-
- const char *start = strchr(ftpResponse(3), '|');
- if ( !start || sscanf(start, "|||%d|", &portnum) != 1)
- return ERR_INTERNAL;
-
- m_data = new FtpSocket("EPSV");
- m_data->setAddress(sin->nodeName(), portnum);
- return m_data->connectSocket(connectTimeout(), false) != 0;
-}
-
-/*
- * ftpOpenEPRTDataConnection
- * @return 0 on success, ERR_INTERNAL if mode not acceptable -or- a fatal error code
- */
-int Ftp::ftpOpenEPRTDataConnection()
-{
- assert(m_control != NULL); // must have control connection socket
- assert(m_data == NULL); // ... but no data connection
-
- // yes, we are sure this is a KInetSocketAddress
- const KInetSocketAddress *sin = static_cast<const KInetSocketAddress*>(m_control->localAddress());
- m_bPasv = false;
- if (m_extControl & eprtUnknown || sin == NULL)
- return ERR_INTERNAL;
-
- m_data = new FtpSocket("EPRT");
- m_data->setHost(sin->nodeName());
- m_data->setPort(0); // setting port to 0 will make us bind to a random, free port
- m_data->setSocketFlags(KExtendedSocket::noResolve | KExtendedSocket::passiveSocket |
- KExtendedSocket::inetSocket);
-
- if (m_data->listen(1) < 0)
- return ERR_COULD_NOT_LISTEN;
-
- sin = static_cast<const KInetSocketAddress*>(m_data->localAddress());
- if (sin == NULL)
- return ERR_INTERNAL;
-
- // TQString command = TQString::fromLatin1("eprt |%1|%2|%3|").arg(sin->ianaFamily())
- // .arg(sin->nodeName())
- // .arg(sin->port());
- TQCString command;
- command.sprintf("eprt |%d|%s|%d|", sin->ianaFamily(),
- sin->nodeName().latin1(), sin->port());
-
- // FIXME! Encoding for hostnames?
- if( ftpSendCmd(command) && (m_iRespType == 2) )
- return 0;
-
- // unknown command?
- if( m_iRespType == 5 )
- {
- kdDebug(7102) << "disabling use of EPRT" << endl;
- m_extControl |= eprtUnknown;
- }
- return ERR_INTERNAL;
-}
-
-/*
- * ftpOpenDataConnection - set up data connection
- *
- * The routine calls several ftpOpenXxxxConnection() helpers to find
- * the best connection mode. If a helper cannot connect if returns
- * ERR_INTERNAL - so this is not really an error! All other error
- * codes are treated as fatal, e.g. they are passed back to the caller
- * who is responsible for calling error(). ftpOpenPortDataConnection
- * can be called as last try and it does never return ERR_INTERNAL.
- *
- * @return 0 if successful, err code otherwise
- */
-int Ftp::ftpOpenDataConnection()
-{
- // make sure that we are logged on and have no data connection...
- assert( m_bLoggedOn );
- ftpCloseDataConnection();
-
- int iErrCode = 0;
- int iErrCodePASV = 0; // Remember error code from PASV
-
- // First try passive (EPSV & PASV) modes
- if( !config()->readBoolEntry("DisablePassiveMode", false) )
- {
- iErrCode = ftpOpenPASVDataConnection();
- if(iErrCode == 0)
- return 0; // success
- iErrCodePASV = iErrCode;
- ftpCloseDataConnection();
-
- if( !config()->readBoolEntry("DisableEPSV", false) )
- {
- iErrCode = ftpOpenEPSVDataConnection();
- if(iErrCode == 0)
- return 0; // success
- ftpCloseDataConnection();
- }
-
- // if we sent EPSV ALL already and it was accepted, then we can't
- // use active connections any more
- if (m_extControl & epsvAllSent)
- return iErrCodePASV ? iErrCodePASV : iErrCode;
- }
-
- if( !config()->readBoolEntry("DisableEPRT", false) )
- {
- iErrCode = ftpOpenEPRTDataConnection();
- if(iErrCode == 0)
- return 0; // success
- ftpCloseDataConnection();
- }
-
- // fall back to port mode
- iErrCode = ftpOpenPortDataConnection();
- if(iErrCode == 0)
- return 0; // success
-
- ftpCloseDataConnection();
- // prefer to return the error code from PASV if any, since that's what should have worked in the first place
- return iErrCodePASV ? iErrCodePASV : iErrCode;
-}
-
-/*
- * ftpOpenPortDataConnection - set up data connection
- *
- * @return 0 if successfull, err code otherwise (but never ERR_INTERNAL
- * because this is the last connection mode that is tried)
- */
-int Ftp::ftpOpenPortDataConnection()
-{
- assert(m_control != NULL); // must have control connection socket
- assert(m_data == NULL); // ... but no data connection
-
- m_bPasv = false;
-
- // create a socket, bind it and let it listen ...
- m_data = new FtpSocket("PORT");
- m_data->setSocketFlags(KExtendedSocket::noResolve | KExtendedSocket::passiveSocket |
- KExtendedSocket::inetSocket);
-
- // yes, we are sure this is a KInetSocketAddress
- const KInetSocketAddress* pAddr = static_cast<const KInetSocketAddress*>(m_control->localAddress());
- m_data->setAddress(pAddr->nodeName(), "0");
- m_data->setAddressReusable(true);
-
- if(m_data->listen(1) < 0)
- return ERR_COULD_NOT_LISTEN;
- struct linger lng = { 0, 0 };
- if ( !m_data->setSocketOption(SO_LINGER, (char*)&lng, sizeof(lng)) )
- return ERR_COULD_NOT_CREATE_SOCKET;
-
- // send the PORT command ...
- pAddr = static_cast<const KInetSocketAddress*>(m_data->localAddress());
- struct sockaddr* psa = (struct sockaddr*)pAddr->addressV4();
- unsigned char* pData = (unsigned char*)(psa->sa_data);
- TQCString portCmd;
- portCmd.sprintf("port %d,%d,%d,%d,%d,%d",
- pData[2], pData[3], pData[4], pData[5], pData[0], pData[1]);
- if( ftpSendCmd(portCmd) && (m_iRespType == 2) )
- return 0;
- return ERR_COULD_NOT_CONNECT;
-}
-
-/*
- * ftpAcceptConnect - wait for incoming connection
- * Used by @ref ftpOpenCommand
- *
- * return false on error or timeout
- */
-int Ftp::ftpAcceptConnect()
-{
- assert(m_data != NULL);
-
- if ( m_bPasv )
- {
- m_data->setServer(-1);
- return true;
- }
-
- int sSock = m_data->fd();
- struct sockaddr addr;
- for(;;)
- {
- fd_set mask;
- FD_ZERO(&mask);
- FD_SET(sSock,&mask);
- int r = KSocks::self()->select(sSock + 1, &mask, NULL, NULL, 0L);
- if( r < 0 && errno != EINTR && errno != EAGAIN )
- continue;
- if( r > 0 )
- break;
- }
-
- ksocklen_t l = sizeof(addr);
- m_data->setServer( KSocks::self()->accept(sSock, &addr, &l) );
- return (m_data->server() != -1);
-}
-
-bool Ftp::ftpOpenCommand( const char *_command, const TQString & _path, char _mode,
- int errorcode, TDEIO::fileoffset_t _offset )
-{
- int errCode = 0;
- if( !ftpDataMode(_mode) )
- errCode = ERR_COULD_NOT_CONNECT;
- else
- errCode = ftpOpenDataConnection();
-
- if(errCode != 0)
- {
- error(errCode, m_host);
- return false;
- }
-
- if ( _offset > 0 ) {
- // send rest command if offset > 0, this applies to retr and stor commands
- char buf[100];
- sprintf(buf, "rest %lld", _offset);
- if ( !ftpSendCmd( buf ) )
- return false;
- if( m_iRespType != 3 )
- {
- error( ERR_CANNOT_RESUME, _path ); // should never happen
- return false;
- }
- }
-
- TQCString tmp = _command;
- TQString errormessage;
-
- if ( !_path.isEmpty() ) {
- tmp += " ";
- tmp += remoteEncoding()->encode(_path);
- }
-
- if( !ftpSendCmd( tmp ) || (m_iRespType != 1) )
- {
- if( _offset > 0 && strcmp(_command, "retr") == 0 && (m_iRespType == 4) )
- errorcode = ERR_CANNOT_RESUME;
- // The error here depends on the command
- errormessage = _path;
- }
-
- else
- {
- // Only now we know for sure that we can resume
- if ( _offset > 0 && strcmp(_command, "retr") == 0 )
- canResume();
-
- if( ftpAcceptConnect() )
- { m_bBusy = true; // cleared in ftpCloseCommand
- return true;
- }
- errorcode = ERR_COULD_NOT_ACCEPT;
- }
-
- error(errorcode, errormessage);
- return false;
-}
-
-
-bool Ftp::ftpCloseCommand()
-{
- // first close data sockets (if opened), then read response that
- // we got for whatever was used in ftpOpenCommand ( should be 226 )
- if(m_data)
- {
- delete m_data;
- m_data = NULL;
- }
- if(!m_bBusy)
- return true;
-
- kdDebug(7102) << "ftpCloseCommand: reading command result" << endl;
- m_bBusy = false;
-
- if(!ftpResponse(-1) || (m_iRespType != 2) )
- {
- kdDebug(7102) << "ftpCloseCommand: no transfer complete message" << endl;
- return false;
- }
- return true;
-}
-
-void Ftp::mkdir( const KURL & url, int permissions )
-{
- if( !ftpOpenConnection(loginImplicit) )
- return;
-
- TQString path = remoteEncoding()->encode(url);
- TQCString buf = "mkd ";
- buf += remoteEncoding()->encode(path);
-
- if( !ftpSendCmd( buf ) || (m_iRespType != 2) )
- {
- TQString currentPath( m_currentPath );
-
- // Check whether or not mkdir failed because
- // the directory already exists...
- if( ftpFolder( path, false ) )
- {
- error( ERR_DIR_ALREADY_EXIST, path );
- // Change the directory back to what it was...
- (void) ftpFolder( currentPath, false );
- return;
- }
-
- error( ERR_COULD_NOT_MKDIR, path );
- return;
- }
-
- if ( permissions != -1 )
- {
- // chmod the dir we just created, ignoring errors.
- (void) ftpChmod( path, permissions );
- }
-
- finished();
-}
-
-void Ftp::rename( const KURL& src, const KURL& dst, bool overwrite )
-{
- if( !ftpOpenConnection(loginImplicit) )
- return;
-
- // The actual functionality is in ftpRename because put needs it
- if ( ftpRename( src.path(), dst.path(), overwrite ) )
- finished();
- else
- error( ERR_CANNOT_RENAME, src.path() );
-}
-
-bool Ftp::ftpRename( const TQString & src, const TQString & dst, bool overwrite )
-{
- assert( m_bLoggedOn );
-
- // Must check if dst already exists, RNFR+RNTO overwrites by default (#127793).
- if (!overwrite) {
- if (ftpSize(dst, 'I')) {
- error(ERR_FILE_ALREADY_EXIST, dst);
- return false;
- }
- }
- if (ftpFolder(dst, false)) {
- error(ERR_DIR_ALREADY_EXIST, dst);
- return false;
- }
-
- // Must check if dst already exists, RNFR+RNTO overwrites by default (#127793).
- if (ftpFileExists(dst)) {
- error(ERR_FILE_ALREADY_EXIST, dst);
- return false;
- }
- if (ftpFolder(dst, false)) {
- error(ERR_DIR_ALREADY_EXIST, dst);
- return false;
- }
-
- int pos = src.findRev("/");
- if( !ftpFolder(src.left(pos+1), false) )
- return false;
-
- TQCString from_cmd = "RNFR ";
- from_cmd += remoteEncoding()->encode(src.mid(pos+1));
- if( !ftpSendCmd( from_cmd ) || (m_iRespType != 3) )
- return false;
-
- TQCString to_cmd = "RNTO ";
- to_cmd += remoteEncoding()->encode(dst);
- if( !ftpSendCmd( to_cmd ) || (m_iRespType != 2) )
- return false;
-
- return true;
-}
-
-void Ftp::del( const KURL& url, bool isfile )
-{
- if( !ftpOpenConnection(loginImplicit) )
- return;
-
- // When deleting a directory, we must exit from it first
- // The last command probably went into it (to stat it)
- if ( !isfile )
- ftpFolder(remoteEncoding()->directory(url), false); // ignore errors
-
- TQCString cmd = isfile ? "DELE " : "RMD ";
- cmd += remoteEncoding()->encode(url);
-
- if( !ftpSendCmd( cmd ) || (m_iRespType != 2) )
- error( ERR_CANNOT_DELETE, url.path() );
- else
- finished();
-}
-
-bool Ftp::ftpChmod( const TQString & path, int permissions )
-{
- assert( m_bLoggedOn );
-
- if(m_extControl & chmodUnknown) // previous errors?
- return false;
-
- // we need to do bit AND 777 to get permissions, in case
- // we were sent a full mode (unlikely)
- TQCString cmd;
- cmd.sprintf("SITE CHMOD %o ", permissions & 511 );
- cmd += remoteEncoding()->encode(path);
-
- ftpSendCmd(cmd);
- if(m_iRespType == 2)
- return true;
-
- if(m_iRespCode == 500)
- {
- m_extControl |= chmodUnknown;
- kdDebug(7102) << "ftpChmod: CHMOD not supported - disabling";
- }
- return false;
-}
-
-void Ftp::chmod( const KURL & url, int permissions )
-{
- if( !ftpOpenConnection(loginImplicit) )
- return;
-
- if ( !ftpChmod( url.path(), permissions ) )
- error( ERR_CANNOT_CHMOD, url.path() );
- else
- finished();
-}
-
-void Ftp::ftpCreateUDSEntry( const TQString & filename, FtpEntry& ftpEnt, UDSEntry& entry, bool isDir )
-{
- assert(entry.count() == 0); // by contract :-)
- UDSAtom atom;
- atom.m_uds = UDS_NAME;
- atom.m_str = filename;
- entry.append( atom );
-
- atom.m_uds = UDS_SIZE;
- atom.m_long = ftpEnt.size;
- entry.append( atom );
-
- atom.m_uds = UDS_MODIFICATION_TIME;
- atom.m_long = ftpEnt.date;
- entry.append( atom );
-
- atom.m_uds = UDS_ACCESS;
- atom.m_long = ftpEnt.access;
- entry.append( atom );
-
- atom.m_uds = UDS_USER;
- atom.m_str = ftpEnt.owner;
- entry.append( atom );
-
- if ( !ftpEnt.group.isEmpty() )
- {
- atom.m_uds = UDS_GROUP;
- atom.m_str = ftpEnt.group;
- entry.append( atom );
- }
-
- if ( !ftpEnt.link.isEmpty() )
- {
- atom.m_uds = UDS_LINK_DEST;
- atom.m_str = ftpEnt.link;
- entry.append( atom );
-
- KMimeType::Ptr mime = KMimeType::findByURL( KURL("ftp://host/" + filename ) );
- // Links on ftp sites are often links to dirs, and we have no way to check
- // that. Let's do like Netscape : assume dirs generally.
- // But we do this only when the mimetype can't be known from the filename.
- // --> we do better than Netscape :-)
- if ( mime->name() == KMimeType::defaultMimeType() )
- {
- kdDebug(7102) << "Setting guessed mime type to inode/directory for " << filename << endl;
- atom.m_uds = UDS_GUESSED_MIME_TYPE;
- atom.m_str = "inode/directory";
- entry.append( atom );
- isDir = true;
- }
- }
-
- atom.m_uds = UDS_FILE_TYPE;
- atom.m_long = isDir ? S_IFDIR : ftpEnt.type;
- entry.append( atom );
-
- /* atom.m_uds = UDS_ACCESS_TIME;
- atom.m_long = buff.st_atime;
- entry.append( atom );
-
- atom.m_uds = UDS_CREATION_TIME;
- atom.m_long = buff.st_ctime;
- entry.append( atom ); */
-}
-
-
-void Ftp::ftpShortStatAnswer( const TQString& filename, bool isDir )
-{
- UDSEntry entry;
- UDSAtom atom;
-
- atom.m_uds = TDEIO::UDS_NAME;
- atom.m_str = filename;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_FILE_TYPE;
- atom.m_long = isDir ? S_IFDIR : S_IFREG;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
- entry.append( atom );
-
- // No details about size, ownership, group, etc.
-
- statEntry(entry);
- finished();
-}
-
-void Ftp::ftpStatAnswerNotFound( const TQString & path, const TQString & filename )
-{
- // Only do the 'hack' below if we want to download an existing file (i.e. when looking at the "source")
- // When e.g. uploading a file, we still need stat() to return "not found"
- // when the file doesn't exist.
- TQString statSide = metaData("statSide");
- kdDebug(7102) << "Ftp::stat statSide=" << statSide << endl;
- if ( statSide == "source" )
- {
- kdDebug(7102) << "Not found, but assuming found, because some servers don't allow listing" << endl;
- // MS Server is incapable of handling "list <blah>" in a case insensitive way
- // But "retr <blah>" works. So lie in stat(), to get going...
- //
- // There's also the case of ftp://ftp2.3ddownloads.com/90380/linuxgames/loki/patches/ut/ut-patch-436.run
- // where listing permissions are denied, but downloading is still possible.
- ftpShortStatAnswer( filename, false /*file, not dir*/ );
-
- return;
- }
-
- error( ERR_DOES_NOT_EXIST, path );
-}
-
-void Ftp::stat( const KURL &url)
-{
- kdDebug(7102) << "Ftp::stat : path='" << url.path() << "'" << endl;
- if( !ftpOpenConnection(loginImplicit) )
- return;
-
- TQString path = TQDir::cleanDirPath( url.path() );
- kdDebug(7102) << "Ftp::stat : cleaned path='" << path << "'" << endl;
-
- // We can't stat root, but we know it's a dir.
- if( path.isEmpty() || path == "/" )
- {
- UDSEntry entry;
- UDSAtom atom;
-
- atom.m_uds = TDEIO::UDS_NAME;
- atom.m_str = TQString::null;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_FILE_TYPE;
- atom.m_long = S_IFDIR;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_USER;
- atom.m_str = "root";
- entry.append( atom );
- atom.m_uds = TDEIO::UDS_GROUP;
- entry.append( atom );
-
- // no size
-
- statEntry( entry );
- finished();
- return;
- }
-
- KURL tempurl( url );
- tempurl.setPath( path ); // take the clean one
- TQString listarg; // = tempurl.directory(false /*keep trailing slash*/);
- TQString parentDir;
- TQString filename = tempurl.fileName();
- Q_ASSERT(!filename.isEmpty());
- TQString search = filename;
-
- // Try cwd into it, if it works it's a dir (and then we'll list the parent directory to get more info)
- // if it doesn't work, it's a file (and then we'll use dir filename)
- bool isDir = ftpFolder(path, false);
-
- // if we're only interested in "file or directory", we should stop here
- TQString sDetails = metaData("details");
- int details = sDetails.isEmpty() ? 2 : sDetails.toInt();
- kdDebug(7102) << "Ftp::stat details=" << details << endl;
- if ( details == 0 )
- {
- if ( !isDir && !ftpSize( path, 'I' ) ) // ok, not a dir -> is it a file ?
- { // no -> it doesn't exist at all
- ftpStatAnswerNotFound( path, filename );
- return;
- }
- ftpShortStatAnswer( filename, isDir ); // successfully found a dir or a file -> done
- return;
- }
-
- if (!isDir)
- {
- // It is a file or it doesn't exist, try going to parent directory
- parentDir = tempurl.directory(false /*keep trailing slash*/);
- // With files we can do "LIST <filename>" to avoid listing the whole dir
- listarg = filename;
- }
- else
- {
- // --- New implementation:
- // Don't list the parent dir. Too slow, might not show it, etc.
- // Just return that it's a dir.
- UDSEntry entry;
- UDSAtom atom;
-
- atom.m_uds = TDEIO::UDS_NAME;
- atom.m_str = filename;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_FILE_TYPE;
- atom.m_long = S_IFDIR;
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
- entry.append( atom );
-
- // No clue about size, ownership, group, etc.
-
- statEntry(entry);
- finished();
- return;
-
- // --- Old implementation:
-#if 0
- // It's a dir, remember that
- // Reason: it could be a symlink to a dir, in which case ftpReadDir
- // in the parent dir will have no idea about that. But we know better.
- isDir = true;
- // If the dir starts with '.', we'll need '-a' to see it in the listing.
- if ( search[0] == '.' )
- listarg = "-a";
- parentDir = "..";
-#endif
- }
-
- // Now cwd the parent dir, to prepare for listing
- if( !ftpFolder(parentDir, true) )
- return;
-
- if( !ftpOpenCommand( "list", listarg, 'I', ERR_DOES_NOT_EXIST ) )
- {
- kdError(7102) << "COULD NOT LIST" << endl;
- return;
- }
- kdDebug(7102) << "Starting of list was ok" << endl;
-
- Q_ASSERT( !search.isEmpty() && search != "/" );
-
- bool bFound = false;
- KURL linkURL;
- FtpEntry ftpEnt;
- while( ftpReadDir(ftpEnt) )
- {
- // We look for search or filename, since some servers (e.g. ftp.tuwien.ac.at)
- // return only the filename when doing "dir /full/path/to/file"
- if ( !bFound )
- {
- if ( ( search == ftpEnt.name || filename == ftpEnt.name ) ) {
- if ( !filename.isEmpty() ) {
- bFound = true;
- UDSEntry entry;
- ftpCreateUDSEntry( filename, ftpEnt, entry, isDir );
- statEntry( entry );
- }
- } else if ( isDir && ( ftpEnt.name == listarg || ftpEnt.name+'/' == listarg ) ) {
- // Damn, the dir we're trying to list is in fact a symlink
- // Follow it and try again
- if ( ftpEnt.link.isEmpty() )
- kdWarning(7102) << "Got " << listarg << " as answer, but empty link!" << endl;
- else
- {
- linkURL = url;
- kdDebug(7102) << "ftpEnt.link=" << ftpEnt.link << endl;
- if ( ftpEnt.link[0] == '/' )
- linkURL.setPath( ftpEnt.link ); // Absolute link
- else
- {
- // Relative link (stat will take care of cleaning ../.. etc.)
- linkURL.setPath( listarg ); // this is what we were listing (the link)
- linkURL.setPath( linkURL.directory() ); // go up one dir
- linkURL.addPath( ftpEnt.link ); // replace link by its destination
- kdDebug(7102) << "linkURL now " << linkURL.prettyURL() << endl;
- }
- // Re-add the filename we're looking for
- linkURL.addPath( filename );
- }
- bFound = true;
- }
- }
-
- // kdDebug(7102) << ftpEnt.name << endl;
- }
-
- ftpCloseCommand(); // closes the data connection only
-
- if ( !bFound )
- {
- ftpStatAnswerNotFound( path, filename );
- return;
- }
-
- if ( !linkURL.isEmpty() )
- {
- if ( linkURL == url || linkURL == tempurl )
- {
- error( ERR_CYCLIC_LINK, linkURL.prettyURL() );
- return;
- }
- stat( linkURL );
- return;
- }
-
- kdDebug(7102) << "stat : finished successfully" << endl;
- finished();
-}
-
-
-void Ftp::listDir( const KURL &url )
-{
- kdDebug(7102) << "Ftp::listDir " << url.prettyURL() << endl;
- if( !ftpOpenConnection(loginImplicit) )
- return;
-
- // No path specified ?
- TQString path = url.path();
- if ( path.isEmpty() )
- {
- KURL realURL;
- realURL.setProtocol( "ftp" );
- if ( m_user != FTP_LOGIN )
- realURL.setUser( m_user );
- // We set the password, so that we don't ask for it if it was given
- if ( m_pass != FTP_PASSWD )
- realURL.setPass( m_pass );
- realURL.setHost( m_host );
- realURL.setPort( m_port );
- if ( m_initialPath.isEmpty() )
- m_initialPath = "/";
- realURL.setPath( m_initialPath );
- kdDebug(7102) << "REDIRECTION to " << realURL.prettyURL() << endl;
- redirection( realURL );
- finished();
- return;
- }
-
- kdDebug(7102) << "hunting for path '" << path << "'" << endl;
-
- if (!ftpOpenDir( path ) )
- {
- if ( ftpSize( path, 'I' ) ) // is it a file ?
- {
- error( ERR_IS_FILE, path );
- return;
- }
- // not sure which to emit
- //error( ERR_DOES_NOT_EXIST, path );
- error( ERR_CANNOT_ENTER_DIRECTORY, path );
- return;
- }
-
- UDSEntry entry;
- FtpEntry ftpEnt;
- while( ftpReadDir(ftpEnt) )
- {
- //kdDebug(7102) << ftpEnt.name << endl;
- //Q_ASSERT( !ftpEnt.name.isEmpty() );
- if ( !ftpEnt.name.isEmpty() )
- {
- //if ( S_ISDIR( (mode_t)ftpEnt.type ) )
- // kdDebug(7102) << "is a dir" << endl;
- //if ( !ftpEnt.link.isEmpty() )
- // kdDebug(7102) << "is a link to " << ftpEnt.link << endl;
- entry.clear();
- ftpCreateUDSEntry( ftpEnt.name, ftpEnt, entry, false );
- listEntry( entry, false );
- }
- }
- listEntry( entry, true ); // ready
- ftpCloseCommand(); // closes the data connection only
- finished();
-}
-
-void Ftp::slave_status()
-{
- kdDebug(7102) << "Got slave_status host = " << (m_host.ascii() ? m_host.ascii() : "[None]") << " [" << (m_bLoggedOn ? "Connected" : "Not connected") << "]" << endl;
- slaveStatus( m_host, m_bLoggedOn );
-}
-
-bool Ftp::ftpOpenDir( const TQString & path )
-{
- //TQString path( _url.path(-1) );
-
- // We try to change to this directory first to see whether it really is a directory.
- // (And also to follow symlinks)
- TQString tmp = path.isEmpty() ? TQString("/") : path;
-
- // We get '550', whether it's a file or doesn't exist...
- if( !ftpFolder(tmp, false) )
- return false;
-
- // Don't use the path in the list command:
- // We changed into this directory anyway - so it's enough just to send "list".
- // We use '-a' because the application MAY be interested in dot files.
- // The only way to really know would be to have a metadata flag for this...
- // Since some windows ftp server seems not to support the -a argument, we use a fallback here.
- // In fact we have to use -la otherwise -a removes the default -l (e.g. ftp.trolltech.com)
- if( !ftpOpenCommand( "list -la", TQString::null, 'I', ERR_CANNOT_ENTER_DIRECTORY ) )
- {
- if ( !ftpOpenCommand( "list", TQString::null, 'I', ERR_CANNOT_ENTER_DIRECTORY ) )
- {
- kdWarning(7102) << "Can't open for listing" << endl;
- return false;
- }
- }
- kdDebug(7102) << "Starting of list was ok" << endl;
- return true;
-}
-
-bool Ftp::ftpReadDir(FtpEntry& de)
-{
- assert(m_data != NULL);
-
- // get a line from the data connecetion ...
- while( !m_data->textEOF() )
- {
- if(m_data->textRead() <= 0)
- continue;
- if(m_data->textTooLong())
- kdWarning(7102) << "ftpReadDir line too long - truncated" << endl;
-
- const char* buffer = m_data->textLine();
- kdDebug(7102) << "dir > " << buffer << endl;
-
- //Normally the listing looks like
- // -rw-r--r-- 1 dfaure dfaure 102 Nov 9 12:30 log
- // but on Netware servers like ftp://ci-1.ci.pwr.wroc.pl/ it looks like (#76442)
- // d [RWCEAFMS] Admin 512 Oct 13 2004 PSI
-
- // we should always get the following 5 fields ...
- const char *p_access, *p_junk, *p_owner, *p_group, *p_size;
- if( (p_access = strtok((char*)buffer," ")) == 0) continue;
- if( (p_junk = strtok(NULL," ")) == 0) continue;
- if( (p_owner = strtok(NULL," ")) == 0) continue;
- if( (p_group = strtok(NULL," ")) == 0) continue;
- if( (p_size = strtok(NULL," ")) == 0) continue;
-
- //kdDebug(7102) << "p_access=" << p_access << " p_junk=" << p_junk << " p_owner=" << p_owner << " p_group=" << p_group << " p_size=" << p_size << endl;
-
- de.access = 0;
- if ( strlen( p_access ) == 1 && p_junk[0] == '[' ) { // Netware
- de.access = S_IRWXU | S_IRWXG | S_IRWXO; // unknown -> give all permissions
- }
-
- const char *p_date_1, *p_date_2, *p_date_3, *p_name;
-
- // A special hack for "/dev". A listing may look like this:
- // crw-rw-rw- 1 root root 1, 5 Jun 29 1997 zero
- // So we just ignore the number in front of the ",". Ok, its a hack :-)
- if ( strchr( p_size, ',' ) != 0L )
- {
- //kdDebug(7102) << "Size contains a ',' -> reading size again (/dev hack)" << endl;
- if ((p_size = strtok(NULL," ")) == 0)
- continue;
- }
-
- // Check whether the size we just read was really the size
- // or a month (this happens when the server lists no group)
- // Used to be the case on sunsite.uio.no, but not anymore
- // This is needed for the Netware case, too.
- if ( !isdigit( *p_size ) )
- {
- p_date_1 = p_size;
- p_size = p_group;
- p_group = 0;
- //kdDebug(7102) << "Size didn't have a digit -> size=" << p_size << " date_1=" << p_date_1 << endl;
- }
- else
- {
- p_date_1 = strtok(NULL," ");
- //kdDebug(7102) << "Size has a digit -> ok. p_date_1=" << p_date_1 << endl;
- }
-
- if ( p_date_1 != 0 &&
- (p_date_2 = strtok(NULL," ")) != 0 &&
- (p_date_3 = strtok(NULL," ")) != 0 &&
- (p_name = strtok(NULL,"\r\n")) != 0 )
- {
- {
- TQCString tmp( p_name );
- if ( p_access[0] == 'l' )
- {
- int i = tmp.findRev( " -> " );
- if ( i != -1 ) {
- de.link = remoteEncoding()->decode(p_name + i + 4);
- tmp.truncate( i );
- }
- else
- de.link = TQString::null;
- }
- else
- de.link = TQString::null;
-
- if ( tmp[0] == '/' ) // listing on ftp://ftp.gnupg.org/ starts with '/'
- tmp.remove( 0, 1 );
-
- if (tmp.find('/') != -1)
- continue; // Don't trick us!
- // Some sites put more than one space between the date and the name
- // e.g. ftp://ftp.uni-marburg.de/mirror/
- de.name = remoteEncoding()->decode(tmp.stripWhiteSpace());
- }
-
- de.type = S_IFREG;
- switch ( p_access[0] ) {
- case 'd':
- de.type = S_IFDIR;
- break;
- case 's':
- de.type = S_IFSOCK;
- break;
- case 'b':
- de.type = S_IFBLK;
- break;
- case 'c':
- de.type = S_IFCHR;
- break;
- case 'l':
- de.type = S_IFREG;
- // we don't set S_IFLNK here. de.link says it.
- break;
- default:
- break;
- }
-
- if ( p_access[1] == 'r' )
- de.access |= S_IRUSR;
- if ( p_access[2] == 'w' )
- de.access |= S_IWUSR;
- if ( p_access[3] == 'x' || p_access[3] == 's' )
- de.access |= S_IXUSR;
- if ( p_access[4] == 'r' )
- de.access |= S_IRGRP;
- if ( p_access[5] == 'w' )
- de.access |= S_IWGRP;
- if ( p_access[6] == 'x' || p_access[6] == 's' )
- de.access |= S_IXGRP;
- if ( p_access[7] == 'r' )
- de.access |= S_IROTH;
- if ( p_access[8] == 'w' )
- de.access |= S_IWOTH;
- if ( p_access[9] == 'x' || p_access[9] == 't' )
- de.access |= S_IXOTH;
- if ( p_access[3] == 's' || p_access[3] == 'S' )
- de.access |= S_ISUID;
- if ( p_access[6] == 's' || p_access[6] == 'S' )
- de.access |= S_ISGID;
- if ( p_access[9] == 't' || p_access[9] == 'T' )
- de.access |= S_ISVTX;
-
- de.owner = remoteEncoding()->decode(p_owner);
- de.group = remoteEncoding()->decode(p_group);
- de.size = charToLongLong(p_size);
-
- // Parsing the date is somewhat tricky
- // Examples : "Oct 6 22:49", "May 13 1999"
-
- // First get current time - we need the current month and year
- time_t currentTime = time( 0L );
- struct tm * tmptr = gmtime( &currentTime );
- int currentMonth = tmptr->tm_mon;
- //kdDebug(7102) << "Current time :" << asctime( tmptr ) << endl;
- // Reset time fields
- tmptr->tm_isdst = -1; // We do not know anything about day saving time (of any random day of the year)
- tmptr->tm_sec = 0;
- tmptr->tm_min = 0;
- tmptr->tm_hour = 0;
- // Get day number (always second field)
- tmptr->tm_mday = atoi( p_date_2 );
- // Get month from first field
- // NOTE : no, we don't want to use KLocale here
- // It seems all FTP servers use the English way
- //kdDebug(7102) << "Looking for month " << p_date_1 << endl;
- static const char * s_months[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
- for ( int c = 0 ; c < 12 ; c ++ )
- if ( !strcmp( p_date_1, s_months[c]) )
- {
- //kdDebug(7102) << "Found month " << c << " for " << p_date_1 << endl;
- tmptr->tm_mon = c;
- break;
- }
-
- // Parse third field
- if ( strlen( p_date_3 ) == 4 ) // 4 digits, looks like a year
- tmptr->tm_year = atoi( p_date_3 ) - 1900;
- else
- {
- // otherwise, the year is implicit
- // according to man ls, this happens when it is between than 6 months
- // old and 1 hour in the future.
- // So the year is : current year if tm_mon <= currentMonth+1
- // otherwise current year minus one
- // (The +1 is a security for the "+1 hour" at the end of the month issue)
- if ( tmptr->tm_mon > currentMonth + 1 )
- tmptr->tm_year--;
-
- // and p_date_3 contains probably a time
- char * semicolon;
- if ( ( semicolon = const_cast<char*>(strchr( p_date_3, ':' )) ) )
- {
- *semicolon = '\0';
- tmptr->tm_min = atoi( semicolon + 1 );
- tmptr->tm_hour = atoi( p_date_3 );
- }
- else
- kdWarning(7102) << "Can't parse third field " << p_date_3 << endl;
- }
-
- //kdDebug(7102) << asctime( tmptr ) << endl;
- de.date = mktime( tmptr );
- return true;
- }
- } // line invalid, loop to get another line
- return false;
-}
-
-//===============================================================================
-// public: get download file from server
-// helper: ftpGet called from get() and copy()
-//===============================================================================
-void Ftp::get( const KURL & url )
-{
- kdDebug(7102) << "Ftp::get " << url.url() << endl;
- int iError = 0;
- ftpGet(iError, -1, url, 0); // iError gets status
- if(iError) // can have only server side errs
- error(iError, url.path());
- ftpCloseCommand(); // must close command!
-}
-
-Ftp::StatusCode Ftp::ftpGet(int& iError, int iCopyFile, const KURL& url, TDEIO::fileoffset_t llOffset)
-{
- // Calls error() by itself!
- if( !ftpOpenConnection(loginImplicit) )
- return statusServerError;
-
- // Try to find the size of the file (and check that it exists at
- // the same time). If we get back a 550, "File does not exist"
- // or "not a plain file", check if it is a directory. If it is a
- // directory, return an error; otherwise simply try to retrieve
- // the request...
- if ( !ftpSize( url.path(), '?' ) && (m_iRespCode == 550) &&
- ftpFolder(url.path(), false) )
- {
- // Ok it's a dir in fact
- kdDebug(7102) << "ftpGet: it is a directory in fact" << endl;
- iError = ERR_IS_DIRECTORY;
- return statusServerError;
- }
-
- TQString resumeOffset = metaData("resume");
- if ( !resumeOffset.isEmpty() )
- {
- llOffset = resumeOffset.toLongLong();
- kdDebug(7102) << "ftpGet: got offset from metadata : " << llOffset << endl;
- }
-
- if( !ftpOpenCommand("retr", url.path(), '?', ERR_CANNOT_OPEN_FOR_READING, llOffset) )
- {
- kdWarning(7102) << "ftpGet: Can't open for reading" << endl;
- return statusServerError;
- }
-
- // Read the size from the response string
- if(m_size == UnknownSize)
- {
- const char* psz = strrchr( ftpResponse(4), '(' );
- if(psz) m_size = charToLongLong(psz+1);
- if (!m_size) m_size = UnknownSize;
- }
-
- TDEIO::filesize_t bytesLeft = 0;
- if ( m_size != UnknownSize )
- bytesLeft = m_size - llOffset;
-
- kdDebug(7102) << "ftpGet: starting with offset=" << llOffset << endl;
- TDEIO::fileoffset_t processed_size = llOffset;
-
- TQByteArray array;
- bool mimetypeEmitted = false;
- char buffer[maximumIpcSize];
- // start whith small data chunks in case of a slow data source (modem)
- // - unfortunately this has a negative impact on performance for large
- // - files - so we will increase the block size after a while ...
- int iBlockSize = initialIpcSize;
- int iBufferCur = 0;
-
- while(m_size == UnknownSize || bytesLeft > 0)
- { // let the buffer size grow if the file is larger 64kByte ...
- if(processed_size-llOffset > 1024 * 64)
- iBlockSize = maximumIpcSize;
-
- // read the data and detect EOF or error ...
- if(iBlockSize+iBufferCur > (int)sizeof(buffer))
- iBlockSize = sizeof(buffer) - iBufferCur;
- int n = m_data->read( buffer+iBufferCur, iBlockSize );
- if(n <= 0)
- { // this is how we detect EOF in case of unknown size
- if( m_size == UnknownSize && n == 0 )
- break;
- // unexpected eof. Happens when the daemon gets killed.
- iError = ERR_COULD_NOT_READ;
- return statusServerError;
- }
- processed_size += n;
-
- // collect very small data chunks in buffer before processing ...
- if(m_size != UnknownSize)
- {
- bytesLeft -= n;
- iBufferCur += n;
- if(iBufferCur < mimimumMimeSize && bytesLeft > 0)
- {
- processedSize( processed_size );
- continue;
- }
- n = iBufferCur;
- iBufferCur = 0;
- }
-
- // get the mime type and set the total size ...
- if(!mimetypeEmitted)
- {
- mimetypeEmitted = true;
-
- // We need a KMimeType::findByNameAndContent(data,filename)
- // For now we do: find by extension, and if not found (or extension not reliable)
- // then find by content.
- bool accurate = false;
- KMimeType::Ptr mime = KMimeType::findByURL( url, 0, false, true, &accurate );
- if ( !mime || mime->name() == KMimeType::defaultMimeType()
- || !accurate )
- {
- array.setRawData(buffer, n);
- KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType(array, url.fileName());
- array.resetRawData(buffer, n);
- if ( result->mimeType() != KMimeType::defaultMimeType() )
- mime = KMimeType::mimeType( result->mimeType() );
- }
-
- kdDebug(7102) << "ftpGet: Emitting mimetype " << mime->name() << endl;
- mimeType( mime->name() );
- if( m_size != UnknownSize ) // Emit total size AFTER mimetype
- totalSize( m_size );
- }
-
- // write output file or pass to data pump ...
- if(iCopyFile == -1)
- {
- array.setRawData(buffer, n);
- data( array );
- array.resetRawData(buffer, n);
- }
- else if( (iError = WriteToFile(iCopyFile, buffer, n)) != 0)
- return statusClientError; // client side error
- processedSize( processed_size );
- }
-
- kdDebug(7102) << "ftpGet: done" << endl;
- if(iCopyFile == -1) // must signal EOF to data pump ...
- data(array); // array is empty and must be empty!
-
- processedSize( m_size == UnknownSize ? processed_size : m_size );
- kdDebug(7102) << "ftpGet: emitting finished()" << endl;
- finished();
- return statusSuccess;
-}
-
-/*
-void Ftp::mimetype( const KURL& url )
-{
- if( !ftpOpenConnection(loginImplicit) )
- return;
-
- if ( !ftpOpenCommand( "retr", url.path(), 'I', ERR_CANNOT_OPEN_FOR_READING, 0 ) ) {
- kdWarning(7102) << "Can't open for reading" << endl;
- return;
- }
- char buffer[ 2048 ];
- TQByteArray array;
- // Get one chunk of data only and send it, TDEIO::Job will determine the
- // mimetype from it using KMimeMagic
- int n = m_data->read( buffer, 2048 );
- array.setRawData(buffer, n);
- data( array );
- array.resetRawData(buffer, n);
-
- kdDebug(7102) << "aborting" << endl;
- ftpAbortTransfer();
-
- kdDebug(7102) << "finished" << endl;
- finished();
- kdDebug(7102) << "after finished" << endl;
-}
-
-void Ftp::ftpAbortTransfer()
-{
- // RFC 959, page 34-35
- // IAC (interpret as command) = 255 ; IP (interrupt process) = 254
- // DM = 242 (data mark)
- char msg[4];
- // 1. User system inserts the Telnet "Interrupt Process" (IP) signal
- // in the Telnet stream.
- msg[0] = (char) 255; //IAC
- msg[1] = (char) 254; //IP
- (void) send(sControl, msg, 2, 0);
- // 2. User system sends the Telnet "Sync" signal.
- msg[0] = (char) 255; //IAC
- msg[1] = (char) 242; //DM
- if (send(sControl, msg, 2, MSG_OOB) != 2)
- ; // error...
-
- // Send ABOR
- kdDebug(7102) << "send ABOR" << endl;
- TQCString buf = "ABOR\r\n";
- if ( KSocks::self()->write( sControl, buf.data(), buf.length() ) <= 0 ) {
- error( ERR_COULD_NOT_WRITE, TQString::null );
- return;
- }
-
- //
- kdDebug(7102) << "read resp" << endl;
- if ( readresp() != '2' )
- {
- error( ERR_COULD_NOT_READ, TQString::null );
- return;
- }
-
- kdDebug(7102) << "close sockets" << endl;
- closeSockets();
-}
-*/
-
-//===============================================================================
-// public: put upload file to server
-// helper: ftpPut called from put() and copy()
-//===============================================================================
-void Ftp::put(const KURL& url, int permissions, bool overwrite, bool resume)
-{
- kdDebug(7102) << "Ftp::put " << url.url() << endl;
- int iError = 0; // iError gets status
- ftpPut(iError, -1, url, permissions, overwrite, resume);
- if(iError) // can have only server side errs
- error(iError, url.path());
- ftpCloseCommand(); // must close command!
-}
-
-Ftp::StatusCode Ftp::ftpPut(int& iError, int iCopyFile, const KURL& dest_url,
- int permissions, bool overwrite, bool resume)
-{
- if( !ftpOpenConnection(loginImplicit) )
- return statusServerError;
-
- // Don't use mark partial over anonymous FTP.
- // My incoming dir allows put but not rename...
- bool bMarkPartial;
- if (m_user.isEmpty () || m_user == FTP_LOGIN)
- bMarkPartial = false;
- else
- bMarkPartial = config()->readBoolEntry("MarkPartial", true);
-
- TQString dest_orig = dest_url.path();
- TQString dest_part( dest_orig );
- dest_part += ".part";
-
- if ( ftpSize( dest_orig, 'I' ) )
- {
- if ( m_size == 0 )
- { // delete files with zero size
- TQCString cmd = "DELE ";
- cmd += remoteEncoding()->encode(dest_orig);
- if( !ftpSendCmd( cmd ) || (m_iRespType != 2) )
- {
- iError = ERR_CANNOT_DELETE_PARTIAL;
- return statusServerError;
- }
- }
- else if ( !overwrite && !resume )
- {
- iError = ERR_FILE_ALREADY_EXIST;
- return statusServerError;
- }
- else if ( bMarkPartial )
- { // when using mark partial, append .part extension
- if ( !ftpRename( dest_orig, dest_part, true ) )
- {
- iError = ERR_CANNOT_RENAME_PARTIAL;
- return statusServerError;
- }
- }
- // Don't chmod an existing file
- permissions = -1;
- }
- else if ( bMarkPartial && ftpSize( dest_part, 'I' ) )
- { // file with extension .part exists
- if ( m_size == 0 )
- { // delete files with zero size
- TQCString cmd = "DELE ";
- cmd += remoteEncoding()->encode(dest_part);
- if ( !ftpSendCmd( cmd ) || (m_iRespType != 2) )
- {
- iError = ERR_CANNOT_DELETE_PARTIAL;
- return statusServerError;
- }
- }
- else if ( !overwrite && !resume )
- {
- resume = canResume (m_size);
- if (!resume)
- {
- iError = ERR_FILE_ALREADY_EXIST;
- return statusServerError;
- }
- }
- }
- else
- m_size = 0;
-
- TQString dest;
-
- // if we are using marking of partial downloads -> add .part extension
- if ( bMarkPartial ) {
- kdDebug(7102) << "Adding .part extension to " << dest_orig << endl;
- dest = dest_part;
- } else
- dest = dest_orig;
-
- TDEIO::fileoffset_t offset = 0;
-
- // set the mode according to offset
- if( resume && m_size > 0 )
- {
- offset = m_size;
- if(iCopyFile != -1)
- {
- if( KDE_lseek(iCopyFile, offset, SEEK_SET) < 0 )
- {
- iError = ERR_CANNOT_RESUME;
- return statusClientError;
- }
- }
- }
-
- if (! ftpOpenCommand( "stor", dest, '?', ERR_COULD_NOT_WRITE, offset ) )
- return statusServerError;
-
- kdDebug(7102) << "ftpPut: starting with offset=" << offset << endl;
- TDEIO::fileoffset_t processed_size = offset;
-
- TQByteArray buffer;
- int result;
- int iBlockSize = initialIpcSize;
- // Loop until we got 'dataEnd'
- do
- {
- if(iCopyFile == -1)
- {
- dataReq(); // Request for data
- result = readData( buffer );
- }
- else
- { // let the buffer size grow if the file is larger 64kByte ...
- if(processed_size-offset > 1024 * 64)
- iBlockSize = maximumIpcSize;
- buffer.resize(iBlockSize);
- result = ::read(iCopyFile, buffer.data(), buffer.size());
- if(result < 0)
- iError = ERR_COULD_NOT_WRITE;
- else
- buffer.resize(result);
- }
-
- if (result > 0)
- {
- m_data->write( buffer.data(), buffer.size() );
- processed_size += result;
- processedSize (processed_size);
- }
- }
- while ( result > 0 );
-
- if (result != 0) // error
- {
- ftpCloseCommand(); // don't care about errors
- kdDebug(7102) << "Error during 'put'. Aborting." << endl;
- if (bMarkPartial)
- {
- // Remove if smaller than minimum size
- if ( ftpSize( dest, 'I' ) &&
- ( processed_size < (unsigned long) config()->readNumEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE) ) )
- {
- TQCString cmd = "DELE ";
- cmd += remoteEncoding()->encode(dest);
- (void) ftpSendCmd( cmd );
- }
- }
- return statusServerError;
- }
-
- if ( !ftpCloseCommand() )
- {
- iError = ERR_COULD_NOT_WRITE;
- return statusServerError;
- }
-
- // after full download rename the file back to original name
- if ( bMarkPartial )
- {
- kdDebug(7102) << "renaming dest (" << dest << ") back to dest_orig (" << dest_orig << ")" << endl;
- if ( !ftpRename( dest, dest_orig, true ) )
- {
- iError = ERR_CANNOT_RENAME_PARTIAL;
- return statusServerError;
- }
- }
-
- // set final permissions
- if ( permissions != -1 )
- {
- if ( m_user == FTP_LOGIN )
- kdDebug(7102) << "Trying to chmod over anonymous FTP ???" << endl;
- // chmod the file we just put
- if ( ! ftpChmod( dest_orig, permissions ) )
- {
- // To be tested
- //if ( m_user != FTP_LOGIN )
- // warning( i18n( "Could not change permissions for\n%1" ).arg( dest_orig ) );
- }
- }
-
- // We have done our job => finish
- finished();
- return statusSuccess;
-}
-
-
-/** Use the SIZE command to get the file size.
- Warning : the size depends on the transfer mode, hence the second arg. */
-bool Ftp::ftpSize( const TQString & path, char mode )
-{
- m_size = UnknownSize;
- if( !ftpDataMode(mode) )
- return false;
-
- TQCString buf;
- buf = "SIZE ";
- buf += remoteEncoding()->encode(path);
- if( !ftpSendCmd( buf ) || (m_iRespType != 2) )
- return false;
-
- // skip leading "213 " (response code)
- const char* psz = ftpResponse(4);
- if(!psz)
- return false;
- m_size = charToLongLong(psz);
- if (!m_size) m_size = UnknownSize;
- return true;
-}
-
-bool Ftp::ftpFileExists(const TQString& path)
-{
- TQCString buf;
- buf = "SIZE ";
- buf += remoteEncoding()->encode(path);
- if( !ftpSendCmd( buf ) || (m_iRespType != 2) )
- return false;
-
- // skip leading "213 " (response code)
- const char* psz = ftpResponse(4);
- return psz != 0;
-}
-
-// Today the differences between ASCII and BINARY are limited to
-// CR or CR/LF line terminators. Many servers ignore ASCII (like
-// win2003 -or- vsftp with default config). In the early days of
-// computing, when even text-files had structure, this stuff was
-// more important.
-// Theoretically "list" could return different results in ASCII
-// and BINARY mode. But again, most servers ignore ASCII here.
-bool Ftp::ftpDataMode(char cMode)
-{
- if(cMode == '?') cMode = m_bTextMode ? 'A' : 'I';
- else if(cMode == 'a') cMode = 'A';
- else if(cMode != 'A') cMode = 'I';
-
- kdDebug(7102) << "ftpDataMode: want '" << cMode << "' has '" << m_cDataMode << "'" << endl;
- if(m_cDataMode == cMode)
- return true;
-
- TQCString buf;
- buf.sprintf("TYPE %c", cMode);
- if( !ftpSendCmd(buf) || (m_iRespType != 2) )
- return false;
- m_cDataMode = cMode;
- return true;
-}
-
-
-bool Ftp::ftpFolder(const TQString& path, bool bReportError)
-{
- TQString newPath = path;
- int iLen = newPath.length();
- if(iLen > 1 && newPath[iLen-1] == '/') newPath.truncate(iLen-1);
-
- //kdDebug(7102) << "ftpFolder: want '" << newPath << "' has '" << m_currentPath << "'" << endl;
- if(m_currentPath == newPath)
- return true;
-
- TQCString tmp = "cwd ";
- tmp += remoteEncoding()->encode(newPath);
- if( !ftpSendCmd(tmp) )
- return false; // connection failure
- if(m_iRespType != 2)
- {
- if(bReportError)
- error(ERR_CANNOT_ENTER_DIRECTORY, path);
- return false; // not a folder
- }
- m_currentPath = newPath;
- return true;
-}
-
-
-//===============================================================================
-// public: copy don't use kio data pump if one side is a local file
-// helper: ftpCopyPut called from copy() on upload
-// helper: ftpCopyGet called from copy() on download
-//===============================================================================
-void Ftp::copy( const KURL &src, const KURL &dest, int permissions, bool overwrite )
-{
- int iError = 0;
- int iCopyFile = -1;
- StatusCode cs = statusSuccess;
- bool bSrcLocal = src.isLocalFile();
- bool bDestLocal = dest.isLocalFile();
- TQString sCopyFile;
-
- if(bSrcLocal && !bDestLocal) // File -> Ftp
- {
- sCopyFile = src.path();
- kdDebug(7102) << "Ftp::copy local file '" << sCopyFile << "' -> ftp '" << dest.path() << "'" << endl;
- cs = ftpCopyPut(iError, iCopyFile, sCopyFile, dest, permissions, overwrite);
- if( cs == statusServerError) sCopyFile = dest.url();
- }
- else if(!bSrcLocal && bDestLocal) // Ftp -> File
- {
- sCopyFile = dest.path();
- kdDebug(7102) << "Ftp::copy ftp '" << src.path() << "' -> local file '" << sCopyFile << "'" << endl;
- cs = ftpCopyGet(iError, iCopyFile, sCopyFile, src, permissions, overwrite);
- if( cs == statusServerError ) sCopyFile = src.url();
- }
- else {
- error( ERR_UNSUPPORTED_ACTION, TQString::null );
- return;
- }
-
- // perform clean-ups and report error (if any)
- if(iCopyFile != -1)
- ::close(iCopyFile);
- if(iError)
- error(iError, sCopyFile);
- ftpCloseCommand(); // must close command!
-}
-
-
-Ftp::StatusCode Ftp::ftpCopyPut(int& iError, int& iCopyFile, TQString sCopyFile,
- const KURL& url, int permissions, bool overwrite)
-{
- // check if source is ok ...
- KDE_struct_stat buff;
- TQCString sSrc( TQFile::encodeName(sCopyFile) );
- bool bSrcExists = (KDE_stat( sSrc.data(), &buff ) != -1);
- if(bSrcExists)
- { if(S_ISDIR(buff.st_mode))
- {
- iError = ERR_IS_DIRECTORY;
- return statusClientError;
- }
- }
- else
- {
- iError = ERR_DOES_NOT_EXIST;
- return statusClientError;
- }
-
- iCopyFile = KDE_open( sSrc.data(), O_RDONLY );
- if(iCopyFile == -1)
- {
- iError = ERR_CANNOT_OPEN_FOR_READING;
- return statusClientError;
- }
-
- // delegate the real work (iError gets status) ...
- totalSize(buff.st_size);
-#ifdef ENABLE_CAN_RESUME
- return ftpPut(iError, iCopyFile, url, permissions, overwrite, false);
-#else
- return ftpPut(iError, iCopyFile, url, permissions, overwrite, true);
-#endif
-}
-
-
-Ftp::StatusCode Ftp::ftpCopyGet(int& iError, int& iCopyFile, const TQString sCopyFile,
- const KURL& url, int permissions, bool overwrite)
-{
- // check if destination is ok ...
- KDE_struct_stat buff;
- TQCString sDest( TQFile::encodeName(sCopyFile) );
- bool bDestExists = (KDE_stat( sDest.data(), &buff ) != -1);
- if(bDestExists)
- { if(S_ISDIR(buff.st_mode))
- {
- iError = ERR_IS_DIRECTORY;
- return statusClientError;
- }
- if(!overwrite)
- {
- iError = ERR_FILE_ALREADY_EXIST;
- return statusClientError;
- }
- }
-
- // do we have a ".part" file?
- TQCString sPart = TQFile::encodeName(sCopyFile + ".part");
- bool bResume = false;
- bool bPartExists = (KDE_stat( sPart.data(), &buff ) != -1);
- const bool bMarkPartial = config()->readBoolEntry("MarkPartial", true);
-
- if(!bMarkPartial)
- {
- sPart = TQFile::encodeName(sCopyFile);
- }
- else if(bPartExists && buff.st_size > 0)
- { // must not be a folder! please fix a similar bug in kio_file!!
- if(S_ISDIR(buff.st_mode))
- {
- iError = ERR_DIR_ALREADY_EXIST;
- return statusClientError; // client side error
- }
- //doesn't work for copy? -> design flaw?
-#ifdef ENABLE_CAN_RESUME
- bResume = canResume( buff.st_size );
-#else
- bResume = true;
-#endif
- }
-
- if(bPartExists && !bResume) // get rid of an unwanted ".part" file
- remove(sPart.data());
-
- // JPF: in kio_file overwrite disables ".part" operations. I do not believe
- // JPF: that this is a good behaviour!
- if(bDestExists) // must delete for overwrite
- remove(sDest.data());
-
- // WABA: Make sure that we keep writing permissions ourselves,
- // otherwise we can be in for a surprise on NFS.
- mode_t initialMode;
- if (permissions != -1)
- initialMode = permissions | S_IWUSR;
- else
- initialMode = 0666;
-
- // open the output file ...
- TDEIO::fileoffset_t hCopyOffset = 0;
- if(bResume)
- {
- iCopyFile = KDE_open( sPart.data(), O_RDWR ); // append if resuming
- hCopyOffset = KDE_lseek(iCopyFile, 0, SEEK_END);
- if(hCopyOffset < 0)
- {
- iError = ERR_CANNOT_RESUME;
- return statusClientError; // client side error
- }
- kdDebug(7102) << "copy: resuming at " << hCopyOffset << endl;
- }
- else
- iCopyFile = KDE_open(sPart.data(), O_CREAT | O_TRUNC | O_WRONLY, initialMode);
-
- if(iCopyFile == -1)
- {
- kdDebug(7102) << "copy: ### COULD NOT WRITE " << sCopyFile << endl;
- iError = (errno == EACCES) ? ERR_WRITE_ACCESS_DENIED
- : ERR_CANNOT_OPEN_FOR_WRITING;
- return statusClientError;
- }
-
- // delegate the real work (iError gets status) ...
- StatusCode iRes = ftpGet(iError, iCopyFile, url, hCopyOffset);
- if( ::close(iCopyFile) && iRes == statusSuccess )
- {
- iError = ERR_COULD_NOT_WRITE;
- iRes = statusClientError;
- }
-
- // handle renaming or deletion of a partial file ...
- if(bMarkPartial)
- {
- if(iRes == statusSuccess)
- { // rename ".part" on success
- if ( ::rename( sPart.data(), sDest.data() ) )
- {
- kdDebug(7102) << "copy: cannot rename " << sPart << " to " << sDest << endl;
- iError = ERR_CANNOT_RENAME_PARTIAL;
- iRes = statusClientError;
- }
- }
- else if(KDE_stat( sPart.data(), &buff ) == 0)
- { // should a very small ".part" be deleted?
- int size = config()->readNumEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE);
- if (buff.st_size < size)
- remove(sPart.data());
- }
- }
- return iRes;
-}
diff --git a/kioslave/ftp/ftp.h b/kioslave/ftp/ftp.h
deleted file mode 100644
index 8a847e6da..000000000
--- a/kioslave/ftp/ftp.h
+++ /dev/null
@@ -1,603 +0,0 @@
-// -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 2; -*-
-/* This file is part of the KDE libraries
- Copyright (C) 2000 David Faure <faure@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#ifndef __ftp_h__
-#define __ftp_h__
-
-#include <config.h>
-
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <tqcstring.h>
-#include <tqstring.h>
-
-#include <kurl.h>
-#include <kio/slavebase.h>
-#include <kextsock.h>
-#include <ksocks.h>
-
-struct FtpEntry
-{
- TQString name;
- TQString owner;
- TQString group;
- TQString link;
-
- TDEIO::filesize_t size;
- mode_t type;
- mode_t access;
- time_t date;
-};
-
-//===============================================================================
-// FtpTextReader A helper class to read text lines from a socket
-//===============================================================================
-
-#ifdef KIO_FTP_PRIVATE_INCLUDE
-class FtpSocket;
-
-class FtpTextReader
-{
-public:
- FtpTextReader() { textClear(); }
-
-/**
- * Resets the status of the object, also called from xtor
- */
- void textClear();
-
-/**
- * Read a line from the socket into m_szText. Only the first RESP_READ_LIMIT
- * characters are copied. If the server response is longer all extra data up to
- * the new-line gets discarded. An ending CR gets stripped. The number of chars
- * in the buffer is returned. Use textToLong() to check for truncation!
- */
- int textRead(FtpSocket *pSock);
-
-/**
- * An accessor to the data read by textRead()
- */
- const char* textLine() const { return m_szText; }
-
-/**
- * Returns true if the last textRead() resulted in a truncated line
- */
- bool textTooLong() const { return m_bTextTruncated; }
-
-/**
- * Returns true if the last textRead() got an EOF or an error
- */
- bool textEOF() const { return m_bTextEOF; }
-
- enum {
-
- /**
- * This is the physical size of m_szText. Only up to textReadLimit
- * characters are used to store a server reply. If the server reply
- * is longer, the stored line gets truncated - see textTooLong()!
- */
- textReadBuffer = 2048,
-
-/**
- * Max number of chars returned from textLine(). If the server
- * sends more all chars until the next new-line are discarded.
- */
- textReadLimit = 1024
- };
-
-private:
- /**
- * textRead() sets this true on trucation (e.g. line too long)
- */
- bool m_bTextTruncated;
-
- /**
- * textRead() sets this true if the read returns 0 bytes or error
- */
- bool m_bTextEOF;
-
- /**
- * textRead() fills this buffer with data
- */
- char m_szText[textReadBuffer];
-
- /**
- * the number of bytes in the current response line
- */
- int m_iTextLine;
-
- /**
- * the number of bytes in the response buffer (includes m_iRespLine)
- */
- int m_iTextBuff;
-};
-#endif // KIO_FTP_PRIVATE_INCLUDE
-
-//===============================================================================
-// FtpSocket Helper Class for Data or Control Connections
-//===============================================================================
-#ifdef KIO_FTP_PRIVATE_INCLUDE
-class FtpSocket : public FtpTextReader, public KExtendedSocket
-{
-private:
- // hide the default xtor
- FtpSocket() {}
-public:
-/**
- * The one and only public xtor. The string data passed to the
- * xtor must remain valid during the object's lifetime - it is
- * used in debug messages to identify the socket instance.
- */
- FtpSocket(const char* pszName)
- {
- m_pszName = pszName;
- m_server = -1;
- }
-
- ~FtpSocket() { closeSocket(); }
-
-/**
- * Resets the status of the object, also called from xtor
- */
- void closeSocket();
-
-/**
- * We may have a server connection socket if not in passive mode. This
- * routine returns the server socket set by setServer. The sock()
- * function will return the server socket - if it is set.
- */
- int server() const { return m_server; }
-
-/**
- * Set the server socket if arg >= 0, otherwise clear it.
- */
- void setServer(int i) { m_server = (i >= 0) ? i : -1; }
-
-/**
- * returns the effective socket that user used for read/write. See server()
- */
- int sock() const { return (m_server != -1) ? m_server : fd(); }
-
-/**
- * output an debug message via kdDebug
- */
- void debugMessage(const char* pszMsg) const;
-
-/**
- * output an error message via kdError, returns iErrorCode
- */
- int errorMessage(int iErrorCode, const char* pszMsg) const;
-
-/**
- * connect socket and set some options (reuse, keepalive, linger)
- */
- int connectSocket(int iTimeOutSec, bool bControl);
-
-/**
- * utility to simplify calls to ::setsockopt(). Uses sock().
- */
- bool setSocketOption(int opt, char*arg, socklen_t len) const;
-
-/**
- * utility to read data from the effective socket, see sock()
- */
- long read(void* pData, long iMaxlen)
- {
- return KSocks::self()->read(sock(), pData, iMaxlen);
- }
-
-/**
- * utility to write data to the effective socket, see sock()
- */
- long write(void* pData, long iMaxlen)
- {
- return KSocks::self()->write(sock(), pData, iMaxlen);
- }
-
-/**
- * Use the inherited FtpTextReader to read a line from the socket
- */
- int textRead()
- {
- return FtpTextReader::textRead(this);
- }
-
-private:
- const char* m_pszName; // set by the xtor, used for debug output
- int m_server; // socket override, see setSock()
-};
-#else
- class FtpSocket;
-#endif // KIO_FTP_PRIVATE_INCLUDE
-
-//===============================================================================
-// Ftp
-//===============================================================================
-class Ftp : public TDEIO::SlaveBase
-{
- // Ftp() {}
-
-public:
- Ftp( const TQCString &pool, const TQCString &app );
- virtual ~Ftp();
-
- virtual void setHost( const TQString& host, int port, const TQString& user, const TQString& pass );
-
- /**
- * Connects to a ftp server and logs us in
- * m_bLoggedOn is set to true if logging on was successful.
- * It is set to false if the connection becomes closed.
- *
- */
- virtual void openConnection();
-
- /**
- * Closes the connection
- */
- virtual void closeConnection();
-
- virtual void stat( const KURL &url );
-
- virtual void listDir( const KURL & url );
- virtual void mkdir( const KURL & url, int permissions );
- virtual void rename( const KURL & src, const KURL & dest, bool overwrite );
- virtual void del( const KURL & url, bool isfile );
- virtual void chmod( const KURL & url, int permissions );
-
- virtual void get( const KURL& url );
- virtual void put( const KURL& url, int permissions, bool overwrite, bool resume);
- //virtual void mimetype( const KURL& url );
-
- virtual void slave_status();
-
- /**
- * Handles the case that one side of the job is a local file
- */
- virtual void copy( const KURL &src, const KURL &dest, int permissions, bool overwrite );
-
-private:
- // ------------------------------------------------------------------------
- // All the methods named ftpXyz are lowlevel methods that are not exported.
- // The implement functionality used by the public high-level methods. Some
- // low-level methods still use error() to emit errors. This behaviour is not
- // recommended - please return a boolean status or an error code instead!
- // ------------------------------------------------------------------------
-
- /**
- * Status Code returned from ftpPut() and ftpGet(), used to select
- * source or destination url for error messages
- */
- typedef enum {
- statusSuccess,
- statusClientError,
- statusServerError
- } StatusCode;
-
- /**
- * Login Mode for ftpOpenConnection
- */
- typedef enum {
- loginDefered,
- loginExplicit,
- loginImplicit
- } LoginMode;
-
- /**
- * Connect and login to the FTP server.
- *
- * @param loginMode controls if login info should be sent<br>
- * loginDefered - must not be logged on, no login info is sent<br>
- * loginExplicit - must not be logged on, login info is sent<br>
- * loginImplicit - login info is sent if not logged on
- *
- * @return true on success (a login failure would return false).
- */
- bool ftpOpenConnection (LoginMode loginMode);
-
- /**
- * Executes any auto login macro's as specified in a .netrc file.
- */
- void ftpAutoLoginMacro ();
-
- /**
- * Called by openConnection. It logs us in.
- * m_initialPath is set to the current working directory
- * if logging on was successful.
- *
- * @return true on success.
- */
- bool ftpLogin();
-
- /**
- * ftpSendCmd - send a command (@p cmd) and read response
- *
- * @param maxretries number of time it should retry. Since it recursively
- * calls itself if it can't read the answer (this happens especially after
- * timeouts), we need to limit the recursiveness ;-)
- *
- * return true if any response received, false on error
- */
- bool ftpSendCmd( const TQCString& cmd, int maxretries = 1 );
-
- /**
- * Use the SIZE command to get the file size.
- * @param mode the size depends on the transfer mode, hence this arg.
- * @return true on success
- * Gets the size into m_size.
- */
- bool ftpSize( const TQString & path, char mode );
-
- /**
- * Set the current working directory, but only if not yet current
- */
- bool ftpFileExists(const TQString& path);
-
- /**
- * Set the current working directory, but only if not yet current
- */
- bool ftpFolder(const TQString& path, bool bReportError);
-
- /**
- * Runs a command on the ftp server like "list" or "retr". In contrast to
- * ftpSendCmd a data connection is opened. The corresponding socket
- * sData is available for reading/writing on success.
- * The connection must be closed afterwards with ftpCloseCommand.
- *
- * @param mode is 'A' or 'I'. 'A' means ASCII transfer, 'I' means binary transfer.
- * @param errorcode the command-dependent error code to emit on error
- *
- * @return true if the command was accepted by the server.
- */
- bool ftpOpenCommand( const char *command, const TQString & path, char mode,
- int errorcode, TDEIO::fileoffset_t offset = 0 );
-
- /**
- * The counterpart to openCommand.
- * Closes data sockets and then reads line sent by server at
- * end of command.
- * @return false on error (line doesn't start with '2')
- */
- bool ftpCloseCommand();
-
- /**
- * Send "TYPE I" or "TYPE A" only if required, see m_cDataMode.
- *
- * Use 'A' to select ASCII and 'I' to select BINARY mode. If
- * cMode is '?' the m_bTextMode flag is used to choose a mode.
- */
- bool ftpDataMode(char cMode);
-
- //void ftpAbortTransfer();
-
- /**
- * Used by ftpOpenCommand, return 0 on success or an error code
- */
- int ftpOpenDataConnection();
-
- /**
- * closes a data connection, see ftpOpenDataConnection()
- */
- void ftpCloseDataConnection();
-
- /**
- * Helper for ftpOpenDataConnection
- */
- int ftpOpenPASVDataConnection();
- /**
- * Helper for ftpOpenDataConnection
- */
- int ftpOpenEPSVDataConnection();
- /**
- * Helper for ftpOpenDataConnection
- */
- int ftpOpenEPRTDataConnection();
- /**
- * Helper for ftpOpenDataConnection
- */
- int ftpOpenPortDataConnection();
-
- /**
- * ftpAcceptConnect - wait for incoming connection
- *
- * return -2 on error or timeout
- * otherwise returns socket descriptor
- */
- int ftpAcceptConnect();
-
- bool ftpChmod( const TQString & path, int permissions );
-
- // used by listDir
- bool ftpOpenDir( const TQString & path );
- /**
- * Called to parse directory listings, call this until it returns false
- */
- bool ftpReadDir(FtpEntry& ftpEnt);
-
- /**
- * Helper to fill an UDSEntry
- */
- void ftpCreateUDSEntry( const TQString & filename, FtpEntry& ftpEnt, TDEIO::UDSEntry& entry, bool isDir );
-
- void ftpShortStatAnswer( const TQString& filename, bool isDir );
-
- void ftpStatAnswerNotFound( const TQString & path, const TQString & filename );
-
- /**
- * This is the internal implementation of rename() - set put().
- *
- * @return true on success.
- */
- bool ftpRename( const TQString & src, const TQString & dst, bool overwrite );
-
- /**
- * Called by openConnection. It opens the control connection to the ftp server.
- *
- * @return true on success.
- */
- bool ftpOpenControlConnection( const TQString & host, unsigned short int port );
-
- /**
- * closes the socket holding the control connection (see ftpOpenControlConnection)
- */
- void ftpCloseControlConnection();
-
- /**
- * read a response from the server (a trailing CR gets stripped)
- * @param iOffset -1 to read a new line from the server<br>
- * 0 to return the whole response string
- * >0 to return the response with iOffset chars skipped
- * @return the reponse message with iOffset chars skipped (or "" if iOffset points
- * behind the available data)
- */
- const char* ftpResponse(int iOffset);
-
- /**
- * This is the internal implementation of get() - see copy().
- *
- * IMPORTANT: the caller should call ftpCloseCommand() on return.
- * The function does not call error(), the caller should do this.
- *
- * @param iError set to an ERR_xxxx code on error
- * @param iCopyFile -1 -or- handle of a local destination file
- * @param hCopyOffset local file only: non-zero for resume
- * @return 0 for success, -1 for server error, -2 for client error
- */
- StatusCode ftpGet(int& iError, int iCopyFile, const KURL& url, TDEIO::fileoffset_t hCopyOffset);
-
- /**
- * This is the internal implementation of put() - see copy().
- *
- * IMPORTANT: the caller should call ftpCloseCommand() on return.
- * The function does not call error(), the caller should do this.
- *
- * @param iError set to an ERR_xxxx code on error
- * @param iCopyFile -1 -or- handle of a local source file
- * @return 0 for success, -1 for server error, -2 for client error
- */
- StatusCode ftpPut(int& iError, int iCopyFile, const KURL& url, int permissions, bool overwrite, bool resume);
-
- /**
- * helper called from copy() to implement FILE -> FTP transfers
- *
- * @param iError set to an ERR_xxxx code on error
- * @param iCopyFile [out] handle of a local source file
- * @param sCopyFile path of the local source file
- * @return 0 for success, -1 for server error, -2 for client error
- */
- StatusCode ftpCopyPut(int& iError, int& iCopyFile, TQString sCopyFile, const KURL& url, int permissions, bool overwrite);
-
- /**
- * helper called from copy() to implement FTP -> FILE transfers
- *
- * @param iError set to an ERR_xxxx code on error
- * @param iCopyFile [out] handle of a local source file
- * @param sCopyFile path of the local destination file
- * @return 0 for success, -1 for server error, -2 for client error
- */
- StatusCode ftpCopyGet(int& iError, int& iCopyFile, TQString sCopyFile, const KURL& url, int permissions, bool overwrite);
-
-private: // data members
-
- TQString m_host;
- unsigned short int m_port;
- TQString m_user;
- TQString m_pass;
- /**
- * Where we end up after connecting
- */
- TQString m_initialPath;
- KURL m_proxyURL;
-
- /**
- * the current working directory - see ftpFolder
- */
- TQString m_currentPath;
-
- /**
- * the status returned by the FTP protocol, set in ftpResponse()
- */
- int m_iRespCode;
-
- /**
- * the status/100 returned by the FTP protocol, set in ftpResponse()
- */
- int m_iRespType;
-
- /**
- * This flag is maintained by ftpDataMode() and contains I or A after
- * ftpDataMode() has successfully set the mode.
- */
- char m_cDataMode;
-
- /**
- * true if logged on (m_control should also be non-NULL)
- */
- bool m_bLoggedOn;
-
- /**
- * true if a "textmode" metadata key was found by ftpLogin(). This
- * switches the ftp data transfer mode from binary to ASCII.
- */
- bool m_bTextMode;
-
- /**
- * true if a data stream is open, used in closeConnection().
- *
- * When the user cancels a get or put command the Ftp dtor will be called,
- * which in turn calls closeConnection(). The later would try to send QUIT
- * which won't work until timeout. ftpOpenCommand sets the m_bBusy flag so
- * that the sockets will be closed immedeately - the server should be
- * capable of handling this and return an error code on thru the control
- * connection. The m_bBusy gets cleared by the ftpCloseCommand() routine.
- */
- bool m_bBusy;
-
- bool m_bPasv;
- bool m_bUseProxy;
-
- TDEIO::filesize_t m_size;
- static TDEIO::filesize_t UnknownSize;
-
- enum
- {
- epsvUnknown = 0x01,
- epsvAllUnknown = 0x02,
- eprtUnknown = 0x04,
- epsvAllSent = 0x10,
- pasvUnknown = 0x20,
- chmodUnknown = 0x100
- };
- int m_extControl;
-
- /**
- * control connection socket, only set if openControl() succeeded
- */
- FtpSocket *m_control;
-
- /**
- * data connection socket
- */
- FtpSocket *m_data;
-};
-
-#endif
diff --git a/kioslave/ftp/ftp.protocol b/kioslave/ftp/ftp.protocol
deleted file mode 100644
index 3af1e33ec..000000000
--- a/kioslave/ftp/ftp.protocol
+++ /dev/null
@@ -1,18 +0,0 @@
-[Protocol]
-exec=kio_ftp
-protocol=ftp
-input=none
-output=filesystem
-copyToFile=true
-copyFromFile=true
-listing=Name,Type,Size,Date,Access,Owner,Group,Link,
-reading=true
-writing=true
-makedir=true
-deleting=true
-moving=true
-ProxiedBy=http
-Icon=ftp
-maxInstances=2
-DocPath=kioslave/ftp.html
-Class=:internet
diff --git a/kioslave/gzip/CMakeLists.txt b/kioslave/gzip/CMakeLists.txt
deleted file mode 100644
index e71908c31..000000000
--- a/kioslave/gzip/CMakeLists.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install( FILES kgzipfilter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-##### kgzipfilter ###############################
-
-set( target kgzipfilter )
-
-set( ${target}_SRCS
- kgzipfilter.cpp
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kioslave/gzip/Makefile.am b/kioslave/gzip/Makefile.am
deleted file mode 100644
index 0ec2e03c9..000000000
--- a/kioslave/gzip/Makefile.am
+++ /dev/null
@@ -1,12 +0,0 @@
-INCLUDES = -I$(top_srcdir)/kio $(all_includes)
-AM_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-METASOURCES = AUTO
-
-kde_module_LTLIBRARIES = kgzipfilter.la
-
-kgzipfilter_la_SOURCES = kgzipfilter.cpp
-kgzipfilter_la_LIBADD = $(LIB_KIO) $(LIBZ) $(LIB_QT) $(LIB_TDECORE)
-kgzipfilter_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
-
-kde_services_DATA = kgzipfilter.desktop
-
diff --git a/kioslave/http/CMakeLists.txt b/kioslave/http/CMakeLists.txt
deleted file mode 100644
index c093df483..000000000
--- a/kioslave/http/CMakeLists.txt
+++ /dev/null
@@ -1,69 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-add_subdirectory( kcookiejar )
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore/network
- ${CMAKE_SOURCE_DIR}/interfaces
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/httpfilter
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install( FILES
- http_cache_cleaner.desktop http.protocol https.protocol
- webdav.protocol webdavs.protocol
- DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-##### kio_http_cache_cleaner ####################
-
-set( target kio_http_cache_cleaner )
-
-set( ${target}_SRCS
- http_cache_cleaner.cpp
-)
-
-tde_add_tdeinit_executable( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
-)
-
-
-##### kio_http ##################################
-
-# FIXME GSSAPI support is not handled yet
-
-set( target kio_http )
-
-set( ${target}_SRCS
- http.cc
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK httpfilter-static tdentlm-shared kio-shared
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kioslave/http/Makefile.am b/kioslave/http/Makefile.am
deleted file mode 100644
index 5946fc9f8..000000000
--- a/kioslave/http/Makefile.am
+++ /dev/null
@@ -1,31 +0,0 @@
-# $Id$
-# Makefile.am of tdebase/kioslave/http
-
-SUBDIRS = kcookiejar
-
-INCLUDES= -I$(top_srcdir)/interfaces -I$(top_srcdir)/kio/httpfilter -I$(top_srcdir)/tdecore/network $(all_includes) $(GSSAPI_INCS)
-AM_LDFLAGS = $(all_libraries) $(GSSAPI_RPATH)
-
-####### Files
-
-bin_PROGRAMS=
-lib_LTLIBRARIES=
-tdeinit_LTLIBRARIES = kio_http_cache_cleaner.la
-kde_module_LTLIBRARIES = kio_http.la
-
-kio_http_la_SOURCES = http.cc
-kio_http_la_METASOURCES = AUTO
-kio_http_la_LIBADD = $(LIB_KIO) $(top_builddir)/kio/httpfilter/libhttpfilter.la $(LIB_QT) $(LIB_TDECORE) $(LIBZ) $(top_builddir)/dcop/libDCOP.la $(top_builddir)/kio/misc/tdentlm/libtdentlm.la
-kio_http_la_LDFLAGS = $(all_libraries) $(GSSAPI_RPATH) -module $(KDE_PLUGIN) $(GSSAPI_LIBS)
-
-kio_http_cache_cleaner_la_SOURCES = http_cache_cleaner.cpp
-kio_http_cache_cleaner_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la
-kio_http_cache_cleaner_la_LDFLAGS = -module -avoid-version
-
-noinst_HEADERS = http.h
-
-kdelnkdir = $(kde_servicesdir)
-kdelnk_DATA = http_cache_cleaner.desktop http.protocol https.protocol \
- webdav.protocol webdavs.protocol
-
-include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kioslave/http/THOUGHTS b/kioslave/http/THOUGHTS
deleted file mode 100644
index 9715b5c2f..000000000
--- a/kioslave/http/THOUGHTS
+++ /dev/null
@@ -1,28 +0,0 @@
-Here's a few ideas for those with blistered hands and nothing better to
-do:
-
-SSL certificate verification:
-We do establish SSL connections, but we never actually verify a
-certificate!
-
-HTTP/1.1 Persistant Connections:
-The header often specifies the timeout value used for connections.
-Close the connection ourselves when the timeout has expired. That way
-we don't loose time sending stuff to an already closed connection.
-
-Rating(s) support. http://www.w3.org/PICS
-This might involve an external program to parse the labels, and something
-to configure access.
-
-WebDAV support. MSIE5 calls it web folders support, and a similar
-approach would probably be a good idea. Perhaps with an exists()
-function.. one could tell if an http url was part of a WebDAV collection..
-and this could be used for some kind of integration with kfile... to
-provide seamless integration. Uhm, also, this might entail an external
-program (xml parser and such).
-
-"Friendly" error messages. How often have you seen a useless 404 message?
-Again something I first notied in MSIE5, and that would be some sort of
-translation of what an error really means. Yes this would have to be
-i18n'd and easily turned off. But this could also be extended to all the
-slaves (ftp, pop3, etc, etc).
diff --git a/kioslave/http/http.cc b/kioslave/http/http.cc
deleted file mode 100644
index e1eefa595..000000000
--- a/kioslave/http/http.cc
+++ /dev/null
@@ -1,6108 +0,0 @@
-/*
- Copyright (C) 2000-2003 Waldo Bastian <bastian@kde.org>
- Copyright (C) 2000-2002 George Staikos <staikos@kde.org>
- Copyright (C) 2000-2002 Dawit Alemayehu <adawit@kde.org>
- Copyright (C) 2001,2002 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License (LGPL) as published by the Free Software Foundation;
- either version 2 of the License, or (at your option) any later
- version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <config.h>
-
-#include <errno.h>
-#include <fcntl.h>
-#include <utime.h>
-#include <stdlib.h>
-#include <signal.h>
-#include <sys/stat.h>
-#include <sys/socket.h>
-#include <netinet/in.h> // Required for AIX
-#include <netinet/tcp.h>
-#include <unistd.h> // must be explicitly included for MacOSX
-
-/*
-#include <netdb.h>
-#include <sys/time.h>
-#include <sys/wait.h>
-*/
-
-#include <tqdom.h>
-#include <tqfile.h>
-#include <tqregexp.h>
-#include <tqdatetime.h>
-#include <tqstringlist.h>
-#include <tqurl.h>
-
-#include <kurl.h>
-#include <kidna.h>
-#include <ksocks.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kconfig.h>
-#include <kextsock.h>
-#include <kservice.h>
-#include <krfcdate.h>
-#include <kmdcodec.h>
-#include <kinstance.h>
-#include <kresolver.h>
-#include <kmimemagic.h>
-#include <dcopclient.h>
-#include <kdatastream.h>
-#include <kapplication.h>
-#include <kstandarddirs.h>
-#include <kstringhandler.h>
-#include <kremoteencoding.h>
-
-#include "kio/ioslave_defaults.h"
-#include "kio/http_slave_defaults.h"
-
-#include "httpfilter.h"
-#include "http.h"
-
-#ifdef HAVE_LIBGSSAPI
-#ifdef GSSAPI_MIT
-#include <gssapi/gssapi.h>
-#else
-#include <gssapi.h>
-#endif /* GSSAPI_MIT */
-
-// Catch uncompatible crap (BR86019)
-#if defined(GSS_RFC_COMPLIANT_OIDS) && (GSS_RFC_COMPLIANT_OIDS == 0)
-#include <gssapi/gssapi_generic.h>
-#define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
-#endif
-
-#endif /* HAVE_LIBGSSAPI */
-
-#include <misc/tdentlm/tdentlm.h>
-
-using namespace TDEIO;
-
-extern "C" {
- KDE_EXPORT int kdemain(int argc, char **argv);
-}
-
-int kdemain( int argc, char **argv )
-{
- KLocale::setMainCatalogue("tdelibs");
- TDEInstance instance( "kio_http" );
- ( void ) TDEGlobal::locale();
-
- if (argc != 4)
- {
- fprintf(stderr, "Usage: kio_http protocol domain-socket1 domain-socket2\n");
- exit(-1);
- }
-
- HTTPProtocol slave(argv[1], argv[2], argv[3]);
- slave.dispatchLoop();
- return 0;
-}
-
-/*********************************** Generic utility functions ********************/
-
-static char * trimLead (char *orig_string)
-{
- while (*orig_string == ' ')
- orig_string++;
- return orig_string;
-}
-
-static bool isCrossDomainRequest( const TQString& fqdn, const TQString& originURL )
-{
- if (originURL == "true") // Backwards compatibility
- return true;
-
- KURL url ( originURL );
-
- // Document Origin domain
- TQString a = url.host();
-
- // Current request domain
- TQString b = fqdn;
-
- if (a == b)
- return false;
-
- TQStringList l1 = TQStringList::split('.', a);
- TQStringList l2 = TQStringList::split('.', b);
-
- while(l1.count() > l2.count())
- l1.pop_front();
-
- while(l2.count() > l1.count())
- l2.pop_front();
-
- while(l2.count() >= 2)
- {
- if (l1 == l2)
- return false;
-
- l1.pop_front();
- l2.pop_front();
- }
-
- return true;
-}
-
-/*
- Eliminates any custom header that could potentically alter the request
-*/
-static TQString sanitizeCustomHTTPHeader(const TQString& _header)
-{
- TQString sanitizedHeaders;
- TQStringList headers = TQStringList::split(TQRegExp("[\r\n]"), _header);
-
- for(TQStringList::Iterator it = headers.begin(); it != headers.end(); ++it)
- {
- TQString header = (*it).lower();
- // Do not allow Request line to be specified and ignore
- // the other HTTP headers.
- if (header.find(':') == -1 ||
- header.startsWith("host") ||
- header.startsWith("via"))
- continue;
-
- sanitizedHeaders += (*it);
- sanitizedHeaders += "\r\n";
- }
-
- return sanitizedHeaders.stripWhiteSpace();
-}
-
-
-#define NO_SIZE ((TDEIO::filesize_t) -1)
-
-#ifdef HAVE_STRTOLL
-#define STRTOLL strtoll
-#else
-#define STRTOLL strtol
-#endif
-
-
-/************************************** HTTPProtocol **********************************************/
-
-HTTPProtocol::HTTPProtocol( const TQCString &protocol, const TQCString &pool,
- const TQCString &app )
- :TCPSlaveBase( 0, protocol , pool, app,
- (protocol == "https" || protocol == "webdavs") )
-{
- m_requestQueue.setAutoDelete(true);
-
- m_bBusy = false;
- m_bFirstRequest = false;
- m_bProxyAuthValid = false;
-
- m_iSize = NO_SIZE;
- m_lineBufUnget = 0;
-
- m_protocol = protocol;
-
- m_maxCacheAge = DEFAULT_MAX_CACHE_AGE;
- m_maxCacheSize = DEFAULT_MAX_CACHE_SIZE / 2;
- m_remoteConnTimeout = DEFAULT_CONNECT_TIMEOUT;
- m_remoteRespTimeout = DEFAULT_RESPONSE_TIMEOUT;
- m_proxyConnTimeout = DEFAULT_PROXY_CONNECT_TIMEOUT;
-
- m_pid = getpid();
-
- setMultipleAuthCaching( true );
- reparseConfiguration();
-}
-
-HTTPProtocol::~HTTPProtocol()
-{
- httpClose(false);
-}
-
-void HTTPProtocol::reparseConfiguration()
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::reparseConfiguration" << endl;
-
- m_strProxyRealm = TQString::null;
- m_strProxyAuthorization = TQString::null;
- ProxyAuthentication = AUTH_None;
- m_bUseProxy = false;
-
- if (m_protocol == "https" || m_protocol == "webdavs")
- m_iDefaultPort = DEFAULT_HTTPS_PORT;
- else if (m_protocol == "ftp")
- m_iDefaultPort = DEFAULT_FTP_PORT;
- else
- m_iDefaultPort = DEFAULT_HTTP_PORT;
-}
-
-void HTTPProtocol::resetConnectionSettings()
-{
- m_bEOF = false;
- m_bError = false;
- m_lineCount = 0;
- m_iWWWAuthCount = 0;
- m_lineCountUnget = 0;
- m_iProxyAuthCount = 0;
-
-}
-
-void HTTPProtocol::resetResponseSettings()
-{
- m_bRedirect = false;
- m_redirectLocation = KURL();
- m_bChunked = false;
- m_iSize = NO_SIZE;
-
- m_responseHeader.clear();
- m_qContentEncodings.clear();
- m_qTransferEncodings.clear();
- m_sContentMD5 = TQString::null;
- m_strMimeType = TQString::null;
-
- setMetaData("request-id", m_request.id);
-}
-
-void HTTPProtocol::resetSessionSettings()
-{
- // Do not reset the URL on redirection if the proxy
- // URL, username or password has not changed!
- KURL proxy ( config()->readEntry("UseProxy") );
-
- if ( m_strProxyRealm.isEmpty() || !proxy.isValid() ||
- m_proxyURL.host() != proxy.host() ||
- (!proxy.user().isNull() && proxy.user() != m_proxyURL.user()) ||
- (!proxy.pass().isNull() && proxy.pass() != m_proxyURL.pass()) )
- {
- m_bProxyAuthValid = false;
- m_proxyURL = proxy;
- m_bUseProxy = m_proxyURL.isValid();
-
- kdDebug(7113) << "(" << m_pid << ") Using proxy: " << m_bUseProxy <<
- " URL: " << m_proxyURL.url() <<
- " Realm: " << m_strProxyRealm << endl;
- }
-
- m_bPersistentProxyConnection = config()->readBoolEntry("PersistentProxyConnection", false);
- kdDebug(7113) << "(" << m_pid << ") Enable Persistent Proxy Connection: "
- << m_bPersistentProxyConnection << endl;
-
- m_request.bUseCookiejar = config()->readBoolEntry("Cookies");
- m_request.bUseCache = config()->readBoolEntry("UseCache", true);
- m_request.bErrorPage = config()->readBoolEntry("errorPage", true);
- m_request.bNoAuth = config()->readBoolEntry("no-auth");
- m_strCacheDir = config()->readPathEntry("CacheDir");
- m_maxCacheAge = config()->readNumEntry("MaxCacheAge", DEFAULT_MAX_CACHE_AGE);
- m_request.window = config()->readEntry("window-id");
-
- kdDebug(7113) << "(" << m_pid << ") Window Id = " << m_request.window << endl;
- kdDebug(7113) << "(" << m_pid << ") ssl_was_in_use = "
- << metaData ("ssl_was_in_use") << endl;
-
- m_request.referrer = TQString::null;
- if ( config()->readBoolEntry("SendReferrer", true) &&
- (m_protocol == "https" || m_protocol == "webdavs" ||
- metaData ("ssl_was_in_use") != "TRUE" ) )
- {
- KURL referrerURL ( metaData("referrer") );
- if (referrerURL.isValid())
- {
- // Sanitize
- TQString protocol = referrerURL.protocol();
- if (protocol.startsWith("webdav"))
- {
- protocol.replace(0, 6, "http");
- referrerURL.setProtocol(protocol);
- }
-
- if (protocol.startsWith("http"))
- {
- referrerURL.setRef(TQString::null);
- referrerURL.setUser(TQString::null);
- referrerURL.setPass(TQString::null);
- m_request.referrer = referrerURL.url();
- }
- }
- }
-
- if ( config()->readBoolEntry("SendLanguageSettings", true) )
- {
- m_request.charsets = config()->readEntry( "Charsets", "iso-8859-1" );
-
- if ( !m_request.charsets.isEmpty() )
- m_request.charsets += DEFAULT_PARTIAL_CHARSET_HEADER;
-
- m_request.languages = config()->readEntry( "Languages", DEFAULT_LANGUAGE_HEADER );
- }
- else
- {
- m_request.charsets = TQString::null;
- m_request.languages = TQString::null;
- }
-
- // Adjust the offset value based on the "resume" meta-data.
- TQString resumeOffset = metaData("resume");
- if ( !resumeOffset.isEmpty() )
- m_request.offset = resumeOffset.toInt(); // TODO: Convert to 64 bit
- else
- m_request.offset = 0;
-
- m_request.disablePassDlg = config()->readBoolEntry("DisablePassDlg", false);
- m_request.allowCompressedPage = config()->readBoolEntry("AllowCompressedPage", true);
- m_request.id = metaData("request-id");
-
- // Store user agent for this host.
- if ( config()->readBoolEntry("SendUserAgent", true) )
- m_request.userAgent = metaData("UserAgent");
- else
- m_request.userAgent = TQString::null;
-
- // Deal with cache cleaning.
- // TODO: Find a smarter way to deal with cleaning the
- // cache ?
- if ( m_request.bUseCache )
- cleanCache();
-
- // Deal with HTTP tunneling
- if ( m_bIsSSL && m_bUseProxy && m_proxyURL.protocol() != "https" &&
- m_proxyURL.protocol() != "webdavs")
- {
- m_bNeedTunnel = true;
- setRealHost( m_request.hostname );
- kdDebug(7113) << "(" << m_pid << ") SSL tunnel: Setting real hostname to: "
- << m_request.hostname << endl;
- }
- else
- {
- m_bNeedTunnel = false;
- setRealHost( TQString::null);
- }
-
- m_responseCode = 0;
- m_prevResponseCode = 0;
-
- m_strRealm = TQString::null;
- m_strAuthorization = TQString::null;
- Authentication = AUTH_None;
-
- // Obtain the proxy and remote server timeout values
- m_proxyConnTimeout = proxyConnectTimeout();
- m_remoteConnTimeout = connectTimeout();
- m_remoteRespTimeout = responseTimeout();
-
- // Set the SSL meta-data here...
- setSSLMetaData();
-
- // Bounce back the actual referrer sent
- setMetaData("referrer", m_request.referrer);
-
- // Follow HTTP/1.1 spec and enable keep-alive by default
- // unless the remote side tells us otherwise or we determine
- // the persistent link has been terminated by the remote end.
- m_bKeepAlive = true;
- m_keepAliveTimeout = 0;
- m_bUnauthorized = false;
-
- // A single request can require multiple exchanges with the remote
- // server due to authentication challenges or SSL tunneling.
- // m_bFirstRequest is a flag that indicates whether we are
- // still processing the first request. This is important because we
- // should not force a close of a keep-alive connection in the middle
- // of the first request.
- // m_bFirstRequest is set to "true" whenever a new connection is
- // made in httpOpenConnection()
- m_bFirstRequest = false;
-}
-
-void HTTPProtocol::setHost( const TQString& host, int port,
- const TQString& user, const TQString& pass )
-{
- // Reset the webdav-capable flags for this host
- if ( m_request.hostname != host )
- m_davHostOk = m_davHostUnsupported = false;
-
- // is it an IPv6 address?
- if (host.find(':') == -1)
- {
- m_request.hostname = host;
- m_request.encoded_hostname = KIDNA::toAscii(host);
- }
- else
- {
- m_request.hostname = host;
- int pos = host.find('%');
- if (pos == -1)
- m_request.encoded_hostname = '[' + host + ']';
- else
- // don't send the scope-id in IPv6 addresses to the server
- m_request.encoded_hostname = '[' + host.left(pos) + ']';
- }
- m_request.port = (port == 0) ? m_iDefaultPort : port;
- m_request.user = user;
- m_request.passwd = pass;
-
- m_bIsTunneled = false;
-
- kdDebug(7113) << "(" << m_pid << ") Hostname is now: " << m_request.hostname <<
- " (" << m_request.encoded_hostname << ")" <<endl;
-}
-
-bool HTTPProtocol::checkRequestURL( const KURL& u )
-{
- kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::checkRequestURL: " << u.url() << endl;
-
- m_request.url = u;
-
- if (m_request.hostname.isEmpty())
- {
- error( TDEIO::ERR_UNKNOWN_HOST, i18n("No host specified."));
- return false;
- }
-
- if (u.path().isEmpty())
- {
- KURL newUrl(u);
- newUrl.setPath("/");
- redirection(newUrl);
- finished();
- return false;
- }
-
- if ( m_protocol != u.protocol().latin1() )
- {
- short unsigned int oldDefaultPort = m_iDefaultPort;
- m_protocol = u.protocol().latin1();
- reparseConfiguration();
- if ( m_iDefaultPort != oldDefaultPort &&
- m_request.port == oldDefaultPort )
- m_request.port = m_iDefaultPort;
- }
-
- resetSessionSettings();
- return true;
-}
-
-void HTTPProtocol::retrieveContent( bool dataInternal /* = false */ )
-{
- kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveContent " << endl;
- if ( !retrieveHeader( false ) )
- {
- if ( m_bError )
- return;
- }
- else
- {
- if ( !readBody( dataInternal ) && m_bError )
- return;
- }
-
- httpClose(m_bKeepAlive);
-
- // if data is required internally, don't finish,
- // it is processed before we finish()
- if ( !dataInternal )
- {
- if ((m_responseCode == 204) &&
- ((m_request.method == HTTP_GET) || (m_request.method == HTTP_POST)))
- error(ERR_NO_CONTENT, "");
- else
- finished();
- }
-}
-
-bool HTTPProtocol::retrieveHeader( bool close_connection )
-{
- kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveHeader " << endl;
- while ( 1 )
- {
- if (!httpOpen())
- return false;
-
- resetResponseSettings();
- if (!readHeader())
- {
- if ( m_bError )
- return false;
-
- if (m_bIsTunneled)
- {
- kdDebug(7113) << "(" << m_pid << ") Re-establishing SSL tunnel..." << endl;
- httpCloseConnection();
- }
- }
- else
- {
- // Do not save authorization if the current response code is
- // 4xx (client error) or 5xx (server error).
- kdDebug(7113) << "(" << m_pid << ") Previous Response: "
- << m_prevResponseCode << endl;
- kdDebug(7113) << "(" << m_pid << ") Current Response: "
- << m_responseCode << endl;
-
- if (isSSLTunnelEnabled() && m_bIsSSL && !m_bUnauthorized && !m_bError)
- {
- // If there is no error, disable tunneling
- if ( m_responseCode < 400 )
- {
- kdDebug(7113) << "(" << m_pid << ") Unset tunneling flag!" << endl;
- setEnableSSLTunnel( false );
- m_bIsTunneled = true;
- // Reset the CONNECT response code...
- m_responseCode = m_prevResponseCode;
- continue;
- }
- else
- {
- if ( !m_request.bErrorPage )
- {
- kdDebug(7113) << "(" << m_pid << ") Sending an error message!" << endl;
- error( ERR_UNKNOWN_PROXY_HOST, m_proxyURL.host() );
- return false;
- }
-
- kdDebug(7113) << "(" << m_pid << ") Sending an error page!" << endl;
- }
- }
-
- if (m_responseCode < 400 && (m_prevResponseCode == 401 ||
- m_prevResponseCode == 407))
- saveAuthorization();
- break;
- }
- }
-
- // Clear of the temporary POST buffer if it is not empty...
- if (!m_bufPOST.isEmpty())
- {
- m_bufPOST.resize(0);
- kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
- "buffer..." << endl;
- }
-
- if ( close_connection )
- {
- httpClose(m_bKeepAlive);
- finished();
- }
-
- return true;
-}
-
-void HTTPProtocol::stat(const KURL& url)
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::stat " << url.prettyURL()
- << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- if ( m_protocol != "webdav" && m_protocol != "webdavs" )
- {
- TQString statSide = metaData(TQString::fromLatin1("statSide"));
- if ( statSide != "source" )
- {
- // When uploading we assume the file doesn't exit
- error( ERR_DOES_NOT_EXIST, url.prettyURL() );
- return;
- }
-
- // When downloading we assume it exists
- UDSEntry entry;
- UDSAtom atom;
- atom.m_uds = TDEIO::UDS_NAME;
- atom.m_str = url.fileName();
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_FILE_TYPE;
- atom.m_long = S_IFREG; // a file
- entry.append( atom );
-
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = S_IRUSR | S_IRGRP | S_IROTH; // readable by everybody
- entry.append( atom );
-
- statEntry( entry );
- finished();
- return;
- }
-
- davStatList( url );
-}
-
-void HTTPProtocol::listDir( const KURL& url )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::listDir " << url.url()
- << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- if (!url.protocol().startsWith("webdav")) {
- error(ERR_UNSUPPORTED_ACTION, url.prettyURL());
- return;
- }
-
- davStatList( url, false );
-}
-
-void HTTPProtocol::davSetRequest( const TQCString& requestXML )
-{
- // insert the document into the POST buffer, kill trailing zero byte
- m_bufPOST = requestXML;
-
- if (m_bufPOST.size())
- m_bufPOST.truncate( m_bufPOST.size() - 1 );
-}
-
-void HTTPProtocol::davStatList( const KURL& url, bool stat )
-{
- UDSEntry entry;
- UDSAtom atom;
-
- // check to make sure this host supports WebDAV
- if ( !davHostOk() )
- return;
-
- // Maybe it's a disguised SEARCH...
- TQString query = metaData("davSearchQuery");
- if ( !query.isEmpty() )
- {
- TQCString request = "<?xml version=\"1.0\"?>\r\n";
- request.append( "<D:searchrequest xmlns:D=\"DAV:\">\r\n" );
- request.append( query.utf8() );
- request.append( "</D:searchrequest>\r\n" );
-
- davSetRequest( request );
- } else {
- // We are only after certain features...
- TQCString request;
- request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
- "<D:propfind xmlns:D=\"DAV:\">";
-
- // insert additional XML request from the davRequestResponse metadata
- if ( hasMetaData( "davRequestResponse" ) )
- request += metaData( "davRequestResponse" ).utf8();
- else {
- // No special request, ask for default properties
- request += "<D:prop>"
- "<D:creationdate/>"
- "<D:getcontentlength/>"
- "<D:displayname/>"
- "<D:source/>"
- "<D:getcontentlanguage/>"
- "<D:getcontenttype/>"
- "<D:executable/>"
- "<D:getlastmodified/>"
- "<D:getetag/>"
- "<D:supportedlock/>"
- "<D:lockdiscovery/>"
- "<D:resourcetype/>"
- "</D:prop>";
- }
- request += "</D:propfind>";
-
- davSetRequest( request );
- }
-
- // WebDAV Stat or List...
- m_request.method = query.isEmpty() ? DAV_PROPFIND : DAV_SEARCH;
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
- m_request.davData.depth = stat ? 0 : 1;
- if (!stat)
- m_request.url.adjustPath(+1);
-
- retrieveContent( true );
-
- // Has a redirection already been called? If so, we're done.
- if (m_bRedirect) {
- finished();
- return;
- }
-
- TQDomDocument multiResponse;
- multiResponse.setContent( m_bufWebDavData, true );
-
- bool hasResponse = false;
-
- for ( TQDomNode n = multiResponse.documentElement().firstChild();
- !n.isNull(); n = n.nextSibling())
- {
- TQDomElement thisResponse = n.toElement();
- if (thisResponse.isNull())
- continue;
-
- hasResponse = true;
-
- TQDomElement href = thisResponse.namedItem( "href" ).toElement();
- if ( !href.isNull() )
- {
- entry.clear();
-
- TQString urlStr = href.text();
-#if 0
- int encoding = remoteEncoding()->encodingMib();
- if ((encoding == 106) && (!KStringHandler::isUtf8(KURL::decode_string(urlStr, 4).latin1())))
- encoding = 4; // Use latin1 if the file is not actually utf-8
-#else
- TQUrl::decode(urlStr);
- int encoding = 106;
-#endif
-
- KURL thisURL ( urlStr, encoding );
-
- atom.m_uds = TDEIO::UDS_NAME;
-
- if ( thisURL.isValid() ) {
- // don't list the base dir of a listDir()
- if ( !stat && thisURL.path(+1).length() == url.path(+1).length() )
- continue;
-
- atom.m_str = thisURL.fileName();
- } else {
- // This is a relative URL.
- atom.m_str = href.text();
- }
-
- entry.append( atom );
-
- TQDomNodeList propstats = thisResponse.elementsByTagName( "propstat" );
-
- davParsePropstats( propstats, entry );
-
- if ( stat )
- {
- // return an item
- statEntry( entry );
- finished();
- return;
- }
- else
- {
- listEntry( entry, false );
- }
- }
- else
- {
- kdDebug(7113) << "Error: no URL contained in response to PROPFIND on "
- << url.prettyURL() << endl;
- }
- }
-
- if ( stat || !hasResponse )
- {
- error( ERR_DOES_NOT_EXIST, url.prettyURL() );
- }
- else
- {
- listEntry( entry, true );
- finished();
- }
-}
-
-void HTTPProtocol::davGeneric( const KURL& url, TDEIO::HTTP_METHOD method )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davGeneric " << url.url()
- << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- // check to make sure this host supports WebDAV
- if ( !davHostOk() )
- return;
-
- // WebDAV method
- m_request.method = method;
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveContent( false );
-}
-
-int HTTPProtocol::codeFromResponse( const TQString& response )
-{
- int firstSpace = response.find( ' ' );
- int secondSpace = response.find( ' ', firstSpace + 1 );
- return response.mid( firstSpace + 1, secondSpace - firstSpace - 1 ).toInt();
-}
-
-void HTTPProtocol::davParsePropstats( const TQDomNodeList& propstats, UDSEntry& entry )
-{
- TQString mimeType;
- UDSAtom atom;
- bool foundExecutable = false;
- bool isDirectory = false;
- uint lockCount = 0;
- uint supportedLockCount = 0;
-
- for ( uint i = 0; i < propstats.count(); i++)
- {
- TQDomElement propstat = propstats.item(i).toElement();
-
- TQDomElement status = propstat.namedItem( "status" ).toElement();
- if ( status.isNull() )
- {
- // error, no status code in this propstat
- kdDebug(7113) << "Error, no status code in this propstat" << endl;
- return;
- }
-
- int code = codeFromResponse( status.text() );
-
- if ( code != 200 )
- {
- kdDebug(7113) << "Warning: status code " << code << " (this may mean that some properties are unavailable" << endl;
- continue;
- }
-
- TQDomElement prop = propstat.namedItem( "prop" ).toElement();
- if ( prop.isNull() )
- {
- kdDebug(7113) << "Error: no prop segment in this propstat." << endl;
- return;
- }
-
- if ( hasMetaData( "davRequestResponse" ) )
- {
- atom.m_uds = TDEIO::UDS_XML_PROPERTIES;
- TQDomDocument doc;
- doc.appendChild(prop);
- atom.m_str = doc.toString();
- entry.append( atom );
- }
-
- for ( TQDomNode n = prop.firstChild(); !n.isNull(); n = n.nextSibling() )
- {
- TQDomElement property = n.toElement();
- if (property.isNull())
- continue;
-
- if ( property.namespaceURI() != "DAV:" )
- {
- // break out - we're only interested in properties from the DAV namespace
- continue;
- }
-
- if ( property.tagName() == "creationdate" )
- {
- // Resource creation date. Should be is ISO 8601 format.
- atom.m_uds = TDEIO::UDS_CREATION_TIME;
- atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
- entry.append( atom );
- }
- else if ( property.tagName() == "getcontentlength" )
- {
- // Content length (file size)
- atom.m_uds = TDEIO::UDS_SIZE;
- atom.m_long = property.text().toULong();
- entry.append( atom );
- }
- else if ( property.tagName() == "displayname" )
- {
- // Name suitable for presentation to the user
- setMetaData( "davDisplayName", property.text() );
- }
- else if ( property.tagName() == "source" )
- {
- // Source template location
- TQDomElement source = property.namedItem( "link" ).toElement()
- .namedItem( "dst" ).toElement();
- if ( !source.isNull() )
- setMetaData( "davSource", source.text() );
- }
- else if ( property.tagName() == "getcontentlanguage" )
- {
- // equiv. to Content-Language header on a GET
- setMetaData( "davContentLanguage", property.text() );
- }
- else if ( property.tagName() == "getcontenttype" )
- {
- // Content type (mime type)
- // This may require adjustments for other server-side webdav implementations
- // (tested with Apache + mod_dav 1.0.3)
- if ( property.text() == "httpd/unix-directory" )
- {
- isDirectory = true;
- }
- else
- {
- mimeType = property.text();
- }
- }
- else if ( property.tagName() == "executable" )
- {
- // File executable status
- if ( property.text() == "T" )
- foundExecutable = true;
-
- }
- else if ( property.tagName() == "getlastmodified" )
- {
- // Last modification date
- atom.m_uds = TDEIO::UDS_MODIFICATION_TIME;
- atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
- entry.append( atom );
-
- }
- else if ( property.tagName() == "getetag" )
- {
- // Entity tag
- setMetaData( "davEntityTag", property.text() );
- }
- else if ( property.tagName() == "supportedlock" )
- {
- // Supported locking specifications
- for ( TQDomNode n2 = property.firstChild(); !n2.isNull(); n2 = n2.nextSibling() )
- {
- TQDomElement lockEntry = n2.toElement();
- if ( lockEntry.tagName() == "lockentry" )
- {
- TQDomElement lockScope = lockEntry.namedItem( "lockscope" ).toElement();
- TQDomElement lockType = lockEntry.namedItem( "locktype" ).toElement();
- if ( !lockScope.isNull() && !lockType.isNull() )
- {
- // Lock type was properly specified
- supportedLockCount++;
- TQString scope = lockScope.firstChild().toElement().tagName();
- TQString type = lockType.firstChild().toElement().tagName();
-
- setMetaData( TQString("davSupportedLockScope%1").arg(supportedLockCount), scope );
- setMetaData( TQString("davSupportedLockType%1").arg(supportedLockCount), type );
- }
- }
- }
- }
- else if ( property.tagName() == "lockdiscovery" )
- {
- // Lists the available locks
- davParseActiveLocks( property.elementsByTagName( "activelock" ), lockCount );
- }
- else if ( property.tagName() == "resourcetype" )
- {
- // Resource type. "Specifies the nature of the resource."
- if ( !property.namedItem( "collection" ).toElement().isNull() )
- {
- // This is a collection (directory)
- isDirectory = true;
- }
- }
- else
- {
- kdDebug(7113) << "Found unknown webdav property: " << property.tagName() << endl;
- }
- }
- }
-
- setMetaData( "davLockCount", TQString("%1").arg(lockCount) );
- setMetaData( "davSupportedLockCount", TQString("%1").arg(supportedLockCount) );
-
- atom.m_uds = TDEIO::UDS_FILE_TYPE;
- atom.m_long = isDirectory ? S_IFDIR : S_IFREG;
- entry.append( atom );
-
- if ( foundExecutable || isDirectory )
- {
- // File was executable, or is a directory.
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = 0700;
- entry.append(atom);
- }
- else
- {
- atom.m_uds = TDEIO::UDS_ACCESS;
- atom.m_long = 0600;
- entry.append(atom);
- }
-
- if ( !isDirectory && !mimeType.isEmpty() )
- {
- atom.m_uds = TDEIO::UDS_MIME_TYPE;
- atom.m_str = mimeType;
- entry.append( atom );
- }
-}
-
-void HTTPProtocol::davParseActiveLocks( const TQDomNodeList& activeLocks,
- uint& lockCount )
-{
- for ( uint i = 0; i < activeLocks.count(); i++ )
- {
- TQDomElement activeLock = activeLocks.item(i).toElement();
-
- lockCount++;
- // required
- TQDomElement lockScope = activeLock.namedItem( "lockscope" ).toElement();
- TQDomElement lockType = activeLock.namedItem( "locktype" ).toElement();
- TQDomElement lockDepth = activeLock.namedItem( "depth" ).toElement();
- // optional
- TQDomElement lockOwner = activeLock.namedItem( "owner" ).toElement();
- TQDomElement lockTimeout = activeLock.namedItem( "timeout" ).toElement();
- TQDomElement lockToken = activeLock.namedItem( "locktoken" ).toElement();
-
- if ( !lockScope.isNull() && !lockType.isNull() && !lockDepth.isNull() )
- {
- // lock was properly specified
- lockCount++;
- TQString scope = lockScope.firstChild().toElement().tagName();
- TQString type = lockType.firstChild().toElement().tagName();
- TQString depth = lockDepth.text();
-
- setMetaData( TQString("davLockScope%1").arg( lockCount ), scope );
- setMetaData( TQString("davLockType%1").arg( lockCount ), type );
- setMetaData( TQString("davLockDepth%1").arg( lockCount ), depth );
-
- if ( !lockOwner.isNull() )
- setMetaData( TQString("davLockOwner%1").arg( lockCount ), lockOwner.text() );
-
- if ( !lockTimeout.isNull() )
- setMetaData( TQString("davLockTimeout%1").arg( lockCount ), lockTimeout.text() );
-
- if ( !lockToken.isNull() )
- {
- TQDomElement tokenVal = lockScope.namedItem( "href" ).toElement();
- if ( !tokenVal.isNull() )
- setMetaData( TQString("davLockToken%1").arg( lockCount ), tokenVal.text() );
- }
- }
- }
-}
-
-long HTTPProtocol::parseDateTime( const TQString& input, const TQString& type )
-{
- if ( type == "dateTime.tz" )
- {
- return KRFCDate::parseDateISO8601( input );
- }
- else if ( type == "dateTime.rfc1123" )
- {
- return KRFCDate::parseDate( input );
- }
-
- // format not advertised... try to parse anyway
- time_t time = KRFCDate::parseDate( input );
- if ( time != 0 )
- return time;
-
- return KRFCDate::parseDateISO8601( input );
-}
-
-TQString HTTPProtocol::davProcessLocks()
-{
- if ( hasMetaData( "davLockCount" ) )
- {
- TQString response("If:");
- int numLocks;
- numLocks = metaData( "davLockCount" ).toInt();
- bool bracketsOpen = false;
- for ( int i = 0; i < numLocks; i++ )
- {
- if ( hasMetaData( TQString("davLockToken%1").arg(i) ) )
- {
- if ( hasMetaData( TQString("davLockURL%1").arg(i) ) )
- {
- if ( bracketsOpen )
- {
- response += ")";
- bracketsOpen = false;
- }
- response += " <" + metaData( TQString("davLockURL%1").arg(i) ) + ">";
- }
-
- if ( !bracketsOpen )
- {
- response += " (";
- bracketsOpen = true;
- }
- else
- {
- response += " ";
- }
-
- if ( hasMetaData( TQString("davLockNot%1").arg(i) ) )
- response += "Not ";
-
- response += "<" + metaData( TQString("davLockToken%1").arg(i) ) + ">";
- }
- }
-
- if ( bracketsOpen )
- response += ")";
-
- response += "\r\n";
- return response;
- }
-
- return TQString::null;
-}
-
-bool HTTPProtocol::davHostOk()
-{
- // FIXME needs to be reworked. Switched off for now.
- return true;
-
- // cached?
- if ( m_davHostOk )
- {
- kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " true" << endl;
- return true;
- }
- else if ( m_davHostUnsupported )
- {
- kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " false" << endl;
- davError( -2 );
- return false;
- }
-
- m_request.method = HTTP_OPTIONS;
-
- // query the server's capabilities generally, not for a specific URL
- m_request.path = "*";
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- // clear davVersions variable, which holds the response to the DAV: header
- m_davCapabilities.clear();
-
- retrieveHeader(false);
-
- if (m_davCapabilities.count())
- {
- for (uint i = 0; i < m_davCapabilities.count(); i++)
- {
- bool ok;
- uint verNo = m_davCapabilities[i].toUInt(&ok);
- if (ok && verNo > 0 && verNo < 3)
- {
- m_davHostOk = true;
- kdDebug(7113) << "Server supports DAV version " << verNo << "." << endl;
- }
- }
-
- if ( m_davHostOk )
- return true;
- }
-
- m_davHostUnsupported = true;
- davError( -2 );
- return false;
-}
-
-// This function is for closing retrieveHeader( false ); requests
-// Required because there may or may not be further info expected
-void HTTPProtocol::davFinished()
-{
- // TODO: Check with the DAV extension developers
- httpClose(m_bKeepAlive);
- finished();
-}
-
-void HTTPProtocol::mkdir( const KURL& url, int )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mkdir " << url.url()
- << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.method = DAV_MKCOL;
- m_request.path = url.path();
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveHeader( false );
-
- if ( m_responseCode == 201 )
- davFinished();
- else
- davError();
-}
-
-void HTTPProtocol::get( const KURL& url )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::get " << url.url()
- << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.method = HTTP_GET;
- m_request.path = url.path();
- m_request.query = url.query();
-
- TQString tmp = metaData("cache");
- if (!tmp.isEmpty())
- m_request.cache = parseCacheControl(tmp);
- else
- m_request.cache = DEFAULT_CACHE_CONTROL;
-
- m_request.passwd = url.pass();
- m_request.user = url.user();
- m_request.doProxy = m_bUseProxy;
-
- retrieveContent();
-}
-
-void HTTPProtocol::put( const KURL &url, int, bool overwrite, bool)
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put " << url.prettyURL()
- << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- // Webdav hosts are capable of observing overwrite == false
- if (!overwrite && m_protocol.left(6) == "webdav") {
- // check to make sure this host supports WebDAV
- if ( !davHostOk() )
- return;
-
- TQCString request;
- request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
- "<D:propfind xmlns:D=\"DAV:\"><D:prop>"
- "<D:creationdate/>"
- "<D:getcontentlength/>"
- "<D:displayname/>"
- "<D:resourcetype/>"
- "</D:prop></D:propfind>";
-
- davSetRequest( request );
-
- // WebDAV Stat or List...
- m_request.method = DAV_PROPFIND;
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
- m_request.davData.depth = 0;
-
- retrieveContent(true);
-
- if (m_responseCode == 207) {
- error(ERR_FILE_ALREADY_EXIST, TQString::null);
- return;
- }
-
- m_bError = false;
- }
-
- m_request.method = HTTP_PUT;
- m_request.path = url.path();
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveHeader( false );
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put error = " << m_bError << endl;
- if (m_bError)
- return;
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put responseCode = " << m_responseCode << endl;
-
- httpClose(false); // Always close connection.
-
- if ( (m_responseCode >= 200) && (m_responseCode < 300) )
- finished();
- else
- httpError();
-}
-
-void HTTPProtocol::copy( const KURL& src, const KURL& dest, int, bool overwrite )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::copy " << src.prettyURL()
- << " -> " << dest.prettyURL() << endl;
-
- if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
- return;
-
- // destination has to be "http(s)://..."
- KURL newDest = dest;
- if (newDest.protocol() == "webdavs")
- newDest.setProtocol("https");
- else
- newDest.setProtocol("http");
-
- m_request.method = DAV_COPY;
- m_request.path = src.path();
- m_request.davData.desturl = newDest.url();
- m_request.davData.overwrite = overwrite;
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveHeader( false );
-
- // The server returns a HTTP/1.1 201 Created or 204 No Content on successful completion
- if ( m_responseCode == 201 || m_responseCode == 204 )
- davFinished();
- else
- davError();
-}
-
-void HTTPProtocol::rename( const KURL& src, const KURL& dest, bool overwrite )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::rename " << src.prettyURL()
- << " -> " << dest.prettyURL() << endl;
-
- if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
- return;
-
- // destination has to be "http://..."
- KURL newDest = dest;
- if (newDest.protocol() == "webdavs")
- newDest.setProtocol("https");
- else
- newDest.setProtocol("http");
-
- m_request.method = DAV_MOVE;
- m_request.path = src.path();
- m_request.davData.desturl = newDest.url();
- m_request.davData.overwrite = overwrite;
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveHeader( false );
-
- if ( m_responseCode == 301 )
- {
- // Work around strict Apache-2 WebDAV implementation which refuses to cooperate
- // with webdav://host/directory, instead requiring webdav://host/directory/
- // (strangely enough it accepts Destination: without a trailing slash)
-
- if (m_redirectLocation.protocol() == "https")
- m_redirectLocation.setProtocol("webdavs");
- else
- m_redirectLocation.setProtocol("webdav");
-
- if ( !checkRequestURL( m_redirectLocation ) )
- return;
-
- m_request.method = DAV_MOVE;
- m_request.path = m_redirectLocation.path();
- m_request.davData.desturl = newDest.url();
- m_request.davData.overwrite = overwrite;
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveHeader( false );
- }
-
- if ( m_responseCode == 201 )
- davFinished();
- else
- davError();
-}
-
-void HTTPProtocol::del( const KURL& url, bool )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::del " << url.prettyURL()
- << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.method = HTTP_DELETE;
- m_request.path = url.path();
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveHeader( false );
-
- // The server returns a HTTP/1.1 200 Ok or HTTP/1.1 204 No Content
- // on successful completion
- if ( m_responseCode == 200 || m_responseCode == 204 )
- davFinished();
- else
- davError();
-}
-
-void HTTPProtocol::post( const KURL& url )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::post "
- << url.prettyURL() << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.method = HTTP_POST;
- m_request.path = url.path();
- m_request.query = url.query();
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveContent();
-}
-
-void HTTPProtocol::davLock( const KURL& url, const TQString& scope,
- const TQString& type, const TQString& owner )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davLock "
- << url.prettyURL() << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.method = DAV_LOCK;
- m_request.path = url.path();
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- /* Create appropriate lock XML request. */
- TQDomDocument lockReq;
-
- TQDomElement lockInfo = lockReq.createElementNS( "DAV:", "lockinfo" );
- lockReq.appendChild( lockInfo );
-
- TQDomElement lockScope = lockReq.createElement( "lockscope" );
- lockInfo.appendChild( lockScope );
-
- lockScope.appendChild( lockReq.createElement( scope ) );
-
- TQDomElement lockType = lockReq.createElement( "locktype" );
- lockInfo.appendChild( lockType );
-
- lockType.appendChild( lockReq.createElement( type ) );
-
- if ( !owner.isNull() ) {
- TQDomElement ownerElement = lockReq.createElement( "owner" );
- lockReq.appendChild( ownerElement );
-
- TQDomElement ownerHref = lockReq.createElement( "href" );
- ownerElement.appendChild( ownerHref );
-
- ownerHref.appendChild( lockReq.createTextNode( owner ) );
- }
-
- // insert the document into the POST buffer
- m_bufPOST = lockReq.toCString();
-
- retrieveContent( true );
-
- if ( m_responseCode == 200 ) {
- // success
- TQDomDocument multiResponse;
- multiResponse.setContent( m_bufWebDavData, true );
-
- TQDomElement prop = multiResponse.documentElement().namedItem( "prop" ).toElement();
-
- TQDomElement lockdiscovery = prop.namedItem( "lockdiscovery" ).toElement();
-
- uint lockCount = 0;
- davParseActiveLocks( lockdiscovery.elementsByTagName( "activelock" ), lockCount );
-
- setMetaData( "davLockCount", TQString("%1").arg( lockCount ) );
-
- finished();
-
- } else
- davError();
-}
-
-void HTTPProtocol::davUnlock( const KURL& url )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davUnlock "
- << url.prettyURL() << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.method = DAV_UNLOCK;
- m_request.path = url.path();
- m_request.query = TQString::null;
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- retrieveContent( true );
-
- if ( m_responseCode == 200 )
- finished();
- else
- davError();
-}
-
-TQString HTTPProtocol::davError( int code /* = -1 */, TQString url )
-{
- bool callError = false;
- if ( code == -1 ) {
- code = m_responseCode;
- callError = true;
- }
- if ( code == -2 ) {
- callError = true;
- }
-
- if ( !url.isNull() )
- url = m_request.url.url();
-
- TQString action, errorString;
- TDEIO::Error kError;
-
- // for 412 Precondition Failed
- TQString ow = i18n( "Otherwise, the request would have succeeded." );
-
- switch ( m_request.method ) {
- case DAV_PROPFIND:
- action = i18n( "retrieve property values" );
- break;
- case DAV_PROPPATCH:
- action = i18n( "set property values" );
- break;
- case DAV_MKCOL:
- action = i18n( "create the requested folder" );
- break;
- case DAV_COPY:
- action = i18n( "copy the specified file or folder" );
- break;
- case DAV_MOVE:
- action = i18n( "move the specified file or folder" );
- break;
- case DAV_SEARCH:
- action = i18n( "search in the specified folder" );
- break;
- case DAV_LOCK:
- action = i18n( "lock the specified file or folder" );
- break;
- case DAV_UNLOCK:
- action = i18n( "unlock the specified file or folder" );
- break;
- case HTTP_DELETE:
- action = i18n( "delete the specified file or folder" );
- break;
- case HTTP_OPTIONS:
- action = i18n( "query the server's capabilities" );
- break;
- case HTTP_GET:
- action = i18n( "retrieve the contents of the specified file or folder" );
- break;
- case HTTP_PUT:
- case HTTP_POST:
- case HTTP_HEAD:
- default:
- // this should not happen, this function is for webdav errors only
- Q_ASSERT(0);
- }
-
- // default error message if the following code fails
- kError = ERR_INTERNAL;
- errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
- .arg( code ).arg( action );
-
- switch ( code )
- {
- case -2:
- // internal error: OPTIONS request did not specify DAV compliance
- kError = ERR_UNSUPPORTED_PROTOCOL;
- errorString = i18n("The server does not support the WebDAV protocol.");
- break;
- case 207:
- // 207 Multi-status
- {
- // our error info is in the returned XML document.
- // retrieve the XML document
-
- // there was an error retrieving the XML document.
- // ironic, eh?
- if ( !readBody( true ) && m_bError )
- return TQString::null;
-
- TQStringList errors;
- TQDomDocument multiResponse;
-
- multiResponse.setContent( m_bufWebDavData, true );
-
- TQDomElement multistatus = multiResponse.documentElement().namedItem( "multistatus" ).toElement();
-
- TQDomNodeList responses = multistatus.elementsByTagName( "response" );
-
- for (uint i = 0; i < responses.count(); i++)
- {
- int errCode;
- TQString errUrl;
-
- TQDomElement response = responses.item(i).toElement();
- TQDomElement code = response.namedItem( "status" ).toElement();
-
- if ( !code.isNull() )
- {
- errCode = codeFromResponse( code.text() );
- TQDomElement href = response.namedItem( "href" ).toElement();
- if ( !href.isNull() )
- errUrl = href.text();
- errors << davError( errCode, errUrl );
- }
- }
-
- //kError = ERR_SLAVE_DEFINED;
- errorString = i18n("An error occurred while attempting to %1, %2. A "
- "summary of the reasons is below.<ul>").arg( action ).arg( url );
-
- for ( TQStringList::Iterator it = errors.begin(); it != errors.end(); ++it )
- errorString += "<li>" + *it + "</li>";
-
- errorString += "</ul>";
- }
- case 403:
- case 500: // hack: Apache mod_dav returns this instead of 403 (!)
- // 403 Forbidden
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("Access was denied while attempting to %1.").arg( action );
- break;
- case 405:
- // 405 Method Not Allowed
- if ( m_request.method == DAV_MKCOL )
- {
- kError = ERR_DIR_ALREADY_EXIST;
- errorString = i18n("The specified folder already exists.");
- }
- break;
- case 409:
- // 409 Conflict
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("A resource cannot be created at the destination "
- "until one or more intermediate collections (folders) "
- "have been created.");
- break;
- case 412:
- // 412 Precondition failed
- if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
- {
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("The server was unable to maintain the liveness of "
- "the properties listed in the propertybehavior XML "
- "element or you attempted to overwrite a file while "
- "requesting that files are not overwritten. %1")
- .arg( ow );
-
- }
- else if ( m_request.method == DAV_LOCK )
- {
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("The requested lock could not be granted. %1").arg( ow );
- }
- break;
- case 415:
- // 415 Unsupported Media Type
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("The server does not support the request type of the body.");
- break;
- case 423:
- // 423 Locked
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
- break;
- case 425:
- // 424 Failed Dependency
- errorString = i18n("This action was prevented by another error.");
- break;
- case 502:
- // 502 Bad Gateway
- if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
- {
- kError = ERR_WRITE_ACCESS_DENIED;
- errorString = i18n("Unable to %1 because the destination server refuses "
- "to accept the file or folder.").arg( action );
- }
- break;
- case 507:
- // 507 Insufficient Storage
- kError = ERR_DISK_FULL;
- errorString = i18n("The destination resource does not have sufficient space "
- "to record the state of the resource after the execution "
- "of this method.");
- break;
- }
-
- // if ( kError != ERR_SLAVE_DEFINED )
- //errorString += " (" + url + ")";
-
- if ( callError )
- error( ERR_SLAVE_DEFINED, errorString );
-
- return errorString;
-}
-
-void HTTPProtocol::httpError()
-{
- TQString action, errorString;
- TDEIO::Error kError;
-
- switch ( m_request.method ) {
- case HTTP_PUT:
- action = i18n( "upload %1" ).arg(m_request.url.prettyURL());
- break;
- default:
- // this should not happen, this function is for http errors only
- Q_ASSERT(0);
- }
-
- // default error message if the following code fails
- kError = ERR_INTERNAL;
- errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
- .arg( m_responseCode ).arg( action );
-
- switch ( m_responseCode )
- {
- case 403:
- case 405:
- case 500: // hack: Apache mod_dav returns this instead of 403 (!)
- // 403 Forbidden
- // 405 Method Not Allowed
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("Access was denied while attempting to %1.").arg( action );
- break;
- case 409:
- // 409 Conflict
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("A resource cannot be created at the destination "
- "until one or more intermediate collections (folders) "
- "have been created.");
- break;
- case 423:
- // 423 Locked
- kError = ERR_ACCESS_DENIED;
- errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
- break;
- case 502:
- // 502 Bad Gateway
- kError = ERR_WRITE_ACCESS_DENIED;
- errorString = i18n("Unable to %1 because the destination server refuses "
- "to accept the file or folder.").arg( action );
- break;
- case 507:
- // 507 Insufficient Storage
- kError = ERR_DISK_FULL;
- errorString = i18n("The destination resource does not have sufficient space "
- "to record the state of the resource after the execution "
- "of this method.");
- break;
- }
-
- // if ( kError != ERR_SLAVE_DEFINED )
- //errorString += " (" + url + ")";
-
- error( ERR_SLAVE_DEFINED, errorString );
-}
-
-bool HTTPProtocol::isOffline(const KURL &url)
-{
- const int NetWorkStatusUnknown = 1;
- const int NetWorkStatusOnline = 8;
- TQCString replyType;
- TQByteArray params;
- TQByteArray reply;
-
- TQDataStream stream(params, IO_WriteOnly);
-
- if ( url.host() == TQString::fromLatin1("localhost") || url.host() == TQString::fromLatin1("127.0.0.1") || url.host() == TQString::fromLatin1("::") ) {
- return false;
- }
- if ( dcopClient()->call( "kded", "networkstatus", "status()",
- params, replyType, reply ) && (replyType == "int") )
- {
- int result;
- TQDataStream stream2( reply, IO_ReadOnly );
- stream2 >> result;
- kdDebug(7113) << "(" << m_pid << ") networkstatus status = " << result << endl;
- return (result != NetWorkStatusUnknown) && (result != NetWorkStatusOnline);
- }
- kdDebug(7113) << "(" << m_pid << ") networkstatus <unreachable>" << endl;
- return false; // On error, assume we are online
-}
-
-void HTTPProtocol::multiGet(const TQByteArray &data)
-{
- TQDataStream stream(data, IO_ReadOnly);
- TQ_UINT32 n;
- stream >> n;
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtcool::multiGet n = " << n << endl;
-
- HTTPRequest saveRequest;
- if (m_bBusy)
- saveRequest = m_request;
-
-// m_requestQueue.clear();
- for(unsigned i = 0; i < n; i++)
- {
- KURL url;
- stream >> url >> mIncomingMetaData;
-
- if ( !checkRequestURL( url ) )
- continue;
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::multi_get " << url.url() << endl;
-
- m_request.method = HTTP_GET;
- m_request.path = url.path();
- m_request.query = url.query();
- TQString tmp = metaData("cache");
- if (!tmp.isEmpty())
- m_request.cache = parseCacheControl(tmp);
- else
- m_request.cache = DEFAULT_CACHE_CONTROL;
-
- m_request.passwd = url.pass();
- m_request.user = url.user();
- m_request.doProxy = m_bUseProxy;
-
- HTTPRequest *newRequest = new HTTPRequest(m_request);
- m_requestQueue.append(newRequest);
- }
-
- if (m_bBusy)
- m_request = saveRequest;
-
- if (!m_bBusy)
- {
- m_bBusy = true;
- while(!m_requestQueue.isEmpty())
- {
- HTTPRequest *request = m_requestQueue.take(0);
- m_request = *request;
- delete request;
- retrieveContent();
- }
- m_bBusy = false;
- }
-}
-
-ssize_t HTTPProtocol::write (const void *_buf, size_t nbytes)
-{
- int bytes_sent = 0;
- const char* buf = static_cast<const char*>(_buf);
- while ( nbytes > 0 )
- {
- int n = TCPSlaveBase::write(buf, nbytes);
-
- if ( n <= 0 )
- {
- // remote side closed connection ?
- if ( n == 0 )
- break;
- // a valid exception(s) occurred, let's retry...
- if (n < 0 && ((errno == EINTR) || (errno == EAGAIN)))
- continue;
- // some other error occurred ?
- return -1;
- }
-
- nbytes -= n;
- buf += n;
- bytes_sent += n;
- }
-
- return bytes_sent;
-}
-
-void HTTPProtocol::setRewindMarker()
-{
- m_rewindCount = 0;
-}
-
-void HTTPProtocol::rewind()
-{
- m_linePtrUnget = m_rewindBuf,
- m_lineCountUnget = m_rewindCount;
- m_rewindCount = 0;
-}
-
-
-char *HTTPProtocol::gets (char *s, int size)
-{
- int len=0;
- char *buf=s;
- char mybuf[2]={0,0};
-
- while (len < size)
- {
- read(mybuf, 1);
- if (m_bEOF)
- break;
-
- if (m_rewindCount < sizeof(m_rewindBuf))
- m_rewindBuf[m_rewindCount++] = *mybuf;
-
- if (*mybuf == '\r') // Ignore!
- continue;
-
- if ((*mybuf == '\n') || !*mybuf)
- break;
-
- *buf++ = *mybuf;
- len++;
- }
-
- *buf=0;
- return s;
-}
-
-ssize_t HTTPProtocol::read (void *b, size_t nbytes)
-{
- ssize_t ret = 0;
-
- if (m_lineCountUnget > 0)
- {
- ret = ( nbytes < m_lineCountUnget ? nbytes : m_lineCountUnget );
- m_lineCountUnget -= ret;
- memcpy(b, m_linePtrUnget, ret);
- m_linePtrUnget += ret;
-
- return ret;
- }
-
- if (m_lineCount > 0)
- {
- ret = ( nbytes < m_lineCount ? nbytes : m_lineCount );
- m_lineCount -= ret;
- memcpy(b, m_linePtr, ret);
- m_linePtr += ret;
- return ret;
- }
-
- if (nbytes == 1)
- {
- ret = read(m_lineBuf, 1024); // Read into buffer
- m_linePtr = m_lineBuf;
- if (ret <= 0)
- {
- m_lineCount = 0;
- return ret;
- }
- m_lineCount = ret;
- return read(b, 1); // Read from buffer
- }
-
- do
- {
- ret = TCPSlaveBase::read( b, nbytes);
- if (ret == 0)
- m_bEOF = true;
-
- } while ((ret == -1) && (errno == EAGAIN || errno == EINTR));
-
- return ret;
-}
-
-void HTTPProtocol::httpCheckConnection()
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCheckConnection: " <<
- " Socket status: " << m_iSock <<
- " Keep Alive: " << m_bKeepAlive <<
- " First: " << m_bFirstRequest << endl;
-
- if ( !m_bFirstRequest && (m_iSock != -1) )
- {
- bool closeDown = false;
- if ( !isConnectionValid())
- {
- kdDebug(7113) << "(" << m_pid << ") Connection lost!" << endl;
- closeDown = true;
- }
- else if ( m_request.method != HTTP_GET )
- {
- closeDown = true;
- }
- else if ( !m_state.doProxy && !m_request.doProxy )
- {
- if (m_state.hostname != m_request.hostname ||
- m_state.port != m_request.port ||
- m_state.user != m_request.user ||
- m_state.passwd != m_request.passwd)
- closeDown = true;
- }
- else
- {
- // Keep the connection to the proxy.
- if ( !(m_request.doProxy && m_state.doProxy) )
- closeDown = true;
- }
-
- if (closeDown)
- httpCloseConnection();
- }
-
- // Let's update our current state
- m_state.hostname = m_request.hostname;
- m_state.encoded_hostname = m_request.encoded_hostname;
- m_state.port = m_request.port;
- m_state.user = m_request.user;
- m_state.passwd = m_request.passwd;
- m_state.doProxy = m_request.doProxy;
-}
-
-bool HTTPProtocol::httpOpenConnection()
-{
- int errCode;
- TQString errMsg;
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpenConnection" << endl;
-
- setBlockConnection( true );
- // kio_http uses its own proxying:
- KSocks::self()->disableSocks();
-
- if ( m_state.doProxy )
- {
- TQString proxy_host = m_proxyURL.host();
- int proxy_port = m_proxyURL.port();
-
- kdDebug(7113) << "(" << m_pid << ") Connecting to proxy server: "
- << proxy_host << ", port: " << proxy_port << endl;
-
- infoMessage( i18n("Connecting to %1...").arg(m_state.hostname) );
-
- setConnectTimeout( m_proxyConnTimeout );
-
- if ( !connectToHost(proxy_host, proxy_port, false) )
- {
- if (userAborted()) {
- error(ERR_NO_CONTENT, "");
- return false;
- }
-
- switch ( connectResult() )
- {
- case IO_LookupError:
- errMsg = proxy_host;
- errCode = ERR_UNKNOWN_PROXY_HOST;
- break;
- case IO_TimeOutError:
- errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
- errCode = ERR_SERVER_TIMEOUT;
- break;
- default:
- errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
- errCode = ERR_COULD_NOT_CONNECT;
- }
- error( errCode, errMsg );
- return false;
- }
- }
- else
- {
- // Apparently we don't want a proxy. let's just connect directly
- setConnectTimeout(m_remoteConnTimeout);
-
- if ( !connectToHost(m_state.hostname, m_state.port, false ) )
- {
- if (userAborted()) {
- error(ERR_NO_CONTENT, "");
- return false;
- }
-
- switch ( connectResult() )
- {
- case IO_LookupError:
- errMsg = m_state.hostname;
- errCode = ERR_UNKNOWN_HOST;
- break;
- case IO_TimeOutError:
- errMsg = i18n("Connection was to %1 at port %2").arg(m_state.hostname).arg(m_state.port);
- errCode = ERR_SERVER_TIMEOUT;
- break;
- default:
- errCode = ERR_COULD_NOT_CONNECT;
- if (m_state.port != m_iDefaultPort)
- errMsg = i18n("%1 (port %2)").arg(m_state.hostname).arg(m_state.port);
- else
- errMsg = m_state.hostname;
- }
- error( errCode, errMsg );
- return false;
- }
- }
-
- // Set our special socket option!!
- int on = 1;
- (void) setsockopt( m_iSock, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on) );
-
- m_bFirstRequest = true;
-
- connected();
- return true;
-}
-
-
-/**
- * This function is responsible for opening up the connection to the remote
- * HTTP server and sending the header. If this requires special
- * authentication or other such fun stuff, then it will handle it. This
- * function will NOT receive anything from the server, however. This is in
- * contrast to previous incarnations of 'httpOpen'.
- *
- * The reason for the change is due to one small fact: some requests require
- * data to be sent in addition to the header (POST requests) and there is no
- * way for this function to get that data. This function is called in the
- * slotPut() or slotGet() functions which, in turn, are called (indirectly) as
- * a result of a TDEIOJob::put() or TDEIOJob::get(). It is those latter functions
- * which are responsible for starting up this ioslave in the first place.
- * This means that 'httpOpen' is called (essentially) as soon as the ioslave
- * is created -- BEFORE any data gets to this slave.
- *
- * The basic process now is this:
- *
- * 1) Open up the socket and port
- * 2) Format our request/header
- * 3) Send the header to the remote server
- */
-bool HTTPProtocol::httpOpen()
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen" << endl;
-
- // Cannot have an https request without the m_bIsSSL being set! This can
- // only happen if TCPSlaveBase::InitializeSSL() function failed in which it
- // means the current installation does not support SSL...
- if ( (m_protocol == "https" || m_protocol == "webdavs") && !m_bIsSSL )
- {
- error( ERR_UNSUPPORTED_PROTOCOL, m_protocol );
- return false;
- }
-
- m_request.fcache = 0;
- m_request.bCachedRead = false;
- m_request.bCachedWrite = false;
- m_request.bMustRevalidate = false;
- m_request.expireDate = 0;
- m_request.creationDate = 0;
-
- if (m_request.bUseCache)
- {
- m_request.fcache = checkCacheEntry( );
-
- bool bCacheOnly = (m_request.cache == TDEIO::CC_CacheOnly);
- bool bOffline = isOffline(m_request.doProxy ? m_proxyURL : m_request.url);
- if (bOffline && (m_request.cache != TDEIO::CC_Reload))
- m_request.cache = TDEIO::CC_CacheOnly;
-
- if (m_request.cache == CC_Reload && m_request.fcache)
- {
- if (m_request.fcache)
- fclose(m_request.fcache);
- m_request.fcache = 0;
- }
- if ((m_request.cache == TDEIO::CC_CacheOnly) || (m_request.cache == TDEIO::CC_Cache))
- m_request.bMustRevalidate = false;
-
- m_request.bCachedWrite = true;
-
- if (m_request.fcache && !m_request.bMustRevalidate)
- {
- // Cache entry is OK.
- m_request.bCachedRead = true; // Cache hit.
- return true;
- }
- else if (!m_request.fcache)
- {
- m_request.bMustRevalidate = false; // Cache miss
- }
- else
- {
- // Conditional cache hit. (Validate)
- }
-
- if (bCacheOnly && bOffline)
- {
- error( ERR_OFFLINE_MODE, m_request.url.url() );
- return false;
- }
- if (bCacheOnly)
- {
- error( ERR_DOES_NOT_EXIST, m_request.url.url() );
- return false;
- }
- if (bOffline)
- {
- error( ERR_OFFLINE_MODE, m_request.url.url() );
- return false;
- }
- }
-
- TQString header;
- TQString davHeader;
-
- bool moreData = false;
- bool davData = false;
-
- // Clear out per-connection settings...
- resetConnectionSettings ();
-
- // Check the validity of the current connection, if one exists.
- httpCheckConnection();
-
- if ( !m_bIsTunneled && m_bNeedTunnel )
- {
- setEnableSSLTunnel( true );
- // We send a HTTP 1.0 header since some proxies refuse HTTP 1.1 and we don't
- // need any HTTP 1.1 capabilities for CONNECT - Waba
- header = TQString("CONNECT %1:%2 HTTP/1.0"
- "\r\n").arg( m_request.encoded_hostname).arg(m_request.port);
-
- // Identify who you are to the proxy server!
- if (!m_request.userAgent.isEmpty())
- header += "User-Agent: " + m_request.userAgent + "\r\n";
-
- /* Add hostname information */
- header += "Host: " + m_state.encoded_hostname;
-
- if (m_state.port != m_iDefaultPort)
- header += TQString(":%1").arg(m_state.port);
- header += "\r\n";
-
- header += proxyAuthenticationHeader();
- }
- else
- {
- // Determine if this is a POST or GET method
- switch (m_request.method)
- {
- case HTTP_GET:
- header = "GET ";
- break;
- case HTTP_PUT:
- header = "PUT ";
- moreData = true;
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case HTTP_POST:
- header = "POST ";
- moreData = true;
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case HTTP_HEAD:
- header = "HEAD ";
- break;
- case HTTP_DELETE:
- header = "DELETE ";
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case HTTP_OPTIONS:
- header = "OPTIONS ";
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case DAV_PROPFIND:
- header = "PROPFIND ";
- davData = true;
- davHeader = "Depth: ";
- if ( hasMetaData( "davDepth" ) )
- {
- kdDebug(7113) << "Reading DAV depth from metadata: " << metaData( "davDepth" ) << endl;
- davHeader += metaData( "davDepth" );
- }
- else
- {
- if ( m_request.davData.depth == 2 )
- davHeader += "infinity";
- else
- davHeader += TQString("%1").arg( m_request.davData.depth );
- }
- davHeader += "\r\n";
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case DAV_PROPPATCH:
- header = "PROPPATCH ";
- davData = true;
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case DAV_MKCOL:
- header = "MKCOL ";
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case DAV_COPY:
- case DAV_MOVE:
- header = ( m_request.method == DAV_COPY ) ? "COPY " : "MOVE ";
- davHeader = "Destination: " + m_request.davData.desturl;
- // infinity depth means copy recursively
- // (optional for copy -> but is the desired action)
- davHeader += "\r\nDepth: infinity\r\nOverwrite: ";
- davHeader += m_request.davData.overwrite ? "T" : "F";
- davHeader += "\r\n";
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case DAV_LOCK:
- header = "LOCK ";
- davHeader = "Timeout: ";
- {
- uint timeout = 0;
- if ( hasMetaData( "davTimeout" ) )
- timeout = metaData( "davTimeout" ).toUInt();
- if ( timeout == 0 )
- davHeader += "Infinite";
- else
- davHeader += TQString("Seconds-%1").arg(timeout);
- }
- davHeader += "\r\n";
- m_request.bCachedWrite = false; // Do not put any result in the cache
- davData = true;
- break;
- case DAV_UNLOCK:
- header = "UNLOCK ";
- davHeader = "Lock-token: " + metaData("davLockToken") + "\r\n";
- m_request.bCachedWrite = false; // Do not put any result in the cache
- break;
- case DAV_SEARCH:
- header = "SEARCH ";
- davData = true;
- m_request.bCachedWrite = false;
- break;
- case DAV_SUBSCRIBE:
- header = "SUBSCRIBE ";
- m_request.bCachedWrite = false;
- break;
- case DAV_UNSUBSCRIBE:
- header = "UNSUBSCRIBE ";
- m_request.bCachedWrite = false;
- break;
- case DAV_POLL:
- header = "POLL ";
- m_request.bCachedWrite = false;
- break;
- default:
- error (ERR_UNSUPPORTED_ACTION, TQString::null);
- return false;
- }
- // DAV_POLL; DAV_NOTIFY
-
- // format the URI
- if (m_state.doProxy && !m_bIsTunneled)
- {
- KURL u;
-
- if (m_protocol == "webdav")
- u.setProtocol( "http" );
- else if (m_protocol == "webdavs" )
- u.setProtocol( "https" );
- else
- u.setProtocol( m_protocol );
-
- // For all protocols other than the once handled by this io-slave
- // append the username. This fixes a long standing bug of ftp io-slave
- // logging in anonymously in proxied connections even when the username
- // is explicitly specified.
- if (m_protocol != "http" && m_protocol != "https" &&
- !m_state.user.isEmpty())
- u.setUser (m_state.user);
-
- u.setHost( m_state.hostname );
- if (m_state.port != m_iDefaultPort)
- u.setPort( m_state.port );
- u.setEncodedPathAndQuery( m_request.url.encodedPathAndQuery(0,true) );
- header += u.url();
- }
- else
- {
- header += m_request.url.encodedPathAndQuery(0, true);
- }
-
- header += " HTTP/1.1\r\n"; /* start header */
-
- if (!m_request.userAgent.isEmpty())
- {
- header += "User-Agent: ";
- header += m_request.userAgent;
- header += "\r\n";
- }
-
- if (!m_request.referrer.isEmpty())
- {
- header += "Referer: "; //Don't try to correct spelling!
- header += m_request.referrer;
- header += "\r\n";
- }
-
- if ( m_request.offset > 0 )
- {
- header += TQString("Range: bytes=%1-\r\n").arg(TDEIO::number(m_request.offset));
- kdDebug(7103) << "kio_http : Range = " << TDEIO::number(m_request.offset) << endl;
- }
-
- if ( m_request.cache == CC_Reload )
- {
- /* No caching for reload */
- header += "Pragma: no-cache\r\n"; /* for HTTP/1.0 caches */
- header += "Cache-control: no-cache\r\n"; /* for HTTP >=1.1 caches */
- }
-
- if (m_request.bMustRevalidate)
- {
- /* conditional get */
- if (!m_request.etag.isEmpty())
- header += "If-None-Match: "+m_request.etag+"\r\n";
- if (!m_request.lastModified.isEmpty())
- header += "If-Modified-Since: "+m_request.lastModified+"\r\n";
- }
-
- header += "Accept: ";
- TQString acceptHeader = metaData("accept");
- if (!acceptHeader.isEmpty())
- header += acceptHeader;
- else
- header += DEFAULT_ACCEPT_HEADER;
- header += "\r\n";
-
-#ifdef DO_GZIP
- if (m_request.allowCompressedPage)
- header += "Accept-Encoding: x-gzip, x-deflate, gzip, deflate\r\n";
-#endif
-
- if (!m_request.charsets.isEmpty())
- header += "Accept-Charset: " + m_request.charsets + "\r\n";
-
- if (!m_request.languages.isEmpty())
- header += "Accept-Language: " + m_request.languages + "\r\n";
-
-
- /* support for virtual hosts and required by HTTP 1.1 */
- header += "Host: " + m_state.encoded_hostname;
-
- if (m_state.port != m_iDefaultPort)
- header += TQString(":%1").arg(m_state.port);
- header += "\r\n";
-
- TQString cookieStr;
- TQString cookieMode = metaData("cookies").lower();
- if (cookieMode == "none")
- {
- m_request.cookieMode = HTTPRequest::CookiesNone;
- }
- else if (cookieMode == "manual")
- {
- m_request.cookieMode = HTTPRequest::CookiesManual;
- cookieStr = metaData("setcookies");
- }
- else
- {
- m_request.cookieMode = HTTPRequest::CookiesAuto;
- if (m_request.bUseCookiejar)
- cookieStr = findCookies( m_request.url.url());
- }
-
- if (!cookieStr.isEmpty())
- header += cookieStr + "\r\n";
-
- TQString customHeader = metaData( "customHTTPHeader" );
- if (!customHeader.isEmpty())
- {
- header += sanitizeCustomHTTPHeader(customHeader);
- header += "\r\n";
- }
-
- if (m_request.method == HTTP_POST)
- {
- header += metaData("content-type");
- header += "\r\n";
- }
-
- // Only check for a cached copy if the previous
- // response was NOT a 401 or 407.
- // no caching for Negotiate auth.
- if ( !m_request.bNoAuth && m_responseCode != 401 && m_responseCode != 407 && Authentication != AUTH_Negotiate )
- {
- kdDebug(7113) << "(" << m_pid << ") Calling checkCachedAuthentication " << endl;
- AuthInfo info;
- info.url = m_request.url;
- info.verifyPath = true;
- if ( !m_request.user.isEmpty() )
- info.username = m_request.user;
- if ( checkCachedAuthentication( info ) && !info.digestInfo.isEmpty() )
- {
- Authentication = info.digestInfo.startsWith("Basic") ? AUTH_Basic : info.digestInfo.startsWith("NTLM") ? AUTH_NTLM : info.digestInfo.startsWith("Negotiate") ? AUTH_Negotiate : AUTH_Digest ;
- m_state.user = info.username;
- m_state.passwd = info.password;
- m_strRealm = info.realmValue;
- if ( Authentication != AUTH_NTLM && Authentication != AUTH_Negotiate ) // don't use the cached challenge
- m_strAuthorization = info.digestInfo;
- }
- }
- else
- {
- kdDebug(7113) << "(" << m_pid << ") Not calling checkCachedAuthentication " << endl;
- }
-
- switch ( Authentication )
- {
- case AUTH_Basic:
- header += createBasicAuth();
- break;
- case AUTH_Digest:
- header += createDigestAuth();
- break;
-#ifdef HAVE_LIBGSSAPI
- case AUTH_Negotiate:
- header += createNegotiateAuth();
- break;
-#endif
- case AUTH_NTLM:
- header += createNTLMAuth();
- break;
- case AUTH_None:
- default:
- break;
- }
-
- /********* Only for debugging purpose *********/
- if ( Authentication != AUTH_None )
- {
- kdDebug(7113) << "(" << m_pid << ") Using Authentication: " << endl;
- kdDebug(7113) << "(" << m_pid << ") HOST= " << m_state.hostname << endl;
- kdDebug(7113) << "(" << m_pid << ") PORT= " << m_state.port << endl;
- kdDebug(7113) << "(" << m_pid << ") USER= " << m_state.user << endl;
- kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
- kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strRealm << endl;
- kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strAuthorization << endl;
- }
-
- // Do we need to authorize to the proxy server ?
- if ( m_state.doProxy && !m_bIsTunneled )
- header += proxyAuthenticationHeader();
-
- // Support old HTTP/1.0 style keep-alive header for compatability
- // purposes as well as performance improvements while giving end
- // users the ability to disable this feature proxy servers that
- // don't not support such feature, e.g. junkbuster proxy server.
- if (!m_bUseProxy || m_bPersistentProxyConnection || m_bIsTunneled)
- header += "Connection: Keep-Alive\r\n";
- else
- header += "Connection: close\r\n";
-
- if ( m_protocol == "webdav" || m_protocol == "webdavs" )
- {
- header += davProcessLocks();
-
- // add extra webdav headers, if supplied
- TQString davExtraHeader = metaData("davHeader");
- if ( !davExtraHeader.isEmpty() )
- davHeader += davExtraHeader;
-
- // Set content type of webdav data
- if (davData)
- davHeader += "Content-Type: text/xml; charset=utf-8\r\n";
-
- // add extra header elements for WebDAV
- if ( !davHeader.isNull() )
- header += davHeader;
- }
- }
-
- kdDebug(7103) << "(" << m_pid << ") ============ Sending Header:" << endl;
-
- TQStringList headerOutput = TQStringList::split("\r\n", header);
- TQStringList::Iterator it = headerOutput.begin();
-
- for (; it != headerOutput.end(); it++)
- kdDebug(7103) << "(" << m_pid << ") " << (*it) << endl;
-
- if ( !moreData && !davData)
- header += "\r\n"; /* end header */
-
- // Now that we have our formatted header, let's send it!
- // Create a new connection to the remote machine if we do
- // not already have one...
- if ( m_iSock == -1)
- {
- if (!httpOpenConnection())
- return false;
- }
-
- // Send the data to the remote machine...
- bool sendOk = (write(header.latin1(), header.length()) == (ssize_t) header.length());
- if (!sendOk)
- {
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: "
- "Connection broken! (" << m_state.hostname << ")" << endl;
-
- // With a Keep-Alive connection this can happen.
- // Just reestablish the connection.
- if (m_bKeepAlive)
- {
- httpCloseConnection();
- return true; // Try again
- }
-
- if (!sendOk)
- {
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: sendOk==false."
- " Connnection broken !" << endl;
- error( ERR_CONNECTION_BROKEN, m_state.hostname );
- return false;
- }
- }
-
- bool res = true;
-
- if ( moreData || davData )
- res = sendBody();
-
- infoMessage(i18n("%1 contacted. Waiting for reply...").arg(m_request.hostname));
-
- return res;
-}
-
-void HTTPProtocol::forwardHttpResponseHeader()
-{
- // Send the response header if it was requested
- if ( config()->readBoolEntry("PropagateHttpHeader", false) )
- {
- setMetaData("HTTP-Headers", m_responseHeader.join("\n"));
- sendMetaData();
- }
- m_responseHeader.clear();
-}
-
-/**
- * This function will read in the return header from the server. It will
- * not read in the body of the return message. It will also not transmit
- * the header to our client as the client doesn't need to know the gory
- * details of HTTP headers.
- */
-bool HTTPProtocol::readHeader()
-{
-try_again:
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader" << endl;
-
- // Check
- if (m_request.bCachedRead)
- {
- m_responseHeader << "HTTP-CACHE";
- // Read header from cache...
- char buffer[4097];
- if (!fgets(buffer, 4096, m_request.fcache) )
- {
- // Error, delete cache entry
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
- << "Could not access cache to obtain mimetype!" << endl;
- error( ERR_CONNECTION_BROKEN, m_state.hostname );
- return false;
- }
-
- m_strMimeType = TQString(TQString::fromUtf8( buffer)).stripWhiteSpace();
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: cached "
- << "data mimetype: " << m_strMimeType << endl;
-
- if (!fgets(buffer, 4096, m_request.fcache) )
- {
- // Error, delete cache entry
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
- << "Could not access cached data! " << endl;
- error( ERR_CONNECTION_BROKEN, m_state.hostname );
- return false;
- }
-
- m_request.strCharset = TQString(TQString::fromUtf8( buffer)).stripWhiteSpace().lower();
- setMetaData("charset", m_request.strCharset);
- if (!m_request.lastModified.isEmpty())
- setMetaData("modified", m_request.lastModified);
- TQString tmp;
- tmp.setNum(m_request.expireDate);
- setMetaData("expire-date", tmp);
- tmp.setNum(m_request.creationDate);
- setMetaData("cache-creation-date", tmp);
- mimeType(m_strMimeType);
- forwardHttpResponseHeader();
- return true;
- }
-
- TQCString locationStr; // In case we get a redirect.
- TQCString cookieStr; // In case we get a cookie.
-
- TQString dispositionType; // In case we get a Content-Disposition type
- TQString dispositionFilename; // In case we get a Content-Disposition filename
-
- TQString mediaValue;
- TQString mediaAttribute;
-
- TQStringList upgradeOffers;
-
- bool upgradeRequired = false; // Server demands that we upgrade to something
- // This is also true if we ask to upgrade and
- // the server accepts, since we are now
- // committed to doing so
- bool canUpgrade = false; // The server offered an upgrade
-
-
- m_request.etag = TQString::null;
- m_request.lastModified = TQString::null;
- m_request.strCharset = TQString::null;
-
- time_t dateHeader = 0;
- time_t expireDate = 0; // 0 = no info, 1 = already expired, > 1 = actual date
- int currentAge = 0;
- int maxAge = -1; // -1 = no max age, 0 already expired, > 0 = actual time
- int maxHeaderSize = 64*1024; // 64Kb to catch DOS-attacks
-
- // read in 8192 bytes at a time (HTTP cookies can be quite large.)
- int len = 0;
- char buffer[8193];
- bool cont = false;
- bool cacheValidated = false; // Revalidation was successful
- bool mayCache = true;
- bool hasCacheDirective = false;
- bool bCanResume = false;
-
- if (m_iSock == -1)
- {
- kdDebug(7113) << "HTTPProtocol::readHeader: No connection." << endl;
- return false; // Restablish connection and try again
- }
-
- if (!waitForResponse(m_remoteRespTimeout))
- {
- // No response error
- error( ERR_SERVER_TIMEOUT , m_state.hostname );
- return false;
- }
-
- setRewindMarker();
-
- gets(buffer, sizeof(buffer)-1);
-
- if (m_bEOF || *buffer == '\0')
- {
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
- << "EOF while waiting for header start." << endl;
- if (m_bKeepAlive) // Try to reestablish connection.
- {
- httpCloseConnection();
- return false; // Reestablish connection and try again.
- }
-
- if (m_request.method == HTTP_HEAD)
- {
- // HACK
- // Some web-servers fail to respond properly to a HEAD request.
- // We compensate for their failure to properly implement the HTTP standard
- // by assuming that they will be sending html.
- kdDebug(7113) << "(" << m_pid << ") HTTPPreadHeader: HEAD -> returned "
- << "mimetype: " << DEFAULT_MIME_TYPE << endl;
- mimeType(TQString::fromLatin1(DEFAULT_MIME_TYPE));
- return true;
- }
-
- kdDebug(7113) << "HTTPProtocol::readHeader: Connection broken !" << endl;
- error( ERR_CONNECTION_BROKEN, m_state.hostname );
- return false;
- }
-
- kdDebug(7103) << "(" << m_pid << ") ============ Received Response:"<< endl;
-
- bool noHeader = true;
- HTTP_REV httpRev = HTTP_None;
- int headerSize = 0;
-
- do
- {
- // strip off \r and \n if we have them
- len = strlen(buffer);
-
- while(len && (buffer[len-1] == '\n' || buffer[len-1] == '\r'))
- buffer[--len] = 0;
-
- // if there was only a newline then continue
- if (!len)
- {
- kdDebug(7103) << "(" << m_pid << ") --empty--" << endl;
- continue;
- }
-
- headerSize += len;
-
- // We have a response header. This flag is a work around for
- // servers that append a "\r\n" before the beginning of the HEADER
- // response!!! It only catches x number of \r\n being placed at the
- // top of the reponse...
- noHeader = false;
-
- kdDebug(7103) << "(" << m_pid << ") \"" << buffer << "\"" << endl;
-
- // Save broken servers from damnation!!
- char* buf = buffer;
- while( *buf == ' ' )
- buf++;
-
-
- if (buf[0] == '<')
- {
- // We get XML / HTTP without a proper header
- // put string back
- kdDebug(7103) << "kio_http: No valid HTTP header found! Document starts with XML/HTML tag" << endl;
-
- // Document starts with a tag, assume html instead of text/plain
- m_strMimeType = "text/html";
-
- rewind();
- break;
- }
-
- // Store the the headers so they can be passed to the
- // calling application later
- m_responseHeader << TQString::fromLatin1(buf);
-
- if ((strncasecmp(buf, "HTTP/", 5) == 0) ||
- (strncasecmp(buf, "ICY ", 4) == 0)) // Shoutcast support
- {
- if (strncasecmp(buf, "ICY ", 4) == 0)
- {
- // Shoutcast support
- httpRev = SHOUTCAST;
- m_bKeepAlive = false;
- }
- else if (strncmp((buf + 5), "1.0",3) == 0)
- {
- httpRev = HTTP_10;
- // For 1.0 servers, the server itself has to explicitly
- // tell us whether it supports persistent connection or
- // not. By default, we assume it does not, but we do
- // send the old style header "Connection: Keep-Alive" to
- // inform it that we support persistence.
- m_bKeepAlive = false;
- }
- else if (strncmp((buf + 5), "1.1",3) == 0)
- {
- httpRev = HTTP_11;
- }
- else
- {
- httpRev = HTTP_Unknown;
- }
-
- if (m_responseCode)
- m_prevResponseCode = m_responseCode;
-
- const char* rptr = buf;
- while ( *rptr && *rptr > ' ' )
- ++rptr;
- m_responseCode = atoi(rptr);
-
- // server side errors
- if (m_responseCode >= 500 && m_responseCode <= 599)
- {
- if (m_request.method == HTTP_HEAD)
- {
- ; // Ignore error
- }
- else
- {
- if (m_request.bErrorPage)
- errorPage();
- else
- {
- error(ERR_INTERNAL_SERVER, m_request.url.url());
- return false;
- }
- }
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- }
- // Unauthorized access
- else if (m_responseCode == 401 || m_responseCode == 407)
- {
- // Double authorization requests, i.e. a proxy auth
- // request followed immediately by a regular auth request.
- if ( m_prevResponseCode != m_responseCode &&
- (m_prevResponseCode == 401 || m_prevResponseCode == 407) )
- saveAuthorization();
-
- m_bUnauthorized = true;
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- }
- //
- else if (m_responseCode == 416) // Range not supported
- {
- m_request.offset = 0;
- httpCloseConnection();
- return false; // Try again.
- }
- // Upgrade Required
- else if (m_responseCode == 426)
- {
- upgradeRequired = true;
- }
- // Any other client errors
- else if (m_responseCode >= 400 && m_responseCode <= 499)
- {
- // Tell that we will only get an error page here.
- if (m_request.bErrorPage)
- errorPage();
- else
- {
- error(ERR_DOES_NOT_EXIST, m_request.url.url());
- return false;
- }
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- }
- else if (m_responseCode == 307)
- {
- // 307 Temporary Redirect
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- }
- else if (m_responseCode == 304)
- {
- // 304 Not Modified
- // The value in our cache is still valid.
- cacheValidated = true;
- }
- else if (m_responseCode >= 301 && m_responseCode<= 303)
- {
- // 301 Moved permanently
- if (m_responseCode == 301)
- setMetaData("permanent-redirect", "true");
-
- // 302 Found (temporary location)
- // 303 See Other
- if (m_request.method != HTTP_HEAD && m_request.method != HTTP_GET)
- {
-#if 0
- // Reset the POST buffer to avoid a double submit
- // on redirection
- if (m_request.method == HTTP_POST)
- m_bufPOST.resize(0);
-#endif
-
- // NOTE: This is wrong according to RFC 2616. However,
- // because most other existing user agent implementations
- // treat a 301/302 response as a 303 response and preform
- // a GET action regardless of what the previous method was,
- // many servers have simply adapted to this way of doing
- // things!! Thus, we are forced to do the same thing or we
- // won't be able to retrieve these pages correctly!! See RFC
- // 2616 sections 10.3.[2/3/4/8]
- m_request.method = HTTP_GET; // Force a GET
- }
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- }
- else if ( m_responseCode == 207 ) // Multi-status (for WebDav)
- {
-
- }
- else if ( m_responseCode == 204 ) // No content
- {
- // error(ERR_NO_CONTENT, i18n("Data have been successfully sent."));
- // Short circuit and do nothing!
-
- // The original handling here was wrong, this is not an error: eg. in the
- // example of a 204 No Content response to a PUT completing.
- // m_bError = true;
- // return false;
- }
- else if ( m_responseCode == 206 )
- {
- if ( m_request.offset )
- bCanResume = true;
- }
- else if (m_responseCode == 102) // Processing (for WebDAV)
- {
- /***
- * This status code is given when the server expects the
- * command to take significant time to complete. So, inform
- * the user.
- */
- infoMessage( i18n( "Server processing request, please wait..." ) );
- cont = true;
- }
- else if (m_responseCode == 100)
- {
- // We got 'Continue' - ignore it
- cont = true;
- }
- }
-
- // are we allowd to resume? this will tell us
- else if (strncasecmp(buf, "Accept-Ranges:", 14) == 0) {
- if (strncasecmp(trimLead(buf + 14), "none", 4) == 0)
- bCanResume = false;
- }
- // Keep Alive
- else if (strncasecmp(buf, "Keep-Alive:", 11) == 0) {
- TQStringList options = TQStringList::split(',',
- TQString::fromLatin1(trimLead(buf+11)));
- for(TQStringList::ConstIterator it = options.begin();
- it != options.end();
- it++)
- {
- TQString option = (*it).stripWhiteSpace().lower();
- if (option.startsWith("timeout="))
- {
- m_keepAliveTimeout = option.mid(8).toInt();
- }
- }
- }
-
- // Cache control
- else if (strncasecmp(buf, "Cache-Control:", 14) == 0) {
- TQStringList cacheControls = TQStringList::split(',',
- TQString::fromLatin1(trimLead(buf+14)));
- for(TQStringList::ConstIterator it = cacheControls.begin();
- it != cacheControls.end();
- it++)
- {
- TQString cacheControl = (*it).stripWhiteSpace();
- if (strncasecmp(cacheControl.latin1(), "no-cache", 8) == 0)
- {
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- }
- else if (strncasecmp(cacheControl.latin1(), "no-store", 8) == 0)
- {
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- }
- else if (strncasecmp(cacheControl.latin1(), "max-age=", 8) == 0)
- {
- TQString age = cacheControl.mid(8).stripWhiteSpace();
- if (!age.isNull())
- maxAge = STRTOLL(age.latin1(), 0, 10);
- }
- }
- hasCacheDirective = true;
- }
-
- // get the size of our data
- else if (strncasecmp(buf, "Content-length:", 15) == 0) {
- char* len = trimLead(buf + 15);
- if (len)
- m_iSize = STRTOLL(len, 0, 10);
- }
-
- else if (strncasecmp(buf, "Content-location:", 17) == 0) {
- setMetaData ("content-location",
- TQString::fromLatin1(trimLead(buf+17)).stripWhiteSpace());
- }
-
- // what type of data do we have?
- else if (strncasecmp(buf, "Content-type:", 13) == 0) {
- char *start = trimLead(buf + 13);
- char *pos = start;
-
- // Increment until we encounter ";" or the end of the buffer
- while ( *pos && *pos != ';' ) pos++;
-
- // Assign the mime-type.
- m_strMimeType = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
- kdDebug(7113) << "(" << m_pid << ") Content-type: " << m_strMimeType << endl;
-
- // If we still have text, then it means we have a mime-type with a
- // parameter (eg: charset=iso-8851) ; so let's get that...
- while (*pos)
- {
- start = ++pos;
- while ( *pos && *pos != '=' ) pos++;
-
- char *end = pos;
- while ( *end && *end != ';' ) end++;
-
- if (*pos)
- {
- mediaAttribute = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
- mediaValue = TQString::fromLatin1(pos+1, end-pos-1).stripWhiteSpace();
- pos = end;
- if (mediaValue.length() &&
- (mediaValue[0] == '"') &&
- (mediaValue[mediaValue.length()-1] == '"'))
- mediaValue = mediaValue.mid(1, mediaValue.length()-2);
-
- kdDebug (7113) << "(" << m_pid << ") Media-Parameter Attribute: "
- << mediaAttribute << endl;
- kdDebug (7113) << "(" << m_pid << ") Media-Parameter Value: "
- << mediaValue << endl;
-
- if ( mediaAttribute == "charset")
- {
- mediaValue = mediaValue.lower();
- m_request.strCharset = mediaValue;
- }
- else
- {
- setMetaData("media-"+mediaAttribute, mediaValue);
- }
- }
- }
- }
-
- // Date
- else if (strncasecmp(buf, "Date:", 5) == 0) {
- dateHeader = KRFCDate::parseDate(trimLead(buf+5));
- }
-
- // Cache management
- else if (strncasecmp(buf, "ETag:", 5) == 0) {
- m_request.etag = trimLead(buf+5);
- }
-
- // Cache management
- else if (strncasecmp(buf, "Expires:", 8) == 0) {
- expireDate = KRFCDate::parseDate(trimLead(buf+8));
- if (!expireDate)
- expireDate = 1; // Already expired
- }
-
- // Cache management
- else if (strncasecmp(buf, "Last-Modified:", 14) == 0) {
- m_request.lastModified = (TQString::fromLatin1(trimLead(buf+14))).stripWhiteSpace();
- }
-
- // whoops.. we received a warning
- else if (strncasecmp(buf, "Warning:", 8) == 0) {
- //Don't use warning() here, no need to bother the user.
- //Those warnings are mostly about caches.
- infoMessage(trimLead(buf + 8));
- }
-
- // Cache management (HTTP 1.0)
- else if (strncasecmp(buf, "Pragma:", 7) == 0) {
- TQCString pragma = TQCString(trimLead(buf+7)).stripWhiteSpace().lower();
- if (pragma == "no-cache")
- {
- m_request.bCachedWrite = false; // Don't put in cache
- mayCache = false;
- hasCacheDirective = true;
- }
- }
-
- // The deprecated Refresh Response
- else if (strncasecmp(buf,"Refresh:", 8) == 0) {
- mayCache = false; // Do not cache page as it defeats purpose of Refresh tag!
- setMetaData( "http-refresh", TQString::fromLatin1(trimLead(buf+8)).stripWhiteSpace() );
- }
-
- // In fact we should do redirection only if we got redirection code
- else if (strncasecmp(buf, "Location:", 9) == 0) {
- // Redirect only for 3xx status code, will ya! Thanks, pal!
- if ( m_responseCode > 299 && m_responseCode < 400 )
- locationStr = TQCString(trimLead(buf+9)).stripWhiteSpace();
- }
-
- // Check for cookies
- else if (strncasecmp(buf, "Set-Cookie", 10) == 0) {
- cookieStr += buf;
- cookieStr += '\n';
- }
-
- // check for direct authentication
- else if (strncasecmp(buf, "WWW-Authenticate:", 17) == 0) {
- configAuth(trimLead(buf + 17), false);
- }
-
- // check for proxy-based authentication
- else if (strncasecmp(buf, "Proxy-Authenticate:", 19) == 0) {
- configAuth(trimLead(buf + 19), true);
- }
-
- else if (strncasecmp(buf, "Upgrade:", 8) == 0) {
- // Now we have to check to see what is offered for the upgrade
- TQString offered = &(buf[8]);
- upgradeOffers = TQStringList::split(TQRegExp("[ \n,\r\t]"), offered);
- }
-
- // content?
- else if (strncasecmp(buf, "Content-Encoding:", 17) == 0) {
- // This is so wrong !! No wonder kio_http is stripping the
- // gzip encoding from downloaded files. This solves multiple
- // bug reports and caitoo's problem with downloads when such a
- // header is encountered...
-
- // A quote from RFC 2616:
- // " When present, its (Content-Encoding) value indicates what additional
- // content have been applied to the entity body, and thus what decoding
- // mechanism must be applied to obtain the media-type referenced by the
- // Content-Type header field. Content-Encoding is primarily used to allow
- // a document to be compressed without loosing the identity of its underlying
- // media type. Simply put if it is specified, this is the actual mime-type
- // we should use when we pull the resource !!!
- addEncoding(trimLead(buf + 17), m_qContentEncodings);
- }
- // Refer to RFC 2616 sec 15.5/19.5.1 and RFC 2183
- else if(strncasecmp(buf, "Content-Disposition:", 20) == 0) {
- char* dispositionBuf = trimLead(buf + 20);
- while ( *dispositionBuf )
- {
- if ( strncasecmp( dispositionBuf, "filename", 8 ) == 0 )
- {
- dispositionBuf += 8;
-
- while ( *dispositionBuf == ' ' || *dispositionBuf == '=' )
- dispositionBuf++;
-
- char* bufStart = dispositionBuf;
-
- while ( *dispositionBuf && *dispositionBuf != ';' )
- dispositionBuf++;
-
- if ( dispositionBuf > bufStart )
- {
- // Skip any leading quotes...
- while ( *bufStart == '"' )
- bufStart++;
-
- // Skip any trailing quotes as well as white spaces...
- while ( *(dispositionBuf-1) == ' ' || *(dispositionBuf-1) == '"')
- dispositionBuf--;
-
- if ( dispositionBuf > bufStart )
- dispositionFilename = TQString::fromLatin1( bufStart, dispositionBuf-bufStart );
-
- break;
- }
- }
- else
- {
- char *bufStart = dispositionBuf;
-
- while ( *dispositionBuf && *dispositionBuf != ';' )
- dispositionBuf++;
-
- if ( dispositionBuf > bufStart )
- dispositionType = TQString::fromLatin1( bufStart, dispositionBuf-bufStart ).stripWhiteSpace();
-
- while ( *dispositionBuf == ';' || *dispositionBuf == ' ' )
- dispositionBuf++;
- }
- }
-
- // Content-Dispostion is not allowed to dictate directory
- // path, thus we extract the filename only.
- if ( !dispositionFilename.isEmpty() )
- {
- int pos = dispositionFilename.findRev( '/' );
-
- if( pos > -1 )
- dispositionFilename = dispositionFilename.mid(pos+1);
-
- kdDebug(7113) << "(" << m_pid << ") Content-Disposition: filename="
- << dispositionFilename<< endl;
- }
- }
- else if(strncasecmp(buf, "Content-Language:", 17) == 0) {
- TQString language = TQString::fromLatin1(trimLead(buf+17)).stripWhiteSpace();
- if (!language.isEmpty())
- setMetaData("content-language", language);
- }
- else if (strncasecmp(buf, "Proxy-Connection:", 17) == 0)
- {
- if (strncasecmp(trimLead(buf + 17), "Close", 5) == 0)
- m_bKeepAlive = false;
- else if (strncasecmp(trimLead(buf + 17), "Keep-Alive", 10)==0)
- m_bKeepAlive = true;
- }
- else if (strncasecmp(buf, "Link:", 5) == 0) {
- // We only support Link: <url>; rel="type" so far
- TQStringList link = TQStringList::split(";", TQString(buf)
- .replace(TQRegExp("^Link:[ ]*"),
- ""));
- if (link.count() == 2) {
- TQString rel = link[1].stripWhiteSpace();
- if (rel.startsWith("rel=\"")) {
- rel = rel.mid(5, rel.length() - 6);
- if (rel.lower() == "pageservices") {
- TQString url = TQString(link[0].replace(TQRegExp("[<>]"),"")).stripWhiteSpace();
- setMetaData("PageServices", url);
- }
- }
- }
- }
- else if (strncasecmp(buf, "P3P:", 4) == 0) {
- TQString p3pstr = buf;
- p3pstr = p3pstr.mid(4).simplifyWhiteSpace();
- TQStringList policyrefs, compact;
- TQStringList policyfields = TQStringList::split(TQRegExp(",[ ]*"), p3pstr);
- for (TQStringList::Iterator it = policyfields.begin();
- it != policyfields.end();
- ++it) {
- TQStringList policy = TQStringList::split("=", *it);
-
- if (policy.count() == 2) {
- if (policy[0].lower() == "policyref") {
- policyrefs << TQString(policy[1].replace(TQRegExp("[\"\']"), ""))
- .stripWhiteSpace();
- } else if (policy[0].lower() == "cp") {
- // We convert to cp\ncp\ncp\n[...]\ncp to be consistent with
- // other metadata sent in strings. This could be a bit more
- // efficient but I'm going for correctness right now.
- TQStringList cps = TQStringList::split(" ",
- TQString(policy[1].replace(TQRegExp("[\"\']"), ""))
- .simplifyWhiteSpace());
-
- for (TQStringList::Iterator j = cps.begin(); j != cps.end(); ++j)
- compact << *j;
- }
- }
- }
-
- if (!policyrefs.isEmpty())
- setMetaData("PrivacyPolicy", policyrefs.join("\n"));
-
- if (!compact.isEmpty())
- setMetaData("PrivacyCompactPolicy", compact.join("\n"));
- }
- // let them tell us if we should stay alive or not
- else if (strncasecmp(buf, "Connection:", 11) == 0)
- {
- if (strncasecmp(trimLead(buf + 11), "Close", 5) == 0)
- m_bKeepAlive = false;
- else if (strncasecmp(trimLead(buf + 11), "Keep-Alive", 10)==0)
- m_bKeepAlive = true;
- else if (strncasecmp(trimLead(buf + 11), "Upgrade", 7)==0)
- {
- if (m_responseCode == 101) {
- // Ok, an upgrade was accepted, now we must do it
- upgradeRequired = true;
- } else if (upgradeRequired) { // 426
- // Nothing to do since we did it above already
- } else {
- // Just an offer to upgrade - no need to take it
- canUpgrade = true;
- }
- }
- }
- // continue only if we know that we're HTTP/1.1
- else if ( httpRev == HTTP_11) {
- // what kind of encoding do we have? transfer?
- if (strncasecmp(buf, "Transfer-Encoding:", 18) == 0) {
- // If multiple encodings have been applied to an entity, the
- // transfer-codings MUST be listed in the order in which they
- // were applied.
- addEncoding(trimLead(buf + 18), m_qTransferEncodings);
- }
-
- // md5 signature
- else if (strncasecmp(buf, "Content-MD5:", 12) == 0) {
- m_sContentMD5 = TQString::fromLatin1(trimLead(buf + 12));
- }
-
- // *** Responses to the HTTP OPTIONS method follow
- // WebDAV capabilities
- else if (strncasecmp(buf, "DAV:", 4) == 0) {
- if (m_davCapabilities.isEmpty()) {
- m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
- }
- else {
- m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
- }
- }
- // *** Responses to the HTTP OPTIONS method finished
- }
- else if ((httpRev == HTTP_None) && (strlen(buf) != 0))
- {
- // Remote server does not seem to speak HTTP at all
- // Put the crap back into the buffer and hope for the best
- rewind();
- if (m_responseCode)
- m_prevResponseCode = m_responseCode;
-
- m_responseCode = 200; // Fake it
- httpRev = HTTP_Unknown;
- m_bKeepAlive = false;
- break;
- }
- setRewindMarker();
-
- // Clear out our buffer for further use.
- memset(buffer, 0, sizeof(buffer));
-
- } while (!m_bEOF && (len || noHeader) && (headerSize < maxHeaderSize) && (gets(buffer, sizeof(buffer)-1)));
-
- // Now process the HTTP/1.1 upgrade
- TQStringList::Iterator opt = upgradeOffers.begin();
- for( ; opt != upgradeOffers.end(); ++opt) {
- if (*opt == "TLS/1.0") {
- if(upgradeRequired) {
- if (!startTLS() && !usingTLS()) {
- error(ERR_UPGRADE_REQUIRED, *opt);
- return false;
- }
- }
- } else if (*opt == "HTTP/1.1") {
- httpRev = HTTP_11;
- } else {
- // unknown
- if (upgradeRequired) {
- error(ERR_UPGRADE_REQUIRED, *opt);
- return false;
- }
- }
- }
-
- setMetaData("charset", m_request.strCharset);
-
- // If we do not support the requested authentication method...
- if ( (m_responseCode == 401 && Authentication == AUTH_None) ||
- (m_responseCode == 407 && ProxyAuthentication == AUTH_None) )
- {
- m_bUnauthorized = false;
- if (m_request.bErrorPage)
- errorPage();
- else
- {
- error( ERR_UNSUPPORTED_ACTION, "Unknown Authorization method!" );
- return false;
- }
- }
-
- // Fixup expire date for clock drift.
- if (expireDate && (expireDate <= dateHeader))
- expireDate = 1; // Already expired.
-
- // Convert max-age into expireDate (overriding previous set expireDate)
- if (maxAge == 0)
- expireDate = 1; // Already expired.
- else if (maxAge > 0)
- {
- if (currentAge)
- maxAge -= currentAge;
- if (maxAge <=0)
- maxAge = 0;
- expireDate = time(0) + maxAge;
- }
-
- if (!expireDate)
- {
- time_t lastModifiedDate = 0;
- if (!m_request.lastModified.isEmpty())
- lastModifiedDate = KRFCDate::parseDate(m_request.lastModified);
-
- if (lastModifiedDate)
- {
- long diff = static_cast<long>(difftime(dateHeader, lastModifiedDate));
- if (diff < 0)
- expireDate = time(0) + 1;
- else
- expireDate = time(0) + (diff / 10);
- }
- else
- {
- expireDate = time(0) + DEFAULT_CACHE_EXPIRE;
- }
- }
-
- // DONE receiving the header!
- if (!cookieStr.isEmpty())
- {
- if ((m_request.cookieMode == HTTPRequest::CookiesAuto) && m_request.bUseCookiejar)
- {
- // Give cookies to the cookiejar.
- TQString domain = config()->readEntry("cross-domain");
- if (!domain.isEmpty() && isCrossDomainRequest(m_request.url.host(), domain))
- cookieStr = "Cross-Domain\n" + cookieStr;
- addCookies( m_request.url.url(), cookieStr );
- }
- else if (m_request.cookieMode == HTTPRequest::CookiesManual)
- {
- // Pass cookie to application
- setMetaData("setcookies", cookieStr);
- }
- }
-
- if (m_request.bMustRevalidate)
- {
- m_request.bMustRevalidate = false; // Reset just in case.
- if (cacheValidated)
- {
- // Yippie, we can use the cached version.
- // Update the cache with new "Expire" headers.
- fclose(m_request.fcache);
- m_request.fcache = 0;
- updateExpireDate( expireDate, true );
- m_request.fcache = checkCacheEntry( ); // Re-read cache entry
-
- if (m_request.fcache)
- {
- m_request.bCachedRead = true;
- goto try_again; // Read header again, but now from cache.
- }
- else
- {
- // Where did our cache entry go???
- }
- }
- else
- {
- // Validation failed. Close cache.
- fclose(m_request.fcache);
- m_request.fcache = 0;
- }
- }
-
- // We need to reread the header if we got a '100 Continue' or '102 Processing'
- if ( cont )
- {
- goto try_again;
- }
-
- // Do not do a keep-alive connection if the size of the
- // response is not known and the response is not Chunked.
- if (!m_bChunked && (m_iSize == NO_SIZE))
- m_bKeepAlive = false;
-
- if ( m_responseCode == 204 )
- {
- return true;
- }
-
- // We need to try to login again if we failed earlier
- if ( m_bUnauthorized )
- {
- if ( (m_responseCode == 401) ||
- (m_bUseProxy && (m_responseCode == 407))
- )
- {
- if ( getAuthorization() )
- {
- // for NTLM Authentication we have to keep the connection open!
- if ( Authentication == AUTH_NTLM && m_strAuthorization.length() > 4 )
- {
- m_bKeepAlive = true;
- readBody( true );
- }
- else if (ProxyAuthentication == AUTH_NTLM && m_strProxyAuthorization.length() > 4)
- {
- readBody( true );
- }
- else
- httpCloseConnection();
- return false; // Try again.
- }
-
- if (m_bError)
- return false; // Error out
-
- // Show error page...
- }
- m_bUnauthorized = false;
- }
-
- // We need to do a redirect
- if (!locationStr.isEmpty())
- {
- KURL u(m_request.url, locationStr);
- if(!u.isValid())
- {
- error(ERR_MALFORMED_URL, u.url());
- return false;
- }
- if ((u.protocol() != "http") && (u.protocol() != "https") &&
- (u.protocol() != "ftp") && (u.protocol() != "webdav") &&
- (u.protocol() != "webdavs"))
- {
- redirection(u);
- error(ERR_ACCESS_DENIED, u.url());
- return false;
- }
-
- // preserve #ref: (bug 124654)
- // if we were at http://host/resource1#ref, we sent a GET for "/resource1"
- // if we got redirected to http://host/resource2, then we have to re-add
- // the fragment:
- if (m_request.url.hasRef() && !u.hasRef() &&
- (m_request.url.host() == u.host()) &&
- (m_request.url.protocol() == u.protocol()))
- u.setRef(m_request.url.ref());
-
- m_bRedirect = true;
- m_redirectLocation = u;
-
- if (!m_request.id.isEmpty())
- {
- sendMetaData();
- }
-
- kdDebug(7113) << "(" << m_pid << ") request.url: " << m_request.url.url()
- << endl << "LocationStr: " << locationStr.data() << endl;
-
- kdDebug(7113) << "(" << m_pid << ") Requesting redirection to: " << u.url()
- << endl;
-
- // If we're redirected to a http:// url, remember that we're doing webdav...
- if (m_protocol == "webdav" || m_protocol == "webdavs")
- u.setProtocol(m_protocol);
-
- redirection(u);
- m_request.bCachedWrite = false; // Turn off caching on re-direction (DA)
- mayCache = false;
- }
-
- // Inform the job that we can indeed resume...
- if ( bCanResume && m_request.offset )
- canResume();
- else
- m_request.offset = 0;
-
- // We don't cache certain text objects
- if (m_strMimeType.startsWith("text/") &&
- (m_strMimeType != "text/css") &&
- (m_strMimeType != "text/x-javascript") &&
- !hasCacheDirective)
- {
- // Do not cache secure pages or pages
- // originating from password protected sites
- // unless the webserver explicitly allows it.
- if ( m_bIsSSL || (Authentication != AUTH_None) )
- {
- m_request.bCachedWrite = false;
- mayCache = false;
- }
- }
-
- // WABA: Correct for tgz files with a gzip-encoding.
- // They really shouldn't put gzip in the Content-Encoding field!
- // Web-servers really shouldn't do this: They let Content-Size refer
- // to the size of the tgz file, not to the size of the tar file,
- // while the Content-Type refers to "tar" instead of "tgz".
- if (m_qContentEncodings.last() == "gzip")
- {
- if (m_strMimeType == "application/x-tar")
- {
- m_qContentEncodings.remove(m_qContentEncodings.fromLast());
- m_strMimeType = TQString::fromLatin1("application/x-tgz");
- }
- else if (m_strMimeType == "application/postscript")
- {
- // LEONB: Adding another exception for psgz files.
- // Could we use the mimelnk files instead of hardcoding all this?
- m_qContentEncodings.remove(m_qContentEncodings.fromLast());
- m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
- }
- else if ( m_request.allowCompressedPage &&
- m_strMimeType != "application/x-tgz" &&
- m_strMimeType != "application/x-targz" &&
- m_strMimeType != "application/x-gzip" &&
- m_request.url.path().right(6) == ".ps.gz" )
- {
- m_qContentEncodings.remove(m_qContentEncodings.fromLast());
- m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
- }
- else if ( (m_request.allowCompressedPage &&
- m_strMimeType == "text/html")
- ||
- (m_request.allowCompressedPage &&
- m_strMimeType != "application/x-tgz" &&
- m_strMimeType != "application/x-targz" &&
- m_strMimeType != "application/x-gzip" &&
- m_request.url.path().right(3) != ".gz")
- )
- {
- // Unzip!
- }
- else
- {
- m_qContentEncodings.remove(m_qContentEncodings.fromLast());
- m_strMimeType = TQString::fromLatin1("application/x-gzip");
- }
- }
-
- // We can't handle "bzip2" encoding (yet). So if we get something with
- // bzip2 encoding, we change the mimetype to "application/x-bzip2".
- // Note for future changes: some web-servers send both "bzip2" as
- // encoding and "application/x-bzip2" as mimetype. That is wrong.
- // currently that doesn't bother us, because we remove the encoding
- // and set the mimetype to x-bzip2 anyway.
- if (m_qContentEncodings.last() == "bzip2")
- {
- m_qContentEncodings.remove(m_qContentEncodings.fromLast());
- m_strMimeType = TQString::fromLatin1("application/x-bzip2");
- }
-
- // Convert some common mimetypes to standard KDE mimetypes
- if (m_strMimeType == "application/x-targz")
- m_strMimeType = TQString::fromLatin1("application/x-tgz");
- else if (m_strMimeType == "application/zip")
- m_strMimeType = TQString::fromLatin1("application/x-zip");
- else if (m_strMimeType == "image/x-png")
- m_strMimeType = TQString::fromLatin1("image/png");
- else if (m_strMimeType == "image/bmp")
- m_strMimeType = TQString::fromLatin1("image/x-bmp");
- else if (m_strMimeType == "audio/mpeg" || m_strMimeType == "audio/x-mpeg" || m_strMimeType == "audio/mp3")
- m_strMimeType = TQString::fromLatin1("audio/x-mp3");
- else if (m_strMimeType == "audio/microsoft-wave")
- m_strMimeType = TQString::fromLatin1("audio/x-wav");
- else if (m_strMimeType == "audio/midi")
- m_strMimeType = TQString::fromLatin1("audio/x-midi");
- else if (m_strMimeType == "image/x-xpixmap")
- m_strMimeType = TQString::fromLatin1("image/x-xpm");
- else if (m_strMimeType == "application/rtf")
- m_strMimeType = TQString::fromLatin1("text/rtf");
-
- // Crypto ones....
- else if (m_strMimeType == "application/pkix-cert" ||
- m_strMimeType == "application/binary-certificate")
- {
- m_strMimeType = TQString::fromLatin1("application/x-x509-ca-cert");
- }
-
- // Prefer application/x-tgz or x-gzpostscript over application/x-gzip.
- else if (m_strMimeType == "application/x-gzip")
- {
- if ((m_request.url.path().right(7) == ".tar.gz") ||
- (m_request.url.path().right(4) == ".tar"))
- m_strMimeType = TQString::fromLatin1("application/x-tgz");
- if ((m_request.url.path().right(6) == ".ps.gz"))
- m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
- }
-
- // Some webservers say "text/plain" when they mean "application/x-bzip2"
- else if ((m_strMimeType == "text/plain") || (m_strMimeType == "application/octet-stream"))
- {
- TQString ext = m_request.url.path().right(4).upper();
- if (ext == ".BZ2")
- m_strMimeType = TQString::fromLatin1("application/x-bzip2");
- else if (ext == ".PEM")
- m_strMimeType = TQString::fromLatin1("application/x-x509-ca-cert");
- else if (ext == ".SWF")
- m_strMimeType = TQString::fromLatin1("application/x-shockwave-flash");
- else if (ext == ".PLS")
- m_strMimeType = TQString::fromLatin1("audio/x-scpls");
- else if (ext == ".WMV")
- m_strMimeType = TQString::fromLatin1("video/x-ms-wmv");
- }
-
-#if 0
- // Even if we can't rely on content-length, it seems that we should
- // never get more data than content-length. Maybe less, if the
- // content-length refers to the unzipped data.
- if (!m_qContentEncodings.isEmpty())
- {
- // If we still have content encoding we can't rely on the Content-Length.
- m_iSize = NO_SIZE;
- }
-#endif
-
- if( !dispositionType.isEmpty() )
- {
- kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition type to: "
- << dispositionType << endl;
- setMetaData("content-disposition-type", dispositionType);
- }
- if( !dispositionFilename.isEmpty() )
- {
- kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition filename to: "
- << dispositionFilename << endl;
- // ### KDE4: setting content-disposition to filename for pre 3.5.2 compatability
- setMetaData("content-disposition", dispositionFilename);
- setMetaData("content-disposition-filename", dispositionFilename);
- }
-
- if (!m_request.lastModified.isEmpty())
- setMetaData("modified", m_request.lastModified);
-
- if (!mayCache)
- {
- setMetaData("no-cache", "true");
- setMetaData("expire-date", "1"); // Expired
- }
- else
- {
- TQString tmp;
- tmp.setNum(expireDate);
- setMetaData("expire-date", tmp);
- tmp.setNum(time(0)); // Cache entry will be created shortly.
- setMetaData("cache-creation-date", tmp);
- }
-
- // Let the app know about the mime-type iff this is not
- // a redirection and the mime-type string is not empty.
- if (locationStr.isEmpty() && (!m_strMimeType.isEmpty() ||
- m_request.method == HTTP_HEAD))
- {
- kdDebug(7113) << "(" << m_pid << ") Emitting mimetype " << m_strMimeType << endl;
- mimeType( m_strMimeType );
- }
-
- // Do not move send response header before any redirection as it seems
- // to screw up some sites. See BR# 150904.
- forwardHttpResponseHeader();
-
- if (m_request.method == HTTP_HEAD)
- return true;
-
- // Do we want to cache this request?
- if (m_request.bUseCache)
- {
- ::unlink( TQFile::encodeName(m_request.cef));
- if ( m_request.bCachedWrite && !m_strMimeType.isEmpty() )
- {
- // Check...
- createCacheEntry(m_strMimeType, expireDate); // Create a cache entry
- if (!m_request.fcache)
- {
- m_request.bCachedWrite = false; // Error creating cache entry.
- kdDebug(7113) << "(" << m_pid << ") Error creating cache entry for " << m_request.url.url()<<"!\n";
- }
- m_request.expireDate = expireDate;
- m_maxCacheSize = config()->readNumEntry("MaxCacheSize", DEFAULT_MAX_CACHE_SIZE) / 2;
- }
- }
-
- if (m_request.bCachedWrite && !m_strMimeType.isEmpty())
- kdDebug(7113) << "(" << m_pid << ") Cache, adding \"" << m_request.url.url() << "\"" << endl;
- else if (m_request.bCachedWrite && m_strMimeType.isEmpty())
- kdDebug(7113) << "(" << m_pid << ") Cache, pending \"" << m_request.url.url() << "\"" << endl;
- else
- kdDebug(7113) << "(" << m_pid << ") Cache, not adding \"" << m_request.url.url() << "\"" << endl;
- return true;
-}
-
-
-void HTTPProtocol::addEncoding(TQString encoding, TQStringList &encs)
-{
- encoding = encoding.stripWhiteSpace().lower();
- // Identity is the same as no encoding
- if (encoding == "identity") {
- return;
- } else if (encoding == "8bit") {
- // Strange encoding returned by http://linac.ikp.physik.tu-darmstadt.de
- return;
- } else if (encoding == "chunked") {
- m_bChunked = true;
- // Anyone know of a better way to handle unknown sizes possibly/ideally with unsigned ints?
- //if ( m_cmd != CMD_COPY )
- m_iSize = NO_SIZE;
- } else if ((encoding == "x-gzip") || (encoding == "gzip")) {
- encs.append(TQString::fromLatin1("gzip"));
- } else if ((encoding == "x-bzip2") || (encoding == "bzip2")) {
- encs.append(TQString::fromLatin1("bzip2")); // Not yet supported!
- } else if ((encoding == "x-deflate") || (encoding == "deflate")) {
- encs.append(TQString::fromLatin1("deflate"));
- } else {
- kdDebug(7113) << "(" << m_pid << ") Unknown encoding encountered. "
- << "Please write code. Encoding = \"" << encoding
- << "\"" << endl;
- }
-}
-
-bool HTTPProtocol::sendBody()
-{
- int result=-1;
- int length=0;
-
- infoMessage( i18n( "Requesting data to send" ) );
-
- // m_bufPOST will NOT be empty iff authentication was required before posting
- // the data OR a re-connect is requested from ::readHeader because the
- // connection was lost for some reason.
- if ( !m_bufPOST.isNull() )
- {
- kdDebug(7113) << "(" << m_pid << ") POST'ing saved data..." << endl;
-
- result = 0;
- length = m_bufPOST.size();
- }
- else
- {
- kdDebug(7113) << "(" << m_pid << ") POST'ing live data..." << endl;
-
- TQByteArray buffer;
- int old_size;
-
- m_bufPOST.resize(0);
- do
- {
- dataReq(); // Request for data
- result = readData( buffer );
- if ( result > 0 )
- {
- length += result;
- old_size = m_bufPOST.size();
- m_bufPOST.resize( old_size+result );
- memcpy( m_bufPOST.data()+ old_size, buffer.data(), buffer.size() );
- buffer.resize(0);
- }
- } while ( result > 0 );
- }
-
- if ( result < 0 )
- {
- error( ERR_ABORTED, m_request.hostname );
- return false;
- }
-
- infoMessage( i18n( "Sending data to %1" ).arg( m_request.hostname ) );
-
- TQString size = TQString ("Content-Length: %1\r\n\r\n").arg(length);
- kdDebug( 7113 ) << "(" << m_pid << ")" << size << endl;
-
- // Send the content length...
- bool sendOk = (write(size.latin1(), size.length()) == (ssize_t) size.length());
- if (!sendOk)
- {
- kdDebug( 7113 ) << "(" << m_pid << ") Connection broken when sending "
- << "content length: (" << m_state.hostname << ")" << endl;
- error( ERR_CONNECTION_BROKEN, m_state.hostname );
- return false;
- }
-
- // Send the data...
- // kdDebug( 7113 ) << "(" << m_pid << ") POST DATA: " << TQCString(m_bufPOST) << endl;
- sendOk = (write(m_bufPOST.data(), m_bufPOST.size()) == (ssize_t) m_bufPOST.size());
- if (!sendOk)
- {
- kdDebug(7113) << "(" << m_pid << ") Connection broken when sending message body: ("
- << m_state.hostname << ")" << endl;
- error( ERR_CONNECTION_BROKEN, m_state.hostname );
- return false;
- }
-
- return true;
-}
-
-void HTTPProtocol::httpClose( bool keepAlive )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose" << endl;
-
- if (m_request.fcache)
- {
- fclose(m_request.fcache);
- m_request.fcache = 0;
- if (m_request.bCachedWrite)
- {
- TQString filename = m_request.cef + ".new";
- ::unlink( TQFile::encodeName(filename) );
- }
- }
-
- // Only allow persistent connections for GET requests.
- // NOTE: we might even want to narrow this down to non-form
- // based submit requests which will require a meta-data from
- // tdehtml.
- if (keepAlive && (!m_bUseProxy ||
- m_bPersistentProxyConnection || m_bIsTunneled))
- {
- if (!m_keepAliveTimeout)
- m_keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
- else if (m_keepAliveTimeout > 2*DEFAULT_KEEP_ALIVE_TIMEOUT)
- m_keepAliveTimeout = 2*DEFAULT_KEEP_ALIVE_TIMEOUT;
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose: keep alive (" << m_keepAliveTimeout << ")" << endl;
- TQByteArray data;
- TQDataStream stream( data, IO_WriteOnly );
- stream << int(99); // special: Close connection
- setTimeoutSpecialCommand(m_keepAliveTimeout, data);
- return;
- }
-
- httpCloseConnection();
-}
-
-void HTTPProtocol::closeConnection()
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::closeConnection" << endl;
- httpCloseConnection ();
-}
-
-void HTTPProtocol::httpCloseConnection ()
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCloseConnection" << endl;
- m_bIsTunneled = false;
- m_bKeepAlive = false;
- closeDescriptor();
- setTimeoutSpecialCommand(-1); // Cancel any connection timeout
-}
-
-void HTTPProtocol::slave_status()
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::slave_status" << endl;
-
- if ( m_iSock != -1 && !isConnectionValid() )
- httpCloseConnection();
-
- slaveStatus( m_state.hostname, (m_iSock != -1) );
-}
-
-void HTTPProtocol::mimetype( const KURL& url )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mimetype: "
- << url.prettyURL() << endl;
-
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.method = HTTP_HEAD;
- m_request.path = url.path();
- m_request.query = url.query();
- m_request.cache = CC_Cache;
- m_request.doProxy = m_bUseProxy;
-
- retrieveHeader();
-
- kdDebug(7113) << "(" << m_pid << ") http: mimetype = " << m_strMimeType
- << endl;
-}
-
-void HTTPProtocol::special( const TQByteArray &data )
-{
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::special" << endl;
-
- int tmp;
- TQDataStream stream(data, IO_ReadOnly);
-
- stream >> tmp;
- switch (tmp) {
- case 1: // HTTP POST
- {
- KURL url;
- stream >> url;
- post( url );
- break;
- }
- case 2: // cache_update
- {
- KURL url;
- bool no_cache;
- time_t expireDate;
- stream >> url >> no_cache >> expireDate;
- cacheUpdate( url, no_cache, expireDate );
- break;
- }
- case 5: // WebDAV lock
- {
- KURL url;
- TQString scope, type, owner;
- stream >> url >> scope >> type >> owner;
- davLock( url, scope, type, owner );
- break;
- }
- case 6: // WebDAV unlock
- {
- KURL url;
- stream >> url;
- davUnlock( url );
- break;
- }
- case 7: // Generic WebDAV
- {
- KURL url;
- int method;
- stream >> url >> method;
- davGeneric( url, (TDEIO::HTTP_METHOD) method );
- break;
- }
- case 99: // Close Connection
- {
- httpCloseConnection();
- break;
- }
- default:
- // Some command we don't understand.
- // Just ignore it, it may come from some future version of KDE.
- break;
- }
-}
-
-/**
- * Read a chunk from the data stream.
- */
-int HTTPProtocol::readChunked()
-{
- if ((m_iBytesLeft == 0) || (m_iBytesLeft == NO_SIZE))
- {
- setRewindMarker();
-
- m_bufReceive.resize(4096);
-
- if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
- {
- kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
- return -1;
- }
- // We could have got the CRLF of the previous chunk.
- // If so, try again.
- if (m_bufReceive[0] == '\0')
- {
- if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
- {
- kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
- return -1;
- }
- }
-
- // m_bEOF is set to true when read called from gets returns 0. For chunked reading 0
- // means end of chunked transfer and not error. See RFC 2615 section 3.6.1
- #if 0
- if (m_bEOF)
- {
- kdDebug(7113) << "(" << m_pid << ") EOF on Chunk header" << endl;
- return -1;
- }
- #endif
-
- long long trunkSize = STRTOLL(m_bufReceive.data(), 0, 16);
- if (trunkSize < 0)
- {
- kdDebug(7113) << "(" << m_pid << ") Negative chunk size" << endl;
- return -1;
- }
- m_iBytesLeft = trunkSize;
-
- // kdDebug(7113) << "(" << m_pid << ") Chunk size = " << m_iBytesLeft << " bytes" << endl;
-
- if (m_iBytesLeft == 0)
- {
- // Last chunk.
- // Skip trailers.
- do {
- // Skip trailer of last chunk.
- if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
- {
- kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk trailer" << endl;
- return -1;
- }
- // kdDebug(7113) << "(" << m_pid << ") Chunk trailer = \"" << m_bufReceive.data() << "\"" << endl;
- }
- while (strlen(m_bufReceive.data()) != 0);
-
- return 0;
- }
- }
-
- int bytesReceived = readLimited();
- if (!m_iBytesLeft)
- m_iBytesLeft = NO_SIZE; // Don't stop, continue with next chunk
-
- // kdDebug(7113) << "(" << m_pid << ") readChunked: BytesReceived=" << bytesReceived << endl;
- return bytesReceived;
-}
-
-int HTTPProtocol::readLimited()
-{
- if (!m_iBytesLeft)
- return 0;
-
- m_bufReceive.resize(4096);
-
- int bytesReceived;
- int bytesToReceive;
-
- if (m_iBytesLeft > m_bufReceive.size())
- bytesToReceive = m_bufReceive.size();
- else
- bytesToReceive = m_iBytesLeft;
-
- bytesReceived = read(m_bufReceive.data(), bytesToReceive);
-
- if (bytesReceived <= 0)
- return -1; // Error: connection lost
-
- m_iBytesLeft -= bytesReceived;
- return bytesReceived;
-}
-
-int HTTPProtocol::readUnlimited()
-{
- if (m_bKeepAlive)
- {
- kdDebug(7113) << "(" << m_pid << ") Unbounded datastream on a Keep "
- << "alive connection!" << endl;
- m_bKeepAlive = false;
- }
-
- m_bufReceive.resize(4096);
-
- int result = read(m_bufReceive.data(), m_bufReceive.size());
- if (result > 0)
- return result;
-
- m_bEOF = true;
- m_iBytesLeft = 0;
- return 0;
-}
-
-void HTTPProtocol::slotData(const TQByteArray &_d)
-{
- if (!_d.size())
- {
- m_bEOD = true;
- return;
- }
-
- if (m_iContentLeft != NO_SIZE)
- {
- if (m_iContentLeft >= _d.size())
- m_iContentLeft -= _d.size();
- else
- m_iContentLeft = NO_SIZE;
- }
-
- TQByteArray d = _d;
- if ( !m_dataInternal )
- {
- // If a broken server does not send the mime-type,
- // we try to id it from the content before dealing
- // with the content itself.
- if ( m_strMimeType.isEmpty() && !m_bRedirect &&
- !( m_responseCode >= 300 && m_responseCode <=399) )
- {
- kdDebug(7113) << "(" << m_pid << ") Determining mime-type from content..." << endl;
- int old_size = m_mimeTypeBuffer.size();
- m_mimeTypeBuffer.resize( old_size + d.size() );
- memcpy( m_mimeTypeBuffer.data() + old_size, d.data(), d.size() );
- if ( (m_iBytesLeft != NO_SIZE) && (m_iBytesLeft > 0)
- && (m_mimeTypeBuffer.size() < 1024) )
- {
- m_cpMimeBuffer = true;
- return; // Do not send up the data since we do not yet know its mimetype!
- }
-
- kdDebug(7113) << "(" << m_pid << ") Mimetype buffer size: " << m_mimeTypeBuffer.size()
- << endl;
-
- KMimeMagicResult *result;
- result = KMimeMagic::self()->findBufferFileType( m_mimeTypeBuffer,
- m_request.url.fileName() );
- if( result )
- {
- m_strMimeType = result->mimeType();
- kdDebug(7113) << "(" << m_pid << ") Mimetype from content: "
- << m_strMimeType << endl;
- }
-
- if ( m_strMimeType.isEmpty() )
- {
- m_strMimeType = TQString::fromLatin1( DEFAULT_MIME_TYPE );
- kdDebug(7113) << "(" << m_pid << ") Using default mimetype: "
- << m_strMimeType << endl;
- }
-
- if ( m_request.bCachedWrite )
- {
- createCacheEntry( m_strMimeType, m_request.expireDate );
- if (!m_request.fcache)
- m_request.bCachedWrite = false;
- }
-
- if ( m_cpMimeBuffer )
- {
- // Do not make any assumption about the state of the TQByteArray we received.
- // Fix the crash described by BR# 130104.
- d.detach();
- d.resize(0);
- d.resize(m_mimeTypeBuffer.size());
- memcpy( d.data(), m_mimeTypeBuffer.data(),
- d.size() );
- }
- mimeType(m_strMimeType);
- m_mimeTypeBuffer.resize(0);
- }
-
- data( d );
- if (m_request.bCachedWrite && m_request.fcache)
- writeCacheEntry(d.data(), d.size());
- }
- else
- {
- uint old_size = m_bufWebDavData.size();
- m_bufWebDavData.resize (old_size + d.size());
- memcpy (m_bufWebDavData.data() + old_size, d.data(), d.size());
- }
-}
-
-/**
- * This function is our "receive" function. It is responsible for
- * downloading the message (not the header) from the HTTP server. It
- * is called either as a response to a client's TDEIOJob::dataEnd()
- * (meaning that the client is done sending data) or by 'httpOpen()'
- * (if we are in the process of a PUT/POST request). It can also be
- * called by a webDAV function, to receive stat/list/property/etc.
- * data; in this case the data is stored in m_bufWebDavData.
- */
-bool HTTPProtocol::readBody( bool dataInternal /* = false */ )
-{
- if (m_responseCode == 204)
- return true;
-
- m_bEOD = false;
- // Note that when dataInternal is true, we are going to:
- // 1) save the body data to a member variable, m_bufWebDavData
- // 2) _not_ advertise the data, speed, size, etc., through the
- // corresponding functions.
- // This is used for returning data to WebDAV.
- m_dataInternal = dataInternal;
- if ( dataInternal )
- m_bufWebDavData.resize (0);
-
- // Check if we need to decode the data.
- // If we are in copy mode, then use only transfer decoding.
- bool useMD5 = !m_sContentMD5.isEmpty();
-
- // Deal with the size of the file.
- TDEIO::filesize_t sz = m_request.offset;
- if ( sz )
- m_iSize += sz;
-
- // Update the application with total size except when
- // it is compressed, or when the data is to be handled
- // internally (webDAV). If compressed we have to wait
- // until we uncompress to find out the actual data size
- if ( !dataInternal ) {
- if ( (m_iSize > 0) && (m_iSize != NO_SIZE)) {
- totalSize(m_iSize);
- infoMessage( i18n( "Retrieving %1 from %2...").arg(TDEIO::convertSize(m_iSize))
- .arg( m_request.hostname ) );
- }
- else
- {
- totalSize ( 0 );
- }
- }
- else
- infoMessage( i18n( "Retrieving from %1..." ).arg( m_request.hostname ) );
-
- if (m_request.bCachedRead)
- {
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: read data from cache!" << endl;
- m_request.bCachedWrite = false;
-
- char buffer[ MAX_IPC_SIZE ];
-
- m_iContentLeft = NO_SIZE;
-
- // Jippie! It's already in the cache :-)
- while (!feof(m_request.fcache) && !ferror(m_request.fcache))
- {
- int nbytes = fread( buffer, 1, MAX_IPC_SIZE, m_request.fcache);
-
- if (nbytes > 0)
- {
- m_bufReceive.setRawData( buffer, nbytes);
- slotData( m_bufReceive );
- m_bufReceive.resetRawData( buffer, nbytes );
- sz += nbytes;
- }
- }
-
- m_bufReceive.resize( 0 );
-
- if ( !dataInternal )
- {
- processedSize( sz );
- data( TQByteArray() );
- }
-
- return true;
- }
-
-
- if (m_iSize != NO_SIZE)
- m_iBytesLeft = m_iSize - sz;
- else
- m_iBytesLeft = NO_SIZE;
-
- m_iContentLeft = m_iBytesLeft;
-
- if (m_bChunked)
- m_iBytesLeft = NO_SIZE;
-
- kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: retrieve data. "
- << TDEIO::number(m_iBytesLeft) << " left." << endl;
-
- // Main incoming loop... Gather everything while we can...
- m_cpMimeBuffer = false;
- m_mimeTypeBuffer.resize(0);
- struct timeval last_tv;
- gettimeofday( &last_tv, 0L );
-
- HTTPFilterChain chain;
-
- TQObject::connect(&chain, TQT_SIGNAL(output(const TQByteArray &)),
- this, TQT_SLOT(slotData(const TQByteArray &)));
- TQObject::connect(&chain, TQT_SIGNAL(error(int, const TQString &)),
- this, TQT_SLOT(error(int, const TQString &)));
-
- // decode all of the transfer encodings
- while (!m_qTransferEncodings.isEmpty())
- {
- TQString enc = m_qTransferEncodings.last();
- m_qTransferEncodings.remove(m_qTransferEncodings.fromLast());
- if ( enc == "gzip" )
- chain.addFilter(new HTTPFilterGZip);
- else if ( enc == "deflate" )
- chain.addFilter(new HTTPFilterDeflate);
- }
-
- // From HTTP 1.1 Draft 6:
- // The MD5 digest is computed based on the content of the entity-body,
- // including any content-coding that has been applied, but not including
- // any transfer-encoding applied to the message-body. If the message is
- // received with a transfer-encoding, that encoding MUST be removed
- // prior to checking the Content-MD5 value against the received entity.
- HTTPFilterMD5 *md5Filter = 0;
- if ( useMD5 )
- {
- md5Filter = new HTTPFilterMD5;
- chain.addFilter(md5Filter);
- }
-
- // now decode all of the content encodings
- // -- Why ?? We are not
- // -- a proxy server, be a client side implementation!! The applications
- // -- are capable of determinig how to extract the encoded implementation.
- // WB: That's a misunderstanding. We are free to remove the encoding.
- // WB: Some braindead www-servers however, give .tgz files an encoding
- // WB: of "gzip" (or even "x-gzip") and a content-type of "applications/tar"
- // WB: They shouldn't do that. We can work around that though...
- while (!m_qContentEncodings.isEmpty())
- {
- TQString enc = m_qContentEncodings.last();
- m_qContentEncodings.remove(m_qContentEncodings.fromLast());
- if ( enc == "gzip" )
- chain.addFilter(new HTTPFilterGZip);
- else if ( enc == "deflate" )
- chain.addFilter(new HTTPFilterDeflate);
- }
-
- while (!m_bEOF)
- {
- int bytesReceived;
-
- if (m_bChunked)
- bytesReceived = readChunked();
- else if (m_iSize != NO_SIZE)
- bytesReceived = readLimited();
- else
- bytesReceived = readUnlimited();
-
- // make sure that this wasn't an error, first
- // kdDebug(7113) << "(" << (int) m_pid << ") readBody: bytesReceived: "
- // << (int) bytesReceived << " m_iSize: " << (int) m_iSize << " Chunked: "
- // << (int) m_bChunked << " BytesLeft: "<< (int) m_iBytesLeft << endl;
- if (bytesReceived == -1)
- {
- if (m_iContentLeft == 0)
- {
- // gzip'ed data sometimes reports a too long content-length.
- // (The length of the unzipped data)
- m_iBytesLeft = 0;
- break;
- }
- // Oh well... log an error and bug out
- kdDebug(7113) << "(" << m_pid << ") readBody: bytesReceived==-1 sz=" << (int)sz
- << " Connnection broken !" << endl;
- error(ERR_CONNECTION_BROKEN, m_state.hostname);
- return false;
- }
-
- // I guess that nbytes == 0 isn't an error.. but we certainly
- // won't work with it!
- if (bytesReceived > 0)
- {
- // Important: truncate the buffer to the actual size received!
- // Otherwise garbage will be passed to the app
- m_bufReceive.truncate( bytesReceived );
-
- chain.slotInput(m_bufReceive);
-
- if (m_bError)
- return false;
-
- sz += bytesReceived;
- if (!dataInternal)
- processedSize( sz );
- }
- m_bufReceive.resize(0); // res
-
- if (m_iBytesLeft && m_bEOD && !m_bChunked)
- {
- // gzip'ed data sometimes reports a too long content-length.
- // (The length of the unzipped data)
- m_iBytesLeft = 0;
- }
-
- if (m_iBytesLeft == 0)
- {
- kdDebug(7113) << "("<<m_pid<<") EOD received! Left = "<< TDEIO::number(m_iBytesLeft) << endl;
- break;
- }
- }
- chain.slotInput(TQByteArray()); // Flush chain.
-
- if ( useMD5 )
- {
- TQString calculatedMD5 = md5Filter->md5();
-
- if ( m_sContentMD5 == calculatedMD5 )
- kdDebug(7113) << "(" << m_pid << ") MD5 checksum MATCHED!!" << endl;
- else
- kdDebug(7113) << "(" << m_pid << ") MD5 checksum MISMATCH! Expected: "
- << calculatedMD5 << ", Got: " << m_sContentMD5 << endl;
- }
-
- // Close cache entry
- if (m_iBytesLeft == 0)
- {
- if (m_request.bCachedWrite && m_request.fcache)
- closeCacheEntry();
- else if (m_request.bCachedWrite)
- kdDebug(7113) << "(" << m_pid << ") no cache file!\n";
- }
- else
- {
- kdDebug(7113) << "(" << m_pid << ") still "<< TDEIO::number(m_iBytesLeft)
- << " bytes left! can't close cache entry!\n";
- }
-
- if (sz <= 1)
- {
- /* kdDebug(7113) << "(" << m_pid << ") readBody: sz = " << TDEIO::number(sz)
- << ", responseCode =" << m_responseCode << endl; */
- if (m_responseCode >= 500 && m_responseCode <= 599)
- error(ERR_INTERNAL_SERVER, m_state.hostname);
- else if (m_responseCode >= 400 && m_responseCode <= 499)
- error(ERR_DOES_NOT_EXIST, m_state.hostname);
- }
-
- if (!dataInternal)
- data( TQByteArray() );
-
- return true;
-}
-
-
-void HTTPProtocol::error( int _err, const TQString &_text )
-{
- httpClose(false);
-
- if (!m_request.id.isEmpty())
- {
- forwardHttpResponseHeader();
- sendMetaData();
- }
-
- // Clear of the temporary POST buffer if it is not empty...
- if (!m_bufPOST.isEmpty())
- {
- m_bufPOST.resize(0);
- kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
- "buffer..." << endl;
- }
-
- SlaveBase::error( _err, _text );
- m_bError = true;
-}
-
-
-void HTTPProtocol::addCookies( const TQString &url, const TQCString &cookieHeader )
-{
- long windowId = m_request.window.toLong();
- TQByteArray params;
- TQDataStream stream(params, IO_WriteOnly);
- stream << url << cookieHeader << windowId;
-
- kdDebug(7113) << "(" << m_pid << ") " << cookieHeader << endl;
- kdDebug(7113) << "(" << m_pid << ") " << "Window ID: "
- << windowId << ", for host = " << url << endl;
-
- if ( !dcopClient()->send( "kded", "kcookiejar", "addCookies(TQString,TQCString,long int)", params ) )
- {
- kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
- }
-}
-
-TQString HTTPProtocol::findCookies( const TQString &url)
-{
- TQCString replyType;
- TQByteArray params;
- TQByteArray reply;
- TQString result;
-
- long windowId = m_request.window.toLong();
- result = TQString::null;
- TQDataStream stream(params, IO_WriteOnly);
- stream << url << windowId;
-
- if ( !dcopClient()->call( "kded", "kcookiejar", "findCookies(TQString,long int)",
- params, replyType, reply ) )
- {
- kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
- return result;
- }
- if ( replyType == "TQString" )
- {
- TQDataStream stream2( reply, IO_ReadOnly );
- stream2 >> result;
- }
- else
- {
- kdError(7113) << "(" << m_pid << ") DCOP function findCookies(...) returns "
- << replyType << ", expected TQString" << endl;
- }
- return result;
-}
-
-/******************************* CACHING CODE ****************************/
-
-
-void HTTPProtocol::cacheUpdate( const KURL& url, bool no_cache, time_t expireDate)
-{
- if ( !checkRequestURL( url ) )
- return;
-
- m_request.path = url.path();
- m_request.query = url.query();
- m_request.cache = CC_Reload;
- m_request.doProxy = m_bUseProxy;
-
- if (no_cache)
- {
- m_request.fcache = checkCacheEntry( );
- if (m_request.fcache)
- {
- fclose(m_request.fcache);
- m_request.fcache = 0;
- ::unlink( TQFile::encodeName(m_request.cef) );
- }
- }
- else
- {
- updateExpireDate( expireDate );
- }
- finished();
-}
-
-// !START SYNC!
-// The following code should be kept in sync
-// with the code in http_cache_cleaner.cpp
-
-FILE* HTTPProtocol::checkCacheEntry( bool readWrite)
-{
- const TQChar separator = '_';
-
- TQString CEF = m_request.path;
-
- int p = CEF.find('/');
-
- while(p != -1)
- {
- CEF[p] = separator;
- p = CEF.find('/', p);
- }
-
- TQString host = m_request.hostname.lower();
- CEF = host + CEF + '_';
-
- TQString dir = m_strCacheDir;
- if (dir[dir.length()-1] != '/')
- dir += "/";
-
- int l = host.length();
- for(int i = 0; i < l; i++)
- {
- if (host[i].isLetter() && (host[i] != 'w'))
- {
- dir += host[i];
- break;
- }
- }
- if (dir[dir.length()-1] == '/')
- dir += "0";
-
- unsigned long hash = 0x00000000;
- TQCString u = m_request.url.url().latin1();
- for(int i = u.length(); i--;)
- {
- hash = (hash * 12211 + static_cast<const char>(u.at(i))) % 2147483563;
- }
-
- TQString hashString;
- hashString.sprintf("%08lx", hash);
-
- CEF = CEF + hashString;
-
- CEF = dir + "/" + CEF;
-
- m_request.cef = CEF;
-
- const char *mode = (readWrite ? "r+" : "r");
-
- FILE *fs = fopen( TQFile::encodeName(CEF), mode); // Open for reading and writing
- if (!fs)
- return 0;
-
- char buffer[401];
- bool ok = true;
-
- // CacheRevision
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
- ok = false;
-
- time_t date;
- time_t currentDate = time(0);
-
- // URL
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- int l = strlen(buffer);
- if (l>0)
- buffer[l-1] = 0; // Strip newline
- if (m_request.url.url() != buffer)
- {
- ok = false; // Hash collision
- }
- }
-
- // Creation Date
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- date = (time_t) strtoul(buffer, 0, 10);
- m_request.creationDate = date;
- if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
- {
- m_request.bMustRevalidate = true;
- m_request.expireDate = currentDate;
- }
- }
-
- // Expiration Date
- m_request.cacheExpireDateOffset = ftell(fs);
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- if (m_request.cache == CC_Verify)
- {
- date = (time_t) strtoul(buffer, 0, 10);
- // After the expire date we need to revalidate.
- if (!date || difftime(currentDate, date) >= 0)
- m_request.bMustRevalidate = true;
- m_request.expireDate = date;
- }
- else if (m_request.cache == CC_Refresh)
- {
- m_request.bMustRevalidate = true;
- m_request.expireDate = currentDate;
- }
- }
-
- // ETag
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- m_request.etag = TQString(buffer).stripWhiteSpace();
- }
-
- // Last-Modified
- if (ok && (!fgets(buffer, 400, fs)))
- ok = false;
- if (ok)
- {
- m_request.lastModified = TQString(buffer).stripWhiteSpace();
- }
-
- if (ok)
- return fs;
-
- fclose(fs);
- unlink( TQFile::encodeName(CEF));
- return 0;
-}
-
-void HTTPProtocol::updateExpireDate(time_t expireDate, bool updateCreationDate)
-{
- bool ok = true;
-
- FILE *fs = checkCacheEntry(true);
- if (fs)
- {
- TQString date;
- char buffer[401];
- time_t creationDate;
-
- fseek(fs, 0, SEEK_SET);
- if (ok && !fgets(buffer, 400, fs))
- ok = false;
- if (ok && !fgets(buffer, 400, fs))
- ok = false;
- long cacheCreationDateOffset = ftell(fs);
- if (ok && !fgets(buffer, 400, fs))
- ok = false;
- creationDate = strtoul(buffer, 0, 10);
- if (!creationDate)
- ok = false;
-
- if (updateCreationDate)
- {
- if (!ok || fseek(fs, cacheCreationDateOffset, SEEK_SET))
- return;
- TQString date;
- date.setNum( time(0) );
- date = date.leftJustify(16);
- fputs(date.latin1(), fs); // Creation date
- fputc('\n', fs);
- }
-
- if (expireDate>(30*365*24*60*60))
- {
- // expire date is a really a big number, it can't be
- // a relative date.
- date.setNum( expireDate );
- }
- else
- {
- // expireDate before 2000. those values must be
- // interpreted as relative expiration dates from
- // <META http-equiv="Expires"> tags.
- // so we have to scan the creation time and add
- // it to the expiryDate
- date.setNum( creationDate + expireDate );
- }
- date = date.leftJustify(16);
- if (!ok || fseek(fs, m_request.cacheExpireDateOffset, SEEK_SET))
- return;
- fputs(date.latin1(), fs); // Expire date
- fseek(fs, 0, SEEK_END);
- fclose(fs);
- }
-}
-
-void HTTPProtocol::createCacheEntry( const TQString &mimetype, time_t expireDate)
-{
- TQString dir = m_request.cef;
- int p = dir.findRev('/');
- if (p == -1) return; // Error.
- dir.truncate(p);
-
- // Create file
- (void) ::mkdir( TQFile::encodeName(dir), 0700 );
-
- TQString filename = m_request.cef + ".new"; // Create a new cache entryexpireDate
-
-// kdDebug( 7103 ) << "creating new cache entry: " << filename << endl;
-
- m_request.fcache = fopen( TQFile::encodeName(filename), "w");
- if (!m_request.fcache)
- {
- kdWarning(7113) << "(" << m_pid << ")createCacheEntry: opening " << filename << " failed." << endl;
- return; // Error.
- }
-
- fputs(CACHE_REVISION, m_request.fcache); // Revision
-
- fputs(m_request.url.url().latin1(), m_request.fcache); // Url
- fputc('\n', m_request.fcache);
-
- TQString date;
- m_request.creationDate = time(0);
- date.setNum( m_request.creationDate );
- date = date.leftJustify(16);
- fputs(date.latin1(), m_request.fcache); // Creation date
- fputc('\n', m_request.fcache);
-
- date.setNum( expireDate );
- date = date.leftJustify(16);
- fputs(date.latin1(), m_request.fcache); // Expire date
- fputc('\n', m_request.fcache);
-
- if (!m_request.etag.isEmpty())
- fputs(m_request.etag.latin1(), m_request.fcache); //ETag
- fputc('\n', m_request.fcache);
-
- if (!m_request.lastModified.isEmpty())
- fputs(m_request.lastModified.latin1(), m_request.fcache); // Last modified
- fputc('\n', m_request.fcache);
-
- fputs(mimetype.latin1(), m_request.fcache); // Mimetype
- fputc('\n', m_request.fcache);
-
- if (!m_request.strCharset.isEmpty())
- fputs(m_request.strCharset.latin1(), m_request.fcache); // Charset
- fputc('\n', m_request.fcache);
-
- return;
-}
-// The above code should be kept in sync
-// with the code in http_cache_cleaner.cpp
-// !END SYNC!
-
-void HTTPProtocol::writeCacheEntry( const char *buffer, int nbytes)
-{
- if (fwrite( buffer, nbytes, 1, m_request.fcache) != 1)
- {
- kdWarning(7113) << "(" << m_pid << ") writeCacheEntry: writing " << nbytes << " bytes failed." << endl;
- fclose(m_request.fcache);
- m_request.fcache = 0;
- TQString filename = m_request.cef + ".new";
- ::unlink( TQFile::encodeName(filename) );
- return;
- }
- long file_pos = ftell( m_request.fcache ) / 1024;
- if ( file_pos > m_maxCacheSize )
- {
- kdDebug(7113) << "writeCacheEntry: File size reaches " << file_pos
- << "Kb, exceeds cache limits. (" << m_maxCacheSize << "Kb)" << endl;
- fclose(m_request.fcache);
- m_request.fcache = 0;
- TQString filename = m_request.cef + ".new";
- ::unlink( TQFile::encodeName(filename) );
- return;
- }
-}
-
-void HTTPProtocol::closeCacheEntry()
-{
- TQString filename = m_request.cef + ".new";
- int result = fclose( m_request.fcache);
- m_request.fcache = 0;
- if (result == 0)
- {
- if (::rename( TQFile::encodeName(filename), TQFile::encodeName(m_request.cef)) == 0)
- return; // Success
-
- kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error renaming "
- << "cache entry. (" << filename << " -> " << m_request.cef
- << ")" << endl;
- }
-
- kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error closing cache "
- << "entry. (" << filename<< ")" << endl;
-}
-
-void HTTPProtocol::cleanCache()
-{
- const time_t maxAge = DEFAULT_CLEAN_CACHE_INTERVAL; // 30 Minutes.
- bool doClean = false;
- TQString cleanFile = m_strCacheDir;
- if (cleanFile[cleanFile.length()-1] != '/')
- cleanFile += "/";
- cleanFile += "cleaned";
-
- struct stat stat_buf;
-
- int result = ::stat(TQFile::encodeName(cleanFile), &stat_buf);
- if (result == -1)
- {
- int fd = creat( TQFile::encodeName(cleanFile), 0600);
- if (fd != -1)
- {
- doClean = true;
- ::close(fd);
- }
- }
- else
- {
- time_t age = (time_t) difftime( time(0), stat_buf.st_mtime );
- if (age > maxAge) //
- doClean = true;
- }
- if (doClean)
- {
- // Touch file.
- utime(TQFile::encodeName(cleanFile), 0);
- TDEApplication::startServiceByDesktopPath("http_cache_cleaner.desktop");
- }
-}
-
-
-
-//************************** AUTHENTICATION CODE ********************/
-
-
-void HTTPProtocol::configAuth( char *p, bool isForProxy )
-{
- HTTP_AUTH f = AUTH_None;
- const char *strAuth = p;
-
- if ( strncasecmp( p, "Basic", 5 ) == 0 )
- {
- f = AUTH_Basic;
- p += 5;
- strAuth = "Basic"; // Correct for upper-case variations.
- }
- else if ( strncasecmp (p, "Digest", 6) == 0 )
- {
- f = AUTH_Digest;
- memcpy((void *)p, "Digest", 6); // Correct for upper-case variations.
- p += 6;
- }
- else if (strncasecmp( p, "MBS_PWD_COOKIE", 14 ) == 0)
- {
- // Found on http://www.webscription.net/baen/default.asp
- f = AUTH_Basic;
- p += 14;
- strAuth = "Basic";
- }
-#ifdef HAVE_LIBGSSAPI
- else if ( strncasecmp( p, "Negotiate", 9 ) == 0 )
- {
- // if we get two 401 in a row let's assume for now that
- // Negotiate isn't working and ignore it
- if ( !isForProxy && !(m_responseCode == 401 && m_prevResponseCode == 401) )
- {
- f = AUTH_Negotiate;
- memcpy((void *)p, "Negotiate", 9); // Correct for upper-case variations.
- p += 9;
- };
- }
-#endif
- else if ( strncasecmp( p, "NTLM", 4 ) == 0 )
- {
- f = AUTH_NTLM;
- memcpy((void *)p, "NTLM", 4); // Correct for upper-case variations.
- p += 4;
- m_strRealm = "NTLM"; // set a dummy realm
- }
- else
- {
- kdWarning(7113) << "(" << m_pid << ") Unsupported or invalid authorization "
- << "type requested" << endl;
- if (isForProxy)
- kdWarning(7113) << "(" << m_pid << ") Proxy URL: " << m_proxyURL << endl;
- else
- kdWarning(7113) << "(" << m_pid << ") URL: " << m_request.url << endl;
- kdWarning(7113) << "(" << m_pid << ") Request Authorization: " << p << endl;
- }
-
- /*
- This check ensures the following:
- 1.) Rejection of any unknown/unsupported authentication schemes
- 2.) Usage of the strongest possible authentication schemes if
- and when multiple Proxy-Authenticate or WWW-Authenticate
- header field is sent.
- */
- if (isForProxy)
- {
- if ((f == AUTH_None) ||
- ((m_iProxyAuthCount > 0) && (f < ProxyAuthentication)))
- {
- // Since I purposefully made the Proxy-Authentication settings
- // persistent to reduce the number of round-trips to tdesud we
- // have to take special care when an unknown/unsupported auth-
- // scheme is received. This check accomplishes just that...
- if ( m_iProxyAuthCount == 0)
- ProxyAuthentication = f;
- kdDebug(7113) << "(" << m_pid << ") Rejected proxy auth method: " << f << endl;
- return;
- }
- m_iProxyAuthCount++;
- kdDebug(7113) << "(" << m_pid << ") Accepted proxy auth method: " << f << endl;
- }
- else
- {
- if ((f == AUTH_None) ||
- ((m_iWWWAuthCount > 0) && (f < Authentication)))
- {
- kdDebug(7113) << "(" << m_pid << ") Rejected auth method: " << f << endl;
- return;
- }
- m_iWWWAuthCount++;
- kdDebug(7113) << "(" << m_pid << ") Accepted auth method: " << f << endl;
- }
-
-
- while (*p)
- {
- int i = 0;
- while( (*p == ' ') || (*p == ',') || (*p == '\t') ) { p++; }
- if ( strncasecmp( p, "realm=", 6 ) == 0 )
- {
- //for sites like lib.homelinux.org
- TQTextCodec* oldCodec=TQTextCodec::codecForCStrings();
- if (TDEGlobal::locale()->language().contains("ru"))
- TQTextCodec::setCodecForCStrings(TQTextCodec::codecForName("CP1251"));
-
- p += 6;
- if (*p == '"') p++;
- while( p[i] && p[i] != '"' ) i++;
- if( isForProxy )
- m_strProxyRealm = TQString::fromAscii( p, i );
- else
- m_strRealm = TQString::fromAscii( p, i );
-
- TQTextCodec::setCodecForCStrings(oldCodec);
-
- if (!p[i]) break;
- }
- p+=(i+1);
- }
-
- if( isForProxy )
- {
- ProxyAuthentication = f;
- m_strProxyAuthorization = TQString::fromLatin1( strAuth );
- }
- else
- {
- Authentication = f;
- m_strAuthorization = TQString::fromLatin1( strAuth );
- }
-}
-
-
-bool HTTPProtocol::retryPrompt()
-{
- TQString prompt;
- switch ( m_responseCode )
- {
- case 401:
- prompt = i18n("Authentication Failed.");
- break;
- case 407:
- prompt = i18n("Proxy Authentication Failed.");
- break;
- default:
- break;
- }
- prompt += i18n(" Do you want to retry?");
- return (messageBox(QuestionYesNo, prompt, i18n("Authentication")) == 3);
-}
-
-void HTTPProtocol::promptInfo( AuthInfo& info )
-{
- if ( m_responseCode == 401 )
- {
- info.url = m_request.url;
- if ( !m_state.user.isEmpty() )
- info.username = m_state.user;
- info.readOnly = !m_request.url.user().isEmpty();
- info.prompt = i18n( "You need to supply a username and a "
- "password to access this site." );
- info.keepPassword = true; // Prompt the user for persistence as well.
- if ( !m_strRealm.isEmpty() )
- {
- info.realmValue = m_strRealm;
- info.verifyPath = false;
- info.digestInfo = m_strAuthorization;
- info.commentLabel = i18n( "Site:" );
- info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( m_strRealm ).arg( m_request.hostname );
- }
- }
- else if ( m_responseCode == 407 )
- {
- info.url = m_proxyURL;
- info.username = m_proxyURL.user();
- info.prompt = i18n( "You need to supply a username and a password for "
- "the proxy server listed below before you are allowed "
- "to access any sites." );
- info.keepPassword = true;
- if ( !m_strProxyRealm.isEmpty() )
- {
- info.realmValue = m_strProxyRealm;
- info.verifyPath = false;
- info.digestInfo = m_strProxyAuthorization;
- info.commentLabel = i18n( "Proxy:" );
- info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( m_strProxyRealm ).arg( m_proxyURL.host() );
- }
- }
-}
-
-bool HTTPProtocol::getAuthorization()
-{
- AuthInfo info;
- bool result = false;
-
- kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::getAuthorization: "
- << "Current Response: " << m_responseCode << ", "
- << "Previous Response: " << m_prevResponseCode << ", "
- << "Authentication: " << Authentication << ", "
- << "ProxyAuthentication: " << ProxyAuthentication << endl;
-
- if (m_request.bNoAuth)
- {
- if (m_request.bErrorPage)
- errorPage();
- else
- error( ERR_COULD_NOT_LOGIN, i18n("Authentication needed for %1 but authentication is disabled.").arg(m_request.hostname));
- return false;
- }
-
- bool repeatFailure = (m_prevResponseCode == m_responseCode);
-
- TQString errorMsg;
-
- if (repeatFailure)
- {
- bool prompt = true;
- if ( Authentication == AUTH_Digest || ProxyAuthentication == AUTH_Digest )
- {
- bool isStaleNonce = false;
- TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
- int pos = auth.find("stale", 0, false);
- if ( pos != -1 )
- {
- pos += 5;
- int len = auth.length();
- while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
- if ( pos < len && auth.find("true", pos, false) != -1 )
- {
- isStaleNonce = true;
- kdDebug(7113) << "(" << m_pid << ") Stale nonce value. "
- << "Will retry using same info..." << endl;
- }
- }
- if ( isStaleNonce )
- {
- prompt = false;
- result = true;
- if ( m_responseCode == 401 )
- {
- info.username = m_request.user;
- info.password = m_request.passwd;
- info.realmValue = m_strRealm;
- info.digestInfo = m_strAuthorization;
- }
- else if ( m_responseCode == 407 )
- {
- info.username = m_proxyURL.user();
- info.password = m_proxyURL.pass();
- info.realmValue = m_strProxyRealm;
- info.digestInfo = m_strProxyAuthorization;
- }
- }
- }
-
- if ( Authentication == AUTH_NTLM || ProxyAuthentication == AUTH_NTLM )
- {
- TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
- kdDebug(7113) << "auth: " << auth << endl;
- if ( auth.length() > 4 )
- {
- prompt = false;
- result = true;
- kdDebug(7113) << "(" << m_pid << ") NTLM auth second phase, "
- << "sending response..." << endl;
- if ( m_responseCode == 401 )
- {
- info.username = m_request.user;
- info.password = m_request.passwd;
- info.realmValue = m_strRealm;
- info.digestInfo = m_strAuthorization;
- }
- else if ( m_responseCode == 407 )
- {
- info.username = m_proxyURL.user();
- info.password = m_proxyURL.pass();
- info.realmValue = m_strProxyRealm;
- info.digestInfo = m_strProxyAuthorization;
- }
- }
- }
-
- if ( prompt )
- {
- switch ( m_responseCode )
- {
- case 401:
- errorMsg = i18n("Authentication Failed.");
- break;
- case 407:
- errorMsg = i18n("Proxy Authentication Failed.");
- break;
- default:
- break;
- }
- }
- }
- else
- {
- // At this point we know more details, so use it to find
- // out if we have a cached version and avoid a re-prompt!
- // We also do not use verify path unlike the pre-emptive
- // requests because we already know the realm value...
-
- if (m_bProxyAuthValid)
- {
- // Reset cached proxy auth
- m_bProxyAuthValid = false;
- KURL proxy ( config()->readEntry("UseProxy") );
- m_proxyURL.setUser(proxy.user());
- m_proxyURL.setPass(proxy.pass());
- }
-
- info.verifyPath = false;
- if ( m_responseCode == 407 )
- {
- info.url = m_proxyURL;
- info.username = m_proxyURL.user();
- info.password = m_proxyURL.pass();
- info.realmValue = m_strProxyRealm;
- info.digestInfo = m_strProxyAuthorization;
- }
- else
- {
- info.url = m_request.url;
- info.username = m_request.user;
- info.password = m_request.passwd;
- info.realmValue = m_strRealm;
- info.digestInfo = m_strAuthorization;
- }
-
- // If either username or password is not supplied
- // with the request, check the password cache.
- if ( info.username.isNull() ||
- info.password.isNull() )
- result = checkCachedAuthentication( info );
-
- if ( Authentication == AUTH_Digest )
- {
- TQString auth;
-
- if (m_responseCode == 401)
- auth = m_strAuthorization;
- else
- auth = m_strProxyAuthorization;
-
- int pos = auth.find("stale", 0, false);
- if ( pos != -1 )
- {
- pos += 5;
- int len = auth.length();
- while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
- if ( pos < len && auth.find("true", pos, false) != -1 )
- {
- info.digestInfo = (m_responseCode == 401) ? m_strAuthorization : m_strProxyAuthorization;
- kdDebug(7113) << "(" << m_pid << ") Just a stale nonce value! "
- << "Retrying using the new nonce sent..." << endl;
- }
- }
- }
- }
-
- if (!result )
- {
- // Do not prompt if the username & password
- // is already supplied and the login attempt
- // did not fail before.
- if ( !repeatFailure &&
- !info.username.isNull() &&
- !info.password.isNull() )
- result = true;
- else
- {
- if (Authentication == AUTH_Negotiate)
- {
- if (!repeatFailure)
- result = true;
- }
- else if ( m_request.disablePassDlg == false )
- {
- kdDebug( 7113 ) << "(" << m_pid << ") Prompting the user for authorization..." << endl;
- promptInfo( info );
- result = openPassDlg( info, errorMsg );
- }
- }
- }
-
- if ( result )
- {
- switch (m_responseCode)
- {
- case 401: // Request-Authentication
- m_request.user = info.username;
- m_request.passwd = info.password;
- m_strRealm = info.realmValue;
- m_strAuthorization = info.digestInfo;
- break;
- case 407: // Proxy-Authentication
- m_proxyURL.setUser( info.username );
- m_proxyURL.setPass( info.password );
- m_strProxyRealm = info.realmValue;
- m_strProxyAuthorization = info.digestInfo;
- break;
- default:
- break;
- }
- return true;
- }
-
- if (m_request.bErrorPage)
- errorPage();
- else
- error( ERR_USER_CANCELED, TQString::null );
- return false;
-}
-
-void HTTPProtocol::saveAuthorization()
-{
- AuthInfo info;
- if ( m_prevResponseCode == 407 )
- {
- if (!m_bUseProxy)
- return;
- m_bProxyAuthValid = true;
- info.url = m_proxyURL;
- info.username = m_proxyURL.user();
- info.password = m_proxyURL.pass();
- info.realmValue = m_strProxyRealm;
- info.digestInfo = m_strProxyAuthorization;
- cacheAuthentication( info );
- }
- else
- {
- info.url = m_request.url;
- info.username = m_request.user;
- info.password = m_request.passwd;
- info.realmValue = m_strRealm;
- info.digestInfo = m_strAuthorization;
- cacheAuthentication( info );
- }
-}
-
-#ifdef HAVE_LIBGSSAPI
-TQCString HTTPProtocol::gssError( int major_status, int minor_status )
-{
- OM_uint32 new_status;
- OM_uint32 msg_ctx = 0;
- gss_buffer_desc major_string;
- gss_buffer_desc minor_string;
- OM_uint32 ret;
- TQCString errorstr;
-
- errorstr = "";
-
- do {
- ret = gss_display_status(&new_status, major_status, GSS_C_GSS_CODE, GSS_C_NULL_OID, &msg_ctx, &major_string);
- errorstr += (const char *)major_string.value;
- errorstr += " ";
- ret = gss_display_status(&new_status, minor_status, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &minor_string);
- errorstr += (const char *)minor_string.value;
- errorstr += " ";
- } while (!GSS_ERROR(ret) && msg_ctx != 0);
-
- return errorstr;
-}
-
-TQString HTTPProtocol::createNegotiateAuth()
-{
- TQString auth;
- TQCString servicename;
- TQByteArray input;
- OM_uint32 major_status, minor_status;
- OM_uint32 req_flags = 0;
- gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
- gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
- gss_name_t server;
- gss_ctx_id_t ctx;
- gss_OID mech_oid;
- static gss_OID_desc krb5_oid_desc = {9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"};
- static gss_OID_desc spnego_oid_desc = {6, (void *) "\x2b\x06\x01\x05\x05\x02"};
- int found = 0;
- unsigned int i;
- gss_OID_set mech_set;
- gss_OID tmp_oid;
-
- ctx = GSS_C_NO_CONTEXT;
- mech_oid = &krb5_oid_desc;
-
- // see whether we can use the SPNEGO mechanism
- major_status = gss_indicate_mechs(&minor_status, &mech_set);
- if (GSS_ERROR(major_status)) {
- kdDebug(7113) << "(" << m_pid << ") gss_indicate_mechs failed: " << gssError(major_status, minor_status) << endl;
- } else {
- for (i=0; i<mech_set->count && !found; i++) {
- tmp_oid = &mech_set->elements[i];
- if (tmp_oid->length == spnego_oid_desc.length &&
- !memcmp(tmp_oid->elements, spnego_oid_desc.elements, tmp_oid->length)) {
- kdDebug(7113) << "(" << m_pid << ") createNegotiateAuth: found SPNEGO mech" << endl;
- found = 1;
- mech_oid = &spnego_oid_desc;
- break;
- }
- }
- gss_release_oid_set(&minor_status, &mech_set);
- }
-
- // the service name is "HTTP/f.q.d.n"
- servicename = "HTTP@";
- servicename += m_state.hostname.ascii();
-
- input_token.value = (void *)servicename.data();
- input_token.length = servicename.length() + 1;
-
- major_status = gss_import_name(&minor_status, &input_token,
- GSS_C_NT_HOSTBASED_SERVICE, &server);
-
- input_token.value = NULL;
- input_token.length = 0;
-
- if (GSS_ERROR(major_status)) {
- kdDebug(7113) << "(" << m_pid << ") gss_import_name failed: " << gssError(major_status, minor_status) << endl;
- // reset the auth string so that subsequent methods aren't confused
- m_strAuthorization = TQString::null;
- return TQString::null;
- }
-
- major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
- &ctx, server, mech_oid,
- req_flags, GSS_C_INDEFINITE,
- GSS_C_NO_CHANNEL_BINDINGS,
- GSS_C_NO_BUFFER, NULL, &output_token,
- NULL, NULL);
-
-
- if (GSS_ERROR(major_status) || (output_token.length == 0)) {
- kdDebug(7113) << "(" << m_pid << ") gss_init_sec_context failed: " << gssError(major_status, minor_status) << endl;
- gss_release_name(&minor_status, &server);
- if (ctx != GSS_C_NO_CONTEXT) {
- gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
- ctx = GSS_C_NO_CONTEXT;
- }
- // reset the auth string so that subsequent methods aren't confused
- m_strAuthorization = TQString::null;
- return TQString::null;
- }
-
- input.duplicate((const char *)output_token.value, output_token.length);
- auth = "Authorization: Negotiate ";
- auth += KCodecs::base64Encode( input );
- auth += "\r\n";
-
- // free everything
- gss_release_name(&minor_status, &server);
- if (ctx != GSS_C_NO_CONTEXT) {
- gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
- ctx = GSS_C_NO_CONTEXT;
- }
- gss_release_buffer(&minor_status, &output_token);
-
- return auth;
-}
-#else
-
-// Dummy
-TQCString HTTPProtocol::gssError( int, int )
-{
- return "";
-}
-
-// Dummy
-TQString HTTPProtocol::createNegotiateAuth()
-{
- return TQString::null;
-}
-#endif
-
-TQString HTTPProtocol::createNTLMAuth( bool isForProxy )
-{
- uint len;
- TQString auth, user, domain, passwd;
- TQCString strauth;
- TQByteArray buf;
-
- if ( isForProxy )
- {
- auth = "Proxy-Connection: Keep-Alive\r\n";
- auth += "Proxy-Authorization: NTLM ";
- user = m_proxyURL.user();
- passwd = m_proxyURL.pass();
- strauth = m_strProxyAuthorization.latin1();
- len = m_strProxyAuthorization.length();
- }
- else
- {
- auth = "Authorization: NTLM ";
- user = m_state.user;
- passwd = m_state.passwd;
- strauth = m_strAuthorization.latin1();
- len = m_strAuthorization.length();
- }
- if ( user.contains('\\') ) {
- domain = user.section( '\\', 0, 0);
- user = user.section( '\\', 1 );
- }
-
- kdDebug(7113) << "(" << m_pid << ") NTLM length: " << len << endl;
- if ( user.isEmpty() || passwd.isEmpty() || len < 4 )
- return TQString::null;
-
- if ( len > 4 )
- {
- // create a response
- TQByteArray challenge;
- KCodecs::base64Decode( strauth.right( len - 5 ), challenge );
- KNTLM::getAuth( buf, challenge, user, passwd, domain,
- KNetwork::KResolver::localHostName(), false, false );
- }
- else
- {
- KNTLM::getNegotiate( buf );
- }
-
- // remove the challenge to prevent reuse
- if ( isForProxy )
- m_strProxyAuthorization = "NTLM";
- else
- m_strAuthorization = "NTLM";
-
- auth += KCodecs::base64Encode( buf );
- auth += "\r\n";
-
- return auth;
-}
-
-TQString HTTPProtocol::createBasicAuth( bool isForProxy )
-{
- TQString auth;
- TQCString user, passwd;
- if ( isForProxy )
- {
- auth = "Proxy-Authorization: Basic ";
- user = m_proxyURL.user().latin1();
- passwd = m_proxyURL.pass().latin1();
- }
- else
- {
- auth = "Authorization: Basic ";
- user = m_state.user.latin1();
- passwd = m_state.passwd.latin1();
- }
-
- if ( user.isEmpty() )
- user = "";
- if ( passwd.isEmpty() )
- passwd = "";
-
- user += ':';
- user += passwd;
- auth += KCodecs::base64Encode( user );
- auth += "\r\n";
-
- return auth;
-}
-
-void HTTPProtocol::calculateResponse( DigestAuthInfo& info, TQCString& Response )
-{
- KMD5 md;
- TQCString HA1;
- TQCString HA2;
-
- // Calculate H(A1)
- TQCString authStr = info.username;
- authStr += ':';
- authStr += info.realm;
- authStr += ':';
- authStr += info.password;
- md.update( authStr );
-
- if ( info.algorithm.lower() == "md5-sess" )
- {
- authStr = md.hexDigest();
- authStr += ':';
- authStr += info.nonce;
- authStr += ':';
- authStr += info.cnonce;
- md.reset();
- md.update( authStr );
- }
- HA1 = md.hexDigest();
-
- kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A1 => " << HA1 << endl;
-
- // Calcualte H(A2)
- authStr = info.method;
- authStr += ':';
- authStr += m_request.url.encodedPathAndQuery(0, true).latin1();
- if ( info.qop == "auth-int" )
- {
- authStr += ':';
- authStr += info.entityBody;
- }
- md.reset();
- md.update( authStr );
- HA2 = md.hexDigest();
-
- kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A2 => "
- << HA2 << endl;
-
- // Calcualte the response.
- authStr = HA1;
- authStr += ':';
- authStr += info.nonce;
- authStr += ':';
- if ( !info.qop.isEmpty() )
- {
- authStr += info.nc;
- authStr += ':';
- authStr += info.cnonce;
- authStr += ':';
- authStr += info.qop;
- authStr += ':';
- }
- authStr += HA2;
- md.reset();
- md.update( authStr );
- Response = md.hexDigest();
-
- kdDebug(7113) << "(" << m_pid << ") calculateResponse(): Response => "
- << Response << endl;
-}
-
-TQString HTTPProtocol::createDigestAuth ( bool isForProxy )
-{
- const char *p;
-
- TQString auth;
- TQCString opaque;
- TQCString Response;
-
- DigestAuthInfo info;
-
- opaque = "";
- if ( isForProxy )
- {
- auth = "Proxy-Authorization: Digest ";
- info.username = m_proxyURL.user().latin1();
- info.password = m_proxyURL.pass().latin1();
- p = m_strProxyAuthorization.latin1();
- }
- else
- {
- auth = "Authorization: Digest ";
- info.username = m_state.user.latin1();
- info.password = m_state.passwd.latin1();
- p = m_strAuthorization.latin1();
- }
- if (!p || !*p)
- return TQString::null;
-
- p += 6; // Skip "Digest"
-
- if ( info.username.isEmpty() || info.password.isEmpty() || !p )
- return TQString::null;
-
- // info.entityBody = p; // FIXME: send digest of data for POST action ??
- info.realm = "";
- info.algorithm = "MD5";
- info.nonce = "";
- info.qop = "";
-
- // cnonce is recommended to contain about 64 bits of entropy
- info.cnonce = TDEApplication::randomString(16).latin1();
-
- // HACK: Should be fixed according to RFC 2617 section 3.2.2
- info.nc = "00000001";
-
- // Set the method used...
- switch ( m_request.method )
- {
- case HTTP_GET:
- info.method = "GET";
- break;
- case HTTP_PUT:
- info.method = "PUT";
- break;
- case HTTP_POST:
- info.method = "POST";
- break;
- case HTTP_HEAD:
- info.method = "HEAD";
- break;
- case HTTP_DELETE:
- info.method = "DELETE";
- break;
- case DAV_PROPFIND:
- info.method = "PROPFIND";
- break;
- case DAV_PROPPATCH:
- info.method = "PROPPATCH";
- break;
- case DAV_MKCOL:
- info.method = "MKCOL";
- break;
- case DAV_COPY:
- info.method = "COPY";
- break;
- case DAV_MOVE:
- info.method = "MOVE";
- break;
- case DAV_LOCK:
- info.method = "LOCK";
- break;
- case DAV_UNLOCK:
- info.method = "UNLOCK";
- break;
- case DAV_SEARCH:
- info.method = "SEARCH";
- break;
- case DAV_SUBSCRIBE:
- info.method = "SUBSCRIBE";
- break;
- case DAV_UNSUBSCRIBE:
- info.method = "UNSUBSCRIBE";
- break;
- case DAV_POLL:
- info.method = "POLL";
- break;
- default:
- error( ERR_UNSUPPORTED_ACTION, i18n("Unsupported method: authentication will fail. Please submit a bug report."));
- break;
- }
-
- // Parse the Digest response....
- while (*p)
- {
- int i = 0;
- while ( (*p == ' ') || (*p == ',') || (*p == '\t')) { p++; }
- if (strncasecmp(p, "realm=", 6 )==0)
- {
- p+=6;
- while ( *p == '"' ) p++; // Go past any number of " mark(s) first
- while ( p[i] != '"' ) i++; // Read everything until the last " mark
- info.realm = TQCString( p, i+1 );
- }
- else if (strncasecmp(p, "algorith=", 9)==0)
- {
- p+=9;
- while ( *p == '"' ) p++; // Go past any number of " mark(s) first
- while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
- info.algorithm = TQCString(p, i+1);
- }
- else if (strncasecmp(p, "algorithm=", 10)==0)
- {
- p+=10;
- while ( *p == '"' ) p++; // Go past any " mark(s) first
- while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
- info.algorithm = TQCString(p,i+1);
- }
- else if (strncasecmp(p, "domain=", 7)==0)
- {
- p+=7;
- while ( *p == '"' ) p++; // Go past any " mark(s) first
- while ( p[i] != '"' ) i++; // Read everything until the last " mark
- int pos;
- int idx = 0;
- TQCString uri = TQCString(p,i+1);
- do
- {
- pos = uri.find( ' ', idx );
- if ( pos != -1 )
- {
- KURL u (m_request.url, uri.mid(idx, pos-idx));
- if (u.isValid ())
- info.digestURI.append( u.url().latin1() );
- }
- else
- {
- KURL u (m_request.url, uri.mid(idx, uri.length()-idx));
- if (u.isValid ())
- info.digestURI.append( u.url().latin1() );
- }
- idx = pos+1;
- } while ( pos != -1 );
- }
- else if (strncasecmp(p, "nonce=", 6)==0)
- {
- p+=6;
- while ( *p == '"' ) p++; // Go past any " mark(s) first
- while ( p[i] != '"' ) i++; // Read everything until the last " mark
- info.nonce = TQCString(p,i+1);
- }
- else if (strncasecmp(p, "opaque=", 7)==0)
- {
- p+=7;
- while ( *p == '"' ) p++; // Go past any " mark(s) first
- while ( p[i] != '"' ) i++; // Read everything until the last " mark
- opaque = TQCString(p,i+1);
- }
- else if (strncasecmp(p, "qop=", 4)==0)
- {
- p+=4;
- while ( *p == '"' ) p++; // Go past any " mark(s) first
- while ( p[i] != '"' ) i++; // Read everything until the last " mark
- info.qop = TQCString(p,i+1);
- }
- p+=(i+1);
- }
-
- if (info.realm.isEmpty() || info.nonce.isEmpty())
- return TQString::null;
-
- // If the "domain" attribute was not specified and the current response code
- // is authentication needed, add the current request url to the list over which
- // this credential can be automatically applied.
- if (info.digestURI.isEmpty() && (m_responseCode == 401 || m_responseCode == 407))
- info.digestURI.append (m_request.url.url().latin1());
- else
- {
- // Verify whether or not we should send a cached credential to the
- // server based on the stored "domain" attribute...
- bool send = true;
-
- // Determine the path of the request url...
- TQString requestPath = m_request.url.directory(false, false);
- if (requestPath.isEmpty())
- requestPath = "/";
-
- int count = info.digestURI.count();
-
- for (int i = 0; i < count; i++ )
- {
- KURL u ( info.digestURI.at(i) );
-
- send &= (m_request.url.protocol().lower() == u.protocol().lower());
- send &= (m_request.hostname.lower() == u.host().lower());
-
- if (m_request.port > 0 && u.port() > 0)
- send &= (m_request.port == u.port());
-
- TQString digestPath = u.directory (false, false);
- if (digestPath.isEmpty())
- digestPath = "/";
-
- send &= (requestPath.startsWith(digestPath));
-
- if (send)
- break;
- }
-
- kdDebug(7113) << "(" << m_pid << ") createDigestAuth(): passed digest "
- "authentication credential test: " << send << endl;
-
- if (!send)
- return TQString::null;
- }
-
- kdDebug(7113) << "(" << m_pid << ") RESULT OF PARSING:" << endl;
- kdDebug(7113) << "(" << m_pid << ") algorithm: " << info.algorithm << endl;
- kdDebug(7113) << "(" << m_pid << ") realm: " << info.realm << endl;
- kdDebug(7113) << "(" << m_pid << ") nonce: " << info.nonce << endl;
- kdDebug(7113) << "(" << m_pid << ") opaque: " << opaque << endl;
- kdDebug(7113) << "(" << m_pid << ") qop: " << info.qop << endl;
-
- // Calculate the response...
- calculateResponse( info, Response );
-
- auth += "username=\"";
- auth += info.username;
-
- auth += "\", realm=\"";
- auth += info.realm;
- auth += "\"";
-
- auth += ", nonce=\"";
- auth += info.nonce;
-
- auth += "\", uri=\"";
- auth += m_request.url.encodedPathAndQuery(0, true);
-
- auth += "\", algorithm=\"";
- auth += info.algorithm;
- auth +="\"";
-
- if ( !info.qop.isEmpty() )
- {
- auth += ", qop=\"";
- auth += info.qop;
- auth += "\", cnonce=\"";
- auth += info.cnonce;
- auth += "\", nc=";
- auth += info.nc;
- }
-
- auth += ", response=\"";
- auth += Response;
- if ( !opaque.isEmpty() )
- {
- auth += "\", opaque=\"";
- auth += opaque;
- }
- auth += "\"\r\n";
-
- return auth;
-}
-
-TQString HTTPProtocol::proxyAuthenticationHeader()
-{
- TQString header;
-
- // We keep proxy authentication locally until they are changed.
- // Thus, no need to check with the password manager for every
- // connection.
- if ( m_strProxyRealm.isEmpty() )
- {
- AuthInfo info;
- info.url = m_proxyURL;
- info.username = m_proxyURL.user();
- info.password = m_proxyURL.pass();
- info.verifyPath = true;
-
- // If the proxy URL already contains username
- // and password simply attempt to retrieve it
- // without prompting the user...
- if ( !info.username.isNull() && !info.password.isNull() )
- {
- if( m_strProxyAuthorization.isEmpty() )
- ProxyAuthentication = AUTH_None;
- else if( m_strProxyAuthorization.startsWith("Basic") )
- ProxyAuthentication = AUTH_Basic;
- else if( m_strProxyAuthorization.startsWith("NTLM") )
- ProxyAuthentication = AUTH_NTLM;
- else
- ProxyAuthentication = AUTH_Digest;
- }
- else
- {
- if ( checkCachedAuthentication(info) && !info.digestInfo.isEmpty() )
- {
- m_proxyURL.setUser( info.username );
- m_proxyURL.setPass( info.password );
- m_strProxyRealm = info.realmValue;
- m_strProxyAuthorization = info.digestInfo;
- if( m_strProxyAuthorization.startsWith("Basic") )
- ProxyAuthentication = AUTH_Basic;
- else if( m_strProxyAuthorization.startsWith("NTLM") )
- ProxyAuthentication = AUTH_NTLM;
- else
- ProxyAuthentication = AUTH_Digest;
- }
- else
- {
- ProxyAuthentication = AUTH_None;
- }
- }
- }
-
- /********* Only for debugging purpose... *********/
- if ( ProxyAuthentication != AUTH_None )
- {
- kdDebug(7113) << "(" << m_pid << ") Using Proxy Authentication: " << endl;
- kdDebug(7113) << "(" << m_pid << ") HOST= " << m_proxyURL.host() << endl;
- kdDebug(7113) << "(" << m_pid << ") PORT= " << m_proxyURL.port() << endl;
- kdDebug(7113) << "(" << m_pid << ") USER= " << m_proxyURL.user() << endl;
- kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
- kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strProxyRealm << endl;
- kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strProxyAuthorization << endl;
- }
-
- switch ( ProxyAuthentication )
- {
- case AUTH_Basic:
- header += createBasicAuth( true );
- break;
- case AUTH_Digest:
- header += createDigestAuth( true );
- break;
- case AUTH_NTLM:
- if ( m_bFirstRequest ) header += createNTLMAuth( true );
- break;
- case AUTH_None:
- default:
- break;
- }
-
- return header;
-}
-
-#include "http.moc"
diff --git a/kioslave/http/http.h b/kioslave/http/http.h
deleted file mode 100644
index ccbb60ce6..000000000
--- a/kioslave/http/http.h
+++ /dev/null
@@ -1,577 +0,0 @@
-/*
- Copyright (C) 2000,2001 Dawit Alemayehu <adawit@kde.org>
- Copyright (C) 2000,2001 Waldo Bastian <bastian@kde.org>
- Copyright (C) 2000,2001 George Staikos <staikos@kde.org>
- Copyright (C) 2001,2002 Hamish Rodda <rodda@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef HTTP_H_
-#define HTTP_H_
-
-
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <string.h>
-#include <stdio.h>
-#include <time.h>
-
-#include <tqptrlist.h>
-#include <tqstrlist.h>
-#include <tqstringlist.h>
-
-#include <kurl.h>
-#include "kio/tcpslavebase.h"
-#include "kio/http.h"
-
-class DCOPClient;
-class TQDomElement;
-class TQDomNodeList;
-
-namespace TDEIO {
- class AuthInfo;
-}
-
-class HTTPProtocol : public TQObject, public TDEIO::TCPSlaveBase
-{
- Q_OBJECT
-public:
- HTTPProtocol( const TQCString &protocol, const TQCString &pool,
- const TQCString &app );
- virtual ~HTTPProtocol();
-
- /** HTTP version **/
- enum HTTP_REV {HTTP_None, HTTP_Unknown, HTTP_10, HTTP_11, SHOUTCAST};
-
- /** Authorization method used **/
- enum HTTP_AUTH {AUTH_None, AUTH_Basic, AUTH_NTLM, AUTH_Digest, AUTH_Negotiate};
-
- /** HTTP / DAV method **/
- // Removed to interfaces/kio/http.h
- //enum HTTP_METHOD {HTTP_GET, HTTP_PUT, HTTP_POST, HTTP_HEAD, HTTP_DELETE,
- // HTTP_OPTIONS, DAV_PROPFIND, DAV_PROPPATCH, DAV_MKCOL,
- // DAV_COPY, DAV_MOVE, DAV_LOCK, DAV_UNLOCK, DAV_SEARCH };
-
- /** State of the current Connection **/
- struct HTTPState
- {
- HTTPState ()
- {
- port = 0;
- doProxy = false;
- }
-
- TQString hostname;
- TQString encoded_hostname;
- short unsigned int port;
- TQString user;
- TQString passwd;
- bool doProxy;
- };
-
- /** DAV-specific request elements for the current connection **/
- struct DAVRequest
- {
- DAVRequest ()
- {
- overwrite = false;
- depth = 0;
- }
-
- TQString desturl;
- bool overwrite;
- int depth;
- };
-
- /** The request for the current connection **/
- struct HTTPRequest
- {
- HTTPRequest ()
- {
- port = 0;
- method = TDEIO::HTTP_UNKNOWN;
- offset = 0;
- doProxy = false;
- allowCompressedPage = false;
- disablePassDlg = false;
- bNoAuth = false;
- bUseCache = false;
- bCachedRead = false;
- bCachedWrite = false;
- fcache = 0;
- bMustRevalidate = false;
- cacheExpireDateOffset = 0;
- bErrorPage = false;
- bUseCookiejar = false;
- expireDate = 0;
- creationDate = 0;
- }
-
- TQString hostname;
- TQString encoded_hostname;
- short unsigned int port;
- TQString user;
- TQString passwd;
- TQString path;
- TQString query;
- TDEIO::HTTP_METHOD method;
- TDEIO::CacheControl cache;
- TDEIO::filesize_t offset;
- bool doProxy;
- KURL url;
- TQString window; // Window Id this request is related to.
- TQString referrer;
- TQString charsets;
- TQString languages;
- bool allowCompressedPage;
- bool disablePassDlg;
- TQString userAgent;
- TQString id;
- DAVRequest davData;
-
- bool bNoAuth; // Do not authenticate
-
- // Cache related
- TQString cef; // Cache Entry File belonging to this URL.
- bool bUseCache; // Whether the cache is active
- bool bCachedRead; // Whether the file is to be read from m_fcache.
- bool bCachedWrite; // Whether the file is to be written to m_fcache.
- FILE* fcache; // File stream of a cache entry
- TQString etag; // ETag header.
- TQString lastModified; // Last modified.
- bool bMustRevalidate; // Cache entry is expired.
- long cacheExpireDateOffset; // Position in the cache entry where the
- // 16 byte expire date is stored.
- time_t expireDate; // Date when the cache entry will expire
- time_t creationDate; // Date when the cache entry was created
- TQString strCharset; // Charset
-
- // Indicates whether an error-page or error-msg should is preferred.
- bool bErrorPage;
-
- // Cookie flags
- bool bUseCookiejar;
- enum { CookiesAuto, CookiesManual, CookiesNone } cookieMode;
- };
-
- struct DigestAuthInfo
- {
- TQCString nc;
- TQCString qop;
- TQCString realm;
- TQCString nonce;
- TQCString method;
- TQCString cnonce;
- TQCString username;
- TQCString password;
- TQStrList digestURI;
- TQCString algorithm;
- TQCString entityBody;
- };
-
-//---------------------- Re-implemented methods ----------------
- virtual void setHost(const TQString& host, int port, const TQString& user,
- const TQString& pass);
-
- virtual void slave_status();
-
- virtual void get( const KURL& url );
- virtual void put( const KURL& url, int permissions, bool overwrite,
- bool resume );
-
-//----------------- Re-implemented methods for WebDAV -----------
- virtual void listDir( const KURL& url );
- virtual void mkdir( const KURL& url, int permissions );
-
- virtual void rename( const KURL& src, const KURL& dest, bool overwrite );
- virtual void copy( const KURL& src, const KURL& dest, int permissions, bool overwrite );
- virtual void del( const KURL& url, bool isfile );
-
- // ask the host whether it supports WebDAV & cache this info
- bool davHostOk();
-
- // send generic DAV request
- void davGeneric( const KURL& url, TDEIO::HTTP_METHOD method );
-
- // Send requests to lock and unlock resources
- void davLock( const KURL& url, const TQString& scope,
- const TQString& type, const TQString& owner );
- void davUnlock( const KURL& url );
-
- // Calls httpClose() and finished()
- void davFinished();
-
- // Handle error conditions
- TQString davError( int code = -1, TQString url = TQString::null );
-//---------------------------- End WebDAV -----------------------
-
- /**
- * Special commands supported by this slave :
- * 1 - HTTP POST
- * 2 - Cache has been updated
- * 3 - SSL Certificate Cache has been updated
- * 4 - HTTP multi get
- * 5 - DAV LOCK (see
- * 6 - DAV UNLOCK README.webdav)
- */
- virtual void special( const TQByteArray &data );
-
- virtual void mimetype( const KURL& url);
-
- virtual void stat( const KURL& url );
-
- virtual void reparseConfiguration();
-
- virtual void closeConnection(); // Forced close of connection
-
- void post( const KURL& url );
- void multiGet(const TQByteArray &data);
- bool checkRequestURL( const KURL& );
- void cacheUpdate( const KURL &url, bool nocache, time_t expireDate);
-
- void httpError(); // Generate error message based on response code
-
- bool isOffline(const KURL &url); // Check network status
-
-protected slots:
- void slotData(const TQByteArray &);
- void error( int _errid, const TQString &_text );
-
-protected:
- int readChunked(); // Read a chunk
- int readLimited(); // Read maximum m_iSize bytes.
- int readUnlimited(); // Read as much as possible.
-
- /**
- * A "smart" wrapper around write that will use SSL_write or
- * write(2) depending on whether you've got an SSL connection or not.
- * The only shortcomming is that it uses the "global" file handles and
- * soforth. So you can't really use this on individual files/sockets.
- */
- ssize_t write(const void *buf, size_t nbytes);
-
- /**
- * Another "smart" wrapper, this time around read that will
- * use SSL_read or read(2) depending on whether you've got an
- * SSL connection or not.
- */
- ssize_t read (void *b, size_t nbytes);
-
- char *gets (char *str, int size);
-
- void setRewindMarker();
- void rewind();
-
- /**
- * Add an encoding on to the appropriate stack this
- * is nececesary because transfer encodings and
- * content encodings must be handled separately.
- */
- void addEncoding(TQString, TQStringList &);
-
- void configAuth( char *, bool );
-
- bool httpOpen(); // Open transfer
- void httpClose(bool keepAlive); // Close transfer
-
- bool httpOpenConnection(); // Open connection
- void httpCloseConnection(); // Close connection
- void httpCheckConnection(); // Check whether to keep connection.
-
- void forwardHttpResponseHeader();
-
- bool readHeader();
-
- bool sendBody();
-
- // where dataInternal == true, the content is to be made available
- // to an internal function.
- bool readBody( bool dataInternal = false );
-
- /**
- * Performs a WebDAV stat or list
- */
- void davSetRequest( const TQCString& requestXML );
- void davStatList( const KURL& url, bool stat = true );
- void davParsePropstats( const TQDomNodeList& propstats, TDEIO::UDSEntry& entry );
- void davParseActiveLocks( const TQDomNodeList& activeLocks,
- uint& lockCount );
-
- /**
- * Parses a date & time string
- */
- long parseDateTime( const TQString& input, const TQString& type );
-
- /**
- * Returns the error code from a "HTTP/1.1 code Code Name" string
- */
- int codeFromResponse( const TQString& response );
-
- /**
- * Extracts locks from metadata
- * Returns the appropriate If: header
- */
- TQString davProcessLocks();
-
- /**
- * Send a cookie to the cookiejar
- */
- void addCookies( const TQString &url, const TQCString &cookieHeader);
-
- /**
- * Look for cookies in the cookiejar
- */
- TQString findCookies( const TQString &url);
-
- /**
- * Do a cache lookup for the current url. (m_state.url)
- *
- * @param readWrite If true, file is opened read/write.
- * If false, file is opened read-only.
- *
- * @return a file stream open for reading and at the start of
- * the header section when the Cache entry exists and is valid.
- * 0 if no cache entry could be found, or if the entry is not
- * valid (any more).
- */
- FILE *checkCacheEntry(bool readWrite = false);
-
- /**
- * Create a cache entry for the current url. (m_state.url)
- *
- * Set the contents type of the cache entry to 'mimetype'.
- */
- void createCacheEntry(const TQString &mimetype, time_t expireDate);
-
- /**
- * Write data to cache.
- *
- * Write 'nbytes' from 'buffer' to the Cache Entry File
- */
- void writeCacheEntry( const char *buffer, int nbytes);
-
- /**
- * Close cache entry
- */
- void closeCacheEntry();
-
- /**
- * Update expire time of current cache entry.
- */
- void updateExpireDate(time_t expireDate, bool updateCreationDate=false);
-
- /**
- * Quick check whether the cache needs cleaning.
- */
- void cleanCache();
-
- /**
- * Performs a GET HTTP request.
- */
- // where dataInternal == true, the content is to be made available
- // to an internal function.
- void retrieveContent( bool dataInternal = false );
-
- /**
- * Performs a HEAD HTTP request.
- */
- bool retrieveHeader(bool close_connection = true);
-
- /**
- * Resets any per session settings.
- */
- void resetSessionSettings();
-
- /**
- * Resets settings related to parsing a response.
- */
- void resetResponseSettings();
-
- /**
- * Resets any per connection settings. These are different from
- * per-session settings in that they must be invalidates every time
- * a request is made, e.g. a retry to re-send the header to the
- * server, as compared to only when a new request arrives.
- */
- void resetConnectionSettings();
-
- /**
- * Returns any pre-cached proxy authentication info
- * info in HTTP header format.
- */
- TQString proxyAuthenticationHeader();
-
- /**
- * Retrieves authorization info from cache or user.
- */
- bool getAuthorization();
-
- /**
- * Saves valid authorization info in the cache daemon.
- */
- void saveAuthorization();
-
- /**
- * Creates the entity-header for Basic authentication.
- */
- TQString createBasicAuth( bool isForProxy = false );
-
- /**
- * Creates the entity-header for Digest authentication.
- */
- TQString createDigestAuth( bool isForProxy = false );
-
- /**
- * Creates the entity-header for NTLM authentication.
- */
- TQString createNTLMAuth( bool isForProxy = false );
-
- /**
- * Creates the entity-header for Negotiate authentication.
- */
- TQString createNegotiateAuth();
-
- /**
- * create GSS error string
- */
- TQCString gssError( int major_status, int minor_status );
-
- /**
- * Calcualtes the message digest response based on RFC 2617.
- */
- void calculateResponse( DigestAuthInfo &info, TQCString &Response );
-
- /**
- * Prompts the user for authorization retry.
- */
- bool retryPrompt();
-
- /**
- * Creates authorization prompt info.
- */
- void promptInfo( TDEIO::AuthInfo& info );
-
-protected:
- HTTPState m_state;
- HTTPRequest m_request;
- TQPtrList<HTTPRequest> m_requestQueue;
-
- bool m_bBusy; // Busy handling request queue.
- bool m_bEOF;
- bool m_bEOD;
-
-//--- Settings related to a single response only
- TQStringList m_responseHeader; // All headers
- KURL m_redirectLocation;
- bool m_bRedirect; // Indicates current request is a redirection
-
- // Processing related
- bool m_bChunked; // Chunked tranfer encoding
- TDEIO::filesize_t m_iSize; // Expected size of message
- TDEIO::filesize_t m_iBytesLeft; // # of bytes left to receive in this message.
- TDEIO::filesize_t m_iContentLeft; // # of content bytes left
- TQByteArray m_bufReceive; // Receive buffer
- bool m_dataInternal; // Data is for internal consumption
- char m_lineBuf[1024];
- char m_rewindBuf[8192];
- size_t m_rewindCount;
- char *m_linePtr;
- size_t m_lineCount;
- char *m_lineBufUnget;
- char *m_linePtrUnget;
- size_t m_lineCountUnget;
-
- // Mimetype determination
- bool m_cpMimeBuffer;
- TQByteArray m_mimeTypeBuffer;
-
- // Language/Encoding related
- TQStringList m_qTransferEncodings;
- TQStringList m_qContentEncodings;
- TQString m_sContentMD5;
- TQString m_strMimeType;
-
-
-//--- WebDAV
- // Data structure to hold data which will be passed to an internal func.
- TQByteArray m_bufWebDavData;
- TQStringList m_davCapabilities;
-
- bool m_davHostOk;
- bool m_davHostUnsupported;
-//----------
-
- // Holds the POST data so it won't get lost on if we
- // happend to get a 401/407 response when submitting,
- // a form.
- TQByteArray m_bufPOST;
-
- // Cache related
- int m_maxCacheAge; // Maximum age of a cache entry.
- long m_maxCacheSize; // Maximum cache size in Kb.
- TQString m_strCacheDir; // Location of the cache.
-
-
-
-//--- Proxy related members
- bool m_bUseProxy;
- bool m_bNeedTunnel; // Whether we need to make a SSL tunnel
- bool m_bIsTunneled; // Whether we have an active SSL tunnel
- bool m_bProxyAuthValid;
- int m_iProxyPort;
- KURL m_proxyURL;
- TQString m_strProxyRealm;
-
- // Operation mode
- TQCString m_protocol;
-
- // Authentication
- TQString m_strRealm;
- TQString m_strAuthorization;
- TQString m_strProxyAuthorization;
- HTTP_AUTH Authentication;
- HTTP_AUTH ProxyAuthentication;
- bool m_bUnauthorized;
- short unsigned int m_iProxyAuthCount;
- short unsigned int m_iWWWAuthCount;
-
- // First request on a connection
- bool m_bFirstRequest;
-
- // Persistent connections
- bool m_bKeepAlive;
- int m_keepAliveTimeout; // Timeout in seconds.
-
- // Persistent proxy connections
- bool m_bPersistentProxyConnection;
-
-
- // Indicates whether there was some connection error.
- bool m_bError;
-
- // Previous and current response codes
- unsigned int m_responseCode;
- unsigned int m_prevResponseCode;
-
- // Values that determine the remote connection timeouts.
- int m_proxyConnTimeout;
- int m_remoteConnTimeout;
- int m_remoteRespTimeout;
-
- int m_pid;
-};
-#endif
diff --git a/kioslave/http/http.protocol b/kioslave/http/http.protocol
deleted file mode 100644
index ea7b57869..000000000
--- a/kioslave/http/http.protocol
+++ /dev/null
@@ -1,12 +0,0 @@
-[Protocol]
-exec=kio_http
-protocol=http
-input=none
-output=filesystem
-reading=true
-defaultMimetype=application/octet-stream
-determineMimetypeFromExtension=false
-Icon=www
-maxInstances=3
-DocPath=kioslave/http.html
-Class=:internet
diff --git a/kioslave/http/https.protocol b/kioslave/http/https.protocol
deleted file mode 100644
index 8a9c2f0da..000000000
--- a/kioslave/http/https.protocol
+++ /dev/null
@@ -1,12 +0,0 @@
-[Protocol]
-exec=kio_http
-protocol=https
-input=none
-output=filesystem
-reading=true
-defaultMimetype=application/octet-stream
-determineMimetypeFromExtension=false
-Icon=www
-config=http
-DocPath=kioslave/https.html
-Class=:internet
diff --git a/kioslave/http/kcookiejar/Makefile.am b/kioslave/http/kcookiejar/Makefile.am
deleted file mode 100644
index 431502c12..000000000
--- a/kioslave/http/kcookiejar/Makefile.am
+++ /dev/null
@@ -1,31 +0,0 @@
-# Makefile.am of tdebase/kioslave/http
-
-SUBDIRS=tests
-INCLUDES= $(all_includes)
-
-####### Files
-
-bin_PROGRAMS =
-lib_LTLIBRARIES =
-tdeinit_LTLIBRARIES = kcookiejar.la
-kde_module_LTLIBRARIES = kded_kcookiejar.la
-
-kcookiejar_la_SOURCES = main.cpp
-METASOURCES = AUTO
-kcookiejar_la_LDFLAGS = $(all_libraries) -module -avoid-version
-kcookiejar_la_LIBADD = $(LIB_TDECORE) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la
-
-kded_kcookiejar_la_SOURCES = kcookiejar.cpp kcookieserver.cpp \
- kcookieserver.skel kcookiewin.cpp
-kded_kcookiejar_la_LDFLAGS = $(all_libraries) -module -avoid-version
-kded_kcookiejar_la_LIBADD = $(LIB_KDED) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE) $(LIB_X11) $(LIB_TDEUI) $(top_builddir)/kded/libtdeinit_kded.la
-
-kded_DATA = kcookiejar.desktop
-kdeddir = $(kde_servicesdir)/kded
-
-update_DATA = kcookiescfg.upd
-updatedir = $(kde_datadir)/kconf_update
-
-cookie_DATA = domain_info
-cookiedir = $(kde_datadir)/tdehtml
-
diff --git a/kioslave/http/kcookiejar/kcookiejar.cpp b/kioslave/http/kcookiejar/kcookiejar.cpp
deleted file mode 100644
index 12d92a8df..000000000
--- a/kioslave/http/kcookiejar/kcookiejar.cpp
+++ /dev/null
@@ -1,1559 +0,0 @@
-/* This file is part of the KDE File Manager
-
- Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
- Copyright (C) 2000,2001 Dawit Alemayehu (adawit@kde.org)
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, and/or sell copies of the
- Software, and to permit persons to whom the Software is furnished to do so,
- subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-*/
-//----------------------------------------------------------------------------
-//
-// KDE File Manager -- HTTP Cookies
-// $Id$
-
-//
-// The cookie protocol is a mess. RFC2109 is a joke since nobody seems to
-// use it. Apart from that it is badly written.
-// We try to implement Netscape Cookies and try to behave us according to
-// RFC2109 as much as we can.
-//
-// We assume cookies do not contain any spaces (Netscape spec.)
-// According to RFC2109 this is allowed though.
-//
-
-#include <config.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_SYS_PARAM_H
-#include <sys/param.h>
-#endif
-#include <fcntl.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <string.h>
-
-#ifdef USE_SOLARIS
-#include <strings.h>
-#endif
-
-#include <stdlib.h>
-
-//#include <netinet/in.h>
-//#include <arpa/inet.h>
-
-#include <tqstring.h>
-#include <tqstrlist.h>
-#include <tqptrlist.h>
-#include <tqptrdict.h>
-#include <tqfile.h>
-#include <tqdir.h>
-#include <tqregexp.h>
-
-#include <kurl.h>
-#include <krfcdate.h>
-#include <kconfig.h>
-#include <ksavefile.h>
-#include <kdebug.h>
-
-#include "kcookiejar.h"
-
-
-// BR87227
-// Waba: Should the number of cookies be limited?
-// I am not convinced of the need of such limit
-// Mozilla seems to limit to 20 cookies / domain
-// but it is unclear which policy it uses to expire
-// cookies when it exceeds that amount
-#undef MAX_COOKIE_LIMIT
-
-#define MAX_COOKIES_PER_HOST 25
-#define READ_BUFFER_SIZE 8192
-#define IP_ADDRESS_EXPRESSION "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
-
-// Note with respect to TQString::fromLatin1( )
-// Cookies are stored as 8 bit data and passed to kio_http as
-// latin1 regardless of their actual encoding.
-
-// L1 is used to indicate latin1 constants
-#define L1(x) TQString::fromLatin1(x)
-
-template class TQPtrList<KHttpCookie>;
-template class TQPtrDict<KHttpCookieList>;
-
-TQString KCookieJar::adviceToStr(KCookieAdvice _advice)
-{
- switch( _advice )
- {
- case KCookieAccept: return L1("Accept");
- case KCookieReject: return L1("Reject");
- case KCookieAsk: return L1("Ask");
- default: return L1("Dunno");
- }
-}
-
-KCookieAdvice KCookieJar::strToAdvice(const TQString &_str)
-{
- if (_str.isEmpty())
- return KCookieDunno;
-
- TQCString advice = _str.lower().latin1();
-
- if (advice == "accept")
- return KCookieAccept;
- else if (advice == "reject")
- return KCookieReject;
- else if (advice == "ask")
- return KCookieAsk;
-
- return KCookieDunno;
-}
-
-// KHttpCookie
-///////////////////////////////////////////////////////////////////////////
-
-//
-// Cookie constructor
-//
-KHttpCookie::KHttpCookie(const TQString &_host,
- const TQString &_domain,
- const TQString &_path,
- const TQString &_name,
- const TQString &_value,
- time_t _expireDate,
- int _protocolVersion,
- bool _secure,
- bool _httpOnly,
- bool _explicitPath) :
- mHost(_host),
- mDomain(_domain),
- mPath(_path.isEmpty() ? TQString::null : _path),
- mName(_name),
- mValue(_value),
- mExpireDate(_expireDate),
- mProtocolVersion(_protocolVersion),
- mSecure(_secure),
- mCrossDomain(false),
- mHttpOnly(_httpOnly),
- mExplicitPath(_explicitPath)
-{
-}
-
-//
-// Checks if a cookie has been expired
-//
-bool KHttpCookie::isExpired(time_t currentDate)
-{
- return (mExpireDate != 0) && (mExpireDate < currentDate);
-}
-
-//
-// Returns a string for a HTTP-header
-//
-TQString KHttpCookie::cookieStr(bool useDOMFormat)
-{
- TQString result;
-
- if (useDOMFormat || (mProtocolVersion == 0))
- {
- if ( !mName.isEmpty() )
- result = mName + '=';
- result += mValue;
- }
- else
- {
- result = mName + '=' + mValue;
- if (mExplicitPath)
- result += L1("; $Path=\"") + mPath + L1("\"");
- if (!mDomain.isEmpty())
- result += L1("; $Domain=\"") + mDomain + L1("\"");
- }
- return result;
-}
-
-//
-// Returns whether this cookie should be send to this location.
-bool KHttpCookie::match(const TQString &fqdn, const TQStringList &domains,
- const TQString &path)
-{
- // Cookie domain match check
- if (mDomain.isEmpty())
- {
- if (fqdn != mHost)
- return false;
- }
- else if (!domains.contains(mDomain))
- {
- if (mDomain[0] == '.')
- return false;
-
- // Maybe the domain needs an extra dot.
- TQString domain = '.' + mDomain;
- if ( !domains.contains( domain ) )
- if ( fqdn != mDomain )
- return false;
- }
-
- // Cookie path match check
- if (mPath.isEmpty())
- return true;
-
- // According to the netscape spec both http://www.acme.com/foobar,
- // http://www.acme.com/foo.bar and http://www.acme.com/foo/bar
- // match http://www.acme.com/foo.
- // We only match http://www.acme.com/foo/bar
-
- if( path.startsWith(mPath) &&
- (
- (path.length() == mPath.length() ) || // Paths are exact match
- (path[mPath.length()-1] == '/') || // mPath ended with a slash
- (path[mPath.length()] == '/') // A slash follows.
- ))
- return true; // Path of URL starts with cookie-path
-
- return false;
-}
-
-// KHttpCookieList
-///////////////////////////////////////////////////////////////////////////
-
-int KHttpCookieList::compareItems( void * item1, void * item2)
-{
- int pathLen1 = ((KHttpCookie *)item1)->path().length();
- int pathLen2 = ((KHttpCookie *)item2)->path().length();
- if (pathLen1 > pathLen2)
- return -1;
- if (pathLen1 < pathLen2)
- return 1;
- return 0;
-}
-
-
-// KCookieJar
-///////////////////////////////////////////////////////////////////////////
-
-//
-// Constructs a new cookie jar
-//
-// One jar should be enough for all cookies.
-//
-KCookieJar::KCookieJar()
-{
- m_cookieDomains.setAutoDelete( true );
- m_globalAdvice = KCookieDunno;
- m_configChanged = false;
- m_cookiesChanged = false;
-
- TDEConfig cfg("tdehtml/domain_info", true, false, "data");
- TQStringList countries = cfg.readListEntry("twoLevelTLD");
- for(TQStringList::ConstIterator it = countries.begin();
- it != countries.end(); ++it)
- {
- m_twoLevelTLD.replace(*it, (int *) 1);
- }
-}
-
-//
-// Destructs the cookie jar
-//
-// Poor little cookies, they will all be eaten by the cookie monster!
-//
-KCookieJar::~KCookieJar()
-{
- // Not much to do here
-}
-
-static void removeDuplicateFromList(KHttpCookieList *list, KHttpCookie *cookiePtr, bool nameMatchOnly=false, bool updateWindowId=false)
-{
- TQString domain1 = cookiePtr->domain();
- if (domain1.isEmpty())
- domain1 = cookiePtr->host();
-
- for ( KHttpCookiePtr cookie=list->first(); cookie != 0; )
- {
- TQString domain2 = cookie->domain();
- if (domain2.isEmpty())
- domain2 = cookie->host();
-
- if (
- (cookiePtr->name() == cookie->name()) &&
- (
- nameMatchOnly ||
- ( (domain1 == domain2) && (cookiePtr->path() == cookie->path()) )
- )
- )
- {
- if (updateWindowId)
- {
- for(TQValueList<long>::ConstIterator it = cookie->windowIds().begin();
- it != cookie->windowIds().end(); ++it)
- {
- long windowId = *it;
- if (windowId && (cookiePtr->windowIds().find(windowId) == cookiePtr->windowIds().end()))
- {
- cookiePtr->windowIds().append(windowId);
- }
- }
- }
- KHttpCookiePtr old_cookie = cookie;
- cookie = list->next();
- list->removeRef( old_cookie );
- break;
- }
- else
- {
- cookie = list->next();
- }
- }
-}
-
-
-//
-// Looks for cookies in the cookie jar which are appropriate for _url.
-// Returned is a string containing all appropriate cookies in a format
-// which can be added to a HTTP-header without any additional processing.
-//
-TQString KCookieJar::findCookies(const TQString &_url, bool useDOMFormat, long windowId, KHttpCookieList *pendingCookies)
-{
- TQString cookieStr;
- TQStringList domains;
- TQString fqdn;
- TQString path;
- KHttpCookiePtr cookie;
- KCookieAdvice advice = m_globalAdvice;
-
- if (!parseURL(_url, fqdn, path))
- return cookieStr;
-
- bool secureRequest = (_url.find( L1("https://"), 0, false) == 0 ||
- _url.find( L1("webdavs://"), 0, false) == 0);
-
- // kdDebug(7104) << "findCookies: URL= " << _url << ", secure = " << secureRequest << endl;
-
- extractDomains(fqdn, domains);
-
- KHttpCookieList allCookies;
-
- for(TQStringList::ConstIterator it = domains.begin();
- true;
- ++it)
- {
- KHttpCookieList *cookieList;
- if (it == domains.end())
- {
- cookieList = pendingCookies; // Add pending cookies
- pendingCookies = 0;
- if (!cookieList)
- break;
- }
- else
- {
- TQString key = (*it).isNull() ? L1("") : (*it);
- cookieList = m_cookieDomains[key];
- if (!cookieList)
- continue; // No cookies for this domain
- }
-
- if (cookieList->getAdvice() != KCookieDunno)
- advice = cookieList->getAdvice();
-
- for ( cookie=cookieList->first(); cookie != 0; cookie=cookieList->next() )
- {
- // If the we are setup to automatically accept all session cookies and to
- // treat all cookies as session cookies or the current cookie is a session
- // cookie, then send the cookie back regardless of either policy.
- if (advice == KCookieReject &&
- !(m_autoAcceptSessionCookies &&
- (m_ignoreCookieExpirationDate || cookie->expireDate() == 0)))
- continue;
-
- if (!cookie->match(fqdn, domains, path))
- continue;
-
- if( cookie->isSecure() && !secureRequest )
- continue;
-
- if( cookie->isHttpOnly() && useDOMFormat )
- continue;
-
- // Do not send expired cookies.
- if ( cookie->isExpired (time(0)) )
- {
- // Note there is no need to actually delete the cookie here
- // since the cookieserver will invoke ::saveCookieJar because
- // of the state change below. This will then do the job of
- // deleting the cookie for us.
- m_cookiesChanged = true;
- continue;
- }
-
- if (windowId && (cookie->windowIds().find(windowId) == cookie->windowIds().end()))
- {
- cookie->windowIds().append(windowId);
- }
-
- if (it == domains.end()) // Only needed when processing pending cookies
- removeDuplicateFromList(&allCookies, cookie);
-
- allCookies.append(cookie);
- }
- if (it == domains.end())
- break; // Finished.
- }
-
- int cookieCount = 0;
-
- int protVersion=0;
- for ( cookie=allCookies.first(); cookie != 0; cookie=allCookies.next() )
- {
- if (cookie->protocolVersion() > protVersion)
- protVersion = cookie->protocolVersion();
- }
-
- for ( cookie=allCookies.first(); cookie != 0; cookie=allCookies.next() )
- {
- if (useDOMFormat)
- {
- if (cookieCount > 0)
- cookieStr += L1("; ");
- cookieStr += cookie->cookieStr(true);
- }
- else
- {
- if (cookieCount == 0)
- {
- cookieStr += L1("Cookie: ");
- if (protVersion > 0)
- {
- TQString version;
- version.sprintf("$Version=%d; ", protVersion); // Without quotes
- cookieStr += version;
- }
- }
- else
- {
- cookieStr += L1("; ");
- }
- cookieStr += cookie->cookieStr(false);
- }
- cookieCount++;
- }
-
- return cookieStr;
-}
-
-//
-// This function parses a string like 'my_name="my_value";' and returns
-// 'my_name' in Name and 'my_value' in Value.
-//
-// A pointer to the end of the parsed part is returned.
-// This pointer points either to:
-// '\0' - The end of the string has reached.
-// ';' - Another my_name="my_value" pair follows
-// ',' - Another cookie follows
-// '\n' - Another header follows
-static const char * parseNameValue(const char *header,
- TQString &Name,
- TQString &Value,
- bool keepQuotes=false,
- bool rfcQuotes=false)
-{
- const char *s = header;
- // Parse 'my_name' part
- for(; (*s != '='); s++)
- {
- if ((*s=='\0') || (*s==';') || (*s=='\n'))
- {
- // No '=' sign -> use string as the value, name is empty
- // (behavior found in Mozilla and IE)
- Name = "";
- Value = TQString::fromLatin1(header);
- Value.truncate( s - header );
- Value = Value.stripWhiteSpace();
- return (s);
- }
- }
-
- Name = header;
- Name.truncate( s - header );
- Name = Name.stripWhiteSpace();
-
- // *s == '='
- s++;
-
- // Skip any whitespace
- for(; (*s == ' ') || (*s == '\t'); s++)
- {
- if ((*s=='\0') || (*s==';') || (*s=='\n'))
- {
- // End of Name
- Value = "";
- return (s);
- }
- }
-
- if ((rfcQuotes || !keepQuotes) && (*s == '\"'))
- {
- // Parse '"my_value"' part (quoted value)
- if (keepQuotes)
- header = s++;
- else
- header = ++s; // skip "
- for(;(*s != '\"');s++)
- {
- if ((*s=='\0') || (*s=='\n'))
- {
- // End of Name
- Value = TQString::fromLatin1(header);
- Value.truncate(s - header);
- return (s);
- }
- }
- Value = TQString::fromLatin1(header);
- // *s == '\"';
- if (keepQuotes)
- Value.truncate( ++s - header );
- else
- Value.truncate( s++ - header );
-
- // Skip any remaining garbage
- for(;; s++)
- {
- if ((*s=='\0') || (*s==';') || (*s=='\n'))
- break;
- }
- }
- else
- {
- // Parse 'my_value' part (unquoted value)
- header = s;
- while ((*s != '\0') && (*s != ';') && (*s != '\n'))
- s++;
- // End of Name
- Value = TQString::fromLatin1(header);
- Value.truncate( s - header );
- Value = Value.stripWhiteSpace();
- }
- return (s);
-
-}
-
-void KCookieJar::stripDomain(const TQString &_fqdn, TQString &_domain)
-{
- TQStringList domains;
- extractDomains(_fqdn, domains);
- if (domains.count() > 3)
- _domain = domains[3];
- else
- _domain = domains[0];
-}
-
-TQString KCookieJar::stripDomain( KHttpCookiePtr cookiePtr)
-{
- TQString domain; // We file the cookie under this domain.
- if (cookiePtr->domain().isEmpty())
- stripDomain( cookiePtr->host(), domain);
- else
- stripDomain (cookiePtr->domain(), domain);
- return domain;
-}
-
-bool KCookieJar::parseURL(const TQString &_url,
- TQString &_fqdn,
- TQString &_path)
-{
- KURL kurl(_url);
- if (!kurl.isValid())
- return false;
-
- _fqdn = kurl.host().lower();
- if (kurl.port())
- {
- if (((kurl.protocol() == L1("http")) && (kurl.port() != 80)) ||
- ((kurl.protocol() == L1("https")) && (kurl.port() != 443)))
- {
- _fqdn = L1("%1:%2").arg(kurl.port()).arg(_fqdn);
- }
- }
-
- // Cookie spoofing protection. Since there is no way a path separator
- // or escape encoded character is allowed in the hostname according
- // to RFC 2396, reject attempts to include such things there!
- if(_fqdn.find('/') > -1 || _fqdn.find('%') > -1)
- {
- return false; // deny everything!!
- }
-
- _path = kurl.path();
- if (_path.isEmpty())
- _path = L1("/");
-
- TQRegExp exp(L1("[\\\\/]\\.\\.[\\\\/]"));
- // Weird path, cookie stealing attempt?
- if (exp.search(_path) != -1)
- return false; // Deny everything!!
-
- return true;
-}
-
-void KCookieJar::extractDomains(const TQString &_fqdn,
- TQStringList &_domains)
-{
- // Return numeric IPv6 addresses as is...
- if (_fqdn[0] == '[')
- {
- _domains.append( _fqdn );
- return;
- }
- // Return numeric IPv4 addresses as is...
- if ((_fqdn.at(0) >= TQChar('0')) && (_fqdn.at(0) <= TQChar('9')))
- {
- if (_fqdn.find(TQRegExp(IP_ADDRESS_EXPRESSION)) > -1)
- {
- _domains.append( _fqdn );
- return;
- }
- }
-
- TQStringList partList = TQStringList::split('.', _fqdn, false);
-
- if (partList.count())
- partList.remove(partList.begin()); // Remove hostname
-
- while(partList.count())
- {
-
- if (partList.count() == 1)
- break; // We only have a TLD left.
-
- if ((partList.count() == 2) && (m_twoLevelTLD[partList[1].lower()]))
- {
- // This domain uses two-level TLDs in the form xxxx.yy
- break;
- }
-
- if ((partList.count() == 2) && (partList[1].length() == 2))
- {
- // If this is a TLD, we should stop. (e.g. co.uk)
- // We assume this is a TLD if it ends with .xx.yy or .x.yy
- if (partList[0].length() <= 2)
- break; // This is a TLD.
-
- // Catch some TLDs that we miss with the previous check
- // e.g. com.au, org.uk, mil.co
- TQCString t = partList[0].lower().utf8();
- if ((t == "com") || (t == "net") || (t == "org") || (t == "gov") || (t == "edu") || (t == "mil") || (t == "int"))
- break;
- }
-
- TQString domain = partList.join(L1("."));
- _domains.append(domain);
- _domains.append('.' + domain);
- partList.remove(partList.begin()); // Remove part
- }
-
- // Always add the FQDN at the start of the list for
- // hostname == cookie-domainname checks!
- _domains.prepend( '.' + _fqdn );
- _domains.prepend( _fqdn );
-}
-
-
-/*
- Changes dates in from the following format
-
- Wed Sep 12 07:00:00 2007 GMT
- to
- Wed Sep 12 2007 07:00:00 GMT
-
- to allow KRFCDate::parseDate to properly parse expiration date formats
- used in cookies by some servers such as amazon.com. See BR# 145244.
-*/
-static TQString fixupDateTime(const TQString& dt)
-{
- const int index = dt.find(TQRegExp("[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}"));
-
- if (index > -1)
- {
- TQStringList dateStrList = TQStringList::split(' ', dt.mid(index));
- if (dateStrList.count() > 1)
- {
- TQString date = dateStrList[0];
- dateStrList[0] = dateStrList[1];
- dateStrList[1] = date;
- date = dt;
- return date.replace(index, date.length(), dateStrList.join(" "));
- }
- }
-
- return dt;
-}
-
-//
-// This function parses cookie_headers and returns a linked list of
-// KHttpCookie objects for all cookies found in cookie_headers.
-// If no cookies could be found 0 is returned.
-//
-// cookie_headers should be a concatenation of all lines of a HTTP-header
-// which start with "Set-Cookie". The lines should be separated by '\n's.
-//
-KHttpCookieList KCookieJar::makeCookies(const TQString &_url,
- const TQCString &cookie_headers,
- long windowId)
-{
- KHttpCookieList cookieList;
- KHttpCookieList cookieList2;
- KHttpCookiePtr lastCookie = 0;
- const char *cookieStr = cookie_headers.data();
- TQString Name;
- TQString Value;
- TQString fqdn;
- TQString path;
- bool crossDomain = false;
-
- if (!parseURL(_url, fqdn, path))
- {
- // Error parsing _url
- return KHttpCookieList();
- }
- TQString defaultPath;
- int i = path.findRev('/');
- if (i > 0)
- defaultPath = path.left(i);
-
- // The hard stuff :)
- for(;;)
- {
- // check for "Set-Cookie"
- if (strncmp(cookieStr, "Cross-Domain\n", 13) == 0)
- {
- cookieStr += 13;
- crossDomain = true;
- }
- else if (strncasecmp(cookieStr, "Set-Cookie:", 11) == 0)
- {
- cookieStr = parseNameValue(cookieStr+11, Name, Value, true);
-
- // Host = FQDN
- // Default domain = ""
- // Default path according to rfc2109
-
- KHttpCookie *cookie = new KHttpCookie(fqdn, L1(""), defaultPath, Name, Value);
- if (windowId)
- cookie->mWindowIds.append(windowId);
- cookie->mCrossDomain = crossDomain;
-
- // Insert cookie in chain
- cookieList.append(cookie);
- lastCookie = cookie;
- }
- else if (strncasecmp(cookieStr, "Set-Cookie2:", 12) == 0)
- {
- // Attempt to follow rfc2965
- cookieStr = parseNameValue(cookieStr+12, Name, Value, true, true);
-
- // Host = FQDN
- // Default domain = ""
- // Default path according to rfc2965
-
- KHttpCookie *cookie = new KHttpCookie(fqdn, L1(""), defaultPath, Name, Value);
- if (windowId)
- cookie->mWindowIds.append(windowId);
- cookie->mCrossDomain = crossDomain;
-
- // Insert cookie in chain
- cookieList2.append(cookie);
- lastCookie = cookie;
- }
- else
- {
- // This is not the start of a cookie header, skip till next line.
- while (*cookieStr && *cookieStr != '\n')
- cookieStr++;
-
- if (*cookieStr == '\n')
- cookieStr++;
-
- if (!*cookieStr)
- break; // End of cookie_headers
- else
- continue; // end of this header, continue with next.
- }
-
- while ((*cookieStr == ';') || (*cookieStr == ' '))
- {
- cookieStr++;
-
- // Name-Value pair follows
- cookieStr = parseNameValue(cookieStr, Name, Value);
-
- TQCString cName = Name.lower().latin1();
- if (cName == "domain")
- {
- TQString dom = Value.lower();
- // RFC2965 3.2.2: If an explicitly specified value does not
- // start with a dot, the user agent supplies a leading dot
- if(dom.length() && dom[0] != '.')
- dom.prepend(".");
- // remove a trailing dot
- if(dom.length() > 2 && dom[dom.length()-1] == '.')
- dom = dom.left(dom.length()-1);
-
- if(dom.contains('.') > 1 || dom == ".local")
- lastCookie->mDomain = dom;
- }
- else if (cName == "max-age")
- {
- int max_age = Value.toInt();
- if (max_age == 0)
- lastCookie->mExpireDate = 1;
- else
- lastCookie->mExpireDate = time(0)+max_age;
- }
- else if (cName == "expires")
- {
- // Parse brain-dead netscape cookie-format
- lastCookie->mExpireDate = KRFCDate::parseDate(Value);
-
- // Workaround for servers that send the expiration date in
- // 'Wed Sep 12 07:00:00 2007 GMT' format. See BR# 145244.
- if (lastCookie->mExpireDate == 0)
- lastCookie->mExpireDate = KRFCDate::parseDate(fixupDateTime(Value));
- }
- else if (cName == "path")
- {
- if (Value.isEmpty())
- lastCookie->mPath = TQString::null; // Catch "" <> TQString::null
- else
- lastCookie->mPath = KURL::decode_string(Value);
- lastCookie->mExplicitPath = true;
- }
- else if (cName == "version")
- {
- lastCookie->mProtocolVersion = Value.toInt();
- }
- else if ((cName == "secure") ||
- (cName.isEmpty() && Value.lower() == L1("secure")))
- {
- lastCookie->mSecure = true;
- }
- else if ((cName == "httponly") ||
- (cName.isEmpty() && Value.lower() == L1("httponly")))
- {
- lastCookie->mHttpOnly = true;
- }
- }
-
- if (*cookieStr == '\0')
- break; // End of header
-
- // Skip ';' or '\n'
- cookieStr++;
- }
-
- // RFC2965 cookies come last so that they override netscape cookies.
- while( !cookieList2.isEmpty() && (lastCookie = cookieList2.take(0)) )
- {
- removeDuplicateFromList(&cookieList, lastCookie, true);
- cookieList.append(lastCookie);
- }
-
- return cookieList;
-}
-
-/**
-* Parses cookie_domstr and returns a linked list of KHttpCookie objects.
-* cookie_domstr should be a semicolon-delimited list of "name=value"
-* pairs. Any whitespace before "name" or around '=' is discarded.
-* If no cookies are found, 0 is returned.
-*/
-KHttpCookieList KCookieJar::makeDOMCookies(const TQString &_url,
- const TQCString &cookie_domstring,
- long windowId)
-{
- // A lot copied from above
- KHttpCookieList cookieList;
- KHttpCookiePtr lastCookie = 0;
-
- const char *cookieStr = cookie_domstring.data();
- TQString Name;
- TQString Value;
- TQString fqdn;
- TQString path;
-
- if (!parseURL(_url, fqdn, path))
- {
- // Error parsing _url
- return KHttpCookieList();
- }
-
- // This time it's easy
- while(*cookieStr)
- {
- cookieStr = parseNameValue(cookieStr, Name, Value);
-
- // Host = FQDN
- // Default domain = ""
- // Default path = ""
- KHttpCookie *cookie = new KHttpCookie(fqdn, TQString::null, TQString::null,
- Name, Value );
- if (windowId)
- cookie->mWindowIds.append(windowId);
-
- cookieList.append(cookie);
- lastCookie = cookie;
-
- if (*cookieStr != '\0')
- cookieStr++; // Skip ';' or '\n'
- }
-
- return cookieList;
-}
-
-#ifdef MAX_COOKIE_LIMIT
-static void makeRoom(KHttpCookieList *cookieList, KHttpCookiePtr &cookiePtr)
-{
- // Too much cookies: throw one away, try to be somewhat clever
- KHttpCookiePtr lastCookie = 0;
- for(KHttpCookiePtr cookie = cookieList->first(); cookie; cookie = cookieList->next())
- {
- if (cookieList->compareItems(cookie, cookiePtr) < 0)
- break;
- lastCookie = cookie;
- }
- if (!lastCookie)
- lastCookie = cookieList->first();
- cookieList->removeRef(lastCookie);
-}
-#endif
-
-//
-// This function hands a KHttpCookie object over to the cookie jar.
-//
-// On return cookiePtr is set to 0.
-//
-void KCookieJar::addCookie(KHttpCookiePtr &cookiePtr)
-{
- TQStringList domains;
- KHttpCookieList *cookieList = 0L;
-
- // We always need to do this to make sure that the
- // that cookies of type hostname == cookie-domainname
- // are properly removed and/or updated as necessary!
- extractDomains( cookiePtr->host(), domains );
- for ( TQStringList::ConstIterator it = domains.begin();
- (it != domains.end() && !cookieList);
- ++it )
- {
- TQString key = (*it).isNull() ? L1("") : (*it);
- KHttpCookieList *list= m_cookieDomains[key];
- if ( !list ) continue;
-
- removeDuplicateFromList(list, cookiePtr, false, true);
- }
-
- TQString domain = stripDomain( cookiePtr );
- TQString key = domain.isNull() ? L1("") : domain;
- cookieList = m_cookieDomains[ key ];
- if (!cookieList)
- {
- // Make a new cookie list
- cookieList = new KHttpCookieList();
- cookieList->setAutoDelete(true);
-
- // All cookies whose domain is not already
- // known to us should be added with KCookieDunno.
- // KCookieDunno means that we use the global policy.
- cookieList->setAdvice( KCookieDunno );
-
- m_cookieDomains.insert( domain, cookieList);
-
- // Update the list of domains
- m_domainList.append(domain);
- }
-
- // Add the cookie to the cookie list
- // The cookie list is sorted 'longest path first'
- if (!cookiePtr->isExpired(time(0)))
- {
-#ifdef MAX_COOKIE_LIMIT
- if (cookieList->count() >= MAX_COOKIES_PER_HOST)
- makeRoom(cookieList, cookiePtr); // Delete a cookie
-#endif
- cookieList->inSort( cookiePtr );
- m_cookiesChanged = true;
- }
- else
- {
- delete cookiePtr;
- }
- cookiePtr = 0;
-}
-
-//
-// This function advices whether a single KHttpCookie object should
-// be added to the cookie jar.
-//
-KCookieAdvice KCookieJar::cookieAdvice(KHttpCookiePtr cookiePtr)
-{
- if (m_rejectCrossDomainCookies && cookiePtr->isCrossDomain())
- return KCookieReject;
-
- TQStringList domains;
-
- extractDomains(cookiePtr->host(), domains);
-
- // If the cookie specifies a domain, check whether it is valid. Otherwise,
- // accept the cookie anyways but remove the domain="" value to prevent
- // cross-site cookie injection.
- if (!cookiePtr->domain().isEmpty())
- {
- if (!domains.contains(cookiePtr->domain()) &&
- !cookiePtr->domain().endsWith("."+cookiePtr->host()))
- cookiePtr->fixDomain(TQString::null);
- }
-
- if (m_autoAcceptSessionCookies && (cookiePtr->expireDate() == 0 ||
- m_ignoreCookieExpirationDate))
- return KCookieAccept;
-
- KCookieAdvice advice = KCookieDunno;
- bool isFQDN = true; // First is FQDN
- TQStringList::Iterator it = domains.begin(); // Start with FQDN which first in the list.
- while( (advice == KCookieDunno) && (it != domains.end()))
- {
- TQString domain = *it;
- // Check if a policy for the FQDN/domain is set.
- if ( domain[0] == '.' || isFQDN )
- {
- isFQDN = false;
- KHttpCookieList *cookieList = m_cookieDomains[domain];
- if (cookieList)
- advice = cookieList->getAdvice();
- }
- domains.remove(it);
- it = domains.begin(); // Continue from begin of remaining list
- }
-
- if (advice == KCookieDunno)
- advice = m_globalAdvice;
-
- return advice;
-}
-
-//
-// This function gets the advice for all cookies originating from
-// _domain.
-//
-KCookieAdvice KCookieJar::getDomainAdvice(const TQString &_domain)
-{
- KHttpCookieList *cookieList = m_cookieDomains[_domain];
- KCookieAdvice advice;
-
- if (cookieList)
- {
- advice = cookieList->getAdvice();
- }
- else
- {
- advice = KCookieDunno;
- }
-
- return advice;
-}
-
-//
-// This function sets the advice for all cookies originating from
-// _domain.
-//
-void KCookieJar::setDomainAdvice(const TQString &_domain, KCookieAdvice _advice)
-{
- TQString domain(_domain);
- KHttpCookieList *cookieList = m_cookieDomains[domain];
-
- if (cookieList)
- {
- if (cookieList->getAdvice() != _advice)
- {
- m_configChanged = true;
- // domain is already known
- cookieList->setAdvice( _advice);
- }
-
- if ((cookieList->isEmpty()) &&
- (_advice == KCookieDunno))
- {
- // This deletes cookieList!
- m_cookieDomains.remove(domain);
- m_domainList.remove(domain);
- }
- }
- else
- {
- // domain is not yet known
- if (_advice != KCookieDunno)
- {
- // We should create a domain entry
- m_configChanged = true;
- // Make a new cookie list
- cookieList = new KHttpCookieList();
- cookieList->setAutoDelete(true);
- cookieList->setAdvice( _advice);
- m_cookieDomains.insert( domain, cookieList);
- // Update the list of domains
- m_domainList.append( domain);
- }
- }
-}
-
-//
-// This function sets the advice for all cookies originating from
-// the same domain as _cookie
-//
-void KCookieJar::setDomainAdvice(KHttpCookiePtr cookiePtr, KCookieAdvice _advice)
-{
- TQString domain;
- stripDomain(cookiePtr->host(), domain); // We file the cookie under this domain.
-
- setDomainAdvice(domain, _advice);
-}
-
-//
-// This function sets the global advice for cookies
-//
-void KCookieJar::setGlobalAdvice(KCookieAdvice _advice)
-{
- if (m_globalAdvice != _advice)
- m_configChanged = true;
- m_globalAdvice = _advice;
-}
-
-//
-// Get a list of all domains known to the cookie jar.
-//
-const TQStringList& KCookieJar::getDomainList()
-{
- return m_domainList;
-}
-
-//
-// Get a list of all cookies in the cookie jar originating from _domain.
-//
-const KHttpCookieList *KCookieJar::getCookieList(const TQString & _domain,
- const TQString & _fqdn )
-{
- TQString domain;
-
- if (_domain.isEmpty())
- stripDomain( _fqdn, domain );
- else
- domain = _domain;
-
- return m_cookieDomains[domain];
-}
-
-//
-// Eat a cookie out of the jar.
-// cookiePtr should be one of the cookies returned by getCookieList()
-//
-void KCookieJar::eatCookie(KHttpCookiePtr cookiePtr)
-{
- TQString domain = stripDomain(cookiePtr); // We file the cookie under this domain.
- KHttpCookieList *cookieList = m_cookieDomains[domain];
-
- if (cookieList)
- {
- // This deletes cookiePtr!
- if (cookieList->removeRef( cookiePtr ))
- m_cookiesChanged = true;
-
- if ((cookieList->isEmpty()) &&
- (cookieList->getAdvice() == KCookieDunno))
- {
- // This deletes cookieList!
- m_cookieDomains.remove(domain);
-
- m_domainList.remove(domain);
- }
- }
-}
-
-void KCookieJar::eatCookiesForDomain(const TQString &domain)
-{
- KHttpCookieList *cookieList = m_cookieDomains[domain];
- if (!cookieList || cookieList->isEmpty()) return;
-
- cookieList->clear();
- if (cookieList->getAdvice() == KCookieDunno)
- {
- // This deletes cookieList!
- m_cookieDomains.remove(domain);
- m_domainList.remove(domain);
- }
- m_cookiesChanged = true;
-}
-
-void KCookieJar::eatSessionCookies( long windowId )
-{
- if (!windowId)
- return;
-
- TQStringList::Iterator it=m_domainList.begin();
- for ( ; it != m_domainList.end(); ++it )
- eatSessionCookies( *it, windowId, false );
-}
-
-void KCookieJar::eatAllCookies()
-{
- for ( TQStringList::Iterator it=m_domainList.begin();
- it != m_domainList.end();)
- {
- TQString domain = *it++;
- // This might remove domain from domainList!
- eatCookiesForDomain(domain);
- }
-}
-
-void KCookieJar::eatSessionCookies( const TQString& fqdn, long windowId,
- bool isFQDN )
-{
- KHttpCookieList* cookieList;
- if ( !isFQDN )
- cookieList = m_cookieDomains[fqdn];
- else
- {
- TQString domain;
- stripDomain( fqdn, domain );
- cookieList = m_cookieDomains[domain];
- }
-
- if ( cookieList )
- {
- KHttpCookiePtr cookie=cookieList->first();
- for (; cookie != 0;)
- {
- if ((cookie->expireDate() != 0) && !m_ignoreCookieExpirationDate)
- {
- cookie = cookieList->next();
- continue;
- }
-
- TQValueList<long> &ids = cookie->windowIds();
- if (!ids.remove(windowId) || !ids.isEmpty())
- {
- cookie = cookieList->next();
- continue;
- }
- KHttpCookiePtr old_cookie = cookie;
- cookie = cookieList->next();
- cookieList->removeRef( old_cookie );
- }
- }
-}
-
-//
-// Saves all cookies to the file '_filename'.
-// On succes 'true' is returned.
-// On failure 'false' is returned.
-bool KCookieJar::saveCookies(const TQString &_filename)
-{
- KSaveFile saveFile(_filename, 0600);
-
- if (saveFile.status() != 0)
- return false;
-
- FILE *fStream = saveFile.fstream();
-
- time_t curTime = time(0);
-
- fprintf(fStream, "# KDE Cookie File v2\n#\n");
-
- fprintf(fStream, "%-20s %-20s %-12s %-10s %-4s %-20s %-4s %s\n",
- "# Host", "Domain", "Path", "Exp.date", "Prot",
- "Name", "Sec", "Value");
-
- for ( TQStringList::Iterator it=m_domainList.begin(); it != m_domainList.end();
- it++ )
- {
- const TQString &domain = *it;
- bool domainPrinted = false;
-
- KHttpCookieList *cookieList = m_cookieDomains[domain];
- KHttpCookiePtr cookie=cookieList->last();
-
- for (; cookie != 0;)
- {
- if (cookie->isExpired(curTime))
- {
- // Delete expired cookies
- KHttpCookiePtr old_cookie = cookie;
- cookie = cookieList->prev();
- cookieList->removeRef( old_cookie );
- }
- else if (cookie->expireDate() != 0 && !m_ignoreCookieExpirationDate)
- {
- if (!domainPrinted)
- {
- domainPrinted = true;
- fprintf(fStream, "[%s]\n", domain.local8Bit().data());
- }
- // Store persistent cookies
- TQString path = L1("\"");
- path += cookie->path();
- path += '"';
- TQString domain = L1("\"");
- domain += cookie->domain();
- domain += '"';
- fprintf(fStream, "%-20s %-20s %-12s %10lu %3d %-20s %-4i %s\n",
- cookie->host().latin1(), domain.latin1(),
- path.latin1(), (unsigned long) cookie->expireDate(),
- cookie->protocolVersion(),
- cookie->name().isEmpty() ? cookie->value().latin1() : cookie->name().latin1(),
- (cookie->isSecure() ? 1 : 0) + (cookie->isHttpOnly() ? 2 : 0) +
- (cookie->hasExplicitPath() ? 4 : 0) + (cookie->name().isEmpty() ? 8 : 0),
- cookie->value().latin1());
- cookie = cookieList->prev();
- }
- else
- {
- // Skip session-only cookies
- cookie = cookieList->prev();
- }
- }
- }
-
- return saveFile.close();
-}
-
-typedef char *charPtr;
-
-static const char *parseField(charPtr &buffer, bool keepQuotes=false)
-{
- char *result;
- if (!keepQuotes && (*buffer == '\"'))
- {
- // Find terminating "
- buffer++;
- result = buffer;
- while((*buffer != '\"') && (*buffer))
- buffer++;
- }
- else
- {
- // Find first white space
- result = buffer;
- while((*buffer != ' ') && (*buffer != '\t') && (*buffer != '\n') && (*buffer))
- buffer++;
- }
-
- if (!*buffer)
- return result; //
- *buffer++ = '\0';
-
- // Skip white-space
- while((*buffer == ' ') || (*buffer == '\t') || (*buffer == '\n'))
- buffer++;
-
- return result;
-}
-
-
-//
-// Reloads all cookies from the file '_filename'.
-// On succes 'true' is returned.
-// On failure 'false' is returned.
-bool KCookieJar::loadCookies(const TQString &_filename)
-{
- FILE *fStream = fopen( TQFile::encodeName(_filename), "r");
- if (fStream == 0)
- {
- return false;
- }
-
- time_t curTime = time(0);
-
- char *buffer = new char[READ_BUFFER_SIZE];
-
- bool err = false;
- err = (fgets(buffer, READ_BUFFER_SIZE, fStream) == 0);
-
- int version = 1;
- if (!err)
- {
- if (strcmp(buffer, "# KDE Cookie File\n") == 0)
- {
- // version 1
- }
- else if (sscanf(buffer, "# KDE Cookie File v%d\n", &version) != 1)
- {
- err = true;
- }
- }
-
- if (!err)
- {
- while(fgets(buffer, READ_BUFFER_SIZE, fStream) != 0)
- {
- char *line = buffer;
- // Skip lines which begin with '#' or '['
- if ((line[0] == '#') || (line[0] == '['))
- continue;
-
- const char *host( parseField(line) );
- const char *domain( parseField(line) );
- const char *path( parseField(line) );
- const char *expStr( parseField(line) );
- if (!expStr) continue;
- int expDate = (time_t) strtoul(expStr, 0, 10);
- const char *verStr( parseField(line) );
- if (!verStr) continue;
- int protVer = (time_t) strtoul(verStr, 0, 10);
- const char *name( parseField(line) );
- bool keepQuotes = false;
- bool secure = false;
- bool httpOnly = false;
- bool explicitPath = false;
- const char *value = 0;
- if ((version == 2) || (protVer >= 200))
- {
- if (protVer >= 200)
- protVer -= 200;
- int i = atoi( parseField(line) );
- secure = i & 1;
- httpOnly = i & 2;
- explicitPath = i & 4;
- if (i & 8)
- name = "";
- line[strlen(line)-1] = '\0'; // Strip LF.
- value = line;
- }
- else
- {
- if (protVer >= 100)
- {
- protVer -= 100;
- keepQuotes = true;
- }
- value = parseField(line, keepQuotes);
- secure = atoi( parseField(line) );
- }
-
- // Parse error
- if (!value) continue;
-
- // Expired or parse error
- if ((expDate == 0) || (expDate < curTime))
- continue;
-
- KHttpCookie *cookie = new KHttpCookie(TQString::fromLatin1(host),
- TQString::fromLatin1(domain),
- TQString::fromLatin1(path),
- TQString::fromLatin1(name),
- TQString::fromLatin1(value),
- expDate, protVer,
- secure, httpOnly, explicitPath);
- addCookie(cookie);
- }
- }
- delete [] buffer;
- m_cookiesChanged = false;
-
- fclose( fStream);
- return err;
-}
-
-//
-// Save the cookie configuration
-//
-
-void KCookieJar::saveConfig(TDEConfig *_config)
-{
- if (!m_configChanged)
- return;
-
- _config->setGroup("Cookie Dialog");
- _config->writeEntry("PreferredPolicy", m_preferredPolicy);
- _config->writeEntry("ShowCookieDetails", m_showCookieDetails );
- _config->setGroup("Cookie Policy");
- _config->writeEntry("CookieGlobalAdvice", adviceToStr( m_globalAdvice));
-
- TQStringList domainSettings;
- for ( TQStringList::Iterator it=m_domainList.begin();
- it != m_domainList.end();
- it++ )
- {
- const TQString &domain = *it;
- KCookieAdvice advice = getDomainAdvice( domain);
- if (advice != KCookieDunno)
- {
- TQString value(domain);
- value += ':';
- value += adviceToStr(advice);
- domainSettings.append(value);
- }
- }
- _config->writeEntry("CookieDomainAdvice", domainSettings);
- _config->sync();
- m_configChanged = false;
-}
-
-
-//
-// Load the cookie configuration
-//
-
-void KCookieJar::loadConfig(TDEConfig *_config, bool reparse )
-{
- if ( reparse )
- _config->reparseConfiguration();
-
- _config->setGroup("Cookie Dialog");
- m_showCookieDetails = _config->readBoolEntry( "ShowCookieDetails" );
- m_preferredPolicy = _config->readNumEntry( "PreferredPolicy", 0 );
-
- _config->setGroup("Cookie Policy");
- TQStringList domainSettings = _config->readListEntry("CookieDomainAdvice");
- m_rejectCrossDomainCookies = _config->readBoolEntry( "RejectCrossDomainCookies", true );
- m_autoAcceptSessionCookies = _config->readBoolEntry( "AcceptSessionCookies", true );
- m_ignoreCookieExpirationDate = _config->readBoolEntry( "IgnoreExpirationDate", false );
- TQString value = _config->readEntry("CookieGlobalAdvice", L1("Ask"));
- m_globalAdvice = strToAdvice(value);
-
- // Reset current domain settings first.
- for ( TQStringList::Iterator it=m_domainList.begin(); it != m_domainList.end(); )
- {
- // Make sure to update iterator before calling setDomainAdvice()
- // setDomainAdvice() might delete the domain from domainList.
- TQString domain = *it++;
- setDomainAdvice(domain, KCookieDunno);
- }
-
- // Now apply the domain settings read from config file...
- for ( TQStringList::Iterator it=domainSettings.begin();
- it != domainSettings.end(); )
- {
- const TQString &value = *it++;
-
- int sepPos = value.findRev(':');
-
- if (sepPos <= 0)
- continue;
-
- TQString domain(value.left(sepPos));
- KCookieAdvice advice = strToAdvice( value.mid(sepPos + 1) );
- setDomainAdvice(domain, advice);
- }
-}
diff --git a/kioslave/http/kcookiejar/kcookieserver.cpp b/kioslave/http/kcookiejar/kcookieserver.cpp
deleted file mode 100644
index 94df40b63..000000000
--- a/kioslave/http/kcookiejar/kcookieserver.cpp
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
-This file is part of KDE
-
- Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-//----------------------------------------------------------------------------
-//
-// KDE Cookie Server
-// $Id$
-
-#define SAVE_DELAY 3 // Save after 3 minutes
-
-#include <unistd.h>
-
-#include <tqtimer.h>
-#include <tqptrlist.h>
-#include <tqfile.h>
-
-#include <dcopclient.h>
-
-#include <kconfig.h>
-#include <kdebug.h>
-#include <kapplication.h>
-#include <kcmdlineargs.h>
-#include <kstandarddirs.h>
-
-#include "kcookiejar.h"
-#include "kcookiewin.h"
-#include "kcookieserver.h"
-
-extern "C" {
- KDE_EXPORT KDEDModule *create_kcookiejar(const TQCString &name)
- {
- return new KCookieServer(name);
- }
-}
-
-
-// Cookie field indexes
-enum CookieDetails { CF_DOMAIN=0, CF_PATH, CF_NAME, CF_HOST,
- CF_VALUE, CF_EXPIRE, CF_PROVER, CF_SECURE };
-
-
-class CookieRequest {
-public:
- DCOPClient *client;
- DCOPClientTransaction *transaction;
- TQString url;
- bool DOM;
- long windowId;
-};
-
-template class TQPtrList<CookieRequest>;
-
-class RequestList : public TQPtrList<CookieRequest>
-{
-public:
- RequestList() : TQPtrList<CookieRequest>() { }
-};
-
-KCookieServer::KCookieServer(const TQCString &name)
- :KDEDModule(name)
-{
- mOldCookieServer = new DCOPClient(); // backwards compatibility.
- mOldCookieServer->registerAs("kcookiejar", false);
- mOldCookieServer->setDaemonMode( true );
- mCookieJar = new KCookieJar;
- mPendingCookies = new KHttpCookieList;
- mPendingCookies->setAutoDelete(true);
- mRequestList = new RequestList;
- mAdvicePending = false;
- mTimer = new TQTimer();
- connect( mTimer, TQT_SIGNAL( timeout()), TQT_SLOT( slotSave()));
- mConfig = new TDEConfig("kcookiejarrc");
- mCookieJar->loadConfig( mConfig );
-
- TQString filename = locateLocal("data", "kcookiejar/cookies");
-
- // Stay backwards compatible!
- TQString filenameOld = locate("data", "kfm/cookies");
- if (!filenameOld.isEmpty())
- {
- mCookieJar->loadCookies( filenameOld );
- if (mCookieJar->saveCookies( filename))
- {
- unlink(TQFile::encodeName(filenameOld)); // Remove old kfm cookie file
- }
- }
- else
- {
- mCookieJar->loadCookies( filename);
- }
- connect(this, TQT_SIGNAL(windowUnregistered(long)),
- this, TQT_SLOT(slotDeleteSessionCookies(long)));
-}
-
-KCookieServer::~KCookieServer()
-{
- if (mCookieJar->changed())
- slotSave();
- delete mOldCookieServer;
- delete mCookieJar;
- delete mTimer;
- delete mPendingCookies;
- delete mConfig;
-}
-
-bool KCookieServer::cookiesPending( const TQString &url, KHttpCookieList *cookieList )
-{
- TQString fqdn;
- TQStringList domains;
- TQString path;
- // Check whether 'url' has cookies on the pending list
- if (mPendingCookies->isEmpty())
- return false;
- if (!KCookieJar::parseURL(url, fqdn, path))
- return false;
-
- mCookieJar->extractDomains( fqdn, domains );
- for( KHttpCookie *cookie = mPendingCookies->first();
- cookie != 0L;
- cookie = mPendingCookies->next())
- {
- if (cookie->match( fqdn, domains, path))
- {
- if (!cookieList)
- return true;
- cookieList->append(cookie);
- }
- }
- if (!cookieList)
- return false;
- return cookieList->isEmpty();
-}
-
-void KCookieServer::addCookies( const TQString &url, const TQCString &cookieHeader,
- long windowId, bool useDOMFormat )
-{
- KHttpCookieList cookieList;
- if (useDOMFormat)
- cookieList = mCookieJar->makeDOMCookies(url, cookieHeader, windowId);
- else
- cookieList = mCookieJar->makeCookies(url, cookieHeader, windowId);
-
- checkCookies(&cookieList);
-
- for(KHttpCookiePtr cookie = cookieList.first(); cookie; cookie = cookieList.first())
- mPendingCookies->append(cookieList.take());
-
- if (!mAdvicePending)
- {
- mAdvicePending = true;
- while (!mPendingCookies->isEmpty())
- {
- checkCookies(0);
- }
- mAdvicePending = false;
- }
-}
-
-void KCookieServer::checkCookies( KHttpCookieList *cookieList)
-{
- KHttpCookieList *list;
-
- if (cookieList)
- list = cookieList;
- else
- list = mPendingCookies;
-
- KHttpCookiePtr cookie = list->first();
- while (cookie)
- {
- kdDebug(7104) << "checkCookies: Asking cookie advice for " << cookie->host() << endl;
- KCookieAdvice advice = mCookieJar->cookieAdvice(cookie);
- switch(advice)
- {
- case KCookieAccept:
- list->take();
- mCookieJar->addCookie(cookie);
- cookie = list->current();
- break;
-
- case KCookieReject:
- list->take();
- delete cookie;
- cookie = list->current();
- break;
-
- default:
- cookie = list->next();
- break;
- }
- }
-
- if (cookieList || list->isEmpty())
- return;
-
- KHttpCookiePtr currentCookie = mPendingCookies->first();
-
- KHttpCookieList currentList;
- currentList.append(currentCookie);
- TQString currentHost = currentCookie->host();
-
- cookie = mPendingCookies->next();
- while (cookie)
- {
- if (cookie->host() == currentHost)
- {
- currentList.append(cookie);
- }
- cookie = mPendingCookies->next();
- }
-
- KCookieWin *kw = new KCookieWin( 0L, currentList,
- mCookieJar->preferredDefaultPolicy(),
- mCookieJar->showCookieDetails() );
- KCookieAdvice userAdvice = kw->advice(mCookieJar, currentCookie);
- delete kw;
- // Save the cookie config if it has changed
- mCookieJar->saveConfig( mConfig );
-
- // Apply the user's choice to all cookies that are currently
- // queued for this host.
- cookie = mPendingCookies->first();
- while (cookie)
- {
- if (cookie->host() == currentHost)
- {
- switch(userAdvice)
- {
- case KCookieAccept:
- mPendingCookies->take();
- mCookieJar->addCookie(cookie);
- cookie = mPendingCookies->current();
- break;
-
- case KCookieReject:
- mPendingCookies->take();
- delete cookie;
- cookie = mPendingCookies->current();
- break;
-
- default:
- tqWarning(__FILE__":%d Problem!", __LINE__);
- cookie = mPendingCookies->next();
- break;
- }
- }
- else
- {
- cookie = mPendingCookies->next();
- }
- }
-
-
- // Check if we can handle any request
- for ( CookieRequest *request = mRequestList->first(); request;)
- {
- if (!cookiesPending( request->url ))
- {
- TQCString replyType;
- TQByteArray replyData;
- TQString res = mCookieJar->findCookies( request->url, request->DOM, request->windowId );
-
- TQDataStream stream2(replyData, IO_WriteOnly);
- stream2 << res;
- replyType = "TQString";
- request->client->endTransaction( request->transaction,
- replyType, replyData);
- CookieRequest *tmp = request;
- request = mRequestList->next();
- mRequestList->removeRef( tmp );
- delete tmp;
- }
- else
- {
- request = mRequestList->next();
- }
- }
- if (mCookieJar->changed())
- saveCookieJar();
-}
-
-void KCookieServer::slotSave()
-{
- TQString filename = locateLocal("data", "kcookiejar/cookies");
- mCookieJar->saveCookies(filename);
-}
-
-void KCookieServer::saveCookieJar()
-{
- if( mTimer->isActive() )
- return;
-
- mTimer->start( 1000*60*SAVE_DELAY, true );
-}
-
-void KCookieServer::putCookie( TQStringList& out, KHttpCookie *cookie,
- const TQValueList<int>& fields )
-{
- TQValueList<int>::ConstIterator i = fields.begin();
- for ( ; i != fields.end(); ++i )
- {
- switch(*i)
- {
- case CF_DOMAIN :
- out << cookie->domain();
- break;
- case CF_NAME :
- out << cookie->name();
- break;
- case CF_PATH :
- out << cookie->path();
- break;
- case CF_HOST :
- out << cookie->host();
- break;
- case CF_VALUE :
- out << cookie->value();
- break;
- case CF_EXPIRE :
- out << TQString::number(cookie->expireDate());
- break;
- case CF_PROVER :
- out << TQString::number(cookie->protocolVersion());
- break;
- case CF_SECURE :
- out << TQString::number( cookie->isSecure() ? 1 : 0 );
- break;
- default :
- out << TQString::null;
- }
- }
-}
-
-bool KCookieServer::cookieMatches( KHttpCookiePtr c,
- TQString domain, TQString fqdn,
- TQString path, TQString name )
-{
- if( c )
- {
- bool hasDomain = !domain.isEmpty();
- return
- ((hasDomain && c->domain() == domain) ||
- fqdn == c->host()) &&
- (c->path() == path) &&
- (c->name() == name) &&
- (!c->isExpired(time(0)));
- }
- return false;
-}
-
-// DCOP function
-TQString
-KCookieServer::findCookies(TQString url)
-{
- return findCookies(url, 0);
-}
-
-// DCOP function
-TQString
-KCookieServer::findCookies(TQString url, long windowId)
-{
- if (cookiesPending(url))
- {
- CookieRequest *request = new CookieRequest;
- request->client = callingDcopClient();
- request->transaction = request->client->beginTransaction();
- request->url = url;
- request->DOM = false;
- request->windowId = windowId;
- mRequestList->append( request );
- return TQString::null; // Talk to you later :-)
- }
-
- TQString cookies = mCookieJar->findCookies(url, false, windowId);
-
- if (mCookieJar->changed())
- saveCookieJar();
-
- return cookies;
-}
-
-// DCOP function
-TQStringList
-KCookieServer::findDomains()
-{
- TQStringList result;
- const TQStringList domains = mCookieJar->getDomainList();
- for ( TQStringList::ConstIterator domIt = domains.begin();
- domIt != domains.end(); ++domIt )
- {
- // Ignore domains that have policy set for but contain
- // no cookies whatsoever...
- const KHttpCookieList* list = mCookieJar->getCookieList(*domIt, "");
- if ( list && !list->isEmpty() )
- result << *domIt;
- }
- return result;
-}
-
-// DCOP function
-TQStringList
-KCookieServer::findCookies(TQValueList<int> fields,
- TQString domain,
- TQString fqdn,
- TQString path,
- TQString name)
-{
- TQStringList result;
- bool allDomCookies = name.isEmpty();
-
- const KHttpCookieList* list = mCookieJar->getCookieList(domain, fqdn);
- if ( list && !list->isEmpty() )
- {
- TQPtrListIterator<KHttpCookie>it( *list );
- for ( ; it.current(); ++it )
- {
- if ( !allDomCookies )
- {
- if ( cookieMatches(it.current(), domain, fqdn, path, name) )
- {
- putCookie(result, it.current(), fields);
- break;
- }
- }
- else
- putCookie(result, it.current(), fields);
- }
- }
- return result;
-}
-
-// DCOP function
-TQString
-KCookieServer::findDOMCookies(TQString url)
-{
- return findDOMCookies(url, 0);
-}
-
-// DCOP function
-TQString
-KCookieServer::findDOMCookies(TQString url, long windowId)
-{
- // We don't wait for pending cookies because it locks up konqueror
- // which can cause a deadlock if it happens to have a popup-menu up.
- // Instead we just return pending cookies as if they had been accepted already.
- KHttpCookieList pendingCookies;
- cookiesPending(url, &pendingCookies);
-
- return mCookieJar->findCookies(url, true, windowId, &pendingCookies);
-}
-
-// DCOP function
-void
-KCookieServer::addCookies(TQString arg1, TQCString arg2, long arg3)
-{
- addCookies(arg1, arg2, arg3, false);
-}
-
-// DCOP function
-void
-KCookieServer::deleteCookie(TQString domain, TQString fqdn,
- TQString path, TQString name)
-{
- const KHttpCookieList* list = mCookieJar->getCookieList( domain, fqdn );
- if ( list && !list->isEmpty() )
- {
- TQPtrListIterator<KHttpCookie>it (*list);
- for ( ; it.current(); ++it )
- {
- if( cookieMatches(it.current(), domain, fqdn, path, name) )
- {
- mCookieJar->eatCookie( it.current() );
- saveCookieJar();
- break;
- }
- }
- }
-}
-
-// DCOP function
-void
-KCookieServer::deleteCookiesFromDomain(TQString domain)
-{
- mCookieJar->eatCookiesForDomain(domain);
- saveCookieJar();
-}
-
-
-// Qt function
-void
-KCookieServer::slotDeleteSessionCookies( long windowId )
-{
- deleteSessionCookies(windowId);
-}
-
-// DCOP function
-void
-KCookieServer::deleteSessionCookies( long windowId )
-{
- mCookieJar->eatSessionCookies( windowId );
- saveCookieJar();
-}
-
-void
-KCookieServer::deleteSessionCookiesFor(TQString fqdn, long windowId)
-{
- mCookieJar->eatSessionCookies( fqdn, windowId );
- saveCookieJar();
-}
-
-// DCOP function
-void
-KCookieServer::deleteAllCookies()
-{
- mCookieJar->eatAllCookies();
- saveCookieJar();
-}
-
-// DCOP function
-void
-KCookieServer::addDOMCookies(TQString arg1, TQCString arg2, long arg3)
-{
- addCookies(arg1, arg2, arg3, true);
-}
-
-// DCOP function
-void
-KCookieServer::setDomainAdvice(TQString url, TQString advice)
-{
- TQString fqdn;
- TQString dummy;
- if (KCookieJar::parseURL(url, fqdn, dummy))
- {
- TQStringList domains;
- mCookieJar->extractDomains(fqdn, domains);
-
- mCookieJar->setDomainAdvice(domains[domains.count() > 3 ? 3 : 0],
- KCookieJar::strToAdvice(advice));
- // Save the cookie config if it has changed
- mCookieJar->saveConfig( mConfig );
- }
-}
-
-// DCOP function
-TQString
-KCookieServer::getDomainAdvice(TQString url)
-{
- KCookieAdvice advice = KCookieDunno;
- TQString fqdn;
- TQString dummy;
- if (KCookieJar::parseURL(url, fqdn, dummy))
- {
- TQStringList domains;
- mCookieJar->extractDomains(fqdn, domains);
-
- TQStringList::ConstIterator it = domains.begin();
- while ( (advice == KCookieDunno) && (it != domains.end()) )
- {
- // Always check advice in both ".domain" and "domain". Note
- // that we only want to check "domain" if it matches the
- // fqdn of the requested URL.
- if ( (*it)[0] == '.' || (*it) == fqdn )
- advice = mCookieJar->getDomainAdvice(*it);
- ++it;
- }
- if (advice == KCookieDunno)
- advice = mCookieJar->getGlobalAdvice();
- }
- return KCookieJar::adviceToStr(advice);
-}
-
-// DCOP function
-void
-KCookieServer::reloadPolicy()
-{
- mCookieJar->loadConfig( mConfig, true );
-}
-
-// DCOP function
-void
-KCookieServer::shutdown()
-{
- deleteLater();
-}
-
-#include "kcookieserver.moc"
-
diff --git a/kioslave/http/kcookiejar/tests/Makefile.am b/kioslave/http/kcookiejar/tests/Makefile.am
deleted file mode 100644
index 4059cdcd1..000000000
--- a/kioslave/http/kcookiejar/tests/Makefile.am
+++ /dev/null
@@ -1,18 +0,0 @@
-# $Id$
-# Makefile.am of tdebase/kioslave/http
-
-INCLUDES= $(all_includes)
-
-####### Files
-
-check_PROGRAMS = kcookiejartest
-
-kcookiejartest_SOURCES = kcookiejartest.cpp
-kcookiejartest_LDADD = $(LIB_KIO)
-kcookiejartest_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-
-check-local: kcookiejartest
- ./kcookiejartest $(srcdir)/cookie.test
- ./kcookiejartest $(srcdir)/cookie_rfc.test
- ./kcookiejartest $(srcdir)/cookie_saving.test
- ./kcookiejartest $(srcdir)/cookie_settings.test
diff --git a/kioslave/http/webdav.protocol b/kioslave/http/webdav.protocol
deleted file mode 100644
index f4f4df462..000000000
--- a/kioslave/http/webdav.protocol
+++ /dev/null
@@ -1,18 +0,0 @@
-[Protocol]
-exec=kio_http
-protocol=webdav
-input=none
-output=filesystem
-listing=Name,Type,Size,Date,AccessDate,Access
-reading=true
-writing=true
-makedir=true
-deleting=true
-moving=true
-deleteRecursive=true
-defaultMimetype=application/octet-stream
-determineMimetypeFromExtension=false
-Icon=www
-maxInstances=3
-DocPath=kioslave/webdav.html
-Class=:internet
diff --git a/kioslave/http/webdavs.protocol b/kioslave/http/webdavs.protocol
deleted file mode 100644
index c8b7cba3f..000000000
--- a/kioslave/http/webdavs.protocol
+++ /dev/null
@@ -1,18 +0,0 @@
-[Protocol]
-exec=kio_http
-protocol=webdavs
-input=none
-output=filesystem
-listing=Name,Type,Size,Date,AccessDate,Access
-reading=true
-writing=true
-makedir=true
-deleting=true
-moving=true
-deleteRecursive=true
-defaultMimetype=application/octet-stream
-determineMimetypeFromExtension=false
-Icon=www
-config=webdav
-DocPath=kioslave/webdavs.html
-Class=:internet
diff --git a/kioslave/iso/CMakeLists.txt b/kioslave/iso/CMakeLists.txt
deleted file mode 100644
index da6315b77..000000000
--- a/kioslave/iso/CMakeLists.txt
+++ /dev/null
@@ -1,51 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-add_subdirectory( libisofs )
-
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}
- ${CMAKE_CURRENT_SOURCE_DIR}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install( FILES iso.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
-install( FILES isoservice.desktop DESTINATION ${DATA_INSTALL_DIR}/konqueror/servicemenus )
-install( FILES kio_isorc DESTINATION ${CONFIG_INSTALL_DIR} )
-install( FILES kio_iso.desktop DESTINATION ${APPS_INSTALL_DIR} )
-
-
-##### kio_iso ###################################
-
-set( target kio_iso )
-
-set( ${target}_SRCS
- kisodirectory.cpp kisofile.cpp qfilehack.cpp
- kiso.cpp iso.cpp
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK isofs-static kio-shared
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kioslave/iso/Makefile.am b/kioslave/iso/Makefile.am
deleted file mode 100644
index f9c0bb754..000000000
--- a/kioslave/iso/Makefile.am
+++ /dev/null
@@ -1,67 +0,0 @@
-kde_module_LTLIBRARIES = kio_iso.la
-
-
-INCLUDES = $(all_includes)
-
-
-#LDFLAGS =
-
-kio_iso_la_METASOURCES=AUTO
-
-kio_iso_la_SOURCES = kisodirectory.cpp kisofile.cpp qfilehack.cpp kiso.cpp iso.cpp
-kio_iso_la_LIBADD = libisofs/libisofs.la $(LIB_QT) $(LIB_TDECORE) $(LIB_KIO)
-
-kio_iso_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
-
-
-SUBDIRS = libisofs
-
-noinst_HEADERS = iso.h kiso.h qfilehack.h kisofile.h kisodirectory.h
-EXTRA_DIST = iso.protocol isoservice.desktop kio_iso.desktop
-
-install-data-local:
- $(mkinstalldirs) $(DESTDIR)$(kde_servicesdir)/
- $(INSTALL_DATA) $(srcdir)/iso.protocol $(DESTDIR)$(kde_servicesdir)/iso.protocol
- $(mkinstalldirs) $(DESTDIR)$(kde_datadir)/konqueror/servicemenus/
- $(INSTALL_DATA) $(srcdir)/isoservice.desktop $(DESTDIR)$(kde_datadir)/konqueror/servicemenus/isoservice.desktop
- $(mkinstalldirs) $(DESTDIR)$(kde_confdir)/
- $(INSTALL_DATA) $(srcdir)/kio_isorc $(DESTDIR)$(kde_confdir)/kio_isorc
- $(mkinstalldirs) $(DESTDIR)$(kde_appsdir)/
- $(INSTALL_DATA) $(srcdir)/kio_iso.desktop $(DESTDIR)$(kde_appsdir)/kio_iso.desktop
-
-uninstall-local:
- -rm -f $(DESTDIR)$(kde_servicesdir)/iso.protocol
- -rm -f $(DESTDIR)$(kde_datadir)/konqueror/servicemenus/isoservice.desktop
- -rm -f $(DESTDIR)$(kde_confdir)/kio_isorc
- -rm -f $(DESTDIR)$(kde_appsdir)/kio_iso.desktop
-
-# These paths are KDE specific. Use them:
-# kde_appsdir Where your application's menu entry (.desktop) should go to.
-# kde_icondir Where your icon should go to - better use KDE_ICON.
-# kde_sounddir Where your sounds should go to.
-# kde_htmldir Where your docs should go to. (contains lang subdirs)
-# kde_datadir Where you install application data. (Use a subdir)
-# kde_locale Where translation files should go to. (contains lang subdirs)
-# kde_cgidir Where cgi-bin executables should go to.
-# kde_confdir Where config files should go to (system-wide ones with default values).
-# kde_mimedir Where mimetypes .desktop files should go to.
-# kde_servicesdir Where services .desktop files should go to.
-# kde_servicetypesdir Where servicetypes .desktop files should go to.
-# kde_toolbardir Where general toolbar icons should go to (deprecated, use KDE_ICON).
-# kde_wallpaperdir Where general wallpapers should go to.
-# kde_templatesdir Where templates for the "New" menu (Konqueror/KDesktop) should go to.
-# kde_bindir Where executables should go to. Use bin_PROGRAMS or bin_SCRIPTS.
-# kde_libdir Where shared libraries should go to. Use lib_LTLIBRARIES.
-# kde_moduledir Where modules (e.g. parts) should go to. Use kde_module_LTLIBRARIES.
-# kde_styledir Where Qt/KDE widget styles should go to (new in KDE 3).
-# kde_designerdir Where Qt Designer plugins should go to (new in KDE 3).
-
-
-# make messages.po. Move this one to ../po/ and "make merge" in po
-# the -x is for skipping messages already translated in tdelibs
-messages:
- LIST=`find . -name \*.h -o -name \*.hh -o -name \*.H -o -name \*.hxx -o -name \*.hpp -o -name \*.cpp -o -name \*.cc -o -name \*.cxx -o -name \*.ecpp -o -name \*.C`; \
- if test -n "$$LIST"; then \
- $(XGETTEXT) -C -ki18n -x $(kde_includes)/kde.pot $$LIST -o ../po/iso.pot; \
- fi
-
diff --git a/kioslave/iso/iso.h b/kioslave/iso/iso.h
deleted file mode 100644
index 136c32736..000000000
--- a/kioslave/iso/iso.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/***************************************************************************
- iso.h
- -------------------
- begin : Oct 25 2002
- copyright : (C) 2002 by Szombathelyi György
- email : gyurco@users.sourceforge.net
- ***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 file is heavily based on tar.h from tdebase
- * (c) David Faure <faure@kde.org>
- */
-
-#ifndef _ISO_H
-#define _ISO_H
-
-#include <kio/slavebase.h>
-#include <sys/types.h>
-#include "kisofile.h"
-
-class KIso;
-
-class kio_isoProtocol : public TDEIO::SlaveBase
-{
-public:
- kio_isoProtocol( const TQCString &pool, const TQCString &app );
- virtual ~kio_isoProtocol();
-
- virtual void listDir( const KURL & url );
- virtual void stat( const KURL & url );
- virtual void get( const KURL & url );
-
-protected:
- void getFile( const KIsoFile *isoFileEntry, const TQString &path );
- void createUDSEntry( const KArchiveEntry * isoEntry, TDEIO::UDSEntry & entry );
- bool checkNewFile( TQString fullPath, TQString & path, int startsec );
-
- KIso * m_isoFile;
- time_t m_mtime;
- int m_mode;
-};
-
-#endif
diff --git a/kioslave/iso/iso.protocol b/kioslave/iso/iso.protocol
deleted file mode 100644
index 0e7d71b64..000000000
--- a/kioslave/iso/iso.protocol
+++ /dev/null
@@ -1,11 +0,0 @@
-[Protocol]
-exec=kio_iso
-protocol=iso
-listing=Name,Type,Size,Date,AccessDate,CreationDate,Access,Owner,Group,Link
-input=filesystem
-output=filesystem
-reading=true
-source=true
-Icon=cd
-Description=A kioslave for ISO9660 filesystems
-MimeType=application/x-iso
diff --git a/kioslave/iso/kiso.cpp b/kioslave/iso/kiso.cpp
deleted file mode 100644
index b19ec589b..000000000
--- a/kioslave/iso/kiso.cpp
+++ /dev/null
@@ -1,460 +0,0 @@
-/***************************************************************************
- kiso.cpp
- -------------------
- begin : Oct 25 2002
- copyright : (C) 2002 by Szombathelyi Gy�gy
- email : gyurco@users.sourceforge.net
- ***************************************************************************/
-
-/***************************************************************************
- * *
- * 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 file is heavily based on ktar.cpp from tdelibs (c) David Faure */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-#include <unistd.h>
-#include <grp.h>
-#include <pwd.h>
-#include <assert.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <tqcstring.h>
-#include <tqdir.h>
-#include <tqfile.h>
-#include <kdebug.h>
-#include <kurl.h>
-#include <kmimetype.h>
-#include <kconfig.h>
-#include <kfilterdev.h>
-#include <kfilterbase.h>
-
-#include "kiso.h"
-#include "libisofs/isofs.h"
-#include "qfilehack.h"
-
-
-#ifdef __linux__
-#undef __STRICT_ANSI__
-#include <linux/cdrom.h>
-#define __STRICT_ANSI__
-#include <sys/ioctl.h>
-#include <fcntl.h>
-#endif
-
-////////////////////////////////////////////////////////////////////////
-/////////////////////////// KIso ///////////////////////////////////
-////////////////////////////////////////////////////////////////////////
-
-/**
- * puts the track layout of the device 'fname' into 'tracks'
- * tracks structure: start sector, track number, ...
- * tracks should be 100*2 entry long (this is the maximum in the CD-ROM standard)
- * currently it's linux only, porters are welcome
- */
-static int getTracks(const char *fname,int *tracks) {
- int ret=0;
- memset(tracks,0,200*sizeof(int));
-
-#ifdef __linux__
- int fd,i;
- struct cdrom_tochdr tochead;
- struct cdrom_tocentry tocentry;
-
- kdDebug() << "getTracks open:" << fname << endl;
- fd=open(fname, O_RDONLY | O_NONBLOCK);
- if (fd > 0) {
- if (ioctl(fd,CDROMREADTOCHDR,&tochead)!=-1) {
- kdDebug() << "getTracks first track:" << tochead.cdth_trk0
- << " last track " << tochead.cdth_trk1 << endl;
- for (i=tochead.cdth_trk0;i<=tochead.cdth_trk1;i++) {
- if (ret>99) break;
- memset(&tocentry,0,sizeof(struct cdrom_tocentry));
- tocentry.cdte_track=i;
- tocentry.cdte_format=CDROM_LBA;
- if (ioctl(fd,CDROMREADTOCENTRY,&tocentry)<0) break;
- kdDebug() << "getTracks got track " << i << " starting at: " <<
- tocentry.cdte_addr.lba << endl;
- if ((tocentry.cdte_ctrl & 0x4) == 0x4) {
- tracks[ret<<1]=tocentry.cdte_addr.lba;
- tracks[(ret<<1)+1]=i;
- ret++;
- }
- }
- }
- close(fd);
- }
-
-#endif
-
- return ret;
-}
-
-class KIso::KIsoPrivate
-{
-public:
- KIsoPrivate() {}
- TQStringList dirList;
-};
-
-KIso::KIso( const TQString& filename, const TQString & _mimetype )
- : KArchive( 0L )
-{
- m_startsec = -1;
- m_filename = filename;
- d = new KIsoPrivate;
- TQString mimetype( _mimetype );
- bool forced = true;
- if ( mimetype.isEmpty() )
- {
- mimetype = KMimeType::findByFileContent( filename )->name();
- kdDebug() << "KIso::KIso mimetype=" << mimetype << endl;
-
- // Don't move to prepareDevice - the other constructor theoretically allows ANY filter
- if ( mimetype == "application/x-tgz" || mimetype == "application/x-targz" || // the latter is deprecated but might still be around
- mimetype == "application/x-webarchive" )
- // that's a gzipped tar file, so ask for gzip filter
- mimetype = "application/x-gzip";
- else if ( mimetype == "application/x-tbz" ) // that's a bzipped2 tar file, so ask for bz2 filter
- mimetype = "application/x-bzip2";
- else
- {
- // Something else. Check if it's not really gzip though (e.g. for KOffice docs)
- TQFile file( filename );
- if ( file.open( IO_ReadOnly ) )
- {
- unsigned char firstByte = file.getch();
- unsigned char secondByte = file.getch();
- unsigned char thirdByte = file.getch();
- if ( firstByte == 0037 && secondByte == 0213 )
- mimetype = "application/x-gzip";
- else if ( firstByte == 'B' && secondByte == 'Z' && thirdByte == 'h' )
- mimetype = "application/x-bzip2";
- else if ( firstByte == 'P' && secondByte == 'K' && thirdByte == 3 )
- {
- unsigned char fourthByte = file.getch();
- if ( fourthByte == 4 )
- mimetype = "application/x-zip";
- }
- }
- }
- forced = false;
- }
-
- prepareDevice( filename, mimetype, forced );
-}
-
-void KIso::prepareDevice( const TQString & filename,
- const TQString & mimetype, bool forced )
-{
- /* 'hack' for Qt's false assumption that only S_ISREG is seekable */
- if( "inode/blockdevice" == mimetype )
- setDevice( TQT_TQIODEVICE(new QFileHack( filename )) );
- else
- {
- if( "application/x-gzip" == mimetype
- || "application/x-bzip2" == mimetype)
- forced = true;
-
- TQIODevice *dev = KFilterDev::deviceForFile( filename, mimetype, forced );
- if( dev )
- setDevice( dev );
- }
-
-}
-
-KIso::KIso( TQIODevice * dev )
- : KArchive( dev )
-{
- d = new KIsoPrivate;
-}
-
-KIso::~KIso()
-{
- // mjarrett: Closes to prevent ~KArchive from aborting w/o device
- if( isOpened() )
- close();
- if ( !m_filename.isEmpty() )
- delete device(); // we created it ourselves
- delete d;
-}
-
-/* callback function for libisofs */
-static int readf(char *buf, long long start, long long len,void *udata) {
-
- TQIODevice* dev = ( static_cast<KIso*> (udata) )->device();
-
- if (dev->at(start<<11)) {
- if ((dev->readBlock(buf, len<<11)) != -1) return (len);
- }
- kdDebug() << "KIso::ReadRequest failed start: " << start << " len: " << len << endl;
-
- return -1;
-}
-
-/* callback function for libisofs */
-static int mycallb(struct iso_directory_record *idr,void *udata) {
-
- KIso *iso = static_cast<KIso*> (udata);
- TQString path,user,group,symlink;
- int i;
- int access;
- int time,cdate,adate;
- rr_entry rr;
- bool special=false;
- KArchiveEntry *entry=NULL,*oldentry=NULL;
- char z_algo[2],z_params[2];
- long long z_size=0;
-
- if ((idr->flags[0] & 1) && !iso->showhidden) return 0;
- if (iso->level) {
- if (isonum_711(idr->name_len)==1) {
- switch (idr->name[0]) {
- case 0:
- path+=(".");
- special=true;
- break;
- case 1:
- path+=("..");
- special=true;
- break;
- }
- }
- if (iso->showrr && ParseRR(idr,&rr)>0) {
- if (!special) path=rr.name;
- symlink=rr.sl;
- access=rr.mode;
- time=rr.t_mtime;
- adate=rr.t_atime;
- cdate=rr.t_ctime;
- user.setNum(rr.uid);
- group.setNum(rr.gid);
- z_algo[0]=rr.z_algo[0];z_algo[1]=rr.z_algo[1];
- z_params[0]=rr.z_params[0];z_params[1]=rr.z_params[1];
- z_size=rr.z_size;
- } else {
- access=iso->dirent->permissions() & ~S_IFMT;
- adate=cdate=time=isodate_915(idr->date,0);
- user=iso->dirent->user();
- group=iso->dirent->group();
- if (idr->flags[0] & 2) access |= S_IFDIR; else access |= S_IFREG;
- if (!special) {
- if (iso->joliet) {
- for (i=0;i<(isonum_711(idr->name_len)-1);i+=2) {
- TQChar ch( be2me_16(*((ushort*)&(idr->name[i]))) );
- if (ch==';') break;
- path+=ch;
- }
- } else {
- for (i=0;i<isonum_711(idr->name_len);i++) {
- if (idr->name[i]==';') break;
- if (idr->name[i]) path+=(idr->name[i]);
- }
- }
- if (path.endsWith(".")) path.setLength(path.length()-1);
- }
- }
- if (iso->showrr) FreeRR(&rr);
- if (idr->flags[0] & 2) {
- entry = new KIsoDirectory( iso, path, access | S_IFDIR, time, adate, cdate,
- user, group, symlink );
- } else {
- entry = new KIsoFile( iso, path, access, time, adate, cdate,
- user, group, symlink, isonum_733(idr->extent)<<11,isonum_733(idr->size) );
- if (z_size) (static_cast <KIsoFile*> (entry))->setZF(z_algo,z_params,z_size);
-
- }
- iso->dirent->addEntry(entry);
- }
- if ( (idr->flags[0] & 2) && (iso->level==0 || !special) ) {
- if (iso->level) {
- oldentry=iso->dirent;
- iso->dirent=static_cast<KIsoDirectory*> (entry);
- }
- iso->level++;
- ProcessDir(&readf,isonum_733(idr->extent),isonum_733(idr->size),&mycallb,udata);
- iso->level--;
- if (iso->level) iso->dirent=static_cast<KIsoDirectory*> (oldentry);
- }
- return 0;
-}
-
-void KIso::addBoot(struct el_torito_boot_descriptor* bootdesc) {
-
- int i;
- long long size;
- boot_head boot;
- boot_entry *be;
- TQString path;
- KIsoFile *entry;
-
- entry=new KIsoFile( this, "Catalog", dirent->permissions() & ~S_IFDIR,
- dirent->date(), dirent->adate(), dirent->cdate(),
- dirent->user(), dirent->group(), TQString::null,
- isonum_731(bootdesc->boot_catalog)<<11, 2048 );
- dirent->addEntry(entry);
- if (!ReadBootTable(&readf,isonum_731(bootdesc->boot_catalog),&boot,this)) {
- i=1;
- be=boot.defentry;
- while (be) {
- size=BootImageSize( isonum_711((reinterpret_cast<struct default_entry*>(be->data))->media),
- isonum_721((reinterpret_cast<struct default_entry*>(be->data))->seccount));
- path="Default Image";
- if (i>1) path += " (" + TQString::number(i) + ")";
- entry=new KIsoFile( this, path, dirent->permissions() & ~S_IFDIR,
- dirent->date(), dirent->adate(), dirent->cdate(),
- dirent->user(), dirent->group(), TQString::null,
- isonum_731((reinterpret_cast<struct default_entry*>(be->data))->start)<<11, size<<9 );
- dirent->addEntry(entry);
- be=be->next;
- i++;
- }
-
- FreeBootTable(&boot);
- }
-}
-
-void KIso::readParams()
-{
- TDEConfig *config;
-
- config = new TDEConfig("kio_isorc");
-
- showhidden=config->readBoolEntry("showhidden",false);
- showrr=config->readBoolEntry("showrr",true);
- delete config;
-}
-
-bool KIso::openArchive( int mode )
-{
- iso_vol_desc *desc;
- TQString path,tmp,uid,gid;
- struct stat buf;
- int tracks[2*100],trackno=0,i,access,c_b,c_i,c_j;
- KArchiveDirectory *root;
- struct iso_directory_record* idr;
- struct el_torito_boot_descriptor* bootdesc;
-
- if ( mode == IO_WriteOnly )
- return false;
-
- readParams();
- d->dirList.clear();
-
- tracks[0]=0;
- if (m_startsec>0) tracks[0]=m_startsec;
- kdDebug() << " m_startsec: " << m_startsec << endl;
- /* We'll use the permission and user/group of the 'host' file except
- * in Rock Ridge, where the permissions are stored on the file system
- */
- if (::stat( m_filename.local8Bit(), &buf )<0) {
- /* defaults, if stat fails */
- memset(&buf,0,sizeof(struct stat));
- buf.st_mode=0777;
- } else {
- /* If it's a block device, try to query the track layout (for multisession) */
- if (m_startsec == -1 && S_ISBLK(buf.st_mode))
- trackno=getTracks(m_filename.latin1(),(int*) &tracks);
- }
- uid.setNum(buf.st_uid);
- gid.setNum(buf.st_gid);
- access = buf.st_mode & ~S_IFMT;
-
- kdDebug() << "KIso::openArchive number of tracks: " << trackno << endl;
-
- if (trackno==0) trackno=1;
- for (i=0;i<trackno;i++) {
-
- c_b=1;c_i=1;c_j=1;
- root=rootDir();
- if (trackno>1) {
- path=TQString::null;
- TQTextOStream(&path) << "Track " << tracks[(i<<1)+1];
- root = new KIsoDirectory( this, path, access | S_IFDIR,
- buf.st_mtime, buf.st_atime, buf.st_ctime, uid, gid, TQString::null );
- rootDir()->addEntry(root);
- }
-
- desc=ReadISO9660(&readf,tracks[i<<1],this);
- if (!desc) {
- kdDebug() << "KIso::openArchive no volume descriptors" << endl;
- continue;
- }
-
- while (desc) {
- switch (isonum_711(desc->data.type)) {
- case ISO_VD_BOOT:
-
- bootdesc=(struct el_torito_boot_descriptor*) &(desc->data);
- if ( !memcmp(EL_TORITO_ID,bootdesc->system_id,ISODCL(8,39)) ) {
- path="El Torito Boot";
- if (c_b>1) path += " (" + TQString::number(c_b) + ")";
-
- dirent = new KIsoDirectory( this, path, access | S_IFDIR,
- buf.st_mtime, buf.st_atime, buf.st_ctime, uid, gid, TQString::null );
- root->addEntry(dirent);
-
- addBoot(bootdesc);
- c_b++;
- }
- break;
-
- case ISO_VD_PRIMARY:
- case ISO_VD_SUPPLEMENTARY:
- idr=(struct iso_directory_record*) &( ((struct iso_primary_descriptor*) &desc->data)->root_directory_record);
- joliet = JolietLevel(&desc->data);
- if (joliet) {
- TQTextOStream(&path) << "Joliet level " << joliet;
- if (c_j>1) path += " (" + TQString::number(c_j) + ")";
- } else {
- path = "ISO9660";
- if (c_i>1) path += " (" + TQString::number(c_i) + ")";
- }
- dirent = new KIsoDirectory( this, path, access | S_IFDIR,
- buf.st_mtime, buf.st_atime, buf.st_ctime, uid, gid, TQString::null );
- root->addEntry(dirent);
- level=0;
- mycallb(idr, this );
- if (joliet) c_j++; else c_i++;
- break;
- }
- desc=desc->next;
- }
- free(desc);
- }
- device()->close();
- return true;
-}
-
-bool KIso::closeArchive()
-{
- d->dirList.clear();
- return true;
-}
-
-bool KIso::writeDir( const TQString&, const TQString&, const TQString& )
-{
- return false;
-}
-
-bool KIso::prepareWriting( const TQString&, const TQString&, const TQString&, uint)
-{
- return false;
-}
-
-bool KIso::doneWriting( uint )
-{
- return false;
-}
-
-void KIso::virtual_hook( int id, void* data )
-{ KArchive::virtual_hook( id, data ); }
-
diff --git a/kioslave/metainfo/CMakeLists.txt b/kioslave/metainfo/CMakeLists.txt
deleted file mode 100644
index 9c5fcdf20..000000000
--- a/kioslave/metainfo/CMakeLists.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/dcop
- ${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### other data ################################
-
-install( FILES metainfo.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
-
-
-##### kio_metainfo ##############################
-
-set( target kio_metainfo )
-
-set( ${target}_SRCS
- metainfo.cpp
-)
-
-tde_add_kpart( ${target} AUTOMOC
- SOURCES ${${target}_SRCS}
- LINK kio-shared
- DESTINATION ${PLUGIN_INSTALL_DIR}
-)
diff --git a/kioslave/metainfo/Makefile.am b/kioslave/metainfo/Makefile.am
deleted file mode 100644
index c1d1d295e..000000000
--- a/kioslave/metainfo/Makefile.am
+++ /dev/null
@@ -1,24 +0,0 @@
-## $Id$
-## Makefile.am of tdebase/kioslave/metainfo
-
-INCLUDES = $(all_includes)
-AM_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-METASOURCES = AUTO
-
-kde_module_LTLIBRARIES = kio_metainfo.la
-
-kio_metainfo_la_SOURCES = metainfo.cpp
-kio_metainfo_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE)
-kio_metainfo_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
-
-noinst_HEADERS = metainfo.h
-
-kdelnk_DATA = metainfo.protocol
-kdelnkdir = $(kde_servicesdir)
-
-#servicetypes_DATA = thumbcreator.desktop
-#servicetypesdir = $(kde_servicetypesdir)
-
-#services_DATA = imagethumbnail.desktop textthumbnail.desktop
-# htmlthumbnail.desktop gsthumbnail.desktop
-#servicesdir = $(kde_servicesdir)
diff --git a/kioslave/metainfo/metainfo.cpp b/kioslave/metainfo/metainfo.cpp
deleted file mode 100644
index 66e5357f9..000000000
--- a/kioslave/metainfo/metainfo.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Rolf Magnus <ramagnus@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation version 2.0
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#include <kdatastream.h> // Do not remove, needed for correct bool serialization
-#include <kurl.h>
-#include <kapplication.h>
-#include <kmimetype.h>
-#include <kdebug.h>
-#include <kfilemetainfo.h>
-#include <klocale.h>
-#include <stdlib.h>
-
-#include "metainfo.h"
-
-// Recognized metadata entries:
-// mimeType - the mime type of the file, so we need not extra determine it
-// what - what to load
-
-using namespace TDEIO;
-
-extern "C"
-{
- KDE_EXPORT int kdemain(int argc, char **argv);
-}
-
-int kdemain(int argc, char **argv)
-{
- TDEApplication app(argc, argv, "kio_metainfo", false, true);
-
- if (argc != 4)
- {
- kdError() << "Usage: kio_metainfo protocol domain-socket1 domain-socket2" << endl;
- exit(-1);
- }
-
- MetaInfoProtocol slave(argv[2], argv[3]);
- slave.dispatchLoop();
-
- return 0;
-}
-
-MetaInfoProtocol::MetaInfoProtocol(const TQCString &pool, const TQCString &app)
- : SlaveBase("metainfo", pool, app)
-{
-}
-
-MetaInfoProtocol::~MetaInfoProtocol()
-{
-}
-
-void MetaInfoProtocol::get(const KURL &url)
-{
- TQString mimeType = metaData("mimeType");
- KFileMetaInfo info(url.path(), mimeType);
-
- TQByteArray arr;
- TQDataStream stream(arr, IO_WriteOnly);
-
- stream << info;
-
- data(arr);
- finished();
-}
-
-void MetaInfoProtocol::put(const KURL& url, int, bool, bool)
-{
- TQString mimeType = metaData("mimeType");
- KFileMetaInfo info;
-
- TQByteArray arr;
- readData(arr);
- TQDataStream stream(arr, IO_ReadOnly);
-
- stream >> info;
-
- if (info.isValid())
- {
- info.applyChanges();
- }
- else
- {
- error(ERR_NO_CONTENT, i18n("No metainfo for %1").arg(url.path()));
- return;
- }
- finished();
-}
diff --git a/kioslave/metainfo/metainfo.h b/kioslave/metainfo/metainfo.h
deleted file mode 100644
index a77647180..000000000
--- a/kioslave/metainfo/metainfo.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 2002 Rolf Magnus <ramagnus@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation version 2.0
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#ifndef _METAINFO_H_
-#define _METAINFO_H_
-
-#include <kio/slavebase.h>
-
-class MetaInfoProtocol : public TDEIO::SlaveBase
-{
-public:
- MetaInfoProtocol(const TQCString &pool, const TQCString &app);
- virtual ~MetaInfoProtocol();
-
- virtual void get(const KURL &url);
- virtual void put(const KURL& url, int permissions,
- bool overwrite, bool resume);
-
-};
-
-#endif
diff --git a/knewstuff/CMakeLists.txt b/knewstuff/CMakeLists.txt
index 50350f29f..4493ee385 100644
--- a/knewstuff/CMakeLists.txt
+++ b/knewstuff/CMakeLists.txt
@@ -16,9 +16,9 @@ include_directories(
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
@@ -38,7 +38,7 @@ install( FILES
##### other data ################################
install( FILES types DESTINATION ${DATA_INSTALL_DIR}/knewstuff )
-install( FILES khotnewstuffrc DESTINATION ${CONFIG_INSTALL_DIR} )
+install( FILES tdehotnewstuffrc DESTINATION ${CONFIG_INSTALL_DIR} )
tde_install_icons( )
@@ -55,17 +55,17 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 1.0.0
- LINK kio-shared
+ LINK tdeio-shared
DESTINATION ${LIB_INSTALL_DIR}
)
-##### khotnewstuff ##############################
+##### tdehotnewstuff ##############################
-set( target khotnewstuff )
+set( target tdehotnewstuff )
set( ${target}_SRCS
- khotnewstuff.cpp
+ tdehotnewstuff.cpp
)
tde_add_executable( ${target} AUTOMOC
diff --git a/knewstuff/Makefile.am b/knewstuff/Makefile.am
index 0f0bc9676..c15716c8e 100644
--- a/knewstuff/Makefile.am
+++ b/knewstuff/Makefile.am
@@ -10,11 +10,11 @@ libknewstuff_la_SOURCES = engine.cpp entry.cpp downloaddialog.cpp \
uploaddialog.cpp providerdialog.cpp provider.cpp knewstuff.cpp \
knewstuffgeneric.cpp knewstuffbutton.cpp knewstuffsecure.cpp security.cpp
-bin_PROGRAMS = khotnewstuff
+bin_PROGRAMS = tdehotnewstuff
-khotnewstuff_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-khotnewstuff_LDADD = libknewstuff.la
-khotnewstuff_SOURCES = khotnewstuff.cpp
+tdehotnewstuff_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+tdehotnewstuff_LDADD = libknewstuff.la
+tdehotnewstuff_SOURCES = tdehotnewstuff.cpp
EXTRA_PROGRAMS = testnewstuff ghns
@@ -29,7 +29,7 @@ ghns_SOURCES = ghns.cpp
knewstuffdir = $(kde_datadir)/knewstuff
knewstuff_DATA = types
-kde_conf_DATA = khotnewstuffrc
+kde_conf_DATA = tdehotnewstuffrc
knsdir = $(includedir)/knewstuff
kns_HEADERS = downloaddialog.h engine.h entry.h knewstuffgeneric.h knewstuff.h providerdialog.h provider.h uploaddialog.h knewstuffbutton.h knewstuffsecure.h
diff --git a/knewstuff/downloaddialog.cpp b/knewstuff/downloaddialog.cpp
index f8e03295c..3cc476254 100644
--- a/knewstuff/downloaddialog.cpp
+++ b/knewstuff/downloaddialog.cpp
@@ -24,11 +24,11 @@
#include <klocale.h>
#include <klistview.h>
#include <kdebug.h>
-#include <kio/job.h>
-#include <kio/netaccess.h>
+#include <tdeio/job.h>
+#include <tdeio/netaccess.h>
#include <kmessagebox.h>
#include <kurl.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kapplication.h>
#include <kiconloader.h>
diff --git a/knewstuff/engine.cpp b/knewstuff/engine.cpp
index 7152a0ccd..063c2c7b9 100644
--- a/knewstuff/engine.cpp
+++ b/knewstuff/engine.cpp
@@ -24,7 +24,7 @@
#include <kapplication.h>
#include <kdebug.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
diff --git a/knewstuff/khotnewstuff.cpp b/knewstuff/khotnewstuff.cpp
deleted file mode 100644
index 67c6c70b2..000000000
--- a/knewstuff/khotnewstuff.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- This file is part of KOrganizer.
- Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-#include <kaboutdata.h>
-
-#include "downloaddialog.h"
-
-static const KCmdLineOptions op[] =
-{
- {"type <type>", I18N_NOOP("Display only media of this type"), 0},
- {"+[providerlist]", I18N_NOOP("Provider list to use"), 0},
- KCmdLineLastOption
-};
-
-int main(int argc, char **argv)
-{
- TDEAboutData about("khotnewstuff", "KHotNewStuff", "0.2");
- TDECmdLineArgs *args;
-
- TDECmdLineArgs::init(argc, argv, &about);
- TDECmdLineArgs::addCmdLineOptions(op);
- args = TDECmdLineArgs::parsedArgs();
-
- TDEApplication i;
-
- KNS::DownloadDialog d;
- if(args->isSet("type")) d.setType(args->getOption("type"));
- if(args->count() == 1) d.setProviderList(args->arg(0));
- d.load();
- d.exec();
-
- return 0;
-}
-
diff --git a/knewstuff/knewstuffgeneric.cpp b/knewstuff/knewstuffgeneric.cpp
index 1e4e6ecc3..be1d404b2 100644
--- a/knewstuff/knewstuffgeneric.cpp
+++ b/knewstuff/knewstuffgeneric.cpp
@@ -26,7 +26,7 @@
#include <kdebug.h>
#include <klocale.h>
#include <kprocess.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <ktar.h>
diff --git a/knewstuff/knewstuffsecure.cpp b/knewstuff/knewstuffsecure.cpp
index f467530c8..b61924243 100644
--- a/knewstuff/knewstuffsecure.cpp
+++ b/knewstuff/knewstuffsecure.cpp
@@ -16,10 +16,10 @@
#include <tqfileinfo.h>
//kde includes
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
diff --git a/knewstuff/provider.cpp b/knewstuff/provider.cpp
index a29183532..d5da6bdde 100644
--- a/knewstuff/provider.cpp
+++ b/knewstuff/provider.cpp
@@ -18,9 +18,9 @@
Boston, MA 02110-1301, USA.
*/
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <kglobal.h>
#include <kmessagebox.h>
#include <klocale.h>
diff --git a/knewstuff/tdehotnewstuff.cpp b/knewstuff/tdehotnewstuff.cpp
new file mode 100644
index 000000000..7b8ceae9c
--- /dev/null
+++ b/knewstuff/tdehotnewstuff.cpp
@@ -0,0 +1,55 @@
+/*
+ This file is part of KOrganizer.
+ Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+#include <kaboutdata.h>
+
+#include "downloaddialog.h"
+
+static const KCmdLineOptions op[] =
+{
+ {"type <type>", I18N_NOOP("Display only media of this type"), 0},
+ {"+[providerlist]", I18N_NOOP("Provider list to use"), 0},
+ KCmdLineLastOption
+};
+
+int main(int argc, char **argv)
+{
+ TDEAboutData about("tdehotnewstuff", "KHotNewStuff", "0.2");
+ TDECmdLineArgs *args;
+
+ TDECmdLineArgs::init(argc, argv, &about);
+ TDECmdLineArgs::addCmdLineOptions(op);
+ args = TDECmdLineArgs::parsedArgs();
+
+ TDEApplication i;
+
+ KNS::DownloadDialog d;
+ if(args->isSet("type")) d.setType(args->getOption("type"));
+ if(args->count() == 1) d.setProviderList(args->arg(0));
+ d.load();
+ d.exec();
+
+ return 0;
+}
+
diff --git a/knewstuff/khotnewstuffrc b/knewstuff/tdehotnewstuffrc
index 737ad61c2..737ad61c2 100644
--- a/knewstuff/khotnewstuffrc
+++ b/knewstuff/tdehotnewstuffrc
diff --git a/knewstuff/uploaddialog.cpp b/knewstuff/uploaddialog.cpp
index f82e466ff..69c823fd0 100644
--- a/knewstuff/uploaddialog.cpp
+++ b/knewstuff/uploaddialog.cpp
@@ -31,7 +31,7 @@
#include <kdebug.h>
#include <kurlrequester.h>
#include <kmessagebox.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kapplication.h>
#include <kuser.h>
diff --git a/kstyles/plastik/config/CMakeLists.txt b/kstyles/plastik/config/CMakeLists.txt
index b8534cea7..8de92d14a 100644
--- a/kstyles/plastik/config/CMakeLists.txt
+++ b/kstyles/plastik/config/CMakeLists.txt
@@ -27,7 +27,7 @@ link_directories(
set( target kstyle_plastik_config )
set( ${target}_SRCS
- plastikconf.cpp
+ plastitdeconf.cpp
)
tde_add_kpart( ${target} AUTOMOC
diff --git a/kstyles/plastik/config/Makefile.am b/kstyles/plastik/config/Makefile.am
index 887c7ea89..d97df31bb 100644
--- a/kstyles/plastik/config/Makefile.am
+++ b/kstyles/plastik/config/Makefile.am
@@ -1,10 +1,10 @@
INCLUDES = $(all_includes)
-noinst_HEADERS = plastikconf.h
+noinst_HEADERS = plastitdeconf.h
kde_module_LTLIBRARIES = kstyle_plastik_config.la
kstyle_plastik_config_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN) -module
kstyle_plastik_config_la_LIBADD = $(LIB_TDEUI) $(LIB_QT) $(LIB_TDECORE)
-kstyle_plastik_config_la_SOURCES = plastikconf.cpp
+kstyle_plastik_config_la_SOURCES = plastitdeconf.cpp
kstyle_plastik_config_la_METASOURCES = AUTO
diff --git a/kstyles/plastik/config/plastikconf.cpp b/kstyles/plastik/config/plastikconf.cpp
deleted file mode 100644
index 338cdcd1e..000000000
--- a/kstyles/plastik/config/plastikconf.cpp
+++ /dev/null
@@ -1,223 +0,0 @@
-/*
-Copyright (C) 2003 Sandro Giessl <ceebx@users.sourceforge.net>
-
-based on the Keramik configuration dialog:
-Copyright (c) 2003 Maksim Orlovich <maksim.orlovich@kdemail.net>
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the "Software"),
-to deal in the Software without restriction, including without limitation
-the rights to use, copy, modify, merge, publish, distribute, sublicense,
-and/or sell copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE.
-
-*/
-
-#include <tqcheckbox.h>
-#include <tqlayout.h>
-#include <tqhbox.h>
-#include <tqsettings.h>
-#include <tqcolor.h>
-#include <tqgroupbox.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kcolorbutton.h>
-#include <kdemacros.h>
-
-#include "plastikconf.h"
-
-extern "C"
-{
- KDE_EXPORT TQWidget* allocate_kstyle_config(TQWidget* parent)
- {
- TDEGlobal::locale()->insertCatalogue("kstyle_plastik_config");
- return new PlastikStyleConfig(parent);
- }
-}
-
-PlastikStyleConfig::PlastikStyleConfig(TQWidget* parent): TQWidget(parent)
-{
- //Should have no margins here, the dialog provides them
- TQVBoxLayout* layout = new TQVBoxLayout(this, 0, 0);
- TDEGlobal::locale()->insertCatalogue("kstyle_plastik_config");
-
-// scrollBarLines = new TQCheckBox(i18n("Scrollbar handle lines"), this);
- animateProgressBar = new TQCheckBox(i18n("Animate progress bars"), this);
- drawToolBarSeparator = new TQCheckBox(i18n("Draw toolbar separator"), this);
- drawToolBarItemSeparator = new TQCheckBox(i18n("Draw toolbar item separators"), this);
-// drawFocusRect = new TQCheckBox(i18n("Draw focus rectangles"), this);
- drawTriangularExpander = new TQCheckBox(i18n("Triangular tree expander"), this);
- inputFocusHighlight = new TQCheckBox(i18n("Highlight focused text input fields"), this);
-
- customFocusHighlightColor = new TQCheckBox(i18n("Custom text input highlight color:"), this);
- TQHBox *hbox1 = new TQHBox(this);
- hbox1->layout()->addItem(new TQSpacerItem(20, 0, TQSizePolicy::Fixed, TQSizePolicy::Minimum) );
- focusHighlightColor = new KColorButton(hbox1);
-
- customOverHighlightColor = new TQCheckBox(i18n("Custom mouseover highlight color:"), this);
- TQHBox *hbox2 = new TQHBox(this);
- hbox2->layout()->addItem(new TQSpacerItem(20, 0, TQSizePolicy::Fixed, TQSizePolicy::Minimum) );
- overHighlightColor = new KColorButton(hbox2);
-
- customCheckMarkColor = new TQCheckBox(i18n("Custom checkmark color:"), this);
- TQHBox *hbox3 = new TQHBox(this);
- hbox3->layout()->addItem(new TQSpacerItem(20, 0, TQSizePolicy::Fixed, TQSizePolicy::Minimum) );
- checkMarkColor = new KColorButton(hbox3);
-
-// layout->add(scrollBarLines);
- layout->add(animateProgressBar);
- layout->add(drawToolBarSeparator);
- layout->add(drawToolBarItemSeparator);
-// layout->add(drawFocusRect);
- layout->add(drawTriangularExpander);
- layout->add(inputFocusHighlight);
- layout->add(customFocusHighlightColor);
- layout->add(hbox1);
- layout->add(customOverHighlightColor);
- layout->add(hbox2);
- layout->add(customCheckMarkColor);
- layout->add(hbox3);
- layout->addStretch(1);
-
- TQSettings s;
-// origScrollBarLines = s.readBoolEntry("/plastikstyle/Settings/scrollBarLines", false);
-// scrollBarLines->setChecked(origScrollBarLines);
- origAnimProgressBar = s.readBoolEntry("/plastikstyle/Settings/animateProgressBar", false);
- animateProgressBar->setChecked(origAnimProgressBar);
- origDrawToolBarSeparator = s.readBoolEntry("/plastikstyle/Settings/drawToolBarSeparator", false);
- drawToolBarSeparator->setChecked(origDrawToolBarSeparator);
- origDrawToolBarItemSeparator = s.readBoolEntry("/plastikstyle/Settings/drawToolBarItemSeparator", true);
- drawToolBarItemSeparator->setChecked(origDrawToolBarItemSeparator);
-// origDrawFocusRect = s.readBoolEntry("/plastikstyle/Settings/drawFocusRect", true);
-// drawFocusRect->setChecked(origDrawFocusRect);
- origDrawTriangularExpander = s.readBoolEntry("/plastikstyle/Settings/drawTriangularExpander", false);
- drawTriangularExpander->setChecked(origDrawTriangularExpander);
- origInputFocusHighlight = s.readBoolEntry("/plastikstyle/Settings/inputFocusHighlight", true);
- inputFocusHighlight->setChecked(origInputFocusHighlight);
- origCustomOverHighlightColor = s.readBoolEntry("/plastikstyle/Settings/customOverHighlightColor", false);
- customOverHighlightColor->setChecked(origCustomOverHighlightColor);
- origOverHighlightColor = s.readEntry("/plastikstyle/Settings/overHighlightColor", "black");
- overHighlightColor->setColor(origOverHighlightColor);
- origCustomFocusHighlightColor = s.readBoolEntry("/plastikstyle/Settings/customFocusHighlightColor", false);
- customFocusHighlightColor->setChecked(origCustomFocusHighlightColor);
- origFocusHighlightColor = s.readEntry("/plastikstyle/Settings/focusHighlightColor", "black");
- focusHighlightColor->setColor(origFocusHighlightColor);
- origCustomCheckMarkColor = s.readBoolEntry("/plastikstyle/Settings/customCheckMarkColor", false);
- customCheckMarkColor->setChecked(origCustomCheckMarkColor);
- origCheckMarkColor = s.readEntry("/plastikstyle/Settings/checkMarkColor", "black");
- checkMarkColor->setColor(origCheckMarkColor);
-
-// connect(scrollBarLines, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(animateProgressBar, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(drawToolBarSeparator, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(drawToolBarItemSeparator, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
-// connect(drawFocusRect, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(drawTriangularExpander, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(inputFocusHighlight, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(customOverHighlightColor, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(overHighlightColor, TQT_SIGNAL( changed(const TQColor&) ), TQT_SLOT( updateChanged() ) );
- connect(customFocusHighlightColor, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(focusHighlightColor, TQT_SIGNAL( changed(const TQColor&) ), TQT_SLOT( updateChanged() ) );
- connect(customCheckMarkColor, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
- connect(checkMarkColor, TQT_SIGNAL( changed(const TQColor&) ), TQT_SLOT( updateChanged() ) );
- if ( customOverHighlightColor->isChecked() )
- overHighlightColor->setEnabled(true);
- else
- overHighlightColor->setEnabled(false);
- if ( customFocusHighlightColor->isChecked() )
- focusHighlightColor->setEnabled(true);
- else
- focusHighlightColor->setEnabled(false);
- if ( customCheckMarkColor->isChecked() )
- checkMarkColor->setEnabled(true);
- else
- checkMarkColor->setEnabled(false);
-}
-
-PlastikStyleConfig::~PlastikStyleConfig()
-{
-}
-
-
-void PlastikStyleConfig::save()
-{
- TQSettings s;
-// s.writeEntry("/plastikstyle/Settings/scrollBarLines", scrollBarLines->isChecked());
- s.writeEntry("/plastikstyle/Settings/animateProgressBar", animateProgressBar->isChecked());
- s.writeEntry("/plastikstyle/Settings/drawToolBarSeparator", drawToolBarSeparator->isChecked());
- s.writeEntry("/plastikstyle/Settings/drawToolBarItemSeparator", drawToolBarItemSeparator->isChecked());
-// s.writeEntry("/plastikstyle/Settings/drawFocusRect", drawFocusRect->isChecked());
- s.writeEntry("/plastikstyle/Settings/drawTriangularExpander", drawTriangularExpander->isChecked());
- s.writeEntry("/plastikstyle/Settings/inputFocusHighlight", inputFocusHighlight->isChecked());
- s.writeEntry("/plastikstyle/Settings/customOverHighlightColor", customOverHighlightColor->isChecked());
- s.writeEntry("/plastikstyle/Settings/overHighlightColor", TQColor(overHighlightColor->color()).name());
- s.writeEntry("/plastikstyle/Settings/customFocusHighlightColor", customFocusHighlightColor->isChecked());
- s.writeEntry("/plastikstyle/Settings/focusHighlightColor", TQColor(focusHighlightColor->color()).name());
- s.writeEntry("/plastikstyle/Settings/customCheckMarkColor", customCheckMarkColor->isChecked());
- s.writeEntry("/plastikstyle/Settings/checkMarkColor", TQColor(checkMarkColor->color()).name());
-}
-
-void PlastikStyleConfig::defaults()
-{
-// scrollBarLines->setChecked(false);
- animateProgressBar->setChecked(false);
- drawToolBarSeparator->setChecked(false);
- drawToolBarItemSeparator->setChecked(true);
-// drawFocusRect->setChecked(true);
- drawTriangularExpander->setChecked(false);
- inputFocusHighlight->setChecked(true);
- customOverHighlightColor->setChecked(false);
- overHighlightColor->setColor("black");
- customFocusHighlightColor->setChecked(false);
- focusHighlightColor->setColor("black");
- customCheckMarkColor->setChecked(false);
- checkMarkColor->setColor("black");
- //updateChanged would be done by setChecked already
-}
-
-void PlastikStyleConfig::updateChanged()
-{
- if ( customOverHighlightColor->isChecked() )
- overHighlightColor->setEnabled(true);
- else
- overHighlightColor->setEnabled(false);
- if ( customFocusHighlightColor->isChecked() )
- focusHighlightColor->setEnabled(true);
- else
- focusHighlightColor->setEnabled(false);
- if ( customCheckMarkColor->isChecked() )
- checkMarkColor->setEnabled(true);
- else
- checkMarkColor->setEnabled(false);
-
- if (/*(scrollBarLines->isChecked() == origScrollBarLines) &&*/
- (animateProgressBar->isChecked() == origAnimProgressBar) &&
- (drawToolBarSeparator->isChecked() == origDrawToolBarSeparator) &&
- (drawToolBarItemSeparator->isChecked() == origDrawToolBarItemSeparator) &&
-// (drawFocusRect->isChecked() == origDrawFocusRect) &&
- (drawTriangularExpander->isChecked() == origDrawTriangularExpander) &&
- (inputFocusHighlight->isChecked() == origInputFocusHighlight) &&
- (customOverHighlightColor->isChecked() == origCustomOverHighlightColor) &&
- (overHighlightColor->color() == origOverHighlightColor) &&
- (customFocusHighlightColor->isChecked() == origCustomFocusHighlightColor) &&
- (focusHighlightColor->color() == origFocusHighlightColor) &&
- (customCheckMarkColor->isChecked() == origCustomCheckMarkColor) &&
- (checkMarkColor->color() == origCheckMarkColor)
- )
- emit changed(false);
- else
- emit changed(true);
-}
-
-#include "plastikconf.moc"
diff --git a/kstyles/plastik/config/plastitdeconf.cpp b/kstyles/plastik/config/plastitdeconf.cpp
new file mode 100644
index 000000000..8d3e4acfd
--- /dev/null
+++ b/kstyles/plastik/config/plastitdeconf.cpp
@@ -0,0 +1,223 @@
+/*
+Copyright (C) 2003 Sandro Giessl <ceebx@users.sourceforge.net>
+
+based on the Keramik configuration dialog:
+Copyright (c) 2003 Maksim Orlovich <maksim.orlovich@kdemail.net>
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include <tqcheckbox.h>
+#include <tqlayout.h>
+#include <tqhbox.h>
+#include <tqsettings.h>
+#include <tqcolor.h>
+#include <tqgroupbox.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kcolorbutton.h>
+#include <kdemacros.h>
+
+#include "plastitdeconf.h"
+
+extern "C"
+{
+ KDE_EXPORT TQWidget* allocate_kstyle_config(TQWidget* parent)
+ {
+ TDEGlobal::locale()->insertCatalogue("kstyle_plastik_config");
+ return new PlastikStyleConfig(parent);
+ }
+}
+
+PlastikStyleConfig::PlastikStyleConfig(TQWidget* parent): TQWidget(parent)
+{
+ //Should have no margins here, the dialog provides them
+ TQVBoxLayout* layout = new TQVBoxLayout(this, 0, 0);
+ TDEGlobal::locale()->insertCatalogue("kstyle_plastik_config");
+
+// scrollBarLines = new TQCheckBox(i18n("Scrollbar handle lines"), this);
+ animateProgressBar = new TQCheckBox(i18n("Animate progress bars"), this);
+ drawToolBarSeparator = new TQCheckBox(i18n("Draw toolbar separator"), this);
+ drawToolBarItemSeparator = new TQCheckBox(i18n("Draw toolbar item separators"), this);
+// drawFocusRect = new TQCheckBox(i18n("Draw focus rectangles"), this);
+ drawTriangularExpander = new TQCheckBox(i18n("Triangular tree expander"), this);
+ inputFocusHighlight = new TQCheckBox(i18n("Highlight focused text input fields"), this);
+
+ customFocusHighlightColor = new TQCheckBox(i18n("Custom text input highlight color:"), this);
+ TQHBox *hbox1 = new TQHBox(this);
+ hbox1->layout()->addItem(new TQSpacerItem(20, 0, TQSizePolicy::Fixed, TQSizePolicy::Minimum) );
+ focusHighlightColor = new KColorButton(hbox1);
+
+ customOverHighlightColor = new TQCheckBox(i18n("Custom mouseover highlight color:"), this);
+ TQHBox *hbox2 = new TQHBox(this);
+ hbox2->layout()->addItem(new TQSpacerItem(20, 0, TQSizePolicy::Fixed, TQSizePolicy::Minimum) );
+ overHighlightColor = new KColorButton(hbox2);
+
+ customCheckMarkColor = new TQCheckBox(i18n("Custom checkmark color:"), this);
+ TQHBox *hbox3 = new TQHBox(this);
+ hbox3->layout()->addItem(new TQSpacerItem(20, 0, TQSizePolicy::Fixed, TQSizePolicy::Minimum) );
+ checkMarkColor = new KColorButton(hbox3);
+
+// layout->add(scrollBarLines);
+ layout->add(animateProgressBar);
+ layout->add(drawToolBarSeparator);
+ layout->add(drawToolBarItemSeparator);
+// layout->add(drawFocusRect);
+ layout->add(drawTriangularExpander);
+ layout->add(inputFocusHighlight);
+ layout->add(customFocusHighlightColor);
+ layout->add(hbox1);
+ layout->add(customOverHighlightColor);
+ layout->add(hbox2);
+ layout->add(customCheckMarkColor);
+ layout->add(hbox3);
+ layout->addStretch(1);
+
+ TQSettings s;
+// origScrollBarLines = s.readBoolEntry("/plastikstyle/Settings/scrollBarLines", false);
+// scrollBarLines->setChecked(origScrollBarLines);
+ origAnimProgressBar = s.readBoolEntry("/plastikstyle/Settings/animateProgressBar", false);
+ animateProgressBar->setChecked(origAnimProgressBar);
+ origDrawToolBarSeparator = s.readBoolEntry("/plastikstyle/Settings/drawToolBarSeparator", false);
+ drawToolBarSeparator->setChecked(origDrawToolBarSeparator);
+ origDrawToolBarItemSeparator = s.readBoolEntry("/plastikstyle/Settings/drawToolBarItemSeparator", true);
+ drawToolBarItemSeparator->setChecked(origDrawToolBarItemSeparator);
+// origDrawFocusRect = s.readBoolEntry("/plastikstyle/Settings/drawFocusRect", true);
+// drawFocusRect->setChecked(origDrawFocusRect);
+ origDrawTriangularExpander = s.readBoolEntry("/plastikstyle/Settings/drawTriangularExpander", false);
+ drawTriangularExpander->setChecked(origDrawTriangularExpander);
+ origInputFocusHighlight = s.readBoolEntry("/plastikstyle/Settings/inputFocusHighlight", true);
+ inputFocusHighlight->setChecked(origInputFocusHighlight);
+ origCustomOverHighlightColor = s.readBoolEntry("/plastikstyle/Settings/customOverHighlightColor", false);
+ customOverHighlightColor->setChecked(origCustomOverHighlightColor);
+ origOverHighlightColor = s.readEntry("/plastikstyle/Settings/overHighlightColor", "black");
+ overHighlightColor->setColor(origOverHighlightColor);
+ origCustomFocusHighlightColor = s.readBoolEntry("/plastikstyle/Settings/customFocusHighlightColor", false);
+ customFocusHighlightColor->setChecked(origCustomFocusHighlightColor);
+ origFocusHighlightColor = s.readEntry("/plastikstyle/Settings/focusHighlightColor", "black");
+ focusHighlightColor->setColor(origFocusHighlightColor);
+ origCustomCheckMarkColor = s.readBoolEntry("/plastikstyle/Settings/customCheckMarkColor", false);
+ customCheckMarkColor->setChecked(origCustomCheckMarkColor);
+ origCheckMarkColor = s.readEntry("/plastikstyle/Settings/checkMarkColor", "black");
+ checkMarkColor->setColor(origCheckMarkColor);
+
+// connect(scrollBarLines, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(animateProgressBar, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(drawToolBarSeparator, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(drawToolBarItemSeparator, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+// connect(drawFocusRect, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(drawTriangularExpander, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(inputFocusHighlight, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(customOverHighlightColor, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(overHighlightColor, TQT_SIGNAL( changed(const TQColor&) ), TQT_SLOT( updateChanged() ) );
+ connect(customFocusHighlightColor, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(focusHighlightColor, TQT_SIGNAL( changed(const TQColor&) ), TQT_SLOT( updateChanged() ) );
+ connect(customCheckMarkColor, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( updateChanged() ) );
+ connect(checkMarkColor, TQT_SIGNAL( changed(const TQColor&) ), TQT_SLOT( updateChanged() ) );
+ if ( customOverHighlightColor->isChecked() )
+ overHighlightColor->setEnabled(true);
+ else
+ overHighlightColor->setEnabled(false);
+ if ( customFocusHighlightColor->isChecked() )
+ focusHighlightColor->setEnabled(true);
+ else
+ focusHighlightColor->setEnabled(false);
+ if ( customCheckMarkColor->isChecked() )
+ checkMarkColor->setEnabled(true);
+ else
+ checkMarkColor->setEnabled(false);
+}
+
+PlastikStyleConfig::~PlastikStyleConfig()
+{
+}
+
+
+void PlastikStyleConfig::save()
+{
+ TQSettings s;
+// s.writeEntry("/plastikstyle/Settings/scrollBarLines", scrollBarLines->isChecked());
+ s.writeEntry("/plastikstyle/Settings/animateProgressBar", animateProgressBar->isChecked());
+ s.writeEntry("/plastikstyle/Settings/drawToolBarSeparator", drawToolBarSeparator->isChecked());
+ s.writeEntry("/plastikstyle/Settings/drawToolBarItemSeparator", drawToolBarItemSeparator->isChecked());
+// s.writeEntry("/plastikstyle/Settings/drawFocusRect", drawFocusRect->isChecked());
+ s.writeEntry("/plastikstyle/Settings/drawTriangularExpander", drawTriangularExpander->isChecked());
+ s.writeEntry("/plastikstyle/Settings/inputFocusHighlight", inputFocusHighlight->isChecked());
+ s.writeEntry("/plastikstyle/Settings/customOverHighlightColor", customOverHighlightColor->isChecked());
+ s.writeEntry("/plastikstyle/Settings/overHighlightColor", TQColor(overHighlightColor->color()).name());
+ s.writeEntry("/plastikstyle/Settings/customFocusHighlightColor", customFocusHighlightColor->isChecked());
+ s.writeEntry("/plastikstyle/Settings/focusHighlightColor", TQColor(focusHighlightColor->color()).name());
+ s.writeEntry("/plastikstyle/Settings/customCheckMarkColor", customCheckMarkColor->isChecked());
+ s.writeEntry("/plastikstyle/Settings/checkMarkColor", TQColor(checkMarkColor->color()).name());
+}
+
+void PlastikStyleConfig::defaults()
+{
+// scrollBarLines->setChecked(false);
+ animateProgressBar->setChecked(false);
+ drawToolBarSeparator->setChecked(false);
+ drawToolBarItemSeparator->setChecked(true);
+// drawFocusRect->setChecked(true);
+ drawTriangularExpander->setChecked(false);
+ inputFocusHighlight->setChecked(true);
+ customOverHighlightColor->setChecked(false);
+ overHighlightColor->setColor("black");
+ customFocusHighlightColor->setChecked(false);
+ focusHighlightColor->setColor("black");
+ customCheckMarkColor->setChecked(false);
+ checkMarkColor->setColor("black");
+ //updateChanged would be done by setChecked already
+}
+
+void PlastikStyleConfig::updateChanged()
+{
+ if ( customOverHighlightColor->isChecked() )
+ overHighlightColor->setEnabled(true);
+ else
+ overHighlightColor->setEnabled(false);
+ if ( customFocusHighlightColor->isChecked() )
+ focusHighlightColor->setEnabled(true);
+ else
+ focusHighlightColor->setEnabled(false);
+ if ( customCheckMarkColor->isChecked() )
+ checkMarkColor->setEnabled(true);
+ else
+ checkMarkColor->setEnabled(false);
+
+ if (/*(scrollBarLines->isChecked() == origScrollBarLines) &&*/
+ (animateProgressBar->isChecked() == origAnimProgressBar) &&
+ (drawToolBarSeparator->isChecked() == origDrawToolBarSeparator) &&
+ (drawToolBarItemSeparator->isChecked() == origDrawToolBarItemSeparator) &&
+// (drawFocusRect->isChecked() == origDrawFocusRect) &&
+ (drawTriangularExpander->isChecked() == origDrawTriangularExpander) &&
+ (inputFocusHighlight->isChecked() == origInputFocusHighlight) &&
+ (customOverHighlightColor->isChecked() == origCustomOverHighlightColor) &&
+ (overHighlightColor->color() == origOverHighlightColor) &&
+ (customFocusHighlightColor->isChecked() == origCustomFocusHighlightColor) &&
+ (focusHighlightColor->color() == origFocusHighlightColor) &&
+ (customCheckMarkColor->isChecked() == origCustomCheckMarkColor) &&
+ (checkMarkColor->color() == origCheckMarkColor)
+ )
+ emit changed(false);
+ else
+ emit changed(true);
+}
+
+#include "plastitdeconf.moc"
diff --git a/kstyles/plastik/config/plastikconf.h b/kstyles/plastik/config/plastitdeconf.h
index 512ad6f2e..512ad6f2e 100644
--- a/kstyles/plastik/config/plastikconf.h
+++ b/kstyles/plastik/config/plastitdeconf.h
diff --git a/libtdemid/deviceman.cc b/libtdemid/deviceman.cc
index c7649f5a5..b8210af6d 100644
--- a/libtdemid/deviceman.cc
+++ b/libtdemid/deviceman.cc
@@ -68,7 +68,7 @@
#if 1
#include <kinstance.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#endif
//#define DEVICEMANDEBUG
diff --git a/tdecert/CMakeLists.txt b/tdecert/CMakeLists.txt
index 045d77720..2a9c391e3 100644
--- a/tdecert/CMakeLists.txt
+++ b/tdecert/CMakeLists.txt
@@ -14,14 +14,14 @@ include_directories(
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_BINARY_DIR}/kio/kssl
+ ${CMAKE_BINARY_DIR}/tdeio/kssl
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
- ${CMAKE_SOURCE_DIR}/kio/kssl
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
+ ${CMAKE_SOURCE_DIR}/tdeio/kssl
)
link_directories(
@@ -45,6 +45,6 @@ set( ${target}_SRCS
tde_add_kpart( ${target} AUTOMOC
SOURCES ${${target}_SRCS}
- LINK kio-shared tdeparts-shared
+ LINK tdeio-shared tdeparts-shared
DESTINATION ${PLUGIN_INSTALL_DIR}
)
diff --git a/tdecert/Makefile.am b/tdecert/Makefile.am
index d43ce0f5b..a6f605f4a 100644
--- a/tdecert/Makefile.am
+++ b/tdecert/Makefile.am
@@ -1,4 +1,4 @@
-INCLUDES= -I$(top_srcdir)/kio/kssl -I$(top_builddir)/kio/kssl -I$(top_srcdir) $(SSL_INCLUDES) $(all_includes)
+INCLUDES= -I$(top_srcdir)/tdeio/kssl -I$(top_builddir)/tdeio/kssl -I$(top_srcdir) $(SSL_INCLUDES) $(all_includes)
kde_module_LTLIBRARIES = libtdecertpart.la
diff --git a/tdecert/tdecertpart.cc b/tdecert/tdecertpart.cc
index ebb6e77ad..08e3ec5e0 100644
--- a/tdecert/tdecertpart.cc
+++ b/tdecert/tdecertpart.cc
@@ -36,18 +36,18 @@
#include <ksslall.h>
#include <kopenssl.h>
#include <ksslpemcallback.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kprocess.h>
#include <tqtabwidget.h>
#include <kseparator.h>
#include <klistview.h>
-#include <kio/kmimemagic.h>
+#include <tdeio/kmimemagic.h>
#include <tqmultilineedit.h>
#include <tqregexp.h>
#include <kcombobox.h>
#include <tdeparts/browserextension.h>
#include <tdeparts/browserinterface.h>
-#include <kio/kservicetypefactory.h>
+#include <tdeio/kservicetypefactory.h>
K_EXPORT_COMPONENT_FACTORY( libtdecertpart, KParts::GenericFactory<KCertPart> )
@@ -774,7 +774,7 @@ void KCertPart::slotDone() {
void KCertPart::slotLaunch() {
KShellProcess p;
-p << "kcmshell" << "crypto";
+p << "tdecmshell" << "crypto";
p.start(TDEProcess::DontCare);
}
diff --git a/tdecmshell/CMakeLists.txt b/tdecmshell/CMakeLists.txt
new file mode 100644
index 000000000..2b07bbdcc
--- /dev/null
+++ b/tdecmshell/CMakeLists.txt
@@ -0,0 +1,41 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeutils
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### tdecmshell ##################################
+
+set( target tdecmshell )
+
+set( ${target}_SRCS
+ main.cpp main.skel
+)
+
+tde_add_tdeinit_executable( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeutils-shared
+ DEPENDENCIES dcopidl
+)
diff --git a/tdecmshell/Makefile.am b/tdecmshell/Makefile.am
new file mode 100644
index 000000000..a6e1d2d74
--- /dev/null
+++ b/tdecmshell/Makefile.am
@@ -0,0 +1,39 @@
+#
+# Copyright (c) 1999 Matthias Hoelzer-Kluepfel <hoelzer@kde.org>
+# Copyright (c) 2000 Matthias Elter <elter@kde.org>
+# Copyright (c) 2004 Frans Englich <frans.englich@telia.com>
+#
+# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+
+AM_CPPFLAGS = -I$(top_srcdir)/tdeutils $(all_includes)
+METASOURCES = AUTO
+
+lib_LTLIBRARIES =
+bin_PROGRAMS =
+tdeinit_LTLIBRARIES = tdecmshell.la
+
+tdecmshell_la_SOURCES = main.cpp main.skel
+tdecmshell_la_LIBADD = ../tdeutils/libtdeutils.la $(LIB_QT) $(LIB_TDEUI) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE) $(LIB_KFILE)
+tdecmshell_la_LDFLAGS = $(all_libraries) -module -avoid-version
+
+noinst_HEADERS = main.h
+
+messages: rc.cpp
+ $(XGETTEXT) *.cpp -o $(podir)/tdecmshell.pot
+
+
+include $(top_srcdir)/admin/Doxyfile.am
+
diff --git a/tdecmshell/main.cpp b/tdecmshell/main.cpp
new file mode 100644
index 000000000..358b00ccb
--- /dev/null
+++ b/tdecmshell/main.cpp
@@ -0,0 +1,350 @@
+/*
+ Copyright (c) 1999 Matthias Hoelzer-Kluepfel <hoelzer@kde.org>
+ Copyright (c) 2000 Matthias Elter <elter@kde.org>
+ Copyright (c) 2004 Frans Englich <frans.englich@telia.com>
+
+ 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+*/
+
+#include <iostream>
+
+#include <tqcstring.h>
+#include <tqfile.h>
+
+#include <dcopclient.h>
+#include <qxembed.h>
+
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kcmdlineargs.h>
+#include <tdecmoduleinfo.h>
+#include <tdecmoduleloader.h>
+#include <tdecmoduleproxy.h>
+#include <kcmultidialog.h>
+#include <kdebug.h>
+#include <kdialogbase.h>
+#include <kiconloader.h>
+#include <klocale.h>
+#include <kservice.h>
+#include <kservicegroup.h>
+#include <kstartupinfo.h>
+#include <twin.h>
+#include <kglobal.h>
+
+#include "main.h"
+#include "main.moc"
+
+using namespace std;
+
+KService::List m_modules;
+
+static KCmdLineOptions options[] =
+{
+ { "list", I18N_NOOP("List all possible modules"), 0},
+ { "+module", I18N_NOOP("Configuration module to open"), 0 },
+ { "lang <language>", I18N_NOOP("Specify a particular language"), 0 },
+ { "embed <id>", I18N_NOOP("Embeds the module with buttons in window with id <id>"), 0 },
+ { "embed-proxy <id>", I18N_NOOP("Embeds the module without buttons in window with id <id>"), 0 },
+ { "silent", I18N_NOOP("Do not display main window"), 0 },
+ KCmdLineLastOption
+};
+
+static void listModules(const TQString &baseGroup)
+{
+
+ KServiceGroup::Ptr group = KServiceGroup::group(baseGroup);
+
+ if (!group || !group->isValid())
+ return;
+
+ KServiceGroup::List list = group->entries(true, true);
+
+ for( KServiceGroup::List::ConstIterator it = list.begin();
+ it != list.end(); it++)
+ {
+ KSycocaEntry *p = (*it);
+ if (p->isType(KST_KService))
+ {
+ KService *s = static_cast<KService*>(p);
+ if (!kapp->authorizeControlModule(s->menuId()))
+ continue;
+ m_modules.append(s);
+ }
+ else if (p->isType(KST_KServiceGroup))
+ listModules(p->entryPath());
+ }
+}
+
+static KService::Ptr locateModule(const TQCString& module)
+{
+ TQString path = TQFile::decodeName(module);
+
+ if (!path.endsWith(".desktop"))
+ path += ".desktop";
+
+ KService::Ptr service = KService::serviceByStorageId( path );
+ if (!service)
+ {
+ kdWarning(780) << "Could not find module '" << module << "'." << endl;
+ return 0;
+ }
+
+ // avoid finding random non-TDE applications
+ if ( module.left( 4 ) != "kde-" && service->library().isEmpty() )
+ return locateModule( "kde-" + module );
+
+ if(!TDECModuleLoader::testModule( module ))
+ {
+ kdDebug(780) << "According to \"" << module << "\"'s test function, it should Not be loaded." << endl;
+ return 0;
+ }
+
+ return service;
+}
+
+bool KCMShell::isRunning()
+{
+ if( dcopClient()->appId() == m_dcopName )
+ return false; // We are the one and only.
+
+ kdDebug(780) << "tdecmshell with modules '" <<
+ m_dcopName << "' is already running." << endl;
+
+ dcopClient()->attach(); // Reregister as anonymous
+ dcopClient()->setNotifications(true);
+
+ TQByteArray data;
+ TQDataStream str( data, IO_WriteOnly );
+ str << kapp->startupId();
+ TQCString replyType;
+ TQByteArray replyData;
+ if (!dcopClient()->call(m_dcopName, "dialog", "activate(TQCString)",
+ data, replyType, replyData))
+ {
+ kdDebug(780) << "Calling DCOP function dialog::activate() failed." << endl;
+ return false; // Error, we have to do it ourselves.
+ }
+
+ return true;
+}
+
+KCMShellMultiDialog::KCMShellMultiDialog( int dialogFace, const TQString& caption,
+ TQWidget *parent, const char *name, bool modal)
+ : KCMultiDialog( dialogFace, caption, parent, name, modal ),
+ DCOPObject("dialog")
+{
+}
+
+void KCMShellMultiDialog::activate( TQCString asn_id )
+{
+ kdDebug(780) << k_funcinfo << endl;
+
+ KStartupInfo::setNewStartupId( this, asn_id );
+}
+
+void KCMShell::setDCOPName(const TQCString &dcopName, bool rootMode )
+{
+ m_dcopName = "tdecmshell_";
+ if( rootMode )
+ m_dcopName += "rootMode_";
+
+ m_dcopName += dcopName;
+
+ dcopClient()->registerAs(m_dcopName, false);
+}
+
+void KCMShell::waitForExit()
+{
+ kdDebug(780) << k_funcinfo << endl;
+
+ connect(dcopClient(), TQT_SIGNAL(applicationRemoved(const TQCString&)),
+ TQT_SLOT( appExit(const TQCString&) ));
+ exec();
+}
+
+void KCMShell::appExit(const TQCString &appId)
+{
+ kdDebug(780) << k_funcinfo << endl;
+
+ if( appId == m_dcopName )
+ {
+ kdDebug(780) << "'" << appId << "' closed, dereferencing." << endl;
+ deref();
+ }
+}
+
+static void setIcon(TQWidget *w, const TQString &iconName)
+{
+ TQPixmap icon = DesktopIcon(iconName);
+ TQPixmap miniIcon = SmallIcon(iconName);
+ w->setIcon( icon ); //standard X11
+#if defined Q_WS_X11 && ! defined K_WS_QTONLY
+ KWin::setIcons(w->winId(), icon, miniIcon );
+#endif
+}
+
+extern "C" KDE_EXPORT int kdemain(int _argc, char *_argv[])
+{
+ TDEAboutData aboutData( "tdecmshell", I18N_NOOP("TDE Control Module"),
+ 0,
+ I18N_NOOP("A tool to start single TDE control modules"),
+ TDEAboutData::License_GPL,
+ I18N_NOOP("(c) 1999-2004, The KDE Developers") );
+
+ aboutData.addAuthor("Frans Englich", I18N_NOOP("Maintainer"), "frans.englich@kde.org");
+ aboutData.addAuthor("Daniel Molkentin", 0, "molkentin@kde.org");
+ aboutData.addAuthor("Matthias Hoelzer-Kluepfel",0, "hoelzer@kde.org");
+ aboutData.addAuthor("Matthias Elter",0, "elter@kde.org");
+ aboutData.addAuthor("Matthias Ettrich",0, "ettrich@kde.org");
+ aboutData.addAuthor("Waldo Bastian",0, "bastian@kde.org");
+
+ TDEGlobal::locale()->setMainCatalogue("tdecmshell");
+
+ TDECmdLineArgs::init(_argc, _argv, &aboutData);
+ TDECmdLineArgs::addCmdLineOptions( options ); // Add our own options.
+ KCMShell app;
+
+ const TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ const TQCString lang = args->getOption("lang");
+ if( !lang.isNull() )
+ TDEGlobal::locale()->setLanguage(lang);
+
+ if (args->isSet("list"))
+ {
+ cout << static_cast<const char *>(i18n("The following modules are available:").local8Bit()) << endl;
+
+ listModules( "Settings/" );
+
+ int maxLen=0;
+
+ for( KService::List::ConstIterator it = m_modules.begin(); it != m_modules.end(); ++it)
+ {
+ int len = (*it)->desktopEntryName().length();
+ if (len > maxLen)
+ maxLen = len;
+ }
+
+ for( KService::List::ConstIterator it = m_modules.begin(); it != m_modules.end(); ++it)
+ {
+ TQString entry("%1 - %2");
+
+ entry = entry.arg((*it)->desktopEntryName().leftJustify(maxLen, ' '))
+ .arg(!(*it)->comment().isEmpty() ? (*it)->comment()
+ : i18n("No description available"));
+
+ cout << static_cast<const char *>(entry.local8Bit()) << endl;
+ }
+ return 0;
+ }
+
+ if (args->count() < 1)
+ {
+ args->usage();
+ return -1;
+ }
+
+ TQCString dcopName;
+ KService::List modules;
+ for (int i = 0; i < args->count(); i++)
+ {
+ KService::Ptr service = locateModule(args->arg(i));
+ if( service )
+ {
+ modules.append(service);
+ if( !dcopName.isEmpty() )
+ dcopName += "_";
+
+ dcopName += args->arg(i);
+ }
+ }
+
+ /* Check if this particular module combination is already running, but
+ * allow the same module to run when embedding(root mode) */
+ app.setDCOPName(dcopName,
+ ( args->isSet( "embed-proxy" ) || args->isSet( "embed" )));
+ if( app.isRunning() )
+ {
+ app.waitForExit();
+ return 0;
+ }
+
+ //KDialogBase::DialogType dtype = KDialogBase::Plain; // FIXME
+ KDialogBase::DialogType dtype = KDialogBase::IconList; // Work around a bug whereby several kcontrol modules (such as displayconfig) use an incorrect size when loaded with tdecmshell in the Plain mode
+ // This bug is possibly related to kcmultidialog.cpp:266 [( new TQHBoxLayout( page ) )->setAutoAdd( true );]
+ // In fact, this method of display may be preferable to the Plain mode from a UX perspective,
+ // as the icon shows the user what the active kcontrol module is called.
+
+ if ( modules.count() < 1 )
+ return 0;
+ else if( modules.count() > 1 )
+ dtype = KDialogBase::IconList;
+
+ bool idValid;
+ int id;
+
+ if ( args->isSet( "embed-proxy" ))
+ {
+ id = args->getOption( "embed-proxy" ).toInt(&idValid);
+ if( idValid )
+ {
+ TDECModuleProxy *module = new TDECModuleProxy( modules.first()->desktopEntryName() );
+ module->realModule();
+ QXEmbed::embedClientIntoWindow( module, id);
+ app.exec();
+ delete module;
+ }
+ else
+ kdDebug(780) << "Supplied id '" << id << "' is not valid." << endl;
+
+ return 0;
+
+ }
+
+ KCMShellMultiDialog *dlg = new KCMShellMultiDialog( dtype,
+ i18n("Configure - %1").arg(kapp->caption()), 0, "", true );
+
+ for (KService::List::ConstIterator it = modules.begin(); it != modules.end(); ++it)
+ dlg->addModule(TDECModuleInfo(*it));
+
+ if ( args->isSet( "embed" ))
+ {
+ id = args->getOption( "embed" ).toInt(&idValid);
+ if( idValid )
+ {
+ QXEmbed::embedClientIntoWindow( dlg, id );
+ dlg->exec();
+ delete dlg;
+ }
+ else
+ kdDebug(780) << "Supplied id '" << id << "' is not valid." << endl;
+
+ }
+ else
+ {
+
+ if (kapp->iconName() != kapp->name())
+ setIcon(dlg, kapp->iconName());
+ else if ( modules.count() == 1 )
+ setIcon(dlg, TDECModuleInfo( modules.first()).icon());
+
+ dlg->exec();
+ delete dlg;
+ }
+
+ return 0;
+}
+// vim: sw=4 et sts=4
diff --git a/tdecmshell/main.h b/tdecmshell/main.h
new file mode 100644
index 000000000..f135c2a33
--- /dev/null
+++ b/tdecmshell/main.h
@@ -0,0 +1,104 @@
+/*
+ Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
+ Copyright (c) 2004 Frans Englich <frans.englich@telia.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+*/
+
+#ifndef __tdecmshell_h__
+#define __tdecmshell_h__
+
+#include <dcopobject.h>
+
+#include <kapplication.h>
+#include <kcmultidialog.h>
+
+/**
+ * The TDEApplication instance for tdecmshell.
+ */
+class KCMShell : public TDEApplication
+{
+ Q_OBJECT
+
+public:
+
+ /**
+ * Sets m_dcopName basically to @p dcopName,
+ * and then registers with DCOP.
+ *
+ * @param dcopName name to set the DCOP name to
+ * @param rootMode true if the tdecmshell is embedding
+ */
+ void setDCOPName(const TQCString &dcopName, bool rootMode );
+
+ /**
+ * Waits until the last instance of tdecmshell with the same
+ * module as this one exits, and then exits.
+ */
+ void waitForExit();
+
+ /**
+ * @return true if the shell is running
+ */
+ bool isRunning();
+
+private slots:
+
+ /**
+ */
+ void appExit( const TQCString &appId );
+
+private:
+
+ /**
+ * The DCOP name which actually is registered.
+ * For example "tdecmshell_mouse".
+ */
+ TQCString m_dcopName;
+
+};
+
+
+/**
+ * Essentially a plain KCMultiDialog, but has the additional functionality
+ * of allowing it to be told to request windows focus.
+ *
+ * @author Waldo Bastian <bastian@kde.org>
+ */
+class KCMShellMultiDialog : public KCMultiDialog, public DCOPObject
+{
+ Q_OBJECT
+ K_DCOP
+
+public:
+
+ /**
+ */
+ KCMShellMultiDialog( int dialogFace, const TQString& caption,
+ TQWidget *parent=0, const char *name=0, bool modal=false);
+
+k_dcop:
+
+ /**
+ */
+ virtual void activate( TQCString asn_id );
+
+};
+
+
+// vim: sw=4 et sts=4
+#endif //__tdecmshell_h__
diff --git a/tdeconf_update/CMakeLists.txt b/tdeconf_update/CMakeLists.txt
new file mode 100644
index 000000000..fffb66e80
--- /dev/null
+++ b/tdeconf_update/CMakeLists.txt
@@ -0,0 +1,34 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### tdeconf_update ##############################
+
+set( target tdeconf_update )
+
+set( ${target}_SRCS
+ tdeconf_update.cpp
+)
+
+tde_add_tdeinit_executable( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdecore-shared
+)
diff --git a/tdeconf_update/Mainpage.dox b/tdeconf_update/Mainpage.dox
new file mode 100644
index 000000000..2557fe1c0
--- /dev/null
+++ b/tdeconf_update/Mainpage.dox
@@ -0,0 +1,31 @@
+/** @mainpage ./tdeconf_update
+
+tdeconf_update is a tool designed to update config files. Over time applications
+sometimes need to rearrange the way configuration options are stored. Since
+such an update shouldn't influence the configuration options that the user
+has selected, the application must take care that the options stored in the
+old way will still be honored.
+
+What used to happen is that the application looks up both the old and the
+new configuration option and then decides which one to use. This method has
+several drawbacks:
+- The application may need to read more configuration files than strictly
+ needed, resulting in a slower startup.
+- The application becomes bigger with code that will only be used once.
+
+tdeconf_update addresses these problems by offering a framework to update
+configuration files without adding code to the application itself.
+
+See the README file for more information.
+
+@authors
+Waldo Bastian \<bastian@kde.org\>
+
+@maintainers
+[Unknown/None]
+
+@licenses
+@lgpl
+
+*/
+// vim:ts=4:sw=4:expandtab:filetype=doxygen
diff --git a/tdeconf_update/Makefile.am b/tdeconf_update/Makefile.am
new file mode 100644
index 000000000..9041aad8a
--- /dev/null
+++ b/tdeconf_update/Makefile.am
@@ -0,0 +1,33 @@
+# This file is part of the KDE libraries
+# Copyright (C) 2001 Waldo Bastian <bastian@kde.org>
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+INCLUDES= -I../kded $(all_includes)
+
+bin_PROGRAMS =
+lib_LTLIBRARIES =
+tdeinit_LTLIBRARIES = tdeconf_update.la
+
+tdeconf_update_la_SOURCES = tdeconf_update.cpp
+tdeconf_update_la_LIBADD = $(LIB_TDECORE) $(LIB_QT)
+tdeconf_update_la_LDFLAGS = $(all_libraries) -module -avoid-version
+
+METASOURCES = AUTO
+
+# Internal
+# noinst_HEADERS = tdeconf_update.h
+
diff --git a/tdeconf_update/README.tdeconf_update b/tdeconf_update/README.tdeconf_update
new file mode 100644
index 000000000..340f71eaa
--- /dev/null
+++ b/tdeconf_update/README.tdeconf_update
@@ -0,0 +1,251 @@
+README tdeconf_update
+
+Version: 1.1
+Author: Waldo Bastian <bastian@kde.org>, <bastian@suse.com>
+
+What it does
+============
+
+tdeconf_update is a tool designed to update config files. Over time applications
+sometimes need to rearrange the way configuration options are stored. Since
+such an update shouldn't influence the configuration options that the user
+has selected, the application must take care that the options stored in the
+old way will still be honored.
+
+What used to happen is that the application looks up both the old and the
+new configuration option and then decides which one to use. This method has
+several drawbacks:
+* The application may need to read more configuration files than strictly
+needed, resulting in a slower startup.
+* The application becomes bigger with code that will only be used once.
+
+tdeconf_update addresses these problems by offering a framework to update
+configuration files without adding code to the application itself.
+
+
+How it works
+============
+
+Applications can install so called "update files" under
+$TDEDIR/share/apps/tdeconf_update. An update file has ".upd" as extension and
+contains instructions for transferring/converting configuration information
+from one place to another.
+
+Updating the configuration happens automatically, either when KDE gets started
+or when kded detects a new update file in the above mentioned location.
+
+Update files are separated into sections. Each section has an Id. When a
+section describing a configuration change has been applied, the Id will be
+stored in the file "tdeconf_updaterc". This information is used to make sure
+that a configuration update is only performed once.
+
+If you overwrite an existing update file with a new version that contains a
+new section, only the update instructions from this extra section will be
+performed.
+
+File format of the update file
+==============================
+
+Empty lines or lines that start with '#' are considered comments.
+Commas (,) are used to seperate fields and may not occur as part
+of any field and all of the keywords are case-sensitive, i.e. you
+cannot say "key" instead of "Key" for example.
+
+For the rest the file is parsed and executed sequentially from top to bottom.
+Each line can contain one entry. The following entries are recognized:
+
+
+Id=<id>
+
+With <id> identifying the group of update entries that follows. Once a group
+of entries have been applied, their <id> is stored and this group of entries
+will not be applied again.
+
+
+File=<oldfile>,<newfile>
+File=<oldfile>
+
+Specifies that configuration information is read from <oldfile> and written
+to <newfile>. If you only specify <oldfile>, the information is read from
+as well as written to <oldfile>.
+
+Script=<script>[,<interpreter>]
+
+All entries from <oldfile> are piped into <script>. The output of script
+is used as new entries for <newfile>. Existing entries can be deleted by
+adding lines with "# DELETE [group]key" in the output of the script.
+To delete a whole group use "# DELETEGROUP [group]".
+
+<script> should be installed into $(kde_datadir)/tdeconf_update, or
+tdeconf_update will not be able to find it. It is not portable to install
+binary applications in $kde_datadir, so you have to stick with interpreted
+scripts like sh or perl scripts. From KDE 3.2 onwards it's also possible
+to install tdeconf_update applications in $(kde_bindir)/tdeconf_update_bin,
+which opens the door to tdeconf_update applications that are written in C++
+and use Qt's powerful string API instead.
+
+A workaround for KDE 3.1.x and older is to install a .sh script in
+$(kde_datadir) that contains a simple exec:
+
+ exec "`tde-config --prefix`/bin/tdeconf_update_bin/my_update_app"
+
+This is equivalent to what KDE 3.2 can do directly, but of course the .upd
+file now points to the .sh script instead of the binary application.
+
+If Script was issued after a "Group" command the behavior is slightly
+different:
+All entries from <oldfile>/<oldgroup> are piped into <script>. The output
+of script is used as new entries for <newfile>/<newgroup>, unless a different
+group is specified with "[group]". Existing entries can be deleted from
+<oldgroup> by adding lines with "# DELETE key" in the output of the script.
+To delete <oldgroup> use "# DELETEGROUP".
+
+<interpreter> can be something like "perl".
+
+Since KDE 3.3 it is also possible to have a Script without specifying
+<oldfile> or <newfile>. In that case the script is run but it will not be
+fed any input and its output will simply be discarded.
+
+ScriptArguments=<arguments>
+
+If specified, the arguments will be passed to <script>.
+IMPORTANT: It has to be specified before Script=.
+
+Group=<oldgroup>,<newgroup>
+Group=<oldgroup>
+
+Specifies that configuration information is read from the group <oldgroup>
+and written to <newgroup>. If you only specify <oldgroup>, the information
+is read from as well as written to <oldgroup>. You can use <default> to
+specify keys that are not under any group.
+
+RemoveGroup=<oldgroup>
+
+Specifies that <oldgroup> is removed entirely. This can be used
+to remove obsolete entries or to force a revert to default values.
+
+Options=<option1>, <option2>, ....
+
+With this entry you can specify options that apply to the next "Script",
+"Key" or "AllKeys" entry (only to the first!). Possible options are:
+
+- "copy" Copy the configuration item instead of moving it. This means that
+ the configuration item will not be deleted from <oldfile>/<oldgroup>.
+
+- "overwrite" Normally, a configuration item is not moved if an item with the
+ new name already exists. When this option is specified the old
+ configuration item will overwrite any existing item.
+
+
+Key=<oldkey>,<newkey>
+Key=<oldkey>
+
+Specifies that configuration information is read from the key <oldkey>
+and written to <newkey>. If you only specify <oldkey>, the information
+is read from as well as written to <oldkey>.
+
+
+AllKeys
+
+Specifies that all configuration information in the selected group should
+be moved (All keys).
+
+AllGroups
+
+Specifies that all configuration information from all keys in ALL
+groups should be moved.
+
+
+RemoveKey=<oldkey>
+
+Specifies that <oldkey> is removed from the selected group. This can be used
+to remove obsolete entries or to force a revert to default values.
+
+
+Example update file
+===================
+
+# This is comment
+Id=kde2.2
+File=tdeioslaverc,kio_httprc
+Group=Proxy Settings
+Key=NoProxyFor
+Key=UseProxy
+Key=httpProxy,Proxy
+Group=Cache Settings,Cache
+Key=MaxCacheSize
+Key=UseCache
+Group=UserAgent
+AllKeys
+RemoveGroup=KDE
+# End of file
+
+
+The above update file extracts config information from the file "tdeioslaverc"
+and stores it into the file "kio_httprc".
+
+It reads the keys "NoProxyFor", "UseProxy" and "httpProxy" from the group
+"Proxy Settings" in the "tdeioslaverc" file. If any of these options are present
+they are written to the keys "NoProxyFor", "UseProxy" and "Proxy" (!) in
+the group "Proxy Settings" in the "kio_httprc" file.
+
+It also reads the keys "MaxCacheSize" and "UseCache" from the group
+"Cache Settings" in the "tdeioslaverc" file and writes this information to the
+keys "MaxCacheSize" and "UseCache" in the group "Cache" (!) in the
+"kio_httprc" file.
+
+Then it takes all keys in the "UserAgent" group of the file "tdeioslaverc"
+and moves then to the "UserAgent" group in the "kio_httprc" file.
+
+Finally it removes the entire "KDE" group in the tdeioslaverc file.
+
+
+Debugging and testing
+=====================
+
+If you are developing a tdeconf_update script and want to test or debug it you
+need to make sure tdeconf_update runs again after each of your changes. There
+are a number of ways to achieve this.
+
+The easiest is to not install the tdeconf_update script in the first place, but
+manually call it through a pipe. If you want to test the update script for
+your application KHello's config file khellorc, you can test by using
+
+ cat ~/.trinity/share/config/khellorc | khello_conf_update.sh
+
+(assuming khello_conf_update.sh is the tdeconf_update script and ~/.trinity is your
+$TDEHOME). This is easier than making install every time, but has the obvious
+downside that you need to 'parse' your script's output yourself instead of
+letting tdeconf_update do it and check the resulting output file.
+
+After 'make install' the tdeconf_update script is run by kded, but it does so
+only once. This is of course the idea behind it, but while developing it can
+be a problem. You can increase the revision number for each subsequent run
+of 'make install' to force a new tdeconf_update run, but there's a better
+approach that doesn't skyrocket the version number for a mediocre debug
+session.
+
+kded doesn't really ignore scripts that it has already run right away.
+Instead it checks the affected config file every time a .upd file is added
+or changed. The reason it still doesn't run again on your config file lies
+in the traces tdeconf_update leaves behind: it adds a special config group
+'[$Version]' with a key 'update_info'. This key lists all tdeconf_update
+scripts that have already been run on this config file. Just remove your
+file's entry, 'make install', and tdeconf_update will happily run your script
+again, without you having to increase the version number.
+
+If you want to know what tdeconf_update has been up to lately, have a look
+at $TDEHOME/share/apps/tdeconf_update/update.log
+
+
+Common Problems
+===============
+
+* tdeconf_update refuses to update an entry
+If you change the value of an entry without changing the key or file,
+make sure to tell tdeconf_update that it should overwrite the old entry
+by adding "Options=overwrite".
+
+
+Have fun,
+Waldo
diff --git a/tdeconf_update/tdeconf_update.cpp b/tdeconf_update/tdeconf_update.cpp
new file mode 100644
index 000000000..206711274
--- /dev/null
+++ b/tdeconf_update/tdeconf_update.cpp
@@ -0,0 +1,959 @@
+/*
+ *
+ * This file is part of the KDE libraries
+ * Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
+ *
+ * $Id$
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+#include <tqfile.h>
+#include <tqtextstream.h>
+
+#include <tdeconfig.h>
+#include <ksimpleconfig.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+#include <kglobal.h>
+#include <kstandarddirs.h>
+#include <kaboutdata.h>
+#include <kinstance.h>
+#include <ktempfile.h>
+
+static KCmdLineOptions options[] =
+{
+ { "debug", I18N_NOOP("Keep output results from scripts"), 0 },
+ { "check <update-file>", I18N_NOOP("Check whether config file itself requires updating"), 0 },
+ { "+[file]", I18N_NOOP("File to read update instructions from"), 0 },
+ KCmdLineLastOption
+};
+
+class KonfUpdate
+{
+public:
+ KonfUpdate();
+ ~KonfUpdate();
+ TQStringList findUpdateFiles(bool dirtyOnly);
+
+ TQTextStream &log();
+
+ bool checkFile(const TQString &filename);
+ void checkGotFile(const TQString &_file, const TQString &id);
+
+ bool updateFile(const TQString &filename);
+
+ void gotId(const TQString &_id);
+ void gotFile(const TQString &_file);
+ void gotGroup(const TQString &_group);
+ void gotRemoveGroup(const TQString &_group);
+ void gotKey(const TQString &_key);
+ void gotRemoveKey(const TQString &_key);
+ void gotAllKeys();
+ void gotAllGroups();
+ void gotOptions(const TQString &_options);
+ void gotScript(const TQString &_script);
+ void gotScriptArguments(const TQString &_arguments);
+ void resetOptions();
+
+ void copyGroup(TDEConfigBase *cfg1, const TQString &grp1,
+ TDEConfigBase *cfg2, const TQString &grp2);
+
+protected:
+ TDEConfig *config;
+ TQString currentFilename;
+ bool skip;
+ bool debug;
+ TQString id;
+
+ TQString oldFile;
+ TQString newFile;
+ TQString newFileName;
+ TDEConfig *oldConfig1; // Config to read keys from.
+ TDEConfig *oldConfig2; // Config to delete keys from.
+ TDEConfig *newConfig;
+
+ TQString oldGroup;
+ TQString newGroup;
+ TQString oldKey;
+ TQString newKey;
+
+ bool m_bCopy;
+ bool m_bOverwrite;
+ bool m_bUseConfigInfo;
+ TQString m_arguments;
+ TQTextStream *m_textStream;
+ TQFile *m_file;
+ TQString m_line;
+ int m_lineCount;
+};
+
+KonfUpdate::KonfUpdate()
+ : m_textStream(0), m_file(0)
+{
+ bool updateAll = false;
+ oldConfig1 = 0;
+ oldConfig2 = 0;
+ newConfig = 0;
+
+ config = new TDEConfig("tdeconf_updaterc");
+
+ TQStringList updateFiles;
+ TDECmdLineArgs *args=TDECmdLineArgs::parsedArgs();
+
+ debug = args->isSet("debug");
+
+ m_bUseConfigInfo = false;
+ if (args->isSet("check"))
+ {
+ m_bUseConfigInfo = true;
+ TQString file = locate("data", "tdeconf_update/"+TQFile::decodeName(args->getOption("check")));
+ if (file.isEmpty())
+ {
+ tqWarning("File '%s' not found.", args->getOption("check").data());
+ log() << "File '" << TQFile::decodeName(args->getOption("check")) << "' passed on command line not found" << endl;
+ return;
+ }
+ updateFiles.append(file);
+ }
+ else if (args->count())
+ {
+ for(int i = 0; i < args->count(); i++)
+ {
+ KURL url = args->url(i);
+ if (!url.isLocalFile())
+ TDECmdLineArgs::usage(i18n("Only local files are supported."));
+ updateFiles.append(url.path());
+ }
+ }
+ else
+ {
+ if (config->readBoolEntry("autoUpdateDisabled", false))
+ return;
+ updateFiles = findUpdateFiles(true);
+ updateAll = true;
+ }
+
+ for(TQStringList::ConstIterator it = updateFiles.begin();
+ it != updateFiles.end();
+ ++it)
+ {
+ TQString file = *it;
+ updateFile(file);
+ }
+
+ config->setGroup(TQString::null);
+ if (updateAll && !config->readBoolEntry("updateInfoAdded", false))
+ {
+ config->writeEntry("updateInfoAdded", true);
+ updateFiles = findUpdateFiles(false);
+
+ for(TQStringList::ConstIterator it = updateFiles.begin();
+ it != updateFiles.end();
+ ++it)
+ {
+ TQString file = *it;
+ checkFile(file);
+ }
+ updateFiles.clear();
+ }
+}
+
+KonfUpdate::~KonfUpdate()
+{
+ delete config;
+ delete m_file;
+ delete m_textStream;
+}
+
+TQTextStream &
+KonfUpdate::log()
+{
+ if (!m_textStream)
+ {
+ TQString file = locateLocal("data", "tdeconf_update/log/update.log");
+ m_file = new TQFile(file);
+ if (m_file->open(IO_WriteOnly | IO_Append))
+ {
+ m_textStream = new TQTextStream(m_file);
+ }
+ else
+ {
+ // Error
+ m_textStream = new TQTextStream(stderr, IO_WriteOnly);
+ }
+ }
+
+ (*m_textStream) << TQDateTime::currentDateTime().toString( Qt::ISODate ) << " ";
+
+ return *m_textStream;
+}
+
+TQStringList KonfUpdate::findUpdateFiles(bool dirtyOnly)
+{
+ TQStringList result;
+ TQStringList list = TDEGlobal::dirs()->findAllResources("data", "tdeconf_update/*.upd", false, true);
+ for(TQStringList::ConstIterator it = list.begin();
+ it != list.end();
+ ++it)
+ {
+ TQString file = *it;
+ struct stat buff;
+ if (stat( TQFile::encodeName(file), &buff) == 0)
+ {
+ int i = file.findRev('/');
+ if (i != -1)
+ file = file.mid(i+1);
+ config->setGroup(file);
+ time_t ctime = config->readUnsignedLongNumEntry("ctime");
+ time_t mtime = config->readUnsignedLongNumEntry("mtime");
+ if (!dirtyOnly ||
+ (ctime != buff.st_ctime) || (mtime != buff.st_mtime))
+ {
+ result.append(*it);
+ }
+ }
+ }
+ return result;
+}
+
+bool KonfUpdate::checkFile(const TQString &filename)
+{
+ currentFilename = filename;
+ int i = currentFilename.findRev('/');
+ if (i != -1)
+ currentFilename = currentFilename.mid(i+1);
+ skip = true;
+ TQFile file(filename);
+ if (!file.open(IO_ReadOnly))
+ return false;
+
+ TQTextStream ts(&file);
+ ts.setEncoding(TQTextStream::Latin1);
+ int lineCount = 0;
+ resetOptions();
+ TQString id;
+ while(!ts.atEnd())
+ {
+ TQString line = ts.readLine().stripWhiteSpace();
+ lineCount++;
+ if (line.isEmpty() || (line[0] == '#'))
+ continue;
+ if (line.startsWith("Id="))
+ id = currentFilename+":"+line.mid(3);
+ else if (line.startsWith("File="))
+ checkGotFile(line.mid(5), id);
+ }
+
+ return true;
+}
+
+void KonfUpdate::checkGotFile(const TQString &_file, const TQString &id)
+{
+ TQString file;
+ int i = _file.find(',');
+ if (i == -1)
+ {
+ file = _file.stripWhiteSpace();
+ }
+ else
+ {
+ file = _file.mid(i+1).stripWhiteSpace();
+ }
+
+// tqDebug("File %s, id %s", file.latin1(), id.latin1());
+
+ KSimpleConfig cfg(file);
+ cfg.setGroup("$Version");
+ TQStringList ids = cfg.readListEntry("update_info");
+ if (ids.contains(id))
+ return;
+ ids.append(id);
+ cfg.writeEntry("update_info", ids);
+}
+
+/**
+ * Syntax:
+ * # Comment
+ * Id=id
+ * File=oldfile[,newfile]
+ * AllGroups
+ * Group=oldgroup[,newgroup]
+ * RemoveGroup=oldgroup
+ * Options=[copy,][overwrite,]
+ * Key=oldkey[,newkey]
+ * RemoveKey=ldkey
+ * AllKeys
+ * Keys= [Options](AllKeys|(Key|RemoveKey)*)
+ * ScriptArguments=arguments
+ * Script=scriptfile[,interpreter]
+ *
+ * Sequence:
+ * (Id,(File(Group,Keys)*)*)*
+ **/
+bool KonfUpdate::updateFile(const TQString &filename)
+{
+ currentFilename = filename;
+ int i = currentFilename.findRev('/');
+ if (i != -1)
+ currentFilename = currentFilename.mid(i+1);
+ skip = true;
+ TQFile file(filename);
+ if (!file.open(IO_ReadOnly))
+ return false;
+
+ log() << "Checking update-file '" << filename << "' for new updates" << endl;
+
+ TQTextStream ts(&file);
+ ts.setEncoding(TQTextStream::Latin1);
+ m_lineCount = 0;
+ resetOptions();
+ while(!ts.atEnd())
+ {
+ m_line = ts.readLine().stripWhiteSpace();
+ m_lineCount++;
+ if (m_line.isEmpty() || (m_line[0] == '#'))
+ continue;
+ if (m_line.startsWith("Id="))
+ gotId(m_line.mid(3));
+ else if (skip)
+ continue;
+ else if (m_line.startsWith("Options="))
+ gotOptions(m_line.mid(8));
+ else if (m_line.startsWith("File="))
+ gotFile(m_line.mid(5));
+ else if (m_line.startsWith("Group="))
+ gotGroup(m_line.mid(6));
+ else if (m_line.startsWith("RemoveGroup="))
+ {
+ gotRemoveGroup(m_line.mid(12));
+ resetOptions();
+ }
+ else if (m_line.startsWith("Script="))
+ {
+ gotScript(m_line.mid(7));
+ resetOptions();
+ }
+ else if (m_line.startsWith("ScriptArguments="))
+ gotScriptArguments(m_line.mid(16));
+ else if (m_line.startsWith("Key="))
+ {
+ gotKey(m_line.mid(4));
+ resetOptions();
+ }
+ else if (m_line.startsWith("RemoveKey="))
+ {
+ gotRemoveKey(m_line.mid(10));
+ resetOptions();
+ }
+ else if (m_line == "AllKeys")
+ {
+ gotAllKeys();
+ resetOptions();
+ }
+ else if (m_line == "AllGroups")
+ {
+ gotAllGroups();
+ resetOptions();
+ }
+ else
+ {
+ log() << currentFilename << ": parse error in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ }
+ }
+ // Flush.
+ gotId(TQString::null);
+
+ struct stat buff;
+ stat( TQFile::encodeName(filename), &buff);
+ config->setGroup(currentFilename);
+ config->writeEntry("ctime", buff.st_ctime);
+ config->writeEntry("mtime", buff.st_mtime);
+ config->sync();
+ return true;
+}
+
+
+
+void KonfUpdate::gotId(const TQString &_id)
+{
+ if (!id.isEmpty() && !skip)
+ {
+ config->setGroup(currentFilename);
+ TQStringList ids = config->readListEntry("done");
+ if (!ids.contains(id))
+ {
+ ids.append(id);
+ config->writeEntry("done", ids);
+ config->sync();
+ }
+ }
+
+ // Flush pending changes
+ gotFile(TQString::null);
+
+ config->setGroup(currentFilename);
+ TQStringList ids = config->readListEntry("done");
+ if (!_id.isEmpty())
+ {
+ if (ids.contains(_id))
+ {
+ //tqDebug("Id '%s' was already in done-list", _id.latin1());
+ if (!m_bUseConfigInfo)
+ {
+ skip = true;
+ return;
+ }
+ }
+ skip = false;
+ id = _id;
+ if (m_bUseConfigInfo)
+ log() << currentFilename << ": Checking update '" << _id << "'" << endl;
+ else
+ log() << currentFilename << ": Found new update '" << _id << "'" << endl;
+ }
+}
+
+void KonfUpdate::gotFile(const TQString &_file)
+{
+ // Reset group
+ gotGroup(TQString::null);
+
+ if (!oldFile.isEmpty())
+ {
+ // Close old file.
+ delete oldConfig1;
+ oldConfig1 = 0;
+
+ oldConfig2->setGroup("$Version");
+ TQStringList ids = oldConfig2->readListEntry("update_info");
+ TQString cfg_id = currentFilename + ":" + id;
+ if (!ids.contains(cfg_id) && !skip)
+ {
+ ids.append(cfg_id);
+ oldConfig2->writeEntry("update_info", ids);
+ }
+ oldConfig2->sync();
+ delete oldConfig2;
+ oldConfig2 = 0;
+
+ TQString file = locateLocal("config", oldFile);
+ struct stat s_buf;
+ if (stat(TQFile::encodeName(file), &s_buf) == 0)
+ {
+ if (s_buf.st_size == 0)
+ {
+ // Delete empty file.
+ unlink(TQFile::encodeName(file));
+ }
+ }
+
+ oldFile = TQString::null;
+ }
+ if (!newFile.isEmpty())
+ {
+ // Close new file.
+ newConfig->setGroup("$Version");
+ TQStringList ids = newConfig->readListEntry("update_info");
+ TQString cfg_id = currentFilename + ":" + id;
+ if (!ids.contains(cfg_id) && !skip)
+ {
+ ids.append(cfg_id);
+ newConfig->writeEntry("update_info", ids);
+ }
+ newConfig->sync();
+ delete newConfig;
+ newConfig = 0;
+
+ newFile = TQString::null;
+ }
+ newConfig = 0;
+
+ int i = _file.find(',');
+ if (i == -1)
+ {
+ oldFile = _file.stripWhiteSpace();
+ }
+ else
+ {
+ oldFile = _file.left(i).stripWhiteSpace();
+ newFile = _file.mid(i+1).stripWhiteSpace();
+ if (oldFile == newFile)
+ newFile = TQString::null;
+ }
+
+ if (!oldFile.isEmpty())
+ {
+ oldConfig2 = new TDEConfig(oldFile, false, false);
+ TQString cfg_id = currentFilename + ":" + id;
+ oldConfig2->setGroup("$Version");
+ TQStringList ids = oldConfig2->readListEntry("update_info");
+ if (ids.contains(cfg_id))
+ {
+ skip = true;
+ newFile = TQString::null;
+ log() << currentFilename << ": Skipping update '" << id << "'" << endl;
+ }
+
+ if (!newFile.isEmpty())
+ {
+ newConfig = new TDEConfig(newFile, false, false);
+ newConfig->setGroup("$Version");
+ ids = newConfig->readListEntry("update_info");
+ if (ids.contains(cfg_id))
+ {
+ skip = true;
+ log() << currentFilename << ": Skipping update '" << id << "'" << endl;
+ }
+ }
+ else
+ {
+ newConfig = oldConfig2;
+ }
+
+ oldConfig1 = new TDEConfig(oldFile, true, false);
+ }
+ else
+ {
+ newFile = TQString::null;
+ }
+ newFileName = newFile;
+ if (newFileName.isEmpty())
+ newFileName = oldFile;
+}
+
+void KonfUpdate::gotGroup(const TQString &_group)
+{
+ int i = _group.find(',');
+ if (i == -1)
+ {
+ oldGroup = _group.stripWhiteSpace();
+ newGroup = oldGroup;
+ }
+ else
+ {
+ oldGroup = _group.left(i).stripWhiteSpace();
+ newGroup = _group.mid(i+1).stripWhiteSpace();
+ }
+}
+
+void KonfUpdate::gotRemoveGroup(const TQString &_group)
+{
+ oldGroup = _group.stripWhiteSpace();
+
+ if (!oldConfig1)
+ {
+ log() << currentFilename << ": !! RemoveGroup without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ return;
+ }
+
+ if (!oldConfig1->hasGroup(oldGroup))
+ return;
+ // Delete group.
+ oldConfig2->deleteGroup(oldGroup, true);
+ log() << currentFilename << ": RemoveGroup removes group " << oldFile << ":" << oldGroup << endl;
+}
+
+
+void KonfUpdate::gotKey(const TQString &_key)
+{
+ int i = _key.find(',');
+ if (i == -1)
+ {
+ oldKey = _key.stripWhiteSpace();
+ newKey = oldKey;
+ }
+ else
+ {
+ oldKey = _key.left(i).stripWhiteSpace();
+ newKey = _key.mid(i+1).stripWhiteSpace();
+ }
+
+ if (oldKey.isEmpty() || newKey.isEmpty())
+ {
+ log() << currentFilename << ": !! Key specifies invalid key in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ return;
+ }
+ if (!oldConfig1)
+ {
+ log() << currentFilename << ": !! Key without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ return;
+ }
+ oldConfig1->setGroup(oldGroup);
+ if (!oldConfig1->hasKey(oldKey))
+ return;
+ TQString value = oldConfig1->readEntry(oldKey);
+ newConfig->setGroup(newGroup);
+ if (!m_bOverwrite && newConfig->hasKey(newKey))
+ {
+ log() << currentFilename << ": Skipping " << newFileName << ":" << newGroup << ":" << newKey << ", already exists."<< endl;
+ return;
+ }
+ log() << currentFilename << ": Updating " << newFileName << ":" << newGroup << ":" << newKey << " to '" << value << "'" << endl;
+ newConfig->writeEntry(newKey, value);
+
+ if (m_bCopy)
+ return; // Done.
+
+ // Delete old entry
+ if ((oldConfig2 == newConfig) &&
+ (oldGroup == newGroup) &&
+ (oldKey == newKey))
+ return; // Don't delete!
+ oldConfig2->setGroup(oldGroup);
+ oldConfig2->deleteEntry(oldKey, false);
+ log() << currentFilename << ": Removing " << oldFile << ":" << oldGroup << ":" << oldKey << ", moved." << endl;
+ if (oldConfig2->deleteGroup(oldGroup, false)) { // Delete group if empty.
+ log() << currentFilename << ": Removing empty group " << oldFile << ":" << oldGroup << endl;
+ }
+}
+
+void KonfUpdate::gotRemoveKey(const TQString &_key)
+{
+ oldKey = _key.stripWhiteSpace();
+
+ if (oldKey.isEmpty())
+ {
+ log() << currentFilename << ": !! RemoveKey specifies invalid key in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ return;
+ }
+
+ if (!oldConfig1)
+ {
+ log() << currentFilename << ": !! Key without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ return;
+ }
+
+ oldConfig1->setGroup(oldGroup);
+ if (!oldConfig1->hasKey(oldKey))
+ return;
+ log() << currentFilename << ": RemoveKey removes " << oldFile << ":" << oldGroup << ":" << oldKey << endl;
+
+ // Delete old entry
+ oldConfig2->setGroup(oldGroup);
+ oldConfig2->deleteEntry(oldKey, false);
+ if (oldConfig2->deleteGroup(oldGroup, false)) { // Delete group if empty.
+ log() << currentFilename << ": Removing empty group " << oldFile << ":" << oldGroup << endl;
+ }
+}
+
+void KonfUpdate::gotAllKeys()
+{
+ if (!oldConfig1)
+ {
+ log() << currentFilename << ": !! AllKeys without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ return;
+ }
+
+ TQMap<TQString, TQString> list = oldConfig1->entryMap(oldGroup);
+ for(TQMap<TQString, TQString>::Iterator it = list.begin();
+ it != list.end(); ++it)
+ {
+ gotKey(it.key());
+ }
+}
+
+void KonfUpdate::gotAllGroups()
+{
+ if (!oldConfig1)
+ {
+ log() << currentFilename << ": !! AllGroups without previous File specification in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ return;
+ }
+
+ TQStringList allGroups = oldConfig1->groupList();
+ for(TQStringList::ConstIterator it = allGroups.begin();
+ it != allGroups.end(); ++it)
+ {
+ oldGroup = *it;
+ newGroup = oldGroup;
+ gotAllKeys();
+ }
+}
+
+void KonfUpdate::gotOptions(const TQString &_options)
+{
+ TQStringList options = TQStringList::split(',', _options);
+ for(TQStringList::ConstIterator it = options.begin();
+ it != options.end();
+ ++it)
+ {
+ if ( (*it).lower().stripWhiteSpace() == "copy")
+ m_bCopy = true;
+
+ if ( (*it).lower().stripWhiteSpace() == "overwrite")
+ m_bOverwrite = true;
+ }
+}
+
+void KonfUpdate::copyGroup(TDEConfigBase *cfg1, const TQString &grp1,
+ TDEConfigBase *cfg2, const TQString &grp2)
+{
+ cfg1->setGroup(grp1);
+ cfg2->setGroup(grp2);
+ TQMap<TQString, TQString> list = cfg1->entryMap(grp1);
+ for(TQMap<TQString, TQString>::Iterator it = list.begin();
+ it != list.end(); ++it)
+ {
+ cfg2->writeEntry(it.key(), cfg1->readEntry(it.key()));
+ }
+}
+
+void KonfUpdate::gotScriptArguments(const TQString &_arguments)
+{
+ m_arguments = _arguments;
+}
+
+void KonfUpdate::gotScript(const TQString &_script)
+{
+ TQString script, interpreter;
+ int i = _script.find(',');
+ if (i == -1)
+ {
+ script = _script.stripWhiteSpace();
+ }
+ else
+ {
+ script = _script.left(i).stripWhiteSpace();
+ interpreter = _script.mid(i+1).stripWhiteSpace();
+ }
+
+
+ if (script.isEmpty())
+ {
+ log() << currentFilename << ": !! Script fails to specifiy filename in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ skip = true;
+ return;
+ }
+
+
+
+ TQString path = locate("data","tdeconf_update/"+script);
+ if (path.isEmpty())
+ {
+ if (interpreter.isEmpty())
+ path = locate("lib", "tdeconf_update_bin/"+script);
+
+ if (path.isEmpty())
+ {
+ log() << currentFilename << ": !! Script '" << script << "' not found in line " << m_lineCount << " : '" << m_line << "'" << endl;
+ skip = true;
+ return;
+ }
+ }
+
+ if( !m_arguments.isNull())
+ log() << currentFilename << ": Running script '" << script << "' with arguments '" << m_arguments << "'" << endl;
+ else
+ log() << currentFilename << ": Running script '" << script << "'" << endl;
+
+ TQString cmd;
+ if (interpreter.isEmpty())
+ cmd = path;
+ else
+ cmd = interpreter + " " + path;
+
+ if( !m_arguments.isNull())
+ {
+ cmd += ' ';
+ cmd += m_arguments;
+ }
+
+ KTempFile tmp1;
+ tmp1.setAutoDelete(true);
+ KTempFile tmp2;
+ tmp2.setAutoDelete(true);
+ KTempFile tmp3;
+ tmp3.setAutoDelete(true);
+
+ int result;
+ if (oldConfig1)
+ {
+ if (debug)
+ {
+ tmp1.setAutoDelete(false);
+ log() << "Script input stored in " << tmp1.name() << endl;
+ }
+ KSimpleConfig cfg(tmp1.name());
+
+ if (oldGroup.isEmpty())
+ {
+ // Write all entries to tmpFile;
+ TQStringList grpList = oldConfig1->groupList();
+ for(TQStringList::ConstIterator it = grpList.begin();
+ it != grpList.end();
+ ++it)
+ {
+ copyGroup(oldConfig1, *it, &cfg, *it);
+ }
+ }
+ else
+ {
+ copyGroup(oldConfig1, oldGroup, &cfg, TQString::null);
+ }
+ cfg.sync();
+ result = system(TQFile::encodeName(TQString("%1 < %2 > %3 2> %4").arg(cmd, tmp1.name(), tmp2.name(), tmp3.name())));
+ }
+ else
+ {
+ // No config file
+ result = system(TQFile::encodeName(TQString("%1 2> %2").arg(cmd, tmp3.name())));
+ }
+
+ // Copy script stderr to log file
+ {
+ TQFile output(tmp3.name());
+ if (output.open(IO_ReadOnly))
+ {
+ TQTextStream ts( &output );
+ ts.setEncoding(TQTextStream::UnicodeUTF8);
+ while(!ts.atEnd())
+ {
+ TQString line = ts.readLine();
+ log() << "[Script] " << line << endl;
+ }
+ }
+ }
+
+ if (result)
+ {
+ log() << currentFilename << ": !! An error occured while running '" << cmd << "'" << endl;
+ return;
+ }
+
+ if (!oldConfig1)
+ return; // Nothing to merge
+
+ if (debug)
+ {
+ tmp2.setAutoDelete(false);
+ log() << "Script output stored in " << tmp2.name() << endl;
+ }
+
+ // Deleting old entries
+ {
+ TQString group = oldGroup;
+ TQFile output(tmp2.name());
+ if (output.open(IO_ReadOnly))
+ {
+ TQTextStream ts( &output );
+ ts.setEncoding(TQTextStream::UnicodeUTF8);
+ while(!ts.atEnd())
+ {
+ TQString line = ts.readLine();
+ if (line.startsWith("["))
+ {
+ int j = line.find(']')+1;
+ if (j > 0)
+ group = line.mid(1, j-2);
+ }
+ else if (line.startsWith("# DELETE "))
+ {
+ TQString key = line.mid(9);
+ if (key[0] == '[')
+ {
+ int j = key.find(']')+1;
+ if (j > 0)
+ {
+ group = key.mid(1,j-2);
+ key = key.mid(j);
+ }
+ }
+ oldConfig2->setGroup(group);
+ oldConfig2->deleteEntry(key, false);
+ log() << currentFilename << ": Script removes " << oldFile << ":" << group << ":" << key << endl;
+ if (oldConfig2->deleteGroup(group, false)) { // Delete group if empty.
+ log() << currentFilename << ": Removing empty group " << oldFile << ":" << group << endl;
+ }
+ }
+ else if (line.startsWith("# DELETEGROUP"))
+ {
+ TQString key = line.mid(13).stripWhiteSpace();
+ if (key[0] == '[')
+ {
+ int j = key.find(']')+1;
+ if (j > 0)
+ {
+ group = key.mid(1,j-2);
+ }
+ }
+ if (oldConfig2->deleteGroup(group, true)) { // Delete group
+ log() << currentFilename << ": Script removes group " << oldFile << ":" << group << endl;
+ }
+ }
+ }
+ }
+ }
+
+ // Merging in new entries.
+ m_bCopy = true;
+ {
+ TDEConfig *saveOldConfig1 = oldConfig1;
+ TQString saveOldGroup = oldGroup;
+ TQString saveNewGroup = newGroup;
+ oldConfig1 = new TDEConfig(tmp2.name(), true, false);
+
+ // For all groups...
+ TQStringList grpList = oldConfig1->groupList();
+ for(TQStringList::ConstIterator it = grpList.begin();
+ it != grpList.end();
+ ++it)
+ {
+ oldGroup = *it;
+ if (oldGroup != "<default>")
+ {
+ newGroup = oldGroup;
+ }
+ gotAllKeys(); // Copy all keys
+ }
+ delete oldConfig1;
+ oldConfig1 = saveOldConfig1;
+ oldGroup = saveOldGroup;
+ newGroup = saveNewGroup;
+ }
+}
+
+void KonfUpdate::resetOptions()
+{
+ m_bCopy = false;
+ m_bOverwrite = false;
+ m_arguments = TQString::null;
+}
+
+
+extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
+{
+ TDEAboutData aboutData("tdeconf_update", I18N_NOOP("KConf Update"),
+ "1.0.2",
+ I18N_NOOP("TDE Tool for updating user configuration files"),
+ TDEAboutData::License_GPL,
+ "(c) 2001, Waldo Bastian");
+
+ aboutData.addAuthor("Waldo Bastian", 0, "bastian@kde.org");
+
+ TDECmdLineArgs::init(argc, argv, &aboutData);
+ TDECmdLineArgs::addCmdLineOptions(options);
+
+ TDEInstance instance(&aboutData);
+
+ KonfUpdate konfUpdate;
+
+ return 0;
+}
diff --git a/tdecore/CMakeLists.txt b/tdecore/CMakeLists.txt
index 8d4939d83..dbc2a7065 100644
--- a/tdecore/CMakeLists.txt
+++ b/tdecore/CMakeLists.txt
@@ -11,7 +11,7 @@
add_subdirectory( malloc )
add_subdirectory( network )
-add_subdirectory( kconfig_compiler )
+add_subdirectory( tdeconfig_compiler )
add_subdirectory( hwlibdata )
add_subdirectory( hwlibdaemons )
@@ -53,7 +53,7 @@ include_directories(
${CMAKE_SOURCE_DIR}/libltdl
${CMAKE_SOURCE_DIR}/tdefx
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${LIBART_INCLUDE_DIRS}
${LIBIDN_INCLUDE_DIRS}
${GAMIN_INCLUDEDIR}
@@ -69,9 +69,9 @@ link_directories(
##### headers ###################################
install( FILES
- kconfig.h kconfigskeleton.h kconfigdata.h ksimpleconfig.h
- kconfigdialogmanager.h kconfigbase.h kdesktopfile.h
- kurl.h ksock.h kaboutdata.h kcmdlineargs.h kconfigbackend.h
+ tdeconfig.h tdeconfigskeleton.h tdeconfigdata.h ksimpleconfig.h
+ tdeconfigdialogmanager.h tdeconfigbase.h kdesktopfile.h
+ kurl.h ksock.h kaboutdata.h kcmdlineargs.h tdeconfigbackend.h
kapp.h kapplication.h kuniqueapp.h kuniqueapplication.h
kcharsets.h tdeversion.h kpty.h kprocess.h kprocctrl.h
klocale.h kicontheme.h kiconloader.h kdebug.h twinmodule.h
@@ -110,7 +110,7 @@ install( FILES kdebug.areas kdebugrc language.codes
DESTINATION ${CONFIG_INSTALL_DIR} )
install( FILES kmdcodec_compat.h
- DESTINATION ${INCLUDE_INSTALL_DIR}/kio RENAME kmdcodec.h )
+ DESTINATION ${INCLUDE_INSTALL_DIR}/tdeio RENAME kmdcodec.h )
install( FILES eventsrc
DESTINATION ${DATA_INSTALL_DIR}/knotify )
@@ -121,7 +121,7 @@ set( target tdecore )
set( ${target}_SRCS
libintl.cpp kapplication.cpp kdebug.cpp netwm.cpp
- kconfigbase.cpp kconfig.cpp ksimpleconfig.cpp kconfigbackend.cpp
+ tdeconfigbase.cpp tdeconfig.cpp ksimpleconfig.cpp tdeconfigbackend.cpp
kmanagerselection.cpp kdesktopfile.cpp kstandarddirs.cpp
ksock.cpp kpty.cpp kprocess.cpp kprocctrl.cpp klocale.cpp
krfcdate.cpp kiconeffect.cpp kicontheme.cpp kiconloader.cpp
@@ -148,7 +148,7 @@ set( ${target}_SRCS
kcalendarsystemfactory.cpp kmacroexpander.cpp kidna.cpp
ktempdir.cpp kshell.cpp kmountpoint.cpp kcalendarsystemjalali.cpp
kprotocolinfo_tdecore.cpp kprotocolinfofactory.cpp kxerrorhandler.cpp
- kuser.cpp kconfigskeleton.cpp kconfigdialogmanager.cpp klockfile.cpp
+ kuser.cpp tdeconfigskeleton.cpp tdeconfigdialogmanager.cpp klockfile.cpp
kqiodevicegzip_p.cpp ktimezones.cpp tdehardwaredevices.cpp tdenetworkconnections.cpp
ksimpledirwatch.cpp
${TDENM_BACKEND_SOURCES}
diff --git a/tdecore/DESIGN.kconfig b/tdecore/DESIGN.kconfig
deleted file mode 100644
index c4c68b28e..000000000
--- a/tdecore/DESIGN.kconfig
+++ /dev/null
@@ -1,224 +0,0 @@
-kconfigdata.h contains definitions of the data formats used by kconfig.
-
-Configuration entries are stored as "KEntry". They are indexed with "KEntryKey".
-The primary store is a "KEntryMap" which is defined as a QMap from "KEntryKey"
-to "KEntry"
-
-KEntry's are stored in order in the KEntryMap. The most significant sort
-criteria is mGroup. This means that all entries who belong in the same group,
-are grouped in the QMap as well.
-
-The start of a group is indicated with a KEntryKey with an empty mKey and a
-dummy KEntry. This allows us to search for the start of the group and then to
-iterate until we end up in another group. That way we will find all entries
-of a certain group.
-
-Entries that are localised with the _current_ locale are stored with bLocal
-set to true. Entries that are localised with another locale are either not
-stored at all (default), or with the localization as part of the key (when
-reading a file in order to merge it).
-[WABA: Does it make sense to keep both localized and non-localised around?
-Can't we just let the localised version override the non-localised version?]
-
-Currently the localization bit is the least significant sort criteria, that
-means that the localised version always follows the non-localised version
-immediately.
-
-<Changed for KDE 3.0>
-Entries that are being read from a location other than the location to
-which is written back are marked as "default" and will be added both as
-normal entry as well as an entry with the key marked as default.
-
-When entries are written to disk, it is checked whether the entry to write
-is equal to the default, if so the entry will not be written. The default
-entry always follows directly after the normal entry, due to the sorting.
-(After that the localised version follows)
-
-When entries are written to disk, it is checked whether the entry to write
-is equal to the default, if so the entry will not be written.
-</Changed>
-
-Open question:
-Should unmodified entries that are written back be compared with the default
-too? This seems to be mostly a transition issue.
-
-<Changed during KDE 3.0 / 3.2>
-Extra functions:
-
-bool entryIsImmutable(key); // Can entry be modified?
-bool hasDefault(key); // Is there a system wide default set for the entry?
-void revertToDefault(key); // Restore to default
-void deleteEntry(key); // Remove entry
-
-Note that there is a subtle difference between revertToDefault() and deleteEntry().
-revertToDefault() will change the entry to the default value set by the system
-administrator (Via e.g. $TDEDIR/share/config) or, if no such default was set,
-non-existant.
-deleteEntry() will make the entry non-existant.
-
-Entries are marked "immutable" if the key is followed by [$i]. This means
-that a user can not override these entries.
-
-Entries can be marked as deleted if they are followed by [$d]. This
-is needed if the system administrator has specified a default value but the
-entry was deleted (made 'non-existant'). In that case we can't just leave
-the entry out since that would mean we get the default from the system
-administrator back the next time we read the file.
-</changed>
-
-When an entry is read with readEntry(key, defaultValue), non-existing
-entries will return "defaultValue" while hasKey(key) will return "false"
-for such entries.
-
-Currently all entries are stored in memory. When TDEConfig is "sync()'ed"
-it reads the file that it is about to overwrite (for the second time), it
-then merges in the entries it has in memory and writes the result back to
-the file. It does NOT update its map of entries in memory with the entries
-(re)read from disk. It only updates the entries in memory when
-"reparseConfiguration()" is called.
-
-
-Open Question: The standard writeEntry() function returns the original value,
-is this needed? Nobody seems to use it.
-
-Open Question: The bPersistent flag doesn't seem to be used... could it be removed?
-
-Open Question: Is the bNLS flag needed? Localised entries seem to be mostly
-useful for default files, are they ever created by the user itself?
-
-Open Question: Would it be worthwhile to lock a user option that is equal to the
-default so that it doesn't change when the default changes?
-
-
-KDE3.0 Changes
-==============
-
-*) writeEntry now returns void instead of QString.
-*) deleteEntry functions added
-
-
-------------------------------------------------------------------------------
-
-TDEConfig XT
-==========
-
-My buzzword picker offered TDEConfig XT ("eXtended Technology") and TDEConfig NG
-("Next Generation"). Since the planned changes are ment to be evolutionary
-rather than revolutionary, TDEConfig NG was dropped.
-
-Goals
-=====
-
-* Have the default value for config entries defined in 1 place. Currently it is
-not uncommon to have them defined in three places:
- 1) In the application that reads the setting in order to use it
- 2) In the settings dialog when reading the setting
- 3) In the settings dialog when selecting "Use defaults".
-
-* Provide type-information about config entries to facilate "KConfEdit" like
-tools. Ideally type-information also includes range-information; this is even
-mandatory if enums become an explicit type.
-
-* Facilitate the documentation of config entries.
-
-
-Instead of relying on the defaults that are hard-coded in the application,
-rely on default configuration files being installed in $TDEDIR. The technical
-changes required for this are very minimal, it is mostly a change in policy.
-
-Type information can be provide by preceding every entry with a formalized
-comment.
-
-Work to be done:
-* TDEConfig needs to be extended to provide access to the default values provided
-by the default config files. TDEConfig already stores this information internally.
-(DONE)
-* A formal comment structure needs to be designed that can convey type-information.
-Preferably in such a way that it is easily parsable by both machine and user.
-* TDEConfig needs to be extended, or another class created, that is able to parse
-the formalized comments.
-* A tool needs to be developed that can assist developers with the generation
-and verification of default configuration files including type-information.
-
-Drawbacks:
-* We rely on default configuration files being properly installed.
-* The user can break applications by making improper modifications to these
-files.
-* It is not possible to store defaults settings in a config file that are
-of a dynamic nature. Examples are settings derived from other settings,
-e.g. a color setting could be derived from the current color theme, or
-e.g. the default high score user name which is determined by the user
-currently logged in.
-
-
-Some random ideas:
-* The format of the entries would be something like this:
-
-[Mail Settings]
-#!Type=string
-#!Description=SMTP server to use for sending mail
-#!Description[nl]=SMTP server voor het versturen van mail
-Host=wantelbos.zogje.fr
-
-- the type could be subclassed more, e.g. strings can be "email", "hostname",
- "url", etc.
-
-- having translations in these files is very arguable. external po's would be
- better.
-
-
-
-Class overview
-
- TDEConfigBase
- |
- v
- TDEConfigBackend <-----> TDEConfig <------> TDEConfigSkeleton /--< myapp.kcfg
- | | | /
- v v |*---------------<
-TDEConfigINIBackend KSimpleConfig |kconfig_compiler \
- | \--< myconfig.kcfg-codegen
- v
- MyConfig <-----TDEConfigDialogManager----> MyConfigWidget *---< myconfigwidget.ui
- uic
-
-TDEConfigBase: defines API for generic config class
-
-TDEConfig: functional generic config class that supports merging of cascaded
- configuration files
-
-KSimpleConfig: functional generic config class without support for cascading
- configuration files.
-
-TDEConfigBackend: defines API for config backend, t.i. the actual handling
- of the storage method and storage format.
-
-TDEConfigINIBackend: the standard (and only one so far) class that implements
- the config backend using the file-based .INI format
- for configuration files
-
-TDEConfigSkeleton: base class for deriving classes that store application
- specific options providing type-safety and single-point
- defaults.
-
-MyConfig: An application specific class that offers configuration options
- to the applications via variables or accessor functions and that
- handles type-safety and defaults. MyConfig is just an example
- name, the application developer choses the actual name.
-
-myapp.kcfg: File describing the configuration options used by a specific
- application. myapp.kcfg is just an example name, the application
- developer choses the actual name.
-
-myconfig.kcfg-codegen: Implementation specific code generation instructions
- for the MyConfig class. myconfig.kcfg-codegen is
- just an example name, the application developer
- choses the actual name.
-
-TDEConfigDialogManager: Class that links widgets in a dialog up with their
- corresponding confguration options in a configuration
- object derived from TDEConfigSkeleton.
-
-MyConfigWidget: Dialog generated from a .ui description file. Widget names
- in the dialog that start with "kcfg_" refer to configuration
- options.
diff --git a/tdecore/DESIGN.tdeconfig b/tdecore/DESIGN.tdeconfig
new file mode 100644
index 000000000..a1fb48dbd
--- /dev/null
+++ b/tdecore/DESIGN.tdeconfig
@@ -0,0 +1,224 @@
+tdeconfigdata.h contains definitions of the data formats used by tdeconfig.
+
+Configuration entries are stored as "KEntry". They are indexed with "KEntryKey".
+The primary store is a "KEntryMap" which is defined as a QMap from "KEntryKey"
+to "KEntry"
+
+KEntry's are stored in order in the KEntryMap. The most significant sort
+criteria is mGroup. This means that all entries who belong in the same group,
+are grouped in the QMap as well.
+
+The start of a group is indicated with a KEntryKey with an empty mKey and a
+dummy KEntry. This allows us to search for the start of the group and then to
+iterate until we end up in another group. That way we will find all entries
+of a certain group.
+
+Entries that are localised with the _current_ locale are stored with bLocal
+set to true. Entries that are localised with another locale are either not
+stored at all (default), or with the localization as part of the key (when
+reading a file in order to merge it).
+[WABA: Does it make sense to keep both localized and non-localised around?
+Can't we just let the localised version override the non-localised version?]
+
+Currently the localization bit is the least significant sort criteria, that
+means that the localised version always follows the non-localised version
+immediately.
+
+<Changed for KDE 3.0>
+Entries that are being read from a location other than the location to
+which is written back are marked as "default" and will be added both as
+normal entry as well as an entry with the key marked as default.
+
+When entries are written to disk, it is checked whether the entry to write
+is equal to the default, if so the entry will not be written. The default
+entry always follows directly after the normal entry, due to the sorting.
+(After that the localised version follows)
+
+When entries are written to disk, it is checked whether the entry to write
+is equal to the default, if so the entry will not be written.
+</Changed>
+
+Open question:
+Should unmodified entries that are written back be compared with the default
+too? This seems to be mostly a transition issue.
+
+<Changed during KDE 3.0 / 3.2>
+Extra functions:
+
+bool entryIsImmutable(key); // Can entry be modified?
+bool hasDefault(key); // Is there a system wide default set for the entry?
+void revertToDefault(key); // Restore to default
+void deleteEntry(key); // Remove entry
+
+Note that there is a subtle difference between revertToDefault() and deleteEntry().
+revertToDefault() will change the entry to the default value set by the system
+administrator (Via e.g. $TDEDIR/share/config) or, if no such default was set,
+non-existant.
+deleteEntry() will make the entry non-existant.
+
+Entries are marked "immutable" if the key is followed by [$i]. This means
+that a user can not override these entries.
+
+Entries can be marked as deleted if they are followed by [$d]. This
+is needed if the system administrator has specified a default value but the
+entry was deleted (made 'non-existant'). In that case we can't just leave
+the entry out since that would mean we get the default from the system
+administrator back the next time we read the file.
+</changed>
+
+When an entry is read with readEntry(key, defaultValue), non-existing
+entries will return "defaultValue" while hasKey(key) will return "false"
+for such entries.
+
+Currently all entries are stored in memory. When TDEConfig is "sync()'ed"
+it reads the file that it is about to overwrite (for the second time), it
+then merges in the entries it has in memory and writes the result back to
+the file. It does NOT update its map of entries in memory with the entries
+(re)read from disk. It only updates the entries in memory when
+"reparseConfiguration()" is called.
+
+
+Open Question: The standard writeEntry() function returns the original value,
+is this needed? Nobody seems to use it.
+
+Open Question: The bPersistent flag doesn't seem to be used... could it be removed?
+
+Open Question: Is the bNLS flag needed? Localised entries seem to be mostly
+useful for default files, are they ever created by the user itself?
+
+Open Question: Would it be worthwhile to lock a user option that is equal to the
+default so that it doesn't change when the default changes?
+
+
+KDE3.0 Changes
+==============
+
+*) writeEntry now returns void instead of QString.
+*) deleteEntry functions added
+
+
+------------------------------------------------------------------------------
+
+TDEConfig XT
+==========
+
+My buzzword picker offered TDEConfig XT ("eXtended Technology") and TDEConfig NG
+("Next Generation"). Since the planned changes are ment to be evolutionary
+rather than revolutionary, TDEConfig NG was dropped.
+
+Goals
+=====
+
+* Have the default value for config entries defined in 1 place. Currently it is
+not uncommon to have them defined in three places:
+ 1) In the application that reads the setting in order to use it
+ 2) In the settings dialog when reading the setting
+ 3) In the settings dialog when selecting "Use defaults".
+
+* Provide type-information about config entries to facilate "KConfEdit" like
+tools. Ideally type-information also includes range-information; this is even
+mandatory if enums become an explicit type.
+
+* Facilitate the documentation of config entries.
+
+
+Instead of relying on the defaults that are hard-coded in the application,
+rely on default configuration files being installed in $TDEDIR. The technical
+changes required for this are very minimal, it is mostly a change in policy.
+
+Type information can be provide by preceding every entry with a formalized
+comment.
+
+Work to be done:
+* TDEConfig needs to be extended to provide access to the default values provided
+by the default config files. TDEConfig already stores this information internally.
+(DONE)
+* A formal comment structure needs to be designed that can convey type-information.
+Preferably in such a way that it is easily parsable by both machine and user.
+* TDEConfig needs to be extended, or another class created, that is able to parse
+the formalized comments.
+* A tool needs to be developed that can assist developers with the generation
+and verification of default configuration files including type-information.
+
+Drawbacks:
+* We rely on default configuration files being properly installed.
+* The user can break applications by making improper modifications to these
+files.
+* It is not possible to store defaults settings in a config file that are
+of a dynamic nature. Examples are settings derived from other settings,
+e.g. a color setting could be derived from the current color theme, or
+e.g. the default high score user name which is determined by the user
+currently logged in.
+
+
+Some random ideas:
+* The format of the entries would be something like this:
+
+[Mail Settings]
+#!Type=string
+#!Description=SMTP server to use for sending mail
+#!Description[nl]=SMTP server voor het versturen van mail
+Host=wantelbos.zogje.fr
+
+- the type could be subclassed more, e.g. strings can be "email", "hostname",
+ "url", etc.
+
+- having translations in these files is very arguable. external po's would be
+ better.
+
+
+
+Class overview
+
+ TDEConfigBase
+ |
+ v
+ TDEConfigBackend <-----> TDEConfig <------> TDEConfigSkeleton /--< myapp.kcfg
+ | | | /
+ v v |*---------------<
+TDEConfigINIBackend KSimpleConfig |tdeconfig_compiler \
+ | \--< myconfig.kcfg-codegen
+ v
+ MyConfig <-----TDEConfigDialogManager----> MyConfigWidget *---< myconfigwidget.ui
+ uic
+
+TDEConfigBase: defines API for generic config class
+
+TDEConfig: functional generic config class that supports merging of cascaded
+ configuration files
+
+KSimpleConfig: functional generic config class without support for cascading
+ configuration files.
+
+TDEConfigBackend: defines API for config backend, t.i. the actual handling
+ of the storage method and storage format.
+
+TDEConfigINIBackend: the standard (and only one so far) class that implements
+ the config backend using the file-based .INI format
+ for configuration files
+
+TDEConfigSkeleton: base class for deriving classes that store application
+ specific options providing type-safety and single-point
+ defaults.
+
+MyConfig: An application specific class that offers configuration options
+ to the applications via variables or accessor functions and that
+ handles type-safety and defaults. MyConfig is just an example
+ name, the application developer choses the actual name.
+
+myapp.kcfg: File describing the configuration options used by a specific
+ application. myapp.kcfg is just an example name, the application
+ developer choses the actual name.
+
+myconfig.kcfg-codegen: Implementation specific code generation instructions
+ for the MyConfig class. myconfig.kcfg-codegen is
+ just an example name, the application developer
+ choses the actual name.
+
+TDEConfigDialogManager: Class that links widgets in a dialog up with their
+ corresponding confguration options in a configuration
+ object derived from TDEConfigSkeleton.
+
+MyConfigWidget: Dialog generated from a .ui description file. Widget names
+ in the dialog that start with "kcfg_" refer to configuration
+ options.
diff --git a/tdecore/MAINTAINERS b/tdecore/MAINTAINERS
index 995ab753a..6295c102d 100644
--- a/tdecore/MAINTAINERS
+++ b/tdecore/MAINTAINERS
@@ -20,9 +20,9 @@ kckey.cpp
kcmdlineargs.cpp Waldo Bastian <bastian@kde.org>
kcompletion.cpp Carsten Pfeiffer <pfeiffer@kde.org>
kcompletionbase.cpp
-kconfig.cpp Waldo Bastian <bastian@kde.org>
-kconfigbackend.cpp Waldo Bastian <bastian@kde.org>
-kconfigbase.cpp Waldo Bastian <bastian@kde.org>
+tdeconfig.cpp Waldo Bastian <bastian@kde.org>
+tdeconfigbackend.cpp Waldo Bastian <bastian@kde.org>
+tdeconfigbase.cpp Waldo Bastian <bastian@kde.org>
kcrash.cpp Waldo Bastian <bastian@kde.org>
kdcoppropertyproxy.cpp
kdebug.cpp Stephan Kulow <coolo@kde.org>
@@ -94,8 +94,8 @@ kcalendarsystemhijri.cpp
kcalendarsystemjalali.cpp Arash Bijanzadeh and FarsiKDE Project <www.farsikde.org> (copyright)
kcheckaccelerators.cpp Matthias Kalle Dalheimer (kalle@kde.org) (copyright)
kclipboard.cpp Carsten Pfeiffer <pfeiffer@kde.org> (copyright)
-kconfigdialogmanager.cpp
-kconfigskeleton.cpp
+tdeconfigdialogmanager.cpp
+tdeconfigskeleton.cpp
kdebugdcopiface.cpp Andreas Beckermann (b_mann@gmx.de) (copyright)
tdeversion.cpp
kglobalaccel_win.cpp Ellis Whitehead <ellis@kde.org> (copyright)
diff --git a/tdecore/Makefile.am b/tdecore/Makefile.am
index 75037eccf..2204ab749 100644
--- a/tdecore/Makefile.am
+++ b/tdecore/Makefile.am
@@ -27,7 +27,7 @@ SVGICONS=svgicons
SVGICON_LIB=svgicons/libkdesvgicons.la
endif
-SUBDIRS = malloc network $(SVGICONS) . kconfig_compiler tests
+SUBDIRS = malloc network $(SVGICONS) . tdeconfig_compiler tests
# For the future: examine if condensing the tons of *_LDFLAGS variables
# into $(all_libraries) isn't better
@@ -36,10 +36,10 @@ AM_LDFLAGS = $(LDFLAGS_AS_NEEDED) $(LDFLAGS_NEW_DTAGS)
lib_LTLIBRARIES = libtdefakes.la libtdecore.la
lib_LIBRARIES = libtdefakes_nonpic.a libtdefakes_pic.a
-include_HEADERS = kconfig.h kconfigskeleton.h \
- kconfigdata.h ksimpleconfig.h kconfigdialogmanager.h \
- kconfigbase.h kdesktopfile.h kurl.h ksock.h kaboutdata.h \
- kcmdlineargs.h kconfigbackend.h kapp.h kapplication.h kuniqueapp.h \
+include_HEADERS = tdeconfig.h tdeconfigskeleton.h \
+ tdeconfigdata.h ksimpleconfig.h tdeconfigdialogmanager.h \
+ tdeconfigbase.h kdesktopfile.h kurl.h ksock.h kaboutdata.h \
+ kcmdlineargs.h tdeconfigbackend.h kapp.h kapplication.h kuniqueapp.h \
kuniqueapplication.h kcharsets.h tdeversion.h kpty.h kprocess.h \
kprocctrl.h klocale.h kicontheme.h kiconloader.h kdebug.h \
twinmodule.h twin.h krootprop.h kshortcut.h kkeynative.h kaccel.h \
@@ -90,8 +90,8 @@ noinst_HEADERS = kaccelaction.h kaccelbase.h kaccelprivate.h kckey.h \
kprotocolinfofactory.h kqiodevicegzip_p.h kiconloader_p.h
libtdecore_la_SOURCES = libintl.cpp kapplication.cpp \
- kdebug.cpp netwm.cpp kconfigbase.cpp kconfig.cpp ksimpleconfig.cpp \
- kconfigbackend.cpp kmanagerselection.cpp kdesktopfile.cpp \
+ kdebug.cpp netwm.cpp tdeconfigbase.cpp tdeconfig.cpp ksimpleconfig.cpp \
+ tdeconfigbackend.cpp kmanagerselection.cpp kdesktopfile.cpp \
kstandarddirs.cpp ksock.cpp kpty.cpp kprocess.cpp kprocctrl.cpp \
klocale.cpp krfcdate.cpp kiconeffect.cpp kicontheme.cpp \
kiconloader.cpp twin.cpp twinmodule.cpp krootprop.cpp kcharsets.cpp \
@@ -118,7 +118,7 @@ libtdecore_la_SOURCES = libintl.cpp kapplication.cpp \
kcalendarsystemfactory.cpp kmacroexpander.cpp kidna.cpp \
ktempdir.cpp kshell.cpp kmountpoint.cpp kcalendarsystemjalali.cpp \
kprotocolinfo_tdecore.cpp kprotocolinfofactory.cpp kxerrorhandler.cpp \
- kuser.cpp kconfigskeleton.cpp kconfigdialogmanager.cpp klockfile.cpp \
+ kuser.cpp tdeconfigskeleton.cpp tdeconfigdialogmanager.cpp klockfile.cpp \
kqiodevicegzip_p.cpp ktimezones.cpp
libtdecore_la_LDFLAGS = $(QT_LDFLAGS) $(KDE_RPATH) $(KDE_MT_LDFLAGS) $(X_LDFLAGS) $(USER_LDFLAGS) -version-info 6:0:2 -no-undefined
@@ -143,16 +143,16 @@ kckey_h : $(srcdir)/generate_keys.sh $(QNAMESPACE_H)
install-data-local:
$(mkinstalldirs) $(DESTDIR)$(kde_locale)
$(INSTALL_DATA) $(srcdir)/all_languages.desktop $(DESTDIR)$(kde_locale)/all_languages
- $(mkinstalldirs) $(DESTDIR)$(includedir)/kio
+ $(mkinstalldirs) $(DESTDIR)$(includedir)/tdeio
$(mkinstalldirs) $(DESTDIR)$(kde_datadir)/knotify
$(INSTALL_DATA) $(srcdir)/eventsrc $(DESTDIR)$(kde_datadir)/knotify/eventsrc
- $(INSTALL_DATA) $(srcdir)/kmdcodec_compat.h $(DESTDIR)$(includedir)/kio/kmdcodec.h
+ $(INSTALL_DATA) $(srcdir)/kmdcodec_compat.h $(DESTDIR)$(includedir)/tdeio/kmdcodec.h
rm -f "$(DESTDIR)$(kde_confdir)/colors/40 Colors"
rm -f $(DESTDIR)$(kde_confdir)/colors/Web
rm -f $(DESTDIR)$(kde_confdir)/colors/Royal
uninstall-local:
- -rm -f $(DESTDIR)$(includedir)/kio/kmdcodec.h
+ -rm -f $(DESTDIR)$(includedir)/tdeio/kmdcodec.h
# If you add a color palette file here, please change tdelibs/tdeui/kcolordialog.cpp too to allow to translate the name
colors_DATA = 40.colors Web.colors Royal.colors Rainbow.colors
diff --git a/tdecore/README.kiosk b/tdecore/README.kiosk
index 657a6a72b..b0d6cddfb 100644
--- a/tdecore/README.kiosk
+++ b/tdecore/README.kiosk
@@ -616,7 +616,7 @@ tde-display.desktop
tde-proxy.desktop
tde-screensaver.desktop
-See also kcmshell --list for a list of all the base names.
+See also tdecmshell --list for a list of all the base names.
Expansion of environment variables in KDE config files.
=======================================================
diff --git a/tdecore/README.kstartupinfo b/tdecore/README.kstartupinfo
index 051b1fae6..995b9883a 100644
--- a/tdecore/README.kstartupinfo
+++ b/tdecore/README.kstartupinfo
@@ -173,7 +173,7 @@ matter ).
The ASN identification string must be a unique string for every ASN.
In KStartupInfo class, it's created as 'hostname;tm.sec;tm.usec;pid',
tm being the current time. If the identification string is set to "0",
-it means no ASN should be done ( e.g. for things like kio_uiserver,
+it means no ASN should be done ( e.g. for things like tdeio_uiserver,
which shouldn't get ASN ). Empty identification string means the same
like "0", except for the call to KStartupInfoId::initId(), where it means
to create a new one.
diff --git a/tdecore/kaccelaction.cpp b/tdecore/kaccelaction.cpp
index e8696cc26..34448fe90 100644
--- a/tdecore/kaccelaction.cpp
+++ b/tdecore/kaccelaction.cpp
@@ -25,7 +25,7 @@
#include <tqkeycode.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include "kckey.h"
#include <kdebug.h>
#include <kglobal.h>
diff --git a/tdecore/kaccelbase.cpp b/tdecore/kaccelbase.cpp
index 729de1c42..75810b2e3 100644
--- a/tdecore/kaccelbase.cpp
+++ b/tdecore/kaccelbase.cpp
@@ -26,7 +26,7 @@
#include <tqlabel.h>
#include <tqpopupmenu.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include "kckey.h"
#include <kdebug.h>
#include <kglobal.h>
diff --git a/tdecore/kappdcopiface.cpp b/tdecore/kappdcopiface.cpp
index 768a94fff..9f1148579 100644
--- a/tdecore/kappdcopiface.cpp
+++ b/tdecore/kappdcopiface.cpp
@@ -21,7 +21,7 @@
#include <kapplication.h>
#include <dcopclient.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
KAppDCOPInterface::KAppDCOPInterface(TDEApplication * theKApp)
diff --git a/tdecore/kapplication.cpp b/tdecore/kapplication.cpp
index 2950d6170..bd17e972a 100644
--- a/tdecore/kapplication.cpp
+++ b/tdecore/kapplication.cpp
@@ -68,7 +68,7 @@
#include <kstyle.h>
#include <kiconloader.h>
#include <kclipboard.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ksimpleconfig.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
@@ -2970,7 +2970,7 @@ void TDEApplication::broadcastKeyCode(unsigned int keyCode)
TQCString
TDEApplication::launcher()
{
- return "klauncher";
+ return "tdelauncher";
}
static int
diff --git a/tdecore/kcharsets.cpp b/tdecore/kcharsets.cpp
index 4c8a405cb..17617bf9e 100644
--- a/tdecore/kcharsets.cpp
+++ b/tdecore/kcharsets.cpp
@@ -24,7 +24,7 @@
#include <kapplication.h>
#include <kglobal.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqfontinfo.h>
#include <tqstrlist.h>
diff --git a/tdecore/kcheckaccelerators.cpp b/tdecore/kcheckaccelerators.cpp
index 69cd06dee..1051cd362 100644
--- a/tdecore/kcheckaccelerators.cpp
+++ b/tdecore/kcheckaccelerators.cpp
@@ -39,7 +39,7 @@
#include <tqmetaobject.h>
#include <tqcheckbox.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kshortcut.h>
diff --git a/tdecore/kclipboard.cpp b/tdecore/kclipboard.cpp
index f7812a713..53865a2c2 100644
--- a/tdecore/kclipboard.cpp
+++ b/tdecore/kclipboard.cpp
@@ -17,7 +17,7 @@
*/
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include "kclipboard.h"
diff --git a/tdecore/kconfig.cpp b/tdecore/kconfig.cpp
deleted file mode 100644
index 26459cdde..000000000
--- a/tdecore/kconfig.cpp
+++ /dev/null
@@ -1,367 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Preston Brown <pbrown@kde.org>
- Copyright (C) 1997-1999 Matthias Kalle Dalheimer (kalle@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-// $Id$
-
-#include <config.h>
-
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#endif
-
-#include <stdlib.h>
-#include <unistd.h>
-
-#include <tqfileinfo.h>
-
-#include <kapplication.h>
-#include "kconfigbackend.h"
-
-#include "kconfig.h"
-#include "kglobal.h"
-#include "kstandarddirs.h"
-#include "kstaticdeleter.h"
-#include <tqtimer.h>
-
-TDEConfig::TDEConfig( const TQString& fileName,
- bool bReadOnly, bool bUseKderc, const char *resType )
- : TDEConfigBase(), bGroupImmutable(false), bFileImmutable(false),
- bForceGlobal(false)
-{
- // set the object's read-only status.
- setReadOnly(bReadOnly);
-
- // for right now we will hardcode that we are using the INI
- // back end driver. In the future this should be converted over to
- // a object factory of some sorts.
- TDEConfigINIBackEnd *aBackEnd = new TDEConfigINIBackEnd(this,
- fileName,
- resType,
- bUseKderc);
-
- // set the object's back end pointer to this new backend
- backEnd = aBackEnd;
-
- // read initial information off disk
- reparseConfiguration();
-
- // we let KStandardDirs add custom user config files. It will do
- // this only once. So only the first call ever to this constructor
- // will anything else than return here We have to reparse here as
- // configuration files may appear after customized directories have
- // been added. and the info they contain needs to be inserted into the
- // config object.
- // Since this makes only sense for config directories, addCustomized
- // returns true only if new config directories appeared.
- if (TDEGlobal::dirs()->addCustomized(this))
- reparseConfiguration();
-}
-
-TDEConfig::TDEConfig(TDEConfigBackEnd *aBackEnd, bool bReadOnly)
- : bGroupImmutable(false), bFileImmutable(false),
- bForceGlobal(false)
-{
- setReadOnly(bReadOnly);
- backEnd = aBackEnd;
- reparseConfiguration();
-}
-
-TDEConfig::~TDEConfig()
-{
- sync();
-
- delete backEnd;
-}
-
-void TDEConfig::rollback(bool bDeep)
-{
- TDEConfigBase::rollback(bDeep);
-
- if (!bDeep)
- return; // object's bDeep flag is set in TDEConfigBase method
-
- // clear any dirty flags that entries might have set
- for (KEntryMapIterator aIt = aEntryMap.begin();
- aIt != aEntryMap.end(); ++aIt)
- (*aIt).bDirty = false;
-}
-
-TQStringList TDEConfig::groupList() const
-{
- TQStringList retList;
-
- KEntryMapConstIterator aIt = aEntryMap.begin();
- KEntryMapConstIterator aEnd = aEntryMap.end();
- for (; aIt != aEnd; ++aIt)
- {
- while(aIt.key().mKey.isEmpty())
- {
- TQCString group = aIt.key().mGroup;
- ++aIt;
- while (true)
- {
- if (aIt == aEnd)
- return retList; // done
-
- if (aIt.key().mKey.isEmpty())
- break; // Group is empty, next group
-
- if (!aIt.key().bDefault && !(*aIt).bDeleted)
- {
- if (group != "$Version") // Special case!
- retList.append(TQString::fromUtf8(group));
- break; // Group is non-empty, added, next group
- }
- ++aIt;
- }
- }
- }
-
- return retList;
-}
-
-TQMap<TQString, TQString> TDEConfig::entryMap(const TQString &pGroup) const
-{
- TQCString pGroup_utf = pGroup.utf8();
- KEntryKey groupKey( pGroup_utf, 0 );
- TQMap<TQString, TQString> tmpMap;
-
- KEntryMapConstIterator aIt = aEntryMap.find(groupKey);
- if (aIt == aEntryMap.end())
- return tmpMap;
- ++aIt; // advance past special group entry marker
- for (; aIt.key().mGroup == pGroup_utf && aIt != aEntryMap.end(); ++aIt)
- {
- // Leave the default values out && leave deleted entries out
- if (!aIt.key().bDefault && !(*aIt).bDeleted)
- tmpMap.insert(TQString::fromUtf8(aIt.key().mKey), TQString::fromUtf8((*aIt).mValue.data(), (*aIt).mValue.length()));
- }
-
- return tmpMap;
-}
-
-void TDEConfig::reparseConfiguration()
-{
- // Don't lose pending changes
- if (!isReadOnly() && backEnd && bDirty)
- backEnd->sync();
-
- aEntryMap.clear();
-
- // add the "default group" marker to the map
- KEntryKey groupKey("<default>", 0);
- aEntryMap.insert(groupKey, KEntry());
-
- bFileImmutable = false;
- parseConfigFiles();
- bFileImmutable = bReadOnly;
-}
-
-KEntryMap TDEConfig::internalEntryMap(const TQString &pGroup) const
-{
- TQCString pGroup_utf = pGroup.utf8();
- KEntry aEntry;
- KEntryMapConstIterator aIt;
- KEntryKey aKey(pGroup_utf, 0);
- KEntryMap tmpEntryMap;
-
- aIt = aEntryMap.find(aKey);
- if (aIt == aEntryMap.end()) {
- // the special group key is not in the map,
- // so it must be an invalid group. Return
- // an empty map.
- return tmpEntryMap;
- }
- // we now have a pointer to the nodes we want to copy.
- for (; aIt.key().mGroup == pGroup_utf && aIt != aEntryMap.end(); ++aIt)
- {
- tmpEntryMap.insert(aIt.key(), *aIt);
- }
-
- return tmpEntryMap;
-}
-
-void TDEConfig::putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup)
-{
- if (bFileImmutable && !_key.bDefault)
- return;
-
- // check to see if the special group key is present,
- // and if not, put it in.
- if (_checkGroup)
- {
- KEntryKey groupKey( _key.mGroup, 0);
- KEntry &entry = aEntryMap[groupKey];
- bGroupImmutable = entry.bImmutable;
- }
- if (bGroupImmutable && !_key.bDefault)
- return;
-
- // now either add or replace the data
- KEntry &entry = aEntryMap[_key];
- bool immutable = entry.bImmutable;
- if (immutable && !_key.bDefault)
- return;
-
- entry = _data;
- entry.bImmutable |= immutable;
- entry.bGlobal |= bForceGlobal; // force to kdeglobals
-
- if (_key.bDefault)
- {
- // We have added the data as default value,
- // add it as normal value as well.
- KEntryKey key(_key);
- key.bDefault = false;
- aEntryMap[key] = _data;
- }
-}
-
-KEntry TDEConfig::lookupData(const KEntryKey &_key) const
-{
- KEntryMapConstIterator aIt = aEntryMap.find(_key);
- if (aIt != aEntryMap.end())
- {
- const KEntry &entry = *aIt;
- if (entry.bDeleted)
- return KEntry();
- else
- return entry;
- }
- else {
- return KEntry();
- }
-}
-
-bool TDEConfig::internalHasGroup(const TQCString &group) const
-{
- KEntryKey groupKey( group, 0);
-
- KEntryMapConstIterator aIt = aEntryMap.find(groupKey);
- KEntryMapConstIterator aEnd = aEntryMap.end();
-
- if (aIt == aEnd)
- return false;
- ++aIt;
- for(; (aIt != aEnd); ++aIt)
- {
- if (aIt.key().mKey.isEmpty())
- break;
-
- if (!aIt.key().bDefault && !(*aIt).bDeleted)
- return true;
- }
- return false;
-}
-
-void TDEConfig::setFileWriteMode(int mode)
-{
- backEnd->setFileWriteMode(mode);
-}
-
-KLockFile::Ptr TDEConfig::lockFile(bool bGlobal)
-{
- TDEConfigINIBackEnd *aBackEnd = dynamic_cast<TDEConfigINIBackEnd*>(backEnd);
- if (!aBackEnd) return 0;
- return aBackEnd->lockFile(bGlobal);
-}
-
-void TDEConfig::checkUpdate(const TQString &id, const TQString &updateFile)
-{
- TQString oldGroup = group();
- setGroup("$Version");
- TQString cfg_id = updateFile+":"+id;
- TQStringList ids = readListEntry("update_info");
- if (!ids.contains(cfg_id))
- {
- TQStringList args;
- args << "--check" << updateFile;
- TDEApplication::tdeinitExecWait("kconf_update", args);
- reparseConfiguration();
- }
- setGroup(oldGroup);
-}
-
-TDEConfig* TDEConfig::copyTo(const TQString &file, TDEConfig *config) const
-{
- if (!config)
- config = new TDEConfig(TQString::null, false, false);
- config->backEnd->changeFileName(file, "config", false);
- config->setReadOnly(false);
- config->bFileImmutable = false;
- config->backEnd->mConfigState = ReadWrite;
-
- TQStringList groups = groupList();
- for(TQStringList::ConstIterator it = groups.begin();
- it != groups.end(); ++it)
- {
- TQMap<TQString, TQString> map = entryMap(*it);
- config->setGroup(*it);
- for (TQMap<TQString,TQString>::Iterator it2 = map.begin();
- it2 != map.end(); ++it2)
- {
- config->writeEntry(it2.key(), it2.data());
- }
-
- }
- return config;
-}
-
-void TDEConfig::virtual_hook( int id, void* data )
-{ TDEConfigBase::virtual_hook( id, data ); }
-
-static KStaticDeleter< TQValueList<KSharedConfig*> > sd;
-TQValueList<KSharedConfig*> *KSharedConfig::s_list = 0;
-
-KSharedConfig::Ptr KSharedConfig::openConfig(const TQString& fileName, bool readOnly, bool useKDEGlobals )
-{
- if (s_list)
- {
- for(TQValueList<KSharedConfig*>::ConstIterator it = s_list->begin();
- it != s_list->end(); ++it)
- {
- if ((*it)->backEnd->fileName() == fileName &&
- (*it)->bReadOnly == readOnly &&
- (*it)->backEnd->useKDEGlobals == useKDEGlobals )
- return (*it);
- }
- }
- return new KSharedConfig(fileName, readOnly, useKDEGlobals);
-}
-
-KSharedConfig::KSharedConfig( const TQString& fileName, bool readonly, bool usekdeglobals)
- : TDEConfig(fileName, readonly, usekdeglobals)
-{
- if (!s_list)
- {
- sd.setObject(s_list, new TQValueList<KSharedConfig*>);
- }
-
- s_list->append(this);
-}
-
-KSharedConfig::~KSharedConfig()
-{
- if ( s_list )
- s_list->remove(this);
-}
-
-#include "kconfig.moc"
diff --git a/tdecore/kconfig.h b/tdecore/kconfig.h
deleted file mode 100644
index c5084c109..000000000
--- a/tdecore/kconfig.h
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Preston Brown <pbrown@kde.org>
- Copyright (C) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KCONFIG_H
-#define _KCONFIG_H
-
-class TQTimer;
-
-#include <tqvaluelist.h>
-
-#include "kconfigbase.h"
-#include "klockfile.h"
-
-class TDEConfigPrivate;
-
-/**
-* Access KDE Configuration entries.
-*
-* This class implements KDE's default configuration system.
-*
-* @author Kalle Dalheimer <kalle@kde.org>, Preston Brown <pbrown@kde.org>
-* @see TDEGlobal::config(), TDEConfigBase, KSimpleConfig
-* @short KDE Configuration Management class
-*/
-class TDECORE_EXPORT TDEConfig : public TDEConfigBase
-{
- Q_OBJECT
-
-public:
-
- /**
- * Constructs a TDEConfig object.
- *
- * @param fileName A file to parse in addition to the
- * system-wide file(s). If it is not provided, only global
- * KDE configuration data will be read (depending on the value of
- * @p bUseKDEGlobals).
- * @param bReadOnly Set the config object's read-only status. Note that the
- * object will automatically become read-only if either the user does not have
- * write permission to @p fileName or if no file was specified.
- * @param bUseKDEGlobals Toggle reading the global KDE configuration file.
- * @param resType the place to look in (config, data, etc) See KStandardDirs.
- */
- TDEConfig( const TQString& fileName = TQString::null,
- bool bReadOnly = false, bool bUseKDEGlobals = true, const char *resType="config");
-
- TDEConfig(TDEConfigBackEnd *backEnd, bool bReadOnly = false);
-
- /**
- * Destructs the TDEConfig object.
- *
- * Writes back any dirty configuration entries, and destroys
- * dynamically created objects.
- */
- virtual ~TDEConfig();
-
- /**
- * Clears all entries out of the @p dirtyEntryMap, so the
- * values will not be written to disk on a later call to
- * sync().
- *
- * @param bDeep If true, the dirty map is actually emptied.
- * otherwise, the config object's global dirty flag is set to
- * false, but the dirty entries remain in the dirty entry
- * map.
- *
- * @see TDEConfigBase::rollback
- */
- virtual void rollback(bool bDeep = true);
-
-
- /**
- * Returns a list of groups that are known.
- * @return a list of of groups
- */
- virtual TQStringList groupList() const;
-
- /**
- * Returns a map (tree) of entries for all entries in a particular
- * group.
- *
- * Only the actual entry string is returned, none of the
- * other internal data should be included.
- *
- * @param pGroup A group to get keys from.
- * @return A map of entries in the group specified, indexed by key.
- * The returned map may be empty if the group is not found.
- */
- virtual TQMap<TQString, TQString> entryMap(const TQString &pGroup) const;
-
- /**
- * Clears all internal data structures and then reread
- * configuration information from disk.
- */
- virtual void reparseConfiguration();
-
- /**
- * Set the file mode for newly created files.
- *
- * @param mode the mode for new files as described in chmod(2)
- * @see man:chmod(2) for a description of @p mode
- */
- void setFileWriteMode(int mode);
-
- /**
- * Forces all following write-operations being performed on kdeglobals,
- * independent of the bGlobal flag in writeEntry().
- * @param force true to force writing in kdeglobals
- * @see forceGlobal
- */
- void setForceGlobal( bool force ) { bForceGlobal = force; }
-
- /**
- * Returns true if all entries are being written into kdeglobals.
- * @return true if all entries are being written into kdeglobals
- * @see setForceGlobal
- */
- bool forceGlobal() const { return bForceGlobal; }
-
- /**
- * Checks whether the config file contains the update @p id
- * as contained in @p updateFile. If not, it runs kconf_update
- * to update the config file.
- *
- * If you install config update files with critical fixes
- * you may wish to use this method to verify that a critical
- * update has indeed been performed to catch the case where
- * a user restores an old config file from backup that has
- * not been updated yet.
- * @param id the update to check
- * @param updateFile the file containing the update
- * @since 3.1
- */
- void checkUpdate(const TQString &id, const TQString &updateFile);
-
- /**
- * Copies all entries from this config object to a new config
- * object that will save itself to @p file.
- *
- * Actual saving to @p file happens when the returned object is
- * destructed or when sync() is called upon it.
- *
- * @param file the new config object will save itself to.
- * @param config optional config object to reuse
- * @since 3.2
- */
- TDEConfig* copyTo(const TQString &file, TDEConfig *config=0) const;
-
- /**
- * Returns a lock file object for the configuration file or 0 if
- * the backend does not support locking.
- * @param bGlobal if true, return the lock file for the global config file
- *
- * NOTE: TDEConfig::sync() requires a lock on both the normal and global
- * config file. When calling TDEConfig::sync() while having a lock on the
- * global config file, the normal config file MUST be locked AS WELL and the
- * normal config file MUST be locked BEFORE the global config file!
- * Otherwise there is a risk of deadlock.
- * @since 3.3
- */
- KLockFile::Ptr lockFile( bool bGlobal=false );
-
-protected:
-
- /**
- * Returns true if the specified group is known.
- *
- * @param group The group to search for.
- * @returns true if the group exists.
- */
- virtual bool internalHasGroup(const TQCString &group) const;
-
- /**
- * @internal
- * Returns a map (tree) of the entries in the specified group.
- *
- * Do not use this function, the implementation / return type are
- * subject to change.
- *
- * @param pGroup the group to provide a KEntryMap for.
- * @return The map of the entries in the group.
- */
- virtual KEntryMap internalEntryMap(const TQString &pGroup) const;
-
- /**
- * @internal
- * Returns a copy of the internal map used to hold all entries.
- *
- * Do not use this function, the implementation / return type are
- * subject to change.
- *
- * @return The map of the entries in the group.
- */
- virtual KEntryMap internalEntryMap() const { return aEntryMap; }
-
- /**
- * Inserts a (key, value) pair into the internal storage mechanism of
- * the configuration object.
- *
- * @param _key The key to insert. It contains information both on
- * the group of the key and the key itself. If the key already
- * exists, the old value will be replaced.
- * @param _data the KEntry that is to be stored.
- * @param _checkGroup When false, assume that the group already exists.
- */
- virtual void putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup=true);
-
- /**
- * Looks up an entry in the config object's internal structure.
- *
- * @param _key The key to look up It contains information both on
- * the group of the key and the entry's key itself.
- * @return the KEntry value (data) found for the key. KEntry.aValue
- * will be the null string if nothing was located.
- */
- virtual KEntry lookupData(const KEntryKey &_key) const;
-
- /**
- * Contains all key,value entries, as well as some "special"
- * keys which indicate the start of a group of entries.
- *
- * These special keys will have the .key portion of their KEntryKey
- * set to TQString::null.
- */
- KEntryMap aEntryMap;
-
-private:
- /**
- * @internal
- * copy-construction and assignment are not allowed
- */
- TDEConfig( const TDEConfig& );
- /**
- * @internal
- * copy-construction and assignment are not allowed
- */
- TDEConfig& operator= ( const TDEConfig& rConfig );
-
-private:
- bool bGroupImmutable : 1; // Current group is immutable.
- bool bFileImmutable : 1; // Current file is immutable.
- bool bForceGlobal : 1; // Apply everything to kdeglobals.
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- TDEConfigPrivate *d;
-};
-
-/**
- * TDEConfig variant using shared memory
- *
- * KSharedConfig provides a reference counted, shared memory variant
- * of TDEConfig.
- */
-class TDECORE_EXPORT KSharedConfig : public TDEConfig, public KShared
-{
- friend class TQValueList<KSharedConfig*>;
-public:
- typedef KSharedPtr<KSharedConfig> Ptr;
-
-public:
- /**
- * Returns a ref-counted pointer to a shared read-write config object.
- * @param fileName the name of the file to use for the configuration
- * @param readOnly set the config object's read-only status
- * @param bUseKDEGlobals Toggle reading the global KDE configuration file.
- */
- static KSharedConfig::Ptr openConfig(const TQString& fileName, bool readOnly = false,
- bool bUseKDEGlobals = true);
-
-private:
- KSharedConfig( const TQString& fileName, bool readOnly, bool useKDEGlobals );
- ~KSharedConfig();
-
- static TQValueList<KSharedConfig*> *s_list;
-};
-
-#endif
diff --git a/tdecore/kconfig_compiler/CMakeLists.txt b/tdecore/kconfig_compiler/CMakeLists.txt
deleted file mode 100644
index 4acc09f51..000000000
--- a/tdecore/kconfig_compiler/CMakeLists.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-#################################################
-#
-# (C) 2010 Serghei Amelian
-# serghei (DOT) amelian (AT) gmail.com
-#
-# Improvements and feedback are welcome
-#
-# This file is released under GPL >= 2
-#
-#################################################
-
-include_directories(
- ${TQT_INCLUDE_DIRS}
- ${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/tdecore
-)
-
-link_directories(
- ${TQT_LIBRARY_DIRS}
-)
-
-
-##### kconfig_compiler ##########################
-
-tde_add_executable( kconfig_compiler
- SOURCES kconfig_compiler.cpp
- LINK tdecore-shared
- DESTINATION ${BIN_INSTALL_DIR}
-)
diff --git a/tdecore/kconfig_compiler/Makefile.am b/tdecore/kconfig_compiler/Makefile.am
deleted file mode 100644
index d4f287381..000000000
--- a/tdecore/kconfig_compiler/Makefile.am
+++ /dev/null
@@ -1,18 +0,0 @@
-SUBDIRS = example tests
-
-AM_CPPFLAGS = -I$(top_srcdir)/tdecore -I$(top_srcdir) $(all_includes)
-
-bin_PROGRAMS = kconfig_compiler
-
-kconfig_compiler_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-kconfig_compiler_LDADD = $(LIB_TDECORE)
-kconfig_compiler_SOURCES = kconfig_compiler.cpp
-
-TESTFILES = test1.kcfg test2.kcfg test3.kcfg test4.kcfg test_dpointer.kcfg
-
-check-local:
- for i in $(TESTFILES); \
- do xmllint --noout --schema $(srcdir)/kcfg.xsd $(srcdir)/tests/$$i; \
- perl $(top_srcdir)/tdecore/kconfig_compiler/checkkcfg.pl \
- $(top_srcdir)/tdecore/kconfig_compiler/tests/$$i; done
-
diff --git a/tdecore/kconfig_compiler/README.dox b/tdecore/kconfig_compiler/README.dox
deleted file mode 100644
index 76dbc04c2..000000000
--- a/tdecore/kconfig_compiler/README.dox
+++ /dev/null
@@ -1,255 +0,0 @@
-/**
-\page kconfig_compiler The KDE Configuration Compiler
-
-kconfig_compiler generates C++ source code from an XML file containing
-information about configuration options (.kcfg) and a file that provides
-the code generation options (.kcfgc) The generated class is based on
-TDEConfigSkeleton and provides an API for the application to access its
-configuration data.
-
-<h2>XML description of the configuration options</h2>
-
-The structure of the .kcfg file is described by its DTD kcfg.dtd.
-
-The \<kcfgfile\> tag contains the name of the configuration file described.
-Omitting the name will make the generated class use the default configuration
-file ("<appname>rc").
-
-The \<include\> tags are optional and may contain C++ header files that
-are needed to compile the code needed to compute default values.
-
-The remaining entries in the XML file are grouped by the tag \<group\>
-which describes the corresponding group in the configuration file.
-
-The individual entries must have at least a name or a key. The name is used to
-create accessor and modifier functions. It's also used as the key in the config
-file. If \<key\> is given, but not \<name\>, the name is constructed by removing
-all spaces from \<key\>.
-
-An entry must also have a type. The list of allowable types is
-specified in the DTD and loosely follows the list of types supported
-by the QVariant with exception of the clearly binary types
-(e.g. Pixmap, Image...) which are not supported. Besides those basic
-type the following special types are supported:
-
-- Path This is a string that is specially treated as a file-path.
- In particular paths in the home directory are prefixed with $HOME in
- when being stored in the configuration file.
-
-- Enum This indicates an enumeration. The possible enum values should
- be provided via the \<choices\> tag. Enum values are accessed as integers
- by the application but stored as string in the configuration file. This
- makes it possible to add more values at a later date without breaking
- compatibility.
-
-- IntList This indicates a list of integers. This information is provided
- to the application as QValueList<int>. Useful for storing QSplitter
- geometries.
-
-An entry can optionally have a default value which is used as default when
-the value isn't specified in any config file. Default values are interpreted
-as literal constant values. If a default value needs to be computed
-or if it needs to be obtained from a function call, the \<default\> tag
-should contain the code="true" attribute. The contents of the \<default\>
-tag is then considered to be a C++ expression. Note that in this case you
-might have to add an \<include\> tag as described above so that the code
-which computes the default value can be compiled.
-
-Additional code for computing default values can be provided via
-the \<code\> tag. The contents of the \<code\> tag is inserted as-is. A
-typical use for this is to compute a common default value which can
-then be referenced by multiple entries that follow.
-
-<h2>Code generation options</h2>
-
-The options for generating the C++ sources are read from the file with the
-extension .kcfgc. To generate a class add the corresponding kcfgc file to the
-SOURCES line in the Makefile.am.
-
-The following options are read from the kcfgc file:
-
-<table>
-<tr>
- <td><b><i>Name</i></b></td>
- <td><b><i>Type</i></b></td>
- <td><b><i>Default</i></b></td>
- <td><b><i>Description</i></b></td>
-</tr>
-<tr>
- <td><b>File</b></td>
- <td>string</td>
- <td>programname.kcfg</td>
- <td>Name of kcfg file containing the options the class is generated for</td>
-</tr>
-<tr>
- <td><b>NameSpace</b></td>
- <td>string</td>
- <td>-</td>
- <td>Optional namespace for generated class</td>
-</tr>
-<tr>
- <td><b>ClassName</b></td>
- <td>string</td>
- <td>-</td>
- <td>Name of generated class (required)</td>
-</tr>
-<tr>
- <td><b>Inherits</b></td>
- <td>string</td>
- <td>TDEConfigSkeleton</td>
- <td>Class the generated class inherits from. This class must inherit
- TDEConfigSkeleton.</td>
-</tr>
-<tr>
- <td><b>Visibility</b></td>
- <td>string</td>
- <td>-</td>
- <td>Inserts visibility directive (for example KDE_EXPORT) between "class" keyword and class
- name in header file</td>
-</tr>
-<tr>
- <td><b>Singleton</b></td>
- <td>bool</td>
- <td>false</td>
- <td>Generated class is a singleton.</td>
-</tr>
-<tr>
- <td><b>CustomAdditions</b></td>
- <td>bool</td>
- <td>-</td>
- <td></td>
-</tr>
-<tr>
- <td><b>MemberVariables</b></td>
- <td>string: public|protected|private</td>
- <td>private</td>
- <td>C++ access modifier used for memeber variables holding the configuration
- valuse</td>
-</tr>
-<tr>
- <td><b>IncludeFiles</b></td>
- <td>comma separated list of strings</td>
- <td>-</td>
- <td>Names of files to be included in the header of the generated class</td>
-</tr>
-<tr>
- <td><b>Mutators</b></td>
- <td>true, false or a comma seperated list of options</td>
- <td>-</td>
- <td>If true, mutator functions for all configuration options are generated.
- If false, no mutator functions are generated. If a list is provided,
- mutator functions are generated for the options that are listed.</td>
-</tr>
-<tr>
- <td><b>ItemAccessors</b></td>
- <td>bool</td>
- <td>false</td>
- <td>Generate accessor functions for the TDEConfigSkeletonItem objects
- corresponding to the configuration options. If <b>SetUserTexts</b> is set,
- <b>ItemAccessors</b> also has to be set.</td>
-</tr>
-<tr>
- <td><b>SetUserTexts</b></td>
- <td>bool</td>
- <td>false</td>
- <td>Set the label and whatthis texts of the items from the kcfg file.If
- <b>SetUserTexts</b> is set, <b>ItemAccessors</b> also has to be set.</td>
-</tr>
-<tr>
- <td><b>GlobalEnums</b></td>
- <td>bool</td>
- <td>false</td>
- <td>If set to true all choices of Enum items will be created in the global
- scope of the generated class. If set to false, each Enum item will get an own
- namespace for its choices.</td>
-</tr>
-</table>
-
-
-<h2>Advanced options</h2>
-
-There are several possibilities to parameterize entries.
-
-- Parameterized entries
-
-An entry can be parameterized using a fixed range parameter specified with
-the \<parameter\> tag. Such parameter can either be an Enum or an int. An Enum
-parameter should specify the possible enumeration values with the \<choices\>
-tag. An int parameter should specify its maximum value. Its minimum value
-is always 0.
-
-A parameterized entry is expanded to a number of entries, one for each
-value in the parameter range. The name and key should contain a reference
-to the parameter in the form of $(parameter-name). When expanding the entries
-the $(parameter-name) part is replaced with the value of the parameter.
-In the case of an Enum parameter it is replaced with the name of the
-enumuration value. In the case of an int parameter it is replaced with
-the numeric value of the parameter.
-
-Parameterized entries all share the same default value unless different
-default values have been specified for specific parameter values.
-This can be done with the param= attribute of the \<default\>. When a
-param attribute is specified the default value only applies to that
-particular parameter value.
-
-Example 1:
-\verbatim
- <entry name="Color$(ColorIndex)" type="Color" key="color_$(ColorIndex)">
- <parameter name="ColorIndex" type="Int" max="3"/>
- <default param="0">#ff0000</default>
- <default param="1">#00ff00</default>
- <default param="2">#0000ff</default>
- <default param="3">#ffff00</default>
- </entry>
-\endverbatim
-
-The above describes 4 color configuration entries with the following defaults:
-
-\verbatim
-color_0=#ff0000
-color_1=#00ff00
-color_2=#0000ff
-color_3=#ffff00
-\endverbatim
-
-The configuration options will be accessible to the application via
-a QColor color(int ColorIndex) and a
-void setColor(int ColorIndex, const QColor &v) function.
-
-Example 2:
-\verbatim
- <entry name="Sound$(SoundEvent)" type="String" key="sound_$(SoundEvent)">
- <parameter name="SoundEvent" type="Enum">
- <values>
- <value>Explosion</value>
- <value>Crash</value>
- <value>Missile</value>
- </values>
- </parameter>
- <default param="Explosion">boom.wav</default>
- <default param="Crash">crash.wav</default>
- <default param="Missile">missile.wav</default>
- </entry>
-\endverbatim
-
-The above describes 3 string configuration entries with the following defaults:
-
-sound_Explosion=boom.wav
-sound_Crash=crash.wav
-sound_Missile=missile.wav
-
-The configuration options will be accessible to the application via
-a QString sound(int SoundEvent) and a
-void setSound(int SoundEvent, const QString &v) function.
-
-- Parameterized groups
-
-...STILL TODO...
-
-
-
-
-
-If you have questions or comments please contact Cornelius Schumacher
-<schumacher@kde.org> or Waldo Bastian <bastian@kde.org>
-*/
diff --git a/tdecore/kconfig_compiler/checkkcfg.pl b/tdecore/kconfig_compiler/checkkcfg.pl
deleted file mode 100755
index 2eddbeee6..000000000
--- a/tdecore/kconfig_compiler/checkkcfg.pl
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/perl
-
-if ( @ARGV != 1 ) {
- print STDERR "Missing arg: filename\n";
- exit 1;
-}
-
-$file = $ARGV[0];
-
-$file =~ /^(.*)\.[^\.]*$/;
-$filebase = $1;
-
-$file_h = "$filebase.h";
-$file_cpp = "$filebase.cpp";
-
-$kcfgc = $file . "c";
-
-$cmd = "./kconfig_compiler $file $kcfgc";
-
-#print "CMD $cmd\n";
-
-if ( system( $cmd ) != 0 ) {
- print STDERR "Unable to run kconfig_compiler\n";
- exit 1;
-}
-
-checkfile( $file_h );
-checkfile( $file_cpp );
-
-exit 0;
-
-sub checkfile()
-{
- my $file = shift;
-
- $file =~ /\/([^\/]*)$/;
- my $filename = $1;
-
- print "Checking '$filename':\n";
-
- my @ref;
- if ( !open( REF, "$file.ref" ) ) {
- print STDERR "Unable to open $file.ref\n";
- exit 1;
- }
- while( <REF> ) {
- push @ref, $_;
- }
- close REF;
-
- if ( !open( READ, $filename ) ) {
- print STDERR "Unable to open $filename\n";
- exit 1;
- }
-
- $error = 0;
- $i = 0;
- $line = 1;
- while( <READ> ) {
- $out = $_;
- $ref = @ref[$i++];
-
- if ( $out ne $ref ) {
- $error++;
- print " Line $line: Expected : $ref";
- print " Line $line: Compiler output : $out";
- }
-
- $line++;
- }
-
- close READ;
-
- if ( $error > 0 ) {
- print "\n FAILED: $error errors found.\n";
- if ( $error > 5 ) {
- system( "diff -u $file.ref $filename" );
- }
- exit 1;
- } else {
- print " OK\n";
- }
-}
diff --git a/tdecore/kconfig_compiler/example/Makefile.am b/tdecore/kconfig_compiler/example/Makefile.am
deleted file mode 100644
index 4e7a59fec..000000000
--- a/tdecore/kconfig_compiler/example/Makefile.am
+++ /dev/null
@@ -1,27 +0,0 @@
-AM_CPPFLAGS = -I$(top_srcdir)/tdecore -I$(top_srcdir) $(all_includes)
-
-check_PROGRAMS = example # autoexample
-EXTRA_PROGRAMS = autoexample
-
-example_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-example_LDADD = $(LIB_TDECORE)
-example_SOURCES = example.cpp exampleprefs_base.cpp
-
-autoexample_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-autoexample_LDADD = $(LIB_TDECORE) $(LIB_TDEUI)
-autoexample_SOURCES = exampleprefs_base.cpp general_base.ui myoptions_base.ui \
- autoexample.cpp
-
-example.o exampleprefs_base.o: exampleprefs_base.h
-# avoid running the below command in parallel
-exampleprefs_base.cpp: exampleprefs_base.h
-exampleprefs_base.cpp exampleprefs_base.h: $(srcdir)/example.kcfg ../kconfig_compiler $(srcdir)/exampleprefs_base.kcfgc
- ../kconfig_compiler $(srcdir)/example.kcfg $(srcdir)/exampleprefs_base.kcfgc
-
-METASOURCES = AUTO
-
-CLEANFILES = exampleprefs_base.h exampleprefs_base.cpp
-
-## The example's messages should not go into tdelibs.pot
-messages: rc.cpp
- true
diff --git a/tdecore/kconfig_compiler/example/autoexample.cpp b/tdecore/kconfig_compiler/example/autoexample.cpp
deleted file mode 100644
index 53e02f68d..000000000
--- a/tdecore/kconfig_compiler/example/autoexample.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- This file is part of KDE.
-
- Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "general_base.h"
-#include "myoptions_base.h"
-
-#include "exampleprefs_base.h"
-
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-#include <kglobal.h>
-#include <kconfig.h>
-#include <kstandarddirs.h>
-#include <kconfigdialog.h>
-
-#include <tqlabel.h>
-
-int main( int argc, char **argv )
-{
- TDEAboutData aboutData( "example", I18N_NOOP("autoconfig example"), "0.1" );
- aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
-
- TDECmdLineArgs::init( argc, argv, &aboutData );
-
- TDEApplication app;
-
- ExamplePrefsBase configSkeleton( "dummy1", "dummy2" );
- configSkeleton.readConfig();
-
- TDEConfigDialog *dialog = new TDEConfigDialog( 0, "settings", &configSkeleton );
-
- GeneralBase *general = new GeneralBase( 0 );
- dialog->addPage( general, i18n("General"), "General", "" );
-
- MyOptionsBase *myOptions = new MyOptionsBase( 0 );
- dialog->addPage( myOptions, i18n("MyOptions"), "MyOptions", "" );
-
- app.setMainWidget( dialog );
-
- dialog->show();
-
- return app.exec();
-}
diff --git a/tdecore/kconfig_compiler/example/example.cpp b/tdecore/kconfig_compiler/example/example.cpp
deleted file mode 100644
index cf808c9b2..000000000
--- a/tdecore/kconfig_compiler/example/example.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- This file is part of KDE.
-
- Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "exampleprefs_base.h"
-
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-#include <kglobal.h>
-#include <kconfig.h>
-#include <kstandarddirs.h>
-
-int main( int argc, char **argv )
-{
- TDEAboutData aboutData( "example", I18N_NOOP("cfgc example"), "0.1" );
- aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
-
- TDECmdLineArgs::init( argc, argv, &aboutData );
-
- TDEApplication app;
-
- ExamplePrefsBase *prefs = new ExamplePrefsBase("Trans1", "Folder2");
-
- prefs->readConfig();
-
- prefs->setAnotherOption(17);
-
- kdWarning() << "Another Option = " << prefs->anotherOption() << endl;
- kdWarning() << "Another Option2 = " << prefs->anotherOption2() << endl;
- kdWarning() << "MyPaths = " << prefs->myPaths() << endl;
- kdWarning() << "MyPaths2 = " << prefs->myPaths2() << endl;
-}
diff --git a/tdecore/kconfig_compiler/example/exampleprefs_base.kcfgc b/tdecore/kconfig_compiler/example/exampleprefs_base.kcfgc
deleted file mode 100644
index a9ac98dc7..000000000
--- a/tdecore/kconfig_compiler/example/exampleprefs_base.kcfgc
+++ /dev/null
@@ -1,18 +0,0 @@
-# Code generation options for kconfig_compiler
-ClassName=ExamplePrefsBase
-#
-# Singleton=false
-#
-# Inherits=TDEConfigSkeleton
-#
-# IncludeFiles=libtdepim/kpimprefs.h
-#
-# MemberVariables=public
-#
-### The following line includes the file exampleprefs_base_addon.h
-### It can be used to add extra functions and variables to the
-### class.
-# CustomAdditions=true
-#
-### Provide setFooBar(int) style functions
-Mutators=true
diff --git a/tdecore/kconfig_compiler/kconfig_compiler.cpp b/tdecore/kconfig_compiler/kconfig_compiler.cpp
deleted file mode 100644
index b8839f677..000000000
--- a/tdecore/kconfig_compiler/kconfig_compiler.cpp
+++ /dev/null
@@ -1,1700 +0,0 @@
-// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
-/*
- This file is part of KDE.
-
- Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
- Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
- Copyright (c) 2003 Zack Rusin <zack@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqfile.h>
-#include <tqtextstream.h>
-#include <tqdom.h>
-#include <tqregexp.h>
-
-#include <kaboutdata.h>
-#include <kapplication.h>
-#include <kdebug.h>
-#include <klocale.h>
-#include <kcmdlineargs.h>
-#include <kglobal.h>
-#include <kconfig.h>
-#include <ksimpleconfig.h>
-#include <kstandarddirs.h>
-
-#include <iostream>
-
-static const KCmdLineOptions options[] =
-{
- { "d", 0, 0 },
- { "directory <dir>", I18N_NOOP("Directory to generate files in"), "." },
- { "+file.kcfg", I18N_NOOP("Input kcfg XML file"), 0 },
- { "+file.kcfgc", I18N_NOOP("Code generation options file"), 0 },
- KCmdLineLastOption
-};
-
-
-bool globalEnums;
-bool itemAccessors;
-bool dpointer;
-TQStringList allNames;
-TQRegExp *validNameRegexp;
-TQString This;
-TQString Const;
-
-class CfgEntry
-{
- public:
- struct Choice
- {
- TQString name;
- TQString label;
- TQString whatsThis;
- };
-
- CfgEntry( const TQString &group, const TQString &type, const TQString &key,
- const TQString &name, const TQString &label,
- const TQString &whatsThis, const TQString &code,
- const TQString &defaultValue, const TQValueList<Choice> &choices,
- bool hidden )
- : mGroup( group ), mType( type ), mKey( key ), mName( name ),
- mLabel( label ), mWhatsThis( whatsThis ), mCode( code ),
- mDefaultValue( defaultValue ),
- mChoices( choices ), mHidden( hidden )
- {
- }
-
- void setGroup( const TQString &group ) { mGroup = group; }
- TQString group() const { return mGroup; }
-
- void setType( const TQString &type ) { mType = type; }
- TQString type() const { return mType; }
-
- void setKey( const TQString &key ) { mKey = key; }
- TQString key() const { return mKey; }
-
- void setName( const TQString &name ) { mName = name; }
- TQString name() const { return mName; }
-
- void setLabel( const TQString &label ) { mLabel = label; }
- TQString label() const { return mLabel; }
-
- void setWhatsThis( const TQString &whatsThis ) { mWhatsThis = whatsThis; }
- TQString whatsThis() const { return mWhatsThis; }
-
- void setDefaultValue( const TQString &d ) { mDefaultValue = d; }
- TQString defaultValue() const { return mDefaultValue; }
-
- void setCode( const TQString &d ) { mCode = d; }
- TQString code() const { return mCode; }
-
- void setMinValue( const TQString &d ) { mMin = d; }
- TQString minValue() const { return mMin; }
-
- void setMaxValue( const TQString &d ) { mMax = d; }
- TQString maxValue() const { return mMax; }
-
- void setParam( const TQString &d ) { mParam = d; }
- TQString param() const { return mParam; }
-
- void setParamName( const TQString &d ) { mParamName = d; }
- TQString paramName() const { return mParamName; }
-
- void setParamType( const TQString &d ) { mParamType = d; }
- TQString paramType() const { return mParamType; }
-
- void setChoices( const TQValueList<Choice> &d ) { mChoices = d; }
- TQValueList<Choice> choices() const { return mChoices; }
-
- void setParamValues( const TQStringList &d ) { mParamValues = d; }
- TQStringList paramValues() const { return mParamValues; }
-
- void setParamDefaultValues( const TQStringList &d ) { mParamDefaultValues = d; }
- TQString paramDefaultValue(int i) const { return mParamDefaultValues[i]; }
-
- void setParamMax( int d ) { mParamMax = d; }
- int paramMax() const { return mParamMax; }
-
- bool hidden() const { return mHidden; }
-
- void dump() const
- {
- kdDebug() << "<entry>" << endl;
- kdDebug() << " group: " << mGroup << endl;
- kdDebug() << " type: " << mType << endl;
- kdDebug() << " key: " << mKey << endl;
- kdDebug() << " name: " << mName << endl;
- kdDebug() << " label: " << mLabel << endl;
-// whatsthis
- kdDebug() << " code: " << mCode << endl;
-// kdDebug() << " values: " << mValues.join(":") << endl;
-
- if (!param().isEmpty())
- {
- kdDebug() << " param name: "<< mParamName << endl;
- kdDebug() << " param type: "<< mParamType << endl;
- kdDebug() << " paramvalues: " << mParamValues.join(":") << endl;
- }
- kdDebug() << " default: " << mDefaultValue << endl;
- kdDebug() << " hidden: " << mHidden << endl;
- kdDebug() << " min: " << mMin << endl;
- kdDebug() << " max: " << mMax << endl;
- kdDebug() << "</entry>" << endl;
- }
-
- private:
- TQString mGroup;
- TQString mType;
- TQString mKey;
- TQString mName;
- TQString mLabel;
- TQString mWhatsThis;
- TQString mCode;
- TQString mDefaultValue;
- TQString mParam;
- TQString mParamName;
- TQString mParamType;
- TQValueList<Choice> mChoices;
- TQStringList mParamValues;
- TQStringList mParamDefaultValues;
- int mParamMax;
- bool mHidden;
- TQString mMin;
- TQString mMax;
-};
-
-class Param {
-public:
- TQString name;
- TQString type;
-};
-
-// returns the name of an member variable
-// use itemPath to know the full path
-// like using d-> in case of dpointer
-static TQString varName(const TQString &n)
-{
- TQString result;
- if ( !dpointer ) {
- result = "m"+n;
- result[1] = result[1].upper();
- }
- else {
- result = n;
- result[0] = result[0].lower();
- }
- return result;
-}
-
-static TQString varPath(const TQString &n)
-{
- TQString result;
- if ( dpointer ) {
- result = "d->"+varName(n);
- }
- else {
- result = varName(n);
- }
- return result;
-}
-
-static TQString enumName(const TQString &n)
-{
- TQString result = "Enum"+n;
- result[4] = result[4].upper();
- return result;
-}
-
-static TQString setFunction(const TQString &n, const TQString &className = TQString())
-{
- TQString result = "set"+n;
- result[3] = result[3].upper();
-
- if ( !className.isEmpty() )
- result = className + "::" + result;
- return result;
-}
-
-
-static TQString getFunction(const TQString &n, const TQString &className = TQString())
-{
- TQString result = n;
- result[0] = result[0].lower();
-
- if ( !className.isEmpty() )
- result = className + "::" + result;
- return result;
-}
-
-
-static void addQuotes( TQString &s )
-{
- if ( s.left( 1 ) != "\"" ) s.prepend( "\"" );
- if ( s.right( 1 ) != "\"" ) s.append( "\"" );
-}
-
-static TQString quoteString( const TQString &s )
-{
- TQString r = s;
- r.replace( "\\", "\\\\" );
- r.replace( "\"", "\\\"" );
- r.replace( "\r", "" );
- r.replace( "\n", "\\n\"\n\"" );
- return "\"" + r + "\"";
-}
-
-static TQString literalString( const TQString &s )
-{
- bool isAscii = true;
- for(int i = s.length(); i--;)
- if (s[i].unicode() > 127) isAscii = false;
-
- if (isAscii)
- return "TQString::fromLatin1( " + quoteString(s) + " )";
- else
- return "TQString::fromUtf8( " + quoteString(s) + " )";
-}
-
-static TQString dumpNode(const TQDomNode &node)
-{
- TQString msg;
- TQTextStream s(&msg, IO_WriteOnly );
- node.save(s, 0);
-
- msg = msg.simplifyWhiteSpace();
- if (msg.length() > 40)
- return msg.left(37)+"...";
- return msg;
-}
-
-static TQString filenameOnly(TQString path)
-{
- int i = path.findRev('/');
- if (i >= 0)
- return path.mid(i+1);
- return path;
-}
-
-static void preProcessDefault( TQString &defaultValue, const TQString &name,
- const TQString &type,
- const TQValueList<CfgEntry::Choice> &choices,
- TQString &code )
-{
- if ( type == "String" && !defaultValue.isEmpty() ) {
- defaultValue = literalString(defaultValue);
-
- } else if ( type == "Path" && !defaultValue.isEmpty() ) {
- defaultValue = literalString( defaultValue );
-
- } else if ( (type == "StringList" || type == "PathList") && !defaultValue.isEmpty() ) {
- TQTextStream cpp( &code, IO_WriteOnly | IO_Append );
- if (!code.isEmpty())
- cpp << endl;
-
- cpp << " TQStringList default" << name << ";" << endl;
- TQStringList defaults = TQStringList::split( ",", defaultValue );
- TQStringList::ConstIterator it;
- for( it = defaults.begin(); it != defaults.end(); ++it ) {
- cpp << " default" << name << ".append( TQString::fromUtf8( \"" << *it << "\" ) );"
- << endl;
- }
- defaultValue = "default" + name;
-
- } else if ( type == "Color" && !defaultValue.isEmpty() ) {
- TQRegExp colorRe("\\d+,\\s*\\d+,\\s*\\d+");
- if (colorRe.exactMatch(defaultValue))
- {
- defaultValue = "TQColor( " + defaultValue + " )";
- }
- else
- {
- defaultValue = "TQColor( \"" + defaultValue + "\" )";
- }
-
- } else if ( type == "Enum" ) {
- if ( !globalEnums ) {
- TQValueList<CfgEntry::Choice>::ConstIterator it;
- for( it = choices.begin(); it != choices.end(); ++it ) {
- if ( (*it).name == defaultValue ) {
- defaultValue.prepend( enumName(name) + "::");
- break;
- }
- }
- }
-
- } else if ( type == "IntList" ) {
- TQTextStream cpp( &code, IO_WriteOnly | IO_Append );
- if (!code.isEmpty())
- cpp << endl;
-
- cpp << " TQValueList<int> default" << name << ";" << endl;
- TQStringList defaults = TQStringList::split( ",", defaultValue );
- TQStringList::ConstIterator it;
- for( it = defaults.begin(); it != defaults.end(); ++it ) {
- cpp << " default" << name << ".append( " << *it << " );"
- << endl;
- }
- defaultValue = "default" + name;
- }
-}
-
-
-CfgEntry *parseEntry( const TQString &group, const TQDomElement &element )
-{
- bool defaultCode = false;
- TQString type = element.attribute( "type" );
- TQString name = element.attribute( "name" );
- TQString key = element.attribute( "key" );
- TQString hidden = element.attribute( "hidden" );
- TQString label;
- TQString whatsThis;
- TQString defaultValue;
- TQString code;
- TQString param;
- TQString paramName;
- TQString paramType;
- TQValueList<CfgEntry::Choice> choices;
- TQStringList paramValues;
- TQStringList paramDefaultValues;
- TQString minValue;
- TQString maxValue;
- int paramMax = 0;
-
- TQDomNode n;
- for ( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
- TQDomElement e = n.toElement();
- TQString tag = e.tagName();
- if ( tag == "label" ) label = e.text();
- else if ( tag == "whatsthis" ) whatsThis = e.text();
- else if ( tag == "min" ) minValue = e.text();
- else if ( tag == "max" ) maxValue = e.text();
- else if ( tag == "code" ) code = e.text();
- else if ( tag == "parameter" )
- {
- param = e.attribute( "name" );
- paramType = e.attribute( "type" );
- if ( param.isEmpty() ) {
- kdError() << "Parameter must have a name: " << dumpNode(e) << endl;
- return 0;
- }
- if ( paramType.isEmpty() ) {
- kdError() << "Parameter must have a type: " << dumpNode(e) << endl;
- return 0;
- }
- if ((paramType == "Int") || (paramType == "UInt"))
- {
- bool ok;
- paramMax = e.attribute("max").toInt(&ok);
- if (!ok)
- {
- kdError() << "Integer parameter must have a maximum (e.g. max=\"0\"): " << dumpNode(e) << endl;
- return 0;
- }
- }
- else if (paramType == "Enum")
- {
- TQDomNode n2;
- for ( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
- TQDomElement e2 = n2.toElement();
- if (e2.tagName() == "values")
- {
- TQDomNode n3;
- for ( n3 = e2.firstChild(); !n3.isNull(); n3 = n3.nextSibling() ) {
- TQDomElement e3 = n3.toElement();
- if (e3.tagName() == "value")
- {
- paramValues.append( e3.text() );
- }
- }
- break;
- }
- }
- if (paramValues.isEmpty())
- {
- kdError() << "No values specified for parameter '" << param << "'." << endl;
- return 0;
- }
- paramMax = paramValues.count()-1;
- }
- else
- {
- kdError() << "Parameter '" << param << "' has type " << paramType << " but must be of type int, uint or Enum." << endl;
- return 0;
- }
- }
- else if ( tag == "default" )
- {
- if (e.attribute("param").isEmpty())
- {
- defaultValue = e.text();
- if (e.attribute( "code" ) == "true")
- defaultCode = true;
- }
- }
- else if ( tag == "choices" ) {
- TQDomNode n2;
- for( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
- TQDomElement e2 = n2.toElement();
- if ( e2.tagName() == "choice" ) {
- TQDomNode n3;
- CfgEntry::Choice choice;
- choice.name = e2.attribute( "name" );
- if ( choice.name.isEmpty() ) {
- kdError() << "Tag <choice> requires attribute 'name'." << endl;
- }
- for( n3 = e2.firstChild(); !n3.isNull(); n3 = n3.nextSibling() ) {
- TQDomElement e3 = n3.toElement();
- if ( e3.tagName() == "label" ) choice.label = e3.text();
- if ( e3.tagName() == "whatsthis" ) choice.whatsThis = e3.text();
- }
- choices.append( choice );
- }
- }
- }
- }
-
- bool nameIsEmpty = name.isEmpty();
- if ( nameIsEmpty && key.isEmpty() ) {
- kdError() << "Entry must have a name or a key: " << dumpNode(element) << endl;
- return 0;
- }
-
- if ( key.isEmpty() ) {
- key = name;
- }
-
- if ( nameIsEmpty ) {
- name = key;
- name.replace( " ", TQString() );
- } else if ( name.contains( ' ' ) ) {
- kdWarning()<<"Entry '"<<name<<"' contains spaces! <name> elements can't contain speces!"<<endl;
- name.remove( ' ' );
- }
-
- if (name.contains("$("))
- {
- if (param.isEmpty())
- {
- kdError() << "Name may not be parameterized: " << name << endl;
- return 0;
- }
- }
- else
- {
- if (!param.isEmpty())
- {
- kdError() << "Name must contain '$(" << param << ")': " << name << endl;
- return 0;
- }
- }
-
- if ( label.isEmpty() ) {
- label = key;
- }
-
- if ( type.isEmpty() ) type = "String"; // XXX : implicit type might be bad
-
- if (!param.isEmpty())
- {
- // Adjust name
- paramName = name;
- name.replace("$("+param+")", TQString());
- // Lookup defaults for indexed entries
- for(int i = 0; i <= paramMax; i++)
- {
- paramDefaultValues.append(TQString());
- }
-
- TQDomNode n;
- for ( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
- TQDomElement e = n.toElement();
- TQString tag = e.tagName();
- if ( tag == "default" )
- {
- TQString index = e.attribute("param");
- if (index.isEmpty())
- continue;
-
- bool ok;
- int i = index.toInt(&ok);
- if (!ok)
- {
- i = paramValues.findIndex(index);
- if (i == -1)
- {
- kdError() << "Index '" << index << "' for default value is unknown." << endl;
- return 0;
- }
- }
-
- if ((i < 0) || (i > paramMax))
- {
- kdError() << "Index '" << i << "' for default value is out of range [0, "<< paramMax<<"]." << endl;
- return 0;
- }
-
- TQString tmpDefaultValue = e.text();
-
- if (e.attribute( "code" ) != "true")
- preProcessDefault(tmpDefaultValue, name, type, choices, code);
-
- paramDefaultValues[i] = tmpDefaultValue;
- }
- }
- }
-
- if (!validNameRegexp->exactMatch(name))
- {
- if (nameIsEmpty)
- kdError() << "The key '" << key << "' can not be used as name for the entry because "
- "it is not a valid name. You need to specify a valid name for this entry." << endl;
- else
- kdError() << "The name '" << name << "' is not a valid name for an entry." << endl;
- return 0;
- }
-
- if (allNames.contains(name))
- {
- if (nameIsEmpty)
- kdError() << "The key '" << key << "' can not be used as name for the entry because "
- "it does not result in a unique name. You need to specify a unique name for this entry." << endl;
- else
- kdError() << "The name '" << name << "' is not unique." << endl;
- return 0;
- }
- allNames.append(name);
-
- if (!defaultCode)
- {
- preProcessDefault(defaultValue, name, type, choices, code);
- }
-
- CfgEntry *result = new CfgEntry( group, type, key, name, label, whatsThis,
- code, defaultValue, choices,
- hidden == "true" );
- if (!param.isEmpty())
- {
- result->setParam(param);
- result->setParamName(paramName);
- result->setParamType(paramType);
- result->setParamValues(paramValues);
- result->setParamDefaultValues(paramDefaultValues);
- result->setParamMax(paramMax);
- }
- result->setMinValue(minValue);
- result->setMaxValue(maxValue);
-
- return result;
-}
-
-/**
- Return parameter declaration for given type.
-*/
-TQString param( const TQString &type )
-{
- if ( type == "String" ) return "const TQString &";
- else if ( type == "StringList" ) return "const TQStringList &";
- else if ( type == "Font" ) return "const TQFont &";
- else if ( type == "Rect" ) return "const TQRect &";
- else if ( type == "Size" ) return "const TQSize &";
- else if ( type == "Color" ) return "const TQColor &";
- else if ( type == "Point" ) return "const TQPoint &";
- else if ( type == "Int" ) return "int";
- else if ( type == "UInt" ) return "uint";
- else if ( type == "Bool" ) return "bool";
- else if ( type == "Double" ) return "double";
- else if ( type == "DateTime" ) return "const TQDateTime &";
- else if ( type == "Int64" ) return "TQ_INT64";
- else if ( type == "UInt64" ) return "TQ_UINT64";
- else if ( type == "IntList" ) return "const TQValueList<int> &";
- else if ( type == "Enum" ) return "int";
- else if ( type == "Path" ) return "const TQString &";
- else if ( type == "PathList" ) return "const TQStringList &";
- else if ( type == "Password" ) return "const TQString &";
- else {
- kdError() <<"kconfig_compiler does not support type \""<< type <<"\""<<endl;
- return TQSTRING_OBJECT_NAME_STRING; //For now, but an assert would be better
- }
-}
-
-/**
- Actual C++ storage type for given type.
-*/
-TQString cppType( const TQString &type )
-{
- if ( type == "String" ) return TQSTRING_OBJECT_NAME_STRING;
- else if ( type == "StringList" ) return TQSTRINGLIST_OBJECT_NAME_STRING;
- else if ( type == "Font" ) return "TQFont";
- else if ( type == "Rect" ) return "TQRect";
- else if ( type == "Size" ) return "TQSize";
- else if ( type == "Color" ) return "TQColor";
- else if ( type == "Point" ) return TQPOINT_OBJECT_NAME_STRING;
- else if ( type == "Int" ) return "int";
- else if ( type == "UInt" ) return "uint";
- else if ( type == "Bool" ) return "bool";
- else if ( type == "Double" ) return "double";
- else if ( type == "DateTime" ) return "TQDateTime";
- else if ( type == "Int64" ) return "TQ_INT64";
- else if ( type == "UInt64" ) return "TQ_UINT64";
- else if ( type == "IntList" ) return "TQValueList<int>";
- else if ( type == "Enum" ) return "int";
- else if ( type == "Path" ) return TQSTRING_OBJECT_NAME_STRING;
- else if ( type == "PathList" ) return TQSTRINGLIST_OBJECT_NAME_STRING;
- else if ( type == "Password" ) return TQSTRING_OBJECT_NAME_STRING;
- else {
- kdError()<<"kconfig_compiler does not support type \""<< type <<"\""<<endl;
- return TQSTRING_OBJECT_NAME_STRING; //For now, but an assert would be better
- }
-}
-
-TQString defaultValue( const TQString &type )
-{
- if ( type == "String" ) return "\"\""; // Use empty string, not null string!
- else if ( type == "StringList" ) return "TQStringList()";
- else if ( type == "Font" ) return "TDEGlobalSettings::generalFont()";
- else if ( type == "Rect" ) return "TQRect()";
- else if ( type == "Size" ) return "TQSize()";
- else if ( type == "Color" ) return "TQColor(128, 128, 128)";
- else if ( type == "Point" ) return "TQPoint()";
- else if ( type == "Int" ) return "0";
- else if ( type == "UInt" ) return "0";
- else if ( type == "Bool" ) return "false";
- else if ( type == "Double" ) return "0.0";
- else if ( type == "DateTime" ) return "TQDateTime()";
- else if ( type == "Int64" ) return "0";
- else if ( type == "UInt64" ) return "0";
- else if ( type == "IntList" ) return "TQValueList<int>()";
- else if ( type == "Enum" ) return "0";
- else if ( type == "Path" ) return "\"\""; // Use empty string, not null string!
- else if ( type == "PathList" ) return "TQStringList()";
- else if ( type == "Password" ) return "\"\""; // Use empty string, not null string!
- else {
- kdWarning()<<"Error, kconfig_compiler doesn't support the \""<< type <<"\" type!"<<endl;
- return TQSTRING_OBJECT_NAME_STRING; //For now, but an assert would be better
- }
-}
-
-TQString itemType( const TQString &type )
-{
- TQString t;
-
- t = type;
- t.replace( 0, 1, t.left( 1 ).upper() );
-
- return t;
-}
-
-static TQString itemDeclaration(const CfgEntry *e)
-{
- if (itemAccessors)
- return TQString();
-
- TQString fCap = e->name();
- fCap[0] = fCap[0].upper();
- return " TDEConfigSkeleton::Item"+itemType( e->type() ) +
- " *item" + fCap +
- ( (!e->param().isEmpty())?(TQString("[%1]").arg(e->paramMax()+1)) : TQString()) +
- ";\n";
-}
-
-// returns the name of an item variable
-// use itemPath to know the full path
-// like using d-> in case of dpointer
-static TQString itemVar(const CfgEntry *e)
-{
- TQString result;
- if (itemAccessors)
- {
- if ( !dpointer )
- {
- result = "m" + e->name() + "Item";
- result[1] = result[1].upper();
- }
- else
- {
- result = e->name() + "Item";
- result[0] = result[0].lower();
- }
- }
- else
- {
- result = "item" + e->name();
- result[4] = result[4].upper();
- }
- return result;
-}
-
-static TQString itemPath(const CfgEntry *e)
-{
- TQString result;
- if ( dpointer ) {
- result = "d->"+itemVar(e);
- }
- else {
- result = itemVar(e);
- }
- return result;
-}
-
-TQString newItem( const TQString &type, const TQString &name, const TQString &key,
- const TQString &defaultValue, const TQString &param = TQString())
-{
- TQString t = "new TDEConfigSkeleton::Item" + itemType( type ) +
- "( currentGroup(), " + key + ", " + varPath( name ) + param;
- if ( type == "Enum" ) t += ", values" + name;
- if ( !defaultValue.isEmpty() ) {
- t += ", ";
- if ( type == "String" ) t += defaultValue;
- else t+= defaultValue;
- }
- t += " );";
-
- return t;
-}
-
-TQString paramString(const TQString &s, const CfgEntry *e, int i)
-{
- TQString result = s;
- TQString needle = "$("+e->param()+")";
- if (result.contains(needle))
- {
- TQString tmp;
- if (e->paramType() == "Enum")
- {
- tmp = e->paramValues()[i];
- }
- else
- {
- tmp = TQString::number(i);
- }
-
- result.replace(needle, tmp);
- }
- return result;
-}
-
-TQString paramString(const TQString &group, const TQValueList<Param> &parameters)
-{
- TQString paramString = group;
- TQString arguments;
- int i = 1;
- for (TQValueList<Param>::ConstIterator it = parameters.begin();
- it != parameters.end(); ++it)
- {
- if (paramString.contains("$("+(*it).name+")"))
- {
- TQString tmp;
- tmp.sprintf("%%%d", i++);
- paramString.replace("$("+(*it).name+")", tmp);
- arguments += ".arg( mParam"+(*it).name+" )";
- }
- }
- if (arguments.isEmpty())
- return "TQString::fromLatin1( \""+group+"\" )";
-
- return "TQString::fromLatin1( \""+paramString+"\" )"+arguments;
-}
-
-/* int i is the value of the parameter */
-TQString userTextsFunctions( CfgEntry *e, TQString itemVarStr=TQString(), TQString i=TQString() )
-{
- TQString txt;
- if (itemVarStr.isNull()) itemVarStr=itemPath(e);
- if ( !e->label().isEmpty() ) {
- txt += " " + itemVarStr + "->setLabel( i18n(";
- if ( !e->param().isEmpty() )
- txt += quoteString(e->label().replace("$("+e->param()+")", i));
- else
- txt+= quoteString(e->label());
- txt+= ") );\n";
- }
- if ( !e->whatsThis().isEmpty() ) {
- txt += " " + itemVarStr + "->setWhatsThis( i18n(";
- if ( !e->param().isEmpty() )
- txt += quoteString(e->whatsThis().replace("$("+e->param()+")", i));
- else
- txt+= quoteString(e->whatsThis());
- txt+=") );\n";
- }
- return txt;
-}
-
-// returns the member accesor implementation
-// which should go in the h file if inline
-// or the cpp file if not inline
-TQString memberAccessorBody( CfgEntry *e )
-{
- TQString result;
- TQTextStream out(&result, IO_WriteOnly);
- TQString n = e->name();
- TQString t = e->type();
-
- out << "return " << This << varPath(n);
- if (!e->param().isEmpty()) out << "[i]";
- out << ";" << endl;
-
- return result;
-}
-
-// returns the member mutator implementation
-// which should go in the h file if inline
-// or the cpp file if not inline
-TQString memberMutatorBody( CfgEntry *e )
-{
- TQString result;
- TQTextStream out(&result, IO_WriteOnly);
- TQString n = e->name();
- TQString t = e->type();
-
- if (!e->minValue().isEmpty())
- {
- out << "if (v < " << e->minValue() << ")" << endl;
- out << "{" << endl;
- out << " kdDebug() << \"" << setFunction(n);
- out << ": value \" << v << \" is less than the minimum value of ";
- out << e->minValue()<< "\" << endl;" << endl;
- out << " v = " << e->minValue() << ";" << endl;
- out << "}" << endl;
- }
-
- if (!e->maxValue().isEmpty())
- {
- out << endl << "if (v > " << e->maxValue() << ")" << endl;
- out << "{" << endl;
- out << " kdDebug() << \"" << setFunction(n);
- out << ": value \" << v << \" is greater than the maximum value of ";
- out << e->maxValue()<< "\" << endl;" << endl;
- out << " v = " << e->maxValue() << ";" << endl;
- out << "}" << endl << endl;
- }
-
- out << "if (!" << This << "isImmutable( TQString::fromLatin1( \"";
- if (!e->param().isEmpty())
- {
- out << e->paramName().replace("$("+e->param()+")", "%1") << "\" ).arg( ";
- if ( e->paramType() == "Enum" ) {
- out << "TQString::fromLatin1( ";
-
- if (globalEnums)
- out << enumName(e->param()) << "ToString[i]";
- else
- out << enumName(e->param()) << "::enumToString[i]";
-
- out << " )";
- }
- else
- {
- out << "i";
- }
- out << " )";
- }
- else
- {
- out << n << "\" )";
- }
- out << " ))" << endl;
- out << " " << This << varPath(n);
- if (!e->param().isEmpty())
- out << "[i]";
- out << " = v;" << endl;
-
- return result;
-}
-
-// returns the item accesor implementation
-// which should go in the h file if inline
-// or the cpp file if not inline
-TQString itemAccessorBody( CfgEntry *e )
-{
- TQString result;
- TQTextStream out(&result, IO_WriteOnly);
-
- out << "return " << itemPath(e);
- if (!e->param().isEmpty()) out << "[i]";
- out << ";" << endl;
-
- return result;
-}
-
-//indents text adding X spaces per line
-TQString indent(TQString text, int spaces)
-{
- TQString result;
- TQTextStream out(&result, IO_WriteOnly);
- TQTextStream in(&text, IO_ReadOnly);
- TQString currLine;
- while ( !in.atEnd() )
- {
- currLine = in.readLine();
- if (!currLine.isEmpty())
- for (int i=0; i < spaces; i++)
- out << " ";
- out << currLine << endl;
- }
- return result;
-}
-
-
-int main( int argc, char **argv )
-{
- TDEAboutData aboutData( "kconfig_compiler", I18N_NOOP("TDE .kcfg compiler"), "0.3",
- I18N_NOOP("TDEConfig Compiler") , TDEAboutData::License_LGPL );
- aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
- aboutData.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
- aboutData.addAuthor( "Zack Rusin", 0, "zack@kde.org" );
- aboutData.addCredit( "Reinhold Kainhofer", "Fix for parametrized entries",
- "reinhold@kainhofer.com", "http://reinhold.kainhofer.com" );
- aboutData.addCredit( "Duncan Mac-Vicar P.", "dpointer support",
- "duncan@kde.org", "http://www.mac-vicar.com/~duncan" );
-
- TDECmdLineArgs::init( argc, argv, &aboutData );
- TDECmdLineArgs::addCmdLineOptions( options );
-
- TDEInstance app( &aboutData );
-
- TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
-
- if ( args->count() < 2 ) {
- kdError() << "Too few arguments." << endl;
- return 1;
- }
- if ( args->count() > 2 ) {
- kdError() << "Too many arguments." << endl;
- return 1;
- }
-
- validNameRegexp = new TQRegExp("[a-zA-Z_][a-zA-Z0-9_]*");
-
- TQString baseDir = TQFile::decodeName(args->getOption("directory"));
- if (!baseDir.endsWith("/"))
- baseDir.append("/");
-
- TQString inputFilename = args->url( 0 ).path();
- TQString codegenFilename = args->url( 1 ).path();
-
- if (!codegenFilename.endsWith(".kcfgc"))
- {
- kdError() << "Codegen options file must have extension .kcfgc" << endl;
- return 1;
- }
- TQString baseName = args->url( 1 ).fileName();
- baseName = baseName.left(baseName.length() - 6);
-
- KSimpleConfig codegenConfig( codegenFilename, true );
-
- TQString nameSpace = codegenConfig.readEntry("NameSpace");
- TQString className = codegenConfig.readEntry("ClassName");
- TQString inherits = codegenConfig.readEntry("Inherits");
- TQString visibility = codegenConfig.readEntry("Visibility");
- if (!visibility.isEmpty()) visibility+=" ";
- bool singleton = codegenConfig.readBoolEntry("Singleton", false);
- bool staticAccessors = singleton;
- //bool useDPointer = codegenConfig.readBoolEntry("DPointer", false);
- bool customAddons = codegenConfig.readBoolEntry("CustomAdditions");
- TQString memberVariables = codegenConfig.readEntry("MemberVariables");
- TQStringList headerIncludes = codegenConfig.readListEntry("IncludeFiles");
- TQStringList mutators = codegenConfig.readListEntry("Mutators");
- bool allMutators = false;
- if ((mutators.count() == 1) && (mutators[0].lower() == "true"))
- allMutators = true;
- itemAccessors = codegenConfig.readBoolEntry( "ItemAccessors", false );
- bool setUserTexts = codegenConfig.readBoolEntry( "SetUserTexts", false );
-
- globalEnums = codegenConfig.readBoolEntry( "GlobalEnums", false );
-
- dpointer = (memberVariables == "dpointer");
-
- TQFile input( inputFilename );
-
- TQDomDocument doc;
- TQString errorMsg;
- int errorRow;
- int errorCol;
- if ( !doc.setContent( &input, &errorMsg, &errorRow, &errorCol ) ) {
- kdError() << "Unable to load document." << endl;
- kdError() << "Parse error in " << args->url( 0 ).fileName() << ", line " << errorRow << ", col " << errorCol << ": " << errorMsg << endl;
- return 1;
- }
-
- TQDomElement cfgElement = doc.documentElement();
-
- if ( cfgElement.isNull() ) {
- kdError() << "No document in kcfg file" << endl;
- return 1;
- }
-
- TQString cfgFileName;
- bool cfgFileNameArg = false;
- TQValueList<Param> parameters;
- TQStringList includes;
-
- TQPtrList<CfgEntry> entries;
- entries.setAutoDelete( true );
-
- TQDomNode n;
- for ( n = cfgElement.firstChild(); !n.isNull(); n = n.nextSibling() ) {
- TQDomElement e = n.toElement();
-
- TQString tag = e.tagName();
-
- if ( tag == "include" ) {
- TQString includeFile = e.text();
- if (!includeFile.isEmpty())
- includes.append(includeFile);
-
- } else if ( tag == "kcfgfile" ) {
- cfgFileName = e.attribute( "name" );
- cfgFileNameArg = e.attribute( "arg" ).lower() == "true";
- TQDomNode n2;
- for( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
- TQDomElement e2 = n2.toElement();
- if ( e2.tagName() == "parameter" ) {
- Param p;
- p.name = e2.attribute( "name" );
- p.type = e2.attribute( "type" );
- if (p.type.isEmpty())
- p.type = "String";
- parameters.append( p );
- }
- }
-
- } else if ( tag == "group" ) {
- TQString group = e.attribute( "name" );
- if ( group.isEmpty() ) {
- kdError() << "Group without name" << endl;
- return 1;
- }
- TQDomNode n2;
- for( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
- TQDomElement e2 = n2.toElement();
- if ( e2.tagName() != "entry" ) continue;
- CfgEntry *entry = parseEntry( group, e2 );
- if ( entry ) entries.append( entry );
- else {
- kdError() << "Can't parse entry." << endl;
- return 1;
- }
- }
- }
- }
-
- if ( inherits.isEmpty() ) inherits = "TDEConfigSkeleton";
-
- if ( className.isEmpty() ) {
- kdError() << "Class name missing" << endl;
- return 1;
- }
-
- if ( singleton && !parameters.isEmpty() ) {
- kdError() << "Singleton class can not have parameters" << endl;
- return 1;
- }
-
- if ( !cfgFileName.isEmpty() && cfgFileNameArg)
- {
- kdError() << "Having both a fixed filename and a filename as argument is not possible." << endl;
- return 1;
- }
-
- if ( entries.isEmpty() ) {
- kdWarning() << "No entries." << endl;
- }
-
-#if 0
- CfgEntry *cfg;
- for( cfg = entries.first(); cfg; cfg = entries.next() ) {
- cfg->dump();
- }
-#endif
-
- TQString headerFileName = baseName + ".h";
- TQString implementationFileName = baseName + ".cpp";
- TQString cppPreamble; // code to be inserted at the beginnin of the cpp file, e.g. initialization of static values
-
- TQFile header( baseDir + headerFileName );
- if ( !header.open( IO_WriteOnly ) ) {
- kdError() << "Can't open '" << headerFileName << "' for writing." << endl;
- return 1;
- }
-
- TQTextStream h( &header );
-
- h << "// This file is generated by kconfig_compiler from " << args->url(0).fileName() << "." << endl;
- h << "// All changes you do to this file will be lost." << endl;
-
- h << "#ifndef " << ( !nameSpace.isEmpty() ? nameSpace.upper() + "_" : "" )
- << className.upper() << "_H" << endl;
- h << "#define " << ( !nameSpace.isEmpty() ? nameSpace.upper() + "_" : "" )
- << className.upper() << "_H" << endl << endl;
-
- // Includes
- TQStringList::ConstIterator it;
- for( it = headerIncludes.begin(); it != headerIncludes.end(); ++it ) {
- h << "#include <" << *it << ">" << endl;
- }
-
- if ( headerIncludes.count() > 0 ) h << endl;
-
- if ( !singleton && cfgFileNameArg && parameters.isEmpty() )
- h << "#include <kglobal.h>" << endl;
-
- h << "#include <kconfigskeleton.h>" << endl;
- h << "#include <kdebug.h>" << endl << endl;
-
- // Includes
- for( it = includes.begin(); it != includes.end(); ++it ) {
- h << "#include <" << *it << ">" << endl;
- }
-
-
- if ( !nameSpace.isEmpty() )
- h << "namespace " << nameSpace << " {" << endl << endl;
-
- // Private class declaration
- if ( dpointer )
- h << "class " << className << "Private;" << endl << endl;
-
- // Class declaration header
- h << "class " << visibility << className << " : public " << inherits << endl;
- h << "{" << endl;
- h << " public:" << endl;
-
- // enums
- CfgEntry *e;
- for( e = entries.first(); e; e = entries.next() ) {
- TQValueList<CfgEntry::Choice> choices = e->choices();
- if ( !choices.isEmpty() ) {
- TQStringList values;
- TQValueList<CfgEntry::Choice>::ConstIterator itChoice;
- for( itChoice = choices.begin(); itChoice != choices.end(); ++itChoice ) {
- values.append( (*itChoice).name );
- }
- if ( globalEnums ) {
- h << " enum { " << values.join( ", " ) << " };" << endl;
- } else {
- h << " class " << enumName(e->name()) << endl;
- h << " {" << endl;
- h << " public:" << endl;
- h << " enum type { " << values.join( ", " ) << ", COUNT };" << endl;
- h << " };" << endl;
- }
- }
- TQStringList values = e->paramValues();
- if ( !values.isEmpty() ) {
- if ( globalEnums ) {
- h << " enum { " << values.join( ", " ) << " };" << endl;
- h << " static const char* const " << enumName(e->param()) << "ToString[];" << endl;
- cppPreamble += "const char* const " + className + "::" + enumName(e->param()) + "ToString[] = " +
- "{ \"" + values.join( "\", \"" ) + "\" };\n";
- } else {
- h << " class " << enumName(e->param()) << endl;
- h << " {" << endl;
- h << " public:" << endl;
- h << " enum type { " << values.join( ", " ) << ", COUNT };" << endl;
- h << " static const char* const enumToString[];" << endl;
- h << " };" << endl;
- cppPreamble += "const char* const " + className + "::" + enumName(e->param()) + "::enumToString[] = " +
- "{ \"" + values.join( "\", \"" ) + "\" };\n";
- }
- }
- }
-
- h << endl;
-
- // Constructor or singleton accessor
- if ( !singleton ) {
- h << " " << className << "(";
- if (cfgFileNameArg)
- h << " KSharedConfig::Ptr config" << (parameters.isEmpty() ? " = TDEGlobal::sharedConfig()" : ", ");
- for (TQValueList<Param>::ConstIterator it = parameters.begin();
- it != parameters.end(); ++it)
- {
- if (it != parameters.begin())
- h << ",";
- h << " " << param((*it).type) << " " << (*it).name;
- }
- h << " );" << endl;
- } else {
- h << " static " << className << " *self();" << endl;
- if (cfgFileNameArg)
- h << " static void instance(const char * cfgfilename);" << endl;
- }
-
- // Destructor
- h << " ~" << className << "();" << endl << endl;
-
- // global variables
- if (staticAccessors)
- This = "self()->";
- else
- Const = " const";
-
- for( e = entries.first(); e; e = entries.next() ) {
- TQString n = e->name();
- TQString t = e->type();
-
- // Manipulator
- if (allMutators || mutators.contains(n))
- {
- h << " /**" << endl;
- h << " Set " << e->label() << endl;
- h << " */" << endl;
- if (staticAccessors)
- h << " static" << endl;
- h << " void " << setFunction(n) << "( ";
- if (!e->param().isEmpty())
- h << cppType(e->paramType()) << " i, ";
- h << param( t ) << " v )";
- // function body inline only if not using dpointer
- // for BC mode
- if ( !dpointer )
- {
- h << endl << " {" << endl;
- h << indent(memberMutatorBody(e), 6 );
- h << " }" << endl;
- }
- else
- {
- h << ";" << endl;
- }
- }
- h << endl;
- // Accessor
- h << " /**" << endl;
- h << " Get " << e->label() << endl;
- h << " */" << endl;
- if (staticAccessors)
- h << " static" << endl;
- h << " " << cppType(t) << " " << getFunction(n) << "(";
- if (!e->param().isEmpty())
- h << " " << cppType(e->paramType()) <<" i ";
- h << ")" << Const;
- // function body inline only if not using dpointer
- // for BC mode
- if ( !dpointer )
- {
- h << endl << " {" << endl;
- h << indent(memberAccessorBody(e), 6 );
- h << " }" << endl;
- }
- else
- {
- h << ";" << endl;
- }
-
- // Item accessor
- if ( itemAccessors ) {
- h << endl;
- h << " /**" << endl;
- h << " Get Item object corresponding to " << n << "()"
- << endl;
- h << " */" << endl;
- h << " Item" << itemType( e->type() ) << " *"
- << getFunction( n ) << "Item(";
- if (!e->param().isEmpty()) {
- h << " " << cppType(e->paramType()) << " i ";
- }
- h << ")";
- if (! dpointer )
- {
- h << endl << " {" << endl;
- h << indent( itemAccessorBody(e), 6);
- h << " }" << endl;
- }
- else
- {
- h << ";" << endl;
- }
- }
-
- h << endl;
- }
-
- // Static writeConfig method for singleton
- if ( singleton ) {
- h << " static" << endl;
- h << " void writeConfig()" << endl;
- h << " {" << endl;
- h << " static_cast<TDEConfigSkeleton*>(self())->writeConfig();" << endl;
- h << " }" << endl;
- }
-
- h << " protected:" << endl;
-
- // Private constructor for singleton
- if ( singleton ) {
- h << " " << className << "(";
- if ( cfgFileNameArg )
- h << "const char *arg";
- h << ");" << endl;
- h << " static " << className << " *mSelf;" << endl << endl;
- }
-
- // Member variables
- if ( !memberVariables.isEmpty() && memberVariables != "private" && memberVariables != "dpointer") {
- h << " " << memberVariables << ":" << endl;
- }
-
- // Class Parameters
- for (TQValueList<Param>::ConstIterator it = parameters.begin();
- it != parameters.end(); ++it)
- {
- h << " " << cppType((*it).type) << " mParam" << (*it).name << ";" << endl;
- }
-
- if ( memberVariables != "dpointer" )
- {
- TQString group;
- for( e = entries.first(); e; e = entries.next() ) {
- if ( e->group() != group ) {
- group = e->group();
- h << endl;
- h << " // " << group << endl;
- }
- h << " " << cppType(e->type()) << " " << varName(e->name());
- if (!e->param().isEmpty())
- {
- h << TQString("[%1]").arg(e->paramMax()+1);
- }
- h << ";" << endl;
- }
-
- h << endl << " private:" << endl;
- if ( itemAccessors ) {
- for( e = entries.first(); e; e = entries.next() ) {
- h << " Item" << itemType( e->type() ) << " *" << itemVar( e );
- if (!e->param().isEmpty() ) h << TQString("[%1]").arg( e->paramMax()+1 );
- h << ";" << endl;
- }
- }
-
- }
- else
- {
- // use a private class for both member variables and items
- h << " private:" << endl;
- h << " " + className + "Private *d;" << endl;
- }
-
- if (customAddons)
- {
- h << " // Include custom additions" << endl;
- h << " #include \"" << filenameOnly(baseName) << "_addons.h\"" <<endl;
- }
-
- h << "};" << endl << endl;
-
- if ( !nameSpace.isEmpty() ) h << "}" << endl << endl;
-
- h << "#endif" << endl << endl;
-
-
- header.close();
-
- TQFile implementation( baseDir + implementationFileName );
- if ( !implementation.open( IO_WriteOnly ) ) {
- kdError() << "Can't open '" << implementationFileName << "' for writing."
- << endl;
- return 1;
- }
-
- TQTextStream cpp( &implementation );
-
-
- cpp << "// This file is generated by kconfig_compiler from " << args->url(0).fileName() << "." << endl;
- cpp << "// All changes you do to this file will be lost." << endl << endl;
-
- cpp << "#include \"" << headerFileName << "\"" << endl << endl;
-
- if ( setUserTexts ) cpp << "#include <klocale.h>" << endl << endl;
-
- // Header required by singleton implementation
- if ( singleton )
- cpp << "#include <kstaticdeleter.h>" << endl << endl;
- if ( singleton && cfgFileNameArg )
- cpp << "#include <kdebug.h>" << endl << endl;
-
- if ( !nameSpace.isEmpty() )
- cpp << "using namespace " << nameSpace << ";" << endl << endl;
-
- TQString group;
-
- // private class implementation
- if ( dpointer )
- {
- cpp << "class " << className << "Private" << endl;
- cpp << "{" << endl;
- cpp << " public:" << endl;
- for( e = entries.first(); e; e = entries.next() ) {
- if ( e->group() != group ) {
- group = e->group();
- cpp << endl;
- cpp << " // " << group << endl;
- }
- cpp << " " << cppType(e->type()) << " " << varName(e->name());
- if (!e->param().isEmpty())
- {
- cpp << TQString("[%1]").arg(e->paramMax()+1);
- }
- cpp << ";" << endl;
- }
- cpp << endl << " // items" << endl;
- for( e = entries.first(); e; e = entries.next() ) {
- cpp << " TDEConfigSkeleton::Item" << itemType( e->type() ) << " *" << itemVar( e );
- if (!e->param().isEmpty() ) cpp << TQString("[%1]").arg( e->paramMax()+1 );
- cpp << ";" << endl;
- }
-
- cpp << "};" << endl << endl;
- }
-
- // Singleton implementation
- if ( singleton ) {
- cpp << className << " *" << className << "::mSelf = 0;" << endl;
- cpp << "static KStaticDeleter<" << className << "> static" << className << "Deleter;" << endl << endl;
-
- cpp << className << " *" << className << "::self()" << endl;
- cpp << "{" << endl;
- if ( cfgFileNameArg ) {
- cpp << " if (!mSelf)" << endl;
- cpp << " kdFatal() << \"you need to call " << className << "::instance before using\" << endl;" << endl;
- } else {
- cpp << " if ( !mSelf ) {" << endl;
- cpp << " static" << className << "Deleter.setObject( mSelf, new " << className << "() );" << endl;
- cpp << " mSelf->readConfig();" << endl;
- cpp << " }" << endl << endl;
- }
- cpp << " return mSelf;" << endl;
- cpp << "}" << endl << endl;
-
- if ( cfgFileNameArg ) {
- cpp << "void " << className << "::instance(const char *cfgfilename)" << endl;
- cpp << "{" << endl;
- cpp << " if (mSelf) {" << endl;
- cpp << " kdError() << \"" << className << "::instance called after the first use - ignoring\" << endl;" << endl;
- cpp << " return;" << endl;
- cpp << " }" << endl;
- cpp << " static" << className << "Deleter.setObject( mSelf, new " << className << "(cfgfilename) );" << endl;
- cpp << " mSelf->readConfig();" << endl;
- cpp << "}" << endl << endl;
- }
- }
-
- if ( !cppPreamble.isEmpty() )
- cpp << cppPreamble << endl;
-
- // Constructor
- cpp << className << "::" << className << "( ";
- if ( cfgFileNameArg ) {
- if ( !singleton )
- cpp << " KSharedConfig::Ptr config";
- else
- cpp << " const char *config";
- cpp << (parameters.isEmpty() ? " " : ", ");
- }
-
- for (TQValueList<Param>::ConstIterator it = parameters.begin();
- it != parameters.end(); ++it)
- {
- if (it != parameters.begin())
- cpp << ",";
- cpp << " " << param((*it).type) << " " << (*it).name;
- }
- cpp << " )" << endl;
-
- cpp << " : " << inherits << "(";
- if ( !cfgFileName.isEmpty() ) cpp << " TQString::fromLatin1( \"" << cfgFileName << "\" ";
- if ( cfgFileNameArg ) cpp << " config ";
- if ( !cfgFileName.isEmpty() ) cpp << ") ";
- cpp << ")" << endl;
-
- // Store parameters
- for (TQValueList<Param>::ConstIterator it = parameters.begin();
- it != parameters.end(); ++it)
- {
- cpp << " , mParam" << (*it).name << "(" << (*it).name << ")" << endl;
- }
-
- cpp << "{" << endl;
-
- if (dpointer)
- cpp << " d = new " + className + "Private;" << endl;
- // Needed in case the singleton class is used as baseclass for
- // another singleton.
- if ( singleton )
- cpp << " mSelf = this;" << endl;
-
- group = TQString();
- for( e = entries.first(); e; e = entries.next() ) {
- if ( e->group() != group ) {
- if ( !group.isEmpty() ) cpp << endl;
- group = e->group();
- cpp << " setCurrentGroup( " << paramString(group, parameters) << " );" << endl << endl;
- }
-
- TQString key = paramString(e->key(), parameters);
- if ( !e->code().isEmpty())
- {
- cpp << e->code() << endl;
- }
- if ( e->type() == "Enum" ) {
- cpp << " TQValueList<TDEConfigSkeleton::ItemEnum::Choice> values"
- << e->name() << ";" << endl;
- TQValueList<CfgEntry::Choice> choices = e->choices();
- TQValueList<CfgEntry::Choice>::ConstIterator it;
- for( it = choices.begin(); it != choices.end(); ++it ) {
- cpp << " {" << endl;
- cpp << " TDEConfigSkeleton::ItemEnum::Choice choice;" << endl;
- cpp << " choice.name = TQString::fromLatin1( \"" << (*it).name << "\" );" << endl;
- if ( setUserTexts ) {
- if ( !(*it).label.isEmpty() )
- cpp << " choice.label = i18n(" << quoteString((*it).label) << ");" << endl;
- if ( !(*it).whatsThis.isEmpty() )
- cpp << " choice.whatsThis = i18n(" << quoteString((*it).whatsThis) << ");" << endl;
- }
- cpp << " values" << e->name() << ".append( choice );" << endl;
- cpp << " }" << endl;
- }
- }
-
- if (!dpointer)
- cpp << itemDeclaration(e);
-
- if (e->param().isEmpty())
- {
- // Normal case
- cpp << " " << itemPath(e) << " = "
- << newItem( e->type(), e->name(), key, e->defaultValue() ) << endl;
-
- if ( !e->minValue().isEmpty() )
- cpp << " " << itemPath(e) << "->setMinValue(" << e->minValue() << ");" << endl;
- if ( !e->maxValue().isEmpty() )
- cpp << " " << itemPath(e) << "->setMaxValue(" << e->maxValue() << ");" << endl;
-
- if ( setUserTexts )
- cpp << userTextsFunctions( e );
-
- cpp << " addItem( " << itemPath(e);
- TQString quotedName = e->name();
- addQuotes( quotedName );
- if ( quotedName != key ) cpp << ", TQString::fromLatin1( \"" << e->name() << "\" )";
- cpp << " );" << endl;
- }
- else
- {
- // Indexed
- for(int i = 0; i <= e->paramMax(); i++)
- {
- TQString defaultStr;
- TQString itemVarStr(itemPath(e)+TQString("[%1]").arg(i));
-
- if ( !e->paramDefaultValue(i).isEmpty() )
- defaultStr = e->paramDefaultValue(i);
- else if ( !e->defaultValue().isEmpty() )
- defaultStr = paramString(e->defaultValue(), e, i);
- else
- defaultStr = defaultValue( e->type() );
-
- cpp << " " << itemVarStr << " = "
- << newItem( e->type(), e->name(), paramString(key, e, i), defaultStr, TQString("[%1]").arg(i) )
- << endl;
-
- if ( setUserTexts )
- cpp << userTextsFunctions( e, itemVarStr, e->paramName() );
-
- // Make mutators for enum parameters work by adding them with $(..) replaced by the
- // param name. The check for isImmutable in the set* functions doesn't have the param
- // name available, just the corresponding enum value (int), so we need to store the
- // param names in a separate static list!.
- cpp << " addItem( " << itemVarStr << ", TQString::fromLatin1( \"";
- if ( e->paramType()=="Enum" )
- cpp << e->paramName().replace( "$("+e->param()+")", "%1").arg(e->paramValues()[i] );
- else
- cpp << e->paramName().replace( "$("+e->param()+")", "%1").arg(i);
- cpp << "\" ) );" << endl;
- }
- }
- }
-
- cpp << "}" << endl << endl;
-
- if (dpointer)
- {
- // setters and getters go in Cpp if in dpointer mode
- for( e = entries.first(); e; e = entries.next() )
- {
- TQString n = e->name();
- TQString t = e->type();
-
- // Manipulator
- if (allMutators || mutators.contains(n))
- {
- cpp << "void " << setFunction(n, className) << "( ";
- if (!e->param().isEmpty())
- cpp << cppType(e->paramType()) << " i, ";
- cpp << param( t ) << " v )" << endl;
- // function body inline only if not using dpointer
- // for BC mode
- cpp << "{" << endl;
- cpp << indent(memberMutatorBody(e), 6);
- cpp << "}" << endl << endl;
- }
-
- // Accessor
- cpp << cppType(t) << " " << getFunction(n, className) << "(";
- if (!e->param().isEmpty())
- cpp << " " << cppType(e->paramType()) <<" i ";
- cpp << ")" << Const << endl;
- // function body inline only if not using dpointer
- // for BC mode
- cpp << "{" << endl;
- cpp << indent(memberAccessorBody(e), 2);
- cpp << "}" << endl << endl;
-
- // Item accessor
- if ( itemAccessors )
- {
- cpp << endl;
- cpp << "TDEConfigSkeleton::Item" << itemType( e->type() ) << " *"
- << getFunction( n, className ) << "Item(";
- if (!e->param().isEmpty()) {
- cpp << " " << cppType(e->paramType()) << " i ";
- }
- cpp << ")" << endl;
- cpp << "{" << endl;
- cpp << indent(itemAccessorBody(e), 2);
- cpp << "}" << endl;
- }
-
- cpp << endl;
- }
- }
-
- // Destructor
- cpp << className << "::~" << className << "()" << endl;
- cpp << "{" << endl;
- if ( singleton ) {
- if ( dpointer )
- cpp << " delete d;" << endl;
- cpp << " if ( mSelf == this )" << endl;
- cpp << " static" << className << "Deleter.setObject( mSelf, 0, false );" << endl;
- }
- cpp << "}" << endl << endl;
-
- implementation.close();
-}
diff --git a/tdecore/kconfig_compiler/tests/Makefile.am b/tdecore/kconfig_compiler/tests/Makefile.am
deleted file mode 100644
index 953d1c6b4..000000000
--- a/tdecore/kconfig_compiler/tests/Makefile.am
+++ /dev/null
@@ -1,134 +0,0 @@
-AM_CPPFLAGS = -I$(top_srcdir)/tdecore -I$(top_srcdir)/tdeunittest $(all_includes) -DQT_NO_CAST_ASCII -DSRCDIR=\"$(srcdir)\"
-
-check_PROGRAMS = test1 test2 test3 test4 test5 test6 test7 test8 test9 test_dpointer
-
-CLEANFILES = test1.cpp test1.h \
- test2.cpp test2.h \
- test3.cpp test3.h \
- test4.cpp test4.h \
- test5.cpp test5.h \
- test6.cpp test6.h \
- test7.cpp test7.h \
- test8a.cpp test8a.h test8b.cpp test8b.h \
- test9.cpp test9.h \
- test_dpointer.cpp test_dpointer.h \
- md5sums
-
-test1_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test1_LDADD = $(LIB_TDECORE)
-test1_SOURCES = test1main.cpp test1.cpp
-
-test2_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test2_LDADD = $(LIB_TDECORE)
-test2_SOURCES = test2main.cpp test2.cpp
-
-test3_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test3_LDADD = $(LIB_TDECORE)
-test3_SOURCES = test3main.cpp test3.cpp
-
-test4_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test4_LDADD = $(LIB_TDECORE)
-test4_SOURCES = test4main.cpp test4.cpp
-
-test5_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test5_LDADD = $(LIB_TDECORE)
-test5_SOURCES = test5main.cpp test5.cpp
-
-test6_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test6_LDADD = $(LIB_TDECORE)
-test6_SOURCES = test6main.cpp test6.cpp
-
-test7_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test7_LDADD = $(LIB_TDECORE)
-test7_SOURCES = test7main.cpp test7.cpp
-
-test8_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test8_LDADD = $(LIB_TDECORE)
-test8_SOURCES = test8main.cpp test8a.cpp test8b.cpp
-
-test9_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test9_LDADD = $(LIB_TDECORE)
-test9_SOURCES = test9main.cpp test9.cpp
-
-test_dpointer_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
-test_dpointer_LDADD = $(LIB_TDECORE)
-test_dpointer_SOURCES = test_dpointer_main.cpp test_dpointer.cpp
-
-check_LTLIBRARIES = tdeunittest_kconfigcompiler_test.la
-
-tdeunittest_kconfigcompiler_test_la_SOURCES = kconfigcompiler_test.cpp
-tdeunittest_kconfigcompiler_test_la_LIBADD = \
- $(top_builddir)/tdeunittest/libtdeunittest.la
-tdeunittest_kconfigcompiler_test_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN) \
- $(all_libraries)
-
-
-test1main.o test1.o: test1.h
-# avoid running the below command in parallel
-test1.cpp: test1.h
-test1.cpp test1.h: $(srcdir)/test1.kcfg ../kconfig_compiler $(srcdir)/test1.kcfgc
- ../kconfig_compiler $(srcdir)/test1.kcfg $(srcdir)/test1.kcfgc
-
-test2main.o test2.o: test2.h
-# avoid running the below command in parallel
-test2.cpp: test2.h
-test2.cpp test2.h: $(srcdir)/test2.kcfg ../kconfig_compiler $(srcdir)/test2.kcfgc
- ../kconfig_compiler $(srcdir)/test2.kcfg $(srcdir)/test2.kcfgc
-
-test3main.o test3.o: test3.h
-# avoid running the below command in parallel
-test3.cpp: test3.h
-test3.cpp test3.h: $(srcdir)/test3.kcfg ../kconfig_compiler $(srcdir)/test3.kcfgc
- ../kconfig_compiler $(srcdir)/test3.kcfg $(srcdir)/test3.kcfgc
-
-test4main.o test4.o: test4.h
-# avoid running the below command in parallel
-test4.cpp: test4.h
-test4.cpp test4.h: $(srcdir)/test4.kcfg ../kconfig_compiler $(srcdir)/test4.kcfgc
- ../kconfig_compiler $(srcdir)/test4.kcfg $(srcdir)/test4.kcfgc
-
-test5main.o test5.o: test5.h
-# avoid running the below command in parallel
-test5.cpp: test5.h
-test5.cpp test5.h: $(srcdir)/test5.kcfg ../kconfig_compiler $(srcdir)/test5.kcfgc
- ../kconfig_compiler $(srcdir)/test5.kcfg $(srcdir)/test5.kcfgc
-
-test6main.o test6.o: test6.h
-# avoid running the below command in parallel
-test6.cpp: test6.h
-test6.cpp test6.h: $(srcdir)/test6.kcfg ../kconfig_compiler $(srcdir)/test6.kcfgc
- ../kconfig_compiler $(srcdir)/test6.kcfg $(srcdir)/test6.kcfgc
-
-test7main.o test7.o: test7.h
-# avoid running the below command in parallel
-test7.cpp: test7.h
-test7.cpp test7.h: $(srcdir)/test7.kcfg ../kconfig_compiler $(srcdir)/test7.kcfgc
- ../kconfig_compiler $(srcdir)/test7.kcfg $(srcdir)/test7.kcfgc
-
-test8main.o test8a.o test8b.o: test8a.h test8b.h
-# avoid running the below command in parallel
-test8a.cpp: test8a.h
-test8a.cpp test8a.h: $(srcdir)/test8a.kcfg ../kconfig_compiler $(srcdir)/test8a.kcfgc
- ../kconfig_compiler $(srcdir)/test8a.kcfg $(srcdir)/test8a.kcfgc
-test8b.cpp: test8b.h
-test8b.cpp test8b.h: $(srcdir)/test8b.kcfg ../kconfig_compiler $(srcdir)/test8b.kcfgc
- ../kconfig_compiler $(srcdir)/test8b.kcfg $(srcdir)/test8b.kcfgc
-
-test9main.o test9.o: test9.h
-# avoid running the below command in parallel
-test9.cpp: test9.h
-test9.cpp test9.h: $(srcdir)/test9.kcfg ../kconfig_compiler $(srcdir)/test9.kcfgc
- ../kconfig_compiler $(srcdir)/test9.kcfg $(srcdir)/test9.kcfgc
-
-test_dpointer_main.o test_dpointer.o: test_dpointer.h
-# avoid running the below command in parallel
-test_dpointer.cpp: test_dpointer.h
-test_dpointer.cpp test_dpointer.h: $(srcdir)/test_dpointer.kcfg ../kconfig_compiler $(srcdir)/test_dpointer.kcfgc
- ../kconfig_compiler $(srcdir)/test_dpointer.kcfg $(srcdir)/test_dpointer.kcfgc
-
-md5sums:
- $(MD5SUM) $(srcdir)/test*.ref | sed -e "s,$(srcdir)/,,; s,\.ref$$,," > md5sums
-
-md5check: test1.cpp test2.cpp test3.cpp test4.cpp test5.cpp test6.cpp test7.cpp test8a.cpp test8b.cpp test9.cpp md5sums
- $(MD5SUM) -c md5sums
-
diff --git a/tdecore/kconfig_compiler/tests/kconfigcompiler_test.cpp b/tdecore/kconfig_compiler/tests/kconfigcompiler_test.cpp
deleted file mode 100644
index c9f2f8471..000000000
--- a/tdecore/kconfig_compiler/tests/kconfigcompiler_test.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- Tests for TDEConfig Compiler
-
- Copyright (c) 2005 by Duncan Mac-Vicar <duncan@kde.org>
-
- *************************************************************************
- * *
- * This library is free software; you can redistribute it and/or *
- * modify it under the terms of the GNU Lesser General Public *
- * License as published by the Free Software Foundation; either *
- * version 2 of the License, or (at your option) any later version. *
- * *
- *************************************************************************
-*/
-
-#include <tqfile.h>
-#include <tqstring.h>
-#include <kdebug.h>
-#include <tdeunittest/module.h>
-#include "kconfigcompiler_test.h"
-
-using namespace KUnitTest;
-
-KUNITTEST_MODULE( tdeunittest_kconfigcompiler_test, "TDEConfigXT")
-KUNITTEST_MODULE_REGISTER_TESTER( TDEConfigCompiler_Test )
-
-typedef const char * CompilerTestSet[];
-
-static CompilerTestSet testCases =
-{
- "test1.cpp", "test1.h",
- "test2.cpp", "test2.h",
- "test3.cpp", "test3.h",
- "test4.cpp", "test4.h",
- "test5.cpp", "test5.h",
- "test6.cpp", "test6.h",
- "test7.cpp", "test7.h",
- "test8a.cpp", "test8a.h",
- "test8b.cpp", "test8b.h",
- "test9.h", "test9.cpp",
- "test_dpointer.cpp", "test_dpointer.h",
- NULL
-};
-
-static CompilerTestSet willFailCases =
-{
- // where is that TQDir comming from?
- //"test9.cpp", NULL
- NULL
-};
-
-
-void TDEConfigCompiler_Test::allTests()
-{
- testExpectedOutput();
-}
-
-void TDEConfigCompiler_Test::testExpectedOutput()
-{
- uint i = 0;
- // Known to pass test cases
- while (testCases[ i ])
- {
- performCompare(TQString::fromLatin1(testCases[ i ]));
- ++i;
- }
-
- // broken test cases
- i= 0;
- while (willFailCases[ i ])
- {
- performCompare(TQString::fromLatin1(willFailCases[ i ]), true);
- ++i;
- }
-}
-
-void TDEConfigCompiler_Test::performCompare(const TQString &fileName, bool fail)
-{
- TQFile file(fileName);
- TQFile fileRef(TQString::fromLatin1(SRCDIR) + TQString::fromLatin1("/") + fileName + TQString::fromLatin1(".ref"));
-
- if ( file.open(IO_ReadOnly) && fileRef.open(IO_ReadOnly) )
- {
- TQString content = file.readAll();
- TQString contentRef = fileRef.readAll();
-
- if (!fail)
- CHECK( content, contentRef);
- else
- XFAIL( content, contentRef);
- }
- else
- {
- SKIP("Can't open file for comparision");
- }
-}
diff --git a/tdecore/kconfig_compiler/tests/myprefs.h b/tdecore/kconfig_compiler/tests/myprefs.h
deleted file mode 100644
index 020dc6bfa..000000000
--- a/tdecore/kconfig_compiler/tests/myprefs.h
+++ /dev/null
@@ -1,7 +0,0 @@
-#include <kconfigskeleton.h>
-
-class MyPrefs : public TDEConfigSkeleton
-{
- public:
- MyPrefs( const TQString &a ) : TDEConfigSkeleton( a ) {}
-};
diff --git a/tdecore/kconfig_compiler/tests/test1.cpp.ref b/tdecore/kconfig_compiler/tests/test1.cpp.ref
deleted file mode 100644
index d0b6b76f1..000000000
--- a/tdecore/kconfig_compiler/tests/test1.cpp.ref
+++ /dev/null
@@ -1,72 +0,0 @@
-// This file is generated by kconfig_compiler from test1.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test1.h"
-
-Test1::Test1( const TQString & transport, const TQString & folder )
- : TDEConfigSkeleton( TQString::fromLatin1( "examplerc" ) )
- , mParamtransport(transport)
- , mParamfolder(folder)
-{
- setCurrentGroup( TQString::fromLatin1( "General-%1" ).arg( mParamfolder ) );
-
- TDEConfigSkeleton::ItemBool *itemOneOption;
- itemOneOption = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "OneOption" ), mOneOption, true );
- addItem( itemOneOption, TQString::fromLatin1( "OneOption" ) );
- TDEConfigSkeleton::ItemInt *itemAnotherOption;
- itemAnotherOption = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Another Option" ), mAnotherOption, 5 );
- addItem( itemAnotherOption, TQString::fromLatin1( "AnotherOption" ) );
- TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesListOption;
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "One" );
- valuesListOption.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "Two" );
- valuesListOption.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "Three" );
- valuesListOption.append( choice );
- }
- TDEConfigSkeleton::ItemEnum *itemListOption;
- itemListOption = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "ListOption" ), mListOption, valuesListOption, EnumListOption::One );
- addItem( itemListOption, TQString::fromLatin1( "ListOption" ) );
-
- setCurrentGroup( TQString::fromLatin1( "MyOptions" ) );
-
- TDEConfigSkeleton::ItemString *itemMyString;
- itemMyString = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "MyString" ), mMyString, TQString::fromLatin1( "Default String" ) );
- addItem( itemMyString, TQString::fromLatin1( "MyString" ) );
- TDEConfigSkeleton::ItemPath *itemMyPath;
- itemMyPath = new TDEConfigSkeleton::ItemPath( currentGroup(), TQString::fromLatin1( "MyPath" ), mMyPath, TQDir::homeDirPath()+TQString::fromLatin1(".hidden_file") );
- addItem( itemMyPath, TQString::fromLatin1( "MyPath" ) );
- TDEConfigSkeleton::ItemInt *itemAnotherOption2;
- itemAnotherOption2 = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Another Option" ), mAnotherOption2, 10 );
- addItem( itemAnotherOption2, TQString::fromLatin1( "AnotherOption2" ) );
- TQStringList defaultMyStringList;
- defaultMyStringList.append( TQString::fromUtf8( "up" ) );
- defaultMyStringList.append( TQString::fromUtf8( "down" ) );
-
- TDEConfigSkeleton::ItemStringList *itemMyStringList;
- itemMyStringList = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "MyStringList" ), mMyStringList, defaultMyStringList );
- addItem( itemMyStringList, TQString::fromLatin1( "MyStringList" ) );
- TQStringList defaultMyStringListHidden;
- defaultMyStringListHidden.append( TQString::fromUtf8( "up" ) );
- defaultMyStringListHidden.append( TQString::fromUtf8( "down" ) );
-
- TDEConfigSkeleton::ItemStringList *itemMyStringListHidden;
- itemMyStringListHidden = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "MyStringListHidden" ), mMyStringListHidden, defaultMyStringListHidden );
- addItem( itemMyStringListHidden, TQString::fromLatin1( "MyStringListHidden" ) );
- TDEConfigSkeleton::ItemInt *itemMyNumber;
- itemMyNumber = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "List-%1-%2" ).arg( mParamtransport ).arg( mParamfolder ), mMyNumber, 1 );
- addItem( itemMyNumber, TQString::fromLatin1( "MyNumber" ) );
-}
-
-Test1::~Test1()
-{
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test1.h.ref b/tdecore/kconfig_compiler/tests/test1.h.ref
deleted file mode 100644
index 584dcb7ff..000000000
--- a/tdecore/kconfig_compiler/tests/test1.h.ref
+++ /dev/null
@@ -1,196 +0,0 @@
-// This file is generated by kconfig_compiler from test1.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST1_H
-#define TEST1_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-#include <tqdir.h>
-class Test1 : public TDEConfigSkeleton
-{
- public:
- class EnumListOption
- {
- public:
- enum type { One, Two, Three, COUNT };
- };
-
- Test1( const TQString & transport, const TQString & folder );
- ~Test1();
-
- /**
- Set One option
- */
- void setOneOption( bool v )
- {
- if (!isImmutable( TQString::fromLatin1( "OneOption" ) ))
- mOneOption = v;
- }
-
- /**
- Get One option
- */
- bool oneOption() const
- {
- return mOneOption;
- }
-
- /**
- Set Another option
- */
- void setAnotherOption( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "AnotherOption" ) ))
- mAnotherOption = v;
- }
-
- /**
- Get Another option
- */
- int anotherOption() const
- {
- return mAnotherOption;
- }
-
- /**
- Set This is some funky option
- */
- void setListOption( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "ListOption" ) ))
- mListOption = v;
- }
-
- /**
- Get This is some funky option
- */
- int listOption() const
- {
- return mListOption;
- }
-
- /**
- Set This is a string
- */
- void setMyString( const TQString & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyString" ) ))
- mMyString = v;
- }
-
- /**
- Get This is a string
- */
- TQString myString() const
- {
- return mMyString;
- }
-
- /**
- Set This is a path
- */
- void setMyPath( const TQString & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyPath" ) ))
- mMyPath = v;
- }
-
- /**
- Get This is a path
- */
- TQString myPath() const
- {
- return mMyPath;
- }
-
- /**
- Set Another option
- */
- void setAnotherOption2( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "AnotherOption2" ) ))
- mAnotherOption2 = v;
- }
-
- /**
- Get Another option
- */
- int anotherOption2() const
- {
- return mAnotherOption2;
- }
-
- /**
- Set MyStringList
- */
- void setMyStringList( const TQStringList & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyStringList" ) ))
- mMyStringList = v;
- }
-
- /**
- Get MyStringList
- */
- TQStringList myStringList() const
- {
- return mMyStringList;
- }
-
- /**
- Set MyStringListHidden
- */
- void setMyStringListHidden( const TQStringList & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyStringListHidden" ) ))
- mMyStringListHidden = v;
- }
-
- /**
- Get MyStringListHidden
- */
- TQStringList myStringListHidden() const
- {
- return mMyStringListHidden;
- }
-
- /**
- Set List Number
- */
- void setMyNumber( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyNumber" ) ))
- mMyNumber = v;
- }
-
- /**
- Get List Number
- */
- int myNumber() const
- {
- return mMyNumber;
- }
-
- protected:
- TQString mParamtransport;
- TQString mParamfolder;
-
- // General-$(folder)
- bool mOneOption;
- int mAnotherOption;
- int mListOption;
-
- // MyOptions
- TQString mMyString;
- TQString mMyPath;
- int mAnotherOption2;
- TQStringList mMyStringList;
- TQStringList mMyStringListHidden;
- int mMyNumber;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test1.kcfgc b/tdecore/kconfig_compiler/tests/test1.kcfgc
deleted file mode 100644
index ecab7b851..000000000
--- a/tdecore/kconfig_compiler/tests/test1.kcfgc
+++ /dev/null
@@ -1,18 +0,0 @@
-# Code generation options for kconfig_compiler
-ClassName=Test1
-#
-# Singleton=false
-#
-# Inherits=TDEConfigSkeleton
-#
-# IncludeFiles=libtdepim/kpimprefs.h
-#
-# MemberVariables=public
-#
-### The following line includes the file exampleprefs_base_addon.h
-### It can be used to add extra functions and variables to the
-### class.
-# CustomAdditions=true
-#
-### Provide setFooBar(int) style functions
-Mutators=true
diff --git a/tdecore/kconfig_compiler/tests/test2.cpp.ref b/tdecore/kconfig_compiler/tests/test2.cpp.ref
deleted file mode 100644
index fe7b8af80..000000000
--- a/tdecore/kconfig_compiler/tests/test2.cpp.ref
+++ /dev/null
@@ -1,98 +0,0 @@
-// This file is generated by kconfig_compiler from test2.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test2.h"
-
-#include <klocale.h>
-
-Test2::Test2( )
- : MyPrefs( TQString::fromLatin1( "korganizerrc" ) )
-{
- setCurrentGroup( TQString::fromLatin1( "General" ) );
-
- mAutoSaveItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Auto Save" ), mAutoSave, false );
- mAutoSaveItem->setLabel( i18n("Enable automatic saving of calendar") );
- mAutoSaveItem->setWhatsThis( i18n("WhatsThis text for AutoSave option") );
- addItem( mAutoSaveItem, TQString::fromLatin1( "AutoSave" ) );
- mAutoSaveIntervalItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Auto Save Interval" ), mAutoSaveInterval, 10 );
- mAutoSaveIntervalItem->setLabel( i18n("Auto Save Interval") );
- addItem( mAutoSaveIntervalItem, TQString::fromLatin1( "AutoSaveInterval" ) );
- mConfirmItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Confirm Deletes" ), mConfirm, true );
- mConfirmItem->setLabel( i18n("Confirm deletes") );
- addItem( mConfirmItem, TQString::fromLatin1( "Confirm" ) );
- mArchiveFileItem = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "Archive File" ), mArchiveFile );
- mArchiveFileItem->setLabel( i18n("Archive File") );
- addItem( mArchiveFileItem, TQString::fromLatin1( "ArchiveFile" ) );
- TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesDestination;
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "standardDestination" );
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "askDestination" );
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "argl1" );
- choice.label = i18n("Argl1 Label");
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "argl2" );
- choice.whatsThis = i18n("Argl2 Whatsthis");
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "argl3" );
- choice.label = i18n("Argl3 Label");
- choice.whatsThis = i18n("Argl3 Whatsthis");
- valuesDestination.append( choice );
- }
- mDestinationItem = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "Destination" ), mDestination, valuesDestination, standardDestination );
- mDestinationItem->setLabel( i18n("New Events/Todos Should") );
- addItem( mDestinationItem, TQString::fromLatin1( "Destination" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Views" ) );
-
- mHourSizeItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Hour Size" ), mHourSize, 10 );
- mHourSizeItem->setLabel( i18n("Hour Size") );
- addItem( mHourSizeItem, TQString::fromLatin1( "HourSize" ) );
- mSelectionStartsEditorItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "SelectionStartsEditor" ), mSelectionStartsEditor, false );
- mSelectionStartsEditorItem->setLabel( i18n("Time range selection in agenda view starts event editor") );
- addItem( mSelectionStartsEditorItem, TQString::fromLatin1( "SelectionStartsEditor" ) );
-
- setCurrentGroup( TQString::fromLatin1( "KOrganizer Plugins" ) );
-
- TQStringList defaultSelectedPlugins;
- defaultSelectedPlugins.append( TQString::fromUtf8( "holidays" ) );
- defaultSelectedPlugins.append( TQString::fromUtf8( "webexport" ) );
-
- mSelectedPluginsItem = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "SelectedPlugins" ), mSelectedPlugins, defaultSelectedPlugins );
- mSelectedPluginsItem->setLabel( i18n("SelectedPlugins") );
- addItem( mSelectedPluginsItem, TQString::fromLatin1( "SelectedPlugins" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Colors" ) );
-
- mHighlightColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Highlight Color" ), mHighlightColor, TQColor( 100, 100, 255 ) );
- mHighlightColorItem->setLabel( i18n("Highlight color") );
- addItem( mHighlightColorItem, TQString::fromLatin1( "HighlightColor" ) );
- mAgendaBgColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Agenda Background Color" ), mAgendaBgColor, TQColor( 255, 255, 255 ) );
- mAgendaBgColorItem->setLabel( i18n("Agenda view background color") );
- addItem( mAgendaBgColorItem, TQString::fromLatin1( "AgendaBgColor" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Fonts" ) );
-
- mTimeBarFontItem = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "TimeBar Font" ), mTimeBarFont );
- mTimeBarFontItem->setLabel( i18n("Time bar") );
- addItem( mTimeBarFontItem, TQString::fromLatin1( "TimeBarFont" ) );
-}
-
-Test2::~Test2()
-{
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test2.h.ref b/tdecore/kconfig_compiler/tests/test2.h.ref
deleted file mode 100644
index 6c0a74d66..000000000
--- a/tdecore/kconfig_compiler/tests/test2.h.ref
+++ /dev/null
@@ -1,333 +0,0 @@
-// This file is generated by kconfig_compiler from test2.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST2_H
-#define TEST2_H
-
-#include <myprefs.h>
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class Test2 : public MyPrefs
-{
- public:
- enum { standardDestination, askDestination, argl1, argl2, argl3 };
-
- Test2( );
- ~Test2();
-
- /**
- Set Enable automatic saving of calendar
- */
- void setAutoSave( bool v )
- {
- if (!isImmutable( TQString::fromLatin1( "AutoSave" ) ))
- mAutoSave = v;
- }
-
- /**
- Get Enable automatic saving of calendar
- */
- bool autoSave() const
- {
- return mAutoSave;
- }
-
- /**
- Get Item object corresponding to AutoSave()
- */
- ItemBool *autoSaveItem()
- {
- return mAutoSaveItem;
- }
-
- /**
- Set Auto Save Interval
- */
- void setAutoSaveInterval( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "AutoSaveInterval" ) ))
- mAutoSaveInterval = v;
- }
-
- /**
- Get Auto Save Interval
- */
- int autoSaveInterval() const
- {
- return mAutoSaveInterval;
- }
-
- /**
- Get Item object corresponding to AutoSaveInterval()
- */
- ItemInt *autoSaveIntervalItem()
- {
- return mAutoSaveIntervalItem;
- }
-
- /**
- Set Confirm deletes
- */
- void setConfirm( bool v )
- {
- if (!isImmutable( TQString::fromLatin1( "Confirm" ) ))
- mConfirm = v;
- }
-
- /**
- Get Confirm deletes
- */
- bool confirm() const
- {
- return mConfirm;
- }
-
- /**
- Get Item object corresponding to Confirm()
- */
- ItemBool *confirmItem()
- {
- return mConfirmItem;
- }
-
- /**
- Set Archive File
- */
- void setArchiveFile( const TQString & v )
- {
- if (!isImmutable( TQString::fromLatin1( "ArchiveFile" ) ))
- mArchiveFile = v;
- }
-
- /**
- Get Archive File
- */
- TQString archiveFile() const
- {
- return mArchiveFile;
- }
-
- /**
- Get Item object corresponding to ArchiveFile()
- */
- ItemString *archiveFileItem()
- {
- return mArchiveFileItem;
- }
-
- /**
- Set New Events/Todos Should
- */
- void setDestination( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "Destination" ) ))
- mDestination = v;
- }
-
- /**
- Get New Events/Todos Should
- */
- int destination() const
- {
- return mDestination;
- }
-
- /**
- Get Item object corresponding to Destination()
- */
- ItemEnum *destinationItem()
- {
- return mDestinationItem;
- }
-
- /**
- Set Hour Size
- */
- void setHourSize( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "HourSize" ) ))
- mHourSize = v;
- }
-
- /**
- Get Hour Size
- */
- int hourSize() const
- {
- return mHourSize;
- }
-
- /**
- Get Item object corresponding to HourSize()
- */
- ItemInt *hourSizeItem()
- {
- return mHourSizeItem;
- }
-
- /**
- Set Time range selection in agenda view starts event editor
- */
- void setSelectionStartsEditor( bool v )
- {
- if (!isImmutable( TQString::fromLatin1( "SelectionStartsEditor" ) ))
- mSelectionStartsEditor = v;
- }
-
- /**
- Get Time range selection in agenda view starts event editor
- */
- bool selectionStartsEditor() const
- {
- return mSelectionStartsEditor;
- }
-
- /**
- Get Item object corresponding to SelectionStartsEditor()
- */
- ItemBool *selectionStartsEditorItem()
- {
- return mSelectionStartsEditorItem;
- }
-
- /**
- Set SelectedPlugins
- */
- void setSelectedPlugins( const TQStringList & v )
- {
- if (!isImmutable( TQString::fromLatin1( "SelectedPlugins" ) ))
- mSelectedPlugins = v;
- }
-
- /**
- Get SelectedPlugins
- */
- TQStringList selectedPlugins() const
- {
- return mSelectedPlugins;
- }
-
- /**
- Get Item object corresponding to SelectedPlugins()
- */
- ItemStringList *selectedPluginsItem()
- {
- return mSelectedPluginsItem;
- }
-
- /**
- Set Highlight color
- */
- void setHighlightColor( const TQColor & v )
- {
- if (!isImmutable( TQString::fromLatin1( "HighlightColor" ) ))
- mHighlightColor = v;
- }
-
- /**
- Get Highlight color
- */
- TQColor highlightColor() const
- {
- return mHighlightColor;
- }
-
- /**
- Get Item object corresponding to HighlightColor()
- */
- ItemColor *highlightColorItem()
- {
- return mHighlightColorItem;
- }
-
- /**
- Set Agenda view background color
- */
- void setAgendaBgColor( const TQColor & v )
- {
- if (!isImmutable( TQString::fromLatin1( "AgendaBgColor" ) ))
- mAgendaBgColor = v;
- }
-
- /**
- Get Agenda view background color
- */
- TQColor agendaBgColor() const
- {
- return mAgendaBgColor;
- }
-
- /**
- Get Item object corresponding to AgendaBgColor()
- */
- ItemColor *agendaBgColorItem()
- {
- return mAgendaBgColorItem;
- }
-
- /**
- Set Time bar
- */
- void setTimeBarFont( const TQFont & v )
- {
- if (!isImmutable( TQString::fromLatin1( "TimeBarFont" ) ))
- mTimeBarFont = v;
- }
-
- /**
- Get Time bar
- */
- TQFont timeBarFont() const
- {
- return mTimeBarFont;
- }
-
- /**
- Get Item object corresponding to TimeBarFont()
- */
- ItemFont *timeBarFontItem()
- {
- return mTimeBarFontItem;
- }
-
- protected:
- public:
-
- // General
- bool mAutoSave;
- int mAutoSaveInterval;
- bool mConfirm;
- TQString mArchiveFile;
- int mDestination;
-
- // Views
- int mHourSize;
- bool mSelectionStartsEditor;
-
- // KOrganizer Plugins
- TQStringList mSelectedPlugins;
-
- // Colors
- TQColor mHighlightColor;
- TQColor mAgendaBgColor;
-
- // Fonts
- TQFont mTimeBarFont;
-
- private:
- ItemBool *mAutoSaveItem;
- ItemInt *mAutoSaveIntervalItem;
- ItemBool *mConfirmItem;
- ItemString *mArchiveFileItem;
- ItemEnum *mDestinationItem;
- ItemInt *mHourSizeItem;
- ItemBool *mSelectionStartsEditorItem;
- ItemStringList *mSelectedPluginsItem;
- ItemColor *mHighlightColorItem;
- ItemColor *mAgendaBgColorItem;
- ItemFont *mTimeBarFontItem;
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test2.kcfgc b/tdecore/kconfig_compiler/tests/test2.kcfgc
deleted file mode 100644
index 56620d2f4..000000000
--- a/tdecore/kconfig_compiler/tests/test2.kcfgc
+++ /dev/null
@@ -1,11 +0,0 @@
-# Code generation options for kconfig_compiler
-File=test2.kcfg
-ClassName=Test2
-Singleton=false
-Mutators=true
-Inherits=MyPrefs
-IncludeFiles=myprefs.h
-MemberVariables=public
-GlobalEnums=true
-ItemAccessors=true
-SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test3.cpp.ref b/tdecore/kconfig_compiler/tests/test3.cpp.ref
deleted file mode 100644
index 3bd0eb8c9..000000000
--- a/tdecore/kconfig_compiler/tests/test3.cpp.ref
+++ /dev/null
@@ -1,29 +0,0 @@
-// This file is generated by kconfig_compiler from test3.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test3.h"
-
-using namespace TestNameSpace;
-
-Test3::Test3( )
- : TDEConfigSkeleton( TQString::fromLatin1( "test3rc" ) )
-{
- setCurrentGroup( TQString::fromLatin1( "General" ) );
-
- mAutoSaveItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Auto Save" ), mAutoSave, false );
- addItem( mAutoSaveItem, TQString::fromLatin1( "AutoSave" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Blah" ) );
-
- mBlubbItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Blubb" ), mBlubb, 10 );
- addItem( mBlubbItem, TQString::fromLatin1( "Blubb" ) );
- mBlahBlahItem = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "BlahBlah" ), mBlahBlah, TQString::fromLatin1( "a string" ) );
- addItem( mBlahBlahItem, TQString::fromLatin1( "BlahBlah" ) );
- mMyPasswordItem = new TDEConfigSkeleton::ItemPassword( currentGroup(), TQString::fromLatin1( "MyPassword" ), mMyPassword );
- addItem( mMyPasswordItem, TQString::fromLatin1( "MyPassword" ) );
-}
-
-Test3::~Test3()
-{
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test3.h.ref b/tdecore/kconfig_compiler/tests/test3.h.ref
deleted file mode 100644
index 4c35a138a..000000000
--- a/tdecore/kconfig_compiler/tests/test3.h.ref
+++ /dev/null
@@ -1,138 +0,0 @@
-// This file is generated by kconfig_compiler from test3.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TESTNAMESPACE_TEST3_H
-#define TESTNAMESPACE_TEST3_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-namespace TestNameSpace {
-
-class Test3 : public TDEConfigSkeleton
-{
- public:
-
- Test3( );
- ~Test3();
-
- /**
- Set Enable automatic saving of calendar
- */
- void setAutoSave( bool v )
- {
- if (!isImmutable( TQString::fromLatin1( "AutoSave" ) ))
- mAutoSave = v;
- }
-
- /**
- Get Enable automatic saving of calendar
- */
- bool autoSave() const
- {
- return mAutoSave;
- }
-
- /**
- Get Item object corresponding to AutoSave()
- */
- ItemBool *autoSaveItem()
- {
- return mAutoSaveItem;
- }
-
- /**
- Set Blubb
- */
- void setBlubb( int v )
- {
- if (!isImmutable( TQString::fromLatin1( "Blubb" ) ))
- mBlubb = v;
- }
-
- /**
- Get Blubb
- */
- int blubb() const
- {
- return mBlubb;
- }
-
- /**
- Get Item object corresponding to Blubb()
- */
- ItemInt *blubbItem()
- {
- return mBlubbItem;
- }
-
- /**
- Set BlahBlah
- */
- void setBlahBlah( const TQString & v )
- {
- if (!isImmutable( TQString::fromLatin1( "BlahBlah" ) ))
- mBlahBlah = v;
- }
-
- /**
- Get BlahBlah
- */
- TQString blahBlah() const
- {
- return mBlahBlah;
- }
-
- /**
- Get Item object corresponding to BlahBlah()
- */
- ItemString *blahBlahItem()
- {
- return mBlahBlahItem;
- }
-
- /**
- Set MyPassword
- */
- void setMyPassword( const TQString & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyPassword" ) ))
- mMyPassword = v;
- }
-
- /**
- Get MyPassword
- */
- TQString myPassword() const
- {
- return mMyPassword;
- }
-
- /**
- Get Item object corresponding to MyPassword()
- */
- ItemPassword *myPasswordItem()
- {
- return mMyPasswordItem;
- }
-
- protected:
-
- // General
- bool mAutoSave;
-
- // Blah
- int mBlubb;
- TQString mBlahBlah;
- TQString mMyPassword;
-
- private:
- ItemBool *mAutoSaveItem;
- ItemInt *mBlubbItem;
- ItemString *mBlahBlahItem;
- ItemPassword *mMyPasswordItem;
-};
-
-}
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test3.kcfgc b/tdecore/kconfig_compiler/tests/test3.kcfgc
deleted file mode 100644
index ca2c22057..000000000
--- a/tdecore/kconfig_compiler/tests/test3.kcfgc
+++ /dev/null
@@ -1,12 +0,0 @@
-# Code generation options for kconfig_compiler
-File=test3.kcfg
-NameSpace=TestNameSpace
-ClassName=Test3
-#Singleton=false
-Mutators=true
-#Inherits=MyPrefs
-#IncludeFiles=myprefs.h
-#MemberVariables=public
-GlobalEnums=true
-ItemAccessors=true
-#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test4.cpp.ref b/tdecore/kconfig_compiler/tests/test4.cpp.ref
deleted file mode 100644
index c6b29bec2..000000000
--- a/tdecore/kconfig_compiler/tests/test4.cpp.ref
+++ /dev/null
@@ -1,82 +0,0 @@
-// This file is generated by kconfig_compiler from test4.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test4.h"
-
-#include <kstaticdeleter.h>
-
-Test4 *Test4::mSelf = 0;
-static KStaticDeleter<Test4> staticTest4Deleter;
-
-Test4 *Test4::self()
-{
- if ( !mSelf ) {
- staticTest4Deleter.setObject( mSelf, new Test4() );
- mSelf->readConfig();
- }
-
- return mSelf;
-}
-
-const char* const Test4::EnumButton::enumToString[] = { "right", "mid", "left" };
-
-Test4::Test4( )
- : TDEConfigSkeleton( TQString::fromLatin1( "test4rc" ) )
-{
- mSelf = this;
- setCurrentGroup( TQString::fromLatin1( "Foo" ) );
-
-TQColor defaultColor[4] = { Qt::red, Qt::blue, Qt::green, Qt::black };
- TDEConfigSkeleton::ItemColor *itemColor[4];
- itemColor[0] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #0" ), mColor[0], defaultColor[0] );
- addItem( itemColor[0], TQString::fromLatin1( "Color0" ) );
- itemColor[1] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #1" ), mColor[1], defaultColor[1] );
- addItem( itemColor[1], TQString::fromLatin1( "Color1" ) );
- itemColor[2] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #2" ), mColor[2], defaultColor[2] );
- addItem( itemColor[2], TQString::fromLatin1( "Color2" ) );
- itemColor[3] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #3" ), mColor[3], defaultColor[3] );
- addItem( itemColor[3], TQString::fromLatin1( "Color3" ) );
- TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesMouseAction;
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "Encrypt" );
- valuesMouseAction.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "Decrypt" );
- valuesMouseAction.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "CrashNBurn" );
- valuesMouseAction.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "PumpNDump" );
- valuesMouseAction.append( choice );
- }
- TDEConfigSkeleton::ItemEnum *itemMouseAction[3];
- itemMouseAction[0] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "right_mouse_action" ), mMouseAction[0], valuesMouseAction, EnumMouseAction::Decrypt );
- addItem( itemMouseAction[0], TQString::fromLatin1( "MouseActionright" ) );
- itemMouseAction[1] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "mid_mouse_action" ), mMouseAction[1], valuesMouseAction, EnumMouseAction::Encrypt );
- addItem( itemMouseAction[1], TQString::fromLatin1( "MouseActionmid" ) );
- itemMouseAction[2] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "left_mouse_action" ), mMouseAction[2], valuesMouseAction, EnumMouseAction::PumpNDump );
- addItem( itemMouseAction[2], TQString::fromLatin1( "MouseActionleft" ) );
- TDEConfigSkeleton::ItemString *itemFooBar;
- itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
- addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
- TDEConfigSkeleton::ItemInt *itemAge;
- itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
- itemAge->setMinValue(8);
- itemAge->setMaxValue(88);
- addItem( itemAge, TQString::fromLatin1( "Age" ) );
-}
-
-Test4::~Test4()
-{
- if ( mSelf == this )
- staticTest4Deleter.setObject( mSelf, 0, false );
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test4.h.ref b/tdecore/kconfig_compiler/tests/test4.h.ref
deleted file mode 100644
index 9457413a1..000000000
--- a/tdecore/kconfig_compiler/tests/test4.h.ref
+++ /dev/null
@@ -1,135 +0,0 @@
-// This file is generated by kconfig_compiler from test4.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST4_H
-#define TEST4_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class Test4 : public TDEConfigSkeleton
-{
- public:
- class EnumMouseAction
- {
- public:
- enum type { Encrypt, Decrypt, CrashNBurn, PumpNDump, COUNT };
- };
- class EnumButton
- {
- public:
- enum type { right, mid, left, COUNT };
- static const char* const enumToString[];
- };
-
- static Test4 *self();
- ~Test4();
-
- /**
- Set Block colors.
- */
- static
- void setColor( int i, const TQColor & v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "Color%1" ).arg( i ) ))
- self()->mColor[i] = v;
- }
-
- /**
- Get Block colors.
- */
- static
- TQColor color( int i )
- {
- return self()->mColor[i];
- }
-
- /**
- Set Mouse actions.
- */
- static
- void setMouseAction( int i, int v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "MouseAction%1" ).arg( TQString::fromLatin1( EnumButton::enumToString[i] ) ) ))
- self()->mMouseAction[i] = v;
- }
-
- /**
- Get Mouse actions.
- */
- static
- int mouseAction( int i )
- {
- return self()->mMouseAction[i];
- }
-
- /**
- Set foo bar
- */
- static
- void setFooBar( const TQString & v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "FooBar" ) ))
- self()->mFooBar = v;
- }
-
- /**
- Get foo bar
- */
- static
- TQString fooBar()
- {
- return self()->mFooBar;
- }
-
- /**
- Set Age
- */
- static
- void setAge( int v )
- {
- if (v < 8)
- {
- kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
- v = 8;
- }
-
- if (v > 88)
- {
- kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
- v = 88;
- }
-
- if (!self()->isImmutable( TQString::fromLatin1( "Age" ) ))
- self()->mAge = v;
- }
-
- /**
- Get Age
- */
- static
- int age()
- {
- return self()->mAge;
- }
-
- static
- void writeConfig()
- {
- static_cast<TDEConfigSkeleton*>(self())->writeConfig();
- }
- protected:
- Test4();
- static Test4 *mSelf;
-
-
- // Foo
- TQColor mColor[4];
- int mMouseAction[3];
- TQString mFooBar;
- int mAge;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test4.kcfgc b/tdecore/kconfig_compiler/tests/test4.kcfgc
deleted file mode 100644
index 754706dff..000000000
--- a/tdecore/kconfig_compiler/tests/test4.kcfgc
+++ /dev/null
@@ -1,11 +0,0 @@
-# Code generation options for kconfig_compiler
-File=test4.kcfg
-ClassName=Test4
-Singleton=true
-Mutators=true
-#Inherits=MyPrefs
-#IncludeFiles=myprefs.h
-#MemberVariables=public
-GlobalEnums=false
-ItemAccessors=false
-#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test5.cpp.ref b/tdecore/kconfig_compiler/tests/test5.cpp.ref
deleted file mode 100644
index 9e295bc0e..000000000
--- a/tdecore/kconfig_compiler/tests/test5.cpp.ref
+++ /dev/null
@@ -1,82 +0,0 @@
-// This file is generated by kconfig_compiler from test5.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test5.h"
-
-#include <kstaticdeleter.h>
-
-Test5 *Test5::mSelf = 0;
-static KStaticDeleter<Test5> staticTest5Deleter;
-
-Test5 *Test5::self()
-{
- if ( !mSelf ) {
- staticTest5Deleter.setObject( mSelf, new Test5() );
- mSelf->readConfig();
- }
-
- return mSelf;
-}
-
-const char* const Test5::EnumButtonToString[] = { "right", "mid", "left" };
-
-Test5::Test5( )
- : TDEConfigSkeleton( TQString::fromLatin1( "test4rc" ) )
-{
- mSelf = this;
- setCurrentGroup( TQString::fromLatin1( "Foo" ) );
-
-TQColor defaultColor[4] = { Qt::red, Qt::blue, Qt::green, Qt::black };
- TDEConfigSkeleton::ItemColor *itemColor[4];
- itemColor[0] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #0" ), mColor[0], defaultColor[0] );
- addItem( itemColor[0], TQString::fromLatin1( "Color0" ) );
- itemColor[1] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #1" ), mColor[1], defaultColor[1] );
- addItem( itemColor[1], TQString::fromLatin1( "Color1" ) );
- itemColor[2] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #2" ), mColor[2], defaultColor[2] );
- addItem( itemColor[2], TQString::fromLatin1( "Color2" ) );
- itemColor[3] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #3" ), mColor[3], defaultColor[3] );
- addItem( itemColor[3], TQString::fromLatin1( "Color3" ) );
- TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesMouseAction;
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "Encrypt" );
- valuesMouseAction.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "Decrypt" );
- valuesMouseAction.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "CrashNBurn" );
- valuesMouseAction.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "PumpNDump" );
- valuesMouseAction.append( choice );
- }
- TDEConfigSkeleton::ItemEnum *itemMouseAction[3];
- itemMouseAction[0] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "right_mouse_action" ), mMouseAction[0], valuesMouseAction, Decrypt );
- addItem( itemMouseAction[0], TQString::fromLatin1( "MouseActionright" ) );
- itemMouseAction[1] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "mid_mouse_action" ), mMouseAction[1], valuesMouseAction, Encrypt );
- addItem( itemMouseAction[1], TQString::fromLatin1( "MouseActionmid" ) );
- itemMouseAction[2] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "left_mouse_action" ), mMouseAction[2], valuesMouseAction, PumpNDump );
- addItem( itemMouseAction[2], TQString::fromLatin1( "MouseActionleft" ) );
- TDEConfigSkeleton::ItemString *itemFooBar;
- itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
- addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
- TDEConfigSkeleton::ItemInt *itemAge;
- itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
- itemAge->setMinValue(8);
- itemAge->setMaxValue(88);
- addItem( itemAge, TQString::fromLatin1( "Age" ) );
-}
-
-Test5::~Test5()
-{
- if ( mSelf == this )
- staticTest5Deleter.setObject( mSelf, 0, false );
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test5.h.ref b/tdecore/kconfig_compiler/tests/test5.h.ref
deleted file mode 100644
index 274da4761..000000000
--- a/tdecore/kconfig_compiler/tests/test5.h.ref
+++ /dev/null
@@ -1,127 +0,0 @@
-// This file is generated by kconfig_compiler from test5.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST5_H
-#define TEST5_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class Test5 : public TDEConfigSkeleton
-{
- public:
- enum { Encrypt, Decrypt, CrashNBurn, PumpNDump };
- enum { right, mid, left };
- static const char* const EnumButtonToString[];
-
- static Test5 *self();
- ~Test5();
-
- /**
- Set Block colors.
- */
- static
- void setColor( int i, const TQColor & v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "Color%1" ).arg( i ) ))
- self()->mColor[i] = v;
- }
-
- /**
- Get Block colors.
- */
- static
- TQColor color( int i )
- {
- return self()->mColor[i];
- }
-
- /**
- Set Mouse actions.
- */
- static
- void setMouseAction( int i, int v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "MouseAction%1" ).arg( TQString::fromLatin1( EnumButtonToString[i] ) ) ))
- self()->mMouseAction[i] = v;
- }
-
- /**
- Get Mouse actions.
- */
- static
- int mouseAction( int i )
- {
- return self()->mMouseAction[i];
- }
-
- /**
- Set foo bar
- */
- static
- void setFooBar( const TQString & v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "FooBar" ) ))
- self()->mFooBar = v;
- }
-
- /**
- Get foo bar
- */
- static
- TQString fooBar()
- {
- return self()->mFooBar;
- }
-
- /**
- Set Age
- */
- static
- void setAge( int v )
- {
- if (v < 8)
- {
- kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
- v = 8;
- }
-
- if (v > 88)
- {
- kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
- v = 88;
- }
-
- if (!self()->isImmutable( TQString::fromLatin1( "Age" ) ))
- self()->mAge = v;
- }
-
- /**
- Get Age
- */
- static
- int age()
- {
- return self()->mAge;
- }
-
- static
- void writeConfig()
- {
- static_cast<TDEConfigSkeleton*>(self())->writeConfig();
- }
- protected:
- Test5();
- static Test5 *mSelf;
-
-
- // Foo
- TQColor mColor[4];
- int mMouseAction[3];
- TQString mFooBar;
- int mAge;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test5.kcfgc b/tdecore/kconfig_compiler/tests/test5.kcfgc
deleted file mode 100644
index 663005e5e..000000000
--- a/tdecore/kconfig_compiler/tests/test5.kcfgc
+++ /dev/null
@@ -1,11 +0,0 @@
-# Code generation options for kconfig_compiler
-File=test5.kcfg
-ClassName=Test5
-Singleton=true
-Mutators=true
-#Inherits=MyPrefs
-#IncludeFiles=myprefs.h
-#MemberVariables=public
-GlobalEnums=true
-ItemAccessors=false
-#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test6.cpp.ref b/tdecore/kconfig_compiler/tests/test6.cpp.ref
deleted file mode 100644
index fc19613a9..000000000
--- a/tdecore/kconfig_compiler/tests/test6.cpp.ref
+++ /dev/null
@@ -1,31 +0,0 @@
-// This file is generated by kconfig_compiler from test6.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test6.h"
-
-Test6::Test6( const TQString & Number )
- : TDEConfigSkeleton( TQString::fromLatin1( "test4rc" ) )
- , mParamNumber(Number)
-{
- setCurrentGroup( TQString::fromLatin1( "Foo" ) );
-
- TDEConfigSkeleton::ItemColor *itemColor;
- itemColor = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #%1" ).arg( mParamNumber ), mColor, TQColor( "red" ) );
- addItem( itemColor, TQString::fromLatin1( "Color" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Bar%1" ).arg( mParamNumber ) );
-
- TDEConfigSkeleton::ItemString *itemFooBar;
- itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
- addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
- TDEConfigSkeleton::ItemInt *itemAge;
- itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
- itemAge->setMinValue(8);
- itemAge->setMaxValue(88);
- addItem( itemAge, TQString::fromLatin1( "Age" ) );
-}
-
-Test6::~Test6()
-{
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test6.h.ref b/tdecore/kconfig_compiler/tests/test6.h.ref
deleted file mode 100644
index eee776b5a..000000000
--- a/tdecore/kconfig_compiler/tests/test6.h.ref
+++ /dev/null
@@ -1,93 +0,0 @@
-// This file is generated by kconfig_compiler from test6.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST6_H
-#define TEST6_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class Test6 : public TDEConfigSkeleton
-{
- public:
-
- Test6( const TQString & Number );
- ~Test6();
-
- /**
- Set Block colors.
- */
- void setColor( const TQColor & v )
- {
- if (!isImmutable( TQString::fromLatin1( "Color" ) ))
- mColor = v;
- }
-
- /**
- Get Block colors.
- */
- TQColor color() const
- {
- return mColor;
- }
-
- /**
- Set foo bar
- */
- void setFooBar( const TQString & v )
- {
- if (!isImmutable( TQString::fromLatin1( "FooBar" ) ))
- mFooBar = v;
- }
-
- /**
- Get foo bar
- */
- TQString fooBar() const
- {
- return mFooBar;
- }
-
- /**
- Set Age
- */
- void setAge( int v )
- {
- if (v < 8)
- {
- kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
- v = 8;
- }
-
- if (v > 88)
- {
- kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
- v = 88;
- }
-
- if (!isImmutable( TQString::fromLatin1( "Age" ) ))
- mAge = v;
- }
-
- /**
- Get Age
- */
- int age() const
- {
- return mAge;
- }
-
- protected:
- TQString mParamNumber;
-
- // Foo
- TQColor mColor;
-
- // Bar$(Number)
- TQString mFooBar;
- int mAge;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test6.kcfgc b/tdecore/kconfig_compiler/tests/test6.kcfgc
deleted file mode 100644
index b69dc152d..000000000
--- a/tdecore/kconfig_compiler/tests/test6.kcfgc
+++ /dev/null
@@ -1,11 +0,0 @@
-# Code generation options for kconfig_compiler
-File=test6.kcfg
-ClassName=Test6
-Singleton=false
-Mutators=true
-#Inherits=MyPrefs
-#IncludeFiles=myprefs.h
-#MemberVariables=public
-GlobalEnums=true
-ItemAccessors=false
-#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test7.cpp.ref b/tdecore/kconfig_compiler/tests/test7.cpp.ref
deleted file mode 100644
index 81f7de10e..000000000
--- a/tdecore/kconfig_compiler/tests/test7.cpp.ref
+++ /dev/null
@@ -1,31 +0,0 @@
-// This file is generated by kconfig_compiler from test7.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test7.h"
-
-Test7::Test7( int Number )
- : TDEConfigSkeleton( TQString::fromLatin1( "test7rc" ) )
- , mParamNumber(Number)
-{
- setCurrentGroup( TQString::fromLatin1( "Foo" ) );
-
- TDEConfigSkeleton::ItemColor *itemColor;
- itemColor = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #%1" ).arg( mParamNumber ), mColor, TQColor( "red" ) );
- addItem( itemColor, TQString::fromLatin1( "Color" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Bar%1" ).arg( mParamNumber ) );
-
- TDEConfigSkeleton::ItemString *itemFooBar;
- itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
- addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
- TDEConfigSkeleton::ItemInt *itemAge;
- itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
- itemAge->setMinValue(8);
- itemAge->setMaxValue(88);
- addItem( itemAge, TQString::fromLatin1( "Age" ) );
-}
-
-Test7::~Test7()
-{
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test7.h.ref b/tdecore/kconfig_compiler/tests/test7.h.ref
deleted file mode 100644
index fb6dd6c77..000000000
--- a/tdecore/kconfig_compiler/tests/test7.h.ref
+++ /dev/null
@@ -1,93 +0,0 @@
-// This file is generated by kconfig_compiler from test7.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST7_H
-#define TEST7_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class Test7 : public TDEConfigSkeleton
-{
- public:
-
- Test7( int Number );
- ~Test7();
-
- /**
- Set Block colors.
- */
- void setColor( const TQColor & v )
- {
- if (!isImmutable( TQString::fromLatin1( "Color" ) ))
- mColor = v;
- }
-
- /**
- Get Block colors.
- */
- TQColor color() const
- {
- return mColor;
- }
-
- /**
- Set foo bar
- */
- void setFooBar( const TQString & v )
- {
- if (!isImmutable( TQString::fromLatin1( "FooBar" ) ))
- mFooBar = v;
- }
-
- /**
- Get foo bar
- */
- TQString fooBar() const
- {
- return mFooBar;
- }
-
- /**
- Set Age
- */
- void setAge( int v )
- {
- if (v < 8)
- {
- kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
- v = 8;
- }
-
- if (v > 88)
- {
- kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
- v = 88;
- }
-
- if (!isImmutable( TQString::fromLatin1( "Age" ) ))
- mAge = v;
- }
-
- /**
- Get Age
- */
- int age() const
- {
- return mAge;
- }
-
- protected:
- int mParamNumber;
-
- // Foo
- TQColor mColor;
-
- // Bar$(Number)
- TQString mFooBar;
- int mAge;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test7.kcfgc b/tdecore/kconfig_compiler/tests/test7.kcfgc
deleted file mode 100644
index 9a6c40954..000000000
--- a/tdecore/kconfig_compiler/tests/test7.kcfgc
+++ /dev/null
@@ -1,11 +0,0 @@
-# Code generation options for kconfig_compiler
-File=test7.kcfg
-ClassName=Test7
-Singleton=false
-Mutators=true
-#Inherits=MyPrefs
-#IncludeFiles=myprefs.h
-#MemberVariables=public
-GlobalEnums=true
-ItemAccessors=false
-#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test8a.cpp.ref b/tdecore/kconfig_compiler/tests/test8a.cpp.ref
deleted file mode 100644
index c0267452d..000000000
--- a/tdecore/kconfig_compiler/tests/test8a.cpp.ref
+++ /dev/null
@@ -1,22 +0,0 @@
-// This file is generated by kconfig_compiler from test8a.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test8a.h"
-
-Test8a::Test8a( KSharedConfig::Ptr config )
- : TDEConfigSkeleton( config )
-{
- setCurrentGroup( TQString::fromLatin1( "Group" ) );
-
- TDEConfigSkeleton::ItemFont *itemFont;
- itemFont = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "Font" ), mFont, TDEGlobalSettings::generalFont() );
- addItem( itemFont, TQString::fromLatin1( "Font" ) );
- TDEConfigSkeleton::ItemFont *itemTitleFont;
- itemTitleFont = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "TitleFont" ), mTitleFont, TDEGlobalSettings::windowTitleFont() );
- addItem( itemTitleFont, TQString::fromLatin1( "TitleFont" ) );
-}
-
-Test8a::~Test8a()
-{
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test8a.h.ref b/tdecore/kconfig_compiler/tests/test8a.h.ref
deleted file mode 100644
index 747c6dd58..000000000
--- a/tdecore/kconfig_compiler/tests/test8a.h.ref
+++ /dev/null
@@ -1,61 +0,0 @@
-// This file is generated by kconfig_compiler from test8a.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST8A_H
-#define TEST8A_H
-
-#include <kglobal.h>
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class Test8a : public TDEConfigSkeleton
-{
- public:
-
- Test8a( KSharedConfig::Ptr config = TDEGlobal::sharedConfig() );
- ~Test8a();
-
- /**
- Set Font
- */
- void setFont( const TQFont & v )
- {
- if (!isImmutable( TQString::fromLatin1( "Font" ) ))
- mFont = v;
- }
-
- /**
- Get Font
- */
- TQFont font() const
- {
- return mFont;
- }
-
- /**
- Set TitleFont
- */
- void setTitleFont( const TQFont & v )
- {
- if (!isImmutable( TQString::fromLatin1( "TitleFont" ) ))
- mTitleFont = v;
- }
-
- /**
- Get TitleFont
- */
- TQFont titleFont() const
- {
- return mTitleFont;
- }
-
- protected:
-
- // Group
- TQFont mFont;
- TQFont mTitleFont;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test8b.cpp.ref b/tdecore/kconfig_compiler/tests/test8b.cpp.ref
deleted file mode 100644
index 6a0a16b48..000000000
--- a/tdecore/kconfig_compiler/tests/test8b.cpp.ref
+++ /dev/null
@@ -1,46 +0,0 @@
-// This file is generated by kconfig_compiler from test8b.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test8b.h"
-
-#include <kstaticdeleter.h>
-
-Test8b *Test8b::mSelf = 0;
-static KStaticDeleter<Test8b> staticTest8bDeleter;
-
-Test8b *Test8b::self()
-{
- if ( !mSelf ) {
- staticTest8bDeleter.setObject( mSelf, new Test8b() );
- mSelf->readConfig();
- }
-
- return mSelf;
-}
-
-Test8b::Test8b( )
- : Test8a()
-{
- mSelf = this;
- setCurrentGroup( TQString::fromLatin1( "Group8b1" ) );
-
- TDEConfigSkeleton::ItemUInt *itemSomething;
- itemSomething = new TDEConfigSkeleton::ItemUInt( currentGroup(), TQString::fromLatin1( "Something" ), mSomething, 60 );
- addItem( itemSomething, TQString::fromLatin1( "Something" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Group8b2" ) );
-
- TDEConfigSkeleton::ItemBool *itemFooBoo;
- itemFooBoo = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "FooBoo" ), mFooBoo, false );
- addItem( itemFooBoo, TQString::fromLatin1( "FooBoo" ) );
- TDEConfigSkeleton::ItemUInt *itemPort;
- itemPort = new TDEConfigSkeleton::ItemUInt( currentGroup(), TQString::fromLatin1( "Port" ), mPort, 1000 );
- addItem( itemPort, TQString::fromLatin1( "Port" ) );
-}
-
-Test8b::~Test8b()
-{
- if ( mSelf == this )
- staticTest8bDeleter.setObject( mSelf, 0, false );
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test8b.h.ref b/tdecore/kconfig_compiler/tests/test8b.h.ref
deleted file mode 100644
index 052746bfb..000000000
--- a/tdecore/kconfig_compiler/tests/test8b.h.ref
+++ /dev/null
@@ -1,96 +0,0 @@
-// This file is generated by kconfig_compiler from test8b.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST8B_H
-#define TEST8B_H
-
-#include <test8a.h>
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class Test8b : public Test8a
-{
- public:
-
- static Test8b *self();
- ~Test8b();
-
- /**
- Set Something
- */
- static
- void setSomething( uint v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "Something" ) ))
- self()->mSomething = v;
- }
-
- /**
- Get Something
- */
- static
- uint something()
- {
- return self()->mSomething;
- }
-
- /**
- Set FooBoo
- */
- static
- void setFooBoo( bool v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "FooBoo" ) ))
- self()->mFooBoo = v;
- }
-
- /**
- Get FooBoo
- */
- static
- bool fooBoo()
- {
- return self()->mFooBoo;
- }
-
- /**
- Set Port
- */
- static
- void setPort( uint v )
- {
- if (!self()->isImmutable( TQString::fromLatin1( "Port" ) ))
- self()->mPort = v;
- }
-
- /**
- Get Port
- */
- static
- uint port()
- {
- return self()->mPort;
- }
-
- static
- void writeConfig()
- {
- static_cast<TDEConfigSkeleton*>(self())->writeConfig();
- }
- protected:
- Test8b();
- static Test8b *mSelf;
-
-
- // Group8b1
- uint mSomething;
-
- // Group8b2
- bool mFooBoo;
- uint mPort;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test9.cpp.ref b/tdecore/kconfig_compiler/tests/test9.cpp.ref
deleted file mode 100644
index f6765fb42..000000000
--- a/tdecore/kconfig_compiler/tests/test9.cpp.ref
+++ /dev/null
@@ -1,35 +0,0 @@
-// This file is generated by kconfig_compiler from test9.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test9.h"
-
-Test9::Test9( const TQString & transport, const TQString & folder )
- : TDEConfigSkeleton( TQString::fromLatin1( "examplerc" ) )
- , mParamtransport(transport)
- , mParamfolder(folder)
-{
- setCurrentGroup( TQString::fromLatin1( "MyOptionsXX" ) );
-
- TQStringList defaultMyStringList;
- defaultMyStringList.append( TQString::fromUtf8( "up" ) );
- defaultMyStringList.append( TQString::fromUtf8( "down" ) );
-
- TDEConfigSkeleton::ItemStringList *itemMyStringList;
- itemMyStringList = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "MyStringList" ), mMyStringList, defaultMyStringList );
- addItem( itemMyStringList, TQString::fromLatin1( "MyStringList" ) );
- TQStringList defaultMyPathList;
- defaultMyPathList.append( TQString::fromUtf8( "/home" ) );
- defaultMyPathList.append( TQString::fromUtf8( "~" ) );
-
- TDEConfigSkeleton::ItemPathList *itemMyPathList;
- itemMyPathList = new TDEConfigSkeleton::ItemPathList( currentGroup(), TQString::fromLatin1( "MyPathList" ), mMyPathList, defaultMyPathList );
- addItem( itemMyPathList, TQString::fromLatin1( "MyPathList" ) );
- TDEConfigSkeleton::ItemPathList *itemMyPathsList2;
- itemMyPathsList2 = new TDEConfigSkeleton::ItemPathList( currentGroup(), TQString::fromLatin1( "MyPathsList2" ), mMyPathsList2, TQStringList(TQString::fromLatin1("/usr/bin")) += TQDir::homeDirPath() );
- addItem( itemMyPathsList2, TQString::fromLatin1( "MyPathsList2" ) );
-}
-
-Test9::~Test9()
-{
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test9.h.ref b/tdecore/kconfig_compiler/tests/test9.h.ref
deleted file mode 100644
index 99d94c957..000000000
--- a/tdecore/kconfig_compiler/tests/test9.h.ref
+++ /dev/null
@@ -1,82 +0,0 @@
-// This file is generated by kconfig_compiler from test9.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TEST9_H
-#define TEST9_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-#include <tqdir.h>
-class Test9 : public TDEConfigSkeleton
-{
- public:
-
- Test9( const TQString & transport, const TQString & folder );
- ~Test9();
-
- /**
- Set MyStringList
- */
- void setMyStringList( const TQStringList & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyStringList" ) ))
- mMyStringList = v;
- }
-
- /**
- Get MyStringList
- */
- TQStringList myStringList() const
- {
- return mMyStringList;
- }
-
- /**
- Set This is a list of paths
- */
- void setMyPathList( const TQStringList & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyPathList" ) ))
- mMyPathList = v;
- }
-
- /**
- Get This is a list of paths
- */
- TQStringList myPathList() const
- {
- return mMyPathList;
- }
-
- /**
- Set This is an additional test for PathList
- */
- void setMyPathsList2( const TQStringList & v )
- {
- if (!isImmutable( TQString::fromLatin1( "MyPathsList2" ) ))
- mMyPathsList2 = v;
- }
-
- /**
- Get This is an additional test for PathList
- */
- TQStringList myPathsList2() const
- {
- return mMyPathsList2;
- }
-
- protected:
- public:
- TQString mParamtransport;
- TQString mParamfolder;
-
- // MyOptionsXX
- TQStringList mMyStringList;
- TQStringList mMyPathList;
- TQStringList mMyPathsList2;
-
- private:
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test9.kcfgc b/tdecore/kconfig_compiler/tests/test9.kcfgc
deleted file mode 100644
index 0a88064b6..000000000
--- a/tdecore/kconfig_compiler/tests/test9.kcfgc
+++ /dev/null
@@ -1,18 +0,0 @@
-# Code generation options for kconfig_compiler
-ClassName=Test9
-#
-# Singleton=false
-#
-# Inherits=TDEConfigSkeleton
-#
-# IncludeFiles=libtdepim/kpimprefs.h
-#
-MemberVariables=public
-#
-### The following line includes the file exampleprefs_base_addon.h
-### It can be used to add extra functions and variables to the
-### class.
-# CustomAdditions=true
-#
-### Provide setFooBar(int) style functions
-Mutators=true
diff --git a/tdecore/kconfig_compiler/tests/test_dpointer.cpp.ref b/tdecore/kconfig_compiler/tests/test_dpointer.cpp.ref
deleted file mode 100644
index 3aad5b689..000000000
--- a/tdecore/kconfig_compiler/tests/test_dpointer.cpp.ref
+++ /dev/null
@@ -1,344 +0,0 @@
-// This file is generated by kconfig_compiler from test_dpointer.kcfg.
-// All changes you do to this file will be lost.
-
-#include "test_dpointer.h"
-
-#include <klocale.h>
-
-#include <kstaticdeleter.h>
-
-class TestDPointerPrivate
-{
- public:
-
- // General
- bool autoSave;
- int autoSaveInterval;
- bool confirm;
- TQString archiveFile;
- int destination;
-
- // Views
- int hourSize;
- bool selectionStartsEditor;
-
- // KOrganizer Plugins
- TQStringList selectedPlugins;
-
- // Colors
- TQColor highlightColor;
- TQColor agendaBgColor;
-
- // Fonts
- TQFont timeBarFont;
-
- // items
- TDEConfigSkeleton::ItemBool *autoSaveItem;
- TDEConfigSkeleton::ItemInt *autoSaveIntervalItem;
- TDEConfigSkeleton::ItemBool *confirmItem;
- TDEConfigSkeleton::ItemString *archiveFileItem;
- TDEConfigSkeleton::ItemEnum *destinationItem;
- TDEConfigSkeleton::ItemInt *hourSizeItem;
- TDEConfigSkeleton::ItemBool *selectionStartsEditorItem;
- TDEConfigSkeleton::ItemStringList *selectedPluginsItem;
- TDEConfigSkeleton::ItemColor *highlightColorItem;
- TDEConfigSkeleton::ItemColor *agendaBgColorItem;
- TDEConfigSkeleton::ItemFont *timeBarFontItem;
-};
-
-TestDPointer *TestDPointer::mSelf = 0;
-static KStaticDeleter<TestDPointer> staticTestDPointerDeleter;
-
-TestDPointer *TestDPointer::self()
-{
- if ( !mSelf ) {
- staticTestDPointerDeleter.setObject( mSelf, new TestDPointer() );
- mSelf->readConfig();
- }
-
- return mSelf;
-}
-
-TestDPointer::TestDPointer( )
- : TDEConfigSkeleton( TQString::fromLatin1( "korganizerrc" ) )
-{
- d = new TestDPointerPrivate;
- mSelf = this;
- setCurrentGroup( TQString::fromLatin1( "General" ) );
-
- d->autoSaveItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Auto Save" ), d->autoSave, false );
- d->autoSaveItem->setLabel( i18n("Enable automatic saving of calendar") );
- d->autoSaveItem->setWhatsThis( i18n("WhatsThis text for AutoSave option") );
- addItem( d->autoSaveItem, TQString::fromLatin1( "AutoSave" ) );
- d->autoSaveIntervalItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Auto Save Interval" ), d->autoSaveInterval, 10 );
- d->autoSaveIntervalItem->setLabel( i18n("Auto Save Interval") );
- addItem( d->autoSaveIntervalItem, TQString::fromLatin1( "AutoSaveInterval" ) );
- d->confirmItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Confirm Deletes" ), d->confirm, true );
- d->confirmItem->setLabel( i18n("Confirm deletes") );
- addItem( d->confirmItem, TQString::fromLatin1( "Confirm" ) );
- d->archiveFileItem = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "Archive File" ), d->archiveFile );
- d->archiveFileItem->setLabel( i18n("Archive File") );
- addItem( d->archiveFileItem, TQString::fromLatin1( "ArchiveFile" ) );
- TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesDestination;
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "standardDestination" );
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "askDestination" );
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "argl1" );
- choice.label = i18n("Argl1 Label");
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "argl2" );
- choice.whatsThis = i18n("Argl2 Whatsthis");
- valuesDestination.append( choice );
- }
- {
- TDEConfigSkeleton::ItemEnum::Choice choice;
- choice.name = TQString::fromLatin1( "argl3" );
- choice.label = i18n("Argl3 Label");
- choice.whatsThis = i18n("Argl3 Whatsthis");
- valuesDestination.append( choice );
- }
- d->destinationItem = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "Destination" ), d->destination, valuesDestination, EnumDestination::standardDestination );
- d->destinationItem->setLabel( i18n("New Events/Todos Should") );
- addItem( d->destinationItem, TQString::fromLatin1( "Destination" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Views" ) );
-
- d->hourSizeItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Hour Size" ), d->hourSize, 10 );
- d->hourSizeItem->setLabel( i18n("Hour Size") );
- addItem( d->hourSizeItem, TQString::fromLatin1( "HourSize" ) );
- d->selectionStartsEditorItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "SelectionStartsEditor" ), d->selectionStartsEditor, false );
- d->selectionStartsEditorItem->setLabel( i18n("Time range selection in agenda view starts event editor") );
- addItem( d->selectionStartsEditorItem, TQString::fromLatin1( "SelectionStartsEditor" ) );
-
- setCurrentGroup( TQString::fromLatin1( "KOrganizer Plugins" ) );
-
- TQStringList defaultSelectedPlugins;
- defaultSelectedPlugins.append( TQString::fromUtf8( "holidays" ) );
- defaultSelectedPlugins.append( TQString::fromUtf8( "webexport" ) );
-
- d->selectedPluginsItem = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "SelectedPlugins" ), d->selectedPlugins, defaultSelectedPlugins );
- d->selectedPluginsItem->setLabel( i18n("SelectedPlugins") );
- addItem( d->selectedPluginsItem, TQString::fromLatin1( "SelectedPlugins" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Colors" ) );
-
- d->highlightColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Highlight Color" ), d->highlightColor, TQColor( 100, 100, 255 ) );
- d->highlightColorItem->setLabel( i18n("Highlight color") );
- addItem( d->highlightColorItem, TQString::fromLatin1( "HighlightColor" ) );
- d->agendaBgColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Agenda Background Color" ), d->agendaBgColor, TQColor( 255, 255, 255 ) );
- d->agendaBgColorItem->setLabel( i18n("Agenda view background color") );
- addItem( d->agendaBgColorItem, TQString::fromLatin1( "AgendaBgColor" ) );
-
- setCurrentGroup( TQString::fromLatin1( "Fonts" ) );
-
- d->timeBarFontItem = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "TimeBar Font" ), d->timeBarFont );
- d->timeBarFontItem->setLabel( i18n("Time bar") );
- addItem( d->timeBarFontItem, TQString::fromLatin1( "TimeBarFont" ) );
-}
-
-void TestDPointer::setAutoSave( bool v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "AutoSave" ) ))
- self()->d->autoSave = v;
-}
-
-bool TestDPointer::autoSave()
-{
- return self()->d->autoSave;
-}
-
-
-TDEConfigSkeleton::ItemBool *TestDPointer::autoSaveItem()
-{
- return d->autoSaveItem;
-}
-
-void TestDPointer::setAutoSaveInterval( int v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "AutoSaveInterval" ) ))
- self()->d->autoSaveInterval = v;
-}
-
-int TestDPointer::autoSaveInterval()
-{
- return self()->d->autoSaveInterval;
-}
-
-
-TDEConfigSkeleton::ItemInt *TestDPointer::autoSaveIntervalItem()
-{
- return d->autoSaveIntervalItem;
-}
-
-void TestDPointer::setConfirm( bool v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "Confirm" ) ))
- self()->d->confirm = v;
-}
-
-bool TestDPointer::confirm()
-{
- return self()->d->confirm;
-}
-
-
-TDEConfigSkeleton::ItemBool *TestDPointer::confirmItem()
-{
- return d->confirmItem;
-}
-
-void TestDPointer::setArchiveFile( const TQString & v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "ArchiveFile" ) ))
- self()->d->archiveFile = v;
-}
-
-TQString TestDPointer::archiveFile()
-{
- return self()->d->archiveFile;
-}
-
-
-TDEConfigSkeleton::ItemString *TestDPointer::archiveFileItem()
-{
- return d->archiveFileItem;
-}
-
-void TestDPointer::setDestination( int v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "Destination" ) ))
- self()->d->destination = v;
-}
-
-int TestDPointer::destination()
-{
- return self()->d->destination;
-}
-
-
-TDEConfigSkeleton::ItemEnum *TestDPointer::destinationItem()
-{
- return d->destinationItem;
-}
-
-void TestDPointer::setHourSize( int v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "HourSize" ) ))
- self()->d->hourSize = v;
-}
-
-int TestDPointer::hourSize()
-{
- return self()->d->hourSize;
-}
-
-
-TDEConfigSkeleton::ItemInt *TestDPointer::hourSizeItem()
-{
- return d->hourSizeItem;
-}
-
-void TestDPointer::setSelectionStartsEditor( bool v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "SelectionStartsEditor" ) ))
- self()->d->selectionStartsEditor = v;
-}
-
-bool TestDPointer::selectionStartsEditor()
-{
- return self()->d->selectionStartsEditor;
-}
-
-
-TDEConfigSkeleton::ItemBool *TestDPointer::selectionStartsEditorItem()
-{
- return d->selectionStartsEditorItem;
-}
-
-void TestDPointer::setSelectedPlugins( const TQStringList & v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "SelectedPlugins" ) ))
- self()->d->selectedPlugins = v;
-}
-
-TQStringList TestDPointer::selectedPlugins()
-{
- return self()->d->selectedPlugins;
-}
-
-
-TDEConfigSkeleton::ItemStringList *TestDPointer::selectedPluginsItem()
-{
- return d->selectedPluginsItem;
-}
-
-void TestDPointer::setHighlightColor( const TQColor & v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "HighlightColor" ) ))
- self()->d->highlightColor = v;
-}
-
-TQColor TestDPointer::highlightColor()
-{
- return self()->d->highlightColor;
-}
-
-
-TDEConfigSkeleton::ItemColor *TestDPointer::highlightColorItem()
-{
- return d->highlightColorItem;
-}
-
-void TestDPointer::setAgendaBgColor( const TQColor & v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "AgendaBgColor" ) ))
- self()->d->agendaBgColor = v;
-}
-
-TQColor TestDPointer::agendaBgColor()
-{
- return self()->d->agendaBgColor;
-}
-
-
-TDEConfigSkeleton::ItemColor *TestDPointer::agendaBgColorItem()
-{
- return d->agendaBgColorItem;
-}
-
-void TestDPointer::setTimeBarFont( const TQFont & v )
-{
- if (!self()->isImmutable( TQString::fromLatin1( "TimeBarFont" ) ))
- self()->d->timeBarFont = v;
-}
-
-TQFont TestDPointer::timeBarFont()
-{
- return self()->d->timeBarFont;
-}
-
-
-TDEConfigSkeleton::ItemFont *TestDPointer::timeBarFontItem()
-{
- return d->timeBarFontItem;
-}
-
-TestDPointer::~TestDPointer()
-{
- delete d;
- if ( mSelf == this )
- staticTestDPointerDeleter.setObject( mSelf, 0, false );
-}
-
diff --git a/tdecore/kconfig_compiler/tests/test_dpointer.h.ref b/tdecore/kconfig_compiler/tests/test_dpointer.h.ref
deleted file mode 100644
index d9b7b94c1..000000000
--- a/tdecore/kconfig_compiler/tests/test_dpointer.h.ref
+++ /dev/null
@@ -1,224 +0,0 @@
-// This file is generated by kconfig_compiler from test_dpointer.kcfg.
-// All changes you do to this file will be lost.
-#ifndef TESTDPOINTER_H
-#define TESTDPOINTER_H
-
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-
-class TestDPointerPrivate;
-
-class TestDPointer : public TDEConfigSkeleton
-{
- public:
- class EnumDestination
- {
- public:
- enum type { standardDestination, askDestination, argl1, argl2, argl3, COUNT };
- };
-
- static TestDPointer *self();
- ~TestDPointer();
-
- /**
- Set Enable automatic saving of calendar
- */
- static
- void setAutoSave( bool v );
-
- /**
- Get Enable automatic saving of calendar
- */
- static
- bool autoSave();
-
- /**
- Get Item object corresponding to AutoSave()
- */
- ItemBool *autoSaveItem();
-
- /**
- Set Auto Save Interval
- */
- static
- void setAutoSaveInterval( int v );
-
- /**
- Get Auto Save Interval
- */
- static
- int autoSaveInterval();
-
- /**
- Get Item object corresponding to AutoSaveInterval()
- */
- ItemInt *autoSaveIntervalItem();
-
- /**
- Set Confirm deletes
- */
- static
- void setConfirm( bool v );
-
- /**
- Get Confirm deletes
- */
- static
- bool confirm();
-
- /**
- Get Item object corresponding to Confirm()
- */
- ItemBool *confirmItem();
-
- /**
- Set Archive File
- */
- static
- void setArchiveFile( const TQString & v );
-
- /**
- Get Archive File
- */
- static
- TQString archiveFile();
-
- /**
- Get Item object corresponding to ArchiveFile()
- */
- ItemString *archiveFileItem();
-
- /**
- Set New Events/Todos Should
- */
- static
- void setDestination( int v );
-
- /**
- Get New Events/Todos Should
- */
- static
- int destination();
-
- /**
- Get Item object corresponding to Destination()
- */
- ItemEnum *destinationItem();
-
- /**
- Set Hour Size
- */
- static
- void setHourSize( int v );
-
- /**
- Get Hour Size
- */
- static
- int hourSize();
-
- /**
- Get Item object corresponding to HourSize()
- */
- ItemInt *hourSizeItem();
-
- /**
- Set Time range selection in agenda view starts event editor
- */
- static
- void setSelectionStartsEditor( bool v );
-
- /**
- Get Time range selection in agenda view starts event editor
- */
- static
- bool selectionStartsEditor();
-
- /**
- Get Item object corresponding to SelectionStartsEditor()
- */
- ItemBool *selectionStartsEditorItem();
-
- /**
- Set SelectedPlugins
- */
- static
- void setSelectedPlugins( const TQStringList & v );
-
- /**
- Get SelectedPlugins
- */
- static
- TQStringList selectedPlugins();
-
- /**
- Get Item object corresponding to SelectedPlugins()
- */
- ItemStringList *selectedPluginsItem();
-
- /**
- Set Highlight color
- */
- static
- void setHighlightColor( const TQColor & v );
-
- /**
- Get Highlight color
- */
- static
- TQColor highlightColor();
-
- /**
- Get Item object corresponding to HighlightColor()
- */
- ItemColor *highlightColorItem();
-
- /**
- Set Agenda view background color
- */
- static
- void setAgendaBgColor( const TQColor & v );
-
- /**
- Get Agenda view background color
- */
- static
- TQColor agendaBgColor();
-
- /**
- Get Item object corresponding to AgendaBgColor()
- */
- ItemColor *agendaBgColorItem();
-
- /**
- Set Time bar
- */
- static
- void setTimeBarFont( const TQFont & v );
-
- /**
- Get Time bar
- */
- static
- TQFont timeBarFont();
-
- /**
- Get Item object corresponding to TimeBarFont()
- */
- ItemFont *timeBarFontItem();
-
- static
- void writeConfig()
- {
- static_cast<TDEConfigSkeleton*>(self())->writeConfig();
- }
- protected:
- TestDPointer();
- static TestDPointer *mSelf;
-
- private:
- TestDPointerPrivate *d;
-};
-
-#endif
-
diff --git a/tdecore/kconfig_compiler/tests/test_dpointer.kcfgc b/tdecore/kconfig_compiler/tests/test_dpointer.kcfgc
deleted file mode 100644
index 48baa376e..000000000
--- a/tdecore/kconfig_compiler/tests/test_dpointer.kcfgc
+++ /dev/null
@@ -1,11 +0,0 @@
-# Code generation options for kconfig_compiler
-File=test_dpointer.kcfg
-ClassName=TestDPointer
-Singleton=true
-Mutators=true
-#Inherits=MyPrefs
-#IncludeFiles=myprefs.h
-MemberVariables=dpointer
-#GlobalEnums=true
-ItemAccessors=true
-SetUserTexts=true
diff --git a/tdecore/kconfigbackend.cpp b/tdecore/kconfigbackend.cpp
deleted file mode 100644
index 178198509..000000000
--- a/tdecore/kconfigbackend.cpp
+++ /dev/null
@@ -1,1190 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Preston Brown <pbrown@kde.org>
- Copyright (c) 1997-1999 Matthias Kalle Dalheimer <kalle@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <config.h>
-
-#include <unistd.h>
-#include <ctype.h>
-#ifdef HAVE_SYS_MMAN_H
-#include <sys/mman.h>
-#endif
-#include <sys/types.h>
-#ifdef HAVE_SYS_STAT_H
-#include <sys/stat.h>
-#endif
-#include <fcntl.h>
-#include <signal.h>
-#include <setjmp.h>
-
-#include <tqdir.h>
-#include <tqfileinfo.h>
-#include <tqtextcodec.h>
-#include <tqtextstream.h>
-
-#include "kconfigbackend.h"
-#include "kconfigbase.h"
-#include <kapplication.h>
-#include <kglobal.h>
-#include <kprocess.h>
-#include <klocale.h>
-#include <kstandarddirs.h>
-#include <ksavefile.h>
-#include <kurl.h>
-#include <kde_file.h>
-
-extern bool checkAccess(const TQString& pathname, int mode);
-/* translate escaped escape sequences to their actual values. */
-static TQCString printableToString(const char *str, int l)
-{
- // Strip leading white-space.
- while((l>0) &&
- ((*str == ' ') || (*str == '\t') || (*str == '\r')))
- {
- str++; l--;
- }
-
- // Strip trailing white-space.
- while((l>0) &&
- ((str[l-1] == ' ') || (str[l-1] == '\t') || (str[l-1] == '\r')))
- {
- l--;
- }
-
- TQCString result(l + 1);
- char *r = result.data();
-
- for(int i = 0; i < l;i++, str++)
- {
- if (*str == '\\')
- {
- i++, str++;
- if (i >= l) // End of line. (Line ends with single slash)
- {
- *r++ = '\\';
- break;
- }
- switch(*str)
- {
- case 's':
- *r++ = ' ';
- break;
- case 't':
- *r++ = '\t';
- break;
- case 'n':
- *r++ = '\n';
- break;
- case 'r':
- *r++ = '\r';
- break;
- case '\\':
- *r++ = '\\';
- break;
- default:
- *r++ = '\\';
- *r++ = *str;
- }
- }
- else
- {
- *r++ = *str;
- }
- }
- result.truncate(r-result.data());
- return result;
-}
-
-static TQCString stringToPrintable(const TQCString& str){
- TQCString result(str.length()*2); // Maximum 2x as long as source string
- register char *r = const_cast<TQCString&>(result).data();
- register char *s = const_cast<TQCString&>(str).data();
-
- if (!s) return TQCString("");
-
- // Escape leading space
- if (*s == ' ')
- {
- *r++ = '\\'; *r++ = 's';
- s++;
- }
-
- if (*s)
- {
- while(*s)
- {
- if (*s == '\n')
- {
- *r++ = '\\'; *r++ = 'n';
- }
- else if (*s == '\t')
- {
- *r++ = '\\'; *r++ = 't';
- }
- else if (*s == '\r')
- {
- *r++ = '\\'; *r++ = 'r';
- }
- else if (*s == '\\')
- {
- *r++ = '\\'; *r++ = '\\';
- }
- else
- {
- *r++ = *s;
- }
- s++;
- }
- // Escape trailing space
- if (*(r-1) == ' ')
- {
- *(r-1) = '\\'; *r++ = 's';
- }
- }
-
- result.truncate(r - result.data());
- return result;
-}
-
-static TQCString decodeGroup(const char*s, int l)
-{
- TQCString result(l);
- register char *r = result.data();
-
- l--; // Correct for trailing \0
- while(l)
- {
- if ((*s == '[') && (l > 1))
- {
- if ((*(s+1) == '['))
- {
- l--;
- s++;
- }
- }
- if ((*s == ']') && (l > 1))
- {
- if ((*(s+1) == ']'))
- {
- l--;
- s++;
- }
- }
- *r++ = *s++;
- l--;
- }
- result.truncate(r - result.data());
- return result;
-}
-
-static TQCString encodeGroup(const TQCString &str)
-{
- int l = str.length();
- TQCString result(l*2+1);
- register char *r = const_cast<TQCString&>(result).data();
- register char *s = const_cast<TQCString&>(str).data();
- while(l)
- {
- if ((*s == '[') || (*s == ']'))
- *r++ = *s;
- *r++ = *s++;
- l--;
- }
- result.truncate(r - result.data());
- return result;
-}
-
-static TQCString encodeKey(const char* key)
-{
- TQCString newKey(key);
-
- newKey.replace('[', "%5b");
- newKey.replace(']', "%5d");
-
- return newKey;
-}
-
-static TQCString decodeKey(const char* key)
-{
- TQCString newKey(key);
-
- newKey.replace("%5b", "[");
- newKey.replace("%5d", "]");
-
- return newKey;
-}
-
-class TDEConfigBackEnd::TDEConfigBackEndPrivate
-{
-public:
- TQDateTime localLastModified;
- uint localLastSize;
- KLockFile::Ptr localLockFile;
- KLockFile::Ptr globalLockFile;
-};
-
-void TDEConfigBackEnd::changeFileName(const TQString &_fileName,
- const char * _resType,
- bool _useKDEGlobals)
-{
- mfileName = _fileName;
- resType = _resType;
- useKDEGlobals = _useKDEGlobals;
- if (mfileName.isEmpty()) {
- mLocalFileName = TQString::null;
- }
- else if (!TQDir::isRelativePath(mfileName)) {
- mLocalFileName = mfileName;
- }
- else {
- mLocalFileName = TDEGlobal::dirs()->saveLocation(resType, TQString(), false) + mfileName;
- }
-
- if (useKDEGlobals) {
- mGlobalFileName = TDEGlobal::dirs()->saveLocation("config", TQString(), false) + TQString::fromLatin1("kdeglobals");
- }
- else {
- mGlobalFileName = TQString::null;
- }
-
- d->localLastModified = TQDateTime();
- d->localLastSize = 0;
- d->localLockFile = 0;
- d->globalLockFile = 0;
-}
-
-KLockFile::Ptr TDEConfigBackEnd::lockFile(bool bGlobal)
-{
- if (bGlobal)
- {
- if (d->globalLockFile)
- return d->globalLockFile;
-
- if (!mGlobalFileName.isEmpty())
- {
- d->globalLockFile = new KLockFile(mGlobalFileName+".lock");
- return d->globalLockFile;
- }
- }
- else
- {
- if (d->localLockFile)
- return d->localLockFile;
-
- if (!mLocalFileName.isEmpty())
- {
- d->localLockFile = new KLockFile(mLocalFileName+".lock");
- return d->localLockFile;
- }
- }
- return 0;
-}
-
-TDEConfigBackEnd::TDEConfigBackEnd(TDEConfigBase *_config,
- const TQString &_fileName,
- const char * _resType,
- bool _useKDEGlobals)
- : pConfig(_config), bFileImmutable(false), mConfigState(TDEConfigBase::NoAccess), mFileMode(-1)
-{
- d = new TDEConfigBackEndPrivate;
- changeFileName(_fileName, _resType, _useKDEGlobals);
-}
-
-TDEConfigBackEnd::~TDEConfigBackEnd()
-{
- delete d;
-}
-
-void TDEConfigBackEnd::setFileWriteMode(int mode)
-{
- mFileMode = mode;
-}
-
-bool TDEConfigINIBackEnd::parseConfigFiles()
-{
- // Check if we can write to the local file.
- mConfigState = TDEConfigBase::ReadOnly;
- if (!mLocalFileName.isEmpty() && !pConfig->isReadOnly())
- {
- if (checkAccess(mLocalFileName, W_OK))
- {
- mConfigState = TDEConfigBase::ReadWrite;
- }
- else
- {
- // Create the containing dir, maybe it wasn't there
- KURL path;
- path.setPath(mLocalFileName);
- TQString dir=path.directory();
- KStandardDirs::makeDir(dir);
-
- if (checkAccess(mLocalFileName, W_OK))
- {
- mConfigState = TDEConfigBase::ReadWrite;
- }
- }
- TQFileInfo info(mLocalFileName);
- d->localLastModified = info.lastModified();
- d->localLastSize = info.size();
- }
-
- // Parse all desired files from the least to the most specific.
- bFileImmutable = false;
-
- // Parse the general config files
- if (useKDEGlobals) {
- TQStringList kdercs = TDEGlobal::dirs()->
- findAllResources("config", TQString::fromLatin1("kdeglobals"));
-
-#ifdef Q_WS_WIN
- TQString etc_kderc = TQFile::decodeName( TQCString(getenv("WINDIR")) + "\\kderc" );
-#else
- TQString etc_kderc = TQString::fromLatin1("/etc/kderc");
-#endif
-
- if (checkAccess(etc_kderc, R_OK))
- kdercs += etc_kderc;
-
- kdercs += TDEGlobal::dirs()->
- findAllResources("config", TQString::fromLatin1("system.kdeglobals"));
-
- TQStringList::ConstIterator it;
-
- for (it = kdercs.fromLast(); it != kdercs.end(); --it) {
-
- TQFile aConfigFile( *it );
- if (!aConfigFile.open( IO_ReadOnly ))
- continue;
- parseSingleConfigFile( aConfigFile, 0L, true, (*it != mGlobalFileName) );
- aConfigFile.close();
- if (bFileImmutable)
- break;
- }
- }
-
- bool bReadFile = !mfileName.isEmpty();
- while(bReadFile) {
- bReadFile = false;
- TQString bootLanguage;
- if (useKDEGlobals && localeString.isEmpty() && !TDEGlobal::_locale) {
- // Boot strap language
- bootLanguage = KLocale::_initLanguage(pConfig);
- setLocaleString(bootLanguage.utf8());
- }
-
- bFileImmutable = false;
- TQStringList list;
- if ( !TQDir::isRelativePath(mfileName) )
- list << mfileName;
- else
- list = TDEGlobal::dirs()->findAllResources(resType, mfileName);
-
- TQStringList::ConstIterator it;
-
- for (it = list.fromLast(); it != list.end(); --it) {
-
- TQFile aConfigFile( *it );
- // we can already be sure that this file exists
- bool bIsLocal = (*it == mLocalFileName);
- if (aConfigFile.open( IO_ReadOnly )) {
- parseSingleConfigFile( aConfigFile, 0L, false, !bIsLocal );
- aConfigFile.close();
- if (bFileImmutable)
- break;
- }
- }
- if (TDEGlobal::dirs()->isRestrictedResource(resType, mfileName))
- bFileImmutable = true;
- TQString currentLanguage;
- if (!bootLanguage.isEmpty())
- {
- currentLanguage = KLocale::_initLanguage(pConfig);
- // If the file changed the language, we need to read the file again
- // with the new language setting.
- if (bootLanguage != currentLanguage)
- {
- bReadFile = true;
- setLocaleString(currentLanguage.utf8());
- }
- }
- }
- if (bFileImmutable)
- mConfigState = TDEConfigBase::ReadOnly;
-
- return true;
-}
-
-#ifdef HAVE_MMAP
-#ifdef SIGBUS
-static sigjmp_buf mmap_jmpbuf;
-struct sigaction mmap_old_sigact;
-
-extern "C" {
- static void mmap_sigbus_handler(int)
- {
- siglongjmp (mmap_jmpbuf, 1);
- }
-}
-#endif
-#endif
-
-extern bool kde_kiosk_exception;
-
-void TDEConfigINIBackEnd::parseSingleConfigFile(TQFile &rFile,
- KEntryMap *pWriteBackMap,
- bool bGlobal, bool bDefault)
-{
- const char *s; // May get clobbered by sigsetjump, but we don't use them afterwards.
- const char *eof; // May get clobbered by sigsetjump, but we don't use them afterwards.
- TQByteArray data;
-
- if (!rFile.isOpen()) // come back, if you have real work for us ;->
- return;
-
- //using kdDebug() here leads to an infinite loop
- //remove this for the release, aleXXX
- //tqWarning("Parsing %s, global = %s default = %s",
- // rFile.name().latin1(), bGlobal ? "true" : "false", bDefault ? "true" : "false");
-
- TQCString aCurrentGroup("<default>");
-
- unsigned int ll = localeString.length();
-
-#ifdef HAVE_MMAP
- static volatile const char *map;
- map = ( const char* ) mmap(0, rFile.size(), PROT_READ, MAP_PRIVATE,
- rFile.handle(), 0);
-
- if ( map != MAP_FAILED )
- {
- s = (const char*) map;
- eof = s + rFile.size();
-
-#ifdef SIGBUS
- struct sigaction act;
- act.sa_handler = mmap_sigbus_handler;
- sigemptyset( &act.sa_mask );
-#ifdef SA_ONESHOT
- act.sa_flags = SA_ONESHOT;
-#else
- act.sa_flags = SA_RESETHAND;
-#endif
- sigaction( SIGBUS, &act, &mmap_old_sigact );
-
- if (sigsetjmp (mmap_jmpbuf, 1))
- {
-tqWarning("SIGBUS while reading %s", rFile.name().latin1());
- munmap(( char* )map, rFile.size());
- sigaction (SIGBUS, &mmap_old_sigact, 0);
- return;
- }
-#endif
- }
- else
-#endif
- {
- rFile.at(0);
- data = rFile.readAll();
- s = data.data();
- eof = s + data.size();
- }
-
- bool fileOptionImmutable = false;
- bool groupOptionImmutable = false;
- bool groupSkip = false;
- bool foundGettextDomain = false;
- TQCString gettextDomain;
-
- int line = 0;
- for(; s < eof; s++)
- {
- line++;
-
- while((s < eof) && isspace(*s) && (*s != '\n'))
- s++; //skip leading whitespace, shouldn't happen too often
-
- //skip empty lines, lines starting with #
- if ((s < eof) && ((*s == '\n') || (*s == '#')))
- {
- sktoeol: //skip till end-of-line
- while ((s < eof) && (*s != '\n'))
- s++;
- continue; // Empty or comment or no keyword
- }
- const char *startLine = s;
-
- if (*s == '[') //group
- {
- // In a group [[ and ]] have a special meaning
- while ((s < eof) && (*s != '\n'))
- {
- if (*s == ']')
- {
- if ((s+1 < eof) && (*(s+1) == ']'))
- s++; // Skip "]]"
- else
- break;
- }
-
- s++; // Search till end of group
- }
- const char *e = s;
- while ((s < eof) && (*s != '\n')) s++; // Search till end of line / end of file
- if ((e >= eof) || (*e != ']'))
- {
- fprintf(stderr, "Invalid group header at %s:%d\n", rFile.name().latin1(), line);
- continue;
- }
- // group found; get the group name by taking everything in
- // between the brackets
- if ((e-startLine == 3) &&
- (startLine[1] == '$') &&
- (startLine[2] == 'i'))
- {
- if (!kde_kiosk_exception)
- fileOptionImmutable = true;
- continue;
- }
-
- aCurrentGroup = decodeGroup(startLine + 1, e - startLine);
- //cout<<"found group ["<<aCurrentGroup<<"]"<<endl;
-
- // Backwards compatibility
- if (aCurrentGroup == "KDE Desktop Entry")
- aCurrentGroup = "Desktop Entry";
-
- groupOptionImmutable = fileOptionImmutable;
-
- e++;
- if ((e+2 < eof) && (*e++ == '[') && (*e++ == '$')) // Option follows
- {
- if ((*e == 'i') && !kde_kiosk_exception)
- {
- groupOptionImmutable = true;
- }
- }
-
- KEntryKey groupKey(aCurrentGroup, 0);
- KEntry entry = pConfig->lookupData(groupKey);
- groupSkip = entry.bImmutable;
-
- if (groupSkip && !bDefault)
- continue;
-
- entry.bImmutable |= groupOptionImmutable;
- pConfig->putData(groupKey, entry, false);
-
- if (pWriteBackMap)
- {
- // add the special group key indicator
- (*pWriteBackMap)[groupKey] = entry;
- }
-
- continue;
- }
- if (groupSkip && !bDefault)
- goto sktoeol; // Skip entry
-
-
- bool optionImmutable = groupOptionImmutable;
- bool optionDeleted = false;
- bool optionExpand = false;
- const char *endOfKey = 0, *locale = 0, *elocale = 0;
- for (; (s < eof) && (*s != '\n'); s++)
- {
- if (*s == '=') //find the equal sign
- {
- if (!endOfKey)
- endOfKey = s;
- goto haveeq;
- }
- if (*s == '[') //find the locale or options.
- {
- const char *option;
- const char *eoption;
- endOfKey = s;
- option = ++s;
- for (;; s++)
- {
- if ((s >= eof) || (*s == '\n') || (*s == '=')) {
- fprintf(stderr, "Invalid entry (missing ']') at %s:%d\n", rFile.name().latin1(), line);
- goto sktoeol;
- }
- if (*s == ']')
- break;
- }
- eoption = s;
- if (*option != '$')
- {
- // Locale
- if (locale) {
- fprintf(stderr, "Invalid entry (second locale!?) at %s:%d\n", rFile.name().latin1(), line);
- goto sktoeol;
- }
- locale = option;
- elocale = eoption;
- }
- else
- {
- // Option
- while (option < eoption)
- {
- option++;
- if ((*option == 'i') && !kde_kiosk_exception)
- optionImmutable = true;
- else if (*option == 'e')
- optionExpand = true;
- else if (*option == 'd')
- {
- optionDeleted = true;
- goto haveeq;
- }
- else if (*option == ']')
- break;
- }
- }
- }
- }
- fprintf(stderr, "Invalid entry (missing '=') at %s:%d\n", rFile.name().latin1(), line);
- continue;
-
- haveeq:
- for (endOfKey--; ; endOfKey--)
- {
- if (endOfKey < startLine)
- {
- fprintf(stderr, "Invalid entry (empty key) at %s:%d\n", rFile.name().latin1(), line);
- goto sktoeol;
- }
- if (!isspace(*endOfKey))
- break;
- }
-
- const char *st = ++s;
- while ((s < eof) && (*s != '\n')) s++; // Search till end of line / end of file
-
- if (locale) {
- unsigned int cl = static_cast<unsigned int>(elocale - locale);
- if ((ll != cl) || memcmp(locale, localeString.data(), ll))
- {
- // backward compatibility. C == en_US
- if ( cl != 1 || ll != 5 || *locale != 'C' || memcmp(localeString.data(), "en_US", 5)) {
- //cout<<"mismatched locale '"<<TQCString(locale, elocale-locale +1)<<"'"<<endl;
- // We can ignore this one
- if (!pWriteBackMap)
- continue; // We just ignore it
- // We just store it as is to be able to write it back later.
- endOfKey = elocale;
- locale = 0;
- }
- }
- }
-
- // insert the key/value line
- TQCString key(startLine, endOfKey - startLine + 2);
- TQCString val = printableToString(st, s - st);
- //tqDebug("found key '%s' with value '%s'", key.data(), val.data());
-
- if (TQString(key.data()) == "X-Ubuntu-Gettext-Domain") {
- gettextDomain = val.data();
- foundGettextDomain = true;
- }
-
- KEntryKey aEntryKey(aCurrentGroup, decodeKey(key));
- aEntryKey.bLocal = (locale != 0);
- aEntryKey.bDefault = bDefault;
-
- KEntry aEntry;
- aEntry.mValue = val;
- aEntry.bGlobal = bGlobal;
- aEntry.bImmutable = optionImmutable;
- aEntry.bDeleted = optionDeleted;
- aEntry.bExpand = optionExpand;
- aEntry.bNLS = (locale != 0);
-
- if (pWriteBackMap) {
- // don't insert into the config object but into the temporary
- // scratchpad map
- pWriteBackMap->insert(aEntryKey, aEntry);
- } else {
- // directly insert value into config object
- // no need to specify localization; if the key we just
- // retrieved was localized already, no need to localize it again.
- pConfig->putData(aEntryKey, aEntry, false);
- }
- }
- // Look up translations using KLocale
- // https://launchpad.net/distros/ubuntu/+spec/langpacks-desktopfiles-kde
- // This calls KLocale up to 10 times for each config file (and each TDEConfig has up to 4 files)
- // so I'll see how much of a performance hit it is
- // it also only acts on the last group in a file
- // Ideas: only translate most important fields, only translate "Desktop Entry" files,
- // do translation per TDEConfig not per single file
- if (!pWriteBackMap) {
- TQFile file("file.txt");
- if (foundGettextDomain) {
-
- KLocale locale(gettextDomain);
-
- TQString language = locale.language();
- translateKey(locale, aCurrentGroup, TQCString("Name"));
- translateKey(locale, aCurrentGroup, TQCString("Comment"));
- translateKey(locale, aCurrentGroup, TQCString("Language"));
- translateKey(locale, aCurrentGroup, TQCString("Keywords"));
- translateKey(locale, aCurrentGroup, TQCString("About"));
- translateKey(locale, aCurrentGroup, TQCString("Description"));
- translateKey(locale, aCurrentGroup, TQCString("GenericName"));
- translateKey(locale, aCurrentGroup, TQCString("Query"));
- translateKey(locale, aCurrentGroup, TQCString("ExtraNames"));
- translateKey(locale, aCurrentGroup, TQCString("X-TDE-Submenu"));
- }
- }
-
-
- if (fileOptionImmutable)
- bFileImmutable = true;
-
-#ifdef HAVE_MMAP
- if (map)
- {
- munmap(( char* )map, rFile.size());
-#ifdef SIGBUS
- sigaction (SIGBUS, &mmap_old_sigact, 0);
-#endif
- }
-#endif
-}
-
-void TDEConfigINIBackEnd::translateKey(KLocale& locale, TQCString currentGroup, TQCString key) {
- KEntryKey entryKey = KEntryKey(currentGroup, key);
- KEntry entry = pConfig->lookupData(entryKey);
- if (TQString(entry.mValue) != "") {
- TQString orig = key + "=" + entry.mValue;
- TQString translate = locale.translate(key + "=" + entry.mValue);
- if (TQString::compare(orig, translate) != 0) {
- translate = translate.mid(key.length() + 1);
- entry.mValue = translate.utf8();
- entryKey.bLocal = true;
- entry.bNLS = true;
- pConfig->putData(entryKey, entry, false);
- }
- }
-}
-
-void TDEConfigINIBackEnd::sync(bool bMerge)
-{
- // write-sync is only necessary if there are dirty entries
- if (!pConfig->isDirty())
- return;
-
- bool bEntriesLeft = true;
-
- // find out the file to write to (most specific writable file)
- // try local app-specific file first
-
- if (!mfileName.isEmpty()) {
- // Create the containing dir if needed
- if ((resType!="config") && !TQDir::isRelativePath(mLocalFileName))
- {
- KURL path;
- path.setPath(mLocalFileName);
- TQString dir=path.directory();
- KStandardDirs::makeDir(dir);
- }
-
- // Can we allow the write? We can, if the program
- // doesn't run SUID. But if it runs SUID, we must
- // check if the user would be allowed to write if
- // it wasn't SUID.
- if (checkAccess(mLocalFileName, W_OK)) {
- // File is writable
- KLockFile::Ptr lf;
-
- bool mergeLocalFile = bMerge;
- // Check if the file has been updated since.
- if (mergeLocalFile)
- {
- lf = lockFile(false); // Lock file for local file
- if (lf && lf->isLocked())
- lf = 0; // Already locked, we don't need to lock/unlock again
-
- if (lf)
- {
- lf->lock( KLockFile::LockForce );
- // But what if the locking failed? Ignore it for now...
- }
-
- TQFileInfo info(mLocalFileName);
- if ((d->localLastSize == info.size()) &&
- (d->localLastModified == info.lastModified()))
- {
- // Not changed, don't merge.
- mergeLocalFile = false;
- }
- else
- {
- // Changed...
- d->localLastModified = TQDateTime();
- d->localLastSize = 0;
- }
- }
-
- bEntriesLeft = writeConfigFile( mLocalFileName, false, mergeLocalFile );
-
- // Only if we didn't have to merge anything can we use our in-memory state
- // the next time around. Otherwise the config-file may contain entries
- // that are different from our in-memory state which means we will have to
- // do a merge from then on.
- // We do not automatically update the in-memory state with the on-disk
- // state when writing the config to disk. We only do so when
- // KCOnfig::reparseConfiguration() is called.
- // For KDE 4.0 we may wish to reconsider that.
- if (!mergeLocalFile)
- {
- TQFileInfo info(mLocalFileName);
- d->localLastModified = info.lastModified();
- d->localLastSize = info.size();
- }
- if (lf) lf->unlock();
- }
- }
-
- // only write out entries to the kdeglobals file if there are any
- // entries marked global (indicated by bEntriesLeft) and
- // the useKDEGlobals flag is set.
- if (bEntriesLeft && useKDEGlobals) {
-
- // can we allow the write? (see above)
- if (checkAccess ( mGlobalFileName, W_OK )) {
- KLockFile::Ptr lf = lockFile(true); // Lock file for global file
- if (lf && lf->isLocked())
- lf = 0; // Already locked, we don't need to lock/unlock again
-
- if (lf)
- {
- lf->lock( KLockFile::LockForce );
- // But what if the locking failed? Ignore it for now...
- }
- writeConfigFile( mGlobalFileName, true, bMerge ); // Always merge
- if (lf) lf->unlock();
- }
- }
-
-}
-
-static void writeEntries(FILE *pStream, const KEntryMap& entryMap, bool defaultGroup, bool &firstEntry, const TQCString &localeString)
-{
- // now write out all other groups.
- TQCString currentGroup;
- for (KEntryMapConstIterator aIt = entryMap.begin();
- aIt != entryMap.end(); ++aIt)
- {
- const KEntryKey &key = aIt.key();
-
- // Either proces the default group or all others
- if ((key.mGroup != "<default>") == defaultGroup)
- continue; // Skip
-
- // Skip default values and group headers.
- if ((key.bDefault) || key.mKey.isEmpty())
- continue; // Skip
-
- const KEntry &currentEntry = *aIt;
-
- KEntryMapConstIterator aTestIt = aIt;
- ++aTestIt;
- bool hasDefault = (aTestIt != entryMap.end());
- if (hasDefault)
- {
- const KEntryKey &defaultKey = aTestIt.key();
- if ((!defaultKey.bDefault) ||
- (defaultKey.mKey != key.mKey) ||
- (defaultKey.mGroup != key.mGroup) ||
- (defaultKey.bLocal != key.bLocal))
- hasDefault = false;
- }
-
-
- if (hasDefault)
- {
- // Entry had a default value
- if ((currentEntry.mValue == (*aTestIt).mValue) &&
- (currentEntry.bDeleted == (*aTestIt).bDeleted))
- continue; // Same as default, don't write.
- }
- else
- {
- // Entry had no default value.
- if (currentEntry.bDeleted)
- continue; // Don't write deleted entries if there is no default.
- }
-
- if (!defaultGroup && (currentGroup != key.mGroup)) {
- if (!firstEntry)
- fprintf(pStream, "\n");
- currentGroup = key.mGroup;
- fprintf(pStream, "[%s]\n", encodeGroup(currentGroup).data());
- }
-
- firstEntry = false;
- // it is data for a group
- fputs(encodeKey(key.mKey.data()), pStream); // Key
-
- if ( currentEntry.bNLS )
- {
- fputc('[', pStream);
- fputs(localeString.data(), pStream);
- fputc(']', pStream);
- }
-
- if (currentEntry.bDeleted)
- {
- fputs("[$d]\n", pStream); // Deleted
- }
- else
- {
- if (currentEntry.bImmutable || currentEntry.bExpand)
- {
- fputc('[', pStream);
- fputc('$', pStream);
- if (currentEntry.bImmutable)
- fputc('i', pStream);
- if (currentEntry.bExpand)
- fputc('e', pStream);
-
- fputc(']', pStream);
- }
- fputc('=', pStream);
- fputs(stringToPrintable(currentEntry.mValue).data(), pStream);
- fputc('\n', pStream);
- }
- } // for loop
-}
-
-bool TDEConfigINIBackEnd::getEntryMap(KEntryMap &aTempMap, bool bGlobal,
- TQFile *mergeFile)
-{
- bool bEntriesLeft = false;
- bFileImmutable = false;
-
- // Read entries from disk
- if (mergeFile && mergeFile->open(IO_ReadOnly))
- {
- // fill the temporary structure with entries from the file
- parseSingleConfigFile(*mergeFile, &aTempMap, bGlobal, false );
-
- if (bFileImmutable) // File has become immutable on disk
- return bEntriesLeft;
- }
-
- KEntryMap aMap = pConfig->internalEntryMap();
-
- // augment this structure with the dirty entries from the config object
- for (KEntryMapIterator aIt = aMap.begin();
- aIt != aMap.end(); ++aIt)
- {
- const KEntry &currentEntry = *aIt;
- if(aIt.key().bDefault)
- {
- aTempMap.replace(aIt.key(), currentEntry);
- continue;
- }
-
- if (mergeFile && !currentEntry.bDirty)
- continue;
-
- // only write back entries that have the same
- // "globality" as the file
- if (currentEntry.bGlobal != bGlobal)
- {
- // wrong "globality" - might have to be saved later
- bEntriesLeft = true;
- continue;
- }
-
- // put this entry from the config object into the
- // temporary map, possibly replacing an existing entry
- KEntryMapIterator aIt2 = aTempMap.find(aIt.key());
- if (aIt2 != aTempMap.end() && (*aIt2).bImmutable)
- continue; // Bail out if the on-disk entry is immutable
-
- aTempMap.insert(aIt.key(), currentEntry, true);
- } // loop
-
- return bEntriesLeft;
-}
-
-/* antlarr: KDE 4.0: make the first parameter "const TQString &" */
-bool TDEConfigINIBackEnd::writeConfigFile(TQString filename, bool bGlobal,
- bool bMerge)
-{
- // is the config object read-only?
- if (pConfig->isReadOnly())
- return true; // pretend we wrote it
-
- KEntryMap aTempMap;
- TQFile *mergeFile = (bMerge ? new TQFile(filename) : 0);
- bool bEntriesLeft = getEntryMap(aTempMap, bGlobal, mergeFile);
- delete mergeFile;
- if (bFileImmutable)
- return true; // pretend we wrote it
-
- // OK now the temporary map should be full of ALL entries.
- // write it out to disk.
-
- // Check if file exists:
- int fileMode = -1;
- bool createNew = true;
-
- KDE_struct_stat buf;
- if (KDE_stat(TQFile::encodeName(filename), &buf) == 0)
- {
- if (buf.st_uid == getuid())
- {
- // Preserve file mode if file exists and is owned by user.
- fileMode = buf.st_mode & 0777;
- }
- else
- {
- // File is not owned by user:
- // Don't create new file but write to existing file instead.
- createNew = false;
- }
- }
-
- KSaveFile *pConfigFile = 0;
- FILE *pStream = 0;
-
- if (createNew)
- {
- pConfigFile = new KSaveFile( filename, 0600 );
-
- if (pConfigFile->status() != 0)
- {
- delete pConfigFile;
- return bEntriesLeft;
- }
-
- if (!bGlobal && (fileMode == -1))
- fileMode = mFileMode;
-
- if (fileMode != -1)
- {
- fchmod(pConfigFile->handle(), fileMode);
- }
-
- pStream = pConfigFile->fstream();
- }
- else
- {
- // Open existing file.
- // We use open() to ensure that we call without O_CREAT.
- int fd = KDE_open( TQFile::encodeName(filename), O_WRONLY | O_TRUNC );
- if (fd < 0)
- {
- return bEntriesLeft;
- }
- pStream = KDE_fdopen( fd, "w");
- if (!pStream)
- {
- close(fd);
- return bEntriesLeft;
- }
- }
-
- writeEntries(pStream, aTempMap);
-
- if (pConfigFile)
- {
- bool bEmptyFile = (ftell(pStream) == 0);
- if ( bEmptyFile && ((fileMode == -1) || (fileMode == 0600)) )
- {
- // File is empty and doesn't have special permissions: delete it.
- ::unlink(TQFile::encodeName(filename));
- pConfigFile->abort();
- }
- else
- {
- // Normal case: Close the file
- pConfigFile->close();
- }
- delete pConfigFile;
- }
- else
- {
- fclose(pStream);
- }
-
- return bEntriesLeft;
-}
-
-void TDEConfigINIBackEnd::writeEntries(FILE *pStream, const KEntryMap &aTempMap)
-{
- bool firstEntry = true;
-
- // Write default group
- ::writeEntries(pStream, aTempMap, true, firstEntry, localeString);
-
- // Write all other groups
- ::writeEntries(pStream, aTempMap, false, firstEntry, localeString);
-}
-
-void TDEConfigBackEnd::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-void TDEConfigINIBackEnd::virtual_hook( int id, void* data )
-{ TDEConfigBackEnd::virtual_hook( id, data ); }
-
-bool TDEConfigBackEnd::checkConfigFilesWritable(bool warnUser)
-{
- // WARNING: Do NOT use the event loop as it may not exist at this time.
- bool allWritable = true;
- TQString errorMsg;
- if ( !mLocalFileName.isEmpty() && !bFileImmutable && !checkAccess(mLocalFileName,W_OK) )
- {
- errorMsg = i18n("Will not save configuration.\n");
- allWritable = false;
- errorMsg += i18n("Configuration file \"%1\" not writable.\n").arg(mLocalFileName);
- }
- // We do not have an immutability flag for kdeglobals. However, making kdeglobals mutable while making
- // the local config file immutable is senseless.
- if ( !mGlobalFileName.isEmpty() && useKDEGlobals && !bFileImmutable && !checkAccess(mGlobalFileName,W_OK) )
- {
- if ( errorMsg.isEmpty() )
- errorMsg = i18n("Will not save configuration.\n");
- errorMsg += i18n("Configuration file \"%1\" not writable.\n").arg(mGlobalFileName);
- allWritable = false;
- }
-
- if (warnUser && !allWritable)
- {
- // Note: We don't ask the user if we should not ask this question again because we can't save the answer.
- errorMsg += i18n("Please contact your system administrator.");
- TQString cmdToExec = KStandardDirs::findExe(TQString("kdialog"));
- TDEApplication *app = kapp;
- if (!cmdToExec.isEmpty() && app)
- {
- TDEProcess lprocess;
- lprocess << cmdToExec << "--title" << app->instanceName() << "--msgbox" << TQCString(errorMsg.local8Bit());
- lprocess.start( TDEProcess::Block );
- }
- }
- return allWritable;
-}
diff --git a/tdecore/kconfigbackend.h b/tdecore/kconfigbackend.h
deleted file mode 100644
index 87ddfa3bb..000000000
--- a/tdecore/kconfigbackend.h
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Preston Brown <pbrown@kde.org>
- Portions copyright (c) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KCONFIGBACKEND_H
-#define _KCONFIGBACKEND_H
-
-#include "kconfigdata.h"
-#include <kconfigbase.h>
-#include <klockfile.h>
-#include <klocale.h>
-#include "tdelibs_export.h"
-
-class TQFile;
-class TDEConfigBackEndPrivate;
-
-/**
- * Abstract base class for KDE configuration file loading/saving.
- *
- * This class forms the base for all classes that implement some
- * manner of loading/saving to configuration files. It is an
- * abstract base class, meaning that you cannot directly instantiate
- * objects of this class. As of right now, the only back end available
- * is one to read/write to INI-style files, but in the future, other
- * formats may be available, such as XML or a database.
- *
- * @author Preston Brown <pbrown@kde.org>,
- * Matthias Kalle Dalheimer <kalle@kde.org>
- * @short KDE Configuration file loading/saving abstract base class
- */
-class TDECORE_EXPORT TDEConfigBackEnd
-{
- friend class TDEConfig;
- friend class KSharedConfig;
-public:
- /**
- * Constructs a configuration back end.
- *
- * @param _config Specifies the configuration object which values
- * will be passed to as they are read, or from where values
- * to be written to will be obtained from.
- * @param _fileName The name of the file in which config
- * data is stored. All registered configuration directories
- * will be looked in in order of decreasing relevance.
- * @param _resType the resource type of the fileName specified, _if_
- * it is not an absolute path (otherwise this parameter is ignored).
- * @param _useKDEGlobals If true, the user's system-wide kdeglobals file
- * will be imported into the config object. If false, only
- * the filename specified will be dealt with.
- */
- TDEConfigBackEnd(TDEConfigBase *_config, const TQString &_fileName,
- const char * _resType, bool _useKDEGlobals);
-
- /**
- * Destructs the configuration backend.
- */
- virtual ~TDEConfigBackEnd();
-
- /**
- * Parses all configuration files for a configuration object. This
- * method must be reimplemented by the derived classes.
- *
- * @returns Whether or not parsing was successful.
- */
- virtual bool parseConfigFiles() = 0;
-
- /**
- * Writes configuration data to file(s). This method must be
- * reimplemented by the derived classes.
- *
- * @param bMerge Specifies whether the old config file already
- * on disk should be merged in with the data in memory. If true,
- * data is read off the disk and merged. If false, the on-disk
- * file is removed and only in-memory data is written out.
- */
- virtual void sync(bool bMerge = true) = 0;
-
- /**
- * Changes the filenames associated with this back end. You should
- * probably reparse your config info after doing this.
- *
- * @param _fileName the new filename to use
- * @param _resType the resource type of the fileName specified, _if_
- * it is not an absolute path (otherwise this parameter is ignored).
- * @param _useKDEGlobals specifies whether or not to also parse the
- * global KDE configuration files.
- */
- void changeFileName(const TQString &_fileName, const char * _resType,
- bool _useKDEGlobals);
-
- /**
- * Returns the state of the app-config object.
- *
- * @see TDEConfig::getConfigState
- */
- virtual TDEConfigBase::ConfigState getConfigState() const
- { return mConfigState; }
-
- /**
- * Returns the filename as passed to the constructor.
- * @return the filename as passed to the constructor.
- */
- TQString fileName() const { return mfileName; }
-
- /**
- * Returns the resource type as passed to the constructor.
- * @return the resource type as passed to the constructor.
- */
- const char * resource() const { return resType; }
-
- /**
- * Set the locale string that defines the current language.
- * @param _localeString the identifier of the language
- * @see KLocale
- */
- void setLocaleString(const TQCString &_localeString) { localeString = _localeString; }
-
- /**
- * Set the file mode for newly created files.
- * @param mode the filemode (as in chmod)
- */
- void setFileWriteMode(int mode);
-
- /**
- * Check whether the config files are writable.
- * @param warnUser Warn the user if the configuration files are not writable.
- * @return Indicates that all of the configuration files used are writable.
- * @since 3.2
- */
- bool checkConfigFilesWritable(bool warnUser);
-
- /**
- * Returns a lock file object for the configuration file
- * @param bGlobal If true, returns a lock file object for kdeglobals
- * @since 3.3
- */
- KLockFile::Ptr lockFile( bool bGlobal = false );
-
-#ifdef KDE_NO_COMPAT
-private:
-#endif
- /**
- * @deprecated Use fileName() instead
- */
- KDE_DEPRECATED TQString filename() const { return mfileName; }
-
-protected:
- TDEConfigBase *pConfig;
-
- TQString mfileName;
- TQCString resType;
- bool useKDEGlobals : 1;
- bool bFileImmutable : 1;
- TQCString localeString;
- TQString mLocalFileName;
- TQString mGlobalFileName;
- TDEConfigBase::ConfigState mConfigState;
- int mFileMode;
-
-protected:
- virtual void virtual_hook( int id, void* data );
-protected:
- class TDEConfigBackEndPrivate;
- TDEConfigBackEndPrivate *d;
-};
-
-
-/**
- * Class for KDE INI-style configuration file loading/saving.
- *
- * @author Preston Brown <pbrown@kde.org>,
- * Matthias Kalle Dalheimer <kalle@kde.org>
- */
-class TDECORE_EXPORT TDEConfigINIBackEnd : public TDEConfigBackEnd
-{
-
-public:
- /**
- * Constructs an ini-style configuration back end.
- *
- * @param _config Specifies the configuration object which values
- * will be passed to as they are read, or from where values
- * to be written to will be obtained from.
- * @param _fileName The name of the file in which config
- * data is stored. All registered configuration directories
- * will be looked in in order of decreasing relevance.
- * @param _resType the resource type of the fileName specified, _if_
- * it is not an absolute path (otherwise this parameter is ignored).
- * @param _useKDEGlobals If true, the user's system-wide kdeglobals file
- * will be imported into the config object. If false, only
- * the filename specified will be dealt with.
- */
- TDEConfigINIBackEnd(TDEConfigBase *_config, const TQString &_fileName,
- const char * _resType, bool _useKDEGlobals = true)
- : TDEConfigBackEnd(_config, _fileName, _resType, _useKDEGlobals) {}
-
- /**
- * Destructs the configuration backend.
- */
- virtual ~TDEConfigINIBackEnd() {}
-
- /**
- * Parses all INI-style configuration files for a config object.
- *
- * @returns Whether or not parsing was successful.
- */
- bool parseConfigFiles();
-
- /**
- * Writes configuration data to file(s).
- * @param bMerge Specifies whether the old config file already
- * on disk should be merged in with the data in memory. If true,
- * data is read off the disk and merged. If false, the on-disk
- * file is removed and only in-memory data is written out.
- */
- virtual void sync(bool bMerge = true);
-
-protected:
- /**
- * Parses one configuration file.
- *
- * @param rFile The configuration file to parse
- * @param pWriteBackMap If specified, points to a KEntryMap where
- * the data read from the file should be stored, instead of
- * inserting them directly into the configuration object.
- * Use this area as a "scratchpad" when you need to know what is
- * on disk but don't want to effect the configuration object.
- * @param bGlobal Specifies whether entries should be marked as
- * belonging to the global KDE configuration file rather
- * than the application-specific KDE configuration file(s).
- * @param bDefault Specifies whether entries should be marked as
- * being default values.
- */
- void parseSingleConfigFile(TQFile& rFile, KEntryMap *pWriteBackMap = 0L,
- bool bGlobal = false, bool bDefault = false);
-
- // Kubuntu patch, 2006-08-03
- // looks up a key in with KLocale
- // see https://launchpad.net/distros/ubuntu/+spec/langpacks-desktopfiles-kde
- void translateKey(KLocale& locale, TQCString currentGroup, TQCString key);
-
- /**
- * Writes configuration file back.
- *
- * @param filename The name of the file to write.
- * @param bGlobal Specifies whether to write only entries which
- * are marked as belonging to the global KDE config file.
- * If this is false, it skips those entries.
- * @param bMerge Specifies whether the old config file already
- * on disk should be merged in with the data in memory. If true,
- * data is read off the disk and merged. If false, the on-disk
- * file is removed and only in-memory data is written out.
- * @return Whether some entries are left to be written to other
- * files.
- */
- bool writeConfigFile(TQString filename, bool bGlobal = false, bool bMerge = true);
-
- /** Get the entry map.
- *
- * @param map the entries will be stored in this object.
- * @param bGlobal Specifies whether to get only entries which
- * are marked as belonging to the global KDE config file.
- * If this is false, it skips those entries.
- * @param mergeFile if not null, the dirty entries for this file will
- * be merged.
- *
- * @return Whether there will be some entries left for writing to other
- * files.
- */
- bool getEntryMap(KEntryMap &map, bool bGlobal, TQFile *mergeFile);
-
- /** Write the entries in @e aTempMap to the file stream.*/
- void writeEntries(FILE *pStream, const KEntryMap &aTempMap);
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class TDEConfigINIBackEndPrivate;
- TDEConfigINIBackEndPrivate *not_d;
-};
-
-#endif
diff --git a/tdecore/kconfigbase.cpp b/tdecore/kconfigbase.cpp
deleted file mode 100644
index e65338c50..000000000
--- a/tdecore/kconfigbase.cpp
+++ /dev/null
@@ -1,1937 +0,0 @@
-// -*- c-basic-offset: 2 -*-
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Preston Brown <pbrown@kde.org>
- Copyright (c) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <stdlib.h>
-#include <string.h>
-
-#include <tqfile.h>
-#include <tqdir.h>
-#include <tqtextstream.h>
-
-#include <kapplication.h>
-#include <kglobal.h>
-#include <klocale.h>
-#include <kcharsets.h>
-
-#include "kconfigbase.h"
-#include "kconfigbackend.h"
-#include "kdebug.h"
-#include "kstandarddirs.h"
-#include "kstringhandler.h"
-
-class TDEConfigBase::TDEConfigBasePrivate
-{
-public:
- TDEConfigBasePrivate() : readDefaults(false) { };
-
-public:
- bool readDefaults;
-};
-
-TDEConfigBase::TDEConfigBase()
- : backEnd(0L), bDirty(false), bLocaleInitialized(false),
- bReadOnly(false), bExpand(false), d(0)
-{
- setGroup(TQString::null);
-}
-
-TDEConfigBase::~TDEConfigBase()
-{
- delete d;
-}
-
-void TDEConfigBase::setLocale()
-{
- bLocaleInitialized = true;
-
- if (TDEGlobal::locale())
- aLocaleString = TDEGlobal::locale()->language().utf8();
- else
- aLocaleString = KLocale::defaultLanguage().utf8();
- if (backEnd)
- backEnd->setLocaleString(aLocaleString);
-}
-
-TQString TDEConfigBase::locale() const
-{
- return TQString::fromUtf8(aLocaleString);
-}
-
-void TDEConfigBase::setGroup( const TQString& group )
-{
- if ( group.isEmpty() )
- mGroup = "<default>";
- else
- mGroup = group.utf8();
-}
-
-void TDEConfigBase::setGroup( const char *pGroup )
-{
- setGroup(TQCString(pGroup));
-}
-
-void TDEConfigBase::setGroup( const TQCString &group )
-{
- if ( group.isEmpty() )
- mGroup = "<default>";
- else
- mGroup = group;
-}
-
-TQString TDEConfigBase::group() const {
- return TQString::fromUtf8(mGroup);
-}
-
-void TDEConfigBase::setDesktopGroup()
-{
- mGroup = "Desktop Entry";
-}
-
-bool TDEConfigBase::hasKey(const TQString &key) const
-{
- return hasKey(key.utf8().data());
-}
-
-bool TDEConfigBase::hasKey(const char *pKey) const
-{
- KEntryKey aEntryKey(mGroup, 0);
- aEntryKey.c_key = pKey;
- aEntryKey.bDefault = readDefaults();
-
- if (!locale().isNull()) {
- // try the localized key first
- aEntryKey.bLocal = true;
- KEntry entry = lookupData(aEntryKey);
- if (!entry.mValue.isNull())
- return true;
- aEntryKey.bLocal = false;
- }
-
- // try the non-localized version
- KEntry entry = lookupData(aEntryKey);
- return !entry.mValue.isNull();
-}
-
-bool TDEConfigBase::hasTranslatedKey(const char* pKey) const
-{
- KEntryKey aEntryKey(mGroup, 0);
- aEntryKey.c_key = pKey;
- aEntryKey.bDefault = readDefaults();
-
- if (!locale().isNull()) {
- // try the localized key first
- aEntryKey.bLocal = true;
- KEntry entry = lookupData(aEntryKey);
- if (!entry.mValue.isNull())
- return true;
- aEntryKey.bLocal = false;
- }
-
- return false;
-}
-
-bool TDEConfigBase::hasGroup(const TQString &group) const
-{
- return internalHasGroup( group.utf8());
-}
-
-bool TDEConfigBase::hasGroup(const char *_pGroup) const
-{
- return internalHasGroup( TQCString(_pGroup));
-}
-
-bool TDEConfigBase::hasGroup(const TQCString &_pGroup) const
-{
- return internalHasGroup( _pGroup);
-}
-
-bool TDEConfigBase::isImmutable() const
-{
- return (getConfigState() != ReadWrite);
-}
-
-bool TDEConfigBase::groupIsImmutable(const TQString &group) const
-{
- if (getConfigState() != ReadWrite)
- return true;
-
- KEntryKey groupKey(group.utf8(), 0);
- KEntry entry = lookupData(groupKey);
- return entry.bImmutable;
-}
-
-bool TDEConfigBase::entryIsImmutable(const TQString &key) const
-{
- if (getConfigState() != ReadWrite)
- return true;
-
- KEntryKey entryKey(mGroup, 0);
- KEntry aEntryData = lookupData(entryKey); // Group
- if (aEntryData.bImmutable)
- return true;
-
- TQCString utf8_key = key.utf8();
- entryKey.c_key = utf8_key.data();
- aEntryData = lookupData(entryKey); // Normal entry
- if (aEntryData.bImmutable)
- return true;
-
- entryKey.bLocal = true;
- aEntryData = lookupData(entryKey); // Localized entry
- return aEntryData.bImmutable;
-}
-
-
-TQString TDEConfigBase::readEntryUntranslated( const TQString& pKey,
- const TQString& aDefault ) const
-{
- return TDEConfigBase::readEntryUntranslated(pKey.utf8().data(), aDefault);
-}
-
-
-TQString TDEConfigBase::readEntryUntranslated( const char *pKey,
- const TQString& aDefault ) const
-{
- TQCString result = readEntryUtf8(pKey);
- if (result.isNull())
- return aDefault;
- return TQString::fromUtf8(result);
-}
-
-
-TQString TDEConfigBase::readEntry( const TQString& pKey,
- const TQString& aDefault ) const
-{
- return TDEConfigBase::readEntry(pKey.utf8().data(), aDefault);
-}
-
-TQString TDEConfigBase::readEntry( const char *pKey,
- const TQString& aDefault ) const
-{
- // we need to access _locale instead of the method locale()
- // because calling locale() will create a locale object if it
- // doesn't exist, which requires TDEConfig, which will create a infinite
- // loop, and nobody likes those.
- if (!bLocaleInitialized && TDEGlobal::_locale) {
- // get around const'ness.
- TDEConfigBase *that = const_cast<TDEConfigBase *>(this);
- that->setLocale();
- }
-
- TQString aValue;
-
- bool expand = false;
- // construct a localized version of the key
- // try the localized key first
- KEntry aEntryData;
- KEntryKey entryKey(mGroup, 0);
- entryKey.c_key = pKey;
- entryKey.bDefault = readDefaults();
- entryKey.bLocal = true;
- aEntryData = lookupData(entryKey);
- if (!aEntryData.mValue.isNull()) {
- // for GNOME .desktop
- aValue = KStringHandler::from8Bit( aEntryData.mValue.data() );
- expand = aEntryData.bExpand;
- } else {
- entryKey.bLocal = false;
- aEntryData = lookupData(entryKey);
- if (!aEntryData.mValue.isNull()) {
- aValue = TQString::fromUtf8(aEntryData.mValue.data());
- if (aValue.isNull())
- {
- static const TQString &emptyString = TDEGlobal::staticQString("");
- aValue = emptyString;
- }
- expand = aEntryData.bExpand;
- } else {
- aValue = aDefault;
- }
- }
-
- // only do dollar expansion if so desired
- if( expand || bExpand )
- {
- // check for environment variables and make necessary translations
- int nDollarPos = aValue.find( '$' );
-
- while( nDollarPos != -1 && nDollarPos+1 < static_cast<int>(aValue.length())) {
- // there is at least one $
- if( (aValue)[nDollarPos+1] == '(' ) {
- uint nEndPos = nDollarPos+1;
- // the next character is no $
- while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!=')') )
- nEndPos++;
- nEndPos++;
- TQString cmd = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
-
- TQString result;
- FILE *fs = popen(TQFile::encodeName(cmd).data(), "r");
- if (fs)
- {
- {
- TQTextStream ts(fs, IO_ReadOnly);
- result = ts.read().stripWhiteSpace();
- }
- pclose(fs);
- }
- aValue.replace( nDollarPos, nEndPos-nDollarPos, result );
- } else if( (aValue)[nDollarPos+1] != '$' ) {
- uint nEndPos = nDollarPos+1;
- // the next character is no $
- TQString aVarName;
- if (aValue[nEndPos]=='{')
- {
- while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') )
- nEndPos++;
- nEndPos++;
- aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
- }
- else
- {
- while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber()
- || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' ) )
- nEndPos++;
- aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 );
- }
- const char* pEnv = 0;
- if (!aVarName.isEmpty())
- pEnv = getenv( aVarName.ascii() );
- if( pEnv ) {
- // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
- // A environment variables may contain values in 8bit
- // locale cpecified encoding or in UTF8 encoding.
- aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) );
- } else
- aValue.remove( nDollarPos, nEndPos-nDollarPos );
- } else {
- // remove one of the dollar signs
- aValue.remove( nDollarPos, 1 );
- nDollarPos++;
- }
- nDollarPos = aValue.find( '$', nDollarPos );
- }
- }
-
- return aValue;
-}
-
-TQCString TDEConfigBase::readEntryUtf8( const char *pKey) const
-{
- // We don't try the localized key
- KEntryKey entryKey(mGroup, 0);
- entryKey.bDefault = readDefaults();
- entryKey.c_key = pKey;
- KEntry aEntryData = lookupData(entryKey);
- if (aEntryData.bExpand)
- {
- // We need to do fancy, take the slow route.
- return readEntry(pKey, TQString::null).utf8();
- }
- return aEntryData.mValue;
-}
-
-TQVariant TDEConfigBase::readPropertyEntry( const TQString& pKey,
- TQVariant::Type type ) const
-{
- return readPropertyEntry(pKey.utf8().data(), type);
-}
-
-TQVariant TDEConfigBase::readPropertyEntry( const char *pKey,
- TQVariant::Type type ) const
-{
- TQVariant va;
- if ( !hasKey( pKey ) ) return va;
- (void)va.cast(type);
- return readPropertyEntry(pKey, va);
-}
-
-TQVariant TDEConfigBase::readPropertyEntry( const TQString& pKey,
- const TQVariant &aDefault ) const
-{
- return readPropertyEntry(pKey.utf8().data(), aDefault);
-}
-
-TQVariant TDEConfigBase::readPropertyEntry( const char *pKey,
- const TQVariant &aDefault ) const
-{
- if ( !hasKey( pKey ) ) return aDefault;
-
- TQVariant tmp = aDefault;
-
- switch( aDefault.type() )
- {
- case TQVariant::Invalid:
- return TQVariant();
- case TQVariant::String:
- return TQVariant( readEntry( pKey, aDefault.toString() ) );
- case TQVariant::StringList:
- return TQVariant( readListEntry( pKey ) );
- case TQVariant::List: {
- TQStringList strList = readListEntry( pKey );
- TQStringList::ConstIterator it = strList.begin();
- TQStringList::ConstIterator end = strList.end();
- TQValueList<TQVariant> list;
-
- for (; it != end; ++it ) {
- tmp = *it;
- list.append( tmp );
- }
- return TQVariant( list );
- }
- case TQVariant::Font:
- return TQVariant( readFontEntry( pKey, &tmp.asFont() ) );
- case TQVariant::Point:
- return TQVariant( readPointEntry( pKey, &tmp.asPoint() ) );
- case TQVariant::Rect:
- return TQVariant( readRectEntry( pKey, &tmp.asRect() ) );
- case TQVariant::Size:
- return TQVariant( readSizeEntry( pKey, &tmp.asSize() ) );
- case TQVariant::Color:
- return TQVariant( readColorEntry( pKey, &tmp.asColor() ) );
- case TQVariant::Int:
- return TQVariant( readNumEntry( pKey, aDefault.toInt() ) );
- case TQVariant::UInt:
- return TQVariant( readUnsignedNumEntry( pKey, aDefault.toUInt() ) );
- case TQVariant::LongLong:
- return TQVariant( readNum64Entry( pKey, aDefault.toLongLong() ) );
- case TQVariant::ULongLong:
- return TQVariant( readUnsignedNum64Entry( pKey, aDefault.toULongLong() ) );
- case TQVariant::Bool:
- return TQVariant( readBoolEntry( pKey, aDefault.toBool() ), 0 );
- case TQVariant::Double:
- return TQVariant( readDoubleNumEntry( pKey, aDefault.toDouble() ) );
- case TQVariant::DateTime:
- return TQVariant( readDateTimeEntry( pKey, &tmp.asDateTime() ) );
- case TQVariant::Date:
- return TQVariant(TQT_TQDATE_OBJECT(readDateTimeEntry( pKey, &tmp.asDateTime() ).date()));
-
- case TQVariant::Pixmap:
- case TQVariant::Image:
- case TQVariant::Brush:
- case TQVariant::Palette:
- case TQVariant::ColorGroup:
- case TQVariant::Map:
- case TQVariant::IconSet:
- case TQVariant::CString:
- case TQVariant::PointArray:
- case TQVariant::Region:
- case TQVariant::Bitmap:
- case TQVariant::Cursor:
- case TQVariant::SizePolicy:
- case TQVariant::Time:
-#ifdef USE_QT3
- case TQVariant::ByteArray:
-#endif // USE_QT3
- case TQVariant::BitArray:
- case TQVariant::KeySequence:
- case TQVariant::Pen:
-#ifdef USE_QT4
- case TQVariant::Char:
- case TQVariant::Url:
- case TQVariant::Locale:
- case TQVariant::RectF:
- case TQVariant::SizeF:
- case TQVariant::Line:
- case TQVariant::LineF:
- case TQVariant::PointF:
- case TQVariant::RegExp:
- case TQVariant::Hash:
- case TQVariant::TextLength:
- case QVariant::TextFormat:
- case TQVariant::Matrix:
- case TQVariant::Transform:
- case TQVariant::Matrix4x4:
- case TQVariant::Vector2D:
- case TQVariant::Vector3D:
- case TQVariant::Vector4D:
- case TQVariant::Quaternion:
- case TQVariant::UserType:
-#endif // USE_QT4
- break;
- }
-
- Q_ASSERT( 0 );
- return TQVariant();
-}
-
-int TDEConfigBase::readListEntry( const TQString& pKey,
- TQStrList &list, char sep ) const
-{
- return readListEntry(pKey.utf8().data(), list, sep);
-}
-
-int TDEConfigBase::readListEntry( const char *pKey,
- TQStrList &list, char sep ) const
-{
- if( !hasKey( pKey ) )
- return 0;
-
- TQCString str_list = readEntryUtf8( pKey );
- if (str_list.isEmpty())
- return 0;
-
- list.clear();
- TQCString value = "";
- int len = str_list.length();
-
- for (int i = 0; i < len; i++) {
- if (str_list[i] != sep && str_list[i] != '\\') {
- value += str_list[i];
- continue;
- }
- if (str_list[i] == '\\') {
- i++;
- if ( i < len )
- value += str_list[i];
- continue;
- }
- // if we fell through to here, we are at a separator. Append
- // contents of value to the list
- // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
- // A TQStrList may contain values in 8bit locale cpecified
- // encoding
- list.append( value );
- value.truncate(0);
- }
-
- if ( str_list[len-1] != sep || ( len > 1 && str_list[len-2] == '\\' ) )
- list.append( value );
- return list.count();
-}
-
-TQStringList TDEConfigBase::readListEntry( const TQString& pKey, char sep ) const
-{
- return readListEntry(pKey.utf8().data(), sep);
-}
-
-TQStringList TDEConfigBase::readListEntry( const char *pKey, char sep ) const
-{
- static const TQString& emptyString = TDEGlobal::staticQString("");
-
- TQStringList list;
- if( !hasKey( pKey ) )
- return list;
- TQString str_list = readEntry( pKey );
- if( str_list.isEmpty() )
- return list;
- TQString value(emptyString);
- int len = str_list.length();
- // obviously too big, but faster than letting each += resize the string.
- value.reserve( len );
- for( int i = 0; i < len; i++ )
- {
- if( str_list[i] != sep && str_list[i] != '\\' )
- {
- value += str_list[i];
- continue;
- }
- if( str_list[i] == '\\' )
- {
- i++;
- if ( i < len )
- value += str_list[i];
- continue;
- }
- TQString finalvalue( value );
- finalvalue.squeeze();
- list.append( finalvalue );
- value.truncate( 0 );
- }
- if ( str_list[len-1] != sep || ( len > 1 && str_list[len-2] == '\\' ) )
- {
- value.squeeze();
- list.append( value );
- }
- return list;
-}
-
-TQStringList TDEConfigBase::readListEntry( const char* pKey, const TQStringList& aDefault,
- char sep ) const
-{
- if ( !hasKey( pKey ) )
- return aDefault;
- else
- return readListEntry( pKey, sep );
-}
-
-TQValueList<int> TDEConfigBase::readIntListEntry( const TQString& pKey ) const
-{
- return readIntListEntry(pKey.utf8().data());
-}
-
-TQValueList<int> TDEConfigBase::readIntListEntry( const char *pKey ) const
-{
- TQStringList strlist = readListEntry(pKey);
- TQValueList<int> list;
- TQStringList::ConstIterator end(strlist.end());
- for (TQStringList::ConstIterator it = strlist.begin(); it != end; ++it)
- // I do not check if the toInt failed because I consider the number of items
- // more important than their value
- list << (*it).toInt();
-
- return list;
-}
-
-TQString TDEConfigBase::readPathEntry( const TQString& pKey, const TQString& pDefault ) const
-{
- return readPathEntry(pKey.utf8().data(), pDefault);
-}
-
-TQString TDEConfigBase::readPathEntry( const char *pKey, const TQString& pDefault ) const
-{
- const bool bExpandSave = bExpand;
- bExpand = true;
- TQString aValue = readEntry( pKey, pDefault );
- bExpand = bExpandSave;
- return aValue;
-}
-
-TQStringList TDEConfigBase::readPathListEntry( const TQString& pKey, char sep ) const
-{
- return readPathListEntry(pKey.utf8().data(), sep);
-}
-
-TQStringList TDEConfigBase::readPathListEntry( const char *pKey, char sep ) const
-{
- const bool bExpandSave = bExpand;
- bExpand = true;
- TQStringList aValue = readListEntry( pKey, sep );
- bExpand = bExpandSave;
- return aValue;
-}
-
-int TDEConfigBase::readNumEntry( const TQString& pKey, int nDefault) const
-{
- return readNumEntry(pKey.utf8().data(), nDefault);
-}
-
-int TDEConfigBase::readNumEntry( const char *pKey, int nDefault) const
-{
- TQCString aValue = readEntryUtf8( pKey );
- if( aValue.isNull() )
- return nDefault;
- else if( aValue == "true" || aValue == "on" || aValue == "yes" )
- return 1;
- else
- {
- bool ok;
- int rc = aValue.toInt( &ok );
- return( ok ? rc : nDefault );
- }
-}
-
-
-unsigned int TDEConfigBase::readUnsignedNumEntry( const TQString& pKey, unsigned int nDefault) const
-{
- return readUnsignedNumEntry(pKey.utf8().data(), nDefault);
-}
-
-unsigned int TDEConfigBase::readUnsignedNumEntry( const char *pKey, unsigned int nDefault) const
-{
- TQCString aValue = readEntryUtf8( pKey );
- if( aValue.isNull() )
- return nDefault;
- else
- {
- bool ok;
- unsigned int rc = aValue.toUInt( &ok );
- return( ok ? rc : nDefault );
- }
-}
-
-
-long TDEConfigBase::readLongNumEntry( const TQString& pKey, long nDefault) const
-{
- return readLongNumEntry(pKey.utf8().data(), nDefault);
-}
-
-long TDEConfigBase::readLongNumEntry( const char *pKey, long nDefault) const
-{
- TQCString aValue = readEntryUtf8( pKey );
- if( aValue.isNull() )
- return nDefault;
- else
- {
- bool ok;
- long rc = aValue.toLong( &ok );
- return( ok ? rc : nDefault );
- }
-}
-
-
-unsigned long TDEConfigBase::readUnsignedLongNumEntry( const TQString& pKey, unsigned long nDefault) const
-{
- return readUnsignedLongNumEntry(pKey.utf8().data(), nDefault);
-}
-
-unsigned long TDEConfigBase::readUnsignedLongNumEntry( const char *pKey, unsigned long nDefault) const
-{
- TQCString aValue = readEntryUtf8( pKey );
- if( aValue.isNull() )
- return nDefault;
- else
- {
- bool ok;
- unsigned long rc = aValue.toULong( &ok );
- return( ok ? rc : nDefault );
- }
-}
-
-TQ_INT64 TDEConfigBase::readNum64Entry( const TQString& pKey, TQ_INT64 nDefault) const
-{
- return readNum64Entry(pKey.utf8().data(), nDefault);
-}
-
-TQ_INT64 TDEConfigBase::readNum64Entry( const char *pKey, TQ_INT64 nDefault) const
-{
- // Note that TQCString::toLongLong() is missing, we muse use a TQString instead.
- TQString aValue = readEntry( pKey );
- if( aValue.isNull() )
- return nDefault;
- else
- {
- bool ok;
- TQ_INT64 rc = aValue.toLongLong( &ok );
- return( ok ? rc : nDefault );
- }
-}
-
-
-TQ_UINT64 TDEConfigBase::readUnsignedNum64Entry( const TQString& pKey, TQ_UINT64 nDefault) const
-{
- return readUnsignedNum64Entry(pKey.utf8().data(), nDefault);
-}
-
-TQ_UINT64 TDEConfigBase::readUnsignedNum64Entry( const char *pKey, TQ_UINT64 nDefault) const
-{
- // Note that TQCString::toULongLong() is missing, we muse use a TQString instead.
- TQString aValue = readEntry( pKey );
- if( aValue.isNull() )
- return nDefault;
- else
- {
- bool ok;
- TQ_UINT64 rc = aValue.toULongLong( &ok );
- return( ok ? rc : nDefault );
- }
-}
-
-double TDEConfigBase::readDoubleNumEntry( const TQString& pKey, double nDefault) const
-{
- return readDoubleNumEntry(pKey.utf8().data(), nDefault);
-}
-
-double TDEConfigBase::readDoubleNumEntry( const char *pKey, double nDefault) const
-{
- TQCString aValue = readEntryUtf8( pKey );
- if( aValue.isNull() )
- return nDefault;
- else
- {
- bool ok;
- double rc = aValue.toDouble( &ok );
- return( ok ? rc : nDefault );
- }
-}
-
-
-bool TDEConfigBase::readBoolEntry( const TQString& pKey, bool bDefault ) const
-{
- return readBoolEntry(pKey.utf8().data(), bDefault);
-}
-
-bool TDEConfigBase::readBoolEntry( const char *pKey, bool bDefault ) const
-{
- TQCString aValue = readEntryUtf8( pKey );
-
- if( aValue.isNull() )
- return bDefault;
- else
- {
- if( aValue == "true" || aValue == "on" || aValue == "yes" || aValue == "1" )
- return true;
- else
- {
- bool bOK;
- int val = aValue.toInt( &bOK );
- if( bOK && val != 0 )
- return true;
- else
- return false;
- }
- }
-}
-
-TQFont TDEConfigBase::readFontEntry( const TQString& pKey, const TQFont* pDefault ) const
-{
- return readFontEntry(pKey.utf8().data(), pDefault);
-}
-
-TQFont TDEConfigBase::readFontEntry( const char *pKey, const TQFont* pDefault ) const
-{
- TQFont aRetFont;
-
- TQString aValue = readEntry( pKey );
- if( !aValue.isNull() ) {
- if ( aValue.contains( ',' ) > 5 ) {
- // KDE3 and upwards entry
- if ( !aRetFont.fromString( aValue ) && pDefault )
- aRetFont = *pDefault;
- }
- else {
- // backward compatibility with older font formats
- // ### remove KDE 3.1 ?
- // find first part (font family)
- int nIndex = aValue.find( ',' );
- if( nIndex == -1 ){
- if( pDefault )
- aRetFont = *pDefault;
- return aRetFont;
- }
- aRetFont.setFamily( aValue.left( nIndex ) );
-
- // find second part (point size)
- int nOldIndex = nIndex;
- nIndex = aValue.find( ',', nOldIndex+1 );
- if( nIndex == -1 ){
- if( pDefault )
- aRetFont = *pDefault;
- return aRetFont;
- }
-
- aRetFont.setPointSize( aValue.mid( nOldIndex+1,
- nIndex-nOldIndex-1 ).toInt() );
-
- // find third part (style hint)
- nOldIndex = nIndex;
- nIndex = aValue.find( ',', nOldIndex+1 );
-
- if( nIndex == -1 ){
- if( pDefault )
- aRetFont = *pDefault;
- return aRetFont;
- }
-
- aRetFont.setStyleHint( (TQFont::StyleHint)aValue.mid( nOldIndex+1, nIndex-nOldIndex-1 ).toUInt() );
-
- // find fourth part (char set)
- nOldIndex = nIndex;
- nIndex = aValue.find( ',', nOldIndex+1 );
-
- if( nIndex == -1 ){
- if( pDefault )
- aRetFont = *pDefault;
- return aRetFont;
- }
-
- TQString chStr=aValue.mid( nOldIndex+1,
- nIndex-nOldIndex-1 );
- // find fifth part (weight)
- nOldIndex = nIndex;
- nIndex = aValue.find( ',', nOldIndex+1 );
-
- if( nIndex == -1 ){
- if( pDefault )
- aRetFont = *pDefault;
- return aRetFont;
- }
-
- aRetFont.setWeight( aValue.mid( nOldIndex+1,
- nIndex-nOldIndex-1 ).toUInt() );
-
- // find sixth part (font bits)
- uint nFontBits = aValue.right( aValue.length()-nIndex-1 ).toUInt();
-
- aRetFont.setItalic( nFontBits & 0x01 );
- aRetFont.setUnderline( nFontBits & 0x02 );
- aRetFont.setStrikeOut( nFontBits & 0x04 );
- aRetFont.setFixedPitch( nFontBits & 0x08 );
- aRetFont.setRawMode( nFontBits & 0x20 );
- }
- }
- else
- {
- if( pDefault )
- aRetFont = *pDefault;
- }
-
- return aRetFont;
-}
-
-
-TQRect TDEConfigBase::readRectEntry( const TQString& pKey, const TQRect* pDefault ) const
-{
- return readRectEntry(pKey.utf8().data(), pDefault);
-}
-
-TQRect TDEConfigBase::readRectEntry( const char *pKey, const TQRect* pDefault ) const
-{
- TQCString aValue = readEntryUtf8(pKey);
-
- if (!aValue.isEmpty())
- {
- int left, top, width, height;
-
- if (sscanf(aValue.data(), "%d,%d,%d,%d", &left, &top, &width, &height) == 4)
- {
- return TQRect(left, top, width, height);
- }
- }
- if (pDefault)
- return *pDefault;
- return TQRect();
-}
-
-
-TQPoint TDEConfigBase::readPointEntry( const TQString& pKey,
- const TQPoint* pDefault ) const
-{
- return readPointEntry(pKey.utf8().data(), pDefault);
-}
-
-TQPoint TDEConfigBase::readPointEntry( const char *pKey,
- const TQPoint* pDefault ) const
-{
- TQCString aValue = readEntryUtf8(pKey);
-
- if (!aValue.isEmpty())
- {
- int x,y;
-
- if (sscanf(aValue.data(), "%d,%d", &x, &y) == 2)
- {
- return TQPoint(x,y);
- }
- }
- if (pDefault)
- return *pDefault;
- return TQPoint();
-}
-
-TQSize TDEConfigBase::readSizeEntry( const TQString& pKey,
- const TQSize* pDefault ) const
-{
- return readSizeEntry(pKey.utf8().data(), pDefault);
-}
-
-TQSize TDEConfigBase::readSizeEntry( const char *pKey,
- const TQSize* pDefault ) const
-{
- TQCString aValue = readEntryUtf8(pKey);
-
- if (!aValue.isEmpty())
- {
- int width,height;
-
- if (sscanf(aValue.data(), "%d,%d", &width, &height) == 2)
- {
- return TQSize(width, height);
- }
- }
- if (pDefault)
- return *pDefault;
- return TQSize();
-}
-
-
-TQColor TDEConfigBase::readColorEntry( const TQString& pKey,
- const TQColor* pDefault ) const
-{
- return readColorEntry(pKey.utf8().data(), pDefault);
-}
-
-TQColor TDEConfigBase::readColorEntry( const char *pKey,
- const TQColor* pDefault ) const
-{
- TQColor aRetColor;
- int nRed = 0, nGreen = 0, nBlue = 0;
-
- TQString aValue = readEntry( pKey );
- if( !aValue.isEmpty() )
- {
- if ( aValue.at(0) == (QChar)'#' )
- {
- aRetColor.setNamedColor(aValue);
- }
- else
- {
-
- bool bOK;
-
- // find first part (red)
- int nIndex = aValue.find( ',' );
-
- if( nIndex == -1 ){
- // return a sensible default -- Bernd
- if( pDefault )
- aRetColor = *pDefault;
- return aRetColor;
- }
-
- nRed = aValue.left( nIndex ).toInt( &bOK );
-
- // find second part (green)
- int nOldIndex = nIndex;
- nIndex = aValue.find( ',', nOldIndex+1 );
-
- if( nIndex == -1 ){
- // return a sensible default -- Bernd
- if( pDefault )
- aRetColor = *pDefault;
- return aRetColor;
- }
- nGreen = aValue.mid( nOldIndex+1,
- nIndex-nOldIndex-1 ).toInt( &bOK );
-
- // find third part (blue)
- nBlue = aValue.right( aValue.length()-nIndex-1 ).toInt( &bOK );
-
- aRetColor.setRgb( nRed, nGreen, nBlue );
- }
- }
- else {
-
- if( pDefault )
- aRetColor = *pDefault;
- }
-
- return aRetColor;
-}
-
-
-TQDateTime TDEConfigBase::readDateTimeEntry( const TQString& pKey,
- const TQDateTime* pDefault ) const
-{
- return readDateTimeEntry(pKey.utf8().data(), pDefault);
-}
-
-// ### currentDateTime() as fallback ? (Harri)
-TQDateTime TDEConfigBase::readDateTimeEntry( const char *pKey,
- const TQDateTime* pDefault ) const
-{
- if( !hasKey( pKey ) )
- {
- if( pDefault )
- return *pDefault;
- else
- return TQDateTime::currentDateTime();
- }
-
- TQStrList list;
- int count = readListEntry( pKey, list, ',' );
- if( count == 6 ) {
- TQDate date( atoi( list.at( 0 ) ), atoi( list.at( 1 ) ),
- atoi( list.at( 2 ) ) );
- TQTime time( atoi( list.at( 3 ) ), atoi( list.at( 4 ) ),
- atoi( list.at( 5 ) ) );
-
- return TQDateTime( date, time );
- }
-
- return TQDateTime::currentDateTime();
-}
-
-void TDEConfigBase::writeEntry( const TQString& pKey, const TQString& value,
- bool bPersistent,
- bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey.utf8().data(), value, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQString& value,
- bool bPersistent,
- bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey, value, bPersistent, bGlobal, bNLS, false);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQString& value,
- bool bPersistent,
- bool bGlobal,
- bool bNLS,
- bool bExpand )
-{
- // the TDEConfig object is dirty now
- // set this before any IO takes place so that if any derivative
- // classes do caching, they won't try and flush the cache out
- // from under us before we read. A race condition is still
- // possible but minimized.
- if( bPersistent )
- setDirty(true);
-
- if (!bLocaleInitialized && TDEGlobal::locale())
- setLocale();
-
- KEntryKey entryKey(mGroup, pKey);
- entryKey.bLocal = bNLS;
-
- KEntry aEntryData;
- aEntryData.mValue = value.utf8(); // set new value
- aEntryData.bGlobal = bGlobal;
- aEntryData.bNLS = bNLS;
- aEntryData.bExpand = bExpand;
-
- if (bPersistent)
- aEntryData.bDirty = true;
-
- // rewrite the new value
- putData(entryKey, aEntryData, true);
-}
-
-void TDEConfigBase::writePathEntry( const TQString& pKey, const TQString & path,
- bool bPersistent, bool bGlobal,
- bool bNLS)
-{
- writePathEntry(pKey.utf8().data(), path, bPersistent, bGlobal, bNLS);
-}
-
-
-static bool cleanHomeDirPath( TQString &path, const TQString &homeDir )
-{
-#ifdef Q_WS_WIN //safer
- if (!TQDir::convertSeparators(path).startsWith(TQDir::convertSeparators(homeDir)))
- return false;
-#else
- if (!path.startsWith(homeDir))
- return false;
-#endif
-
- unsigned int len = homeDir.length();
- // replace by "$HOME" if possible
- if (len && (path.length() == len || path[len] == '/')) {
- path.replace(0, len, TQString::fromLatin1("$HOME"));
- return true;
- } else
- return false;
-}
-
-static TQString translatePath( TQString path )
-{
- if (path.isEmpty())
- return path;
-
- // only "our" $HOME should be interpreted
- path.replace('$', "$$");
-
- bool startsWithFile = path.startsWith("file:", false);
-
- // return original path, if it refers to another type of URL (e.g. http:/), or
- // if the path is already relative to another directory
- if (((!startsWithFile) && (path[0] != '/')) || (startsWithFile && (path[5] != '/'))) {
- return path;
- }
-
- if (startsWithFile) {
- path.remove(0,5); // strip leading "file:/" off the string
- }
-
- // keep only one single '/' at the beginning - needed for cleanHomeDirPath()
- while (path[0] == '/' && path[1] == '/') {
- path.remove(0,1);
- }
-
- // we can not use TDEGlobal::dirs()->relativeLocation("home", path) here,
- // since it would not recognize paths without a trailing '/'.
- // All of the 3 following functions to return the user's home directory
- // can return different paths. We have to test all them.
- TQString homeDir0 = TQFile::decodeName(getenv("HOME"));
- TQString homeDir1 = TQDir::homeDirPath();
- TQString homeDir2 = TQDir(homeDir1).canonicalPath();
- if (cleanHomeDirPath(path, homeDir0) ||
- cleanHomeDirPath(path, homeDir1) ||
- cleanHomeDirPath(path, homeDir2) ) {
- // kdDebug() << "Path was replaced\n";
- }
-
- if (startsWithFile)
- path.prepend( "file://" );
-
- return path;
-}
-
-void TDEConfigBase::writePathEntry( const char *pKey, const TQString & path,
- bool bPersistent, bool bGlobal,
- bool bNLS)
-{
- writeEntry(pKey, translatePath(path), bPersistent, bGlobal, bNLS, true);
-}
-
-void TDEConfigBase::writePathEntry ( const TQString& pKey, const TQStringList &list,
- char sep , bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- writePathEntry(pKey.utf8().data(), list, sep, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writePathEntry ( const char *pKey, const TQStringList &list,
- char sep , bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- if( list.isEmpty() )
- {
- writeEntry( pKey, TQString::fromLatin1(""), bPersistent );
- return;
- }
- TQStringList new_list;
- TQStringList::ConstIterator it = list.begin();
- for( ; it != list.end(); ++it )
- {
- TQString value = *it;
- new_list.append( translatePath(value) );
- }
- writeEntry( pKey, new_list, sep, bPersistent, bGlobal, bNLS, true );
-}
-
-void TDEConfigBase::deleteEntry( const TQString& pKey,
- bool bNLS,
- bool bGlobal)
-{
- deleteEntry(pKey.utf8().data(), bNLS, bGlobal);
-}
-
-void TDEConfigBase::deleteEntry( const char *pKey,
- bool bNLS,
- bool bGlobal)
-{
- // the TDEConfig object is dirty now
- // set this before any IO takes place so that if any derivative
- // classes do caching, they won't try and flush the cache out
- // from under us before we read. A race condition is still
- // possible but minimized.
- setDirty(true);
-
- if (!bLocaleInitialized && TDEGlobal::locale())
- setLocale();
-
- KEntryKey entryKey(mGroup, pKey);
- KEntry aEntryData;
-
- aEntryData.bGlobal = bGlobal;
- aEntryData.bNLS = bNLS;
- aEntryData.bDirty = true;
- aEntryData.bDeleted = true;
-
- // rewrite the new value
- putData(entryKey, aEntryData, true);
-}
-
-bool TDEConfigBase::deleteGroup( const TQString& group, bool bDeep, bool bGlobal )
-{
- KEntryMap aEntryMap = internalEntryMap(group);
-
- if (!bDeep) {
- // Check if it empty
- return aEntryMap.isEmpty();
- }
-
- bool dirty = false;
- bool checkGroup = true;
- // we want to remove all entries in the group
- KEntryMapIterator aIt;
- for (aIt = aEntryMap.begin(); aIt != aEntryMap.end(); ++aIt)
- {
- if (!aIt.key().mKey.isEmpty() && !aIt.key().bDefault && !(*aIt).bDeleted)
- {
- (*aIt).bDeleted = true;
- (*aIt).bDirty = true;
- (*aIt).bGlobal = bGlobal;
- (*aIt).mValue = 0;
- putData(aIt.key(), *aIt, checkGroup);
- checkGroup = false;
- dirty = true;
- }
- }
- if (dirty)
- setDirty(true);
- return true;
-}
-
-void TDEConfigBase::writeEntry ( const TQString& pKey, const TQVariant &prop,
- bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- writeEntry(pKey.utf8().data(), prop, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry ( const char *pKey, const TQVariant &prop,
- bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- switch( prop.type() )
- {
- case TQVariant::Invalid:
- writeEntry( pKey, "", bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::String:
- writeEntry( pKey, prop.toString(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::StringList:
- writeEntry( pKey, prop.toStringList(), ',', bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::List: {
- TQValueList<TQVariant> list = prop.toList();
- TQValueList<TQVariant>::ConstIterator it = list.begin();
- TQValueList<TQVariant>::ConstIterator end = list.end();
- TQStringList strList;
-
- for (; it != end; ++it )
- strList.append( (*it).toString() );
-
- writeEntry( pKey, strList, ',', bPersistent, bGlobal, bNLS );
-
- return;
- }
- case TQVariant::Font:
- writeEntry( pKey, prop.toFont(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::Point:
- writeEntry( pKey, prop.toPoint(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::Rect:
- writeEntry( pKey, prop.toRect(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::Size:
- writeEntry( pKey, prop.toSize(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::Color:
- writeEntry( pKey, prop.toColor(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::Int:
- writeEntry( pKey, prop.toInt(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::UInt:
- writeEntry( pKey, prop.toUInt(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::LongLong:
- writeEntry( pKey, prop.toLongLong(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::ULongLong:
- writeEntry( pKey, prop.toULongLong(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::Bool:
- writeEntry( pKey, prop.toBool(), bPersistent, bGlobal, bNLS );
- return;
- case TQVariant::Double:
- writeEntry( pKey, prop.toDouble(), bPersistent, bGlobal, 'g', 6, bNLS );
- return;
- case TQVariant::DateTime:
- writeEntry( pKey, prop.toDateTime(), bPersistent, bGlobal, bNLS);
- return;
- case TQVariant::Date:
- writeEntry( pKey, TQDateTime(prop.toDate()), bPersistent, bGlobal, bNLS);
- return;
-
- case TQVariant::Pixmap:
- case TQVariant::Image:
- case TQVariant::Brush:
- case TQVariant::Palette:
- case TQVariant::ColorGroup:
- case TQVariant::Map:
- case TQVariant::IconSet:
- case TQVariant::CString:
- case TQVariant::PointArray:
- case TQVariant::Region:
- case TQVariant::Bitmap:
- case TQVariant::Cursor:
- case TQVariant::SizePolicy:
- case TQVariant::Time:
-#ifdef USE_QT3
- case TQVariant::ByteArray:
-#endif // USE_QT3
- case TQVariant::BitArray:
- case TQVariant::KeySequence:
- case TQVariant::Pen:
-#ifdef USE_QT4
- case TQVariant::Char:
- case TQVariant::Url:
- case TQVariant::Locale:
- case TQVariant::RectF:
- case TQVariant::SizeF:
- case TQVariant::Line:
- case TQVariant::LineF:
- case TQVariant::PointF:
- case TQVariant::RegExp:
- case TQVariant::Hash:
- case TQVariant::TextLength:
- case QVariant::TextFormat:
- case TQVariant::Matrix:
- case TQVariant::Transform:
- case TQVariant::Matrix4x4:
- case TQVariant::Vector2D:
- case TQVariant::Vector3D:
- case TQVariant::Vector4D:
- case TQVariant::Quaternion:
- case TQVariant::UserType:
-#endif // USE_QT4
- break;
- }
-
- Q_ASSERT( 0 );
-}
-
-void TDEConfigBase::writeEntry ( const TQString& pKey, const TQStrList &list,
- char sep , bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- writeEntry(pKey.utf8().data(), list, sep, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry ( const char *pKey, const TQStrList &list,
- char sep , bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- if( list.isEmpty() )
- {
- writeEntry( pKey, TQString::fromLatin1(""), bPersistent );
- return;
- }
- TQString str_list;
- TQStrListIterator it( list );
- for( ; it.current(); ++it )
- {
- uint i;
- TQString value;
- // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
- // A TQStrList may contain values in 8bit locale cpecified
- // encoding or in UTF8 encoding.
- value = KStringHandler::from8Bit(it.current());
- uint strLengh(value.length());
- for( i = 0; i < strLengh; i++ )
- {
- if( value[i] == sep || value[i] == '\\' )
- str_list += '\\';
- str_list += value[i];
- }
- str_list += sep;
- }
- if( str_list.at(str_list.length() - 1) == (QChar)sep )
- str_list.truncate( str_list.length() -1 );
- writeEntry( pKey, str_list, bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry ( const TQString& pKey, const TQStringList &list,
- char sep , bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- writeEntry(pKey.utf8().data(), list, sep, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry ( const char *pKey, const TQStringList &list,
- char sep , bool bPersistent,
- bool bGlobal, bool bNLS )
-{
- writeEntry(pKey, list, sep, bPersistent, bGlobal, bNLS, false);
-}
-
-void TDEConfigBase::writeEntry ( const char *pKey, const TQStringList &list,
- char sep, bool bPersistent,
- bool bGlobal, bool bNLS, bool bExpand )
-{
- if( list.isEmpty() )
- {
- writeEntry( pKey, TQString::fromLatin1(""), bPersistent );
- return;
- }
- TQString str_list;
- str_list.reserve( 4096 );
- TQStringList::ConstIterator it = list.begin();
- for( ; it != list.end(); ++it )
- {
- TQString value = *it;
- uint i;
- uint strLength(value.length());
- for( i = 0; i < strLength; i++ )
- {
- if( value[i] == sep || value[i] == '\\' )
- str_list += '\\';
- str_list += value[i];
- }
- str_list += sep;
- }
- if( str_list.at(str_list.length() - 1) == (QChar)sep )
- str_list.truncate( str_list.length() -1 );
- writeEntry( pKey, str_list, bPersistent, bGlobal, bNLS, bExpand );
-}
-
-void TDEConfigBase::writeEntry ( const TQString& pKey, const TQValueList<int> &list,
- bool bPersistent, bool bGlobal, bool bNLS )
-{
- writeEntry(pKey.utf8().data(), list, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry ( const char *pKey, const TQValueList<int> &list,
- bool bPersistent, bool bGlobal, bool bNLS )
-{
- TQStringList strlist;
- TQValueList<int>::ConstIterator end = list.end();
- for (TQValueList<int>::ConstIterator it = list.begin(); it != end; it++)
- strlist << TQString::number(*it);
- writeEntry(pKey, strlist, ',', bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const TQString& pKey, int nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, int nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, unsigned int nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, unsigned int nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, long nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, long nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, unsigned long nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, unsigned long nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const TQString& pKey, TQ_INT64 nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, TQ_INT64 nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, TQ_UINT64 nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, TQ_UINT64 nValue,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const TQString& pKey, double nValue,
- bool bPersistent, bool bGlobal,
- char format, int precision,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue, format, precision),
- bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, double nValue,
- bool bPersistent, bool bGlobal,
- char format, int precision,
- bool bNLS )
-{
- writeEntry( pKey, TQString::number(nValue, format, precision),
- bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, bool bValue,
- bool bPersistent,
- bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey.utf8().data(), bValue, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, bool bValue,
- bool bPersistent,
- bool bGlobal,
- bool bNLS )
-{
- TQString aValue;
-
- if( bValue )
- aValue = "true";
- else
- aValue = "false";
-
- writeEntry( pKey, aValue, bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, const TQFont& rFont,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey.utf8().data(), rFont, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQFont& rFont,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey, TQString(rFont.toString()), bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, const TQRect& rRect,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey.utf8().data(), rRect, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQRect& rRect,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- TQStrList list;
- TQCString tempstr;
- list.insert( 0, tempstr.setNum( rRect.left() ) );
- list.insert( 1, tempstr.setNum( rRect.top() ) );
- list.insert( 2, tempstr.setNum( rRect.width() ) );
- list.insert( 3, tempstr.setNum( rRect.height() ) );
-
- writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, const TQPoint& rPoint,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey.utf8().data(), rPoint, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQPoint& rPoint,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- TQStrList list;
- TQCString tempstr;
- list.insert( 0, tempstr.setNum( rPoint.x() ) );
- list.insert( 1, tempstr.setNum( rPoint.y() ) );
-
- writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
-}
-
-
-void TDEConfigBase::writeEntry( const TQString& pKey, const TQSize& rSize,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey.utf8().data(), rSize, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQSize& rSize,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- TQStrList list;
- TQCString tempstr;
- list.insert( 0, tempstr.setNum( rSize.width() ) );
- list.insert( 1, tempstr.setNum( rSize.height() ) );
-
- writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const TQString& pKey, const TQColor& rColor,
- bool bPersistent,
- bool bGlobal,
- bool bNLS )
-{
- writeEntry( pKey.utf8().data(), rColor, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQColor& rColor,
- bool bPersistent,
- bool bGlobal,
- bool bNLS )
-{
- TQString aValue;
- if (rColor.isValid())
- aValue.sprintf( "%d,%d,%d", rColor.red(), rColor.green(), rColor.blue() );
- else
- aValue = "invalid";
-
- writeEntry( pKey, aValue, bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::writeEntry( const TQString& pKey, const TQDateTime& rDateTime,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- writeEntry(pKey.utf8().data(), rDateTime, bPersistent, bGlobal, bNLS);
-}
-
-void TDEConfigBase::writeEntry( const char *pKey, const TQDateTime& rDateTime,
- bool bPersistent, bool bGlobal,
- bool bNLS )
-{
- TQStrList list;
- TQCString tempstr;
-
- TQTime time = TQT_TQTIME_OBJECT(rDateTime.time());
- TQDate date = TQT_TQDATE_OBJECT(rDateTime.date());
-
- list.insert( 0, tempstr.setNum( date.year() ) );
- list.insert( 1, tempstr.setNum( date.month() ) );
- list.insert( 2, tempstr.setNum( date.day() ) );
-
- list.insert( 3, tempstr.setNum( time.hour() ) );
- list.insert( 4, tempstr.setNum( time.minute() ) );
- list.insert( 5, tempstr.setNum( time.second() ) );
-
- writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
-}
-
-void TDEConfigBase::parseConfigFiles()
-{
- if (!bLocaleInitialized && TDEGlobal::_locale) {
- setLocale();
- }
- if (backEnd)
- {
- backEnd->parseConfigFiles();
- bReadOnly = (backEnd->getConfigState() == ReadOnly);
- }
-}
-
-void TDEConfigBase::sync()
-{
- if (isReadOnly())
- return;
-
- if (backEnd)
- backEnd->sync();
- if (bDirty)
- rollback();
-}
-
-TDEConfigBase::ConfigState TDEConfigBase::getConfigState() const {
- if (backEnd)
- return backEnd->getConfigState();
- return ReadOnly;
-}
-
-void TDEConfigBase::rollback( bool /*bDeep = true*/ )
-{
- bDirty = false;
-}
-
-
-void TDEConfigBase::setReadDefaults(bool b)
-{
- if (!d)
- {
- if (!b) return;
- d = new TDEConfigBasePrivate();
- }
-
- d->readDefaults = b;
-}
-
-bool TDEConfigBase::readDefaults() const
-{
- return (d && d->readDefaults);
-}
-
-void TDEConfigBase::revertToDefault(const TQString &key)
-{
- setDirty(true);
-
- KEntryKey aEntryKey(mGroup, key.utf8());
- aEntryKey.bDefault = true;
-
- if (!locale().isNull()) {
- // try the localized key first
- aEntryKey.bLocal = true;
- KEntry entry = lookupData(aEntryKey);
- if (entry.mValue.isNull())
- entry.bDeleted = true;
-
- entry.bDirty = true;
- putData(aEntryKey, entry, true); // Revert
- aEntryKey.bLocal = false;
- }
-
- // try the non-localized version
- KEntry entry = lookupData(aEntryKey);
- if (entry.mValue.isNull())
- entry.bDeleted = true;
- entry.bDirty = true;
- putData(aEntryKey, entry, true); // Revert
-}
-
-bool TDEConfigBase::hasDefault(const TQString &key) const
-{
- KEntryKey aEntryKey(mGroup, key.utf8());
- aEntryKey.bDefault = true;
-
- if (!locale().isNull()) {
- // try the localized key first
- aEntryKey.bLocal = true;
- KEntry entry = lookupData(aEntryKey);
- if (!entry.mValue.isNull())
- return true;
-
- aEntryKey.bLocal = false;
- }
-
- // try the non-localized version
- KEntry entry = lookupData(aEntryKey);
- if (!entry.mValue.isNull())
- return true;
-
- return false;
-}
-
-
-
-TDEConfigGroup::TDEConfigGroup(TDEConfigBase *master, const TQString &group)
-{
- mMaster = master;
- backEnd = mMaster->backEnd; // Needed for getConfigState()
- bLocaleInitialized = true;
- bReadOnly = mMaster->bReadOnly;
- bExpand = false;
- bDirty = false; // Not used
- mGroup = group.utf8();
- aLocaleString = mMaster->aLocaleString;
- setReadDefaults(mMaster->readDefaults());
-}
-
-TDEConfigGroup::TDEConfigGroup(TDEConfigBase *master, const TQCString &group)
-{
- mMaster = master;
- backEnd = mMaster->backEnd; // Needed for getConfigState()
- bLocaleInitialized = true;
- bReadOnly = mMaster->bReadOnly;
- bExpand = false;
- bDirty = false; // Not used
- mGroup = group;
- aLocaleString = mMaster->aLocaleString;
- setReadDefaults(mMaster->readDefaults());
-}
-
-TDEConfigGroup::TDEConfigGroup(TDEConfigBase *master, const char * group)
-{
- mMaster = master;
- backEnd = mMaster->backEnd; // Needed for getConfigState()
- bLocaleInitialized = true;
- bReadOnly = mMaster->bReadOnly;
- bExpand = false;
- bDirty = false; // Not used
- mGroup = group;
- aLocaleString = mMaster->aLocaleString;
- setReadDefaults(mMaster->readDefaults());
-}
-
-void TDEConfigGroup::deleteGroup(bool bGlobal)
-{
- mMaster->deleteGroup(TDEConfigBase::group(), true, bGlobal);
-}
-
-bool TDEConfigGroup::groupIsImmutable() const
-{
- return mMaster->groupIsImmutable(TDEConfigBase::group());
-}
-
-void TDEConfigGroup::setDirty(bool _bDirty)
-{
- mMaster->setDirty(_bDirty);
-}
-
-void TDEConfigGroup::putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup)
-{
- mMaster->putData(_key, _data, _checkGroup);
-}
-
-KEntry TDEConfigGroup::lookupData(const KEntryKey &_key) const
-{
- return mMaster->lookupData(_key);
-}
-
-void TDEConfigGroup::sync()
-{
- mMaster->sync();
-}
-
-void TDEConfigBase::virtual_hook( int, void* )
-{ /*BASE::virtual_hook( id, data );*/ }
-
-void TDEConfigGroup::virtual_hook( int id, void* data )
-{ TDEConfigBase::virtual_hook( id, data ); }
-
-bool TDEConfigBase::checkConfigFilesWritable(bool warnUser)
-{
- if (backEnd)
- return backEnd->checkConfigFilesWritable(warnUser);
- else
- return false;
-}
-
-#include "kconfigbase.moc"
diff --git a/tdecore/kconfigbase.h b/tdecore/kconfigbase.h
deleted file mode 100644
index ff02babdd..000000000
--- a/tdecore/kconfigbase.h
+++ /dev/null
@@ -1,2180 +0,0 @@
-/*
- This file is part of the KDE libraries
- Copyright (c) 1999 Preston Brown <pbrown@kde.org>
- Copyright (c) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
- Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef _KCONFIGBASE_H
-#define _KCONFIGBASE_H
-
-#include <tqobject.h>
-#include <tqcolor.h>
-#include <tqfont.h>
-#include <tqdatetime.h>
-#include <tqstrlist.h>
-#include <tqstringlist.h>
-#include <tqvariant.h>
-#include <tqmap.h>
-
-#include "kconfigdata.h"
-#include "tdelibs_export.h"
-
-class TDEConfigBackEnd;
-class TDEConfigBasePrivate;
-class TDEConfigGroup;
-
-/**
- * @short KDE Configuration Management abstract base class
- *
- * This class forms the base for all %KDE configuration. It is an
- * abstract base class, meaning that you cannot directly instantiate
- * objects of this class. Either use TDEConfig (for usual %KDE
- * configuration) or KSimpleConfig (for special needs as in ksamba), or
- * even KSharedConfig (stores values in shared memory).
- *
- * All configuration entries are key, value pairs. Each entry also
- * belongs to a specific group of related entries. All configuration
- * entries that do not explicitly specify which group they are in are
- * in a special group called the default group.
- *
- * If there is a $ character in an entry, TDEConfigBase tries to expand
- * environment variable and uses its value instead of its name. You
- * can avoid this feature by having two consecutive $ characters in
- * your config file which get expanded to one.
- *
- * \note the '=' char is not allowed in keys and the ']' char is not allowed in
- * a group name.
- *
- * @author Kalle Dalheimer <kalle@kde.org>, Preston Brown <pbrown@kde.org>
- * @see TDEGlobal#config()
- * @see TDEConfig
- * @see KSimpleConfig
- * @see KSharedConfig
- */
-class TDECORE_EXPORT TDEConfigBase : public TQObject
-{
- Q_OBJECT
-
-
- friend class TDEConfigBackEnd;
- friend class TDEConfigINIBackEnd;
- friend class TDEConfigGroup;
-
-public:
- /**
- * Construct a TDEConfigBase object.
- */
- TDEConfigBase();
-
- /**
- * Destructs the TDEConfigBase object.
- */
- virtual ~TDEConfigBase();
-
- /**
- * Specifies the group in which keys will be read and written.
- *
- * Subsequent
- * calls to readEntry() and writeEntry() will be applied only in the
- * activated group.
- *
- * Switch back to the default group by passing a null string.
- * @param group The name of the new group.
- */
- void setGroup( const TQString& group );
-
- /**
- * Sets the group to the "Desktop Entry" group used for
- * desktop configuration files for applications, mime types, etc.
- */
- void setDesktopGroup();
-
- /**
- * Returns the name of the group in which we are
- * searching for keys and from which we are retrieving entries.
- *
- * @return The current group.
- */
- TQString group() const;
-
- /**
- * Returns true if the specified group is known about.
- *
- * @param group The group to search for.
- * @return true if the group exists.
- */
- bool hasGroup(const TQString &group) const;
-
- /**
- * Returns a list of groups that are known about.
- *
- * @return The list of groups.
- **/
- virtual TQStringList groupList() const = 0;
-
- /**
- * Returns a the current locale.
- *
- * @return A string representing the current locale.
- */
- TQString locale() const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- * If you want to read a path, please use readPathEntry().
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found.
- * @return The value for this key. Can be TQString::null if aDefault is null.
- */
- TQString readEntry(const TQString& pKey,
- const TQString& aDefault = TQString::null ) const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found.
- * @return The value for this key. Can be TQString::null if aDefault is null.
- */
- TQString readEntry(const char *pKey,
- const TQString& aDefault = TQString::null ) const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- * The value is treated as if it is of the given type.
- *
- * Note that only the following TQVariant types are allowed : String,
- * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
- * Double, DateTime and Date.
- * @deprecated
- *
- * @param pKey The key to search for.
- * @return An invalid TQVariant if the key was not found or if the
- * read value cannot be converted to the given TQVariant::Type.
- */
- TQVariant readPropertyEntry( const TQString& pKey, TQVariant::Type ) const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- * The value is treated as if it is of the given type.
- *
- * Note that only the following TQVariant types are allowed : String,
- * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
- * Double, DateTime and Date.
- *
- * @deprecated
- *
- * @param pKey The key to search for.
- * @return An invalid TQVariant if the key was not found or if the
- * read value cannot be converted to the given TQVariant::Type.
- */
- TQVariant readPropertyEntry( const char *pKey, TQVariant::Type ) const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- * The value is treated as if it is of the type of the given default value.
- *
- * Note that only the following TQVariant types are allowed : String,
- * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
- * Double, DateTime and Date.
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found or
- * if the read value cannot be converted to the TQVariant::Type.
- * @return The value for the key or the default value if the key was not
- * found.
- */
- TQVariant readPropertyEntry( const TQString& pKey,
- const TQVariant &aDefault) const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- * The value is treated as if it is of the type of the given default value.
- *
- * Note that only the following TQVariant types are allowed : String,
- * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
- * Double, DateTime and Date.
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found or
- * if the read value cannot be converted to the TQVariant::Type.
- * @return The value for the key or the default value if the key was not
- * found.
- */
- TQVariant readPropertyEntry( const char *pKey,
- const TQVariant &aDefault) const;
-
- /**
- * Reads a list of strings.
- *
- * @deprecated
- *
- * @param pKey The key to search for
- * @param list In this object, the read list will be returned.
- * @param sep The list separator (default ",")
- * @return The number of entries in the list.
- */
- int readListEntry( const TQString& pKey, TQStrList &list, char sep = ',' ) const;
-
- /**
- * Reads a list of strings.
- *
- * @deprecated
- *
- * @param pKey The key to search for
- * @param list In this object, the read list will be returned.
- * @param sep The list separator (default ",")
- * @return The number of entries in the list.
- */
- int readListEntry( const char *pKey, TQStrList &list, char sep = ',' ) const;
-
- /**
- * Reads a list of strings.
- *
- * @param pKey The key to search for.
- * @param sep The list separator (default is ",").
- * @return The list. Empty if the entry does not exist.
- */
- TQStringList readListEntry( const TQString& pKey, char sep = ',' ) const;
-
- /**
- * Reads a list of strings.
- *
- * @param pKey The key to search for.
- * @param sep The list separator (default is ",").
- * @return The list. Empty if the entry does not exist.
- */
- TQStringList readListEntry( const char *pKey, char sep = ',' ) const;
-
- /**
- * Reads a list of strings, but returns a default if the key
- * did not exist.
- * @param pKey The key to search for.
- * @param aDefault The default value to use if the key does not exist.
- * @param sep The list separator (default is ",").
- * @return The list. Contains @p aDefault if the Key does not exist.
- * @since 3.3
- */
- TQStringList readListEntry( const char* pKey, const TQStringList& aDefault,
- char sep = ',' ) const;
-
- /**
- * Reads a list of Integers.
- *
- * @param pKey The key to search for.
- * @return The list. Empty if the entry does not exist.
- */
- TQValueList<int> readIntListEntry( const TQString& pKey ) const;
-
- /**
- * Reads a list of Integers.
- *
- * @param pKey The key to search for.
- * @return The list. Empty if the entry does not exist.
- */
- TQValueList<int> readIntListEntry( const char *pKey ) const;
-
- /**
- * Reads a path.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a path. This means, dollar expansion is activated
- * for this value, so that e.g. $HOME gets expanded.
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found.
- * @return The value for this key. Can be TQString::null if aDefault is null.
- */
- TQString readPathEntry( const TQString& pKey, const TQString & aDefault = TQString::null ) const;
-
- /**
- * Reads a path.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a path. This means, dollar expansion is activated
- * for this value, so that e.g. $HOME gets expanded.
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found.
- * @return The value for this key. Can be TQString::null if aDefault is null.
- */
- TQString readPathEntry( const char *pKey, const TQString & aDefault = TQString::null ) const;
-
- /**
- * Reads a list of string paths.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a list of paths. This means, dollar expansion is activated
- * for this value, so that e.g. $HOME gets expanded.
- *
- * @param pKey The key to search for.
- * @param sep The list separator (default is ",").
- * @return The list. Empty if the entry does not exist.
- * @since 3.1.3
- */
- TQStringList readPathListEntry( const TQString& pKey, char sep = ',' ) const;
-
- /**
- * Reads a list of string paths.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a list of paths. This means, dollar expansion is activated
- * for this value, so that e.g. $HOME gets expanded.
- *
- * @param pKey The key to search for.
- * @param sep The list separator (default is ",").
- * @return The list. Empty if the entry does not exist.
- * @since 3.1.3
- */
- TQStringList readPathListEntry( const char *pKey, char sep = ',' ) const;
-
-
- /**
- * Reads a numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- int readNumEntry( const TQString& pKey, int nDefault = 0 ) const;
-
- /**
- * Reads a numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- int readNumEntry( const char *pKey, int nDefault = 0 ) const;
-
- /**
- * Reads an unsigned numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- unsigned int readUnsignedNumEntry( const TQString& pKey, unsigned int nDefault = 0 ) const;
-
- /**
- * Reads an unsigned numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- unsigned int readUnsignedNumEntry( const char *pKey, unsigned int nDefault = 0 ) const;
-
-
- /**
- * Reads a numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- long readLongNumEntry( const TQString& pKey, long nDefault = 0 ) const;
-
- /**
- * Reads a numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- long readLongNumEntry( const char *pKey, long nDefault = 0 ) const;
-
- /**
- * Read an unsigned numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- unsigned long readUnsignedLongNumEntry( const TQString& pKey, unsigned long nDefault = 0 ) const;
-
- /**
- * Read an unsigned numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- unsigned long readUnsignedLongNumEntry( const char *pKey, unsigned long nDefault = 0 ) const;
-
- /**
- * Reads a 64-bit numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQ_INT64 readNum64Entry( const TQString& pKey, TQ_INT64 nDefault = 0 ) const;
-
- /**
- * Reads a 64-bit numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQ_INT64 readNum64Entry( const char *pKey, TQ_INT64 nDefault = 0 ) const;
-
- /**
- * Read an 64-bit unsigned numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQ_UINT64 readUnsignedNum64Entry( const TQString& pKey, TQ_UINT64 nDefault = 0 ) const;
-
- /**
- * Read an 64-bit unsigned numerical value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQ_UINT64 readUnsignedNum64Entry( const char *pKey, TQ_UINT64 nDefault = 0 ) const;
-
- /**
- * Reads a floating point value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- double readDoubleNumEntry( const TQString& pKey, double nDefault = 0.0 ) const;
-
- /**
- * Reads a floating point value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it numerically.
- *
- * @param pKey The key to search for.
- * @param nDefault A default value returned if the key was not found or if
- * the read value cannot be interpreted.
- * @return The value for this key.
- */
- double readDoubleNumEntry( const char *pKey, double nDefault = 0.0 ) const;
-
- /**
- * Reads a TQFont value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a font object.
- *
- * @param pKey The key to search for.
- * @param pDefault A default value (null TQFont by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQFont readFontEntry( const TQString& pKey, const TQFont* pDefault = 0L ) const;
-
- /**
- * Reads a TQFont value.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a font object.
- *
- * @param pKey The key to search for.
- * @param pDefault A default value (null TQFont by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQFont readFontEntry( const char *pKey, const TQFont* pDefault = 0L ) const;
-
- /**
- * Reads a boolean entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a boolean value. Currently "on", "yes", "1" and
- * "true" are accepted as true, everything else if false.
- *
- * @param pKey The key to search for
- * @param bDefault A default value returned if the key was not found.
- * @return The value for this key.
- */
- bool readBoolEntry( const TQString& pKey, bool bDefault = false ) const;
-
- /**
- * Reads a boolean entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a boolean value. Currently "on", "yes", "1" and
- * "true" are accepted as true, everything else if false.
- *
- * @param pKey The key to search for
- * @param bDefault A default value returned if the key was not found.
- * @return The value for this key.
- */
- bool readBoolEntry( const char *pKey, bool bDefault = false ) const;
-
- /**
- * Reads a TQRect entry.
- *
- * Read the value of an entry specified by pKey in the current group
- * and interpret it as a TQRect object.
- *
- * @param pKey The key to search for
- * @param pDefault A default value (null TQRect by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQRect readRectEntry( const TQString& pKey, const TQRect* pDefault = 0L ) const;
-
- /**
- * Reads a TQRect entry.
- *
- * Read the value of an entry specified by pKey in the current group
- * and interpret it as a TQRect object.
- *
- * @param pKey The key to search for
- * @param pDefault A default value (null TQRect by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQRect readRectEntry( const char *pKey, const TQRect* pDefault = 0L ) const;
-
- /**
- * Reads a TQPoint entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a TQPoint object.
- *
- * @param pKey The key to search for
- * @param pDefault A default value (null TQPoint by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQPoint readPointEntry( const TQString& pKey, const TQPoint* pDefault = 0L ) const;
-
- /**
- * Reads a TQPoint entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a TQPoint object.
- *
- * @param pKey The key to search for
- * @param pDefault A default value (null TQPoint by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQPoint readPointEntry( const char *pKey, const TQPoint* pDefault = 0L ) const;
-
- /**
- * Reads a TQSize entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a TQSize object.
- *
- * @param pKey The key to search for
- * @param pDefault A default value (null TQSize by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQSize readSizeEntry( const TQString& pKey, const TQSize* pDefault = 0L ) const;
-
- /**
- * Reads a TQSize entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a TQSize object.
- *
- * @param pKey The key to search for
- * @param pDefault A default value (null TQSize by default) returned if the
- * key was not found or if the read value cannot be interpreted.
- * @return The value for this key.
- */
- TQSize readSizeEntry( const char *pKey, const TQSize* pDefault = 0L ) const;
-
-
- /**
- * Reads a TQColor entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a color.
- *
- * @param pKey The key to search for.
- * @param pDefault A default value (null TQColor by default) returned if the
- * key was not found or if the value cannot be interpreted.
- * @return The value for this key.
- */
- TQColor readColorEntry( const TQString& pKey, const TQColor* pDefault = 0L ) const;
-
- /**
- * Reads a TQColor entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a color.
- *
- * @param pKey The key to search for.
- * @param pDefault A default value (null TQColor by default) returned if the
- * key was not found or if the value cannot be interpreted.
- * @return The value for this key.
- */
- TQColor readColorEntry( const char *pKey, const TQColor* pDefault = 0L ) const;
-
- /**
- * Reads a TQDateTime entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a date and time.
- *
- * @param pKey The key to search for.
- * @param pDefault A default value ( currentDateTime() by default)
- * returned if the key was not found or if the read value cannot be
- * interpreted.
- * @return The value for this key.
- */
- TQDateTime readDateTimeEntry( const TQString& pKey, const TQDateTime* pDefault = 0L ) const;
-
- /**
- * Reads a TQDateTime entry.
- *
- * Read the value of an entry specified by @p pKey in the current group
- * and interpret it as a date and time.
- *
- * @param pKey The key to search for.
- * @param pDefault A default value ( currentDateTime() by default)
- * returned if the key was not found or if the read value cannot be
- * interpreted.
- * @return The value for this key.
- */
- TQDateTime readDateTimeEntry( const char *pKey, const TQDateTime* pDefault = 0L ) const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- * The untranslated entry is returned, you normally do not need this.
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found.
- * @return The value for this key.
- */
- TQString readEntryUntranslated( const TQString& pKey,
- const TQString& aDefault = TQString::null ) const;
-
- /**
- * Reads the value of an entry specified by @p pKey in the current group.
- * The untranslated entry is returned, you normally do not need this.
- *
- * @param pKey The key to search for.
- * @param aDefault A default value returned if the key was not found.
- * @return The value for this key.
- */
- TQString readEntryUntranslated( const char *pKey,
- const TQString& aDefault = TQString::null ) const;
-
- /**
- * Writes a key/value pair.
- *
- * This is stored in the most specific config file when destroying the
- * config object or when calling sync().
- *
- * If you want to write a path, please use writePathEntry().
- *
- * @param pKey The key to write.
- * @param pValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will
- * not be written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const TQString& pValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a key/value pair.
- *
- * This is stored in the most specific config file when destroying the
- * config object or when calling sync().
- *
- * @param pKey The key to write.
- * @param pValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will
- * not be written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const TQString& pValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * writeEntry() Overridden to accept a property.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The property to write
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const TQString& pKey, const TQVariant& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * writeEntry() Overridden to accept a property.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The property to write
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const char *pKey, const TQVariant& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * writeEntry() overridden to accept a list of strings.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param sep The list separator (default is ",").
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const TQString& pKey, const TQStrList &rValue,
- char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
- /**
- * writeEntry() overridden to accept a list of strings.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param sep The list separator (default is ",").
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const char *pKey, const TQStrList &rValue,
- char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
-
- /**
- * writeEntry() overridden to accept a list of strings.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param sep The list separator (default is ",").
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const TQString& pKey, const TQStringList &rValue,
- char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
- /**
- * writeEntry() overridden to accept a list of strings.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param sep The list separator (default is ",").
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const char *pKey, const TQStringList &rValue,
- char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
-
-
- /**
- * writeEntry() overridden to accept a list of Integers.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const TQString& pKey, const TQValueList<int>& rValue,
- bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
- /**
- * writeEntry() overridden to accept a list of Integers.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writeEntry()
- */
- void writeEntry( const char *pKey, const TQValueList<int>& rValue,
- bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
-
- /**
- * Write a (key/value) pair.
- *
- * This is stored to the most specific config file when destroying the
- * config object or when calling sync().
- *
- * @param pKey The key to write.
- * @param pValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will
- * not be written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const char *pValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false )
- { writeEntry(pKey, TQString::fromLatin1(pValue), bPersistent, bGlobal, bNLS); }
- /**
- * Write a (key/value) pair.
- *
- * This is stored to the most specific config file when destroying the
- * config object or when calling sync().
- *
- * @param pKey The key to write.
- * @param pValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will
- * not be written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const char *pValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false )
- { writeEntry(pKey, TQString::fromLatin1(pValue), bPersistent, bGlobal, bNLS); }
-
- /**
- * Write a (key/value) pair.
- * Same as above, but writes a numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, int nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Write a (key/value) pair.
- * Same as above, but writes a numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, int nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes an unsigned numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, unsigned int nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes an unsigned numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, unsigned int nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but write a long numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, long nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but write a long numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, long nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes an unsigned long numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, unsigned long nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes an unsigned long numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, unsigned long nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but write a 64-bit numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, TQ_INT64 nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but write a long numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, TQ_INT64 nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes an unsigned 64-bit numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, TQ_UINT64 nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes an unsigned 64-bit numerical value.
- *
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, TQ_UINT64 nValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a floating-point value.
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param format @p format determines the format to which the value
- * is converted. Default is 'g'.
- * @param precision @p precision sets the precision with which the
- * value is converted. Default is 6 as in TQString.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, double nValue,
- bool bPersistent = true, bool bGlobal = false,
- char format = 'g', int precision = 6,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a floating-point value.
- * @param pKey The key to write.
- * @param nValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param format @p format determines the format to which the value
- * is converted. Default is 'g'.
- * @param precision @p precision sets the precision with which the
- * value is converted. Default is 6 as in TQString.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, double nValue,
- bool bPersistent = true, bool bGlobal = false,
- char format = 'g', int precision = 6,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a boolean value.
- *
- * @param pKey The key to write.
- * @param bValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, bool bValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a boolean value.
- *
- * @param pKey The key to write.
- * @param bValue The value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, bool bValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a font value.
- *
- * @param pKey The key to write.
- * @param rFont The font value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const TQFont& rFont,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a font value.
- *
- * @param pKey The key to write.
- * @param rFont The font value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const TQFont& rFont,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but write a color entry.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rColor The color value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const TQColor& rColor,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but write a color entry.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rColor The color value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const TQColor& rColor,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a date and time entry.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * @em not returned here!
- *
- * @param pKey The key to write.
- * @param rDateTime The date and time value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const TQDateTime& rDateTime,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a date and time entry.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * @em not returned here!
- *
- * @param pKey The key to write.
- * @param rDateTime The date and time value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const TQDateTime& rDateTime,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a rectangle.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rValue The rectangle value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const TQRect& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a rectangle.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rValue The rectangle value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const TQRect& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a point.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rValue The point value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const TQPoint& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a point.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rValue The point value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const TQPoint& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a size.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rValue The size value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const TQString& pKey, const TQSize& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a (key/value) pair.
- * Same as above, but writes a size.
- *
- * Note: Unlike the other writeEntry() functions, the old value is
- * _not_ returned here!
- *
- * @param pKey The key to write.
- * @param rValue The size value to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writeEntry( const char *pKey, const TQSize& rValue,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * Writes a file path.
- *
- * It is checked whether the path is located under $HOME. If so the
- * path is written out with the user's home-directory replaced with
- * $HOME. The path should be read back with readPathEntry()
- *
- * @param pKey The key to write.
- * @param path The path to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writePathEntry( const TQString& pKey, const TQString & path,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
- /**
- * Writes a file path.
- *
- * It is checked whether the path is located under $HOME. If so the
- * path is written out with the user's home-directory replaced with
- * $HOME. The path should be read back with readPathEntry()
- *
- * @param pKey The key to write.
- * @param path The path to write.
- * @param bPersistent If @p bPersistent is false, the entry's dirty
- * flag will not be set and thus the entry will not be written to
- * disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- */
- void writePathEntry( const char *pKey, const TQString & path,
- bool bPersistent = true, bool bGlobal = false,
- bool bNLS = false );
-
- /**
- * writePathEntry() overridden to accept a list of paths (strings).
- *
- * It is checked whether the paths are located under $HOME. If so each of
- * the paths are written out with the user's home-directory replaced with
- * $HOME. The paths should be read back with readPathListEntry()
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param sep The list separator (default is ",").
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writePathEntry()
- * @see readPathListEntry()
- * @since 3.1.3
- */
- void writePathEntry( const TQString& pKey, const TQStringList &rValue,
- char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
- /**
- * writePathEntry() overridden to accept a list of paths (strings).
- *
- * It is checked whether the paths are located under $HOME. If so each of
- * the paths are written out with the user's home-directory replaced with
- * $HOME. The paths should be read back with readPathListEntry()
- *
- * @param pKey The key to write
- * @param rValue The list to write
- * @param sep The list separator (default is ",").
- * @param bPersistent If @p bPersistent is false, the entry's dirty flag
- * will not be set and thus the entry will not be
- * written to disk at deletion time.
- * @param bGlobal If @p bGlobal is true, the pair is not saved to the
- * application specific config file, but to the
- * global KDE config file.
- * @param bNLS If @p bNLS is true, the locale tag is added to the key
- * when writing it back.
- *
- * @see writePathEntry()
- * @see readPathListEntry()
- * @since 3.1.3
- */
- void writePathEntry( const char *pKey, const TQStringList &rValue,
- char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
-
-
- /**
- * Deletes the entry specified by @p pKey in the current group.
- *
- * @param pKey The key to delete.
- * @param bGlobal If @p bGlobal is true, the pair is not removed from the
- * application specific config file, but to the global KDE config file.
- * @param bNLS If @p bNLS is true, the key with the locale tag is removed.
- */
- void deleteEntry( const TQString& pKey,
- bool bNLS = false, bool bGlobal = false);
- /**
- * Deletes the entry specified by @p pKey in the current group.
- *
- * @param pKey The key to delete.
- * @param bGlobal If @p bGlobal is true, the pair is not removed from the
- * application specific config file, but from the global KDE config file.
- * @param bNLS If @p bNLS is true, the key with the locale tag is removed.
- */
- void deleteEntry( const char *pKey,
- bool bNLS = false, bool bGlobal = false);
-
- /**
- * Deletes a configuration entry group
- *
- * If the group is not empty and bDeep is false, nothing gets
- * deleted and false is returned.
- * If this group is the current group and it is deleted, the
- * current group is undefined and should be set with setGroup()
- * before the next operation on the configuration object.
- *
- * @param group The name of the group
- * @param bDeep Specify whether non-empty groups should be completely
- * deleted (including their entries).
- * @param bGlobal If @p bGlobal is true, the group is not removed from the
- * application specific config file, but from the global KDE config file.
- * @return If the group is not empty and bDeep is false,
- * deleteGroup returns false.
- */
- bool deleteGroup( const TQString& group, bool bDeep = true, bool bGlobal = false );
-
-
- /**
- * Turns on or off "dollar expansion" (see TDEConfigBase introduction)
- * when reading config entries.
- * Dollar sign expansion is initially OFF.
- *
- * @param _bExpand Tf true, dollar expansion is turned on.
- */
- void setDollarExpansion( bool _bExpand = true ) { bExpand = _bExpand; }
-
- /**
- * Returns whether dollar expansion is on or off. It is initially OFF.
- *
- * @return true if dollar expansion is on.
- */
- bool isDollarExpansion() const { return bExpand; }
-
- /**
- * Mark the config object as "clean," i.e. don't write dirty entries
- * at destruction time. If @p bDeep is false, only the global dirty
- * flag of the TDEConfig object gets cleared. If you then call
- * writeEntry() again, the global dirty flag is set again and all
- * dirty entries will be written at a subsequent sync() call.
- *
- * Classes that derive from TDEConfigBase should override this
- * method and implement storage-specific behavior, as well as
- * calling the TDEConfigBase::rollback() explicitly in the initializer.
- *
- * @param bDeep If true, the dirty flags of all entries are cleared,
- * as well as the global dirty flag.
- */
- virtual void rollback( bool bDeep = true );
-
- /**
- * Flushes all changes that currently reside only in memory
- * back to disk / permanent storage. Dirty configuration entries are
- * written to the most specific file available.
- *
- * Asks the back end to flush out all pending writes, and then calls
- * rollback(). No changes are made if the object has @p readOnly
- * status.
- *
- * You should call this from your destructor in derivative classes.
- *
- * @see rollback(), #isReadOnly()
- */
- virtual void sync();
-
- /**
- * Checks whether the config file has any dirty (modified) entries.
- * @return true if the config file has any dirty (modified) entries.
- */
- bool isDirty() const { return bDirty; }
-
- /**
- * Sets the config object's read-only status.
- *
- * @param _ro If true, the config object will not write out any
- * changes to disk even if it is destroyed or sync() is called.
- *
- */
- virtual void setReadOnly(bool _ro) { bReadOnly = _ro; }
-
- /**
- * Returns the read-only status of the config object.
- *
- * @return The read-only status.
- */
- bool isReadOnly() const { return bReadOnly; }
-
- /**
- * Checks whether the key has an entry in the currently active group.
- * Use this to determine whether a key is not specified for the current
- * group (hasKey() returns false). Keys with null data are considered
- * nonexistent.
- *
- * @param key The key to search for.
- * @return If true, the key is available.
- */
- bool hasKey( const TQString& key ) const;
-
- /**
- * Returns a map (tree) of entries for all entries in a particular
- * group. Only the actual entry string is returned, none of the
- * other internal data should be included.
- *
- * @param group A group to get keys from.
- * @return A map of entries in the group specified, indexed by key.
- * The returned map may be empty if the group is not found.
- * @see QMap
- */
- virtual TQMap<TQString, TQString> entryMap(const TQString &group) const = 0;
-
- /**
- * Reparses all configuration files. This is useful for programs
- * that use stand alone graphical configuration tools. The base
- * method implemented here only clears the group list and then
- * appends the default group.
- *
- * Derivative classes should clear any internal data structures and
- * then simply call parseConfigFiles() when implementing this
- * method.
- *
- * @see parseConfigFiles()
- */
- virtual void reparseConfiguration() = 0;
-
- /**
- * Checks whether this configuration file can be modified.
- * @return whether changes may be made to this configuration file.
- */
- bool isImmutable() const;
-
- /**
- * Checks whether it is possible to change the given group.
- * @param group the group to check
- * @return whether changes may be made to @p group in this configuration
- * file.
- */
- bool groupIsImmutable(const TQString &group) const;
-
- /**
- * Checks whether it is possible to change the given entry.
- * @param key the key to check
- * @return whether the entry @p key may be changed in the current group
- * in this configuration file.
- */
- bool entryIsImmutable(const TQString &key) const;
-
- /**
- * Possible return values for getConfigState().
- *
- * @see getConfigState()
- */
- enum ConfigState { NoAccess, ReadOnly, ReadWrite };
-
- /**
- * Returns the state of the app-config object.
- *
- * Possible return values
- * are NoAccess (the application-specific config file could not be
- * opened neither read-write nor read-only), ReadOnly (the
- * application-specific config file is opened read-only, but not
- * read-write) and ReadWrite (the application-specific config
- * file is opened read-write).
- *
- * @see ConfigState()
- * @return the state of the app-config object
- */
- ConfigState getConfigState() const;
-
- /**
- * Check whether the config files are writable.
- * @param warnUser Warn the user if the configuration files are not writable.
- * @return Indicates that all of the configuration files used are writable.
- * @since 3.2
- */
- bool checkConfigFilesWritable(bool warnUser);
-
- /**
- * When set, all readEntry and readXXXEntry calls return the system
- * wide (default) values instead of the user's preference.
- * This is off by default.
- * @since 3.2
- */
- void setReadDefaults(bool b);
-
- /**
- * @returns true if all readEntry and readXXXEntry calls return the system
- * wide (default) values instead of the user's preference.
- * @since 3.2
- */
- bool readDefaults() const;
-
- /**
- * Reverts the entry with key @p key in the current group in the
- * application specific config file to either the system wide (default)
- * value or the value specified in the global KDE config file.
- *
- * To revert entries in the global KDE config file, the global KDE config
- * file should be opened explicitly in a separate config object.
- *
- * @param key The key of the entry to revert.
- * @since 3.2
- */
- void revertToDefault(const TQString &key);
-
- /**
- * Returns whether a default is specified for an entry in either the
- * system wide configuration file or the global KDE config file.
- *
- * If an application computes a default value at runtime for
- * a certain entry, e.g. like:
- * \code
- * TQColor computedDefault = kapp->palette().color(TQPalette::Active, TQColorGroup::Text)
- * TQColor color = config->readEntry(key, computedDefault);
- * \encode
- *
- * Then it may wish to make the following check before
- * writing back changes:
- * \code
- * if ( (value == computedDefault) && !config->hasDefault(key) )
- * config->revertToDefault(key)
- * else
- * config->writeEntry(key, value)
- * \endcode
- *
- * This ensures that as long as the entry is not modified to differ from
- * the computed default, the application will keep using the computed default
- * and will follow changes the computed default makes over time.
- * @param key The key of the entry to check.
- * @since 3.2
- */
- bool hasDefault(const TQString &key) const;
-
-protected:
- /**
- * Reads the locale and put in the configuration data struct.
- * Note that this should be done in the constructor, but this is not
- * possible due to some mutual dependencies in TDEApplication::init()
- */
- void setLocale();
-
- /**
- * Sets the global dirty flag of the config object
- *
- * @param _bDirty How to mark the object's dirty status
- */
- virtual void setDirty(bool _bDirty = true) { bDirty = _bDirty; }
-
- /**
- * Parses all configuration files for a configuration object.
- *
- * The actual parsing is done by the associated TDEConfigBackEnd.
- */
- virtual void parseConfigFiles();
-
- /**
- * Returns a map (tree) of the entries in the specified group.
- * This may or may not return all entries that belong to the
- * config object. The only guarantee that you are given is that
- * any entries that are dirty (i.e. modified and not yet written back
- * to the disk) will be contained in the map. Some derivative
- * classes may choose to return everything.
- *
- * Do not use this function, the implementation / return type are
- * subject to change.
- *
- * @param pGroup The group to provide a KEntryMap for.
- * @return The map of the entries in the group.
- * @internal
- */
- virtual KEntryMap internalEntryMap( const TQString& pGroup ) const = 0;
-
- /**
- * Returns a map (tree) of the entries in the tree.
- *
- * Do not use this function, the implementation / return type are
- * subject to change.
- *
- * @return A map of the entries in the tree.
- *
- * @internal
- *
- */
- virtual KEntryMap internalEntryMap() const = 0;
-
- /**
- * Inserts a (key/value) pair into the internal storage mechanism of
- * the configuration object. Classes that derive from TDEConfigBase
- * will need to implement this method in a storage-specific manner.
- *
- * Do not use this function, the implementation / return type are
- * subject to change.
- *
- * @param _key The key to insert. It contains information both on
- * the group of the key and the key itself. If the key already
- * exists, the old value will be replaced.
- * @param _data the KEntry that is to be stored.
- * @param _checkGroup When false, assume that the group already exists.
- * @internal
- */
- virtual void putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup = true) = 0;
-
- /**
- * Looks up an entry in the config object's internal structure.
- * Classes that derive from TDEConfigBase will need to implement this
- * method in a storage-specific manner.
- *
- * Do not use this function, the implementation and return type are
- * subject to change.
- *
- * @param _key The key to look up It contains information both on
- * the group of the key and the entry's key itself.
- * @return The KEntry value (data) found for the key. @p KEntry.aValue
- * will be the null string if nothing was located.
- * @internal
- */
- virtual KEntry lookupData(const KEntryKey &_key) const = 0;
-
- virtual bool internalHasGroup(const TQCString &group) const = 0;
-
- /**
- * A back end for loading/saving to disk in a particular format.
- */
- TDEConfigBackEnd *backEnd;
-public:
- /**
- * Overloaded public methods:
- */
- void setGroup( const TQCString &pGroup );
- void setGroup( const char *pGroup );
- bool hasGroup(const TQCString &_pGroup) const;
- bool hasGroup(const char *_pGroup) const;
- bool hasKey( const char *pKey ) const;
-
-protected:
- TQCString readEntryUtf8( const char *pKey) const;
- bool hasTranslatedKey( const char *pKey ) const;
-
- /**
- * The currently selected group. */
- TQCString mGroup;
-
- /**
- * The locale to retrieve keys under if possible, i.e en_US or fr. */
- TQCString aLocaleString;
-
- /**
- * Indicates whether there are any dirty entries in the config object
- * that need to be written back to disk. */
- bool bDirty;
-
- bool bLocaleInitialized;
- bool bReadOnly; // currently only used by KSimpleConfig
- mutable bool bExpand; // whether dollar expansion is used
-
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- class TDEConfigBasePrivate;
- TDEConfigBasePrivate *d;
-
- void writeEntry( const char *pKey, const TQString &rValue,
- bool bPersistent, bool bGlobal, bool bNLS, bool bExpand );
- void writeEntry( const char *pKey, const TQStringList &rValue,
- char sep, bool bPersistent, bool bGlobal, bool bNLS, bool bExpand );
-
-};
-
-class TDEConfigGroupSaverPrivate;
-
-/**
- * Helper class to facilitate working with TDEConfig / KSimpleConfig
- * groups.
- *
- * Careful programmers always set the group of a
- * TDEConfig KSimpleConfig object to the group they want to read from
- * and set it back to the old one of afterwards. This is usually
- * written as:
- * \code
- *
- * TQString oldgroup config->group();
- * config->setGroup( "TheGroupThatIWant" );
- * ...
- * config->writeEntry( "Blah", "Blubb" );
- *
- * config->setGroup( oldgroup );
- * \endcode
- *
- * In order to facilitate this task, you can use
- * TDEConfigGroupSaver. Simply construct such an object ON THE STACK
- * when you want to switch to a new group. Then, when the object goes
- * out of scope, the group will automatically be restored. If you
- * want to use several different groups within a function or method,
- * you can still use TDEConfigGroupSaver: Simply enclose all work with
- * one group (including the creation of the TDEConfigGroupSaver object)
- * in one block.
- *
- * @deprecated This class is deprecated and will be removed in KDE 4.
- * TDEConfigGroup provides similar functionality in a more object oriented
- * way.
- *
- * @author Matthias Kalle Dalheimer <kalle@kde.org>
- * @see TDEConfigBase, TDEConfig, KSimpleConfig, TDEConfigGroup
- * @short Helper class for easier use of TDEConfig/KSimpleConfig groups
- */
-
-class TDECORE_EXPORT TDEConfigGroupSaver // KDE4 remove
-{
-public:
- /**
- * Constructor. You pass a pointer to the TDEConfigBase-derived
- * object you want to work with and a string indicating the _new_
- * group.
- *
- * @param config The TDEConfigBase-derived object this
- * TDEConfigGroupSaver works on.
- * @param group The new group that the config object should switch to.
- */
- TDEConfigGroupSaver( TDEConfigBase* config, TQString group )
- /* KDE 4 : make the second parameter const TQString & */
- : _config(config), _oldgroup(config->group())
- { _config->setGroup( group ); }
-
- TDEConfigGroupSaver( TDEConfigBase* config, const char *group )
- : _config(config), _oldgroup(config->group())
- { _config->setGroup( group ); }
-
- TDEConfigGroupSaver( TDEConfigBase* config, const TQCString &group )
- : _config(config), _oldgroup(config->group())
- { _config->setGroup( group ); }
-
- ~TDEConfigGroupSaver() { _config->setGroup( _oldgroup ); }
-
- TDEConfigBase* config() { return _config; };
-
-private:
- TDEConfigBase* _config;
- TQString _oldgroup;
-
- TDEConfigGroupSaver(const TDEConfigGroupSaver&);
- TDEConfigGroupSaver& operator=(const TDEConfigGroupSaver&);
-
- TDEConfigGroupSaverPrivate *d;
-};
-
-class TDEConfigGroupPrivate;
-
-/**
- * A TDEConfigBase derived class for one specific group in a TDEConfig object.
- */
-class TDECORE_EXPORT TDEConfigGroup: public TDEConfigBase
-{
-public:
- /**
- * Construct a config group corresponding to @p group in @p master.
- * @p group is the group name encoded in UTF-8.
- */
- TDEConfigGroup(TDEConfigBase *master, const TQCString &group);
- /**
- * This is an overloaded constructor provided for convenience.
- * It behaves essentially like the above function.
- *
- * Construct a config group corresponding to @p group in @p master
- */
- TDEConfigGroup(TDEConfigBase *master, const TQString &group);
- /**
- * This is an overloaded constructor provided for convenience.
- * It behaves essentially like the above function.
- *
- * Construct a config group corresponding to @p group in @p master
- * @p group is the group name encoded in UTF-8.
- */
- TDEConfigGroup(TDEConfigBase *master, const char * group);
-
- /**
- * Delete all entries in the entire group
- * @param bGlobal If @p bGlobal is true, the entries are not removed
- * from the application specific config file, but from the global
- * KDE config file.
- */
- void deleteGroup(bool bGlobal = false);
-
- /**
- * Checks whether it is possible to change this group.
- * @return whether changes may be made to this group in this configuration
- * file.
- * @since 3.4
- */
- bool groupIsImmutable() const;
-
- // The following functions are reimplemented:
- virtual void setDirty(bool _bDirty);
- virtual void putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup = true);
- virtual KEntry lookupData(const KEntryKey &_key) const;
- virtual void sync();
-
-private:
- // Hide the following members:
- void setGroup() { }
- void setDesktopGroup() { }
- void group() { }
- void hasGroup() { }
- void setReadOnly(bool) { }
- void isDirty() { }
-
- // The following members are not used.
- virtual TQStringList groupList() const { return TQStringList(); }
- virtual void rollback(bool) { }
- virtual void reparseConfiguration() { }
- virtual TQMap<TQString, TQString> entryMap(const TQString &) const
- { return TQMap<TQString,TQString>(); }
- virtual KEntryMap internalEntryMap( const TQString&) const
- { return KEntryMap(); }
- virtual KEntryMap internalEntryMap() const
- { return KEntryMap(); }
- virtual bool internalHasGroup(const TQCString &) const
- { return false; }
-
- void getConfigState() { }
-
- TDEConfigBase *mMaster;
-protected:
- virtual void virtual_hook( int id, void* data );
-private:
- TDEConfigGroupPrivate* d;
-};
-
-#endif
diff --git a/tdecore/kconfigdialogmanager.cpp b/tdecore/kconfigdialogmanager.cpp
deleted file mode 100644
index dfb81853b..000000000
--- a/tdecore/kconfigdialogmanager.cpp
+++ /dev/null
@@ -1,398 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (C) 2003 Benjamin C Meyer (ben+tdelibs at meyerhome dot net)
- * Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "kconfigdialogmanager.h"
-
-#include <tqbuttongroup.h>
-#include <tqcombobox.h>
-#include <tqlabel.h>
-#include <tqmetaobject.h>
-#include <tqobjectlist.h>
-#include <tqsqlpropertymap.h>
-#include <tqtimer.h>
-#include <tqwhatsthis.h>
-
-#include <kapplication.h>
-#include <kconfigskeleton.h>
-#include <kdebug.h>
-#include <kglobal.h>
-
-#include <assert.h>
-
-class TDEConfigDialogManager::Private {
-
-public:
- Private() : insideGroupBox(false) { }
-
-public:
- TQDict<TQWidget> knownWidget;
- TQDict<TQWidget> buddyWidget;
- bool insideGroupBox;
-};
-
-TDEConfigDialogManager::TDEConfigDialogManager(TQWidget *parent, TDEConfigSkeleton *conf, const char *name)
- : TQObject(parent, name), m_conf(conf), m_dialog(parent)
-{
- d = new Private();
-
- kapp->installKDEPropertyMap();
- propertyMap = TQSqlPropertyMap::defaultMap();
-
- init(true);
-}
-
-TDEConfigDialogManager::~TDEConfigDialogManager()
-{
- delete d;
-}
-
-void TDEConfigDialogManager::init(bool trackChanges)
-{
- if(trackChanges)
- {
- // QT
- changedMap.insert(TQBUTTON_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
- changedMap.insert(TQCHECKBOX_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
- changedMap.insert(TQPUSHBUTTON_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
- changedMap.insert(TQRADIOBUTTON_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
- // We can only store one thing, so you can't have
- // a ButtonGroup that is checkable.
- changedMap.insert(TQBUTTONGROUP_OBJECT_NAME_STRING, TQT_SIGNAL(clicked(int)));
- changedMap.insert(TQGROUPBOX_OBJECT_NAME_STRING, TQT_SIGNAL(toggled(bool)));
- changedMap.insert(TQCOMBOBOX_OBJECT_NAME_STRING, TQT_SIGNAL(activated (int)));
- //qsqlproperty map doesn't store the text, but the value!
- //changedMap.insert(TQCOMBOBOX_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged(const TQString &)));
- changedMap.insert(TQDATEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(const TQDate &)));
- changedMap.insert(TQDATETIMEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(const TQDateTime &)));
- changedMap.insert(TQDIAL_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged (int)));
- changedMap.insert(TQLINEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged(const TQString &)));
- changedMap.insert(TQSLIDER_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(int)));
- changedMap.insert(TQSPINBOX_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(int)));
- changedMap.insert(TQTIMEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(const TQTime &)));
- changedMap.insert(TQTEXTEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged()));
- changedMap.insert(TQTEXTBROWSER_OBJECT_NAME_STRING, TQT_SIGNAL(sourceChanged(const TQString &)));
- changedMap.insert(TQMULTILINEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged()));
- changedMap.insert(TQLISTBOX_OBJECT_NAME_STRING, TQT_SIGNAL(selectionChanged()));
- changedMap.insert(TQTABWIDGET_OBJECT_NAME_STRING, TQT_SIGNAL(currentChanged(TQWidget *)));
-
- // KDE
- changedMap.insert( "KComboBox", TQT_SIGNAL(activated (int)));
- changedMap.insert( "KFontCombo", TQT_SIGNAL(activated (int)));
- changedMap.insert( "KFontRequester", TQT_SIGNAL(fontSelected(const TQFont &)));
- changedMap.insert( "KFontChooser", TQT_SIGNAL(fontSelected(const TQFont &)));
- changedMap.insert( "KHistoryCombo", TQT_SIGNAL(activated (int)));
-
- changedMap.insert( "KColorButton", TQT_SIGNAL(changed(const TQColor &)));
- changedMap.insert( "KDatePicker", TQT_SIGNAL(dateSelected (TQDate)));
- changedMap.insert( "KDateWidget", TQT_SIGNAL(changed (TQDate)));
- changedMap.insert( "KDateTimeWidget", TQT_SIGNAL(valueChanged (const TQDateTime &)));
- changedMap.insert( "KEditListBox", TQT_SIGNAL(changed()));
- changedMap.insert( "KListBox", TQT_SIGNAL(selectionChanged()));
- changedMap.insert( "KLineEdit", TQT_SIGNAL(textChanged(const TQString &)));
- changedMap.insert( "KPasswordEdit", TQT_SIGNAL(textChanged(const TQString &)));
- changedMap.insert( "KRestrictedLine", TQT_SIGNAL(textChanged(const TQString &)));
- changedMap.insert( "KTextBrowser", TQT_SIGNAL(sourceChanged(const TQString &)));
- changedMap.insert( "KTextEdit", TQT_SIGNAL(textChanged()));
- changedMap.insert( "KURLRequester", TQT_SIGNAL(textChanged (const TQString& )));
- changedMap.insert( "KIntNumInput", TQT_SIGNAL(valueChanged (int)));
- changedMap.insert( "KIntSpinBox", TQT_SIGNAL(valueChanged (int)));
- changedMap.insert( "KDoubleNumInput", TQT_SIGNAL(valueChanged (double)));
- }
-
- // Go through all of the children of the widgets and find all known widgets
- (void) parseChildren(m_dialog, trackChanges);
-}
-
-void TDEConfigDialogManager::addWidget(TQWidget *widget)
-{
- (void) parseChildren(widget, true);
-}
-
-void TDEConfigDialogManager::setupWidget(TQWidget *widget, TDEConfigSkeletonItem *item)
-{
- TQVariant minValue = item->minValue();
- if (minValue.isValid())
- {
- if (widget->metaObject()->findProperty("minValue", true) != -1)
- widget->setProperty("minValue", minValue);
- }
- TQVariant maxValue = item->maxValue();
- if (maxValue.isValid())
- {
- if (widget->metaObject()->findProperty("maxValue", true) != -1)
- widget->setProperty("maxValue", maxValue);
- }
- if (TQWhatsThis::textFor( widget ).isEmpty())
- {
- TQString whatsThis = item->whatsThis();
- if ( !whatsThis.isEmpty() )
- {
- TQWhatsThis::add( widget, whatsThis );
- }
- }
-}
-
-bool TDEConfigDialogManager::parseChildren(const TQWidget *widget, bool trackChanges)
-{
- bool valueChanged = false;
- const TQObjectList listOfChildren = widget->childrenListObject();
- if(listOfChildren.isEmpty())
- return valueChanged;
-
- TQObject *object;
- for( TQObjectListIterator it( listOfChildren );
- (object = it.current()); ++it )
- {
- if(!object->isWidgetType())
- continue; // Skip non-widgets
-
- TQWidget *childWidget = (TQWidget *)object;
-
- const char *widgetName = childWidget->name(0);
- bool bParseChildren = true;
- bool bSaveInsideGroupBox = d->insideGroupBox;
-
- if (widgetName && (strncmp(widgetName, "kcfg_", 5) == 0))
- {
- // This is one of our widgets!
- TQString configId = widgetName+5;
- TDEConfigSkeletonItem *item = m_conf->findItem(configId);
- if (item)
- {
- d->knownWidget.insert(configId, childWidget);
-
- setupWidget(childWidget, item);
-
- TQMap<TQString, TQCString>::const_iterator changedIt = changedMap.find(childWidget->className());
-
- if (changedIt == changedMap.end())
- {
- // If the class name of the widget wasn't in the monitored widgets map, then look for
- // it again using the super class name. This fixes a problem with using QtRuby/Korundum
- // widgets with TDEConfigXT where 'Qt::Widget' wasn't being seen a the real deal, even
- // though it was a 'QWidget'.
- changedIt = changedMap.find(childWidget->metaObject()->superClassName());
- }
-
- if (changedIt == changedMap.end())
- {
- kdWarning(178) << "Don't know how to monitor widget '" << childWidget->className() << "' for changes!" << endl;
- }
- else
- {
- connect(childWidget, *changedIt,
- this, TQT_SIGNAL(widgetModified()));
-
- TQGroupBox *gb = dynamic_cast<TQGroupBox *>(childWidget);
- if (!gb)
- bParseChildren = false;
- else
- d->insideGroupBox = true;
-
- TQComboBox *cb = dynamic_cast<TQComboBox *>(childWidget);
- if (cb && cb->editable())
- connect(cb, TQT_SIGNAL(textChanged(const TQString &)),
- this, TQT_SIGNAL(widgetModified()));
- }
- }
- else
- {
- kdWarning(178) << "A widget named '" << widgetName << "' was found but there is no setting named '" << configId << "'" << endl;
- }
- }
- else if (childWidget->inherits(TQLABEL_OBJECT_NAME_STRING))
- {
- TQLabel *label = static_cast<TQLabel *>(childWidget);
- TQWidget *buddy = label->buddy();
- if (!buddy)
- continue;
- const char *buddyName = buddy->name(0);
- if (buddyName && (strncmp(buddyName, "kcfg_", 5) == 0))
- {
- // This is one of our widgets!
- TQString configId = buddyName+5;
- d->buddyWidget.insert(configId, childWidget);
- }
- }
-#ifndef NDEBUG
- else if (widgetName)
- {
- TQMap<TQString, TQCString>::const_iterator changedIt = changedMap.find(childWidget->className());
- if (changedIt != changedMap.end())
- {
- if ((!d->insideGroupBox || !childWidget->inherits(TQRADIOBUTTON_OBJECT_NAME_STRING)) &&
- !childWidget->inherits(TQGROUPBOX_OBJECT_NAME_STRING))
- kdDebug(178) << "Widget '" << widgetName << "' (" << childWidget->className() << ") remains unmanaged." << endl;
- }
- }
-#endif
-
- if(bParseChildren)
- {
- // this widget is not known as something we can store.
- // Maybe we can store one of its children.
- valueChanged |= parseChildren(childWidget, trackChanges);
- }
- d->insideGroupBox = bSaveInsideGroupBox;
- }
- return valueChanged;
-}
-
-void TDEConfigDialogManager::updateWidgets()
-{
- bool changed = false;
- bool bSignalsBlocked = signalsBlocked();
- blockSignals(true);
-
- TQWidget *widget;
- for( TQDictIterator<TQWidget> it( d->knownWidget );
- (widget = it.current()); ++it )
- {
- TDEConfigSkeletonItem *item = m_conf->findItem(it.currentKey());
- if (!item)
- {
- kdWarning(178) << "The setting '" << it.currentKey() << "' has disappeared!" << endl;
- continue;
- }
-
- TQVariant p = item->property();
- if (p != property(widget))
- {
- setProperty(widget, p);
-// kdDebug(178) << "The setting '" << it.currentKey() << "' [" << widget->className() << "] has changed" << endl;
- changed = true;
- }
- if (item->isImmutable())
- {
- widget->setEnabled(false);
- TQWidget *buddy = d->buddyWidget.find(it.currentKey());
- if (buddy)
- buddy->setEnabled(false);
- }
- }
- blockSignals(bSignalsBlocked);
-
- if (changed)
- TQTimer::singleShot(0, this, TQT_SIGNAL(widgetModified()));
-}
-
-void TDEConfigDialogManager::updateWidgetsDefault()
-{
- bool bUseDefaults = m_conf->useDefaults(true);
- updateWidgets();
- m_conf->useDefaults(bUseDefaults);
-}
-
-void TDEConfigDialogManager::updateSettings()
-{
- bool changed = false;
-
- TQWidget *widget;
- for( TQDictIterator<TQWidget> it( d->knownWidget );
- (widget = it.current()); ++it )
- {
- TDEConfigSkeletonItem *item = m_conf->findItem(it.currentKey());
- if (!item)
- {
- kdWarning(178) << "The setting '" << it.currentKey() << "' has disappeared!" << endl;
- continue;
- }
-
- TQVariant p = property(widget);
- if (p != item->property())
- {
- item->setProperty(p);
- changed = true;
- }
- }
- if (changed)
- {
- m_conf->writeConfig();
- emit settingsChanged();
- }
-}
-
-void TDEConfigDialogManager::setProperty(TQWidget *w, const TQVariant &v)
-{
- TQButtonGroup *bg = dynamic_cast<TQButtonGroup *>(w);
- if (bg)
- {
- bg->setButton(v.toInt());
- return;
- }
-
- TQComboBox *cb = dynamic_cast<TQComboBox *>(w);
- if (cb && cb->editable())
- {
- cb->setCurrentText(v.toString());
- return;
- }
-
- propertyMap->setProperty(w, v);
-}
-
-TQVariant TDEConfigDialogManager::property(TQWidget *w)
-{
- TQButtonGroup *bg = dynamic_cast<TQButtonGroup *>(w);
- if (bg)
- return TQVariant(bg->selectedId());
-
- TQComboBox *cb = dynamic_cast<TQComboBox *>(w);
- if (cb && cb->editable())
- return TQVariant(cb->currentText());
-
- return propertyMap->property(w);
-}
-
-bool TDEConfigDialogManager::hasChanged()
-{
-
- TQWidget *widget;
- for( TQDictIterator<TQWidget> it( d->knownWidget );
- (widget = it.current()); ++it )
- {
- TDEConfigSkeletonItem *item = m_conf->findItem(it.currentKey());
- if (!item)
- {
- kdWarning(178) << "The setting '" << it.currentKey() << "' has disappeared!" << endl;
- continue;
- }
-
- TQVariant p = property(widget);
- if (p != item->property())
- {
-// kdDebug(178) << "Widget for '" << it.currentKey() << "' has changed." << endl;
- return true;
- }
- }
- return false;
-}
-
-bool TDEConfigDialogManager::isDefault()
-{
- bool bUseDefaults = m_conf->useDefaults(true);
- bool result = !hasChanged();
- m_conf->useDefaults(bUseDefaults);
- return result;
-}
-
-#include "kconfigdialogmanager.moc"
-
diff --git a/tdecore/kconfigskeleton.cpp b/tdecore/kconfigskeleton.cpp
deleted file mode 100644
index afc45bb87..000000000
--- a/tdecore/kconfigskeleton.cpp
+++ /dev/null
@@ -1,1207 +0,0 @@
-/*
- This file is part of KOrganizer.
- Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>
- Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tqcolor.h>
-#include <tqvariant.h>
-
-#include <kconfig.h>
-#include <kstandarddirs.h>
-#include <kglobal.h>
-#include <kglobalsettings.h>
-#include <kdebug.h>
-
-#include "kstringhandler.h"
-
-#include "kconfigskeleton.h"
-
-void TDEConfigSkeletonItem::readImmutability( TDEConfig *config )
-{
- mIsImmutable = config->entryIsImmutable( mKey );
-}
-
-
-TDEConfigSkeleton::ItemString::ItemString( const TQString &group, const TQString &key,
- TQString &reference,
- const TQString &defaultValue,
- Type type )
- : TDEConfigSkeletonGenericItem<TQString>( group, key, reference, defaultValue ),
- mType( type )
-{
-}
-
-void TDEConfigSkeleton::ItemString::writeConfig( TDEConfig *config )
-{
- if ( mReference != mLoadedValue ) // WABA: Is this test needed?
- {
- config->setGroup( mGroup );
- if ((mDefault == mReference) && !config->hasDefault( mKey))
- config->revertToDefault( mKey );
- else if ( mType == Path )
- config->writePathEntry( mKey, mReference );
- else if ( mType == Password )
- config->writeEntry( mKey, KStringHandler::obscure( mReference ) );
- else
- config->writeEntry( mKey, mReference );
- }
-}
-
-
-void TDEConfigSkeleton::ItemString::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
-
- if ( mType == Path )
- {
- mReference = config->readPathEntry( mKey, mDefault );
- }
- else if ( mType == Password )
- {
- TQString value = config->readEntry( mKey,
- KStringHandler::obscure( mDefault ) );
- mReference = KStringHandler::obscure( value );
- }
- else
- {
- mReference = config->readEntry( mKey, mDefault );
- }
-
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemString::setProperty(const TQVariant & p)
-{
- mReference = p.toString();
-}
-
-TQVariant TDEConfigSkeleton::ItemString::property() const
-{
- return TQVariant(mReference);
-}
-
-TDEConfigSkeleton::ItemPassword::ItemPassword( const TQString &group, const TQString &key,
- TQString &reference,
- const TQString &defaultValue)
- : ItemString( group, key, reference, defaultValue, Password )
-{
-}
-
-TDEConfigSkeleton::ItemPath::ItemPath( const TQString &group, const TQString &key,
- TQString &reference,
- const TQString &defaultValue)
- : ItemString( group, key, reference, defaultValue, Path )
-{
-}
-
-TDEConfigSkeleton::ItemProperty::ItemProperty( const TQString &group,
- const TQString &key,
- TQVariant &reference,
- TQVariant defaultValue )
- : TDEConfigSkeletonGenericItem<TQVariant>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemProperty::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readPropertyEntry( mKey, mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemProperty::setProperty(const TQVariant & p)
-{
- mReference = p;
-}
-
-TQVariant TDEConfigSkeleton::ItemProperty::property() const
-{
- return mReference;
-}
-
-TDEConfigSkeleton::ItemBool::ItemBool( const TQString &group, const TQString &key,
- bool &reference, bool defaultValue )
- : TDEConfigSkeletonGenericItem<bool>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemBool::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readBoolEntry( mKey, mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemBool::setProperty(const TQVariant & p)
-{
- mReference = p.toBool();
-}
-
-TQVariant TDEConfigSkeleton::ItemBool::property() const
-{
- return TQVariant( mReference, 42 /* dummy */ );
-}
-
-
-TDEConfigSkeleton::ItemInt::ItemInt( const TQString &group, const TQString &key,
- int &reference, int defaultValue )
- : TDEConfigSkeletonGenericItem<int>( group, key, reference, defaultValue )
- ,mHasMin(false), mHasMax(false)
-{
-}
-
-void TDEConfigSkeleton::ItemInt::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readNumEntry( mKey, mDefault );
- if (mHasMin)
- mReference = QMAX(mReference, mMin);
- if (mHasMax)
- mReference = QMIN(mReference, mMax);
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemInt::setProperty(const TQVariant & p)
-{
- mReference = p.toInt();
-}
-
-TQVariant TDEConfigSkeleton::ItemInt::property() const
-{
- return TQVariant(mReference);
-}
-
-TQVariant TDEConfigSkeleton::ItemInt::minValue() const
-{
- if (mHasMin)
- return TQVariant(mMin);
- return TQVariant();
-}
-
-TQVariant TDEConfigSkeleton::ItemInt::maxValue() const
-{
- if (mHasMax)
- return TQVariant(mMax);
- return TQVariant();
-}
-
-void TDEConfigSkeleton::ItemInt::setMinValue(int v)
-{
- mHasMin = true;
- mMin = v;
-}
-
-void TDEConfigSkeleton::ItemInt::setMaxValue(int v)
-{
- mHasMax = true;
- mMax = v;
-}
-
-
-TDEConfigSkeleton::ItemInt64::ItemInt64( const TQString &group, const TQString &key,
- TQ_INT64 &reference, TQ_INT64 defaultValue )
- : TDEConfigSkeletonGenericItem<TQ_INT64>( group, key, reference, defaultValue )
- ,mHasMin(false), mHasMax(false)
-{
-}
-
-void TDEConfigSkeleton::ItemInt64::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readNum64Entry( mKey, mDefault );
- if (mHasMin)
- mReference = QMAX(mReference, mMin);
- if (mHasMax)
- mReference = QMIN(mReference, mMax);
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemInt64::setProperty(const TQVariant & p)
-{
- mReference = p.toLongLong();
-}
-
-TQVariant TDEConfigSkeleton::ItemInt64::property() const
-{
- return TQVariant(mReference);
-}
-
-TQVariant TDEConfigSkeleton::ItemInt64::minValue() const
-{
- if (mHasMin)
- return TQVariant(mMin);
- return TQVariant();
-}
-
-TQVariant TDEConfigSkeleton::ItemInt64::maxValue() const
-{
- if (mHasMax)
- return TQVariant(mMax);
- return TQVariant();
-}
-
-void TDEConfigSkeleton::ItemInt64::setMinValue(TQ_INT64 v)
-{
- mHasMin = true;
- mMin = v;
-}
-
-void TDEConfigSkeleton::ItemInt64::setMaxValue(TQ_INT64 v)
-{
- mHasMax = true;
- mMax = v;
-}
-
-TDEConfigSkeleton::ItemEnum::ItemEnum( const TQString &group, const TQString &key,
- int &reference,
- const TQValueList<Choice> &choices,
- int defaultValue )
- : ItemInt( group, key, reference, defaultValue ), mChoices( choices )
-{
-}
-
-void TDEConfigSkeleton::ItemEnum::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- if (!config->hasKey(mKey))
- {
- mReference = mDefault;
- }
- else
- {
- int i = 0;
- mReference = -1;
- TQString tmp = config->readEntry( mKey ).lower();
- for(TQValueList<Choice>::ConstIterator it = mChoices.begin();
- it != mChoices.end(); ++it, ++i)
- {
- if ((*it).name.lower() == tmp)
- {
- mReference = i;
- break;
- }
- }
- if (mReference == -1)
- mReference = config->readNumEntry( mKey, mDefault );
- }
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemEnum::writeConfig( TDEConfig *config )
-{
- if ( mReference != mLoadedValue ) // WABA: Is this test needed?
- {
- config->setGroup( mGroup );
- if ((mDefault == mReference) && !config->hasDefault( mKey))
- config->revertToDefault( mKey );
- else if ((mReference >= 0) && (mReference < (int) mChoices.count()))
- config->writeEntry( mKey, mChoices[mReference].name );
- else
- config->writeEntry( mKey, mReference );
- }
-}
-
-TQValueList<TDEConfigSkeleton::ItemEnum::Choice> TDEConfigSkeleton::ItemEnum::choices() const
-{
- return mChoices;
-}
-
-
-TDEConfigSkeleton::ItemUInt::ItemUInt( const TQString &group, const TQString &key,
- unsigned int &reference,
- unsigned int defaultValue )
- : TDEConfigSkeletonGenericItem<unsigned int>( group, key, reference, defaultValue )
- ,mHasMin(false), mHasMax(false)
-{
-}
-
-void TDEConfigSkeleton::ItemUInt::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readUnsignedNumEntry( mKey, mDefault );
- if (mHasMin)
- mReference = QMAX(mReference, mMin);
- if (mHasMax)
- mReference = QMIN(mReference, mMax);
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemUInt::setProperty(const TQVariant & p)
-{
- mReference = p.toUInt();
-}
-
-TQVariant TDEConfigSkeleton::ItemUInt::property() const
-{
- return TQVariant(mReference);
-}
-
-TQVariant TDEConfigSkeleton::ItemUInt::minValue() const
-{
- if (mHasMin)
- return TQVariant(mMin);
- return TQVariant();
-}
-
-TQVariant TDEConfigSkeleton::ItemUInt::maxValue() const
-{
- if (mHasMax)
- return TQVariant(mMax);
- return TQVariant();
-}
-
-void TDEConfigSkeleton::ItemUInt::setMinValue(unsigned int v)
-{
- mHasMin = true;
- mMin = v;
-}
-
-void TDEConfigSkeleton::ItemUInt::setMaxValue(unsigned int v)
-{
- mHasMax = true;
- mMax = v;
-}
-
-
-TDEConfigSkeleton::ItemUInt64::ItemUInt64( const TQString &group, const TQString &key,
- TQ_UINT64 &reference, TQ_UINT64 defaultValue )
- : TDEConfigSkeletonGenericItem<TQ_UINT64>( group, key, reference, defaultValue )
- ,mHasMin(false), mHasMax(false)
-{
-}
-
-void TDEConfigSkeleton::ItemUInt64::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readUnsignedNum64Entry( mKey, mDefault );
- if (mHasMin)
- mReference = QMAX(mReference, mMin);
- if (mHasMax)
- mReference = QMIN(mReference, mMax);
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemUInt64::setProperty(const TQVariant & p)
-{
- mReference = p.toULongLong();
-}
-
-TQVariant TDEConfigSkeleton::ItemUInt64::property() const
-{
- return TQVariant(mReference);
-}
-
-TQVariant TDEConfigSkeleton::ItemUInt64::minValue() const
-{
- if (mHasMin)
- return TQVariant(mMin);
- return TQVariant();
-}
-
-TQVariant TDEConfigSkeleton::ItemUInt64::maxValue() const
-{
- if (mHasMax)
- return TQVariant(mMax);
- return TQVariant();
-}
-
-void TDEConfigSkeleton::ItemUInt64::setMinValue(TQ_UINT64 v)
-{
- mHasMin = true;
- mMin = v;
-}
-
-void TDEConfigSkeleton::ItemUInt64::setMaxValue(TQ_UINT64 v)
-{
- mHasMax = true;
- mMax = v;
-}
-
-TDEConfigSkeleton::ItemLong::ItemLong( const TQString &group, const TQString &key,
- long &reference, long defaultValue )
- : TDEConfigSkeletonGenericItem<long>( group, key, reference, defaultValue )
- ,mHasMin(false), mHasMax(false)
-{
-}
-
-void TDEConfigSkeleton::ItemLong::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readLongNumEntry( mKey, mDefault );
- if (mHasMin)
- mReference = QMAX(mReference, mMin);
- if (mHasMax)
- mReference = QMIN(mReference, mMax);
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemLong::setProperty(const TQVariant & p)
-{
- mReference = p.toLongLong();
-}
-
-TQVariant TDEConfigSkeleton::ItemLong::property() const
-{
- return TQVariant((TQ_LLONG) mReference);
-}
-
-TQVariant TDEConfigSkeleton::ItemLong::minValue() const
-{
- if (mHasMin)
- return TQVariant((TQ_LLONG) mMin);
- return TQVariant();
-}
-
-TQVariant TDEConfigSkeleton::ItemLong::maxValue() const
-{
- if (mHasMax)
- return TQVariant((TQ_LLONG) mMax);
- return TQVariant();
-}
-
-void TDEConfigSkeleton::ItemLong::setMinValue(long v)
-{
- mHasMin = true;
- mMin = v;
-}
-
-void TDEConfigSkeleton::ItemLong::setMaxValue(long v)
-{
- mHasMax = true;
- mMax = v;
-}
-
-
-TDEConfigSkeleton::ItemULong::ItemULong( const TQString &group, const TQString &key,
- unsigned long &reference,
- unsigned long defaultValue )
- : TDEConfigSkeletonGenericItem<unsigned long>( group, key, reference, defaultValue )
- ,mHasMin(false), mHasMax(false)
-{
-}
-
-void TDEConfigSkeleton::ItemULong::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readUnsignedLongNumEntry( mKey, mDefault );
- if (mHasMin)
- mReference = QMAX(mReference, mMin);
- if (mHasMax)
- mReference = QMIN(mReference, mMax);
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemULong::setProperty(const TQVariant & p)
-{
- mReference = p.toULongLong();
-}
-
-TQVariant TDEConfigSkeleton::ItemULong::property() const
-{
- return TQVariant((TQ_ULLONG) mReference);
-}
-
-TQVariant TDEConfigSkeleton::ItemULong::minValue() const
-{
- if (mHasMin)
- return TQVariant((TQ_ULLONG) mMin);
- return TQVariant();
-}
-
-TQVariant TDEConfigSkeleton::ItemULong::maxValue() const
-{
- if (mHasMax)
- return TQVariant((TQ_ULLONG) mMax);
- return TQVariant();
-}
-
-void TDEConfigSkeleton::ItemULong::setMinValue(unsigned long v)
-{
- mHasMin = true;
- mMin = v;
-}
-
-void TDEConfigSkeleton::ItemULong::setMaxValue(unsigned long v)
-{
- mHasMax = true;
- mMax = v;
-}
-
-
-TDEConfigSkeleton::ItemDouble::ItemDouble( const TQString &group, const TQString &key,
- double &reference, double defaultValue )
- : TDEConfigSkeletonGenericItem<double>( group, key, reference, defaultValue )
- ,mHasMin(false), mHasMax(false)
-{
-}
-
-void TDEConfigSkeleton::ItemDouble::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readDoubleNumEntry( mKey, mDefault );
- if (mHasMin)
- mReference = QMAX(mReference, mMin);
- if (mHasMax)
- mReference = QMIN(mReference, mMax);
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemDouble::setProperty(const TQVariant & p)
-{
- mReference = p.toDouble();
-}
-
-TQVariant TDEConfigSkeleton::ItemDouble::property() const
-{
- return TQVariant(mReference);
-}
-
-TQVariant TDEConfigSkeleton::ItemDouble::minValue() const
-{
- if (mHasMin)
- return TQVariant(mMin);
- return TQVariant();
-}
-
-TQVariant TDEConfigSkeleton::ItemDouble::maxValue() const
-{
- if (mHasMax)
- return TQVariant(mMax);
- return TQVariant();
-}
-
-void TDEConfigSkeleton::ItemDouble::setMinValue(double v)
-{
- mHasMin = true;
- mMin = v;
-}
-
-void TDEConfigSkeleton::ItemDouble::setMaxValue(double v)
-{
- mHasMax = true;
- mMax = v;
-}
-
-
-TDEConfigSkeleton::ItemColor::ItemColor( const TQString &group, const TQString &key,
- TQColor &reference,
- const TQColor &defaultValue )
- : TDEConfigSkeletonGenericItem<TQColor>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemColor::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readColorEntry( mKey, &mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemColor::setProperty(const TQVariant & p)
-{
- mReference = p.toColor();
-}
-
-TQVariant TDEConfigSkeleton::ItemColor::property() const
-{
- return TQVariant(mReference);
-}
-
-
-TDEConfigSkeleton::ItemFont::ItemFont( const TQString &group, const TQString &key,
- TQFont &reference,
- const TQFont &defaultValue )
- : TDEConfigSkeletonGenericItem<TQFont>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemFont::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readFontEntry( mKey, &mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemFont::setProperty(const TQVariant & p)
-{
- mReference = p.toFont();
-}
-
-TQVariant TDEConfigSkeleton::ItemFont::property() const
-{
- return TQVariant(mReference);
-}
-
-
-TDEConfigSkeleton::ItemRect::ItemRect( const TQString &group, const TQString &key,
- TQRect &reference,
- const TQRect &defaultValue )
- : TDEConfigSkeletonGenericItem<TQRect>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemRect::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readRectEntry( mKey, &mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemRect::setProperty(const TQVariant & p)
-{
- mReference = p.toRect();
-}
-
-TQVariant TDEConfigSkeleton::ItemRect::property() const
-{
- return TQVariant(mReference);
-}
-
-
-TDEConfigSkeleton::ItemPoint::ItemPoint( const TQString &group, const TQString &key,
- TQPoint &reference,
- const TQPoint &defaultValue )
- : TDEConfigSkeletonGenericItem<TQPoint>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemPoint::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readPointEntry( mKey, &mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemPoint::setProperty(const TQVariant & p)
-{
- mReference = p.toPoint();
-}
-
-TQVariant TDEConfigSkeleton::ItemPoint::property() const
-{
- return TQVariant(mReference);
-}
-
-
-TDEConfigSkeleton::ItemSize::ItemSize( const TQString &group, const TQString &key,
- TQSize &reference,
- const TQSize &defaultValue )
- : TDEConfigSkeletonGenericItem<TQSize>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemSize::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readSizeEntry( mKey, &mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemSize::setProperty(const TQVariant & p)
-{
- mReference = p.toSize();
-}
-
-TQVariant TDEConfigSkeleton::ItemSize::property() const
-{
- return TQVariant(mReference);
-}
-
-
-TDEConfigSkeleton::ItemDateTime::ItemDateTime( const TQString &group, const TQString &key,
- TQDateTime &reference,
- const TQDateTime &defaultValue )
- : TDEConfigSkeletonGenericItem<TQDateTime>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemDateTime::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- mReference = config->readDateTimeEntry( mKey, &mDefault );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemDateTime::setProperty(const TQVariant & p)
-{
- mReference = p.toDateTime();
-}
-
-TQVariant TDEConfigSkeleton::ItemDateTime::property() const
-{
- return TQVariant(mReference);
-}
-
-
-TDEConfigSkeleton::ItemStringList::ItemStringList( const TQString &group, const TQString &key,
- TQStringList &reference,
- const TQStringList &defaultValue )
- : TDEConfigSkeletonGenericItem<TQStringList>( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemStringList::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- if ( !config->hasKey( mKey ) )
- mReference = mDefault;
- else
- mReference = config->readListEntry( mKey );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemStringList::setProperty(const TQVariant & p)
-{
- mReference = p.toStringList();
-}
-
-TQVariant TDEConfigSkeleton::ItemStringList::property() const
-{
- return TQVariant(mReference);
-}
-
-
-TDEConfigSkeleton::ItemPathList::ItemPathList( const TQString &group, const TQString &key,
- TQStringList &reference,
- const TQStringList &defaultValue )
- : ItemStringList( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemPathList::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- if ( !config->hasKey( mKey ) )
- mReference = mDefault;
- else
- mReference = config->readPathListEntry( mKey );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemPathList::writeConfig( TDEConfig *config )
-{
- if ( mReference != mLoadedValue ) // WABA: Is this test needed?
- {
- config->setGroup( mGroup );
- if ((mDefault == mReference) && !config->hasDefault( mKey))
- config->revertToDefault( mKey );
- else {
- TQStringList sl = mReference;
- config->writePathEntry( mKey, sl );
- }
- }
-}
-
-
-TDEConfigSkeleton::ItemIntList::ItemIntList( const TQString &group, const TQString &key,
- TQValueList<int> &reference,
- const TQValueList<int> &defaultValue )
- : TDEConfigSkeletonGenericItem<TQValueList<int> >( group, key, reference, defaultValue )
-{
-}
-
-void TDEConfigSkeleton::ItemIntList::readConfig( TDEConfig *config )
-{
- config->setGroup( mGroup );
- if ( !config->hasKey( mKey ) )
- mReference = mDefault;
- else
- mReference = config->readIntListEntry( mKey );
- mLoadedValue = mReference;
-
- readImmutability( config );
-}
-
-void TDEConfigSkeleton::ItemIntList::setProperty(const TQVariant &)
-{
- // TODO: Not yet supported
-}
-
-TQVariant TDEConfigSkeleton::ItemIntList::property() const
-{
- // TODO: Not yet supported
- return TQVariant();
-}
-
-
-TDEConfigSkeleton::TDEConfigSkeleton( const TQString &configname )
- : mCurrentGroup( "No Group" ), mUseDefaults(false)
-{
- kdDebug(177) << "Creating TDEConfigSkeleton (" << (void *)this << ")" << endl;
-
- if ( !configname.isEmpty() )
- {
- mConfig = KSharedConfig::openConfig( configname );
- }
- else
- {
- mConfig = TDEGlobal::sharedConfig();
- }
-}
-
-TDEConfigSkeleton::TDEConfigSkeleton(KSharedConfig::Ptr config)
- : mCurrentGroup( "No Group" ), mUseDefaults(false)
-{
- kdDebug(177) << "Creating TDEConfigSkeleton (" << (void *)this << ")" << endl;
- mConfig = config;
-}
-
-
-TDEConfigSkeleton::~TDEConfigSkeleton()
-{
- TDEConfigSkeletonItem::List::ConstIterator it;
- for( it = mItems.begin(); it != mItems.end(); ++it )
- {
- delete *it;
- }
-}
-
-void TDEConfigSkeleton::setCurrentGroup( const TQString &group )
-{
- mCurrentGroup = group;
-}
-
-TDEConfig *TDEConfigSkeleton::config() const
-{
- return mConfig;
-}
-
-bool TDEConfigSkeleton::useDefaults(bool b)
-{
- if (b == mUseDefaults)
- return mUseDefaults;
-
- mUseDefaults = b;
- TDEConfigSkeletonItem::List::ConstIterator it;
- for( it = mItems.begin(); it != mItems.end(); ++it )
- {
- (*it)->swapDefault();
- }
-
- usrUseDefaults(b);
- return !mUseDefaults;
-}
-
-void TDEConfigSkeleton::setDefaults()
-{
- TDEConfigSkeletonItem::List::ConstIterator it;
- for( it = mItems.begin(); it != mItems.end(); ++it ) {
- (*it)->setDefault();
- }
-
- usrSetDefaults();
-}
-
-void TDEConfigSkeleton::readConfig()
-{
- kdDebug(177) << "TDEConfigSkeleton::readConfig()" << endl;
-
- TQString origGroup = mConfig->group();
-
- mConfig->reparseConfiguration();
- TDEConfigSkeletonItem::List::ConstIterator it;
- for( it = mItems.begin(); it != mItems.end(); ++it )
- {
- (*it)->readConfig( mConfig );
- }
-
- usrReadConfig();
-
- mConfig->setGroup(origGroup);
-}
-
-void TDEConfigSkeleton::writeConfig()
-{
- kdDebug(177) << "TDEConfigSkeleton::writeConfig()" << endl;
-
- TQString origGroup = mConfig->group();
-
- TDEConfigSkeletonItem::List::ConstIterator it;
- for( it = mItems.begin(); it != mItems.end(); ++it )
- {
- (*it)->writeConfig( mConfig );
- }
-
- usrWriteConfig();
-
- mConfig->sync();
-
- readConfig();
-
- mConfig->setGroup(origGroup);
-}
-
-void TDEConfigSkeleton::addItem( TDEConfigSkeletonItem *item, const TQString &name )
-{
- item->setName( name.isEmpty() ? item->key() : name );
- mItems.append( item );
- mItemDict.insert( item->name(), item );
- item->readDefault( mConfig );
- item->readConfig( mConfig );
-}
-
-TDEConfigSkeleton::ItemString *TDEConfigSkeleton::addItemString( const TQString &name, TQString &reference,
- const TQString &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemString *item;
- item = new TDEConfigSkeleton::ItemString( mCurrentGroup, key.isEmpty() ? name : key,
- reference, defaultValue,
- TDEConfigSkeleton::ItemString::Normal );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemPassword *TDEConfigSkeleton::addItemPassword( const TQString &name, TQString &reference,
- const TQString &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemPassword *item;
- item = new TDEConfigSkeleton::ItemPassword( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemPath *TDEConfigSkeleton::addItemPath( const TQString &name, TQString &reference,
- const TQString &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemPath *item;
- item = new TDEConfigSkeleton::ItemPath( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemProperty *TDEConfigSkeleton::addItemProperty( const TQString &name, TQVariant &reference,
- const TQVariant &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemProperty *item;
- item = new TDEConfigSkeleton::ItemProperty( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemBool *TDEConfigSkeleton::addItemBool( const TQString &name, bool &reference,
- bool defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemBool *item;
- item = new TDEConfigSkeleton::ItemBool( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemInt *TDEConfigSkeleton::addItemInt( const TQString &name, int &reference,
- int defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemInt *item;
- item = new TDEConfigSkeleton::ItemInt( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemUInt *TDEConfigSkeleton::addItemUInt( const TQString &name, unsigned int &reference,
- unsigned int defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemUInt *item;
- item = new TDEConfigSkeleton::ItemUInt( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemInt64 *TDEConfigSkeleton::addItemInt64( const TQString &name, TQ_INT64 &reference,
- TQ_INT64 defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemInt64 *item;
- item = new TDEConfigSkeleton::ItemInt64( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemUInt64 *TDEConfigSkeleton::addItemUInt64( const TQString &name, TQ_UINT64 &reference,
- TQ_UINT64 defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemUInt64 *item;
- item = new TDEConfigSkeleton::ItemUInt64( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemLong *TDEConfigSkeleton::addItemLong( const TQString &name, long &reference,
- long defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemLong *item;
- item = new TDEConfigSkeleton::ItemLong( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemULong *TDEConfigSkeleton::addItemULong( const TQString &name, unsigned long &reference,
- unsigned long defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemULong *item;
- item = new TDEConfigSkeleton::ItemULong( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemDouble *TDEConfigSkeleton::addItemDouble( const TQString &name, double &reference,
- double defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemDouble *item;
- item = new TDEConfigSkeleton::ItemDouble( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemColor *TDEConfigSkeleton::addItemColor( const TQString &name, TQColor &reference,
- const TQColor &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemColor *item;
- item = new TDEConfigSkeleton::ItemColor( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemFont *TDEConfigSkeleton::addItemFont( const TQString &name, TQFont &reference,
- const TQFont &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemFont *item;
- item = new TDEConfigSkeleton::ItemFont( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemRect *TDEConfigSkeleton::addItemRect( const TQString &name, TQRect &reference,
- const TQRect &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemRect *item;
- item = new TDEConfigSkeleton::ItemRect( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemPoint *TDEConfigSkeleton::addItemPoint( const TQString &name, TQPoint &reference,
- const TQPoint &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemPoint *item;
- item = new TDEConfigSkeleton::ItemPoint( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemSize *TDEConfigSkeleton::addItemSize( const TQString &name, TQSize &reference,
- const TQSize &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemSize *item;
- item = new TDEConfigSkeleton::ItemSize( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemDateTime *TDEConfigSkeleton::addItemDateTime( const TQString &name, TQDateTime &reference,
- const TQDateTime &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemDateTime *item;
- item = new TDEConfigSkeleton::ItemDateTime( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemStringList *TDEConfigSkeleton::addItemStringList( const TQString &name, TQStringList &reference,
- const TQStringList &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemStringList *item;
- item = new TDEConfigSkeleton::ItemStringList( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-TDEConfigSkeleton::ItemIntList *TDEConfigSkeleton::addItemIntList( const TQString &name, TQValueList<int> &reference,
- const TQValueList<int> &defaultValue, const TQString &key )
-{
- TDEConfigSkeleton::ItemIntList *item;
- item = new TDEConfigSkeleton::ItemIntList( mCurrentGroup, key.isNull() ? name : key,
- reference, defaultValue );
- addItem( item, name );
- return item;
-}
-
-bool TDEConfigSkeleton::isImmutable(const TQString &name)
-{
- TDEConfigSkeletonItem *item = findItem(name);
- return !item || item->isImmutable();
-}
-
-TDEConfigSkeletonItem *TDEConfigSkeleton::findItem(const TQString &name)
-{
- return mItemDict.find(name);
-}
diff --git a/tdecore/kconfigskeleton.h b/tdecore/kconfigskeleton.h
deleted file mode 100644
index 30dc98841..000000000
--- a/tdecore/kconfigskeleton.h
+++ /dev/null
@@ -1,1230 +0,0 @@
-/*
- * This file is part of KDE.
- *
- * Copyright (c) 2001,2002,2003 Cornelius Schumacher <schumacher@kde.org>
- * Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef _KCONFIGSKELETON_H
-#define _KCONFIGSKELETON_H
-
-#include <tqcolor.h>
-#include <tqdatetime.h>
-#include <tqfont.h>
-#include <tqpoint.h>
-#include <tqptrlist.h>
-#include <tqdict.h>
-#include <tqrect.h>
-#include <tqsize.h>
-#include <tqstringlist.h>
-#include <tqvariant.h>
-#include <kconfig.h>
-#include <kglobalsettings.h>
-
- /**
- * @short Class for storing a preferences setting
- * @author Cornelius Schumacher
- * @see TDEConfigSkeleton
- *
- * This class represents one preferences setting as used by @ref TDEConfigSkeleton.
- * Subclasses of TDEConfigSkeletonItem implement storage functions for a certain type of
- * setting. Normally you don't have to use this class directly. Use the special
- * addItem() functions of TDEConfigSkeleton instead. If you subclass this class you will
- * have to register instances with the function TDEConfigSkeleton::addItem().
- */
- class TDECORE_EXPORT TDEConfigSkeletonItem
- {
- public:
- typedef TQValueList < TDEConfigSkeletonItem * >List;
- typedef TQDict < TDEConfigSkeletonItem > Dict;
- typedef TQDictIterator < TDEConfigSkeletonItem > DictIterator;
-
- /**
- * Constructor.
- *
- * @param group Config file group.
- * @param key Config file key.
- */
- TDEConfigSkeletonItem(const TQString & group, const TQString & key)
- :mGroup(group),mKey(key), mIsImmutable(true)
- {
- }
-
- /**
- * Destructor.
- */
- virtual ~TDEConfigSkeletonItem()
- {
- }
-
- /**
- * Set config file group.
- */
- void setGroup( const TQString &group )
- {
- mGroup = group;
- }
-
- /**
- * Return config file group.
- */
- TQString group() const
- {
- return mGroup;
- }
-
- /**
- * Set config file key.
- */
- void setKey( const TQString &key )
- {
- mKey = key;
- }
-
- /**
- * Return config file key.
- */
- TQString key() const
- {
- return mKey;
- }
-
- /**
- * Set internal name of entry.
- */
- void setName(const TQString &name)
- {
- mName = name;
- }
-
- /**
- * Return internal name of entry.
- */
- TQString name() const
- {
- return mName;
- }
-
- /**
- Set label providing a translated one-line description of the item.
- */
- void setLabel( const TQString &l )
- {
- mLabel = l;
- }
-
- /**
- Return label of item. See setLabel().
- */
- TQString label() const
- {
- return mLabel;
- }
-
- /**
- Set WhatsThis description og item.
- */
- void setWhatsThis( const TQString &w )
- {
- mWhatsThis = w;
- }
-
- /**
- Return WhatsThis description of item. See setWhatsThis().
- */
- TQString whatsThis() const
- {
- return mWhatsThis;
- }
-
- /**
- * This function is called by @ref TDEConfigSkeleton to read the value for this setting
- * from a config file.
- * value.
- */
- virtual void readConfig(TDEConfig *) = 0;
-
- /**
- * This function is called by @ref TDEConfigSkeleton to write the value of this setting
- * to a config file.
- */
- virtual void writeConfig(TDEConfig *) = 0;
-
- /**
- * Read global default value.
- */
- virtual void readDefault(TDEConfig *) = 0;
-
- /**
- * Set item to @p p
- */
- virtual void setProperty(const TQVariant &p) = 0;
-
- /**
- * Return item as property
- */
- virtual TQVariant property() const = 0;
-
- /**
- * Return minimum value of item or invalid if not specified
- */
- virtual TQVariant minValue() const { return TQVariant(); }
-
- /**
- * Return maximum value of item or invalid if not specified
- */
- virtual TQVariant maxValue() const { return TQVariant(); }
-
- /**
- Sets the current value to the default value.
- */
- virtual void setDefault() = 0;
-
- /**
- * Exchanges the current value with the default value
- * Used by TDEConfigSkeleton::useDefaults(bool);
- */
- virtual void swapDefault() = 0;
-
- /**
- * Return if the entry can be modified.
- */
- bool isImmutable() const
- {
- return mIsImmutable;
- }
-
- protected:
- /**
- * sets mIsImmutable to true if mKey in config is immutable
- * @param config TDEConfig to check if mKey is immutable in
- */
- void readImmutability(TDEConfig *config);
-
- TQString mGroup;
- TQString mKey;
- TQString mName;
-
- private:
- bool mIsImmutable;
-
- TQString mLabel;
- TQString mWhatsThis;
- };
-
-
-template < typename T > class TDEConfigSkeletonGenericItem:public TDEConfigSkeletonItem
- {
- public:
- TDEConfigSkeletonGenericItem(const TQString & group, const TQString & key, T & reference,
- T defaultValue)
- : TDEConfigSkeletonItem(group, key), mReference(reference),
- mDefault(defaultValue), mLoadedValue(defaultValue)
- {
- }
-
- /**
- * Set value of this TDEConfigSkeletonItem.
- */
- void setValue(const T & v)
- {
- mReference = v;
- }
-
- /**
- * Return value of this TDEConfigSkeletonItem.
- */
- T & value()
- {
- return mReference;
- }
-
- /**
- * Return const value of this TDEConfigSkeletonItem.
- */
- const T & value() const
- {
- return mReference;
- }
-
- /**
- Set default value for this item.
- */
- virtual void setDefaultValue( const T &v )
- {
- mDefault = v;
- }
-
- virtual void setDefault()
- {
- mReference = mDefault;
- }
-
- virtual void writeConfig(TDEConfig * config)
- {
- if ( mReference != mLoadedValue ) // Is this needed?
- {
- config->setGroup(mGroup);
- if ((mDefault == mReference) && !config->hasDefault( mKey))
- config->revertToDefault( mKey );
- else
- config->writeEntry(mKey, mReference);
- }
- }
-
- void readDefault(TDEConfig * config)
- {
- config->setReadDefaults(true);
- readConfig(config);
- config->setReadDefaults(false);
- mDefault = mReference;
- }
-
- void swapDefault()
- {
- T tmp = mReference;
- mReference = mDefault;
- mDefault = tmp;
- }
-
- protected:
- T & mReference;
- T mDefault;
- T mLoadedValue;
- };
-
- /**
- * @short Class for handling preferences settings for an application.
- * @author Cornelius Schumacher
- * @see TDEConfigSkeletonItem
- *
- * This class provides an interface to preferences settings. Preferences items
- * can be registered by the addItem() function corresponding to the data type of
- * the seetting. TDEConfigSkeleton then handles reading and writing of config files and
- * setting of default values.
- *
- * Normally you will subclass TDEConfigSkeleton, add data members for the preferences
- * settings and register the members in the constructor of the subclass.
- *
- * Example:
- * \code
- * class MyPrefs : public TDEConfigSkeleton
- * {
- * public:
- * MyPrefs()
- * {
- * setCurrentGroup("MyGroup");
- * addItemBool("MySetting1",mMyBool,false);
- * addItemColor("MySetting2",mMyColor,TQColor(1,2,3));
- *
- * setCurrentGroup("MyOtherGroup");
- * addItemFont("MySetting3",mMyFont,TQFont("helvetica",12));
- * }
- *
- * bool mMyBool;
- * TQColor mMyColor;
- * TQFont mMyFont;
- * }
- * \endcode
- *
- * It might be convenient in many cases to make this subclass of TDEConfigSkeleton a
- * singleton for global access from all over the application without passing
- * references to the TDEConfigSkeleton object around.
- *
- * You can write the data to the configuration file by calling @ref writeConfig()
- * and read the data from the configuration file by calling @ref readConfig().
- *
- * If you have items, which are not covered by the existing addItem() functions
- * you can add customized code for reading, writing and default setting by
- * implementing the functions @ref usrUseDefaults(), @ref usrReadConfig() and
- * @ref usrWriteConfig().
- *
- * Internally preferences settings are stored in instances of subclasses of
- * @ref TDEConfigSkeletonItem. You can also add TDEConfigSkeletonItem subclasses
- * for your own types and call the generic @ref addItem() to register them.
- *
- * In many cases you don't have to write the specific TDEConfigSkeleton
- * subclasses yourself, but you can use \ref kconfig_compiler to automatically
- * generate the C++ code from an XML description of the configuration options.
- */
-class TDECORE_EXPORT TDEConfigSkeleton
-{
-public:
-
- /**
- * Class for handling a string preferences item.
- */
- class TDECORE_EXPORT ItemString:public TDEConfigSkeletonGenericItem < TQString >
- {
- public:
- enum Type { Normal, Password, Path };
-
- ItemString(const TQString & group, const TQString & key,
- TQString & reference,
- const TQString & defaultValue = TQString::fromLatin1(""), // NOT TQString::null !!
- Type type = Normal);
-
- void writeConfig(TDEConfig * config);
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
-
- private:
- Type mType;
- };
-
- /**
- * Class for handling a password preferences item.
- */
- class TDECORE_EXPORT ItemPassword:public ItemString
- {
- public:
- ItemPassword(const TQString & group, const TQString & key,
- TQString & reference,
- const TQString & defaultValue = TQString::fromLatin1("")); // NOT TQString::null !!
- };
-
- /**
- * Class for handling a path preferences item.
- */
- class TDECORE_EXPORT ItemPath:public ItemString
- {
- public:
- ItemPath(const TQString & group, const TQString & key,
- TQString & reference,
- const TQString & defaultValue = TQString::null);
- };
-
-
- /**
- * Class for handling a TQVariant preferences item.
- */
- class TDECORE_EXPORT ItemProperty:public TDEConfigSkeletonGenericItem < TQVariant >
- {
- public:
- ItemProperty(const TQString & group, const TQString & key,
- TQVariant & reference, TQVariant defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a bool preferences item.
- */
- class TDECORE_EXPORT ItemBool:public TDEConfigSkeletonGenericItem < bool >
- {
- public:
- ItemBool(const TQString & group, const TQString & key, bool & reference,
- bool defaultValue = true);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling an integer preferences item.
- */
- class TDECORE_EXPORT ItemInt:public TDEConfigSkeletonGenericItem < int >
- {
- public:
- ItemInt(const TQString & group, const TQString & key, int &reference,
- int defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- TQVariant minValue() const;
- TQVariant maxValue() const;
-
- void setMinValue(int);
- void setMaxValue(int);
-
- private:
- bool mHasMin : 1;
- bool mHasMax : 1;
- int mMin;
- int mMax;
- };
-
- /**
- * Class for handling an 64-bit integer preferences item.
- */
- class TDECORE_EXPORT ItemInt64:public TDEConfigSkeletonGenericItem < TQ_INT64 >
- {
- public:
- ItemInt64(const TQString & group, const TQString & key, TQ_INT64 &reference,
- TQ_INT64 defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
-
- TQVariant minValue() const;
- TQVariant maxValue() const;
-
- void setMinValue(TQ_INT64);
- void setMaxValue(TQ_INT64);
-
- private:
- bool mHasMin : 1;
- bool mHasMax : 1;
- TQ_INT64 mMin;
- TQ_INT64 mMax;
- };
-
- /**
- * Class for handling enums.
- */
- class TDECORE_EXPORT ItemEnum:public ItemInt
- {
- public:
- struct Choice
- {
- TQString name;
- TQString label;
- TQString whatsThis;
- };
-
- ItemEnum(const TQString & group, const TQString & key, int &reference,
- const TQValueList<Choice> &choices, int defaultValue = 0);
-
- TQValueList<Choice> choices() const;
-
- void readConfig(TDEConfig * config);
- void writeConfig(TDEConfig * config);
-
- private:
- TQValueList<Choice> mChoices;
- };
-
-
- /**
- * Class for handling an unsingend integer preferences item.
- */
- class TDECORE_EXPORT ItemUInt:public TDEConfigSkeletonGenericItem < unsigned int >
- {
- public:
- ItemUInt(const TQString & group, const TQString & key,
- unsigned int &reference, unsigned int defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- TQVariant minValue() const;
- TQVariant maxValue() const;
-
- void setMinValue(unsigned int);
- void setMaxValue(unsigned int);
-
- private:
- bool mHasMin : 1;
- bool mHasMax : 1;
- unsigned int mMin;
- unsigned int mMax;
- };
-
-
- /**
- * Class for hanlding a long integer preferences item.
- */
- class TDECORE_EXPORT ItemLong:public TDEConfigSkeletonGenericItem < long >
- {
- public:
- ItemLong(const TQString & group, const TQString & key, long &reference,
- long defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- TQVariant minValue() const;
- TQVariant maxValue() const;
-
- void setMinValue(long);
- void setMaxValue(long);
-
- private:
- bool mHasMin : 1;
- bool mHasMax : 1;
- long mMin;
- long mMax;
- };
-
-
- /**
- * Class for handling an unsigned long integer preferences item.
- */
- class TDECORE_EXPORT ItemULong:public TDEConfigSkeletonGenericItem < unsigned long >
- {
- public:
- ItemULong(const TQString & group, const TQString & key,
- unsigned long &reference, unsigned long defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- TQVariant minValue() const;
- TQVariant maxValue() const;
-
- void setMinValue(unsigned long);
- void setMaxValue(unsigned long);
-
- private:
- bool mHasMin : 1;
- bool mHasMax : 1;
- unsigned long mMin;
- unsigned long mMax;
- };
-
- /**
- * Class for handling unsigned 64-bit integer preferences item.
- */
- class TDECORE_EXPORT ItemUInt64:public TDEConfigSkeletonGenericItem < TQ_UINT64 >
- {
- public:
- ItemUInt64(const TQString & group, const TQString & key, TQ_UINT64 &reference,
- TQ_UINT64 defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
-
- TQVariant minValue() const;
- TQVariant maxValue() const;
-
- void setMinValue(TQ_UINT64);
- void setMaxValue(TQ_UINT64);
-
- private:
- bool mHasMin : 1;
- bool mHasMax : 1;
- TQ_UINT64 mMin;
- TQ_UINT64 mMax;
- };
-
- /**
- * Class for handling a floating point preference item.
- */
- class TDECORE_EXPORT ItemDouble:public TDEConfigSkeletonGenericItem < double >
- {
- public:
- ItemDouble(const TQString & group, const TQString & key,
- double &reference, double defaultValue = 0);
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- TQVariant minValue() const;
- TQVariant maxValue() const;
-
- void setMinValue(double);
- void setMaxValue(double);
-
- private:
- bool mHasMin : 1;
- bool mHasMax : 1;
- double mMin;
- double mMax;
- };
-
-
- /**
- * Class for handling a color preferences item.
- */
- class TDECORE_EXPORT ItemColor:public TDEConfigSkeletonGenericItem < TQColor >
- {
- public:
- ItemColor(const TQString & group, const TQString & key,
- TQColor & reference,
- const TQColor & defaultValue = TQColor(128, 128, 128));
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a font preferences item.
- */
- class TDECORE_EXPORT ItemFont:public TDEConfigSkeletonGenericItem < TQFont >
- {
- public:
- ItemFont(const TQString & group, const TQString & key, TQFont & reference,
- const TQFont & defaultValue = TDEGlobalSettings::generalFont());
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a TQRect preferences item.
- */
- class TDECORE_EXPORT ItemRect:public TDEConfigSkeletonGenericItem < TQRect >
- {
- public:
- ItemRect(const TQString & group, const TQString & key, TQRect & reference,
- const TQRect & defaultValue = TQRect());
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a TQPoint preferences item.
- */
- class TDECORE_EXPORT ItemPoint:public TDEConfigSkeletonGenericItem < TQPoint >
- {
- public:
- ItemPoint(const TQString & group, const TQString & key, TQPoint & reference,
- const TQPoint & defaultValue = TQPoint());
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a TQSize preferences item.
- */
- class TDECORE_EXPORT ItemSize:public TDEConfigSkeletonGenericItem < TQSize >
- {
- public:
- ItemSize(const TQString & group, const TQString & key, TQSize & reference,
- const TQSize & defaultValue = TQSize());
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a TQDateTime preferences item.
- */
- class TDECORE_EXPORT ItemDateTime:public TDEConfigSkeletonGenericItem < TQDateTime >
- {
- public:
- ItemDateTime(const TQString & group, const TQString & key,
- TQDateTime & reference,
- const TQDateTime & defaultValue = TQDateTime());
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a string list preferences item.
- */
- class TDECORE_EXPORT ItemStringList:public TDEConfigSkeletonGenericItem < TQStringList >
- {
- public:
- ItemStringList(const TQString & group, const TQString & key,
- TQStringList & reference,
- const TQStringList & defaultValue = TQStringList());
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
- /**
- * Class for handling a path list preferences item.
- */
- class TDECORE_EXPORT ItemPathList:public ItemStringList
- {
- public:
- ItemPathList(const TQString & group, const TQString & key,
- TQStringList & reference,
- const TQStringList & defaultValue = TQStringList());
-
- void readConfig(TDEConfig * config);
- void writeConfig(TDEConfig * config);
- };
-
-
- /**
- * Class for handling an integer list preferences item.
- */
- class TDECORE_EXPORT ItemIntList:public TDEConfigSkeletonGenericItem < TQValueList < int > >
- {
- public:
- ItemIntList(const TQString & group, const TQString & key,
- TQValueList < int >&reference,
- const TQValueList < int >&defaultValue = TQValueList < int >());
-
- void readConfig(TDEConfig * config);
- void setProperty(const TQVariant & p);
- TQVariant property() const;
- };
-
-
-public:
- /**
- * Constructor.
- *
- * @param configname name of config file. If no name is given, the default
- * config file as returned by kapp()->config() is used.
- */
- TDEConfigSkeleton(const TQString & configname = TQString::null);
-
- /**
- * Constructor.
- *
- * @param config configuration object to use.
- */
- TDEConfigSkeleton(KSharedConfig::Ptr config);
-
- /**
- * Destructor
- */
- virtual ~ TDEConfigSkeleton();
-
- /**
- Set all registered items to their default values.
- */
- void setDefaults();
-
- /**
- * Read preferences from config file. All registered items are set to the
- * values read from disk.
- */
- void readConfig();
-
- /**
- * Write preferences to config file. The values of all registered items are
- * written to disk.
- */
- void writeConfig();
-
- /**
- * Set the config file group for subsequent addItem() calls. It is valid
- * until setCurrentGroup() is called with a new argument. Call this before
- * you add any items. The default value is "No Group".
- */
- void setCurrentGroup(const TQString & group);
-
- /**
- * Returns the current group used for addItem() calls.
- */
- TQString currentGroup() // ### KDE 4.0: make const
- {
- return mCurrentGroup;
- }
-
- /**
- * Register a custom @ref TDEConfigSkeletonItem with a given name. If the name
- * parameter is null, take the name from TDEConfigSkeletonItem::key().
- * Note that all names must be unique but that multiple entries can have
- * the same key if they reside in different groups.
- */
- void addItem(TDEConfigSkeletonItem *, const TQString & name = TQString::null );
-
- /**
- * Register an item of type TQString.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemString *addItemString(const TQString & name, TQString & reference,
- const TQString & defaultValue = TQString::fromLatin1(""), // NOT TQString::null !!
- const TQString & key = TQString::null);
-
- /**
- * Register a password item of type TQString. The string value is written
- * encrypted to the config file. Note that the current encryption scheme
- * is very weak.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemPassword *addItemPassword(const TQString & name, TQString & reference,
- const TQString & defaultValue = TQString::fromLatin1(""),
- const TQString & key = TQString::null);
-
- /**
- * Register a path item of type TQString. The string value is interpreted
- * as a path. This means, dollar expension is activated for this value, so
- * that e.g. $HOME gets expanded.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemPath *addItemPath(const TQString & name, TQString & reference,
- const TQString & defaultValue = TQString::fromLatin1(""),
- const TQString & key = TQString::null);
-
- /**
- * Register a property item of type TQVariant. Note that only the following
- * TQVariant types are allowed: String, StringList, Font, Point, Rect, Size,
- * Color, Int, UInt, Bool, Double, DateTime and Date.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemProperty *addItemProperty(const TQString & name, TQVariant & reference,
- const TQVariant & defaultValue = TQVariant(),
- const TQString & key = TQString::null);
- /**
- * Register an item of type bool.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemBool *addItemBool(const TQString & name, bool & reference,
- bool defaultValue = false,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type int.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemInt *addItemInt(const TQString & name, int &reference, int defaultValue = 0,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type unsigned int.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemUInt *addItemUInt(const TQString & name, unsigned int &reference,
- unsigned int defaultValue = 0,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type long.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemLong *addItemLong(const TQString & name, long &reference,
- long defaultValue = 0,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type unsigned long.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemULong *addItemULong(const TQString & name, unsigned long &reference,
- unsigned long defaultValue = 0,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQ_INT64.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemInt64 *addItemInt64(const TQString & name, TQ_INT64 &reference,
- TQ_INT64 defaultValue = 0,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQ_UINT64
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemUInt64 *addItemUInt64(const TQString & name, TQ_UINT64 &reference,
- TQ_UINT64 defaultValue = 0,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type double.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemDouble *addItemDouble(const TQString & name, double &reference,
- double defaultValue = 0.0,
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQColor.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemColor *addItemColor(const TQString & name, TQColor & reference,
- const TQColor & defaultValue = TQColor(128, 128, 128),
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQFont.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemFont *addItemFont(const TQString & name, TQFont & reference,
- const TQFont & defaultValue =
- TDEGlobalSettings::generalFont(),
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQRect.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemRect *addItemRect(const TQString & name, TQRect & reference,
- const TQRect & defaultValue = TQRect(),
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQPoint.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemPoint *addItemPoint(const TQString & name, TQPoint & reference,
- const TQPoint & defaultValue = TQPoint(),
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQSize.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemSize *addItemSize(const TQString & name, TQSize & reference,
- const TQSize & defaultValue = TQSize(),
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQDateTime.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemDateTime *addItemDateTime(const TQString & name, TQDateTime & reference,
- const TQDateTime & defaultValue = TQDateTime(),
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQStringList.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemStringList *addItemStringList(const TQString & name, TQStringList & reference,
- const TQStringList & defaultValue = TQStringList(),
- const TQString & key = TQString::null);
-
- /**
- * Register an item of type TQValueList<int>.
- *
- * @param name Name used to indentify this setting. Names must be unique.
- * @param reference Pointer to the variable, which is set by readConfig()
- * calls and read by writeConfig() calls.
- * @param defaultValue Default value, which is used when the config file
- * does not yet contain the key of this item.
- * @param key Key used in config file. If key is null, name is used as key.
- * @return The created item
- */
- ItemIntList *addItemIntList(const TQString & name, TQValueList < int >&reference,
- const TQValueList < int >&defaultValue =
- TQValueList < int >(),
- const TQString & key = TQString::null);
-
- /**
- * Return the @ref TDEConfig object used for reading and writing the settings.
- */
- TDEConfig *config() const;
-
- /**
- * Return list of items managed by this TDEConfigSkeleton object.
- */
- TDEConfigSkeletonItem::List items() const
- {
- return mItems;
- }
-
- /**
- * Return whether a certain item is immutable
- */
- bool isImmutable(const TQString & name);
-
- /**
- * Lookup item by name
- */
- TDEConfigSkeletonItem * findItem(const TQString & name);
-
- /**
- * Indicate whether this object should reflect the actual
- * values or the default values.
- * @param b If true this object reflects the default values.
- * @return The state prior to this call
- */
- bool useDefaults(bool b);
-
-protected:
- /**
- * Implemented by subclasses that use special defaults.
- * It should replace the default values with the actual
- * values and vice versa.
- */
- virtual void usrUseDefaults(bool)
- {
- }
-
- virtual void usrSetDefaults()
- {
- }
-
- /**
- * Implemented by subclasses that read special config values.
- */
- virtual void usrReadConfig()
- {
- }
-
- /**
- * Implemented by subclasses that write special config values.
- */
- virtual void usrWriteConfig()
- {
- }
-
-private:
- TQString mCurrentGroup;
-
- KSharedConfig::Ptr mConfig; // pointer to TDEConfig object
-
- TDEConfigSkeletonItem::List mItems;
- TDEConfigSkeletonItem::Dict mItemDict;
-
- bool mUseDefaults;
-
- class Private;
- Private *d;
-
-};
-
-#endif
diff --git a/tdecore/kcrash.cpp b/tdecore/kcrash.cpp
index ae767ffb2..420ff177c 100644
--- a/tdecore/kcrash.cpp
+++ b/tdecore/kcrash.cpp
@@ -51,7 +51,7 @@
#include <kapplication.h>
#include <dcopclient.h>
-#include <../kinit/klauncher_cmds.h>
+#include <../kinit/tdelauncher_cmds.h>
#if defined Q_WS_X11
#include <X11/Xlib.h>
@@ -262,7 +262,7 @@ void KCrash::startDrKonqi( const char* argv[], int argc )
startDirectly( argv, argc );
return;
}
- klauncher_header header;
+ tdelauncher_header header;
header.cmd = LAUNCHER_EXEC_NEW;
const int BUFSIZE = 8192; // make sure this is big enough
char buffer[ BUFSIZE + 10 ];
diff --git a/tdecore/kdebug.areas b/tdecore/kdebug.areas
index f2da61c43..d714c6535 100644
--- a/tdecore/kdebug.areas
+++ b/tdecore/kdebug.areas
@@ -29,7 +29,7 @@
220 tdeui (KToolBar)
230 tdeui (KCommand)
240 tdeui (tdelibs)
-250 kfile (tdelibs)
+250 tdefile (tdelibs)
264 tdecore (KIconLoader)
265 tdecore (KIconEffect)
270 tdeui (KRootPixmap)
@@ -58,7 +58,7 @@
713 tdeutils (TDECModuleContainer)
750 tdespell (tdelibs)
760 tdemdi
-780 kcmshell (tdelibs)
+780 tdecmshell (tdelibs)
790 tdeimproxy (tdelibs)
800 kabapi (tdelibs)
900 tdesu (tdelibs)
@@ -87,8 +87,8 @@
1216 twin (client errors)
1217 khotkeys
1218 ksmserver
-1219 media kioslave
-1220 remote kioslave
+1219 media tdeioslave
+1220 remote tdeioslave
1400 khelpcenter (tdebase)
1401 kcmhelpcenter
@@ -220,7 +220,7 @@
6201 tdehtml (caret table)
6210 tdehtml (editor)
-# libkio
+# libtdeio
7000 kio
7001 kio (KDirWatch)
7002 kio (Slave)
@@ -239,9 +239,9 @@
7016 kio (KLauncher)
7017 kio (KIOConnection)
7018 kio (KMimeMagic)
-7019 kio (kioslave)
+7019 kio (tdeioslave)
7020 kded
-7021 kbuildsycoca
+7021 tdebuildsycoca
7022 kurifilter
7023 kurifilter (plugins)
7024 kio (UIServer)
@@ -260,7 +260,7 @@
7042 KAr
7043 kio (bookmarks)
-# 71xx are for kioslaves
+# 71xx are for tdeioslaves
7101 kio_file
7102 kio_ftp
7103 kio_http
@@ -427,8 +427,8 @@
20011 KDB (Connection)
20012 KDB (plugin)
-#kfilereplace
-23000 KFileReplace (kfilereplacepart)
+#tdefilereplace
+23000 KFileReplace (tdefilereplacepart)
#klinkstatus
23100 KLinkStatus
diff --git a/tdecore/kdebug.cpp b/tdecore/kdebug.cpp
index e484a3711..27dcf1418 100644
--- a/tdecore/kdebug.cpp
+++ b/tdecore/kdebug.cpp
@@ -55,7 +55,7 @@
#include <syslog.h>
#include <errno.h>
#include <string.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include "kstaticdeleter.h"
#include <config.h>
diff --git a/tdecore/kdesktopfile.cpp b/tdecore/kdesktopfile.cpp
index 1b9a49890..a30b2046b 100644
--- a/tdecore/kdesktopfile.cpp
+++ b/tdecore/kdesktopfile.cpp
@@ -30,7 +30,7 @@
#include <kdebug.h>
#include "kurl.h"
-#include "kconfigbackend.h"
+#include "tdeconfigbackend.h"
#include "kapplication.h"
#include "kstandarddirs.h"
#include "kmountpoint.h"
diff --git a/tdecore/kdesktopfile.h b/tdecore/kdesktopfile.h
index 28db47842..60e9fc096 100644
--- a/tdecore/kdesktopfile.h
+++ b/tdecore/kdesktopfile.h
@@ -19,7 +19,7 @@
#ifndef _KDESKTOPFILE_H
#define _KDESKTOPFILE_H
-#include "kconfig.h"
+#include "tdeconfig.h"
#include "tdelibs_export.h"
class KDesktopFilePrivate;
diff --git a/tdecore/kdetcompmgr.cpp b/tdecore/kdetcompmgr.cpp
index 2047a7707..e34554073 100644
--- a/tdecore/kdetcompmgr.cpp
+++ b/tdecore/kdetcompmgr.cpp
@@ -26,7 +26,7 @@
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <pwd.h>
#include <signal.h>
diff --git a/tdecore/kglobal.cpp b/tdecore/kglobal.cpp
index 9759edbcf..d26bbb678 100644
--- a/tdecore/kglobal.cpp
+++ b/tdecore/kglobal.cpp
@@ -30,7 +30,7 @@
#include <kapplication.h>
#include <kaboutdata.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
#include <kcharsets.h>
#include <kiconloader.h>
diff --git a/tdecore/kglobalsettings.cpp b/tdecore/kglobalsettings.cpp
index 8e617b06a..dbd751eea 100644
--- a/tdecore/kglobalsettings.cpp
+++ b/tdecore/kglobalsettings.cpp
@@ -23,7 +23,7 @@
#include <tqfontdatabase.h>
#include <tqcursor.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ksimpleconfig.h>
#include <kapplication.h>
diff --git a/tdecore/kiconeffect.cpp b/tdecore/kiconeffect.cpp
index 4fd16a49a..ae33d744d 100644
--- a/tdecore/kiconeffect.cpp
+++ b/tdecore/kiconeffect.cpp
@@ -30,7 +30,7 @@
#include <kdebug.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobalsettings.h>
#include <kicontheme.h>
#include "kiconeffect.h"
diff --git a/tdecore/kiconloader.cpp b/tdecore/kiconloader.cpp
index 127f8eaba..e63f09d0f 100644
--- a/tdecore/kiconloader.cpp
+++ b/tdecore/kiconloader.cpp
@@ -31,7 +31,7 @@
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ksimpleconfig.h>
#include <kinstance.h>
diff --git a/tdecore/kicontheme.cpp b/tdecore/kicontheme.cpp
index 853c0ab78..abced574e 100644
--- a/tdecore/kicontheme.cpp
+++ b/tdecore/kicontheme.cpp
@@ -31,7 +31,7 @@
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ksimpleconfig.h>
#include <kinstance.h>
diff --git a/tdecore/kinstance.cpp b/tdecore/kinstance.cpp
index 9b4b7c2c7..cef932fa1 100644
--- a/tdecore/kinstance.cpp
+++ b/tdecore/kinstance.cpp
@@ -20,7 +20,7 @@
#include <stdlib.h>
#include <unistd.h>
-#include "kconfig.h"
+#include "tdeconfig.h"
#include "klocale.h"
#include "kcharsets.h"
#include "kiconloader.h"
diff --git a/tdecore/kkeyserver_x11.cpp b/tdecore/kkeyserver_x11.cpp
index e7673debb..69acd0d5e 100644
--- a/tdecore/kkeyserver_x11.cpp
+++ b/tdecore/kkeyserver_x11.cpp
@@ -31,7 +31,7 @@
#include "kkeynative.h"
#include "kshortcut.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
diff --git a/tdecore/klocale.cpp b/tdecore/klocale.cpp
index 4c60bed43..f7a3cf77a 100644
--- a/tdecore/klocale.cpp
+++ b/tdecore/klocale.cpp
@@ -37,7 +37,7 @@
#include "kstandarddirs.h"
#include "ksimpleconfig.h"
#include "kinstance.h"
-#include "kconfig.h"
+#include "tdeconfig.h"
#include "kdebug.h"
#include "kcalendarsystem.h"
#include "kcalendarsystemfactory.h"
@@ -672,7 +672,7 @@ void KLocale::updateCatalogues( )
}
// now iterate over all languages and all wanted catalog names and append or create them in the right order
- // the sequence must be e.g. nds/appname nds/tdelibs nds/kio de/appname de/tdelibs de/kio etc.
+ // the sequence must be e.g. nds/appname nds/tdelibs nds/tdeio de/appname de/tdelibs de/tdeio etc.
// and not nds/appname de/appname nds/tdelibs de/tdelibs etc. Otherwise we would be in trouble with a language
// sequende nds,en_US, de. In this case en_US must hide everything below in the language list.
for ( TQStringList::ConstIterator itLangs = d->languageList.begin();
diff --git a/tdecore/kmdcodec_compat.h b/tdecore/kmdcodec_compat.h
index f2ed3b580..80da5356b 100644
--- a/tdecore/kmdcodec_compat.h
+++ b/tdecore/kmdcodec_compat.h
@@ -1,4 +1,4 @@
#ifdef __GNUC__
-#warning #include <kio/kmdcodec.h> is deprecated, use #include <kmdcodec.h> instead.
+#warning #include <tdeio/kmdcodec.h> is deprecated, use #include <kmdcodec.h> instead.
#endif
#include "../kmdcodec.h"
diff --git a/tdecore/knotifyclient.cpp b/tdecore/knotifyclient.cpp
index e5d088dcb..309be40f0 100644
--- a/tdecore/knotifyclient.cpp
+++ b/tdecore/knotifyclient.cpp
@@ -26,7 +26,7 @@
#include <kapplication.h>
#include <kstandarddirs.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <dcopclient.h>
#include <kdebug.h>
#include <kstaticdeleter.h>
diff --git a/tdecore/kprotocolinfo_tdecore.cpp b/tdecore/kprotocolinfo_tdecore.cpp
index de16f0128..02976616e 100644
--- a/tdecore/kprotocolinfo_tdecore.cpp
+++ b/tdecore/kprotocolinfo_tdecore.cpp
@@ -30,7 +30,7 @@
#include <kapplication.h>
#include <kdebug.h>
#include <ksimpleconfig.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstringhandler.h>
class KProtocolInfo::KProtocolInfoPrivate
@@ -555,7 +555,7 @@ TQDataStream& operator<<( TQDataStream& s, const KProtocolInfo::ExtraField& fiel
return s;
}
-// KURL based static functions are implemented in ../kio/kio/kprotocolinfo.cpp
+// KURL based static functions are implemented in ../tdeio/tdeio/kprotocolinfo.cpp
void KProtocolInfo::virtual_hook( int id, void* data )
{ KSycocaEntry::virtual_hook( id, data ); }
diff --git a/tdecore/kprotocolinfofactory.h b/tdecore/kprotocolinfofactory.h
index 04883bde0..89ba330a9 100644
--- a/tdecore/kprotocolinfofactory.h
+++ b/tdecore/kprotocolinfofactory.h
@@ -20,7 +20,7 @@
#ifndef __kprotocolinfofactory_h__
#define __kprotocolinfofactory_h__
-#include "../kio/kio/kprotocolinfo.h"
+#include "../tdeio/tdeio/kprotocolinfo.h"
#include <tqmap.h>
#include <tqstring.h>
diff --git a/tdecore/kshortcutlist.cpp b/tdecore/kshortcutlist.cpp
index fcfc48b48..dd171062e 100644
--- a/tdecore/kshortcutlist.cpp
+++ b/tdecore/kshortcutlist.cpp
@@ -3,7 +3,7 @@
#include <kaccel.h>
#include "kaccelaction.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalaccel.h>
diff --git a/tdecore/ksimpleconfig.cpp b/tdecore/ksimpleconfig.cpp
index 5c0203a9f..55cf7485b 100644
--- a/tdecore/ksimpleconfig.cpp
+++ b/tdecore/ksimpleconfig.cpp
@@ -33,7 +33,7 @@
#include "kglobal.h"
#include "kstandarddirs.h"
-#include "kconfigbackend.h"
+#include "tdeconfigbackend.h"
#include "ksimpleconfig.h"
diff --git a/tdecore/ksimpleconfig.h b/tdecore/ksimpleconfig.h
index 326fc8094..541117500 100644
--- a/tdecore/ksimpleconfig.h
+++ b/tdecore/ksimpleconfig.h
@@ -21,7 +21,7 @@
#ifndef _KSIMPLECONFIG_H
#define _KSIMPLECONFIG_H
-#include "kconfig.h"
+#include "tdeconfig.h"
class KSimpleConfigPrivate;
diff --git a/tdecore/ksimpledirwatch.cpp b/tdecore/ksimpledirwatch.cpp
index 08d686beb..d961d4657 100644
--- a/tdecore/ksimpledirwatch.cpp
+++ b/tdecore/ksimpledirwatch.cpp
@@ -45,7 +45,7 @@
#include <kapplication.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kstaticdeleter.h>
#include <kde_file.h>
@@ -184,7 +184,7 @@ void KSimpleDirWatchPrivate::dnotify_sigio_handler(int sig, siginfo_t *si, void
* are supported:
* - Polling: All files to be watched are polled regularly
* using stat (more precise: TQFileInfo.lastModified()).
- * The polling frequency is determined from global kconfig
+ * The polling frequency is determined from global tdeconfig
* settings, defaulting to 500 ms for local directories
* and 5000 ms for remote mounts
* - FAM (File Alternation Monitor): first used on IRIX, SGI
diff --git a/tdecore/ksocks.cpp b/tdecore/ksocks.cpp
index eb00b1cec..cc0cde8ca 100644
--- a/tdecore/ksocks.cpp
+++ b/tdecore/ksocks.cpp
@@ -29,7 +29,7 @@
#include <klocale.h>
#include <kdebug.h>
#include "klibloader.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kapplication.h>
#include <sys/types.h>
diff --git a/tdecore/kstandarddirs.cpp b/tdecore/kstandarddirs.cpp
index c902cd6f1..c44f60458 100644
--- a/tdecore/kstandarddirs.cpp
+++ b/tdecore/kstandarddirs.cpp
@@ -47,7 +47,7 @@
#include <tqstringlist.h>
#include "kstandarddirs.h"
-#include "kconfig.h"
+#include "tdeconfig.h"
#include "kinstance.h"
#include "kshell.h"
#include "ksimpleconfig.h"
diff --git a/tdecore/kstdaccel.cpp b/tdecore/kstdaccel.cpp
index 5bda8ebf5..afc49aac4 100644
--- a/tdecore/kstdaccel.cpp
+++ b/tdecore/kstdaccel.cpp
@@ -23,7 +23,7 @@
#include "kaccelaction.h"
#include "kaccelbase.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
diff --git a/tdecore/kuniqueapplication.cpp b/tdecore/kuniqueapplication.cpp
index d8b69eade..422b39a1b 100644
--- a/tdecore/kuniqueapplication.cpp
+++ b/tdecore/kuniqueapplication.cpp
@@ -43,7 +43,7 @@
#include <kstartupinfo.h>
#endif
-#include <kconfig.h>
+#include <tdeconfig.h>
#include "kdebug.h"
#include "kuniqueapplication.h"
diff --git a/tdecore/networkbackends/network-manager/network-manager.cpp b/tdecore/networkbackends/network-manager/network-manager.cpp
index 206e75737..d747b61ae 100644
--- a/tdecore/networkbackends/network-manager/network-manager.cpp
+++ b/tdecore/networkbackends/network-manager/network-manager.cpp
@@ -20,7 +20,7 @@
#include <tqdbusmessage.h>
-#include "kconfig.h"
+#include "tdeconfig.h"
#include "tdehardwaredevices.h"
#include "network-manager.h"
@@ -4828,10 +4828,10 @@ TDENetworkVPNTypeList TDENetworkConnectionManager_BackendNM::availableVPNTypes()
// read in all available Services
for (TQStringList::Iterator i = services.begin (); i != services.end (); ++i) {
TQString service = NM_PLUGIN_SERVICE_DIR + TQString ("/") + *i;
- TDEConfig* kconfig = new TDEConfig (service, true, true, "config");
- kconfig->setGroup ("VPN Connection");
+ TDEConfig* tdeconfig = new TDEConfig (service, true, true, "config");
+ tdeconfig->setGroup ("VPN Connection");
- TQString serviceName = kconfig->readEntry("name", TQString());
+ TQString serviceName = tdeconfig->readEntry("name", TQString());
serviceName = serviceName.lower();
if (serviceName == "openvpn") {
@@ -4847,7 +4847,7 @@ TDENetworkVPNTypeList TDENetworkConnectionManager_BackendNM::availableVPNTypes()
ret.append(TDENetworkVPNType::VPNC);
}
- delete kconfig;
+ delete tdeconfig;
}
}
diff --git a/tdecore/tdeconfig.cpp b/tdecore/tdeconfig.cpp
new file mode 100644
index 000000000..62464b81f
--- /dev/null
+++ b/tdecore/tdeconfig.cpp
@@ -0,0 +1,367 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Preston Brown <pbrown@kde.org>
+ Copyright (C) 1997-1999 Matthias Kalle Dalheimer (kalle@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#include <config.h>
+
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <tqfileinfo.h>
+
+#include <kapplication.h>
+#include "tdeconfigbackend.h"
+
+#include "tdeconfig.h"
+#include "kglobal.h"
+#include "kstandarddirs.h"
+#include "kstaticdeleter.h"
+#include <tqtimer.h>
+
+TDEConfig::TDEConfig( const TQString& fileName,
+ bool bReadOnly, bool bUseKderc, const char *resType )
+ : TDEConfigBase(), bGroupImmutable(false), bFileImmutable(false),
+ bForceGlobal(false)
+{
+ // set the object's read-only status.
+ setReadOnly(bReadOnly);
+
+ // for right now we will hardcode that we are using the INI
+ // back end driver. In the future this should be converted over to
+ // a object factory of some sorts.
+ TDEConfigINIBackEnd *aBackEnd = new TDEConfigINIBackEnd(this,
+ fileName,
+ resType,
+ bUseKderc);
+
+ // set the object's back end pointer to this new backend
+ backEnd = aBackEnd;
+
+ // read initial information off disk
+ reparseConfiguration();
+
+ // we let KStandardDirs add custom user config files. It will do
+ // this only once. So only the first call ever to this constructor
+ // will anything else than return here We have to reparse here as
+ // configuration files may appear after customized directories have
+ // been added. and the info they contain needs to be inserted into the
+ // config object.
+ // Since this makes only sense for config directories, addCustomized
+ // returns true only if new config directories appeared.
+ if (TDEGlobal::dirs()->addCustomized(this))
+ reparseConfiguration();
+}
+
+TDEConfig::TDEConfig(TDEConfigBackEnd *aBackEnd, bool bReadOnly)
+ : bGroupImmutable(false), bFileImmutable(false),
+ bForceGlobal(false)
+{
+ setReadOnly(bReadOnly);
+ backEnd = aBackEnd;
+ reparseConfiguration();
+}
+
+TDEConfig::~TDEConfig()
+{
+ sync();
+
+ delete backEnd;
+}
+
+void TDEConfig::rollback(bool bDeep)
+{
+ TDEConfigBase::rollback(bDeep);
+
+ if (!bDeep)
+ return; // object's bDeep flag is set in TDEConfigBase method
+
+ // clear any dirty flags that entries might have set
+ for (KEntryMapIterator aIt = aEntryMap.begin();
+ aIt != aEntryMap.end(); ++aIt)
+ (*aIt).bDirty = false;
+}
+
+TQStringList TDEConfig::groupList() const
+{
+ TQStringList retList;
+
+ KEntryMapConstIterator aIt = aEntryMap.begin();
+ KEntryMapConstIterator aEnd = aEntryMap.end();
+ for (; aIt != aEnd; ++aIt)
+ {
+ while(aIt.key().mKey.isEmpty())
+ {
+ TQCString group = aIt.key().mGroup;
+ ++aIt;
+ while (true)
+ {
+ if (aIt == aEnd)
+ return retList; // done
+
+ if (aIt.key().mKey.isEmpty())
+ break; // Group is empty, next group
+
+ if (!aIt.key().bDefault && !(*aIt).bDeleted)
+ {
+ if (group != "$Version") // Special case!
+ retList.append(TQString::fromUtf8(group));
+ break; // Group is non-empty, added, next group
+ }
+ ++aIt;
+ }
+ }
+ }
+
+ return retList;
+}
+
+TQMap<TQString, TQString> TDEConfig::entryMap(const TQString &pGroup) const
+{
+ TQCString pGroup_utf = pGroup.utf8();
+ KEntryKey groupKey( pGroup_utf, 0 );
+ TQMap<TQString, TQString> tmpMap;
+
+ KEntryMapConstIterator aIt = aEntryMap.find(groupKey);
+ if (aIt == aEntryMap.end())
+ return tmpMap;
+ ++aIt; // advance past special group entry marker
+ for (; aIt.key().mGroup == pGroup_utf && aIt != aEntryMap.end(); ++aIt)
+ {
+ // Leave the default values out && leave deleted entries out
+ if (!aIt.key().bDefault && !(*aIt).bDeleted)
+ tmpMap.insert(TQString::fromUtf8(aIt.key().mKey), TQString::fromUtf8((*aIt).mValue.data(), (*aIt).mValue.length()));
+ }
+
+ return tmpMap;
+}
+
+void TDEConfig::reparseConfiguration()
+{
+ // Don't lose pending changes
+ if (!isReadOnly() && backEnd && bDirty)
+ backEnd->sync();
+
+ aEntryMap.clear();
+
+ // add the "default group" marker to the map
+ KEntryKey groupKey("<default>", 0);
+ aEntryMap.insert(groupKey, KEntry());
+
+ bFileImmutable = false;
+ parseConfigFiles();
+ bFileImmutable = bReadOnly;
+}
+
+KEntryMap TDEConfig::internalEntryMap(const TQString &pGroup) const
+{
+ TQCString pGroup_utf = pGroup.utf8();
+ KEntry aEntry;
+ KEntryMapConstIterator aIt;
+ KEntryKey aKey(pGroup_utf, 0);
+ KEntryMap tmpEntryMap;
+
+ aIt = aEntryMap.find(aKey);
+ if (aIt == aEntryMap.end()) {
+ // the special group key is not in the map,
+ // so it must be an invalid group. Return
+ // an empty map.
+ return tmpEntryMap;
+ }
+ // we now have a pointer to the nodes we want to copy.
+ for (; aIt.key().mGroup == pGroup_utf && aIt != aEntryMap.end(); ++aIt)
+ {
+ tmpEntryMap.insert(aIt.key(), *aIt);
+ }
+
+ return tmpEntryMap;
+}
+
+void TDEConfig::putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup)
+{
+ if (bFileImmutable && !_key.bDefault)
+ return;
+
+ // check to see if the special group key is present,
+ // and if not, put it in.
+ if (_checkGroup)
+ {
+ KEntryKey groupKey( _key.mGroup, 0);
+ KEntry &entry = aEntryMap[groupKey];
+ bGroupImmutable = entry.bImmutable;
+ }
+ if (bGroupImmutable && !_key.bDefault)
+ return;
+
+ // now either add or replace the data
+ KEntry &entry = aEntryMap[_key];
+ bool immutable = entry.bImmutable;
+ if (immutable && !_key.bDefault)
+ return;
+
+ entry = _data;
+ entry.bImmutable |= immutable;
+ entry.bGlobal |= bForceGlobal; // force to kdeglobals
+
+ if (_key.bDefault)
+ {
+ // We have added the data as default value,
+ // add it as normal value as well.
+ KEntryKey key(_key);
+ key.bDefault = false;
+ aEntryMap[key] = _data;
+ }
+}
+
+KEntry TDEConfig::lookupData(const KEntryKey &_key) const
+{
+ KEntryMapConstIterator aIt = aEntryMap.find(_key);
+ if (aIt != aEntryMap.end())
+ {
+ const KEntry &entry = *aIt;
+ if (entry.bDeleted)
+ return KEntry();
+ else
+ return entry;
+ }
+ else {
+ return KEntry();
+ }
+}
+
+bool TDEConfig::internalHasGroup(const TQCString &group) const
+{
+ KEntryKey groupKey( group, 0);
+
+ KEntryMapConstIterator aIt = aEntryMap.find(groupKey);
+ KEntryMapConstIterator aEnd = aEntryMap.end();
+
+ if (aIt == aEnd)
+ return false;
+ ++aIt;
+ for(; (aIt != aEnd); ++aIt)
+ {
+ if (aIt.key().mKey.isEmpty())
+ break;
+
+ if (!aIt.key().bDefault && !(*aIt).bDeleted)
+ return true;
+ }
+ return false;
+}
+
+void TDEConfig::setFileWriteMode(int mode)
+{
+ backEnd->setFileWriteMode(mode);
+}
+
+KLockFile::Ptr TDEConfig::lockFile(bool bGlobal)
+{
+ TDEConfigINIBackEnd *aBackEnd = dynamic_cast<TDEConfigINIBackEnd*>(backEnd);
+ if (!aBackEnd) return 0;
+ return aBackEnd->lockFile(bGlobal);
+}
+
+void TDEConfig::checkUpdate(const TQString &id, const TQString &updateFile)
+{
+ TQString oldGroup = group();
+ setGroup("$Version");
+ TQString cfg_id = updateFile+":"+id;
+ TQStringList ids = readListEntry("update_info");
+ if (!ids.contains(cfg_id))
+ {
+ TQStringList args;
+ args << "--check" << updateFile;
+ TDEApplication::tdeinitExecWait("tdeconf_update", args);
+ reparseConfiguration();
+ }
+ setGroup(oldGroup);
+}
+
+TDEConfig* TDEConfig::copyTo(const TQString &file, TDEConfig *config) const
+{
+ if (!config)
+ config = new TDEConfig(TQString::null, false, false);
+ config->backEnd->changeFileName(file, "config", false);
+ config->setReadOnly(false);
+ config->bFileImmutable = false;
+ config->backEnd->mConfigState = ReadWrite;
+
+ TQStringList groups = groupList();
+ for(TQStringList::ConstIterator it = groups.begin();
+ it != groups.end(); ++it)
+ {
+ TQMap<TQString, TQString> map = entryMap(*it);
+ config->setGroup(*it);
+ for (TQMap<TQString,TQString>::Iterator it2 = map.begin();
+ it2 != map.end(); ++it2)
+ {
+ config->writeEntry(it2.key(), it2.data());
+ }
+
+ }
+ return config;
+}
+
+void TDEConfig::virtual_hook( int id, void* data )
+{ TDEConfigBase::virtual_hook( id, data ); }
+
+static KStaticDeleter< TQValueList<KSharedConfig*> > sd;
+TQValueList<KSharedConfig*> *KSharedConfig::s_list = 0;
+
+KSharedConfig::Ptr KSharedConfig::openConfig(const TQString& fileName, bool readOnly, bool useKDEGlobals )
+{
+ if (s_list)
+ {
+ for(TQValueList<KSharedConfig*>::ConstIterator it = s_list->begin();
+ it != s_list->end(); ++it)
+ {
+ if ((*it)->backEnd->fileName() == fileName &&
+ (*it)->bReadOnly == readOnly &&
+ (*it)->backEnd->useKDEGlobals == useKDEGlobals )
+ return (*it);
+ }
+ }
+ return new KSharedConfig(fileName, readOnly, useKDEGlobals);
+}
+
+KSharedConfig::KSharedConfig( const TQString& fileName, bool readonly, bool usekdeglobals)
+ : TDEConfig(fileName, readonly, usekdeglobals)
+{
+ if (!s_list)
+ {
+ sd.setObject(s_list, new TQValueList<KSharedConfig*>);
+ }
+
+ s_list->append(this);
+}
+
+KSharedConfig::~KSharedConfig()
+{
+ if ( s_list )
+ s_list->remove(this);
+}
+
+#include "tdeconfig.moc"
diff --git a/tdecore/tdeconfig.h b/tdecore/tdeconfig.h
new file mode 100644
index 000000000..77a009efa
--- /dev/null
+++ b/tdecore/tdeconfig.h
@@ -0,0 +1,296 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Preston Brown <pbrown@kde.org>
+ Copyright (C) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KCONFIG_H
+#define _KCONFIG_H
+
+class TQTimer;
+
+#include <tqvaluelist.h>
+
+#include "tdeconfigbase.h"
+#include "klockfile.h"
+
+class TDEConfigPrivate;
+
+/**
+* Access KDE Configuration entries.
+*
+* This class implements KDE's default configuration system.
+*
+* @author Kalle Dalheimer <kalle@kde.org>, Preston Brown <pbrown@kde.org>
+* @see TDEGlobal::config(), TDEConfigBase, KSimpleConfig
+* @short KDE Configuration Management class
+*/
+class TDECORE_EXPORT TDEConfig : public TDEConfigBase
+{
+ Q_OBJECT
+
+public:
+
+ /**
+ * Constructs a TDEConfig object.
+ *
+ * @param fileName A file to parse in addition to the
+ * system-wide file(s). If it is not provided, only global
+ * KDE configuration data will be read (depending on the value of
+ * @p bUseKDEGlobals).
+ * @param bReadOnly Set the config object's read-only status. Note that the
+ * object will automatically become read-only if either the user does not have
+ * write permission to @p fileName or if no file was specified.
+ * @param bUseKDEGlobals Toggle reading the global KDE configuration file.
+ * @param resType the place to look in (config, data, etc) See KStandardDirs.
+ */
+ TDEConfig( const TQString& fileName = TQString::null,
+ bool bReadOnly = false, bool bUseKDEGlobals = true, const char *resType="config");
+
+ TDEConfig(TDEConfigBackEnd *backEnd, bool bReadOnly = false);
+
+ /**
+ * Destructs the TDEConfig object.
+ *
+ * Writes back any dirty configuration entries, and destroys
+ * dynamically created objects.
+ */
+ virtual ~TDEConfig();
+
+ /**
+ * Clears all entries out of the @p dirtyEntryMap, so the
+ * values will not be written to disk on a later call to
+ * sync().
+ *
+ * @param bDeep If true, the dirty map is actually emptied.
+ * otherwise, the config object's global dirty flag is set to
+ * false, but the dirty entries remain in the dirty entry
+ * map.
+ *
+ * @see TDEConfigBase::rollback
+ */
+ virtual void rollback(bool bDeep = true);
+
+
+ /**
+ * Returns a list of groups that are known.
+ * @return a list of of groups
+ */
+ virtual TQStringList groupList() const;
+
+ /**
+ * Returns a map (tree) of entries for all entries in a particular
+ * group.
+ *
+ * Only the actual entry string is returned, none of the
+ * other internal data should be included.
+ *
+ * @param pGroup A group to get keys from.
+ * @return A map of entries in the group specified, indexed by key.
+ * The returned map may be empty if the group is not found.
+ */
+ virtual TQMap<TQString, TQString> entryMap(const TQString &pGroup) const;
+
+ /**
+ * Clears all internal data structures and then reread
+ * configuration information from disk.
+ */
+ virtual void reparseConfiguration();
+
+ /**
+ * Set the file mode for newly created files.
+ *
+ * @param mode the mode for new files as described in chmod(2)
+ * @see man:chmod(2) for a description of @p mode
+ */
+ void setFileWriteMode(int mode);
+
+ /**
+ * Forces all following write-operations being performed on kdeglobals,
+ * independent of the bGlobal flag in writeEntry().
+ * @param force true to force writing in kdeglobals
+ * @see forceGlobal
+ */
+ void setForceGlobal( bool force ) { bForceGlobal = force; }
+
+ /**
+ * Returns true if all entries are being written into kdeglobals.
+ * @return true if all entries are being written into kdeglobals
+ * @see setForceGlobal
+ */
+ bool forceGlobal() const { return bForceGlobal; }
+
+ /**
+ * Checks whether the config file contains the update @p id
+ * as contained in @p updateFile. If not, it runs tdeconf_update
+ * to update the config file.
+ *
+ * If you install config update files with critical fixes
+ * you may wish to use this method to verify that a critical
+ * update has indeed been performed to catch the case where
+ * a user restores an old config file from backup that has
+ * not been updated yet.
+ * @param id the update to check
+ * @param updateFile the file containing the update
+ * @since 3.1
+ */
+ void checkUpdate(const TQString &id, const TQString &updateFile);
+
+ /**
+ * Copies all entries from this config object to a new config
+ * object that will save itself to @p file.
+ *
+ * Actual saving to @p file happens when the returned object is
+ * destructed or when sync() is called upon it.
+ *
+ * @param file the new config object will save itself to.
+ * @param config optional config object to reuse
+ * @since 3.2
+ */
+ TDEConfig* copyTo(const TQString &file, TDEConfig *config=0) const;
+
+ /**
+ * Returns a lock file object for the configuration file or 0 if
+ * the backend does not support locking.
+ * @param bGlobal if true, return the lock file for the global config file
+ *
+ * NOTE: TDEConfig::sync() requires a lock on both the normal and global
+ * config file. When calling TDEConfig::sync() while having a lock on the
+ * global config file, the normal config file MUST be locked AS WELL and the
+ * normal config file MUST be locked BEFORE the global config file!
+ * Otherwise there is a risk of deadlock.
+ * @since 3.3
+ */
+ KLockFile::Ptr lockFile( bool bGlobal=false );
+
+protected:
+
+ /**
+ * Returns true if the specified group is known.
+ *
+ * @param group The group to search for.
+ * @returns true if the group exists.
+ */
+ virtual bool internalHasGroup(const TQCString &group) const;
+
+ /**
+ * @internal
+ * Returns a map (tree) of the entries in the specified group.
+ *
+ * Do not use this function, the implementation / return type are
+ * subject to change.
+ *
+ * @param pGroup the group to provide a KEntryMap for.
+ * @return The map of the entries in the group.
+ */
+ virtual KEntryMap internalEntryMap(const TQString &pGroup) const;
+
+ /**
+ * @internal
+ * Returns a copy of the internal map used to hold all entries.
+ *
+ * Do not use this function, the implementation / return type are
+ * subject to change.
+ *
+ * @return The map of the entries in the group.
+ */
+ virtual KEntryMap internalEntryMap() const { return aEntryMap; }
+
+ /**
+ * Inserts a (key, value) pair into the internal storage mechanism of
+ * the configuration object.
+ *
+ * @param _key The key to insert. It contains information both on
+ * the group of the key and the key itself. If the key already
+ * exists, the old value will be replaced.
+ * @param _data the KEntry that is to be stored.
+ * @param _checkGroup When false, assume that the group already exists.
+ */
+ virtual void putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup=true);
+
+ /**
+ * Looks up an entry in the config object's internal structure.
+ *
+ * @param _key The key to look up It contains information both on
+ * the group of the key and the entry's key itself.
+ * @return the KEntry value (data) found for the key. KEntry.aValue
+ * will be the null string if nothing was located.
+ */
+ virtual KEntry lookupData(const KEntryKey &_key) const;
+
+ /**
+ * Contains all key,value entries, as well as some "special"
+ * keys which indicate the start of a group of entries.
+ *
+ * These special keys will have the .key portion of their KEntryKey
+ * set to TQString::null.
+ */
+ KEntryMap aEntryMap;
+
+private:
+ /**
+ * @internal
+ * copy-construction and assignment are not allowed
+ */
+ TDEConfig( const TDEConfig& );
+ /**
+ * @internal
+ * copy-construction and assignment are not allowed
+ */
+ TDEConfig& operator= ( const TDEConfig& rConfig );
+
+private:
+ bool bGroupImmutable : 1; // Current group is immutable.
+ bool bFileImmutable : 1; // Current file is immutable.
+ bool bForceGlobal : 1; // Apply everything to kdeglobals.
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ TDEConfigPrivate *d;
+};
+
+/**
+ * TDEConfig variant using shared memory
+ *
+ * KSharedConfig provides a reference counted, shared memory variant
+ * of TDEConfig.
+ */
+class TDECORE_EXPORT KSharedConfig : public TDEConfig, public KShared
+{
+ friend class TQValueList<KSharedConfig*>;
+public:
+ typedef KSharedPtr<KSharedConfig> Ptr;
+
+public:
+ /**
+ * Returns a ref-counted pointer to a shared read-write config object.
+ * @param fileName the name of the file to use for the configuration
+ * @param readOnly set the config object's read-only status
+ * @param bUseKDEGlobals Toggle reading the global KDE configuration file.
+ */
+ static KSharedConfig::Ptr openConfig(const TQString& fileName, bool readOnly = false,
+ bool bUseKDEGlobals = true);
+
+private:
+ KSharedConfig( const TQString& fileName, bool readOnly, bool useKDEGlobals );
+ ~KSharedConfig();
+
+ static TQValueList<KSharedConfig*> *s_list;
+};
+
+#endif
diff --git a/tdecore/tdeconfig_compiler/CMakeLists.txt b/tdecore/tdeconfig_compiler/CMakeLists.txt
new file mode 100644
index 000000000..a4f24c43e
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/CMakeLists.txt
@@ -0,0 +1,29 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### tdeconfig_compiler ##########################
+
+tde_add_executable( tdeconfig_compiler
+ SOURCES tdeconfig_compiler.cpp
+ LINK tdecore-shared
+ DESTINATION ${BIN_INSTALL_DIR}
+)
diff --git a/tdecore/tdeconfig_compiler/Makefile.am b/tdecore/tdeconfig_compiler/Makefile.am
new file mode 100644
index 000000000..d5141f102
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/Makefile.am
@@ -0,0 +1,18 @@
+SUBDIRS = example tests
+
+AM_CPPFLAGS = -I$(top_srcdir)/tdecore -I$(top_srcdir) $(all_includes)
+
+bin_PROGRAMS = tdeconfig_compiler
+
+tdeconfig_compiler_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+tdeconfig_compiler_LDADD = $(LIB_TDECORE)
+tdeconfig_compiler_SOURCES = tdeconfig_compiler.cpp
+
+TESTFILES = test1.kcfg test2.kcfg test3.kcfg test4.kcfg test_dpointer.kcfg
+
+check-local:
+ for i in $(TESTFILES); \
+ do xmllint --noout --schema $(srcdir)/kcfg.xsd $(srcdir)/tests/$$i; \
+ perl $(top_srcdir)/tdecore/tdeconfig_compiler/checkkcfg.pl \
+ $(top_srcdir)/tdecore/tdeconfig_compiler/tests/$$i; done
+
diff --git a/tdecore/tdeconfig_compiler/README.dox b/tdecore/tdeconfig_compiler/README.dox
new file mode 100644
index 000000000..1b4926e96
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/README.dox
@@ -0,0 +1,255 @@
+/**
+\page tdeconfig_compiler The KDE Configuration Compiler
+
+tdeconfig_compiler generates C++ source code from an XML file containing
+information about configuration options (.kcfg) and a file that provides
+the code generation options (.kcfgc) The generated class is based on
+TDEConfigSkeleton and provides an API for the application to access its
+configuration data.
+
+<h2>XML description of the configuration options</h2>
+
+The structure of the .kcfg file is described by its DTD kcfg.dtd.
+
+The \<kcfgfile\> tag contains the name of the configuration file described.
+Omitting the name will make the generated class use the default configuration
+file ("<appname>rc").
+
+The \<include\> tags are optional and may contain C++ header files that
+are needed to compile the code needed to compute default values.
+
+The remaining entries in the XML file are grouped by the tag \<group\>
+which describes the corresponding group in the configuration file.
+
+The individual entries must have at least a name or a key. The name is used to
+create accessor and modifier functions. It's also used as the key in the config
+file. If \<key\> is given, but not \<name\>, the name is constructed by removing
+all spaces from \<key\>.
+
+An entry must also have a type. The list of allowable types is
+specified in the DTD and loosely follows the list of types supported
+by the QVariant with exception of the clearly binary types
+(e.g. Pixmap, Image...) which are not supported. Besides those basic
+type the following special types are supported:
+
+- Path This is a string that is specially treated as a file-path.
+ In particular paths in the home directory are prefixed with $HOME in
+ when being stored in the configuration file.
+
+- Enum This indicates an enumeration. The possible enum values should
+ be provided via the \<choices\> tag. Enum values are accessed as integers
+ by the application but stored as string in the configuration file. This
+ makes it possible to add more values at a later date without breaking
+ compatibility.
+
+- IntList This indicates a list of integers. This information is provided
+ to the application as QValueList<int>. Useful for storing QSplitter
+ geometries.
+
+An entry can optionally have a default value which is used as default when
+the value isn't specified in any config file. Default values are interpreted
+as literal constant values. If a default value needs to be computed
+or if it needs to be obtained from a function call, the \<default\> tag
+should contain the code="true" attribute. The contents of the \<default\>
+tag is then considered to be a C++ expression. Note that in this case you
+might have to add an \<include\> tag as described above so that the code
+which computes the default value can be compiled.
+
+Additional code for computing default values can be provided via
+the \<code\> tag. The contents of the \<code\> tag is inserted as-is. A
+typical use for this is to compute a common default value which can
+then be referenced by multiple entries that follow.
+
+<h2>Code generation options</h2>
+
+The options for generating the C++ sources are read from the file with the
+extension .kcfgc. To generate a class add the corresponding kcfgc file to the
+SOURCES line in the Makefile.am.
+
+The following options are read from the kcfgc file:
+
+<table>
+<tr>
+ <td><b><i>Name</i></b></td>
+ <td><b><i>Type</i></b></td>
+ <td><b><i>Default</i></b></td>
+ <td><b><i>Description</i></b></td>
+</tr>
+<tr>
+ <td><b>File</b></td>
+ <td>string</td>
+ <td>programname.kcfg</td>
+ <td>Name of kcfg file containing the options the class is generated for</td>
+</tr>
+<tr>
+ <td><b>NameSpace</b></td>
+ <td>string</td>
+ <td>-</td>
+ <td>Optional namespace for generated class</td>
+</tr>
+<tr>
+ <td><b>ClassName</b></td>
+ <td>string</td>
+ <td>-</td>
+ <td>Name of generated class (required)</td>
+</tr>
+<tr>
+ <td><b>Inherits</b></td>
+ <td>string</td>
+ <td>TDEConfigSkeleton</td>
+ <td>Class the generated class inherits from. This class must inherit
+ TDEConfigSkeleton.</td>
+</tr>
+<tr>
+ <td><b>Visibility</b></td>
+ <td>string</td>
+ <td>-</td>
+ <td>Inserts visibility directive (for example KDE_EXPORT) between "class" keyword and class
+ name in header file</td>
+</tr>
+<tr>
+ <td><b>Singleton</b></td>
+ <td>bool</td>
+ <td>false</td>
+ <td>Generated class is a singleton.</td>
+</tr>
+<tr>
+ <td><b>CustomAdditions</b></td>
+ <td>bool</td>
+ <td>-</td>
+ <td></td>
+</tr>
+<tr>
+ <td><b>MemberVariables</b></td>
+ <td>string: public|protected|private</td>
+ <td>private</td>
+ <td>C++ access modifier used for memeber variables holding the configuration
+ valuse</td>
+</tr>
+<tr>
+ <td><b>IncludeFiles</b></td>
+ <td>comma separated list of strings</td>
+ <td>-</td>
+ <td>Names of files to be included in the header of the generated class</td>
+</tr>
+<tr>
+ <td><b>Mutators</b></td>
+ <td>true, false or a comma seperated list of options</td>
+ <td>-</td>
+ <td>If true, mutator functions for all configuration options are generated.
+ If false, no mutator functions are generated. If a list is provided,
+ mutator functions are generated for the options that are listed.</td>
+</tr>
+<tr>
+ <td><b>ItemAccessors</b></td>
+ <td>bool</td>
+ <td>false</td>
+ <td>Generate accessor functions for the TDEConfigSkeletonItem objects
+ corresponding to the configuration options. If <b>SetUserTexts</b> is set,
+ <b>ItemAccessors</b> also has to be set.</td>
+</tr>
+<tr>
+ <td><b>SetUserTexts</b></td>
+ <td>bool</td>
+ <td>false</td>
+ <td>Set the label and whatthis texts of the items from the kcfg file.If
+ <b>SetUserTexts</b> is set, <b>ItemAccessors</b> also has to be set.</td>
+</tr>
+<tr>
+ <td><b>GlobalEnums</b></td>
+ <td>bool</td>
+ <td>false</td>
+ <td>If set to true all choices of Enum items will be created in the global
+ scope of the generated class. If set to false, each Enum item will get an own
+ namespace for its choices.</td>
+</tr>
+</table>
+
+
+<h2>Advanced options</h2>
+
+There are several possibilities to parameterize entries.
+
+- Parameterized entries
+
+An entry can be parameterized using a fixed range parameter specified with
+the \<parameter\> tag. Such parameter can either be an Enum or an int. An Enum
+parameter should specify the possible enumeration values with the \<choices\>
+tag. An int parameter should specify its maximum value. Its minimum value
+is always 0.
+
+A parameterized entry is expanded to a number of entries, one for each
+value in the parameter range. The name and key should contain a reference
+to the parameter in the form of $(parameter-name). When expanding the entries
+the $(parameter-name) part is replaced with the value of the parameter.
+In the case of an Enum parameter it is replaced with the name of the
+enumuration value. In the case of an int parameter it is replaced with
+the numeric value of the parameter.
+
+Parameterized entries all share the same default value unless different
+default values have been specified for specific parameter values.
+This can be done with the param= attribute of the \<default\>. When a
+param attribute is specified the default value only applies to that
+particular parameter value.
+
+Example 1:
+\verbatim
+ <entry name="Color$(ColorIndex)" type="Color" key="color_$(ColorIndex)">
+ <parameter name="ColorIndex" type="Int" max="3"/>
+ <default param="0">#ff0000</default>
+ <default param="1">#00ff00</default>
+ <default param="2">#0000ff</default>
+ <default param="3">#ffff00</default>
+ </entry>
+\endverbatim
+
+The above describes 4 color configuration entries with the following defaults:
+
+\verbatim
+color_0=#ff0000
+color_1=#00ff00
+color_2=#0000ff
+color_3=#ffff00
+\endverbatim
+
+The configuration options will be accessible to the application via
+a QColor color(int ColorIndex) and a
+void setColor(int ColorIndex, const QColor &v) function.
+
+Example 2:
+\verbatim
+ <entry name="Sound$(SoundEvent)" type="String" key="sound_$(SoundEvent)">
+ <parameter name="SoundEvent" type="Enum">
+ <values>
+ <value>Explosion</value>
+ <value>Crash</value>
+ <value>Missile</value>
+ </values>
+ </parameter>
+ <default param="Explosion">boom.wav</default>
+ <default param="Crash">crash.wav</default>
+ <default param="Missile">missile.wav</default>
+ </entry>
+\endverbatim
+
+The above describes 3 string configuration entries with the following defaults:
+
+sound_Explosion=boom.wav
+sound_Crash=crash.wav
+sound_Missile=missile.wav
+
+The configuration options will be accessible to the application via
+a QString sound(int SoundEvent) and a
+void setSound(int SoundEvent, const QString &v) function.
+
+- Parameterized groups
+
+...STILL TODO...
+
+
+
+
+
+If you have questions or comments please contact Cornelius Schumacher
+<schumacher@kde.org> or Waldo Bastian <bastian@kde.org>
+*/
diff --git a/tdecore/kconfig_compiler/TODO b/tdecore/tdeconfig_compiler/TODO
index e69de29bb..e69de29bb 100644
--- a/tdecore/kconfig_compiler/TODO
+++ b/tdecore/tdeconfig_compiler/TODO
diff --git a/tdecore/tdeconfig_compiler/checkkcfg.pl b/tdecore/tdeconfig_compiler/checkkcfg.pl
new file mode 100755
index 000000000..26b12bad2
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/checkkcfg.pl
@@ -0,0 +1,83 @@
+#!/usr/bin/perl
+
+if ( @ARGV != 1 ) {
+ print STDERR "Missing arg: filename\n";
+ exit 1;
+}
+
+$file = $ARGV[0];
+
+$file =~ /^(.*)\.[^\.]*$/;
+$filebase = $1;
+
+$file_h = "$filebase.h";
+$file_cpp = "$filebase.cpp";
+
+$kcfgc = $file . "c";
+
+$cmd = "./tdeconfig_compiler $file $kcfgc";
+
+#print "CMD $cmd\n";
+
+if ( system( $cmd ) != 0 ) {
+ print STDERR "Unable to run tdeconfig_compiler\n";
+ exit 1;
+}
+
+chectdefile( $file_h );
+chectdefile( $file_cpp );
+
+exit 0;
+
+sub chectdefile()
+{
+ my $file = shift;
+
+ $file =~ /\/([^\/]*)$/;
+ my $filename = $1;
+
+ print "Checking '$filename':\n";
+
+ my @ref;
+ if ( !open( REF, "$file.ref" ) ) {
+ print STDERR "Unable to open $file.ref\n";
+ exit 1;
+ }
+ while( <REF> ) {
+ push @ref, $_;
+ }
+ close REF;
+
+ if ( !open( READ, $filename ) ) {
+ print STDERR "Unable to open $filename\n";
+ exit 1;
+ }
+
+ $error = 0;
+ $i = 0;
+ $line = 1;
+ while( <READ> ) {
+ $out = $_;
+ $ref = @ref[$i++];
+
+ if ( $out ne $ref ) {
+ $error++;
+ print " Line $line: Expected : $ref";
+ print " Line $line: Compiler output : $out";
+ }
+
+ $line++;
+ }
+
+ close READ;
+
+ if ( $error > 0 ) {
+ print "\n FAILED: $error errors found.\n";
+ if ( $error > 5 ) {
+ system( "diff -u $file.ref $filename" );
+ }
+ exit 1;
+ } else {
+ print " OK\n";
+ }
+}
diff --git a/tdecore/tdeconfig_compiler/example/Makefile.am b/tdecore/tdeconfig_compiler/example/Makefile.am
new file mode 100644
index 000000000..612788f6b
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/example/Makefile.am
@@ -0,0 +1,27 @@
+AM_CPPFLAGS = -I$(top_srcdir)/tdecore -I$(top_srcdir) $(all_includes)
+
+check_PROGRAMS = example # autoexample
+EXTRA_PROGRAMS = autoexample
+
+example_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+example_LDADD = $(LIB_TDECORE)
+example_SOURCES = example.cpp exampleprefs_base.cpp
+
+autoexample_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+autoexample_LDADD = $(LIB_TDECORE) $(LIB_TDEUI)
+autoexample_SOURCES = exampleprefs_base.cpp general_base.ui myoptions_base.ui \
+ autoexample.cpp
+
+example.o exampleprefs_base.o: exampleprefs_base.h
+# avoid running the below command in parallel
+exampleprefs_base.cpp: exampleprefs_base.h
+exampleprefs_base.cpp exampleprefs_base.h: $(srcdir)/example.kcfg ../tdeconfig_compiler $(srcdir)/exampleprefs_base.kcfgc
+ ../tdeconfig_compiler $(srcdir)/example.kcfg $(srcdir)/exampleprefs_base.kcfgc
+
+METASOURCES = AUTO
+
+CLEANFILES = exampleprefs_base.h exampleprefs_base.cpp
+
+## The example's messages should not go into tdelibs.pot
+messages: rc.cpp
+ true
diff --git a/tdecore/tdeconfig_compiler/example/autoexample.cpp b/tdecore/tdeconfig_compiler/example/autoexample.cpp
new file mode 100644
index 000000000..6ed89d75f
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/example/autoexample.cpp
@@ -0,0 +1,64 @@
+/*
+ This file is part of KDE.
+
+ Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "general_base.h"
+#include "myoptions_base.h"
+
+#include "exampleprefs_base.h"
+
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+#include <kglobal.h>
+#include <tdeconfig.h>
+#include <kstandarddirs.h>
+#include <tdeconfigdialog.h>
+
+#include <tqlabel.h>
+
+int main( int argc, char **argv )
+{
+ TDEAboutData aboutData( "example", I18N_NOOP("autoconfig example"), "0.1" );
+ aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
+
+ TDECmdLineArgs::init( argc, argv, &aboutData );
+
+ TDEApplication app;
+
+ ExamplePrefsBase configSkeleton( "dummy1", "dummy2" );
+ configSkeleton.readConfig();
+
+ TDEConfigDialog *dialog = new TDEConfigDialog( 0, "settings", &configSkeleton );
+
+ GeneralBase *general = new GeneralBase( 0 );
+ dialog->addPage( general, i18n("General"), "General", "" );
+
+ MyOptionsBase *myOptions = new MyOptionsBase( 0 );
+ dialog->addPage( myOptions, i18n("MyOptions"), "MyOptions", "" );
+
+ app.setMainWidget( dialog );
+
+ dialog->show();
+
+ return app.exec();
+}
diff --git a/tdecore/tdeconfig_compiler/example/example.cpp b/tdecore/tdeconfig_compiler/example/example.cpp
new file mode 100644
index 000000000..6788d1ee0
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/example/example.cpp
@@ -0,0 +1,52 @@
+/*
+ This file is part of KDE.
+
+ Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "exampleprefs_base.h"
+
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+#include <kglobal.h>
+#include <tdeconfig.h>
+#include <kstandarddirs.h>
+
+int main( int argc, char **argv )
+{
+ TDEAboutData aboutData( "example", I18N_NOOP("cfgc example"), "0.1" );
+ aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
+
+ TDECmdLineArgs::init( argc, argv, &aboutData );
+
+ TDEApplication app;
+
+ ExamplePrefsBase *prefs = new ExamplePrefsBase("Trans1", "Folder2");
+
+ prefs->readConfig();
+
+ prefs->setAnotherOption(17);
+
+ kdWarning() << "Another Option = " << prefs->anotherOption() << endl;
+ kdWarning() << "Another Option2 = " << prefs->anotherOption2() << endl;
+ kdWarning() << "MyPaths = " << prefs->myPaths() << endl;
+ kdWarning() << "MyPaths2 = " << prefs->myPaths2() << endl;
+}
diff --git a/tdecore/kconfig_compiler/example/example.kcfg b/tdecore/tdeconfig_compiler/example/example.kcfg
index 076bfb644..076bfb644 100644
--- a/tdecore/kconfig_compiler/example/example.kcfg
+++ b/tdecore/tdeconfig_compiler/example/example.kcfg
diff --git a/tdecore/tdeconfig_compiler/example/exampleprefs_base.kcfgc b/tdecore/tdeconfig_compiler/example/exampleprefs_base.kcfgc
new file mode 100644
index 000000000..9b72fdb07
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/example/exampleprefs_base.kcfgc
@@ -0,0 +1,18 @@
+# Code generation options for tdeconfig_compiler
+ClassName=ExamplePrefsBase
+#
+# Singleton=false
+#
+# Inherits=TDEConfigSkeleton
+#
+# IncludeFiles=libtdepim/kpimprefs.h
+#
+# MemberVariables=public
+#
+### The following line includes the file exampleprefs_base_addon.h
+### It can be used to add extra functions and variables to the
+### class.
+# CustomAdditions=true
+#
+### Provide setFooBar(int) style functions
+Mutators=true
diff --git a/tdecore/kconfig_compiler/example/general_base.ui b/tdecore/tdeconfig_compiler/example/general_base.ui
index 9b41370c7..9b41370c7 100644
--- a/tdecore/kconfig_compiler/example/general_base.ui
+++ b/tdecore/tdeconfig_compiler/example/general_base.ui
diff --git a/tdecore/kconfig_compiler/example/myoptions_base.ui b/tdecore/tdeconfig_compiler/example/myoptions_base.ui
index 3c0c2e6cb..3c0c2e6cb 100644
--- a/tdecore/kconfig_compiler/example/myoptions_base.ui
+++ b/tdecore/tdeconfig_compiler/example/myoptions_base.ui
diff --git a/tdecore/kconfig_compiler/kcfg.xsd b/tdecore/tdeconfig_compiler/kcfg.xsd
index 9eb18a068..9eb18a068 100644
--- a/tdecore/kconfig_compiler/kcfg.xsd
+++ b/tdecore/tdeconfig_compiler/kcfg.xsd
diff --git a/tdecore/tdeconfig_compiler/tdeconfig_compiler.cpp b/tdecore/tdeconfig_compiler/tdeconfig_compiler.cpp
new file mode 100644
index 000000000..c7f2fd7bd
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tdeconfig_compiler.cpp
@@ -0,0 +1,1700 @@
+// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
+/*
+ This file is part of KDE.
+
+ Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
+ Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
+ Copyright (c) 2003 Zack Rusin <zack@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqfile.h>
+#include <tqtextstream.h>
+#include <tqdom.h>
+#include <tqregexp.h>
+
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+#include <kglobal.h>
+#include <tdeconfig.h>
+#include <ksimpleconfig.h>
+#include <kstandarddirs.h>
+
+#include <iostream>
+
+static const KCmdLineOptions options[] =
+{
+ { "d", 0, 0 },
+ { "directory <dir>", I18N_NOOP("Directory to generate files in"), "." },
+ { "+file.kcfg", I18N_NOOP("Input kcfg XML file"), 0 },
+ { "+file.kcfgc", I18N_NOOP("Code generation options file"), 0 },
+ KCmdLineLastOption
+};
+
+
+bool globalEnums;
+bool itemAccessors;
+bool dpointer;
+TQStringList allNames;
+TQRegExp *validNameRegexp;
+TQString This;
+TQString Const;
+
+class CfgEntry
+{
+ public:
+ struct Choice
+ {
+ TQString name;
+ TQString label;
+ TQString whatsThis;
+ };
+
+ CfgEntry( const TQString &group, const TQString &type, const TQString &key,
+ const TQString &name, const TQString &label,
+ const TQString &whatsThis, const TQString &code,
+ const TQString &defaultValue, const TQValueList<Choice> &choices,
+ bool hidden )
+ : mGroup( group ), mType( type ), mKey( key ), mName( name ),
+ mLabel( label ), mWhatsThis( whatsThis ), mCode( code ),
+ mDefaultValue( defaultValue ),
+ mChoices( choices ), mHidden( hidden )
+ {
+ }
+
+ void setGroup( const TQString &group ) { mGroup = group; }
+ TQString group() const { return mGroup; }
+
+ void setType( const TQString &type ) { mType = type; }
+ TQString type() const { return mType; }
+
+ void setKey( const TQString &key ) { mKey = key; }
+ TQString key() const { return mKey; }
+
+ void setName( const TQString &name ) { mName = name; }
+ TQString name() const { return mName; }
+
+ void setLabel( const TQString &label ) { mLabel = label; }
+ TQString label() const { return mLabel; }
+
+ void setWhatsThis( const TQString &whatsThis ) { mWhatsThis = whatsThis; }
+ TQString whatsThis() const { return mWhatsThis; }
+
+ void setDefaultValue( const TQString &d ) { mDefaultValue = d; }
+ TQString defaultValue() const { return mDefaultValue; }
+
+ void setCode( const TQString &d ) { mCode = d; }
+ TQString code() const { return mCode; }
+
+ void setMinValue( const TQString &d ) { mMin = d; }
+ TQString minValue() const { return mMin; }
+
+ void setMaxValue( const TQString &d ) { mMax = d; }
+ TQString maxValue() const { return mMax; }
+
+ void setParam( const TQString &d ) { mParam = d; }
+ TQString param() const { return mParam; }
+
+ void setParamName( const TQString &d ) { mParamName = d; }
+ TQString paramName() const { return mParamName; }
+
+ void setParamType( const TQString &d ) { mParamType = d; }
+ TQString paramType() const { return mParamType; }
+
+ void setChoices( const TQValueList<Choice> &d ) { mChoices = d; }
+ TQValueList<Choice> choices() const { return mChoices; }
+
+ void setParamValues( const TQStringList &d ) { mParamValues = d; }
+ TQStringList paramValues() const { return mParamValues; }
+
+ void setParamDefaultValues( const TQStringList &d ) { mParamDefaultValues = d; }
+ TQString paramDefaultValue(int i) const { return mParamDefaultValues[i]; }
+
+ void setParamMax( int d ) { mParamMax = d; }
+ int paramMax() const { return mParamMax; }
+
+ bool hidden() const { return mHidden; }
+
+ void dump() const
+ {
+ kdDebug() << "<entry>" << endl;
+ kdDebug() << " group: " << mGroup << endl;
+ kdDebug() << " type: " << mType << endl;
+ kdDebug() << " key: " << mKey << endl;
+ kdDebug() << " name: " << mName << endl;
+ kdDebug() << " label: " << mLabel << endl;
+// whatsthis
+ kdDebug() << " code: " << mCode << endl;
+// kdDebug() << " values: " << mValues.join(":") << endl;
+
+ if (!param().isEmpty())
+ {
+ kdDebug() << " param name: "<< mParamName << endl;
+ kdDebug() << " param type: "<< mParamType << endl;
+ kdDebug() << " paramvalues: " << mParamValues.join(":") << endl;
+ }
+ kdDebug() << " default: " << mDefaultValue << endl;
+ kdDebug() << " hidden: " << mHidden << endl;
+ kdDebug() << " min: " << mMin << endl;
+ kdDebug() << " max: " << mMax << endl;
+ kdDebug() << "</entry>" << endl;
+ }
+
+ private:
+ TQString mGroup;
+ TQString mType;
+ TQString mKey;
+ TQString mName;
+ TQString mLabel;
+ TQString mWhatsThis;
+ TQString mCode;
+ TQString mDefaultValue;
+ TQString mParam;
+ TQString mParamName;
+ TQString mParamType;
+ TQValueList<Choice> mChoices;
+ TQStringList mParamValues;
+ TQStringList mParamDefaultValues;
+ int mParamMax;
+ bool mHidden;
+ TQString mMin;
+ TQString mMax;
+};
+
+class Param {
+public:
+ TQString name;
+ TQString type;
+};
+
+// returns the name of an member variable
+// use itemPath to know the full path
+// like using d-> in case of dpointer
+static TQString varName(const TQString &n)
+{
+ TQString result;
+ if ( !dpointer ) {
+ result = "m"+n;
+ result[1] = result[1].upper();
+ }
+ else {
+ result = n;
+ result[0] = result[0].lower();
+ }
+ return result;
+}
+
+static TQString varPath(const TQString &n)
+{
+ TQString result;
+ if ( dpointer ) {
+ result = "d->"+varName(n);
+ }
+ else {
+ result = varName(n);
+ }
+ return result;
+}
+
+static TQString enumName(const TQString &n)
+{
+ TQString result = "Enum"+n;
+ result[4] = result[4].upper();
+ return result;
+}
+
+static TQString setFunction(const TQString &n, const TQString &className = TQString())
+{
+ TQString result = "set"+n;
+ result[3] = result[3].upper();
+
+ if ( !className.isEmpty() )
+ result = className + "::" + result;
+ return result;
+}
+
+
+static TQString getFunction(const TQString &n, const TQString &className = TQString())
+{
+ TQString result = n;
+ result[0] = result[0].lower();
+
+ if ( !className.isEmpty() )
+ result = className + "::" + result;
+ return result;
+}
+
+
+static void addQuotes( TQString &s )
+{
+ if ( s.left( 1 ) != "\"" ) s.prepend( "\"" );
+ if ( s.right( 1 ) != "\"" ) s.append( "\"" );
+}
+
+static TQString quoteString( const TQString &s )
+{
+ TQString r = s;
+ r.replace( "\\", "\\\\" );
+ r.replace( "\"", "\\\"" );
+ r.replace( "\r", "" );
+ r.replace( "\n", "\\n\"\n\"" );
+ return "\"" + r + "\"";
+}
+
+static TQString literalString( const TQString &s )
+{
+ bool isAscii = true;
+ for(int i = s.length(); i--;)
+ if (s[i].unicode() > 127) isAscii = false;
+
+ if (isAscii)
+ return "TQString::fromLatin1( " + quoteString(s) + " )";
+ else
+ return "TQString::fromUtf8( " + quoteString(s) + " )";
+}
+
+static TQString dumpNode(const TQDomNode &node)
+{
+ TQString msg;
+ TQTextStream s(&msg, IO_WriteOnly );
+ node.save(s, 0);
+
+ msg = msg.simplifyWhiteSpace();
+ if (msg.length() > 40)
+ return msg.left(37)+"...";
+ return msg;
+}
+
+static TQString filenameOnly(TQString path)
+{
+ int i = path.findRev('/');
+ if (i >= 0)
+ return path.mid(i+1);
+ return path;
+}
+
+static void preProcessDefault( TQString &defaultValue, const TQString &name,
+ const TQString &type,
+ const TQValueList<CfgEntry::Choice> &choices,
+ TQString &code )
+{
+ if ( type == "String" && !defaultValue.isEmpty() ) {
+ defaultValue = literalString(defaultValue);
+
+ } else if ( type == "Path" && !defaultValue.isEmpty() ) {
+ defaultValue = literalString( defaultValue );
+
+ } else if ( (type == "StringList" || type == "PathList") && !defaultValue.isEmpty() ) {
+ TQTextStream cpp( &code, IO_WriteOnly | IO_Append );
+ if (!code.isEmpty())
+ cpp << endl;
+
+ cpp << " TQStringList default" << name << ";" << endl;
+ TQStringList defaults = TQStringList::split( ",", defaultValue );
+ TQStringList::ConstIterator it;
+ for( it = defaults.begin(); it != defaults.end(); ++it ) {
+ cpp << " default" << name << ".append( TQString::fromUtf8( \"" << *it << "\" ) );"
+ << endl;
+ }
+ defaultValue = "default" + name;
+
+ } else if ( type == "Color" && !defaultValue.isEmpty() ) {
+ TQRegExp colorRe("\\d+,\\s*\\d+,\\s*\\d+");
+ if (colorRe.exactMatch(defaultValue))
+ {
+ defaultValue = "TQColor( " + defaultValue + " )";
+ }
+ else
+ {
+ defaultValue = "TQColor( \"" + defaultValue + "\" )";
+ }
+
+ } else if ( type == "Enum" ) {
+ if ( !globalEnums ) {
+ TQValueList<CfgEntry::Choice>::ConstIterator it;
+ for( it = choices.begin(); it != choices.end(); ++it ) {
+ if ( (*it).name == defaultValue ) {
+ defaultValue.prepend( enumName(name) + "::");
+ break;
+ }
+ }
+ }
+
+ } else if ( type == "IntList" ) {
+ TQTextStream cpp( &code, IO_WriteOnly | IO_Append );
+ if (!code.isEmpty())
+ cpp << endl;
+
+ cpp << " TQValueList<int> default" << name << ";" << endl;
+ TQStringList defaults = TQStringList::split( ",", defaultValue );
+ TQStringList::ConstIterator it;
+ for( it = defaults.begin(); it != defaults.end(); ++it ) {
+ cpp << " default" << name << ".append( " << *it << " );"
+ << endl;
+ }
+ defaultValue = "default" + name;
+ }
+}
+
+
+CfgEntry *parseEntry( const TQString &group, const TQDomElement &element )
+{
+ bool defaultCode = false;
+ TQString type = element.attribute( "type" );
+ TQString name = element.attribute( "name" );
+ TQString key = element.attribute( "key" );
+ TQString hidden = element.attribute( "hidden" );
+ TQString label;
+ TQString whatsThis;
+ TQString defaultValue;
+ TQString code;
+ TQString param;
+ TQString paramName;
+ TQString paramType;
+ TQValueList<CfgEntry::Choice> choices;
+ TQStringList paramValues;
+ TQStringList paramDefaultValues;
+ TQString minValue;
+ TQString maxValue;
+ int paramMax = 0;
+
+ TQDomNode n;
+ for ( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
+ TQDomElement e = n.toElement();
+ TQString tag = e.tagName();
+ if ( tag == "label" ) label = e.text();
+ else if ( tag == "whatsthis" ) whatsThis = e.text();
+ else if ( tag == "min" ) minValue = e.text();
+ else if ( tag == "max" ) maxValue = e.text();
+ else if ( tag == "code" ) code = e.text();
+ else if ( tag == "parameter" )
+ {
+ param = e.attribute( "name" );
+ paramType = e.attribute( "type" );
+ if ( param.isEmpty() ) {
+ kdError() << "Parameter must have a name: " << dumpNode(e) << endl;
+ return 0;
+ }
+ if ( paramType.isEmpty() ) {
+ kdError() << "Parameter must have a type: " << dumpNode(e) << endl;
+ return 0;
+ }
+ if ((paramType == "Int") || (paramType == "UInt"))
+ {
+ bool ok;
+ paramMax = e.attribute("max").toInt(&ok);
+ if (!ok)
+ {
+ kdError() << "Integer parameter must have a maximum (e.g. max=\"0\"): " << dumpNode(e) << endl;
+ return 0;
+ }
+ }
+ else if (paramType == "Enum")
+ {
+ TQDomNode n2;
+ for ( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
+ TQDomElement e2 = n2.toElement();
+ if (e2.tagName() == "values")
+ {
+ TQDomNode n3;
+ for ( n3 = e2.firstChild(); !n3.isNull(); n3 = n3.nextSibling() ) {
+ TQDomElement e3 = n3.toElement();
+ if (e3.tagName() == "value")
+ {
+ paramValues.append( e3.text() );
+ }
+ }
+ break;
+ }
+ }
+ if (paramValues.isEmpty())
+ {
+ kdError() << "No values specified for parameter '" << param << "'." << endl;
+ return 0;
+ }
+ paramMax = paramValues.count()-1;
+ }
+ else
+ {
+ kdError() << "Parameter '" << param << "' has type " << paramType << " but must be of type int, uint or Enum." << endl;
+ return 0;
+ }
+ }
+ else if ( tag == "default" )
+ {
+ if (e.attribute("param").isEmpty())
+ {
+ defaultValue = e.text();
+ if (e.attribute( "code" ) == "true")
+ defaultCode = true;
+ }
+ }
+ else if ( tag == "choices" ) {
+ TQDomNode n2;
+ for( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
+ TQDomElement e2 = n2.toElement();
+ if ( e2.tagName() == "choice" ) {
+ TQDomNode n3;
+ CfgEntry::Choice choice;
+ choice.name = e2.attribute( "name" );
+ if ( choice.name.isEmpty() ) {
+ kdError() << "Tag <choice> requires attribute 'name'." << endl;
+ }
+ for( n3 = e2.firstChild(); !n3.isNull(); n3 = n3.nextSibling() ) {
+ TQDomElement e3 = n3.toElement();
+ if ( e3.tagName() == "label" ) choice.label = e3.text();
+ if ( e3.tagName() == "whatsthis" ) choice.whatsThis = e3.text();
+ }
+ choices.append( choice );
+ }
+ }
+ }
+ }
+
+ bool nameIsEmpty = name.isEmpty();
+ if ( nameIsEmpty && key.isEmpty() ) {
+ kdError() << "Entry must have a name or a key: " << dumpNode(element) << endl;
+ return 0;
+ }
+
+ if ( key.isEmpty() ) {
+ key = name;
+ }
+
+ if ( nameIsEmpty ) {
+ name = key;
+ name.replace( " ", TQString() );
+ } else if ( name.contains( ' ' ) ) {
+ kdWarning()<<"Entry '"<<name<<"' contains spaces! <name> elements can't contain speces!"<<endl;
+ name.remove( ' ' );
+ }
+
+ if (name.contains("$("))
+ {
+ if (param.isEmpty())
+ {
+ kdError() << "Name may not be parameterized: " << name << endl;
+ return 0;
+ }
+ }
+ else
+ {
+ if (!param.isEmpty())
+ {
+ kdError() << "Name must contain '$(" << param << ")': " << name << endl;
+ return 0;
+ }
+ }
+
+ if ( label.isEmpty() ) {
+ label = key;
+ }
+
+ if ( type.isEmpty() ) type = "String"; // XXX : implicit type might be bad
+
+ if (!param.isEmpty())
+ {
+ // Adjust name
+ paramName = name;
+ name.replace("$("+param+")", TQString());
+ // Lookup defaults for indexed entries
+ for(int i = 0; i <= paramMax; i++)
+ {
+ paramDefaultValues.append(TQString());
+ }
+
+ TQDomNode n;
+ for ( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
+ TQDomElement e = n.toElement();
+ TQString tag = e.tagName();
+ if ( tag == "default" )
+ {
+ TQString index = e.attribute("param");
+ if (index.isEmpty())
+ continue;
+
+ bool ok;
+ int i = index.toInt(&ok);
+ if (!ok)
+ {
+ i = paramValues.findIndex(index);
+ if (i == -1)
+ {
+ kdError() << "Index '" << index << "' for default value is unknown." << endl;
+ return 0;
+ }
+ }
+
+ if ((i < 0) || (i > paramMax))
+ {
+ kdError() << "Index '" << i << "' for default value is out of range [0, "<< paramMax<<"]." << endl;
+ return 0;
+ }
+
+ TQString tmpDefaultValue = e.text();
+
+ if (e.attribute( "code" ) != "true")
+ preProcessDefault(tmpDefaultValue, name, type, choices, code);
+
+ paramDefaultValues[i] = tmpDefaultValue;
+ }
+ }
+ }
+
+ if (!validNameRegexp->exactMatch(name))
+ {
+ if (nameIsEmpty)
+ kdError() << "The key '" << key << "' can not be used as name for the entry because "
+ "it is not a valid name. You need to specify a valid name for this entry." << endl;
+ else
+ kdError() << "The name '" << name << "' is not a valid name for an entry." << endl;
+ return 0;
+ }
+
+ if (allNames.contains(name))
+ {
+ if (nameIsEmpty)
+ kdError() << "The key '" << key << "' can not be used as name for the entry because "
+ "it does not result in a unique name. You need to specify a unique name for this entry." << endl;
+ else
+ kdError() << "The name '" << name << "' is not unique." << endl;
+ return 0;
+ }
+ allNames.append(name);
+
+ if (!defaultCode)
+ {
+ preProcessDefault(defaultValue, name, type, choices, code);
+ }
+
+ CfgEntry *result = new CfgEntry( group, type, key, name, label, whatsThis,
+ code, defaultValue, choices,
+ hidden == "true" );
+ if (!param.isEmpty())
+ {
+ result->setParam(param);
+ result->setParamName(paramName);
+ result->setParamType(paramType);
+ result->setParamValues(paramValues);
+ result->setParamDefaultValues(paramDefaultValues);
+ result->setParamMax(paramMax);
+ }
+ result->setMinValue(minValue);
+ result->setMaxValue(maxValue);
+
+ return result;
+}
+
+/**
+ Return parameter declaration for given type.
+*/
+TQString param( const TQString &type )
+{
+ if ( type == "String" ) return "const TQString &";
+ else if ( type == "StringList" ) return "const TQStringList &";
+ else if ( type == "Font" ) return "const TQFont &";
+ else if ( type == "Rect" ) return "const TQRect &";
+ else if ( type == "Size" ) return "const TQSize &";
+ else if ( type == "Color" ) return "const TQColor &";
+ else if ( type == "Point" ) return "const TQPoint &";
+ else if ( type == "Int" ) return "int";
+ else if ( type == "UInt" ) return "uint";
+ else if ( type == "Bool" ) return "bool";
+ else if ( type == "Double" ) return "double";
+ else if ( type == "DateTime" ) return "const TQDateTime &";
+ else if ( type == "Int64" ) return "TQ_INT64";
+ else if ( type == "UInt64" ) return "TQ_UINT64";
+ else if ( type == "IntList" ) return "const TQValueList<int> &";
+ else if ( type == "Enum" ) return "int";
+ else if ( type == "Path" ) return "const TQString &";
+ else if ( type == "PathList" ) return "const TQStringList &";
+ else if ( type == "Password" ) return "const TQString &";
+ else {
+ kdError() <<"tdeconfig_compiler does not support type \""<< type <<"\""<<endl;
+ return TQSTRING_OBJECT_NAME_STRING; //For now, but an assert would be better
+ }
+}
+
+/**
+ Actual C++ storage type for given type.
+*/
+TQString cppType( const TQString &type )
+{
+ if ( type == "String" ) return TQSTRING_OBJECT_NAME_STRING;
+ else if ( type == "StringList" ) return TQSTRINGLIST_OBJECT_NAME_STRING;
+ else if ( type == "Font" ) return "TQFont";
+ else if ( type == "Rect" ) return "TQRect";
+ else if ( type == "Size" ) return "TQSize";
+ else if ( type == "Color" ) return "TQColor";
+ else if ( type == "Point" ) return TQPOINT_OBJECT_NAME_STRING;
+ else if ( type == "Int" ) return "int";
+ else if ( type == "UInt" ) return "uint";
+ else if ( type == "Bool" ) return "bool";
+ else if ( type == "Double" ) return "double";
+ else if ( type == "DateTime" ) return "TQDateTime";
+ else if ( type == "Int64" ) return "TQ_INT64";
+ else if ( type == "UInt64" ) return "TQ_UINT64";
+ else if ( type == "IntList" ) return "TQValueList<int>";
+ else if ( type == "Enum" ) return "int";
+ else if ( type == "Path" ) return TQSTRING_OBJECT_NAME_STRING;
+ else if ( type == "PathList" ) return TQSTRINGLIST_OBJECT_NAME_STRING;
+ else if ( type == "Password" ) return TQSTRING_OBJECT_NAME_STRING;
+ else {
+ kdError()<<"tdeconfig_compiler does not support type \""<< type <<"\""<<endl;
+ return TQSTRING_OBJECT_NAME_STRING; //For now, but an assert would be better
+ }
+}
+
+TQString defaultValue( const TQString &type )
+{
+ if ( type == "String" ) return "\"\""; // Use empty string, not null string!
+ else if ( type == "StringList" ) return "TQStringList()";
+ else if ( type == "Font" ) return "TDEGlobalSettings::generalFont()";
+ else if ( type == "Rect" ) return "TQRect()";
+ else if ( type == "Size" ) return "TQSize()";
+ else if ( type == "Color" ) return "TQColor(128, 128, 128)";
+ else if ( type == "Point" ) return "TQPoint()";
+ else if ( type == "Int" ) return "0";
+ else if ( type == "UInt" ) return "0";
+ else if ( type == "Bool" ) return "false";
+ else if ( type == "Double" ) return "0.0";
+ else if ( type == "DateTime" ) return "TQDateTime()";
+ else if ( type == "Int64" ) return "0";
+ else if ( type == "UInt64" ) return "0";
+ else if ( type == "IntList" ) return "TQValueList<int>()";
+ else if ( type == "Enum" ) return "0";
+ else if ( type == "Path" ) return "\"\""; // Use empty string, not null string!
+ else if ( type == "PathList" ) return "TQStringList()";
+ else if ( type == "Password" ) return "\"\""; // Use empty string, not null string!
+ else {
+ kdWarning()<<"Error, tdeconfig_compiler doesn't support the \""<< type <<"\" type!"<<endl;
+ return TQSTRING_OBJECT_NAME_STRING; //For now, but an assert would be better
+ }
+}
+
+TQString itemType( const TQString &type )
+{
+ TQString t;
+
+ t = type;
+ t.replace( 0, 1, t.left( 1 ).upper() );
+
+ return t;
+}
+
+static TQString itemDeclaration(const CfgEntry *e)
+{
+ if (itemAccessors)
+ return TQString();
+
+ TQString fCap = e->name();
+ fCap[0] = fCap[0].upper();
+ return " TDEConfigSkeleton::Item"+itemType( e->type() ) +
+ " *item" + fCap +
+ ( (!e->param().isEmpty())?(TQString("[%1]").arg(e->paramMax()+1)) : TQString()) +
+ ";\n";
+}
+
+// returns the name of an item variable
+// use itemPath to know the full path
+// like using d-> in case of dpointer
+static TQString itemVar(const CfgEntry *e)
+{
+ TQString result;
+ if (itemAccessors)
+ {
+ if ( !dpointer )
+ {
+ result = "m" + e->name() + "Item";
+ result[1] = result[1].upper();
+ }
+ else
+ {
+ result = e->name() + "Item";
+ result[0] = result[0].lower();
+ }
+ }
+ else
+ {
+ result = "item" + e->name();
+ result[4] = result[4].upper();
+ }
+ return result;
+}
+
+static TQString itemPath(const CfgEntry *e)
+{
+ TQString result;
+ if ( dpointer ) {
+ result = "d->"+itemVar(e);
+ }
+ else {
+ result = itemVar(e);
+ }
+ return result;
+}
+
+TQString newItem( const TQString &type, const TQString &name, const TQString &key,
+ const TQString &defaultValue, const TQString &param = TQString())
+{
+ TQString t = "new TDEConfigSkeleton::Item" + itemType( type ) +
+ "( currentGroup(), " + key + ", " + varPath( name ) + param;
+ if ( type == "Enum" ) t += ", values" + name;
+ if ( !defaultValue.isEmpty() ) {
+ t += ", ";
+ if ( type == "String" ) t += defaultValue;
+ else t+= defaultValue;
+ }
+ t += " );";
+
+ return t;
+}
+
+TQString paramString(const TQString &s, const CfgEntry *e, int i)
+{
+ TQString result = s;
+ TQString needle = "$("+e->param()+")";
+ if (result.contains(needle))
+ {
+ TQString tmp;
+ if (e->paramType() == "Enum")
+ {
+ tmp = e->paramValues()[i];
+ }
+ else
+ {
+ tmp = TQString::number(i);
+ }
+
+ result.replace(needle, tmp);
+ }
+ return result;
+}
+
+TQString paramString(const TQString &group, const TQValueList<Param> &parameters)
+{
+ TQString paramString = group;
+ TQString arguments;
+ int i = 1;
+ for (TQValueList<Param>::ConstIterator it = parameters.begin();
+ it != parameters.end(); ++it)
+ {
+ if (paramString.contains("$("+(*it).name+")"))
+ {
+ TQString tmp;
+ tmp.sprintf("%%%d", i++);
+ paramString.replace("$("+(*it).name+")", tmp);
+ arguments += ".arg( mParam"+(*it).name+" )";
+ }
+ }
+ if (arguments.isEmpty())
+ return "TQString::fromLatin1( \""+group+"\" )";
+
+ return "TQString::fromLatin1( \""+paramString+"\" )"+arguments;
+}
+
+/* int i is the value of the parameter */
+TQString userTextsFunctions( CfgEntry *e, TQString itemVarStr=TQString(), TQString i=TQString() )
+{
+ TQString txt;
+ if (itemVarStr.isNull()) itemVarStr=itemPath(e);
+ if ( !e->label().isEmpty() ) {
+ txt += " " + itemVarStr + "->setLabel( i18n(";
+ if ( !e->param().isEmpty() )
+ txt += quoteString(e->label().replace("$("+e->param()+")", i));
+ else
+ txt+= quoteString(e->label());
+ txt+= ") );\n";
+ }
+ if ( !e->whatsThis().isEmpty() ) {
+ txt += " " + itemVarStr + "->setWhatsThis( i18n(";
+ if ( !e->param().isEmpty() )
+ txt += quoteString(e->whatsThis().replace("$("+e->param()+")", i));
+ else
+ txt+= quoteString(e->whatsThis());
+ txt+=") );\n";
+ }
+ return txt;
+}
+
+// returns the member accesor implementation
+// which should go in the h file if inline
+// or the cpp file if not inline
+TQString memberAccessorBody( CfgEntry *e )
+{
+ TQString result;
+ TQTextStream out(&result, IO_WriteOnly);
+ TQString n = e->name();
+ TQString t = e->type();
+
+ out << "return " << This << varPath(n);
+ if (!e->param().isEmpty()) out << "[i]";
+ out << ";" << endl;
+
+ return result;
+}
+
+// returns the member mutator implementation
+// which should go in the h file if inline
+// or the cpp file if not inline
+TQString memberMutatorBody( CfgEntry *e )
+{
+ TQString result;
+ TQTextStream out(&result, IO_WriteOnly);
+ TQString n = e->name();
+ TQString t = e->type();
+
+ if (!e->minValue().isEmpty())
+ {
+ out << "if (v < " << e->minValue() << ")" << endl;
+ out << "{" << endl;
+ out << " kdDebug() << \"" << setFunction(n);
+ out << ": value \" << v << \" is less than the minimum value of ";
+ out << e->minValue()<< "\" << endl;" << endl;
+ out << " v = " << e->minValue() << ";" << endl;
+ out << "}" << endl;
+ }
+
+ if (!e->maxValue().isEmpty())
+ {
+ out << endl << "if (v > " << e->maxValue() << ")" << endl;
+ out << "{" << endl;
+ out << " kdDebug() << \"" << setFunction(n);
+ out << ": value \" << v << \" is greater than the maximum value of ";
+ out << e->maxValue()<< "\" << endl;" << endl;
+ out << " v = " << e->maxValue() << ";" << endl;
+ out << "}" << endl << endl;
+ }
+
+ out << "if (!" << This << "isImmutable( TQString::fromLatin1( \"";
+ if (!e->param().isEmpty())
+ {
+ out << e->paramName().replace("$("+e->param()+")", "%1") << "\" ).arg( ";
+ if ( e->paramType() == "Enum" ) {
+ out << "TQString::fromLatin1( ";
+
+ if (globalEnums)
+ out << enumName(e->param()) << "ToString[i]";
+ else
+ out << enumName(e->param()) << "::enumToString[i]";
+
+ out << " )";
+ }
+ else
+ {
+ out << "i";
+ }
+ out << " )";
+ }
+ else
+ {
+ out << n << "\" )";
+ }
+ out << " ))" << endl;
+ out << " " << This << varPath(n);
+ if (!e->param().isEmpty())
+ out << "[i]";
+ out << " = v;" << endl;
+
+ return result;
+}
+
+// returns the item accesor implementation
+// which should go in the h file if inline
+// or the cpp file if not inline
+TQString itemAccessorBody( CfgEntry *e )
+{
+ TQString result;
+ TQTextStream out(&result, IO_WriteOnly);
+
+ out << "return " << itemPath(e);
+ if (!e->param().isEmpty()) out << "[i]";
+ out << ";" << endl;
+
+ return result;
+}
+
+//indents text adding X spaces per line
+TQString indent(TQString text, int spaces)
+{
+ TQString result;
+ TQTextStream out(&result, IO_WriteOnly);
+ TQTextStream in(&text, IO_ReadOnly);
+ TQString currLine;
+ while ( !in.atEnd() )
+ {
+ currLine = in.readLine();
+ if (!currLine.isEmpty())
+ for (int i=0; i < spaces; i++)
+ out << " ";
+ out << currLine << endl;
+ }
+ return result;
+}
+
+
+int main( int argc, char **argv )
+{
+ TDEAboutData aboutData( "tdeconfig_compiler", I18N_NOOP("TDE .kcfg compiler"), "0.3",
+ I18N_NOOP("TDEConfig Compiler") , TDEAboutData::License_LGPL );
+ aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );
+ aboutData.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
+ aboutData.addAuthor( "Zack Rusin", 0, "zack@kde.org" );
+ aboutData.addCredit( "Reinhold Kainhofer", "Fix for parametrized entries",
+ "reinhold@kainhofer.com", "http://reinhold.kainhofer.com" );
+ aboutData.addCredit( "Duncan Mac-Vicar P.", "dpointer support",
+ "duncan@kde.org", "http://www.mac-vicar.com/~duncan" );
+
+ TDECmdLineArgs::init( argc, argv, &aboutData );
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDEInstance app( &aboutData );
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ if ( args->count() < 2 ) {
+ kdError() << "Too few arguments." << endl;
+ return 1;
+ }
+ if ( args->count() > 2 ) {
+ kdError() << "Too many arguments." << endl;
+ return 1;
+ }
+
+ validNameRegexp = new TQRegExp("[a-zA-Z_][a-zA-Z0-9_]*");
+
+ TQString baseDir = TQFile::decodeName(args->getOption("directory"));
+ if (!baseDir.endsWith("/"))
+ baseDir.append("/");
+
+ TQString inputFilename = args->url( 0 ).path();
+ TQString codegenFilename = args->url( 1 ).path();
+
+ if (!codegenFilename.endsWith(".kcfgc"))
+ {
+ kdError() << "Codegen options file must have extension .kcfgc" << endl;
+ return 1;
+ }
+ TQString baseName = args->url( 1 ).fileName();
+ baseName = baseName.left(baseName.length() - 6);
+
+ KSimpleConfig codegenConfig( codegenFilename, true );
+
+ TQString nameSpace = codegenConfig.readEntry("NameSpace");
+ TQString className = codegenConfig.readEntry("ClassName");
+ TQString inherits = codegenConfig.readEntry("Inherits");
+ TQString visibility = codegenConfig.readEntry("Visibility");
+ if (!visibility.isEmpty()) visibility+=" ";
+ bool singleton = codegenConfig.readBoolEntry("Singleton", false);
+ bool staticAccessors = singleton;
+ //bool useDPointer = codegenConfig.readBoolEntry("DPointer", false);
+ bool customAddons = codegenConfig.readBoolEntry("CustomAdditions");
+ TQString memberVariables = codegenConfig.readEntry("MemberVariables");
+ TQStringList headerIncludes = codegenConfig.readListEntry("IncludeFiles");
+ TQStringList mutators = codegenConfig.readListEntry("Mutators");
+ bool allMutators = false;
+ if ((mutators.count() == 1) && (mutators[0].lower() == "true"))
+ allMutators = true;
+ itemAccessors = codegenConfig.readBoolEntry( "ItemAccessors", false );
+ bool setUserTexts = codegenConfig.readBoolEntry( "SetUserTexts", false );
+
+ globalEnums = codegenConfig.readBoolEntry( "GlobalEnums", false );
+
+ dpointer = (memberVariables == "dpointer");
+
+ TQFile input( inputFilename );
+
+ TQDomDocument doc;
+ TQString errorMsg;
+ int errorRow;
+ int errorCol;
+ if ( !doc.setContent( &input, &errorMsg, &errorRow, &errorCol ) ) {
+ kdError() << "Unable to load document." << endl;
+ kdError() << "Parse error in " << args->url( 0 ).fileName() << ", line " << errorRow << ", col " << errorCol << ": " << errorMsg << endl;
+ return 1;
+ }
+
+ TQDomElement cfgElement = doc.documentElement();
+
+ if ( cfgElement.isNull() ) {
+ kdError() << "No document in kcfg file" << endl;
+ return 1;
+ }
+
+ TQString cfgFileName;
+ bool cfgFileNameArg = false;
+ TQValueList<Param> parameters;
+ TQStringList includes;
+
+ TQPtrList<CfgEntry> entries;
+ entries.setAutoDelete( true );
+
+ TQDomNode n;
+ for ( n = cfgElement.firstChild(); !n.isNull(); n = n.nextSibling() ) {
+ TQDomElement e = n.toElement();
+
+ TQString tag = e.tagName();
+
+ if ( tag == "include" ) {
+ TQString includeFile = e.text();
+ if (!includeFile.isEmpty())
+ includes.append(includeFile);
+
+ } else if ( tag == "kcfgfile" ) {
+ cfgFileName = e.attribute( "name" );
+ cfgFileNameArg = e.attribute( "arg" ).lower() == "true";
+ TQDomNode n2;
+ for( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
+ TQDomElement e2 = n2.toElement();
+ if ( e2.tagName() == "parameter" ) {
+ Param p;
+ p.name = e2.attribute( "name" );
+ p.type = e2.attribute( "type" );
+ if (p.type.isEmpty())
+ p.type = "String";
+ parameters.append( p );
+ }
+ }
+
+ } else if ( tag == "group" ) {
+ TQString group = e.attribute( "name" );
+ if ( group.isEmpty() ) {
+ kdError() << "Group without name" << endl;
+ return 1;
+ }
+ TQDomNode n2;
+ for( n2 = e.firstChild(); !n2.isNull(); n2 = n2.nextSibling() ) {
+ TQDomElement e2 = n2.toElement();
+ if ( e2.tagName() != "entry" ) continue;
+ CfgEntry *entry = parseEntry( group, e2 );
+ if ( entry ) entries.append( entry );
+ else {
+ kdError() << "Can't parse entry." << endl;
+ return 1;
+ }
+ }
+ }
+ }
+
+ if ( inherits.isEmpty() ) inherits = "TDEConfigSkeleton";
+
+ if ( className.isEmpty() ) {
+ kdError() << "Class name missing" << endl;
+ return 1;
+ }
+
+ if ( singleton && !parameters.isEmpty() ) {
+ kdError() << "Singleton class can not have parameters" << endl;
+ return 1;
+ }
+
+ if ( !cfgFileName.isEmpty() && cfgFileNameArg)
+ {
+ kdError() << "Having both a fixed filename and a filename as argument is not possible." << endl;
+ return 1;
+ }
+
+ if ( entries.isEmpty() ) {
+ kdWarning() << "No entries." << endl;
+ }
+
+#if 0
+ CfgEntry *cfg;
+ for( cfg = entries.first(); cfg; cfg = entries.next() ) {
+ cfg->dump();
+ }
+#endif
+
+ TQString headerFileName = baseName + ".h";
+ TQString implementationFileName = baseName + ".cpp";
+ TQString cppPreamble; // code to be inserted at the beginnin of the cpp file, e.g. initialization of static values
+
+ TQFile header( baseDir + headerFileName );
+ if ( !header.open( IO_WriteOnly ) ) {
+ kdError() << "Can't open '" << headerFileName << "' for writing." << endl;
+ return 1;
+ }
+
+ TQTextStream h( &header );
+
+ h << "// This file is generated by tdeconfig_compiler from " << args->url(0).fileName() << "." << endl;
+ h << "// All changes you do to this file will be lost." << endl;
+
+ h << "#ifndef " << ( !nameSpace.isEmpty() ? nameSpace.upper() + "_" : "" )
+ << className.upper() << "_H" << endl;
+ h << "#define " << ( !nameSpace.isEmpty() ? nameSpace.upper() + "_" : "" )
+ << className.upper() << "_H" << endl << endl;
+
+ // Includes
+ TQStringList::ConstIterator it;
+ for( it = headerIncludes.begin(); it != headerIncludes.end(); ++it ) {
+ h << "#include <" << *it << ">" << endl;
+ }
+
+ if ( headerIncludes.count() > 0 ) h << endl;
+
+ if ( !singleton && cfgFileNameArg && parameters.isEmpty() )
+ h << "#include <kglobal.h>" << endl;
+
+ h << "#include <tdeconfigskeleton.h>" << endl;
+ h << "#include <kdebug.h>" << endl << endl;
+
+ // Includes
+ for( it = includes.begin(); it != includes.end(); ++it ) {
+ h << "#include <" << *it << ">" << endl;
+ }
+
+
+ if ( !nameSpace.isEmpty() )
+ h << "namespace " << nameSpace << " {" << endl << endl;
+
+ // Private class declaration
+ if ( dpointer )
+ h << "class " << className << "Private;" << endl << endl;
+
+ // Class declaration header
+ h << "class " << visibility << className << " : public " << inherits << endl;
+ h << "{" << endl;
+ h << " public:" << endl;
+
+ // enums
+ CfgEntry *e;
+ for( e = entries.first(); e; e = entries.next() ) {
+ TQValueList<CfgEntry::Choice> choices = e->choices();
+ if ( !choices.isEmpty() ) {
+ TQStringList values;
+ TQValueList<CfgEntry::Choice>::ConstIterator itChoice;
+ for( itChoice = choices.begin(); itChoice != choices.end(); ++itChoice ) {
+ values.append( (*itChoice).name );
+ }
+ if ( globalEnums ) {
+ h << " enum { " << values.join( ", " ) << " };" << endl;
+ } else {
+ h << " class " << enumName(e->name()) << endl;
+ h << " {" << endl;
+ h << " public:" << endl;
+ h << " enum type { " << values.join( ", " ) << ", COUNT };" << endl;
+ h << " };" << endl;
+ }
+ }
+ TQStringList values = e->paramValues();
+ if ( !values.isEmpty() ) {
+ if ( globalEnums ) {
+ h << " enum { " << values.join( ", " ) << " };" << endl;
+ h << " static const char* const " << enumName(e->param()) << "ToString[];" << endl;
+ cppPreamble += "const char* const " + className + "::" + enumName(e->param()) + "ToString[] = " +
+ "{ \"" + values.join( "\", \"" ) + "\" };\n";
+ } else {
+ h << " class " << enumName(e->param()) << endl;
+ h << " {" << endl;
+ h << " public:" << endl;
+ h << " enum type { " << values.join( ", " ) << ", COUNT };" << endl;
+ h << " static const char* const enumToString[];" << endl;
+ h << " };" << endl;
+ cppPreamble += "const char* const " + className + "::" + enumName(e->param()) + "::enumToString[] = " +
+ "{ \"" + values.join( "\", \"" ) + "\" };\n";
+ }
+ }
+ }
+
+ h << endl;
+
+ // Constructor or singleton accessor
+ if ( !singleton ) {
+ h << " " << className << "(";
+ if (cfgFileNameArg)
+ h << " KSharedConfig::Ptr config" << (parameters.isEmpty() ? " = TDEGlobal::sharedConfig()" : ", ");
+ for (TQValueList<Param>::ConstIterator it = parameters.begin();
+ it != parameters.end(); ++it)
+ {
+ if (it != parameters.begin())
+ h << ",";
+ h << " " << param((*it).type) << " " << (*it).name;
+ }
+ h << " );" << endl;
+ } else {
+ h << " static " << className << " *self();" << endl;
+ if (cfgFileNameArg)
+ h << " static void instance(const char * cfgfilename);" << endl;
+ }
+
+ // Destructor
+ h << " ~" << className << "();" << endl << endl;
+
+ // global variables
+ if (staticAccessors)
+ This = "self()->";
+ else
+ Const = " const";
+
+ for( e = entries.first(); e; e = entries.next() ) {
+ TQString n = e->name();
+ TQString t = e->type();
+
+ // Manipulator
+ if (allMutators || mutators.contains(n))
+ {
+ h << " /**" << endl;
+ h << " Set " << e->label() << endl;
+ h << " */" << endl;
+ if (staticAccessors)
+ h << " static" << endl;
+ h << " void " << setFunction(n) << "( ";
+ if (!e->param().isEmpty())
+ h << cppType(e->paramType()) << " i, ";
+ h << param( t ) << " v )";
+ // function body inline only if not using dpointer
+ // for BC mode
+ if ( !dpointer )
+ {
+ h << endl << " {" << endl;
+ h << indent(memberMutatorBody(e), 6 );
+ h << " }" << endl;
+ }
+ else
+ {
+ h << ";" << endl;
+ }
+ }
+ h << endl;
+ // Accessor
+ h << " /**" << endl;
+ h << " Get " << e->label() << endl;
+ h << " */" << endl;
+ if (staticAccessors)
+ h << " static" << endl;
+ h << " " << cppType(t) << " " << getFunction(n) << "(";
+ if (!e->param().isEmpty())
+ h << " " << cppType(e->paramType()) <<" i ";
+ h << ")" << Const;
+ // function body inline only if not using dpointer
+ // for BC mode
+ if ( !dpointer )
+ {
+ h << endl << " {" << endl;
+ h << indent(memberAccessorBody(e), 6 );
+ h << " }" << endl;
+ }
+ else
+ {
+ h << ";" << endl;
+ }
+
+ // Item accessor
+ if ( itemAccessors ) {
+ h << endl;
+ h << " /**" << endl;
+ h << " Get Item object corresponding to " << n << "()"
+ << endl;
+ h << " */" << endl;
+ h << " Item" << itemType( e->type() ) << " *"
+ << getFunction( n ) << "Item(";
+ if (!e->param().isEmpty()) {
+ h << " " << cppType(e->paramType()) << " i ";
+ }
+ h << ")";
+ if (! dpointer )
+ {
+ h << endl << " {" << endl;
+ h << indent( itemAccessorBody(e), 6);
+ h << " }" << endl;
+ }
+ else
+ {
+ h << ";" << endl;
+ }
+ }
+
+ h << endl;
+ }
+
+ // Static writeConfig method for singleton
+ if ( singleton ) {
+ h << " static" << endl;
+ h << " void writeConfig()" << endl;
+ h << " {" << endl;
+ h << " static_cast<TDEConfigSkeleton*>(self())->writeConfig();" << endl;
+ h << " }" << endl;
+ }
+
+ h << " protected:" << endl;
+
+ // Private constructor for singleton
+ if ( singleton ) {
+ h << " " << className << "(";
+ if ( cfgFileNameArg )
+ h << "const char *arg";
+ h << ");" << endl;
+ h << " static " << className << " *mSelf;" << endl << endl;
+ }
+
+ // Member variables
+ if ( !memberVariables.isEmpty() && memberVariables != "private" && memberVariables != "dpointer") {
+ h << " " << memberVariables << ":" << endl;
+ }
+
+ // Class Parameters
+ for (TQValueList<Param>::ConstIterator it = parameters.begin();
+ it != parameters.end(); ++it)
+ {
+ h << " " << cppType((*it).type) << " mParam" << (*it).name << ";" << endl;
+ }
+
+ if ( memberVariables != "dpointer" )
+ {
+ TQString group;
+ for( e = entries.first(); e; e = entries.next() ) {
+ if ( e->group() != group ) {
+ group = e->group();
+ h << endl;
+ h << " // " << group << endl;
+ }
+ h << " " << cppType(e->type()) << " " << varName(e->name());
+ if (!e->param().isEmpty())
+ {
+ h << TQString("[%1]").arg(e->paramMax()+1);
+ }
+ h << ";" << endl;
+ }
+
+ h << endl << " private:" << endl;
+ if ( itemAccessors ) {
+ for( e = entries.first(); e; e = entries.next() ) {
+ h << " Item" << itemType( e->type() ) << " *" << itemVar( e );
+ if (!e->param().isEmpty() ) h << TQString("[%1]").arg( e->paramMax()+1 );
+ h << ";" << endl;
+ }
+ }
+
+ }
+ else
+ {
+ // use a private class for both member variables and items
+ h << " private:" << endl;
+ h << " " + className + "Private *d;" << endl;
+ }
+
+ if (customAddons)
+ {
+ h << " // Include custom additions" << endl;
+ h << " #include \"" << filenameOnly(baseName) << "_addons.h\"" <<endl;
+ }
+
+ h << "};" << endl << endl;
+
+ if ( !nameSpace.isEmpty() ) h << "}" << endl << endl;
+
+ h << "#endif" << endl << endl;
+
+
+ header.close();
+
+ TQFile implementation( baseDir + implementationFileName );
+ if ( !implementation.open( IO_WriteOnly ) ) {
+ kdError() << "Can't open '" << implementationFileName << "' for writing."
+ << endl;
+ return 1;
+ }
+
+ TQTextStream cpp( &implementation );
+
+
+ cpp << "// This file is generated by tdeconfig_compiler from " << args->url(0).fileName() << "." << endl;
+ cpp << "// All changes you do to this file will be lost." << endl << endl;
+
+ cpp << "#include \"" << headerFileName << "\"" << endl << endl;
+
+ if ( setUserTexts ) cpp << "#include <klocale.h>" << endl << endl;
+
+ // Header required by singleton implementation
+ if ( singleton )
+ cpp << "#include <kstaticdeleter.h>" << endl << endl;
+ if ( singleton && cfgFileNameArg )
+ cpp << "#include <kdebug.h>" << endl << endl;
+
+ if ( !nameSpace.isEmpty() )
+ cpp << "using namespace " << nameSpace << ";" << endl << endl;
+
+ TQString group;
+
+ // private class implementation
+ if ( dpointer )
+ {
+ cpp << "class " << className << "Private" << endl;
+ cpp << "{" << endl;
+ cpp << " public:" << endl;
+ for( e = entries.first(); e; e = entries.next() ) {
+ if ( e->group() != group ) {
+ group = e->group();
+ cpp << endl;
+ cpp << " // " << group << endl;
+ }
+ cpp << " " << cppType(e->type()) << " " << varName(e->name());
+ if (!e->param().isEmpty())
+ {
+ cpp << TQString("[%1]").arg(e->paramMax()+1);
+ }
+ cpp << ";" << endl;
+ }
+ cpp << endl << " // items" << endl;
+ for( e = entries.first(); e; e = entries.next() ) {
+ cpp << " TDEConfigSkeleton::Item" << itemType( e->type() ) << " *" << itemVar( e );
+ if (!e->param().isEmpty() ) cpp << TQString("[%1]").arg( e->paramMax()+1 );
+ cpp << ";" << endl;
+ }
+
+ cpp << "};" << endl << endl;
+ }
+
+ // Singleton implementation
+ if ( singleton ) {
+ cpp << className << " *" << className << "::mSelf = 0;" << endl;
+ cpp << "static KStaticDeleter<" << className << "> static" << className << "Deleter;" << endl << endl;
+
+ cpp << className << " *" << className << "::self()" << endl;
+ cpp << "{" << endl;
+ if ( cfgFileNameArg ) {
+ cpp << " if (!mSelf)" << endl;
+ cpp << " kdFatal() << \"you need to call " << className << "::instance before using\" << endl;" << endl;
+ } else {
+ cpp << " if ( !mSelf ) {" << endl;
+ cpp << " static" << className << "Deleter.setObject( mSelf, new " << className << "() );" << endl;
+ cpp << " mSelf->readConfig();" << endl;
+ cpp << " }" << endl << endl;
+ }
+ cpp << " return mSelf;" << endl;
+ cpp << "}" << endl << endl;
+
+ if ( cfgFileNameArg ) {
+ cpp << "void " << className << "::instance(const char *cfgfilename)" << endl;
+ cpp << "{" << endl;
+ cpp << " if (mSelf) {" << endl;
+ cpp << " kdError() << \"" << className << "::instance called after the first use - ignoring\" << endl;" << endl;
+ cpp << " return;" << endl;
+ cpp << " }" << endl;
+ cpp << " static" << className << "Deleter.setObject( mSelf, new " << className << "(cfgfilename) );" << endl;
+ cpp << " mSelf->readConfig();" << endl;
+ cpp << "}" << endl << endl;
+ }
+ }
+
+ if ( !cppPreamble.isEmpty() )
+ cpp << cppPreamble << endl;
+
+ // Constructor
+ cpp << className << "::" << className << "( ";
+ if ( cfgFileNameArg ) {
+ if ( !singleton )
+ cpp << " KSharedConfig::Ptr config";
+ else
+ cpp << " const char *config";
+ cpp << (parameters.isEmpty() ? " " : ", ");
+ }
+
+ for (TQValueList<Param>::ConstIterator it = parameters.begin();
+ it != parameters.end(); ++it)
+ {
+ if (it != parameters.begin())
+ cpp << ",";
+ cpp << " " << param((*it).type) << " " << (*it).name;
+ }
+ cpp << " )" << endl;
+
+ cpp << " : " << inherits << "(";
+ if ( !cfgFileName.isEmpty() ) cpp << " TQString::fromLatin1( \"" << cfgFileName << "\" ";
+ if ( cfgFileNameArg ) cpp << " config ";
+ if ( !cfgFileName.isEmpty() ) cpp << ") ";
+ cpp << ")" << endl;
+
+ // Store parameters
+ for (TQValueList<Param>::ConstIterator it = parameters.begin();
+ it != parameters.end(); ++it)
+ {
+ cpp << " , mParam" << (*it).name << "(" << (*it).name << ")" << endl;
+ }
+
+ cpp << "{" << endl;
+
+ if (dpointer)
+ cpp << " d = new " + className + "Private;" << endl;
+ // Needed in case the singleton class is used as baseclass for
+ // another singleton.
+ if ( singleton )
+ cpp << " mSelf = this;" << endl;
+
+ group = TQString();
+ for( e = entries.first(); e; e = entries.next() ) {
+ if ( e->group() != group ) {
+ if ( !group.isEmpty() ) cpp << endl;
+ group = e->group();
+ cpp << " setCurrentGroup( " << paramString(group, parameters) << " );" << endl << endl;
+ }
+
+ TQString key = paramString(e->key(), parameters);
+ if ( !e->code().isEmpty())
+ {
+ cpp << e->code() << endl;
+ }
+ if ( e->type() == "Enum" ) {
+ cpp << " TQValueList<TDEConfigSkeleton::ItemEnum::Choice> values"
+ << e->name() << ";" << endl;
+ TQValueList<CfgEntry::Choice> choices = e->choices();
+ TQValueList<CfgEntry::Choice>::ConstIterator it;
+ for( it = choices.begin(); it != choices.end(); ++it ) {
+ cpp << " {" << endl;
+ cpp << " TDEConfigSkeleton::ItemEnum::Choice choice;" << endl;
+ cpp << " choice.name = TQString::fromLatin1( \"" << (*it).name << "\" );" << endl;
+ if ( setUserTexts ) {
+ if ( !(*it).label.isEmpty() )
+ cpp << " choice.label = i18n(" << quoteString((*it).label) << ");" << endl;
+ if ( !(*it).whatsThis.isEmpty() )
+ cpp << " choice.whatsThis = i18n(" << quoteString((*it).whatsThis) << ");" << endl;
+ }
+ cpp << " values" << e->name() << ".append( choice );" << endl;
+ cpp << " }" << endl;
+ }
+ }
+
+ if (!dpointer)
+ cpp << itemDeclaration(e);
+
+ if (e->param().isEmpty())
+ {
+ // Normal case
+ cpp << " " << itemPath(e) << " = "
+ << newItem( e->type(), e->name(), key, e->defaultValue() ) << endl;
+
+ if ( !e->minValue().isEmpty() )
+ cpp << " " << itemPath(e) << "->setMinValue(" << e->minValue() << ");" << endl;
+ if ( !e->maxValue().isEmpty() )
+ cpp << " " << itemPath(e) << "->setMaxValue(" << e->maxValue() << ");" << endl;
+
+ if ( setUserTexts )
+ cpp << userTextsFunctions( e );
+
+ cpp << " addItem( " << itemPath(e);
+ TQString quotedName = e->name();
+ addQuotes( quotedName );
+ if ( quotedName != key ) cpp << ", TQString::fromLatin1( \"" << e->name() << "\" )";
+ cpp << " );" << endl;
+ }
+ else
+ {
+ // Indexed
+ for(int i = 0; i <= e->paramMax(); i++)
+ {
+ TQString defaultStr;
+ TQString itemVarStr(itemPath(e)+TQString("[%1]").arg(i));
+
+ if ( !e->paramDefaultValue(i).isEmpty() )
+ defaultStr = e->paramDefaultValue(i);
+ else if ( !e->defaultValue().isEmpty() )
+ defaultStr = paramString(e->defaultValue(), e, i);
+ else
+ defaultStr = defaultValue( e->type() );
+
+ cpp << " " << itemVarStr << " = "
+ << newItem( e->type(), e->name(), paramString(key, e, i), defaultStr, TQString("[%1]").arg(i) )
+ << endl;
+
+ if ( setUserTexts )
+ cpp << userTextsFunctions( e, itemVarStr, e->paramName() );
+
+ // Make mutators for enum parameters work by adding them with $(..) replaced by the
+ // param name. The check for isImmutable in the set* functions doesn't have the param
+ // name available, just the corresponding enum value (int), so we need to store the
+ // param names in a separate static list!.
+ cpp << " addItem( " << itemVarStr << ", TQString::fromLatin1( \"";
+ if ( e->paramType()=="Enum" )
+ cpp << e->paramName().replace( "$("+e->param()+")", "%1").arg(e->paramValues()[i] );
+ else
+ cpp << e->paramName().replace( "$("+e->param()+")", "%1").arg(i);
+ cpp << "\" ) );" << endl;
+ }
+ }
+ }
+
+ cpp << "}" << endl << endl;
+
+ if (dpointer)
+ {
+ // setters and getters go in Cpp if in dpointer mode
+ for( e = entries.first(); e; e = entries.next() )
+ {
+ TQString n = e->name();
+ TQString t = e->type();
+
+ // Manipulator
+ if (allMutators || mutators.contains(n))
+ {
+ cpp << "void " << setFunction(n, className) << "( ";
+ if (!e->param().isEmpty())
+ cpp << cppType(e->paramType()) << " i, ";
+ cpp << param( t ) << " v )" << endl;
+ // function body inline only if not using dpointer
+ // for BC mode
+ cpp << "{" << endl;
+ cpp << indent(memberMutatorBody(e), 6);
+ cpp << "}" << endl << endl;
+ }
+
+ // Accessor
+ cpp << cppType(t) << " " << getFunction(n, className) << "(";
+ if (!e->param().isEmpty())
+ cpp << " " << cppType(e->paramType()) <<" i ";
+ cpp << ")" << Const << endl;
+ // function body inline only if not using dpointer
+ // for BC mode
+ cpp << "{" << endl;
+ cpp << indent(memberAccessorBody(e), 2);
+ cpp << "}" << endl << endl;
+
+ // Item accessor
+ if ( itemAccessors )
+ {
+ cpp << endl;
+ cpp << "TDEConfigSkeleton::Item" << itemType( e->type() ) << " *"
+ << getFunction( n, className ) << "Item(";
+ if (!e->param().isEmpty()) {
+ cpp << " " << cppType(e->paramType()) << " i ";
+ }
+ cpp << ")" << endl;
+ cpp << "{" << endl;
+ cpp << indent(itemAccessorBody(e), 2);
+ cpp << "}" << endl;
+ }
+
+ cpp << endl;
+ }
+ }
+
+ // Destructor
+ cpp << className << "::~" << className << "()" << endl;
+ cpp << "{" << endl;
+ if ( singleton ) {
+ if ( dpointer )
+ cpp << " delete d;" << endl;
+ cpp << " if ( mSelf == this )" << endl;
+ cpp << " static" << className << "Deleter.setObject( mSelf, 0, false );" << endl;
+ }
+ cpp << "}" << endl << endl;
+
+ implementation.close();
+}
diff --git a/tdecore/tdeconfig_compiler/tests/Makefile.am b/tdecore/tdeconfig_compiler/tests/Makefile.am
new file mode 100644
index 000000000..fa88f0b4b
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/Makefile.am
@@ -0,0 +1,134 @@
+AM_CPPFLAGS = -I$(top_srcdir)/tdecore -I$(top_srcdir)/tdeunittest $(all_includes) -DQT_NO_CAST_ASCII -DSRCDIR=\"$(srcdir)\"
+
+check_PROGRAMS = test1 test2 test3 test4 test5 test6 test7 test8 test9 test_dpointer
+
+CLEANFILES = test1.cpp test1.h \
+ test2.cpp test2.h \
+ test3.cpp test3.h \
+ test4.cpp test4.h \
+ test5.cpp test5.h \
+ test6.cpp test6.h \
+ test7.cpp test7.h \
+ test8a.cpp test8a.h test8b.cpp test8b.h \
+ test9.cpp test9.h \
+ test_dpointer.cpp test_dpointer.h \
+ md5sums
+
+test1_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test1_LDADD = $(LIB_TDECORE)
+test1_SOURCES = test1main.cpp test1.cpp
+
+test2_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test2_LDADD = $(LIB_TDECORE)
+test2_SOURCES = test2main.cpp test2.cpp
+
+test3_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test3_LDADD = $(LIB_TDECORE)
+test3_SOURCES = test3main.cpp test3.cpp
+
+test4_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test4_LDADD = $(LIB_TDECORE)
+test4_SOURCES = test4main.cpp test4.cpp
+
+test5_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test5_LDADD = $(LIB_TDECORE)
+test5_SOURCES = test5main.cpp test5.cpp
+
+test6_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test6_LDADD = $(LIB_TDECORE)
+test6_SOURCES = test6main.cpp test6.cpp
+
+test7_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test7_LDADD = $(LIB_TDECORE)
+test7_SOURCES = test7main.cpp test7.cpp
+
+test8_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test8_LDADD = $(LIB_TDECORE)
+test8_SOURCES = test8main.cpp test8a.cpp test8b.cpp
+
+test9_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test9_LDADD = $(LIB_TDECORE)
+test9_SOURCES = test9main.cpp test9.cpp
+
+test_dpointer_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+test_dpointer_LDADD = $(LIB_TDECORE)
+test_dpointer_SOURCES = test_dpointer_main.cpp test_dpointer.cpp
+
+check_LTLIBRARIES = tdeunittest_tdeconfigcompiler_test.la
+
+tdeunittest_tdeconfigcompiler_test_la_SOURCES = tdeconfigcompiler_test.cpp
+tdeunittest_tdeconfigcompiler_test_la_LIBADD = \
+ $(top_builddir)/tdeunittest/libtdeunittest.la
+tdeunittest_tdeconfigcompiler_test_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN) \
+ $(all_libraries)
+
+
+test1main.o test1.o: test1.h
+# avoid running the below command in parallel
+test1.cpp: test1.h
+test1.cpp test1.h: $(srcdir)/test1.kcfg ../tdeconfig_compiler $(srcdir)/test1.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test1.kcfg $(srcdir)/test1.kcfgc
+
+test2main.o test2.o: test2.h
+# avoid running the below command in parallel
+test2.cpp: test2.h
+test2.cpp test2.h: $(srcdir)/test2.kcfg ../tdeconfig_compiler $(srcdir)/test2.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test2.kcfg $(srcdir)/test2.kcfgc
+
+test3main.o test3.o: test3.h
+# avoid running the below command in parallel
+test3.cpp: test3.h
+test3.cpp test3.h: $(srcdir)/test3.kcfg ../tdeconfig_compiler $(srcdir)/test3.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test3.kcfg $(srcdir)/test3.kcfgc
+
+test4main.o test4.o: test4.h
+# avoid running the below command in parallel
+test4.cpp: test4.h
+test4.cpp test4.h: $(srcdir)/test4.kcfg ../tdeconfig_compiler $(srcdir)/test4.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test4.kcfg $(srcdir)/test4.kcfgc
+
+test5main.o test5.o: test5.h
+# avoid running the below command in parallel
+test5.cpp: test5.h
+test5.cpp test5.h: $(srcdir)/test5.kcfg ../tdeconfig_compiler $(srcdir)/test5.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test5.kcfg $(srcdir)/test5.kcfgc
+
+test6main.o test6.o: test6.h
+# avoid running the below command in parallel
+test6.cpp: test6.h
+test6.cpp test6.h: $(srcdir)/test6.kcfg ../tdeconfig_compiler $(srcdir)/test6.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test6.kcfg $(srcdir)/test6.kcfgc
+
+test7main.o test7.o: test7.h
+# avoid running the below command in parallel
+test7.cpp: test7.h
+test7.cpp test7.h: $(srcdir)/test7.kcfg ../tdeconfig_compiler $(srcdir)/test7.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test7.kcfg $(srcdir)/test7.kcfgc
+
+test8main.o test8a.o test8b.o: test8a.h test8b.h
+# avoid running the below command in parallel
+test8a.cpp: test8a.h
+test8a.cpp test8a.h: $(srcdir)/test8a.kcfg ../tdeconfig_compiler $(srcdir)/test8a.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test8a.kcfg $(srcdir)/test8a.kcfgc
+test8b.cpp: test8b.h
+test8b.cpp test8b.h: $(srcdir)/test8b.kcfg ../tdeconfig_compiler $(srcdir)/test8b.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test8b.kcfg $(srcdir)/test8b.kcfgc
+
+test9main.o test9.o: test9.h
+# avoid running the below command in parallel
+test9.cpp: test9.h
+test9.cpp test9.h: $(srcdir)/test9.kcfg ../tdeconfig_compiler $(srcdir)/test9.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test9.kcfg $(srcdir)/test9.kcfgc
+
+test_dpointer_main.o test_dpointer.o: test_dpointer.h
+# avoid running the below command in parallel
+test_dpointer.cpp: test_dpointer.h
+test_dpointer.cpp test_dpointer.h: $(srcdir)/test_dpointer.kcfg ../tdeconfig_compiler $(srcdir)/test_dpointer.kcfgc
+ ../tdeconfig_compiler $(srcdir)/test_dpointer.kcfg $(srcdir)/test_dpointer.kcfgc
+
+md5sums:
+ $(MD5SUM) $(srcdir)/test*.ref | sed -e "s,$(srcdir)/,,; s,\.ref$$,," > md5sums
+
+md5check: test1.cpp test2.cpp test3.cpp test4.cpp test5.cpp test6.cpp test7.cpp test8a.cpp test8b.cpp test9.cpp md5sums
+ $(MD5SUM) -c md5sums
+
diff --git a/tdecore/tdeconfig_compiler/tests/myprefs.h b/tdecore/tdeconfig_compiler/tests/myprefs.h
new file mode 100644
index 000000000..99ea62ec1
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/myprefs.h
@@ -0,0 +1,7 @@
+#include <tdeconfigskeleton.h>
+
+class MyPrefs : public TDEConfigSkeleton
+{
+ public:
+ MyPrefs( const TQString &a ) : TDEConfigSkeleton( a ) {}
+};
diff --git a/tdecore/tdeconfig_compiler/tests/tdeconfigcompiler_test.cpp b/tdecore/tdeconfig_compiler/tests/tdeconfigcompiler_test.cpp
new file mode 100644
index 000000000..e5bb3dcea
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/tdeconfigcompiler_test.cpp
@@ -0,0 +1,96 @@
+/*
+ Tests for TDEConfig Compiler
+
+ Copyright (c) 2005 by Duncan Mac-Vicar <duncan@kde.org>
+
+ *************************************************************************
+ * *
+ * This library is free software; you can redistribute it and/or *
+ * modify it under the terms of the GNU Lesser General Public *
+ * License as published by the Free Software Foundation; either *
+ * version 2 of the License, or (at your option) any later version. *
+ * *
+ *************************************************************************
+*/
+
+#include <tqfile.h>
+#include <tqstring.h>
+#include <kdebug.h>
+#include <tdeunittest/module.h>
+#include "tdeconfigcompiler_test.h"
+
+using namespace KUnitTest;
+
+KUNITTEST_MODULE( tdeunittest_tdeconfigcompiler_test, "TDEConfigXT")
+KUNITTEST_MODULE_REGISTER_TESTER( TDEConfigCompiler_Test )
+
+typedef const char * CompilerTestSet[];
+
+static CompilerTestSet testCases =
+{
+ "test1.cpp", "test1.h",
+ "test2.cpp", "test2.h",
+ "test3.cpp", "test3.h",
+ "test4.cpp", "test4.h",
+ "test5.cpp", "test5.h",
+ "test6.cpp", "test6.h",
+ "test7.cpp", "test7.h",
+ "test8a.cpp", "test8a.h",
+ "test8b.cpp", "test8b.h",
+ "test9.h", "test9.cpp",
+ "test_dpointer.cpp", "test_dpointer.h",
+ NULL
+};
+
+static CompilerTestSet willFailCases =
+{
+ // where is that TQDir comming from?
+ //"test9.cpp", NULL
+ NULL
+};
+
+
+void TDEConfigCompiler_Test::allTests()
+{
+ testExpectedOutput();
+}
+
+void TDEConfigCompiler_Test::testExpectedOutput()
+{
+ uint i = 0;
+ // Known to pass test cases
+ while (testCases[ i ])
+ {
+ performCompare(TQString::fromLatin1(testCases[ i ]));
+ ++i;
+ }
+
+ // broken test cases
+ i= 0;
+ while (willFailCases[ i ])
+ {
+ performCompare(TQString::fromLatin1(willFailCases[ i ]), true);
+ ++i;
+ }
+}
+
+void TDEConfigCompiler_Test::performCompare(const TQString &fileName, bool fail)
+{
+ TQFile file(fileName);
+ TQFile fileRef(TQString::fromLatin1(SRCDIR) + TQString::fromLatin1("/") + fileName + TQString::fromLatin1(".ref"));
+
+ if ( file.open(IO_ReadOnly) && fileRef.open(IO_ReadOnly) )
+ {
+ TQString content = file.readAll();
+ TQString contentRef = fileRef.readAll();
+
+ if (!fail)
+ CHECK( content, contentRef);
+ else
+ XFAIL( content, contentRef);
+ }
+ else
+ {
+ SKIP("Can't open file for comparision");
+ }
+}
diff --git a/tdecore/kconfig_compiler/tests/kconfigcompiler_test.h b/tdecore/tdeconfig_compiler/tests/tdeconfigcompiler_test.h
index df3f4cf37..df3f4cf37 100644
--- a/tdecore/kconfig_compiler/tests/kconfigcompiler_test.h
+++ b/tdecore/tdeconfig_compiler/tests/tdeconfigcompiler_test.h
diff --git a/tdecore/tdeconfig_compiler/tests/test1.cpp.ref b/tdecore/tdeconfig_compiler/tests/test1.cpp.ref
new file mode 100644
index 000000000..50f084874
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test1.cpp.ref
@@ -0,0 +1,72 @@
+// This file is generated by tdeconfig_compiler from test1.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test1.h"
+
+Test1::Test1( const TQString & transport, const TQString & folder )
+ : TDEConfigSkeleton( TQString::fromLatin1( "examplerc" ) )
+ , mParamtransport(transport)
+ , mParamfolder(folder)
+{
+ setCurrentGroup( TQString::fromLatin1( "General-%1" ).arg( mParamfolder ) );
+
+ TDEConfigSkeleton::ItemBool *itemOneOption;
+ itemOneOption = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "OneOption" ), mOneOption, true );
+ addItem( itemOneOption, TQString::fromLatin1( "OneOption" ) );
+ TDEConfigSkeleton::ItemInt *itemAnotherOption;
+ itemAnotherOption = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Another Option" ), mAnotherOption, 5 );
+ addItem( itemAnotherOption, TQString::fromLatin1( "AnotherOption" ) );
+ TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesListOption;
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "One" );
+ valuesListOption.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "Two" );
+ valuesListOption.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "Three" );
+ valuesListOption.append( choice );
+ }
+ TDEConfigSkeleton::ItemEnum *itemListOption;
+ itemListOption = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "ListOption" ), mListOption, valuesListOption, EnumListOption::One );
+ addItem( itemListOption, TQString::fromLatin1( "ListOption" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "MyOptions" ) );
+
+ TDEConfigSkeleton::ItemString *itemMyString;
+ itemMyString = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "MyString" ), mMyString, TQString::fromLatin1( "Default String" ) );
+ addItem( itemMyString, TQString::fromLatin1( "MyString" ) );
+ TDEConfigSkeleton::ItemPath *itemMyPath;
+ itemMyPath = new TDEConfigSkeleton::ItemPath( currentGroup(), TQString::fromLatin1( "MyPath" ), mMyPath, TQDir::homeDirPath()+TQString::fromLatin1(".hidden_file") );
+ addItem( itemMyPath, TQString::fromLatin1( "MyPath" ) );
+ TDEConfigSkeleton::ItemInt *itemAnotherOption2;
+ itemAnotherOption2 = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Another Option" ), mAnotherOption2, 10 );
+ addItem( itemAnotherOption2, TQString::fromLatin1( "AnotherOption2" ) );
+ TQStringList defaultMyStringList;
+ defaultMyStringList.append( TQString::fromUtf8( "up" ) );
+ defaultMyStringList.append( TQString::fromUtf8( "down" ) );
+
+ TDEConfigSkeleton::ItemStringList *itemMyStringList;
+ itemMyStringList = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "MyStringList" ), mMyStringList, defaultMyStringList );
+ addItem( itemMyStringList, TQString::fromLatin1( "MyStringList" ) );
+ TQStringList defaultMyStringListHidden;
+ defaultMyStringListHidden.append( TQString::fromUtf8( "up" ) );
+ defaultMyStringListHidden.append( TQString::fromUtf8( "down" ) );
+
+ TDEConfigSkeleton::ItemStringList *itemMyStringListHidden;
+ itemMyStringListHidden = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "MyStringListHidden" ), mMyStringListHidden, defaultMyStringListHidden );
+ addItem( itemMyStringListHidden, TQString::fromLatin1( "MyStringListHidden" ) );
+ TDEConfigSkeleton::ItemInt *itemMyNumber;
+ itemMyNumber = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "List-%1-%2" ).arg( mParamtransport ).arg( mParamfolder ), mMyNumber, 1 );
+ addItem( itemMyNumber, TQString::fromLatin1( "MyNumber" ) );
+}
+
+Test1::~Test1()
+{
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test1.h.ref b/tdecore/tdeconfig_compiler/tests/test1.h.ref
new file mode 100644
index 000000000..bb74038a5
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test1.h.ref
@@ -0,0 +1,196 @@
+// This file is generated by tdeconfig_compiler from test1.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST1_H
+#define TEST1_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+#include <tqdir.h>
+class Test1 : public TDEConfigSkeleton
+{
+ public:
+ class EnumListOption
+ {
+ public:
+ enum type { One, Two, Three, COUNT };
+ };
+
+ Test1( const TQString & transport, const TQString & folder );
+ ~Test1();
+
+ /**
+ Set One option
+ */
+ void setOneOption( bool v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "OneOption" ) ))
+ mOneOption = v;
+ }
+
+ /**
+ Get One option
+ */
+ bool oneOption() const
+ {
+ return mOneOption;
+ }
+
+ /**
+ Set Another option
+ */
+ void setAnotherOption( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "AnotherOption" ) ))
+ mAnotherOption = v;
+ }
+
+ /**
+ Get Another option
+ */
+ int anotherOption() const
+ {
+ return mAnotherOption;
+ }
+
+ /**
+ Set This is some funky option
+ */
+ void setListOption( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "ListOption" ) ))
+ mListOption = v;
+ }
+
+ /**
+ Get This is some funky option
+ */
+ int listOption() const
+ {
+ return mListOption;
+ }
+
+ /**
+ Set This is a string
+ */
+ void setMyString( const TQString & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyString" ) ))
+ mMyString = v;
+ }
+
+ /**
+ Get This is a string
+ */
+ TQString myString() const
+ {
+ return mMyString;
+ }
+
+ /**
+ Set This is a path
+ */
+ void setMyPath( const TQString & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyPath" ) ))
+ mMyPath = v;
+ }
+
+ /**
+ Get This is a path
+ */
+ TQString myPath() const
+ {
+ return mMyPath;
+ }
+
+ /**
+ Set Another option
+ */
+ void setAnotherOption2( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "AnotherOption2" ) ))
+ mAnotherOption2 = v;
+ }
+
+ /**
+ Get Another option
+ */
+ int anotherOption2() const
+ {
+ return mAnotherOption2;
+ }
+
+ /**
+ Set MyStringList
+ */
+ void setMyStringList( const TQStringList & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyStringList" ) ))
+ mMyStringList = v;
+ }
+
+ /**
+ Get MyStringList
+ */
+ TQStringList myStringList() const
+ {
+ return mMyStringList;
+ }
+
+ /**
+ Set MyStringListHidden
+ */
+ void setMyStringListHidden( const TQStringList & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyStringListHidden" ) ))
+ mMyStringListHidden = v;
+ }
+
+ /**
+ Get MyStringListHidden
+ */
+ TQStringList myStringListHidden() const
+ {
+ return mMyStringListHidden;
+ }
+
+ /**
+ Set List Number
+ */
+ void setMyNumber( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyNumber" ) ))
+ mMyNumber = v;
+ }
+
+ /**
+ Get List Number
+ */
+ int myNumber() const
+ {
+ return mMyNumber;
+ }
+
+ protected:
+ TQString mParamtransport;
+ TQString mParamfolder;
+
+ // General-$(folder)
+ bool mOneOption;
+ int mAnotherOption;
+ int mListOption;
+
+ // MyOptions
+ TQString mMyString;
+ TQString mMyPath;
+ int mAnotherOption2;
+ TQStringList mMyStringList;
+ TQStringList mMyStringListHidden;
+ int mMyNumber;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test1.kcfg b/tdecore/tdeconfig_compiler/tests/test1.kcfg
index ce42aebfb..ce42aebfb 100644
--- a/tdecore/kconfig_compiler/tests/test1.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test1.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test1.kcfgc b/tdecore/tdeconfig_compiler/tests/test1.kcfgc
new file mode 100644
index 000000000..dd086cdda
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test1.kcfgc
@@ -0,0 +1,18 @@
+# Code generation options for tdeconfig_compiler
+ClassName=Test1
+#
+# Singleton=false
+#
+# Inherits=TDEConfigSkeleton
+#
+# IncludeFiles=libtdepim/kpimprefs.h
+#
+# MemberVariables=public
+#
+### The following line includes the file exampleprefs_base_addon.h
+### It can be used to add extra functions and variables to the
+### class.
+# CustomAdditions=true
+#
+### Provide setFooBar(int) style functions
+Mutators=true
diff --git a/tdecore/kconfig_compiler/tests/test1main.cpp b/tdecore/tdeconfig_compiler/tests/test1main.cpp
index 79546639f..79546639f 100644
--- a/tdecore/kconfig_compiler/tests/test1main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test1main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test2.cpp.ref b/tdecore/tdeconfig_compiler/tests/test2.cpp.ref
new file mode 100644
index 000000000..cc3f67b5e
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test2.cpp.ref
@@ -0,0 +1,98 @@
+// This file is generated by tdeconfig_compiler from test2.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test2.h"
+
+#include <klocale.h>
+
+Test2::Test2( )
+ : MyPrefs( TQString::fromLatin1( "korganizerrc" ) )
+{
+ setCurrentGroup( TQString::fromLatin1( "General" ) );
+
+ mAutoSaveItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Auto Save" ), mAutoSave, false );
+ mAutoSaveItem->setLabel( i18n("Enable automatic saving of calendar") );
+ mAutoSaveItem->setWhatsThis( i18n("WhatsThis text for AutoSave option") );
+ addItem( mAutoSaveItem, TQString::fromLatin1( "AutoSave" ) );
+ mAutoSaveIntervalItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Auto Save Interval" ), mAutoSaveInterval, 10 );
+ mAutoSaveIntervalItem->setLabel( i18n("Auto Save Interval") );
+ addItem( mAutoSaveIntervalItem, TQString::fromLatin1( "AutoSaveInterval" ) );
+ mConfirmItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Confirm Deletes" ), mConfirm, true );
+ mConfirmItem->setLabel( i18n("Confirm deletes") );
+ addItem( mConfirmItem, TQString::fromLatin1( "Confirm" ) );
+ mArchiveFileItem = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "Archive File" ), mArchiveFile );
+ mArchiveFileItem->setLabel( i18n("Archive File") );
+ addItem( mArchiveFileItem, TQString::fromLatin1( "ArchiveFile" ) );
+ TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesDestination;
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "standardDestination" );
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "askDestination" );
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "argl1" );
+ choice.label = i18n("Argl1 Label");
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "argl2" );
+ choice.whatsThis = i18n("Argl2 Whatsthis");
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "argl3" );
+ choice.label = i18n("Argl3 Label");
+ choice.whatsThis = i18n("Argl3 Whatsthis");
+ valuesDestination.append( choice );
+ }
+ mDestinationItem = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "Destination" ), mDestination, valuesDestination, standardDestination );
+ mDestinationItem->setLabel( i18n("New Events/Todos Should") );
+ addItem( mDestinationItem, TQString::fromLatin1( "Destination" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Views" ) );
+
+ mHourSizeItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Hour Size" ), mHourSize, 10 );
+ mHourSizeItem->setLabel( i18n("Hour Size") );
+ addItem( mHourSizeItem, TQString::fromLatin1( "HourSize" ) );
+ mSelectionStartsEditorItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "SelectionStartsEditor" ), mSelectionStartsEditor, false );
+ mSelectionStartsEditorItem->setLabel( i18n("Time range selection in agenda view starts event editor") );
+ addItem( mSelectionStartsEditorItem, TQString::fromLatin1( "SelectionStartsEditor" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "KOrganizer Plugins" ) );
+
+ TQStringList defaultSelectedPlugins;
+ defaultSelectedPlugins.append( TQString::fromUtf8( "holidays" ) );
+ defaultSelectedPlugins.append( TQString::fromUtf8( "webexport" ) );
+
+ mSelectedPluginsItem = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "SelectedPlugins" ), mSelectedPlugins, defaultSelectedPlugins );
+ mSelectedPluginsItem->setLabel( i18n("SelectedPlugins") );
+ addItem( mSelectedPluginsItem, TQString::fromLatin1( "SelectedPlugins" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Colors" ) );
+
+ mHighlightColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Highlight Color" ), mHighlightColor, TQColor( 100, 100, 255 ) );
+ mHighlightColorItem->setLabel( i18n("Highlight color") );
+ addItem( mHighlightColorItem, TQString::fromLatin1( "HighlightColor" ) );
+ mAgendaBgColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Agenda Background Color" ), mAgendaBgColor, TQColor( 255, 255, 255 ) );
+ mAgendaBgColorItem->setLabel( i18n("Agenda view background color") );
+ addItem( mAgendaBgColorItem, TQString::fromLatin1( "AgendaBgColor" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Fonts" ) );
+
+ mTimeBarFontItem = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "TimeBar Font" ), mTimeBarFont );
+ mTimeBarFontItem->setLabel( i18n("Time bar") );
+ addItem( mTimeBarFontItem, TQString::fromLatin1( "TimeBarFont" ) );
+}
+
+Test2::~Test2()
+{
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test2.h.ref b/tdecore/tdeconfig_compiler/tests/test2.h.ref
new file mode 100644
index 000000000..47895ccaf
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test2.h.ref
@@ -0,0 +1,333 @@
+// This file is generated by tdeconfig_compiler from test2.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST2_H
+#define TEST2_H
+
+#include <myprefs.h>
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class Test2 : public MyPrefs
+{
+ public:
+ enum { standardDestination, askDestination, argl1, argl2, argl3 };
+
+ Test2( );
+ ~Test2();
+
+ /**
+ Set Enable automatic saving of calendar
+ */
+ void setAutoSave( bool v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "AutoSave" ) ))
+ mAutoSave = v;
+ }
+
+ /**
+ Get Enable automatic saving of calendar
+ */
+ bool autoSave() const
+ {
+ return mAutoSave;
+ }
+
+ /**
+ Get Item object corresponding to AutoSave()
+ */
+ ItemBool *autoSaveItem()
+ {
+ return mAutoSaveItem;
+ }
+
+ /**
+ Set Auto Save Interval
+ */
+ void setAutoSaveInterval( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "AutoSaveInterval" ) ))
+ mAutoSaveInterval = v;
+ }
+
+ /**
+ Get Auto Save Interval
+ */
+ int autoSaveInterval() const
+ {
+ return mAutoSaveInterval;
+ }
+
+ /**
+ Get Item object corresponding to AutoSaveInterval()
+ */
+ ItemInt *autoSaveIntervalItem()
+ {
+ return mAutoSaveIntervalItem;
+ }
+
+ /**
+ Set Confirm deletes
+ */
+ void setConfirm( bool v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "Confirm" ) ))
+ mConfirm = v;
+ }
+
+ /**
+ Get Confirm deletes
+ */
+ bool confirm() const
+ {
+ return mConfirm;
+ }
+
+ /**
+ Get Item object corresponding to Confirm()
+ */
+ ItemBool *confirmItem()
+ {
+ return mConfirmItem;
+ }
+
+ /**
+ Set Archive File
+ */
+ void setArchiveFile( const TQString & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "ArchiveFile" ) ))
+ mArchiveFile = v;
+ }
+
+ /**
+ Get Archive File
+ */
+ TQString archiveFile() const
+ {
+ return mArchiveFile;
+ }
+
+ /**
+ Get Item object corresponding to ArchiveFile()
+ */
+ ItemString *archiveFileItem()
+ {
+ return mArchiveFileItem;
+ }
+
+ /**
+ Set New Events/Todos Should
+ */
+ void setDestination( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "Destination" ) ))
+ mDestination = v;
+ }
+
+ /**
+ Get New Events/Todos Should
+ */
+ int destination() const
+ {
+ return mDestination;
+ }
+
+ /**
+ Get Item object corresponding to Destination()
+ */
+ ItemEnum *destinationItem()
+ {
+ return mDestinationItem;
+ }
+
+ /**
+ Set Hour Size
+ */
+ void setHourSize( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "HourSize" ) ))
+ mHourSize = v;
+ }
+
+ /**
+ Get Hour Size
+ */
+ int hourSize() const
+ {
+ return mHourSize;
+ }
+
+ /**
+ Get Item object corresponding to HourSize()
+ */
+ ItemInt *hourSizeItem()
+ {
+ return mHourSizeItem;
+ }
+
+ /**
+ Set Time range selection in agenda view starts event editor
+ */
+ void setSelectionStartsEditor( bool v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "SelectionStartsEditor" ) ))
+ mSelectionStartsEditor = v;
+ }
+
+ /**
+ Get Time range selection in agenda view starts event editor
+ */
+ bool selectionStartsEditor() const
+ {
+ return mSelectionStartsEditor;
+ }
+
+ /**
+ Get Item object corresponding to SelectionStartsEditor()
+ */
+ ItemBool *selectionStartsEditorItem()
+ {
+ return mSelectionStartsEditorItem;
+ }
+
+ /**
+ Set SelectedPlugins
+ */
+ void setSelectedPlugins( const TQStringList & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "SelectedPlugins" ) ))
+ mSelectedPlugins = v;
+ }
+
+ /**
+ Get SelectedPlugins
+ */
+ TQStringList selectedPlugins() const
+ {
+ return mSelectedPlugins;
+ }
+
+ /**
+ Get Item object corresponding to SelectedPlugins()
+ */
+ ItemStringList *selectedPluginsItem()
+ {
+ return mSelectedPluginsItem;
+ }
+
+ /**
+ Set Highlight color
+ */
+ void setHighlightColor( const TQColor & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "HighlightColor" ) ))
+ mHighlightColor = v;
+ }
+
+ /**
+ Get Highlight color
+ */
+ TQColor highlightColor() const
+ {
+ return mHighlightColor;
+ }
+
+ /**
+ Get Item object corresponding to HighlightColor()
+ */
+ ItemColor *highlightColorItem()
+ {
+ return mHighlightColorItem;
+ }
+
+ /**
+ Set Agenda view background color
+ */
+ void setAgendaBgColor( const TQColor & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "AgendaBgColor" ) ))
+ mAgendaBgColor = v;
+ }
+
+ /**
+ Get Agenda view background color
+ */
+ TQColor agendaBgColor() const
+ {
+ return mAgendaBgColor;
+ }
+
+ /**
+ Get Item object corresponding to AgendaBgColor()
+ */
+ ItemColor *agendaBgColorItem()
+ {
+ return mAgendaBgColorItem;
+ }
+
+ /**
+ Set Time bar
+ */
+ void setTimeBarFont( const TQFont & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "TimeBarFont" ) ))
+ mTimeBarFont = v;
+ }
+
+ /**
+ Get Time bar
+ */
+ TQFont timeBarFont() const
+ {
+ return mTimeBarFont;
+ }
+
+ /**
+ Get Item object corresponding to TimeBarFont()
+ */
+ ItemFont *timeBarFontItem()
+ {
+ return mTimeBarFontItem;
+ }
+
+ protected:
+ public:
+
+ // General
+ bool mAutoSave;
+ int mAutoSaveInterval;
+ bool mConfirm;
+ TQString mArchiveFile;
+ int mDestination;
+
+ // Views
+ int mHourSize;
+ bool mSelectionStartsEditor;
+
+ // KOrganizer Plugins
+ TQStringList mSelectedPlugins;
+
+ // Colors
+ TQColor mHighlightColor;
+ TQColor mAgendaBgColor;
+
+ // Fonts
+ TQFont mTimeBarFont;
+
+ private:
+ ItemBool *mAutoSaveItem;
+ ItemInt *mAutoSaveIntervalItem;
+ ItemBool *mConfirmItem;
+ ItemString *mArchiveFileItem;
+ ItemEnum *mDestinationItem;
+ ItemInt *mHourSizeItem;
+ ItemBool *mSelectionStartsEditorItem;
+ ItemStringList *mSelectedPluginsItem;
+ ItemColor *mHighlightColorItem;
+ ItemColor *mAgendaBgColorItem;
+ ItemFont *mTimeBarFontItem;
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test2.kcfg b/tdecore/tdeconfig_compiler/tests/test2.kcfg
index 3b19e270e..3b19e270e 100644
--- a/tdecore/kconfig_compiler/tests/test2.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test2.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test2.kcfgc b/tdecore/tdeconfig_compiler/tests/test2.kcfgc
new file mode 100644
index 000000000..e29040686
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test2.kcfgc
@@ -0,0 +1,11 @@
+# Code generation options for tdeconfig_compiler
+File=test2.kcfg
+ClassName=Test2
+Singleton=false
+Mutators=true
+Inherits=MyPrefs
+IncludeFiles=myprefs.h
+MemberVariables=public
+GlobalEnums=true
+ItemAccessors=true
+SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test2main.cpp b/tdecore/tdeconfig_compiler/tests/test2main.cpp
index 5970bf03d..5970bf03d 100644
--- a/tdecore/kconfig_compiler/tests/test2main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test2main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test3.cpp.ref b/tdecore/tdeconfig_compiler/tests/test3.cpp.ref
new file mode 100644
index 000000000..be3e5c6c1
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test3.cpp.ref
@@ -0,0 +1,29 @@
+// This file is generated by tdeconfig_compiler from test3.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test3.h"
+
+using namespace TestNameSpace;
+
+Test3::Test3( )
+ : TDEConfigSkeleton( TQString::fromLatin1( "test3rc" ) )
+{
+ setCurrentGroup( TQString::fromLatin1( "General" ) );
+
+ mAutoSaveItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Auto Save" ), mAutoSave, false );
+ addItem( mAutoSaveItem, TQString::fromLatin1( "AutoSave" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Blah" ) );
+
+ mBlubbItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Blubb" ), mBlubb, 10 );
+ addItem( mBlubbItem, TQString::fromLatin1( "Blubb" ) );
+ mBlahBlahItem = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "BlahBlah" ), mBlahBlah, TQString::fromLatin1( "a string" ) );
+ addItem( mBlahBlahItem, TQString::fromLatin1( "BlahBlah" ) );
+ mMyPasswordItem = new TDEConfigSkeleton::ItemPassword( currentGroup(), TQString::fromLatin1( "MyPassword" ), mMyPassword );
+ addItem( mMyPasswordItem, TQString::fromLatin1( "MyPassword" ) );
+}
+
+Test3::~Test3()
+{
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test3.h.ref b/tdecore/tdeconfig_compiler/tests/test3.h.ref
new file mode 100644
index 000000000..596e154e4
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test3.h.ref
@@ -0,0 +1,138 @@
+// This file is generated by tdeconfig_compiler from test3.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TESTNAMESPACE_TEST3_H
+#define TESTNAMESPACE_TEST3_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+namespace TestNameSpace {
+
+class Test3 : public TDEConfigSkeleton
+{
+ public:
+
+ Test3( );
+ ~Test3();
+
+ /**
+ Set Enable automatic saving of calendar
+ */
+ void setAutoSave( bool v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "AutoSave" ) ))
+ mAutoSave = v;
+ }
+
+ /**
+ Get Enable automatic saving of calendar
+ */
+ bool autoSave() const
+ {
+ return mAutoSave;
+ }
+
+ /**
+ Get Item object corresponding to AutoSave()
+ */
+ ItemBool *autoSaveItem()
+ {
+ return mAutoSaveItem;
+ }
+
+ /**
+ Set Blubb
+ */
+ void setBlubb( int v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "Blubb" ) ))
+ mBlubb = v;
+ }
+
+ /**
+ Get Blubb
+ */
+ int blubb() const
+ {
+ return mBlubb;
+ }
+
+ /**
+ Get Item object corresponding to Blubb()
+ */
+ ItemInt *blubbItem()
+ {
+ return mBlubbItem;
+ }
+
+ /**
+ Set BlahBlah
+ */
+ void setBlahBlah( const TQString & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "BlahBlah" ) ))
+ mBlahBlah = v;
+ }
+
+ /**
+ Get BlahBlah
+ */
+ TQString blahBlah() const
+ {
+ return mBlahBlah;
+ }
+
+ /**
+ Get Item object corresponding to BlahBlah()
+ */
+ ItemString *blahBlahItem()
+ {
+ return mBlahBlahItem;
+ }
+
+ /**
+ Set MyPassword
+ */
+ void setMyPassword( const TQString & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyPassword" ) ))
+ mMyPassword = v;
+ }
+
+ /**
+ Get MyPassword
+ */
+ TQString myPassword() const
+ {
+ return mMyPassword;
+ }
+
+ /**
+ Get Item object corresponding to MyPassword()
+ */
+ ItemPassword *myPasswordItem()
+ {
+ return mMyPasswordItem;
+ }
+
+ protected:
+
+ // General
+ bool mAutoSave;
+
+ // Blah
+ int mBlubb;
+ TQString mBlahBlah;
+ TQString mMyPassword;
+
+ private:
+ ItemBool *mAutoSaveItem;
+ ItemInt *mBlubbItem;
+ ItemString *mBlahBlahItem;
+ ItemPassword *mMyPasswordItem;
+};
+
+}
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test3.kcfg b/tdecore/tdeconfig_compiler/tests/test3.kcfg
index 77916da40..77916da40 100644
--- a/tdecore/kconfig_compiler/tests/test3.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test3.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test3.kcfgc b/tdecore/tdeconfig_compiler/tests/test3.kcfgc
new file mode 100644
index 000000000..d699810d0
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test3.kcfgc
@@ -0,0 +1,12 @@
+# Code generation options for tdeconfig_compiler
+File=test3.kcfg
+NameSpace=TestNameSpace
+ClassName=Test3
+#Singleton=false
+Mutators=true
+#Inherits=MyPrefs
+#IncludeFiles=myprefs.h
+#MemberVariables=public
+GlobalEnums=true
+ItemAccessors=true
+#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test3main.cpp b/tdecore/tdeconfig_compiler/tests/test3main.cpp
index f73ae38e3..f73ae38e3 100644
--- a/tdecore/kconfig_compiler/tests/test3main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test3main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test4.cpp.ref b/tdecore/tdeconfig_compiler/tests/test4.cpp.ref
new file mode 100644
index 000000000..c68437969
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test4.cpp.ref
@@ -0,0 +1,82 @@
+// This file is generated by tdeconfig_compiler from test4.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test4.h"
+
+#include <kstaticdeleter.h>
+
+Test4 *Test4::mSelf = 0;
+static KStaticDeleter<Test4> staticTest4Deleter;
+
+Test4 *Test4::self()
+{
+ if ( !mSelf ) {
+ staticTest4Deleter.setObject( mSelf, new Test4() );
+ mSelf->readConfig();
+ }
+
+ return mSelf;
+}
+
+const char* const Test4::EnumButton::enumToString[] = { "right", "mid", "left" };
+
+Test4::Test4( )
+ : TDEConfigSkeleton( TQString::fromLatin1( "test4rc" ) )
+{
+ mSelf = this;
+ setCurrentGroup( TQString::fromLatin1( "Foo" ) );
+
+TQColor defaultColor[4] = { Qt::red, Qt::blue, Qt::green, Qt::black };
+ TDEConfigSkeleton::ItemColor *itemColor[4];
+ itemColor[0] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #0" ), mColor[0], defaultColor[0] );
+ addItem( itemColor[0], TQString::fromLatin1( "Color0" ) );
+ itemColor[1] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #1" ), mColor[1], defaultColor[1] );
+ addItem( itemColor[1], TQString::fromLatin1( "Color1" ) );
+ itemColor[2] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #2" ), mColor[2], defaultColor[2] );
+ addItem( itemColor[2], TQString::fromLatin1( "Color2" ) );
+ itemColor[3] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #3" ), mColor[3], defaultColor[3] );
+ addItem( itemColor[3], TQString::fromLatin1( "Color3" ) );
+ TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesMouseAction;
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "Encrypt" );
+ valuesMouseAction.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "Decrypt" );
+ valuesMouseAction.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "CrashNBurn" );
+ valuesMouseAction.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "PumpNDump" );
+ valuesMouseAction.append( choice );
+ }
+ TDEConfigSkeleton::ItemEnum *itemMouseAction[3];
+ itemMouseAction[0] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "right_mouse_action" ), mMouseAction[0], valuesMouseAction, EnumMouseAction::Decrypt );
+ addItem( itemMouseAction[0], TQString::fromLatin1( "MouseActionright" ) );
+ itemMouseAction[1] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "mid_mouse_action" ), mMouseAction[1], valuesMouseAction, EnumMouseAction::Encrypt );
+ addItem( itemMouseAction[1], TQString::fromLatin1( "MouseActionmid" ) );
+ itemMouseAction[2] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "left_mouse_action" ), mMouseAction[2], valuesMouseAction, EnumMouseAction::PumpNDump );
+ addItem( itemMouseAction[2], TQString::fromLatin1( "MouseActionleft" ) );
+ TDEConfigSkeleton::ItemString *itemFooBar;
+ itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
+ addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
+ TDEConfigSkeleton::ItemInt *itemAge;
+ itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
+ itemAge->setMinValue(8);
+ itemAge->setMaxValue(88);
+ addItem( itemAge, TQString::fromLatin1( "Age" ) );
+}
+
+Test4::~Test4()
+{
+ if ( mSelf == this )
+ staticTest4Deleter.setObject( mSelf, 0, false );
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test4.h.ref b/tdecore/tdeconfig_compiler/tests/test4.h.ref
new file mode 100644
index 000000000..9901a4208
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test4.h.ref
@@ -0,0 +1,135 @@
+// This file is generated by tdeconfig_compiler from test4.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST4_H
+#define TEST4_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class Test4 : public TDEConfigSkeleton
+{
+ public:
+ class EnumMouseAction
+ {
+ public:
+ enum type { Encrypt, Decrypt, CrashNBurn, PumpNDump, COUNT };
+ };
+ class EnumButton
+ {
+ public:
+ enum type { right, mid, left, COUNT };
+ static const char* const enumToString[];
+ };
+
+ static Test4 *self();
+ ~Test4();
+
+ /**
+ Set Block colors.
+ */
+ static
+ void setColor( int i, const TQColor & v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "Color%1" ).arg( i ) ))
+ self()->mColor[i] = v;
+ }
+
+ /**
+ Get Block colors.
+ */
+ static
+ TQColor color( int i )
+ {
+ return self()->mColor[i];
+ }
+
+ /**
+ Set Mouse actions.
+ */
+ static
+ void setMouseAction( int i, int v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "MouseAction%1" ).arg( TQString::fromLatin1( EnumButton::enumToString[i] ) ) ))
+ self()->mMouseAction[i] = v;
+ }
+
+ /**
+ Get Mouse actions.
+ */
+ static
+ int mouseAction( int i )
+ {
+ return self()->mMouseAction[i];
+ }
+
+ /**
+ Set foo bar
+ */
+ static
+ void setFooBar( const TQString & v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "FooBar" ) ))
+ self()->mFooBar = v;
+ }
+
+ /**
+ Get foo bar
+ */
+ static
+ TQString fooBar()
+ {
+ return self()->mFooBar;
+ }
+
+ /**
+ Set Age
+ */
+ static
+ void setAge( int v )
+ {
+ if (v < 8)
+ {
+ kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
+ v = 8;
+ }
+
+ if (v > 88)
+ {
+ kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
+ v = 88;
+ }
+
+ if (!self()->isImmutable( TQString::fromLatin1( "Age" ) ))
+ self()->mAge = v;
+ }
+
+ /**
+ Get Age
+ */
+ static
+ int age()
+ {
+ return self()->mAge;
+ }
+
+ static
+ void writeConfig()
+ {
+ static_cast<TDEConfigSkeleton*>(self())->writeConfig();
+ }
+ protected:
+ Test4();
+ static Test4 *mSelf;
+
+
+ // Foo
+ TQColor mColor[4];
+ int mMouseAction[3];
+ TQString mFooBar;
+ int mAge;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test4.kcfg b/tdecore/tdeconfig_compiler/tests/test4.kcfg
index d8ef2bfae..d8ef2bfae 100644
--- a/tdecore/kconfig_compiler/tests/test4.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test4.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test4.kcfgc b/tdecore/tdeconfig_compiler/tests/test4.kcfgc
new file mode 100644
index 000000000..a81655b6c
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test4.kcfgc
@@ -0,0 +1,11 @@
+# Code generation options for tdeconfig_compiler
+File=test4.kcfg
+ClassName=Test4
+Singleton=true
+Mutators=true
+#Inherits=MyPrefs
+#IncludeFiles=myprefs.h
+#MemberVariables=public
+GlobalEnums=false
+ItemAccessors=false
+#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test4main.cpp b/tdecore/tdeconfig_compiler/tests/test4main.cpp
index 5229d8a87..5229d8a87 100644
--- a/tdecore/kconfig_compiler/tests/test4main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test4main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test5.cpp.ref b/tdecore/tdeconfig_compiler/tests/test5.cpp.ref
new file mode 100644
index 000000000..17965999b
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test5.cpp.ref
@@ -0,0 +1,82 @@
+// This file is generated by tdeconfig_compiler from test5.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test5.h"
+
+#include <kstaticdeleter.h>
+
+Test5 *Test5::mSelf = 0;
+static KStaticDeleter<Test5> staticTest5Deleter;
+
+Test5 *Test5::self()
+{
+ if ( !mSelf ) {
+ staticTest5Deleter.setObject( mSelf, new Test5() );
+ mSelf->readConfig();
+ }
+
+ return mSelf;
+}
+
+const char* const Test5::EnumButtonToString[] = { "right", "mid", "left" };
+
+Test5::Test5( )
+ : TDEConfigSkeleton( TQString::fromLatin1( "test4rc" ) )
+{
+ mSelf = this;
+ setCurrentGroup( TQString::fromLatin1( "Foo" ) );
+
+TQColor defaultColor[4] = { Qt::red, Qt::blue, Qt::green, Qt::black };
+ TDEConfigSkeleton::ItemColor *itemColor[4];
+ itemColor[0] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #0" ), mColor[0], defaultColor[0] );
+ addItem( itemColor[0], TQString::fromLatin1( "Color0" ) );
+ itemColor[1] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #1" ), mColor[1], defaultColor[1] );
+ addItem( itemColor[1], TQString::fromLatin1( "Color1" ) );
+ itemColor[2] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #2" ), mColor[2], defaultColor[2] );
+ addItem( itemColor[2], TQString::fromLatin1( "Color2" ) );
+ itemColor[3] = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #3" ), mColor[3], defaultColor[3] );
+ addItem( itemColor[3], TQString::fromLatin1( "Color3" ) );
+ TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesMouseAction;
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "Encrypt" );
+ valuesMouseAction.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "Decrypt" );
+ valuesMouseAction.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "CrashNBurn" );
+ valuesMouseAction.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "PumpNDump" );
+ valuesMouseAction.append( choice );
+ }
+ TDEConfigSkeleton::ItemEnum *itemMouseAction[3];
+ itemMouseAction[0] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "right_mouse_action" ), mMouseAction[0], valuesMouseAction, Decrypt );
+ addItem( itemMouseAction[0], TQString::fromLatin1( "MouseActionright" ) );
+ itemMouseAction[1] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "mid_mouse_action" ), mMouseAction[1], valuesMouseAction, Encrypt );
+ addItem( itemMouseAction[1], TQString::fromLatin1( "MouseActionmid" ) );
+ itemMouseAction[2] = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "left_mouse_action" ), mMouseAction[2], valuesMouseAction, PumpNDump );
+ addItem( itemMouseAction[2], TQString::fromLatin1( "MouseActionleft" ) );
+ TDEConfigSkeleton::ItemString *itemFooBar;
+ itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
+ addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
+ TDEConfigSkeleton::ItemInt *itemAge;
+ itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
+ itemAge->setMinValue(8);
+ itemAge->setMaxValue(88);
+ addItem( itemAge, TQString::fromLatin1( "Age" ) );
+}
+
+Test5::~Test5()
+{
+ if ( mSelf == this )
+ staticTest5Deleter.setObject( mSelf, 0, false );
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test5.h.ref b/tdecore/tdeconfig_compiler/tests/test5.h.ref
new file mode 100644
index 000000000..e2f1f8118
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test5.h.ref
@@ -0,0 +1,127 @@
+// This file is generated by tdeconfig_compiler from test5.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST5_H
+#define TEST5_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class Test5 : public TDEConfigSkeleton
+{
+ public:
+ enum { Encrypt, Decrypt, CrashNBurn, PumpNDump };
+ enum { right, mid, left };
+ static const char* const EnumButtonToString[];
+
+ static Test5 *self();
+ ~Test5();
+
+ /**
+ Set Block colors.
+ */
+ static
+ void setColor( int i, const TQColor & v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "Color%1" ).arg( i ) ))
+ self()->mColor[i] = v;
+ }
+
+ /**
+ Get Block colors.
+ */
+ static
+ TQColor color( int i )
+ {
+ return self()->mColor[i];
+ }
+
+ /**
+ Set Mouse actions.
+ */
+ static
+ void setMouseAction( int i, int v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "MouseAction%1" ).arg( TQString::fromLatin1( EnumButtonToString[i] ) ) ))
+ self()->mMouseAction[i] = v;
+ }
+
+ /**
+ Get Mouse actions.
+ */
+ static
+ int mouseAction( int i )
+ {
+ return self()->mMouseAction[i];
+ }
+
+ /**
+ Set foo bar
+ */
+ static
+ void setFooBar( const TQString & v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "FooBar" ) ))
+ self()->mFooBar = v;
+ }
+
+ /**
+ Get foo bar
+ */
+ static
+ TQString fooBar()
+ {
+ return self()->mFooBar;
+ }
+
+ /**
+ Set Age
+ */
+ static
+ void setAge( int v )
+ {
+ if (v < 8)
+ {
+ kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
+ v = 8;
+ }
+
+ if (v > 88)
+ {
+ kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
+ v = 88;
+ }
+
+ if (!self()->isImmutable( TQString::fromLatin1( "Age" ) ))
+ self()->mAge = v;
+ }
+
+ /**
+ Get Age
+ */
+ static
+ int age()
+ {
+ return self()->mAge;
+ }
+
+ static
+ void writeConfig()
+ {
+ static_cast<TDEConfigSkeleton*>(self())->writeConfig();
+ }
+ protected:
+ Test5();
+ static Test5 *mSelf;
+
+
+ // Foo
+ TQColor mColor[4];
+ int mMouseAction[3];
+ TQString mFooBar;
+ int mAge;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test5.kcfg b/tdecore/tdeconfig_compiler/tests/test5.kcfg
index d8ef2bfae..d8ef2bfae 100644
--- a/tdecore/kconfig_compiler/tests/test5.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test5.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test5.kcfgc b/tdecore/tdeconfig_compiler/tests/test5.kcfgc
new file mode 100644
index 000000000..dbc5603a0
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test5.kcfgc
@@ -0,0 +1,11 @@
+# Code generation options for tdeconfig_compiler
+File=test5.kcfg
+ClassName=Test5
+Singleton=true
+Mutators=true
+#Inherits=MyPrefs
+#IncludeFiles=myprefs.h
+#MemberVariables=public
+GlobalEnums=true
+ItemAccessors=false
+#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test5main.cpp b/tdecore/tdeconfig_compiler/tests/test5main.cpp
index 89f28587f..89f28587f 100644
--- a/tdecore/kconfig_compiler/tests/test5main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test5main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test6.cpp.ref b/tdecore/tdeconfig_compiler/tests/test6.cpp.ref
new file mode 100644
index 000000000..36717a7c8
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test6.cpp.ref
@@ -0,0 +1,31 @@
+// This file is generated by tdeconfig_compiler from test6.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test6.h"
+
+Test6::Test6( const TQString & Number )
+ : TDEConfigSkeleton( TQString::fromLatin1( "test4rc" ) )
+ , mParamNumber(Number)
+{
+ setCurrentGroup( TQString::fromLatin1( "Foo" ) );
+
+ TDEConfigSkeleton::ItemColor *itemColor;
+ itemColor = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #%1" ).arg( mParamNumber ), mColor, TQColor( "red" ) );
+ addItem( itemColor, TQString::fromLatin1( "Color" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Bar%1" ).arg( mParamNumber ) );
+
+ TDEConfigSkeleton::ItemString *itemFooBar;
+ itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
+ addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
+ TDEConfigSkeleton::ItemInt *itemAge;
+ itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
+ itemAge->setMinValue(8);
+ itemAge->setMaxValue(88);
+ addItem( itemAge, TQString::fromLatin1( "Age" ) );
+}
+
+Test6::~Test6()
+{
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test6.h.ref b/tdecore/tdeconfig_compiler/tests/test6.h.ref
new file mode 100644
index 000000000..da83c90c4
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test6.h.ref
@@ -0,0 +1,93 @@
+// This file is generated by tdeconfig_compiler from test6.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST6_H
+#define TEST6_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class Test6 : public TDEConfigSkeleton
+{
+ public:
+
+ Test6( const TQString & Number );
+ ~Test6();
+
+ /**
+ Set Block colors.
+ */
+ void setColor( const TQColor & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "Color" ) ))
+ mColor = v;
+ }
+
+ /**
+ Get Block colors.
+ */
+ TQColor color() const
+ {
+ return mColor;
+ }
+
+ /**
+ Set foo bar
+ */
+ void setFooBar( const TQString & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "FooBar" ) ))
+ mFooBar = v;
+ }
+
+ /**
+ Get foo bar
+ */
+ TQString fooBar() const
+ {
+ return mFooBar;
+ }
+
+ /**
+ Set Age
+ */
+ void setAge( int v )
+ {
+ if (v < 8)
+ {
+ kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
+ v = 8;
+ }
+
+ if (v > 88)
+ {
+ kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
+ v = 88;
+ }
+
+ if (!isImmutable( TQString::fromLatin1( "Age" ) ))
+ mAge = v;
+ }
+
+ /**
+ Get Age
+ */
+ int age() const
+ {
+ return mAge;
+ }
+
+ protected:
+ TQString mParamNumber;
+
+ // Foo
+ TQColor mColor;
+
+ // Bar$(Number)
+ TQString mFooBar;
+ int mAge;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test6.kcfg b/tdecore/tdeconfig_compiler/tests/test6.kcfg
index e59fa88f3..e59fa88f3 100644
--- a/tdecore/kconfig_compiler/tests/test6.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test6.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test6.kcfgc b/tdecore/tdeconfig_compiler/tests/test6.kcfgc
new file mode 100644
index 000000000..4c395ac08
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test6.kcfgc
@@ -0,0 +1,11 @@
+# Code generation options for tdeconfig_compiler
+File=test6.kcfg
+ClassName=Test6
+Singleton=false
+Mutators=true
+#Inherits=MyPrefs
+#IncludeFiles=myprefs.h
+#MemberVariables=public
+GlobalEnums=true
+ItemAccessors=false
+#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test6main.cpp b/tdecore/tdeconfig_compiler/tests/test6main.cpp
index 9b1b7503e..9b1b7503e 100644
--- a/tdecore/kconfig_compiler/tests/test6main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test6main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test7.cpp.ref b/tdecore/tdeconfig_compiler/tests/test7.cpp.ref
new file mode 100644
index 000000000..e4b5f08f9
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test7.cpp.ref
@@ -0,0 +1,31 @@
+// This file is generated by tdeconfig_compiler from test7.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test7.h"
+
+Test7::Test7( int Number )
+ : TDEConfigSkeleton( TQString::fromLatin1( "test7rc" ) )
+ , mParamNumber(Number)
+{
+ setCurrentGroup( TQString::fromLatin1( "Foo" ) );
+
+ TDEConfigSkeleton::ItemColor *itemColor;
+ itemColor = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "color #%1" ).arg( mParamNumber ), mColor, TQColor( "red" ) );
+ addItem( itemColor, TQString::fromLatin1( "Color" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Bar%1" ).arg( mParamNumber ) );
+
+ TDEConfigSkeleton::ItemString *itemFooBar;
+ itemFooBar = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "foo bar" ), mFooBar );
+ addItem( itemFooBar, TQString::fromLatin1( "FooBar" ) );
+ TDEConfigSkeleton::ItemInt *itemAge;
+ itemAge = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Age" ), mAge, 35 );
+ itemAge->setMinValue(8);
+ itemAge->setMaxValue(88);
+ addItem( itemAge, TQString::fromLatin1( "Age" ) );
+}
+
+Test7::~Test7()
+{
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test7.h.ref b/tdecore/tdeconfig_compiler/tests/test7.h.ref
new file mode 100644
index 000000000..8bd22ae97
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test7.h.ref
@@ -0,0 +1,93 @@
+// This file is generated by tdeconfig_compiler from test7.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST7_H
+#define TEST7_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class Test7 : public TDEConfigSkeleton
+{
+ public:
+
+ Test7( int Number );
+ ~Test7();
+
+ /**
+ Set Block colors.
+ */
+ void setColor( const TQColor & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "Color" ) ))
+ mColor = v;
+ }
+
+ /**
+ Get Block colors.
+ */
+ TQColor color() const
+ {
+ return mColor;
+ }
+
+ /**
+ Set foo bar
+ */
+ void setFooBar( const TQString & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "FooBar" ) ))
+ mFooBar = v;
+ }
+
+ /**
+ Get foo bar
+ */
+ TQString fooBar() const
+ {
+ return mFooBar;
+ }
+
+ /**
+ Set Age
+ */
+ void setAge( int v )
+ {
+ if (v < 8)
+ {
+ kdDebug() << "setAge: value " << v << " is less than the minimum value of 8" << endl;
+ v = 8;
+ }
+
+ if (v > 88)
+ {
+ kdDebug() << "setAge: value " << v << " is greater than the maximum value of 88" << endl;
+ v = 88;
+ }
+
+ if (!isImmutable( TQString::fromLatin1( "Age" ) ))
+ mAge = v;
+ }
+
+ /**
+ Get Age
+ */
+ int age() const
+ {
+ return mAge;
+ }
+
+ protected:
+ int mParamNumber;
+
+ // Foo
+ TQColor mColor;
+
+ // Bar$(Number)
+ TQString mFooBar;
+ int mAge;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test7.kcfg b/tdecore/tdeconfig_compiler/tests/test7.kcfg
index 0a7fd3272..0a7fd3272 100644
--- a/tdecore/kconfig_compiler/tests/test7.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test7.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test7.kcfgc b/tdecore/tdeconfig_compiler/tests/test7.kcfgc
new file mode 100644
index 000000000..c50aac7e3
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test7.kcfgc
@@ -0,0 +1,11 @@
+# Code generation options for tdeconfig_compiler
+File=test7.kcfg
+ClassName=Test7
+Singleton=false
+Mutators=true
+#Inherits=MyPrefs
+#IncludeFiles=myprefs.h
+#MemberVariables=public
+GlobalEnums=true
+ItemAccessors=false
+#SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test7main.cpp b/tdecore/tdeconfig_compiler/tests/test7main.cpp
index 81cca0184..81cca0184 100644
--- a/tdecore/kconfig_compiler/tests/test7main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test7main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test8a.cpp.ref b/tdecore/tdeconfig_compiler/tests/test8a.cpp.ref
new file mode 100644
index 000000000..c0a9ddda5
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test8a.cpp.ref
@@ -0,0 +1,22 @@
+// This file is generated by tdeconfig_compiler from test8a.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test8a.h"
+
+Test8a::Test8a( KSharedConfig::Ptr config )
+ : TDEConfigSkeleton( config )
+{
+ setCurrentGroup( TQString::fromLatin1( "Group" ) );
+
+ TDEConfigSkeleton::ItemFont *itemFont;
+ itemFont = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "Font" ), mFont, TDEGlobalSettings::generalFont() );
+ addItem( itemFont, TQString::fromLatin1( "Font" ) );
+ TDEConfigSkeleton::ItemFont *itemTitleFont;
+ itemTitleFont = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "TitleFont" ), mTitleFont, TDEGlobalSettings::windowTitleFont() );
+ addItem( itemTitleFont, TQString::fromLatin1( "TitleFont" ) );
+}
+
+Test8a::~Test8a()
+{
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test8a.h.ref b/tdecore/tdeconfig_compiler/tests/test8a.h.ref
new file mode 100644
index 000000000..9913cfc49
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test8a.h.ref
@@ -0,0 +1,61 @@
+// This file is generated by tdeconfig_compiler from test8a.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST8A_H
+#define TEST8A_H
+
+#include <kglobal.h>
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class Test8a : public TDEConfigSkeleton
+{
+ public:
+
+ Test8a( KSharedConfig::Ptr config = TDEGlobal::sharedConfig() );
+ ~Test8a();
+
+ /**
+ Set Font
+ */
+ void setFont( const TQFont & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "Font" ) ))
+ mFont = v;
+ }
+
+ /**
+ Get Font
+ */
+ TQFont font() const
+ {
+ return mFont;
+ }
+
+ /**
+ Set TitleFont
+ */
+ void setTitleFont( const TQFont & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "TitleFont" ) ))
+ mTitleFont = v;
+ }
+
+ /**
+ Get TitleFont
+ */
+ TQFont titleFont() const
+ {
+ return mTitleFont;
+ }
+
+ protected:
+
+ // Group
+ TQFont mFont;
+ TQFont mTitleFont;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test8a.kcfg b/tdecore/tdeconfig_compiler/tests/test8a.kcfg
index 53448b624..53448b624 100644
--- a/tdecore/kconfig_compiler/tests/test8a.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test8a.kcfg
diff --git a/tdecore/kconfig_compiler/tests/test8a.kcfgc b/tdecore/tdeconfig_compiler/tests/test8a.kcfgc
index 5f63c31c2..5f63c31c2 100644
--- a/tdecore/kconfig_compiler/tests/test8a.kcfgc
+++ b/tdecore/tdeconfig_compiler/tests/test8a.kcfgc
diff --git a/tdecore/tdeconfig_compiler/tests/test8b.cpp.ref b/tdecore/tdeconfig_compiler/tests/test8b.cpp.ref
new file mode 100644
index 000000000..288faeb12
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test8b.cpp.ref
@@ -0,0 +1,46 @@
+// This file is generated by tdeconfig_compiler from test8b.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test8b.h"
+
+#include <kstaticdeleter.h>
+
+Test8b *Test8b::mSelf = 0;
+static KStaticDeleter<Test8b> staticTest8bDeleter;
+
+Test8b *Test8b::self()
+{
+ if ( !mSelf ) {
+ staticTest8bDeleter.setObject( mSelf, new Test8b() );
+ mSelf->readConfig();
+ }
+
+ return mSelf;
+}
+
+Test8b::Test8b( )
+ : Test8a()
+{
+ mSelf = this;
+ setCurrentGroup( TQString::fromLatin1( "Group8b1" ) );
+
+ TDEConfigSkeleton::ItemUInt *itemSomething;
+ itemSomething = new TDEConfigSkeleton::ItemUInt( currentGroup(), TQString::fromLatin1( "Something" ), mSomething, 60 );
+ addItem( itemSomething, TQString::fromLatin1( "Something" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Group8b2" ) );
+
+ TDEConfigSkeleton::ItemBool *itemFooBoo;
+ itemFooBoo = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "FooBoo" ), mFooBoo, false );
+ addItem( itemFooBoo, TQString::fromLatin1( "FooBoo" ) );
+ TDEConfigSkeleton::ItemUInt *itemPort;
+ itemPort = new TDEConfigSkeleton::ItemUInt( currentGroup(), TQString::fromLatin1( "Port" ), mPort, 1000 );
+ addItem( itemPort, TQString::fromLatin1( "Port" ) );
+}
+
+Test8b::~Test8b()
+{
+ if ( mSelf == this )
+ staticTest8bDeleter.setObject( mSelf, 0, false );
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test8b.h.ref b/tdecore/tdeconfig_compiler/tests/test8b.h.ref
new file mode 100644
index 000000000..82ab5d92b
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test8b.h.ref
@@ -0,0 +1,96 @@
+// This file is generated by tdeconfig_compiler from test8b.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST8B_H
+#define TEST8B_H
+
+#include <test8a.h>
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class Test8b : public Test8a
+{
+ public:
+
+ static Test8b *self();
+ ~Test8b();
+
+ /**
+ Set Something
+ */
+ static
+ void setSomething( uint v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "Something" ) ))
+ self()->mSomething = v;
+ }
+
+ /**
+ Get Something
+ */
+ static
+ uint something()
+ {
+ return self()->mSomething;
+ }
+
+ /**
+ Set FooBoo
+ */
+ static
+ void setFooBoo( bool v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "FooBoo" ) ))
+ self()->mFooBoo = v;
+ }
+
+ /**
+ Get FooBoo
+ */
+ static
+ bool fooBoo()
+ {
+ return self()->mFooBoo;
+ }
+
+ /**
+ Set Port
+ */
+ static
+ void setPort( uint v )
+ {
+ if (!self()->isImmutable( TQString::fromLatin1( "Port" ) ))
+ self()->mPort = v;
+ }
+
+ /**
+ Get Port
+ */
+ static
+ uint port()
+ {
+ return self()->mPort;
+ }
+
+ static
+ void writeConfig()
+ {
+ static_cast<TDEConfigSkeleton*>(self())->writeConfig();
+ }
+ protected:
+ Test8b();
+ static Test8b *mSelf;
+
+
+ // Group8b1
+ uint mSomething;
+
+ // Group8b2
+ bool mFooBoo;
+ uint mPort;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test8b.kcfg b/tdecore/tdeconfig_compiler/tests/test8b.kcfg
index 3e203a155..3e203a155 100644
--- a/tdecore/kconfig_compiler/tests/test8b.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test8b.kcfg
diff --git a/tdecore/kconfig_compiler/tests/test8b.kcfgc b/tdecore/tdeconfig_compiler/tests/test8b.kcfgc
index 7be055203..7be055203 100644
--- a/tdecore/kconfig_compiler/tests/test8b.kcfgc
+++ b/tdecore/tdeconfig_compiler/tests/test8b.kcfgc
diff --git a/tdecore/kconfig_compiler/tests/test8main.cpp b/tdecore/tdeconfig_compiler/tests/test8main.cpp
index 04864a95c..04864a95c 100644
--- a/tdecore/kconfig_compiler/tests/test8main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test8main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test9.cpp.ref b/tdecore/tdeconfig_compiler/tests/test9.cpp.ref
new file mode 100644
index 000000000..a5ee144aa
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test9.cpp.ref
@@ -0,0 +1,35 @@
+// This file is generated by tdeconfig_compiler from test9.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test9.h"
+
+Test9::Test9( const TQString & transport, const TQString & folder )
+ : TDEConfigSkeleton( TQString::fromLatin1( "examplerc" ) )
+ , mParamtransport(transport)
+ , mParamfolder(folder)
+{
+ setCurrentGroup( TQString::fromLatin1( "MyOptionsXX" ) );
+
+ TQStringList defaultMyStringList;
+ defaultMyStringList.append( TQString::fromUtf8( "up" ) );
+ defaultMyStringList.append( TQString::fromUtf8( "down" ) );
+
+ TDEConfigSkeleton::ItemStringList *itemMyStringList;
+ itemMyStringList = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "MyStringList" ), mMyStringList, defaultMyStringList );
+ addItem( itemMyStringList, TQString::fromLatin1( "MyStringList" ) );
+ TQStringList defaultMyPathList;
+ defaultMyPathList.append( TQString::fromUtf8( "/home" ) );
+ defaultMyPathList.append( TQString::fromUtf8( "~" ) );
+
+ TDEConfigSkeleton::ItemPathList *itemMyPathList;
+ itemMyPathList = new TDEConfigSkeleton::ItemPathList( currentGroup(), TQString::fromLatin1( "MyPathList" ), mMyPathList, defaultMyPathList );
+ addItem( itemMyPathList, TQString::fromLatin1( "MyPathList" ) );
+ TDEConfigSkeleton::ItemPathList *itemMyPathsList2;
+ itemMyPathsList2 = new TDEConfigSkeleton::ItemPathList( currentGroup(), TQString::fromLatin1( "MyPathsList2" ), mMyPathsList2, TQStringList(TQString::fromLatin1("/usr/bin")) += TQDir::homeDirPath() );
+ addItem( itemMyPathsList2, TQString::fromLatin1( "MyPathsList2" ) );
+}
+
+Test9::~Test9()
+{
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test9.h.ref b/tdecore/tdeconfig_compiler/tests/test9.h.ref
new file mode 100644
index 000000000..23755f411
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test9.h.ref
@@ -0,0 +1,82 @@
+// This file is generated by tdeconfig_compiler from test9.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TEST9_H
+#define TEST9_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+#include <tqdir.h>
+class Test9 : public TDEConfigSkeleton
+{
+ public:
+
+ Test9( const TQString & transport, const TQString & folder );
+ ~Test9();
+
+ /**
+ Set MyStringList
+ */
+ void setMyStringList( const TQStringList & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyStringList" ) ))
+ mMyStringList = v;
+ }
+
+ /**
+ Get MyStringList
+ */
+ TQStringList myStringList() const
+ {
+ return mMyStringList;
+ }
+
+ /**
+ Set This is a list of paths
+ */
+ void setMyPathList( const TQStringList & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyPathList" ) ))
+ mMyPathList = v;
+ }
+
+ /**
+ Get This is a list of paths
+ */
+ TQStringList myPathList() const
+ {
+ return mMyPathList;
+ }
+
+ /**
+ Set This is an additional test for PathList
+ */
+ void setMyPathsList2( const TQStringList & v )
+ {
+ if (!isImmutable( TQString::fromLatin1( "MyPathsList2" ) ))
+ mMyPathsList2 = v;
+ }
+
+ /**
+ Get This is an additional test for PathList
+ */
+ TQStringList myPathsList2() const
+ {
+ return mMyPathsList2;
+ }
+
+ protected:
+ public:
+ TQString mParamtransport;
+ TQString mParamfolder;
+
+ // MyOptionsXX
+ TQStringList mMyStringList;
+ TQStringList mMyPathList;
+ TQStringList mMyPathsList2;
+
+ private:
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test9.kcfg b/tdecore/tdeconfig_compiler/tests/test9.kcfg
index b7495e2b6..b7495e2b6 100644
--- a/tdecore/kconfig_compiler/tests/test9.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test9.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test9.kcfgc b/tdecore/tdeconfig_compiler/tests/test9.kcfgc
new file mode 100644
index 000000000..47f5e5f43
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test9.kcfgc
@@ -0,0 +1,18 @@
+# Code generation options for tdeconfig_compiler
+ClassName=Test9
+#
+# Singleton=false
+#
+# Inherits=TDEConfigSkeleton
+#
+# IncludeFiles=libtdepim/kpimprefs.h
+#
+MemberVariables=public
+#
+### The following line includes the file exampleprefs_base_addon.h
+### It can be used to add extra functions and variables to the
+### class.
+# CustomAdditions=true
+#
+### Provide setFooBar(int) style functions
+Mutators=true
diff --git a/tdecore/kconfig_compiler/tests/test9main.cpp b/tdecore/tdeconfig_compiler/tests/test9main.cpp
index 8668d8d8c..8668d8d8c 100644
--- a/tdecore/kconfig_compiler/tests/test9main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test9main.cpp
diff --git a/tdecore/tdeconfig_compiler/tests/test_dpointer.cpp.ref b/tdecore/tdeconfig_compiler/tests/test_dpointer.cpp.ref
new file mode 100644
index 000000000..5aad12fe8
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test_dpointer.cpp.ref
@@ -0,0 +1,344 @@
+// This file is generated by tdeconfig_compiler from test_dpointer.kcfg.
+// All changes you do to this file will be lost.
+
+#include "test_dpointer.h"
+
+#include <klocale.h>
+
+#include <kstaticdeleter.h>
+
+class TestDPointerPrivate
+{
+ public:
+
+ // General
+ bool autoSave;
+ int autoSaveInterval;
+ bool confirm;
+ TQString archiveFile;
+ int destination;
+
+ // Views
+ int hourSize;
+ bool selectionStartsEditor;
+
+ // KOrganizer Plugins
+ TQStringList selectedPlugins;
+
+ // Colors
+ TQColor highlightColor;
+ TQColor agendaBgColor;
+
+ // Fonts
+ TQFont timeBarFont;
+
+ // items
+ TDEConfigSkeleton::ItemBool *autoSaveItem;
+ TDEConfigSkeleton::ItemInt *autoSaveIntervalItem;
+ TDEConfigSkeleton::ItemBool *confirmItem;
+ TDEConfigSkeleton::ItemString *archiveFileItem;
+ TDEConfigSkeleton::ItemEnum *destinationItem;
+ TDEConfigSkeleton::ItemInt *hourSizeItem;
+ TDEConfigSkeleton::ItemBool *selectionStartsEditorItem;
+ TDEConfigSkeleton::ItemStringList *selectedPluginsItem;
+ TDEConfigSkeleton::ItemColor *highlightColorItem;
+ TDEConfigSkeleton::ItemColor *agendaBgColorItem;
+ TDEConfigSkeleton::ItemFont *timeBarFontItem;
+};
+
+TestDPointer *TestDPointer::mSelf = 0;
+static KStaticDeleter<TestDPointer> staticTestDPointerDeleter;
+
+TestDPointer *TestDPointer::self()
+{
+ if ( !mSelf ) {
+ staticTestDPointerDeleter.setObject( mSelf, new TestDPointer() );
+ mSelf->readConfig();
+ }
+
+ return mSelf;
+}
+
+TestDPointer::TestDPointer( )
+ : TDEConfigSkeleton( TQString::fromLatin1( "korganizerrc" ) )
+{
+ d = new TestDPointerPrivate;
+ mSelf = this;
+ setCurrentGroup( TQString::fromLatin1( "General" ) );
+
+ d->autoSaveItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Auto Save" ), d->autoSave, false );
+ d->autoSaveItem->setLabel( i18n("Enable automatic saving of calendar") );
+ d->autoSaveItem->setWhatsThis( i18n("WhatsThis text for AutoSave option") );
+ addItem( d->autoSaveItem, TQString::fromLatin1( "AutoSave" ) );
+ d->autoSaveIntervalItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Auto Save Interval" ), d->autoSaveInterval, 10 );
+ d->autoSaveIntervalItem->setLabel( i18n("Auto Save Interval") );
+ addItem( d->autoSaveIntervalItem, TQString::fromLatin1( "AutoSaveInterval" ) );
+ d->confirmItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "Confirm Deletes" ), d->confirm, true );
+ d->confirmItem->setLabel( i18n("Confirm deletes") );
+ addItem( d->confirmItem, TQString::fromLatin1( "Confirm" ) );
+ d->archiveFileItem = new TDEConfigSkeleton::ItemString( currentGroup(), TQString::fromLatin1( "Archive File" ), d->archiveFile );
+ d->archiveFileItem->setLabel( i18n("Archive File") );
+ addItem( d->archiveFileItem, TQString::fromLatin1( "ArchiveFile" ) );
+ TQValueList<TDEConfigSkeleton::ItemEnum::Choice> valuesDestination;
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "standardDestination" );
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "askDestination" );
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "argl1" );
+ choice.label = i18n("Argl1 Label");
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "argl2" );
+ choice.whatsThis = i18n("Argl2 Whatsthis");
+ valuesDestination.append( choice );
+ }
+ {
+ TDEConfigSkeleton::ItemEnum::Choice choice;
+ choice.name = TQString::fromLatin1( "argl3" );
+ choice.label = i18n("Argl3 Label");
+ choice.whatsThis = i18n("Argl3 Whatsthis");
+ valuesDestination.append( choice );
+ }
+ d->destinationItem = new TDEConfigSkeleton::ItemEnum( currentGroup(), TQString::fromLatin1( "Destination" ), d->destination, valuesDestination, EnumDestination::standardDestination );
+ d->destinationItem->setLabel( i18n("New Events/Todos Should") );
+ addItem( d->destinationItem, TQString::fromLatin1( "Destination" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Views" ) );
+
+ d->hourSizeItem = new TDEConfigSkeleton::ItemInt( currentGroup(), TQString::fromLatin1( "Hour Size" ), d->hourSize, 10 );
+ d->hourSizeItem->setLabel( i18n("Hour Size") );
+ addItem( d->hourSizeItem, TQString::fromLatin1( "HourSize" ) );
+ d->selectionStartsEditorItem = new TDEConfigSkeleton::ItemBool( currentGroup(), TQString::fromLatin1( "SelectionStartsEditor" ), d->selectionStartsEditor, false );
+ d->selectionStartsEditorItem->setLabel( i18n("Time range selection in agenda view starts event editor") );
+ addItem( d->selectionStartsEditorItem, TQString::fromLatin1( "SelectionStartsEditor" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "KOrganizer Plugins" ) );
+
+ TQStringList defaultSelectedPlugins;
+ defaultSelectedPlugins.append( TQString::fromUtf8( "holidays" ) );
+ defaultSelectedPlugins.append( TQString::fromUtf8( "webexport" ) );
+
+ d->selectedPluginsItem = new TDEConfigSkeleton::ItemStringList( currentGroup(), TQString::fromLatin1( "SelectedPlugins" ), d->selectedPlugins, defaultSelectedPlugins );
+ d->selectedPluginsItem->setLabel( i18n("SelectedPlugins") );
+ addItem( d->selectedPluginsItem, TQString::fromLatin1( "SelectedPlugins" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Colors" ) );
+
+ d->highlightColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Highlight Color" ), d->highlightColor, TQColor( 100, 100, 255 ) );
+ d->highlightColorItem->setLabel( i18n("Highlight color") );
+ addItem( d->highlightColorItem, TQString::fromLatin1( "HighlightColor" ) );
+ d->agendaBgColorItem = new TDEConfigSkeleton::ItemColor( currentGroup(), TQString::fromLatin1( "Agenda Background Color" ), d->agendaBgColor, TQColor( 255, 255, 255 ) );
+ d->agendaBgColorItem->setLabel( i18n("Agenda view background color") );
+ addItem( d->agendaBgColorItem, TQString::fromLatin1( "AgendaBgColor" ) );
+
+ setCurrentGroup( TQString::fromLatin1( "Fonts" ) );
+
+ d->timeBarFontItem = new TDEConfigSkeleton::ItemFont( currentGroup(), TQString::fromLatin1( "TimeBar Font" ), d->timeBarFont );
+ d->timeBarFontItem->setLabel( i18n("Time bar") );
+ addItem( d->timeBarFontItem, TQString::fromLatin1( "TimeBarFont" ) );
+}
+
+void TestDPointer::setAutoSave( bool v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "AutoSave" ) ))
+ self()->d->autoSave = v;
+}
+
+bool TestDPointer::autoSave()
+{
+ return self()->d->autoSave;
+}
+
+
+TDEConfigSkeleton::ItemBool *TestDPointer::autoSaveItem()
+{
+ return d->autoSaveItem;
+}
+
+void TestDPointer::setAutoSaveInterval( int v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "AutoSaveInterval" ) ))
+ self()->d->autoSaveInterval = v;
+}
+
+int TestDPointer::autoSaveInterval()
+{
+ return self()->d->autoSaveInterval;
+}
+
+
+TDEConfigSkeleton::ItemInt *TestDPointer::autoSaveIntervalItem()
+{
+ return d->autoSaveIntervalItem;
+}
+
+void TestDPointer::setConfirm( bool v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "Confirm" ) ))
+ self()->d->confirm = v;
+}
+
+bool TestDPointer::confirm()
+{
+ return self()->d->confirm;
+}
+
+
+TDEConfigSkeleton::ItemBool *TestDPointer::confirmItem()
+{
+ return d->confirmItem;
+}
+
+void TestDPointer::setArchiveFile( const TQString & v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "ArchiveFile" ) ))
+ self()->d->archiveFile = v;
+}
+
+TQString TestDPointer::archiveFile()
+{
+ return self()->d->archiveFile;
+}
+
+
+TDEConfigSkeleton::ItemString *TestDPointer::archiveFileItem()
+{
+ return d->archiveFileItem;
+}
+
+void TestDPointer::setDestination( int v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "Destination" ) ))
+ self()->d->destination = v;
+}
+
+int TestDPointer::destination()
+{
+ return self()->d->destination;
+}
+
+
+TDEConfigSkeleton::ItemEnum *TestDPointer::destinationItem()
+{
+ return d->destinationItem;
+}
+
+void TestDPointer::setHourSize( int v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "HourSize" ) ))
+ self()->d->hourSize = v;
+}
+
+int TestDPointer::hourSize()
+{
+ return self()->d->hourSize;
+}
+
+
+TDEConfigSkeleton::ItemInt *TestDPointer::hourSizeItem()
+{
+ return d->hourSizeItem;
+}
+
+void TestDPointer::setSelectionStartsEditor( bool v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "SelectionStartsEditor" ) ))
+ self()->d->selectionStartsEditor = v;
+}
+
+bool TestDPointer::selectionStartsEditor()
+{
+ return self()->d->selectionStartsEditor;
+}
+
+
+TDEConfigSkeleton::ItemBool *TestDPointer::selectionStartsEditorItem()
+{
+ return d->selectionStartsEditorItem;
+}
+
+void TestDPointer::setSelectedPlugins( const TQStringList & v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "SelectedPlugins" ) ))
+ self()->d->selectedPlugins = v;
+}
+
+TQStringList TestDPointer::selectedPlugins()
+{
+ return self()->d->selectedPlugins;
+}
+
+
+TDEConfigSkeleton::ItemStringList *TestDPointer::selectedPluginsItem()
+{
+ return d->selectedPluginsItem;
+}
+
+void TestDPointer::setHighlightColor( const TQColor & v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "HighlightColor" ) ))
+ self()->d->highlightColor = v;
+}
+
+TQColor TestDPointer::highlightColor()
+{
+ return self()->d->highlightColor;
+}
+
+
+TDEConfigSkeleton::ItemColor *TestDPointer::highlightColorItem()
+{
+ return d->highlightColorItem;
+}
+
+void TestDPointer::setAgendaBgColor( const TQColor & v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "AgendaBgColor" ) ))
+ self()->d->agendaBgColor = v;
+}
+
+TQColor TestDPointer::agendaBgColor()
+{
+ return self()->d->agendaBgColor;
+}
+
+
+TDEConfigSkeleton::ItemColor *TestDPointer::agendaBgColorItem()
+{
+ return d->agendaBgColorItem;
+}
+
+void TestDPointer::setTimeBarFont( const TQFont & v )
+{
+ if (!self()->isImmutable( TQString::fromLatin1( "TimeBarFont" ) ))
+ self()->d->timeBarFont = v;
+}
+
+TQFont TestDPointer::timeBarFont()
+{
+ return self()->d->timeBarFont;
+}
+
+
+TDEConfigSkeleton::ItemFont *TestDPointer::timeBarFontItem()
+{
+ return d->timeBarFontItem;
+}
+
+TestDPointer::~TestDPointer()
+{
+ delete d;
+ if ( mSelf == this )
+ staticTestDPointerDeleter.setObject( mSelf, 0, false );
+}
+
diff --git a/tdecore/tdeconfig_compiler/tests/test_dpointer.h.ref b/tdecore/tdeconfig_compiler/tests/test_dpointer.h.ref
new file mode 100644
index 000000000..0bd7e771e
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test_dpointer.h.ref
@@ -0,0 +1,224 @@
+// This file is generated by tdeconfig_compiler from test_dpointer.kcfg.
+// All changes you do to this file will be lost.
+#ifndef TESTDPOINTER_H
+#define TESTDPOINTER_H
+
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+
+class TestDPointerPrivate;
+
+class TestDPointer : public TDEConfigSkeleton
+{
+ public:
+ class EnumDestination
+ {
+ public:
+ enum type { standardDestination, askDestination, argl1, argl2, argl3, COUNT };
+ };
+
+ static TestDPointer *self();
+ ~TestDPointer();
+
+ /**
+ Set Enable automatic saving of calendar
+ */
+ static
+ void setAutoSave( bool v );
+
+ /**
+ Get Enable automatic saving of calendar
+ */
+ static
+ bool autoSave();
+
+ /**
+ Get Item object corresponding to AutoSave()
+ */
+ ItemBool *autoSaveItem();
+
+ /**
+ Set Auto Save Interval
+ */
+ static
+ void setAutoSaveInterval( int v );
+
+ /**
+ Get Auto Save Interval
+ */
+ static
+ int autoSaveInterval();
+
+ /**
+ Get Item object corresponding to AutoSaveInterval()
+ */
+ ItemInt *autoSaveIntervalItem();
+
+ /**
+ Set Confirm deletes
+ */
+ static
+ void setConfirm( bool v );
+
+ /**
+ Get Confirm deletes
+ */
+ static
+ bool confirm();
+
+ /**
+ Get Item object corresponding to Confirm()
+ */
+ ItemBool *confirmItem();
+
+ /**
+ Set Archive File
+ */
+ static
+ void setArchiveFile( const TQString & v );
+
+ /**
+ Get Archive File
+ */
+ static
+ TQString archiveFile();
+
+ /**
+ Get Item object corresponding to ArchiveFile()
+ */
+ ItemString *archiveFileItem();
+
+ /**
+ Set New Events/Todos Should
+ */
+ static
+ void setDestination( int v );
+
+ /**
+ Get New Events/Todos Should
+ */
+ static
+ int destination();
+
+ /**
+ Get Item object corresponding to Destination()
+ */
+ ItemEnum *destinationItem();
+
+ /**
+ Set Hour Size
+ */
+ static
+ void setHourSize( int v );
+
+ /**
+ Get Hour Size
+ */
+ static
+ int hourSize();
+
+ /**
+ Get Item object corresponding to HourSize()
+ */
+ ItemInt *hourSizeItem();
+
+ /**
+ Set Time range selection in agenda view starts event editor
+ */
+ static
+ void setSelectionStartsEditor( bool v );
+
+ /**
+ Get Time range selection in agenda view starts event editor
+ */
+ static
+ bool selectionStartsEditor();
+
+ /**
+ Get Item object corresponding to SelectionStartsEditor()
+ */
+ ItemBool *selectionStartsEditorItem();
+
+ /**
+ Set SelectedPlugins
+ */
+ static
+ void setSelectedPlugins( const TQStringList & v );
+
+ /**
+ Get SelectedPlugins
+ */
+ static
+ TQStringList selectedPlugins();
+
+ /**
+ Get Item object corresponding to SelectedPlugins()
+ */
+ ItemStringList *selectedPluginsItem();
+
+ /**
+ Set Highlight color
+ */
+ static
+ void setHighlightColor( const TQColor & v );
+
+ /**
+ Get Highlight color
+ */
+ static
+ TQColor highlightColor();
+
+ /**
+ Get Item object corresponding to HighlightColor()
+ */
+ ItemColor *highlightColorItem();
+
+ /**
+ Set Agenda view background color
+ */
+ static
+ void setAgendaBgColor( const TQColor & v );
+
+ /**
+ Get Agenda view background color
+ */
+ static
+ TQColor agendaBgColor();
+
+ /**
+ Get Item object corresponding to AgendaBgColor()
+ */
+ ItemColor *agendaBgColorItem();
+
+ /**
+ Set Time bar
+ */
+ static
+ void setTimeBarFont( const TQFont & v );
+
+ /**
+ Get Time bar
+ */
+ static
+ TQFont timeBarFont();
+
+ /**
+ Get Item object corresponding to TimeBarFont()
+ */
+ ItemFont *timeBarFontItem();
+
+ static
+ void writeConfig()
+ {
+ static_cast<TDEConfigSkeleton*>(self())->writeConfig();
+ }
+ protected:
+ TestDPointer();
+ static TestDPointer *mSelf;
+
+ private:
+ TestDPointerPrivate *d;
+};
+
+#endif
+
diff --git a/tdecore/kconfig_compiler/tests/test_dpointer.kcfg b/tdecore/tdeconfig_compiler/tests/test_dpointer.kcfg
index 3b19e270e..3b19e270e 100644
--- a/tdecore/kconfig_compiler/tests/test_dpointer.kcfg
+++ b/tdecore/tdeconfig_compiler/tests/test_dpointer.kcfg
diff --git a/tdecore/tdeconfig_compiler/tests/test_dpointer.kcfgc b/tdecore/tdeconfig_compiler/tests/test_dpointer.kcfgc
new file mode 100644
index 000000000..83f4bce3b
--- /dev/null
+++ b/tdecore/tdeconfig_compiler/tests/test_dpointer.kcfgc
@@ -0,0 +1,11 @@
+# Code generation options for tdeconfig_compiler
+File=test_dpointer.kcfg
+ClassName=TestDPointer
+Singleton=true
+Mutators=true
+#Inherits=MyPrefs
+#IncludeFiles=myprefs.h
+MemberVariables=dpointer
+#GlobalEnums=true
+ItemAccessors=true
+SetUserTexts=true
diff --git a/tdecore/kconfig_compiler/tests/test_dpointer_main.cpp b/tdecore/tdeconfig_compiler/tests/test_dpointer_main.cpp
index b62ee17af..b62ee17af 100644
--- a/tdecore/kconfig_compiler/tests/test_dpointer_main.cpp
+++ b/tdecore/tdeconfig_compiler/tests/test_dpointer_main.cpp
diff --git a/tdecore/tdeconfigbackend.cpp b/tdecore/tdeconfigbackend.cpp
new file mode 100644
index 000000000..5074f8d22
--- /dev/null
+++ b/tdecore/tdeconfigbackend.cpp
@@ -0,0 +1,1190 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Preston Brown <pbrown@kde.org>
+ Copyright (c) 1997-1999 Matthias Kalle Dalheimer <kalle@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <config.h>
+
+#include <unistd.h>
+#include <ctype.h>
+#ifdef HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+#include <sys/types.h>
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+#include <fcntl.h>
+#include <signal.h>
+#include <setjmp.h>
+
+#include <tqdir.h>
+#include <tqfileinfo.h>
+#include <tqtextcodec.h>
+#include <tqtextstream.h>
+
+#include "tdeconfigbackend.h"
+#include "tdeconfigbase.h"
+#include <kapplication.h>
+#include <kglobal.h>
+#include <kprocess.h>
+#include <klocale.h>
+#include <kstandarddirs.h>
+#include <ksavefile.h>
+#include <kurl.h>
+#include <kde_file.h>
+
+extern bool checkAccess(const TQString& pathname, int mode);
+/* translate escaped escape sequences to their actual values. */
+static TQCString printableToString(const char *str, int l)
+{
+ // Strip leading white-space.
+ while((l>0) &&
+ ((*str == ' ') || (*str == '\t') || (*str == '\r')))
+ {
+ str++; l--;
+ }
+
+ // Strip trailing white-space.
+ while((l>0) &&
+ ((str[l-1] == ' ') || (str[l-1] == '\t') || (str[l-1] == '\r')))
+ {
+ l--;
+ }
+
+ TQCString result(l + 1);
+ char *r = result.data();
+
+ for(int i = 0; i < l;i++, str++)
+ {
+ if (*str == '\\')
+ {
+ i++, str++;
+ if (i >= l) // End of line. (Line ends with single slash)
+ {
+ *r++ = '\\';
+ break;
+ }
+ switch(*str)
+ {
+ case 's':
+ *r++ = ' ';
+ break;
+ case 't':
+ *r++ = '\t';
+ break;
+ case 'n':
+ *r++ = '\n';
+ break;
+ case 'r':
+ *r++ = '\r';
+ break;
+ case '\\':
+ *r++ = '\\';
+ break;
+ default:
+ *r++ = '\\';
+ *r++ = *str;
+ }
+ }
+ else
+ {
+ *r++ = *str;
+ }
+ }
+ result.truncate(r-result.data());
+ return result;
+}
+
+static TQCString stringToPrintable(const TQCString& str){
+ TQCString result(str.length()*2); // Maximum 2x as long as source string
+ register char *r = const_cast<TQCString&>(result).data();
+ register char *s = const_cast<TQCString&>(str).data();
+
+ if (!s) return TQCString("");
+
+ // Escape leading space
+ if (*s == ' ')
+ {
+ *r++ = '\\'; *r++ = 's';
+ s++;
+ }
+
+ if (*s)
+ {
+ while(*s)
+ {
+ if (*s == '\n')
+ {
+ *r++ = '\\'; *r++ = 'n';
+ }
+ else if (*s == '\t')
+ {
+ *r++ = '\\'; *r++ = 't';
+ }
+ else if (*s == '\r')
+ {
+ *r++ = '\\'; *r++ = 'r';
+ }
+ else if (*s == '\\')
+ {
+ *r++ = '\\'; *r++ = '\\';
+ }
+ else
+ {
+ *r++ = *s;
+ }
+ s++;
+ }
+ // Escape trailing space
+ if (*(r-1) == ' ')
+ {
+ *(r-1) = '\\'; *r++ = 's';
+ }
+ }
+
+ result.truncate(r - result.data());
+ return result;
+}
+
+static TQCString decodeGroup(const char*s, int l)
+{
+ TQCString result(l);
+ register char *r = result.data();
+
+ l--; // Correct for trailing \0
+ while(l)
+ {
+ if ((*s == '[') && (l > 1))
+ {
+ if ((*(s+1) == '['))
+ {
+ l--;
+ s++;
+ }
+ }
+ if ((*s == ']') && (l > 1))
+ {
+ if ((*(s+1) == ']'))
+ {
+ l--;
+ s++;
+ }
+ }
+ *r++ = *s++;
+ l--;
+ }
+ result.truncate(r - result.data());
+ return result;
+}
+
+static TQCString encodeGroup(const TQCString &str)
+{
+ int l = str.length();
+ TQCString result(l*2+1);
+ register char *r = const_cast<TQCString&>(result).data();
+ register char *s = const_cast<TQCString&>(str).data();
+ while(l)
+ {
+ if ((*s == '[') || (*s == ']'))
+ *r++ = *s;
+ *r++ = *s++;
+ l--;
+ }
+ result.truncate(r - result.data());
+ return result;
+}
+
+static TQCString encodeKey(const char* key)
+{
+ TQCString newKey(key);
+
+ newKey.replace('[', "%5b");
+ newKey.replace(']', "%5d");
+
+ return newKey;
+}
+
+static TQCString decodeKey(const char* key)
+{
+ TQCString newKey(key);
+
+ newKey.replace("%5b", "[");
+ newKey.replace("%5d", "]");
+
+ return newKey;
+}
+
+class TDEConfigBackEnd::TDEConfigBackEndPrivate
+{
+public:
+ TQDateTime localLastModified;
+ uint localLastSize;
+ KLockFile::Ptr localLockFile;
+ KLockFile::Ptr globalLockFile;
+};
+
+void TDEConfigBackEnd::changeFileName(const TQString &_fileName,
+ const char * _resType,
+ bool _useKDEGlobals)
+{
+ mfileName = _fileName;
+ resType = _resType;
+ useKDEGlobals = _useKDEGlobals;
+ if (mfileName.isEmpty()) {
+ mLocalFileName = TQString::null;
+ }
+ else if (!TQDir::isRelativePath(mfileName)) {
+ mLocalFileName = mfileName;
+ }
+ else {
+ mLocalFileName = TDEGlobal::dirs()->saveLocation(resType, TQString(), false) + mfileName;
+ }
+
+ if (useKDEGlobals) {
+ mGlobalFileName = TDEGlobal::dirs()->saveLocation("config", TQString(), false) + TQString::fromLatin1("kdeglobals");
+ }
+ else {
+ mGlobalFileName = TQString::null;
+ }
+
+ d->localLastModified = TQDateTime();
+ d->localLastSize = 0;
+ d->localLockFile = 0;
+ d->globalLockFile = 0;
+}
+
+KLockFile::Ptr TDEConfigBackEnd::lockFile(bool bGlobal)
+{
+ if (bGlobal)
+ {
+ if (d->globalLockFile)
+ return d->globalLockFile;
+
+ if (!mGlobalFileName.isEmpty())
+ {
+ d->globalLockFile = new KLockFile(mGlobalFileName+".lock");
+ return d->globalLockFile;
+ }
+ }
+ else
+ {
+ if (d->localLockFile)
+ return d->localLockFile;
+
+ if (!mLocalFileName.isEmpty())
+ {
+ d->localLockFile = new KLockFile(mLocalFileName+".lock");
+ return d->localLockFile;
+ }
+ }
+ return 0;
+}
+
+TDEConfigBackEnd::TDEConfigBackEnd(TDEConfigBase *_config,
+ const TQString &_fileName,
+ const char * _resType,
+ bool _useKDEGlobals)
+ : pConfig(_config), bFileImmutable(false), mConfigState(TDEConfigBase::NoAccess), mFileMode(-1)
+{
+ d = new TDEConfigBackEndPrivate;
+ changeFileName(_fileName, _resType, _useKDEGlobals);
+}
+
+TDEConfigBackEnd::~TDEConfigBackEnd()
+{
+ delete d;
+}
+
+void TDEConfigBackEnd::setFileWriteMode(int mode)
+{
+ mFileMode = mode;
+}
+
+bool TDEConfigINIBackEnd::parseConfigFiles()
+{
+ // Check if we can write to the local file.
+ mConfigState = TDEConfigBase::ReadOnly;
+ if (!mLocalFileName.isEmpty() && !pConfig->isReadOnly())
+ {
+ if (checkAccess(mLocalFileName, W_OK))
+ {
+ mConfigState = TDEConfigBase::ReadWrite;
+ }
+ else
+ {
+ // Create the containing dir, maybe it wasn't there
+ KURL path;
+ path.setPath(mLocalFileName);
+ TQString dir=path.directory();
+ KStandardDirs::makeDir(dir);
+
+ if (checkAccess(mLocalFileName, W_OK))
+ {
+ mConfigState = TDEConfigBase::ReadWrite;
+ }
+ }
+ TQFileInfo info(mLocalFileName);
+ d->localLastModified = info.lastModified();
+ d->localLastSize = info.size();
+ }
+
+ // Parse all desired files from the least to the most specific.
+ bFileImmutable = false;
+
+ // Parse the general config files
+ if (useKDEGlobals) {
+ TQStringList kdercs = TDEGlobal::dirs()->
+ findAllResources("config", TQString::fromLatin1("kdeglobals"));
+
+#ifdef Q_WS_WIN
+ TQString etc_kderc = TQFile::decodeName( TQCString(getenv("WINDIR")) + "\\kderc" );
+#else
+ TQString etc_kderc = TQString::fromLatin1("/etc/kderc");
+#endif
+
+ if (checkAccess(etc_kderc, R_OK))
+ kdercs += etc_kderc;
+
+ kdercs += TDEGlobal::dirs()->
+ findAllResources("config", TQString::fromLatin1("system.kdeglobals"));
+
+ TQStringList::ConstIterator it;
+
+ for (it = kdercs.fromLast(); it != kdercs.end(); --it) {
+
+ TQFile aConfigFile( *it );
+ if (!aConfigFile.open( IO_ReadOnly ))
+ continue;
+ parseSingleConfigFile( aConfigFile, 0L, true, (*it != mGlobalFileName) );
+ aConfigFile.close();
+ if (bFileImmutable)
+ break;
+ }
+ }
+
+ bool bReadFile = !mfileName.isEmpty();
+ while(bReadFile) {
+ bReadFile = false;
+ TQString bootLanguage;
+ if (useKDEGlobals && localeString.isEmpty() && !TDEGlobal::_locale) {
+ // Boot strap language
+ bootLanguage = KLocale::_initLanguage(pConfig);
+ setLocaleString(bootLanguage.utf8());
+ }
+
+ bFileImmutable = false;
+ TQStringList list;
+ if ( !TQDir::isRelativePath(mfileName) )
+ list << mfileName;
+ else
+ list = TDEGlobal::dirs()->findAllResources(resType, mfileName);
+
+ TQStringList::ConstIterator it;
+
+ for (it = list.fromLast(); it != list.end(); --it) {
+
+ TQFile aConfigFile( *it );
+ // we can already be sure that this file exists
+ bool bIsLocal = (*it == mLocalFileName);
+ if (aConfigFile.open( IO_ReadOnly )) {
+ parseSingleConfigFile( aConfigFile, 0L, false, !bIsLocal );
+ aConfigFile.close();
+ if (bFileImmutable)
+ break;
+ }
+ }
+ if (TDEGlobal::dirs()->isRestrictedResource(resType, mfileName))
+ bFileImmutable = true;
+ TQString currentLanguage;
+ if (!bootLanguage.isEmpty())
+ {
+ currentLanguage = KLocale::_initLanguage(pConfig);
+ // If the file changed the language, we need to read the file again
+ // with the new language setting.
+ if (bootLanguage != currentLanguage)
+ {
+ bReadFile = true;
+ setLocaleString(currentLanguage.utf8());
+ }
+ }
+ }
+ if (bFileImmutable)
+ mConfigState = TDEConfigBase::ReadOnly;
+
+ return true;
+}
+
+#ifdef HAVE_MMAP
+#ifdef SIGBUS
+static sigjmp_buf mmap_jmpbuf;
+struct sigaction mmap_old_sigact;
+
+extern "C" {
+ static void mmap_sigbus_handler(int)
+ {
+ siglongjmp (mmap_jmpbuf, 1);
+ }
+}
+#endif
+#endif
+
+extern bool kde_kiosk_exception;
+
+void TDEConfigINIBackEnd::parseSingleConfigFile(TQFile &rFile,
+ KEntryMap *pWriteBackMap,
+ bool bGlobal, bool bDefault)
+{
+ const char *s; // May get clobbered by sigsetjump, but we don't use them afterwards.
+ const char *eof; // May get clobbered by sigsetjump, but we don't use them afterwards.
+ TQByteArray data;
+
+ if (!rFile.isOpen()) // come back, if you have real work for us ;->
+ return;
+
+ //using kdDebug() here leads to an infinite loop
+ //remove this for the release, aleXXX
+ //tqWarning("Parsing %s, global = %s default = %s",
+ // rFile.name().latin1(), bGlobal ? "true" : "false", bDefault ? "true" : "false");
+
+ TQCString aCurrentGroup("<default>");
+
+ unsigned int ll = localeString.length();
+
+#ifdef HAVE_MMAP
+ static volatile const char *map;
+ map = ( const char* ) mmap(0, rFile.size(), PROT_READ, MAP_PRIVATE,
+ rFile.handle(), 0);
+
+ if ( map != MAP_FAILED )
+ {
+ s = (const char*) map;
+ eof = s + rFile.size();
+
+#ifdef SIGBUS
+ struct sigaction act;
+ act.sa_handler = mmap_sigbus_handler;
+ sigemptyset( &act.sa_mask );
+#ifdef SA_ONESHOT
+ act.sa_flags = SA_ONESHOT;
+#else
+ act.sa_flags = SA_RESETHAND;
+#endif
+ sigaction( SIGBUS, &act, &mmap_old_sigact );
+
+ if (sigsetjmp (mmap_jmpbuf, 1))
+ {
+tqWarning("SIGBUS while reading %s", rFile.name().latin1());
+ munmap(( char* )map, rFile.size());
+ sigaction (SIGBUS, &mmap_old_sigact, 0);
+ return;
+ }
+#endif
+ }
+ else
+#endif
+ {
+ rFile.at(0);
+ data = rFile.readAll();
+ s = data.data();
+ eof = s + data.size();
+ }
+
+ bool fileOptionImmutable = false;
+ bool groupOptionImmutable = false;
+ bool groupSkip = false;
+ bool foundGettextDomain = false;
+ TQCString gettextDomain;
+
+ int line = 0;
+ for(; s < eof; s++)
+ {
+ line++;
+
+ while((s < eof) && isspace(*s) && (*s != '\n'))
+ s++; //skip leading whitespace, shouldn't happen too often
+
+ //skip empty lines, lines starting with #
+ if ((s < eof) && ((*s == '\n') || (*s == '#')))
+ {
+ sktoeol: //skip till end-of-line
+ while ((s < eof) && (*s != '\n'))
+ s++;
+ continue; // Empty or comment or no keyword
+ }
+ const char *startLine = s;
+
+ if (*s == '[') //group
+ {
+ // In a group [[ and ]] have a special meaning
+ while ((s < eof) && (*s != '\n'))
+ {
+ if (*s == ']')
+ {
+ if ((s+1 < eof) && (*(s+1) == ']'))
+ s++; // Skip "]]"
+ else
+ break;
+ }
+
+ s++; // Search till end of group
+ }
+ const char *e = s;
+ while ((s < eof) && (*s != '\n')) s++; // Search till end of line / end of file
+ if ((e >= eof) || (*e != ']'))
+ {
+ fprintf(stderr, "Invalid group header at %s:%d\n", rFile.name().latin1(), line);
+ continue;
+ }
+ // group found; get the group name by taking everything in
+ // between the brackets
+ if ((e-startLine == 3) &&
+ (startLine[1] == '$') &&
+ (startLine[2] == 'i'))
+ {
+ if (!kde_kiosk_exception)
+ fileOptionImmutable = true;
+ continue;
+ }
+
+ aCurrentGroup = decodeGroup(startLine + 1, e - startLine);
+ //cout<<"found group ["<<aCurrentGroup<<"]"<<endl;
+
+ // Backwards compatibility
+ if (aCurrentGroup == "KDE Desktop Entry")
+ aCurrentGroup = "Desktop Entry";
+
+ groupOptionImmutable = fileOptionImmutable;
+
+ e++;
+ if ((e+2 < eof) && (*e++ == '[') && (*e++ == '$')) // Option follows
+ {
+ if ((*e == 'i') && !kde_kiosk_exception)
+ {
+ groupOptionImmutable = true;
+ }
+ }
+
+ KEntryKey groupKey(aCurrentGroup, 0);
+ KEntry entry = pConfig->lookupData(groupKey);
+ groupSkip = entry.bImmutable;
+
+ if (groupSkip && !bDefault)
+ continue;
+
+ entry.bImmutable |= groupOptionImmutable;
+ pConfig->putData(groupKey, entry, false);
+
+ if (pWriteBackMap)
+ {
+ // add the special group key indicator
+ (*pWriteBackMap)[groupKey] = entry;
+ }
+
+ continue;
+ }
+ if (groupSkip && !bDefault)
+ goto sktoeol; // Skip entry
+
+
+ bool optionImmutable = groupOptionImmutable;
+ bool optionDeleted = false;
+ bool optionExpand = false;
+ const char *endOfKey = 0, *locale = 0, *elocale = 0;
+ for (; (s < eof) && (*s != '\n'); s++)
+ {
+ if (*s == '=') //find the equal sign
+ {
+ if (!endOfKey)
+ endOfKey = s;
+ goto haveeq;
+ }
+ if (*s == '[') //find the locale or options.
+ {
+ const char *option;
+ const char *eoption;
+ endOfKey = s;
+ option = ++s;
+ for (;; s++)
+ {
+ if ((s >= eof) || (*s == '\n') || (*s == '=')) {
+ fprintf(stderr, "Invalid entry (missing ']') at %s:%d\n", rFile.name().latin1(), line);
+ goto sktoeol;
+ }
+ if (*s == ']')
+ break;
+ }
+ eoption = s;
+ if (*option != '$')
+ {
+ // Locale
+ if (locale) {
+ fprintf(stderr, "Invalid entry (second locale!?) at %s:%d\n", rFile.name().latin1(), line);
+ goto sktoeol;
+ }
+ locale = option;
+ elocale = eoption;
+ }
+ else
+ {
+ // Option
+ while (option < eoption)
+ {
+ option++;
+ if ((*option == 'i') && !kde_kiosk_exception)
+ optionImmutable = true;
+ else if (*option == 'e')
+ optionExpand = true;
+ else if (*option == 'd')
+ {
+ optionDeleted = true;
+ goto haveeq;
+ }
+ else if (*option == ']')
+ break;
+ }
+ }
+ }
+ }
+ fprintf(stderr, "Invalid entry (missing '=') at %s:%d\n", rFile.name().latin1(), line);
+ continue;
+
+ haveeq:
+ for (endOfKey--; ; endOfKey--)
+ {
+ if (endOfKey < startLine)
+ {
+ fprintf(stderr, "Invalid entry (empty key) at %s:%d\n", rFile.name().latin1(), line);
+ goto sktoeol;
+ }
+ if (!isspace(*endOfKey))
+ break;
+ }
+
+ const char *st = ++s;
+ while ((s < eof) && (*s != '\n')) s++; // Search till end of line / end of file
+
+ if (locale) {
+ unsigned int cl = static_cast<unsigned int>(elocale - locale);
+ if ((ll != cl) || memcmp(locale, localeString.data(), ll))
+ {
+ // backward compatibility. C == en_US
+ if ( cl != 1 || ll != 5 || *locale != 'C' || memcmp(localeString.data(), "en_US", 5)) {
+ //cout<<"mismatched locale '"<<TQCString(locale, elocale-locale +1)<<"'"<<endl;
+ // We can ignore this one
+ if (!pWriteBackMap)
+ continue; // We just ignore it
+ // We just store it as is to be able to write it back later.
+ endOfKey = elocale;
+ locale = 0;
+ }
+ }
+ }
+
+ // insert the key/value line
+ TQCString key(startLine, endOfKey - startLine + 2);
+ TQCString val = printableToString(st, s - st);
+ //tqDebug("found key '%s' with value '%s'", key.data(), val.data());
+
+ if (TQString(key.data()) == "X-Ubuntu-Gettext-Domain") {
+ gettextDomain = val.data();
+ foundGettextDomain = true;
+ }
+
+ KEntryKey aEntryKey(aCurrentGroup, decodeKey(key));
+ aEntryKey.bLocal = (locale != 0);
+ aEntryKey.bDefault = bDefault;
+
+ KEntry aEntry;
+ aEntry.mValue = val;
+ aEntry.bGlobal = bGlobal;
+ aEntry.bImmutable = optionImmutable;
+ aEntry.bDeleted = optionDeleted;
+ aEntry.bExpand = optionExpand;
+ aEntry.bNLS = (locale != 0);
+
+ if (pWriteBackMap) {
+ // don't insert into the config object but into the temporary
+ // scratchpad map
+ pWriteBackMap->insert(aEntryKey, aEntry);
+ } else {
+ // directly insert value into config object
+ // no need to specify localization; if the key we just
+ // retrieved was localized already, no need to localize it again.
+ pConfig->putData(aEntryKey, aEntry, false);
+ }
+ }
+ // Look up translations using KLocale
+ // https://launchpad.net/distros/ubuntu/+spec/langpacks-desktopfiles-kde
+ // This calls KLocale up to 10 times for each config file (and each TDEConfig has up to 4 files)
+ // so I'll see how much of a performance hit it is
+ // it also only acts on the last group in a file
+ // Ideas: only translate most important fields, only translate "Desktop Entry" files,
+ // do translation per TDEConfig not per single file
+ if (!pWriteBackMap) {
+ TQFile file("file.txt");
+ if (foundGettextDomain) {
+
+ KLocale locale(gettextDomain);
+
+ TQString language = locale.language();
+ translateKey(locale, aCurrentGroup, TQCString("Name"));
+ translateKey(locale, aCurrentGroup, TQCString("Comment"));
+ translateKey(locale, aCurrentGroup, TQCString("Language"));
+ translateKey(locale, aCurrentGroup, TQCString("Keywords"));
+ translateKey(locale, aCurrentGroup, TQCString("About"));
+ translateKey(locale, aCurrentGroup, TQCString("Description"));
+ translateKey(locale, aCurrentGroup, TQCString("GenericName"));
+ translateKey(locale, aCurrentGroup, TQCString("Query"));
+ translateKey(locale, aCurrentGroup, TQCString("ExtraNames"));
+ translateKey(locale, aCurrentGroup, TQCString("X-TDE-Submenu"));
+ }
+ }
+
+
+ if (fileOptionImmutable)
+ bFileImmutable = true;
+
+#ifdef HAVE_MMAP
+ if (map)
+ {
+ munmap(( char* )map, rFile.size());
+#ifdef SIGBUS
+ sigaction (SIGBUS, &mmap_old_sigact, 0);
+#endif
+ }
+#endif
+}
+
+void TDEConfigINIBackEnd::translateKey(KLocale& locale, TQCString currentGroup, TQCString key) {
+ KEntryKey entryKey = KEntryKey(currentGroup, key);
+ KEntry entry = pConfig->lookupData(entryKey);
+ if (TQString(entry.mValue) != "") {
+ TQString orig = key + "=" + entry.mValue;
+ TQString translate = locale.translate(key + "=" + entry.mValue);
+ if (TQString::compare(orig, translate) != 0) {
+ translate = translate.mid(key.length() + 1);
+ entry.mValue = translate.utf8();
+ entryKey.bLocal = true;
+ entry.bNLS = true;
+ pConfig->putData(entryKey, entry, false);
+ }
+ }
+}
+
+void TDEConfigINIBackEnd::sync(bool bMerge)
+{
+ // write-sync is only necessary if there are dirty entries
+ if (!pConfig->isDirty())
+ return;
+
+ bool bEntriesLeft = true;
+
+ // find out the file to write to (most specific writable file)
+ // try local app-specific file first
+
+ if (!mfileName.isEmpty()) {
+ // Create the containing dir if needed
+ if ((resType!="config") && !TQDir::isRelativePath(mLocalFileName))
+ {
+ KURL path;
+ path.setPath(mLocalFileName);
+ TQString dir=path.directory();
+ KStandardDirs::makeDir(dir);
+ }
+
+ // Can we allow the write? We can, if the program
+ // doesn't run SUID. But if it runs SUID, we must
+ // check if the user would be allowed to write if
+ // it wasn't SUID.
+ if (checkAccess(mLocalFileName, W_OK)) {
+ // File is writable
+ KLockFile::Ptr lf;
+
+ bool mergeLocalFile = bMerge;
+ // Check if the file has been updated since.
+ if (mergeLocalFile)
+ {
+ lf = lockFile(false); // Lock file for local file
+ if (lf && lf->isLocked())
+ lf = 0; // Already locked, we don't need to lock/unlock again
+
+ if (lf)
+ {
+ lf->lock( KLockFile::LockForce );
+ // But what if the locking failed? Ignore it for now...
+ }
+
+ TQFileInfo info(mLocalFileName);
+ if ((d->localLastSize == info.size()) &&
+ (d->localLastModified == info.lastModified()))
+ {
+ // Not changed, don't merge.
+ mergeLocalFile = false;
+ }
+ else
+ {
+ // Changed...
+ d->localLastModified = TQDateTime();
+ d->localLastSize = 0;
+ }
+ }
+
+ bEntriesLeft = writeConfigFile( mLocalFileName, false, mergeLocalFile );
+
+ // Only if we didn't have to merge anything can we use our in-memory state
+ // the next time around. Otherwise the config-file may contain entries
+ // that are different from our in-memory state which means we will have to
+ // do a merge from then on.
+ // We do not automatically update the in-memory state with the on-disk
+ // state when writing the config to disk. We only do so when
+ // KCOnfig::reparseConfiguration() is called.
+ // For KDE 4.0 we may wish to reconsider that.
+ if (!mergeLocalFile)
+ {
+ TQFileInfo info(mLocalFileName);
+ d->localLastModified = info.lastModified();
+ d->localLastSize = info.size();
+ }
+ if (lf) lf->unlock();
+ }
+ }
+
+ // only write out entries to the kdeglobals file if there are any
+ // entries marked global (indicated by bEntriesLeft) and
+ // the useKDEGlobals flag is set.
+ if (bEntriesLeft && useKDEGlobals) {
+
+ // can we allow the write? (see above)
+ if (checkAccess ( mGlobalFileName, W_OK )) {
+ KLockFile::Ptr lf = lockFile(true); // Lock file for global file
+ if (lf && lf->isLocked())
+ lf = 0; // Already locked, we don't need to lock/unlock again
+
+ if (lf)
+ {
+ lf->lock( KLockFile::LockForce );
+ // But what if the locking failed? Ignore it for now...
+ }
+ writeConfigFile( mGlobalFileName, true, bMerge ); // Always merge
+ if (lf) lf->unlock();
+ }
+ }
+
+}
+
+static void writeEntries(FILE *pStream, const KEntryMap& entryMap, bool defaultGroup, bool &firstEntry, const TQCString &localeString)
+{
+ // now write out all other groups.
+ TQCString currentGroup;
+ for (KEntryMapConstIterator aIt = entryMap.begin();
+ aIt != entryMap.end(); ++aIt)
+ {
+ const KEntryKey &key = aIt.key();
+
+ // Either proces the default group or all others
+ if ((key.mGroup != "<default>") == defaultGroup)
+ continue; // Skip
+
+ // Skip default values and group headers.
+ if ((key.bDefault) || key.mKey.isEmpty())
+ continue; // Skip
+
+ const KEntry &currentEntry = *aIt;
+
+ KEntryMapConstIterator aTestIt = aIt;
+ ++aTestIt;
+ bool hasDefault = (aTestIt != entryMap.end());
+ if (hasDefault)
+ {
+ const KEntryKey &defaultKey = aTestIt.key();
+ if ((!defaultKey.bDefault) ||
+ (defaultKey.mKey != key.mKey) ||
+ (defaultKey.mGroup != key.mGroup) ||
+ (defaultKey.bLocal != key.bLocal))
+ hasDefault = false;
+ }
+
+
+ if (hasDefault)
+ {
+ // Entry had a default value
+ if ((currentEntry.mValue == (*aTestIt).mValue) &&
+ (currentEntry.bDeleted == (*aTestIt).bDeleted))
+ continue; // Same as default, don't write.
+ }
+ else
+ {
+ // Entry had no default value.
+ if (currentEntry.bDeleted)
+ continue; // Don't write deleted entries if there is no default.
+ }
+
+ if (!defaultGroup && (currentGroup != key.mGroup)) {
+ if (!firstEntry)
+ fprintf(pStream, "\n");
+ currentGroup = key.mGroup;
+ fprintf(pStream, "[%s]\n", encodeGroup(currentGroup).data());
+ }
+
+ firstEntry = false;
+ // it is data for a group
+ fputs(encodeKey(key.mKey.data()), pStream); // Key
+
+ if ( currentEntry.bNLS )
+ {
+ fputc('[', pStream);
+ fputs(localeString.data(), pStream);
+ fputc(']', pStream);
+ }
+
+ if (currentEntry.bDeleted)
+ {
+ fputs("[$d]\n", pStream); // Deleted
+ }
+ else
+ {
+ if (currentEntry.bImmutable || currentEntry.bExpand)
+ {
+ fputc('[', pStream);
+ fputc('$', pStream);
+ if (currentEntry.bImmutable)
+ fputc('i', pStream);
+ if (currentEntry.bExpand)
+ fputc('e', pStream);
+
+ fputc(']', pStream);
+ }
+ fputc('=', pStream);
+ fputs(stringToPrintable(currentEntry.mValue).data(), pStream);
+ fputc('\n', pStream);
+ }
+ } // for loop
+}
+
+bool TDEConfigINIBackEnd::getEntryMap(KEntryMap &aTempMap, bool bGlobal,
+ TQFile *mergeFile)
+{
+ bool bEntriesLeft = false;
+ bFileImmutable = false;
+
+ // Read entries from disk
+ if (mergeFile && mergeFile->open(IO_ReadOnly))
+ {
+ // fill the temporary structure with entries from the file
+ parseSingleConfigFile(*mergeFile, &aTempMap, bGlobal, false );
+
+ if (bFileImmutable) // File has become immutable on disk
+ return bEntriesLeft;
+ }
+
+ KEntryMap aMap = pConfig->internalEntryMap();
+
+ // augment this structure with the dirty entries from the config object
+ for (KEntryMapIterator aIt = aMap.begin();
+ aIt != aMap.end(); ++aIt)
+ {
+ const KEntry &currentEntry = *aIt;
+ if(aIt.key().bDefault)
+ {
+ aTempMap.replace(aIt.key(), currentEntry);
+ continue;
+ }
+
+ if (mergeFile && !currentEntry.bDirty)
+ continue;
+
+ // only write back entries that have the same
+ // "globality" as the file
+ if (currentEntry.bGlobal != bGlobal)
+ {
+ // wrong "globality" - might have to be saved later
+ bEntriesLeft = true;
+ continue;
+ }
+
+ // put this entry from the config object into the
+ // temporary map, possibly replacing an existing entry
+ KEntryMapIterator aIt2 = aTempMap.find(aIt.key());
+ if (aIt2 != aTempMap.end() && (*aIt2).bImmutable)
+ continue; // Bail out if the on-disk entry is immutable
+
+ aTempMap.insert(aIt.key(), currentEntry, true);
+ } // loop
+
+ return bEntriesLeft;
+}
+
+/* antlarr: KDE 4.0: make the first parameter "const TQString &" */
+bool TDEConfigINIBackEnd::writeConfigFile(TQString filename, bool bGlobal,
+ bool bMerge)
+{
+ // is the config object read-only?
+ if (pConfig->isReadOnly())
+ return true; // pretend we wrote it
+
+ KEntryMap aTempMap;
+ TQFile *mergeFile = (bMerge ? new TQFile(filename) : 0);
+ bool bEntriesLeft = getEntryMap(aTempMap, bGlobal, mergeFile);
+ delete mergeFile;
+ if (bFileImmutable)
+ return true; // pretend we wrote it
+
+ // OK now the temporary map should be full of ALL entries.
+ // write it out to disk.
+
+ // Check if file exists:
+ int fileMode = -1;
+ bool createNew = true;
+
+ KDE_struct_stat buf;
+ if (KDE_stat(TQFile::encodeName(filename), &buf) == 0)
+ {
+ if (buf.st_uid == getuid())
+ {
+ // Preserve file mode if file exists and is owned by user.
+ fileMode = buf.st_mode & 0777;
+ }
+ else
+ {
+ // File is not owned by user:
+ // Don't create new file but write to existing file instead.
+ createNew = false;
+ }
+ }
+
+ KSaveFile *pConfigFile = 0;
+ FILE *pStream = 0;
+
+ if (createNew)
+ {
+ pConfigFile = new KSaveFile( filename, 0600 );
+
+ if (pConfigFile->status() != 0)
+ {
+ delete pConfigFile;
+ return bEntriesLeft;
+ }
+
+ if (!bGlobal && (fileMode == -1))
+ fileMode = mFileMode;
+
+ if (fileMode != -1)
+ {
+ fchmod(pConfigFile->handle(), fileMode);
+ }
+
+ pStream = pConfigFile->fstream();
+ }
+ else
+ {
+ // Open existing file.
+ // We use open() to ensure that we call without O_CREAT.
+ int fd = KDE_open( TQFile::encodeName(filename), O_WRONLY | O_TRUNC );
+ if (fd < 0)
+ {
+ return bEntriesLeft;
+ }
+ pStream = KDE_fdopen( fd, "w");
+ if (!pStream)
+ {
+ close(fd);
+ return bEntriesLeft;
+ }
+ }
+
+ writeEntries(pStream, aTempMap);
+
+ if (pConfigFile)
+ {
+ bool bEmptyFile = (ftell(pStream) == 0);
+ if ( bEmptyFile && ((fileMode == -1) || (fileMode == 0600)) )
+ {
+ // File is empty and doesn't have special permissions: delete it.
+ ::unlink(TQFile::encodeName(filename));
+ pConfigFile->abort();
+ }
+ else
+ {
+ // Normal case: Close the file
+ pConfigFile->close();
+ }
+ delete pConfigFile;
+ }
+ else
+ {
+ fclose(pStream);
+ }
+
+ return bEntriesLeft;
+}
+
+void TDEConfigINIBackEnd::writeEntries(FILE *pStream, const KEntryMap &aTempMap)
+{
+ bool firstEntry = true;
+
+ // Write default group
+ ::writeEntries(pStream, aTempMap, true, firstEntry, localeString);
+
+ // Write all other groups
+ ::writeEntries(pStream, aTempMap, false, firstEntry, localeString);
+}
+
+void TDEConfigBackEnd::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+void TDEConfigINIBackEnd::virtual_hook( int id, void* data )
+{ TDEConfigBackEnd::virtual_hook( id, data ); }
+
+bool TDEConfigBackEnd::checkConfigFilesWritable(bool warnUser)
+{
+ // WARNING: Do NOT use the event loop as it may not exist at this time.
+ bool allWritable = true;
+ TQString errorMsg;
+ if ( !mLocalFileName.isEmpty() && !bFileImmutable && !checkAccess(mLocalFileName,W_OK) )
+ {
+ errorMsg = i18n("Will not save configuration.\n");
+ allWritable = false;
+ errorMsg += i18n("Configuration file \"%1\" not writable.\n").arg(mLocalFileName);
+ }
+ // We do not have an immutability flag for kdeglobals. However, making kdeglobals mutable while making
+ // the local config file immutable is senseless.
+ if ( !mGlobalFileName.isEmpty() && useKDEGlobals && !bFileImmutable && !checkAccess(mGlobalFileName,W_OK) )
+ {
+ if ( errorMsg.isEmpty() )
+ errorMsg = i18n("Will not save configuration.\n");
+ errorMsg += i18n("Configuration file \"%1\" not writable.\n").arg(mGlobalFileName);
+ allWritable = false;
+ }
+
+ if (warnUser && !allWritable)
+ {
+ // Note: We don't ask the user if we should not ask this question again because we can't save the answer.
+ errorMsg += i18n("Please contact your system administrator.");
+ TQString cmdToExec = KStandardDirs::findExe(TQString("kdialog"));
+ TDEApplication *app = kapp;
+ if (!cmdToExec.isEmpty() && app)
+ {
+ TDEProcess lprocess;
+ lprocess << cmdToExec << "--title" << app->instanceName() << "--msgbox" << TQCString(errorMsg.local8Bit());
+ lprocess.start( TDEProcess::Block );
+ }
+ }
+ return allWritable;
+}
diff --git a/tdecore/tdeconfigbackend.h b/tdecore/tdeconfigbackend.h
new file mode 100644
index 000000000..c1092364c
--- /dev/null
+++ b/tdecore/tdeconfigbackend.h
@@ -0,0 +1,299 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Preston Brown <pbrown@kde.org>
+ Portions copyright (c) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KCONFIGBACKEND_H
+#define _KCONFIGBACKEND_H
+
+#include "tdeconfigdata.h"
+#include <tdeconfigbase.h>
+#include <klockfile.h>
+#include <klocale.h>
+#include "tdelibs_export.h"
+
+class TQFile;
+class TDEConfigBackEndPrivate;
+
+/**
+ * Abstract base class for KDE configuration file loading/saving.
+ *
+ * This class forms the base for all classes that implement some
+ * manner of loading/saving to configuration files. It is an
+ * abstract base class, meaning that you cannot directly instantiate
+ * objects of this class. As of right now, the only back end available
+ * is one to read/write to INI-style files, but in the future, other
+ * formats may be available, such as XML or a database.
+ *
+ * @author Preston Brown <pbrown@kde.org>,
+ * Matthias Kalle Dalheimer <kalle@kde.org>
+ * @short KDE Configuration file loading/saving abstract base class
+ */
+class TDECORE_EXPORT TDEConfigBackEnd
+{
+ friend class TDEConfig;
+ friend class KSharedConfig;
+public:
+ /**
+ * Constructs a configuration back end.
+ *
+ * @param _config Specifies the configuration object which values
+ * will be passed to as they are read, or from where values
+ * to be written to will be obtained from.
+ * @param _fileName The name of the file in which config
+ * data is stored. All registered configuration directories
+ * will be looked in in order of decreasing relevance.
+ * @param _resType the resource type of the fileName specified, _if_
+ * it is not an absolute path (otherwise this parameter is ignored).
+ * @param _useKDEGlobals If true, the user's system-wide kdeglobals file
+ * will be imported into the config object. If false, only
+ * the filename specified will be dealt with.
+ */
+ TDEConfigBackEnd(TDEConfigBase *_config, const TQString &_fileName,
+ const char * _resType, bool _useKDEGlobals);
+
+ /**
+ * Destructs the configuration backend.
+ */
+ virtual ~TDEConfigBackEnd();
+
+ /**
+ * Parses all configuration files for a configuration object. This
+ * method must be reimplemented by the derived classes.
+ *
+ * @returns Whether or not parsing was successful.
+ */
+ virtual bool parseConfigFiles() = 0;
+
+ /**
+ * Writes configuration data to file(s). This method must be
+ * reimplemented by the derived classes.
+ *
+ * @param bMerge Specifies whether the old config file already
+ * on disk should be merged in with the data in memory. If true,
+ * data is read off the disk and merged. If false, the on-disk
+ * file is removed and only in-memory data is written out.
+ */
+ virtual void sync(bool bMerge = true) = 0;
+
+ /**
+ * Changes the filenames associated with this back end. You should
+ * probably reparse your config info after doing this.
+ *
+ * @param _fileName the new filename to use
+ * @param _resType the resource type of the fileName specified, _if_
+ * it is not an absolute path (otherwise this parameter is ignored).
+ * @param _useKDEGlobals specifies whether or not to also parse the
+ * global KDE configuration files.
+ */
+ void changeFileName(const TQString &_fileName, const char * _resType,
+ bool _useKDEGlobals);
+
+ /**
+ * Returns the state of the app-config object.
+ *
+ * @see TDEConfig::getConfigState
+ */
+ virtual TDEConfigBase::ConfigState getConfigState() const
+ { return mConfigState; }
+
+ /**
+ * Returns the filename as passed to the constructor.
+ * @return the filename as passed to the constructor.
+ */
+ TQString fileName() const { return mfileName; }
+
+ /**
+ * Returns the resource type as passed to the constructor.
+ * @return the resource type as passed to the constructor.
+ */
+ const char * resource() const { return resType; }
+
+ /**
+ * Set the locale string that defines the current language.
+ * @param _localeString the identifier of the language
+ * @see KLocale
+ */
+ void setLocaleString(const TQCString &_localeString) { localeString = _localeString; }
+
+ /**
+ * Set the file mode for newly created files.
+ * @param mode the filemode (as in chmod)
+ */
+ void setFileWriteMode(int mode);
+
+ /**
+ * Check whether the config files are writable.
+ * @param warnUser Warn the user if the configuration files are not writable.
+ * @return Indicates that all of the configuration files used are writable.
+ * @since 3.2
+ */
+ bool checkConfigFilesWritable(bool warnUser);
+
+ /**
+ * Returns a lock file object for the configuration file
+ * @param bGlobal If true, returns a lock file object for kdeglobals
+ * @since 3.3
+ */
+ KLockFile::Ptr lockFile( bool bGlobal = false );
+
+#ifdef KDE_NO_COMPAT
+private:
+#endif
+ /**
+ * @deprecated Use fileName() instead
+ */
+ KDE_DEPRECATED TQString filename() const { return mfileName; }
+
+protected:
+ TDEConfigBase *pConfig;
+
+ TQString mfileName;
+ TQCString resType;
+ bool useKDEGlobals : 1;
+ bool bFileImmutable : 1;
+ TQCString localeString;
+ TQString mLocalFileName;
+ TQString mGlobalFileName;
+ TDEConfigBase::ConfigState mConfigState;
+ int mFileMode;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+protected:
+ class TDEConfigBackEndPrivate;
+ TDEConfigBackEndPrivate *d;
+};
+
+
+/**
+ * Class for KDE INI-style configuration file loading/saving.
+ *
+ * @author Preston Brown <pbrown@kde.org>,
+ * Matthias Kalle Dalheimer <kalle@kde.org>
+ */
+class TDECORE_EXPORT TDEConfigINIBackEnd : public TDEConfigBackEnd
+{
+
+public:
+ /**
+ * Constructs an ini-style configuration back end.
+ *
+ * @param _config Specifies the configuration object which values
+ * will be passed to as they are read, or from where values
+ * to be written to will be obtained from.
+ * @param _fileName The name of the file in which config
+ * data is stored. All registered configuration directories
+ * will be looked in in order of decreasing relevance.
+ * @param _resType the resource type of the fileName specified, _if_
+ * it is not an absolute path (otherwise this parameter is ignored).
+ * @param _useKDEGlobals If true, the user's system-wide kdeglobals file
+ * will be imported into the config object. If false, only
+ * the filename specified will be dealt with.
+ */
+ TDEConfigINIBackEnd(TDEConfigBase *_config, const TQString &_fileName,
+ const char * _resType, bool _useKDEGlobals = true)
+ : TDEConfigBackEnd(_config, _fileName, _resType, _useKDEGlobals) {}
+
+ /**
+ * Destructs the configuration backend.
+ */
+ virtual ~TDEConfigINIBackEnd() {}
+
+ /**
+ * Parses all INI-style configuration files for a config object.
+ *
+ * @returns Whether or not parsing was successful.
+ */
+ bool parseConfigFiles();
+
+ /**
+ * Writes configuration data to file(s).
+ * @param bMerge Specifies whether the old config file already
+ * on disk should be merged in with the data in memory. If true,
+ * data is read off the disk and merged. If false, the on-disk
+ * file is removed and only in-memory data is written out.
+ */
+ virtual void sync(bool bMerge = true);
+
+protected:
+ /**
+ * Parses one configuration file.
+ *
+ * @param rFile The configuration file to parse
+ * @param pWriteBackMap If specified, points to a KEntryMap where
+ * the data read from the file should be stored, instead of
+ * inserting them directly into the configuration object.
+ * Use this area as a "scratchpad" when you need to know what is
+ * on disk but don't want to effect the configuration object.
+ * @param bGlobal Specifies whether entries should be marked as
+ * belonging to the global KDE configuration file rather
+ * than the application-specific KDE configuration file(s).
+ * @param bDefault Specifies whether entries should be marked as
+ * being default values.
+ */
+ void parseSingleConfigFile(TQFile& rFile, KEntryMap *pWriteBackMap = 0L,
+ bool bGlobal = false, bool bDefault = false);
+
+ // Kubuntu patch, 2006-08-03
+ // looks up a key in with KLocale
+ // see https://launchpad.net/distros/ubuntu/+spec/langpacks-desktopfiles-kde
+ void translateKey(KLocale& locale, TQCString currentGroup, TQCString key);
+
+ /**
+ * Writes configuration file back.
+ *
+ * @param filename The name of the file to write.
+ * @param bGlobal Specifies whether to write only entries which
+ * are marked as belonging to the global KDE config file.
+ * If this is false, it skips those entries.
+ * @param bMerge Specifies whether the old config file already
+ * on disk should be merged in with the data in memory. If true,
+ * data is read off the disk and merged. If false, the on-disk
+ * file is removed and only in-memory data is written out.
+ * @return Whether some entries are left to be written to other
+ * files.
+ */
+ bool writeConfigFile(TQString filename, bool bGlobal = false, bool bMerge = true);
+
+ /** Get the entry map.
+ *
+ * @param map the entries will be stored in this object.
+ * @param bGlobal Specifies whether to get only entries which
+ * are marked as belonging to the global KDE config file.
+ * If this is false, it skips those entries.
+ * @param mergeFile if not null, the dirty entries for this file will
+ * be merged.
+ *
+ * @return Whether there will be some entries left for writing to other
+ * files.
+ */
+ bool getEntryMap(KEntryMap &map, bool bGlobal, TQFile *mergeFile);
+
+ /** Write the entries in @e aTempMap to the file stream.*/
+ void writeEntries(FILE *pStream, const KEntryMap &aTempMap);
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class TDEConfigINIBackEndPrivate;
+ TDEConfigINIBackEndPrivate *not_d;
+};
+
+#endif
diff --git a/tdecore/tdeconfigbase.cpp b/tdecore/tdeconfigbase.cpp
new file mode 100644
index 000000000..b00430f27
--- /dev/null
+++ b/tdecore/tdeconfigbase.cpp
@@ -0,0 +1,1937 @@
+// -*- c-basic-offset: 2 -*-
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Preston Brown <pbrown@kde.org>
+ Copyright (c) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <tqfile.h>
+#include <tqdir.h>
+#include <tqtextstream.h>
+
+#include <kapplication.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kcharsets.h>
+
+#include "tdeconfigbase.h"
+#include "tdeconfigbackend.h"
+#include "kdebug.h"
+#include "kstandarddirs.h"
+#include "kstringhandler.h"
+
+class TDEConfigBase::TDEConfigBasePrivate
+{
+public:
+ TDEConfigBasePrivate() : readDefaults(false) { };
+
+public:
+ bool readDefaults;
+};
+
+TDEConfigBase::TDEConfigBase()
+ : backEnd(0L), bDirty(false), bLocaleInitialized(false),
+ bReadOnly(false), bExpand(false), d(0)
+{
+ setGroup(TQString::null);
+}
+
+TDEConfigBase::~TDEConfigBase()
+{
+ delete d;
+}
+
+void TDEConfigBase::setLocale()
+{
+ bLocaleInitialized = true;
+
+ if (TDEGlobal::locale())
+ aLocaleString = TDEGlobal::locale()->language().utf8();
+ else
+ aLocaleString = KLocale::defaultLanguage().utf8();
+ if (backEnd)
+ backEnd->setLocaleString(aLocaleString);
+}
+
+TQString TDEConfigBase::locale() const
+{
+ return TQString::fromUtf8(aLocaleString);
+}
+
+void TDEConfigBase::setGroup( const TQString& group )
+{
+ if ( group.isEmpty() )
+ mGroup = "<default>";
+ else
+ mGroup = group.utf8();
+}
+
+void TDEConfigBase::setGroup( const char *pGroup )
+{
+ setGroup(TQCString(pGroup));
+}
+
+void TDEConfigBase::setGroup( const TQCString &group )
+{
+ if ( group.isEmpty() )
+ mGroup = "<default>";
+ else
+ mGroup = group;
+}
+
+TQString TDEConfigBase::group() const {
+ return TQString::fromUtf8(mGroup);
+}
+
+void TDEConfigBase::setDesktopGroup()
+{
+ mGroup = "Desktop Entry";
+}
+
+bool TDEConfigBase::hasKey(const TQString &key) const
+{
+ return hasKey(key.utf8().data());
+}
+
+bool TDEConfigBase::hasKey(const char *pKey) const
+{
+ KEntryKey aEntryKey(mGroup, 0);
+ aEntryKey.c_key = pKey;
+ aEntryKey.bDefault = readDefaults();
+
+ if (!locale().isNull()) {
+ // try the localized key first
+ aEntryKey.bLocal = true;
+ KEntry entry = lookupData(aEntryKey);
+ if (!entry.mValue.isNull())
+ return true;
+ aEntryKey.bLocal = false;
+ }
+
+ // try the non-localized version
+ KEntry entry = lookupData(aEntryKey);
+ return !entry.mValue.isNull();
+}
+
+bool TDEConfigBase::hasTranslatedKey(const char* pKey) const
+{
+ KEntryKey aEntryKey(mGroup, 0);
+ aEntryKey.c_key = pKey;
+ aEntryKey.bDefault = readDefaults();
+
+ if (!locale().isNull()) {
+ // try the localized key first
+ aEntryKey.bLocal = true;
+ KEntry entry = lookupData(aEntryKey);
+ if (!entry.mValue.isNull())
+ return true;
+ aEntryKey.bLocal = false;
+ }
+
+ return false;
+}
+
+bool TDEConfigBase::hasGroup(const TQString &group) const
+{
+ return internalHasGroup( group.utf8());
+}
+
+bool TDEConfigBase::hasGroup(const char *_pGroup) const
+{
+ return internalHasGroup( TQCString(_pGroup));
+}
+
+bool TDEConfigBase::hasGroup(const TQCString &_pGroup) const
+{
+ return internalHasGroup( _pGroup);
+}
+
+bool TDEConfigBase::isImmutable() const
+{
+ return (getConfigState() != ReadWrite);
+}
+
+bool TDEConfigBase::groupIsImmutable(const TQString &group) const
+{
+ if (getConfigState() != ReadWrite)
+ return true;
+
+ KEntryKey groupKey(group.utf8(), 0);
+ KEntry entry = lookupData(groupKey);
+ return entry.bImmutable;
+}
+
+bool TDEConfigBase::entryIsImmutable(const TQString &key) const
+{
+ if (getConfigState() != ReadWrite)
+ return true;
+
+ KEntryKey entryKey(mGroup, 0);
+ KEntry aEntryData = lookupData(entryKey); // Group
+ if (aEntryData.bImmutable)
+ return true;
+
+ TQCString utf8_key = key.utf8();
+ entryKey.c_key = utf8_key.data();
+ aEntryData = lookupData(entryKey); // Normal entry
+ if (aEntryData.bImmutable)
+ return true;
+
+ entryKey.bLocal = true;
+ aEntryData = lookupData(entryKey); // Localized entry
+ return aEntryData.bImmutable;
+}
+
+
+TQString TDEConfigBase::readEntryUntranslated( const TQString& pKey,
+ const TQString& aDefault ) const
+{
+ return TDEConfigBase::readEntryUntranslated(pKey.utf8().data(), aDefault);
+}
+
+
+TQString TDEConfigBase::readEntryUntranslated( const char *pKey,
+ const TQString& aDefault ) const
+{
+ TQCString result = readEntryUtf8(pKey);
+ if (result.isNull())
+ return aDefault;
+ return TQString::fromUtf8(result);
+}
+
+
+TQString TDEConfigBase::readEntry( const TQString& pKey,
+ const TQString& aDefault ) const
+{
+ return TDEConfigBase::readEntry(pKey.utf8().data(), aDefault);
+}
+
+TQString TDEConfigBase::readEntry( const char *pKey,
+ const TQString& aDefault ) const
+{
+ // we need to access _locale instead of the method locale()
+ // because calling locale() will create a locale object if it
+ // doesn't exist, which requires TDEConfig, which will create a infinite
+ // loop, and nobody likes those.
+ if (!bLocaleInitialized && TDEGlobal::_locale) {
+ // get around const'ness.
+ TDEConfigBase *that = const_cast<TDEConfigBase *>(this);
+ that->setLocale();
+ }
+
+ TQString aValue;
+
+ bool expand = false;
+ // construct a localized version of the key
+ // try the localized key first
+ KEntry aEntryData;
+ KEntryKey entryKey(mGroup, 0);
+ entryKey.c_key = pKey;
+ entryKey.bDefault = readDefaults();
+ entryKey.bLocal = true;
+ aEntryData = lookupData(entryKey);
+ if (!aEntryData.mValue.isNull()) {
+ // for GNOME .desktop
+ aValue = KStringHandler::from8Bit( aEntryData.mValue.data() );
+ expand = aEntryData.bExpand;
+ } else {
+ entryKey.bLocal = false;
+ aEntryData = lookupData(entryKey);
+ if (!aEntryData.mValue.isNull()) {
+ aValue = TQString::fromUtf8(aEntryData.mValue.data());
+ if (aValue.isNull())
+ {
+ static const TQString &emptyString = TDEGlobal::staticQString("");
+ aValue = emptyString;
+ }
+ expand = aEntryData.bExpand;
+ } else {
+ aValue = aDefault;
+ }
+ }
+
+ // only do dollar expansion if so desired
+ if( expand || bExpand )
+ {
+ // check for environment variables and make necessary translations
+ int nDollarPos = aValue.find( '$' );
+
+ while( nDollarPos != -1 && nDollarPos+1 < static_cast<int>(aValue.length())) {
+ // there is at least one $
+ if( (aValue)[nDollarPos+1] == '(' ) {
+ uint nEndPos = nDollarPos+1;
+ // the next character is no $
+ while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!=')') )
+ nEndPos++;
+ nEndPos++;
+ TQString cmd = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
+
+ TQString result;
+ FILE *fs = popen(TQFile::encodeName(cmd).data(), "r");
+ if (fs)
+ {
+ {
+ TQTextStream ts(fs, IO_ReadOnly);
+ result = ts.read().stripWhiteSpace();
+ }
+ pclose(fs);
+ }
+ aValue.replace( nDollarPos, nEndPos-nDollarPos, result );
+ } else if( (aValue)[nDollarPos+1] != '$' ) {
+ uint nEndPos = nDollarPos+1;
+ // the next character is no $
+ TQString aVarName;
+ if (aValue[nEndPos]=='{')
+ {
+ while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') )
+ nEndPos++;
+ nEndPos++;
+ aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
+ }
+ else
+ {
+ while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber()
+ || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' ) )
+ nEndPos++;
+ aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 );
+ }
+ const char* pEnv = 0;
+ if (!aVarName.isEmpty())
+ pEnv = getenv( aVarName.ascii() );
+ if( pEnv ) {
+ // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
+ // A environment variables may contain values in 8bit
+ // locale cpecified encoding or in UTF8 encoding.
+ aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) );
+ } else
+ aValue.remove( nDollarPos, nEndPos-nDollarPos );
+ } else {
+ // remove one of the dollar signs
+ aValue.remove( nDollarPos, 1 );
+ nDollarPos++;
+ }
+ nDollarPos = aValue.find( '$', nDollarPos );
+ }
+ }
+
+ return aValue;
+}
+
+TQCString TDEConfigBase::readEntryUtf8( const char *pKey) const
+{
+ // We don't try the localized key
+ KEntryKey entryKey(mGroup, 0);
+ entryKey.bDefault = readDefaults();
+ entryKey.c_key = pKey;
+ KEntry aEntryData = lookupData(entryKey);
+ if (aEntryData.bExpand)
+ {
+ // We need to do fancy, take the slow route.
+ return readEntry(pKey, TQString::null).utf8();
+ }
+ return aEntryData.mValue;
+}
+
+TQVariant TDEConfigBase::readPropertyEntry( const TQString& pKey,
+ TQVariant::Type type ) const
+{
+ return readPropertyEntry(pKey.utf8().data(), type);
+}
+
+TQVariant TDEConfigBase::readPropertyEntry( const char *pKey,
+ TQVariant::Type type ) const
+{
+ TQVariant va;
+ if ( !hasKey( pKey ) ) return va;
+ (void)va.cast(type);
+ return readPropertyEntry(pKey, va);
+}
+
+TQVariant TDEConfigBase::readPropertyEntry( const TQString& pKey,
+ const TQVariant &aDefault ) const
+{
+ return readPropertyEntry(pKey.utf8().data(), aDefault);
+}
+
+TQVariant TDEConfigBase::readPropertyEntry( const char *pKey,
+ const TQVariant &aDefault ) const
+{
+ if ( !hasKey( pKey ) ) return aDefault;
+
+ TQVariant tmp = aDefault;
+
+ switch( aDefault.type() )
+ {
+ case TQVariant::Invalid:
+ return TQVariant();
+ case TQVariant::String:
+ return TQVariant( readEntry( pKey, aDefault.toString() ) );
+ case TQVariant::StringList:
+ return TQVariant( readListEntry( pKey ) );
+ case TQVariant::List: {
+ TQStringList strList = readListEntry( pKey );
+ TQStringList::ConstIterator it = strList.begin();
+ TQStringList::ConstIterator end = strList.end();
+ TQValueList<TQVariant> list;
+
+ for (; it != end; ++it ) {
+ tmp = *it;
+ list.append( tmp );
+ }
+ return TQVariant( list );
+ }
+ case TQVariant::Font:
+ return TQVariant( readFontEntry( pKey, &tmp.asFont() ) );
+ case TQVariant::Point:
+ return TQVariant( readPointEntry( pKey, &tmp.asPoint() ) );
+ case TQVariant::Rect:
+ return TQVariant( readRectEntry( pKey, &tmp.asRect() ) );
+ case TQVariant::Size:
+ return TQVariant( readSizeEntry( pKey, &tmp.asSize() ) );
+ case TQVariant::Color:
+ return TQVariant( readColorEntry( pKey, &tmp.asColor() ) );
+ case TQVariant::Int:
+ return TQVariant( readNumEntry( pKey, aDefault.toInt() ) );
+ case TQVariant::UInt:
+ return TQVariant( readUnsignedNumEntry( pKey, aDefault.toUInt() ) );
+ case TQVariant::LongLong:
+ return TQVariant( readNum64Entry( pKey, aDefault.toLongLong() ) );
+ case TQVariant::ULongLong:
+ return TQVariant( readUnsignedNum64Entry( pKey, aDefault.toULongLong() ) );
+ case TQVariant::Bool:
+ return TQVariant( readBoolEntry( pKey, aDefault.toBool() ), 0 );
+ case TQVariant::Double:
+ return TQVariant( readDoubleNumEntry( pKey, aDefault.toDouble() ) );
+ case TQVariant::DateTime:
+ return TQVariant( readDateTimeEntry( pKey, &tmp.asDateTime() ) );
+ case TQVariant::Date:
+ return TQVariant(TQT_TQDATE_OBJECT(readDateTimeEntry( pKey, &tmp.asDateTime() ).date()));
+
+ case TQVariant::Pixmap:
+ case TQVariant::Image:
+ case TQVariant::Brush:
+ case TQVariant::Palette:
+ case TQVariant::ColorGroup:
+ case TQVariant::Map:
+ case TQVariant::IconSet:
+ case TQVariant::CString:
+ case TQVariant::PointArray:
+ case TQVariant::Region:
+ case TQVariant::Bitmap:
+ case TQVariant::Cursor:
+ case TQVariant::SizePolicy:
+ case TQVariant::Time:
+#ifdef USE_QT3
+ case TQVariant::ByteArray:
+#endif // USE_QT3
+ case TQVariant::BitArray:
+ case TQVariant::KeySequence:
+ case TQVariant::Pen:
+#ifdef USE_QT4
+ case TQVariant::Char:
+ case TQVariant::Url:
+ case TQVariant::Locale:
+ case TQVariant::RectF:
+ case TQVariant::SizeF:
+ case TQVariant::Line:
+ case TQVariant::LineF:
+ case TQVariant::PointF:
+ case TQVariant::RegExp:
+ case TQVariant::Hash:
+ case TQVariant::TextLength:
+ case QVariant::TextFormat:
+ case TQVariant::Matrix:
+ case TQVariant::Transform:
+ case TQVariant::Matrix4x4:
+ case TQVariant::Vector2D:
+ case TQVariant::Vector3D:
+ case TQVariant::Vector4D:
+ case TQVariant::Quaternion:
+ case TQVariant::UserType:
+#endif // USE_QT4
+ break;
+ }
+
+ Q_ASSERT( 0 );
+ return TQVariant();
+}
+
+int TDEConfigBase::readListEntry( const TQString& pKey,
+ TQStrList &list, char sep ) const
+{
+ return readListEntry(pKey.utf8().data(), list, sep);
+}
+
+int TDEConfigBase::readListEntry( const char *pKey,
+ TQStrList &list, char sep ) const
+{
+ if( !hasKey( pKey ) )
+ return 0;
+
+ TQCString str_list = readEntryUtf8( pKey );
+ if (str_list.isEmpty())
+ return 0;
+
+ list.clear();
+ TQCString value = "";
+ int len = str_list.length();
+
+ for (int i = 0; i < len; i++) {
+ if (str_list[i] != sep && str_list[i] != '\\') {
+ value += str_list[i];
+ continue;
+ }
+ if (str_list[i] == '\\') {
+ i++;
+ if ( i < len )
+ value += str_list[i];
+ continue;
+ }
+ // if we fell through to here, we are at a separator. Append
+ // contents of value to the list
+ // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
+ // A TQStrList may contain values in 8bit locale cpecified
+ // encoding
+ list.append( value );
+ value.truncate(0);
+ }
+
+ if ( str_list[len-1] != sep || ( len > 1 && str_list[len-2] == '\\' ) )
+ list.append( value );
+ return list.count();
+}
+
+TQStringList TDEConfigBase::readListEntry( const TQString& pKey, char sep ) const
+{
+ return readListEntry(pKey.utf8().data(), sep);
+}
+
+TQStringList TDEConfigBase::readListEntry( const char *pKey, char sep ) const
+{
+ static const TQString& emptyString = TDEGlobal::staticQString("");
+
+ TQStringList list;
+ if( !hasKey( pKey ) )
+ return list;
+ TQString str_list = readEntry( pKey );
+ if( str_list.isEmpty() )
+ return list;
+ TQString value(emptyString);
+ int len = str_list.length();
+ // obviously too big, but faster than letting each += resize the string.
+ value.reserve( len );
+ for( int i = 0; i < len; i++ )
+ {
+ if( str_list[i] != sep && str_list[i] != '\\' )
+ {
+ value += str_list[i];
+ continue;
+ }
+ if( str_list[i] == '\\' )
+ {
+ i++;
+ if ( i < len )
+ value += str_list[i];
+ continue;
+ }
+ TQString finalvalue( value );
+ finalvalue.squeeze();
+ list.append( finalvalue );
+ value.truncate( 0 );
+ }
+ if ( str_list[len-1] != sep || ( len > 1 && str_list[len-2] == '\\' ) )
+ {
+ value.squeeze();
+ list.append( value );
+ }
+ return list;
+}
+
+TQStringList TDEConfigBase::readListEntry( const char* pKey, const TQStringList& aDefault,
+ char sep ) const
+{
+ if ( !hasKey( pKey ) )
+ return aDefault;
+ else
+ return readListEntry( pKey, sep );
+}
+
+TQValueList<int> TDEConfigBase::readIntListEntry( const TQString& pKey ) const
+{
+ return readIntListEntry(pKey.utf8().data());
+}
+
+TQValueList<int> TDEConfigBase::readIntListEntry( const char *pKey ) const
+{
+ TQStringList strlist = readListEntry(pKey);
+ TQValueList<int> list;
+ TQStringList::ConstIterator end(strlist.end());
+ for (TQStringList::ConstIterator it = strlist.begin(); it != end; ++it)
+ // I do not check if the toInt failed because I consider the number of items
+ // more important than their value
+ list << (*it).toInt();
+
+ return list;
+}
+
+TQString TDEConfigBase::readPathEntry( const TQString& pKey, const TQString& pDefault ) const
+{
+ return readPathEntry(pKey.utf8().data(), pDefault);
+}
+
+TQString TDEConfigBase::readPathEntry( const char *pKey, const TQString& pDefault ) const
+{
+ const bool bExpandSave = bExpand;
+ bExpand = true;
+ TQString aValue = readEntry( pKey, pDefault );
+ bExpand = bExpandSave;
+ return aValue;
+}
+
+TQStringList TDEConfigBase::readPathListEntry( const TQString& pKey, char sep ) const
+{
+ return readPathListEntry(pKey.utf8().data(), sep);
+}
+
+TQStringList TDEConfigBase::readPathListEntry( const char *pKey, char sep ) const
+{
+ const bool bExpandSave = bExpand;
+ bExpand = true;
+ TQStringList aValue = readListEntry( pKey, sep );
+ bExpand = bExpandSave;
+ return aValue;
+}
+
+int TDEConfigBase::readNumEntry( const TQString& pKey, int nDefault) const
+{
+ return readNumEntry(pKey.utf8().data(), nDefault);
+}
+
+int TDEConfigBase::readNumEntry( const char *pKey, int nDefault) const
+{
+ TQCString aValue = readEntryUtf8( pKey );
+ if( aValue.isNull() )
+ return nDefault;
+ else if( aValue == "true" || aValue == "on" || aValue == "yes" )
+ return 1;
+ else
+ {
+ bool ok;
+ int rc = aValue.toInt( &ok );
+ return( ok ? rc : nDefault );
+ }
+}
+
+
+unsigned int TDEConfigBase::readUnsignedNumEntry( const TQString& pKey, unsigned int nDefault) const
+{
+ return readUnsignedNumEntry(pKey.utf8().data(), nDefault);
+}
+
+unsigned int TDEConfigBase::readUnsignedNumEntry( const char *pKey, unsigned int nDefault) const
+{
+ TQCString aValue = readEntryUtf8( pKey );
+ if( aValue.isNull() )
+ return nDefault;
+ else
+ {
+ bool ok;
+ unsigned int rc = aValue.toUInt( &ok );
+ return( ok ? rc : nDefault );
+ }
+}
+
+
+long TDEConfigBase::readLongNumEntry( const TQString& pKey, long nDefault) const
+{
+ return readLongNumEntry(pKey.utf8().data(), nDefault);
+}
+
+long TDEConfigBase::readLongNumEntry( const char *pKey, long nDefault) const
+{
+ TQCString aValue = readEntryUtf8( pKey );
+ if( aValue.isNull() )
+ return nDefault;
+ else
+ {
+ bool ok;
+ long rc = aValue.toLong( &ok );
+ return( ok ? rc : nDefault );
+ }
+}
+
+
+unsigned long TDEConfigBase::readUnsignedLongNumEntry( const TQString& pKey, unsigned long nDefault) const
+{
+ return readUnsignedLongNumEntry(pKey.utf8().data(), nDefault);
+}
+
+unsigned long TDEConfigBase::readUnsignedLongNumEntry( const char *pKey, unsigned long nDefault) const
+{
+ TQCString aValue = readEntryUtf8( pKey );
+ if( aValue.isNull() )
+ return nDefault;
+ else
+ {
+ bool ok;
+ unsigned long rc = aValue.toULong( &ok );
+ return( ok ? rc : nDefault );
+ }
+}
+
+TQ_INT64 TDEConfigBase::readNum64Entry( const TQString& pKey, TQ_INT64 nDefault) const
+{
+ return readNum64Entry(pKey.utf8().data(), nDefault);
+}
+
+TQ_INT64 TDEConfigBase::readNum64Entry( const char *pKey, TQ_INT64 nDefault) const
+{
+ // Note that TQCString::toLongLong() is missing, we muse use a TQString instead.
+ TQString aValue = readEntry( pKey );
+ if( aValue.isNull() )
+ return nDefault;
+ else
+ {
+ bool ok;
+ TQ_INT64 rc = aValue.toLongLong( &ok );
+ return( ok ? rc : nDefault );
+ }
+}
+
+
+TQ_UINT64 TDEConfigBase::readUnsignedNum64Entry( const TQString& pKey, TQ_UINT64 nDefault) const
+{
+ return readUnsignedNum64Entry(pKey.utf8().data(), nDefault);
+}
+
+TQ_UINT64 TDEConfigBase::readUnsignedNum64Entry( const char *pKey, TQ_UINT64 nDefault) const
+{
+ // Note that TQCString::toULongLong() is missing, we muse use a TQString instead.
+ TQString aValue = readEntry( pKey );
+ if( aValue.isNull() )
+ return nDefault;
+ else
+ {
+ bool ok;
+ TQ_UINT64 rc = aValue.toULongLong( &ok );
+ return( ok ? rc : nDefault );
+ }
+}
+
+double TDEConfigBase::readDoubleNumEntry( const TQString& pKey, double nDefault) const
+{
+ return readDoubleNumEntry(pKey.utf8().data(), nDefault);
+}
+
+double TDEConfigBase::readDoubleNumEntry( const char *pKey, double nDefault) const
+{
+ TQCString aValue = readEntryUtf8( pKey );
+ if( aValue.isNull() )
+ return nDefault;
+ else
+ {
+ bool ok;
+ double rc = aValue.toDouble( &ok );
+ return( ok ? rc : nDefault );
+ }
+}
+
+
+bool TDEConfigBase::readBoolEntry( const TQString& pKey, bool bDefault ) const
+{
+ return readBoolEntry(pKey.utf8().data(), bDefault);
+}
+
+bool TDEConfigBase::readBoolEntry( const char *pKey, bool bDefault ) const
+{
+ TQCString aValue = readEntryUtf8( pKey );
+
+ if( aValue.isNull() )
+ return bDefault;
+ else
+ {
+ if( aValue == "true" || aValue == "on" || aValue == "yes" || aValue == "1" )
+ return true;
+ else
+ {
+ bool bOK;
+ int val = aValue.toInt( &bOK );
+ if( bOK && val != 0 )
+ return true;
+ else
+ return false;
+ }
+ }
+}
+
+TQFont TDEConfigBase::readFontEntry( const TQString& pKey, const TQFont* pDefault ) const
+{
+ return readFontEntry(pKey.utf8().data(), pDefault);
+}
+
+TQFont TDEConfigBase::readFontEntry( const char *pKey, const TQFont* pDefault ) const
+{
+ TQFont aRetFont;
+
+ TQString aValue = readEntry( pKey );
+ if( !aValue.isNull() ) {
+ if ( aValue.contains( ',' ) > 5 ) {
+ // KDE3 and upwards entry
+ if ( !aRetFont.fromString( aValue ) && pDefault )
+ aRetFont = *pDefault;
+ }
+ else {
+ // backward compatibility with older font formats
+ // ### remove KDE 3.1 ?
+ // find first part (font family)
+ int nIndex = aValue.find( ',' );
+ if( nIndex == -1 ){
+ if( pDefault )
+ aRetFont = *pDefault;
+ return aRetFont;
+ }
+ aRetFont.setFamily( aValue.left( nIndex ) );
+
+ // find second part (point size)
+ int nOldIndex = nIndex;
+ nIndex = aValue.find( ',', nOldIndex+1 );
+ if( nIndex == -1 ){
+ if( pDefault )
+ aRetFont = *pDefault;
+ return aRetFont;
+ }
+
+ aRetFont.setPointSize( aValue.mid( nOldIndex+1,
+ nIndex-nOldIndex-1 ).toInt() );
+
+ // find third part (style hint)
+ nOldIndex = nIndex;
+ nIndex = aValue.find( ',', nOldIndex+1 );
+
+ if( nIndex == -1 ){
+ if( pDefault )
+ aRetFont = *pDefault;
+ return aRetFont;
+ }
+
+ aRetFont.setStyleHint( (TQFont::StyleHint)aValue.mid( nOldIndex+1, nIndex-nOldIndex-1 ).toUInt() );
+
+ // find fourth part (char set)
+ nOldIndex = nIndex;
+ nIndex = aValue.find( ',', nOldIndex+1 );
+
+ if( nIndex == -1 ){
+ if( pDefault )
+ aRetFont = *pDefault;
+ return aRetFont;
+ }
+
+ TQString chStr=aValue.mid( nOldIndex+1,
+ nIndex-nOldIndex-1 );
+ // find fifth part (weight)
+ nOldIndex = nIndex;
+ nIndex = aValue.find( ',', nOldIndex+1 );
+
+ if( nIndex == -1 ){
+ if( pDefault )
+ aRetFont = *pDefault;
+ return aRetFont;
+ }
+
+ aRetFont.setWeight( aValue.mid( nOldIndex+1,
+ nIndex-nOldIndex-1 ).toUInt() );
+
+ // find sixth part (font bits)
+ uint nFontBits = aValue.right( aValue.length()-nIndex-1 ).toUInt();
+
+ aRetFont.setItalic( nFontBits & 0x01 );
+ aRetFont.setUnderline( nFontBits & 0x02 );
+ aRetFont.setStrikeOut( nFontBits & 0x04 );
+ aRetFont.setFixedPitch( nFontBits & 0x08 );
+ aRetFont.setRawMode( nFontBits & 0x20 );
+ }
+ }
+ else
+ {
+ if( pDefault )
+ aRetFont = *pDefault;
+ }
+
+ return aRetFont;
+}
+
+
+TQRect TDEConfigBase::readRectEntry( const TQString& pKey, const TQRect* pDefault ) const
+{
+ return readRectEntry(pKey.utf8().data(), pDefault);
+}
+
+TQRect TDEConfigBase::readRectEntry( const char *pKey, const TQRect* pDefault ) const
+{
+ TQCString aValue = readEntryUtf8(pKey);
+
+ if (!aValue.isEmpty())
+ {
+ int left, top, width, height;
+
+ if (sscanf(aValue.data(), "%d,%d,%d,%d", &left, &top, &width, &height) == 4)
+ {
+ return TQRect(left, top, width, height);
+ }
+ }
+ if (pDefault)
+ return *pDefault;
+ return TQRect();
+}
+
+
+TQPoint TDEConfigBase::readPointEntry( const TQString& pKey,
+ const TQPoint* pDefault ) const
+{
+ return readPointEntry(pKey.utf8().data(), pDefault);
+}
+
+TQPoint TDEConfigBase::readPointEntry( const char *pKey,
+ const TQPoint* pDefault ) const
+{
+ TQCString aValue = readEntryUtf8(pKey);
+
+ if (!aValue.isEmpty())
+ {
+ int x,y;
+
+ if (sscanf(aValue.data(), "%d,%d", &x, &y) == 2)
+ {
+ return TQPoint(x,y);
+ }
+ }
+ if (pDefault)
+ return *pDefault;
+ return TQPoint();
+}
+
+TQSize TDEConfigBase::readSizeEntry( const TQString& pKey,
+ const TQSize* pDefault ) const
+{
+ return readSizeEntry(pKey.utf8().data(), pDefault);
+}
+
+TQSize TDEConfigBase::readSizeEntry( const char *pKey,
+ const TQSize* pDefault ) const
+{
+ TQCString aValue = readEntryUtf8(pKey);
+
+ if (!aValue.isEmpty())
+ {
+ int width,height;
+
+ if (sscanf(aValue.data(), "%d,%d", &width, &height) == 2)
+ {
+ return TQSize(width, height);
+ }
+ }
+ if (pDefault)
+ return *pDefault;
+ return TQSize();
+}
+
+
+TQColor TDEConfigBase::readColorEntry( const TQString& pKey,
+ const TQColor* pDefault ) const
+{
+ return readColorEntry(pKey.utf8().data(), pDefault);
+}
+
+TQColor TDEConfigBase::readColorEntry( const char *pKey,
+ const TQColor* pDefault ) const
+{
+ TQColor aRetColor;
+ int nRed = 0, nGreen = 0, nBlue = 0;
+
+ TQString aValue = readEntry( pKey );
+ if( !aValue.isEmpty() )
+ {
+ if ( aValue.at(0) == (QChar)'#' )
+ {
+ aRetColor.setNamedColor(aValue);
+ }
+ else
+ {
+
+ bool bOK;
+
+ // find first part (red)
+ int nIndex = aValue.find( ',' );
+
+ if( nIndex == -1 ){
+ // return a sensible default -- Bernd
+ if( pDefault )
+ aRetColor = *pDefault;
+ return aRetColor;
+ }
+
+ nRed = aValue.left( nIndex ).toInt( &bOK );
+
+ // find second part (green)
+ int nOldIndex = nIndex;
+ nIndex = aValue.find( ',', nOldIndex+1 );
+
+ if( nIndex == -1 ){
+ // return a sensible default -- Bernd
+ if( pDefault )
+ aRetColor = *pDefault;
+ return aRetColor;
+ }
+ nGreen = aValue.mid( nOldIndex+1,
+ nIndex-nOldIndex-1 ).toInt( &bOK );
+
+ // find third part (blue)
+ nBlue = aValue.right( aValue.length()-nIndex-1 ).toInt( &bOK );
+
+ aRetColor.setRgb( nRed, nGreen, nBlue );
+ }
+ }
+ else {
+
+ if( pDefault )
+ aRetColor = *pDefault;
+ }
+
+ return aRetColor;
+}
+
+
+TQDateTime TDEConfigBase::readDateTimeEntry( const TQString& pKey,
+ const TQDateTime* pDefault ) const
+{
+ return readDateTimeEntry(pKey.utf8().data(), pDefault);
+}
+
+// ### currentDateTime() as fallback ? (Harri)
+TQDateTime TDEConfigBase::readDateTimeEntry( const char *pKey,
+ const TQDateTime* pDefault ) const
+{
+ if( !hasKey( pKey ) )
+ {
+ if( pDefault )
+ return *pDefault;
+ else
+ return TQDateTime::currentDateTime();
+ }
+
+ TQStrList list;
+ int count = readListEntry( pKey, list, ',' );
+ if( count == 6 ) {
+ TQDate date( atoi( list.at( 0 ) ), atoi( list.at( 1 ) ),
+ atoi( list.at( 2 ) ) );
+ TQTime time( atoi( list.at( 3 ) ), atoi( list.at( 4 ) ),
+ atoi( list.at( 5 ) ) );
+
+ return TQDateTime( date, time );
+ }
+
+ return TQDateTime::currentDateTime();
+}
+
+void TDEConfigBase::writeEntry( const TQString& pKey, const TQString& value,
+ bool bPersistent,
+ bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), value, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQString& value,
+ bool bPersistent,
+ bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey, value, bPersistent, bGlobal, bNLS, false);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQString& value,
+ bool bPersistent,
+ bool bGlobal,
+ bool bNLS,
+ bool bExpand )
+{
+ // the TDEConfig object is dirty now
+ // set this before any IO takes place so that if any derivative
+ // classes do caching, they won't try and flush the cache out
+ // from under us before we read. A race condition is still
+ // possible but minimized.
+ if( bPersistent )
+ setDirty(true);
+
+ if (!bLocaleInitialized && TDEGlobal::locale())
+ setLocale();
+
+ KEntryKey entryKey(mGroup, pKey);
+ entryKey.bLocal = bNLS;
+
+ KEntry aEntryData;
+ aEntryData.mValue = value.utf8(); // set new value
+ aEntryData.bGlobal = bGlobal;
+ aEntryData.bNLS = bNLS;
+ aEntryData.bExpand = bExpand;
+
+ if (bPersistent)
+ aEntryData.bDirty = true;
+
+ // rewrite the new value
+ putData(entryKey, aEntryData, true);
+}
+
+void TDEConfigBase::writePathEntry( const TQString& pKey, const TQString & path,
+ bool bPersistent, bool bGlobal,
+ bool bNLS)
+{
+ writePathEntry(pKey.utf8().data(), path, bPersistent, bGlobal, bNLS);
+}
+
+
+static bool cleanHomeDirPath( TQString &path, const TQString &homeDir )
+{
+#ifdef Q_WS_WIN //safer
+ if (!TQDir::convertSeparators(path).startsWith(TQDir::convertSeparators(homeDir)))
+ return false;
+#else
+ if (!path.startsWith(homeDir))
+ return false;
+#endif
+
+ unsigned int len = homeDir.length();
+ // replace by "$HOME" if possible
+ if (len && (path.length() == len || path[len] == '/')) {
+ path.replace(0, len, TQString::fromLatin1("$HOME"));
+ return true;
+ } else
+ return false;
+}
+
+static TQString translatePath( TQString path )
+{
+ if (path.isEmpty())
+ return path;
+
+ // only "our" $HOME should be interpreted
+ path.replace('$', "$$");
+
+ bool startsWithFile = path.startsWith("file:", false);
+
+ // return original path, if it refers to another type of URL (e.g. http:/), or
+ // if the path is already relative to another directory
+ if (((!startsWithFile) && (path[0] != '/')) || (startsWithFile && (path[5] != '/'))) {
+ return path;
+ }
+
+ if (startsWithFile) {
+ path.remove(0,5); // strip leading "file:/" off the string
+ }
+
+ // keep only one single '/' at the beginning - needed for cleanHomeDirPath()
+ while (path[0] == '/' && path[1] == '/') {
+ path.remove(0,1);
+ }
+
+ // we can not use TDEGlobal::dirs()->relativeLocation("home", path) here,
+ // since it would not recognize paths without a trailing '/'.
+ // All of the 3 following functions to return the user's home directory
+ // can return different paths. We have to test all them.
+ TQString homeDir0 = TQFile::decodeName(getenv("HOME"));
+ TQString homeDir1 = TQDir::homeDirPath();
+ TQString homeDir2 = TQDir(homeDir1).canonicalPath();
+ if (cleanHomeDirPath(path, homeDir0) ||
+ cleanHomeDirPath(path, homeDir1) ||
+ cleanHomeDirPath(path, homeDir2) ) {
+ // kdDebug() << "Path was replaced\n";
+ }
+
+ if (startsWithFile)
+ path.prepend( "file://" );
+
+ return path;
+}
+
+void TDEConfigBase::writePathEntry( const char *pKey, const TQString & path,
+ bool bPersistent, bool bGlobal,
+ bool bNLS)
+{
+ writeEntry(pKey, translatePath(path), bPersistent, bGlobal, bNLS, true);
+}
+
+void TDEConfigBase::writePathEntry ( const TQString& pKey, const TQStringList &list,
+ char sep , bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ writePathEntry(pKey.utf8().data(), list, sep, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writePathEntry ( const char *pKey, const TQStringList &list,
+ char sep , bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ if( list.isEmpty() )
+ {
+ writeEntry( pKey, TQString::fromLatin1(""), bPersistent );
+ return;
+ }
+ TQStringList new_list;
+ TQStringList::ConstIterator it = list.begin();
+ for( ; it != list.end(); ++it )
+ {
+ TQString value = *it;
+ new_list.append( translatePath(value) );
+ }
+ writeEntry( pKey, new_list, sep, bPersistent, bGlobal, bNLS, true );
+}
+
+void TDEConfigBase::deleteEntry( const TQString& pKey,
+ bool bNLS,
+ bool bGlobal)
+{
+ deleteEntry(pKey.utf8().data(), bNLS, bGlobal);
+}
+
+void TDEConfigBase::deleteEntry( const char *pKey,
+ bool bNLS,
+ bool bGlobal)
+{
+ // the TDEConfig object is dirty now
+ // set this before any IO takes place so that if any derivative
+ // classes do caching, they won't try and flush the cache out
+ // from under us before we read. A race condition is still
+ // possible but minimized.
+ setDirty(true);
+
+ if (!bLocaleInitialized && TDEGlobal::locale())
+ setLocale();
+
+ KEntryKey entryKey(mGroup, pKey);
+ KEntry aEntryData;
+
+ aEntryData.bGlobal = bGlobal;
+ aEntryData.bNLS = bNLS;
+ aEntryData.bDirty = true;
+ aEntryData.bDeleted = true;
+
+ // rewrite the new value
+ putData(entryKey, aEntryData, true);
+}
+
+bool TDEConfigBase::deleteGroup( const TQString& group, bool bDeep, bool bGlobal )
+{
+ KEntryMap aEntryMap = internalEntryMap(group);
+
+ if (!bDeep) {
+ // Check if it empty
+ return aEntryMap.isEmpty();
+ }
+
+ bool dirty = false;
+ bool checkGroup = true;
+ // we want to remove all entries in the group
+ KEntryMapIterator aIt;
+ for (aIt = aEntryMap.begin(); aIt != aEntryMap.end(); ++aIt)
+ {
+ if (!aIt.key().mKey.isEmpty() && !aIt.key().bDefault && !(*aIt).bDeleted)
+ {
+ (*aIt).bDeleted = true;
+ (*aIt).bDirty = true;
+ (*aIt).bGlobal = bGlobal;
+ (*aIt).mValue = 0;
+ putData(aIt.key(), *aIt, checkGroup);
+ checkGroup = false;
+ dirty = true;
+ }
+ }
+ if (dirty)
+ setDirty(true);
+ return true;
+}
+
+void TDEConfigBase::writeEntry ( const TQString& pKey, const TQVariant &prop,
+ bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), prop, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry ( const char *pKey, const TQVariant &prop,
+ bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ switch( prop.type() )
+ {
+ case TQVariant::Invalid:
+ writeEntry( pKey, "", bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::String:
+ writeEntry( pKey, prop.toString(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::StringList:
+ writeEntry( pKey, prop.toStringList(), ',', bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::List: {
+ TQValueList<TQVariant> list = prop.toList();
+ TQValueList<TQVariant>::ConstIterator it = list.begin();
+ TQValueList<TQVariant>::ConstIterator end = list.end();
+ TQStringList strList;
+
+ for (; it != end; ++it )
+ strList.append( (*it).toString() );
+
+ writeEntry( pKey, strList, ',', bPersistent, bGlobal, bNLS );
+
+ return;
+ }
+ case TQVariant::Font:
+ writeEntry( pKey, prop.toFont(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::Point:
+ writeEntry( pKey, prop.toPoint(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::Rect:
+ writeEntry( pKey, prop.toRect(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::Size:
+ writeEntry( pKey, prop.toSize(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::Color:
+ writeEntry( pKey, prop.toColor(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::Int:
+ writeEntry( pKey, prop.toInt(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::UInt:
+ writeEntry( pKey, prop.toUInt(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::LongLong:
+ writeEntry( pKey, prop.toLongLong(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::ULongLong:
+ writeEntry( pKey, prop.toULongLong(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::Bool:
+ writeEntry( pKey, prop.toBool(), bPersistent, bGlobal, bNLS );
+ return;
+ case TQVariant::Double:
+ writeEntry( pKey, prop.toDouble(), bPersistent, bGlobal, 'g', 6, bNLS );
+ return;
+ case TQVariant::DateTime:
+ writeEntry( pKey, prop.toDateTime(), bPersistent, bGlobal, bNLS);
+ return;
+ case TQVariant::Date:
+ writeEntry( pKey, TQDateTime(prop.toDate()), bPersistent, bGlobal, bNLS);
+ return;
+
+ case TQVariant::Pixmap:
+ case TQVariant::Image:
+ case TQVariant::Brush:
+ case TQVariant::Palette:
+ case TQVariant::ColorGroup:
+ case TQVariant::Map:
+ case TQVariant::IconSet:
+ case TQVariant::CString:
+ case TQVariant::PointArray:
+ case TQVariant::Region:
+ case TQVariant::Bitmap:
+ case TQVariant::Cursor:
+ case TQVariant::SizePolicy:
+ case TQVariant::Time:
+#ifdef USE_QT3
+ case TQVariant::ByteArray:
+#endif // USE_QT3
+ case TQVariant::BitArray:
+ case TQVariant::KeySequence:
+ case TQVariant::Pen:
+#ifdef USE_QT4
+ case TQVariant::Char:
+ case TQVariant::Url:
+ case TQVariant::Locale:
+ case TQVariant::RectF:
+ case TQVariant::SizeF:
+ case TQVariant::Line:
+ case TQVariant::LineF:
+ case TQVariant::PointF:
+ case TQVariant::RegExp:
+ case TQVariant::Hash:
+ case TQVariant::TextLength:
+ case QVariant::TextFormat:
+ case TQVariant::Matrix:
+ case TQVariant::Transform:
+ case TQVariant::Matrix4x4:
+ case TQVariant::Vector2D:
+ case TQVariant::Vector3D:
+ case TQVariant::Vector4D:
+ case TQVariant::Quaternion:
+ case TQVariant::UserType:
+#endif // USE_QT4
+ break;
+ }
+
+ Q_ASSERT( 0 );
+}
+
+void TDEConfigBase::writeEntry ( const TQString& pKey, const TQStrList &list,
+ char sep , bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), list, sep, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry ( const char *pKey, const TQStrList &list,
+ char sep , bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ if( list.isEmpty() )
+ {
+ writeEntry( pKey, TQString::fromLatin1(""), bPersistent );
+ return;
+ }
+ TQString str_list;
+ TQStrListIterator it( list );
+ for( ; it.current(); ++it )
+ {
+ uint i;
+ TQString value;
+ // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
+ // A TQStrList may contain values in 8bit locale cpecified
+ // encoding or in UTF8 encoding.
+ value = KStringHandler::from8Bit(it.current());
+ uint strLengh(value.length());
+ for( i = 0; i < strLengh; i++ )
+ {
+ if( value[i] == sep || value[i] == '\\' )
+ str_list += '\\';
+ str_list += value[i];
+ }
+ str_list += sep;
+ }
+ if( str_list.at(str_list.length() - 1) == (QChar)sep )
+ str_list.truncate( str_list.length() -1 );
+ writeEntry( pKey, str_list, bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry ( const TQString& pKey, const TQStringList &list,
+ char sep , bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), list, sep, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry ( const char *pKey, const TQStringList &list,
+ char sep , bool bPersistent,
+ bool bGlobal, bool bNLS )
+{
+ writeEntry(pKey, list, sep, bPersistent, bGlobal, bNLS, false);
+}
+
+void TDEConfigBase::writeEntry ( const char *pKey, const TQStringList &list,
+ char sep, bool bPersistent,
+ bool bGlobal, bool bNLS, bool bExpand )
+{
+ if( list.isEmpty() )
+ {
+ writeEntry( pKey, TQString::fromLatin1(""), bPersistent );
+ return;
+ }
+ TQString str_list;
+ str_list.reserve( 4096 );
+ TQStringList::ConstIterator it = list.begin();
+ for( ; it != list.end(); ++it )
+ {
+ TQString value = *it;
+ uint i;
+ uint strLength(value.length());
+ for( i = 0; i < strLength; i++ )
+ {
+ if( value[i] == sep || value[i] == '\\' )
+ str_list += '\\';
+ str_list += value[i];
+ }
+ str_list += sep;
+ }
+ if( str_list.at(str_list.length() - 1) == (QChar)sep )
+ str_list.truncate( str_list.length() -1 );
+ writeEntry( pKey, str_list, bPersistent, bGlobal, bNLS, bExpand );
+}
+
+void TDEConfigBase::writeEntry ( const TQString& pKey, const TQValueList<int> &list,
+ bool bPersistent, bool bGlobal, bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), list, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry ( const char *pKey, const TQValueList<int> &list,
+ bool bPersistent, bool bGlobal, bool bNLS )
+{
+ TQStringList strlist;
+ TQValueList<int>::ConstIterator end = list.end();
+ for (TQValueList<int>::ConstIterator it = list.begin(); it != end; it++)
+ strlist << TQString::number(*it);
+ writeEntry(pKey, strlist, ',', bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const TQString& pKey, int nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, int nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, unsigned int nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, unsigned int nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, long nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, long nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, unsigned long nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, unsigned long nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const TQString& pKey, TQ_INT64 nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, TQ_INT64 nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, TQ_UINT64 nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, TQ_UINT64 nValue,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue), bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const TQString& pKey, double nValue,
+ bool bPersistent, bool bGlobal,
+ char format, int precision,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue, format, precision),
+ bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, double nValue,
+ bool bPersistent, bool bGlobal,
+ char format, int precision,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString::number(nValue, format, precision),
+ bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, bool bValue,
+ bool bPersistent,
+ bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), bValue, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, bool bValue,
+ bool bPersistent,
+ bool bGlobal,
+ bool bNLS )
+{
+ TQString aValue;
+
+ if( bValue )
+ aValue = "true";
+ else
+ aValue = "false";
+
+ writeEntry( pKey, aValue, bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, const TQFont& rFont,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), rFont, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQFont& rFont,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey, TQString(rFont.toString()), bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, const TQRect& rRect,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), rRect, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQRect& rRect,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ TQStrList list;
+ TQCString tempstr;
+ list.insert( 0, tempstr.setNum( rRect.left() ) );
+ list.insert( 1, tempstr.setNum( rRect.top() ) );
+ list.insert( 2, tempstr.setNum( rRect.width() ) );
+ list.insert( 3, tempstr.setNum( rRect.height() ) );
+
+ writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, const TQPoint& rPoint,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), rPoint, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQPoint& rPoint,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ TQStrList list;
+ TQCString tempstr;
+ list.insert( 0, tempstr.setNum( rPoint.x() ) );
+ list.insert( 1, tempstr.setNum( rPoint.y() ) );
+
+ writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
+}
+
+
+void TDEConfigBase::writeEntry( const TQString& pKey, const TQSize& rSize,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), rSize, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQSize& rSize,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ TQStrList list;
+ TQCString tempstr;
+ list.insert( 0, tempstr.setNum( rSize.width() ) );
+ list.insert( 1, tempstr.setNum( rSize.height() ) );
+
+ writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const TQString& pKey, const TQColor& rColor,
+ bool bPersistent,
+ bool bGlobal,
+ bool bNLS )
+{
+ writeEntry( pKey.utf8().data(), rColor, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQColor& rColor,
+ bool bPersistent,
+ bool bGlobal,
+ bool bNLS )
+{
+ TQString aValue;
+ if (rColor.isValid())
+ aValue.sprintf( "%d,%d,%d", rColor.red(), rColor.green(), rColor.blue() );
+ else
+ aValue = "invalid";
+
+ writeEntry( pKey, aValue, bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::writeEntry( const TQString& pKey, const TQDateTime& rDateTime,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ writeEntry(pKey.utf8().data(), rDateTime, bPersistent, bGlobal, bNLS);
+}
+
+void TDEConfigBase::writeEntry( const char *pKey, const TQDateTime& rDateTime,
+ bool bPersistent, bool bGlobal,
+ bool bNLS )
+{
+ TQStrList list;
+ TQCString tempstr;
+
+ TQTime time = TQT_TQTIME_OBJECT(rDateTime.time());
+ TQDate date = TQT_TQDATE_OBJECT(rDateTime.date());
+
+ list.insert( 0, tempstr.setNum( date.year() ) );
+ list.insert( 1, tempstr.setNum( date.month() ) );
+ list.insert( 2, tempstr.setNum( date.day() ) );
+
+ list.insert( 3, tempstr.setNum( time.hour() ) );
+ list.insert( 4, tempstr.setNum( time.minute() ) );
+ list.insert( 5, tempstr.setNum( time.second() ) );
+
+ writeEntry( pKey, list, ',', bPersistent, bGlobal, bNLS );
+}
+
+void TDEConfigBase::parseConfigFiles()
+{
+ if (!bLocaleInitialized && TDEGlobal::_locale) {
+ setLocale();
+ }
+ if (backEnd)
+ {
+ backEnd->parseConfigFiles();
+ bReadOnly = (backEnd->getConfigState() == ReadOnly);
+ }
+}
+
+void TDEConfigBase::sync()
+{
+ if (isReadOnly())
+ return;
+
+ if (backEnd)
+ backEnd->sync();
+ if (bDirty)
+ rollback();
+}
+
+TDEConfigBase::ConfigState TDEConfigBase::getConfigState() const {
+ if (backEnd)
+ return backEnd->getConfigState();
+ return ReadOnly;
+}
+
+void TDEConfigBase::rollback( bool /*bDeep = true*/ )
+{
+ bDirty = false;
+}
+
+
+void TDEConfigBase::setReadDefaults(bool b)
+{
+ if (!d)
+ {
+ if (!b) return;
+ d = new TDEConfigBasePrivate();
+ }
+
+ d->readDefaults = b;
+}
+
+bool TDEConfigBase::readDefaults() const
+{
+ return (d && d->readDefaults);
+}
+
+void TDEConfigBase::revertToDefault(const TQString &key)
+{
+ setDirty(true);
+
+ KEntryKey aEntryKey(mGroup, key.utf8());
+ aEntryKey.bDefault = true;
+
+ if (!locale().isNull()) {
+ // try the localized key first
+ aEntryKey.bLocal = true;
+ KEntry entry = lookupData(aEntryKey);
+ if (entry.mValue.isNull())
+ entry.bDeleted = true;
+
+ entry.bDirty = true;
+ putData(aEntryKey, entry, true); // Revert
+ aEntryKey.bLocal = false;
+ }
+
+ // try the non-localized version
+ KEntry entry = lookupData(aEntryKey);
+ if (entry.mValue.isNull())
+ entry.bDeleted = true;
+ entry.bDirty = true;
+ putData(aEntryKey, entry, true); // Revert
+}
+
+bool TDEConfigBase::hasDefault(const TQString &key) const
+{
+ KEntryKey aEntryKey(mGroup, key.utf8());
+ aEntryKey.bDefault = true;
+
+ if (!locale().isNull()) {
+ // try the localized key first
+ aEntryKey.bLocal = true;
+ KEntry entry = lookupData(aEntryKey);
+ if (!entry.mValue.isNull())
+ return true;
+
+ aEntryKey.bLocal = false;
+ }
+
+ // try the non-localized version
+ KEntry entry = lookupData(aEntryKey);
+ if (!entry.mValue.isNull())
+ return true;
+
+ return false;
+}
+
+
+
+TDEConfigGroup::TDEConfigGroup(TDEConfigBase *master, const TQString &group)
+{
+ mMaster = master;
+ backEnd = mMaster->backEnd; // Needed for getConfigState()
+ bLocaleInitialized = true;
+ bReadOnly = mMaster->bReadOnly;
+ bExpand = false;
+ bDirty = false; // Not used
+ mGroup = group.utf8();
+ aLocaleString = mMaster->aLocaleString;
+ setReadDefaults(mMaster->readDefaults());
+}
+
+TDEConfigGroup::TDEConfigGroup(TDEConfigBase *master, const TQCString &group)
+{
+ mMaster = master;
+ backEnd = mMaster->backEnd; // Needed for getConfigState()
+ bLocaleInitialized = true;
+ bReadOnly = mMaster->bReadOnly;
+ bExpand = false;
+ bDirty = false; // Not used
+ mGroup = group;
+ aLocaleString = mMaster->aLocaleString;
+ setReadDefaults(mMaster->readDefaults());
+}
+
+TDEConfigGroup::TDEConfigGroup(TDEConfigBase *master, const char * group)
+{
+ mMaster = master;
+ backEnd = mMaster->backEnd; // Needed for getConfigState()
+ bLocaleInitialized = true;
+ bReadOnly = mMaster->bReadOnly;
+ bExpand = false;
+ bDirty = false; // Not used
+ mGroup = group;
+ aLocaleString = mMaster->aLocaleString;
+ setReadDefaults(mMaster->readDefaults());
+}
+
+void TDEConfigGroup::deleteGroup(bool bGlobal)
+{
+ mMaster->deleteGroup(TDEConfigBase::group(), true, bGlobal);
+}
+
+bool TDEConfigGroup::groupIsImmutable() const
+{
+ return mMaster->groupIsImmutable(TDEConfigBase::group());
+}
+
+void TDEConfigGroup::setDirty(bool _bDirty)
+{
+ mMaster->setDirty(_bDirty);
+}
+
+void TDEConfigGroup::putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup)
+{
+ mMaster->putData(_key, _data, _checkGroup);
+}
+
+KEntry TDEConfigGroup::lookupData(const KEntryKey &_key) const
+{
+ return mMaster->lookupData(_key);
+}
+
+void TDEConfigGroup::sync()
+{
+ mMaster->sync();
+}
+
+void TDEConfigBase::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+void TDEConfigGroup::virtual_hook( int id, void* data )
+{ TDEConfigBase::virtual_hook( id, data ); }
+
+bool TDEConfigBase::checkConfigFilesWritable(bool warnUser)
+{
+ if (backEnd)
+ return backEnd->checkConfigFilesWritable(warnUser);
+ else
+ return false;
+}
+
+#include "tdeconfigbase.moc"
diff --git a/tdecore/tdeconfigbase.h b/tdecore/tdeconfigbase.h
new file mode 100644
index 000000000..b9522dcb6
--- /dev/null
+++ b/tdecore/tdeconfigbase.h
@@ -0,0 +1,2180 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 1999 Preston Brown <pbrown@kde.org>
+ Copyright (c) 1997 Matthias Kalle Dalheimer <kalle@kde.org>
+ Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KCONFIGBASE_H
+#define _KCONFIGBASE_H
+
+#include <tqobject.h>
+#include <tqcolor.h>
+#include <tqfont.h>
+#include <tqdatetime.h>
+#include <tqstrlist.h>
+#include <tqstringlist.h>
+#include <tqvariant.h>
+#include <tqmap.h>
+
+#include "tdeconfigdata.h"
+#include "tdelibs_export.h"
+
+class TDEConfigBackEnd;
+class TDEConfigBasePrivate;
+class TDEConfigGroup;
+
+/**
+ * @short KDE Configuration Management abstract base class
+ *
+ * This class forms the base for all %KDE configuration. It is an
+ * abstract base class, meaning that you cannot directly instantiate
+ * objects of this class. Either use TDEConfig (for usual %KDE
+ * configuration) or KSimpleConfig (for special needs as in ksamba), or
+ * even KSharedConfig (stores values in shared memory).
+ *
+ * All configuration entries are key, value pairs. Each entry also
+ * belongs to a specific group of related entries. All configuration
+ * entries that do not explicitly specify which group they are in are
+ * in a special group called the default group.
+ *
+ * If there is a $ character in an entry, TDEConfigBase tries to expand
+ * environment variable and uses its value instead of its name. You
+ * can avoid this feature by having two consecutive $ characters in
+ * your config file which get expanded to one.
+ *
+ * \note the '=' char is not allowed in keys and the ']' char is not allowed in
+ * a group name.
+ *
+ * @author Kalle Dalheimer <kalle@kde.org>, Preston Brown <pbrown@kde.org>
+ * @see TDEGlobal#config()
+ * @see TDEConfig
+ * @see KSimpleConfig
+ * @see KSharedConfig
+ */
+class TDECORE_EXPORT TDEConfigBase : public TQObject
+{
+ Q_OBJECT
+
+
+ friend class TDEConfigBackEnd;
+ friend class TDEConfigINIBackEnd;
+ friend class TDEConfigGroup;
+
+public:
+ /**
+ * Construct a TDEConfigBase object.
+ */
+ TDEConfigBase();
+
+ /**
+ * Destructs the TDEConfigBase object.
+ */
+ virtual ~TDEConfigBase();
+
+ /**
+ * Specifies the group in which keys will be read and written.
+ *
+ * Subsequent
+ * calls to readEntry() and writeEntry() will be applied only in the
+ * activated group.
+ *
+ * Switch back to the default group by passing a null string.
+ * @param group The name of the new group.
+ */
+ void setGroup( const TQString& group );
+
+ /**
+ * Sets the group to the "Desktop Entry" group used for
+ * desktop configuration files for applications, mime types, etc.
+ */
+ void setDesktopGroup();
+
+ /**
+ * Returns the name of the group in which we are
+ * searching for keys and from which we are retrieving entries.
+ *
+ * @return The current group.
+ */
+ TQString group() const;
+
+ /**
+ * Returns true if the specified group is known about.
+ *
+ * @param group The group to search for.
+ * @return true if the group exists.
+ */
+ bool hasGroup(const TQString &group) const;
+
+ /**
+ * Returns a list of groups that are known about.
+ *
+ * @return The list of groups.
+ **/
+ virtual TQStringList groupList() const = 0;
+
+ /**
+ * Returns a the current locale.
+ *
+ * @return A string representing the current locale.
+ */
+ TQString locale() const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ * If you want to read a path, please use readPathEntry().
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found.
+ * @return The value for this key. Can be TQString::null if aDefault is null.
+ */
+ TQString readEntry(const TQString& pKey,
+ const TQString& aDefault = TQString::null ) const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found.
+ * @return The value for this key. Can be TQString::null if aDefault is null.
+ */
+ TQString readEntry(const char *pKey,
+ const TQString& aDefault = TQString::null ) const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ * The value is treated as if it is of the given type.
+ *
+ * Note that only the following TQVariant types are allowed : String,
+ * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
+ * Double, DateTime and Date.
+ * @deprecated
+ *
+ * @param pKey The key to search for.
+ * @return An invalid TQVariant if the key was not found or if the
+ * read value cannot be converted to the given TQVariant::Type.
+ */
+ TQVariant readPropertyEntry( const TQString& pKey, TQVariant::Type ) const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ * The value is treated as if it is of the given type.
+ *
+ * Note that only the following TQVariant types are allowed : String,
+ * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
+ * Double, DateTime and Date.
+ *
+ * @deprecated
+ *
+ * @param pKey The key to search for.
+ * @return An invalid TQVariant if the key was not found or if the
+ * read value cannot be converted to the given TQVariant::Type.
+ */
+ TQVariant readPropertyEntry( const char *pKey, TQVariant::Type ) const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ * The value is treated as if it is of the type of the given default value.
+ *
+ * Note that only the following TQVariant types are allowed : String,
+ * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
+ * Double, DateTime and Date.
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found or
+ * if the read value cannot be converted to the TQVariant::Type.
+ * @return The value for the key or the default value if the key was not
+ * found.
+ */
+ TQVariant readPropertyEntry( const TQString& pKey,
+ const TQVariant &aDefault) const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ * The value is treated as if it is of the type of the given default value.
+ *
+ * Note that only the following TQVariant types are allowed : String,
+ * StringList, List, Font, Point, Rect, Size, Color, Int, UInt, Bool,
+ * Double, DateTime and Date.
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found or
+ * if the read value cannot be converted to the TQVariant::Type.
+ * @return The value for the key or the default value if the key was not
+ * found.
+ */
+ TQVariant readPropertyEntry( const char *pKey,
+ const TQVariant &aDefault) const;
+
+ /**
+ * Reads a list of strings.
+ *
+ * @deprecated
+ *
+ * @param pKey The key to search for
+ * @param list In this object, the read list will be returned.
+ * @param sep The list separator (default ",")
+ * @return The number of entries in the list.
+ */
+ int readListEntry( const TQString& pKey, TQStrList &list, char sep = ',' ) const;
+
+ /**
+ * Reads a list of strings.
+ *
+ * @deprecated
+ *
+ * @param pKey The key to search for
+ * @param list In this object, the read list will be returned.
+ * @param sep The list separator (default ",")
+ * @return The number of entries in the list.
+ */
+ int readListEntry( const char *pKey, TQStrList &list, char sep = ',' ) const;
+
+ /**
+ * Reads a list of strings.
+ *
+ * @param pKey The key to search for.
+ * @param sep The list separator (default is ",").
+ * @return The list. Empty if the entry does not exist.
+ */
+ TQStringList readListEntry( const TQString& pKey, char sep = ',' ) const;
+
+ /**
+ * Reads a list of strings.
+ *
+ * @param pKey The key to search for.
+ * @param sep The list separator (default is ",").
+ * @return The list. Empty if the entry does not exist.
+ */
+ TQStringList readListEntry( const char *pKey, char sep = ',' ) const;
+
+ /**
+ * Reads a list of strings, but returns a default if the key
+ * did not exist.
+ * @param pKey The key to search for.
+ * @param aDefault The default value to use if the key does not exist.
+ * @param sep The list separator (default is ",").
+ * @return The list. Contains @p aDefault if the Key does not exist.
+ * @since 3.3
+ */
+ TQStringList readListEntry( const char* pKey, const TQStringList& aDefault,
+ char sep = ',' ) const;
+
+ /**
+ * Reads a list of Integers.
+ *
+ * @param pKey The key to search for.
+ * @return The list. Empty if the entry does not exist.
+ */
+ TQValueList<int> readIntListEntry( const TQString& pKey ) const;
+
+ /**
+ * Reads a list of Integers.
+ *
+ * @param pKey The key to search for.
+ * @return The list. Empty if the entry does not exist.
+ */
+ TQValueList<int> readIntListEntry( const char *pKey ) const;
+
+ /**
+ * Reads a path.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a path. This means, dollar expansion is activated
+ * for this value, so that e.g. $HOME gets expanded.
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found.
+ * @return The value for this key. Can be TQString::null if aDefault is null.
+ */
+ TQString readPathEntry( const TQString& pKey, const TQString & aDefault = TQString::null ) const;
+
+ /**
+ * Reads a path.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a path. This means, dollar expansion is activated
+ * for this value, so that e.g. $HOME gets expanded.
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found.
+ * @return The value for this key. Can be TQString::null if aDefault is null.
+ */
+ TQString readPathEntry( const char *pKey, const TQString & aDefault = TQString::null ) const;
+
+ /**
+ * Reads a list of string paths.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a list of paths. This means, dollar expansion is activated
+ * for this value, so that e.g. $HOME gets expanded.
+ *
+ * @param pKey The key to search for.
+ * @param sep The list separator (default is ",").
+ * @return The list. Empty if the entry does not exist.
+ * @since 3.1.3
+ */
+ TQStringList readPathListEntry( const TQString& pKey, char sep = ',' ) const;
+
+ /**
+ * Reads a list of string paths.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a list of paths. This means, dollar expansion is activated
+ * for this value, so that e.g. $HOME gets expanded.
+ *
+ * @param pKey The key to search for.
+ * @param sep The list separator (default is ",").
+ * @return The list. Empty if the entry does not exist.
+ * @since 3.1.3
+ */
+ TQStringList readPathListEntry( const char *pKey, char sep = ',' ) const;
+
+
+ /**
+ * Reads a numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ int readNumEntry( const TQString& pKey, int nDefault = 0 ) const;
+
+ /**
+ * Reads a numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ int readNumEntry( const char *pKey, int nDefault = 0 ) const;
+
+ /**
+ * Reads an unsigned numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ unsigned int readUnsignedNumEntry( const TQString& pKey, unsigned int nDefault = 0 ) const;
+
+ /**
+ * Reads an unsigned numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ unsigned int readUnsignedNumEntry( const char *pKey, unsigned int nDefault = 0 ) const;
+
+
+ /**
+ * Reads a numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ long readLongNumEntry( const TQString& pKey, long nDefault = 0 ) const;
+
+ /**
+ * Reads a numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ long readLongNumEntry( const char *pKey, long nDefault = 0 ) const;
+
+ /**
+ * Read an unsigned numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ unsigned long readUnsignedLongNumEntry( const TQString& pKey, unsigned long nDefault = 0 ) const;
+
+ /**
+ * Read an unsigned numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ unsigned long readUnsignedLongNumEntry( const char *pKey, unsigned long nDefault = 0 ) const;
+
+ /**
+ * Reads a 64-bit numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQ_INT64 readNum64Entry( const TQString& pKey, TQ_INT64 nDefault = 0 ) const;
+
+ /**
+ * Reads a 64-bit numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQ_INT64 readNum64Entry( const char *pKey, TQ_INT64 nDefault = 0 ) const;
+
+ /**
+ * Read an 64-bit unsigned numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQ_UINT64 readUnsignedNum64Entry( const TQString& pKey, TQ_UINT64 nDefault = 0 ) const;
+
+ /**
+ * Read an 64-bit unsigned numerical value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQ_UINT64 readUnsignedNum64Entry( const char *pKey, TQ_UINT64 nDefault = 0 ) const;
+
+ /**
+ * Reads a floating point value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ double readDoubleNumEntry( const TQString& pKey, double nDefault = 0.0 ) const;
+
+ /**
+ * Reads a floating point value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it numerically.
+ *
+ * @param pKey The key to search for.
+ * @param nDefault A default value returned if the key was not found or if
+ * the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ double readDoubleNumEntry( const char *pKey, double nDefault = 0.0 ) const;
+
+ /**
+ * Reads a TQFont value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a font object.
+ *
+ * @param pKey The key to search for.
+ * @param pDefault A default value (null TQFont by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQFont readFontEntry( const TQString& pKey, const TQFont* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQFont value.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a font object.
+ *
+ * @param pKey The key to search for.
+ * @param pDefault A default value (null TQFont by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQFont readFontEntry( const char *pKey, const TQFont* pDefault = 0L ) const;
+
+ /**
+ * Reads a boolean entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a boolean value. Currently "on", "yes", "1" and
+ * "true" are accepted as true, everything else if false.
+ *
+ * @param pKey The key to search for
+ * @param bDefault A default value returned if the key was not found.
+ * @return The value for this key.
+ */
+ bool readBoolEntry( const TQString& pKey, bool bDefault = false ) const;
+
+ /**
+ * Reads a boolean entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a boolean value. Currently "on", "yes", "1" and
+ * "true" are accepted as true, everything else if false.
+ *
+ * @param pKey The key to search for
+ * @param bDefault A default value returned if the key was not found.
+ * @return The value for this key.
+ */
+ bool readBoolEntry( const char *pKey, bool bDefault = false ) const;
+
+ /**
+ * Reads a TQRect entry.
+ *
+ * Read the value of an entry specified by pKey in the current group
+ * and interpret it as a TQRect object.
+ *
+ * @param pKey The key to search for
+ * @param pDefault A default value (null TQRect by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQRect readRectEntry( const TQString& pKey, const TQRect* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQRect entry.
+ *
+ * Read the value of an entry specified by pKey in the current group
+ * and interpret it as a TQRect object.
+ *
+ * @param pKey The key to search for
+ * @param pDefault A default value (null TQRect by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQRect readRectEntry( const char *pKey, const TQRect* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQPoint entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a TQPoint object.
+ *
+ * @param pKey The key to search for
+ * @param pDefault A default value (null TQPoint by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQPoint readPointEntry( const TQString& pKey, const TQPoint* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQPoint entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a TQPoint object.
+ *
+ * @param pKey The key to search for
+ * @param pDefault A default value (null TQPoint by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQPoint readPointEntry( const char *pKey, const TQPoint* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQSize entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a TQSize object.
+ *
+ * @param pKey The key to search for
+ * @param pDefault A default value (null TQSize by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQSize readSizeEntry( const TQString& pKey, const TQSize* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQSize entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a TQSize object.
+ *
+ * @param pKey The key to search for
+ * @param pDefault A default value (null TQSize by default) returned if the
+ * key was not found or if the read value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQSize readSizeEntry( const char *pKey, const TQSize* pDefault = 0L ) const;
+
+
+ /**
+ * Reads a TQColor entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a color.
+ *
+ * @param pKey The key to search for.
+ * @param pDefault A default value (null TQColor by default) returned if the
+ * key was not found or if the value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQColor readColorEntry( const TQString& pKey, const TQColor* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQColor entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a color.
+ *
+ * @param pKey The key to search for.
+ * @param pDefault A default value (null TQColor by default) returned if the
+ * key was not found or if the value cannot be interpreted.
+ * @return The value for this key.
+ */
+ TQColor readColorEntry( const char *pKey, const TQColor* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQDateTime entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a date and time.
+ *
+ * @param pKey The key to search for.
+ * @param pDefault A default value ( currentDateTime() by default)
+ * returned if the key was not found or if the read value cannot be
+ * interpreted.
+ * @return The value for this key.
+ */
+ TQDateTime readDateTimeEntry( const TQString& pKey, const TQDateTime* pDefault = 0L ) const;
+
+ /**
+ * Reads a TQDateTime entry.
+ *
+ * Read the value of an entry specified by @p pKey in the current group
+ * and interpret it as a date and time.
+ *
+ * @param pKey The key to search for.
+ * @param pDefault A default value ( currentDateTime() by default)
+ * returned if the key was not found or if the read value cannot be
+ * interpreted.
+ * @return The value for this key.
+ */
+ TQDateTime readDateTimeEntry( const char *pKey, const TQDateTime* pDefault = 0L ) const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ * The untranslated entry is returned, you normally do not need this.
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found.
+ * @return The value for this key.
+ */
+ TQString readEntryUntranslated( const TQString& pKey,
+ const TQString& aDefault = TQString::null ) const;
+
+ /**
+ * Reads the value of an entry specified by @p pKey in the current group.
+ * The untranslated entry is returned, you normally do not need this.
+ *
+ * @param pKey The key to search for.
+ * @param aDefault A default value returned if the key was not found.
+ * @return The value for this key.
+ */
+ TQString readEntryUntranslated( const char *pKey,
+ const TQString& aDefault = TQString::null ) const;
+
+ /**
+ * Writes a key/value pair.
+ *
+ * This is stored in the most specific config file when destroying the
+ * config object or when calling sync().
+ *
+ * If you want to write a path, please use writePathEntry().
+ *
+ * @param pKey The key to write.
+ * @param pValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will
+ * not be written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const TQString& pValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a key/value pair.
+ *
+ * This is stored in the most specific config file when destroying the
+ * config object or when calling sync().
+ *
+ * @param pKey The key to write.
+ * @param pValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will
+ * not be written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const TQString& pValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * writeEntry() Overridden to accept a property.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The property to write
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const TQString& pKey, const TQVariant& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * writeEntry() Overridden to accept a property.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The property to write
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const char *pKey, const TQVariant& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * writeEntry() overridden to accept a list of strings.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param sep The list separator (default is ",").
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const TQString& pKey, const TQStrList &rValue,
+ char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+ /**
+ * writeEntry() overridden to accept a list of strings.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param sep The list separator (default is ",").
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const char *pKey, const TQStrList &rValue,
+ char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+
+ /**
+ * writeEntry() overridden to accept a list of strings.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param sep The list separator (default is ",").
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const TQString& pKey, const TQStringList &rValue,
+ char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+ /**
+ * writeEntry() overridden to accept a list of strings.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param sep The list separator (default is ",").
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const char *pKey, const TQStringList &rValue,
+ char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+
+
+ /**
+ * writeEntry() overridden to accept a list of Integers.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const TQString& pKey, const TQValueList<int>& rValue,
+ bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+ /**
+ * writeEntry() overridden to accept a list of Integers.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writeEntry()
+ */
+ void writeEntry( const char *pKey, const TQValueList<int>& rValue,
+ bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+
+ /**
+ * Write a (key/value) pair.
+ *
+ * This is stored to the most specific config file when destroying the
+ * config object or when calling sync().
+ *
+ * @param pKey The key to write.
+ * @param pValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will
+ * not be written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const char *pValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false )
+ { writeEntry(pKey, TQString::fromLatin1(pValue), bPersistent, bGlobal, bNLS); }
+ /**
+ * Write a (key/value) pair.
+ *
+ * This is stored to the most specific config file when destroying the
+ * config object or when calling sync().
+ *
+ * @param pKey The key to write.
+ * @param pValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will
+ * not be written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const char *pValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false )
+ { writeEntry(pKey, TQString::fromLatin1(pValue), bPersistent, bGlobal, bNLS); }
+
+ /**
+ * Write a (key/value) pair.
+ * Same as above, but writes a numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, int nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Write a (key/value) pair.
+ * Same as above, but writes a numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, int nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes an unsigned numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, unsigned int nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes an unsigned numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, unsigned int nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but write a long numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, long nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but write a long numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, long nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes an unsigned long numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, unsigned long nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes an unsigned long numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, unsigned long nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but write a 64-bit numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, TQ_INT64 nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but write a long numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, TQ_INT64 nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes an unsigned 64-bit numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, TQ_UINT64 nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes an unsigned 64-bit numerical value.
+ *
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, TQ_UINT64 nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a floating-point value.
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param format @p format determines the format to which the value
+ * is converted. Default is 'g'.
+ * @param precision @p precision sets the precision with which the
+ * value is converted. Default is 6 as in TQString.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, double nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ char format = 'g', int precision = 6,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a floating-point value.
+ * @param pKey The key to write.
+ * @param nValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param format @p format determines the format to which the value
+ * is converted. Default is 'g'.
+ * @param precision @p precision sets the precision with which the
+ * value is converted. Default is 6 as in TQString.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, double nValue,
+ bool bPersistent = true, bool bGlobal = false,
+ char format = 'g', int precision = 6,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a boolean value.
+ *
+ * @param pKey The key to write.
+ * @param bValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, bool bValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a boolean value.
+ *
+ * @param pKey The key to write.
+ * @param bValue The value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, bool bValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a font value.
+ *
+ * @param pKey The key to write.
+ * @param rFont The font value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const TQFont& rFont,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a font value.
+ *
+ * @param pKey The key to write.
+ * @param rFont The font value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const TQFont& rFont,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but write a color entry.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rColor The color value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const TQColor& rColor,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but write a color entry.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rColor The color value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const TQColor& rColor,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a date and time entry.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * @em not returned here!
+ *
+ * @param pKey The key to write.
+ * @param rDateTime The date and time value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const TQDateTime& rDateTime,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a date and time entry.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * @em not returned here!
+ *
+ * @param pKey The key to write.
+ * @param rDateTime The date and time value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const TQDateTime& rDateTime,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a rectangle.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rValue The rectangle value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const TQRect& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a rectangle.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rValue The rectangle value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const TQRect& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a point.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rValue The point value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const TQPoint& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a point.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rValue The point value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const TQPoint& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a size.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rValue The size value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const TQString& pKey, const TQSize& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a (key/value) pair.
+ * Same as above, but writes a size.
+ *
+ * Note: Unlike the other writeEntry() functions, the old value is
+ * _not_ returned here!
+ *
+ * @param pKey The key to write.
+ * @param rValue The size value to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writeEntry( const char *pKey, const TQSize& rValue,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * Writes a file path.
+ *
+ * It is checked whether the path is located under $HOME. If so the
+ * path is written out with the user's home-directory replaced with
+ * $HOME. The path should be read back with readPathEntry()
+ *
+ * @param pKey The key to write.
+ * @param path The path to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writePathEntry( const TQString& pKey, const TQString & path,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+ /**
+ * Writes a file path.
+ *
+ * It is checked whether the path is located under $HOME. If so the
+ * path is written out with the user's home-directory replaced with
+ * $HOME. The path should be read back with readPathEntry()
+ *
+ * @param pKey The key to write.
+ * @param path The path to write.
+ * @param bPersistent If @p bPersistent is false, the entry's dirty
+ * flag will not be set and thus the entry will not be written to
+ * disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ */
+ void writePathEntry( const char *pKey, const TQString & path,
+ bool bPersistent = true, bool bGlobal = false,
+ bool bNLS = false );
+
+ /**
+ * writePathEntry() overridden to accept a list of paths (strings).
+ *
+ * It is checked whether the paths are located under $HOME. If so each of
+ * the paths are written out with the user's home-directory replaced with
+ * $HOME. The paths should be read back with readPathListEntry()
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param sep The list separator (default is ",").
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writePathEntry()
+ * @see readPathListEntry()
+ * @since 3.1.3
+ */
+ void writePathEntry( const TQString& pKey, const TQStringList &rValue,
+ char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+ /**
+ * writePathEntry() overridden to accept a list of paths (strings).
+ *
+ * It is checked whether the paths are located under $HOME. If so each of
+ * the paths are written out with the user's home-directory replaced with
+ * $HOME. The paths should be read back with readPathListEntry()
+ *
+ * @param pKey The key to write
+ * @param rValue The list to write
+ * @param sep The list separator (default is ",").
+ * @param bPersistent If @p bPersistent is false, the entry's dirty flag
+ * will not be set and thus the entry will not be
+ * written to disk at deletion time.
+ * @param bGlobal If @p bGlobal is true, the pair is not saved to the
+ * application specific config file, but to the
+ * global KDE config file.
+ * @param bNLS If @p bNLS is true, the locale tag is added to the key
+ * when writing it back.
+ *
+ * @see writePathEntry()
+ * @see readPathListEntry()
+ * @since 3.1.3
+ */
+ void writePathEntry( const char *pKey, const TQStringList &rValue,
+ char sep = ',', bool bPersistent = true, bool bGlobal = false, bool bNLS = false );
+
+
+ /**
+ * Deletes the entry specified by @p pKey in the current group.
+ *
+ * @param pKey The key to delete.
+ * @param bGlobal If @p bGlobal is true, the pair is not removed from the
+ * application specific config file, but to the global KDE config file.
+ * @param bNLS If @p bNLS is true, the key with the locale tag is removed.
+ */
+ void deleteEntry( const TQString& pKey,
+ bool bNLS = false, bool bGlobal = false);
+ /**
+ * Deletes the entry specified by @p pKey in the current group.
+ *
+ * @param pKey The key to delete.
+ * @param bGlobal If @p bGlobal is true, the pair is not removed from the
+ * application specific config file, but from the global KDE config file.
+ * @param bNLS If @p bNLS is true, the key with the locale tag is removed.
+ */
+ void deleteEntry( const char *pKey,
+ bool bNLS = false, bool bGlobal = false);
+
+ /**
+ * Deletes a configuration entry group
+ *
+ * If the group is not empty and bDeep is false, nothing gets
+ * deleted and false is returned.
+ * If this group is the current group and it is deleted, the
+ * current group is undefined and should be set with setGroup()
+ * before the next operation on the configuration object.
+ *
+ * @param group The name of the group
+ * @param bDeep Specify whether non-empty groups should be completely
+ * deleted (including their entries).
+ * @param bGlobal If @p bGlobal is true, the group is not removed from the
+ * application specific config file, but from the global KDE config file.
+ * @return If the group is not empty and bDeep is false,
+ * deleteGroup returns false.
+ */
+ bool deleteGroup( const TQString& group, bool bDeep = true, bool bGlobal = false );
+
+
+ /**
+ * Turns on or off "dollar expansion" (see TDEConfigBase introduction)
+ * when reading config entries.
+ * Dollar sign expansion is initially OFF.
+ *
+ * @param _bExpand Tf true, dollar expansion is turned on.
+ */
+ void setDollarExpansion( bool _bExpand = true ) { bExpand = _bExpand; }
+
+ /**
+ * Returns whether dollar expansion is on or off. It is initially OFF.
+ *
+ * @return true if dollar expansion is on.
+ */
+ bool isDollarExpansion() const { return bExpand; }
+
+ /**
+ * Mark the config object as "clean," i.e. don't write dirty entries
+ * at destruction time. If @p bDeep is false, only the global dirty
+ * flag of the TDEConfig object gets cleared. If you then call
+ * writeEntry() again, the global dirty flag is set again and all
+ * dirty entries will be written at a subsequent sync() call.
+ *
+ * Classes that derive from TDEConfigBase should override this
+ * method and implement storage-specific behavior, as well as
+ * calling the TDEConfigBase::rollback() explicitly in the initializer.
+ *
+ * @param bDeep If true, the dirty flags of all entries are cleared,
+ * as well as the global dirty flag.
+ */
+ virtual void rollback( bool bDeep = true );
+
+ /**
+ * Flushes all changes that currently reside only in memory
+ * back to disk / permanent storage. Dirty configuration entries are
+ * written to the most specific file available.
+ *
+ * Asks the back end to flush out all pending writes, and then calls
+ * rollback(). No changes are made if the object has @p readOnly
+ * status.
+ *
+ * You should call this from your destructor in derivative classes.
+ *
+ * @see rollback(), #isReadOnly()
+ */
+ virtual void sync();
+
+ /**
+ * Checks whether the config file has any dirty (modified) entries.
+ * @return true if the config file has any dirty (modified) entries.
+ */
+ bool isDirty() const { return bDirty; }
+
+ /**
+ * Sets the config object's read-only status.
+ *
+ * @param _ro If true, the config object will not write out any
+ * changes to disk even if it is destroyed or sync() is called.
+ *
+ */
+ virtual void setReadOnly(bool _ro) { bReadOnly = _ro; }
+
+ /**
+ * Returns the read-only status of the config object.
+ *
+ * @return The read-only status.
+ */
+ bool isReadOnly() const { return bReadOnly; }
+
+ /**
+ * Checks whether the key has an entry in the currently active group.
+ * Use this to determine whether a key is not specified for the current
+ * group (hasKey() returns false). Keys with null data are considered
+ * nonexistent.
+ *
+ * @param key The key to search for.
+ * @return If true, the key is available.
+ */
+ bool hasKey( const TQString& key ) const;
+
+ /**
+ * Returns a map (tree) of entries for all entries in a particular
+ * group. Only the actual entry string is returned, none of the
+ * other internal data should be included.
+ *
+ * @param group A group to get keys from.
+ * @return A map of entries in the group specified, indexed by key.
+ * The returned map may be empty if the group is not found.
+ * @see QMap
+ */
+ virtual TQMap<TQString, TQString> entryMap(const TQString &group) const = 0;
+
+ /**
+ * Reparses all configuration files. This is useful for programs
+ * that use stand alone graphical configuration tools. The base
+ * method implemented here only clears the group list and then
+ * appends the default group.
+ *
+ * Derivative classes should clear any internal data structures and
+ * then simply call parseConfigFiles() when implementing this
+ * method.
+ *
+ * @see parseConfigFiles()
+ */
+ virtual void reparseConfiguration() = 0;
+
+ /**
+ * Checks whether this configuration file can be modified.
+ * @return whether changes may be made to this configuration file.
+ */
+ bool isImmutable() const;
+
+ /**
+ * Checks whether it is possible to change the given group.
+ * @param group the group to check
+ * @return whether changes may be made to @p group in this configuration
+ * file.
+ */
+ bool groupIsImmutable(const TQString &group) const;
+
+ /**
+ * Checks whether it is possible to change the given entry.
+ * @param key the key to check
+ * @return whether the entry @p key may be changed in the current group
+ * in this configuration file.
+ */
+ bool entryIsImmutable(const TQString &key) const;
+
+ /**
+ * Possible return values for getConfigState().
+ *
+ * @see getConfigState()
+ */
+ enum ConfigState { NoAccess, ReadOnly, ReadWrite };
+
+ /**
+ * Returns the state of the app-config object.
+ *
+ * Possible return values
+ * are NoAccess (the application-specific config file could not be
+ * opened neither read-write nor read-only), ReadOnly (the
+ * application-specific config file is opened read-only, but not
+ * read-write) and ReadWrite (the application-specific config
+ * file is opened read-write).
+ *
+ * @see ConfigState()
+ * @return the state of the app-config object
+ */
+ ConfigState getConfigState() const;
+
+ /**
+ * Check whether the config files are writable.
+ * @param warnUser Warn the user if the configuration files are not writable.
+ * @return Indicates that all of the configuration files used are writable.
+ * @since 3.2
+ */
+ bool checkConfigFilesWritable(bool warnUser);
+
+ /**
+ * When set, all readEntry and readXXXEntry calls return the system
+ * wide (default) values instead of the user's preference.
+ * This is off by default.
+ * @since 3.2
+ */
+ void setReadDefaults(bool b);
+
+ /**
+ * @returns true if all readEntry and readXXXEntry calls return the system
+ * wide (default) values instead of the user's preference.
+ * @since 3.2
+ */
+ bool readDefaults() const;
+
+ /**
+ * Reverts the entry with key @p key in the current group in the
+ * application specific config file to either the system wide (default)
+ * value or the value specified in the global KDE config file.
+ *
+ * To revert entries in the global KDE config file, the global KDE config
+ * file should be opened explicitly in a separate config object.
+ *
+ * @param key The key of the entry to revert.
+ * @since 3.2
+ */
+ void revertToDefault(const TQString &key);
+
+ /**
+ * Returns whether a default is specified for an entry in either the
+ * system wide configuration file or the global KDE config file.
+ *
+ * If an application computes a default value at runtime for
+ * a certain entry, e.g. like:
+ * \code
+ * TQColor computedDefault = kapp->palette().color(TQPalette::Active, TQColorGroup::Text)
+ * TQColor color = config->readEntry(key, computedDefault);
+ * \encode
+ *
+ * Then it may wish to make the following check before
+ * writing back changes:
+ * \code
+ * if ( (value == computedDefault) && !config->hasDefault(key) )
+ * config->revertToDefault(key)
+ * else
+ * config->writeEntry(key, value)
+ * \endcode
+ *
+ * This ensures that as long as the entry is not modified to differ from
+ * the computed default, the application will keep using the computed default
+ * and will follow changes the computed default makes over time.
+ * @param key The key of the entry to check.
+ * @since 3.2
+ */
+ bool hasDefault(const TQString &key) const;
+
+protected:
+ /**
+ * Reads the locale and put in the configuration data struct.
+ * Note that this should be done in the constructor, but this is not
+ * possible due to some mutual dependencies in TDEApplication::init()
+ */
+ void setLocale();
+
+ /**
+ * Sets the global dirty flag of the config object
+ *
+ * @param _bDirty How to mark the object's dirty status
+ */
+ virtual void setDirty(bool _bDirty = true) { bDirty = _bDirty; }
+
+ /**
+ * Parses all configuration files for a configuration object.
+ *
+ * The actual parsing is done by the associated TDEConfigBackEnd.
+ */
+ virtual void parseConfigFiles();
+
+ /**
+ * Returns a map (tree) of the entries in the specified group.
+ * This may or may not return all entries that belong to the
+ * config object. The only guarantee that you are given is that
+ * any entries that are dirty (i.e. modified and not yet written back
+ * to the disk) will be contained in the map. Some derivative
+ * classes may choose to return everything.
+ *
+ * Do not use this function, the implementation / return type are
+ * subject to change.
+ *
+ * @param pGroup The group to provide a KEntryMap for.
+ * @return The map of the entries in the group.
+ * @internal
+ */
+ virtual KEntryMap internalEntryMap( const TQString& pGroup ) const = 0;
+
+ /**
+ * Returns a map (tree) of the entries in the tree.
+ *
+ * Do not use this function, the implementation / return type are
+ * subject to change.
+ *
+ * @return A map of the entries in the tree.
+ *
+ * @internal
+ *
+ */
+ virtual KEntryMap internalEntryMap() const = 0;
+
+ /**
+ * Inserts a (key/value) pair into the internal storage mechanism of
+ * the configuration object. Classes that derive from TDEConfigBase
+ * will need to implement this method in a storage-specific manner.
+ *
+ * Do not use this function, the implementation / return type are
+ * subject to change.
+ *
+ * @param _key The key to insert. It contains information both on
+ * the group of the key and the key itself. If the key already
+ * exists, the old value will be replaced.
+ * @param _data the KEntry that is to be stored.
+ * @param _checkGroup When false, assume that the group already exists.
+ * @internal
+ */
+ virtual void putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup = true) = 0;
+
+ /**
+ * Looks up an entry in the config object's internal structure.
+ * Classes that derive from TDEConfigBase will need to implement this
+ * method in a storage-specific manner.
+ *
+ * Do not use this function, the implementation and return type are
+ * subject to change.
+ *
+ * @param _key The key to look up It contains information both on
+ * the group of the key and the entry's key itself.
+ * @return The KEntry value (data) found for the key. @p KEntry.aValue
+ * will be the null string if nothing was located.
+ * @internal
+ */
+ virtual KEntry lookupData(const KEntryKey &_key) const = 0;
+
+ virtual bool internalHasGroup(const TQCString &group) const = 0;
+
+ /**
+ * A back end for loading/saving to disk in a particular format.
+ */
+ TDEConfigBackEnd *backEnd;
+public:
+ /**
+ * Overloaded public methods:
+ */
+ void setGroup( const TQCString &pGroup );
+ void setGroup( const char *pGroup );
+ bool hasGroup(const TQCString &_pGroup) const;
+ bool hasGroup(const char *_pGroup) const;
+ bool hasKey( const char *pKey ) const;
+
+protected:
+ TQCString readEntryUtf8( const char *pKey) const;
+ bool hasTranslatedKey( const char *pKey ) const;
+
+ /**
+ * The currently selected group. */
+ TQCString mGroup;
+
+ /**
+ * The locale to retrieve keys under if possible, i.e en_US or fr. */
+ TQCString aLocaleString;
+
+ /**
+ * Indicates whether there are any dirty entries in the config object
+ * that need to be written back to disk. */
+ bool bDirty;
+
+ bool bLocaleInitialized;
+ bool bReadOnly; // currently only used by KSimpleConfig
+ mutable bool bExpand; // whether dollar expansion is used
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class TDEConfigBasePrivate;
+ TDEConfigBasePrivate *d;
+
+ void writeEntry( const char *pKey, const TQString &rValue,
+ bool bPersistent, bool bGlobal, bool bNLS, bool bExpand );
+ void writeEntry( const char *pKey, const TQStringList &rValue,
+ char sep, bool bPersistent, bool bGlobal, bool bNLS, bool bExpand );
+
+};
+
+class TDEConfigGroupSaverPrivate;
+
+/**
+ * Helper class to facilitate working with TDEConfig / KSimpleConfig
+ * groups.
+ *
+ * Careful programmers always set the group of a
+ * TDEConfig KSimpleConfig object to the group they want to read from
+ * and set it back to the old one of afterwards. This is usually
+ * written as:
+ * \code
+ *
+ * TQString oldgroup config->group();
+ * config->setGroup( "TheGroupThatIWant" );
+ * ...
+ * config->writeEntry( "Blah", "Blubb" );
+ *
+ * config->setGroup( oldgroup );
+ * \endcode
+ *
+ * In order to facilitate this task, you can use
+ * TDEConfigGroupSaver. Simply construct such an object ON THE STACK
+ * when you want to switch to a new group. Then, when the object goes
+ * out of scope, the group will automatically be restored. If you
+ * want to use several different groups within a function or method,
+ * you can still use TDEConfigGroupSaver: Simply enclose all work with
+ * one group (including the creation of the TDEConfigGroupSaver object)
+ * in one block.
+ *
+ * @deprecated This class is deprecated and will be removed in KDE 4.
+ * TDEConfigGroup provides similar functionality in a more object oriented
+ * way.
+ *
+ * @author Matthias Kalle Dalheimer <kalle@kde.org>
+ * @see TDEConfigBase, TDEConfig, KSimpleConfig, TDEConfigGroup
+ * @short Helper class for easier use of TDEConfig/KSimpleConfig groups
+ */
+
+class TDECORE_EXPORT TDEConfigGroupSaver // KDE4 remove
+{
+public:
+ /**
+ * Constructor. You pass a pointer to the TDEConfigBase-derived
+ * object you want to work with and a string indicating the _new_
+ * group.
+ *
+ * @param config The TDEConfigBase-derived object this
+ * TDEConfigGroupSaver works on.
+ * @param group The new group that the config object should switch to.
+ */
+ TDEConfigGroupSaver( TDEConfigBase* config, TQString group )
+ /* KDE 4 : make the second parameter const TQString & */
+ : _config(config), _oldgroup(config->group())
+ { _config->setGroup( group ); }
+
+ TDEConfigGroupSaver( TDEConfigBase* config, const char *group )
+ : _config(config), _oldgroup(config->group())
+ { _config->setGroup( group ); }
+
+ TDEConfigGroupSaver( TDEConfigBase* config, const TQCString &group )
+ : _config(config), _oldgroup(config->group())
+ { _config->setGroup( group ); }
+
+ ~TDEConfigGroupSaver() { _config->setGroup( _oldgroup ); }
+
+ TDEConfigBase* config() { return _config; };
+
+private:
+ TDEConfigBase* _config;
+ TQString _oldgroup;
+
+ TDEConfigGroupSaver(const TDEConfigGroupSaver&);
+ TDEConfigGroupSaver& operator=(const TDEConfigGroupSaver&);
+
+ TDEConfigGroupSaverPrivate *d;
+};
+
+class TDEConfigGroupPrivate;
+
+/**
+ * A TDEConfigBase derived class for one specific group in a TDEConfig object.
+ */
+class TDECORE_EXPORT TDEConfigGroup: public TDEConfigBase
+{
+public:
+ /**
+ * Construct a config group corresponding to @p group in @p master.
+ * @p group is the group name encoded in UTF-8.
+ */
+ TDEConfigGroup(TDEConfigBase *master, const TQCString &group);
+ /**
+ * This is an overloaded constructor provided for convenience.
+ * It behaves essentially like the above function.
+ *
+ * Construct a config group corresponding to @p group in @p master
+ */
+ TDEConfigGroup(TDEConfigBase *master, const TQString &group);
+ /**
+ * This is an overloaded constructor provided for convenience.
+ * It behaves essentially like the above function.
+ *
+ * Construct a config group corresponding to @p group in @p master
+ * @p group is the group name encoded in UTF-8.
+ */
+ TDEConfigGroup(TDEConfigBase *master, const char * group);
+
+ /**
+ * Delete all entries in the entire group
+ * @param bGlobal If @p bGlobal is true, the entries are not removed
+ * from the application specific config file, but from the global
+ * KDE config file.
+ */
+ void deleteGroup(bool bGlobal = false);
+
+ /**
+ * Checks whether it is possible to change this group.
+ * @return whether changes may be made to this group in this configuration
+ * file.
+ * @since 3.4
+ */
+ bool groupIsImmutable() const;
+
+ // The following functions are reimplemented:
+ virtual void setDirty(bool _bDirty);
+ virtual void putData(const KEntryKey &_key, const KEntry &_data, bool _checkGroup = true);
+ virtual KEntry lookupData(const KEntryKey &_key) const;
+ virtual void sync();
+
+private:
+ // Hide the following members:
+ void setGroup() { }
+ void setDesktopGroup() { }
+ void group() { }
+ void hasGroup() { }
+ void setReadOnly(bool) { }
+ void isDirty() { }
+
+ // The following members are not used.
+ virtual TQStringList groupList() const { return TQStringList(); }
+ virtual void rollback(bool) { }
+ virtual void reparseConfiguration() { }
+ virtual TQMap<TQString, TQString> entryMap(const TQString &) const
+ { return TQMap<TQString,TQString>(); }
+ virtual KEntryMap internalEntryMap( const TQString&) const
+ { return KEntryMap(); }
+ virtual KEntryMap internalEntryMap() const
+ { return KEntryMap(); }
+ virtual bool internalHasGroup(const TQCString &) const
+ { return false; }
+
+ void getConfigState() { }
+
+ TDEConfigBase *mMaster;
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ TDEConfigGroupPrivate* d;
+};
+
+#endif
diff --git a/tdecore/kconfigdata.h b/tdecore/tdeconfigdata.h
index f99f72c08..f99f72c08 100644
--- a/tdecore/kconfigdata.h
+++ b/tdecore/tdeconfigdata.h
diff --git a/tdecore/tdeconfigdialogmanager.cpp b/tdecore/tdeconfigdialogmanager.cpp
new file mode 100644
index 000000000..c488e43cb
--- /dev/null
+++ b/tdecore/tdeconfigdialogmanager.cpp
@@ -0,0 +1,398 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (C) 2003 Benjamin C Meyer (ben+tdelibs at meyerhome dot net)
+ * Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "tdeconfigdialogmanager.h"
+
+#include <tqbuttongroup.h>
+#include <tqcombobox.h>
+#include <tqlabel.h>
+#include <tqmetaobject.h>
+#include <tqobjectlist.h>
+#include <tqsqlpropertymap.h>
+#include <tqtimer.h>
+#include <tqwhatsthis.h>
+
+#include <kapplication.h>
+#include <tdeconfigskeleton.h>
+#include <kdebug.h>
+#include <kglobal.h>
+
+#include <assert.h>
+
+class TDEConfigDialogManager::Private {
+
+public:
+ Private() : insideGroupBox(false) { }
+
+public:
+ TQDict<TQWidget> knownWidget;
+ TQDict<TQWidget> buddyWidget;
+ bool insideGroupBox;
+};
+
+TDEConfigDialogManager::TDEConfigDialogManager(TQWidget *parent, TDEConfigSkeleton *conf, const char *name)
+ : TQObject(parent, name), m_conf(conf), m_dialog(parent)
+{
+ d = new Private();
+
+ kapp->installKDEPropertyMap();
+ propertyMap = TQSqlPropertyMap::defaultMap();
+
+ init(true);
+}
+
+TDEConfigDialogManager::~TDEConfigDialogManager()
+{
+ delete d;
+}
+
+void TDEConfigDialogManager::init(bool trackChanges)
+{
+ if(trackChanges)
+ {
+ // QT
+ changedMap.insert(TQBUTTON_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
+ changedMap.insert(TQCHECKBOX_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
+ changedMap.insert(TQPUSHBUTTON_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
+ changedMap.insert(TQRADIOBUTTON_OBJECT_NAME_STRING, TQT_SIGNAL(stateChanged(int)));
+ // We can only store one thing, so you can't have
+ // a ButtonGroup that is checkable.
+ changedMap.insert(TQBUTTONGROUP_OBJECT_NAME_STRING, TQT_SIGNAL(clicked(int)));
+ changedMap.insert(TQGROUPBOX_OBJECT_NAME_STRING, TQT_SIGNAL(toggled(bool)));
+ changedMap.insert(TQCOMBOBOX_OBJECT_NAME_STRING, TQT_SIGNAL(activated (int)));
+ //qsqlproperty map doesn't store the text, but the value!
+ //changedMap.insert(TQCOMBOBOX_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged(const TQString &)));
+ changedMap.insert(TQDATEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(const TQDate &)));
+ changedMap.insert(TQDATETIMEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(const TQDateTime &)));
+ changedMap.insert(TQDIAL_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged (int)));
+ changedMap.insert(TQLINEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged(const TQString &)));
+ changedMap.insert(TQSLIDER_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(int)));
+ changedMap.insert(TQSPINBOX_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(int)));
+ changedMap.insert(TQTIMEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(valueChanged(const TQTime &)));
+ changedMap.insert(TQTEXTEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged()));
+ changedMap.insert(TQTEXTBROWSER_OBJECT_NAME_STRING, TQT_SIGNAL(sourceChanged(const TQString &)));
+ changedMap.insert(TQMULTILINEEDIT_OBJECT_NAME_STRING, TQT_SIGNAL(textChanged()));
+ changedMap.insert(TQLISTBOX_OBJECT_NAME_STRING, TQT_SIGNAL(selectionChanged()));
+ changedMap.insert(TQTABWIDGET_OBJECT_NAME_STRING, TQT_SIGNAL(currentChanged(TQWidget *)));
+
+ // KDE
+ changedMap.insert( "KComboBox", TQT_SIGNAL(activated (int)));
+ changedMap.insert( "KFontCombo", TQT_SIGNAL(activated (int)));
+ changedMap.insert( "KFontRequester", TQT_SIGNAL(fontSelected(const TQFont &)));
+ changedMap.insert( "KFontChooser", TQT_SIGNAL(fontSelected(const TQFont &)));
+ changedMap.insert( "KHistoryCombo", TQT_SIGNAL(activated (int)));
+
+ changedMap.insert( "KColorButton", TQT_SIGNAL(changed(const TQColor &)));
+ changedMap.insert( "KDatePicker", TQT_SIGNAL(dateSelected (TQDate)));
+ changedMap.insert( "KDateWidget", TQT_SIGNAL(changed (TQDate)));
+ changedMap.insert( "KDateTimeWidget", TQT_SIGNAL(valueChanged (const TQDateTime &)));
+ changedMap.insert( "KEditListBox", TQT_SIGNAL(changed()));
+ changedMap.insert( "KListBox", TQT_SIGNAL(selectionChanged()));
+ changedMap.insert( "KLineEdit", TQT_SIGNAL(textChanged(const TQString &)));
+ changedMap.insert( "KPasswordEdit", TQT_SIGNAL(textChanged(const TQString &)));
+ changedMap.insert( "KRestrictedLine", TQT_SIGNAL(textChanged(const TQString &)));
+ changedMap.insert( "KTextBrowser", TQT_SIGNAL(sourceChanged(const TQString &)));
+ changedMap.insert( "KTextEdit", TQT_SIGNAL(textChanged()));
+ changedMap.insert( "KURLRequester", TQT_SIGNAL(textChanged (const TQString& )));
+ changedMap.insert( "KIntNumInput", TQT_SIGNAL(valueChanged (int)));
+ changedMap.insert( "KIntSpinBox", TQT_SIGNAL(valueChanged (int)));
+ changedMap.insert( "KDoubleNumInput", TQT_SIGNAL(valueChanged (double)));
+ }
+
+ // Go through all of the children of the widgets and find all known widgets
+ (void) parseChildren(m_dialog, trackChanges);
+}
+
+void TDEConfigDialogManager::addWidget(TQWidget *widget)
+{
+ (void) parseChildren(widget, true);
+}
+
+void TDEConfigDialogManager::setupWidget(TQWidget *widget, TDEConfigSkeletonItem *item)
+{
+ TQVariant minValue = item->minValue();
+ if (minValue.isValid())
+ {
+ if (widget->metaObject()->findProperty("minValue", true) != -1)
+ widget->setProperty("minValue", minValue);
+ }
+ TQVariant maxValue = item->maxValue();
+ if (maxValue.isValid())
+ {
+ if (widget->metaObject()->findProperty("maxValue", true) != -1)
+ widget->setProperty("maxValue", maxValue);
+ }
+ if (TQWhatsThis::textFor( widget ).isEmpty())
+ {
+ TQString whatsThis = item->whatsThis();
+ if ( !whatsThis.isEmpty() )
+ {
+ TQWhatsThis::add( widget, whatsThis );
+ }
+ }
+}
+
+bool TDEConfigDialogManager::parseChildren(const TQWidget *widget, bool trackChanges)
+{
+ bool valueChanged = false;
+ const TQObjectList listOfChildren = widget->childrenListObject();
+ if(listOfChildren.isEmpty())
+ return valueChanged;
+
+ TQObject *object;
+ for( TQObjectListIterator it( listOfChildren );
+ (object = it.current()); ++it )
+ {
+ if(!object->isWidgetType())
+ continue; // Skip non-widgets
+
+ TQWidget *childWidget = (TQWidget *)object;
+
+ const char *widgetName = childWidget->name(0);
+ bool bParseChildren = true;
+ bool bSaveInsideGroupBox = d->insideGroupBox;
+
+ if (widgetName && (strncmp(widgetName, "kcfg_", 5) == 0))
+ {
+ // This is one of our widgets!
+ TQString configId = widgetName+5;
+ TDEConfigSkeletonItem *item = m_conf->findItem(configId);
+ if (item)
+ {
+ d->knownWidget.insert(configId, childWidget);
+
+ setupWidget(childWidget, item);
+
+ TQMap<TQString, TQCString>::const_iterator changedIt = changedMap.find(childWidget->className());
+
+ if (changedIt == changedMap.end())
+ {
+ // If the class name of the widget wasn't in the monitored widgets map, then look for
+ // it again using the super class name. This fixes a problem with using QtRuby/Korundum
+ // widgets with TDEConfigXT where 'Qt::Widget' wasn't being seen a the real deal, even
+ // though it was a 'QWidget'.
+ changedIt = changedMap.find(childWidget->metaObject()->superClassName());
+ }
+
+ if (changedIt == changedMap.end())
+ {
+ kdWarning(178) << "Don't know how to monitor widget '" << childWidget->className() << "' for changes!" << endl;
+ }
+ else
+ {
+ connect(childWidget, *changedIt,
+ this, TQT_SIGNAL(widgetModified()));
+
+ TQGroupBox *gb = dynamic_cast<TQGroupBox *>(childWidget);
+ if (!gb)
+ bParseChildren = false;
+ else
+ d->insideGroupBox = true;
+
+ TQComboBox *cb = dynamic_cast<TQComboBox *>(childWidget);
+ if (cb && cb->editable())
+ connect(cb, TQT_SIGNAL(textChanged(const TQString &)),
+ this, TQT_SIGNAL(widgetModified()));
+ }
+ }
+ else
+ {
+ kdWarning(178) << "A widget named '" << widgetName << "' was found but there is no setting named '" << configId << "'" << endl;
+ }
+ }
+ else if (childWidget->inherits(TQLABEL_OBJECT_NAME_STRING))
+ {
+ TQLabel *label = static_cast<TQLabel *>(childWidget);
+ TQWidget *buddy = label->buddy();
+ if (!buddy)
+ continue;
+ const char *buddyName = buddy->name(0);
+ if (buddyName && (strncmp(buddyName, "kcfg_", 5) == 0))
+ {
+ // This is one of our widgets!
+ TQString configId = buddyName+5;
+ d->buddyWidget.insert(configId, childWidget);
+ }
+ }
+#ifndef NDEBUG
+ else if (widgetName)
+ {
+ TQMap<TQString, TQCString>::const_iterator changedIt = changedMap.find(childWidget->className());
+ if (changedIt != changedMap.end())
+ {
+ if ((!d->insideGroupBox || !childWidget->inherits(TQRADIOBUTTON_OBJECT_NAME_STRING)) &&
+ !childWidget->inherits(TQGROUPBOX_OBJECT_NAME_STRING))
+ kdDebug(178) << "Widget '" << widgetName << "' (" << childWidget->className() << ") remains unmanaged." << endl;
+ }
+ }
+#endif
+
+ if(bParseChildren)
+ {
+ // this widget is not known as something we can store.
+ // Maybe we can store one of its children.
+ valueChanged |= parseChildren(childWidget, trackChanges);
+ }
+ d->insideGroupBox = bSaveInsideGroupBox;
+ }
+ return valueChanged;
+}
+
+void TDEConfigDialogManager::updateWidgets()
+{
+ bool changed = false;
+ bool bSignalsBlocked = signalsBlocked();
+ blockSignals(true);
+
+ TQWidget *widget;
+ for( TQDictIterator<TQWidget> it( d->knownWidget );
+ (widget = it.current()); ++it )
+ {
+ TDEConfigSkeletonItem *item = m_conf->findItem(it.currentKey());
+ if (!item)
+ {
+ kdWarning(178) << "The setting '" << it.currentKey() << "' has disappeared!" << endl;
+ continue;
+ }
+
+ TQVariant p = item->property();
+ if (p != property(widget))
+ {
+ setProperty(widget, p);
+// kdDebug(178) << "The setting '" << it.currentKey() << "' [" << widget->className() << "] has changed" << endl;
+ changed = true;
+ }
+ if (item->isImmutable())
+ {
+ widget->setEnabled(false);
+ TQWidget *buddy = d->buddyWidget.find(it.currentKey());
+ if (buddy)
+ buddy->setEnabled(false);
+ }
+ }
+ blockSignals(bSignalsBlocked);
+
+ if (changed)
+ TQTimer::singleShot(0, this, TQT_SIGNAL(widgetModified()));
+}
+
+void TDEConfigDialogManager::updateWidgetsDefault()
+{
+ bool bUseDefaults = m_conf->useDefaults(true);
+ updateWidgets();
+ m_conf->useDefaults(bUseDefaults);
+}
+
+void TDEConfigDialogManager::updateSettings()
+{
+ bool changed = false;
+
+ TQWidget *widget;
+ for( TQDictIterator<TQWidget> it( d->knownWidget );
+ (widget = it.current()); ++it )
+ {
+ TDEConfigSkeletonItem *item = m_conf->findItem(it.currentKey());
+ if (!item)
+ {
+ kdWarning(178) << "The setting '" << it.currentKey() << "' has disappeared!" << endl;
+ continue;
+ }
+
+ TQVariant p = property(widget);
+ if (p != item->property())
+ {
+ item->setProperty(p);
+ changed = true;
+ }
+ }
+ if (changed)
+ {
+ m_conf->writeConfig();
+ emit settingsChanged();
+ }
+}
+
+void TDEConfigDialogManager::setProperty(TQWidget *w, const TQVariant &v)
+{
+ TQButtonGroup *bg = dynamic_cast<TQButtonGroup *>(w);
+ if (bg)
+ {
+ bg->setButton(v.toInt());
+ return;
+ }
+
+ TQComboBox *cb = dynamic_cast<TQComboBox *>(w);
+ if (cb && cb->editable())
+ {
+ cb->setCurrentText(v.toString());
+ return;
+ }
+
+ propertyMap->setProperty(w, v);
+}
+
+TQVariant TDEConfigDialogManager::property(TQWidget *w)
+{
+ TQButtonGroup *bg = dynamic_cast<TQButtonGroup *>(w);
+ if (bg)
+ return TQVariant(bg->selectedId());
+
+ TQComboBox *cb = dynamic_cast<TQComboBox *>(w);
+ if (cb && cb->editable())
+ return TQVariant(cb->currentText());
+
+ return propertyMap->property(w);
+}
+
+bool TDEConfigDialogManager::hasChanged()
+{
+
+ TQWidget *widget;
+ for( TQDictIterator<TQWidget> it( d->knownWidget );
+ (widget = it.current()); ++it )
+ {
+ TDEConfigSkeletonItem *item = m_conf->findItem(it.currentKey());
+ if (!item)
+ {
+ kdWarning(178) << "The setting '" << it.currentKey() << "' has disappeared!" << endl;
+ continue;
+ }
+
+ TQVariant p = property(widget);
+ if (p != item->property())
+ {
+// kdDebug(178) << "Widget for '" << it.currentKey() << "' has changed." << endl;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool TDEConfigDialogManager::isDefault()
+{
+ bool bUseDefaults = m_conf->useDefaults(true);
+ bool result = !hasChanged();
+ m_conf->useDefaults(bUseDefaults);
+ return result;
+}
+
+#include "tdeconfigdialogmanager.moc"
+
diff --git a/tdecore/kconfigdialogmanager.h b/tdecore/tdeconfigdialogmanager.h
index 1b82e9eda..1b82e9eda 100644
--- a/tdecore/kconfigdialogmanager.h
+++ b/tdecore/tdeconfigdialogmanager.h
diff --git a/tdecore/tdeconfigskeleton.cpp b/tdecore/tdeconfigskeleton.cpp
new file mode 100644
index 000000000..0990949d0
--- /dev/null
+++ b/tdecore/tdeconfigskeleton.cpp
@@ -0,0 +1,1207 @@
+/*
+ This file is part of KOrganizer.
+ Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>
+ Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqcolor.h>
+#include <tqvariant.h>
+
+#include <tdeconfig.h>
+#include <kstandarddirs.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <kdebug.h>
+
+#include "kstringhandler.h"
+
+#include "tdeconfigskeleton.h"
+
+void TDEConfigSkeletonItem::readImmutability( TDEConfig *config )
+{
+ mIsImmutable = config->entryIsImmutable( mKey );
+}
+
+
+TDEConfigSkeleton::ItemString::ItemString( const TQString &group, const TQString &key,
+ TQString &reference,
+ const TQString &defaultValue,
+ Type type )
+ : TDEConfigSkeletonGenericItem<TQString>( group, key, reference, defaultValue ),
+ mType( type )
+{
+}
+
+void TDEConfigSkeleton::ItemString::writeConfig( TDEConfig *config )
+{
+ if ( mReference != mLoadedValue ) // WABA: Is this test needed?
+ {
+ config->setGroup( mGroup );
+ if ((mDefault == mReference) && !config->hasDefault( mKey))
+ config->revertToDefault( mKey );
+ else if ( mType == Path )
+ config->writePathEntry( mKey, mReference );
+ else if ( mType == Password )
+ config->writeEntry( mKey, KStringHandler::obscure( mReference ) );
+ else
+ config->writeEntry( mKey, mReference );
+ }
+}
+
+
+void TDEConfigSkeleton::ItemString::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+
+ if ( mType == Path )
+ {
+ mReference = config->readPathEntry( mKey, mDefault );
+ }
+ else if ( mType == Password )
+ {
+ TQString value = config->readEntry( mKey,
+ KStringHandler::obscure( mDefault ) );
+ mReference = KStringHandler::obscure( value );
+ }
+ else
+ {
+ mReference = config->readEntry( mKey, mDefault );
+ }
+
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemString::setProperty(const TQVariant & p)
+{
+ mReference = p.toString();
+}
+
+TQVariant TDEConfigSkeleton::ItemString::property() const
+{
+ return TQVariant(mReference);
+}
+
+TDEConfigSkeleton::ItemPassword::ItemPassword( const TQString &group, const TQString &key,
+ TQString &reference,
+ const TQString &defaultValue)
+ : ItemString( group, key, reference, defaultValue, Password )
+{
+}
+
+TDEConfigSkeleton::ItemPath::ItemPath( const TQString &group, const TQString &key,
+ TQString &reference,
+ const TQString &defaultValue)
+ : ItemString( group, key, reference, defaultValue, Path )
+{
+}
+
+TDEConfigSkeleton::ItemProperty::ItemProperty( const TQString &group,
+ const TQString &key,
+ TQVariant &reference,
+ TQVariant defaultValue )
+ : TDEConfigSkeletonGenericItem<TQVariant>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemProperty::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readPropertyEntry( mKey, mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemProperty::setProperty(const TQVariant & p)
+{
+ mReference = p;
+}
+
+TQVariant TDEConfigSkeleton::ItemProperty::property() const
+{
+ return mReference;
+}
+
+TDEConfigSkeleton::ItemBool::ItemBool( const TQString &group, const TQString &key,
+ bool &reference, bool defaultValue )
+ : TDEConfigSkeletonGenericItem<bool>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemBool::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readBoolEntry( mKey, mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemBool::setProperty(const TQVariant & p)
+{
+ mReference = p.toBool();
+}
+
+TQVariant TDEConfigSkeleton::ItemBool::property() const
+{
+ return TQVariant( mReference, 42 /* dummy */ );
+}
+
+
+TDEConfigSkeleton::ItemInt::ItemInt( const TQString &group, const TQString &key,
+ int &reference, int defaultValue )
+ : TDEConfigSkeletonGenericItem<int>( group, key, reference, defaultValue )
+ ,mHasMin(false), mHasMax(false)
+{
+}
+
+void TDEConfigSkeleton::ItemInt::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readNumEntry( mKey, mDefault );
+ if (mHasMin)
+ mReference = QMAX(mReference, mMin);
+ if (mHasMax)
+ mReference = QMIN(mReference, mMax);
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemInt::setProperty(const TQVariant & p)
+{
+ mReference = p.toInt();
+}
+
+TQVariant TDEConfigSkeleton::ItemInt::property() const
+{
+ return TQVariant(mReference);
+}
+
+TQVariant TDEConfigSkeleton::ItemInt::minValue() const
+{
+ if (mHasMin)
+ return TQVariant(mMin);
+ return TQVariant();
+}
+
+TQVariant TDEConfigSkeleton::ItemInt::maxValue() const
+{
+ if (mHasMax)
+ return TQVariant(mMax);
+ return TQVariant();
+}
+
+void TDEConfigSkeleton::ItemInt::setMinValue(int v)
+{
+ mHasMin = true;
+ mMin = v;
+}
+
+void TDEConfigSkeleton::ItemInt::setMaxValue(int v)
+{
+ mHasMax = true;
+ mMax = v;
+}
+
+
+TDEConfigSkeleton::ItemInt64::ItemInt64( const TQString &group, const TQString &key,
+ TQ_INT64 &reference, TQ_INT64 defaultValue )
+ : TDEConfigSkeletonGenericItem<TQ_INT64>( group, key, reference, defaultValue )
+ ,mHasMin(false), mHasMax(false)
+{
+}
+
+void TDEConfigSkeleton::ItemInt64::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readNum64Entry( mKey, mDefault );
+ if (mHasMin)
+ mReference = QMAX(mReference, mMin);
+ if (mHasMax)
+ mReference = QMIN(mReference, mMax);
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemInt64::setProperty(const TQVariant & p)
+{
+ mReference = p.toLongLong();
+}
+
+TQVariant TDEConfigSkeleton::ItemInt64::property() const
+{
+ return TQVariant(mReference);
+}
+
+TQVariant TDEConfigSkeleton::ItemInt64::minValue() const
+{
+ if (mHasMin)
+ return TQVariant(mMin);
+ return TQVariant();
+}
+
+TQVariant TDEConfigSkeleton::ItemInt64::maxValue() const
+{
+ if (mHasMax)
+ return TQVariant(mMax);
+ return TQVariant();
+}
+
+void TDEConfigSkeleton::ItemInt64::setMinValue(TQ_INT64 v)
+{
+ mHasMin = true;
+ mMin = v;
+}
+
+void TDEConfigSkeleton::ItemInt64::setMaxValue(TQ_INT64 v)
+{
+ mHasMax = true;
+ mMax = v;
+}
+
+TDEConfigSkeleton::ItemEnum::ItemEnum( const TQString &group, const TQString &key,
+ int &reference,
+ const TQValueList<Choice> &choices,
+ int defaultValue )
+ : ItemInt( group, key, reference, defaultValue ), mChoices( choices )
+{
+}
+
+void TDEConfigSkeleton::ItemEnum::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ if (!config->hasKey(mKey))
+ {
+ mReference = mDefault;
+ }
+ else
+ {
+ int i = 0;
+ mReference = -1;
+ TQString tmp = config->readEntry( mKey ).lower();
+ for(TQValueList<Choice>::ConstIterator it = mChoices.begin();
+ it != mChoices.end(); ++it, ++i)
+ {
+ if ((*it).name.lower() == tmp)
+ {
+ mReference = i;
+ break;
+ }
+ }
+ if (mReference == -1)
+ mReference = config->readNumEntry( mKey, mDefault );
+ }
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemEnum::writeConfig( TDEConfig *config )
+{
+ if ( mReference != mLoadedValue ) // WABA: Is this test needed?
+ {
+ config->setGroup( mGroup );
+ if ((mDefault == mReference) && !config->hasDefault( mKey))
+ config->revertToDefault( mKey );
+ else if ((mReference >= 0) && (mReference < (int) mChoices.count()))
+ config->writeEntry( mKey, mChoices[mReference].name );
+ else
+ config->writeEntry( mKey, mReference );
+ }
+}
+
+TQValueList<TDEConfigSkeleton::ItemEnum::Choice> TDEConfigSkeleton::ItemEnum::choices() const
+{
+ return mChoices;
+}
+
+
+TDEConfigSkeleton::ItemUInt::ItemUInt( const TQString &group, const TQString &key,
+ unsigned int &reference,
+ unsigned int defaultValue )
+ : TDEConfigSkeletonGenericItem<unsigned int>( group, key, reference, defaultValue )
+ ,mHasMin(false), mHasMax(false)
+{
+}
+
+void TDEConfigSkeleton::ItemUInt::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readUnsignedNumEntry( mKey, mDefault );
+ if (mHasMin)
+ mReference = QMAX(mReference, mMin);
+ if (mHasMax)
+ mReference = QMIN(mReference, mMax);
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemUInt::setProperty(const TQVariant & p)
+{
+ mReference = p.toUInt();
+}
+
+TQVariant TDEConfigSkeleton::ItemUInt::property() const
+{
+ return TQVariant(mReference);
+}
+
+TQVariant TDEConfigSkeleton::ItemUInt::minValue() const
+{
+ if (mHasMin)
+ return TQVariant(mMin);
+ return TQVariant();
+}
+
+TQVariant TDEConfigSkeleton::ItemUInt::maxValue() const
+{
+ if (mHasMax)
+ return TQVariant(mMax);
+ return TQVariant();
+}
+
+void TDEConfigSkeleton::ItemUInt::setMinValue(unsigned int v)
+{
+ mHasMin = true;
+ mMin = v;
+}
+
+void TDEConfigSkeleton::ItemUInt::setMaxValue(unsigned int v)
+{
+ mHasMax = true;
+ mMax = v;
+}
+
+
+TDEConfigSkeleton::ItemUInt64::ItemUInt64( const TQString &group, const TQString &key,
+ TQ_UINT64 &reference, TQ_UINT64 defaultValue )
+ : TDEConfigSkeletonGenericItem<TQ_UINT64>( group, key, reference, defaultValue )
+ ,mHasMin(false), mHasMax(false)
+{
+}
+
+void TDEConfigSkeleton::ItemUInt64::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readUnsignedNum64Entry( mKey, mDefault );
+ if (mHasMin)
+ mReference = QMAX(mReference, mMin);
+ if (mHasMax)
+ mReference = QMIN(mReference, mMax);
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemUInt64::setProperty(const TQVariant & p)
+{
+ mReference = p.toULongLong();
+}
+
+TQVariant TDEConfigSkeleton::ItemUInt64::property() const
+{
+ return TQVariant(mReference);
+}
+
+TQVariant TDEConfigSkeleton::ItemUInt64::minValue() const
+{
+ if (mHasMin)
+ return TQVariant(mMin);
+ return TQVariant();
+}
+
+TQVariant TDEConfigSkeleton::ItemUInt64::maxValue() const
+{
+ if (mHasMax)
+ return TQVariant(mMax);
+ return TQVariant();
+}
+
+void TDEConfigSkeleton::ItemUInt64::setMinValue(TQ_UINT64 v)
+{
+ mHasMin = true;
+ mMin = v;
+}
+
+void TDEConfigSkeleton::ItemUInt64::setMaxValue(TQ_UINT64 v)
+{
+ mHasMax = true;
+ mMax = v;
+}
+
+TDEConfigSkeleton::ItemLong::ItemLong( const TQString &group, const TQString &key,
+ long &reference, long defaultValue )
+ : TDEConfigSkeletonGenericItem<long>( group, key, reference, defaultValue )
+ ,mHasMin(false), mHasMax(false)
+{
+}
+
+void TDEConfigSkeleton::ItemLong::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readLongNumEntry( mKey, mDefault );
+ if (mHasMin)
+ mReference = QMAX(mReference, mMin);
+ if (mHasMax)
+ mReference = QMIN(mReference, mMax);
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemLong::setProperty(const TQVariant & p)
+{
+ mReference = p.toLongLong();
+}
+
+TQVariant TDEConfigSkeleton::ItemLong::property() const
+{
+ return TQVariant((TQ_LLONG) mReference);
+}
+
+TQVariant TDEConfigSkeleton::ItemLong::minValue() const
+{
+ if (mHasMin)
+ return TQVariant((TQ_LLONG) mMin);
+ return TQVariant();
+}
+
+TQVariant TDEConfigSkeleton::ItemLong::maxValue() const
+{
+ if (mHasMax)
+ return TQVariant((TQ_LLONG) mMax);
+ return TQVariant();
+}
+
+void TDEConfigSkeleton::ItemLong::setMinValue(long v)
+{
+ mHasMin = true;
+ mMin = v;
+}
+
+void TDEConfigSkeleton::ItemLong::setMaxValue(long v)
+{
+ mHasMax = true;
+ mMax = v;
+}
+
+
+TDEConfigSkeleton::ItemULong::ItemULong( const TQString &group, const TQString &key,
+ unsigned long &reference,
+ unsigned long defaultValue )
+ : TDEConfigSkeletonGenericItem<unsigned long>( group, key, reference, defaultValue )
+ ,mHasMin(false), mHasMax(false)
+{
+}
+
+void TDEConfigSkeleton::ItemULong::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readUnsignedLongNumEntry( mKey, mDefault );
+ if (mHasMin)
+ mReference = QMAX(mReference, mMin);
+ if (mHasMax)
+ mReference = QMIN(mReference, mMax);
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemULong::setProperty(const TQVariant & p)
+{
+ mReference = p.toULongLong();
+}
+
+TQVariant TDEConfigSkeleton::ItemULong::property() const
+{
+ return TQVariant((TQ_ULLONG) mReference);
+}
+
+TQVariant TDEConfigSkeleton::ItemULong::minValue() const
+{
+ if (mHasMin)
+ return TQVariant((TQ_ULLONG) mMin);
+ return TQVariant();
+}
+
+TQVariant TDEConfigSkeleton::ItemULong::maxValue() const
+{
+ if (mHasMax)
+ return TQVariant((TQ_ULLONG) mMax);
+ return TQVariant();
+}
+
+void TDEConfigSkeleton::ItemULong::setMinValue(unsigned long v)
+{
+ mHasMin = true;
+ mMin = v;
+}
+
+void TDEConfigSkeleton::ItemULong::setMaxValue(unsigned long v)
+{
+ mHasMax = true;
+ mMax = v;
+}
+
+
+TDEConfigSkeleton::ItemDouble::ItemDouble( const TQString &group, const TQString &key,
+ double &reference, double defaultValue )
+ : TDEConfigSkeletonGenericItem<double>( group, key, reference, defaultValue )
+ ,mHasMin(false), mHasMax(false)
+{
+}
+
+void TDEConfigSkeleton::ItemDouble::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readDoubleNumEntry( mKey, mDefault );
+ if (mHasMin)
+ mReference = QMAX(mReference, mMin);
+ if (mHasMax)
+ mReference = QMIN(mReference, mMax);
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemDouble::setProperty(const TQVariant & p)
+{
+ mReference = p.toDouble();
+}
+
+TQVariant TDEConfigSkeleton::ItemDouble::property() const
+{
+ return TQVariant(mReference);
+}
+
+TQVariant TDEConfigSkeleton::ItemDouble::minValue() const
+{
+ if (mHasMin)
+ return TQVariant(mMin);
+ return TQVariant();
+}
+
+TQVariant TDEConfigSkeleton::ItemDouble::maxValue() const
+{
+ if (mHasMax)
+ return TQVariant(mMax);
+ return TQVariant();
+}
+
+void TDEConfigSkeleton::ItemDouble::setMinValue(double v)
+{
+ mHasMin = true;
+ mMin = v;
+}
+
+void TDEConfigSkeleton::ItemDouble::setMaxValue(double v)
+{
+ mHasMax = true;
+ mMax = v;
+}
+
+
+TDEConfigSkeleton::ItemColor::ItemColor( const TQString &group, const TQString &key,
+ TQColor &reference,
+ const TQColor &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQColor>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemColor::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readColorEntry( mKey, &mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemColor::setProperty(const TQVariant & p)
+{
+ mReference = p.toColor();
+}
+
+TQVariant TDEConfigSkeleton::ItemColor::property() const
+{
+ return TQVariant(mReference);
+}
+
+
+TDEConfigSkeleton::ItemFont::ItemFont( const TQString &group, const TQString &key,
+ TQFont &reference,
+ const TQFont &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQFont>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemFont::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readFontEntry( mKey, &mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemFont::setProperty(const TQVariant & p)
+{
+ mReference = p.toFont();
+}
+
+TQVariant TDEConfigSkeleton::ItemFont::property() const
+{
+ return TQVariant(mReference);
+}
+
+
+TDEConfigSkeleton::ItemRect::ItemRect( const TQString &group, const TQString &key,
+ TQRect &reference,
+ const TQRect &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQRect>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemRect::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readRectEntry( mKey, &mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemRect::setProperty(const TQVariant & p)
+{
+ mReference = p.toRect();
+}
+
+TQVariant TDEConfigSkeleton::ItemRect::property() const
+{
+ return TQVariant(mReference);
+}
+
+
+TDEConfigSkeleton::ItemPoint::ItemPoint( const TQString &group, const TQString &key,
+ TQPoint &reference,
+ const TQPoint &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQPoint>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemPoint::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readPointEntry( mKey, &mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemPoint::setProperty(const TQVariant & p)
+{
+ mReference = p.toPoint();
+}
+
+TQVariant TDEConfigSkeleton::ItemPoint::property() const
+{
+ return TQVariant(mReference);
+}
+
+
+TDEConfigSkeleton::ItemSize::ItemSize( const TQString &group, const TQString &key,
+ TQSize &reference,
+ const TQSize &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQSize>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemSize::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readSizeEntry( mKey, &mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemSize::setProperty(const TQVariant & p)
+{
+ mReference = p.toSize();
+}
+
+TQVariant TDEConfigSkeleton::ItemSize::property() const
+{
+ return TQVariant(mReference);
+}
+
+
+TDEConfigSkeleton::ItemDateTime::ItemDateTime( const TQString &group, const TQString &key,
+ TQDateTime &reference,
+ const TQDateTime &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQDateTime>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemDateTime::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ mReference = config->readDateTimeEntry( mKey, &mDefault );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemDateTime::setProperty(const TQVariant & p)
+{
+ mReference = p.toDateTime();
+}
+
+TQVariant TDEConfigSkeleton::ItemDateTime::property() const
+{
+ return TQVariant(mReference);
+}
+
+
+TDEConfigSkeleton::ItemStringList::ItemStringList( const TQString &group, const TQString &key,
+ TQStringList &reference,
+ const TQStringList &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQStringList>( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemStringList::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ if ( !config->hasKey( mKey ) )
+ mReference = mDefault;
+ else
+ mReference = config->readListEntry( mKey );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemStringList::setProperty(const TQVariant & p)
+{
+ mReference = p.toStringList();
+}
+
+TQVariant TDEConfigSkeleton::ItemStringList::property() const
+{
+ return TQVariant(mReference);
+}
+
+
+TDEConfigSkeleton::ItemPathList::ItemPathList( const TQString &group, const TQString &key,
+ TQStringList &reference,
+ const TQStringList &defaultValue )
+ : ItemStringList( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemPathList::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ if ( !config->hasKey( mKey ) )
+ mReference = mDefault;
+ else
+ mReference = config->readPathListEntry( mKey );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemPathList::writeConfig( TDEConfig *config )
+{
+ if ( mReference != mLoadedValue ) // WABA: Is this test needed?
+ {
+ config->setGroup( mGroup );
+ if ((mDefault == mReference) && !config->hasDefault( mKey))
+ config->revertToDefault( mKey );
+ else {
+ TQStringList sl = mReference;
+ config->writePathEntry( mKey, sl );
+ }
+ }
+}
+
+
+TDEConfigSkeleton::ItemIntList::ItemIntList( const TQString &group, const TQString &key,
+ TQValueList<int> &reference,
+ const TQValueList<int> &defaultValue )
+ : TDEConfigSkeletonGenericItem<TQValueList<int> >( group, key, reference, defaultValue )
+{
+}
+
+void TDEConfigSkeleton::ItemIntList::readConfig( TDEConfig *config )
+{
+ config->setGroup( mGroup );
+ if ( !config->hasKey( mKey ) )
+ mReference = mDefault;
+ else
+ mReference = config->readIntListEntry( mKey );
+ mLoadedValue = mReference;
+
+ readImmutability( config );
+}
+
+void TDEConfigSkeleton::ItemIntList::setProperty(const TQVariant &)
+{
+ // TODO: Not yet supported
+}
+
+TQVariant TDEConfigSkeleton::ItemIntList::property() const
+{
+ // TODO: Not yet supported
+ return TQVariant();
+}
+
+
+TDEConfigSkeleton::TDEConfigSkeleton( const TQString &configname )
+ : mCurrentGroup( "No Group" ), mUseDefaults(false)
+{
+ kdDebug(177) << "Creating TDEConfigSkeleton (" << (void *)this << ")" << endl;
+
+ if ( !configname.isEmpty() )
+ {
+ mConfig = KSharedConfig::openConfig( configname );
+ }
+ else
+ {
+ mConfig = TDEGlobal::sharedConfig();
+ }
+}
+
+TDEConfigSkeleton::TDEConfigSkeleton(KSharedConfig::Ptr config)
+ : mCurrentGroup( "No Group" ), mUseDefaults(false)
+{
+ kdDebug(177) << "Creating TDEConfigSkeleton (" << (void *)this << ")" << endl;
+ mConfig = config;
+}
+
+
+TDEConfigSkeleton::~TDEConfigSkeleton()
+{
+ TDEConfigSkeletonItem::List::ConstIterator it;
+ for( it = mItems.begin(); it != mItems.end(); ++it )
+ {
+ delete *it;
+ }
+}
+
+void TDEConfigSkeleton::setCurrentGroup( const TQString &group )
+{
+ mCurrentGroup = group;
+}
+
+TDEConfig *TDEConfigSkeleton::config() const
+{
+ return mConfig;
+}
+
+bool TDEConfigSkeleton::useDefaults(bool b)
+{
+ if (b == mUseDefaults)
+ return mUseDefaults;
+
+ mUseDefaults = b;
+ TDEConfigSkeletonItem::List::ConstIterator it;
+ for( it = mItems.begin(); it != mItems.end(); ++it )
+ {
+ (*it)->swapDefault();
+ }
+
+ usrUseDefaults(b);
+ return !mUseDefaults;
+}
+
+void TDEConfigSkeleton::setDefaults()
+{
+ TDEConfigSkeletonItem::List::ConstIterator it;
+ for( it = mItems.begin(); it != mItems.end(); ++it ) {
+ (*it)->setDefault();
+ }
+
+ usrSetDefaults();
+}
+
+void TDEConfigSkeleton::readConfig()
+{
+ kdDebug(177) << "TDEConfigSkeleton::readConfig()" << endl;
+
+ TQString origGroup = mConfig->group();
+
+ mConfig->reparseConfiguration();
+ TDEConfigSkeletonItem::List::ConstIterator it;
+ for( it = mItems.begin(); it != mItems.end(); ++it )
+ {
+ (*it)->readConfig( mConfig );
+ }
+
+ usrReadConfig();
+
+ mConfig->setGroup(origGroup);
+}
+
+void TDEConfigSkeleton::writeConfig()
+{
+ kdDebug(177) << "TDEConfigSkeleton::writeConfig()" << endl;
+
+ TQString origGroup = mConfig->group();
+
+ TDEConfigSkeletonItem::List::ConstIterator it;
+ for( it = mItems.begin(); it != mItems.end(); ++it )
+ {
+ (*it)->writeConfig( mConfig );
+ }
+
+ usrWriteConfig();
+
+ mConfig->sync();
+
+ readConfig();
+
+ mConfig->setGroup(origGroup);
+}
+
+void TDEConfigSkeleton::addItem( TDEConfigSkeletonItem *item, const TQString &name )
+{
+ item->setName( name.isEmpty() ? item->key() : name );
+ mItems.append( item );
+ mItemDict.insert( item->name(), item );
+ item->readDefault( mConfig );
+ item->readConfig( mConfig );
+}
+
+TDEConfigSkeleton::ItemString *TDEConfigSkeleton::addItemString( const TQString &name, TQString &reference,
+ const TQString &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemString *item;
+ item = new TDEConfigSkeleton::ItemString( mCurrentGroup, key.isEmpty() ? name : key,
+ reference, defaultValue,
+ TDEConfigSkeleton::ItemString::Normal );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemPassword *TDEConfigSkeleton::addItemPassword( const TQString &name, TQString &reference,
+ const TQString &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemPassword *item;
+ item = new TDEConfigSkeleton::ItemPassword( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemPath *TDEConfigSkeleton::addItemPath( const TQString &name, TQString &reference,
+ const TQString &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemPath *item;
+ item = new TDEConfigSkeleton::ItemPath( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemProperty *TDEConfigSkeleton::addItemProperty( const TQString &name, TQVariant &reference,
+ const TQVariant &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemProperty *item;
+ item = new TDEConfigSkeleton::ItemProperty( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemBool *TDEConfigSkeleton::addItemBool( const TQString &name, bool &reference,
+ bool defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemBool *item;
+ item = new TDEConfigSkeleton::ItemBool( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemInt *TDEConfigSkeleton::addItemInt( const TQString &name, int &reference,
+ int defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemInt *item;
+ item = new TDEConfigSkeleton::ItemInt( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemUInt *TDEConfigSkeleton::addItemUInt( const TQString &name, unsigned int &reference,
+ unsigned int defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemUInt *item;
+ item = new TDEConfigSkeleton::ItemUInt( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemInt64 *TDEConfigSkeleton::addItemInt64( const TQString &name, TQ_INT64 &reference,
+ TQ_INT64 defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemInt64 *item;
+ item = new TDEConfigSkeleton::ItemInt64( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemUInt64 *TDEConfigSkeleton::addItemUInt64( const TQString &name, TQ_UINT64 &reference,
+ TQ_UINT64 defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemUInt64 *item;
+ item = new TDEConfigSkeleton::ItemUInt64( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemLong *TDEConfigSkeleton::addItemLong( const TQString &name, long &reference,
+ long defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemLong *item;
+ item = new TDEConfigSkeleton::ItemLong( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemULong *TDEConfigSkeleton::addItemULong( const TQString &name, unsigned long &reference,
+ unsigned long defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemULong *item;
+ item = new TDEConfigSkeleton::ItemULong( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemDouble *TDEConfigSkeleton::addItemDouble( const TQString &name, double &reference,
+ double defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemDouble *item;
+ item = new TDEConfigSkeleton::ItemDouble( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemColor *TDEConfigSkeleton::addItemColor( const TQString &name, TQColor &reference,
+ const TQColor &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemColor *item;
+ item = new TDEConfigSkeleton::ItemColor( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemFont *TDEConfigSkeleton::addItemFont( const TQString &name, TQFont &reference,
+ const TQFont &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemFont *item;
+ item = new TDEConfigSkeleton::ItemFont( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemRect *TDEConfigSkeleton::addItemRect( const TQString &name, TQRect &reference,
+ const TQRect &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemRect *item;
+ item = new TDEConfigSkeleton::ItemRect( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemPoint *TDEConfigSkeleton::addItemPoint( const TQString &name, TQPoint &reference,
+ const TQPoint &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemPoint *item;
+ item = new TDEConfigSkeleton::ItemPoint( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemSize *TDEConfigSkeleton::addItemSize( const TQString &name, TQSize &reference,
+ const TQSize &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemSize *item;
+ item = new TDEConfigSkeleton::ItemSize( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemDateTime *TDEConfigSkeleton::addItemDateTime( const TQString &name, TQDateTime &reference,
+ const TQDateTime &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemDateTime *item;
+ item = new TDEConfigSkeleton::ItemDateTime( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemStringList *TDEConfigSkeleton::addItemStringList( const TQString &name, TQStringList &reference,
+ const TQStringList &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemStringList *item;
+ item = new TDEConfigSkeleton::ItemStringList( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+TDEConfigSkeleton::ItemIntList *TDEConfigSkeleton::addItemIntList( const TQString &name, TQValueList<int> &reference,
+ const TQValueList<int> &defaultValue, const TQString &key )
+{
+ TDEConfigSkeleton::ItemIntList *item;
+ item = new TDEConfigSkeleton::ItemIntList( mCurrentGroup, key.isNull() ? name : key,
+ reference, defaultValue );
+ addItem( item, name );
+ return item;
+}
+
+bool TDEConfigSkeleton::isImmutable(const TQString &name)
+{
+ TDEConfigSkeletonItem *item = findItem(name);
+ return !item || item->isImmutable();
+}
+
+TDEConfigSkeletonItem *TDEConfigSkeleton::findItem(const TQString &name)
+{
+ return mItemDict.find(name);
+}
diff --git a/tdecore/tdeconfigskeleton.h b/tdecore/tdeconfigskeleton.h
new file mode 100644
index 000000000..d9424e9df
--- /dev/null
+++ b/tdecore/tdeconfigskeleton.h
@@ -0,0 +1,1230 @@
+/*
+ * This file is part of KDE.
+ *
+ * Copyright (c) 2001,2002,2003 Cornelius Schumacher <schumacher@kde.org>
+ * Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef _KCONFIGSKELETON_H
+#define _KCONFIGSKELETON_H
+
+#include <tqcolor.h>
+#include <tqdatetime.h>
+#include <tqfont.h>
+#include <tqpoint.h>
+#include <tqptrlist.h>
+#include <tqdict.h>
+#include <tqrect.h>
+#include <tqsize.h>
+#include <tqstringlist.h>
+#include <tqvariant.h>
+#include <tdeconfig.h>
+#include <kglobalsettings.h>
+
+ /**
+ * @short Class for storing a preferences setting
+ * @author Cornelius Schumacher
+ * @see TDEConfigSkeleton
+ *
+ * This class represents one preferences setting as used by @ref TDEConfigSkeleton.
+ * Subclasses of TDEConfigSkeletonItem implement storage functions for a certain type of
+ * setting. Normally you don't have to use this class directly. Use the special
+ * addItem() functions of TDEConfigSkeleton instead. If you subclass this class you will
+ * have to register instances with the function TDEConfigSkeleton::addItem().
+ */
+ class TDECORE_EXPORT TDEConfigSkeletonItem
+ {
+ public:
+ typedef TQValueList < TDEConfigSkeletonItem * >List;
+ typedef TQDict < TDEConfigSkeletonItem > Dict;
+ typedef TQDictIterator < TDEConfigSkeletonItem > DictIterator;
+
+ /**
+ * Constructor.
+ *
+ * @param group Config file group.
+ * @param key Config file key.
+ */
+ TDEConfigSkeletonItem(const TQString & group, const TQString & key)
+ :mGroup(group),mKey(key), mIsImmutable(true)
+ {
+ }
+
+ /**
+ * Destructor.
+ */
+ virtual ~TDEConfigSkeletonItem()
+ {
+ }
+
+ /**
+ * Set config file group.
+ */
+ void setGroup( const TQString &group )
+ {
+ mGroup = group;
+ }
+
+ /**
+ * Return config file group.
+ */
+ TQString group() const
+ {
+ return mGroup;
+ }
+
+ /**
+ * Set config file key.
+ */
+ void setKey( const TQString &key )
+ {
+ mKey = key;
+ }
+
+ /**
+ * Return config file key.
+ */
+ TQString key() const
+ {
+ return mKey;
+ }
+
+ /**
+ * Set internal name of entry.
+ */
+ void setName(const TQString &name)
+ {
+ mName = name;
+ }
+
+ /**
+ * Return internal name of entry.
+ */
+ TQString name() const
+ {
+ return mName;
+ }
+
+ /**
+ Set label providing a translated one-line description of the item.
+ */
+ void setLabel( const TQString &l )
+ {
+ mLabel = l;
+ }
+
+ /**
+ Return label of item. See setLabel().
+ */
+ TQString label() const
+ {
+ return mLabel;
+ }
+
+ /**
+ Set WhatsThis description og item.
+ */
+ void setWhatsThis( const TQString &w )
+ {
+ mWhatsThis = w;
+ }
+
+ /**
+ Return WhatsThis description of item. See setWhatsThis().
+ */
+ TQString whatsThis() const
+ {
+ return mWhatsThis;
+ }
+
+ /**
+ * This function is called by @ref TDEConfigSkeleton to read the value for this setting
+ * from a config file.
+ * value.
+ */
+ virtual void readConfig(TDEConfig *) = 0;
+
+ /**
+ * This function is called by @ref TDEConfigSkeleton to write the value of this setting
+ * to a config file.
+ */
+ virtual void writeConfig(TDEConfig *) = 0;
+
+ /**
+ * Read global default value.
+ */
+ virtual void readDefault(TDEConfig *) = 0;
+
+ /**
+ * Set item to @p p
+ */
+ virtual void setProperty(const TQVariant &p) = 0;
+
+ /**
+ * Return item as property
+ */
+ virtual TQVariant property() const = 0;
+
+ /**
+ * Return minimum value of item or invalid if not specified
+ */
+ virtual TQVariant minValue() const { return TQVariant(); }
+
+ /**
+ * Return maximum value of item or invalid if not specified
+ */
+ virtual TQVariant maxValue() const { return TQVariant(); }
+
+ /**
+ Sets the current value to the default value.
+ */
+ virtual void setDefault() = 0;
+
+ /**
+ * Exchanges the current value with the default value
+ * Used by TDEConfigSkeleton::useDefaults(bool);
+ */
+ virtual void swapDefault() = 0;
+
+ /**
+ * Return if the entry can be modified.
+ */
+ bool isImmutable() const
+ {
+ return mIsImmutable;
+ }
+
+ protected:
+ /**
+ * sets mIsImmutable to true if mKey in config is immutable
+ * @param config TDEConfig to check if mKey is immutable in
+ */
+ void readImmutability(TDEConfig *config);
+
+ TQString mGroup;
+ TQString mKey;
+ TQString mName;
+
+ private:
+ bool mIsImmutable;
+
+ TQString mLabel;
+ TQString mWhatsThis;
+ };
+
+
+template < typename T > class TDEConfigSkeletonGenericItem:public TDEConfigSkeletonItem
+ {
+ public:
+ TDEConfigSkeletonGenericItem(const TQString & group, const TQString & key, T & reference,
+ T defaultValue)
+ : TDEConfigSkeletonItem(group, key), mReference(reference),
+ mDefault(defaultValue), mLoadedValue(defaultValue)
+ {
+ }
+
+ /**
+ * Set value of this TDEConfigSkeletonItem.
+ */
+ void setValue(const T & v)
+ {
+ mReference = v;
+ }
+
+ /**
+ * Return value of this TDEConfigSkeletonItem.
+ */
+ T & value()
+ {
+ return mReference;
+ }
+
+ /**
+ * Return const value of this TDEConfigSkeletonItem.
+ */
+ const T & value() const
+ {
+ return mReference;
+ }
+
+ /**
+ Set default value for this item.
+ */
+ virtual void setDefaultValue( const T &v )
+ {
+ mDefault = v;
+ }
+
+ virtual void setDefault()
+ {
+ mReference = mDefault;
+ }
+
+ virtual void writeConfig(TDEConfig * config)
+ {
+ if ( mReference != mLoadedValue ) // Is this needed?
+ {
+ config->setGroup(mGroup);
+ if ((mDefault == mReference) && !config->hasDefault( mKey))
+ config->revertToDefault( mKey );
+ else
+ config->writeEntry(mKey, mReference);
+ }
+ }
+
+ void readDefault(TDEConfig * config)
+ {
+ config->setReadDefaults(true);
+ readConfig(config);
+ config->setReadDefaults(false);
+ mDefault = mReference;
+ }
+
+ void swapDefault()
+ {
+ T tmp = mReference;
+ mReference = mDefault;
+ mDefault = tmp;
+ }
+
+ protected:
+ T & mReference;
+ T mDefault;
+ T mLoadedValue;
+ };
+
+ /**
+ * @short Class for handling preferences settings for an application.
+ * @author Cornelius Schumacher
+ * @see TDEConfigSkeletonItem
+ *
+ * This class provides an interface to preferences settings. Preferences items
+ * can be registered by the addItem() function corresponding to the data type of
+ * the seetting. TDEConfigSkeleton then handles reading and writing of config files and
+ * setting of default values.
+ *
+ * Normally you will subclass TDEConfigSkeleton, add data members for the preferences
+ * settings and register the members in the constructor of the subclass.
+ *
+ * Example:
+ * \code
+ * class MyPrefs : public TDEConfigSkeleton
+ * {
+ * public:
+ * MyPrefs()
+ * {
+ * setCurrentGroup("MyGroup");
+ * addItemBool("MySetting1",mMyBool,false);
+ * addItemColor("MySetting2",mMyColor,TQColor(1,2,3));
+ *
+ * setCurrentGroup("MyOtherGroup");
+ * addItemFont("MySetting3",mMyFont,TQFont("helvetica",12));
+ * }
+ *
+ * bool mMyBool;
+ * TQColor mMyColor;
+ * TQFont mMyFont;
+ * }
+ * \endcode
+ *
+ * It might be convenient in many cases to make this subclass of TDEConfigSkeleton a
+ * singleton for global access from all over the application without passing
+ * references to the TDEConfigSkeleton object around.
+ *
+ * You can write the data to the configuration file by calling @ref writeConfig()
+ * and read the data from the configuration file by calling @ref readConfig().
+ *
+ * If you have items, which are not covered by the existing addItem() functions
+ * you can add customized code for reading, writing and default setting by
+ * implementing the functions @ref usrUseDefaults(), @ref usrReadConfig() and
+ * @ref usrWriteConfig().
+ *
+ * Internally preferences settings are stored in instances of subclasses of
+ * @ref TDEConfigSkeletonItem. You can also add TDEConfigSkeletonItem subclasses
+ * for your own types and call the generic @ref addItem() to register them.
+ *
+ * In many cases you don't have to write the specific TDEConfigSkeleton
+ * subclasses yourself, but you can use \ref tdeconfig_compiler to automatically
+ * generate the C++ code from an XML description of the configuration options.
+ */
+class TDECORE_EXPORT TDEConfigSkeleton
+{
+public:
+
+ /**
+ * Class for handling a string preferences item.
+ */
+ class TDECORE_EXPORT ItemString:public TDEConfigSkeletonGenericItem < TQString >
+ {
+ public:
+ enum Type { Normal, Password, Path };
+
+ ItemString(const TQString & group, const TQString & key,
+ TQString & reference,
+ const TQString & defaultValue = TQString::fromLatin1(""), // NOT TQString::null !!
+ Type type = Normal);
+
+ void writeConfig(TDEConfig * config);
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+
+ private:
+ Type mType;
+ };
+
+ /**
+ * Class for handling a password preferences item.
+ */
+ class TDECORE_EXPORT ItemPassword:public ItemString
+ {
+ public:
+ ItemPassword(const TQString & group, const TQString & key,
+ TQString & reference,
+ const TQString & defaultValue = TQString::fromLatin1("")); // NOT TQString::null !!
+ };
+
+ /**
+ * Class for handling a path preferences item.
+ */
+ class TDECORE_EXPORT ItemPath:public ItemString
+ {
+ public:
+ ItemPath(const TQString & group, const TQString & key,
+ TQString & reference,
+ const TQString & defaultValue = TQString::null);
+ };
+
+
+ /**
+ * Class for handling a TQVariant preferences item.
+ */
+ class TDECORE_EXPORT ItemProperty:public TDEConfigSkeletonGenericItem < TQVariant >
+ {
+ public:
+ ItemProperty(const TQString & group, const TQString & key,
+ TQVariant & reference, TQVariant defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a bool preferences item.
+ */
+ class TDECORE_EXPORT ItemBool:public TDEConfigSkeletonGenericItem < bool >
+ {
+ public:
+ ItemBool(const TQString & group, const TQString & key, bool & reference,
+ bool defaultValue = true);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling an integer preferences item.
+ */
+ class TDECORE_EXPORT ItemInt:public TDEConfigSkeletonGenericItem < int >
+ {
+ public:
+ ItemInt(const TQString & group, const TQString & key, int &reference,
+ int defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ TQVariant minValue() const;
+ TQVariant maxValue() const;
+
+ void setMinValue(int);
+ void setMaxValue(int);
+
+ private:
+ bool mHasMin : 1;
+ bool mHasMax : 1;
+ int mMin;
+ int mMax;
+ };
+
+ /**
+ * Class for handling an 64-bit integer preferences item.
+ */
+ class TDECORE_EXPORT ItemInt64:public TDEConfigSkeletonGenericItem < TQ_INT64 >
+ {
+ public:
+ ItemInt64(const TQString & group, const TQString & key, TQ_INT64 &reference,
+ TQ_INT64 defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+
+ TQVariant minValue() const;
+ TQVariant maxValue() const;
+
+ void setMinValue(TQ_INT64);
+ void setMaxValue(TQ_INT64);
+
+ private:
+ bool mHasMin : 1;
+ bool mHasMax : 1;
+ TQ_INT64 mMin;
+ TQ_INT64 mMax;
+ };
+
+ /**
+ * Class for handling enums.
+ */
+ class TDECORE_EXPORT ItemEnum:public ItemInt
+ {
+ public:
+ struct Choice
+ {
+ TQString name;
+ TQString label;
+ TQString whatsThis;
+ };
+
+ ItemEnum(const TQString & group, const TQString & key, int &reference,
+ const TQValueList<Choice> &choices, int defaultValue = 0);
+
+ TQValueList<Choice> choices() const;
+
+ void readConfig(TDEConfig * config);
+ void writeConfig(TDEConfig * config);
+
+ private:
+ TQValueList<Choice> mChoices;
+ };
+
+
+ /**
+ * Class for handling an unsingend integer preferences item.
+ */
+ class TDECORE_EXPORT ItemUInt:public TDEConfigSkeletonGenericItem < unsigned int >
+ {
+ public:
+ ItemUInt(const TQString & group, const TQString & key,
+ unsigned int &reference, unsigned int defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ TQVariant minValue() const;
+ TQVariant maxValue() const;
+
+ void setMinValue(unsigned int);
+ void setMaxValue(unsigned int);
+
+ private:
+ bool mHasMin : 1;
+ bool mHasMax : 1;
+ unsigned int mMin;
+ unsigned int mMax;
+ };
+
+
+ /**
+ * Class for hanlding a long integer preferences item.
+ */
+ class TDECORE_EXPORT ItemLong:public TDEConfigSkeletonGenericItem < long >
+ {
+ public:
+ ItemLong(const TQString & group, const TQString & key, long &reference,
+ long defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ TQVariant minValue() const;
+ TQVariant maxValue() const;
+
+ void setMinValue(long);
+ void setMaxValue(long);
+
+ private:
+ bool mHasMin : 1;
+ bool mHasMax : 1;
+ long mMin;
+ long mMax;
+ };
+
+
+ /**
+ * Class for handling an unsigned long integer preferences item.
+ */
+ class TDECORE_EXPORT ItemULong:public TDEConfigSkeletonGenericItem < unsigned long >
+ {
+ public:
+ ItemULong(const TQString & group, const TQString & key,
+ unsigned long &reference, unsigned long defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ TQVariant minValue() const;
+ TQVariant maxValue() const;
+
+ void setMinValue(unsigned long);
+ void setMaxValue(unsigned long);
+
+ private:
+ bool mHasMin : 1;
+ bool mHasMax : 1;
+ unsigned long mMin;
+ unsigned long mMax;
+ };
+
+ /**
+ * Class for handling unsigned 64-bit integer preferences item.
+ */
+ class TDECORE_EXPORT ItemUInt64:public TDEConfigSkeletonGenericItem < TQ_UINT64 >
+ {
+ public:
+ ItemUInt64(const TQString & group, const TQString & key, TQ_UINT64 &reference,
+ TQ_UINT64 defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+
+ TQVariant minValue() const;
+ TQVariant maxValue() const;
+
+ void setMinValue(TQ_UINT64);
+ void setMaxValue(TQ_UINT64);
+
+ private:
+ bool mHasMin : 1;
+ bool mHasMax : 1;
+ TQ_UINT64 mMin;
+ TQ_UINT64 mMax;
+ };
+
+ /**
+ * Class for handling a floating point preference item.
+ */
+ class TDECORE_EXPORT ItemDouble:public TDEConfigSkeletonGenericItem < double >
+ {
+ public:
+ ItemDouble(const TQString & group, const TQString & key,
+ double &reference, double defaultValue = 0);
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ TQVariant minValue() const;
+ TQVariant maxValue() const;
+
+ void setMinValue(double);
+ void setMaxValue(double);
+
+ private:
+ bool mHasMin : 1;
+ bool mHasMax : 1;
+ double mMin;
+ double mMax;
+ };
+
+
+ /**
+ * Class for handling a color preferences item.
+ */
+ class TDECORE_EXPORT ItemColor:public TDEConfigSkeletonGenericItem < TQColor >
+ {
+ public:
+ ItemColor(const TQString & group, const TQString & key,
+ TQColor & reference,
+ const TQColor & defaultValue = TQColor(128, 128, 128));
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a font preferences item.
+ */
+ class TDECORE_EXPORT ItemFont:public TDEConfigSkeletonGenericItem < TQFont >
+ {
+ public:
+ ItemFont(const TQString & group, const TQString & key, TQFont & reference,
+ const TQFont & defaultValue = TDEGlobalSettings::generalFont());
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a TQRect preferences item.
+ */
+ class TDECORE_EXPORT ItemRect:public TDEConfigSkeletonGenericItem < TQRect >
+ {
+ public:
+ ItemRect(const TQString & group, const TQString & key, TQRect & reference,
+ const TQRect & defaultValue = TQRect());
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a TQPoint preferences item.
+ */
+ class TDECORE_EXPORT ItemPoint:public TDEConfigSkeletonGenericItem < TQPoint >
+ {
+ public:
+ ItemPoint(const TQString & group, const TQString & key, TQPoint & reference,
+ const TQPoint & defaultValue = TQPoint());
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a TQSize preferences item.
+ */
+ class TDECORE_EXPORT ItemSize:public TDEConfigSkeletonGenericItem < TQSize >
+ {
+ public:
+ ItemSize(const TQString & group, const TQString & key, TQSize & reference,
+ const TQSize & defaultValue = TQSize());
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a TQDateTime preferences item.
+ */
+ class TDECORE_EXPORT ItemDateTime:public TDEConfigSkeletonGenericItem < TQDateTime >
+ {
+ public:
+ ItemDateTime(const TQString & group, const TQString & key,
+ TQDateTime & reference,
+ const TQDateTime & defaultValue = TQDateTime());
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a string list preferences item.
+ */
+ class TDECORE_EXPORT ItemStringList:public TDEConfigSkeletonGenericItem < TQStringList >
+ {
+ public:
+ ItemStringList(const TQString & group, const TQString & key,
+ TQStringList & reference,
+ const TQStringList & defaultValue = TQStringList());
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+ /**
+ * Class for handling a path list preferences item.
+ */
+ class TDECORE_EXPORT ItemPathList:public ItemStringList
+ {
+ public:
+ ItemPathList(const TQString & group, const TQString & key,
+ TQStringList & reference,
+ const TQStringList & defaultValue = TQStringList());
+
+ void readConfig(TDEConfig * config);
+ void writeConfig(TDEConfig * config);
+ };
+
+
+ /**
+ * Class for handling an integer list preferences item.
+ */
+ class TDECORE_EXPORT ItemIntList:public TDEConfigSkeletonGenericItem < TQValueList < int > >
+ {
+ public:
+ ItemIntList(const TQString & group, const TQString & key,
+ TQValueList < int >&reference,
+ const TQValueList < int >&defaultValue = TQValueList < int >());
+
+ void readConfig(TDEConfig * config);
+ void setProperty(const TQVariant & p);
+ TQVariant property() const;
+ };
+
+
+public:
+ /**
+ * Constructor.
+ *
+ * @param configname name of config file. If no name is given, the default
+ * config file as returned by kapp()->config() is used.
+ */
+ TDEConfigSkeleton(const TQString & configname = TQString::null);
+
+ /**
+ * Constructor.
+ *
+ * @param config configuration object to use.
+ */
+ TDEConfigSkeleton(KSharedConfig::Ptr config);
+
+ /**
+ * Destructor
+ */
+ virtual ~ TDEConfigSkeleton();
+
+ /**
+ Set all registered items to their default values.
+ */
+ void setDefaults();
+
+ /**
+ * Read preferences from config file. All registered items are set to the
+ * values read from disk.
+ */
+ void readConfig();
+
+ /**
+ * Write preferences to config file. The values of all registered items are
+ * written to disk.
+ */
+ void writeConfig();
+
+ /**
+ * Set the config file group for subsequent addItem() calls. It is valid
+ * until setCurrentGroup() is called with a new argument. Call this before
+ * you add any items. The default value is "No Group".
+ */
+ void setCurrentGroup(const TQString & group);
+
+ /**
+ * Returns the current group used for addItem() calls.
+ */
+ TQString currentGroup() // ### KDE 4.0: make const
+ {
+ return mCurrentGroup;
+ }
+
+ /**
+ * Register a custom @ref TDEConfigSkeletonItem with a given name. If the name
+ * parameter is null, take the name from TDEConfigSkeletonItem::key().
+ * Note that all names must be unique but that multiple entries can have
+ * the same key if they reside in different groups.
+ */
+ void addItem(TDEConfigSkeletonItem *, const TQString & name = TQString::null );
+
+ /**
+ * Register an item of type TQString.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemString *addItemString(const TQString & name, TQString & reference,
+ const TQString & defaultValue = TQString::fromLatin1(""), // NOT TQString::null !!
+ const TQString & key = TQString::null);
+
+ /**
+ * Register a password item of type TQString. The string value is written
+ * encrypted to the config file. Note that the current encryption scheme
+ * is very weak.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemPassword *addItemPassword(const TQString & name, TQString & reference,
+ const TQString & defaultValue = TQString::fromLatin1(""),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register a path item of type TQString. The string value is interpreted
+ * as a path. This means, dollar expension is activated for this value, so
+ * that e.g. $HOME gets expanded.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemPath *addItemPath(const TQString & name, TQString & reference,
+ const TQString & defaultValue = TQString::fromLatin1(""),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register a property item of type TQVariant. Note that only the following
+ * TQVariant types are allowed: String, StringList, Font, Point, Rect, Size,
+ * Color, Int, UInt, Bool, Double, DateTime and Date.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemProperty *addItemProperty(const TQString & name, TQVariant & reference,
+ const TQVariant & defaultValue = TQVariant(),
+ const TQString & key = TQString::null);
+ /**
+ * Register an item of type bool.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemBool *addItemBool(const TQString & name, bool & reference,
+ bool defaultValue = false,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type int.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemInt *addItemInt(const TQString & name, int &reference, int defaultValue = 0,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type unsigned int.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemUInt *addItemUInt(const TQString & name, unsigned int &reference,
+ unsigned int defaultValue = 0,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type long.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemLong *addItemLong(const TQString & name, long &reference,
+ long defaultValue = 0,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type unsigned long.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemULong *addItemULong(const TQString & name, unsigned long &reference,
+ unsigned long defaultValue = 0,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQ_INT64.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemInt64 *addItemInt64(const TQString & name, TQ_INT64 &reference,
+ TQ_INT64 defaultValue = 0,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQ_UINT64
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemUInt64 *addItemUInt64(const TQString & name, TQ_UINT64 &reference,
+ TQ_UINT64 defaultValue = 0,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type double.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemDouble *addItemDouble(const TQString & name, double &reference,
+ double defaultValue = 0.0,
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQColor.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemColor *addItemColor(const TQString & name, TQColor & reference,
+ const TQColor & defaultValue = TQColor(128, 128, 128),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQFont.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemFont *addItemFont(const TQString & name, TQFont & reference,
+ const TQFont & defaultValue =
+ TDEGlobalSettings::generalFont(),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQRect.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemRect *addItemRect(const TQString & name, TQRect & reference,
+ const TQRect & defaultValue = TQRect(),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQPoint.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemPoint *addItemPoint(const TQString & name, TQPoint & reference,
+ const TQPoint & defaultValue = TQPoint(),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQSize.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemSize *addItemSize(const TQString & name, TQSize & reference,
+ const TQSize & defaultValue = TQSize(),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQDateTime.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemDateTime *addItemDateTime(const TQString & name, TQDateTime & reference,
+ const TQDateTime & defaultValue = TQDateTime(),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQStringList.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemStringList *addItemStringList(const TQString & name, TQStringList & reference,
+ const TQStringList & defaultValue = TQStringList(),
+ const TQString & key = TQString::null);
+
+ /**
+ * Register an item of type TQValueList<int>.
+ *
+ * @param name Name used to indentify this setting. Names must be unique.
+ * @param reference Pointer to the variable, which is set by readConfig()
+ * calls and read by writeConfig() calls.
+ * @param defaultValue Default value, which is used when the config file
+ * does not yet contain the key of this item.
+ * @param key Key used in config file. If key is null, name is used as key.
+ * @return The created item
+ */
+ ItemIntList *addItemIntList(const TQString & name, TQValueList < int >&reference,
+ const TQValueList < int >&defaultValue =
+ TQValueList < int >(),
+ const TQString & key = TQString::null);
+
+ /**
+ * Return the @ref TDEConfig object used for reading and writing the settings.
+ */
+ TDEConfig *config() const;
+
+ /**
+ * Return list of items managed by this TDEConfigSkeleton object.
+ */
+ TDEConfigSkeletonItem::List items() const
+ {
+ return mItems;
+ }
+
+ /**
+ * Return whether a certain item is immutable
+ */
+ bool isImmutable(const TQString & name);
+
+ /**
+ * Lookup item by name
+ */
+ TDEConfigSkeletonItem * findItem(const TQString & name);
+
+ /**
+ * Indicate whether this object should reflect the actual
+ * values or the default values.
+ * @param b If true this object reflects the default values.
+ * @return The state prior to this call
+ */
+ bool useDefaults(bool b);
+
+protected:
+ /**
+ * Implemented by subclasses that use special defaults.
+ * It should replace the default values with the actual
+ * values and vice versa.
+ */
+ virtual void usrUseDefaults(bool)
+ {
+ }
+
+ virtual void usrSetDefaults()
+ {
+ }
+
+ /**
+ * Implemented by subclasses that read special config values.
+ */
+ virtual void usrReadConfig()
+ {
+ }
+
+ /**
+ * Implemented by subclasses that write special config values.
+ */
+ virtual void usrWriteConfig()
+ {
+ }
+
+private:
+ TQString mCurrentGroup;
+
+ KSharedConfig::Ptr mConfig; // pointer to TDEConfig object
+
+ TDEConfigSkeletonItem::List mItems;
+ TDEConfigSkeletonItem::Dict mItemDict;
+
+ bool mUseDefaults;
+
+ class Private;
+ Private *d;
+
+};
+
+#endif
diff --git a/tdecore/tdehardwaredevices.cpp b/tdecore/tdehardwaredevices.cpp
index d012c64aa..5044aab8e 100644
--- a/tdecore/tdehardwaredevices.cpp
+++ b/tdecore/tdehardwaredevices.cpp
@@ -25,7 +25,7 @@
#include <kglobal.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ktempfile.h>
#include <ksimpledirwatch.h>
#include <kstandarddirs.h>
diff --git a/tdecore/tdesycoca.cpp b/tdecore/tdesycoca.cpp
index f433510d6..31da8b741 100644
--- a/tdecore/tdesycoca.cpp
+++ b/tdecore/tdesycoca.cpp
@@ -450,7 +450,7 @@ void KSycoca::flagError()
return;
_self->d->readError = true;
if (_self->d->autoRebuild)
- if(system("kbuildsycoca") < 0) // Rebuild the damned thing.
+ if(system("tdebuildsycoca") < 0) // Rebuild the damned thing.
tqWarning("ERROR: Running KSycoca failed.");
}
}
diff --git a/tdecore/tdesycoca.h b/tdecore/tdesycoca.h
index 1b3355de3..bf41da415 100644
--- a/tdecore/tdesycoca.h
+++ b/tdecore/tdesycoca.h
@@ -124,7 +124,7 @@ public:
virtual bool isBuilding() { return false; }
/**
- * @internal - disables launching of kbuildsycoca
+ * @internal - disables launching of tdebuildsycoca
*/
void disableAutoRebuild();
@@ -152,7 +152,7 @@ public:
k_dcop:
/**
- * internal function for receiving kded/kbuildsycoca's signal, when the sycoca file changes
+ * internal function for receiving kded/tdebuildsycoca's signal, when the sycoca file changes
*/
void notifyDatabaseChanged(const TQStringList &);
diff --git a/tdecore/tests/Makefile.am b/tdecore/tests/Makefile.am
index 9d2c5259c..90ba46051 100644
--- a/tdecore/tests/Makefile.am
+++ b/tdecore/tests/Makefile.am
@@ -21,7 +21,7 @@ INCLUDES = -I$(top_srcdir)/tdecore $(all_includes)
AM_LDFLAGS = $(QT_LDFLAGS) $(X_LDFLAGS) $(KDE_RPATH)
-check_PROGRAMS = kconfigtestgui klocaletest kprocesstest ksimpleconfigtest \
+check_PROGRAMS = tdeconfigtestgui klocaletest kprocesstest ksimpleconfigtest \
kstddirstest kurltest kuniqueapptest ktempfiletest krandomsequencetest \
kdebugtest ksocktest kstringhandlertest kcmdlineargstest kapptest \
kmemtest kidlservertest kidlclienttest dcopkonqtest kipctest \
@@ -38,7 +38,7 @@ noinst_HEADERS = klocaletest.h kprocesstest.h KIDLTest.h \
METASOURCES = AUTO
LDADD = ../libtdecore.la
-kconfigtestgui_SOURCES = kconfigtestgui.cpp
+tdeconfigtestgui_SOURCES = tdeconfigtestgui.cpp
kdebugtest_SOURCES = kdebugtest.cpp
klocaletest_SOURCES = klocaletest.cpp
#klocaletest2_SOURCES = klocaletest2.cpp klocale.cpp libintl.cpp kcatalogue.cpp
@@ -79,8 +79,8 @@ kstdacceltest_SOURCES = kstdacceltest.cpp
kglobaltest_SOURCES = kglobaltest.cpp
ktimezonestest_SOURCES = ktimezonestest.cpp
-check_LTLIBRARIES = tdeunittest_kconfig.la
+check_LTLIBRARIES = tdeunittest_tdeconfig.la
-tdeunittest_kconfig_la_SOURCES = kconfigtest.cpp
-tdeunittest_kconfig_la_LIBADD = $(LIB_KUNITTEST)
-tdeunittest_kconfig_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN)
+tdeunittest_tdeconfig_la_SOURCES = tdeconfigtest.cpp
+tdeunittest_tdeconfig_la_LIBADD = $(LIB_KUNITTEST)
+tdeunittest_tdeconfig_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN)
diff --git a/tdecore/tests/kconfigtest.cpp b/tdecore/tests/kconfigtest.cpp
deleted file mode 100644
index d3421a3d8..000000000
--- a/tdecore/tests/kconfigtest.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include <tdeunittest/tester.h>
-#include <tdeunittest/module.h>
-
-#include <kconfig.h>
-
-class TDEConfigTest : public KUnitTest::Tester
-{
-public:
- void allTests();
-private:
- void writeConfigFile();
- void revertEntries();
-};
-
-KUNITTEST_MODULE( tdeunittest_kconfig, "TDEConfigTest" )
-KUNITTEST_MODULE_REGISTER_TESTER( TDEConfigTest )
-
-// test data
-#define BOOLENTRY1 true
-#define BOOLENTRY2 false
-#define STRINGENTRY1 "hello"
-#define STRINGENTRY2 " hello"
-#define STRINGENTRY3 "hello "
-#define STRINGENTRY4 " hello "
-#define STRINGENTRY5 " "
-#define STRINGENTRY6 ""
-#define LOCAL8BITENTRY "Hello äöü"
-#define POINTENTRY TQPoint( 4351, 1235 )
-#define SIZEENTRY TQSize( 10, 20 )
-#define RECTENTRY TQRect( 10, 23, 5321, 13 )
-#define DATETIMEENTRY TQDateTime( TQDate( 2002, 06, 23 ), TQTime( 12, 55, 40 ) )
-#define STRINGLISTENTRY TQStringList( "Hello," )
-
-void TDEConfigTest::writeConfigFile()
-{
- TDEConfig sc( "kconfigtest" );
-
- sc.setGroup("AAA");
- sc.writeEntry("stringEntry1", STRINGENTRY1, true, true);
- sc.deleteEntry("stringEntry2", false, true);
-
- sc.setGroup("Hello");
- sc.writeEntry( "boolEntry1", BOOLENTRY1 );
- sc.writeEntry( "boolEntry2", BOOLENTRY2 );
-
- sc.writeEntry( "Test", TQString::fromLocal8Bit( LOCAL8BITENTRY ) );
- sc.writeEntry( "Test2", "");
- sc.writeEntry( "stringEntry1", STRINGENTRY1 );
- sc.writeEntry( "stringEntry2", STRINGENTRY2 );
- sc.writeEntry( "stringEntry3", STRINGENTRY3 );
- sc.writeEntry( "stringEntry4", STRINGENTRY4 );
- sc.writeEntry( "stringEntry5", STRINGENTRY5 );
-// sc.writeEntry( "stringEntry6", STRINGENTRY6 );
- sc.writeEntry( "keywith=equalsign", STRINGENTRY1 );
- sc.deleteEntry( "stringEntry5" );
- sc.deleteEntry( "stringEntry6" );
-
- sc.deleteGroup("deleteMe", true);
-
- sc.setGroup("Bye");
- sc.writeEntry( "rectEntry", RECTENTRY );
- sc.writeEntry( "pointEntry", POINTENTRY );
- sc.writeEntry( "sizeEntry", SIZEENTRY );
- sc.writeEntry( "dateTimeEntry", DATETIMEENTRY );
- sc.writeEntry( "stringListEntry", STRINGLISTENTRY );
- sc.sync();
-}
-
-// ### TODO: call this, and test the state of things afterwards
-void TDEConfigTest::revertEntries()
-{
- tqWarning("Reverting entries");
- TDEConfig sc( "kconfigtest" );
-
- sc.setGroup("Hello");
- sc.revertToDefault( "boolEntry1");
- sc.revertToDefault( "boolEntry2");
-
- sc.revertToDefault( "Test" );
- sc.revertToDefault( "Test2" );
- sc.revertToDefault( "stringEntry1" );
- sc.revertToDefault( "stringEntry2" );
- sc.revertToDefault( "stringEntry3" );
- sc.revertToDefault( "stringEntry4" );
- sc.revertToDefault( "stringEntry5" );
- sc.sync();
-}
-
-void TDEConfigTest::allTests()
-{
- writeConfigFile();
-
- TDEConfig sc2( "kconfigtest" );
-
- TDEConfigGroup sc3( &sc2, "AAA");
- bool bImmutable = sc3.entryIsImmutable("stringEntry1");
-
- CHECK( bImmutable, false );
- //tqWarning("sc3.entryIsImmutable() 1: %s", bImmutable ? "true" : "false");
-
- sc2.setGroup("AAA");
- CHECK( sc2.hasKey( "stringEntry1" ), true );
- CHECK( sc2.readEntry( "stringEntry1" ), TQString( STRINGENTRY1 ) );
- CHECK( sc2.entryIsImmutable("stringEntry1"), bImmutable );
- CHECK( sc2.hasKey( "stringEntry2" ), false );
- CHECK( sc2.readEntry( "stringEntry2", "bla" ), TQString( "bla" ) );
-
- CHECK( sc2.hasDefault( "stringEntry1" ), false );
-
- sc2.setGroup("Hello");
- CHECK( sc2.readEntry( "Test" ), TQString::fromLocal8Bit( LOCAL8BITENTRY ) );
- CHECK( sc2.readEntry("Test2", "Fietsbel").isEmpty(), true );
- CHECK( sc2.readEntry( "stringEntry1" ), TQString( STRINGENTRY1 ) );
- CHECK( sc2.readEntry( "stringEntry2" ), TQString( STRINGENTRY2 ) );
- CHECK( sc2.readEntry( "stringEntry3" ), TQString( STRINGENTRY3 ) );
- CHECK( sc2.readEntry( "stringEntry4" ), TQString( STRINGENTRY4 ) );
- CHECK( sc2.hasKey( "stringEntry5" ), false);
- CHECK( sc2.readEntry( "stringEntry5", "test" ), TQString( "test" ) );
- CHECK( sc2.hasKey( "stringEntry6" ), false);
- CHECK( sc2.readEntry( "stringEntry6", "foo" ), TQString( "foo" ) );
- CHECK( sc2.readBoolEntry( "boolEntry1" ), BOOLENTRY1 );
- CHECK( sc2.readBoolEntry( "boolEntry2" ), BOOLENTRY2 );
-
-#if 0
- TQString s;
- s = sc2.readEntry( "keywith=equalsign" );
- fprintf(stderr, "comparing keywith=equalsign %s with %s -> ", STRINGENTRY1, s.latin1());
- if (s == STRINGENTRY1)
- fprintf(stderr, "OK\n");
- else {
- fprintf(stderr, "not OK\n");
- exit(-1);
- }
-#endif
-
- sc2.setGroup("Bye");
-
- CHECK( sc2.readPointEntry( "pointEntry" ), POINTENTRY );
- CHECK( sc2.readSizeEntry( "sizeEntry" ), SIZEENTRY);
- CHECK( sc2.readRectEntry( "rectEntry" ), RECTENTRY );
- CHECK( sc2.readDateTimeEntry( "dateTimeEntry" ).toString(), DATETIMEENTRY.toString() );
- CHECK( sc2.readListEntry( "stringListEntry").join( "," ), STRINGLISTENTRY.join( "," ) );
-}
diff --git a/tdecore/tests/kconfigtestgui.cpp b/tdecore/tests/kconfigtestgui.cpp
deleted file mode 100644
index 776082bfb..000000000
--- a/tdecore/tests/kconfigtestgui.cpp
+++ /dev/null
@@ -1,200 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "kconfigtestgui.h"
-#include "kconfigtestgui.moc"
-
-//
-// configtest.cpp: libKDEcore example
-//
-// demonstrates use of TDEConfig class
-//
-// adapted from Qt widgets demo
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <kapplication.h>
-#include <tqdialog.h>
-#include <tqfile.h>
-#include <tqfileinfo.h>
-#include <tqdatetime.h>
-#include <kdebug.h>
-#include <ksimpleconfig.h>
-#include <config.h>
-
-// Standard Qt widgets
-
-#include <tqlabel.h>
-#include <tqlineedit.h>
-#include <tqpushbutton.h>
-
-// KDE includes
-#include <kconfig.h>
-
-#ifdef HAVE_PATHS_H
-#include <paths.h>
-#endif
-
-#ifndef _PATH_TMP
-#define _PATH_TMP "/tmp/"
-#endif
-
-//
-// Construct the TDEConfigTestView with buttons
-//
-
-TDEConfigTestView::TDEConfigTestView( TQWidget *parent, const char *name )
- : TQDialog( parent, name ),
- pConfig( 0L ),
- pFile( 0L ),
- pStream( 0L )
-{
- // Set the window caption/title
-
- setCaption( "TDEConfig test" );
-
- // Label and edit for the app config file
- pAppFileLabel = new TQLabel( this, "appconfiglabel" );
- pAppFileLabel->setText( "Application config file:" );
- pAppFileLabel->setGeometry( 20, 20, 200, 20 );
-
- pAppFileEdit = new TQLineEdit( this, "appconfigedit" );
- pAppFileEdit->setGeometry( 240, 20, 160, 20 );
- connect( pAppFileEdit, TQT_SIGNAL(returnPressed()),
- TQT_SLOT(appConfigEditReturnPressed()));
-
- // Label and edit for the group
- pGroupLabel = new TQLabel( this, "grouplabel" );
- pGroupLabel->setText( "Group:" );
- pGroupLabel->setGeometry( 20, 60, 80, 20 );
-
- pGroupEdit = new TQLineEdit( this, "groupedit" );
- pGroupEdit->setGeometry( 120, 60, 100, 20 );
- connect( pGroupEdit, TQT_SIGNAL(returnPressed()),
- TQT_SLOT(groupEditReturnPressed()));
-
- // Edit and label for the key/value pair
- pKeyEdit = new TQLineEdit( this, "keyedit" );
- pKeyEdit->setGeometry( 20, 100, 80, 20 );
- connect( pKeyEdit, TQT_SIGNAL( returnPressed()),
- TQT_SLOT(keyEditReturnPressed()));
-
- pEqualsLabel = new TQLabel( this, "equalslabel" );
- pEqualsLabel->setGeometry( 105, 100, 20, 20 );
- pEqualsLabel->setText( "=" );
-
- pValueEdit = new TQLineEdit( this, "valueedit" );
- pValueEdit->setGeometry( 120, 100, 100, 20 );
- pValueEdit->setText( "---" );
-
- pWriteButton = new TQPushButton( this, "writebutton" );
- pWriteButton->setGeometry( 20,140, 80, 20 );
- pWriteButton->setText( "Write entry" );
- connect( pWriteButton, TQT_SIGNAL(clicked()), TQT_SLOT( writeButtonClicked() ) );
-
- // Labels for the info line
- pInfoLabel1 = new TQLabel( this, "infolabel1" );
- pInfoLabel1->setGeometry( 20, 200, 60, 20 );
- pInfoLabel1->setText( "Info:" );
-
- pInfoLabel2 = new TQLabel( this, "infolabel2" );
- pInfoLabel2->setGeometry( 100, 200, 300, 20 );
- pInfoLabel2->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
-
- // Quit button
- pQuitButton = new TQPushButton( this, "quitbutton" );
- pQuitButton->setText( "Quit" );
- pQuitButton->setGeometry( 340, 60, 60, 60 );
- connect( pQuitButton, TQT_SIGNAL(clicked()), tqApp, TQT_SLOT(quit()) );
-
- // create a default TDEConfig object in order to be able to start right away
- pConfig = new TDEConfig( TQString::null );
-}
-
-TDEConfigTestView::~TDEConfigTestView()
-{
- delete pConfig;
- delete pFile;
- delete pStream;
-}
-
-void TDEConfigTestView::appConfigEditReturnPressed()
-{
- // if there already was a config object, delete it and its associated data
- delete pConfig;
- pConfig = 0L;
- delete pFile;
- pFile = 0L;
- delete pStream;
- pStream = 0L;
-
- // create a new config object
- if( !pAppFileEdit->text().isEmpty() )
- pConfig = new TDEConfig( pAppFileEdit->text() );
-
- pInfoLabel2->setText( "New config object created." );
-}
-
-void TDEConfigTestView::groupEditReturnPressed()
-{
- pConfig->setGroup( pGroupEdit->text() );
- // according to the Qt doc, this is begging for trouble, but for a
- // test program this will do
- TQString aText;
- aText.sprintf( "Group set to %s", TQString( pConfig->group() ).isEmpty() ?
- TQString("<default>").ascii() : pConfig->group().ascii() );
- pInfoLabel2->setText( aText );
-}
-
-void TDEConfigTestView::keyEditReturnPressed()
-{
- TQString aValue = pConfig->readEntry( pKeyEdit->text() );
- // just checking aValue.isNull() would be easier here, but this is
- // to demonstrate the HasKey()-method. Besides, it is better data
- // encapsulation because we do not make any assumption about coding
- // non-values here.
- if( !pConfig->hasKey( pKeyEdit->text() ) )
- {
- pInfoLabel2->setText( "Key not found!" );
- pValueEdit->setText( "---" );
- }
- else
- {
- pInfoLabel2->setText( "Key found!" );
- pValueEdit->setText( aValue );
- }
-}
-
-void TDEConfigTestView::writeButtonClicked()
-{
- pConfig->writeEntry( pKeyEdit->text(), TQString( pValueEdit->text() ) );
- pInfoLabel2->setText( "Entry written" );
-
- kdDebug() << "Entry written: " << 27 << endl;
-}
-
-
-int main( int argc, char **argv )
-{
- TDEApplication a( argc, argv, "bla" );
-
- TDEConfigTestView *w = new TDEConfigTestView();
- a.setMainWidget( w );
- return w->exec();
-}
diff --git a/tdecore/tests/kconfigtestgui.h b/tdecore/tests/kconfigtestgui.h
deleted file mode 100644
index f5bbfd659..000000000
--- a/tdecore/tests/kconfigtestgui.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/* This file is part of the KDE libraries
- Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-#ifndef _KCONFIG_TEST_H
-#define _KCONFIG_TEST_H
-
-#include <kapplication.h>
-#include <tqdialog.h>
-#include <tqfile.h>
-#include <tqfileinfo.h>
-#include <kdebug.h>
-#include <ksimpleconfig.h>
-#include <tqtextstream.h>
-
-// Standard Qt widgets
-
-#include <tqlabel.h>
-#include <tqlineedit.h>
-#include <tqpushbutton.h>
-
-#include <kconfig.h>
-
-//
-// TDEConfigTestView contains lots of Qt widgets.
-//
-
-class TDEConfigTestView : public TQDialog
-{
- Q_OBJECT
-public:
- TDEConfigTestView( TQWidget *parent=0, const char *name=0 );
- ~TDEConfigTestView();
-
-private slots:
- void appConfigEditReturnPressed();
- void groupEditReturnPressed();
- void keyEditReturnPressed();
- void writeButtonClicked();
-
-private:
- TQLabel* pAppFileLabel;
- TQLineEdit* pAppFileEdit;
- TQLabel* pGroupLabel;
- TQLineEdit* pGroupEdit;
- TQLineEdit* pKeyEdit;
- TQLabel* pEqualsLabel;
- TQLineEdit* pValueEdit;
- TQPushButton* pWriteButton;
- TQLabel* pInfoLabel1, *pInfoLabel2;
- TQPushButton* pQuitButton;
-
- TDEConfig* pConfig;
- TQFile* pFile;
- TQTextStream* pStream;
-};
-
-#endif
diff --git a/tdecore/tests/ksimpleconfigtest.cpp b/tdecore/tests/ksimpleconfigtest.cpp
index f9fbffa65..85193f40b 100644
--- a/tdecore/tests/ksimpleconfigtest.cpp
+++ b/tdecore/tests/ksimpleconfigtest.cpp
@@ -20,7 +20,7 @@
int main( int argc, char **argv )
{
- TDEApplication a( argc, argv, "kconfigtest" );
+ TDEApplication a( argc, argv, "tdeconfigtest" );
KSimpleConfig aConfig( _PATH_TMP"/simpleconfig.cfg" );
diff --git a/tdecore/tests/kstddirstest.cpp b/tdecore/tests/kstddirstest.cpp
index fa7191cce..399282f14 100644
--- a/tdecore/tests/kstddirstest.cpp
+++ b/tdecore/tests/kstddirstest.cpp
@@ -2,7 +2,7 @@
#include <kdebug.h>
#include <kinstance.h>
#include <kstandarddirs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
int main(int argc, char **argv)
{
diff --git a/tdecore/tests/kurltest.cpp b/tdecore/tests/kurltest.cpp
index f1284d394..178aec6d5 100644
--- a/tdecore/tests/kurltest.cpp
+++ b/tdecore/tests/kurltest.cpp
@@ -125,8 +125,8 @@ int main(int argc, char *argv[])
baseURL = "http://www.foo.bar/top//test2/file2.html";
check( "KURL::url()", baseURL.url(), "http://www.foo.bar/top//test2/file2.html" );
- baseURL = "file:/usr/local/src/kde2/////tdelibs/kio";
- check( "KURL::url()", baseURL.url(), "file:///usr/local/src/kde2/////tdelibs/kio" );
+ baseURL = "file:/usr/local/src/kde2/////tdelibs/tdeio";
+ check( "KURL::url()", baseURL.url(), "file:///usr/local/src/kde2/////tdelibs/tdeio" );
baseURL = "http://www.foo.bar";
KURL rel_url2( baseURL, "mailto:bastian@kde.org" );
@@ -135,7 +135,7 @@ int main(int argc, char *argv[])
baseURL = "mailto:bastian@kde.org?subject=hello";
check( "KURL::url()", baseURL.url(), "mailto:bastian@kde.org?subject=hello" );
- baseURL = "file:/usr/local/src/kde2/tdelibs/kio/";
+ baseURL = "file:/usr/local/src/kde2/tdelibs/tdeio/";
KURL url2( baseURL, "../../////tdebase/konqueror" );
check( "KURL::url()", url2.url(), "file:///usr/local/src/kde2/////tdebase/konqueror" );
@@ -318,8 +318,8 @@ int main(int argc, char *argv[])
"http://www.google.com/foo%20%20%20%20%20%20 bar/");
KURL carsten;
- carsten.setPath("/home/gis/src/kde/tdelibs/kfile/.#kfiledetailview.cpp.1.18");
- check("KURL::path()", carsten.path(), "/home/gis/src/kde/tdelibs/kfile/.#kfiledetailview.cpp.1.18");
+ carsten.setPath("/home/gis/src/kde/tdelibs/tdefile/.#tdefiledetailview.cpp.1.18");
+ check("KURL::path()", carsten.path(), "/home/gis/src/kde/tdelibs/tdefile/.#tdefiledetailview.cpp.1.18");
KURL charles;
charles.setPath( "/home/charles/foo%20moo" );
diff --git a/tdecore/tests/tdeconfigtest.cpp b/tdecore/tests/tdeconfigtest.cpp
new file mode 100644
index 000000000..d9c89d6d4
--- /dev/null
+++ b/tdecore/tests/tdeconfigtest.cpp
@@ -0,0 +1,162 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tdeunittest/tester.h>
+#include <tdeunittest/module.h>
+
+#include <tdeconfig.h>
+
+class TDEConfigTest : public KUnitTest::Tester
+{
+public:
+ void allTests();
+private:
+ void writeConfigFile();
+ void revertEntries();
+};
+
+KUNITTEST_MODULE( tdeunittest_tdeconfig, "TDEConfigTest" )
+KUNITTEST_MODULE_REGISTER_TESTER( TDEConfigTest )
+
+// test data
+#define BOOLENTRY1 true
+#define BOOLENTRY2 false
+#define STRINGENTRY1 "hello"
+#define STRINGENTRY2 " hello"
+#define STRINGENTRY3 "hello "
+#define STRINGENTRY4 " hello "
+#define STRINGENTRY5 " "
+#define STRINGENTRY6 ""
+#define LOCAL8BITENTRY "Hello äöü"
+#define POINTENTRY TQPoint( 4351, 1235 )
+#define SIZEENTRY TQSize( 10, 20 )
+#define RECTENTRY TQRect( 10, 23, 5321, 13 )
+#define DATETIMEENTRY TQDateTime( TQDate( 2002, 06, 23 ), TQTime( 12, 55, 40 ) )
+#define STRINGLISTENTRY TQStringList( "Hello," )
+
+void TDEConfigTest::writeConfigFile()
+{
+ TDEConfig sc( "tdeconfigtest" );
+
+ sc.setGroup("AAA");
+ sc.writeEntry("stringEntry1", STRINGENTRY1, true, true);
+ sc.deleteEntry("stringEntry2", false, true);
+
+ sc.setGroup("Hello");
+ sc.writeEntry( "boolEntry1", BOOLENTRY1 );
+ sc.writeEntry( "boolEntry2", BOOLENTRY2 );
+
+ sc.writeEntry( "Test", TQString::fromLocal8Bit( LOCAL8BITENTRY ) );
+ sc.writeEntry( "Test2", "");
+ sc.writeEntry( "stringEntry1", STRINGENTRY1 );
+ sc.writeEntry( "stringEntry2", STRINGENTRY2 );
+ sc.writeEntry( "stringEntry3", STRINGENTRY3 );
+ sc.writeEntry( "stringEntry4", STRINGENTRY4 );
+ sc.writeEntry( "stringEntry5", STRINGENTRY5 );
+// sc.writeEntry( "stringEntry6", STRINGENTRY6 );
+ sc.writeEntry( "keywith=equalsign", STRINGENTRY1 );
+ sc.deleteEntry( "stringEntry5" );
+ sc.deleteEntry( "stringEntry6" );
+
+ sc.deleteGroup("deleteMe", true);
+
+ sc.setGroup("Bye");
+ sc.writeEntry( "rectEntry", RECTENTRY );
+ sc.writeEntry( "pointEntry", POINTENTRY );
+ sc.writeEntry( "sizeEntry", SIZEENTRY );
+ sc.writeEntry( "dateTimeEntry", DATETIMEENTRY );
+ sc.writeEntry( "stringListEntry", STRINGLISTENTRY );
+ sc.sync();
+}
+
+// ### TODO: call this, and test the state of things afterwards
+void TDEConfigTest::revertEntries()
+{
+ tqWarning("Reverting entries");
+ TDEConfig sc( "tdeconfigtest" );
+
+ sc.setGroup("Hello");
+ sc.revertToDefault( "boolEntry1");
+ sc.revertToDefault( "boolEntry2");
+
+ sc.revertToDefault( "Test" );
+ sc.revertToDefault( "Test2" );
+ sc.revertToDefault( "stringEntry1" );
+ sc.revertToDefault( "stringEntry2" );
+ sc.revertToDefault( "stringEntry3" );
+ sc.revertToDefault( "stringEntry4" );
+ sc.revertToDefault( "stringEntry5" );
+ sc.sync();
+}
+
+void TDEConfigTest::allTests()
+{
+ writeConfigFile();
+
+ TDEConfig sc2( "tdeconfigtest" );
+
+ TDEConfigGroup sc3( &sc2, "AAA");
+ bool bImmutable = sc3.entryIsImmutable("stringEntry1");
+
+ CHECK( bImmutable, false );
+ //tqWarning("sc3.entryIsImmutable() 1: %s", bImmutable ? "true" : "false");
+
+ sc2.setGroup("AAA");
+ CHECK( sc2.hasKey( "stringEntry1" ), true );
+ CHECK( sc2.readEntry( "stringEntry1" ), TQString( STRINGENTRY1 ) );
+ CHECK( sc2.entryIsImmutable("stringEntry1"), bImmutable );
+ CHECK( sc2.hasKey( "stringEntry2" ), false );
+ CHECK( sc2.readEntry( "stringEntry2", "bla" ), TQString( "bla" ) );
+
+ CHECK( sc2.hasDefault( "stringEntry1" ), false );
+
+ sc2.setGroup("Hello");
+ CHECK( sc2.readEntry( "Test" ), TQString::fromLocal8Bit( LOCAL8BITENTRY ) );
+ CHECK( sc2.readEntry("Test2", "Fietsbel").isEmpty(), true );
+ CHECK( sc2.readEntry( "stringEntry1" ), TQString( STRINGENTRY1 ) );
+ CHECK( sc2.readEntry( "stringEntry2" ), TQString( STRINGENTRY2 ) );
+ CHECK( sc2.readEntry( "stringEntry3" ), TQString( STRINGENTRY3 ) );
+ CHECK( sc2.readEntry( "stringEntry4" ), TQString( STRINGENTRY4 ) );
+ CHECK( sc2.hasKey( "stringEntry5" ), false);
+ CHECK( sc2.readEntry( "stringEntry5", "test" ), TQString( "test" ) );
+ CHECK( sc2.hasKey( "stringEntry6" ), false);
+ CHECK( sc2.readEntry( "stringEntry6", "foo" ), TQString( "foo" ) );
+ CHECK( sc2.readBoolEntry( "boolEntry1" ), BOOLENTRY1 );
+ CHECK( sc2.readBoolEntry( "boolEntry2" ), BOOLENTRY2 );
+
+#if 0
+ TQString s;
+ s = sc2.readEntry( "keywith=equalsign" );
+ fprintf(stderr, "comparing keywith=equalsign %s with %s -> ", STRINGENTRY1, s.latin1());
+ if (s == STRINGENTRY1)
+ fprintf(stderr, "OK\n");
+ else {
+ fprintf(stderr, "not OK\n");
+ exit(-1);
+ }
+#endif
+
+ sc2.setGroup("Bye");
+
+ CHECK( sc2.readPointEntry( "pointEntry" ), POINTENTRY );
+ CHECK( sc2.readSizeEntry( "sizeEntry" ), SIZEENTRY);
+ CHECK( sc2.readRectEntry( "rectEntry" ), RECTENTRY );
+ CHECK( sc2.readDateTimeEntry( "dateTimeEntry" ).toString(), DATETIMEENTRY.toString() );
+ CHECK( sc2.readListEntry( "stringListEntry").join( "," ), STRINGLISTENTRY.join( "," ) );
+}
diff --git a/tdecore/tests/tdeconfigtestgui.cpp b/tdecore/tests/tdeconfigtestgui.cpp
new file mode 100644
index 000000000..5ae85d26d
--- /dev/null
+++ b/tdecore/tests/tdeconfigtestgui.cpp
@@ -0,0 +1,200 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdeconfigtestgui.h"
+#include "tdeconfigtestgui.moc"
+
+//
+// configtest.cpp: libKDEcore example
+//
+// demonstrates use of TDEConfig class
+//
+// adapted from Qt widgets demo
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <kapplication.h>
+#include <tqdialog.h>
+#include <tqfile.h>
+#include <tqfileinfo.h>
+#include <tqdatetime.h>
+#include <kdebug.h>
+#include <ksimpleconfig.h>
+#include <config.h>
+
+// Standard Qt widgets
+
+#include <tqlabel.h>
+#include <tqlineedit.h>
+#include <tqpushbutton.h>
+
+// KDE includes
+#include <tdeconfig.h>
+
+#ifdef HAVE_PATHS_H
+#include <paths.h>
+#endif
+
+#ifndef _PATH_TMP
+#define _PATH_TMP "/tmp/"
+#endif
+
+//
+// Construct the TDEConfigTestView with buttons
+//
+
+TDEConfigTestView::TDEConfigTestView( TQWidget *parent, const char *name )
+ : TQDialog( parent, name ),
+ pConfig( 0L ),
+ pFile( 0L ),
+ pStream( 0L )
+{
+ // Set the window caption/title
+
+ setCaption( "TDEConfig test" );
+
+ // Label and edit for the app config file
+ pAppFileLabel = new TQLabel( this, "appconfiglabel" );
+ pAppFileLabel->setText( "Application config file:" );
+ pAppFileLabel->setGeometry( 20, 20, 200, 20 );
+
+ pAppFileEdit = new TQLineEdit( this, "appconfigedit" );
+ pAppFileEdit->setGeometry( 240, 20, 160, 20 );
+ connect( pAppFileEdit, TQT_SIGNAL(returnPressed()),
+ TQT_SLOT(appConfigEditReturnPressed()));
+
+ // Label and edit for the group
+ pGroupLabel = new TQLabel( this, "grouplabel" );
+ pGroupLabel->setText( "Group:" );
+ pGroupLabel->setGeometry( 20, 60, 80, 20 );
+
+ pGroupEdit = new TQLineEdit( this, "groupedit" );
+ pGroupEdit->setGeometry( 120, 60, 100, 20 );
+ connect( pGroupEdit, TQT_SIGNAL(returnPressed()),
+ TQT_SLOT(groupEditReturnPressed()));
+
+ // Edit and label for the key/value pair
+ pKeyEdit = new TQLineEdit( this, "keyedit" );
+ pKeyEdit->setGeometry( 20, 100, 80, 20 );
+ connect( pKeyEdit, TQT_SIGNAL( returnPressed()),
+ TQT_SLOT(keyEditReturnPressed()));
+
+ pEqualsLabel = new TQLabel( this, "equalslabel" );
+ pEqualsLabel->setGeometry( 105, 100, 20, 20 );
+ pEqualsLabel->setText( "=" );
+
+ pValueEdit = new TQLineEdit( this, "valueedit" );
+ pValueEdit->setGeometry( 120, 100, 100, 20 );
+ pValueEdit->setText( "---" );
+
+ pWriteButton = new TQPushButton( this, "writebutton" );
+ pWriteButton->setGeometry( 20,140, 80, 20 );
+ pWriteButton->setText( "Write entry" );
+ connect( pWriteButton, TQT_SIGNAL(clicked()), TQT_SLOT( writeButtonClicked() ) );
+
+ // Labels for the info line
+ pInfoLabel1 = new TQLabel( this, "infolabel1" );
+ pInfoLabel1->setGeometry( 20, 200, 60, 20 );
+ pInfoLabel1->setText( "Info:" );
+
+ pInfoLabel2 = new TQLabel( this, "infolabel2" );
+ pInfoLabel2->setGeometry( 100, 200, 300, 20 );
+ pInfoLabel2->setFrameStyle( TQFrame::Panel | TQFrame::Sunken );
+
+ // Quit button
+ pQuitButton = new TQPushButton( this, "quitbutton" );
+ pQuitButton->setText( "Quit" );
+ pQuitButton->setGeometry( 340, 60, 60, 60 );
+ connect( pQuitButton, TQT_SIGNAL(clicked()), tqApp, TQT_SLOT(quit()) );
+
+ // create a default TDEConfig object in order to be able to start right away
+ pConfig = new TDEConfig( TQString::null );
+}
+
+TDEConfigTestView::~TDEConfigTestView()
+{
+ delete pConfig;
+ delete pFile;
+ delete pStream;
+}
+
+void TDEConfigTestView::appConfigEditReturnPressed()
+{
+ // if there already was a config object, delete it and its associated data
+ delete pConfig;
+ pConfig = 0L;
+ delete pFile;
+ pFile = 0L;
+ delete pStream;
+ pStream = 0L;
+
+ // create a new config object
+ if( !pAppFileEdit->text().isEmpty() )
+ pConfig = new TDEConfig( pAppFileEdit->text() );
+
+ pInfoLabel2->setText( "New config object created." );
+}
+
+void TDEConfigTestView::groupEditReturnPressed()
+{
+ pConfig->setGroup( pGroupEdit->text() );
+ // according to the Qt doc, this is begging for trouble, but for a
+ // test program this will do
+ TQString aText;
+ aText.sprintf( "Group set to %s", TQString( pConfig->group() ).isEmpty() ?
+ TQString("<default>").ascii() : pConfig->group().ascii() );
+ pInfoLabel2->setText( aText );
+}
+
+void TDEConfigTestView::keyEditReturnPressed()
+{
+ TQString aValue = pConfig->readEntry( pKeyEdit->text() );
+ // just checking aValue.isNull() would be easier here, but this is
+ // to demonstrate the HasKey()-method. Besides, it is better data
+ // encapsulation because we do not make any assumption about coding
+ // non-values here.
+ if( !pConfig->hasKey( pKeyEdit->text() ) )
+ {
+ pInfoLabel2->setText( "Key not found!" );
+ pValueEdit->setText( "---" );
+ }
+ else
+ {
+ pInfoLabel2->setText( "Key found!" );
+ pValueEdit->setText( aValue );
+ }
+}
+
+void TDEConfigTestView::writeButtonClicked()
+{
+ pConfig->writeEntry( pKeyEdit->text(), TQString( pValueEdit->text() ) );
+ pInfoLabel2->setText( "Entry written" );
+
+ kdDebug() << "Entry written: " << 27 << endl;
+}
+
+
+int main( int argc, char **argv )
+{
+ TDEApplication a( argc, argv, "bla" );
+
+ TDEConfigTestView *w = new TDEConfigTestView();
+ a.setMainWidget( w );
+ return w->exec();
+}
diff --git a/tdecore/tests/tdeconfigtestgui.h b/tdecore/tests/tdeconfigtestgui.h
new file mode 100644
index 000000000..347a9c81d
--- /dev/null
+++ b/tdecore/tests/tdeconfigtestgui.h
@@ -0,0 +1,72 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef _KCONFIG_TEST_H
+#define _KCONFIG_TEST_H
+
+#include <kapplication.h>
+#include <tqdialog.h>
+#include <tqfile.h>
+#include <tqfileinfo.h>
+#include <kdebug.h>
+#include <ksimpleconfig.h>
+#include <tqtextstream.h>
+
+// Standard Qt widgets
+
+#include <tqlabel.h>
+#include <tqlineedit.h>
+#include <tqpushbutton.h>
+
+#include <tdeconfig.h>
+
+//
+// TDEConfigTestView contains lots of Qt widgets.
+//
+
+class TDEConfigTestView : public TQDialog
+{
+ Q_OBJECT
+public:
+ TDEConfigTestView( TQWidget *parent=0, const char *name=0 );
+ ~TDEConfigTestView();
+
+private slots:
+ void appConfigEditReturnPressed();
+ void groupEditReturnPressed();
+ void keyEditReturnPressed();
+ void writeButtonClicked();
+
+private:
+ TQLabel* pAppFileLabel;
+ TQLineEdit* pAppFileEdit;
+ TQLabel* pGroupLabel;
+ TQLineEdit* pGroupEdit;
+ TQLineEdit* pKeyEdit;
+ TQLabel* pEqualsLabel;
+ TQLineEdit* pValueEdit;
+ TQPushButton* pWriteButton;
+ TQLabel* pInfoLabel1, *pInfoLabel2;
+ TQPushButton* pQuitButton;
+
+ TDEConfig* pConfig;
+ TQFile* pFile;
+ TQTextStream* pStream;
+};
+
+#endif
diff --git a/kfile-plugins/CMakeLists.txt b/tdefile-plugins/CMakeLists.txt
index 61e9dd6a3..61e9dd6a3 100644
--- a/kfile-plugins/CMakeLists.txt
+++ b/tdefile-plugins/CMakeLists.txt
diff --git a/tdefile-plugins/elf/CMakeLists.txt b/tdefile-plugins/elf/CMakeLists.txt
new file mode 100644
index 000000000..04bec18fe
--- /dev/null
+++ b/tdefile-plugins/elf/CMakeLists.txt
@@ -0,0 +1,42 @@
+#################################################
+#
+# (C) 2012 Timothy Pearson
+# kb9vqf (AT) pearsoncomputing.net
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${TDE_INCLUDE_DIR}
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_BINARY_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${LIBR_INCLUDEDIR}
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+ ${LIBR_LIBDIR}
+)
+
+#### other data #################################
+
+install( FILES tdefile_elf.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+#### tdefile_elf (module) #########################
+
+tde_add_kpart( tdefile_elf AUTOMOC
+ SOURCES tdefile_elf.cpp
+ EMBED tdelficon-static
+ LINK tdeio-shared ${LIBR_LIBRARIES}
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/tdefile-plugins/elf/tdefile_elf.cpp b/tdefile-plugins/elf/tdefile_elf.cpp
new file mode 100644
index 000000000..cad269713
--- /dev/null
+++ b/tdefile-plugins/elf/tdefile_elf.cpp
@@ -0,0 +1,133 @@
+/* This file is part of the KDE project
+ * Copyright (C) 2012 Timothy Pearson <kb9vqf@pearsoncomputing.net>
+ *
+ * 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 version 2.
+ *
+ * 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; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include <config.h>
+#include "tdefile_elf.h"
+
+#include <kprocess.h>
+#include <klocale.h>
+#include <kgenericfactory.h>
+#include <kstringvalidator.h>
+#include <kdebug.h>
+
+#include <tqdict.h>
+#include <tqvalidator.h>
+#include <tqcstring.h>
+#include <tqfile.h>
+#include <tqdatetime.h>
+
+#include "tdelficon.h"
+
+#if !defined(__osf__)
+#include <inttypes.h>
+#else
+typedef unsigned long uint32_t;
+typedef unsigned short uint16_t;
+#endif
+
+typedef KGenericFactory<KElfPlugin> ElfFactory;
+
+K_EXPORT_COMPONENT_FACTORY(tdefile_elf, ElfFactory( "tdefile_elf" ))
+
+KElfPlugin::KElfPlugin(TQObject *parent, const char *name,
+ const TQStringList &args)
+
+ : KFilePlugin(parent, name, args)
+{
+ KFileMimeTypeInfo* info = addMimeTypeInfo( "application/x-executable" );
+
+ KFileMimeTypeInfo::GroupInfo* group = 0L;
+ KFileMimeTypeInfo::GroupInfo* group2 = 0L;
+
+ group = addGroupInfo(info, "Technical", i18n("Embedded Metadata"));
+ group2 = addGroupInfo(info, "Icon", i18n("Embedded Icon(s)"));
+
+ KFileMimeTypeInfo::ItemInfo* item;
+
+ item = addItemInfo(group, "Name", i18n("Internal Name"), TQVariant::String);
+ item = addItemInfo(group, "Description", i18n("Description"), TQVariant::String);
+ item = addItemInfo(group, "License", i18n("License"), TQVariant::String);
+ item = addItemInfo(group, "Copyright", i18n("Copyright"), TQVariant::String);
+ item = addItemInfo(group, "Authors", i18n("Author(s)"), TQVariant::String);
+ item = addItemInfo(group, "Product", i18n("Product"), TQVariant::String);
+ item = addItemInfo(group, "Organization", i18n("Organization"), TQVariant::String);
+ item = addItemInfo(group, "Version", i18n("Version"), TQVariant::String);
+ item = addItemInfo(group, "DateTime", i18n("Compilation Date/Time"), TQVariant::String);
+ item = addItemInfo(group, "SystemIcon", i18n("Requested Icon"), TQVariant::String);
+ item = addItemInfo(group, "Notes", i18n("Comments"), TQVariant::String);
+
+ item = addItemInfo(group2, "EmbeddedIcon", i18n("Icon Name(s)"), TQVariant::String);
+}
+
+
+bool KElfPlugin::readInfo( KFileMetaInfo& info, uint what)
+{
+ libr_icon *icon = NULL;
+ libr_file *handle = NULL;
+ libr_access_t access = LIBR_READ;
+
+ if((handle = libr_open(const_cast<char*>(info.path().ascii()), access)) == NULL)
+ {
+ kdWarning() << "failed to open file" << info.path() << endl;
+ }
+
+ KFileMetaInfoGroup group = appendGroup(info, "Technical");
+ KFileMetaInfoGroup group2 = appendGroup(info, "Icon");
+
+ appendItem(group, "Name", elf_get_resource(handle, ".metadata_name"));
+ appendItem(group, "Description", elf_get_resource(handle, ".metadata_description"));
+ appendItem(group, "License", elf_get_resource(handle, ".metadata_license"));
+ appendItem(group, "Copyright", elf_get_resource(handle, ".metadata_copyright"));
+ appendItem(group, "Authors", elf_get_resource(handle, ".metadata_authors"));
+ appendItem(group, "Product", elf_get_resource(handle, ".metadata_product"));
+ appendItem(group, "Organization", elf_get_resource(handle, ".metadata_organization"));
+ appendItem(group, "Version", elf_get_resource(handle, ".metadata_version"));
+ appendItem(group, "DateTime", elf_get_resource(handle, ".metadata_datetime"));
+ appendItem(group, "SystemIcon", elf_get_resource(handle, ".metadata_sysicon"));
+ appendItem(group, "Notes", elf_get_resource(handle, ".metadata_notes"));
+
+ TQString iconListing;
+
+ iconentry *entry = NULL;
+ iconlist icons;
+ if(!get_iconlist(handle, &icons))
+ {
+ // Failed to obtain a list of ELF icons
+ }
+ else {
+ while((entry = get_nexticon(&icons, entry)) != NULL)
+ {
+ if (iconListing.isEmpty()) {
+ iconListing = entry->name;
+ }
+ else {
+ iconListing = iconListing.append("\n").append(entry->name);
+ }
+ break;
+ }
+ }
+
+ appendItem(group2, "EmbeddedIcon", iconListing);
+
+ libr_close(handle);
+
+ return true;
+}
+
+#include "tdefile_elf.moc"
diff --git a/tdefile-plugins/elf/tdefile_elf.desktop b/tdefile-plugins/elf/tdefile_elf.desktop
new file mode 100644
index 000000000..d51d3c312
--- /dev/null
+++ b/tdefile-plugins/elf/tdefile_elf.desktop
@@ -0,0 +1,66 @@
+[Desktop Entry]
+Type=Service
+Name=ELF Info
+Name[af]=ELF Inligting
+Name[ar]=معلومات ELF
+Name[br]=Titouroù ELF
+Name[ca]=Informació de ELF
+Name[cs]=ELF info
+Name[cy]=Gwybodaeth ELF
+Name[da]=ELF-info
+Name[de]=ELF-Info
+Name[el]=ΠληÏοφοÏίες ELF
+Name[eo]=ELF-informo
+Name[es]=Info ELF
+Name[et]=ELF info
+Name[fa]=اطلاعات ELF
+Name[fi]=ELF-tiedot
+Name[fr]=Informations ELF
+Name[ga]=Eolas faoi ELF
+Name[gl]=Inf. ELF
+Name[he]=מידע ELF
+Name[hi]=ELF जानकारी
+Name[hr]=ELF informacije
+Name[hu]=ELF-jellemzők
+Name[is]=ELF upplýsingar
+Name[it]=Informazioni ELF
+Name[ja]=ELF 情報
+Name[kk]=ELF мәліметі
+Name[km]=áž–áŸážáŸŒáž˜áž¶áž“ ELF
+Name[lt]=ELF informacija
+Name[ms]=Maklumat ELF
+Name[nds]=ELF-Info
+Name[ne]=ELF सूचना
+Name[nl]=ELF-info
+Name[nn]=ELF-info
+Name[nso]=Tshedimoso ya ELF
+Name[pa]=ELF ਜਾਣਕਾਰੀ
+Name[pl]=Informacja o pliku ELF
+Name[pt]=Informação do ELF
+Name[pt_BR]=Informação sobre ELF
+Name[ro]=Informaţii ELF
+Name[ru]=Ð˜Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ ELF
+Name[se]=ELF-dieđut
+Name[sl]=Podatki o ELF
+Name[sr]=ELF информације
+Name[sr@Latn]=ELF informacije
+Name[sv]=ELF-information
+Name[ta]=ELF தகவலà¯
+Name[tg]=Иттилоот оиди ELF
+Name[th]=ข้อมูลà¹à¸Ÿà¹‰à¸¡ ELF
+Name[tr]=ELF Bilgisi
+Name[uk]=Ð†Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ñ–Ñ Ð¿Ð¾ ELF
+Name[uz]=ELF haqida maʼlumot
+Name[uz@cyrillic]=ELF ҳақида маълумот
+Name[ven]=Mafhungo ELF
+Name[wa]=Informåcion sol imådje ELF
+Name[xh]=Ulwazi lwe ELF
+Name[zh_CN]=ELF ä¿¡æ¯
+Name[zh_HK]=ELF 資訊
+Name[zh_TW]=ELF 資訊
+Name[zu]=Ulwazi lwe-ELF
+ServiceTypes=KFilePlugin
+X-TDE-Library=tdefile_elf
+MimeType=application/x-executable
+PreferredItems=Name,Description,License,Copyright,Authors,Product,Organization,Version,DateTime,Notes"
+SupportsThumbnail=false \ No newline at end of file
diff --git a/tdefile-plugins/elf/tdefile_elf.h b/tdefile-plugins/elf/tdefile_elf.h
new file mode 100644
index 000000000..f53d36e0a
--- /dev/null
+++ b/tdefile-plugins/elf/tdefile_elf.h
@@ -0,0 +1,50 @@
+/* This file is part of the KDE project
+ * Copyright (C) 2002 Shane Wright <me@shanewright.co.uk>
+ *
+ * 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 version 2.
+ *
+ * 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; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef __KFILE_BMP_H__
+#define __KFILE_BMP_H__
+
+#include <tdefilemetainfo.h>
+
+// Elven things
+extern "C" {
+ #include <libr.h>
+ #include <libr-icons.h>
+}
+
+#include <string.h>
+
+#include <sys/stat.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+class TQStringList;
+
+class KElfPlugin: public KFilePlugin
+{
+ Q_OBJECT
+
+
+public:
+ KElfPlugin( TQObject *parent, const char *name, const TQStringList& args );
+
+ virtual bool readInfo( KFileMetaInfo& info, uint what);
+};
+
+#endif
diff --git a/tdehtml/CMakeLists.txt b/tdehtml/CMakeLists.txt
index bab7d78e2..de151a6e3 100644
--- a/tdehtml/CMakeLists.txt
+++ b/tdehtml/CMakeLists.txt
@@ -27,7 +27,7 @@ include_directories(
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}/kjs
- ${CMAKE_BINARY_DIR}/kio/kssl
+ ${CMAKE_BINARY_DIR}/tdeio/kssl
${CMAKE_BINARY_DIR}/tdecore
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}
@@ -35,10 +35,10 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdefx
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
- ${CMAKE_SOURCE_DIR}/kio/kssl
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
+ ${CMAKE_SOURCE_DIR}/tdeio/kssl
${CMAKE_SOURCE_DIR}/tdeutils
${CMAKE_SOURCE_DIR}/tdewallet/client
${CMAKE_SOURCE_DIR}/tdeprint
diff --git a/tdehtml/Makefile.am b/tdehtml/Makefile.am
index 3c9cb05c5..924b3db27 100644
--- a/tdehtml/Makefile.am
+++ b/tdehtml/Makefile.am
@@ -83,7 +83,7 @@ INCLUDES = -I$(top_srcdir)/kjs -I$(top_builddir)/kjs -I$(top_srcdir)/kimgio \
-I$(srcdir)/java -I$(top_srcdir)/dcop -I$(srcdir)/misc \
-I$(srcdir)/dom -I$(srcdir)/xml -I$(srcdir)/html -I$(srcdir)/css \
-I$(top_srcdir)/libltdl \
- -I$(top_srcdir)/kio/kssl -I$(top_builddir)/kio/kssl \
+ -I$(top_srcdir)/tdeio/kssl -I$(top_builddir)/tdeio/kssl \
-I$(top_srcdir)/tdeprint \
-I$(top_srcdir)/interfaces \
-I$(top_srcdir)/interfaces/kregexpeditor \
diff --git a/tdehtml/css/CMakeLists.txt b/tdehtml/css/CMakeLists.txt
index 4d0b52df1..37a5fccf3 100644
--- a/tdehtml/css/CMakeLists.txt
+++ b/tdehtml/css/CMakeLists.txt
@@ -19,8 +19,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/tdewallet/client
${CMAKE_SOURCE_DIR}/tdeutils
)
diff --git a/tdehtml/css/Makefile.am b/tdehtml/css/Makefile.am
index 6c43675ed..fadf66961 100644
--- a/tdehtml/css/Makefile.am
+++ b/tdehtml/css/Makefile.am
@@ -36,7 +36,7 @@ noinst_HEADERS = \
cssstyleselector.h csshelper.h parser.h \
css_renderstyledeclarationimpl.h
-INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/kio -I$(top_srcdir)/dcop \
+INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/tdeio -I$(top_srcdir)/dcop \
-I$(top_srcdir)/tdehtml -I$(top_srcdir)/libltdl -I$(top_srcdir) \
-I$(top_srcdir)/tdewallet/client -I$(top_srcdir)/tdeutils \
$(all_includes)
diff --git a/tdehtml/css/cssstyleselector.cpp b/tdehtml/css/cssstyleselector.cpp
index f2c5703c1..04b66e40a 100644
--- a/tdehtml/css/cssstyleselector.cpp
+++ b/tdehtml/css/cssstyleselector.cpp
@@ -58,7 +58,7 @@ using namespace DOM;
#include <kstandarddirs.h>
#include <kcharsets.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqfile.h>
#include <tqvaluelist.h>
#include <tqstring.h>
diff --git a/tdehtml/dom/CMakeLists.txt b/tdehtml/dom/CMakeLists.txt
index dd637f7bd..e781a62a8 100644
--- a/tdehtml/dom/CMakeLists.txt
+++ b/tdehtml/dom/CMakeLists.txt
@@ -18,7 +18,7 @@ include_directories(
${CMAKE_BINARY_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdehtml
${CMAKE_SOURCE_DIR}/tdecore
- ${CMAKE_SOURCE_DIR}/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
)
diff --git a/tdehtml/dom/Makefile.am b/tdehtml/dom/Makefile.am
index 6a33de62d..0b9f587f1 100644
--- a/tdehtml/dom/Makefile.am
+++ b/tdehtml/dom/Makefile.am
@@ -46,7 +46,7 @@ myinclude_HEADERS = \
dom2_views.h
# css_extensions.h
-INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/kio -I$(top_srcdir)/dcop \
+INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/tdeio -I$(top_srcdir)/dcop \
-I$(top_srcdir)/tdehtml -I$(top_srcdir) $(all_includes)
SRCDOC_DEST=$(kde_htmldir)/en/tdelibs/tdehtml
diff --git a/tdehtml/ecma/CMakeLists.txt b/tdehtml/ecma/CMakeLists.txt
index eddd99f1e..2d7366e28 100644
--- a/tdehtml/ecma/CMakeLists.txt
+++ b/tdehtml/ecma/CMakeLists.txt
@@ -21,9 +21,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdefx
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/bookmarks
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/bookmarks
${CMAKE_SOURCE_DIR}/kjs
${CMAKE_SOURCE_DIR}/tdewallet/client
${CMAKE_SOURCE_DIR}/tdeutils
diff --git a/tdehtml/ecma/Makefile.am b/tdehtml/ecma/Makefile.am
index d69ff807b..ee3334668 100644
--- a/tdehtml/ecma/Makefile.am
+++ b/tdehtml/ecma/Makefile.am
@@ -16,7 +16,7 @@
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
-INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/kio -I$(top_srcdir)/kio/bookmarks -I$(top_srcdir)/tdehtml -I$(top_srcdir)/tdehtml/java -I$(top_srcdir)/tdewallet/client -I$(top_srcdir)/tdeutils -I$(top_builddir)/kjs $(all_includes)
+INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/tdeio -I$(top_srcdir)/tdeio/bookmarks -I$(top_srcdir)/tdehtml -I$(top_srcdir)/tdehtml/java -I$(top_srcdir)/tdewallet/client -I$(top_srcdir)/tdeutils -I$(top_builddir)/kjs $(all_includes)
KDE_CXXFLAGS = $(USE_EXCEPTIONS)
diff --git a/tdehtml/ecma/kjs_debugwin.cpp b/tdehtml/ecma/kjs_debugwin.cpp
index 4830c1108..47921fb2a 100644
--- a/tdehtml/ecma/kjs_debugwin.cpp
+++ b/tdehtml/ecma/kjs_debugwin.cpp
@@ -53,8 +53,8 @@
#include <kactioncollection.h>
#include <kglobalsettings.h>
#include <kshortcut.h>
-#include <kconfig.h>
-#include <kconfigbase.h>
+#include <tdeconfig.h>
+#include <tdeconfigbase.h>
#include <kapplication.h>
#include <dcop/dcopclient.h>
#include <kstringhandler.h>
diff --git a/tdehtml/ecma/kjs_navigator.cpp b/tdehtml/ecma/kjs_navigator.cpp
index 222ef7902..22d5f9cb7 100644
--- a/tdehtml/ecma/kjs_navigator.cpp
+++ b/tdehtml/ecma/kjs_navigator.cpp
@@ -24,13 +24,13 @@
#include <klocale.h>
#include <kstandarddirs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
-#include <kio/kprotocolmanager.h>
-#include <kio/kmimetype.h>
-#include <kio/kservice.h>
-#include <kio/ktrader.h>
+#include <tdeio/kprotocolmanager.h>
+#include <tdeio/kmimetype.h>
+#include <tdeio/kservice.h>
+#include <tdeio/ktrader.h>
#include "kjs_navigator.h"
#include "kjs/lookup.h"
#include "kjs_binding.h"
diff --git a/tdehtml/ecma/xmlhttprequest.cpp b/tdehtml/ecma/xmlhttprequest.cpp
index f3aec5492..bfaa91231 100644
--- a/tdehtml/ecma/xmlhttprequest.cpp
+++ b/tdehtml/ecma/xmlhttprequest.cpp
@@ -33,15 +33,15 @@
#include "tdehtml_part.h"
#include "tdehtmlview.h"
-#include <kio/scheduler.h>
-#include <kio/job.h>
+#include <tdeio/scheduler.h>
+#include <tdeio/job.h>
#include <tqobject.h>
#include <kdebug.h>
#ifdef APPLE_CHANGES
#include "KWQLoader.h"
#else
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
using TDEIO::NetAccess;
#endif
diff --git a/tdehtml/ecma/xmlhttprequest.h b/tdehtml/ecma/xmlhttprequest.h
index 2dc89e227..95a7c9cc2 100644
--- a/tdehtml/ecma/xmlhttprequest.h
+++ b/tdehtml/ecma/xmlhttprequest.h
@@ -24,7 +24,7 @@
#include "ecma/kjs_binding.h"
#include "ecma/kjs_dom.h"
#include "misc/decoder.h"
-#include "kio/jobclasses.h"
+#include "tdeio/jobclasses.h"
namespace KJS {
diff --git a/tdehtml/ecma/xmlserializer.h b/tdehtml/ecma/xmlserializer.h
index 629d09afe..a86df3ed4 100644
--- a/tdehtml/ecma/xmlserializer.h
+++ b/tdehtml/ecma/xmlserializer.h
@@ -24,7 +24,7 @@
#include "ecma/kjs_binding.h"
#include "ecma/kjs_dom.h"
#include "misc/decoder.h"
-#include "kio/jobclasses.h"
+#include "tdeio/jobclasses.h"
namespace KJS {
diff --git a/tdehtml/html/CMakeLists.txt b/tdehtml/html/CMakeLists.txt
index a7a3bf466..a108b11f6 100644
--- a/tdehtml/html/CMakeLists.txt
+++ b/tdehtml/html/CMakeLists.txt
@@ -19,10 +19,10 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
- ${CMAKE_SOURCE_DIR}/kio/kssl
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
+ ${CMAKE_SOURCE_DIR}/tdeio/kssl
${CMAKE_SOURCE_DIR}/tdeutils
${CMAKE_SOURCE_DIR}/tdewallet/client
)
diff --git a/tdehtml/html/Makefile.am b/tdehtml/html/Makefile.am
index 0a3286243..ed6ca0114 100644
--- a/tdehtml/html/Makefile.am
+++ b/tdehtml/html/Makefile.am
@@ -40,7 +40,7 @@ noinst_HEADERS = \
html_formimpl.h html_objectimpl.h
INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/dcop \
- -I$(top_srcdir)/kio/kssl \
+ -I$(top_srcdir)/tdeio/kssl \
-I$(top_srcdir)/kjs -I$(top_srcdir)/tdehtml -I$(top_srcdir) \
-I$(top_srcdir)/tdewallet/client -I$(top_srcdir)/tdeutils \
$(all_includes)
diff --git a/tdehtml/html/html_formimpl.cpp b/tdehtml/html/html_formimpl.cpp
index f8c566511..7e2776ad5 100644
--- a/tdehtml/html/html_formimpl.cpp
+++ b/tdehtml/html/html_formimpl.cpp
@@ -57,7 +57,7 @@
#include <tdewallet.h>
#endif
#include <netaccess.h>
-#include <kfileitem.h>
+#include <tdefileitem.h>
#include <tqfile.h>
#include <tqdir.h>
#include <tqtextcodec.h>
diff --git a/tdehtml/java/CMakeLists.txt b/tdehtml/java/CMakeLists.txt
index 994763c09..e1958d320 100644
--- a/tdehtml/java/CMakeLists.txt
+++ b/tdehtml/java/CMakeLists.txt
@@ -16,14 +16,14 @@ include_directories(
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}/tdecore
- ${CMAKE_BINARY_DIR}/kio/kssl
+ ${CMAKE_BINARY_DIR}/tdeio/kssl
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tdehtml
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kssl
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/kssl
)
link_directories(
diff --git a/tdehtml/java/Makefile.am b/tdehtml/java/Makefile.am
index a5e46a0d5..00eeca230 100644
--- a/tdehtml/java/Makefile.am
+++ b/tdehtml/java/Makefile.am
@@ -15,7 +15,7 @@ libkjava_la_LDFLAGS = $(KDE_MT_LDFLAGS) -no-undefined
libkjava_la_LIBADD = $(LIB_KPARTS)
INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/tdehtml \
- -I$(top_srcdir)/kio/kssl -I$(top_builddir)/kio/kssl \
+ -I$(top_srcdir)/tdeio/kssl -I$(top_builddir)/tdeio/kssl \
$(all_includes)
kjavadata_DATA = kjava.jar kjava.policy pluginsinfo
diff --git a/tdehtml/java/kjavaappletserver.cpp b/tdehtml/java/kjavaappletserver.cpp
index b125bcc1a..7ad046b9a 100644
--- a/tdehtml/java/kjavaappletserver.cpp
+++ b/tdehtml/java/kjavaappletserver.cpp
@@ -26,14 +26,14 @@
#include "kjavadownloader.h"
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
#include <tdeparts/browserextension.h>
#include <kapplication.h>
#include <kstandarddirs.h>
-#include <kio/job.h>
-#include <kio/kprotocolmanager.h>
+#include <tdeio/job.h>
+#include <tdeio/kprotocolmanager.h>
#include <ksslcertificate.h>
#include <ksslcertchain.h>
#include <kssl.h>
diff --git a/tdehtml/java/kjavaappletviewer.cpp b/tdehtml/java/kjavaappletviewer.cpp
index fce5195ff..194a6324a 100644
--- a/tdehtml/java/kjavaappletviewer.cpp
+++ b/tdehtml/java/kjavaappletviewer.cpp
@@ -37,8 +37,8 @@
#include <kiconloader.h>
#include <kapplication.h>
#include <kdebug.h>
-#include <kconfig.h>
-#include <kio/authinfo.h>
+#include <tdeconfig.h>
+#include <tdeio/authinfo.h>
#include <dcopclient.h>
#include "kjavaappletwidget.h"
diff --git a/tdehtml/java/kjavadownloader.cpp b/tdehtml/java/kjavadownloader.cpp
index a0a8abdd2..5b1c55324 100644
--- a/tdehtml/java/kjavadownloader.cpp
+++ b/tdehtml/java/kjavadownloader.cpp
@@ -23,8 +23,8 @@
#include "kjavaappletserver.h"
#include <kurl.h>
-#include <kio/job.h>
-#include <kio/jobclasses.h>
+#include <tdeio/job.h>
+#include <tdeio/jobclasses.h>
#include <kdebug.h>
#include <tqfile.h>
diff --git a/tdehtml/java/kjavaprocess.cpp b/tdehtml/java/kjavaprocess.cpp
index dbe80305e..1ff68dd74 100644
--- a/tdehtml/java/kjavaprocess.cpp
+++ b/tdehtml/java/kjavaprocess.cpp
@@ -22,7 +22,7 @@
#include "kjavaprocess.h"
#include <kdebug.h>
-#include <kio/kprotocolmanager.h>
+#include <tdeio/kprotocolmanager.h>
#include <tqtextstream.h>
#include <tqmap.h>
diff --git a/tdehtml/misc/CMakeLists.txt b/tdehtml/misc/CMakeLists.txt
index da1f0dfd3..0babd6567 100644
--- a/tdehtml/misc/CMakeLists.txt
+++ b/tdehtml/misc/CMakeLists.txt
@@ -19,10 +19,10 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/tdeutils
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
diff --git a/tdehtml/misc/Makefile.am b/tdehtml/misc/Makefile.am
index 670fd5a1f..a26247035 100644
--- a/tdehtml/misc/Makefile.am
+++ b/tdehtml/misc/Makefile.am
@@ -31,7 +31,7 @@ noinst_HEADERS = \
decoder.h tdehtmllayout.h loader_jpeg.h loader.h guess_ja.h\
stringit.h htmlhashes.h helper.h shared.h arena.h knsplugininstaller.h
-INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/dcop -I$(top_srcdir)/kio -I$(top_srcdir)/libltdl \
+INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/dcop -I$(top_srcdir)/tdeio -I$(top_srcdir)/libltdl \
-I$(top_srcdir)/tdehtml -I$(top_srcdir)/tdeutils $(all_includes)
SRCDOC_DEST=$(kde_htmldir)/en/tdelibs/tdehtml
diff --git a/tdehtml/misc/helper.cpp b/tdehtml/misc/helper.cpp
index f759a9957..047a278fa 100644
--- a/tdehtml/misc/helper.cpp
+++ b/tdehtml/misc/helper.cpp
@@ -30,7 +30,7 @@
#include <tqptrlist.h>
#include <kstaticdeleter.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqtooltip.h>
using namespace DOM;
diff --git a/tdehtml/misc/loader.cpp b/tdehtml/misc/loader.cpp
index 60a75f856..5cd18f29b 100644
--- a/tdehtml/misc/loader.cpp
+++ b/tdehtml/misc/loader.cpp
@@ -57,8 +57,8 @@
#include <tqwidget.h>
#include <kapplication.h>
-#include <kio/job.h>
-#include <kio/jobclasses.h>
+#include <tdeio/job.h>
+#include <tdeio/jobclasses.h>
#include <kglobal.h>
#include <kimageio.h>
#include <kcharsets.h>
@@ -70,7 +70,7 @@
#ifdef IMAGE_TITLES
#include <tqfile.h>
-#include <kfilemetainfo.h>
+#include <tdefilemetainfo.h>
#include <ktempfile.h>
#endif
diff --git a/tdehtml/misc/loader.h b/tdehtml/misc/loader.h
index 97e637120..fa00b4ffb 100644
--- a/tdehtml/misc/loader.h
+++ b/tdehtml/misc/loader.h
@@ -49,7 +49,7 @@
#include <tqtimer.h>
#include <kurl.h>
-#include <kio/global.h>
+#include <tdeio/global.h>
#include <tdehtml_settings.h>
#include <dom/dom_string.h>
diff --git a/tdehtml/rendering/CMakeLists.txt b/tdehtml/rendering/CMakeLists.txt
index 757e9a72a..b8346501f 100644
--- a/tdehtml/rendering/CMakeLists.txt
+++ b/tdehtml/rendering/CMakeLists.txt
@@ -19,9 +19,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdehtml
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
${CMAKE_SOURCE_DIR}/tdeutils
)
diff --git a/tdehtml/rendering/Makefile.am b/tdehtml/rendering/Makefile.am
index 605788764..16d30da53 100644
--- a/tdehtml/rendering/Makefile.am
+++ b/tdehtml/rendering/Makefile.am
@@ -41,8 +41,8 @@ noinst_HEADERS = \
render_br.h render_applet.h font.h table_layout.h render_line.h \
render_generated.h enumerate.h
-INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/kio -I$(top_srcdir)/dcop \
- -I$(top_srcdir)/kfile -I$(top_srcdir)/tdehtml -I$(top_srcdir)/tdeutils -I$(top_srcdir) $(all_includes)
+INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/tdeio -I$(top_srcdir)/dcop \
+ -I$(top_srcdir)/tdefile -I$(top_srcdir)/tdehtml -I$(top_srcdir)/tdeutils -I$(top_srcdir) $(all_includes)
SRCDOC_DEST=$(kde_htmldir)/en/tdelibs/tdehtml
diff --git a/tdehtml/rendering/render_form.cpp b/tdehtml/rendering/render_form.cpp
index 7fe009a7f..2872a0e6c 100644
--- a/tdehtml/rendering/render_form.cpp
+++ b/tdehtml/rendering/render_form.cpp
@@ -26,7 +26,7 @@
#include <kcompletionbox.h>
#include <kcursor.h>
#include <kdebug.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kfind.h>
#include <kfinddialog.h>
#include <kiconloader.h>
diff --git a/tdehtml/tdehtml_ext.cpp b/tdehtml/tdehtml_ext.cpp
index 62a5293c1..4127e7762 100644
--- a/tdehtml/tdehtml_ext.cpp
+++ b/tdehtml/tdehtml_ext.cpp
@@ -45,8 +45,8 @@
#include <kdebug.h>
#include <klocale.h>
-#include <kfiledialog.h>
-#include <kio/job.h>
+#include <tdefiledialog.h>
+#include <tdeio/job.h>
#include <kprocess.h>
#include <ktoolbarbutton.h>
#include <ktoolbar.h>
diff --git a/tdehtml/tdehtml_ext.h b/tdehtml/tdehtml_ext.h
index 5e2eafa9e..5a8f00e70 100644
--- a/tdehtml/tdehtml_ext.h
+++ b/tdehtml/tdehtml_ext.h
@@ -32,7 +32,7 @@
#include <tqguardedptr.h>
#include <kaction.h>
-#include <kio/global.h>
+#include <tdeio/global.h>
/**
* This is the BrowserExtension for a KHTMLPart document. Please see the KParts documentation for
diff --git a/tdehtml/tdehtml_iface.cc b/tdehtml/tdehtml_iface.cc
index e42562c51..1ceb6b5d4 100644
--- a/tdehtml/tdehtml_iface.cc
+++ b/tdehtml/tdehtml_iface.cc
@@ -22,7 +22,7 @@
#include "tdehtml_part.h"
#include "tdehtmlview.h"
#include "tdehtml_ext.h"
-#include <kio/global.h>
+#include <tdeio/global.h>
#include <tqapplication.h>
#include <tqvariant.h>
diff --git a/tdehtml/tdehtml_part.cpp b/tdehtml/tdehtml_part.cpp
index 185ded02d..2ebd55df8 100644
--- a/tdehtml/tdehtml_part.cpp
+++ b/tdehtml/tdehtml_part.cpp
@@ -75,9 +75,9 @@ using namespace DOM;
#include <dcopref.h>
#include <kstandarddirs.h>
#include <kstringhandler.h>
-#include <kio/job.h>
-#include <kio/global.h>
-#include <kio/netaccess.h>
+#include <tdeio/job.h>
+#include <tdeio/global.h>
+#include <tdeio/netaccess.h>
#include <kprotocolmanager.h>
#include <kdebug.h>
#include <kiconloader.h>
@@ -85,7 +85,7 @@ using namespace DOM;
#include <kcharsets.h>
#include <kmessagebox.h>
#include <kstdaction.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <ktrader.h>
#include <kdatastream.h>
#include <ktempfile.h>
@@ -102,7 +102,7 @@ using namespace DOM;
#include <ksslcertchain.h>
#include <ksslinfodlg.h>
-#include <kfileitem.h>
+#include <tdefileitem.h>
#include <kurifilter.h>
#include <kstatusbar.h>
#include <kurllabel.h>
@@ -1136,7 +1136,7 @@ void KHTMLPart::launchJSErrorDialog() {
void KHTMLPart::launchJSConfigDialog() {
TQStringList args;
args << "tdehtml_java_js";
- TDEApplication::tdeinitExec( "kcmshell", args );
+ TDEApplication::tdeinitExec( "tdecmshell", args );
}
TQVariant KHTMLPart::executeScript(const TQString& filename, int baseLine, const DOM::Node& n, const TQString& script)
diff --git a/tdehtml/tdehtml_run.cpp b/tdehtml/tdehtml_run.cpp
index e1c34915a..6ae958d67 100644
--- a/tdehtml/tdehtml_run.cpp
+++ b/tdehtml/tdehtml_run.cpp
@@ -22,7 +22,7 @@
*/
#include "tdehtmlpart_p.h"
#include "tdehtml_run.h"
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <kdebug.h>
#include <klocale.h>
#include "tdehtml_ext.h"
diff --git a/tdehtml/tdehtml_settings.cc b/tdehtml/tdehtml_settings.cc
index 4d65aa99b..5675b2105 100644
--- a/tdehtml/tdehtml_settings.cc
+++ b/tdehtml/tdehtml_settings.cc
@@ -22,7 +22,7 @@
#include "tdehtml_settings.h"
#include "tdehtmldefaults.h"
#include <kglobalsettings.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <klocale.h>
#include <kdebug.h>
diff --git a/tdehtml/tdehtmlimage.cpp b/tdehtml/tdehtmlimage.cpp
index cc244ed80..a2b73db5c 100644
--- a/tdehtml/tdehtmlimage.cpp
+++ b/tdehtml/tdehtmlimage.cpp
@@ -29,7 +29,7 @@
#include <tqvbox.h>
#include <tqtimer.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <kinstance.h>
#include <kmimetype.h>
#include <klocale.h>
diff --git a/tdehtml/tdemultipart/CMakeLists.txt b/tdehtml/tdemultipart/CMakeLists.txt
index f0d03953e..6ae8c8d0e 100644
--- a/tdehtml/tdemultipart/CMakeLists.txt
+++ b/tdehtml/tdemultipart/CMakeLists.txt
@@ -18,8 +18,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdehtml
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/tdeutils
)
diff --git a/tdehtml/tdemultipart/Makefile.am b/tdehtml/tdemultipart/Makefile.am
index f02b5931e..f2e119c3f 100644
--- a/tdehtml/tdemultipart/Makefile.am
+++ b/tdehtml/tdemultipart/Makefile.am
@@ -1,11 +1,11 @@
-INCLUDES = -I$(top_srcdir)/tdehtml -I$(top_srcdir)/kio/httpfilter -I$(top_srcdir)/tdeutils $(all_includes)
+INCLUDES = -I$(top_srcdir)/tdehtml -I$(top_srcdir)/tdeio/httpfilter -I$(top_srcdir)/tdeutils $(all_includes)
# These are not really libraries, but modules dynamically opened.
# So they should be installed in kde_module_dir, which is usually $kde_prefix/lib/trinity
kde_module_LTLIBRARIES = libtdemultipart.la
libtdemultipart_la_SOURCES = tdemultipart.cpp
-libtdemultipart_la_LIBADD = $(LIB_KPARTS) $(top_builddir)/kio/httpfilter/libhttpfilter.la $(LIB_QT) $(LIB_TDECORE) $(LIB_TDEUI) $(LIB_KFILE) $(LIBZ)
+libtdemultipart_la_LIBADD = $(LIB_KPARTS) $(top_builddir)/tdeio/httpfilter/libhttpfilter.la $(LIB_QT) $(LIB_TDECORE) $(LIB_TDEUI) $(LIB_KFILE) $(LIBZ)
libtdemultipart_la_DEPENDENCIES = $(LIB_KPARTS)
libtdemultipart_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN)
diff --git a/tdehtml/tdemultipart/tdemultipart.cpp b/tdehtml/tdemultipart/tdemultipart.cpp
index d5195186d..82e94a4c0 100644
--- a/tdehtml/tdemultipart/tdemultipart.cpp
+++ b/tdehtml/tdemultipart/tdemultipart.cpp
@@ -23,7 +23,7 @@
#include <kinstance.h>
#include <kmimetype.h>
#include <klocale.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <tqfile.h>
#include <ktempfile.h>
#include <kmessagebox.h>
diff --git a/tdehtml/test_regression.cpp b/tdehtml/test_regression.cpp
index 233ac8402..497126d8c 100644
--- a/tdehtml/test_regression.cpp
+++ b/tdehtml/test_regression.cpp
@@ -62,7 +62,7 @@
#include <kaction.h>
#include <kcmdlineargs.h>
#include "tdehtml_factory.h"
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <kmainwindow.h>
#include <ksimpleconfig.h>
#include <kglobalsettings.h>
diff --git a/tdehtml/testtdehtml.cpp b/tdehtml/testtdehtml.cpp
index 84ace61fe..1da21be1f 100644
--- a/tdehtml/testtdehtml.cpp
+++ b/tdehtml/testtdehtml.cpp
@@ -30,7 +30,7 @@
#include <kcmdlineargs.h>
#include <kaction.h>
#include "domtreeview.h"
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
static KCmdLineOptions options[] = { { "+file", "url to open", 0 } , KCmdLineLastOption };
diff --git a/tdehtml/xml/CMakeLists.txt b/tdehtml/xml/CMakeLists.txt
index 904d8ba09..c32e139dc 100644
--- a/tdehtml/xml/CMakeLists.txt
+++ b/tdehtml/xml/CMakeLists.txt
@@ -20,8 +20,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdehtml
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/tdewallet/client
${CMAKE_SOURCE_DIR}/tdeutils
)
diff --git a/tdehtml/xml/Makefile.am b/tdehtml/xml/Makefile.am
index 257f63813..febb3ef71 100644
--- a/tdehtml/xml/Makefile.am
+++ b/tdehtml/xml/Makefile.am
@@ -35,7 +35,7 @@ noinst_HEADERS = \
dom2_traversalimpl.h xml_tokenizer.h dom_xmlimpl.h \
dom2_eventsimpl.h dom2_viewsimpl.h dom_restyler.h
-INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/kio -I$(top_srcdir)/dcop \
+INCLUDES = -I$(top_srcdir)/kimgio -I$(top_srcdir)/tdeio -I$(top_srcdir)/dcop \
-I$(top_srcdir)/tdehtml -I$(top_srcdir) -I$(top_srcdir)/tdewallet/client \
-I$(top_srcdir)/tdeutils -I$(top_builddir)/kjs $(all_includes)
diff --git a/tdehtml/xml/dom_docimpl.cpp b/tdehtml/xml/dom_docimpl.cpp
index 3ab639867..5614dbf2e 100644
--- a/tdehtml/xml/dom_docimpl.cpp
+++ b/tdehtml/xml/dom_docimpl.cpp
@@ -78,7 +78,7 @@
#include "html/html_objectimpl.h"
#include <kapplication.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <stdlib.h>
#include "dom_docimpl.h"
diff --git a/tdeio/CMakeLists.txt b/tdeio/CMakeLists.txt
new file mode 100644
index 000000000..826fbf743
--- /dev/null
+++ b/tdeio/CMakeLists.txt
@@ -0,0 +1,71 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+add_definitions(
+ -D_LARGEFILE64_SOURCE=1
+)
+
+add_subdirectory( kssl )
+add_subdirectory( tdeio )
+add_subdirectory( bookmarks )
+add_subdirectory( tdefile )
+add_subdirectory( pics )
+add_subdirectory( tdeioexec )
+add_subdirectory( httpfilter )
+add_subdirectory( misc )
+add_subdirectory( kpasswdserver )
+add_subdirectory( tests )
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+ ${LIBR_LIBDIR}
+)
+
+
+##### other data ################################
+
+install( FILES magic DESTINATION ${MIME_INSTALL_DIR} )
+
+install( FILES
+ application.desktop kurifilterplugin.desktop
+ kcomprfilter.desktop kscan.desktop kdatatool.desktop
+ tdefileplugin.desktop tdecmodule.desktop
+ DESTINATION ${SERVICETYPES_INSTALL_DIR} )
+
+install( FILES tdeioslave.upd DESTINATION ${KCONF_UPDATE_INSTALL_DIR} )
+install( PROGRAMS useragent.pl proxytype.pl DESTINATION ${KCONF_UPDATE_INSTALL_DIR} )
+install( FILES renamedlgplugin.desktop DESTINATION ${SERVICETYPES_INSTALL_DIR} )
+install( FILES kpasswdserver.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
+install( FILES data.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+if( HAVE_ELFICON )
+ set( ELFICON_STATIC_LIB tdelficon-static )
+endif( HAVE_ELFICON )
+
+
+##### libtdeio ####################################
+
+set( target tdeio )
+
+configure_file( ${CMAKE_SOURCE_DIR}/cmake/modules/template_dummy_cpp.cmake dummy.cpp COPYONLY )
+
+tde_add_library( ${target} SHARED
+ SOURCES ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp
+ VERSION 4.2.0
+ EMBED kssl-static tdeiocore-static tdesycoca-static kbookmarks-static tdefile-static ${ELFICON_STATIC_LIB}
+ LINK ltdlc-static tdeui-shared tdesu-shared tdewalletclient-shared ${LIBR_LIBRARIES}
+ DESTINATION ${LIB_INSTALL_DIR}
+)
diff --git a/tdeio/DESIGN b/tdeio/DESIGN
new file mode 100644
index 000000000..22307c5c0
--- /dev/null
+++ b/tdeio/DESIGN
@@ -0,0 +1,272 @@
+DESIGN:
+=======
+
+libtdeio uses tdeioslaves (separate processes) that handle a given protocol.
+Launching those slaves is taken care of by the tdeinit/tdelauncher tandem,
+which are notified by DCOP.
+
+Connection is the most low-level class, the one that encapsulates the pipe.
+
+SlaveInterface is the main class for transferring anything to the slave
+and Slave, which inherits SlaveInterface, is the sub class that Job should handle.
+
+A slave inherits SlaveBase, which is the other half of SlaveInterface.
+
+The scheduling is supposed to be on a two level basis. One is in the daemon
+and one is in the application. The daemon one (as opposite to the holy one? :)
+will determine how many slaves are ok for this app to be opened and it will
+also assign tasks to actually existing slaves.
+The application will still have some kind of a scheduler, but it should be
+a lot simpler as it doesn't have to decide anything besides which
+task goes to which pool of slaves (related to the protocol/host/user/port)
+and move tasks around.
+Currently a design study to name it cool is in scheduler.cpp but in the
+application side. This is just to test other things like recursive jobs
+and signals/slots within SlaveInterface. If someone feels brave, the scheduler
+is yours!
+On a second thought: at the daemon side there is no real scheduler, but a
+pool of slaves. So what we need is some kind of load calculation of the
+scheduler in the application and load balancing in the daemon.
+
+A third thought: Maybe the daemon can just take care of a number of 'unused'
+slaves. When an application needs a slave, it can request it from the daemon.
+The application will get one, either from the pool of unused slaves,
+or a new one will be created. This keeps things simple at the daemon level.
+It is up to the application to give the slaves back to the daemon.
+The scheduler in the application must take care not to request too many
+slaves and could implement priorities.
+
+Thought on usage:
+* Typically a single slave-type is used exclusively in one application. E.g.
+http slaves are used in a web-browser. POP3 slaves used in a mail program.
+
+* Sometimes a single program can have multiple roles. E.g. konqueror is
+both a web-browser and a file-manager. As a web-browser it primarily uses
+http-slaves as a file-manager file-slaves.
+
+* Selecting a link in konqueror: konqueror does a partial download of
+the file to check the mimetype (right??) then the application is
+started which downloads the complete file. In this case it should
+be able to pass the slave which does the partial download from konqueror
+to the application where it can do the complete download.
+
+Do we need to have a hard limit on the number of slaves/host?
+It seems so, because some protocols are about to fail if you
+have two slaves running in parralel (e.g. POP3)
+This has to be implemented in the daemon because only at daemon
+level all the slaves are known. As a consequence slaves must
+be returned to the daemon before connecting to another host.
+(Returning the slaves back to the daemon after every job is not
+strictly needed and only causes extra overhead)
+
+Instead of actually returning the slave to the daemon, it could
+be enough to ask 'recycling permission' from the daemon: the
+application asks the daemon whether it is ok to use a slave for
+another host. The daemon can then update its administration of
+which slave is connected to which host.
+
+The above does of course not apply to hostless protocols (like file).
+(They will never change host).
+
+Apart from a 'hard limit' on the number of slaves/host we can have
+a 'soft limit'. E.g. upon connection to a HTTP 1.1 server, the web-
+server tells the slave the number of parallel connections allowed.
+THe simplest solution seems to be to treat 'soft limits' the same
+as 'hard limits'. This means that the slave has to communicate the
+'soft limit' to the daemon.
+
+Jobs using multiple slaves.
+
+If a job needs multiple slaves in parallel (e.g. copying a file from
+a web-server to a ftp-server or browsing a tar-file on a ftp-site)
+we must make sure to request the daemon for all slaves together since
+otherwise there is a risk of deadlock.
+
+(If two applications both need a 'pop3' and a 'ftp' slave for a single
+job and only a single slave/host is allowed for pop3 and ftp, we must
+prevent giving the single pop3 slave to application #1 and the single
+ftp slave to application #2. Both applications will then wait till the
+end of times till they get the other slave so that they can start the
+job. (This is a quite unlikely situation, but nevertheless possible))
+
+
+File Operations:
+listRecursive is implemented as listDir and finding out if in the result
+ is a directory. If there is, another listDir job is issued. As listDir
+ is a readonly operation it fails when a directory isn't readable
+ .. but the main job goes on and discards the error, because
+bIgnoreSubJobsError is true, which is what we want (David)
+
+del is implemented as listRecursive, removing all files and removing all
+ empty directories. This basically means if one directory isn't readable
+ we don't remove it as listRecursive didn't find it. But the del will later
+ on try to remove it's parent directory and fail. But there are cases when
+ it would be possible to delete the dir in chmod the dir before. On the
+ other hand del("/") shouldn't list the whole file system and remove all
+ user owned files just to find out it can't remove everything else (this
+ basically means we have to take care of things we can remove before we try)
+
+ ... Well, rm -rf / refuses to do anything, so we should just do the same:
+ use a listRecursive with bIgnoreSubJobsError = false. If anything can't
+ be removed, we just abort. (David)
+
+ ... My concern was more that the fact we can list / doesn't mean we can
+ remove it. So we shouldn't remove everything we could list without checking
+ we can. But then the question arises how do we check whether we can remove it?
+ (Stephan)
+
+ ... I was wrong, rm -rf /, even as a user, lists everything and removes
+ everything it can (don't try this at home!). I don't think we can do
+ better, unless we add a protocol-dependent "canDelete(path)", which is
+ _really_ not easy to implement, whatever protocol. (David)
+
+
+Lib docu
+========
+
+mkdir: ...
+
+rmdir: ...
+
+chmod: ...
+
+special: ...
+
+stat: ...
+
+get is implemented as TransferJob. Clients get 'data' signals with the data.
+A data block of zero size indicates end of data (EOD)
+
+put is implemented as TransferJob. Clients have to connect to the
+'dataReq' signal. The slave will call you when it needs your data.
+
+mimetype: ...
+
+file_copy: copies a single file, either using CMD_COPY if the slave
+ supports that or get & put otherwise.
+
+file_move: moves a single file, either using CMD_RENAME if the slave
+ supports that, CMD_COPY + del otherwise, or eventually
+ get & put & del.
+
+file_delete: delete a single file.
+
+copy: copies a file or directory, recursively if the latter
+
+move: moves a file or directory, recursively if the latter
+
+del: deletes a file or directory, recursively if the latter
+
+PROGRESS DISPLAYING :
+=====================
+Taj brought up the idea of deligating all progress informations to an extern
+GUI daemon which could be provided in several implementations - examples
+are popup dialogs (most are annoyed by them, like me :) or a kicker applet
+or something completely different. This would also remove the dependency on
+libtdeui (I hope).
+Conclusion: tdeio_uiserver is this single GUI daemon, but the dependency on
+libtdeui couldn't be removed (for many reasons, including Job::showErrorDialog())
+
+A. progress handling
+---------------------
+There will be two ways how the application can display progress :
+
+1. regular apps will use NetAccess for all kio operations and will not care
+ about progress handling :
+ - NetAccess creates Job
+ - NetAccess creates JobObserver that will connect to the Job's signals and
+ pass them via dcop to the running GUI Progress Server
+
+2. apps that want to do some handling with progress dialogs like Caitoo or
+ KMail :
+ - app creates Job
+ - app creates a progress dialog : this should be a ProgressBase descendant
+ e.g. StatusProgress or custom progress dialog
+ - app calls progress->setJob( job ) in order to connect job's signals with
+ progress dialog slots
+
+B. customized progress dialogs
+-------------------------------
+ This will be similar to what we had before.
+
+ - ProgressBase class that all other dialogs will inherit.
+ will contain an initialization method setJob( TDEIO::Job*) for apps of the
+ second class (see A.2 above), that will connect job's signals to dialog's
+ slots
+
+ - DefaultProgress ( former KIOSimpleProgressDialog ) that will be used for
+ regular progress dialogs created by GUI Progress Server
+
+ - StatusProgress ( former KIOLittleProgressDialog ) that can be used for
+ embedding in status bar
+
+C. GUI Progress Server
+-----------------------
+ This is a special progress server.
+ - createProgress() will either create a DefaultProgress dialog or add new entry
+ in a ListProgress ( an all-jobs-in-one progress dialog )
+ - after receiving signals from the JobObserver via DCOP it will call
+ appropriate method of progress dialog ( either in DefaultProgress or ListProgress )
+ - ListProgres can be a Caitoo style dialog, kicker applet or both in one.
+
+D. Some notes
+--------------
+ 1. most of the apps will not care at all about the progress display
+ 2. user will be able to choose whether he wants to see separate progress
+ dialogs or all-in-one ListProgress dialog
+ 3. developers can create their custom progress dialogs that inherit
+ ProgressBase and do any manipulation with a dialog if they use a second
+ approach ( see A.2 above )
+
+
+Streaming
+---------
+
+ 1. We currently support a streaming "GET": e.g. file:/tmp/test.gz#gzip:/
+ works. The following should also work: file:/tmp/test.gz.gz#gzip:/#gzip:/
+ The current approach makes a TrasnferJob for gzip:/ and then adds a
+ subjob for "file:/tmp/test.gz.gz#gzip:/" which itself adds a subjob
+ for "file:/tmp/test.gz.gz".
+ 2. This doesn't extend very well to PUT, because there the order should
+ basically be the other way around, but the "input" to the job as a whole
+ should go to the "gzip:/" job, not to the "file:/tmp/test.gz.gz."
+ It would probably be easier to implement such a job in the way the
+ current "CopyJob" is done. Have a Job and make all sub-urls sub-jobs of
+ this Job.
+ 3. As a result of 1. COPY FROM an url like file:/tmp/test.gz#gzip:/ should
+ work. COPY TO does not, because that would require PUT.
+
+
+Resuming
+--------
+
+A rough note for now, just to have this somewhere :
+(PJ=put-job, GJ=get-job)
+
+PJ can't resume:
+PJ-->app: canResume(0) (emitted by dataReq)
+GJ-->app: data()
+PJ-->app: dataReq()
+app->PJ: data()
+
+PJ can resume but GJ can't resume:
+PJ-->app: canResume(xx)
+app->GJ: start job with "resume=xxx" metadata.
+GJ-->app: data()
+PJ-->app: dataReq()
+app->PJ: data()
+
+PJ can resume and GJ can resume:
+PJ-->app: canResume(xx)
+app->GJ: start job with "resume=xxx" metadata.
+GJ-->app: canResume(xx)
+GJ-->app: data()
+PJ-->app: dataReq()
+app->PJ: canResume(xx)
+app->PJ: data()
+
+So when the slave supports resume for "put" it has to check after the first
+dataRequest() whether it has got a canResume() back from the app. If it did
+it must resume. Otherwise it must start from 0.
+
+
diff --git a/tdeio/DESIGN.krun b/tdeio/DESIGN.krun
new file mode 100644
index 000000000..9ac31f433
--- /dev/null
+++ b/tdeio/DESIGN.krun
@@ -0,0 +1,35 @@
+
+konq_run / krun should determine the mimetype by actually
+getting the contents of the URL. It should then put the slave
+on hold and tell the job-scheduler which request the
+slave is currently handling. (Status: implemented in konq_run)
+
+Now krun/konq_run should determine which client should process the
+result of the request.
+
+* When the client belongs to the same process, no action needs to be
+taken. When a new job is created for the request which is on hold the
+existing slave will be re-used and the request resumed.
+(Status: implemented)
+
+* When the client is an external process, the on-hold-slave should be
+removed from the job-scheduler and should connect itself with
+tdelauncher. This is hard because it must ensure that the external
+program does not request the slave before it has been transfered to
+tdelauncher. (Status: to be done)
+
+* When a slave is on hold but not used for a certain period of time,
+or, when another slave is put on hold, the slave should be killed.
+(Status: almost done)
+
+=====
+
+The slave must emit "mimetype" during a GET before the first data is send.
+
+It may wait with sending "mimetype" until it has enough data to
+determine the mimetype, but it should not pass any data along before it has
+send the mimetype.
+
+Currently only http _always_ sends a mimetype.
+
+
diff --git a/kio/DESIGN.metadata b/tdeio/DESIGN.metadata
index 783d7f52a..783d7f52a 100644
--- a/kio/DESIGN.metadata
+++ b/tdeio/DESIGN.metadata
diff --git a/kio/DESIGN.mimetypes b/tdeio/DESIGN.mimetypes
index 7f1d81b11..7f1d81b11 100644
--- a/kio/DESIGN.mimetypes
+++ b/tdeio/DESIGN.mimetypes
diff --git a/kio/DESKTOP_ENTRY_STANDARD b/tdeio/DESKTOP_ENTRY_STANDARD
index e19cc24c8..e19cc24c8 100644
--- a/kio/DESKTOP_ENTRY_STANDARD
+++ b/tdeio/DESKTOP_ENTRY_STANDARD
diff --git a/kio/Mainpage.dox b/tdeio/Mainpage.dox
index 7545c29ef..7545c29ef 100644
--- a/kio/Mainpage.dox
+++ b/tdeio/Mainpage.dox
diff --git a/tdeio/Makefile.am b/tdeio/Makefile.am
new file mode 100644
index 000000000..aa23fcb5a
--- /dev/null
+++ b/tdeio/Makefile.am
@@ -0,0 +1,67 @@
+# This file is part of the KDE libraries
+# Copyright (C) 1997 Torben Weis (weis@kde.org)
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
+
+INCLUDES= -I$(srcdir)/.. $(all_includes) $(SSL_INCLUDES)
+
+SUBDIRS = kssl tdeio bookmarks tdefile . pics tests tdeioexec httpfilter misc kpasswdserver
+
+lib_LTLIBRARIES = libtdeio.la
+
+libtdeio_la_SOURCES = dummy.cpp
+
+libtdeio_la_LDFLAGS = -version-info 6:0:2 -no-undefined $(all_libraries) \
+ $(KDE_MT_LDFLAGS)
+libtdeio_la_LIBADD = kssl/libkssl.la tdeio/libtdeiocore.la \
+ tdeio/libtdesycoca.la bookmarks/libkbookmarks.la tdefile/libtdefile.la \
+ ../tdeui/libtdeui.la ../tdesu/libtdesu.la \
+ ../tdewallet/client/libtdewalletclient.la \
+ $(LIBZ) $(LIBFAM) $(LIBVOLMGT) $(ACL_LIBS) $(LIB_QT) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la $(LIB_X11)
+
+kde_mime_DATA = magic
+kde_servicetypes_DATA = application.desktop kurifilterplugin.desktop \
+ kcomprfilter.desktop kscan.desktop kdatatool.desktop \
+ tdefileplugin.desktop tdecmodule.desktop
+
+EXTRA_DIST = $(kde_mime_DATA)
+
+update_DATA = tdeioslave.upd
+update_SCRIPTS = useragent.pl proxytype.pl
+updatedir = $(kde_datadir)/tdeconf_update
+
+servicetype_DATA = renamedlgplugin.desktop
+servicetypedir = $(kde_servicetypesdir)
+
+kded_DATA = kpasswdserver.desktop
+kdeddir = $(kde_servicesdir)/kded
+
+dataprotocol_DATA = data.protocol
+dataprotocoldir = $(kde_servicesdir)
+
+dummy.cpp:
+ echo >dummy.cpp
+
+messages:
+ $(EXTRACTRC) `find . ../tdeioslave -name "*.rc" -o -name "*.ui"` > rc.cpp
+ $(XGETTEXT) `find . ../tdeioslave -name "*.cpp" -o -name "*.cc" -o -name "*.h"` -o $(podir)/tdeio.pot
+ rm -f rc.cpp
+
+DOXYGEN_REFERENCES = tdecore tdefx kjs dcop tdeui tdeio/tdeio tdeio/tdefile
+DOXYGEN_EXCLUDE = kssl/kssl
+include ../admin/Doxyfile.am
diff --git a/kio/application.desktop b/tdeio/application.desktop
index d9e9fc3c2..d9e9fc3c2 100644
--- a/kio/application.desktop
+++ b/tdeio/application.desktop
diff --git a/tdeio/bookmarks/CMakeLists.txt b/tdeio/bookmarks/CMakeLists.txt
new file mode 100644
index 000000000..93121cbac
--- /dev/null
+++ b/tdeio/bookmarks/CMakeLists.txt
@@ -0,0 +1,55 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdefx
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
+)
+
+
+##### headers ###################################
+
+install( FILES
+ kbookmark.h kbookmarkbar.h kbookmarkdrag.h kbookmarkexporter.h
+ kbookmarkimporter.h kbookmarkmanager.h kbookmarkmenu.h
+ kbookmarknotifier.h kbookmarkimporter_crash.h
+ kbookmarkimporter_opera.h kbookmarkimporter_ie.h
+ kbookmarkimporter_ns.h kbookmarkimporter_kde1.h
+ kbookmarkdombuilder.h
+ DESTINATION ${INCLUDE_INSTALL_DIR} )
+
+
+##### kbookmarks ################################
+
+set( target kbookmarks )
+
+set( ${target}_SRCS
+ kbookmark.cc kbookmarkbar.cc kbookmarkdrag.cc kbookmarkexporter.cc
+ kbookmarkimporter.cc kbookmarkmanager.cc kbookmarkmenu.cc
+ kbookmarkimporter_crash.cc kbookmarkimporter_opera.cc
+ kbookmarkimporter_ie.cc kbookmarkimporter_ns.cc
+ kbookmarkimporter_kde1.cc kbookmarkdombuilder.cc
+ kbookmarkmanager.skel kbookmarknotifier.skel
+)
+
+tde_add_library( ${target} STATIC_PIC AUTOMOC
+ SOURCES ${${target}_SRCS}
+ DEPENDENCIES dcopidl
+)
diff --git a/tdeio/bookmarks/Makefile.am b/tdeio/bookmarks/Makefile.am
new file mode 100644
index 000000000..e1ec3a8df
--- /dev/null
+++ b/tdeio/bookmarks/Makefile.am
@@ -0,0 +1,40 @@
+# This file is part of the KDE libraries
+# Copyright (C) 1997 Stephan Kulow (coolo@kde.org)
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this library; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+
+INCLUDES= -I$(srcdir)/../libltdl/ -I$(top_srcdir) -I$(top_srcdir)/tdefx -I$(top_builddir)/tdeio/tdeio $(all_includes)
+
+noinst_LTLIBRARIES = libkbookmarks.la
+
+METASOURCES = AUTO
+
+# convenience lib - no _LDFLAGS or _LIBADD !
+
+include_HEADERS = \
+ kbookmark.h kbookmarkbar.h kbookmarkdrag.h kbookmarkexporter.h \
+ kbookmarkimporter.h kbookmarkmanager.h kbookmarkmenu.h kbookmarknotifier.h \
+ kbookmarkimporter_crash.h kbookmarkimporter_opera.h kbookmarkimporter_ie.h \
+ kbookmarkimporter_ns.h kbookmarkimporter_kde1.h kbookmarkdombuilder.h
+libkbookmarks_la_SOURCES = \
+ kbookmark.cc kbookmarkbar.cc kbookmarkdrag.cc kbookmarkexporter.cc \
+ kbookmarkimporter.cc kbookmarkmanager.cc kbookmarkmenu.cc \
+ kbookmarkimporter_crash.cc kbookmarkimporter_opera.cc kbookmarkimporter_ie.cc \
+ kbookmarkimporter_ns.cc kbookmarkimporter_kde1.cc kbookmarkdombuilder.cc \
+ kbookmarkmanager.skel kbookmarknotifier.skel
+
+include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kio/bookmarks/dptrtemplate.h b/tdeio/bookmarks/dptrtemplate.h
index dbc059e7e..dbc059e7e 100644
--- a/kio/bookmarks/dptrtemplate.h
+++ b/tdeio/bookmarks/dptrtemplate.h
diff --git a/kio/bookmarks/kbookmark.cc b/tdeio/bookmarks/kbookmark.cc
index ab1cc398a..ab1cc398a 100644
--- a/kio/bookmarks/kbookmark.cc
+++ b/tdeio/bookmarks/kbookmark.cc
diff --git a/kio/bookmarks/kbookmark.h b/tdeio/bookmarks/kbookmark.h
index 4e5dc9149..4e5dc9149 100644
--- a/kio/bookmarks/kbookmark.h
+++ b/tdeio/bookmarks/kbookmark.h
diff --git a/tdeio/bookmarks/kbookmarkbar.cc b/tdeio/bookmarks/kbookmarkbar.cc
new file mode 100644
index 000000000..e73801808
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkbar.cc
@@ -0,0 +1,554 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE project
+ Copyright (C) 1999 Kurt Granroth <granroth@kde.org>
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#include <tqregexp.h>
+#include <tqfile.h>
+
+#include <kbookmarkbar.h>
+#include <kbookmarkdrag.h>
+
+#include <kbookmarkmenu.h>
+#include <kdebug.h>
+
+#include <ktoolbar.h>
+#include <ktoolbarbutton.h>
+
+#include <tdeconfig.h>
+#include <kpopupmenu.h>
+
+#include "kbookmarkdrag.h"
+#include "kbookmarkmenu_p.h"
+#include "kbookmarkdombuilder.h"
+
+#include "dptrtemplate.h"
+
+#include <tqapplication.h>
+
+class KBookmarkBarPrivate : public dPtrTemplate<KBookmarkBar, KBookmarkBarPrivate>
+{
+public:
+ TQPtrList<KAction> m_actions;
+ bool m_readOnly;
+ KBookmarkManager* m_filteredMgr;
+ KToolBar* m_sepToolBar;
+ int m_sepIndex;
+ bool m_atFirst;
+ TQString m_dropAddress;
+ TQString m_highlightedAddress;
+public:
+ KBookmarkBarPrivate() {
+ m_readOnly = false;
+ m_filteredMgr = 0;
+ m_sepToolBar = 0;
+ m_sepIndex = -1;
+ m_atFirst = false;
+ }
+};
+template<> TQPtrDict<KBookmarkBarPrivate>* dPtrTemplate<KBookmarkBar, KBookmarkBarPrivate>::d_ptr = 0;
+
+KBookmarkBarPrivate* KBookmarkBar::dptr() const
+{
+ return KBookmarkBarPrivate::d( this );
+}
+
+// usage of KXBELBookmarkImporterImpl is just plain evil, but it reduces code dup. so...
+class ToolbarFilter : public KXBELBookmarkImporterImpl
+{
+public:
+ ToolbarFilter() : m_visible(false) { ; }
+ void filter( const KBookmarkGroup &grp ) { traverse(grp); }
+private:
+ virtual void visit( const KBookmark & );
+ virtual void visitEnter( const KBookmarkGroup & );
+ virtual void visitLeave( const KBookmarkGroup & );
+private:
+ bool m_visible;
+ KBookmarkGroup m_visibleStart;
+};
+
+KBookmarkBar::KBookmarkBar( KBookmarkManager* mgr,
+ KBookmarkOwner *_owner, KToolBar *_toolBar,
+ KActionCollection *coll,
+ TQObject *parent, const char *name )
+ : TQObject( parent, name ), m_pOwner(_owner), m_toolBar(_toolBar),
+ m_actionCollection( coll ), m_pManager(mgr)
+{
+ m_lstSubMenus.setAutoDelete( true );
+
+ m_toolBar->setAcceptDrops( true );
+ m_toolBar->installEventFilter( this ); // for drops
+
+ dptr()->m_actions.setAutoDelete( true );
+
+ connect( mgr, TQT_SIGNAL( changed(const TQString &, const TQString &) ),
+ TQT_SLOT( slotBookmarksChanged(const TQString &) ) );
+
+ KBookmarkGroup toolbar = getToolbar();
+ fillBookmarkBar( toolbar );
+}
+
+TQString KBookmarkBar::parentAddress()
+{
+ return dptr()->m_filteredMgr ? TQString::null : m_pManager->toolbar().address();
+}
+
+#define CURRENT_TOOLBAR() ( \
+ dptr()->m_filteredMgr ? dptr()->m_filteredMgr->root() \
+ : m_pManager->toolbar() )
+
+#define CURRENT_MANAGER() ( \
+ dptr()->m_filteredMgr ? dptr()->m_filteredMgr \
+ : m_pManager )
+
+KBookmarkGroup KBookmarkBar::getToolbar()
+{
+ if ( KBookmarkSettings::self()->m_filteredtoolbar )
+ {
+ if ( !dptr()->m_filteredMgr ) {
+ dptr()->m_filteredMgr = KBookmarkManager::createTempManager();
+ } else {
+ KBookmarkGroup bkRoot = dptr()->m_filteredMgr->root();
+ TQValueList<KBookmark> bks;
+ for (KBookmark bm = bkRoot.first(); !bm.isNull(); bm = bkRoot.next(bm))
+ bks << bm;
+ for ( TQValueListConstIterator<KBookmark> it = bks.begin(); it != bks.end(); ++it )
+ bkRoot.deleteBookmark( (*it) );
+ }
+ ToolbarFilter filter;
+ KBookmarkDomBuilder builder( dptr()->m_filteredMgr->root(),
+ dptr()->m_filteredMgr );
+ builder.connectImporter( &filter );
+ filter.filter( m_pManager->root() );
+ }
+
+ return CURRENT_TOOLBAR();
+}
+
+KBookmarkBar::~KBookmarkBar()
+{
+ //clear();
+ KBookmarkBarPrivate::delete_d(this);
+}
+
+void KBookmarkBar::clear()
+{
+ TQPtrListIterator<KAction> it( dptr()->m_actions );
+ m_toolBar->clear();
+ for (; it.current(); ++it ) {
+ (*it)->unplugAll();
+ }
+ dptr()->m_actions.clear();
+ m_lstSubMenus.clear();
+}
+
+void KBookmarkBar::slotBookmarksChanged( const TQString & group )
+{
+ KBookmarkGroup tb = getToolbar(); // heavy for non cached toolbar version
+ kdDebug(7043) << "slotBookmarksChanged( " << group << " )" << endl;
+
+ if ( tb.isNull() )
+ return;
+
+ if ( KBookmark::commonParent(group, tb.address()) == group // Is group a parent of tb.address?
+ || KBookmarkSettings::self()->m_filteredtoolbar )
+ {
+ clear();
+ fillBookmarkBar( tb );
+ }
+ else
+ {
+ // Iterate recursively into child menus
+ TQPtrListIterator<KBookmarkMenu> it( m_lstSubMenus );
+ for (; it.current(); ++it )
+ {
+ it.current()->slotBookmarksChanged( group );
+ }
+ }
+}
+
+void KBookmarkBar::fillBookmarkBar(KBookmarkGroup & parent)
+{
+ if (parent.isNull())
+ return;
+
+ for (KBookmark bm = parent.first(); !bm.isNull(); bm = parent.next(bm))
+ {
+ TQString text = bm.text();
+ text.replace( '&', "&&" );
+ if (!bm.isGroup())
+ {
+ if ( bm.isSeparator() )
+ m_toolBar->insertLineSeparator();
+ else
+ {
+ KAction *action = new KBookmarkAction( text, bm.icon(), 0, m_actionCollection, 0 );
+ connect(action, TQT_SIGNAL( activated ( KAction::ActivationReason, TQt::ButtonState )),
+ this, TQT_SLOT( slotBookmarkSelected( KAction::ActivationReason, TQt::ButtonState ) ));
+
+ action->setProperty( "url", bm.url().url() );
+ action->setProperty( "address", bm.address() );
+
+ action->setToolTip( bm.url().pathOrURL() );
+
+ action->plug(m_toolBar);
+
+ dptr()->m_actions.append( action );
+ }
+ }
+ else
+ {
+ KActionMenu *action = new KBookmarkActionMenu( text, bm.icon(),
+ m_actionCollection,
+ "bookmarkbar-actionmenu");
+ action->setProperty( "address", bm.address() );
+ action->setProperty( "readOnly", dptr()->m_readOnly );
+ action->setDelayed( false );
+
+ // this flag doesn't have any UI yet
+ TDEGlobal::config()->setGroup( "Settings" );
+ bool addEntriesBookmarkBar = TDEGlobal::config()->readBoolEntry("AddEntriesBookmarkBar",true);
+
+ KBookmarkMenu *menu = new KBookmarkMenu(CURRENT_MANAGER(), m_pOwner, action->popupMenu(),
+ m_actionCollection, false, addEntriesBookmarkBar,
+ bm.address());
+ connect(menu, TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu * ) ),
+ this, TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu * ) ));
+ connect(menu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState) ),
+ this, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState) ));
+ menu->fillBookmarkMenu();
+ action->plug(m_toolBar);
+ m_lstSubMenus.append( menu );
+
+ dptr()->m_actions.append( action );
+ }
+ }
+}
+
+void KBookmarkBar::setReadOnly(bool readOnly)
+{
+ dptr()->m_readOnly = readOnly;
+}
+
+bool KBookmarkBar::isReadOnly() const
+{
+ return dptr()->m_readOnly;
+}
+
+void KBookmarkBar::slotBookmarkSelected( KAction::ActivationReason /*reason*/, TQt::ButtonState state )
+{
+ if (!m_pOwner) return; // this view doesn't handle bookmarks...
+
+ const KAction* action = dynamic_cast<const KAction *>(sender());
+ if(action)
+ {
+ const TQString & url = sender()->property("url").toString();
+ m_pOwner->openBookmarkURL(url);
+ emit openBookmark( url, state );
+ }
+}
+
+void KBookmarkBar::slotBookmarkSelected()
+{
+ slotBookmarkSelected(KAction::ToolBarActivation, Qt::NoButton);
+}
+
+static const int const_sepId = -9999; // FIXME this is ugly,
+ // surely there is another
+ // way of doing this...
+
+static void removeTempSep(KBookmarkBarPrivate* p)
+{
+ if (p->m_sepToolBar) {
+ p->m_sepToolBar->removeItem(const_sepId);
+ p->m_sepToolBar = 0; // needed?
+ }
+}
+
+static KAction* findPluggedAction(TQPtrList<KAction> actions, KToolBar *tb, int id)
+{
+ TQPtrListIterator<KAction> it( actions );
+ for (; (*it); ++it )
+ if ((*it)->isPlugged(tb, id))
+ return (*it);
+ return 0;
+}
+
+/**
+ * Handle a TQDragMoveEvent event on a toolbar drop
+ * @return the address of the bookmark to be dropped after/before
+ * else a TQString::null if event should be ignored
+ * @param pos the current TQDragMoveEvent position
+ * @param the toolbar
+ * @param actions the list of actions plugged into the bar
+ * @param atFirst bool reference, when true the position before the
+ * returned action was dropped on
+ */
+static TQString handleToolbarDragMoveEvent(
+ KBookmarkBarPrivate *p, KToolBar *tb, TQPoint pos, TQPtrList<KAction> actions,
+ bool &atFirst, KBookmarkManager *mgr
+) {
+ Q_UNUSED( mgr );
+ Q_ASSERT( actions.isEmpty() || (tb == dynamic_cast<KToolBar*>(actions.first()->container(0))) );
+ p->m_sepToolBar = tb;
+ p->m_sepToolBar->removeItemDelayed(const_sepId);
+
+ int index = 0;
+ KToolBarButton* b;
+
+ b = dynamic_cast<KToolBarButton*>(tb->childAt(pos));
+ KAction *a = 0;
+ TQString address;
+ atFirst = false;
+
+ if (b)
+ {
+ index = tb->itemIndex(b->id());
+ TQRect r = b->geometry();
+ if (pos.x() < ((r.left() + r.right())/2))
+ {
+ // if in first half of button then
+ // we jump to previous index
+ if ( index == 0 )
+ atFirst = true;
+ else {
+ index--;
+ b = tb->getButton(tb->idAt(index));
+ }
+ }
+ }
+ else if (actions.isEmpty())
+ {
+ atFirst = true;
+ index = 0;
+ // we skip the action related stuff
+ // and do what it should have...
+ // FIXME - here we want to get the
+ // parent address of the bookmark
+ // bar itself and return that + "/0"
+ p->m_sepIndex = 0;
+ goto skipact;
+ }
+ else // (!b)
+ {
+ index = actions.count() - 1;
+ b = tb->getButton(tb->idAt(index));
+ // if !b and not past last button, we didn't find button
+ if (pos.x() <= b->geometry().left())
+ goto skipact; // TODO - rename
+ }
+
+ if ( !b )
+ return TQString::null; // TODO Make it works for that case
+
+ a = findPluggedAction(actions, tb, b->id());
+ Q_ASSERT(a);
+ address = a->property("address").toString();
+ p->m_sepIndex = index + (atFirst ? 0 : 1);
+
+#if 0
+ { // ugly workaround to fix the goto scoping problems...
+ KBookmark bk = mgr->findByAddress( address );
+ if (bk.isGroup()) // TODO - fix this ****!!!, manhatten distance should be used!!!
+ {
+ kdDebug() << "kbookmarkbar:: popping up " << bk.text() << endl;
+ KBookmarkActionMenu *menu = dynamic_cast<KBookmarkActionMenu*>(a);
+ Q_ASSERT(menu);
+ menu->popup(tb->mapToGlobal(b->geometry().center()));
+ }
+ }
+#endif
+
+skipact:
+ tb->insertLineSeparator(p->m_sepIndex, const_sepId);
+ return address;
+}
+
+// TODO - document!!!!
+static KAction* handleToolbarMouseButton(TQPoint pos, TQPtrList<KAction> actions,
+ KBookmarkManager * /*mgr*/, TQPoint & pt)
+{
+ KAction *act = actions.first();
+ if (!act) {
+ return 0;
+ }
+
+ KToolBar *tb = dynamic_cast<KToolBar*>(act->container(0));
+ Q_ASSERT(tb);
+
+ KToolBarButton *b;
+ b = dynamic_cast<KToolBarButton*>(tb->childAt(pos));
+ if (!b)
+ return 0;
+
+ KAction *a = 0;
+ a = findPluggedAction(actions, tb, b->id());
+ Q_ASSERT(a);
+ pt = tb->mapToGlobal(pos);
+
+ return a;
+}
+
+// TODO *** drop improvements ***
+// open submenus on drop interactions
+
+// TODO *** generic rmb improvements ***
+// don't *ever* show the rmb on press, always relase, possible???
+
+class KBookmarkBarRMBAssoc : public dPtrTemplate<KBookmarkBar, RMB> { };
+template<> TQPtrDict<RMB>* dPtrTemplate<KBookmarkBar, RMB>::d_ptr = 0;
+
+static RMB* rmbSelf(KBookmarkBar *m) { return KBookmarkBarRMBAssoc::d(m); }
+
+void RMB::begin_rmb_action(KBookmarkBar *self)
+{
+ RMB *s = rmbSelf(self);
+ s->recv = self;
+ s->m_parentAddress = self->parentAddress();
+ s->s_highlightedAddress = self->dptr()->m_highlightedAddress; // rename in RMB
+ s->m_pManager = self->m_pManager;
+ s->m_pOwner = self->m_pOwner;
+ s->m_parentMenu = 0;
+}
+
+void KBookmarkBar::slotRMBActionEditAt( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionEditAt( val ); }
+
+void KBookmarkBar::slotRMBActionProperties( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionProperties( val ); }
+
+void KBookmarkBar::slotRMBActionInsert( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionInsert( val ); }
+
+void KBookmarkBar::slotRMBActionRemove( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionRemove( val ); }
+
+void KBookmarkBar::slotRMBActionCopyLocation( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionCopyLocation( val ); }
+
+bool KBookmarkBar::eventFilter( TQObject *o, TQEvent *e )
+{
+ if (dptr()->m_readOnly || dptr()->m_filteredMgr) // note, we assume m_pManager in various places,
+ // this shouldn't really be the case
+ return false; // todo: make this limit the actions
+
+ if ( (e->type() == TQEvent::MouseButtonRelease) || (e->type() == TQEvent::MouseButtonPress) ) // FIXME, which one?
+ {
+ TQMouseEvent *mev = (TQMouseEvent*)e;
+
+ TQPoint pt;
+ KAction *_a;
+
+ // FIXME, see how this holds up on an empty toolbar
+ _a = handleToolbarMouseButton( mev->pos(), dptr()->m_actions, m_pManager, pt );
+ if (_a && mev->button() == Qt::RightButton)
+ {
+ dptr()->m_highlightedAddress = _a->property("address").toString();
+ KBookmark bookmark = m_pManager->findByAddress( dptr()->m_highlightedAddress );
+ RMB::begin_rmb_action(this);
+ KPopupMenu *pm = new KPopupMenu;
+ rmbSelf(this)->fillContextMenu( pm, dptr()->m_highlightedAddress, 0 );
+ emit aboutToShowContextMenu( rmbSelf(this)->atAddress( dptr()->m_highlightedAddress ), pm );
+ rmbSelf(this)->fillContextMenu2( pm, dptr()->m_highlightedAddress, 0 );
+ pm->popup( pt );
+ mev->accept();
+ }
+
+ return !!_a; // ignore the event if we didn't find the button
+ }
+ else if ( e->type() == TQEvent::DragLeave )
+ {
+ removeTempSep(dptr());
+ dptr()->m_dropAddress = TQString::null;
+ }
+ else if ( e->type() == TQEvent::Drop )
+ {
+ removeTempSep(dptr());
+ TQDropEvent *dev = (TQDropEvent*)e;
+ if ( !KBookmarkDrag::canDecode( dev ) )
+ return false;
+ TQValueList<KBookmark> list = KBookmarkDrag::decode( dev );
+ if (list.count() > 1)
+ kdWarning(7043) << "Sorry, currently you can only drop one address "
+ "onto the bookmark bar!" << endl;
+ KBookmark toInsert = list.first();
+ KBookmark bookmark = m_pManager->findByAddress( dptr()->m_dropAddress );
+ Q_ASSERT(!bookmark.isNull());
+ kdDebug(7043) << "inserting "
+ << TQString(dptr()->m_atFirst ? "before" : "after")
+ << " dptr()->m_dropAddress == " << dptr()->m_dropAddress << endl;
+ KBookmarkGroup parentBookmark = bookmark.parentGroup();
+ Q_ASSERT(!parentBookmark.isNull());
+ KBookmark newBookmark = parentBookmark.addBookmark(
+ m_pManager, toInsert.fullText(),
+ toInsert.url() );
+ parentBookmark.moveItem( newBookmark, dptr()->m_atFirst ? KBookmark() : bookmark );
+ m_pManager->emitChanged( parentBookmark );
+ return true;
+ }
+ else if ( e->type() == TQEvent::DragMove )
+ {
+ TQDragMoveEvent *dme = (TQDragMoveEvent*)e;
+ if (!KBookmarkDrag::canDecode( dme ))
+ return false;
+ bool _atFirst;
+ TQString dropAddress;
+ KToolBar *tb = (KToolBar*)o;
+ dropAddress = handleToolbarDragMoveEvent(dptr(), tb, dme->pos(), dptr()->m_actions, _atFirst, m_pManager);
+ if (!dropAddress.isNull())
+ {
+ dptr()->m_dropAddress = dropAddress;
+ dptr()->m_atFirst = _atFirst;
+ dme->accept();
+ }
+ }
+ return false;
+}
+
+static bool showInToolbar( const KBookmark &bk ) {
+ return (bk.internalElement().attributes().namedItem("showintoolbar").toAttr().value() == "yes");
+}
+
+void ToolbarFilter::visit( const KBookmark &bk ) {
+ //kdDebug() << "visit(" << bk.text() << ")" << endl;
+ if ( m_visible || showInToolbar(bk) )
+ KXBELBookmarkImporterImpl::visit(bk);
+}
+
+void ToolbarFilter::visitEnter( const KBookmarkGroup &grp ) {
+ //kdDebug() << "visitEnter(" << grp.text() << ")" << endl;
+ if ( !m_visible && showInToolbar(grp) )
+ {
+ m_visibleStart = grp;
+ m_visible = true;
+ }
+ if ( m_visible )
+ KXBELBookmarkImporterImpl::visitEnter(grp);
+}
+
+void ToolbarFilter::visitLeave( const KBookmarkGroup &grp ) {
+ //kdDebug() << "visitLeave()" << endl;
+ if ( m_visible )
+ KXBELBookmarkImporterImpl::visitLeave(grp);
+ if ( m_visible && grp.address() == m_visibleStart.address() )
+ m_visible = false;
+}
+
+#include "kbookmarkbar.moc"
diff --git a/kio/bookmarks/kbookmarkbar.h b/tdeio/bookmarks/kbookmarkbar.h
index 1f100d183..1f100d183 100644
--- a/kio/bookmarks/kbookmarkbar.h
+++ b/tdeio/bookmarks/kbookmarkbar.h
diff --git a/kio/bookmarks/kbookmarkdombuilder.cc b/tdeio/bookmarks/kbookmarkdombuilder.cc
index 5c0882d05..5c0882d05 100644
--- a/kio/bookmarks/kbookmarkdombuilder.cc
+++ b/tdeio/bookmarks/kbookmarkdombuilder.cc
diff --git a/kio/bookmarks/kbookmarkdombuilder.h b/tdeio/bookmarks/kbookmarkdombuilder.h
index 44fe7b170..44fe7b170 100644
--- a/kio/bookmarks/kbookmarkdombuilder.h
+++ b/tdeio/bookmarks/kbookmarkdombuilder.h
diff --git a/kio/bookmarks/kbookmarkdrag.cc b/tdeio/bookmarks/kbookmarkdrag.cc
index d13893eed..d13893eed 100644
--- a/kio/bookmarks/kbookmarkdrag.cc
+++ b/tdeio/bookmarks/kbookmarkdrag.cc
diff --git a/kio/bookmarks/kbookmarkdrag.h b/tdeio/bookmarks/kbookmarkdrag.h
index 016bd6849..016bd6849 100644
--- a/kio/bookmarks/kbookmarkdrag.h
+++ b/tdeio/bookmarks/kbookmarkdrag.h
diff --git a/kio/bookmarks/kbookmarkexporter.cc b/tdeio/bookmarks/kbookmarkexporter.cc
index 30c52bdb8..30c52bdb8 100644
--- a/kio/bookmarks/kbookmarkexporter.cc
+++ b/tdeio/bookmarks/kbookmarkexporter.cc
diff --git a/kio/bookmarks/kbookmarkexporter.h b/tdeio/bookmarks/kbookmarkexporter.h
index 68e8f475a..68e8f475a 100644
--- a/kio/bookmarks/kbookmarkexporter.h
+++ b/tdeio/bookmarks/kbookmarkexporter.h
diff --git a/tdeio/bookmarks/kbookmarkimporter.cc b/tdeio/bookmarks/kbookmarkimporter.cc
new file mode 100644
index 000000000..366802905
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkimporter.cc
@@ -0,0 +1,101 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE libraries
+ Copyright (C) 2003 Alexander Kellett <lypanov@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tdefiledialog.h>
+#include <kstringhandler.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <kcharsets.h>
+#include <tqtextcodec.h>
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <assert.h>
+
+#include "kbookmarkmanager.h"
+
+#include "kbookmarkimporter_ns.h"
+#include "kbookmarkimporter_opera.h"
+#include "kbookmarkimporter_ie.h"
+
+#include "kbookmarkimporter.h"
+
+void KXBELBookmarkImporterImpl::parse()
+{
+ //kdDebug() << "KXBELBookmarkImporterImpl::parse()" << endl;
+ KBookmarkManager *manager = KBookmarkManager::managerForFile(m_fileName);
+ KBookmarkGroup root = manager->root();
+ traverse(root);
+ // FIXME delete it!
+ // delete manager;
+}
+
+void KXBELBookmarkImporterImpl::visit(const KBookmark &bk)
+{
+ //kdDebug() << "KXBELBookmarkImporterImpl::visit" << endl;
+ if (bk.isSeparator())
+ emit newSeparator();
+ else
+ emit newBookmark(bk.fullText(), bk.url().url().utf8(), "");
+}
+
+void KXBELBookmarkImporterImpl::visitEnter(const KBookmarkGroup &grp)
+{
+ //kdDebug() << "KXBELBookmarkImporterImpl::visitEnter" << endl;
+ emit newFolder(grp.fullText(), false, "");
+}
+
+void KXBELBookmarkImporterImpl::visitLeave(const KBookmarkGroup &)
+{
+ //kdDebug() << "KXBELBookmarkImporterImpl::visitLeave" << endl;
+ emit endFolder();
+}
+
+void KBookmarkImporterBase::setupSignalForwards(TQObject *src, TQObject *dst)
+{
+ connect(src, TQT_SIGNAL( newBookmark( const TQString &, const TQCString &, const TQString & ) ),
+ dst, TQT_SIGNAL( newBookmark( const TQString &, const TQCString &, const TQString & ) ));
+ connect(src, TQT_SIGNAL( newFolder( const TQString &, bool, const TQString & ) ),
+ dst, TQT_SIGNAL( newFolder( const TQString &, bool, const TQString & ) ));
+ connect(src, TQT_SIGNAL( newSeparator() ),
+ dst, TQT_SIGNAL( newSeparator() ) );
+ connect(src, TQT_SIGNAL( endFolder() ),
+ dst, TQT_SIGNAL( endFolder() ) );
+}
+
+KBookmarkImporterBase* KBookmarkImporterBase::factory( const TQString &type )
+{
+ if (type == "netscape")
+ return new KNSBookmarkImporterImpl;
+ else if (type == "mozilla")
+ return new KMozillaBookmarkImporterImpl;
+ else if (type == "xbel")
+ return new KXBELBookmarkImporterImpl;
+ else if (type == "ie")
+ return new KIEBookmarkImporterImpl;
+ else if (type == "opera")
+ return new KOperaBookmarkImporterImpl;
+ else
+ return 0;
+}
+
+#include <kbookmarkimporter.moc>
diff --git a/kio/bookmarks/kbookmarkimporter.h b/tdeio/bookmarks/kbookmarkimporter.h
index cc87b2004..cc87b2004 100644
--- a/kio/bookmarks/kbookmarkimporter.h
+++ b/tdeio/bookmarks/kbookmarkimporter.h
diff --git a/tdeio/bookmarks/kbookmarkimporter_crash.cc b/tdeio/bookmarks/kbookmarkimporter_crash.cc
new file mode 100644
index 000000000..b2871eecd
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkimporter_crash.cc
@@ -0,0 +1,215 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE libraries
+ Copyright (C) 2002-2003 Alexander Kellett <lypanov@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kbookmarkimporter_crash.h"
+
+#include <tdefiledialog.h>
+#include <kstringhandler.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <kapplication.h>
+#include <kstandarddirs.h>
+#include <tqfile.h>
+#include <tqdir.h>
+#include <tqstring.h>
+#include <tqtextcodec.h>
+#include <dcopclient.h>
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <dirent.h>
+#include <sys/stat.h>
+
+typedef TQMap<TQString, TQString> ViewMap;
+
+// KDE 4.0: remove this BC keeping stub
+void KCrashBookmarkImporter::parseCrashLog( TQString /*filename*/, bool /*del*/ )
+{
+ ;
+}
+
+ViewMap KCrashBookmarkImporterImpl::parseCrashLog_noemit( const TQString & filename, bool del )
+{
+ static const int g_lineLimit = 16*1024;
+
+ TQFile f( filename );
+ ViewMap views;
+
+ if ( !f.open( IO_ReadOnly ) )
+ return views;
+
+ TQCString s( g_lineLimit );
+
+ TQTextCodec * codec = TQTextCodec::codecForName( "UTF-8" );
+ Q_ASSERT( codec );
+ if ( !codec )
+ return views;
+
+ while ( f.readLine( s.data(), g_lineLimit ) >=0 )
+ {
+ if ( s[s.length()-1] != '\n' )
+ {
+ kdWarning() << "Crash bookmarks contain a line longer than " << g_lineLimit << ". Skipping." << endl;
+ continue;
+ }
+ TQString t = codec->toUnicode( s.stripWhiteSpace() );
+ TQRegExp rx( "(.*)\\((.*)\\):(.*)$" );
+ rx.setMinimal( true );
+ if ( !rx.exactMatch( t ) )
+ continue;
+ if ( rx.cap(1) == "opened" )
+ views[rx.cap(2)] = rx.cap(3);
+ else if ( rx.cap(1) == "close" )
+ views.remove( rx.cap(2) );
+ }
+
+ f.close();
+
+ if ( del )
+ f.remove();
+
+ return views;
+}
+
+TQStringList KCrashBookmarkImporter::getCrashLogs()
+{
+ return KCrashBookmarkImporterImpl::getCrashLogs();
+}
+
+TQStringList KCrashBookmarkImporterImpl::getCrashLogs()
+{
+ TQMap<TQString, bool> activeLogs;
+
+ DCOPClient* dcop = kapp->dcopClient();
+
+ QCStringList apps = dcop->registeredApplications();
+ for ( QCStringList::Iterator it = apps.begin(); it != apps.end(); ++it )
+ {
+ TQCString &clientId = *it;
+
+ if ( tqstrncmp(clientId, "konqueror", 9) != 0 )
+ continue;
+
+ TQByteArray data, replyData;
+ TQCString replyType;
+ TQDataStream arg( data, IO_WriteOnly );
+
+ if ( !dcop->call( clientId.data(), "KonquerorIface",
+ "crashLogFile()", data, replyType, replyData) )
+ {
+ kdWarning() << "can't find dcop function KonquerorIface::crashLogFile()" << endl;
+ continue;
+ }
+
+ if ( replyType != "TQString" )
+ continue;
+
+ TQDataStream reply( replyData, IO_ReadOnly );
+ TQString ret;
+ reply >> ret;
+ activeLogs[ret] = true;
+ }
+
+ TQDir d( KCrashBookmarkImporterImpl().findDefaultLocation() );
+ d.setSorting( TQDir::Time );
+ d.setFilter( TQDir::Files );
+ d.setNameFilter( "konqueror-crash-*.log" );
+
+ const TQFileInfoList *list = d.entryInfoList();
+ TQFileInfoListIterator it( *list );
+
+ TQFileInfo *fi;
+ TQStringList crashFiles;
+
+ int count = 0;
+ for ( ; (( fi = it.current() ) != 0) && (count < 20); ++it, ++count )
+ {
+ bool stillAlive = activeLogs.contains( fi->absFilePath() );
+ if ( !stillAlive )
+ crashFiles << fi->absFilePath();
+ }
+ // Delete remaining ones
+ for ( ; ( fi = it.current() ) != 0; ++it )
+ {
+ TQFile::remove( fi->absFilePath() );
+ }
+
+ return crashFiles;
+}
+
+void KCrashBookmarkImporterImpl::parse()
+{
+ TQDict<bool> signatureMap;
+ TQStringList crashFiles = KCrashBookmarkImporterImpl::getCrashLogs();
+ int count = 1;
+ for ( TQStringList::Iterator it = crashFiles.begin(); it != crashFiles.end(); ++it )
+ {
+ ViewMap views;
+ views = parseCrashLog_noemit( *it, m_shouldDelete );
+ TQString signature;
+ for ( ViewMap::Iterator vit = views.begin(); vit != views.end(); ++vit )
+ signature += "|"+vit.data();
+ if (signatureMap[signature])
+ {
+ // Duplicate... throw away and skip
+ TQFile::remove(*it);
+ continue;
+ }
+
+ signatureMap.insert(signature, (bool *) true); // hack
+
+ int outerFolder = ( crashFiles.count() > 1 ) && (views.count() > 0);
+ if ( outerFolder )
+ emit newFolder( TQString("Konqueror Window %1").arg(count++), false, "" );
+ for ( ViewMap::Iterator vit = views.begin(); vit != views.end(); ++vit )
+ emit newBookmark( vit.data(), vit.data().latin1(), TQString("") );
+ if ( outerFolder )
+ emit endFolder();
+ }
+}
+
+TQString KCrashBookmarkImporter::crashBookmarksDir()
+{
+ static KCrashBookmarkImporterImpl *p = 0;
+ if (!p)
+ p = new KCrashBookmarkImporterImpl;
+ return p->findDefaultLocation();
+}
+
+void KCrashBookmarkImporterImpl::setShouldDelete( bool shouldDelete )
+{
+ m_shouldDelete = shouldDelete;
+}
+
+void KCrashBookmarkImporter::parseCrashBookmarks( bool del )
+{
+ KCrashBookmarkImporterImpl importer;
+ importer.setFilename( m_fileName );
+ importer.setShouldDelete( del );
+ importer.setupSignalForwards( &importer, this );
+ importer.parse();
+}
+
+TQString KCrashBookmarkImporterImpl::findDefaultLocation( bool ) const
+{
+ return locateLocal( "tmp", "" );
+}
+
+#include "kbookmarkimporter_crash.moc"
diff --git a/kio/bookmarks/kbookmarkimporter_crash.h b/tdeio/bookmarks/kbookmarkimporter_crash.h
index f4fc9af32..f4fc9af32 100644
--- a/kio/bookmarks/kbookmarkimporter_crash.h
+++ b/tdeio/bookmarks/kbookmarkimporter_crash.h
diff --git a/tdeio/bookmarks/kbookmarkimporter_ie.cc b/tdeio/bookmarks/kbookmarkimporter_ie.cc
new file mode 100644
index 000000000..092ebe596
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkimporter_ie.cc
@@ -0,0 +1,185 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE libraries
+ Copyright (C) 2002-2003 Alexander Kellett <lypanov@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tdefiledialog.h>
+#include <kstringhandler.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <tqtextcodec.h>
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <dirent.h>
+#include <sys/stat.h>
+
+#include "kbookmarkimporter.h"
+#include "kbookmarkimporter_ie.h"
+
+/* antlarr: KDE 4: Make them const TQString & */
+void KIEBookmarkImporter::parseIEBookmarks_url_file( TQString filename, TQString name ) {
+ static const int g_lineLimit = 16*1024;
+
+ TQFile f(filename);
+
+ if(f.open(IO_ReadOnly)) {
+
+ TQCString s(g_lineLimit);
+
+ while(f.readLine(s.data(), g_lineLimit)>=0) {
+ if ( s[s.length()-1] != '\n' ) // Gosh, this line is longer than g_lineLimit. Skipping.
+ {
+ kdWarning() << "IE bookmarks contain a line longer than " << g_lineLimit << ". Skipping." << endl;
+ continue;
+ }
+ TQCString t = s.stripWhiteSpace();
+ TQRegExp rx( "URL=(.*)" );
+ if (rx.exactMatch(t)) {
+ emit newBookmark( name, TQString(rx.cap(1)).latin1(), TQString("") );
+ }
+ }
+
+ f.close();
+ }
+}
+
+/* antlarr: KDE 4: Make them const TQString & */
+void KIEBookmarkImporter::parseIEBookmarks_dir( TQString dirname, TQString foldername )
+{
+
+ TQDir dir(dirname);
+ dir.setFilter( TQDir::Files | TQDir::Dirs );
+ dir.setSorting( TQDir::Name | TQDir::DirsFirst );
+ dir.setNameFilter("*.url"); // AK - possibly add ";index.ini" ?
+ dir.setMatchAllDirs(true);
+
+ const TQFileInfoList *list = dir.entryInfoList();
+ if (!list) return;
+
+ if (dirname != m_fileName)
+ emit newFolder( foldername, false, "" );
+
+ TQFileInfoListIterator it( *list );
+ TQFileInfo *fi;
+
+ while ( (fi = it.current()) != 0 ) {
+ ++it;
+
+ if (fi->fileName() == "." || fi->fileName() == "..") continue;
+
+ if (fi->isDir()) {
+ parseIEBookmarks_dir(fi->absFilePath(), fi->fileName());
+
+ } else if (fi->isFile()) {
+ if (fi->fileName().endsWith(".url")) {
+ TQString name = fi->fileName();
+ name.truncate(name.length() - 4); // .url
+ parseIEBookmarks_url_file(fi->absFilePath(), name);
+ }
+ // AK - add index.ini
+ }
+ }
+
+ if (dirname != m_fileName)
+ emit endFolder();
+}
+
+
+void KIEBookmarkImporter::parseIEBookmarks( )
+{
+ parseIEBookmarks_dir( m_fileName );
+}
+
+TQString KIEBookmarkImporter::IEBookmarksDir()
+{
+ static KIEBookmarkImporterImpl* p = 0;
+ if (!p)
+ p = new KIEBookmarkImporterImpl;
+ return p->findDefaultLocation();
+}
+
+void KIEBookmarkImporterImpl::parse() {
+ KIEBookmarkImporter importer(m_fileName);
+ setupSignalForwards(&importer, this);
+ importer.parseIEBookmarks();
+}
+
+TQString KIEBookmarkImporterImpl::findDefaultLocation(bool) const
+{
+ // notify user that they must give a new dir such
+ // as "Favourites" as otherwise it'll just place
+ // lots of .url files in the given dir and gui
+ // stuff in the exporter is ugly so that exclues
+ // the possibility of just writing to Favourites
+ // and checking if overwriting...
+ return KFileDialog::getExistingDirectory();
+}
+
+/////////////////////////////////////////////////
+
+class IEExporter : private KBookmarkGroupTraverser {
+public:
+ IEExporter( const TQString & );
+ void write( const KBookmarkGroup &grp ) { traverse(grp); };
+private:
+ virtual void visit( const KBookmark & );
+ virtual void visitEnter( const KBookmarkGroup & );
+ virtual void visitLeave( const KBookmarkGroup & );
+private:
+ TQDir m_currentDir;
+};
+
+static TQString ieStyleQuote( const TQString &str ) {
+ TQString s(str);
+ s.replace(TQRegExp("[/\\:*?\"<>|]"), "_");
+ return s;
+}
+
+IEExporter::IEExporter( const TQString & dname ) {
+ m_currentDir.setPath( dname );
+}
+
+void IEExporter::visit( const KBookmark &bk ) {
+ TQString fname = m_currentDir.path() + "/" + ieStyleQuote( bk.fullText() ) + ".url";
+ // kdDebug() << "visit(" << bk.text() << "), fname == " << fname << endl;
+ TQFile file( fname );
+ file.open( IO_WriteOnly );
+ TQTextStream ts( &file );
+ ts << "[InternetShortcut]\r\n";
+ ts << "URL=" << bk.url().url().utf8() << "\r\n";
+}
+
+void IEExporter::visitEnter( const KBookmarkGroup &grp ) {
+ TQString dname = m_currentDir.path() + "/" + ieStyleQuote( grp.fullText() );
+ // kdDebug() << "visitEnter(" << grp.text() << "), dname == " << dname << endl;
+ m_currentDir.mkdir( dname );
+ m_currentDir.cd( dname );
+}
+
+void IEExporter::visitLeave( const KBookmarkGroup & ) {
+ // kdDebug() << "visitLeave()" << endl;
+ m_currentDir.cdUp();
+}
+
+void KIEBookmarkExporterImpl::write(KBookmarkGroup parent) {
+ IEExporter exporter( m_fileName );
+ exporter.write( parent );
+}
+
+#include "kbookmarkimporter_ie.moc"
diff --git a/kio/bookmarks/kbookmarkimporter_ie.h b/tdeio/bookmarks/kbookmarkimporter_ie.h
index b1b7c651c..b1b7c651c 100644
--- a/kio/bookmarks/kbookmarkimporter_ie.h
+++ b/tdeio/bookmarks/kbookmarkimporter_ie.h
diff --git a/tdeio/bookmarks/kbookmarkimporter_kde1.cc b/tdeio/bookmarks/kbookmarkimporter_kde1.cc
new file mode 100644
index 000000000..6aca22b84
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkimporter_kde1.cc
@@ -0,0 +1,156 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kbookmarkimporter_kde1.h"
+#include <tdefiledialog.h>
+#include <kstringhandler.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <kcharsets.h>
+#include <tqtextcodec.h>
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <assert.h>
+
+////////////////////
+
+void KBookmarkImporter::import( const TQString & path )
+{
+ TQDomElement elem = m_pDoc->documentElement();
+ Q_ASSERT(!elem.isNull());
+ scanIntern( elem, path );
+}
+
+void KBookmarkImporter::scanIntern( TQDomElement & parentElem, const TQString & _path )
+{
+ kdDebug(7043) << "KBookmarkImporter::scanIntern " << _path << endl;
+ // Substitute all symbolic links in the path
+ TQDir dir( _path );
+ TQString canonical = dir.canonicalPath();
+
+ if ( m_lstParsedDirs.contains(canonical) )
+ {
+ kdWarning() << "Directory " << canonical << " already parsed" << endl;
+ return;
+ }
+
+ m_lstParsedDirs.append( canonical );
+
+ DIR *dp;
+ struct dirent *ep;
+ dp = opendir( TQFile::encodeName(_path) );
+ if ( dp == 0L )
+ return;
+
+ // Loop thru all directory entries
+ while ( ( ep = readdir( dp ) ) != 0L )
+ {
+ if ( strcmp( ep->d_name, "." ) != 0 && strcmp( ep->d_name, ".." ) != 0 )
+ {
+ KURL file;
+ file.setPath( TQString( _path ) + '/' + TQFile::decodeName(ep->d_name) );
+
+ KMimeType::Ptr res = KMimeType::findByURL( file, 0, true );
+ //kdDebug(7043) << " - " << file.url() << " -> " << res->name() << endl;
+
+ if ( res->name() == "inode/directory" )
+ {
+ // We could use KBookmarkGroup::createNewFolder, but then it
+ // would notify about the change, so we'd need a flag, etc.
+ TQDomElement groupElem = m_pDoc->createElement( "folder" );
+ parentElem.appendChild( groupElem );
+ TQDomElement textElem = m_pDoc->createElement( "title" );
+ groupElem.appendChild( textElem );
+ textElem.appendChild( m_pDoc->createTextNode( TDEIO::decodeFileName( ep->d_name ) ) );
+ if ( TDEIO::decodeFileName( ep->d_name ) == "Toolbar" )
+ groupElem.setAttribute("toolbar","yes");
+ scanIntern( groupElem, file.path() );
+ }
+ else if ( (res->name() == "application/x-desktop")
+ || (res->name() == "media/builtin-mydocuments")
+ || (res->name() == "media/builtin-mycomputer")
+ || (res->name() == "media/builtin-mynetworkplaces")
+ || (res->name() == "media/builtin-printers")
+ || (res->name() == "media/builtin-trash")
+ || (res->name() == "media/builtin-webbrowser") )
+ {
+ KSimpleConfig cfg( file.path(), true );
+ cfg.setDesktopGroup();
+ TQString type = cfg.readEntry( "Type" );
+ // Is it really a bookmark file ?
+ if ( type == "Link" )
+ parseBookmark( parentElem, ep->d_name, cfg, 0 /* desktop group */ );
+ else
+ kdWarning(7043) << " Not a link ? Type=" << type << endl;
+ }
+ else if ( res->name() == "text/plain")
+ {
+ // maybe its an IE Favourite..
+ KSimpleConfig cfg( file.path(), true );
+ TQStringList grp = cfg.groupList().grep( "internetshortcut", false );
+ if ( grp.count() == 0 )
+ continue;
+ cfg.setGroup( *grp.begin() );
+
+ TQString url = cfg.readPathEntry("URL");
+ if (!url.isEmpty() )
+ parseBookmark( parentElem, ep->d_name, cfg, *grp.begin() );
+ } else
+ kdWarning(7043) << "Invalid bookmark : found mimetype='" << res->name() << "' for file='" << file.path() << "'!" << endl;
+ }
+ }
+
+ closedir( dp );
+}
+
+void KBookmarkImporter::parseBookmark( TQDomElement & parentElem, TQCString _text,
+ KSimpleConfig& _cfg, const TQString &_group )
+{
+ if ( !_group.isEmpty() )
+ _cfg.setGroup( _group );
+ else
+ _cfg.setDesktopGroup();
+
+ TQString url = _cfg.readPathEntry( "URL" );
+ TQString icon = _cfg.readEntry( "Icon" );
+ if (icon.right( 4 ) == ".xpm" ) // prevent warnings
+ icon.truncate( icon.length() - 4 );
+
+ TQString text = TDEIO::decodeFileName( TQString::fromLocal8Bit(_text) );
+ if ( text.length() > 8 && text.right( 8 ) == ".desktop" )
+ text.truncate( text.length() - 8 );
+ if ( text.length() > 7 && text.right( 7 ) == ".kdelnk" )
+ text.truncate( text.length() - 7 );
+
+ TQDomElement elem = m_pDoc->createElement( "bookmark" );
+ parentElem.appendChild( elem );
+ elem.setAttribute( "href", url );
+ //if ( icon != "www" ) // No need to save the default
+ // Hmm, after all, it makes KBookmark::pixmapFile faster,
+ // and it shows a nice feature to those reading the file
+ elem.setAttribute( "icon", icon );
+ TQDomElement textElem = m_pDoc->createElement( "title" );
+ elem.appendChild( textElem );
+ textElem.appendChild( m_pDoc->createTextNode( text ) );
+ kdDebug(7043) << "KBookmarkImporter::parseBookmark text=" << text << endl;
+}
diff --git a/kio/bookmarks/kbookmarkimporter_kde1.h b/tdeio/bookmarks/kbookmarkimporter_kde1.h
index 5af4f04e9..5af4f04e9 100644
--- a/kio/bookmarks/kbookmarkimporter_kde1.h
+++ b/tdeio/bookmarks/kbookmarkimporter_kde1.h
diff --git a/tdeio/bookmarks/kbookmarkimporter_ns.cc b/tdeio/bookmarks/kbookmarkimporter_ns.cc
new file mode 100644
index 000000000..8ce06a79b
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkimporter_ns.cc
@@ -0,0 +1,243 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE libraries
+ Copyright (C) 1996-1998 Martin R. Jones <mjones@kde.org>
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ Copyright (C) 2003 Alexander Kellett <lypanov@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kbookmarkimporter.h"
+#include "kbookmarkexporter.h"
+#include "kbookmarkmanager.h"
+#include <tdefiledialog.h>
+#include <kstringhandler.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <kcharsets.h>
+#include <tqtextcodec.h>
+#include <tqstylesheet.h>
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <assert.h>
+
+void KNSBookmarkImporterImpl::parse()
+{
+ TQFile f(m_fileName);
+ TQTextCodec * codec = m_utf8 ? TQTextCodec::codecForName("UTF-8") : TQTextCodec::codecForLocale();
+ Q_ASSERT(codec);
+ if (!codec)
+ return;
+
+ if(f.open(IO_ReadOnly)) {
+
+ static const int g_lineLimit = 16*1024;
+ TQCString s(g_lineLimit);
+ // skip header
+ while(f.readLine(s.data(), g_lineLimit) >= 0 && !s.contains("<DL>"));
+
+ while(f.readLine(s.data(), g_lineLimit)>=0) {
+ if ( s[s.length()-1] != '\n' ) // Gosh, this line is longer than g_lineLimit. Skipping.
+ {
+ kdWarning() << "Netscape bookmarks contain a line longer than " << g_lineLimit << ". Skipping." << endl;
+ continue;
+ }
+ TQCString t = s.stripWhiteSpace();
+ if(t.left(12).upper() == "<DT><A HREF=" ||
+ t.left(16).upper() == "<DT><H3><A HREF=") {
+ int firstQuotes = t.find('"')+1;
+ int secondQuotes = t.find('"', firstQuotes);
+ if (firstQuotes != -1 && secondQuotes != -1)
+ {
+ TQCString link = t.mid(firstQuotes, secondQuotes-firstQuotes);
+ int endTag = t.find('>', secondQuotes+1);
+ TQCString name = t.mid(endTag+1);
+ name = name.left(name.findRev('<'));
+ if ( name.right(4) == "</A>" )
+ name = name.left( name.length() - 4 );
+ TQString qname = KCharsets::resolveEntities( codec->toUnicode( name ) );
+ TQCString additionalInfo = t.mid( secondQuotes+1, endTag-secondQuotes-1 );
+
+ emit newBookmark( qname,
+ link, codec->toUnicode(additionalInfo) );
+ }
+ }
+ else if(t.left(7).upper() == "<DT><H3") {
+ int endTag = t.find('>', 7);
+ TQCString name = t.mid(endTag+1);
+ name = name.left(name.findRev('<'));
+ TQString qname = KCharsets::resolveEntities( codec->toUnicode( name ) );
+ TQCString additionalInfo = t.mid( 8, endTag-8 );
+ bool folded = (additionalInfo.left(6) == "FOLDED");
+ if (folded) additionalInfo.remove(0,7);
+
+ emit newFolder( qname,
+ !folded,
+ codec->toUnicode(additionalInfo) );
+ }
+ else if(t.left(4).upper() == "<HR>")
+ emit newSeparator();
+ else if(t.left(8).upper() == "</DL><P>")
+ emit endFolder();
+ }
+
+ f.close();
+ }
+}
+
+TQString KNSBookmarkImporterImpl::findDefaultLocation(bool forSaving) const
+{
+ if (m_utf8)
+ {
+ if ( forSaving )
+ return KFileDialog::getSaveFileName( TQDir::homeDirPath() + "/.mozilla",
+ i18n("*.html|HTML Files (*.html)") );
+ else
+ return KFileDialog::getOpenFileName( TQDir::homeDirPath() + "/.mozilla",
+ i18n("*.html|HTML Files (*.html)") );
+ }
+ else
+ {
+ return TQDir::homeDirPath() + "/.netscape/bookmarks.html";
+ }
+}
+
+////////////////////////////////////////////////////////////////
+
+
+void KNSBookmarkImporter::parseNSBookmarks( bool utf8 )
+{
+ KNSBookmarkImporterImpl importer;
+ importer.setFilename(m_fileName);
+ importer.setUtf8(utf8);
+ importer.setupSignalForwards(&importer, this);
+ importer.parse();
+}
+
+TQString KNSBookmarkImporter::netscapeBookmarksFile( bool forSaving )
+{
+ static KNSBookmarkImporterImpl *p = 0;
+ if (!p)
+ {
+ p = new KNSBookmarkImporterImpl;
+ p->setUtf8(false);
+ }
+ return p->findDefaultLocation(forSaving);
+}
+
+TQString KNSBookmarkImporter::mozillaBookmarksFile( bool forSaving )
+{
+ static KNSBookmarkImporterImpl *p = 0;
+ if (!p)
+ {
+ p = new KNSBookmarkImporterImpl;
+ p->setUtf8(true);
+ }
+ return p->findDefaultLocation(forSaving);
+}
+
+
+////////////////////////////////////////////////////////////////
+// compat only
+////////////////////////////////////////////////////////////////
+
+void KNSBookmarkExporter::write(bool utf8) {
+ KNSBookmarkExporterImpl exporter(m_pManager, m_fileName);
+ exporter.setUtf8(utf8);
+ exporter.write(m_pManager->root());
+}
+
+void KNSBookmarkExporter::writeFolder(TQTextStream &/*stream*/, KBookmarkGroup /*gp*/) {
+ // TODO - requires a d pointer workaround hack?
+}
+
+////////////////////////////////////////////////////////////////
+
+void KNSBookmarkExporterImpl::setUtf8(bool utf8) {
+ m_utf8 = utf8;
+}
+
+void KNSBookmarkExporterImpl::write(KBookmarkGroup parent) {
+ if (TQFile::exists(m_fileName)) {
+ ::rename(
+ TQFile::encodeName(m_fileName),
+ TQFile::encodeName(m_fileName + ".beforekde"));
+ }
+
+ TQFile file(m_fileName);
+
+ if (!file.open(IO_WriteOnly)) {
+ kdError(7043) << "Can't write to file " << m_fileName << endl;
+ return;
+ }
+
+ TQTextStream fstream(&file);
+ fstream.setEncoding(m_utf8 ? TQTextStream::UnicodeUTF8 : TQTextStream::Locale);
+
+ TQString charset
+ = m_utf8 ? "UTF-8" : TQString::fromLatin1(TQTextCodec::codecForLocale()->name()).upper();
+
+ fstream << "<!DOCTYPE NETSCAPE-Bookmark-file-1>" << endl
+ << i18n("<!-- This file was generated by Konqueror -->") << endl
+ << "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset="
+ << charset << "\">" << endl
+ << "<TITLE>" << i18n("Bookmarks") << "</TITLE>" << endl
+ << "<H1>" << i18n("Bookmarks") << "</H1>" << endl
+ << "<DL><p>" << endl
+ << folderAsString(parent)
+ << "</DL><P>" << endl;
+}
+
+TQString KNSBookmarkExporterImpl::folderAsString(KBookmarkGroup parent) const {
+ TQString str;
+ TQTextStream fstream(&str, IO_WriteOnly);
+
+ for (KBookmark bk = parent.first(); !bk.isNull(); bk = parent.next(bk)) {
+ if (bk.isSeparator()) {
+ fstream << "<HR>" << endl;
+ continue;
+ }
+
+ TQString text = TQStyleSheet::escape(bk.fullText());
+
+ if (bk.isGroup() ) {
+ fstream << "<DT><H3 "
+ << (!bk.toGroup().isOpen() ? "FOLDED " : "")
+ << bk.internalElement().attribute("netscapeinfo") << ">"
+ << text << "</H3>" << endl
+ << "<DL><P>" << endl
+ << folderAsString(bk.toGroup())
+ << "</DL><P>" << endl;
+ continue;
+
+ } else {
+ // note - netscape seems to use local8bit for url...
+ fstream << "<DT><A HREF=\"" << bk.url().url() << "\""
+ << bk.internalElement().attribute("netscapeinfo") << ">"
+ << text << "</A>" << endl;
+ continue;
+ }
+ }
+
+ return str;
+}
+
+////
+
+#include "kbookmarkimporter_ns.moc"
diff --git a/kio/bookmarks/kbookmarkimporter_ns.h b/tdeio/bookmarks/kbookmarkimporter_ns.h
index 10844fc63..10844fc63 100644
--- a/kio/bookmarks/kbookmarkimporter_ns.h
+++ b/tdeio/bookmarks/kbookmarkimporter_ns.h
diff --git a/tdeio/bookmarks/kbookmarkimporter_opera.cc b/tdeio/bookmarks/kbookmarkimporter_opera.cc
new file mode 100644
index 000000000..57b5d6208
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkimporter_opera.cc
@@ -0,0 +1,170 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE libraries
+ Copyright (C) 2002-2003 Alexander Kellett <lypanov@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tdefiledialog.h>
+#include <kstringhandler.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <tqtextcodec.h>
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <dirent.h>
+#include <sys/stat.h>
+
+#include "kbookmarkimporter.h"
+#include "kbookmarkimporter_opera.h"
+
+void KOperaBookmarkImporter::parseOperaBookmarks( )
+{
+ TQFile file(m_fileName);
+ if(!file.open(IO_ReadOnly)) {
+ return;
+ }
+
+ TQTextCodec * codec = TQTextCodec::codecForName("UTF-8");
+ Q_ASSERT(codec);
+ if (!codec)
+ return;
+
+ int lineno = 0;
+ TQString url, name, type;
+ static const int g_lineLimit = 16*1024;
+ TQCString line(g_lineLimit);
+
+ while ( file.readLine(line.data(), g_lineLimit) >=0 ) {
+ lineno++;
+
+ // skip lines that didn't fit in buffer and first two headers lines
+ if ( line[line.length()-1] != '\n' || lineno <= 2 )
+ continue;
+
+ TQString currentLine = codec->toUnicode(line).stripWhiteSpace();
+
+ if (currentLine.isEmpty()) {
+ // end of data block
+ if (type.isNull())
+ continue;
+ else if ( type == "URL")
+ emit newBookmark( name, url.latin1(), "" );
+ else if (type == "FOLDER" )
+ emit newFolder( name, false, "" );
+
+ type = TQString::null;
+ name = TQString::null;
+ url = TQString::null;
+
+ } else if (currentLine == "-") {
+ // end of folder
+ emit endFolder();
+
+ } else {
+ // data block line
+ TQString tag;
+ if ( tag = "#", currentLine.startsWith( tag ) )
+ type = currentLine.remove( 0, tag.length() );
+ else if ( tag = "NAME=", currentLine.startsWith( tag ) )
+ name = currentLine.remove(0, tag.length());
+ else if ( tag = "URL=", currentLine.startsWith( tag ) )
+ url = currentLine.remove(0, tag.length());
+ }
+ }
+
+}
+
+TQString KOperaBookmarkImporter::operaBookmarksFile()
+{
+ static KOperaBookmarkImporterImpl *p = 0;
+ if (!p)
+ p = new KOperaBookmarkImporterImpl;
+ return p->findDefaultLocation();
+}
+
+void KOperaBookmarkImporterImpl::parse() {
+ KOperaBookmarkImporter importer(m_fileName);
+ setupSignalForwards(&importer, this);
+ importer.parseOperaBookmarks();
+}
+
+TQString KOperaBookmarkImporterImpl::findDefaultLocation(bool saving) const
+{
+ return saving ? KFileDialog::getSaveFileName(
+ TQDir::homeDirPath() + "/.opera",
+ i18n("*.adr|Opera Bookmark Files (*.adr)") )
+ : KFileDialog::getOpenFileName(
+ TQDir::homeDirPath() + "/.opera",
+ i18n("*.adr|Opera Bookmark Files (*.adr)") );
+}
+
+/////////////////////////////////////////////////
+
+class OperaExporter : private KBookmarkGroupTraverser {
+public:
+ OperaExporter();
+ TQString generate( const KBookmarkGroup &grp ) { traverse(grp); return m_string; };
+private:
+ virtual void visit( const KBookmark & );
+ virtual void visitEnter( const KBookmarkGroup & );
+ virtual void visitLeave( const KBookmarkGroup & );
+private:
+ TQString m_string;
+ TQTextStream m_out;
+};
+
+OperaExporter::OperaExporter() : m_out(&m_string, IO_WriteOnly) {
+ m_out << "Opera Hotlist version 2.0" << endl;
+ m_out << "Options: encoding = utf8, version=3" << endl;
+}
+
+void OperaExporter::visit( const KBookmark &bk ) {
+ // kdDebug() << "visit(" << bk.text() << ")" << endl;
+ m_out << "#URL" << endl;
+ m_out << "\tNAME=" << bk.fullText() << endl;
+ m_out << "\tURL=" << bk.url().url().utf8() << endl;
+ m_out << endl;
+}
+
+void OperaExporter::visitEnter( const KBookmarkGroup &grp ) {
+ // kdDebug() << "visitEnter(" << grp.text() << ")" << endl;
+ m_out << "#FOLDER" << endl;
+ m_out << "\tNAME="<< grp.fullText() << endl;
+ m_out << endl;
+}
+
+void OperaExporter::visitLeave( const KBookmarkGroup & ) {
+ // kdDebug() << "visitLeave()" << endl;
+ m_out << "-" << endl;
+ m_out << endl;
+}
+
+void KOperaBookmarkExporterImpl::write(KBookmarkGroup parent) {
+ OperaExporter exporter;
+ TQString content = exporter.generate( parent );
+ TQFile file(m_fileName);
+ if (!file.open(IO_WriteOnly)) {
+ kdError(7043) << "Can't write to file " << m_fileName << endl;
+ return;
+ }
+ TQTextStream fstream(&file);
+ fstream.setEncoding(TQTextStream::UnicodeUTF8);
+ fstream << content;
+}
+
+#include "kbookmarkimporter_opera.moc"
diff --git a/kio/bookmarks/kbookmarkimporter_opera.h b/tdeio/bookmarks/kbookmarkimporter_opera.h
index f6f1028b1..f6f1028b1 100644
--- a/kio/bookmarks/kbookmarkimporter_opera.h
+++ b/tdeio/bookmarks/kbookmarkimporter_opera.h
diff --git a/kio/bookmarks/kbookmarkmanager.cc b/tdeio/bookmarks/kbookmarkmanager.cc
index a87e0f20e..a87e0f20e 100644
--- a/kio/bookmarks/kbookmarkmanager.cc
+++ b/tdeio/bookmarks/kbookmarkmanager.cc
diff --git a/kio/bookmarks/kbookmarkmanager.h b/tdeio/bookmarks/kbookmarkmanager.h
index 4a129704a..4a129704a 100644
--- a/kio/bookmarks/kbookmarkmanager.h
+++ b/tdeio/bookmarks/kbookmarkmanager.h
diff --git a/tdeio/bookmarks/kbookmarkmenu.cc b/tdeio/bookmarks/kbookmarkmenu.cc
new file mode 100644
index 000000000..a4d88ae57
--- /dev/null
+++ b/tdeio/bookmarks/kbookmarkmenu.cc
@@ -0,0 +1,1187 @@
+// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
+// vim: set ts=4 sts=4 sw=4 et:
+/* This file is part of the KDE project
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kbookmarkmenu.h"
+#include "kbookmarkmenu_p.h"
+#include "kbookmarkimporter.h"
+#include "kbookmarkimporter_opera.h"
+#include "kbookmarkimporter_ie.h"
+#include "kbookmarkdrag.h"
+
+#include <kapplication.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <kdialogbase.h>
+#include <kiconloader.h>
+#include <klineedit.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kpopupmenu.h>
+#include <kstdaccel.h>
+#include <kstdaction.h>
+#include <kstringhandler.h>
+
+#include <tqclipboard.h>
+#include <tqfile.h>
+#include <tqheader.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqlineedit.h>
+#include <tqlistview.h>
+#include <tqpushbutton.h>
+
+#include <dptrtemplate.h>
+
+template class TQPtrList<KBookmarkMenu>;
+
+static TQString makeTextNodeMod(KBookmark bk, const TQString &m_nodename, const TQString &m_newText) {
+ TQDomNode subnode = bk.internalElement().namedItem(m_nodename);
+ if (subnode.isNull()) {
+ subnode = bk.internalElement().ownerDocument().createElement(m_nodename);
+ bk.internalElement().appendChild(subnode);
+ }
+
+ if (subnode.firstChild().isNull()) {
+ TQDomText domtext = subnode.ownerDocument().createTextNode("");
+ subnode.appendChild(domtext);
+ }
+
+ TQDomText domtext = subnode.firstChild().toText();
+
+ TQString m_oldText = domtext.data();
+ domtext.setData(m_newText);
+
+ return m_oldText;
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+KBookmarkMenu::KBookmarkMenu( KBookmarkManager* mgr,
+ KBookmarkOwner * _owner, KPopupMenu * _parentMenu,
+ KActionCollection *collec, bool _isRoot, bool _add,
+ const TQString & parentAddress )
+ : TQObject(),
+ m_bIsRoot(_isRoot), m_bAddBookmark(_add),
+ m_bAddShortcuts(true),
+ m_pManager(mgr), m_pOwner(_owner),
+ m_parentMenu( _parentMenu ),
+ m_actionCollection( collec ),
+ m_parentAddress( parentAddress )
+{
+ m_parentMenu->setKeyboardShortcutsEnabled( true );
+
+ m_lstSubMenus.setAutoDelete( true );
+ m_actions.setAutoDelete( true );
+
+ if (m_actionCollection)
+ {
+ m_actionCollection->setHighlightingEnabled(true);
+ disconnect( m_actionCollection, TQT_SIGNAL( actionHighlighted( KAction * ) ), 0, 0 );
+ connect( m_actionCollection, TQT_SIGNAL( actionHighlighted( KAction * ) ),
+ this, TQT_SLOT( slotActionHighlighted( KAction * ) ) );
+ }
+
+ m_bNSBookmark = m_parentAddress.isNull();
+ if ( !m_bNSBookmark ) // not for the netscape bookmark
+ {
+ //kdDebug(7043) << "KBookmarkMenu::KBookmarkMenu " << this << " address : " << m_parentAddress << endl;
+
+ connect( _parentMenu, TQT_SIGNAL( aboutToShow() ),
+ TQT_SLOT( slotAboutToShow() ) );
+
+ if ( KBookmarkSettings::self()->m_contextmenu )
+ {
+ (void) _parentMenu->contextMenu();
+ connect( _parentMenu, TQT_SIGNAL( aboutToShowContextMenu(KPopupMenu*, int, TQPopupMenu*) ),
+ this, TQT_SLOT( slotAboutToShowContextMenu(KPopupMenu*, int, TQPopupMenu*) ));
+ }
+
+ if ( m_bIsRoot )
+ {
+ connect( m_pManager, TQT_SIGNAL( changed(const TQString &, const TQString &) ),
+ TQT_SLOT( slotBookmarksChanged(const TQString &) ) );
+ }
+ }
+
+ // add entries that possibly have a shortcut, so they are available _before_ first popup
+ if ( m_bIsRoot )
+ {
+ if ( m_bAddBookmark )
+ {
+ addAddBookmark();
+ if ( extOwner() )
+ addAddBookmarksList(); // FIXME
+ }
+
+ addEditBookmarks();
+ }
+
+ m_bDirty = true;
+}
+
+KBookmarkMenu::~KBookmarkMenu()
+{
+ //kdDebug(7043) << "KBookmarkMenu::~KBookmarkMenu() " << this << endl;
+ TQPtrListIterator<KAction> it( m_actions );
+ for (; it.current(); ++it )
+ it.current()->unplugAll();
+
+ m_lstSubMenus.clear();
+ m_actions.clear();
+}
+
+void KBookmarkMenu::ensureUpToDate()
+{
+ slotAboutToShow();
+}
+
+void KBookmarkMenu::slotAboutToShow()
+{
+ // Did the bookmarks change since the last time we showed them ?
+ if ( m_bDirty )
+ {
+ m_bDirty = false;
+ refill();
+ }
+}
+
+TQString KBookmarkMenu::s_highlightedAddress;
+TQString KBookmarkMenu::s_highlightedImportType;
+TQString KBookmarkMenu::s_highlightedImportLocation;
+
+void KBookmarkMenu::slotActionHighlighted( KAction* action )
+{
+ if (action->isA("KBookmarkActionMenu") || action->isA("KBookmarkAction"))
+ {
+ s_highlightedAddress = action->property("address").toString();
+ //kdDebug() << "KBookmarkMenu::slotActionHighlighted" << s_highlightedAddress << endl;
+ }
+ else if (action->isA("KImportedBookmarksActionMenu"))
+ {
+ s_highlightedImportType = action->property("type").toString();
+ s_highlightedImportLocation = action->property("location").toString();
+ }
+ else
+ {
+ s_highlightedAddress = TQString::null;
+ s_highlightedImportType = TQString::null;
+ s_highlightedImportLocation = TQString::null;
+ }
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+class KBookmarkMenuRMBAssoc : public dPtrTemplate<KBookmarkMenu, RMB> { };
+template<> TQPtrDict<RMB>* dPtrTemplate<KBookmarkMenu, RMB>::d_ptr = 0;
+
+static RMB* rmbSelf(KBookmarkMenu *m) { return KBookmarkMenuRMBAssoc::d(m); }
+
+// TODO check via dcop before making any changes to the bookmarks file???
+
+void RMB::begin_rmb_action(KBookmarkMenu *self)
+{
+ RMB *s = rmbSelf(self);
+ s->recv = self;
+ s->m_parentAddress = self->m_parentAddress;
+ s->s_highlightedAddress = KBookmarkMenu::s_highlightedAddress;
+ s->m_pManager = self->m_pManager;
+ s->m_pOwner = self->m_pOwner;
+ s->m_parentMenu = self->m_parentMenu;
+}
+
+bool RMB::invalid( int val )
+{
+ bool valid = true;
+
+ if (val == 1)
+ s_highlightedAddress = m_parentAddress;
+
+ if (s_highlightedAddress.isNull())
+ valid = false;
+
+ return !valid;
+}
+
+KBookmark RMB::atAddress(const TQString & address)
+{
+ KBookmark bookmark = m_pManager->findByAddress( address );
+ Q_ASSERT(!bookmark.isNull());
+ return bookmark;
+}
+
+void KBookmarkMenu::slotAboutToShowContextMenu( KPopupMenu*, int, TQPopupMenu* contextMenu )
+{
+ //kdDebug(7043) << "KBookmarkMenu::slotAboutToShowContextMenu" << s_highlightedAddress << endl;
+ if (s_highlightedAddress.isNull())
+ {
+ KPopupMenu::contextMenuFocus()->hideContextMenu();
+ return;
+ }
+ contextMenu->clear();
+ fillContextMenu( contextMenu, s_highlightedAddress, 0 );
+}
+
+void RMB::fillContextMenu( TQPopupMenu* contextMenu, const TQString & address, int val )
+{
+ KBookmark bookmark = atAddress(address);
+
+ int id;
+
+ // binner:
+ // "Add Bookmark Here" when pointing at a bookmark looks strange and if you
+ // call it you have to close and reopen the menu to see an entry was added?
+ //
+ // TODO rename these, but, message freeze... umm...
+
+// if (bookmark.isGroup()) {
+ id = contextMenu->insertItem( SmallIcon("bookmark_add"), i18n( "Add Bookmark Here" ), recv, TQT_SLOT(slotRMBActionInsert(int)) );
+ contextMenu->setItemParameter( id, val );
+/* }
+ else
+ {
+ id = contextMenu->insertItem( SmallIcon("bookmark_add"), i18n( "Add Bookmark Here" ), recv, TQT_SLOT(slotRMBActionInsert(int)) );
+ contextMenu->setItemParameter( id, val );
+ }*/
+}
+
+void RMB::fillContextMenu2( TQPopupMenu* contextMenu, const TQString & address, int val )
+{
+ KBookmark bookmark = atAddress(address);
+
+ int id;
+
+ if (bookmark.isGroup()) {
+ id = contextMenu->insertItem( i18n( "Open Folder in Bookmark Editor" ), recv, TQT_SLOT(slotRMBActionEditAt(int)) );
+ contextMenu->setItemParameter( id, val );
+ contextMenu->insertSeparator();
+ id = contextMenu->insertItem( SmallIcon("editdelete"), i18n( "Delete Folder" ), recv, TQT_SLOT(slotRMBActionRemove(int)) );
+ contextMenu->setItemParameter( id, val );
+ contextMenu->insertSeparator();
+ id = contextMenu->insertItem( i18n( "Properties" ), recv, TQT_SLOT(slotRMBActionProperties(int)) );
+ contextMenu->setItemParameter( id, val );
+ }
+ else
+ {
+ id = contextMenu->insertItem( i18n( "Copy Link Address" ), recv, TQT_SLOT(slotRMBActionCopyLocation(int)) );
+ contextMenu->setItemParameter( id, val );
+ contextMenu->insertSeparator();
+ id = contextMenu->insertItem( SmallIcon("editdelete"), i18n( "Delete Bookmark" ), recv, TQT_SLOT(slotRMBActionRemove(int)) );
+ contextMenu->setItemParameter( id, val );
+ contextMenu->insertSeparator();
+ id = contextMenu->insertItem( i18n( "Properties" ), recv, TQT_SLOT(slotRMBActionProperties(int)) );
+ contextMenu->setItemParameter( id, val );
+ }
+}
+
+void RMB::slotRMBActionEditAt( int val )
+{
+ kdDebug(7043) << "KBookmarkMenu::slotRMBActionEditAt" << s_highlightedAddress << endl;
+ if (invalid(val)) { hidePopup(); return; }
+
+ KBookmark bookmark = atAddress(s_highlightedAddress);
+
+ m_pManager->slotEditBookmarksAtAddress( s_highlightedAddress );
+}
+
+void RMB::slotRMBActionProperties( int val )
+{
+ kdDebug(7043) << "KBookmarkMenu::slotRMBActionProperties" << s_highlightedAddress << endl;
+ if (invalid(val)) { hidePopup(); return; }
+
+ KBookmark bookmark = atAddress(s_highlightedAddress);
+
+ TQString folder = bookmark.isGroup() ? TQString::null : bookmark.url().pathOrURL();
+ KBookmarkEditDialog dlg( bookmark.fullText(), folder,
+ m_pManager, KBookmarkEditDialog::ModifyMode, 0,
+ 0, 0, i18n("Bookmark Properties") );
+ if ( dlg.exec() != KDialogBase::Accepted )
+ return;
+
+ makeTextNodeMod(bookmark, "title", dlg.finalTitle());
+ if ( !dlg.finalUrl().isNull() )
+ {
+ KURL u = KURL::fromPathOrURL(dlg.finalUrl());
+ bookmark.internalElement().setAttribute("href", u.url(0, 106));
+ }
+
+ kdDebug(7043) << "Requested move to " << dlg.finalAddress() << "!" << endl;
+
+ KBookmarkGroup parentBookmark = atAddress(m_parentAddress).toGroup();
+ m_pManager->emitChanged( parentBookmark );
+}
+
+void RMB::slotRMBActionInsert( int val )
+{
+ kdDebug(7043) << "KBookmarkMenu::slotRMBActionInsert" << s_highlightedAddress << endl;
+ if (invalid(val)) { hidePopup(); return; }
+
+ TQString url = m_pOwner->currentURL();
+ if (url.isEmpty())
+ {
+ KMessageBox::error( 0L, i18n("Cannot add bookmark with empty URL."));
+ return;
+ }
+ TQString title = m_pOwner->currentTitle();
+ if (title.isEmpty())
+ title = url;
+
+ KBookmark bookmark = atAddress( s_highlightedAddress );
+
+ // TODO use unique title
+
+ if (bookmark.isGroup())
+ {
+ KBookmarkGroup parentBookmark = bookmark.toGroup();
+ Q_ASSERT(!parentBookmark.isNull());
+ parentBookmark.addBookmark( m_pManager, title, KURL( url ) );
+ m_pManager->emitChanged( parentBookmark );
+ }
+ else
+ {
+ KBookmarkGroup parentBookmark = bookmark.parentGroup();
+ Q_ASSERT(!parentBookmark.isNull());
+ KBookmark newBookmark = parentBookmark.addBookmark( m_pManager, title, KURL( url ) );
+ parentBookmark.moveItem( newBookmark, parentBookmark.previous(bookmark) );
+ m_pManager->emitChanged( parentBookmark );
+ }
+}
+
+void RMB::slotRMBActionRemove( int val )
+{
+ //kdDebug(7043) << "KBookmarkMenu::slotRMBActionRemove" << s_highlightedAddress << endl;
+ if (invalid(val)) { hidePopup(); return; }
+
+ KBookmark bookmark = atAddress( s_highlightedAddress );
+ bool folder = bookmark.isGroup();
+
+ if (KMessageBox::warningContinueCancel(
+ m_parentMenu,
+ folder ? i18n("Are you sure you wish to remove the bookmark folder\n\"%1\"?").arg(bookmark.text())
+ : i18n("Are you sure you wish to remove the bookmark\n\"%1\"?").arg(bookmark.text()),
+ folder ? i18n("Bookmark Folder Deletion")
+ : i18n("Bookmark Deletion"),
+ KStdGuiItem::del())
+ != KMessageBox::Continue
+ )
+ return;
+
+ KBookmarkGroup parentBookmark = atAddress( m_parentAddress ).toGroup();
+ parentBookmark.deleteBookmark( bookmark );
+ m_pManager->emitChanged( parentBookmark );
+ if (m_parentMenu)
+ m_parentMenu->hide();
+}
+
+void RMB::slotRMBActionCopyLocation( int val )
+{
+ //kdDebug(7043) << "KBookmarkMenu::slotRMBActionCopyLocation" << s_highlightedAddress << endl;
+ if (invalid(val)) { hidePopup(); return; }
+
+ KBookmark bookmark = atAddress( s_highlightedAddress );
+
+ if ( !bookmark.isGroup() )
+ {
+ kapp->clipboard()->setData( KBookmarkDrag::newDrag(bookmark, 0),
+ TQClipboard::Selection );
+ kapp->clipboard()->setData( KBookmarkDrag::newDrag(bookmark, 0),
+ TQClipboard::Clipboard );
+ }
+}
+
+void RMB::hidePopup() {
+ KPopupMenu::contextMenuFocus()->hideContextMenu();
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+void KBookmarkMenu::fillContextMenu( TQPopupMenu* contextMenu, const TQString & address, int val )
+{
+ RMB::begin_rmb_action(this);
+ rmbSelf(this)->fillContextMenu(contextMenu, address, val);
+ emit aboutToShowContextMenu( rmbSelf(this)->atAddress(address), contextMenu);
+ rmbSelf(this)->fillContextMenu2(contextMenu, address, val);
+}
+
+void KBookmarkMenu::slotRMBActionEditAt( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionEditAt( val ); }
+
+void KBookmarkMenu::slotRMBActionProperties( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionProperties( val ); }
+
+void KBookmarkMenu::slotRMBActionInsert( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionInsert( val ); }
+
+void KBookmarkMenu::slotRMBActionRemove( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionRemove( val ); }
+
+void KBookmarkMenu::slotRMBActionCopyLocation( int val )
+{ RMB::begin_rmb_action(this); rmbSelf(this)->slotRMBActionCopyLocation( val ); }
+
+void KBookmarkMenu::slotBookmarksChanged( const TQString & groupAddress )
+{
+ if (m_bNSBookmark)
+ return;
+
+ if ( groupAddress == m_parentAddress )
+ {
+ //kdDebug(7043) << "KBookmarkMenu::slotBookmarksChanged -> setting m_bDirty on " << groupAddress << endl;
+ m_bDirty = true;
+ }
+ else
+ {
+ // Iterate recursively into child menus
+ TQPtrListIterator<KBookmarkMenu> it( m_lstSubMenus );
+ for (; it.current(); ++it )
+ {
+ it.current()->slotBookmarksChanged( groupAddress );
+ }
+ }
+}
+
+void KBookmarkMenu::refill()
+{
+ //kdDebug(7043) << "KBookmarkMenu::refill()" << endl;
+ m_lstSubMenus.clear();
+
+ TQPtrListIterator<KAction> it( m_actions );
+ for (; it.current(); ++it )
+ it.current()->unplug( m_parentMenu );
+
+ m_parentMenu->clear();
+ m_actions.clear();
+
+ fillBookmarkMenu();
+ m_parentMenu->adjustSize();
+}
+
+void KBookmarkMenu::addAddBookmarksList()
+{
+ if (!kapp->authorizeKAction("bookmarks"))
+ return;
+
+ TQString title = i18n( "Bookmark Tabs as Folder..." );
+
+ KAction * paAddBookmarksList = new KAction( title,
+ "bookmarks_list_add",
+ 0,
+ this,
+ TQT_SLOT( slotAddBookmarksList() ),
+ m_actionCollection, m_bIsRoot ? "add_bookmarks_list" : 0 );
+
+ paAddBookmarksList->setToolTip( i18n( "Add a folder of bookmarks for all open tabs." ) );
+
+ paAddBookmarksList->plug( m_parentMenu );
+ m_actions.append( paAddBookmarksList );
+}
+
+void KBookmarkMenu::addAddBookmark()
+{
+ if (!kapp->authorizeKAction("bookmarks"))
+ return;
+
+ TQString title = i18n( "Add Bookmark" );
+
+ KAction * paAddBookmarks = new KAction( title,
+ "bookmark_add",
+ m_bIsRoot && m_bAddShortcuts ? KStdAccel::addBookmark() : KShortcut(),
+ this,
+ TQT_SLOT( slotAddBookmark() ),
+ m_actionCollection, m_bIsRoot ? "add_bookmark" : 0 );
+
+ paAddBookmarks->setToolTip( i18n( "Add a bookmark for the current document" ) );
+
+ paAddBookmarks->plug( m_parentMenu );
+ m_actions.append( paAddBookmarks );
+}
+
+void KBookmarkMenu::addEditBookmarks()
+{
+ if (!kapp->authorizeKAction("bookmarks"))
+ return;
+
+ KAction * m_paEditBookmarks = KStdAction::editBookmarks( m_pManager, TQT_SLOT( slotEditBookmarks() ),
+ m_actionCollection, "edit_bookmarks" );
+ m_paEditBookmarks->plug( m_parentMenu );
+ m_paEditBookmarks->setToolTip( i18n( "Edit your bookmark collection in a separate window" ) );
+ m_actions.append( m_paEditBookmarks );
+}
+
+void KBookmarkMenu::addNewFolder()
+{
+ if (!kapp->authorizeKAction("bookmarks"))
+ return;
+
+ TQString title = i18n( "&New Bookmark Folder..." );
+ int p;
+ while ( ( p = title.find( '&' ) ) >= 0 )
+ title.remove( p, 1 );
+
+ KAction * paNewFolder = new KAction( title,
+ "folder_new", //"folder",
+ 0,
+ this,
+ TQT_SLOT( slotNewFolder() ),
+ m_actionCollection );
+
+ paNewFolder->setToolTip( i18n( "Create a new bookmark folder in this menu" ) );
+
+ paNewFolder->plug( m_parentMenu );
+ m_actions.append( paNewFolder );
+}
+
+void KBookmarkMenu::fillBookmarkMenu()
+{
+ if (!kapp->authorizeKAction("bookmarks"))
+ return;
+
+ if ( m_bIsRoot )
+ {
+ if ( m_bAddBookmark )
+ {
+ addAddBookmark();
+ if ( extOwner() )
+ addAddBookmarksList(); // FIXME
+ }
+
+ addEditBookmarks();
+
+ if ( m_bAddBookmark && !KBookmarkSettings::self()->m_advancedaddbookmark )
+ addNewFolder();
+ }
+
+ if ( m_bIsRoot
+ && KBookmarkManager::userBookmarksFile() == m_pManager->path() )
+ {
+ bool haveSep = false;
+
+ TQValueList<TQString> keys = KBookmarkMenu::dynamicBookmarksList();
+ TQValueList<TQString>::const_iterator it;
+ for ( it = keys.begin(); it != keys.end(); ++it )
+ {
+ DynMenuInfo info;
+ info = showDynamicBookmarks((*it));
+
+ if ( !info.show || !TQFile::exists( info.location ) )
+ continue;
+
+ if (!haveSep)
+ {
+ m_parentMenu->insertSeparator();
+ haveSep = true;
+ }
+
+ KActionMenu * actionMenu;
+ actionMenu = new KImportedBookmarksActionMenu(
+ info.name, info.type,
+ m_actionCollection, "kbookmarkmenu" );
+
+ actionMenu->setProperty( "type", info.type );
+ actionMenu->setProperty( "location", info.location );
+
+ actionMenu->plug( m_parentMenu );
+ m_actions.append( actionMenu );
+
+ KBookmarkMenu *subMenu =
+ new KBookmarkMenu( m_pManager, m_pOwner, actionMenu->popupMenu(),
+ m_actionCollection, false,
+ m_bAddBookmark, TQString::null );
+ connect( subMenu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ),
+ this, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ));
+ m_lstSubMenus.append(subMenu);
+
+ connect(actionMenu->popupMenu(), TQT_SIGNAL(aboutToShow()), subMenu, TQT_SLOT(slotNSLoad()));
+ }
+ }
+
+ KBookmarkGroup parentBookmark = m_pManager->findByAddress( m_parentAddress ).toGroup();
+ Q_ASSERT(!parentBookmark.isNull());
+ bool separatorInserted = false;
+ for ( KBookmark bm = parentBookmark.first(); !bm.isNull(); bm = parentBookmark.next(bm) )
+ {
+ TQString text = KStringHandler::csqueeze(bm.fullText(), 60);
+ text.replace( '&', "&&" );
+ if ( !separatorInserted && m_bIsRoot) {
+ // inserted before the first konq bookmark, to avoid the separator if no konq bookmark
+ m_parentMenu->insertSeparator();
+ separatorInserted = true;
+ }
+ if ( !bm.isGroup() )
+ {
+ if ( bm.isSeparator() )
+ {
+ m_parentMenu->insertSeparator();
+ }
+ else
+ {
+ //kdDebug(7043) << "Creating URL bookmark menu item for " << bm.text() << endl;
+ KAction * action = new KBookmarkAction( text, bm.icon(), 0, m_actionCollection, 0 );
+ connect(action, TQT_SIGNAL( activated ( KAction::ActivationReason, TQt::ButtonState )),
+ this, TQT_SLOT( slotBookmarkSelected( KAction::ActivationReason, TQt::ButtonState ) ));
+
+ action->setProperty( "url", bm.url().url() );
+ action->setProperty( "address", bm.address() );
+
+ action->setToolTip( bm.url().pathOrURL() );
+
+ action->plug( m_parentMenu );
+ m_actions.append( action );
+ }
+ }
+ else
+ {
+ //kdDebug(7043) << "Creating bookmark submenu named " << bm.text() << endl;
+ KActionMenu * actionMenu = new KBookmarkActionMenu( text, bm.icon(),
+ m_actionCollection,
+ "kbookmarkmenu" );
+ actionMenu->setProperty( "address", bm.address() );
+ actionMenu->plug( m_parentMenu );
+ m_actions.append( actionMenu );
+
+ KBookmarkMenu *subMenu = new KBookmarkMenu( m_pManager, m_pOwner, actionMenu->popupMenu(),
+ m_actionCollection, false,
+ m_bAddBookmark,
+ bm.address() );
+
+ connect(subMenu, TQT_SIGNAL( aboutToShowContextMenu( const KBookmark &, TQPopupMenu * ) ),
+ this, TQT_SIGNAL( aboutToShowContextMenu( const KBookmark &, TQPopupMenu * ) ));
+ connect(subMenu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ),
+ this, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ));
+ m_lstSubMenus.append( subMenu );
+ }
+ }
+
+ if ( !m_bIsRoot && m_bAddBookmark )
+ {
+ if ( m_parentMenu->count() > 0 )
+ m_parentMenu->insertSeparator();
+
+ if ( KBookmarkSettings::self()->m_quickactions )
+ {
+ KActionMenu * actionMenu = new KActionMenu( i18n("Quick Actions"), m_actionCollection, 0L );
+ fillContextMenu( actionMenu->popupMenu(), m_parentAddress, 1 );
+ actionMenu->plug( m_parentMenu );
+ m_actions.append( actionMenu );
+ }
+ else
+ {
+ addAddBookmark();
+ if ( extOwner() )
+ addAddBookmarksList(); // FIXME
+ addNewFolder();
+ }
+ }
+}
+
+void KBookmarkMenu::slotAddBookmarksList()
+{
+ KExtendedBookmarkOwner *extOwner = dynamic_cast<KExtendedBookmarkOwner*>(m_pOwner);
+ if (!extOwner)
+ {
+ kdWarning() << "erm, sorry ;-)" << endl;
+ return;
+ }
+
+ KExtendedBookmarkOwner::QStringPairList list;
+ extOwner->fillBookmarksList( list );
+
+ KBookmarkGroup parentBookmark = m_pManager->findByAddress( m_parentAddress ).toGroup();
+ Q_ASSERT(!parentBookmark.isNull());
+ KBookmarkGroup group = parentBookmark.createNewFolder( m_pManager );
+ if ( group.isNull() )
+ return; // user canceled i guess
+
+ KExtendedBookmarkOwner::QStringPairList::const_iterator it;
+ for ( it = list.begin(); it != list.end(); ++it )
+ group.addBookmark( m_pManager, (*it).first, KURL((*it).second) );
+
+ m_pManager->emitChanged( parentBookmark );
+}
+
+
+void KBookmarkMenu::slotAddBookmark()
+{
+ KBookmarkGroup parentBookmark;
+ parentBookmark = m_pManager->addBookmarkDialog(m_pOwner->currentURL(), m_pOwner->currentTitle(), m_parentAddress);
+ if (!parentBookmark.isNull())
+ m_pManager->emitChanged( parentBookmark );
+}
+
+void KBookmarkMenu::slotNewFolder()
+{
+ if ( !m_pOwner ) return; // this view doesn't handle bookmarks...
+ KBookmarkGroup parentBookmark = m_pManager->findByAddress( m_parentAddress ).toGroup();
+ Q_ASSERT(!parentBookmark.isNull());
+ KBookmarkGroup group = parentBookmark.createNewFolder( m_pManager );
+ if ( !group.isNull() )
+ {
+ KBookmarkGroup parentGroup = group.parentGroup();
+ m_pManager->emitChanged( parentGroup );
+ }
+}
+
+void KBookmarkMenu::slotBookmarkSelected( KAction::ActivationReason /*reason*/, TQt::ButtonState state )
+{
+ kdDebug(7043) << "KBookmarkMenu::slotBookmarkSelected()" << endl;
+ if ( !m_pOwner ) return; // this view doesn't handle bookmarks...
+ const KAction* action = dynamic_cast<const KAction *>(sender());
+ if(action)
+ {
+ const TQString& url = sender()->property("url").toString();
+ m_pOwner->openBookmarkURL( url );
+ emit openBookmark( url, state );
+ }
+}
+
+void KBookmarkMenu::slotBookmarkSelected()
+{
+ slotBookmarkSelected(KAction::PopupMenuActivation, Qt::NoButton);
+}
+
+KExtendedBookmarkOwner* KBookmarkMenu::extOwner()
+{
+ return dynamic_cast<KExtendedBookmarkOwner*>(m_pOwner);
+}
+
+void KBookmarkMenu::slotNSLoad()
+{
+ // only fill menu once
+ m_parentMenu->disconnect(TQT_SIGNAL(aboutToShow()));
+
+ // not NSImporter, but kept old name for BC reasons
+ KBookmarkMenuNSImporter importer( m_pManager, this, m_actionCollection );
+ importer.openBookmarks(s_highlightedImportLocation, s_highlightedImportType);
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+KBookmarkEditFields::KBookmarkEditFields(TQWidget *main, TQBoxLayout *vbox, FieldsSet fieldsSet)
+{
+ bool isF = (fieldsSet != FolderFieldsSet);
+
+ TQGridLayout *grid = new TQGridLayout( vbox, 2, isF ? 2 : 1 );
+
+ m_title = new KLineEdit( main );
+ grid->addWidget( m_title, 0, 1 );
+ grid->addWidget( new TQLabel( m_title, i18n( "Name:" ), main ), 0, 0 );
+ m_title->setFocus();
+ if (isF)
+ {
+ m_url = new KLineEdit( main );
+ grid->addWidget( m_url, 1, 1 );
+ grid->addWidget( new TQLabel( m_url, i18n( "Location:" ), main ), 1, 0 );
+ }
+ else
+ {
+ m_url = 0;
+ }
+
+ main->setMinimumSize( 300, 0 );
+}
+
+void KBookmarkEditFields::setName(const TQString &str)
+{
+ m_title->setText(str);
+}
+
+void KBookmarkEditFields::setLocation(const TQString &str)
+{
+ m_url->setText(str);
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+// TODO - make the dialog use Properties as a title when in Modify mode... (dirk noticed the bug...)
+KBookmarkEditDialog::KBookmarkEditDialog(const TQString& title, const TQString& url, KBookmarkManager * mgr, BookmarkEditType editType, const TQString& address,
+ TQWidget * parent, const char * name, const TQString& caption )
+ : KDialogBase(parent, name, true, caption,
+ (editType == InsertionMode) ? (User1|Ok|Cancel) : (Ok|Cancel),
+ Ok, false, KGuiItem()),
+ m_folderTree(0), m_mgr(mgr), m_editType(editType), m_address(address)
+{
+ setButtonOK( (editType == InsertionMode) ? KGuiItem( i18n( "&Add" ), "bookmark_add") : i18n( "&Update" ) );
+ if (editType == InsertionMode) {
+ setButtonGuiItem( User1, KGuiItem( i18n( "&New Folder..." ), "folder_new") );
+ }
+
+ bool folder = url.isNull();
+
+ m_main = new TQWidget( this );
+ setMainWidget( m_main );
+
+ TQBoxLayout *vbox = new TQVBoxLayout( m_main, 0, spacingHint() );
+ KBookmarkEditFields::FieldsSet fs =
+ folder ? KBookmarkEditFields::FolderFieldsSet
+ : KBookmarkEditFields::BookmarkFieldsSet;
+ m_fields = new KBookmarkEditFields(m_main, vbox, fs);
+ m_fields->setName(title);
+ if ( !folder )
+ m_fields->setLocation(url);
+
+ if ( editType == InsertionMode )
+ {
+ m_folderTree = KBookmarkFolderTree::createTree( m_mgr, m_main, name, m_address );
+ connect( m_folderTree, TQT_SIGNAL( doubleClicked(TQListViewItem*) ),
+ this, TQT_SLOT( slotDoubleClicked(TQListViewItem*) ) );
+ vbox->addWidget( m_folderTree );
+ connect( this, TQT_SIGNAL( user1Clicked() ), TQT_SLOT( slotUser1() ) );
+ }
+}
+
+void KBookmarkEditDialog::slotDoubleClicked( TQListViewItem* item )
+{
+ Q_ASSERT( m_folderTree );
+ m_folderTree->setCurrentItem( item );
+ accept();
+}
+
+void KBookmarkEditDialog::slotOk()
+{
+ accept();
+}
+
+void KBookmarkEditDialog::slotCancel()
+{
+ reject();
+}
+
+TQString KBookmarkEditDialog::finalAddress() const
+{
+ Q_ASSERT( m_folderTree );
+ return KBookmarkFolderTree::selectedAddress( m_folderTree );
+}
+
+TQString KBookmarkEditDialog::finalUrl() const
+{
+ return m_fields->m_url ? m_fields->m_url->text() : TQString::null;
+}
+
+TQString KBookmarkEditDialog::finalTitle() const
+{
+ return m_fields->m_title ? m_fields->m_title->text() : TQString::null;
+}
+
+void KBookmarkEditDialog::slotUser1()
+{
+ // kdDebug(7043) << "KBookmarkEditDialog::slotUser1" << endl;
+ Q_ASSERT( m_folderTree );
+
+ TQString address = KBookmarkFolderTree::selectedAddress( m_folderTree );
+ if ( address.isNull() ) return;
+ KBookmarkGroup bm = m_mgr->findByAddress( address ).toGroup();
+ Q_ASSERT(!bm.isNull());
+ Q_ASSERT(m_editType == InsertionMode);
+
+ KBookmarkGroup group = bm.createNewFolder( m_mgr );
+ if ( !group.isNull() )
+ {
+ KBookmarkGroup parentGroup = group.parentGroup();
+ m_mgr->emitChanged( parentGroup );
+ }
+ KBookmarkFolderTree::fillTree( m_folderTree, m_mgr );
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+static void fillGroup( TQListView* listview, KBookmarkFolderTreeItem * parentItem, KBookmarkGroup group, bool expandOpenGroups = true, const TQString& address = TQString::null )
+{
+ bool noSubGroups = true;
+ KBookmarkFolderTreeItem * lastItem = 0L;
+ KBookmarkFolderTreeItem * item = 0L;
+ for ( KBookmark bk = group.first() ; !bk.isNull() ; bk = group.next(bk) )
+ {
+ if ( bk.isGroup() )
+ {
+ KBookmarkGroup grp = bk.toGroup();
+ item = new KBookmarkFolderTreeItem( parentItem, lastItem, grp );
+ fillGroup( listview, item, grp, expandOpenGroups, address );
+ if ( expandOpenGroups && grp.isOpen() )
+ item->setOpen( true );
+ lastItem = item;
+ noSubGroups = false;
+ }
+ if (bk.address() == address) {
+ listview->setCurrentItem( lastItem );
+ listview->ensureItemVisible( item );
+ }
+ }
+ if ( noSubGroups ) {
+ parentItem->setOpen( true );
+ }
+}
+
+TQListView* KBookmarkFolderTree::createTree( KBookmarkManager* mgr, TQWidget* parent, const char* name, const TQString& address )
+{
+ TQListView *listview = new TQListView( parent, name );
+
+ listview->setRootIsDecorated( false );
+ listview->header()->hide();
+ listview->addColumn( i18n("Bookmark"), 200 );
+ listview->setSorting( -1, false );
+ listview->setSelectionMode( TQListView::Single );
+ listview->setAllColumnsShowFocus( true );
+ listview->setResizeMode( TQListView::AllColumns );
+ listview->setMinimumSize( 60, 100 );
+
+ fillTree( listview, mgr, address );
+
+ return listview;
+}
+
+void KBookmarkFolderTree::fillTree( TQListView *listview, KBookmarkManager* mgr, const TQString& address )
+{
+ listview->clear();
+
+ KBookmarkGroup root = mgr->root();
+ KBookmarkFolderTreeItem * rootItem = new KBookmarkFolderTreeItem( listview, root );
+ listview->setCurrentItem( rootItem );
+ rootItem->setSelected( true );
+ fillGroup( listview, rootItem, root, (address == root.groupAddress() || address.isNull()) ? true : false, address );
+ rootItem->setOpen( true );
+}
+
+static KBookmarkFolderTreeItem* ft_cast( TQListViewItem *i )
+{
+ return static_cast<KBookmarkFolderTreeItem*>( i );
+}
+
+TQString KBookmarkFolderTree::selectedAddress( TQListView *listview )
+{
+ if ( !listview)
+ return TQString::null;
+ KBookmarkFolderTreeItem *item = ft_cast( listview->currentItem() );
+ return item ? item->m_bookmark.address() : TQString::null;
+}
+
+void KBookmarkFolderTree::setAddress( TQListView *listview, const TQString & address )
+{
+ KBookmarkFolderTreeItem* it = ft_cast( listview->firstChild() );
+ while ( true ) {
+ kdDebug(7043) << it->m_bookmark.address() << endl;
+ it = ft_cast( it->itemBelow() );
+ if ( !it )
+ return;
+ if ( it->m_bookmark.address() == address )
+ break;
+ }
+ it->setSelected( true );
+ listview->setCurrentItem( it );
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+// toplevel item
+KBookmarkFolderTreeItem::KBookmarkFolderTreeItem( TQListView *parent, const KBookmark & gp )
+ : TQListViewItem(parent, i18n("Bookmarks")), m_bookmark(gp)
+{
+ setPixmap(0, SmallIcon("bookmark"));
+ setExpandable(true);
+}
+
+// group
+KBookmarkFolderTreeItem::KBookmarkFolderTreeItem( KBookmarkFolderTreeItem *parent, TQListViewItem *after, const KBookmarkGroup & gp )
+ : TQListViewItem(parent, after, gp.fullText()), m_bookmark(gp)
+{
+ setPixmap(0, SmallIcon( gp.icon() ) );
+ setExpandable(true);
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+// NOTE - KBookmarkMenuNSImporter is really === KBookmarkMenuImporter
+// i.e, it is _not_ ns specific. and in KDE4 it should be renamed.
+
+void KBookmarkMenuNSImporter::openNSBookmarks()
+{
+ openBookmarks( KNSBookmarkImporter::netscapeBookmarksFile(), "netscape" );
+}
+
+void KBookmarkMenuNSImporter::openBookmarks( const TQString &location, const TQString &type )
+{
+ mstack.push(m_menu);
+
+ KBookmarkImporterBase *importer = KBookmarkImporterBase::factory(type);
+ if (!importer)
+ return;
+ importer->setFilename(location);
+ connectToImporter(*importer);
+ importer->parse();
+
+ delete importer;
+}
+
+void KBookmarkMenuNSImporter::connectToImporter(const TQObject &importer)
+{
+ connect( &importer, TQT_SIGNAL( newBookmark( const TQString &, const TQCString &, const TQString & ) ),
+ TQT_SLOT( newBookmark( const TQString &, const TQCString &, const TQString & ) ) );
+ connect( &importer, TQT_SIGNAL( newFolder( const TQString &, bool, const TQString & ) ),
+ TQT_SLOT( newFolder( const TQString &, bool, const TQString & ) ) );
+ connect( &importer, TQT_SIGNAL( newSeparator() ), TQT_SLOT( newSeparator() ) );
+ connect( &importer, TQT_SIGNAL( endFolder() ), TQT_SLOT( endFolder() ) );
+}
+
+void KBookmarkMenuNSImporter::newBookmark( const TQString & text, const TQCString & url, const TQString & )
+{
+ TQString _text = KStringHandler::csqueeze(text);
+ _text.replace( '&', "&&" );
+ KAction * action = new KBookmarkAction(_text, "html", 0, 0, "", m_actionCollection, 0);
+ connect(action, TQT_SIGNAL( activated ( KAction::ActivationReason, TQt::ButtonState )),
+ m_menu, TQT_SLOT( slotBookmarkSelected( KAction::ActivationReason, TQt::ButtonState ) ));
+ action->setProperty( "url", url );
+ action->setToolTip( url );
+ action->plug( mstack.top()->m_parentMenu );
+ mstack.top()->m_actions.append( action );
+}
+
+void KBookmarkMenuNSImporter::newFolder( const TQString & text, bool, const TQString & )
+{
+ TQString _text = KStringHandler::csqueeze(text);
+ _text.replace( '&', "&&" );
+ KActionMenu * actionMenu = new KActionMenu( _text, "folder", m_actionCollection, 0L );
+ actionMenu->plug( mstack.top()->m_parentMenu );
+ mstack.top()->m_actions.append( actionMenu );
+ KBookmarkMenu *subMenu = new KBookmarkMenu( m_pManager, m_menu->m_pOwner, actionMenu->popupMenu(),
+ m_actionCollection, false,
+ m_menu->m_bAddBookmark, TQString::null );
+ connect( subMenu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ),
+ m_menu, TQT_SIGNAL( openBookmark( const TQString &, TQt::ButtonState ) ));
+ mstack.top()->m_lstSubMenus.append( subMenu );
+
+ mstack.push(subMenu);
+}
+
+void KBookmarkMenuNSImporter::newSeparator()
+{
+ mstack.top()->m_parentMenu->insertSeparator();
+}
+
+void KBookmarkMenuNSImporter::endFolder()
+{
+ mstack.pop();
+}
+
+/********************************************************************/
+/********************************************************************/
+/********************************************************************/
+
+KBookmarkMenu::DynMenuInfo KBookmarkMenu::showDynamicBookmarks( const TQString &id )
+{
+ TDEConfig config("kbookmarkrc", false, false);
+ config.setGroup("Bookmarks");
+
+ DynMenuInfo info;
+ info.show = false;
+
+ if (!config.hasKey("DynamicMenus")) {
+ // upgrade path
+ if (id == "netscape") {
+ KBookmarkManager *manager = KBookmarkManager::userBookmarksManager();
+ info.show = manager->root().internalElement().attribute("hide_nsbk") != "yes";
+ info.location = KNSBookmarkImporter::netscapeBookmarksFile();
+ info.type = "netscape";
+ info.name = i18n("Netscape Bookmarks");
+ } // else, no show
+
+ } else {
+ // have new version config
+ if (config.hasGroup("DynamicMenu-" + id)) {
+ config.setGroup("DynamicMenu-" + id);
+ info.show = config.readBoolEntry("Show");
+ info.location = config.readPathEntry("Location");
+ info.type = config.readEntry("Type");
+ info.name = config.readEntry("Name");
+ } // else, no show
+ }
+
+ return info;
+}
+
+TQStringList KBookmarkMenu::dynamicBookmarksList()
+{
+ TDEConfig config("kbookmarkrc", false, false);
+ config.setGroup("Bookmarks");
+
+ TQStringList mlist;
+ if (config.hasKey("DynamicMenus"))
+ mlist = config.readListEntry("DynamicMenus");
+ else
+ mlist << "netscape";
+
+ return mlist;
+}
+
+void KBookmarkMenu::setDynamicBookmarks(const TQString &id, const DynMenuInfo &newMenu)
+{
+ TDEConfig config("kbookmarkrc", false, false);
+
+ // add group unconditionally
+ config.setGroup("DynamicMenu-" + id);
+ config.writeEntry("Show", newMenu.show);
+ config.writePathEntry("Location", newMenu.location);
+ config.writeEntry("Type", newMenu.type);
+ config.writeEntry("Name", newMenu.name);
+
+ TQStringList elist;
+
+ config.setGroup("Bookmarks");
+ if (!config.hasKey("DynamicMenus")) {
+ if (newMenu.type != "netscape") {
+ // update from old xbel method to new rc method
+ // though only if not writing the netscape setting
+ config.setGroup("DynamicMenu-" "netscape");
+ DynMenuInfo xbelSetting;
+ xbelSetting = showDynamicBookmarks("netscape");
+ config.writeEntry("Show", xbelSetting.show);
+ config.writePathEntry("Location", xbelSetting.location);
+ config.writeEntry("Type", xbelSetting.type);
+ config.writeEntry("Name", xbelSetting.name);
+ }
+ } else {
+ elist = config.readListEntry("DynamicMenus");
+ }
+
+ // make sure list includes type
+ config.setGroup("Bookmarks");
+ if (elist.contains(id) < 1) {
+ elist << id;
+ config.writeEntry("DynamicMenus", elist);
+ }
+
+ config.sync();
+}
+
+#include "kbookmarkmenu.moc"
+#include "kbookmarkmenu_p.moc"
diff --git a/kio/bookmarks/kbookmarkmenu.h b/tdeio/bookmarks/kbookmarkmenu.h
index 35e6191e3..35e6191e3 100644
--- a/kio/bookmarks/kbookmarkmenu.h
+++ b/tdeio/bookmarks/kbookmarkmenu.h
diff --git a/kio/bookmarks/kbookmarkmenu_p.h b/tdeio/bookmarks/kbookmarkmenu_p.h
index cb88607fe..cb88607fe 100644
--- a/kio/bookmarks/kbookmarkmenu_p.h
+++ b/tdeio/bookmarks/kbookmarkmenu_p.h
diff --git a/kio/bookmarks/kbookmarknotifier.h b/tdeio/bookmarks/kbookmarknotifier.h
index f99e570bc..f99e570bc 100644
--- a/kio/bookmarks/kbookmarknotifier.h
+++ b/tdeio/bookmarks/kbookmarknotifier.h
diff --git a/tdeio/data.protocol b/tdeio/data.protocol
new file mode 100644
index 000000000..1982efe80
--- /dev/null
+++ b/tdeio/data.protocol
@@ -0,0 +1,71 @@
+[Protocol]
+protocol=data
+input=stream
+output=none
+reading=true
+Icon=www
+Class=:internet
+Description=A tdeioslave for data URIs (rfc2397)
+Description[af]= ´n tdeioslave vir data URIs (rfc2397)
+Description[be]=Модуль tdeioslave Ð´Ð»Ñ URI з даннÑмі (rfc2397)
+Description[br]=Ur tdeioslave evit an URIoù roadoù (rfc2397)
+Description[bs]=Kioslave za data URIs (rfc2397)
+Description[ca]=Un tdeioslave per a URIs de dades (rfc2397)
+Description[cs]=Kioslave pro datová URI (rfc2397)
+Description[csb]=Plugins protokółu pòdôwków URI (rfc2397)
+Description[da]=En tdeioslave for data-URI'er (rfc2397)
+Description[de]=Ein-/Ausgabemodul für Daten-URIs (rfc2397)
+Description[el]=Ένα tdeioslave για URI δεδομένων (rfc2397)
+Description[es]=Un tdeioslave para datos URIs (rfc2397)
+Description[et]=Andme-URI-de I/O-moodul (rfc2397)
+Description[eu]=Datuen URLen (rfc2397) tdeioslave-a
+Description[fa]=یک tdeioslave برای URIهای داده )rfc2397(
+Description[fi]=tdeioslave data URI:lle (rfc2397)
+Description[fr]=Un module d'entrée / sortie pour les URI de données (rfc2397)
+Description[fy]=In tdeioslave foar data-URI-adresse (rfc2397)
+Description[gl]=Un tdeioslave para URIs de dados (rfc2397)
+Description[hi]=डाटा यूआरआई (आरà¤à¤«à¤¸à¥€2397) के लिठà¤à¤• के-आई-ओ-सà¥à¤²à¥‡à¤µ
+Description[hr]=tdeioslave za podatkovne URI-ije (rfc2397)
+Description[hu]=KDE-protokoll adat-URI-k használataához (RFC 2397)
+Description[id]=Kioslave for URI data (rfc2397)
+Description[is]=tdeioslave fyrir gagnaslóðir (rfc2397)
+Description[it]=Un tdeioslave per il protocollo di URI di dati (rfc2397)
+Description[ja]=データ URIs (rfc2397) 㮠tdeioslave
+Description[ka]=URI მáƒáƒœáƒáƒªáƒ”მთრ(rfc2397) დáƒáƒ›áƒ›áƒ£áƒ¨áƒáƒ•áƒ”ბელი
+Description[kk]=URI деректерді өңдеу tdeioslave модулі (rfc2397)
+Description[km]=tdeioslave មួយ​សម្រាប់​ទិន្ននáŸáž™ URIs (rfc2397)
+Description[lb]=E tdeioslave fir Donnéen-URIs (rfc2397)
+Description[lt]=Antrinė KDE programa duomenų URI (rfc2397)
+Description[mk]=kio-Ñлужител за податочни URI (rfc2397)
+Description[ms]=Kioslave untuk URI data (rfc2397)
+Description[nb]=tdeioslave for data URI-er (rfc2397)
+Description[nds]=In-/Utgaavmoduul för Daten-URIs (rfc2397)
+Description[ne]=डेटा URIs का लागि किओसà¥à¤²à¥‡à¤­ (rfc2397)
+Description[nl]=Een tdeioslave voor data-URI-adressen (rfc2397)
+Description[nn]=A tdeioslave for data URI-ar (rfc2397)
+Description[pa]= ਡਾਟਾ URI ਲਈ tdeioslave(rfc2397)
+Description[pl]=Wtyczka protokołu URI danych (rfc2397)
+Description[pt]=Um 'tdeioslave' para URIs data (rfc2397)
+Description[pt_BR]=Uma implementação para o protocolo de URIs de dados (rfc2397)
+Description[ro]=Un dispozitiv de I/E pentru URI-urile de date (rfc2397)
+Description[ru]=Обработчик URI данных (rfc2397)
+Description[rw]=Kioslave y'ibyatanzwe URI (rfc2397)
+Description[se]=kiošláva dáhta-URI:aid várás (rfc2397)
+Description[sk]=IO klient pre dátové URI (rfc2397)
+Description[sl]=tdeioslave za podatkovne URI-je (rfc2397)
+Description[sr]=tdeioslave за URI-ије података (rfc2397)
+Description[sr@Latn]=tdeioslave za URI-ije podataka (rfc2397)
+Description[sv]=En I/O-slav för datawebbadresser (RFC 2397)
+Description[ta]=தரவ௠வலைமனைகளà¯à®•à¯à®•à®¾à®© ஒர௠tdeioslave (rfc2397)
+Description[te]=దతà±à°¤à°¾à°‚శం à°¯à±à°†à°°à±ˆà°² కొరకౠకెà°à°“బానిస (rfc2397)
+Description[tg]=tdeioslave барои URIs (rfc2397)
+Description[th]=tdeioslave สำหรับข้อมูล URIs (rfc2397)
+Description[tr]= Veri adresleri için bir tdeioslave (rfc2397)
+Description[tt]=Biremle URI öçen tdeioslave (rfc2397)
+Description[uk]=Підлеглий Ð’/Ð’ Ð´Ð»Ñ Ð°Ð´Ñ€ÐµÑ (URI) даних (rfc2397)
+Description[vi]=Một tdeioslave cho các địa điểm URI kiểu dữ liệu (rfc2397).
+Description[zh_CN]=data URI(rfc2397) çš„ tdeioslave
+DocPath=tdeioslave/data.html
+URIMode=rawuri
+defaultMimetype=application/octet-stream
+determineMimetypeFromExtension=false
diff --git a/tdeio/httpfilter/CMakeLists.txt b/tdeio/httpfilter/CMakeLists.txt
new file mode 100644
index 000000000..b40f10fdc
--- /dev/null
+++ b/tdeio/httpfilter/CMakeLists.txt
@@ -0,0 +1,32 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio
+)
+
+
+##### httpfilter ################################
+
+set( target httpfilter )
+
+set( ${target}_SRCS
+ httpfilter.cc
+)
+
+tde_add_library( ${target} STATIC_PIC AUTOMOC
+ SOURCES ${${target}_SRCS}
+)
diff --git a/kio/httpfilter/Makefile.am b/tdeio/httpfilter/Makefile.am
index 2da25d1b6..2da25d1b6 100644
--- a/kio/httpfilter/Makefile.am
+++ b/tdeio/httpfilter/Makefile.am
diff --git a/tdeio/httpfilter/httpfilter.cc b/tdeio/httpfilter/httpfilter.cc
new file mode 100644
index 000000000..21086d613
--- /dev/null
+++ b/tdeio/httpfilter/httpfilter.cc
@@ -0,0 +1,372 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (c) 2002 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tdeio/global.h>
+
+#include <klocale.h>
+
+#include "httpfilter.h"
+
+HTTPFilterBase::HTTPFilterBase()
+ : last(0)
+{
+}
+
+HTTPFilterBase::~HTTPFilterBase()
+{
+ delete last;
+}
+
+void
+HTTPFilterBase::chain(HTTPFilterBase *previous)
+{
+ last = previous;
+ connect(last, TQT_SIGNAL(output(const TQByteArray &)),
+ this, TQT_SLOT(slotInput(const TQByteArray &)));
+}
+
+HTTPFilterChain::HTTPFilterChain()
+ : first(0)
+{
+}
+
+void
+HTTPFilterChain::addFilter(HTTPFilterBase *filter)
+{
+ if (!last)
+ {
+ first = filter;
+ }
+ else
+ {
+ disconnect(last, TQT_SIGNAL(output(const TQByteArray &)), 0, 0);
+ filter->chain(last);
+ }
+ last = filter;
+ connect(filter, TQT_SIGNAL(output(const TQByteArray &)),
+ this, TQT_SIGNAL(output(const TQByteArray &)));
+ connect(filter, TQT_SIGNAL(error(int, const TQString &)),
+ this, TQT_SIGNAL(error(int, const TQString &)));
+}
+
+void
+HTTPFilterChain::slotInput(const TQByteArray &d)
+{
+ if (first)
+ first->slotInput(d);
+ else
+ emit output(d);
+}
+
+HTTPFilterMD5::HTTPFilterMD5()
+{
+}
+
+TQString
+HTTPFilterMD5::md5()
+{
+ return TQString::fromLatin1(context.base64Digest());
+}
+
+void
+HTTPFilterMD5::slotInput(const TQByteArray &d)
+{
+ context.update(d);
+ emit output(d);
+}
+
+
+HTTPFilterGZip::HTTPFilterGZip()
+{
+#ifdef DO_GZIP
+ bHasHeader = false;
+ bHasFinished = false;
+ bPlainText = false;
+ bEatTrailer = false;
+ bEof = false;
+ zstr.next_in = (Bytef *) Z_NULL;
+ zstr.avail_in = 0;
+ zstr.zalloc = Z_NULL;
+ zstr.zfree = Z_NULL;
+ zstr.opaque = Z_NULL;
+
+ inflateInit2(&zstr, -MAX_WBITS);
+
+ iTrailer = 8;
+#endif
+}
+
+HTTPFilterGZip::~HTTPFilterGZip()
+{
+#ifdef DO_GZIP
+ inflateEnd(&zstr);
+#endif
+
+}
+
+/* The get_byte() and checkHeader() functions are modified version from */
+/* the correpsonding functions that can be found in zlib, the following */
+/* copyright notice applies to these functions: */
+
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+ version 1.1.3, July 9th, 1998
+
+ Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+
+
+ The data format used by the zlib library is described by RFCs (Request for
+ Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
+ (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
+*/
+
+int
+HTTPFilterGZip::get_byte()
+{
+#ifdef DO_GZIP
+ if (bEof) return EOF;
+ if (zstr.avail_in == 0)
+ {
+ bEof = true;
+ return EOF;
+ }
+ zstr.avail_in--;
+ zstr.total_in++;
+ return *(zstr.next_in)++;
+#else
+ return 0;
+#endif
+}
+
+#ifdef DO_GZIP
+
+static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
+
+/* gzip flag byte */
+#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
+#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
+#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
+#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
+#define COMMENT 0x10 /* bit 4 set: file comment present */
+#define RESERVED 0xE0 /* bits 5..7: reserved */
+#endif
+
+// 0 : ok
+// 1 : not gzip
+// 2 : no header
+int
+HTTPFilterGZip::checkHeader()
+{
+#ifdef DO_GZIP
+ uInt len;
+ int c;
+
+ /* Check the gzip magic header */
+ for (len = 0; len < 2; len++) {
+ c = get_byte();
+ if (c != gz_magic[len]) {
+ if (len != 0)
+ {
+ zstr.avail_in++;
+ zstr.next_in--;
+ }
+ if (c != EOF) {
+ zstr.avail_in++;
+ zstr.next_in--;
+ return 1;
+ }
+ return 2;
+ }
+ }
+
+ int method = get_byte(); /* method byte */
+ int flags = get_byte(); /* flags byte */
+
+ if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
+ return bEof ? 2 : 1;
+ }
+
+ /* Discard time, xflags and OS code: */
+ for (len = 0; len < 6; len++) (void)get_byte();
+
+ if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
+ len = (uInt)get_byte();
+ len += ((uInt)get_byte())<<8;
+ /* len is garbage if EOF but the loop below will quit anyway */
+ while (len-- != 0 && get_byte() != EOF) ;
+ }
+ if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
+ while ((c = get_byte()) != 0 && c != EOF) ;
+ }
+ if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
+ while ((c = get_byte()) != 0 && c != EOF) ;
+ }
+ if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
+ for (len = 0; len < 2; len++) (void)get_byte();
+ }
+
+ return bEof ? 2 : 0;
+#else
+ return 0;
+#endif
+}
+
+void
+HTTPFilterGZip::slotInput(const TQByteArray &d)
+{
+#ifdef DO_GZIP
+ if (bPlainText)
+ {
+ emit output(d);
+ return;
+ }
+ if (d.size() == 0)
+ {
+ if (bEatTrailer)
+ bHasFinished = true;
+ if (!bHasFinished)
+ {
+ // Make sure we get the last bytes still in the pipe.
+ // Needed with "deflate".
+ TQByteArray flush(4);
+ flush.fill(0);
+ slotInput(flush);
+ if (!bHasFinished && !bHasHeader)
+ {
+ // Send as-is
+ emit output(headerData);
+ bHasFinished = true;
+ // End of data
+ emit output(TQByteArray());
+ }
+ }
+ if (!bHasFinished)
+ emit error( TDEIO::ERR_SLAVE_DEFINED, i18n("Unexpected end of data, some information may be lost."));
+ return;
+ }
+ if (bHasFinished)
+ return;
+
+ if (bEatTrailer)
+ {
+ iTrailer -= d.size();
+ if (iTrailer <= 0)
+ {
+ bHasFinished = true;
+ // End of data
+ emit output(TQByteArray());
+ }
+ return;
+ }
+
+ if (!bHasHeader)
+ {
+ bEof = false;
+
+ // Add data to header.
+ int orig_size = headerData.size();
+ headerData.resize(orig_size+d.size());
+ memcpy(headerData.data()+orig_size, d.data(), d.size());
+
+ zstr.avail_in = headerData.size();
+ zstr.next_in = (Bytef *) headerData.data();
+
+ int result = checkHeader();
+ if (result == 1)
+ {
+ bPlainText = true;
+ output(headerData);
+ return;
+ }
+
+ if (result != 0)
+ return; // next time better
+
+ bHasHeader = true;
+ }
+ else
+ {
+ zstr.avail_in = d.size();
+ zstr.next_in = (Bytef *) d.data();
+ }
+
+ while( zstr.avail_in )
+ {
+ char buf[8192];
+ zstr.next_out = (Bytef *) buf;
+ zstr.avail_out = 8192;
+ int result = inflate( &zstr, Z_NO_FLUSH );
+ if ((result != Z_OK) && (result != Z_STREAM_END))
+ {
+ emit error( TDEIO::ERR_SLAVE_DEFINED, i18n("Receiving corrupt data."));
+ break;
+ }
+ int bytesOut = 8192 - zstr.avail_out;
+ if (bytesOut)
+ {
+ TQByteArray d;
+ d.setRawData( buf, bytesOut );
+ emit output(d);
+ d.resetRawData( buf, bytesOut );
+ }
+ if (result == Z_STREAM_END)
+ {
+ if (iTrailer)
+ {
+ bEatTrailer = true;
+ }
+ else
+ {
+ bHasFinished = true;
+ // End of data
+ emit output(TQByteArray());
+ }
+ return;
+ }
+ }
+#endif
+}
+
+HTTPFilterDeflate::HTTPFilterDeflate()
+{
+#ifdef DO_GZIP
+ bHasHeader = true;
+ iTrailer = 0;
+#endif
+}
+
+#include "httpfilter.moc"
diff --git a/kio/httpfilter/httpfilter.h b/tdeio/httpfilter/httpfilter.h
index 520a1c627..520a1c627 100644
--- a/kio/httpfilter/httpfilter.h
+++ b/tdeio/httpfilter/httpfilter.h
diff --git a/kio/kcomprfilter.desktop b/tdeio/kcomprfilter.desktop
index 017bf987d..017bf987d 100644
--- a/kio/kcomprfilter.desktop
+++ b/tdeio/kcomprfilter.desktop
diff --git a/kio/kdatatool.desktop b/tdeio/kdatatool.desktop
index a58357d41..a58357d41 100644
--- a/kio/kdatatool.desktop
+++ b/tdeio/kdatatool.desktop
diff --git a/kio/kpasswdserver.desktop b/tdeio/kpasswdserver.desktop
index db43d621c..db43d621c 100644
--- a/kio/kpasswdserver.desktop
+++ b/tdeio/kpasswdserver.desktop
diff --git a/tdeio/kpasswdserver/CMakeLists.txt b/tdeio/kpasswdserver/CMakeLists.txt
new file mode 100644
index 000000000..1d54ddc95
--- /dev/null
+++ b/tdeio/kpasswdserver/CMakeLists.txt
@@ -0,0 +1,43 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdewallet/client
+ ${CMAKE_SOURCE_DIR}/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+#### kded_kpasswdserver ##############################
+
+set( target kded_kpasswdserver )
+
+set( ${target}_SRCS
+ kpasswdserver.cpp kpasswdserver.skel
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeinit_kded-shared
+ DEPENDENCIES dcopidl
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/kio/kpasswdserver/DESIGN b/tdeio/kpasswdserver/DESIGN
index 6a128f9df..6a128f9df 100644
--- a/kio/kpasswdserver/DESIGN
+++ b/tdeio/kpasswdserver/DESIGN
diff --git a/tdeio/kpasswdserver/Makefile.am b/tdeio/kpasswdserver/Makefile.am
new file mode 100644
index 000000000..d1a58059b
--- /dev/null
+++ b/tdeio/kpasswdserver/Makefile.am
@@ -0,0 +1,15 @@
+# $Id$
+# Makefile.am of tdebase/tdeioslave/http
+
+INCLUDES= -I$(top_srcdir)/tdewallet/client $(all_includes)
+
+####### Files
+
+kde_module_LTLIBRARIES = kded_kpasswdserver.la
+
+kded_kpasswdserver_la_SOURCES = kpasswdserver.cpp kpasswdserver.skel
+kded_kpasswdserver_la_METASOURCES = AUTO
+kded_kpasswdserver_la_LDFLAGS = $(all_libraries) -module -avoid-version
+kded_kpasswdserver_la_LIBADD = $(top_builddir)/tdewallet/client/libtdewalletclient.la $(LIB_KIO) $(LIB_KDED) $(LIB_QT) $(LIB_TDEUI) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la $(LIB_X11)
+
+include $(top_srcdir)/admin/Doxyfile.am
diff --git a/tdeio/kpasswdserver/kpasswdserver.cpp b/tdeio/kpasswdserver/kpasswdserver.cpp
new file mode 100644
index 000000000..ff7295181
--- /dev/null
+++ b/tdeio/kpasswdserver/kpasswdserver.cpp
@@ -0,0 +1,715 @@
+/*
+ This file is part of the KDE Password Server
+
+ Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
+ Copyright (C) 2005 David Faure (faure@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License
+ version 2 as published by the Free Software Foundation.
+
+ This software 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 library; see the file COPYING. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+//----------------------------------------------------------------------------
+//
+// KDE Password Server
+// $Id$
+
+#include "kpasswdserver.h"
+
+#include <time.h>
+
+#include <tqtimer.h>
+
+#include <kapplication.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kdebug.h>
+#include <tdeio/passdlg.h>
+#include <tdewallet.h>
+
+#include "config.h"
+#ifdef Q_WS_X11
+#include <X11/X.h>
+#include <X11/Xlib.h>
+#endif
+
+extern "C" {
+ KDE_EXPORT KDEDModule *create_kpasswdserver(const TQCString &name)
+ {
+ return new KPasswdServer(name);
+ }
+}
+
+int
+KPasswdServer::AuthInfoList::compareItems(TQPtrCollection::Item n1, TQPtrCollection::Item n2)
+{
+ if (!n1 || !n2)
+ return 0;
+
+ AuthInfo *i1 = (AuthInfo *) n1;
+ AuthInfo *i2 = (AuthInfo *) n2;
+
+ int l1 = i1->directory.length();
+ int l2 = i2->directory.length();
+
+ if (l1 > l2)
+ return -1;
+ if (l1 < l2)
+ return 1;
+ return 0;
+}
+
+
+KPasswdServer::KPasswdServer(const TQCString &name)
+ : KDEDModule(name)
+{
+ m_authDict.setAutoDelete(true);
+ m_authPending.setAutoDelete(true);
+ m_seqNr = 0;
+ m_wallet = 0;
+ connect(this, TQT_SIGNAL(windowUnregistered(long)),
+ this, TQT_SLOT(removeAuthForWindowId(long)));
+}
+
+KPasswdServer::~KPasswdServer()
+{
+ delete m_wallet;
+}
+
+// Helper - returns the wallet key to use for read/store/checking for existence.
+static TQString makeWalletKey( const TQString& key, const TQString& realm )
+{
+ return realm.isEmpty() ? key : key + '-' + realm;
+}
+
+// Helper for storeInWallet/readFromWallet
+static TQString makeMapKey( const char* key, int entryNumber )
+{
+ TQString str = TQString::fromLatin1( key );
+ if ( entryNumber > 1 )
+ str += "-" + TQString::number( entryNumber );
+ return str;
+}
+
+static bool storeInWallet( KWallet::Wallet* wallet, const TQString& key, const TDEIO::AuthInfo &info )
+{
+ if ( !wallet->hasFolder( KWallet::Wallet::PasswordFolder() ) )
+ if ( !wallet->createFolder( KWallet::Wallet::PasswordFolder() ) )
+ return false;
+ wallet->setFolder( KWallet::Wallet::PasswordFolder() );
+ // Before saving, check if there's already an entry with this login.
+ // If so, replace it (with the new password). Otherwise, add a new entry.
+ typedef TQMap<TQString,TQString> Map;
+ int entryNumber = 1;
+ Map map;
+ TQString walletKey = makeWalletKey( key, info.realmValue );
+ kdDebug(130) << "storeInWallet: walletKey=" << walletKey << " reading existing map" << endl;
+ if ( wallet->readMap( walletKey, map ) == 0 ) {
+ Map::ConstIterator end = map.end();
+ Map::ConstIterator it = map.find( "login" );
+ while ( it != end ) {
+ if ( it.data() == info.username ) {
+ break; // OK, overwrite this entry
+ }
+ it = map.find( TQString( "login-" ) + TQString::number( ++entryNumber ) );
+ }
+ // If no entry was found, create a new entry - entryNumber is set already.
+ }
+ const TQString loginKey = makeMapKey( "login", entryNumber );
+ const TQString passwordKey = makeMapKey( "password", entryNumber );
+ kdDebug(130) << "storeInWallet: writing to " << loginKey << "," << passwordKey << endl;
+ // note the overwrite=true by default
+ map.insert( loginKey, info.username );
+ map.insert( passwordKey, info.password );
+ wallet->writeMap( walletKey, map );
+ return true;
+}
+
+
+static bool readFromWallet( KWallet::Wallet* wallet, const TQString& key, const TQString& realm, TQString& username, TQString& password, bool userReadOnly, TQMap<TQString,TQString>& knownLogins )
+{
+ //kdDebug(130) << "readFromWallet: key=" << key << " username=" << username << " password=" /*<< password*/ << " userReadOnly=" << userReadOnly << " realm=" << realm << endl;
+ if ( wallet->hasFolder( KWallet::Wallet::PasswordFolder() ) )
+ {
+ wallet->setFolder( KWallet::Wallet::PasswordFolder() );
+
+ TQMap<TQString,TQString> map;
+ if ( wallet->readMap( makeWalletKey( key, realm ), map ) == 0 )
+ {
+ typedef TQMap<TQString,TQString> Map;
+ int entryNumber = 1;
+ Map::ConstIterator end = map.end();
+ Map::ConstIterator it = map.find( "login" );
+ while ( it != end ) {
+ //kdDebug(130) << "readFromWallet: found " << it.key() << "=" << it.data() << endl;
+ Map::ConstIterator pwdIter = map.find( makeMapKey( "password", entryNumber ) );
+ if ( pwdIter != end ) {
+ if ( it.data() == username )
+ password = pwdIter.data();
+ knownLogins.insert( it.data(), pwdIter.data() );
+ }
+
+ it = map.find( TQString( "login-" ) + TQString::number( ++entryNumber ) );
+ }
+ //kdDebug(130) << knownLogins.count() << " known logins" << endl;
+
+ if ( !userReadOnly && !knownLogins.isEmpty() && username.isEmpty() ) {
+ // Pick one, any one...
+ username = knownLogins.begin().key();
+ password = knownLogins.begin().data();
+ //kdDebug(130) << "readFromWallet: picked the first one : " << username << endl;
+ }
+
+ return true;
+ }
+ }
+ return false;
+}
+
+TDEIO::AuthInfo
+KPasswdServer::checkAuthInfo(TDEIO::AuthInfo info, long windowId)
+{
+ return checkAuthInfo(info, windowId, 0);
+}
+
+TDEIO::AuthInfo
+KPasswdServer::checkAuthInfo(TDEIO::AuthInfo info, long windowId, unsigned long usertime)
+{
+ kdDebug(130) << "KPasswdServer::checkAuthInfo: User= " << info.username
+ << ", WindowId = " << windowId << endl;
+ if( usertime != 0 )
+ kapp->updateUserTimestamp( usertime );
+
+ TQString key = createCacheKey(info);
+
+ Request *request = m_authPending.first();
+ TQString path2 = info.url.directory(false, false);
+ for(; request; request = m_authPending.next())
+ {
+ if (request->key != key)
+ continue;
+
+ if (info.verifyPath)
+ {
+ TQString path1 = request->info.url.directory(false, false);
+ if (!path2.startsWith(path1))
+ continue;
+ }
+
+ request = new Request;
+ request->client = callingDcopClient();
+ request->transaction = request->client->beginTransaction();
+ request->key = key;
+ request->info = info;
+ m_authWait.append(request);
+ return info;
+ }
+
+ const AuthInfo *result = findAuthInfoItem(key, info);
+ if (!result || result->isCanceled)
+ {
+ if (!result &&
+ (info.username.isEmpty() || info.password.isEmpty()) &&
+ !KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(),
+ KWallet::Wallet::PasswordFolder(), makeWalletKey(key, info.realmValue)))
+ {
+ TQMap<TQString, TQString> knownLogins;
+ if (openWallet(windowId)) {
+ if (readFromWallet(m_wallet, key, info.realmValue, info.username, info.password,
+ info.readOnly, knownLogins))
+ {
+ info.setModified(true);
+ return info;
+ }
+ }
+ }
+
+ info.setModified(false);
+ return info;
+ }
+
+ updateAuthExpire(key, result, windowId, false);
+
+ return copyAuthInfo(result);
+}
+
+TDEIO::AuthInfo
+KPasswdServer::queryAuthInfo(TDEIO::AuthInfo info, TQString errorMsg, long windowId, long seqNr)
+{
+ return queryAuthInfo(info, errorMsg, windowId, seqNr, 0 );
+}
+
+TDEIO::AuthInfo
+KPasswdServer::queryAuthInfo(TDEIO::AuthInfo info, TQString errorMsg, long windowId, long seqNr, unsigned long usertime)
+{
+ kdDebug(130) << "KPasswdServer::queryAuthInfo: User= " << info.username
+ << ", Message= " << info.prompt << ", WindowId = " << windowId << endl;
+ if ( !info.password.isEmpty() ) // should we really allow the caller to pre-fill the password?
+ kdDebug(130) << "password was set by caller" << endl;
+ if( usertime != 0 )
+ kapp->updateUserTimestamp( usertime );
+
+ TQString key = createCacheKey(info);
+ Request *request = new Request;
+ request->client = callingDcopClient();
+ request->transaction = request->client->beginTransaction();
+ request->key = key;
+ request->info = info;
+ request->windowId = windowId;
+ request->seqNr = seqNr;
+ if (errorMsg == "<NoAuthPrompt>")
+ {
+ request->errorMsg = TQString::null;
+ request->prompt = false;
+ }
+ else
+ {
+ request->errorMsg = errorMsg;
+ request->prompt = true;
+ }
+ m_authPending.append(request);
+
+ if (m_authPending.count() == 1)
+ TQTimer::singleShot(0, this, TQT_SLOT(processRequest()));
+
+ return info;
+}
+
+void
+KPasswdServer::addAuthInfo(TDEIO::AuthInfo info, long windowId)
+{
+ kdDebug(130) << "KPasswdServer::addAuthInfo: User= " << info.username
+ << ", RealmValue= " << info.realmValue << ", WindowId = " << windowId << endl;
+ TQString key = createCacheKey(info);
+
+ m_seqNr++;
+
+ addAuthInfoItem(key, info, windowId, m_seqNr, false);
+}
+
+bool
+KPasswdServer::openWallet( WId windowId )
+{
+ if ( m_wallet && !m_wallet->isOpen() ) { // forced closed
+ delete m_wallet;
+ m_wallet = 0;
+ }
+ if ( !m_wallet )
+ m_wallet = KWallet::Wallet::openWallet(
+ KWallet::Wallet::NetworkWallet(), windowId );
+ return m_wallet != 0;
+}
+
+void
+KPasswdServer::processRequest()
+{
+ Request *request = m_authPending.first();
+ if (!request)
+ return;
+
+ TDEIO::AuthInfo &info = request->info;
+
+ kdDebug(130) << "KPasswdServer::processRequest: User= " << info.username
+ << ", Message= " << info.prompt << endl;
+ const AuthInfo *result = findAuthInfoItem(request->key, request->info);
+
+ if (result && (request->seqNr < result->seqNr))
+ {
+ kdDebug(130) << "KPasswdServer::processRequest: auto retry!" << endl;
+ if (result->isCanceled)
+ {
+ info.setModified(false);
+ }
+ else
+ {
+ updateAuthExpire(request->key, result, request->windowId, false);
+ info = copyAuthInfo(result);
+ }
+ }
+ else
+ {
+ m_seqNr++;
+ bool askPw = request->prompt;
+ if (result && !info.username.isEmpty() &&
+ !request->errorMsg.isEmpty())
+ {
+ TQString prompt = request->errorMsg;
+ prompt += i18n(" Do you want to retry?");
+ int dlgResult = KMessageBox::warningContinueCancelWId(request->windowId, prompt,
+ i18n("Authentication"), i18n("Retry"));
+ if (dlgResult != KMessageBox::Continue)
+ askPw = false;
+ }
+
+ int dlgResult = TQDialog::Rejected;
+ if (askPw)
+ {
+ TQString username = info.username;
+ TQString password = info.password;
+ bool hasWalletData = false;
+ TQMap<TQString, TQString> knownLogins;
+
+ if ( ( username.isEmpty() || password.isEmpty() )
+ && !KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(), KWallet::Wallet::PasswordFolder(), makeWalletKey( request->key, info.realmValue )) )
+ {
+ // no login+pass provided, check if tdewallet has one
+ if ( openWallet( request->windowId ) )
+ hasWalletData = readFromWallet( m_wallet, request->key, info.realmValue, username, password, info.readOnly, knownLogins );
+ }
+
+ TDEIO::PasswordDialog dlg( info.prompt, username, info.keepPassword );
+ if (info.caption.isEmpty())
+ dlg.setPlainCaption( i18n("Authorization Dialog") );
+ else
+ dlg.setPlainCaption( info.caption );
+
+ if ( !info.comment.isEmpty() )
+ dlg.addCommentLine( info.commentLabel, info.comment );
+
+ if ( !password.isEmpty() )
+ dlg.setPassword( password );
+
+ if (info.readOnly)
+ dlg.setUserReadOnly( true );
+ else
+ dlg.setKnownLogins( knownLogins );
+
+ if (hasWalletData)
+ dlg.setKeepPassword( true );
+
+#ifdef Q_WS_X11
+ XSetTransientForHint( tqt_xdisplay(), dlg.winId(), request->windowId);
+#endif
+
+ dlgResult = dlg.exec();
+
+ if (dlgResult == TQDialog::Accepted)
+ {
+ info.username = dlg.username();
+ info.password = dlg.password();
+ info.keepPassword = dlg.keepPassword();
+
+ // When the user checks "keep password", that means:
+ // * if the wallet is enabled, store it there for long-term, and in kpasswdserver
+ // only for the duration of the window (#92928)
+ // * otherwise store in kpasswdserver for the duration of the KDE session.
+ if ( info.keepPassword ) {
+ if ( openWallet( request->windowId ) ) {
+ if ( storeInWallet( m_wallet, request->key, info ) )
+ // password is in wallet, don't keep it in memory after window is closed
+ info.keepPassword = false;
+ }
+ }
+ }
+ }
+ if ( dlgResult != TQDialog::Accepted )
+ {
+ addAuthInfoItem(request->key, info, 0, m_seqNr, true);
+ info.setModified( false );
+ }
+ else
+ {
+ addAuthInfoItem(request->key, info, request->windowId, m_seqNr, false);
+ info.setModified( true );
+ }
+ }
+
+ TQCString replyType;
+ TQByteArray replyData;
+
+ TQDataStream stream2(replyData, IO_WriteOnly);
+ stream2 << info << m_seqNr;
+ replyType = "TDEIO::AuthInfo";
+ request->client->endTransaction( request->transaction,
+ replyType, replyData);
+
+ m_authPending.remove((unsigned int) 0);
+
+ // Check all requests in the wait queue.
+ for(Request *waitRequest = m_authWait.first();
+ waitRequest; )
+ {
+ bool keepQueued = false;
+ TQString key = waitRequest->key;
+
+ request = m_authPending.first();
+ TQString path2 = waitRequest->info.url.directory(false, false);
+ for(; request; request = m_authPending.next())
+ {
+ if (request->key != key)
+ continue;
+
+ if (info.verifyPath)
+ {
+ TQString path1 = request->info.url.directory(false, false);
+ if (!path2.startsWith(path1))
+ continue;
+ }
+
+ keepQueued = true;
+ break;
+ }
+ if (keepQueued)
+ {
+ waitRequest = m_authWait.next();
+ }
+ else
+ {
+ const AuthInfo *result = findAuthInfoItem(waitRequest->key, waitRequest->info);
+
+ TQCString replyType;
+ TQByteArray replyData;
+
+ TQDataStream stream2(replyData, IO_WriteOnly);
+
+ if (!result || result->isCanceled)
+ {
+ waitRequest->info.setModified(false);
+ stream2 << waitRequest->info;
+ }
+ else
+ {
+ updateAuthExpire(waitRequest->key, result, waitRequest->windowId, false);
+ TDEIO::AuthInfo info = copyAuthInfo(result);
+ stream2 << info;
+ }
+
+ replyType = "TDEIO::AuthInfo";
+ waitRequest->client->endTransaction( waitRequest->transaction,
+ replyType, replyData);
+
+ m_authWait.remove();
+ waitRequest = m_authWait.current();
+ }
+ }
+
+ if (m_authPending.count())
+ TQTimer::singleShot(0, this, TQT_SLOT(processRequest()));
+
+}
+
+TQString KPasswdServer::createCacheKey( const TDEIO::AuthInfo &info )
+{
+ if( !info.url.isValid() ) {
+ // Note that a null key will break findAuthInfoItem later on...
+ kdWarning(130) << "createCacheKey: invalid URL " << info.url << endl;
+ return TQString::null;
+ }
+
+ // Generate the basic key sequence.
+ TQString key = info.url.protocol();
+ key += '-';
+ if (!info.url.user().isEmpty())
+ {
+ key += info.url.user();
+ key += "@";
+ }
+ key += info.url.host();
+ int port = info.url.port();
+ if( port )
+ {
+ key += ':';
+ key += TQString::number(port);
+ }
+
+ return key;
+}
+
+TDEIO::AuthInfo
+KPasswdServer::copyAuthInfo(const AuthInfo *i)
+{
+ TDEIO::AuthInfo result;
+ result.url = i->url;
+ result.username = i->username;
+ result.password = i->password;
+ result.realmValue = i->realmValue;
+ result.digestInfo = i->digestInfo;
+ result.setModified(true);
+
+ return result;
+}
+
+const KPasswdServer::AuthInfo *
+KPasswdServer::findAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info)
+{
+ AuthInfoList *authList = m_authDict.find(key);
+ if (!authList)
+ return 0;
+
+ TQString path2 = info.url.directory(false, false);
+ for(AuthInfo *current = authList->first();
+ current; )
+ {
+ if ((current->expire == AuthInfo::expTime) &&
+ (difftime(time(0), current->expireTime) > 0))
+ {
+ authList->remove();
+ current = authList->current();
+ continue;
+ }
+
+ if (info.verifyPath)
+ {
+ TQString path1 = current->directory;
+ if (path2.startsWith(path1) &&
+ (info.username.isEmpty() || info.username == current->username))
+ return current;
+ }
+ else
+ {
+ if (current->realmValue == info.realmValue &&
+ (info.username.isEmpty() || info.username == current->username))
+ return current; // TODO: Update directory info,
+ }
+
+ current = authList->next();
+ }
+ return 0;
+}
+
+void
+KPasswdServer::removeAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info)
+{
+ AuthInfoList *authList = m_authDict.find(key);
+ if (!authList)
+ return;
+
+ for(AuthInfo *current = authList->first();
+ current; )
+ {
+ if (current->realmValue == info.realmValue)
+ {
+ authList->remove();
+ current = authList->current();
+ }
+ else
+ {
+ current = authList->next();
+ }
+ }
+ if (authList->isEmpty())
+ {
+ m_authDict.remove(key);
+ }
+}
+
+
+void
+KPasswdServer::addAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info, long windowId, long seqNr, bool canceled)
+{
+ AuthInfoList *authList = m_authDict.find(key);
+ if (!authList)
+ {
+ authList = new AuthInfoList;
+ m_authDict.insert(key, authList);
+ }
+ AuthInfo *current = authList->first();
+ for(; current; current = authList->next())
+ {
+ if (current->realmValue == info.realmValue)
+ {
+ authList->take();
+ break;
+ }
+ }
+
+ if (!current)
+ {
+ current = new AuthInfo;
+ current->expire = AuthInfo::expTime;
+ kdDebug(130) << "Creating AuthInfo" << endl;
+ }
+ else
+ {
+ kdDebug(130) << "Updating AuthInfo" << endl;
+ }
+
+ current->url = info.url;
+ current->directory = info.url.directory(false, false);
+ current->username = info.username;
+ current->password = info.password;
+ current->realmValue = info.realmValue;
+ current->digestInfo = info.digestInfo;
+ current->seqNr = seqNr;
+ current->isCanceled = canceled;
+
+ updateAuthExpire(key, current, windowId, info.keepPassword && !canceled);
+
+ // Insert into list, keep the list sorted "longest path" first.
+ authList->inSort(current);
+}
+
+void
+KPasswdServer::updateAuthExpire(const TQString &key, const AuthInfo *auth, long windowId, bool keep)
+{
+ AuthInfo *current = const_cast<AuthInfo *>(auth);
+ if (keep)
+ {
+ current->expire = AuthInfo::expNever;
+ }
+ else if (windowId && (current->expire != AuthInfo::expNever))
+ {
+ current->expire = AuthInfo::expWindowClose;
+ if (!current->windowList.contains(windowId))
+ current->windowList.append(windowId);
+ }
+ else if (current->expire == AuthInfo::expTime)
+ {
+ current->expireTime = time(0)+10;
+ }
+
+ // Update mWindowIdList
+ if (windowId)
+ {
+ TQStringList *keysChanged = mWindowIdList.find(windowId);
+ if (!keysChanged)
+ {
+ keysChanged = new TQStringList;
+ mWindowIdList.insert(windowId, keysChanged);
+ }
+ if (!keysChanged->contains(key))
+ keysChanged->append(key);
+ }
+}
+
+void
+KPasswdServer::removeAuthForWindowId(long windowId)
+{
+ TQStringList *keysChanged = mWindowIdList.find(windowId);
+ if (!keysChanged) return;
+
+ for(TQStringList::ConstIterator it = keysChanged->begin();
+ it != keysChanged->end(); ++it)
+ {
+ TQString key = *it;
+ AuthInfoList *authList = m_authDict.find(key);
+ if (!authList)
+ continue;
+
+ AuthInfo *current = authList->first();
+ for(; current; )
+ {
+ if (current->expire == AuthInfo::expWindowClose)
+ {
+ if (current->windowList.remove(windowId) && current->windowList.isEmpty())
+ {
+ authList->remove();
+ current = authList->current();
+ continue;
+ }
+ }
+ current = authList->next();
+ }
+ }
+}
+
+#include "kpasswdserver.moc"
diff --git a/tdeio/kpasswdserver/kpasswdserver.h b/tdeio/kpasswdserver/kpasswdserver.h
new file mode 100644
index 000000000..ce6d0386e
--- /dev/null
+++ b/tdeio/kpasswdserver/kpasswdserver.h
@@ -0,0 +1,118 @@
+/*
+ This file is part of the KDE Password Server
+
+ Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License
+ version 2 as published by the Free Software Foundation.
+
+ This software 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 library; see the file COPYING. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+//----------------------------------------------------------------------------
+//
+// KDE Password Server
+// $Id$
+
+#ifndef KPASSWDSERVER_H
+#define KPASSWDSERVER_H
+
+#include <tqdict.h>
+#include <tqintdict.h>
+
+#include <dcopclient.h>
+#include <tdeio/authinfo.h>
+#include <kded/kdedmodule.h>
+
+namespace KWallet {
+ class Wallet;
+}
+
+class KPasswdServer : public KDEDModule
+{
+ Q_OBJECT
+ K_DCOP
+public:
+ KPasswdServer(const TQCString &);
+ ~KPasswdServer();
+
+k_dcop:
+ // KDE4 merge
+ TDEIO::AuthInfo checkAuthInfo(TDEIO::AuthInfo, long, unsigned long);
+ TDEIO::AuthInfo checkAuthInfo(TDEIO::AuthInfo, long);
+ TDEIO::AuthInfo queryAuthInfo(TDEIO::AuthInfo, TQString, long, long, unsigned long);
+ TDEIO::AuthInfo queryAuthInfo(TDEIO::AuthInfo, TQString, long, long);
+ void addAuthInfo(TDEIO::AuthInfo, long);
+
+public slots:
+ void processRequest();
+ // Remove all authentication info associated with windowId
+ void removeAuthForWindowId(long windowId);
+
+protected:
+ struct AuthInfo;
+
+ TQString createCacheKey( const TDEIO::AuthInfo &info );
+ const AuthInfo *findAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info);
+ void removeAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info);
+ void addAuthInfoItem(const TQString &key, const TDEIO::AuthInfo &info, long windowId, long seqNr, bool canceled);
+ TDEIO::AuthInfo copyAuthInfo(const AuthInfo *);
+ void updateAuthExpire(const TQString &key, const AuthInfo *, long windowId, bool keep);
+ int findWalletEntry( const TQMap<TQString,TQString>& map, const TQString& username );
+ bool openWallet( WId windowId );
+
+ struct AuthInfo {
+ AuthInfo() { expire = expNever; isCanceled = false; seqNr = 0; }
+
+ KURL url;
+ TQString directory;
+ TQString username;
+ TQString password;
+ TQString realmValue;
+ TQString digestInfo;
+
+ enum { expNever, expWindowClose, expTime } expire;
+ TQValueList<long> windowList;
+ unsigned long expireTime;
+ long seqNr;
+
+ bool isCanceled;
+ };
+
+ class AuthInfoList : public TQPtrList<AuthInfo>
+ {
+ public:
+ AuthInfoList() { setAutoDelete(true); }
+ int compareItems(TQPtrCollection::Item n1, TQPtrCollection::Item n2);
+ };
+
+ TQDict< AuthInfoList > m_authDict;
+
+ struct Request {
+ DCOPClient *client;
+ DCOPClientTransaction *transaction;
+ TQString key;
+ TDEIO::AuthInfo info;
+ TQString errorMsg;
+ long windowId;
+ long seqNr;
+ bool prompt;
+ };
+
+ TQPtrList< Request > m_authPending;
+ TQPtrList< Request > m_authWait;
+ TQIntDict<TQStringList> mWindowIdList;
+ DCOPClient *m_dcopClient;
+ KWallet::Wallet* m_wallet;
+ long m_seqNr;
+};
+
+#endif
diff --git a/kio/kscan.desktop b/tdeio/kscan.desktop
index 8d3a026fb..8d3a026fb 100644
--- a/kio/kscan.desktop
+++ b/tdeio/kscan.desktop
diff --git a/kio/kssl/CMakeLists.txt b/tdeio/kssl/CMakeLists.txt
index a2c9f00d6..a2c9f00d6 100644
--- a/kio/kssl/CMakeLists.txt
+++ b/tdeio/kssl/CMakeLists.txt
diff --git a/kio/kssl/KPMG-CA-16389.0.DC80502.pdf b/tdeio/kssl/KPMG-CA-16389.0.DC80502.pdf
index 63a7633ee..63a7633ee 100644
--- a/kio/kssl/KPMG-CA-16389.0.DC80502.pdf
+++ b/tdeio/kssl/KPMG-CA-16389.0.DC80502.pdf
Binary files differ
diff --git a/kio/kssl/Makefile.am b/tdeio/kssl/Makefile.am
index 5d57ab7ab..5d57ab7ab 100644
--- a/kio/kssl/Makefile.am
+++ b/tdeio/kssl/Makefile.am
diff --git a/kio/kssl/README b/tdeio/kssl/README
index b5f404fc7..b5f404fc7 100644
--- a/kio/kssl/README
+++ b/tdeio/kssl/README
diff --git a/kio/kssl/SECURITY-HOLES b/tdeio/kssl/SECURITY-HOLES
index 62b8e9ca7..62b8e9ca7 100644
--- a/kio/kssl/SECURITY-HOLES
+++ b/tdeio/kssl/SECURITY-HOLES
diff --git a/kio/kssl/TODO b/tdeio/kssl/TODO
index 7e2270575..7e2270575 100644
--- a/kio/kssl/TODO
+++ b/tdeio/kssl/TODO
diff --git a/tdeio/kssl/configure.in.in b/tdeio/kssl/configure.in.in
new file mode 100644
index 000000000..7e3848d78
--- /dev/null
+++ b/tdeio/kssl/configure.in.in
@@ -0,0 +1,7 @@
+KDE_CHECK_SSL
+
+if test "$have_ssl" = yes; then
+ AC_DEFINE(KSSL_HAVE_SSL, 1, [Define if we shall use KSSL])
+fi
+
+AM_CONFIG_HEADER([tdeio/kssl/ksslconfig.h])
diff --git a/kio/kssl/keygenwizard.ui b/tdeio/kssl/keygenwizard.ui
index 4cb5fe1df..4cb5fe1df 100644
--- a/kio/kssl/keygenwizard.ui
+++ b/tdeio/kssl/keygenwizard.ui
diff --git a/kio/kssl/keygenwizard2.ui b/tdeio/kssl/keygenwizard2.ui
index 90fef8fef..90fef8fef 100644
--- a/kio/kssl/keygenwizard2.ui
+++ b/tdeio/kssl/keygenwizard2.ui
diff --git a/tdeio/kssl/kopenssl.cc b/tdeio/kssl/kopenssl.cc
new file mode 100644
index 000000000..986609570
--- /dev/null
+++ b/tdeio/kssl/kopenssl.cc
@@ -0,0 +1,1601 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001-2003 George Staikos <staikos@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef KSSL_HAVE_SSL
+#include <openssl/opensslv.h>
+#endif
+
+#include <kdebug.h>
+#include <tdeconfig.h>
+#include <kstaticdeleter.h>
+#include <tqregexp.h>
+#include <tqdir.h>
+
+#include <stdio.h>
+#include <unistd.h>
+#include "kopenssl.h"
+
+extern "C" {
+#ifdef KSSL_HAVE_SSL
+static int (*K_SSL_connect) (SSL *) = 0L;
+static int (*K_SSL_accept) (SSL *) = 0L;
+static int (*K_SSL_read) (SSL *, void *, int) = 0L;
+static int (*K_SSL_write) (SSL *, const void *, int) = 0L;
+static SSL *(*K_SSL_new) (SSL_CTX *) = 0L;
+static void (*K_SSL_free) (SSL *) = 0L;
+static int (*K_SSL_shutdown) (SSL *) = 0L;
+static SSL_CTX *(*K_SSL_CTX_new)(SSL_METHOD *) = 0L;
+static void (*K_SSL_CTX_free) (SSL_CTX *) = 0L;
+static int (*K_SSL_set_fd) (SSL *, int) = 0L;
+static int (*K_SSL_pending) (SSL *) = 0L;
+static int (*K_SSL_peek) (SSL *, void *, int) = 0L;
+static int (*K_SSL_CTX_set_cipher_list)(SSL_CTX *, const char *) = 0L;
+static void (*K_SSL_CTX_set_verify)(SSL_CTX *, int,
+ int (*)(int, X509_STORE_CTX *)) = 0L;
+static int (*K_SSL_use_certificate)(SSL *, X509 *) = 0L;
+static SSL_CIPHER *(*K_SSL_get_current_cipher)(SSL *) = 0L;
+static long (*K_SSL_ctrl) (SSL *,int, long, char *) = 0L;
+static int (*K_RAND_egd) (const char *) = 0L;
+static const char* (*K_RAND_file_name) (char *, size_t) = 0L;
+static int (*K_RAND_load_file) (const char *, long) = 0L;
+static int (*K_RAND_write_file) (const char *) = 0L;
+static SSL_METHOD * (*K_TLSv1_client_method) () = 0L;
+static SSL_METHOD * (*K_SSLv2_client_method) () = 0L;
+static SSL_METHOD * (*K_SSLv3_client_method) () = 0L;
+static SSL_METHOD * (*K_SSLv23_client_method) () = 0L;
+static X509 * (*K_SSL_get_peer_certificate) (SSL *) = 0L;
+static int (*K_SSL_CIPHER_get_bits) (SSL_CIPHER *,int *) = 0L;
+static char * (*K_SSL_CIPHER_get_version) (SSL_CIPHER *) = 0L;
+static const char * (*K_SSL_CIPHER_get_name) (SSL_CIPHER *) = 0L;
+static char * (*K_SSL_CIPHER_description) (SSL_CIPHER *, char *, int) = 0L;
+static X509 * (*K_d2i_X509) (X509 **,unsigned char **,long) = 0L;
+static int (*K_i2d_X509) (X509 *,unsigned char **) = 0L;
+static int (*K_X509_cmp) (X509 *, X509 *) = 0L;
+static void (*K_X509_STORE_CTX_free) (X509_STORE_CTX *) = 0L;
+static int (*K_X509_verify_cert) (X509_STORE_CTX *) = 0L;
+static X509_STORE_CTX *(*K_X509_STORE_CTX_new) (void) = 0L;
+static void (*K_X509_STORE_free) (X509_STORE *) = 0L;
+static X509_STORE *(*K_X509_STORE_new) (void) = 0L;
+static void (*K_X509_free) (X509 *) = 0L;
+static char *(*K_X509_NAME_oneline) (X509_NAME *,char *,int) = 0L;
+static X509_NAME *(*K_X509_get_subject_name) (X509 *) = 0L;
+static X509_NAME *(*K_X509_get_issuer_name) (X509 *) = 0L;
+static X509_LOOKUP *(*K_X509_STORE_add_lookup) (X509_STORE *, X509_LOOKUP_METHOD *) = 0L;
+static X509_LOOKUP_METHOD *(*K_X509_LOOKUP_file)(void) = 0L;
+static void (*K_X509_LOOKUP_free)(X509_LOOKUP *) = 0L;
+static int (*K_X509_LOOKUP_ctrl)(X509_LOOKUP *, int, const char *, long, char **) = 0L;
+static void (*K_X509_STORE_CTX_init)(X509_STORE_CTX *, X509_STORE *, X509 *, STACK_OF(X509) *) = 0L;
+static void (*K_CRYPTO_free) (void *) = 0L;
+static X509* (*K_X509_dup) (X509 *) = 0L;
+static BIO_METHOD *(*K_BIO_s_mem) (void) = 0L;
+static BIO* (*K_BIO_new) (BIO_METHOD *) = 0L;
+static BIO* (*K_BIO_new_fp) (FILE *, int) = 0L;
+static BIO* (*K_BIO_new_mem_buf) (void *, int) = 0L;
+static int (*K_BIO_free) (BIO *) = 0L;
+static long (*K_BIO_ctrl) (BIO *,int,long,void *) = 0L;
+static int (*K_BIO_write) (BIO *b, const void *data, int len) = 0L;
+static int (*K_PEM_ASN1_write_bio) (int (*)(),const char *,BIO *,char *,
+ const EVP_CIPHER *,unsigned char *,int ,
+ pem_password_cb *, void *) = 0L;
+#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+static int (*K_ASN1_item_i2d_fp)(ASN1_ITEM *,FILE *,unsigned char *) = 0L;
+static ASN1_ITEM *K_NETSCAPE_X509_it = 0L;
+#else
+static ASN1_METHOD* (*K_X509_asn1_meth) (void) = 0L;
+static int (*K_ASN1_i2d_fp)(int (*)(),FILE *,unsigned char *) = 0L;
+static int (*K_i2d_ASN1_HEADER)(ASN1_HEADER *, unsigned char **) = 0L;
+#endif
+static int (*K_X509_print_fp) (FILE *, X509*) = 0L;
+static int (*K_i2d_PKCS12) (PKCS12*, unsigned char**) = 0L;
+static int (*K_i2d_PKCS12_fp) (FILE *, PKCS12*) = 0L;
+static int (*K_PKCS12_newpass) (PKCS12*, char*, char*) = 0L;
+static PKCS12* (*K_d2i_PKCS12_fp) (FILE*, PKCS12**) = 0L;
+static PKCS12* (*K_PKCS12_new) (void) = 0L;
+static void (*K_PKCS12_free) (PKCS12 *) = 0L;
+static int (*K_PKCS12_parse) (PKCS12*, const char *, EVP_PKEY**,
+ X509**, STACK_OF(X509)**) = 0L;
+static void (*K_EVP_PKEY_free) (EVP_PKEY *) = 0L;
+static EVP_PKEY* (*K_EVP_PKEY_new) () = 0L;
+static void (*K_X509_REQ_free) (X509_REQ *) = 0L;
+static X509_REQ* (*K_X509_REQ_new) () = 0L;
+static int (*K_SSL_CTX_use_PrivateKey) (SSL_CTX*, EVP_PKEY*) = 0L;
+static int (*K_SSL_CTX_use_certificate) (SSL_CTX*, X509*) = 0L;
+static int (*K_SSL_get_error) (SSL*, int) = 0L;
+static STACK_OF(X509)* (*K_SSL_get_peer_cert_chain) (SSL*) = 0L;
+static void (*K_X509_STORE_CTX_set_chain) (X509_STORE_CTX *, STACK_OF(X509)*) = 0L;
+static void (*K_X509_STORE_CTX_set_purpose) (X509_STORE_CTX *, int) = 0L;
+static void (*K_sk_free) (STACK*) = 0L;
+static int (*K_sk_num) (STACK*) = 0L;
+static char* (*K_sk_pop) (STACK*) = 0L;
+static char* (*K_sk_value) (STACK*, int) = 0L;
+static STACK* (*K_sk_new) (int (*)()) = 0L;
+static int (*K_sk_push) (STACK*, char*) = 0L;
+static STACK* (*K_sk_dup) (STACK *) = 0L;
+static char * (*K_i2s_ASN1_INTEGER) (X509V3_EXT_METHOD *, ASN1_INTEGER *) =0L;
+static ASN1_INTEGER * (*K_X509_get_serialNumber) (X509 *) = 0L;
+static EVP_PKEY *(*K_X509_get_pubkey)(X509 *) = 0L;
+static int (*K_i2d_PublicKey)(EVP_PKEY *, unsigned char **) = 0L;
+static int (*K_X509_check_private_key)(X509 *, EVP_PKEY *) = 0L;
+static char * (*K_BN_bn2hex)(const BIGNUM *) = 0L;
+static int (*K_X509_digest)(const X509 *,const EVP_MD *, unsigned char *, unsigned int *) = 0L;
+static EVP_MD* (*K_EVP_md5)() = 0L;
+static void (*K_ASN1_INTEGER_free)(ASN1_INTEGER *) = 0L;
+static int (*K_OBJ_obj2nid)(ASN1_OBJECT *) = 0L;
+static const char * (*K_OBJ_nid2ln)(int) = 0L;
+static int (*K_X509_get_ext_count)(X509*) = 0L;
+static int (*K_X509_get_ext_by_NID)(X509*, int, int) = 0L;
+static int (*K_X509_get_ext_by_OBJ)(X509*,ASN1_OBJECT*,int) = 0L;
+static X509_EXTENSION *(*K_X509_get_ext)(X509*, int loc) = 0L;
+static X509_EXTENSION *(*K_X509_delete_ext)(X509*, int) = 0L;
+static int (*K_X509_add_ext)(X509*, X509_EXTENSION*, int) = 0L;
+static void *(*K_X509_get_ext_d2i)(X509*, int, int*, int*) = 0L;
+static char *(*K_i2s_ASN1_OCTET_STRING)(X509V3_EXT_METHOD*, ASN1_OCTET_STRING*) = 0L;
+static int (*K_ASN1_BIT_STRING_get_bit)(ASN1_BIT_STRING*, int) = 0L;
+static PKCS7 *(*K_PKCS7_new)() = 0L;
+static void (*K_PKCS7_free)(PKCS7*) = 0L;
+static void (*K_PKCS7_content_free)(PKCS7*) = 0L;
+static int (*K_i2d_PKCS7)(PKCS7*, unsigned char**) = 0L;
+static PKCS7 *(*K_d2i_PKCS7)(PKCS7**, unsigned char**,long) = 0L;
+static int (*K_i2d_PKCS7_fp)(FILE*,PKCS7*) = 0L;
+static PKCS7* (*K_d2i_PKCS7_fp)(FILE*,PKCS7**) = 0L;
+static int (*K_i2d_PKCS7_bio)(BIO *bp,PKCS7 *p7) = 0L;
+static PKCS7 *(*K_d2i_PKCS7_bio)(BIO *bp,PKCS7 **p7) = 0L;
+static PKCS7* (*K_PKCS7_dup)(PKCS7*) = 0L;
+static STACK_OF(X509_NAME) *(*K_SSL_load_client_CA_file)(const char*) = 0L;
+static STACK_OF(X509_INFO) *(*K_PEM_X509_INFO_read)(FILE*, STACK_OF(X509_INFO)*, pem_password_cb*, void*) = 0L;
+static char *(*K_ASN1_d2i_fp)(char *(*)(),char *(*)(),FILE*,unsigned char**) = 0L;
+static X509 *(*K_X509_new)() = 0L;
+static int (*K_X509_PURPOSE_get_count)() = 0L;
+static int (*K_X509_PURPOSE_get_id)(X509_PURPOSE *) = 0L;
+static int (*K_X509_check_purpose)(X509*,int,int) = 0L;
+static X509_PURPOSE* (*K_X509_PURPOSE_get0)(int) = 0L;
+static int (*K_EVP_PKEY_assign)(EVP_PKEY*, int, char*) = 0L;
+static int (*K_X509_REQ_set_pubkey)(X509_REQ*, EVP_PKEY*) = 0L;
+static RSA *(*K_RSA_generate_key)(int, unsigned long, void (*)(int,int,void *), void *) = 0L;
+static int (*K_i2d_X509_REQ_fp)(FILE*, X509_REQ*) = 0L;
+static void (*K_ERR_clear_error)() = 0L;
+static unsigned long (*K_ERR_get_error)() = 0L;
+static void (*K_ERR_print_errors_fp)(FILE*) = 0L;
+static PKCS7 *(*K_PKCS7_sign)(X509*, EVP_PKEY*, STACK_OF(X509)*, BIO*, int) = 0L;
+static int (*K_PKCS7_verify)(PKCS7*,STACK_OF(X509)*,X509_STORE*,BIO*,BIO*,int) = 0L;
+static STACK_OF(X509) *(*K_PKCS7_get0_signers)(PKCS7 *, STACK_OF(X509) *, int) = 0L;
+static PKCS7 *(*K_PKCS7_encrypt)(STACK_OF(X509) *, BIO *, EVP_CIPHER *, int) = 0L;
+static int (*K_PKCS7_decrypt)(PKCS7 *, EVP_PKEY *, X509 *, BIO *, int) = 0L;
+static SSL_SESSION* (*K_SSL_get1_session)(SSL*) = 0L;
+static void (*K_SSL_SESSION_free)(SSL_SESSION*) = 0L;
+static int (*K_SSL_set_session)(SSL*,SSL_SESSION*) = 0L;
+static SSL_SESSION* (*K_d2i_SSL_SESSION)(SSL_SESSION**,unsigned char**, long) = 0L;
+static int (*K_i2d_SSL_SESSION)(SSL_SESSION*,unsigned char**) = 0L;
+static STACK *(*K_X509_get1_email)(X509 *x) = 0L;
+static void (*K_X509_email_free)(STACK *sk) = 0L;
+static EVP_CIPHER *(*K_EVP_des_ede3_cbc)() = 0L;
+static EVP_CIPHER *(*K_EVP_des_cbc)() = 0L;
+static EVP_CIPHER *(*K_EVP_rc2_cbc)() = 0L;
+static EVP_CIPHER *(*K_EVP_rc2_64_cbc)() = 0L;
+static EVP_CIPHER *(*K_EVP_rc2_40_cbc)() = 0L;
+static int (*K_i2d_PrivateKey_fp)(FILE*,EVP_PKEY*) = 0L;
+static int (*K_i2d_PKCS8PrivateKey_fp)(FILE*, EVP_PKEY*, const EVP_CIPHER*, char*, int, pem_password_cb*, void*) = 0L;
+static void (*K_RSA_free)(RSA*) = 0L;
+static EVP_CIPHER *(*K_EVP_bf_cbc)() = 0L;
+static int (*K_X509_REQ_sign)(X509_REQ*, EVP_PKEY*, const EVP_MD*) = 0L;
+static int (*K_X509_NAME_add_entry_by_txt)(X509_NAME*, char*, int, unsigned char*, int, int, int) = 0L;
+static X509_NAME *(*K_X509_NAME_new)() = 0L;
+static int (*K_X509_REQ_set_subject_name)(X509_REQ*,X509_NAME*) = 0L;
+static unsigned char *(*K_ASN1_STRING_data)(ASN1_STRING*) = 0L;
+static int (*K_ASN1_STRING_length)(ASN1_STRING*) = 0L;
+static STACK_OF(SSL_CIPHER) *(*K_SSL_get_ciphers)(const SSL *ssl) = 0L;
+
+#endif
+}
+
+
+bool KOpenSSLProxy::hasLibSSL() const {
+ return _sslLib != 0L;
+}
+
+
+bool KOpenSSLProxy::hasLibCrypto() const {
+ return _cryptoLib != 0L;
+}
+
+
+void KOpenSSLProxy::destroy() {
+ delete this;
+ _me = 0L;
+}
+
+#ifdef __OpenBSD__
+#include <tqdir.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+
+static TQString findMostRecentLib(TQString dir, TQString name)
+{
+ // Grab all shared libraries in the directory
+ TQString filter = "lib"+name+".so.*";
+ TQDir d(dir, filter);
+ if (!d.exists())
+ return 0L;
+ TQStringList l = d.entryList();
+
+ // Find the best one
+ int bestmaj = -1;
+ int bestmin = -1;
+ TQString best = 0L;
+ // where do we start
+ uint s = filter.length()-1;
+ for (TQStringList::Iterator it = l.begin(); it != l.end(); ++it) {
+ TQString numberpart = (*it).mid(s);
+ uint endmaj = numberpart.find('.');
+ if (endmaj == -1)
+ continue;
+ bool ok;
+ int maj = numberpart.left(endmaj).toInt(&ok);
+ if (!ok)
+ continue;
+ int min = numberpart.mid(endmaj+1).toInt(&ok);
+ if (!ok)
+ continue;
+ if (maj > bestmaj || (maj == bestmaj && min > bestmin)) {
+ bestmaj = maj;
+ bestmin = min;
+ best = (*it);
+ }
+ }
+ if (best.isNull())
+ return 0L;
+ else
+ return dir+"/"+best;
+}
+#endif
+
+
+KOpenSSLProxy::KOpenSSLProxy() {
+KLibLoader *ll = KLibLoader::self();
+_ok = false;
+TQStringList libpaths, libnamesc, libnamess;
+TDEConfig *cfg;
+
+ _cryptoLib = 0L;
+ _sslLib = 0L;
+
+ cfg = new TDEConfig("cryptodefaults", false, false);
+ cfg->setGroup("OpenSSL");
+ TQString upath = cfg->readPathEntry("Path");
+ if (!upath.isEmpty())
+ libpaths << upath;
+
+ delete cfg;
+
+#ifdef __OpenBSD__
+ {
+ TQString libname = findMostRecentLib("/usr/lib" KDELIBSUFF, "crypto");
+ if (!libname.isNull())
+ _cryptoLib = ll->globalLibrary(libname.latin1());
+ }
+#elif defined(__CYGWIN__)
+ libpaths << "/usr/bin/"
+ << "/usr/local/bin"
+ << "/usr/local/openssl/bin"
+ << "/opt/openssl/bin"
+ << "/opt/trinity/bin"
+ << "";
+
+ libnamess << "cygssl-0.9.7.dll"
+ << "cygssl.dll"
+ << "libssl.dll"
+ << "";
+
+ libnamesc << "cygcrypto.dll"
+ << "libcrypto.dll"
+ << "";
+#else
+ libpaths
+ #ifdef _AIX
+ << "/opt/freeware/lib/"
+ #endif
+ << "/usr/lib" KDELIBSUFF "/"
+ << "/usr/ssl/lib" KDELIBSUFF "/"
+ << "/usr/local/lib" KDELIBSUFF "/"
+ << "/usr/local/openssl/lib" KDELIBSUFF "/"
+ << "/usr/local/ssl/lib" KDELIBSUFF "/"
+ << "/opt/openssl/lib" KDELIBSUFF "/"
+ << "/lib" KDELIBSUFF "/"
+ << "";
+
+// FIXME: #define here for the various OS types to optimize
+ libnamess
+ #ifdef hpux
+ << "libssl.sl"
+ #elif defined(_AIX)
+ << "libssl.a(libssl.so.0)"
+ #elif defined(__APPLE__)
+ << "libssl.dylib"
+ << "libssl.0.9.dylib"
+ #else
+ #ifdef SHLIB_VERSION_NUMBER
+ << "libssl.so." SHLIB_VERSION_NUMBER
+ #endif
+ << "libssl.so"
+ << "libssl.so.0"
+ #endif
+ ;
+
+ libnamesc
+ #ifdef hpux
+ << "libcrypto.sl"
+ #elif defined(_AIX)
+ << "libcrypto.a(libcrypto.so.0)"
+ #elif defined(__APPLE__)
+ << "libcrypto.dylib"
+ << "libcrypto.0.9.dylib"
+ #else
+ #ifdef SHLIB_VERSION_NUMBER
+ << "libcrypto.so." SHLIB_VERSION_NUMBER
+ #endif
+ << "libcrypto.so"
+ << "libcrypto.so.0"
+ #endif
+ ;
+#endif
+
+ for (TQStringList::Iterator it = libpaths.begin();
+ it != libpaths.end();
+ ++it) {
+ for (TQStringList::Iterator shit = libnamesc.begin();
+ shit != libnamesc.end();
+ ++shit) {
+ TQString alib = *it;
+ if (!alib.isEmpty() && !alib.endsWith("/"))
+ alib += "/";
+ alib += *shit;
+ TQString tmpStr(alib.latin1());
+ tmpStr.replace(TQRegExp("\\(.*\\)"), "");
+ if (!access(tmpStr.latin1(), R_OK))
+ _cryptoLib = ll->globalLibrary(alib.latin1());
+ if (!_cryptoLib) {
+ // Multiarch triplet search
+ TQDir madir (*it);
+ TQStringList multiarchdirs = madir.entryList("*-*-*", TQDir::Dirs);
+ for (TQStringList::Iterator mait = multiarchdirs.begin(); mait != multiarchdirs.end(); ++mait ) {
+ TQString malib = *it + *mait + "/" + *shit;
+ TQString tmpStr(malib.latin1());
+ tmpStr.replace(TQRegExp("\\(.*\\)"), "");
+ if (!access(tmpStr.latin1(), R_OK))
+ _cryptoLib = ll->globalLibrary(malib.latin1());
+ }
+ }
+ if (_cryptoLib) break;
+ }
+ if (_cryptoLib) break;
+ }
+
+ if (_cryptoLib) {
+#ifdef KSSL_HAVE_SSL
+ K_X509_free = (void (*) (X509 *)) _cryptoLib->symbol("X509_free");
+ K_RAND_egd = (int (*)(const char *)) _cryptoLib->symbol("RAND_egd");
+ K_RAND_load_file = (int (*)(const char *, long)) _cryptoLib->symbol("RAND_load_file");
+ K_RAND_file_name = (const char* (*)(char *, size_t)) _cryptoLib->symbol("RAND_file_name");
+ K_RAND_write_file = (int (*)(const char *)) _cryptoLib->symbol("RAND_write_file");
+ K_CRYPTO_free = (void (*) (void *)) _cryptoLib->symbol("CRYPTO_free");
+ K_d2i_X509 = (X509 * (*)(X509 **,unsigned char **,long)) _cryptoLib->symbol("d2i_X509");
+ K_i2d_X509 = (int (*)(X509 *,unsigned char **)) _cryptoLib->symbol("i2d_X509");
+ K_X509_cmp = (int (*)(X509 *, X509 *)) _cryptoLib->symbol("X509_cmp");
+ K_X509_STORE_CTX_new = (X509_STORE_CTX * (*) (void)) _cryptoLib->symbol("X509_STORE_CTX_new");
+ K_X509_STORE_CTX_free = (void (*) (X509_STORE_CTX *)) _cryptoLib->symbol("X509_STORE_CTX_free");
+ K_X509_verify_cert = (int (*) (X509_STORE_CTX *)) _cryptoLib->symbol("X509_verify_cert");
+ K_X509_STORE_new = (X509_STORE * (*) (void)) _cryptoLib->symbol("X509_STORE_new");
+ K_X509_STORE_free = (void (*) (X509_STORE *)) _cryptoLib->symbol("X509_STORE_free");
+ K_X509_NAME_oneline = (char * (*) (X509_NAME *,char *,int)) _cryptoLib->symbol("X509_NAME_oneline");
+ K_X509_get_subject_name = (X509_NAME * (*) (X509 *)) _cryptoLib->symbol("X509_get_subject_name");
+ K_X509_get_issuer_name = (X509_NAME * (*) (X509 *)) _cryptoLib->symbol("X509_get_issuer_name");
+ K_X509_STORE_add_lookup = (X509_LOOKUP *(*) (X509_STORE *, X509_LOOKUP_METHOD *)) _cryptoLib->symbol("X509_STORE_add_lookup");
+ K_X509_LOOKUP_file = (X509_LOOKUP_METHOD *(*)(void)) _cryptoLib->symbol("X509_LOOKUP_file");
+ K_X509_LOOKUP_free = (void (*)(X509_LOOKUP *)) _cryptoLib->symbol("X509_LOOKUP_free");
+ K_X509_LOOKUP_ctrl = (int (*)(X509_LOOKUP *, int, const char *, long, char **)) _cryptoLib->symbol("X509_LOOKUP_ctrl");
+ K_X509_STORE_CTX_init = (void (*)(X509_STORE_CTX *, X509_STORE *, X509 *, STACK_OF(X509) *)) _cryptoLib->symbol("X509_STORE_CTX_init");
+ K_X509_dup = (X509* (*)(X509*)) _cryptoLib->symbol("X509_dup");
+ K_BIO_s_mem = (BIO_METHOD *(*) (void)) _cryptoLib->symbol("BIO_s_mem");
+ K_BIO_new = (BIO* (*)(BIO_METHOD *)) _cryptoLib->symbol("BIO_new");
+ K_BIO_new_fp = (BIO* (*)(FILE*, int)) _cryptoLib->symbol("BIO_new_fp");
+ K_BIO_new_mem_buf = (BIO* (*)(void *, int)) _cryptoLib->symbol("BIO_new_mem_buf");
+ K_BIO_free = (int (*)(BIO*)) _cryptoLib->symbol("BIO_free");
+ K_BIO_ctrl = (long (*) (BIO *,int,long,void *)) _cryptoLib->symbol("BIO_ctrl");
+ K_BIO_write = (int (*) (BIO *b, const void *data, int len)) _cryptoLib->symbol("BIO_write");
+ K_PEM_ASN1_write_bio = (int (*)(int (*)(), const char *,BIO*, char*, const EVP_CIPHER *, unsigned char *, int, pem_password_cb *, void *)) _cryptoLib->symbol("PEM_ASN1_write_bio");
+#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+ K_ASN1_item_i2d_fp = (int (*)(ASN1_ITEM *, FILE*, unsigned char *)) _cryptoLib->symbol("ASN1_item_i2d_fp");
+ K_NETSCAPE_X509_it = (ASN1_ITEM *) _cryptoLib->symbol("NETSCAPE_X509_it");
+#else
+ K_X509_asn1_meth = (ASN1_METHOD* (*)(void)) _cryptoLib->symbol("X509_asn1_meth");
+ K_ASN1_i2d_fp = (int (*)(int (*)(), FILE*, unsigned char *)) _cryptoLib->symbol("ASN1_i2d_fp");
+ K_i2d_ASN1_HEADER = (int (*)(ASN1_HEADER *, unsigned char **)) _cryptoLib->symbol("i2d_ASN1_HEADER");
+#endif
+ K_X509_print_fp = (int (*)(FILE*, X509*)) _cryptoLib->symbol("X509_print_fp");
+ K_i2d_PKCS12 = (int (*)(PKCS12*, unsigned char**)) _cryptoLib->symbol("i2d_PKCS12");
+ K_i2d_PKCS12_fp = (int (*)(FILE *, PKCS12*)) _cryptoLib->symbol("i2d_PKCS12_fp");
+ K_PKCS12_newpass = (int (*)(PKCS12*, char*, char*)) _cryptoLib->symbol("PKCS12_newpass");
+ K_d2i_PKCS12_fp = (PKCS12* (*)(FILE*, PKCS12**)) _cryptoLib->symbol("d2i_PKCS12_fp");
+ K_PKCS12_new = (PKCS12* (*)()) _cryptoLib->symbol("PKCS12_new");
+ K_PKCS12_free = (void (*)(PKCS12 *)) _cryptoLib->symbol("PKCS12_free");
+ K_PKCS12_parse = (int (*)(PKCS12*, const char *, EVP_PKEY**,
+ X509**, STACK_OF(X509)**)) _cryptoLib->symbol("PKCS12_parse");
+ K_EVP_PKEY_free = (void (*) (EVP_PKEY *)) _cryptoLib->symbol("EVP_PKEY_free");
+ K_EVP_PKEY_new = (EVP_PKEY* (*)()) _cryptoLib->symbol("EVP_PKEY_new");
+ K_X509_REQ_free = (void (*)(X509_REQ*)) _cryptoLib->symbol("X509_REQ_free");
+ K_X509_REQ_new = (X509_REQ* (*)()) _cryptoLib->symbol("X509_REQ_new");
+ K_X509_STORE_CTX_set_chain = (void (*)(X509_STORE_CTX *, STACK_OF(X509)*)) _cryptoLib->symbol("X509_STORE_CTX_set_chain");
+ K_X509_STORE_CTX_set_purpose = (void (*)(X509_STORE_CTX *, int)) _cryptoLib->symbol("X509_STORE_CTX_set_purpose");
+ K_sk_free = (void (*) (STACK *)) _cryptoLib->symbol("sk_free");
+ K_sk_num = (int (*) (STACK *)) _cryptoLib->symbol("sk_num");
+ K_sk_pop = (char* (*) (STACK *)) _cryptoLib->symbol("sk_pop");
+ K_sk_value = (char* (*) (STACK *, int)) _cryptoLib->symbol("sk_value");
+ K_sk_new = (STACK* (*) (int (*)())) _cryptoLib->symbol("sk_new");
+ K_sk_push = (int (*) (STACK*, char*)) _cryptoLib->symbol("sk_push");
+ K_sk_dup = (STACK* (*) (STACK *)) _cryptoLib->symbol("sk_dup");
+ K_i2s_ASN1_INTEGER = (char *(*) (X509V3_EXT_METHOD *, ASN1_INTEGER *)) _cryptoLib->symbol("i2s_ASN1_INTEGER");
+ K_X509_get_serialNumber = (ASN1_INTEGER * (*) (X509 *)) _cryptoLib->symbol("X509_get_serialNumber");
+ K_X509_get_pubkey = (EVP_PKEY *(*)(X509 *)) _cryptoLib->symbol("X509_get_pubkey");
+ K_i2d_PublicKey = (int (*)(EVP_PKEY *, unsigned char **)) _cryptoLib->symbol("i2d_PublicKey");
+ K_X509_check_private_key = (int (*)(X509 *, EVP_PKEY *)) _cryptoLib->symbol("X509_check_private_key");
+ K_BN_bn2hex = (char *(*)(const BIGNUM *)) _cryptoLib->symbol("BN_bn2hex");
+ K_X509_digest = (int (*)(const X509 *,const EVP_MD *, unsigned char *, unsigned int *)) _cryptoLib->symbol("X509_digest");
+ K_EVP_md5 = (EVP_MD *(*)()) _cryptoLib->symbol("EVP_md5");
+ K_ASN1_INTEGER_free = (void (*)(ASN1_INTEGER *)) _cryptoLib->symbol("ASN1_INTEGER_free");
+ K_OBJ_obj2nid = (int (*)(ASN1_OBJECT *)) _cryptoLib->symbol("OBJ_obj2nid");
+ K_OBJ_nid2ln = (const char *(*)(int)) _cryptoLib->symbol("OBJ_nid2ln");
+ K_X509_get_ext_count = (int (*)(X509*)) _cryptoLib->symbol("X509_get_ext_count");
+ K_X509_get_ext_by_NID = (int (*)(X509*,int,int)) _cryptoLib->symbol("X509_get_ext_by_NID");
+ K_X509_get_ext_by_OBJ = (int (*)(X509*,ASN1_OBJECT*,int)) _cryptoLib->symbol("X509_get_ext_by_OBJ");
+ K_X509_get_ext = (X509_EXTENSION* (*)(X509*,int)) _cryptoLib->symbol("X509_get_ext");
+ K_X509_delete_ext = (X509_EXTENSION* (*)(X509*,int)) _cryptoLib->symbol("X509_delete_ext");
+ K_X509_add_ext = (int (*)(X509*,X509_EXTENSION*,int)) _cryptoLib->symbol("X509_add_ext");
+ K_X509_get_ext_d2i = (void* (*)(X509*,int,int*,int*)) _cryptoLib->symbol("X509_get_ext_d2i");
+ K_i2s_ASN1_OCTET_STRING = (char *(*)(X509V3_EXT_METHOD*,ASN1_OCTET_STRING*)) _cryptoLib->symbol("i2s_ASN1_OCTET_STRING");
+ K_ASN1_BIT_STRING_get_bit = (int (*)(ASN1_BIT_STRING*,int)) _cryptoLib->symbol("ASN1_BIT_STRING_get_bit");
+ K_PKCS7_new = (PKCS7 *(*)()) _cryptoLib->symbol("PKCS7_new");
+ K_PKCS7_free = (void (*)(PKCS7*)) _cryptoLib->symbol("PKCS7_free");
+ K_PKCS7_content_free = (void (*)(PKCS7*)) _cryptoLib->symbol("PKCS7_content_free");
+ K_i2d_PKCS7 = (int (*)(PKCS7*, unsigned char**)) _cryptoLib->symbol("i2d_PKCS7");
+ K_i2d_PKCS7_fp = (int (*)(FILE*,PKCS7*)) _cryptoLib->symbol("i2d_PKCS7_fp");
+ K_i2d_PKCS7_bio = (int (*)(BIO *bp,PKCS7 *p7)) _cryptoLib->symbol("i2d_PKCS7_bio");
+ K_d2i_PKCS7 = (PKCS7* (*)(PKCS7**,unsigned char**,long)) _cryptoLib->symbol("d2i_PKCS7");
+ K_d2i_PKCS7_fp = (PKCS7 *(*)(FILE *,PKCS7**)) _cryptoLib->symbol("d2i_PKCS7_fp");
+ K_d2i_PKCS7_bio = (PKCS7 *(*)(BIO *bp,PKCS7 **p7)) _cryptoLib->symbol("d2i_PKCS7_bio");
+ K_PKCS7_dup = (PKCS7* (*)(PKCS7*)) _cryptoLib->symbol("PKCS7_dup");
+ K_PKCS7_sign = (PKCS7 *(*)(X509*, EVP_PKEY*, STACK_OF(X509)*, BIO*, int)) _cryptoLib->symbol("PKCS7_sign");
+ K_PKCS7_verify = (int (*)(PKCS7*,STACK_OF(X509)*,X509_STORE*,BIO*,BIO*,int)) _cryptoLib->symbol("PKCS7_verify");
+ K_PKCS7_get0_signers = (STACK_OF(X509) *(*)(PKCS7 *, STACK_OF(X509) *, int)) _cryptoLib->symbol("PKCS7_get0_signers");
+ K_PKCS7_encrypt = (PKCS7* (*)(STACK_OF(X509) *, BIO *, EVP_CIPHER *, int)) _cryptoLib->symbol("PKCS7_encrypt");
+ K_PKCS7_decrypt = (int (*)(PKCS7 *, EVP_PKEY *, X509 *, BIO *, int)) _cryptoLib->symbol("PKCS7_decrypt");
+ K_PEM_X509_INFO_read = (STACK_OF(X509_INFO) *(*)(FILE*, STACK_OF(X509_INFO)*, pem_password_cb*, void *)) _cryptoLib->symbol("PEM_X509_INFO_read");
+ K_ASN1_d2i_fp = (char *(*)(char *(*)(),char *(*)(),FILE*,unsigned char**)) _cryptoLib->symbol("ASN1_d2i_fp");
+ K_X509_new = (X509 *(*)()) _cryptoLib->symbol("X509_new");
+ K_X509_PURPOSE_get_count = (int (*)()) _cryptoLib->symbol("X509_PURPOSE_get_count");
+ K_X509_PURPOSE_get_id = (int (*)(X509_PURPOSE *)) _cryptoLib->symbol("X509_PURPOSE_get_id");
+ K_X509_check_purpose = (int (*)(X509*,int,int)) _cryptoLib->symbol("X509_check_purpose");
+ K_X509_PURPOSE_get0 = (X509_PURPOSE *(*)(int)) _cryptoLib->symbol("X509_PURPOSE_get0");
+ K_EVP_PKEY_assign = (int (*)(EVP_PKEY*, int, char*)) _cryptoLib->symbol("EVP_PKEY_assign");
+ K_X509_REQ_set_pubkey = (int (*)(X509_REQ*, EVP_PKEY*)) _cryptoLib->symbol("X509_REQ_set_pubkey");
+ K_RSA_generate_key = (RSA* (*)(int, unsigned long, void (*)(int,int,void *), void *)) _cryptoLib->symbol("RSA_generate_key");
+ K_i2d_X509_REQ_fp = (int (*)(FILE *, X509_REQ *)) _cryptoLib->symbol("i2d_X509_REQ_fp");
+ K_ERR_clear_error = (void (*)()) _cryptoLib->symbol("ERR_clear_error");
+ K_ERR_get_error = (unsigned long (*)()) _cryptoLib->symbol("ERR_get_error");
+ K_ERR_print_errors_fp = (void (*)(FILE*)) _cryptoLib->symbol("ERR_print_errors_fp");
+ K_X509_get1_email = (STACK *(*)(X509 *x)) _cryptoLib->symbol("X509_get1_email");
+ K_X509_email_free = (void (*)(STACK *sk)) _cryptoLib->symbol("X509_email_free");
+ K_EVP_des_ede3_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_des_ede3_cbc");
+ K_EVP_des_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_des_cbc");
+ K_EVP_rc2_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_rc2_cbc");
+ K_EVP_rc2_64_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_rc2_64_cbc");
+ K_EVP_rc2_40_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_rc2_40_cbc");
+ K_i2d_PrivateKey_fp = (int (*)(FILE*,EVP_PKEY*)) _cryptoLib->symbol("i2d_PrivateKey_fp");
+ K_i2d_PKCS8PrivateKey_fp = (int (*)(FILE*, EVP_PKEY*, const EVP_CIPHER*, char*, int, pem_password_cb*, void*)) _cryptoLib->symbol("i2d_PKCS8PrivateKey_fp");
+ K_RSA_free = (void (*)(RSA*)) _cryptoLib->symbol("RSA_free");
+ K_EVP_bf_cbc = (EVP_CIPHER *(*)()) _cryptoLib->symbol("EVP_bf_cbc");
+ K_X509_REQ_sign = (int (*)(X509_REQ*, EVP_PKEY*, const EVP_MD*)) _cryptoLib->symbol("X509_REQ_sign");
+ K_X509_NAME_add_entry_by_txt = (int (*)(X509_NAME*, char*, int, unsigned char*, int, int, int)) _cryptoLib->symbol("X509_NAME_add_entry_by_txt");
+ K_X509_NAME_new = (X509_NAME *(*)()) _cryptoLib->symbol("X509_NAME_new");
+ K_X509_REQ_set_subject_name = (int (*)(X509_REQ*,X509_NAME*)) _cryptoLib->symbol("X509_REQ_set_subject_name");
+ K_ASN1_STRING_data = (unsigned char *(*)(ASN1_STRING*)) _cryptoLib->symbol("ASN1_STRING_data");
+ K_ASN1_STRING_length = (int (*)(ASN1_STRING*)) _cryptoLib->symbol("ASN1_STRING_length");
+#endif
+ }
+
+#ifdef __OpenBSD__
+ {
+ TQString libname = findMostRecentLib("/usr/lib", "ssl");
+ if (!libname.isNull())
+ _sslLib = ll->globalLibrary(libname.latin1());
+ }
+#else
+ for (TQStringList::Iterator it = libpaths.begin();
+ it != libpaths.end();
+ ++it) {
+ for (TQStringList::Iterator shit = libnamess.begin();
+ shit != libnamess.end();
+ ++shit) {
+ TQString alib = *it;
+ if (!alib.isEmpty() && !alib.endsWith("/"))
+ alib += "/";
+ alib += *shit;
+ TQString tmpStr(alib.latin1());
+ tmpStr.replace(TQRegExp("\\(.*\\)"), "");
+ if (!access(tmpStr.latin1(), R_OK))
+ _sslLib = ll->globalLibrary(alib.latin1());
+ if (!_sslLib) {
+ // Multiarch triplet search
+ TQDir madir (*it);
+ TQStringList multiarchdirs = madir.entryList("*-*-*", TQDir::Dirs);
+ for (TQStringList::Iterator mait = multiarchdirs.begin(); mait != multiarchdirs.end(); ++mait ) {
+ TQString malib = *it + *mait + "/" + *shit;
+ TQString tmpStr(malib.latin1());
+ tmpStr.replace(TQRegExp("\\(.*\\)"), "");
+ if (!access(tmpStr.latin1(), R_OK))
+ _sslLib = ll->globalLibrary(malib.latin1());
+ }
+ }
+ if (_sslLib) break;
+ }
+ if (_sslLib) break;
+ }
+#endif
+
+ if (_sslLib) {
+#ifdef KSSL_HAVE_SSL
+ // stand back from your monitor and look at this. it's fun! :)
+ K_SSL_connect = (int (*)(SSL *)) _sslLib->symbol("SSL_connect");
+ K_SSL_accept = (int (*)(SSL *)) _sslLib->symbol("SSL_accept");
+ K_SSL_read = (int (*)(SSL *, void *, int)) _sslLib->symbol("SSL_read");
+ K_SSL_write = (int (*)(SSL *, const void *, int))
+ _sslLib->symbol("SSL_write");
+ K_SSL_new = (SSL* (*)(SSL_CTX *)) _sslLib->symbol("SSL_new");
+ K_SSL_free = (void (*)(SSL *)) _sslLib->symbol("SSL_free");
+ K_SSL_shutdown = (int (*)(SSL *)) _sslLib->symbol("SSL_shutdown");
+ K_SSL_CTX_new = (SSL_CTX* (*)(SSL_METHOD*)) _sslLib->symbol("SSL_CTX_new");
+ K_SSL_CTX_free = (void (*)(SSL_CTX*)) _sslLib->symbol("SSL_CTX_free");
+ K_SSL_set_fd = (int (*)(SSL *, int)) _sslLib->symbol("SSL_set_fd");
+ K_SSL_pending = (int (*)(SSL *)) _sslLib->symbol("SSL_pending");
+ K_SSL_CTX_set_cipher_list = (int (*)(SSL_CTX *, const char *))
+ _sslLib->symbol("SSL_CTX_set_cipher_list");
+ K_SSL_CTX_set_verify = (void (*)(SSL_CTX*, int, int (*)(int, X509_STORE_CTX*))) _sslLib->symbol("SSL_CTX_set_verify");
+ K_SSL_use_certificate = (int (*)(SSL*, X509*))
+ _sslLib->symbol("SSL_CTX_use_certificate");
+ K_SSL_get_current_cipher = (SSL_CIPHER *(*)(SSL *))
+ _sslLib->symbol("SSL_get_current_cipher");
+ K_SSL_ctrl = (long (*)(SSL * ,int, long, char *))
+ _sslLib->symbol("SSL_ctrl");
+ K_TLSv1_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("TLSv1_client_method");
+ K_SSLv2_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("SSLv2_client_method");
+ K_SSLv3_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("SSLv3_client_method");
+ K_SSLv23_client_method = (SSL_METHOD *(*)()) _sslLib->symbol("SSLv23_client_method");
+ K_SSL_get_peer_certificate = (X509 *(*)(SSL *)) _sslLib->symbol("SSL_get_peer_certificate");
+ K_SSL_CIPHER_get_bits = (int (*)(SSL_CIPHER *,int *)) _sslLib->symbol("SSL_CIPHER_get_bits");
+ K_SSL_CIPHER_get_version = (char * (*)(SSL_CIPHER *)) _sslLib->symbol("SSL_CIPHER_get_version");
+ K_SSL_CIPHER_get_name = (const char * (*)(SSL_CIPHER *)) _sslLib->symbol("SSL_CIPHER_get_name");
+ K_SSL_CIPHER_description = (char * (*)(SSL_CIPHER *, char *, int)) _sslLib->symbol("SSL_CIPHER_description");
+ K_SSL_CTX_use_PrivateKey = (int (*)(SSL_CTX*, EVP_PKEY*)) _sslLib->symbol("SSL_CTX_use_PrivateKey");
+ K_SSL_CTX_use_certificate = (int (*)(SSL_CTX*, X509*)) _sslLib->symbol("SSL_CTX_use_certificate");
+ K_SSL_get_error = (int (*)(SSL*, int)) _sslLib->symbol("SSL_get_error");
+ K_SSL_get_peer_cert_chain = (STACK_OF(X509)* (*)(SSL*)) _sslLib->symbol("SSL_get_peer_cert_chain");
+ K_SSL_load_client_CA_file = (STACK_OF(X509_NAME)* (*)(const char *)) _sslLib->symbol("SSL_load_client_CA_file");
+ K_SSL_peek = (int (*)(SSL*,void*,int)) _sslLib->symbol("SSL_peek");
+ K_SSL_get1_session = (SSL_SESSION* (*)(SSL*)) _sslLib->symbol("SSL_get1_session");
+ K_SSL_SESSION_free = (void (*)(SSL_SESSION*)) _sslLib->symbol("SSL_SESSION_free");
+ K_SSL_set_session = (int (*)(SSL*,SSL_SESSION*)) _sslLib->symbol("SSL_set_session");
+ K_d2i_SSL_SESSION = (SSL_SESSION* (*)(SSL_SESSION**,unsigned char**, long)) _sslLib->symbol("d2i_SSL_SESSION");
+ K_i2d_SSL_SESSION = (int (*)(SSL_SESSION*,unsigned char**)) _sslLib->symbol("i2d_SSL_SESSION");
+ K_SSL_get_ciphers = (STACK_OF(SSL_CIPHER) *(*)(const SSL*)) _sslLib->symbol("SSL_get_ciphers");
+#endif
+
+
+ // Initialize the library (once only!)
+ void *x;
+ x = _sslLib->symbol("SSL_library_init");
+ if (_cryptoLib) {
+ if (x) ((int (*)())x)();
+ x = _cryptoLib->symbol("OpenSSL_add_all_algorithms");
+ if (!x)
+ x = _cryptoLib->symbol("OPENSSL_add_all_algorithms");
+ if (x) {
+ ((void (*)())x)();
+ } else {
+ x = _cryptoLib->symbol("OpenSSL_add_all_algorithms_conf");
+ if (!x)
+ x = _cryptoLib->symbol("OPENSSL_add_all_algorithms_conf");
+ if (x) {
+ ((void (*)())x)();
+ } else {
+ x = _cryptoLib->symbol("OpenSSL_add_all_algorithms_noconf");
+ if (!x)
+ x = _cryptoLib->symbol("OPENSSL_add_all_algorithms_noconf");
+ if (x)
+ ((void (*)())x)();
+ }
+ }
+ x = _cryptoLib->symbol("OpenSSL_add_all_ciphers");
+ if (!x)
+ x = _cryptoLib->symbol("OPENSSL_add_all_ciphers");
+ if (x) ((void (*)())x)();
+ x = _cryptoLib->symbol("OpenSSL_add_all_digests");
+ if (!x)
+ x = _cryptoLib->symbol("OPENSSL_add_all_digests");
+ if (x) ((void (*)())x)();
+ }
+ }
+
+}
+
+
+KOpenSSLProxy* KOpenSSLProxy::_me = 0L;
+static KStaticDeleter<KOpenSSLProxy> medProxy;
+
+
+
+KOpenSSLProxy::~KOpenSSLProxy() {
+ if (_sslLib) {
+ _sslLib->unload();
+ }
+ if (_cryptoLib) {
+ _cryptoLib->unload();
+ }
+ medProxy.setObject(0);
+}
+
+
+// FIXME: we should check "ok" and allow this to init the lib if !ok.
+
+KOpenSSLProxy *KOpenSSLProxy::self() {
+#ifdef KSSL_HAVE_SSL
+ if (!_me) {
+ _me = medProxy.setObject(_me, new KOpenSSLProxy);
+ }
+#endif
+ return _me;
+}
+
+
+
+
+
+
+
+#ifdef KSSL_HAVE_SSL
+
+
+
+int KOpenSSLProxy::SSL_connect(SSL *ssl) {
+ if (K_SSL_connect) return (K_SSL_connect)(ssl);
+ return -1;
+}
+
+
+int KOpenSSLProxy::SSL_accept(SSL *ssl) {
+ if (K_SSL_accept) return (K_SSL_accept)(ssl);
+ return -1;
+}
+
+
+int KOpenSSLProxy::SSL_read(SSL *ssl, void *buf, int num) {
+ if (K_SSL_read) return (K_SSL_read)(ssl, buf, num);
+ return -1;
+}
+
+
+int KOpenSSLProxy::SSL_write(SSL *ssl, const void *buf, int num) {
+ if (K_SSL_write) return (K_SSL_write)(ssl, buf, num);
+ return -1;
+}
+
+
+SSL *KOpenSSLProxy::SSL_new(SSL_CTX *ctx) {
+ if (K_SSL_new) return (K_SSL_new)(ctx);
+ return 0L;
+}
+
+
+void KOpenSSLProxy::SSL_free(SSL *ssl) {
+ if (K_SSL_free) (K_SSL_free)(ssl);
+}
+
+
+int KOpenSSLProxy::SSL_shutdown(SSL *ssl) {
+ if (K_SSL_shutdown) return (K_SSL_shutdown)(ssl);
+ return -1;
+}
+
+
+SSL_CTX *KOpenSSLProxy::SSL_CTX_new(SSL_METHOD *method) {
+ if (K_SSL_CTX_new) return (K_SSL_CTX_new)(method);
+ return 0L;
+}
+
+
+void KOpenSSLProxy::SSL_CTX_free(SSL_CTX *ctx) {
+ if (K_SSL_CTX_free) (K_SSL_CTX_free)(ctx);
+}
+
+
+int KOpenSSLProxy::SSL_set_fd(SSL *ssl, int fd) {
+ if (K_SSL_set_fd) return (K_SSL_set_fd)(ssl, fd);
+ return -1;
+}
+
+
+int KOpenSSLProxy::SSL_pending(SSL *ssl) {
+ if (K_SSL_pending) return (K_SSL_pending)(ssl);
+ return -1;
+}
+
+
+int KOpenSSLProxy::SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str) {
+ if (K_SSL_CTX_set_cipher_list) return (K_SSL_CTX_set_cipher_list)(ctx, str);
+ return -1;
+}
+
+
+void KOpenSSLProxy::SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
+ int (*verify_callback)(int, X509_STORE_CTX *)) {
+ if (K_SSL_CTX_set_verify) (K_SSL_CTX_set_verify)(ctx, mode, verify_callback);
+}
+
+
+int KOpenSSLProxy::SSL_use_certificate(SSL *ssl, X509 *x) {
+ if (K_SSL_use_certificate) return (K_SSL_use_certificate)(ssl, x);
+ return -1;
+}
+
+
+SSL_CIPHER *KOpenSSLProxy::SSL_get_current_cipher(SSL *ssl) {
+ if (K_SSL_get_current_cipher) return (K_SSL_get_current_cipher)(ssl);
+ return 0L;
+}
+
+
+long KOpenSSLProxy::SSL_ctrl(SSL *ssl,int cmd, long larg, char *parg) {
+ if (K_SSL_ctrl) return (K_SSL_ctrl)(ssl, cmd, larg, parg);
+ return -1;
+}
+
+
+int KOpenSSLProxy::RAND_egd(const char *path) {
+ if (K_RAND_egd) return (K_RAND_egd)(path);
+ return -1;
+}
+
+
+SSL_METHOD *KOpenSSLProxy::TLSv1_client_method() {
+ if (K_TLSv1_client_method) return (K_TLSv1_client_method)();
+ return 0L;
+}
+
+
+SSL_METHOD *KOpenSSLProxy::SSLv2_client_method() {
+ if (K_SSLv2_client_method) return (K_SSLv2_client_method)();
+ return 0L;
+}
+
+
+SSL_METHOD *KOpenSSLProxy::SSLv3_client_method() {
+ if (K_SSLv3_client_method) return (K_SSLv3_client_method)();
+ return 0L;
+}
+
+
+SSL_METHOD *KOpenSSLProxy::SSLv23_client_method() {
+ if (K_SSLv23_client_method) return (K_SSLv23_client_method)();
+ return 0L;
+}
+
+
+X509 *KOpenSSLProxy::SSL_get_peer_certificate(SSL *s) {
+ if (K_SSL_get_peer_certificate) return (K_SSL_get_peer_certificate)(s);
+ return 0L;
+}
+
+
+int KOpenSSLProxy::SSL_CIPHER_get_bits(SSL_CIPHER *c,int *alg_bits) {
+ if (K_SSL_CIPHER_get_bits) return (K_SSL_CIPHER_get_bits)(c, alg_bits);
+ return -1;
+}
+
+
+char * KOpenSSLProxy::SSL_CIPHER_get_version(SSL_CIPHER *c) {
+ if (K_SSL_CIPHER_get_version) return (K_SSL_CIPHER_get_version)(c);
+ return 0L;
+}
+
+
+const char * KOpenSSLProxy::SSL_CIPHER_get_name(SSL_CIPHER *c) {
+ if (K_SSL_CIPHER_get_name) return (K_SSL_CIPHER_get_name)(c);
+ return 0L;
+}
+
+
+char * KOpenSSLProxy::SSL_CIPHER_description(SSL_CIPHER *c,char *buf,int size) {
+ if (K_SSL_CIPHER_description) return (K_SSL_CIPHER_description)(c,buf,size);
+ return 0L;
+}
+
+
+X509 * KOpenSSLProxy::d2i_X509(X509 **a,unsigned char **pp,long length) {
+ if (K_d2i_X509) return (K_d2i_X509)(a,pp,length);
+ return 0L;
+}
+
+
+int KOpenSSLProxy::i2d_X509(X509 *a,unsigned char **pp) {
+ if (K_i2d_X509) return (K_i2d_X509)(a,pp);
+ return -1;
+}
+
+
+int KOpenSSLProxy::X509_cmp(X509 *a, X509 *b) {
+ if (K_X509_cmp) return (K_X509_cmp)(a,b);
+ return 0;
+}
+
+
+X509_STORE *KOpenSSLProxy::X509_STORE_new(void) {
+ if (K_X509_STORE_new) return (K_X509_STORE_new)();
+ return 0L;
+}
+
+
+void KOpenSSLProxy::X509_STORE_free(X509_STORE *v) {
+ if (K_X509_STORE_free) (K_X509_STORE_free)(v);
+}
+
+
+X509_STORE_CTX *KOpenSSLProxy::X509_STORE_CTX_new(void) {
+ if (K_X509_STORE_CTX_new) return (K_X509_STORE_CTX_new)();
+ return 0L;
+}
+
+
+void KOpenSSLProxy::X509_STORE_CTX_free(X509_STORE_CTX *ctx) {
+ if (K_X509_STORE_CTX_free) (K_X509_STORE_CTX_free)(ctx);
+}
+
+
+int KOpenSSLProxy::X509_verify_cert(X509_STORE_CTX *ctx) {
+ if (K_X509_verify_cert) return (K_X509_verify_cert)(ctx);
+ return -1;
+}
+
+
+void KOpenSSLProxy::X509_free(X509 *a) {
+ if (K_X509_free) (K_X509_free)(a);
+}
+
+
+char *KOpenSSLProxy::X509_NAME_oneline(X509_NAME *a,char *buf,int size) {
+ if (K_X509_NAME_oneline) return (K_X509_NAME_oneline)(a,buf,size);
+ return 0L;
+}
+
+
+X509_NAME *KOpenSSLProxy::X509_get_subject_name(X509 *a) {
+ if (K_X509_get_subject_name) return (K_X509_get_subject_name)(a);
+ return 0L;
+}
+
+
+X509_NAME *KOpenSSLProxy::X509_get_issuer_name(X509 *a) {
+ if (K_X509_get_issuer_name) return (K_X509_get_issuer_name)(a);
+ return 0L;
+}
+
+
+X509_LOOKUP *KOpenSSLProxy::X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m) {
+ if (K_X509_STORE_add_lookup) return (K_X509_STORE_add_lookup)(v,m);
+ return 0L;
+}
+
+
+X509_LOOKUP_METHOD *KOpenSSLProxy::X509_LOOKUP_file(void) {
+ if (K_X509_LOOKUP_file) return (K_X509_LOOKUP_file)();
+ return 0L;
+}
+
+
+void KOpenSSLProxy::X509_LOOKUP_free(X509_LOOKUP *x) {
+ if (K_X509_LOOKUP_free) (K_X509_LOOKUP_free)(x);
+}
+
+
+int KOpenSSLProxy::X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret) {
+ if (K_X509_LOOKUP_ctrl) return (K_X509_LOOKUP_ctrl)(ctx,cmd,argc,argl,ret);
+ return -1;
+}
+
+
+void KOpenSSLProxy::X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509, STACK_OF(X509) *chain) {
+ if (K_X509_STORE_CTX_init) (K_X509_STORE_CTX_init)(ctx,store,x509,chain);
+}
+
+
+void KOpenSSLProxy::CRYPTO_free(void *x) {
+ if (K_CRYPTO_free) (K_CRYPTO_free)(x);
+}
+
+
+X509 *KOpenSSLProxy::X509_dup(X509 *x509) {
+ if (K_X509_dup) return (K_X509_dup)(x509);
+ return 0L;
+}
+
+
+BIO *KOpenSSLProxy::BIO_new(BIO_METHOD *type) {
+ if (K_BIO_new) return (K_BIO_new)(type);
+ else return 0L;
+}
+
+
+BIO_METHOD *KOpenSSLProxy::BIO_s_mem(void) {
+ if (K_BIO_s_mem) return (K_BIO_s_mem)();
+ else return 0L;
+}
+
+
+BIO *KOpenSSLProxy::BIO_new_fp(FILE *stream, int close_flag) {
+ if (K_BIO_new_fp) return (K_BIO_new_fp)(stream, close_flag);
+ return 0L;
+}
+
+
+BIO *KOpenSSLProxy::BIO_new_mem_buf(void *buf, int len) {
+ if (K_BIO_new_mem_buf) return (K_BIO_new_mem_buf)(buf,len);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::BIO_free(BIO *a) {
+ if (K_BIO_free) return (K_BIO_free)(a);
+ return -1;
+}
+
+
+long KOpenSSLProxy::BIO_ctrl(BIO *bp,int cmd,long larg,void *parg) {
+ if (K_BIO_ctrl) return (K_BIO_ctrl)(bp,cmd,larg,parg);
+ else return 0; // failure return for BIO_ctrl is quite individual, maybe we should abort() instead
+}
+
+
+int KOpenSSLProxy::BIO_write(BIO *b, const void *data, int len) {
+ if (K_BIO_write) return (K_BIO_write)(b, data, len);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::PEM_write_bio_X509(BIO *bp, X509 *x) {
+ if (K_PEM_ASN1_write_bio) return (K_PEM_ASN1_write_bio) ((int (*)())K_i2d_X509, PEM_STRING_X509, bp, (char *)x, 0L, 0L, 0, 0L, 0L);
+ else return -1;
+}
+
+#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+int KOpenSSLProxy::ASN1_i2d_fp(FILE *out,unsigned char *x) {
+ if (K_ASN1_item_i2d_fp && K_NETSCAPE_X509_it)
+ return (K_ASN1_item_i2d_fp)(K_NETSCAPE_X509_it, out, x);
+ else return -1;
+}
+#else
+ASN1_METHOD *KOpenSSLProxy::X509_asn1_meth(void) {
+ if (K_X509_asn1_meth) return (K_X509_asn1_meth)();
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::ASN1_i2d_fp(FILE *out,unsigned char *x) {
+ if (K_ASN1_i2d_fp && K_i2d_ASN1_HEADER)
+ return (K_ASN1_i2d_fp)((int (*)())K_i2d_ASN1_HEADER, out, x);
+ else return -1;
+}
+#endif
+
+int KOpenSSLProxy::X509_print(FILE *fp, X509 *x) {
+ if (K_X509_print_fp) return (K_X509_print_fp)(fp, x);
+ return -1;
+}
+
+
+PKCS12 *KOpenSSLProxy::d2i_PKCS12_fp(FILE *fp, PKCS12 **p12) {
+ if (K_d2i_PKCS12_fp) return (K_d2i_PKCS12_fp)(fp, p12);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::PKCS12_newpass(PKCS12 *p12, char *oldpass, char *newpass) {
+ if (K_PKCS12_newpass) return (K_PKCS12_newpass)(p12, oldpass, newpass);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::i2d_PKCS12(PKCS12 *p12, unsigned char **p) {
+ if (K_i2d_PKCS12) return (K_i2d_PKCS12)(p12, p);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::i2d_PKCS12_fp(FILE *fp, PKCS12 *p12) {
+ if (K_i2d_PKCS12_fp) return (K_i2d_PKCS12_fp)(fp, p12);
+ else return -1;
+}
+
+
+PKCS12 *KOpenSSLProxy::PKCS12_new(void) {
+ if (K_PKCS12_new) return (K_PKCS12_new)();
+ else return 0L;
+}
+
+
+void KOpenSSLProxy::PKCS12_free(PKCS12 *a) {
+ if (K_PKCS12_free) (K_PKCS12_free)(a);
+}
+
+
+int KOpenSSLProxy::PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey,
+ X509 **cert, STACK_OF(X509) **ca) {
+ if (K_PKCS12_parse) return (K_PKCS12_parse) (p12, pass, pkey, cert, ca);
+ else return -1;
+}
+
+
+void KOpenSSLProxy::EVP_PKEY_free(EVP_PKEY *x) {
+ if (K_EVP_PKEY_free) (K_EVP_PKEY_free)(x);
+}
+
+
+EVP_PKEY* KOpenSSLProxy::EVP_PKEY_new() {
+ if (K_EVP_PKEY_new) return (K_EVP_PKEY_new)();
+ else return 0L;
+}
+
+
+void KOpenSSLProxy::X509_REQ_free(X509_REQ *x) {
+ if (K_X509_REQ_free) (K_X509_REQ_free)(x);
+}
+
+
+X509_REQ* KOpenSSLProxy::X509_REQ_new() {
+ if (K_X509_REQ_new) return (K_X509_REQ_new)();
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey) {
+ if (K_SSL_CTX_use_PrivateKey) return (K_SSL_CTX_use_PrivateKey)(ctx,pkey);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x) {
+ if (K_SSL_CTX_use_certificate) return (K_SSL_CTX_use_certificate)(ctx,x);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::SSL_get_error(SSL *ssl, int rc) {
+ if (K_SSL_get_error) return (K_SSL_get_error)(ssl,rc);
+ else return -1;
+}
+
+
+STACK_OF(X509) *KOpenSSLProxy::SSL_get_peer_cert_chain(SSL *s) {
+ if (K_SSL_get_peer_cert_chain) return (K_SSL_get_peer_cert_chain)(s);
+ else return 0L;
+}
+
+
+void KOpenSSLProxy::sk_free(STACK *s) {
+ if (K_sk_free) (K_sk_free)(s);
+}
+
+
+int KOpenSSLProxy::sk_num(STACK *s) {
+ if (K_sk_num) return (K_sk_num)(s);
+ else return -1;
+}
+
+
+char *KOpenSSLProxy::sk_pop(STACK *s) {
+ if (K_sk_pop) return (K_sk_pop)(s);
+ else return 0L;
+}
+
+
+char *KOpenSSLProxy::sk_value(STACK *s, int n) {
+ if (K_sk_value) return (K_sk_value)(s, n);
+ else return 0L;
+}
+
+
+void KOpenSSLProxy::X509_STORE_CTX_set_chain(X509_STORE_CTX *v, STACK_OF(X509)* x) {
+ if (K_X509_STORE_CTX_set_chain) (K_X509_STORE_CTX_set_chain)(v,x);
+}
+
+void KOpenSSLProxy::X509_STORE_CTX_set_purpose(X509_STORE_CTX *v, int purpose) {
+ if (K_X509_STORE_CTX_set_purpose) (K_X509_STORE_CTX_set_purpose)(v,purpose);
+}
+
+
+STACK* KOpenSSLProxy::sk_dup(STACK *s) {
+ if (K_sk_dup) return (K_sk_dup)(s);
+ else return 0L;
+}
+
+
+STACK* KOpenSSLProxy::sk_new(int (*cmp)()) {
+ if (K_sk_new) return (K_sk_new)(cmp);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::sk_push(STACK* s, char* d) {
+ if (K_sk_push) return (K_sk_push)(s,d);
+ else return -1;
+}
+
+
+char *KOpenSSLProxy::i2s_ASN1_INTEGER(X509V3_EXT_METHOD *meth, ASN1_INTEGER *aint) {
+ if (K_i2s_ASN1_INTEGER) return (K_i2s_ASN1_INTEGER)(meth, aint);
+ else return 0L;
+}
+
+
+ASN1_INTEGER *KOpenSSLProxy::X509_get_serialNumber(X509 *x) {
+ if (K_X509_get_serialNumber) return (K_X509_get_serialNumber)(x);
+ else return 0L;
+}
+
+
+EVP_PKEY *KOpenSSLProxy::X509_get_pubkey(X509 *x) {
+ if (K_X509_get_pubkey) return (K_X509_get_pubkey)(x);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::i2d_PublicKey(EVP_PKEY *a, unsigned char **pp) {
+ if (K_i2d_PublicKey) return (K_i2d_PublicKey)(a,pp);
+ else return 0;
+}
+
+
+int KOpenSSLProxy::X509_check_private_key(X509 *x, EVP_PKEY *p) {
+ if (K_X509_check_private_key) return (K_X509_check_private_key)(x,p);
+ return -1;
+}
+
+
+char *KOpenSSLProxy::BN_bn2hex(const BIGNUM *a) {
+ if (K_BN_bn2hex) return (K_BN_bn2hex)(a);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::X509_digest(const X509 *x,const EVP_MD *t, unsigned char *md, unsigned int *len) {
+ if (K_X509_digest) return (K_X509_digest)(x, t, md, len);
+ else return -1;
+}
+
+
+EVP_MD *KOpenSSLProxy::EVP_md5() {
+ if (K_EVP_md5) return (K_EVP_md5)();
+ return 0L;
+}
+
+
+void KOpenSSLProxy::ASN1_INTEGER_free(ASN1_INTEGER *a) {
+ if (K_ASN1_INTEGER_free) (K_ASN1_INTEGER_free)(a);
+}
+
+
+int KOpenSSLProxy::OBJ_obj2nid(ASN1_OBJECT *o) {
+ if (K_OBJ_obj2nid) return (K_OBJ_obj2nid)(o);
+ else return -1;
+}
+
+
+const char * KOpenSSLProxy::OBJ_nid2ln(int n) {
+ if (K_OBJ_nid2ln) return (K_OBJ_nid2ln)(n);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::X509_get_ext_count(X509 *x) {
+ if (K_X509_get_ext_count) return (K_X509_get_ext_count)(x);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::X509_get_ext_by_NID(X509 *x, int nid, int lastpos) {
+ if (K_X509_get_ext_by_NID) return (K_X509_get_ext_by_NID)(x,nid,lastpos);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::X509_get_ext_by_OBJ(X509 *x,ASN1_OBJECT *obj,int lastpos) {
+ if (K_X509_get_ext_by_OBJ) return (K_X509_get_ext_by_OBJ)(x,obj,lastpos);
+ else return -1;
+}
+
+
+X509_EXTENSION *KOpenSSLProxy::X509_get_ext(X509 *x, int loc) {
+ if (K_X509_get_ext) return (K_X509_get_ext)(x,loc);
+ else return 0L;
+}
+
+
+X509_EXTENSION *KOpenSSLProxy::X509_delete_ext(X509 *x, int loc) {
+ if (K_X509_delete_ext) return (K_X509_delete_ext)(x,loc);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc) {
+ if (K_X509_add_ext) return (K_X509_add_ext)(x,ex,loc);
+ else return -1;
+}
+
+
+void *KOpenSSLProxy::X509_get_ext_d2i(X509 *x, int nid, int *crit, int *idx) {
+ if (K_X509_get_ext_d2i) return (K_X509_get_ext_d2i)(x,nid,crit,idx);
+ else return 0L;
+}
+
+
+char *KOpenSSLProxy::i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method, ASN1_OCTET_STRING *ia5) {
+ if (K_i2s_ASN1_OCTET_STRING) return (K_i2s_ASN1_OCTET_STRING)(method,ia5);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *a, int n) {
+ if (K_ASN1_BIT_STRING_get_bit) return (K_ASN1_BIT_STRING_get_bit)(a,n);
+ else return -1;
+}
+
+
+PKCS7 *KOpenSSLProxy::PKCS7_new(void) {
+ if (K_PKCS7_new) return (K_PKCS7_new)();
+ else return 0L;
+}
+
+
+void KOpenSSLProxy::PKCS7_free(PKCS7 *a) {
+ if (K_PKCS7_free) (K_PKCS7_free)(a);
+}
+
+
+void KOpenSSLProxy::PKCS7_content_free(PKCS7 *a) {
+ if (K_PKCS7_content_free) (K_PKCS7_content_free)(a);
+}
+
+
+int KOpenSSLProxy::i2d_PKCS7(PKCS7 *a, unsigned char **pp) {
+ if (K_i2d_PKCS7) return (K_i2d_PKCS7)(a,pp);
+ else return -1;
+}
+
+
+PKCS7 *KOpenSSLProxy::d2i_PKCS7(PKCS7 **a, unsigned char **pp,long length) {
+ if (K_d2i_PKCS7) return (K_d2i_PKCS7)(a,pp,length);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::i2d_PKCS7_fp(FILE *fp,PKCS7 *p7) {
+ if (K_i2d_PKCS7_fp) return (K_i2d_PKCS7_fp)(fp,p7);
+ else return -1;
+}
+
+
+PKCS7 *KOpenSSLProxy::d2i_PKCS7_fp(FILE *fp,PKCS7 **p7) {
+ if (K_d2i_PKCS7_fp) return (K_d2i_PKCS7_fp)(fp,p7);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::i2d_PKCS7_bio(BIO *bp,PKCS7 *p7) {
+ if (K_i2d_PKCS7_bio) return (K_i2d_PKCS7_bio)(bp, p7);
+ else return -1;
+}
+
+
+PKCS7 *KOpenSSLProxy::d2i_PKCS7_bio(BIO *bp,PKCS7 **p7) {
+ if (K_d2i_PKCS7_bio) return (K_d2i_PKCS7_bio)(bp, p7);
+ else return 0L;
+}
+
+
+PKCS7 *KOpenSSLProxy::PKCS7_dup(PKCS7 *p7) {
+ if (K_PKCS7_dup) return (K_PKCS7_dup)(p7);
+ else return 0L;
+}
+
+
+PKCS7 *KOpenSSLProxy::PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
+ BIO *data, int flags) {
+ if (K_PKCS7_sign) return (K_PKCS7_sign)(signcert,pkey,certs,data,flags);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::PKCS7_verify(PKCS7* p, STACK_OF(X509)* st, X509_STORE* s, BIO* in, BIO *out, int flags) {
+ if (K_PKCS7_verify) return (K_PKCS7_verify)(p,st,s,in,out,flags);
+ else return 0;
+}
+
+
+STACK_OF(X509) *KOpenSSLProxy::PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs, int flags) {
+ if (K_PKCS7_get0_signers) return (K_PKCS7_get0_signers)(p7,certs,flags);
+ else return 0L;
+}
+
+
+PKCS7 *KOpenSSLProxy::PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, EVP_CIPHER *cipher,
+ int flags) {
+ if (K_PKCS7_encrypt) return (K_PKCS7_encrypt)(certs,in,cipher,flags);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data, int flags) {
+ if (K_PKCS7_decrypt) return (K_PKCS7_decrypt)(p7,pkey,cert,data,flags);
+ else return 0;
+}
+
+
+STACK_OF(X509_NAME) *KOpenSSLProxy::SSL_load_client_CA_file(const char *file) {
+ if (K_SSL_load_client_CA_file) return (K_SSL_load_client_CA_file)(file);
+ else return 0L;
+}
+
+
+STACK_OF(X509_INFO) *KOpenSSLProxy::PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u) {
+ if (K_PEM_X509_INFO_read) return (K_PEM_X509_INFO_read)(fp,sk,cb,u);
+ else return 0L;
+}
+
+
+X509 *KOpenSSLProxy::X509_d2i_fp(FILE *out, X509** buf) {
+ if (K_ASN1_d2i_fp) return reinterpret_cast<X509 *>((K_ASN1_d2i_fp)(reinterpret_cast<char *(*)()>(K_X509_new), reinterpret_cast<char *(*)()>(K_d2i_X509), out, reinterpret_cast<unsigned char **>(buf)));
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::SSL_peek(SSL *ssl,void *buf,int num) {
+ if (K_SSL_peek) return (K_SSL_peek)(ssl,buf,num);
+ else return -1;
+}
+
+
+const char *KOpenSSLProxy::RAND_file_name(char *buf, size_t num) {
+ if (K_RAND_file_name) return (K_RAND_file_name)(buf, num);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::RAND_load_file(const char *filename, long max_bytes) {
+ if (K_RAND_load_file) return (K_RAND_load_file)(filename, max_bytes);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::RAND_write_file(const char *filename) {
+ if (K_RAND_write_file) return (K_RAND_write_file)(filename);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::X509_PURPOSE_get_count() {
+ if (K_X509_PURPOSE_get_count) return (K_X509_PURPOSE_get_count)();
+ else return -1;
+}
+
+
+int KOpenSSLProxy::X509_PURPOSE_get_id(X509_PURPOSE *p) {
+ if (K_X509_PURPOSE_get_id) return (K_X509_PURPOSE_get_id)(p);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::X509_check_purpose(X509 *x, int id, int ca) {
+ if (K_X509_check_purpose) return (K_X509_check_purpose)(x, id, ca);
+ else return -1;
+}
+
+
+X509_PURPOSE *KOpenSSLProxy::X509_PURPOSE_get0(int idx) {
+ if (K_X509_PURPOSE_get0) return (K_X509_PURPOSE_get0)(idx);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::EVP_PKEY_assign(EVP_PKEY *pkey, int type, char *key) {
+ if (K_EVP_PKEY_assign) return (K_EVP_PKEY_assign)(pkey, type, key);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey) {
+ if (K_X509_REQ_set_pubkey) return (K_X509_REQ_set_pubkey)(x, pkey);
+ else return -1;
+}
+
+
+RSA* KOpenSSLProxy::RSA_generate_key(int bits, unsigned long e, void
+ (*callback)(int,int,void *), void *cb_arg) {
+ if (K_RSA_generate_key) return (K_RSA_generate_key)(bits, e, callback, cb_arg);
+ else return 0L;
+}
+
+STACK *KOpenSSLProxy::X509_get1_email(X509 *x) {
+ if (K_X509_get1_email) return (K_X509_get1_email)(x);
+ else return 0L;
+}
+
+void KOpenSSLProxy::X509_email_free(STACK *sk) {
+ if (K_X509_email_free) (K_X509_email_free)(sk);
+}
+
+EVP_CIPHER *KOpenSSLProxy::EVP_des_ede3_cbc() {
+ if (K_EVP_des_ede3_cbc) return (K_EVP_des_ede3_cbc)();
+ else return 0L;
+}
+
+EVP_CIPHER *KOpenSSLProxy::EVP_des_cbc() {
+ if (K_EVP_des_cbc) return (K_EVP_des_cbc)();
+ else return 0L;
+}
+
+EVP_CIPHER *KOpenSSLProxy::EVP_rc2_cbc() {
+ if (K_EVP_rc2_cbc) return (K_EVP_rc2_cbc)();
+ else return 0L;
+}
+
+EVP_CIPHER *KOpenSSLProxy::EVP_rc2_64_cbc() {
+ if (K_EVP_rc2_64_cbc) return (K_EVP_rc2_64_cbc)();
+ else return 0L;
+}
+
+EVP_CIPHER *KOpenSSLProxy::EVP_rc2_40_cbc() {
+ if (K_EVP_rc2_40_cbc) return (K_EVP_rc2_40_cbc)();
+ else return 0L;
+}
+
+int KOpenSSLProxy::i2d_X509_REQ_fp(FILE *fp, X509_REQ *x) {
+ if (K_i2d_X509_REQ_fp) return (K_i2d_X509_REQ_fp)(fp,x);
+ else return -1;
+}
+
+
+void KOpenSSLProxy::ERR_clear_error() {
+ if (K_ERR_clear_error) (K_ERR_clear_error)();
+}
+
+
+unsigned long KOpenSSLProxy::ERR_get_error() {
+ if (K_ERR_get_error) return (K_ERR_get_error)();
+ else return 0xffffffff;
+}
+
+
+void KOpenSSLProxy::ERR_print_errors_fp(FILE* fp) {
+ if (K_ERR_print_errors_fp) (K_ERR_print_errors_fp)(fp);
+}
+
+
+SSL_SESSION *KOpenSSLProxy::SSL_get1_session(SSL *ssl) {
+ if (K_SSL_get1_session) return (K_SSL_get1_session)(ssl);
+ else return 0L;
+}
+
+
+void KOpenSSLProxy::SSL_SESSION_free(SSL_SESSION *session) {
+ if (K_SSL_SESSION_free) (K_SSL_SESSION_free)(session);
+}
+
+
+int KOpenSSLProxy::SSL_set_session(SSL *ssl, SSL_SESSION *session) {
+ if (K_SSL_set_session) return (K_SSL_set_session)(ssl, session);
+ else return -1;
+}
+
+
+SSL_SESSION *KOpenSSLProxy::d2i_SSL_SESSION(SSL_SESSION **a, unsigned char **pp, long length) {
+ if (K_d2i_SSL_SESSION) return (K_d2i_SSL_SESSION)(a, pp, length);
+ else return 0L;
+}
+
+
+int KOpenSSLProxy::i2d_SSL_SESSION(SSL_SESSION *in, unsigned char **pp) {
+ if (K_i2d_SSL_SESSION) return (K_i2d_SSL_SESSION)(in, pp);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::i2d_PrivateKey_fp(FILE *fp, EVP_PKEY *p) {
+ if (K_i2d_PrivateKey_fp) return (K_i2d_PrivateKey_fp)(fp, p);
+ else return -1;
+}
+
+
+int KOpenSSLProxy::i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *p, const EVP_CIPHER *c, char *k, int klen, pem_password_cb *cb, void *u) {
+ if (K_i2d_PKCS8PrivateKey_fp) return (K_i2d_PKCS8PrivateKey_fp)(fp, p, c, k, klen, cb, u);
+ else return -1;
+}
+
+
+void KOpenSSLProxy::RSA_free(RSA *rsa) {
+ if (K_RSA_free) (K_RSA_free)(rsa);
+}
+
+
+EVP_CIPHER *KOpenSSLProxy::EVP_bf_cbc() {
+ if (K_EVP_bf_cbc) return (K_EVP_bf_cbc)();
+ return 0L;
+}
+
+
+int KOpenSSLProxy::X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md) {
+ if (K_X509_REQ_sign) return (K_X509_REQ_sign)(x, pkey, md);
+ return -1;
+}
+
+
+int KOpenSSLProxy::X509_NAME_add_entry_by_txt(X509_NAME *name, char *field,
+ int type, unsigned char *bytes, int len, int loc, int set) {
+ if (K_X509_NAME_add_entry_by_txt) return (K_X509_NAME_add_entry_by_txt)(name, field, type, bytes, len, loc, set);
+ return -1;
+}
+
+
+X509_NAME *KOpenSSLProxy::X509_NAME_new() {
+ if (K_X509_NAME_new) return (K_X509_NAME_new)();
+ return 0L;
+}
+
+
+int KOpenSSLProxy::X509_REQ_set_subject_name(X509_REQ *req,X509_NAME *name) {
+ if (K_X509_REQ_set_subject_name) return (K_X509_REQ_set_subject_name)(req, name);
+ return -1;
+}
+
+
+unsigned char *KOpenSSLProxy::ASN1_STRING_data(ASN1_STRING *x) {
+ if (K_ASN1_STRING_data) return (K_ASN1_STRING_data)(x);
+ return 0L;
+}
+
+int KOpenSSLProxy::ASN1_STRING_length(ASN1_STRING *x) {
+ if (K_ASN1_STRING_length) return (K_ASN1_STRING_length)(x);
+ return 0L;
+}
+
+STACK_OF(SSL_CIPHER) *KOpenSSLProxy::SSL_get_ciphers(const SSL* ssl) {
+ if (K_SSL_get_ciphers) return (K_SSL_get_ciphers)(ssl);
+ return 0L;
+}
+
+#endif
+
diff --git a/kio/kssl/kopenssl.h b/tdeio/kssl/kopenssl.h
index 59cf7b560..59cf7b560 100644
--- a/kio/kssl/kopenssl.h
+++ b/tdeio/kssl/kopenssl.h
diff --git a/kio/kssl/ksmimecrypto.cc b/tdeio/kssl/ksmimecrypto.cc
index 1a9e37e60..1a9e37e60 100644
--- a/kio/kssl/ksmimecrypto.cc
+++ b/tdeio/kssl/ksmimecrypto.cc
diff --git a/kio/kssl/ksmimecrypto.h b/tdeio/kssl/ksmimecrypto.h
index 5f8e1da73..5f8e1da73 100644
--- a/kio/kssl/ksmimecrypto.h
+++ b/tdeio/kssl/ksmimecrypto.h
diff --git a/kio/kssl/kssl.cc b/tdeio/kssl/kssl.cc
index 66cc503d5..66cc503d5 100644
--- a/kio/kssl/kssl.cc
+++ b/tdeio/kssl/kssl.cc
diff --git a/kio/kssl/kssl.h b/tdeio/kssl/kssl.h
index e10b10eaf..e10b10eaf 100644
--- a/kio/kssl/kssl.h
+++ b/tdeio/kssl/kssl.h
diff --git a/kio/kssl/kssl/CMakeLists.txt b/tdeio/kssl/kssl/CMakeLists.txt
index eeed10125..eeed10125 100644
--- a/kio/kssl/kssl/CMakeLists.txt
+++ b/tdeio/kssl/kssl/CMakeLists.txt
diff --git a/kio/kssl/kssl/DigiCertAssuredIDRootCA.pem b/tdeio/kssl/kssl/DigiCertAssuredIDRootCA.pem
index 2731638b6..2731638b6 100644
--- a/kio/kssl/kssl/DigiCertAssuredIDRootCA.pem
+++ b/tdeio/kssl/kssl/DigiCertAssuredIDRootCA.pem
diff --git a/kio/kssl/kssl/DigiCertGlobalRootCA.pem b/tdeio/kssl/kssl/DigiCertGlobalRootCA.pem
index fd4341df2..fd4341df2 100644
--- a/kio/kssl/kssl/DigiCertGlobalRootCA.pem
+++ b/tdeio/kssl/kssl/DigiCertGlobalRootCA.pem
diff --git a/kio/kssl/kssl/DigiCertHighAssuranceEVRootCA.pem b/tdeio/kssl/kssl/DigiCertHighAssuranceEVRootCA.pem
index 9e6810ab7..9e6810ab7 100644
--- a/kio/kssl/kssl/DigiCertHighAssuranceEVRootCA.pem
+++ b/tdeio/kssl/kssl/DigiCertHighAssuranceEVRootCA.pem
diff --git a/kio/kssl/kssl/GeoTrust_Universal_CA.pem b/tdeio/kssl/kssl/GeoTrust_Universal_CA.pem
index 31d9e7aa7..31d9e7aa7 100644
--- a/kio/kssl/kssl/GeoTrust_Universal_CA.pem
+++ b/tdeio/kssl/kssl/GeoTrust_Universal_CA.pem
diff --git a/kio/kssl/kssl/GeoTrust_Universal_CA2.pem b/tdeio/kssl/kssl/GeoTrust_Universal_CA2.pem
index b61946475..b61946475 100644
--- a/kio/kssl/kssl/GeoTrust_Universal_CA2.pem
+++ b/tdeio/kssl/kssl/GeoTrust_Universal_CA2.pem
diff --git a/tdeio/kssl/kssl/HOWTO b/tdeio/kssl/kssl/HOWTO
new file mode 100644
index 000000000..762535b14
--- /dev/null
+++ b/tdeio/kssl/kssl/HOWTO
@@ -0,0 +1,30 @@
+
+NOTE: If you want to add a root file, please contact kde-core-devel and the
+maintainer (currently bradh@kde.org) with full details.
+
+
+1) Build cert_extract
+2) Make a directory 'certtmp'
+3) cd 'certtmp'
+4) Run ../cert_extract /path/to/netscape/cert7.db
+ This will create many files and an index
+5) Remove the TrustCenter level 0 certificate.
+6) Merge these files into a bundle with:
+ ../cert_bundle /path/to/netscape/cert7.db cert.index ../caroot/ca-bundle.crt
+7) Merge these files into a KDE config file with:
+ ../certkde
+8) mv ksslcalist ../
+9) Merge in the local certs that we added ourselves with:
+ cd ..
+ ./mergelocal
+10) *Do your diffs*! Make *sure* you commit what you think you are committing.
+11) svn commit
+
+
+
+
+To add local files:
+1) Create the .pem file and check it into cvs in tdelibs/tdeio/kssl/kssl.
+2) List the pem file name as a single line in 'localcerts'.
+
+
diff --git a/kio/kssl/kssl/Makefile.am b/tdeio/kssl/kssl/Makefile.am
index a7ad33e95..a7ad33e95 100644
--- a/kio/kssl/kssl/Makefile.am
+++ b/tdeio/kssl/kssl/Makefile.am
diff --git a/kio/kssl/kssl/StartCom.pem b/tdeio/kssl/kssl/StartCom.pem
index a7c9b39a0..a7c9b39a0 100644
--- a/kio/kssl/kssl/StartCom.pem
+++ b/tdeio/kssl/kssl/StartCom.pem
diff --git a/kio/kssl/kssl/SwissSign-Gold-G2.pem b/tdeio/kssl/kssl/SwissSign-Gold-G2.pem
index d72118781..d72118781 100644
--- a/kio/kssl/kssl/SwissSign-Gold-G2.pem
+++ b/tdeio/kssl/kssl/SwissSign-Gold-G2.pem
diff --git a/kio/kssl/kssl/SwissSign-Platinum-G2.pem b/tdeio/kssl/kssl/SwissSign-Platinum-G2.pem
index 0aa3e3577..0aa3e3577 100644
--- a/kio/kssl/kssl/SwissSign-Platinum-G2.pem
+++ b/tdeio/kssl/kssl/SwissSign-Platinum-G2.pem
diff --git a/kio/kssl/kssl/SwissSign-Silver-G2.pem b/tdeio/kssl/kssl/SwissSign-Silver-G2.pem
index 67a172cb6..67a172cb6 100644
--- a/kio/kssl/kssl/SwissSign-Silver-G2.pem
+++ b/tdeio/kssl/kssl/SwissSign-Silver-G2.pem
diff --git a/kio/kssl/kssl/WiseKey.pem b/tdeio/kssl/kssl/WiseKey.pem
index a695c21bb..a695c21bb 100644
--- a/kio/kssl/kssl/WiseKey.pem
+++ b/tdeio/kssl/kssl/WiseKey.pem
diff --git a/kio/kssl/kssl/ac_offline_raiz_certicamara.pem b/tdeio/kssl/kssl/ac_offline_raiz_certicamara.pem
index c60cce890..c60cce890 100644
--- a/kio/kssl/kssl/ac_offline_raiz_certicamara.pem
+++ b/tdeio/kssl/kssl/ac_offline_raiz_certicamara.pem
diff --git a/kio/kssl/kssl/argedaten-root-ca-cert.pem b/tdeio/kssl/kssl/argedaten-root-ca-cert.pem
index 621e30e20..621e30e20 100644
--- a/kio/kssl/kssl/argedaten-root-ca-cert.pem
+++ b/tdeio/kssl/kssl/argedaten-root-ca-cert.pem
diff --git a/kio/kssl/kssl/belgacom.pem b/tdeio/kssl/kssl/belgacom.pem
index 0b581a774..0b581a774 100644
--- a/kio/kssl/kssl/belgacom.pem
+++ b/tdeio/kssl/kssl/belgacom.pem
diff --git a/kio/kssl/kssl/caroot/CMakeLists.txt b/tdeio/kssl/kssl/caroot/CMakeLists.txt
index 05e2381a9..05e2381a9 100644
--- a/kio/kssl/kssl/caroot/CMakeLists.txt
+++ b/tdeio/kssl/kssl/caroot/CMakeLists.txt
diff --git a/kio/kssl/kssl/caroot/Makefile.am b/tdeio/kssl/kssl/caroot/Makefile.am
index cd049a036..cd049a036 100644
--- a/kio/kssl/kssl/caroot/Makefile.am
+++ b/tdeio/kssl/kssl/caroot/Makefile.am
diff --git a/kio/kssl/kssl/caroot/ca-bundle.crt b/tdeio/kssl/kssl/caroot/ca-bundle.crt
index 31409b62f..31409b62f 100644
--- a/kio/kssl/kssl/caroot/ca-bundle.crt
+++ b/tdeio/kssl/kssl/caroot/ca-bundle.crt
diff --git a/kio/kssl/kssl/cert_bundle b/tdeio/kssl/kssl/cert_bundle
index 331a64286..331a64286 100755
--- a/kio/kssl/kssl/cert_bundle
+++ b/tdeio/kssl/kssl/cert_bundle
diff --git a/kio/kssl/kssl/cert_extract.c b/tdeio/kssl/kssl/cert_extract.c
index 095f810f4..095f810f4 100644
--- a/kio/kssl/kssl/cert_extract.c
+++ b/tdeio/kssl/kssl/cert_extract.c
diff --git a/kio/kssl/kssl/certbundle_Makefile b/tdeio/kssl/kssl/certbundle_Makefile
index 5a288f3b6..5a288f3b6 100644
--- a/kio/kssl/kssl/certbundle_Makefile
+++ b/tdeio/kssl/kssl/certbundle_Makefile
diff --git a/kio/kssl/kssl/certkde b/tdeio/kssl/kssl/certkde
index 37c924f83..37c924f83 100755
--- a/kio/kssl/kssl/certkde
+++ b/tdeio/kssl/kssl/certkde
diff --git a/kio/kssl/kssl/certum.pem b/tdeio/kssl/kssl/certum.pem
index b133fcb49..b133fcb49 100644
--- a/kio/kssl/kssl/certum.pem
+++ b/tdeio/kssl/kssl/certum.pem
diff --git a/kio/kssl/kssl/certum1.pem b/tdeio/kssl/kssl/certum1.pem
index aaf9cbc9a..aaf9cbc9a 100644
--- a/kio/kssl/kssl/certum1.pem
+++ b/tdeio/kssl/kssl/certum1.pem
diff --git a/kio/kssl/kssl/certum2.pem b/tdeio/kssl/kssl/certum2.pem
index a90ca2a91..a90ca2a91 100644
--- a/kio/kssl/kssl/certum2.pem
+++ b/tdeio/kssl/kssl/certum2.pem
diff --git a/kio/kssl/kssl/certum3.pem b/tdeio/kssl/kssl/certum3.pem
index d6233c43c..d6233c43c 100644
--- a/kio/kssl/kssl/certum3.pem
+++ b/tdeio/kssl/kssl/certum3.pem
diff --git a/kio/kssl/kssl/certum4.pem b/tdeio/kssl/kssl/certum4.pem
index decbac005..decbac005 100644
--- a/kio/kssl/kssl/certum4.pem
+++ b/tdeio/kssl/kssl/certum4.pem
diff --git a/kio/kssl/kssl/comodo1.pem b/tdeio/kssl/kssl/comodo1.pem
index 536b087db..536b087db 100644
--- a/kio/kssl/kssl/comodo1.pem
+++ b/tdeio/kssl/kssl/comodo1.pem
diff --git a/kio/kssl/kssl/comodo2.pem b/tdeio/kssl/kssl/comodo2.pem
index fef46d9c7..fef46d9c7 100644
--- a/kio/kssl/kssl/comodo2.pem
+++ b/tdeio/kssl/kssl/comodo2.pem
diff --git a/kio/kssl/kssl/comodo3.pem b/tdeio/kssl/kssl/comodo3.pem
index 40c137095..40c137095 100644
--- a/kio/kssl/kssl/comodo3.pem
+++ b/tdeio/kssl/kssl/comodo3.pem
diff --git a/kio/kssl/kssl/comodo4.pem b/tdeio/kssl/kssl/comodo4.pem
index 7490b02be..7490b02be 100644
--- a/kio/kssl/kssl/comodo4.pem
+++ b/tdeio/kssl/kssl/comodo4.pem
diff --git a/kio/kssl/kssl/comodo5.pem b/tdeio/kssl/kssl/comodo5.pem
index 824d542c1..824d542c1 100644
--- a/kio/kssl/kssl/comodo5.pem
+++ b/tdeio/kssl/kssl/comodo5.pem
diff --git a/kio/kssl/kssl/comodo6.pem b/tdeio/kssl/kssl/comodo6.pem
index 4b9f74824..4b9f74824 100644
--- a/kio/kssl/kssl/comodo6.pem
+++ b/tdeio/kssl/kssl/comodo6.pem
diff --git a/kio/kssl/kssl/comodo7.pem b/tdeio/kssl/kssl/comodo7.pem
index 58b02ea94..58b02ea94 100644
--- a/kio/kssl/kssl/comodo7.pem
+++ b/tdeio/kssl/kssl/comodo7.pem
diff --git a/kio/kssl/kssl/dfn-root-ca-cert.pem b/tdeio/kssl/kssl/dfn-root-ca-cert.pem
index eb8a054ac..eb8a054ac 100644
--- a/kio/kssl/kssl/dfn-root-ca-cert.pem
+++ b/tdeio/kssl/kssl/dfn-root-ca-cert.pem
diff --git a/kio/kssl/kssl/gd-class2-root.pem b/tdeio/kssl/kssl/gd-class2-root.pem
index 42e8d1eef..42e8d1eef 100644
--- a/kio/kssl/kssl/gd-class2-root.pem
+++ b/tdeio/kssl/kssl/gd-class2-root.pem
diff --git a/kio/kssl/kssl/geotrust-global-1.pem b/tdeio/kssl/kssl/geotrust-global-1.pem
index b69f0029b..b69f0029b 100644
--- a/kio/kssl/kssl/geotrust-global-1.pem
+++ b/tdeio/kssl/kssl/geotrust-global-1.pem
diff --git a/kio/kssl/kssl/geotrust-global-2.pem b/tdeio/kssl/kssl/geotrust-global-2.pem
index d2ea26636..d2ea26636 100644
--- a/kio/kssl/kssl/geotrust-global-2.pem
+++ b/tdeio/kssl/kssl/geotrust-global-2.pem
diff --git a/kio/kssl/kssl/globalsign-root-r1.pem b/tdeio/kssl/kssl/globalsign-root-r1.pem
index f4ce4ca43..f4ce4ca43 100644
--- a/kio/kssl/kssl/globalsign-root-r1.pem
+++ b/tdeio/kssl/kssl/globalsign-root-r1.pem
diff --git a/kio/kssl/kssl/globalsign-root-r2.pem b/tdeio/kssl/kssl/globalsign-root-r2.pem
index 6f0f8db0d..6f0f8db0d 100644
--- a/kio/kssl/kssl/globalsign-root-r2.pem
+++ b/tdeio/kssl/kssl/globalsign-root-r2.pem
diff --git a/kio/kssl/kssl/icpbrasil.pem b/tdeio/kssl/kssl/icpbrasil.pem
index 53fa58c51..53fa58c51 100644
--- a/kio/kssl/kssl/icpbrasil.pem
+++ b/tdeio/kssl/kssl/icpbrasil.pem
diff --git a/kio/kssl/kssl/ipsservidores.pem b/tdeio/kssl/kssl/ipsservidores.pem
index e5963e72f..e5963e72f 100644
--- a/kio/kssl/kssl/ipsservidores.pem
+++ b/tdeio/kssl/kssl/ipsservidores.pem
diff --git a/kio/kssl/kssl/ksslcalist b/tdeio/kssl/kssl/ksslcalist
index a0761cf4a..a0761cf4a 100644
--- a/kio/kssl/kssl/ksslcalist
+++ b/tdeio/kssl/kssl/ksslcalist
diff --git a/kio/kssl/kssl/localcerts b/tdeio/kssl/kssl/localcerts
index 150763522..150763522 100644
--- a/kio/kssl/kssl/localcerts
+++ b/tdeio/kssl/kssl/localcerts
diff --git a/kio/kssl/kssl/mergelocal b/tdeio/kssl/kssl/mergelocal
index 4fc0f0ff3..4fc0f0ff3 100755
--- a/kio/kssl/kssl/mergelocal
+++ b/tdeio/kssl/kssl/mergelocal
diff --git a/kio/kssl/kssl/netlock1.pem b/tdeio/kssl/kssl/netlock1.pem
index 5f7c1ce43..5f7c1ce43 100644
--- a/kio/kssl/kssl/netlock1.pem
+++ b/tdeio/kssl/kssl/netlock1.pem
diff --git a/kio/kssl/kssl/netlock2.pem b/tdeio/kssl/kssl/netlock2.pem
index c4e610816..c4e610816 100644
--- a/kio/kssl/kssl/netlock2.pem
+++ b/tdeio/kssl/kssl/netlock2.pem
diff --git a/kio/kssl/kssl/netlock3.pem b/tdeio/kssl/kssl/netlock3.pem
index dd373608e..dd373608e 100644
--- a/kio/kssl/kssl/netlock3.pem
+++ b/tdeio/kssl/kssl/netlock3.pem
diff --git a/kio/kssl/kssl/netlock4.pem b/tdeio/kssl/kssl/netlock4.pem
index 3565fef78..3565fef78 100644
--- a/kio/kssl/kssl/netlock4.pem
+++ b/tdeio/kssl/kssl/netlock4.pem
diff --git a/kio/kssl/kssl/oces.pem b/tdeio/kssl/kssl/oces.pem
index 32e08236c..32e08236c 100644
--- a/kio/kssl/kssl/oces.pem
+++ b/tdeio/kssl/kssl/oces.pem
diff --git a/kio/kssl/kssl/quovadis.pem b/tdeio/kssl/kssl/quovadis.pem
index ea68f8876..ea68f8876 100644
--- a/kio/kssl/kssl/quovadis.pem
+++ b/tdeio/kssl/kssl/quovadis.pem
diff --git a/kio/kssl/kssl/qvrca2.pem b/tdeio/kssl/kssl/qvrca2.pem
index 35cc4eb56..35cc4eb56 100644
--- a/kio/kssl/kssl/qvrca2.pem
+++ b/tdeio/kssl/kssl/qvrca2.pem
diff --git a/kio/kssl/kssl/qvrca3.pem b/tdeio/kssl/kssl/qvrca3.pem
index bda7b1aa5..bda7b1aa5 100644
--- a/kio/kssl/kssl/qvrca3.pem
+++ b/tdeio/kssl/kssl/qvrca3.pem
diff --git a/kio/kssl/kssl/sf-class2-root.pem b/tdeio/kssl/kssl/sf-class2-root.pem
index d552e65dd..d552e65dd 100644
--- a/kio/kssl/kssl/sf-class2-root.pem
+++ b/tdeio/kssl/kssl/sf-class2-root.pem
diff --git a/kio/kssl/kssl/sonera1.pem b/tdeio/kssl/kssl/sonera1.pem
index c5dad57ac..c5dad57ac 100644
--- a/kio/kssl/kssl/sonera1.pem
+++ b/tdeio/kssl/kssl/sonera1.pem
diff --git a/kio/kssl/kssl/sonera2.pem b/tdeio/kssl/kssl/sonera2.pem
index 36a998d22..36a998d22 100644
--- a/kio/kssl/kssl/sonera2.pem
+++ b/tdeio/kssl/kssl/sonera2.pem
diff --git a/kio/kssl/kssl/staatdernederlandenrotca.pem b/tdeio/kssl/kssl/staatdernederlandenrotca.pem
index c4eb117fa..c4eb117fa 100644
--- a/kio/kssl/kssl/staatdernederlandenrotca.pem
+++ b/tdeio/kssl/kssl/staatdernederlandenrotca.pem
diff --git a/kio/kssl/kssl/startcom.pem b/tdeio/kssl/kssl/startcom.pem
index 957842c98..957842c98 100644
--- a/kio/kssl/kssl/startcom.pem
+++ b/tdeio/kssl/kssl/startcom.pem
diff --git a/kio/kssl/kssl/startssl.pem b/tdeio/kssl/kssl/startssl.pem
index 960f2657b..960f2657b 100644
--- a/kio/kssl/kssl/startssl.pem
+++ b/tdeio/kssl/kssl/startssl.pem
diff --git a/kio/kssl/kssl/tcclass2-2011.pem b/tdeio/kssl/kssl/tcclass2-2011.pem
index 0c9d89e77..0c9d89e77 100644
--- a/kio/kssl/kssl/tcclass2-2011.pem
+++ b/tdeio/kssl/kssl/tcclass2-2011.pem
diff --git a/kio/kssl/kssl/tcclass3-2011.pem b/tdeio/kssl/kssl/tcclass3-2011.pem
index 14f81c830..14f81c830 100644
--- a/kio/kssl/kssl/tcclass3-2011.pem
+++ b/tdeio/kssl/kssl/tcclass3-2011.pem
diff --git a/kio/kssl/kssl/utn-network.pem b/tdeio/kssl/kssl/utn-network.pem
index 72b576a59..72b576a59 100644
--- a/kio/kssl/kssl/utn-network.pem
+++ b/tdeio/kssl/kssl/utn-network.pem
diff --git a/kio/kssl/kssl/utn-sgc.pem b/tdeio/kssl/kssl/utn-sgc.pem
index 1c747eb57..1c747eb57 100644
--- a/kio/kssl/kssl/utn-sgc.pem
+++ b/tdeio/kssl/kssl/utn-sgc.pem
diff --git a/kio/kssl/kssl/xgca.pem b/tdeio/kssl/kssl/xgca.pem
index f21e6d8b7..f21e6d8b7 100644
--- a/kio/kssl/kssl/xgca.pem
+++ b/tdeio/kssl/kssl/xgca.pem
diff --git a/kio/kssl/ksslall.h b/tdeio/kssl/ksslall.h
index 0e34837bb..0e34837bb 100644
--- a/kio/kssl/ksslall.h
+++ b/tdeio/kssl/ksslall.h
diff --git a/kio/kssl/ksslcallback.c b/tdeio/kssl/ksslcallback.c
index 59f342584..59f342584 100644
--- a/kio/kssl/ksslcallback.c
+++ b/tdeio/kssl/ksslcallback.c
diff --git a/kio/kssl/ksslcertchain.cc b/tdeio/kssl/ksslcertchain.cc
index a401aec3d..a401aec3d 100644
--- a/kio/kssl/ksslcertchain.cc
+++ b/tdeio/kssl/ksslcertchain.cc
diff --git a/kio/kssl/ksslcertchain.h b/tdeio/kssl/ksslcertchain.h
index eb6c27d44..eb6c27d44 100644
--- a/kio/kssl/ksslcertchain.h
+++ b/tdeio/kssl/ksslcertchain.h
diff --git a/kio/kssl/ksslcertdlg.cc b/tdeio/kssl/ksslcertdlg.cc
index 3d51c1e85..3d51c1e85 100644
--- a/kio/kssl/ksslcertdlg.cc
+++ b/tdeio/kssl/ksslcertdlg.cc
diff --git a/kio/kssl/ksslcertdlg.h b/tdeio/kssl/ksslcertdlg.h
index 8d6f3d777..8d6f3d777 100644
--- a/kio/kssl/ksslcertdlg.h
+++ b/tdeio/kssl/ksslcertdlg.h
diff --git a/kio/kssl/ksslcertificate.cc b/tdeio/kssl/ksslcertificate.cc
index 8e2192f7d..8e2192f7d 100644
--- a/kio/kssl/ksslcertificate.cc
+++ b/tdeio/kssl/ksslcertificate.cc
diff --git a/kio/kssl/ksslcertificate.h b/tdeio/kssl/ksslcertificate.h
index 0c5f87323..0c5f87323 100644
--- a/kio/kssl/ksslcertificate.h
+++ b/tdeio/kssl/ksslcertificate.h
diff --git a/kio/kssl/ksslcertificatecache.cc b/tdeio/kssl/ksslcertificatecache.cc
index 2eecd66d6..2eecd66d6 100644
--- a/kio/kssl/ksslcertificatecache.cc
+++ b/tdeio/kssl/ksslcertificatecache.cc
diff --git a/kio/kssl/ksslcertificatecache.h b/tdeio/kssl/ksslcertificatecache.h
index 924cb0f54..924cb0f54 100644
--- a/kio/kssl/ksslcertificatecache.h
+++ b/tdeio/kssl/ksslcertificatecache.h
diff --git a/kio/kssl/ksslcertificatefactory.cc b/tdeio/kssl/ksslcertificatefactory.cc
index 66e272ced..66e272ced 100644
--- a/kio/kssl/ksslcertificatefactory.cc
+++ b/tdeio/kssl/ksslcertificatefactory.cc
diff --git a/kio/kssl/ksslcertificatefactory.h b/tdeio/kssl/ksslcertificatefactory.h
index 503c591a7..503c591a7 100644
--- a/kio/kssl/ksslcertificatefactory.h
+++ b/tdeio/kssl/ksslcertificatefactory.h
diff --git a/kio/kssl/ksslcertificatehome.cc b/tdeio/kssl/ksslcertificatehome.cc
index 39470c5ab..39470c5ab 100644
--- a/kio/kssl/ksslcertificatehome.cc
+++ b/tdeio/kssl/ksslcertificatehome.cc
diff --git a/kio/kssl/ksslcertificatehome.h b/tdeio/kssl/ksslcertificatehome.h
index f8a18a423..f8a18a423 100644
--- a/kio/kssl/ksslcertificatehome.h
+++ b/tdeio/kssl/ksslcertificatehome.h
diff --git a/kio/kssl/ksslconfig.h.cmake b/tdeio/kssl/ksslconfig.h.cmake
index 1be6bbba4..1be6bbba4 100644
--- a/kio/kssl/ksslconfig.h.cmake
+++ b/tdeio/kssl/ksslconfig.h.cmake
diff --git a/kio/kssl/ksslconfig.h.in b/tdeio/kssl/ksslconfig.h.in
index c078298ec..c078298ec 100644
--- a/kio/kssl/ksslconfig.h.in
+++ b/tdeio/kssl/ksslconfig.h.in
diff --git a/kio/kssl/ksslconfig_win.h b/tdeio/kssl/ksslconfig_win.h
index c078298ec..c078298ec 100644
--- a/kio/kssl/ksslconfig_win.h
+++ b/tdeio/kssl/ksslconfig_win.h
diff --git a/kio/kssl/ksslconnectioninfo.cc b/tdeio/kssl/ksslconnectioninfo.cc
index ccc7fc780..ccc7fc780 100644
--- a/kio/kssl/ksslconnectioninfo.cc
+++ b/tdeio/kssl/ksslconnectioninfo.cc
diff --git a/kio/kssl/ksslconnectioninfo.h b/tdeio/kssl/ksslconnectioninfo.h
index 09fd5cdae..09fd5cdae 100644
--- a/kio/kssl/ksslconnectioninfo.h
+++ b/tdeio/kssl/ksslconnectioninfo.h
diff --git a/kio/kssl/ksslcsessioncache.cc b/tdeio/kssl/ksslcsessioncache.cc
index d39638717..d39638717 100644
--- a/kio/kssl/ksslcsessioncache.cc
+++ b/tdeio/kssl/ksslcsessioncache.cc
diff --git a/kio/kssl/ksslcsessioncache.h b/tdeio/kssl/ksslcsessioncache.h
index 9badfe279..9badfe279 100644
--- a/kio/kssl/ksslcsessioncache.h
+++ b/tdeio/kssl/ksslcsessioncache.h
diff --git a/kio/kssl/kssldefs.h b/tdeio/kssl/kssldefs.h
index c33664b14..c33664b14 100644
--- a/kio/kssl/kssldefs.h
+++ b/tdeio/kssl/kssldefs.h
diff --git a/tdeio/kssl/ksslinfodlg.cc b/tdeio/kssl/ksslinfodlg.cc
new file mode 100644
index 000000000..289c3a8d2
--- /dev/null
+++ b/tdeio/kssl/ksslinfodlg.cc
@@ -0,0 +1,463 @@
+/* This file is part of the KDE project
+ *
+ * Copyright (C) 2000,2001 George Staikos <staikos@kde.org>
+ * Copyright (C) 2000 Malte Starostik <malte@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "ksslinfodlg.h"
+
+#include <kssl.h>
+
+#include <tqlayout.h>
+#include <kpushbutton.h>
+#include <tqframe.h>
+#include <tqlabel.h>
+#include <tqscrollview.h>
+#include <tqfile.h>
+
+#include <kapplication.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kprocess.h>
+#include <kiconloader.h>
+#include <kglobalsettings.h>
+#include <ksqueezedtextlabel.h>
+#include <kurllabel.h>
+#include <kstdguiitem.h>
+//#include <kstandarddirs.h>
+//#include <krun.h>
+#include <kcombobox.h>
+#include "ksslcertificate.h"
+#include "ksslcertchain.h"
+#include "ksslsigners.h"
+
+
+class KSSLInfoDlg::KSSLInfoDlgPrivate {
+ private:
+ friend class KSSLInfoDlg;
+ bool m_secCon;
+ TQGridLayout *m_layout;
+ KComboBox *_chain;
+ KSSLCertificate *_cert;
+ KSSLCertificate::KSSLValidationList _cert_ksvl;
+
+ bool inQuestion;
+
+ TQLabel *_serialNum;
+ TQLabel *_csl;
+ TQLabel *_validFrom;
+ TQLabel *_validUntil;
+ TQLabel *_digest;
+
+ TQLabel *pixmap;
+ TQLabel *info;
+
+ KSSLCertBox *_subject, *_issuer;
+};
+
+
+
+KSSLInfoDlg::KSSLInfoDlg(bool secureConnection, TQWidget *parent, const char *name, bool modal)
+ : KDialog(parent, name, modal, (WFlags)TQt::WDestructiveClose), d(new KSSLInfoDlgPrivate) {
+ TQVBoxLayout *topLayout = new TQVBoxLayout(this, KDialog::marginHint(), KDialog::spacingHint());
+ d->m_secCon = secureConnection;
+ d->m_layout = new TQGridLayout(topLayout, 3, 3, KDialog::spacingHint());
+ d->m_layout->setColStretch(1, 1);
+ d->m_layout->setColStretch(2, 1);
+
+ d->pixmap = new TQLabel(this);
+ d->m_layout->addWidget(d->pixmap, 0, 0);
+
+ d->info = new TQLabel(this);
+ d->m_layout->addWidget(d->info, 0, 1);
+
+ if (KSSL::doesSSLWork()) {
+ if (d->m_secCon) {
+ d->pixmap->setPixmap(BarIcon("encrypted"));
+ d->info->setText(i18n("Current connection is secured with SSL."));
+ } else {
+ d->pixmap->setPixmap(BarIcon("decrypted"));
+ d->info->setText(i18n("Current connection is not secured with SSL."));
+ }
+ } else {
+ d->pixmap->setPixmap(BarIcon("decrypted"));
+ d->info->setText(i18n("SSL support is not available in this build of TDE."));
+ }
+ d->m_layout->addRowSpacing( 0, 50 ); // give minimum height to look better
+
+ TQHBoxLayout *buttonLayout = new TQHBoxLayout(topLayout, KDialog::spacingHint());
+ buttonLayout->addStretch( 1 );
+
+ KPushButton *button;
+
+ if (KSSL::doesSSLWork()) {
+ button = new KPushButton(KGuiItem(i18n("C&ryptography Configuration..."),"configure"), this);
+ connect(button, TQT_SIGNAL(clicked()), TQT_SLOT(launchConfig()));
+ buttonLayout->addWidget( button );
+ }
+
+ button = new KPushButton(KStdGuiItem::close(), this);
+ connect(button, TQT_SIGNAL(clicked()), TQT_SLOT(close()));
+ buttonLayout->addWidget( button );
+
+ button->setFocus();
+
+ setCaption(i18n("TDE SSL Information"));
+ d->inQuestion = false;
+ }
+
+
+KSSLInfoDlg::~KSSLInfoDlg() {
+ delete d;
+}
+
+void KSSLInfoDlg::launchConfig() {
+ TDEProcess p;
+ p << "tdecmshell" << "crypto";
+ p.start(TDEProcess::DontCare);
+}
+
+
+void KSSLInfoDlg::setSecurityInQuestion(bool isIt) {
+ d->inQuestion = isIt;
+ if (KSSL::doesSSLWork())
+ if (isIt) {
+ d->pixmap->setPixmap(BarIcon("halfencrypted"));
+ if (d->m_secCon) {
+ d->info->setText(i18n("The main part of this document is secured with SSL, but some parts are not."));
+ } else {
+ d->info->setText(i18n("Some of this document is secured with SSL, but the main part is not."));
+ }
+ } else {
+ if (d->m_secCon) {
+ d->pixmap->setPixmap(BarIcon("encrypted"));
+ d->info->setText(i18n("Current connection is secured with SSL."));
+ } else {
+ d->pixmap->setPixmap(BarIcon("decrypted"));
+ d->info->setText(i18n("Current connection is not secured with SSL."));
+ }
+ }
+}
+
+
+void KSSLInfoDlg::setup( KSSL & ssl, const TQString & ip, const TQString & url )
+{
+ setup(
+ &ssl.peerInfo().getPeerCertificate(),
+ ip,
+ url,
+ ssl.connectionInfo().getCipher(),
+ ssl.connectionInfo().getCipherDescription(),
+ ssl.connectionInfo().getCipherVersion(),
+ ssl.connectionInfo().getCipherUsedBits(),
+ ssl.connectionInfo().getCipherBits(),
+ ssl.peerInfo().getPeerCertificate().validate()
+ );
+}
+
+void KSSLInfoDlg::setup(KSSLCertificate *cert,
+ const TQString& ip, const TQString& url,
+ const TQString& cipher, const TQString& cipherdesc,
+ const TQString& sslversion, int usedbits, int bits,
+ KSSLCertificate::KSSLValidation /*certState*/) {
+ // Needed to put the GUI stuff here to get the layouting right
+
+ d->_cert = cert;
+
+ TQGridLayout *layout = new TQGridLayout(4, 2, KDialog::spacingHint());
+
+ layout->addWidget(new TQLabel(i18n("Chain:"), this), 0, 0);
+ d->_chain = new KComboBox(this);
+ layout->addMultiCellWidget(d->_chain, 1, 1, 0, 1);
+ connect(d->_chain, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotChain(int)));
+
+ d->_chain->clear();
+
+ if (cert->chain().isValid() && cert->chain().depth() > 1) {
+ d->_chain->setEnabled(true);
+ d->_chain->insertItem(i18n("0 - Site Certificate"));
+ int cnt = 0;
+ TQPtrList<KSSLCertificate> cl = cert->chain().getChain();
+ cl.setAutoDelete(true);
+ for (KSSLCertificate *c = cl.first(); c != 0; c = cl.next()) {
+ KSSLX509Map map(c->getSubject());
+ TQString id;
+ id = map.getValue("CN");
+ if (id.length() == 0)
+ id = map.getValue("O");
+ if (id.length() == 0)
+ id = map.getValue("OU");
+ d->_chain->insertItem(TQString::number(++cnt)+" - "+id);
+ }
+ d->_chain->setCurrentItem(0);
+ } else d->_chain->setEnabled(false);
+
+ layout->addWidget(new TQLabel(i18n("Peer certificate:"), this), 2, 0);
+ layout->addWidget(d->_subject = static_cast<KSSLCertBox*>(buildCertInfo(cert->getSubject())), 3, 0);
+ layout->addWidget(new TQLabel(i18n("Issuer:"), this), 2, 1);
+ layout->addWidget(d->_issuer = static_cast<KSSLCertBox*>(buildCertInfo(cert->getIssuer())), 3, 1);
+ d->m_layout->addMultiCell(layout, 1, 1, 0, 2);
+
+ layout = new TQGridLayout(11, 2, KDialog::spacingHint());
+ layout->setColStretch(1, 1);
+ TQLabel *ipl = new TQLabel(i18n("IP address:"), this);
+ layout->addWidget(ipl, 0, 0);
+ if (ip.isEmpty()) {
+ ipl->hide();
+ }
+ layout->addWidget(ipl = new TQLabel(ip, this), 0, 1);
+ if (ip.isEmpty()) {
+ ipl->hide();
+ }
+ layout->addWidget(new TQLabel(i18n("URL:"), this), 1, 0);
+ KSqueezedTextLabel *urlLabel = new KSqueezedTextLabel(url, this);
+ layout->addWidget(urlLabel, 1, 1);
+ layout->addWidget(new TQLabel(i18n("Certificate state:"), this), 2, 0);
+
+ layout->addWidget(d->_csl = new TQLabel("", this), 2, 1);
+
+ update();
+
+ layout->addWidget(new TQLabel(i18n("Valid from:"), this), 3, 0);
+ layout->addWidget(d->_validFrom = new TQLabel("", this), 3, 1);
+ layout->addWidget(new TQLabel(i18n("Valid until:"), this), 4, 0);
+ layout->addWidget(d->_validUntil = new TQLabel("", this), 4, 1);
+
+ layout->addWidget(new TQLabel(i18n("Serial number:"), this), 5, 0);
+ layout->addWidget(d->_serialNum = new TQLabel("", this), 5, 1);
+ layout->addWidget(new TQLabel(i18n("MD5 digest:"), this), 6, 0);
+ layout->addWidget(d->_digest = new TQLabel("", this), 6, 1);
+
+ layout->addWidget(new TQLabel(i18n("Cipher in use:"), this), 7, 0);
+ layout->addWidget(new TQLabel(cipher, this), 7, 1);
+ layout->addWidget(new TQLabel(i18n("Details:"), this), 8, 0);
+ layout->addWidget(new TQLabel(cipherdesc.simplifyWhiteSpace(), this), 8, 1);
+ layout->addWidget(new TQLabel(i18n("SSL version:"), this), 9, 0);
+ layout->addWidget(new TQLabel(sslversion, this), 9, 1);
+ layout->addWidget(new TQLabel(i18n("Cipher strength:"), this), 10, 0);
+ layout->addWidget(new TQLabel(i18n("%1 bits used of a %2 bit cipher").arg(usedbits).arg(bits), this), 10, 1);
+ d->m_layout->addMultiCell(layout, 2, 2, 0, 2);
+
+ displayCert(cert);
+}
+
+void KSSLInfoDlg::setCertState(const TQString &errorNrs)
+{
+ d->_cert_ksvl.clear();
+ TQStringList errors = TQStringList::split(':', errorNrs);
+ for(TQStringList::ConstIterator it = errors.begin();
+ it != errors.end(); ++it)
+ {
+ d->_cert_ksvl << (KSSLCertificate::KSSLValidation) (*it).toInt();
+ }
+}
+
+void KSSLInfoDlg::displayCert(KSSLCertificate *x) {
+ TQPalette cspl;
+
+ d->_serialNum->setText(x->getSerialNumber());
+
+ cspl = d->_validFrom->palette();
+ if (x->getQDTNotBefore() > TQDateTime::currentDateTime(Qt::UTC))
+ cspl.setColor(TQColorGroup::Foreground, TQColor(196,33,21));
+ else cspl.setColor(TQColorGroup::Foreground, TQColor(42,153,59));
+ d->_validFrom->setPalette(cspl);
+ d->_validFrom->setText(x->getNotBefore());
+
+ cspl = d->_validUntil->palette();
+ if (x->getQDTNotAfter() < TQDateTime::currentDateTime(Qt::UTC))
+ cspl.setColor(TQColorGroup::Foreground, TQColor(196,33,21));
+ else cspl.setColor(TQColorGroup::Foreground, TQColor(42,153,59));
+ d->_validUntil->setPalette(cspl);
+ d->_validUntil->setText(x->getNotAfter());
+
+ cspl = palette();
+
+ KSSLCertificate::KSSLValidation ksv;
+ KSSLCertificate::KSSLValidationList ksvl;
+ if ((x == d->_cert) && !d->_cert_ksvl.isEmpty()) {
+ ksvl = d->_cert_ksvl;
+ ksv = ksvl.first();
+ } else {
+ if (x == d->_cert)
+ ksvl = d->_cert->validateVerbose(KSSLCertificate::SSLServer);
+ else
+ ksvl = d->_cert->validateVerbose(KSSLCertificate::SSLServer, x);
+
+ if (ksvl.isEmpty())
+ ksvl << KSSLCertificate::Ok;
+
+ ksv = ksvl.first();
+
+ if (ksv == KSSLCertificate::SelfSigned) {
+ if (x->getQDTNotAfter() > TQDateTime::currentDateTime(Qt::UTC) &&
+ x->getQDTNotBefore() < TQDateTime::currentDateTime(Qt::UTC)) {
+ if (KSSLSigners().useForSSL(*x))
+ ksv = KSSLCertificate::Ok;
+ } else {
+ ksv = KSSLCertificate::Expired;
+ }
+ }
+ }
+
+ if (ksv == KSSLCertificate::Ok) {
+ cspl.setColor(TQColorGroup::Foreground, TQColor(42,153,59));
+ } else if (ksv != KSSLCertificate::Irrelevant) {
+ cspl.setColor(TQColorGroup::Foreground, TQColor(196,33,21));
+ }
+ d->_csl->setPalette(cspl);
+
+ TQString errorStr;
+ for(KSSLCertificate::KSSLValidationList::ConstIterator it = ksvl.begin();
+ it != ksvl.end(); ++it) {
+ if (!errorStr.isEmpty())
+ errorStr.append('\n');
+ errorStr += KSSLCertificate::verifyText(*it);
+ }
+
+ d->_csl->setText(errorStr);
+ d->_csl->setMinimumSize(d->_csl->sizeHint());
+
+ d->_subject->setValues(x->getSubject());
+ d->_issuer->setValues(x->getIssuer());
+
+ d->_digest->setText(x->getMD5DigestText());
+}
+
+
+void KSSLInfoDlg::slotChain(int x) {
+ if (x == 0) {
+ displayCert(d->_cert);
+ } else {
+ TQPtrList<KSSLCertificate> cl = d->_cert->chain().getChain();
+ cl.setAutoDelete(true);
+ for (int i = 0; i < x-1; i++)
+ cl.remove((unsigned int)0);
+ KSSLCertificate thisCert = *(cl.at(0));
+ cl.remove((unsigned int)0);
+ thisCert.chain().setChain(cl);
+ displayCert(&thisCert);
+ }
+}
+
+
+KSSLCertBox *KSSLInfoDlg::certInfoWidget(TQWidget *parent, const TQString &certName, TQWidget *mailCatcher) {
+ KSSLCertBox *result = new KSSLCertBox(parent);
+ if (!certName.isEmpty()) {
+ result->setValues(certName, mailCatcher);
+ }
+ return result;
+}
+
+
+KSSLCertBox::KSSLCertBox(TQWidget *parent, const char *name, WFlags f)
+: TQScrollView(parent, name, f)
+{
+ _frame = 0L;
+ setBackgroundMode(TQWidget::PaletteButton);
+ setValues(TQString::null, 0L);
+}
+
+
+void KSSLCertBox::setValues(TQString certName, TQWidget *mailCatcher) {
+ if (_frame) {
+ removeChild(_frame);
+ delete _frame;
+ }
+
+ if (certName.isEmpty()) {
+ _frame = new TQFrame(this);
+ addChild(_frame);
+ viewport()->setBackgroundMode(_frame->backgroundMode());
+ _frame->show();
+ updateScrollBars();
+ show();
+ return;
+ }
+
+ KSSLX509Map cert(certName);
+ TQString tmp;
+ viewport()->setBackgroundMode(TQWidget::PaletteButton);
+ _frame = new TQFrame(this);
+ TQGridLayout *grid = new TQGridLayout(_frame, 1, 2, KDialog::marginHint(), KDialog::spacingHint());
+ grid->setAutoAdd(true);
+ TQLabel *label = 0L;
+ if (!(tmp = cert.getValue("O")).isEmpty()) {
+ label = new TQLabel(i18n("Organization:"), _frame);
+ label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ new TQLabel(tmp, _frame);
+ }
+ if (!(tmp = cert.getValue("OU")).isEmpty()) {
+ label = new TQLabel(i18n("Organizational unit:"), _frame);
+ label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ new TQLabel(tmp, _frame);
+ }
+ if (!(tmp = cert.getValue("L")).isEmpty()) {
+ label = new TQLabel(i18n("Locality:"), _frame);
+ label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ new TQLabel(tmp, _frame);
+ }
+ if (!(tmp = cert.getValue("ST")).isEmpty()) {
+ label = new TQLabel(i18n("Federal State","State:"), _frame);
+ label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ new TQLabel(tmp, _frame);
+ }
+ if (!(tmp = cert.getValue("C")).isEmpty()) {
+ label = new TQLabel(i18n("Country:"), _frame);
+ label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ new TQLabel(tmp, _frame);
+ }
+ if (!(tmp = cert.getValue("CN")).isEmpty()) {
+ label = new TQLabel(i18n("Common name:"), _frame);
+ label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ new TQLabel(tmp, _frame);
+ }
+ if (!(tmp = cert.getValue("Email")).isEmpty()) {
+ label = new TQLabel(i18n("Email:"), _frame);
+ label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
+ if (mailCatcher) {
+ KURLLabel *mail = new KURLLabel(tmp, tmp, _frame);
+ connect(mail, TQT_SIGNAL(leftClickedURL(const TQString &)), mailCatcher, TQT_SLOT(mailClicked(const TQString &)));
+ } else {
+ label = new TQLabel(tmp, _frame);
+ }
+ }
+ if (label && viewport()) {
+ viewport()->setBackgroundMode(label->backgroundMode());
+ }
+ addChild(_frame);
+ updateScrollBars();
+ _frame->show();
+ show();
+}
+
+
+TQScrollView *KSSLInfoDlg::buildCertInfo(const TQString &certName) {
+ return KSSLInfoDlg::certInfoWidget(this, certName, this);
+}
+
+void KSSLInfoDlg::urlClicked(const TQString &url) {
+ kapp->invokeBrowser(url);
+}
+
+void KSSLInfoDlg::mailClicked(const TQString &url) {
+ kapp->invokeMailer(url, TQString::null);
+}
+
+#include "ksslinfodlg.moc"
+// vim: ts=4 sw=4 et
diff --git a/kio/kssl/ksslinfodlg.h b/tdeio/kssl/ksslinfodlg.h
index c73afbba1..c73afbba1 100644
--- a/kio/kssl/ksslinfodlg.h
+++ b/tdeio/kssl/ksslinfodlg.h
diff --git a/tdeio/kssl/ksslkeygen.cc b/tdeio/kssl/ksslkeygen.cc
new file mode 100644
index 000000000..541c63f02
--- /dev/null
+++ b/tdeio/kssl/ksslkeygen.cc
@@ -0,0 +1,223 @@
+/* This file is part of the KDE project
+ *
+ * Copyright (C) 2001 George Staikos <staikos@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+
+#include "ksslkeygen.h"
+#include "keygenwizard.h"
+#include "keygenwizard2.h"
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kopenssl.h>
+#include <kprogress.h>
+#include <kstandarddirs.h>
+#include <ktempfile.h>
+#include <tdewallet.h>
+
+#include <tqlineedit.h>
+#include <tqpushbutton.h>
+
+#include <assert.h>
+
+
+KSSLKeyGen::KSSLKeyGen(TQWidget *parent, const char *name, bool modal)
+:KWizard(parent,name,modal) {
+ _idx = -1;
+
+#ifdef KSSL_HAVE_SSL
+ page1 = new KGWizardPage1(this, "Wizard Page 1");
+ addPage(page1, i18n("TDE Certificate Request"));
+ page2 = new KGWizardPage2(this, "Wizard Page 2");
+ addPage(page2, i18n("TDE Certificate Request - Password"));
+ setHelpEnabled(page1, false);
+ setHelpEnabled(page2, false);
+ setFinishEnabled(page2, false);
+ connect(page2->_password1, TQT_SIGNAL(textChanged(const TQString&)), this, TQT_SLOT(slotPassChanged()));
+ connect(page2->_password2, TQT_SIGNAL(textChanged(const TQString&)), this, TQT_SLOT(slotPassChanged()));
+ connect(finishButton(), TQT_SIGNAL(clicked()), TQT_SLOT(slotGenerate()));
+#else
+ // tell him he doesn't have SSL
+#endif
+}
+
+
+KSSLKeyGen::~KSSLKeyGen() {
+
+}
+
+
+void KSSLKeyGen::slotPassChanged() {
+ setFinishEnabled(page2, page2->_password1->text() == page2->_password2->text() && page2->_password1->text().length() >= 4);
+}
+
+
+void KSSLKeyGen::slotGenerate() {
+ assert(_idx >= 0 && _idx <= 3); // for now
+
+
+ // Generate the CSR
+ int bits;
+ switch (_idx) {
+ case 0:
+ bits = 2048;
+ break;
+ case 1:
+ bits = 1024;
+ break;
+ case 2:
+ bits = 768;
+ break;
+ case 3:
+ bits = 512;
+ break;
+ default:
+ KMessageBox::sorry(NULL, i18n("Unsupported key size."), i18n("TDE SSL Information"));
+ return;
+ }
+
+ KProgressDialog *kpd = new KProgressDialog(this, "progress dialog", i18n("TDE"), i18n("Please wait while the encryption keys are generated..."));
+ kpd->progressBar()->setProgress(0);
+ kpd->show();
+ // FIXME - progress dialog won't show this way
+
+ int rc = generateCSR("This CSR" /*FIXME */, page2->_password1->text(), bits, 0x10001 /* This is the traditional exponent used */);
+ kpd->progressBar()->setProgress(100);
+
+#ifndef Q_OS_WIN //TODO: reenable for WIN32
+ if (rc == 0 && KWallet::Wallet::isEnabled()) {
+ rc = KMessageBox::questionYesNo(this, i18n("Do you wish to store the passphrase in your wallet file?"), TQString::null, i18n("Store"), i18n("Do Not Store"));
+ if (rc == KMessageBox::Yes) {
+ KWallet::Wallet *w = KWallet::Wallet::openWallet(KWallet::Wallet::LocalWallet(), winId());
+ if (w) {
+ // FIXME: store passphrase in wallet
+ delete w;
+ }
+ }
+ }
+#endif
+
+ kpd->deleteLater();
+}
+
+
+int KSSLKeyGen::generateCSR(const TQString& name, const TQString& pass, int bits, int e) {
+#ifdef KSSL_HAVE_SSL
+ KOSSL *kossl = KOSSL::self();
+ int rc;
+
+ X509_REQ *req = kossl->X509_REQ_new();
+ if (!req) {
+ return -2;
+ }
+
+ EVP_PKEY *pkey = kossl->EVP_PKEY_new();
+ if (!pkey) {
+ kossl->X509_REQ_free(req);
+ return -4;
+ }
+
+ RSA *rsakey = kossl->RSA_generate_key(bits, e, NULL, NULL);
+ if (!rsakey) {
+ kossl->X509_REQ_free(req);
+ kossl->EVP_PKEY_free(pkey);
+ return -3;
+ }
+
+ rc = kossl->EVP_PKEY_assign(pkey, EVP_PKEY_RSA, (char *)rsakey);
+
+ rc = kossl->X509_REQ_set_pubkey(req, pkey);
+
+ // Set the subject
+ X509_NAME *n = kossl->X509_NAME_new();
+
+ kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_countryName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
+ kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_organizationName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
+ kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_organizationalUnitName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
+ kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_localityName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
+ kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_stateOrProvinceName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
+ kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_commonName, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
+ kossl->X509_NAME_add_entry_by_txt(n, (char*)LN_pkcs9_emailAddress, MBSTRING_UTF8, (unsigned char*)name.local8Bit().data(), -1, -1, 0);
+
+ rc = kossl->X509_REQ_set_subject_name(req, n);
+
+
+ rc = kossl->X509_REQ_sign(req, pkey, kossl->EVP_md5());
+
+ // We write it to the database and then the caller can obtain it
+ // back from there. Yes it's inefficient, but it doesn't happen
+ // often and this way things are uniform.
+
+ TDEGlobal::dirs()->addResourceType("kssl", KStandardDirs::kde_default("data") + "kssl");
+
+ TQString path = TDEGlobal::dirs()->saveLocation("kssl");
+ KTempFile csrFile(path + "csr_", ".der");
+
+ if (!csrFile.fstream()) {
+ kossl->X509_REQ_free(req);
+ kossl->EVP_PKEY_free(pkey);
+ return -5;
+ }
+
+ KTempFile p8File(path + "pkey_", ".p8");
+
+ if (!p8File.fstream()) {
+ kossl->X509_REQ_free(req);
+ kossl->EVP_PKEY_free(pkey);
+ return -5;
+ }
+
+ kossl->i2d_X509_REQ_fp(csrFile.fstream(), req);
+
+ kossl->i2d_PKCS8PrivateKey_fp(p8File.fstream(), pkey,
+ kossl->EVP_bf_cbc(), pass.local8Bit().data(),
+ pass.length(), 0L, 0L);
+
+ // FIXME Write tdeconfig entry to store the filenames under the md5 hash
+
+ kossl->X509_REQ_free(req);
+ kossl->EVP_PKEY_free(pkey);
+
+ return 0;
+#else
+ return -1;
+#endif
+}
+
+
+TQStringList KSSLKeyGen::supportedKeySizes() {
+ TQStringList x;
+
+#ifdef KSSL_HAVE_SSL
+ x << i18n("2048 (High Grade)")
+ << i18n("1024 (Medium Grade)")
+ << i18n("768 (Low Grade)")
+ << i18n("512 (Low Grade)");
+#else
+ x << i18n("No SSL support.");
+#endif
+
+ return x;
+}
+
+
+#include "ksslkeygen.moc"
+
diff --git a/kio/kssl/ksslkeygen.h b/tdeio/kssl/ksslkeygen.h
index 5bb99a593..5bb99a593 100644
--- a/kio/kssl/ksslkeygen.h
+++ b/tdeio/kssl/ksslkeygen.h
diff --git a/kio/kssl/ksslpeerinfo.cc b/tdeio/kssl/ksslpeerinfo.cc
index d1c2d00fc..d1c2d00fc 100644
--- a/kio/kssl/ksslpeerinfo.cc
+++ b/tdeio/kssl/ksslpeerinfo.cc
diff --git a/kio/kssl/ksslpeerinfo.h b/tdeio/kssl/ksslpeerinfo.h
index a5cd017c9..a5cd017c9 100644
--- a/kio/kssl/ksslpeerinfo.h
+++ b/tdeio/kssl/ksslpeerinfo.h
diff --git a/kio/kssl/ksslpemcallback.cc b/tdeio/kssl/ksslpemcallback.cc
index 2dfbb9146..2dfbb9146 100644
--- a/kio/kssl/ksslpemcallback.cc
+++ b/tdeio/kssl/ksslpemcallback.cc
diff --git a/kio/kssl/ksslpemcallback.h b/tdeio/kssl/ksslpemcallback.h
index 265edd099..265edd099 100644
--- a/kio/kssl/ksslpemcallback.h
+++ b/tdeio/kssl/ksslpemcallback.h
diff --git a/kio/kssl/ksslpkcs12.cc b/tdeio/kssl/ksslpkcs12.cc
index b8b23cf1c..b8b23cf1c 100644
--- a/kio/kssl/ksslpkcs12.cc
+++ b/tdeio/kssl/ksslpkcs12.cc
diff --git a/kio/kssl/ksslpkcs12.h b/tdeio/kssl/ksslpkcs12.h
index c9dff0d82..c9dff0d82 100644
--- a/kio/kssl/ksslpkcs12.h
+++ b/tdeio/kssl/ksslpkcs12.h
diff --git a/kio/kssl/ksslpkcs7.cc b/tdeio/kssl/ksslpkcs7.cc
index 8db0000f0..8db0000f0 100644
--- a/kio/kssl/ksslpkcs7.cc
+++ b/tdeio/kssl/ksslpkcs7.cc
diff --git a/kio/kssl/ksslpkcs7.h b/tdeio/kssl/ksslpkcs7.h
index c94b7bc7a..c94b7bc7a 100644
--- a/kio/kssl/ksslpkcs7.h
+++ b/tdeio/kssl/ksslpkcs7.h
diff --git a/kio/kssl/ksslsession.cc b/tdeio/kssl/ksslsession.cc
index 3c80233f1..3c80233f1 100644
--- a/kio/kssl/ksslsession.cc
+++ b/tdeio/kssl/ksslsession.cc
diff --git a/kio/kssl/ksslsession.h b/tdeio/kssl/ksslsession.h
index 394a4b91a..394a4b91a 100644
--- a/kio/kssl/ksslsession.h
+++ b/tdeio/kssl/ksslsession.h
diff --git a/kio/kssl/ksslsettings.cc b/tdeio/kssl/ksslsettings.cc
index eb91ea9cb..eb91ea9cb 100644
--- a/kio/kssl/ksslsettings.cc
+++ b/tdeio/kssl/ksslsettings.cc
diff --git a/tdeio/kssl/ksslsettings.h b/tdeio/kssl/ksslsettings.h
new file mode 100644
index 000000000..18b55331f
--- /dev/null
+++ b/tdeio/kssl/ksslsettings.h
@@ -0,0 +1,224 @@
+/* This file is part of the KDE project
+ *
+ * Copyright (C) 2000-2003 George Staikos <staikos@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef _KSSLSETTINGS_H
+#define _KSSLSETTINGS_H
+
+#include <tqstring.h>
+#include <tqvaluelist.h>
+#include <tdeconfig.h>
+
+class KSSLSettingsPrivate;
+
+/**
+ * KDE SSL Settings
+ *
+ * This class contains some of the SSL settings for easy use.
+ *
+ * @author George Staikos <staikos@kde.org>
+ * @see KSSL
+ * @short KDE SSL Settings
+ */
+class TDEIO_EXPORT KSSLSettings {
+public:
+ /**
+ * Construct a KSSL Settings object
+ *
+ * @param readConfig read in the configuration immediately if true
+ */
+ KSSLSettings(bool readConfig = true);
+
+ /**
+ * Destroy this KSSL Settings object
+ */
+ ~KSSLSettings();
+
+ /**
+ * Does the user allow SSLv2
+ * @return true if the user allows SSLv2
+ */
+ bool sslv2() const;
+
+ /**
+ * Does the user allow SSLv3
+ * @return true if the user allows SSLv3
+ */
+ bool sslv3() const;
+
+ /**
+ * Does the user allow TLSv1
+ * @return true if the user allows TLSv1
+ */
+ bool tlsv1() const;
+
+ /**
+ * Does the user want to be warned on entering SSL mode
+ * @return true if the user wants to be warned
+ */
+ bool warnOnEnter() const;
+
+ /**
+ * Change the user's warnOnEnter() setting
+ * @since 3.3
+ * @param x true if the user is to be warned
+ * @see warnOnEnter
+ */
+ void setWarnOnEnter(bool x);
+
+ /**
+ * Does the user want to be warned on sending unencrypted data
+ * @return true if the user wants to be warned
+ * @see setWarnOnUnencrypted
+ */
+ bool warnOnUnencrypted() const;
+
+ /**
+ * Change the user's warnOnUnencrypted() setting
+ * @param x true if the user is to be warned
+ * @see warnOnUnencrypted
+ */
+ void setWarnOnUnencrypted(bool x);
+
+ /**
+ * Does the user want to be warned on leaving SSL mode
+ * @return true if the user wants to be warned
+ */
+ bool warnOnLeave() const;
+
+ /**
+ * Change the user's warnOnLeave() setting
+ * @since 3.3
+ * @param x true if the user is to be warned
+ * @see warnOnLeave
+ */
+ void setWarnOnLeave(bool x);
+
+ /**
+ * Does the user want to be warned during mixed SSL/non-SSL mode
+ * @return true if the user wants to be warned
+ */
+ bool warnOnMixed() const;
+
+ /**
+ * Do not use this
+ * @deprecated
+ */
+ bool warnOnSelfSigned() const KDE_DEPRECATED;
+
+ /**
+ * Do not use this
+ * @deprecated
+ */
+ bool warnOnRevoked() const KDE_DEPRECATED;
+
+ /**
+ * Do not use this
+ * @deprecated
+ */
+ bool warnOnExpired() const KDE_DEPRECATED;
+
+ /**
+ * Does the user want to use the Entropy Gathering Daemon?
+ * @return true if the user wants to use EGD
+ */
+ bool useEGD() const;
+
+ /**
+ * Does the user want to use an entropy file?
+ * @return true if the user wants to use an entropy file
+ */
+ bool useEFile() const;
+
+ /**
+ * Change the user's TLSv1 preference
+ * @param enabled true if TLSv1 is enabled
+ */
+ void setTLSv1(bool enabled);
+
+ /**
+ * Change the user's SSLv2 preference
+ * @param enabled true if SSLv2 is enabled
+ */
+ void setSSLv2(bool enabled);
+
+ /**
+ * Change the user's SSLv3 preference
+ * @param enabled true if SSLv3 is enabled
+ */
+ void setSSLv3(bool enabled);
+
+ /**
+ * Does the user want X.509 client certificates to always be sent when
+ * possible?
+ * @return true if the user always wants a certificate sent
+ */
+ bool autoSendX509() const;
+
+ /**
+ * Does the user want to be prompted to send X.509 client certificates
+ * when possible?
+ * @return true if the user wants to be prompted
+ */
+ bool promptSendX509() const;
+
+ /**
+ * Get the OpenSSL cipher list for selecting the list of ciphers to
+ * use in a connection.
+ * @return the cipher list
+ */
+ TQString getCipherList();
+
+ /**
+ * Get the configured path to the entropy gathering daemon or entropy
+ * file.
+ * @return the path
+ */
+ TQString& getEGDPath();
+
+ /**
+ * Load the user's settings.
+ */
+ void load();
+
+ /**
+ * Revert to default settings.
+ */
+ void defaults();
+
+ /**
+ * Save the current settings.
+ */
+ void save();
+
+private:
+ TDEConfig *m_cfg;
+ bool m_bUseSSLv2, m_bUseSSLv3, m_bUseTLSv1;
+ bool m_bWarnOnEnter, m_bWarnOnUnencrypted, m_bWarnOnLeave, m_bWarnOnMixed;
+ bool m_bWarnSelfSigned, m_bWarnRevoked, m_bWarnExpired;
+
+ TQValueList<TQString> v2ciphers, v2selectedciphers, v3ciphers, v3selectedciphers;
+ TQValueList<int> v2bits, v3bits;
+
+ KSSLSettingsPrivate *d;
+};
+
+
+#endif
+
diff --git a/kio/kssl/ksslsigners.cc b/tdeio/kssl/ksslsigners.cc
index 028ddf555..028ddf555 100644
--- a/kio/kssl/ksslsigners.cc
+++ b/tdeio/kssl/ksslsigners.cc
diff --git a/kio/kssl/ksslsigners.h b/tdeio/kssl/ksslsigners.h
index 3149e852a..3149e852a 100644
--- a/kio/kssl/ksslsigners.h
+++ b/tdeio/kssl/ksslsigners.h
diff --git a/kio/kssl/ksslutils.cc b/tdeio/kssl/ksslutils.cc
index 80651757f..80651757f 100644
--- a/kio/kssl/ksslutils.cc
+++ b/tdeio/kssl/ksslutils.cc
diff --git a/kio/kssl/ksslutils.h b/tdeio/kssl/ksslutils.h
index 4c087374f..4c087374f 100644
--- a/kio/kssl/ksslutils.h
+++ b/tdeio/kssl/ksslutils.h
diff --git a/kio/kssl/ksslx509map.cc b/tdeio/kssl/ksslx509map.cc
index 7896fdfcf..7896fdfcf 100644
--- a/kio/kssl/ksslx509map.cc
+++ b/tdeio/kssl/ksslx509map.cc
diff --git a/kio/kssl/ksslx509map.h b/tdeio/kssl/ksslx509map.h
index f76413100..f76413100 100644
--- a/kio/kssl/ksslx509map.h
+++ b/tdeio/kssl/ksslx509map.h
diff --git a/kio/kssl/ksslx509v3.cc b/tdeio/kssl/ksslx509v3.cc
index a3310b9db..a3310b9db 100644
--- a/kio/kssl/ksslx509v3.cc
+++ b/tdeio/kssl/ksslx509v3.cc
diff --git a/kio/kssl/ksslx509v3.h b/tdeio/kssl/ksslx509v3.h
index c521f3e25..c521f3e25 100644
--- a/kio/kssl/ksslx509v3.h
+++ b/tdeio/kssl/ksslx509v3.h
diff --git a/kio/kurifilterplugin.desktop b/tdeio/kurifilterplugin.desktop
index 5882b35ca..5882b35ca 100644
--- a/kio/kurifilterplugin.desktop
+++ b/tdeio/kurifilterplugin.desktop
diff --git a/kio/magic b/tdeio/magic
index c12cec4ba..c12cec4ba 100644
--- a/kio/magic
+++ b/tdeio/magic
diff --git a/tdeio/misc/CMakeLists.txt b/tdeio/misc/CMakeLists.txt
new file mode 100644
index 000000000..3bfdb0980
--- /dev/null
+++ b/tdeio/misc/CMakeLists.txt
@@ -0,0 +1,100 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+add_subdirectory( tdesendbugmail )
+add_subdirectory( kpac )
+add_subdirectory( tdesasl )
+add_subdirectory( kssld )
+add_subdirectory( tdefile )
+add_subdirectory( tdewalletd )
+add_subdirectory( tdentlm )
+
+add_definitions(
+ -D_LARGEFILE64_SOURCE
+)
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_BINARY_DIR}/tdeio
+ ${CMAKE_BINARY_DIR}/tdeio/tdeio
+ ${CMAKE_BINARY_DIR}/tdeio/kssl
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdefx
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/kssl
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### headers ###################################
+
+install( FILES uiserver.h DESTINATION ${INCLUDE_INSTALL_DIR}/tdeio )
+
+
+##### other data ################################
+
+install(FILES
+ tdeio_uiserver.desktop tdemailservice.protocol
+ telnet.protocol rlogin.protocol rtsp.protocol
+ ssh.protocol mms.protocol mmst.protocol mmsu.protocol
+ pnm.protocol rtspt.protocol rtspu.protocol
+ DESTINATION ${SERVICES_INSTALL_DIR} )
+
+install( FILES fileshareset DESTINATION ${BIN_INSTALL_DIR}
+ PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE SETUID )
+
+
+#### tdeio_uiserver ###############################
+
+set( target tdeio_uiserver )
+
+set( ${target}_SRCS
+ uiserver.cpp uiserver.skel
+)
+
+tde_add_tdeinit_executable( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DEPENDENCIES dcopidl
+)
+
+
+##### tdemailservice ##############################
+
+set( target tdemailservice )
+
+tde_add_executable( ${target}
+ SOURCES ${target}.cpp
+ LINK tdecore-shared
+ DESTINATION ${BIN_INSTALL_DIR}
+)
+
+
+##### tdetelnetservice ############################
+
+set( target tdetelnetservice )
+
+tde_add_executable( ${target}
+ SOURCES ${target}.cpp
+ LINK tdeui-shared
+ DESTINATION ${BIN_INSTALL_DIR}
+)
+
+tde_install_symlink( ${target} ${BIN_INSTALL_DIR}/filesharelist )
diff --git a/tdeio/misc/Makefile.am b/tdeio/misc/Makefile.am
new file mode 100644
index 000000000..6a250cf8a
--- /dev/null
+++ b/tdeio/misc/Makefile.am
@@ -0,0 +1,60 @@
+# This file is part of the KDE libraries
+# Copyright (C) 1997 Torben Weis (weis@kde.org)
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
+
+INCLUDES= -I$(srcdir)/.. -I$(top_srcdir) -I$(srcdir)/../kssl -I../kssl $(all_includes) $(SSL_INCLUDES)
+
+SUBDIRS = . tdesendbugmail kpac tdesasl kssld tdefile tdewalletd tdentlm
+
+lib_LTLIBRARIES =
+tdeinit_LTLIBRARIES = tdeio_uiserver.la
+bin_PROGRAMS = tdemailservice tdetelnetservice
+
+observer_DIR = $(top_srcdir)/tdeio/tdeio
+
+tdeio_uiserver_la_SOURCES = uiserver.cpp uiserver.skel observer.stub
+tdeio_uiserver_la_LIBADD = $(LIB_KIO) $(LIB_TDEUI) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE)
+tdeio_uiserver_la_LDFLAGS = $(all_libraries) -module -avoid-version
+
+METASOURCES = AUTO
+
+kde_services_DATA = tdeio_uiserver.desktop
+
+tdemailservice_SOURCES = tdemailservice.cpp
+tdemailservice_LDADD = $(LIB_TDECORE)
+tdemailservice_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+
+tdetelnetservice_SOURCES = tdetelnetservice.cpp
+tdetelnetservice_LDADD = $(LIB_TDEUI)
+tdetelnetservice_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+
+protocol_DATA = tdemailservice.protocol telnet.protocol rlogin.protocol rtsp.protocol ssh.protocol \
+ mms.protocol mmst.protocol mmsu.protocol pnm.protocol rtspt.protocol rtspu.protocol
+protocoldir = $(kde_servicesdir)
+
+kiomiscdir = $(includedir)/tdeio
+kiomisc_HEADERS = uiserver.h
+
+
+bin_SCRIPTS = fileshareset
+install-exec-local:
+ @-rm -f $(DESTDIR)$(bindir)/filesharelist
+ @$(LN_S) fileshareset $(DESTDIR)$(bindir)/filesharelist
+ @(chown root $(DESTDIR)$(bindir)/fileshareset && chmod 4755 $(DESTDIR)$(bindir)/fileshareset) || echo "Was not able to make fileshareset setuid root"
+
diff --git a/kio/misc/fileshareset b/tdeio/misc/fileshareset
index 4c921ba38..4c921ba38 100755
--- a/kio/misc/fileshareset
+++ b/tdeio/misc/fileshareset
diff --git a/tdeio/misc/kpac/CMakeLists.txt b/tdeio/misc/kpac/CMakeLists.txt
new file mode 100644
index 000000000..14af52de1
--- /dev/null
+++ b/tdeio/misc/kpac/CMakeLists.txt
@@ -0,0 +1,66 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_BINARY_DIR}/kjs
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore/network
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/kded
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+##### other data ################################
+
+install(FILES proxyscout.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
+install(FILES eventsrc DESTINATION ${DATA_INSTALL_DIR}/proxyscout )
+
+
+##### kded_proxyscout ###########################
+
+set( target kded_proxyscout )
+
+set( ${target}_SRCS
+ proxyscout.cpp proxyscout.skel script.cpp
+ downloader.cpp discovery.cpp
+)
+
+set( ${target}_SKELS
+ proxyscout.h
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeinit_kded-shared kjs-shared ${RESOLV_LIBRARIES}
+ DEPENDENCIES dcopidl
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
+
+
+##### kpac_dhcp_helper ##########################
+
+set( target kpac_dhcp_helper )
+
+# FIXME on Gentoo this binary is not suided
+tde_add_executable( ${target} SETUID
+ SOURCES kpac_dhcp_helper.c
+ DESTINATION ${BIN_INSTALL_DIR}
+)
diff --git a/kio/misc/kpac/Makefile.am b/tdeio/misc/kpac/Makefile.am
index beb6a4b86..beb6a4b86 100644
--- a/kio/misc/kpac/Makefile.am
+++ b/tdeio/misc/kpac/Makefile.am
diff --git a/kio/misc/kpac/README b/tdeio/misc/kpac/README
index d211ae07b..d211ae07b 100644
--- a/kio/misc/kpac/README
+++ b/tdeio/misc/kpac/README
diff --git a/kio/misc/kpac/README.wpad b/tdeio/misc/kpac/README.wpad
index f63d25764..f63d25764 100644
--- a/kio/misc/kpac/README.wpad
+++ b/tdeio/misc/kpac/README.wpad
diff --git a/kio/misc/kpac/TODO b/tdeio/misc/kpac/TODO
index ce5cd6a11..ce5cd6a11 100644
--- a/kio/misc/kpac/TODO
+++ b/tdeio/misc/kpac/TODO
diff --git a/kio/misc/kpac/configure.in.in b/tdeio/misc/kpac/configure.in.in
index a65b9a1c8..a65b9a1c8 100644
--- a/kio/misc/kpac/configure.in.in
+++ b/tdeio/misc/kpac/configure.in.in
diff --git a/kio/misc/kpac/dhcp.h b/tdeio/misc/kpac/dhcp.h
index 41643ae3a..41643ae3a 100644
--- a/kio/misc/kpac/dhcp.h
+++ b/tdeio/misc/kpac/dhcp.h
diff --git a/kio/misc/kpac/discovery.cpp b/tdeio/misc/kpac/discovery.cpp
index 4f33d1389..4f33d1389 100644
--- a/kio/misc/kpac/discovery.cpp
+++ b/tdeio/misc/kpac/discovery.cpp
diff --git a/kio/misc/kpac/discovery.h b/tdeio/misc/kpac/discovery.h
index a1443ad8c..a1443ad8c 100644
--- a/kio/misc/kpac/discovery.h
+++ b/tdeio/misc/kpac/discovery.h
diff --git a/tdeio/misc/kpac/downloader.cpp b/tdeio/misc/kpac/downloader.cpp
new file mode 100644
index 000000000..c94cc9b72
--- /dev/null
+++ b/tdeio/misc/kpac/downloader.cpp
@@ -0,0 +1,89 @@
+/*
+ Copyright (c) 2003 Malte Starostik <malte@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+
+#include <cstdlib>
+#include <cstring>
+
+#include <tqtextcodec.h>
+
+#include <kcharsets.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <tdeio/job.h>
+
+#include "downloader.moc"
+
+namespace KPAC
+{
+ Downloader::Downloader( TQObject* parent )
+ : TQObject( parent )
+ {
+ }
+
+ void Downloader::download( const KURL& url )
+ {
+ m_data.resize( 0 );
+ m_script = TQString::null;
+ m_scriptURL = url;
+
+ TDEIO::TransferJob* job = TDEIO::get( url, false, false );
+ connect( job, TQT_SIGNAL( data( TDEIO::Job*, const TQByteArray& ) ),
+ TQT_SLOT( data( TDEIO::Job*, const TQByteArray& ) ) );
+ connect( job, TQT_SIGNAL( result( TDEIO::Job* ) ), TQT_SLOT( result( TDEIO::Job* ) ) );
+ }
+
+ void Downloader::failed()
+ {
+ emit result( false );
+ }
+
+ void Downloader::setError( const TQString& error )
+ {
+ m_error = error;
+ }
+
+ void Downloader::data( TDEIO::Job*, const TQByteArray& data )
+ {
+ unsigned offset = m_data.size();
+ m_data.resize( offset + data.size() );
+ std::memcpy( m_data.data() + offset, data.data(), data.size() );
+ }
+
+ void Downloader::result( TDEIO::Job* job )
+ {
+ if ( !job->error() && !static_cast< TDEIO::TransferJob* >( job )->isErrorPage() )
+ {
+ bool dummy;
+ m_script = TDEGlobal::charsets()->codecForName(
+ job->queryMetaData( "charset" ), dummy )->toUnicode( m_data );
+ emit result( true );
+ }
+ else
+ {
+ if ( job->error() )
+ setError( i18n( "Could not download the proxy configuration script:\n%1" )
+ .arg( job->errorString() ) );
+ else setError( i18n( "Could not download the proxy configuration script" ) ); // error page
+ failed();
+ }
+ }
+}
+
+// vim: ts=4 sw=4 et
diff --git a/kio/misc/kpac/downloader.h b/tdeio/misc/kpac/downloader.h
index 808e09378..808e09378 100644
--- a/kio/misc/kpac/downloader.h
+++ b/tdeio/misc/kpac/downloader.h
diff --git a/kio/misc/kpac/eventsrc b/tdeio/misc/kpac/eventsrc
index c44443a03..c44443a03 100644
--- a/kio/misc/kpac/eventsrc
+++ b/tdeio/misc/kpac/eventsrc
diff --git a/kio/misc/kpac/kpac_dhcp_helper.c b/tdeio/misc/kpac/kpac_dhcp_helper.c
index 906e89dfa..906e89dfa 100644
--- a/kio/misc/kpac/kpac_dhcp_helper.c
+++ b/tdeio/misc/kpac/kpac_dhcp_helper.c
diff --git a/kio/misc/kpac/kpactest.pac b/tdeio/misc/kpac/kpactest.pac
index 69e5aaad7..69e5aaad7 100644
--- a/kio/misc/kpac/kpactest.pac
+++ b/tdeio/misc/kpac/kpactest.pac
diff --git a/kio/misc/kpac/proxyscout.cpp b/tdeio/misc/kpac/proxyscout.cpp
index b651e2313..b651e2313 100644
--- a/kio/misc/kpac/proxyscout.cpp
+++ b/tdeio/misc/kpac/proxyscout.cpp
diff --git a/kio/misc/kpac/proxyscout.desktop b/tdeio/misc/kpac/proxyscout.desktop
index 02e402b50..02e402b50 100644
--- a/kio/misc/kpac/proxyscout.desktop
+++ b/tdeio/misc/kpac/proxyscout.desktop
diff --git a/kio/misc/kpac/proxyscout.h b/tdeio/misc/kpac/proxyscout.h
index 78c8fc237..78c8fc237 100644
--- a/kio/misc/kpac/proxyscout.h
+++ b/tdeio/misc/kpac/proxyscout.h
diff --git a/kio/misc/kpac/script.cpp b/tdeio/misc/kpac/script.cpp
index 55faef8a1..55faef8a1 100644
--- a/kio/misc/kpac/script.cpp
+++ b/tdeio/misc/kpac/script.cpp
diff --git a/kio/misc/kpac/script.h b/tdeio/misc/kpac/script.h
index 49ba0b6a3..49ba0b6a3 100644
--- a/kio/misc/kpac/script.h
+++ b/tdeio/misc/kpac/script.h
diff --git a/tdeio/misc/kssld/CMakeLists.txt b/tdeio/misc/kssld/CMakeLists.txt
new file mode 100644
index 000000000..813ce44f0
--- /dev/null
+++ b/tdeio/misc/kssld/CMakeLists.txt
@@ -0,0 +1,47 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdeio/kssl
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio/kssl
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install(FILES kssld.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
+
+
+##### kded_kssld ###########################
+
+set( target kded_kssld )
+
+set( ${target}_SRCS
+ kssld.cpp kssld.skel
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeinit_kded-shared
+ DEPENDENCIES dcopidl
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/tdeio/misc/kssld/Makefile.am b/tdeio/misc/kssld/Makefile.am
new file mode 100644
index 000000000..09ddfe440
--- /dev/null
+++ b/tdeio/misc/kssld/Makefile.am
@@ -0,0 +1,33 @@
+# This file is part of the KDE libraries
+# Copyright (C) 2001 George Staikos <staikos@kde.org>
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+INCLUDES= -I$(srcdir)/.. -I$(top_srcdir) $(SSL_INCLUDES) -I$(top_srcdir)/tdeio/kssl -I$(top_builddir)/tdeio/kssl $(all_includes)
+
+kde_module_LTLIBRARIES = kded_kssld.la
+
+kded_kssld_la_LDFLAGS = $(all_libraries) -module -avoid-version
+kded_kssld_la_LIBADD = $(LIB_KIO) $(LIB_KDED) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE)
+kded_kssld_la_SOURCES = kssld.cpp kssld.skel
+
+METASOURCES = AUTO
+
+noinst_HEADERS = kssld.h
+
+services_DATA = kssld.desktop
+servicesdir = $(kde_servicesdir)/kded
+
diff --git a/tdeio/misc/kssld/kssld.cpp b/tdeio/misc/kssld/kssld.cpp
new file mode 100644
index 000000000..aa561cc8b
--- /dev/null
+++ b/tdeio/misc/kssld/kssld.cpp
@@ -0,0 +1,1027 @@
+/*
+ This file is part of the KDE libraries
+
+ Copyright (c) 2001-2005 George Staikos <staikos@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <tqtimer.h>
+
+#include "kssld.h"
+#include <tdeconfig.h>
+#include <ksimpleconfig.h>
+#include <ksslcertchain.h>
+#include <ksslcertificate.h>
+#include <ksslcertificatehome.h>
+#include <ksslpkcs12.h>
+#include <ksslx509map.h>
+#include <tqptrlist.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdlib.h>
+#include <pwd.h>
+#include <unistd.h>
+#include <tqfile.h>
+#include <tqsortedlist.h>
+#include <kglobal.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <tqdatetime.h>
+
+#include <kmdcodec.h>
+#include <kopenssl.h>
+
+// See design notes at end
+
+extern "C" {
+ KDE_EXPORT KDEDModule *create_kssld(const TQCString &name) {
+ return new KSSLD(name);
+ }
+
+ KDE_EXPORT void *__kde_do_unload;
+}
+
+
+static void updatePoliciesConfig(TDEConfig *cfg) {
+ TQStringList groups = cfg->groupList();
+
+ for (TQStringList::Iterator i = groups.begin(); i != groups.end(); ++i) {
+ if ((*i).isEmpty() || *i == "General") {
+ continue;
+ }
+
+ cfg->setGroup(*i);
+
+ // remove it if it has expired
+ if (!cfg->readBoolEntry("Permanent") && cfg->readDateTimeEntry("Expires") < TQDateTime::currentDateTime()) {
+ cfg->deleteGroup(*i);
+ continue;
+ }
+
+ TQString encodedCertStr = cfg->readEntry("Certificate");
+ TQCString encodedCert = encodedCertStr.local8Bit();
+ KSSLCertificate *newCert = KSSLCertificate::fromString(encodedCert);
+ if (!newCert) {
+ cfg->deleteGroup(*i);
+ continue;
+ }
+
+ KSSLCertificateCache::KSSLCertificatePolicy policy = (KSSLCertificateCache::KSSLCertificatePolicy) cfg->readNumEntry("Policy");
+ bool permanent = cfg->readBoolEntry("Permanent");
+ TQDateTime expires = cfg->readDateTimeEntry("Expires");
+ TQStringList hosts = cfg->readListEntry("Hosts");
+ TQStringList chain = cfg->readListEntry("Chain");
+ cfg->deleteGroup(*i);
+
+ cfg->setGroup(newCert->getMD5Digest());
+ cfg->writeEntry("Certificate", encodedCertStr);
+ cfg->writeEntry("Policy", policy);
+ cfg->writeEntry("Permanent", permanent);
+ cfg->writeEntry("Expires", expires);
+ cfg->writeEntry("Hosts", hosts);
+ cfg->writeEntry("Chain", chain);
+ delete newCert;
+ }
+
+ cfg->setGroup("General");
+ cfg->writeEntry("policies version", 2);
+
+ cfg->sync();
+}
+
+
+KSSLD::KSSLD(const TQCString &name) : KDEDModule(name)
+{
+// ----------------------- FOR THE CACHE ------------------------------------
+ cfg = new KSimpleConfig("ksslpolicies", false);
+ cfg->setGroup("General");
+ if (2 != cfg->readNumEntry("policies version", 0)) {
+ ::updatePoliciesConfig(cfg);
+ }
+ TDEGlobal::dirs()->addResourceType("kssl", KStandardDirs::kde_default("data") + "kssl");
+ caVerifyUpdate();
+ cacheLoadDefaultPolicies();
+ certList.setAutoDelete(false);
+ kossl = KOSSL::self();
+
+// ----------------------- FOR THE HOME -------------------------------------
+}
+
+
+KSSLD::~KSSLD()
+{
+// ----------------------- FOR THE CACHE ------------------------------------
+ cacheClearList();
+ delete cfg;
+
+// ----------------------- FOR THE HOME -------------------------------------
+}
+
+
+
+
+// A node in the cache
+class KSSLCNode {
+ public:
+ KSSLCertificate *cert;
+ KSSLCertificateCache::KSSLCertificatePolicy policy;
+ bool permanent;
+ TQDateTime expires;
+ TQStringList hosts;
+ KSSLCNode() { cert = 0L;
+ policy = KSSLCertificateCache::Unknown;
+ permanent = true;
+ }
+ ~KSSLCNode() { delete cert; }
+};
+
+
+
+void KSSLD::cacheSaveToDisk() {
+KSSLCNode *node;
+
+ cfg->setGroup("General");
+ cfg->writeEntry("policies version", 2);
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (node->permanent ||
+ node->expires > TQDateTime::currentDateTime()) {
+ // First convert to a binary format and then write the
+ // tdeconfig entry write the (CN, policy, cert) to
+ // KSimpleConfig
+ cfg->setGroup(node->cert->getMD5Digest());
+ cfg->writeEntry("Certificate", node->cert->toString());
+ cfg->writeEntry("Policy", node->policy);
+ cfg->writeEntry("Expires", node->expires);
+ cfg->writeEntry("Permanent", node->permanent);
+ cfg->writeEntry("Hosts", node->hosts);
+
+ // Also write the chain
+ TQStringList qsl;
+ TQPtrList<KSSLCertificate> cl =
+ node->cert->chain().getChain();
+ for (KSSLCertificate *c = cl.first();
+ c != 0;
+ c = cl.next()) {
+ //kdDebug() << "Certificate in chain: "
+ // << c->toString() << endl;
+ qsl << c->toString();
+ }
+
+ cl.setAutoDelete(true);
+ cfg->writeEntry("Chain", qsl);
+ }
+ }
+
+ cfg->sync();
+
+ // insure proper permissions -- contains sensitive data
+ TQString cfgName(TDEGlobal::dirs()->findResource("config", "ksslpolicies"));
+
+ if (!cfgName.isEmpty()) {
+ ::chmod(TQFile::encodeName(cfgName), 0600);
+ }
+}
+
+
+void KSSLD::cacheReload() {
+ cacheClearList();
+ delete cfg;
+ cfg = new KSimpleConfig("ksslpolicies", false);
+ cacheLoadDefaultPolicies();
+}
+
+
+void KSSLD::cacheClearList() {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ certList.remove(node);
+ delete node;
+ }
+
+ skEmail.clear();
+ skMD5Digest.clear();
+}
+
+
+void KSSLD::cacheLoadDefaultPolicies() {
+TQStringList groups = cfg->groupList();
+
+ for (TQStringList::Iterator i = groups.begin();
+ i != groups.end();
+ ++i) {
+ if ((*i).isEmpty() || *i == "General") {
+ continue;
+ }
+
+ cfg->setGroup(*i);
+
+ // remove it if it has expired
+ if (!cfg->readBoolEntry("Permanent") &&
+ cfg->readDateTimeEntry("Expires") <
+ TQDateTime::currentDateTime()) {
+ cfg->deleteGroup(*i);
+ continue;
+ }
+
+ TQCString encodedCert;
+ KSSLCertificate *newCert;
+
+ encodedCert = cfg->readEntry("Certificate").local8Bit();
+ newCert = KSSLCertificate::fromString(encodedCert);
+
+ if (!newCert) {
+ continue;
+ }
+
+ KSSLCNode *n = new KSSLCNode;
+ n->cert = newCert;
+ n->policy = (KSSLCertificateCache::KSSLCertificatePolicy) cfg->readNumEntry("Policy");
+ n->permanent = cfg->readBoolEntry("Permanent");
+ n->expires = cfg->readDateTimeEntry("Expires");
+ n->hosts = cfg->readListEntry("Hosts");
+ newCert->chain().setCertChain(cfg->readListEntry("Chain"));
+ certList.append(n);
+ searchAddCert(newCert);
+ }
+}
+
+
+void KSSLD::cacheAddCertificate(KSSLCertificate cert,
+ KSSLCertificateCache::KSSLCertificatePolicy policy,
+ bool permanent) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ node->policy = policy;
+ node->permanent = permanent;
+
+ if (!permanent) {
+ node->expires = TQDateTime::currentDateTime();
+ // FIXME: make this configurable
+ node->expires = TQT_TQDATETIME_OBJECT(node->expires.addSecs(3600));
+ }
+
+ cacheSaveToDisk();
+ return;
+ }
+ }
+
+ KSSLCNode *n = new KSSLCNode;
+ n->cert = cert.replicate();
+ n->policy = policy;
+ n->permanent = permanent;
+ // remove the old one
+ cacheRemoveByCertificate(*(n->cert));
+ certList.prepend(n);
+
+ if (!permanent) {
+ n->expires = TQDateTime::currentDateTime();
+ n->expires = TQT_TQDATETIME_OBJECT(n->expires.addSecs(3600));
+ }
+
+ searchAddCert(n->cert);
+ cacheSaveToDisk();
+}
+
+
+KSSLCertificateCache::KSSLCertificatePolicy KSSLD::cacheGetPolicyByCN(TQString cn) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
+ if (!node->permanent &&
+ node->expires < TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ delete node;
+ continue;
+ }
+
+ certList.remove(node);
+ certList.prepend(node);
+ cacheSaveToDisk();
+ return node->policy;
+ }
+ }
+
+ cacheSaveToDisk();
+
+return KSSLCertificateCache::Unknown;
+}
+
+
+KSSLCertificateCache::KSSLCertificatePolicy KSSLD::cacheGetPolicyByCertificate(KSSLCertificate cert) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ if (!node->permanent &&
+ node->expires < TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ delete node;
+ cacheSaveToDisk();
+ return KSSLCertificateCache::Unknown;
+ }
+
+ certList.remove(node);
+ certList.prepend(node);
+ return node->policy;
+ }
+ }
+
+return KSSLCertificateCache::Unknown;
+}
+
+
+bool KSSLD::cacheSeenCN(TQString cn) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
+ if (!node->permanent &&
+ node->expires < TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ delete node;
+ cacheSaveToDisk();
+ continue;
+ }
+
+ certList.remove(node);
+ certList.prepend(node);
+ return true;
+ }
+ }
+
+return false;
+}
+
+
+bool KSSLD::cacheSeenCertificate(KSSLCertificate cert) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ if (!node->permanent &&
+ node->expires < TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ delete node;
+ cacheSaveToDisk();
+ return false;
+ }
+
+ certList.remove(node);
+ certList.prepend(node);
+ return true;
+ }
+ }
+
+return false;
+}
+
+
+bool KSSLD::cacheIsPermanent(KSSLCertificate cert) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ if (!node->permanent && node->expires <
+ TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ delete node;
+ cacheSaveToDisk();
+ return false;
+ }
+
+ certList.remove(node);
+ certList.prepend(node);
+ return node->permanent;
+ }
+ }
+
+return false;
+}
+
+
+bool KSSLD::cacheRemoveBySubject(TQString subject) {
+KSSLCNode *node;
+bool gotOne = false;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (node->cert->getSubject() == subject) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ searchRemoveCert(node->cert);
+ delete node;
+ gotOne = true;
+ }
+ }
+
+ cacheSaveToDisk();
+
+return gotOne;
+}
+
+
+bool KSSLD::cacheRemoveByCN(TQString cn) {
+KSSLCNode *node;
+bool gotOne = false;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ searchRemoveCert(node->cert);
+ delete node;
+ gotOne = true;
+ }
+ }
+
+ cacheSaveToDisk();
+
+return gotOne;
+}
+
+
+bool KSSLD::cacheRemoveByCertificate(KSSLCertificate cert) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ searchRemoveCert(node->cert);
+ delete node;
+ cacheSaveToDisk();
+ return true;
+ }
+ }
+
+return false;
+}
+
+
+bool KSSLD::cacheModifyByCN(TQString cn,
+ KSSLCertificateCache::KSSLCertificatePolicy policy, bool permanent,
+ TQDateTime expires) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (KSSLX509Map(node->cert->getSubject()).getValue("CN") == cn) {
+ node->permanent = permanent;
+ node->expires = expires;
+ node->policy = policy;
+ certList.remove(node);
+ certList.prepend(node);
+ cacheSaveToDisk();
+ return true;
+ }
+ }
+
+return false;
+}
+
+
+bool KSSLD::cacheModifyByCertificate(KSSLCertificate cert,
+ KSSLCertificateCache::KSSLCertificatePolicy policy,
+ bool permanent,
+ TQDateTime expires) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ node->permanent = permanent;
+ node->expires = expires;
+ node->policy = policy;
+ certList.remove(node);
+ certList.prepend(node);
+ cacheSaveToDisk();
+ return true;
+ }
+ }
+
+return false;
+}
+
+
+TQStringList KSSLD::cacheGetHostList(KSSLCertificate cert) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ if (!node->permanent && node->expires <
+ TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ searchRemoveCert(node->cert);
+ delete node;
+ cacheSaveToDisk();
+ return TQStringList();
+ }
+
+ certList.remove(node);
+ certList.prepend(node);
+ return node->hosts;
+ }
+ }
+
+return TQStringList();
+}
+
+
+bool KSSLD::cacheAddHost(KSSLCertificate cert, TQString host) {
+KSSLCNode *node;
+
+ if (host.isEmpty())
+ return true;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ if (!node->permanent && node->expires <
+ TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ searchRemoveCert(node->cert);
+ delete node;
+ cacheSaveToDisk();
+ return false;
+ }
+
+ if (!node->hosts.contains(host)) {
+ node->hosts << host;
+ }
+
+ certList.remove(node);
+ certList.prepend(node);
+ cacheSaveToDisk();
+ return true;
+ }
+ }
+
+return false;
+}
+
+
+bool KSSLD::cacheRemoveHost(KSSLCertificate cert, TQString host) {
+KSSLCNode *node;
+
+ for (node = certList.first(); node; node = certList.next()) {
+ if (cert == *(node->cert)) {
+ if (!node->permanent && node->expires <
+ TQDateTime::currentDateTime()) {
+ certList.remove(node);
+ cfg->deleteGroup(node->cert->getMD5Digest());
+ searchRemoveCert(node->cert);
+ delete node;
+ cacheSaveToDisk();
+ return false;
+ }
+ node->hosts.remove(host);
+ certList.remove(node);
+ certList.prepend(node);
+ cacheSaveToDisk();
+ return true;
+ }
+ }
+
+return false;
+}
+
+
+
+
+///////////////////////////////////////////////////////////////////////////
+
+void KSSLD::caVerifyUpdate() {
+ TQString path = TDEGlobal::dirs()->saveLocation("kssl") + "/ca-bundle.crt";
+ if (!TQFile::exists(path))
+ return;
+
+ cfg->setGroup(TQString::null);
+ TQ_UINT32 newStamp = TDEGlobal::dirs()->calcResourceHash("config", "ksslcalist", true);
+ TQ_UINT32 oldStamp = cfg->readUnsignedNumEntry("ksslcalistStamp");
+ if (oldStamp != newStamp)
+ {
+ caRegenerate();
+ cfg->writeEntry("ksslcalistStamp", newStamp);
+ cfg->sync();
+ }
+}
+
+bool KSSLD::caRegenerate() {
+TQString path = TDEGlobal::dirs()->saveLocation("kssl") + "/ca-bundle.crt";
+
+TQFile out(path);
+
+ if (!out.open(IO_WriteOnly))
+ return false;
+
+TDEConfig cfg("ksslcalist", true, false);
+
+TQStringList x = cfg.groupList();
+
+ for (TQStringList::Iterator i = x.begin();
+ i != x.end();
+ ++i) {
+ if ((*i).isEmpty() || *i == "<default>") continue;
+
+ cfg.setGroup(*i);
+
+ if (!cfg.readBoolEntry("site", false)) continue;
+
+ TQString cert = cfg.readEntry("x509", "");
+ if (cert.length() <= 0) continue;
+
+ unsigned int xx = cert.length() - 1;
+ for (unsigned int j = 0; j < xx/64; j++) {
+ cert.insert(64*(j+1)+j, '\n');
+ }
+ out.writeBlock("-----BEGIN CERTIFICATE-----\n", 28);
+ out.writeBlock(cert.latin1(), cert.length());
+ out.writeBlock("\n-----END CERTIFICATE-----\n\n", 28);
+ out.flush();
+ }
+
+return true;
+}
+
+
+
+bool KSSLD::caAdd(TQString certificate, bool ssl, bool email, bool code) {
+KSSLCertificate *x = KSSLCertificate::fromString(certificate.local8Bit());
+
+ if (!x) return false;
+
+TDEConfig cfg("ksslcalist", false, false);
+
+ cfg.setGroup(x->getSubject());
+ cfg.writeEntry("x509", certificate);
+ cfg.writeEntry("site", ssl);
+ cfg.writeEntry("email", email);
+ cfg.writeEntry("code", code);
+
+ cfg.sync();
+ delete x;
+
+return true;
+}
+
+
+/**
+ * @internal
+ * Returns a list of certificates as QStrings read from the given file
+ */
+static TQStringList caReadCerticatesFromFile(TQString filename) {
+
+ TQStringList certificates;
+ TQString certificate, temp;
+ TQFile file(filename);
+
+ if (!file.open(IO_ReadOnly))
+ return certificates;
+
+ while (!file.atEnd()) {
+ file.readLine(temp, 999);
+ if (temp.startsWith("-----BEGIN CERTIFICATE-----")) {
+ certificate = TQString::null;
+ continue;
+ }
+
+ if (temp.startsWith("-----END CERTIFICATE-----")) {
+ certificates.append(certificate);
+ certificate = TQString::null;
+ continue;
+ }
+
+ certificate += temp.stripWhiteSpace();
+ }
+
+ file.close();
+
+ return certificates;
+}
+
+bool KSSLD::caAddFromFile(TQString filename, bool ssl, bool email, bool code) {
+
+ TQStringList certificates;
+ certificates = caReadCerticatesFromFile(filename);
+ if (certificates.isEmpty())
+ return false;
+
+ bool ok = true;
+
+ for (TQStringList::Iterator it = certificates.begin();
+ it != certificates.end(); ++it ) {
+ ok &= caAdd(*it, ssl, email, code);
+ }
+
+ return ok;
+}
+
+bool KSSLD::caRemoveFromFile(TQString filename) {
+
+ TQStringList certificates;
+ certificates = caReadCerticatesFromFile(filename);
+ if (certificates.isEmpty())
+ return false;
+
+ bool ok = true;
+
+ for (TQStringList::Iterator it = certificates.begin();
+ it != certificates.end(); ++it ) {
+ TQString certificate = *it;
+ KSSLCertificate *x = KSSLCertificate::fromString(certificate.local8Bit());
+ ok &= x && caRemove(x->getSubject());
+ delete x;
+ }
+
+ return ok;
+}
+
+
+TQStringList KSSLD::caList() {
+TQStringList x;
+TDEConfig cfg("ksslcalist", true, false);
+
+ x = cfg.groupList();
+ x.remove("<default>");
+
+return x;
+}
+
+
+bool KSSLD::caUseForSSL(TQString subject) {
+TDEConfig cfg("ksslcalist", true, false);
+
+ if (!cfg.hasGroup(subject))
+ return false;
+
+ cfg.setGroup(subject);
+return cfg.readBoolEntry("site", false);
+}
+
+
+
+bool KSSLD::caUseForEmail(TQString subject) {
+TDEConfig cfg("ksslcalist", true, false);
+
+ if (!cfg.hasGroup(subject))
+ return false;
+
+ cfg.setGroup(subject);
+return cfg.readBoolEntry("email", false);
+}
+
+
+
+bool KSSLD::caUseForCode(TQString subject) {
+TDEConfig cfg("ksslcalist", true, false);
+
+ if (!cfg.hasGroup(subject))
+ return false;
+
+ cfg.setGroup(subject);
+return cfg.readBoolEntry("code", false);
+}
+
+
+bool KSSLD::caRemove(TQString subject) {
+TDEConfig cfg("ksslcalist", false, false);
+ if (!cfg.hasGroup(subject))
+ return false;
+
+ cfg.deleteGroup(subject);
+ cfg.sync();
+
+return true;
+}
+
+
+TQString KSSLD::caGetCert(TQString subject) {
+TDEConfig cfg("ksslcalist", true, false);
+ if (!cfg.hasGroup(subject))
+ return TQString::null;
+
+ cfg.setGroup(subject);
+
+return cfg.readEntry("x509", TQString::null);
+}
+
+
+bool KSSLD::caSetUse(TQString subject, bool ssl, bool email, bool code) {
+TDEConfig cfg("ksslcalist", false, false);
+ if (!cfg.hasGroup(subject))
+ return false;
+
+ cfg.setGroup(subject);
+
+ cfg.writeEntry("site", ssl);
+ cfg.writeEntry("email", email);
+ cfg.writeEntry("code", code);
+ cfg.sync();
+
+return true;
+}
+
+///////////////////////////////////////////////////////////////////////////
+
+void KSSLD::searchAddCert(KSSLCertificate *cert) {
+ skMD5Digest.insert(cert->getMD5Digest(), cert, true);
+
+ TQStringList mails;
+ cert->getEmails(mails);
+ for(TQStringList::const_iterator iter = mails.begin(); iter != mails.end(); ++iter) {
+ TQString email = static_cast<const TQString &>(*iter).lower();
+ TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(email);
+
+ if (it == skEmail.end())
+ it = skEmail.insert(email, TQPtrVector<KSSLCertificate>());
+
+ TQPtrVector<KSSLCertificate> &elem = *it;
+
+ if (elem.findRef(cert) == -1) {
+ unsigned int n = 0;
+ for(; n < elem.size(); n++) {
+ if (!elem.at(n)) {
+ elem.insert(n, cert);
+ break;
+ }
+ }
+ if (n == elem.size()) {
+ elem.resize(n+1);
+ elem.insert(n, cert);
+ }
+ }
+ }
+}
+
+
+void KSSLD::searchRemoveCert(KSSLCertificate *cert) {
+ skMD5Digest.remove(cert->getMD5Digest());
+
+ TQStringList mails;
+ cert->getEmails(mails);
+ for(TQStringList::const_iterator iter = mails.begin(); iter != mails.end(); ++iter) {
+ TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(static_cast<const TQString &>(*iter).lower());
+
+ if (it == skEmail.end())
+ break;
+
+ TQPtrVector<KSSLCertificate> &elem = *it;
+
+ int n = elem.findRef(cert);
+ if (n != -1)
+ elem.remove(n);
+ }
+}
+
+
+TQStringList KSSLD::getKDEKeyByEmail(const TQString &email) {
+ TQStringList rc;
+ TQMap<TQString, TQPtrVector<KSSLCertificate> >::iterator it = skEmail.find(email.lower());
+
+ kdDebug() << "GETKDEKey " << email.latin1() << endl;
+
+ if (it == skEmail.end())
+ return rc;
+
+ TQPtrVector<KSSLCertificate> &elem = *it;
+ for (unsigned int n = 0; n < elem.size(); n++) {
+ KSSLCertificate *cert = elem.at(n);
+ if (cert) {
+ rc.append(cert->getKDEKey());
+ }
+ }
+
+ kdDebug() << "ergebnisse: " << rc.size() << " " << elem.size() << endl;
+ return rc;
+}
+
+
+KSSLCertificate KSSLD::getCertByMD5Digest(const TQString &key) {
+ TQMap<TQString, KSSLCertificate *>::iterator iter = skMD5Digest.find(key);
+
+ kdDebug() << "Searching cert for " << key.latin1() << endl;
+
+ if (iter != skMD5Digest.end())
+ return **iter;
+
+ KSSLCertificate rc; // FIXME: Better way to return a not found condition?
+ kdDebug() << "Not found: " << rc.toString().latin1() << endl;
+ return rc;
+}
+
+
+///////////////////////////////////////////////////////////////////////////
+
+//
+// Certificate Home methods
+//
+
+TQStringList KSSLD::getHomeCertificateList() {
+ return KSSLCertificateHome::getCertificateList();
+}
+
+bool KSSLD::addHomeCertificateFile(TQString filename, TQString password, bool storePass) {
+ return KSSLCertificateHome::addCertificate(filename, password, storePass);
+}
+
+bool KSSLD::addHomeCertificatePKCS12(TQString base64cert, TQString passToStore) {
+ bool ok;
+ KSSLPKCS12 *pkcs12 = KSSLPKCS12::fromString(base64cert, passToStore);
+ ok = KSSLCertificateHome::addCertificate(pkcs12, passToStore);
+ delete pkcs12;
+ return ok;
+}
+
+bool KSSLD::deleteHomeCertificateByFile(TQString filename, TQString password) {
+ return KSSLCertificateHome::deleteCertificate(filename, password);
+}
+
+bool KSSLD::deleteHomeCertificateByPKCS12(TQString base64cert, TQString password) {
+ bool ok;
+ KSSLPKCS12 *pkcs12 = KSSLPKCS12::fromString(base64cert, password);
+ ok = KSSLCertificateHome::deleteCertificate(pkcs12);
+ delete pkcs12;
+ return ok;
+}
+
+bool KSSLD::deleteHomeCertificateByName(TQString name) {
+ return KSSLCertificateHome::deleteCertificateByName(name);
+}
+
+
+
+///////////////////////////////////////////////////////////////////////////
+
+#include "kssld.moc"
+
+
+/*
+
+ DESIGN - KSSLCertificateCache
+ ------
+
+ This is the first implementation and I think this cache actually needs
+ experimentation to determine which implementation works best. My current
+ options are:
+
+ (1) Store copies of the X509 certificates in a TQPtrList using a self
+ organizing heuristic as described by Munro and Suwanda.
+ (2) Store copies of the X509 certificates in a tree structure, perhaps
+ a redblack tree, avl tree, or even just a simple binary tree.
+ (3) Store the CN's in a tree or list and use them as a hash to retrieve
+ the X509 certificates.
+ (4) Create "nodes" containing the X509 certificate and place them in
+ two structures concurrently, one organized by CN, the other by
+ X509 serial number.
+
+ This implementation uses (1). (4) is definitely attractive, but I don't
+ think it will be necessary to go so crazy with performance, and perhaps
+ end up performing poorly in situations where there are very few entries in
+ the cache (which is most likely the case most of the time). The style of
+ heuristic is move-to-front, not swap-forward. This seems to make more
+ sense because the typical user will hit a site at least a few times in a
+ row before moving to a new one.
+
+ What I worry about most with respect to performance is that cryptographic
+ routines are expensive and if we have to perform them on each X509
+ certificate until the right one is found, we will perform poorly.
+
+ All in all, this code is actually quite crucial for performance on SSL
+ website, especially those with many image files loaded via SSL. If a
+ site loads 15 images, we will have to run through this code 15 times.
+ A heuristic for self organization will make each successive lookup faster.
+ Sounds good, doesn't it?
+
+ DO NOT ATTEMPT TO GUESS WHICH CERTIFICATES ARE ACCEPTIBLE IN YOUR CODE!!
+ ALWAYS USE THE CACHE. IT MAY CHECK THINGS THAT YOU DON'T THINK OF, AND
+ ALSO IF THERE IS A BUG IN THE CHECKING CODE, IF IT IS ALL CONTAINED IN
+ THIS LIBRARY, A MINOR FIX WILL FIX ALL APPLICATIONS.
+ */
+
diff --git a/kio/misc/kssld/kssld.desktop b/tdeio/misc/kssld/kssld.desktop
index 7054f8bad..7054f8bad 100644
--- a/kio/misc/kssld/kssld.desktop
+++ b/tdeio/misc/kssld/kssld.desktop
diff --git a/kio/misc/kssld/kssld.h b/tdeio/misc/kssld/kssld.h
index 028a30809..028a30809 100644
--- a/kio/misc/kssld/kssld.h
+++ b/tdeio/misc/kssld/kssld.h
diff --git a/kio/misc/mms.protocol b/tdeio/misc/mms.protocol
index 8fde7c000..8fde7c000 100644
--- a/kio/misc/mms.protocol
+++ b/tdeio/misc/mms.protocol
diff --git a/kio/misc/mmst.protocol b/tdeio/misc/mmst.protocol
index 1f0f7636b..1f0f7636b 100644
--- a/kio/misc/mmst.protocol
+++ b/tdeio/misc/mmst.protocol
diff --git a/kio/misc/mmsu.protocol b/tdeio/misc/mmsu.protocol
index deda935fc..deda935fc 100644
--- a/kio/misc/mmsu.protocol
+++ b/tdeio/misc/mmsu.protocol
diff --git a/kio/misc/pnm.protocol b/tdeio/misc/pnm.protocol
index 3ca3a7d23..3ca3a7d23 100644
--- a/kio/misc/pnm.protocol
+++ b/tdeio/misc/pnm.protocol
diff --git a/tdeio/misc/rlogin.protocol b/tdeio/misc/rlogin.protocol
new file mode 100644
index 000000000..3b103a905
--- /dev/null
+++ b/tdeio/misc/rlogin.protocol
@@ -0,0 +1,13 @@
+[Protocol]
+exec=tdetelnetservice %u
+protocol=rlogin
+input=none
+output=none
+helper=true
+listing=
+reading=false
+writing=false
+makedir=false
+deleting=false
+DocPath=tdeioslave/rlogin.html
+Icon=konsole
diff --git a/kio/misc/rtsp.protocol b/tdeio/misc/rtsp.protocol
index 301312260..301312260 100644
--- a/kio/misc/rtsp.protocol
+++ b/tdeio/misc/rtsp.protocol
diff --git a/kio/misc/rtspt.protocol b/tdeio/misc/rtspt.protocol
index 9e4fe9626..9e4fe9626 100644
--- a/kio/misc/rtspt.protocol
+++ b/tdeio/misc/rtspt.protocol
diff --git a/kio/misc/rtspu.protocol b/tdeio/misc/rtspu.protocol
index 9cc9299f6..9cc9299f6 100644
--- a/kio/misc/rtspu.protocol
+++ b/tdeio/misc/rtspu.protocol
diff --git a/tdeio/misc/ssh.protocol b/tdeio/misc/ssh.protocol
new file mode 100644
index 000000000..b0c098f8f
--- /dev/null
+++ b/tdeio/misc/ssh.protocol
@@ -0,0 +1,13 @@
+[Protocol]
+exec=tdetelnetservice %u
+protocol=ssh
+input=none
+output=none
+helper=true
+listing=false
+reading=false
+writing=false
+makedir=false
+deleting=false
+Icon=konsole
+
diff --git a/tdeio/misc/tdefile/CMakeLists.txt b/tdeio/misc/tdefile/CMakeLists.txt
new file mode 100644
index 000000000..9e90b956c
--- /dev/null
+++ b/tdeio/misc/tdefile/CMakeLists.txt
@@ -0,0 +1,39 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### tdefile #####################################
+
+set( target tdefile )
+
+set( ${target}_SRCS
+ fileprops.cpp
+)
+
+tde_add_executable( ${target}
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${BIN_INSTALL_DIR}
+) \ No newline at end of file
diff --git a/tdeio/misc/tdefile/Makefile.am b/tdeio/misc/tdefile/Makefile.am
new file mode 100644
index 000000000..21cdb0627
--- /dev/null
+++ b/tdeio/misc/tdefile/Makefile.am
@@ -0,0 +1,10 @@
+METASOURCES = AUTO
+
+noinst_HEADERS = fileprops.h
+INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/tdeio/tdeio $(all_includes)
+
+bin_PROGRAMS = tdefile
+tdefile_SOURCES = fileprops.cpp
+tdefile_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+tdefile_LDADD = $(LIB_KIO)
+
diff --git a/kio/misc/kfile/README b/tdeio/misc/tdefile/README
index d063b6d58..d063b6d58 100644
--- a/kio/misc/kfile/README
+++ b/tdeio/misc/tdefile/README
diff --git a/tdeio/misc/tdefile/fileprops.cpp b/tdeio/misc/tdefile/fileprops.cpp
new file mode 100644
index 000000000..bb209fbc0
--- /dev/null
+++ b/tdeio/misc/tdefile/fileprops.cpp
@@ -0,0 +1,480 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation, version 2.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <iostream>
+
+#include <tqfile.h>
+#include <tqptrlist.h>
+
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kcmdlineargs.h>
+#include <tdefilemetainfo.h>
+#include <klocale.h>
+#include <kpropertiesdialog.h>
+
+#include "fileprops.h"
+
+#define KFILEVERSION "0.2"
+#define INDENT "\t"
+
+using namespace std;
+
+static TQString beatifyValue( const TQString& value )
+{
+ if ( value.isNull() )
+ return TQString("(no value for key available)");
+ else if ( value.isEmpty() )
+ return TQString("(empty)");
+
+ return value;
+}
+
+FileProps::FileProps( const TQString& path, const TQStringList& suppliedGroups )
+ : m_dirty( false )
+{
+ m_info = new KFileMetaInfo(path, TQString::null, KFileMetaInfo::Everything);
+ m_userSuppliedGroups = !suppliedGroups.isEmpty();
+ m_groupsToUse = m_userSuppliedGroups ? suppliedGroups : m_info->groups();
+}
+
+FileProps::~FileProps()
+{
+ sync();
+ delete m_info;
+}
+
+bool FileProps::sync()
+{
+ if ( !m_dirty )
+ return true;
+
+ return m_info->applyChanges();
+}
+
+bool FileProps::isValid() const
+{
+ return m_info->isValid();
+}
+
+TQStringList FileProps::supportedGroups() const
+{
+ return m_info->supportedGroups();
+}
+
+TQStringList FileProps::availableGroups() const
+{
+ return m_info->groups();
+}
+
+TQStringList FileProps::supportedKeys( const TQString& group ) const
+{
+ KFileMetaInfoGroup g = m_info->group( group );
+ return g.supportedKeys();
+}
+
+TQStringList FileProps::availableKeys( const TQString& group ) const
+{
+ KFileMetaInfoGroup g = m_info->group( group );
+ TQStringList allKeys = g.keys();
+ TQStringList ret;
+ TQStringList::ConstIterator it = allKeys.begin();
+ for ( ; it != allKeys.end(); ++it )
+ {
+ if ( g.item( *it ).isValid() )
+ ret.append( *it );
+ }
+
+ return ret;
+}
+
+TQStringList FileProps::preferredKeys( const TQString& group ) const
+{
+ KFileMetaInfoGroup g = m_info->group( group );
+ return g.preferredKeys();
+}
+
+TQString FileProps::getValue( const TQString& group,
+ const TQString& key ) const
+{
+ KFileMetaInfoGroup g = m_info->group( group );
+ return FileProps::createKeyValue( g, key );
+}
+
+bool FileProps::setValue( const TQString& group,
+ const TQString& key, const TQString &value )
+{
+ KFileMetaInfoGroup g = m_info->group( group );
+ bool wasAdded = false;
+ if ( !g.isValid() )
+ {
+ if ( m_info->addGroup( group ) )
+ {
+ wasAdded = true;
+ g = m_info->group( group );
+ }
+ else
+ return false;
+ }
+
+ bool ok = g[key].setValue( value );
+
+ if ( !ok && wasAdded ) // remove the created group again
+ (void) m_info->removeGroup( group );
+
+ m_dirty |= ok;
+ return ok;
+}
+
+TQStringList FileProps::allValues( const TQString& group ) const
+{
+ KFileMetaInfoGroup g = m_info->group( group );
+ return FileProps::createKeyValueList( g, g.keys() );
+}
+
+TQStringList FileProps::preferredValues( const TQString& group ) const
+{
+ KFileMetaInfoGroup g = m_info->group( group );
+ return FileProps::createKeyValueList( g, g.preferredKeys() );
+}
+
+// static helper:
+// creates strings like
+// "group: translatedKey: value"
+TQString FileProps::createKeyValue( const KFileMetaInfoGroup& g,
+ const TQString& key )
+{
+ static const int MAX_SPACE = 25;
+ KFileMetaInfoItem item = g.item( key );
+
+ TQString result("%1");
+ result = result.arg( (item.isValid() ? item.translatedKey() : key) + ":",
+ -MAX_SPACE );
+ result.append( beatifyValue( item.string() ) );
+
+ TQString group("%1");
+ group = group.arg( g.translatedName() + ":", -MAX_SPACE );
+ result.prepend( group );
+
+ return result;
+}
+
+// static
+TQStringList FileProps::createKeyValueList( const KFileMetaInfoGroup& g,
+ const TQStringList& keys )
+{
+ TQStringList result;
+ TQStringList::ConstIterator it = keys.begin();
+
+ for ( ; it != keys.end(); ++it )
+ result.append( FileProps::createKeyValue( g, *it ) );
+
+ return result;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+
+// tdefile --mimetype --listsupported --listavailable --listpreferred --listwritable --getValue "key" --setValue "key=value" --allValues --preferredValues --dialog --quiet file [file...]
+// "key" may be a list of keys, separated by commas
+static KCmdLineOptions options[] =
+{
+ { "m", 0, 0 }, // short option for --mimetype
+ { "nomimetype", I18N_NOOP("Do not print the mimetype of the given file(s)"), 0 },
+
+ { "ls", 0, 0 }, // short option for --listsupported
+ { "listsupported <mimetype>",
+ I18N_NOOP("List all supported metadata keys of the given file(s). "
+ "If mimetype is not specified, the mimetype of the given "
+ "files is used." ), "file" },
+
+ { "lp", 0, 0 }, // short option for --listpreferred
+ { "listpreferred <mimetype>",
+ I18N_NOOP("List all preferred metadata keys of the given file(s). "
+ "If mimetype is not specified, the mimetype of the given "
+ "files is used." ), "file" },
+
+ { "la", 0, 0 }, // short option for --listavailable
+ { "listavailable",
+ I18N_NOOP("List all metadata keys which have a value in the given "
+ "file(s)."), 0 },
+
+ { "sm", 0, 0 }, // short option for --supportedMimetypes
+ { "supportedMimetypes",
+ I18N_NOOP("Prints all mimetypes for which metadata support is "
+ "available."), 0 },
+
+ { "q", 0, 0 }, // short option for --quiet
+ { "quiet",
+ I18N_NOOP("Do not print a warning when more than one file was given "
+ "and they do not all have the same mimetype."), 0 },
+
+ { "av", 0, 0 }, // short option for --allValues
+ { "allValues",
+ I18N_NOOP("Prints all metadata values, available in the given "
+ "file(s)."), 0 },
+
+ { "pv", 0, 0 }, // short option for --preferredValues
+ { "preferredValues",
+ I18N_NOOP("Prints the preferred metadata values, available in the "
+ "given file(s)."), 0 },
+
+ { "dialog",
+ I18N_NOOP("Opens a TDE properties dialog to allow viewing and "
+ "modifying of metadata of the given file(s)"), 0 },
+
+ { "getValue <key>",
+ I18N_NOOP("Prints the value for 'key' of the given file(s). 'key' "
+ "may also be a comma-separated list of keys"), 0 },
+
+ { "setValue <key=value>",
+ I18N_NOOP("Attempts to set the value 'value' for the metadata key "
+ "'key' for the given file(s)"), 0 },
+
+ { "!groups <arguments>", I18N_NOOP("The group to get values from or set values to"),
+ 0 },
+
+ { "+[files]",
+ I18N_NOOP("The file (or a number of files) to operate on."), 0 },
+ KCmdLineLastOption
+};
+
+
+//
+// helper functions
+//
+
+static void printSupportedMimeTypes()
+{
+ TQStringList allMimeTypes = KFileMetaInfoProvider::self()->supportedMimeTypes();
+ if ( allMimeTypes.isEmpty() )
+ {
+ cout <<
+ i18n("No support for metadata extraction found.").local8Bit().data()
+ << endl;
+ return;
+ }
+
+ cout << i18n("Supported MimeTypes:").local8Bit().data() << endl;
+
+ TQStringList::ConstIterator it = allMimeTypes.begin();
+ for ( ; it != allMimeTypes.end(); it++ )
+ cout << (*it).local8Bit().data() << endl;
+}
+
+// caller needs to delete the returned list!
+static KFileItemList * fileItemList( const TDECmdLineArgs *args )
+{
+ KFileItemList * items = new KFileItemList();
+ items->setAutoDelete( true );
+ for ( int i = 0; i < args->count(); i++ )
+ items->append( new KFileItem( KFileItem::Unknown,
+ KFileItem::Unknown,
+ args->url( i ) ));
+ return items;
+}
+
+static void showPropertiesDialog( const TDECmdLineArgs *args )
+{
+ KFileItemList *items = fileItemList( args );
+ new KPropertiesDialog( *items, 0L, "props dialog", true );
+ delete items;
+}
+
+static void printMimeTypes( const TDECmdLineArgs *args )
+{
+ for ( int i = 0; i < args->count(); i++ )
+ {
+ KURL url = args->url( i );
+ KMimeType::Ptr mt = KMimeType::findByURL( url );
+ cout << args->arg(i) << ": " << mt->comment().local8Bit().data() << " ("
+ << mt->name().local8Bit().data() << ")" << endl;
+ }
+}
+
+static void printList( const TQStringList& list )
+{
+ TQStringList::ConstIterator it = list.begin();
+ for ( ; it != list.end(); ++it )
+ cout << (*it).local8Bit().data() << endl;
+ cout << endl;
+}
+
+static void processMetaDataOptions( const TQPtrList<FileProps> propList,
+ TDECmdLineArgs *args )
+{
+// tdefile --mimetype --supportedMimetypes --listsupported --listavailable --listpreferred --listwritable --getValue "key" --setValue "key=value" --allValues --preferredValues --dialog --quiet file [file...]
+// "key" may be a list of keys, separated by commas
+
+ TQString line("-- -------------------------------------------------------");
+ FileProps *props;
+ TQPtrListIterator<FileProps> it( propList );
+ for ( ; (props = it.current()); ++it )
+ {
+ TQString file = props->fileName() + " ";
+ TQString fileString = line.replace( 3, file.length(), file );
+ cout << TQFile::encodeName( fileString ).data() << endl;
+
+ if ( args->isSet( "listsupported" ) )
+ {
+ cout << "=Supported Keys=" << endl;
+ printList( props->supportedKeys() );
+ }
+ if ( args->isSet( "listpreferred" ) )
+ {
+ cout << "=Preferred Keys=" << endl;
+ printList( props->preferredKeys() );
+ }
+ if ( args->isSet( "listavailable" ) )
+ {
+ cout << "=Available Keys=" << endl;
+ TQStringList groups = props->availableGroups();
+ TQStringList::ConstIterator git = groups.begin();
+ for ( ; git != groups.end(); ++git )
+ {
+ cout << "Group: " << (*git).local8Bit().data() << endl;
+ printList( props->availableKeys( *git ) );
+ }
+ }
+// if ( args->isSet( "listwritable" ) )
+// {
+// cout << "TODO :)" << endl;
+// }
+ if ( args->isSet( "getValue" ) )
+ {
+ cout << "=Value=" << endl;
+ TQString key = TQString::fromLocal8Bit( args->getOption("getValue"));
+ TQStringList::ConstIterator git = props->groupsToUse().begin();
+ for ( ; git != props->groupsToUse().end(); ++git )
+ cout << props->getValue( *git, key ).local8Bit().data() << endl;
+ }
+
+ if ( args->isSet( "setValue" ) )
+ {
+ // separate key and value from the line "key=value"
+ TQString cmd = TQString::fromLocal8Bit( args->getOption("setValue"));
+ TQString key = cmd.section( '=', 0, 0 );
+ TQString value = cmd.section( '=', 1 );
+
+ // either use supplied groups or all supported groups
+ // (not only the available!)
+ TQStringList groups = props->userSuppliedGroups() ?
+ props->groupsToUse() :
+ props->supportedGroups();
+
+ TQStringList::ConstIterator git = groups.begin();
+ for ( ; git != groups.end(); ++git )
+ props->setValue( *git, key, value );
+ }
+
+ if ( args->isSet( "allValues" ) )
+ {
+ cout << "=All Values=" << endl;
+ TQStringList groups = props->availableGroups();
+ TQStringList::ConstIterator group = groups.begin();
+ for ( ; group != groups.end(); ++group )
+ printList( props->allValues( *group ) );
+ }
+ if ( args->isSet( "preferredValues" ) && !args->isSet("allValues") )
+ {
+ cout << "=Preferred Values=" << endl;
+ TQStringList groups = props->availableGroups();
+ TQStringList::ConstIterator group = groups.begin();
+ for ( ; group != groups.end(); ++group )
+ printList( props->preferredValues( *group ) );
+ }
+ }
+
+}
+
+int main( int argc, char **argv )
+{
+ TDEAboutData about(
+ "tdefile", I18N_NOOP( "tdefile" ), KFILEVERSION,
+ I18N_NOOP("A commandline tool to read and modify metadata of files." ),
+ TDEAboutData::License_LGPL, "(c) 2002, Carsten Pfeiffer",
+ 0 /*text*/, "http://devel-home.kde.org/~pfeiffer/",
+ "pfeiffer@kde.org" );
+
+ about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org",
+ "http://devel-home.kde.org/~pfeiffer/" );
+
+ TDECmdLineArgs::init( argc, argv, &about );
+
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+ bool useGUI = args->isSet( "dialog" );
+
+ TDEApplication app( useGUI, useGUI );
+
+ TQPtrList<FileProps> m_props;
+ m_props.setAutoDelete( true );
+
+ bool quiet = args->isSet( "quiet" );
+
+ if ( args->isSet( "supportedMimetypes" ) )
+ printSupportedMimeTypes();
+
+ int files = args->count();
+ if ( files == 0 )
+ TDECmdLineArgs::usage( i18n("No files specified") ); // exit()s
+
+ if ( args->isSet( "dialog" ) )
+ {
+ showPropertiesDialog( args );
+ return true;
+ }
+
+ TQStringList groupsToUse;
+ QCStringList suppliedGroups = args->getOptionList( "groups" );
+ QCStringList::ConstIterator it = suppliedGroups.begin();
+ for ( ; it != suppliedGroups.end(); ++it )
+ groupsToUse.append( TQString::fromLocal8Bit( (*it) ) );
+
+ TQString mimeType;
+
+ for ( int i = 0; i < files; i++ )
+ {
+ if ( args->isSet( "mimetype" ) )
+ printMimeTypes( args );
+
+ FileProps *props = new FileProps( args->url(i).path(), groupsToUse );
+ if ( props->isValid() )
+ m_props.append( props );
+ else
+ {
+ if ( !quiet )
+ {
+ cerr << args->arg(i) << ": " <<
+ i18n("Cannot determine metadata").local8Bit().data() << endl;
+ }
+ delete props;
+ }
+ }
+
+
+ processMetaDataOptions( m_props, args );
+
+ m_props.clear(); // force destruction/sync of props
+ cout.flush();
+
+ return 0;
+}
diff --git a/tdeio/misc/tdefile/fileprops.h b/tdeio/misc/tdefile/fileprops.h
new file mode 100644
index 000000000..45a79239d
--- /dev/null
+++ b/tdeio/misc/tdefile/fileprops.h
@@ -0,0 +1,74 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation, version 2.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef KFILEPROPS_H
+#define KFILEPROPS_H
+
+#include <tqstring.h>
+
+#include <tdefilemetainfo.h>
+
+class FileProps
+{
+public:
+ FileProps( const TQString& path, const TQStringList& suppliedGroups );
+ virtual ~FileProps();
+
+ bool isValid() const;
+
+ TQString fileName() const { return m_info->path(); }
+
+ TQStringList supportedGroups() const;
+ TQStringList availableGroups() const;
+ TQStringList translatedGroups();
+
+ const TQStringList& groupsToUse() const { return m_groupsToUse; }
+ bool userSuppliedGroups() const { return m_userSuppliedGroups; }
+
+ TQStringList supportedKeys( const TQString& group ) const;
+ TQStringList availableKeys( const TQString& group ) const;
+ TQStringList preferredKeys( const TQString& group ) const;
+
+ TQStringList supportedKeys() const { return m_info->supportedKeys(); }
+ TQStringList preferredKeys() const { return m_info->preferredKeys(); }
+
+ TQString getValue( const TQString& group, const TQString& key ) const;
+ bool setValue( const TQString& group,
+ const TQString& key, const TQString &value );
+
+ TQStringList allValues( const TQString& group ) const;
+ TQStringList preferredValues( const TQString& group ) const;
+
+ bool isReadOnly( const TQString& group, const TQString& key );
+
+private:
+ static TQString createKeyValue( const KFileMetaInfoGroup& g,
+ const TQString& key );
+ static TQStringList createKeyValueList( const KFileMetaInfoGroup&,
+ const TQStringList& );
+ bool sync();
+
+ KFileMetaInfo *m_info;
+ bool m_dirty;
+ bool m_userSuppliedGroups;
+
+ TQStringList m_groupsToUse;
+
+};
+
+#endif // KFILEPROPS_H
diff --git a/tdeio/misc/tdeio_uiserver.desktop b/tdeio/misc/tdeio_uiserver.desktop
new file mode 100644
index 000000000..bba0a7c7c
--- /dev/null
+++ b/tdeio/misc/tdeio_uiserver.desktop
@@ -0,0 +1,100 @@
+[Desktop Entry]
+Type=Service
+Name=tdeio_uiserver
+Name[de]=Server der graphischen Oberfläche
+Name[fy]=Kio_uiserver
+Name[ja]=kio_uiサーãƒ
+Name[mn]=График гадаргуугийн Ñервер
+Name[nds]=tdeio_uiserver, Server för de graafsche Böversiet
+Name[nl]=Kio_uiserver
+Name[nso]=kio_uiseabi
+Name[ro]=Kio_uiserver
+Name[sv]=Kio-gränssnittsserver
+Name[ta]=kio_uiசேவையகமà¯
+Name[te]=కేà°à°“_à°¯à±à°à°¸à±†à°°à±à°µà°°à±
+Exec=tdeio_uiserver
+Comment=TDE's Progress Info UI server
+Comment[af]=TDE se vordering inligting UI bediener
+Comment[ar]=خادم معلومات تقدم واجهة كيدي
+Comment[az]=TDE'nin İrəliləmə Bilgisi İstifadaçi Ara Üz Vericisi
+Comment[be]=Сервер паведамленнÑÑž аб выкананні дзеÑннÑÑž
+Comment[bg]=Сървър за отчитане на прогреÑа (TDE's Progress Info UI server)
+Comment[bn]=কে.ডি.ই. অগà§à¦°à¦—তি তথà§à¦¯ UI সারà§à¦­à¦¾à¦°
+Comment[br]=Servijer stlenn EA Progress TDE
+Comment[bs]=TDEov Progess Info UI server
+Comment[ca]=Servidor d'informació de progrés del TDE
+Comment[cs]=UI server zobrazující informace o průběhu
+Comment[csb]=Serwer wëdowiédzë ò pòkròkù procesë
+Comment[cy]=Gweinydd UI TDE i Ddangos Cynnydd
+Comment[da]=TDE's fremgangsinfo-UI-server
+Comment[de]=Ein UI-Server, der Fortschrittsinformationen darstellt
+Comment[el]=ΕξυπηÏετητής πληÏοφοÏιών Ï€Ïοόδου πεÏιβάλλοντος χÏήσης του TDE
+Comment[eo]=Progresinforma servo
+Comment[es]=Servidor UI de información de progreso de TDE
+Comment[et]=TDE edenemise info UI server
+Comment[eu]=TDEren aurrerapen-informazioen UI zerbitzaria
+Comment[fa]=اطلاعات پیشرÙت کارساز UI TDE
+Comment[fi]=TDE:n edistymispalkin käyttöliittymäpalvelin
+Comment[fr]=Serveur graphique d'infos de progression de TDE
+Comment[fy]=TDE's tsjinner foar ynformaasje oer de fuortgong
+Comment[gl]=Servidor UI de Información de Progreso de TDE
+Comment[he]=שרת ממשק מידע ההתקדמות של TDE
+Comment[hi]=केडीई का पà¥à¤°à¥‹à¤—à¥à¤°à¥‡à¤¸ जानकारी UI सरà¥à¤µà¤°
+Comment[hr]=TDEov Progess Info UI poslužitelj
+Comment[hu]=TDE folyamatinformációs kiszolgáló
+Comment[id]=Perkembangan TDE mengenai info server UI
+Comment[is]=Þjónn sem sýnir framvindu ferla
+Comment[it]=Server informazioni avanzamento di TDE
+Comment[ja]=TDE 進æ—情報 UI サーãƒ
+Comment[ka]=TDE-ს მáƒáƒœáƒáƒªáƒ”მთრგáƒáƒ“áƒáƒªáƒ”მის სერვერი
+Comment[kk]=TDE деректерді алу-беруді бақылау Ñервері
+Comment[km]=ម៉ាស៊ីន​បម្រើ UI នៃ​ពáŸážáŸŒáž˜áž¶áž“​វឌ្ážáž“ភាព​របស់ TDE
+Comment[ko]=TDEì—ì„œ 보다 ë°œì „ëœ ì •ë³´ UI 서버
+Comment[lb]=UI-Server vu TDE, dee Fortschrëttsinformatiounen uweist
+Comment[lt]=TDE eigos informacijos UI serveris
+Comment[lv]=TDE Progresa Info UI serveris
+Comment[mk]=TDE Ñервер за информации за прогреÑот
+Comment[mn]=ПрогреÑÑ Ð¼ÑдÑÑллÑÑÑ€ дүрÑлÑгдÑÑн Ñ…ÑÑ€ÑглÑгчийн харьцах Ñ…ÑÑгийн Ñервер
+Comment[ms]=Pelayan Info UI TDE
+Comment[mt]=Server tal-progress tal-UI TDE
+Comment[nb]=TDE UI-tjener for framgangsinfo
+Comment[nds]=Server för graafsche Vörankamen-Informatschonen
+Comment[ne]=TDE को पà¥à¤°à¤—ति सूचना UI सरà¥à¤­à¤°
+Comment[nl]=TDE's server voor informatie over de voortgang.
+Comment[nn]=TDE UI-tenar for framgangsinfo
+Comment[nso]=Seabi sa UI ya Tshedimoso ya Tswelopele ya TDE
+Comment[oc]=Servor d'informacion de progress TDE
+Comment[pa]=TDE ਦੀ ਤਰੱਕੀ ਜਾਣਕਾਰੀ UI ਸਰਵਰ
+Comment[pl]=Serwer informacji o postępie procesu
+Comment[pt]=Servidor de informações sobre o progresso das operações
+Comment[pt_BR]=Servidor de informação de progresso do TDE
+Comment[ro]=Server informaţii de progres TDE
+Comment[ru]=Сервер монитора передачи данных TDE
+Comment[rw]=Amakuru y'Aho bigeze ya TDE Seriveri UI
+Comment[se]=TDE:a ovdánandieđuid UI-bálvá
+Comment[sk]=TDE Progres Info UI server
+Comment[sl]=Strežnik TDE's Progress Info UI
+Comment[sq]=UI Shërbyesi për Informimin e Progresit të TDEs
+Comment[sr]=TDE-ов UI Ñервер информација о напретку
+Comment[sr@Latn]=TDE-ov UI server informacija o napretku
+Comment[sv]=TDE:s server för förloppsinformation
+Comment[ta]=கேடிஇயின௠மà¯à®©à¯à®©à¯‡à®±à¯à®± தகவல௠மà¯à®•à®ªà¯à®ªà¯à®ªà¯ சேவையகமà¯
+Comment[te]=కెడిఈ యొకà±à°• à°ªà±à°°à°—తి సమాచార యూఠసెరà±à°µà°°à±
+Comment[tg]=Инкишофи TDE's Info UI Сервер
+Comment[th]=เซิร์ฟเวอร์à¹à¸ªà¸”งข้อมูลความคืบหน้าของ TDE
+Comment[tr]=TDE'nin İlerleme Bilgisi arayüz sunucusu
+Comment[tt]=TDE'nıñ Alğakiteşne Küzätü servere
+Comment[uk]=Сервер графічного інтерфейÑу інформації про розвиток TDE
+Comment[uz]=TDE'ning maʼlumot uzatishni nazorat qilish serveri
+Comment[uz@cyrillic]=TDE'нинг маълумот узатишни назорат қилиш Ñервери
+Comment[ven]=UI siva ya mafhungo a mwelaphanda a TDE
+Comment[vi]=Trình phục vụ giao diện ngÆ°á»i dùng cho thông tin tiến hành của TDE.
+Comment[xh]=Umcedisi we UI Wenqubela Yenkcukacha we TDE
+Comment[zh_CN]=TDE 的进度信æ¯ç”¨æˆ·ç•Œé¢æœåŠ¡å™¨
+Comment[zh_HK]=TDE 的進度資訊介é¢ä¼ºæœç¨‹å¼
+Comment[zh_TW]=TDE 的進度資訊使用者介é¢ä¼ºæœå™¨
+Comment[zu]=Umlekeleli we-UI Yolwazi Lwenqubo lwe-TDE
+ServiceTypes=
+# It is a server
+X-DCOP-ServiceType=Unique
+X-TDE-StartupNotify=false
diff --git a/tdeio/misc/tdemailservice.cpp b/tdeio/misc/tdemailservice.cpp
new file mode 100644
index 000000000..3f9b04feb
--- /dev/null
+++ b/tdeio/misc/tdemailservice.cpp
@@ -0,0 +1,45 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Simon Hausmann <hausmann@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <kapplication.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+
+static const KCmdLineOptions options[] =
+{
+ { "+url", 0, 0 },
+ KCmdLineLastOption
+};
+
+int main( int argc, char **argv )
+{
+ KLocale::setMainCatalogue("tdelibs");
+ TDECmdLineArgs::init( argc, argv, "tdemailservice", I18N_NOOP("KMailService"), I18N_NOOP("Mail service"), "unknown" );
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDEApplication a( false, false );
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ if ( args->count() != 1 )
+ return 1;
+
+ a.invokeMailer(KURL(args->arg(0)), a.startupId(), true);
+
+ return 0;
+}
diff --git a/tdeio/misc/tdemailservice.protocol b/tdeio/misc/tdemailservice.protocol
new file mode 100644
index 000000000..240c76aca
--- /dev/null
+++ b/tdeio/misc/tdemailservice.protocol
@@ -0,0 +1,15 @@
+[Protocol]
+exec=tdemailservice %u
+protocol=mailto
+input=none
+output=none
+helper=true
+listing=
+reading=false
+writing=false
+makedir=false
+deleting=false
+DocPath=tdeioslave/mailto.html
+Icon=mail_new
+Class=:internet
+URIMode=mailto
diff --git a/tdeio/misc/tdentlm/CMakeLists.txt b/tdeio/misc/tdentlm/CMakeLists.txt
new file mode 100644
index 000000000..dc26da9a1
--- /dev/null
+++ b/tdeio/misc/tdentlm/CMakeLists.txt
@@ -0,0 +1,43 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/tdecore
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### headers ###################################
+
+install(FILES tdentlm.h DESTINATION ${INCLUDE_INSTALL_DIR}/tdeio )
+
+
+##### tdentlm ###################################
+
+set( target tdentlm )
+
+set( ${target}_SRCS
+ tdentlm.cpp des.cpp
+)
+
+tde_add_library( ${target} SHARED
+ SOURCES ${${target}_SRCS}
+ VERSION 0.0.0
+ LINK tdecore-shared
+ DESTINATION ${LIB_INSTALL_DIR}
+)
diff --git a/tdeio/misc/tdentlm/Makefile.am b/tdeio/misc/tdentlm/Makefile.am
new file mode 100644
index 000000000..16164dbe3
--- /dev/null
+++ b/tdeio/misc/tdentlm/Makefile.am
@@ -0,0 +1,12 @@
+INCLUDES=$(all_includes)
+
+lib_LTLIBRARIES = libtdentlm.la
+METASOURCES = AUTO
+
+tdentlmincludedir = $(includedir)/tdeio
+tdentlminclude_HEADERS = tdentlm.h
+
+libtdentlm_la_SOURCES = tdentlm.cpp des.cpp
+libtdentlm_la_LDFLAGS = $(all_libraries) -version-info 0:0:0 -no-undefined
+libtdentlm_la_LIBADD = $(LIB_TDECORE) $(LIB_QT)
+
diff --git a/kio/misc/tdentlm/des.cpp b/tdeio/misc/tdentlm/des.cpp
index bb4fab88b..bb4fab88b 100644
--- a/kio/misc/tdentlm/des.cpp
+++ b/tdeio/misc/tdentlm/des.cpp
diff --git a/kio/misc/tdentlm/des.h b/tdeio/misc/tdentlm/des.h
index 0f6f59dc9..0f6f59dc9 100644
--- a/kio/misc/tdentlm/des.h
+++ b/tdeio/misc/tdentlm/des.h
diff --git a/kio/misc/tdentlm/kswap.h b/tdeio/misc/tdentlm/kswap.h
index 9eca243de..9eca243de 100644
--- a/kio/misc/tdentlm/kswap.h
+++ b/tdeio/misc/tdentlm/kswap.h
diff --git a/kio/misc/tdentlm/tdentlm.cpp b/tdeio/misc/tdentlm/tdentlm.cpp
index 2ef5d1cb6..2ef5d1cb6 100644
--- a/kio/misc/tdentlm/tdentlm.cpp
+++ b/tdeio/misc/tdentlm/tdentlm.cpp
diff --git a/kio/misc/tdentlm/tdentlm.h b/tdeio/misc/tdentlm/tdentlm.h
index 06b8febab..06b8febab 100644
--- a/kio/misc/tdentlm/tdentlm.h
+++ b/tdeio/misc/tdentlm/tdentlm.h
diff --git a/tdeio/misc/tdesasl/CMakeLists.txt b/tdeio/misc/tdesasl/CMakeLists.txt
new file mode 100644
index 000000000..d48322d93
--- /dev/null
+++ b/tdeio/misc/tdesasl/CMakeLists.txt
@@ -0,0 +1,42 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### headers ###################################
+
+install(FILES tdesasl.h DESTINATION ${INCLUDE_INSTALL_DIR}/tdeio )
+
+
+##### tdesasl ###################################
+
+set( target tdesasl )
+
+set( ${target}_SRCS
+ tdesasl.cpp
+)
+
+tde_add_library( ${target} SHARED
+ SOURCES ${${target}_SRCS}
+ VERSION 1.2.0
+ LINK tdecore-shared
+ DESTINATION ${LIB_INSTALL_DIR}
+)
diff --git a/tdeio/misc/tdesasl/Makefile.am b/tdeio/misc/tdesasl/Makefile.am
new file mode 100644
index 000000000..4ebde7e8d
--- /dev/null
+++ b/tdeio/misc/tdesasl/Makefile.am
@@ -0,0 +1,12 @@
+INCLUDES=$(all_includes)
+
+lib_LTLIBRARIES = libtdesasl.la
+METASOURCES = AUTO
+
+tdesaslincludedir = $(includedir)/tdeio
+tdesaslinclude_HEADERS = tdesasl.h
+
+libtdesasl_la_SOURCES = tdesasl.cpp
+libtdesasl_la_LDFLAGS = $(all_libraries) -version-info 3:0:2 -no-undefined
+libtdesasl_la_LIBADD = $(LIB_TDECORE) $(LIB_QT)
+
diff --git a/kio/misc/tdesasl/tdesasl.cpp b/tdeio/misc/tdesasl/tdesasl.cpp
index ef0768f98..ef0768f98 100644
--- a/kio/misc/tdesasl/tdesasl.cpp
+++ b/tdeio/misc/tdesasl/tdesasl.cpp
diff --git a/kio/misc/tdesasl/tdesasl.h b/tdeio/misc/tdesasl/tdesasl.h
index 0c57096a8..0c57096a8 100644
--- a/kio/misc/tdesasl/tdesasl.h
+++ b/tdeio/misc/tdesasl/tdesasl.h
diff --git a/tdeio/misc/tdesendbugmail/CMakeLists.txt b/tdeio/misc/tdesendbugmail/CMakeLists.txt
new file mode 100644
index 000000000..3dffadb22
--- /dev/null
+++ b/tdeio/misc/tdesendbugmail/CMakeLists.txt
@@ -0,0 +1,37 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### tdesendbugmail ##############################
+
+set( target tdesendbugmail )
+
+set( ${target}_SRCS
+ main.cpp smtp.cpp
+)
+
+tde_add_executable( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${BIN_INSTALL_DIR}
+)
diff --git a/tdeio/misc/tdesendbugmail/Makefile.am b/tdeio/misc/tdesendbugmail/Makefile.am
new file mode 100644
index 000000000..f9087a4fe
--- /dev/null
+++ b/tdeio/misc/tdesendbugmail/Makefile.am
@@ -0,0 +1,26 @@
+# This file is part of the KDE libraries
+# Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+bin_PROGRAMS = tdesendbugmail
+INCLUDES= -I$(srcdir)/.. $(all_includes)
+
+tdesendbugmail_SOURCES = main.cpp smtp.cpp
+tdesendbugmail_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+tdesendbugmail_LDADD = ../../libtdeio.la
+
+METASOURCES = AUTO
diff --git a/tdeio/misc/tdesendbugmail/main.cpp b/tdeio/misc/tdesendbugmail/main.cpp
new file mode 100644
index 000000000..162e6ad5c
--- /dev/null
+++ b/tdeio/misc/tdesendbugmail/main.cpp
@@ -0,0 +1,142 @@
+// $Id$
+
+#include <sys/types.h>
+#include "main.h"
+#include <pwd.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <tqtextstream.h>
+
+#include <kapplication.h>
+#include <kemailsettings.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+#include <kaboutdata.h>
+#include <kdebug.h>
+#include <tdeconfig.h>
+
+#include "smtp.h"
+
+static KCmdLineOptions options[] = {
+ { "subject <argument>", I18N_NOOP("Subject line"), 0 },
+ { "recipient <argument>", I18N_NOOP("Recipient"), "submit@bugs.kde.org" },
+ KCmdLineLastOption
+};
+
+void BugMailer::slotError(int errornum) {
+ kdDebug() << "slotError\n";
+ TQString str, lstr;
+
+ switch(errornum) {
+ case SMTP::CONNECTERROR:
+ lstr = i18n("Error connecting to server.");
+ break;
+ case SMTP::NOTCONNECTED:
+ lstr = i18n("Not connected.");
+ break;
+ case SMTP::CONNECTTIMEOUT:
+ lstr = i18n("Connection timed out.");
+ break;
+ case SMTP::INTERACTTIMEOUT:
+ lstr = i18n("Time out waiting for server interaction.");
+ break;
+ default:
+ lstr = sm->getLastLine().stripWhiteSpace();
+ lstr = i18n("Server said: \"%1\"").arg(lstr);
+ }
+ fputs(lstr.utf8().data(), stdout);
+ fflush(stdout);
+
+ ::exit(1);
+}
+
+void BugMailer::slotSend() {
+ kdDebug() << "slotSend\n";
+ ::exit(0);
+}
+
+int main(int argc, char **argv) {
+
+ KLocale::setMainCatalogue("tdelibs");
+ TDEAboutData d("tdesendbugmail", I18N_NOOP("KSendBugMail"), "1.0",
+ I18N_NOOP("Sends a short bug report to submit@bugs.kde.org"),
+ TDEAboutData::License_GPL, "(c) 2000 Stephan Kulow");
+ d.addAuthor("Stephan Kulow", I18N_NOOP("Author"), "coolo@kde.org");
+
+ TDECmdLineArgs::init(argc, argv, &d);
+ TDECmdLineArgs::addCmdLineOptions(options);
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ TDEApplication a(false, false);
+
+ TQCString recipient = args->getOption("recipient");
+ if (recipient.isEmpty())
+ recipient = "submit@bugs.kde.org";
+ else {
+ if (recipient.at(0) == '\'') {
+ recipient = recipient.mid(1).left(recipient.length() - 2);
+ }
+ }
+ kdDebug() << "recp \"" << recipient << "\"\n";
+
+ TQCString subject = args->getOption("subject");
+ if (subject.isEmpty())
+ subject = "(no subject)";
+ else {
+ if (subject.at(0) == '\'')
+ subject = subject.mid(1).left(subject.length() - 2);
+ }
+ TQTextIStream input(stdin);
+ TQString text, line;
+ while (!input.eof()) {
+ line = input.readLine();
+ text += line + "\r\n";
+ }
+ kdDebug() << text << endl;
+
+ KEMailSettings emailConfig;
+ emailConfig.setProfile(emailConfig.defaultProfileName());
+ TQString fromaddr = emailConfig.getSetting(KEMailSettings::EmailAddress);
+ if (!fromaddr.isEmpty()) {
+ TQString name = emailConfig.getSetting(KEMailSettings::RealName);
+ if (!name.isEmpty())
+ fromaddr = name + TQString::fromLatin1(" <") + fromaddr + TQString::fromLatin1(">");
+ } else {
+ struct passwd *p;
+ p = getpwuid(getuid());
+ fromaddr = TQString::fromLatin1(p->pw_name);
+ fromaddr += "@";
+ char buffer[256];
+ buffer[0] = '\0';
+ if(!gethostname(buffer, sizeof(buffer)))
+ buffer[sizeof(buffer)-1] = '\0';
+ fromaddr += buffer;
+ }
+ kdDebug() << "fromaddr \"" << fromaddr << "\"" << endl;
+
+ TQString server = emailConfig.getSetting(KEMailSettings::OutServer);
+ if (server.isEmpty())
+ server=TQString::fromLatin1("bugs.kde.org");
+
+ SMTP *sm = new SMTP;
+ BugMailer bm(sm);
+
+ TQObject::connect(sm, TQT_SIGNAL(messageSent()), &bm, TQT_SLOT(slotSend()));
+ TQObject::connect(sm, TQT_SIGNAL(error(int)), &bm, TQT_SLOT(slotError(int)));
+ sm->setServerHost(server);
+ sm->setPort(25);
+ sm->setSenderAddress(fromaddr);
+ sm->setRecipientAddress(recipient);
+ sm->setMessageSubject(subject);
+ sm->setMessageHeader(TQString::fromLatin1("From: %1\r\nTo: %2\r\n").arg(fromaddr).arg(recipient.data()));
+ sm->setMessageBody(text);
+ sm->sendMessage();
+
+ int r = a.exec();
+ kdDebug() << "execing " << r << endl;
+ delete sm;
+ return r;
+}
+
+#include "main.moc"
diff --git a/kio/misc/ksendbugmail/main.h b/tdeio/misc/tdesendbugmail/main.h
index 39d424bef..39d424bef 100644
--- a/kio/misc/ksendbugmail/main.h
+++ b/tdeio/misc/tdesendbugmail/main.h
diff --git a/kio/misc/ksendbugmail/smtp.cpp b/tdeio/misc/tdesendbugmail/smtp.cpp
index d282782fc..d282782fc 100644
--- a/kio/misc/ksendbugmail/smtp.cpp
+++ b/tdeio/misc/tdesendbugmail/smtp.cpp
diff --git a/kio/misc/ksendbugmail/smtp.h b/tdeio/misc/tdesendbugmail/smtp.h
index acdb4a3c3..acdb4a3c3 100644
--- a/kio/misc/ksendbugmail/smtp.h
+++ b/tdeio/misc/tdesendbugmail/smtp.h
diff --git a/tdeio/misc/tdetelnetservice.cpp b/tdeio/misc/tdetelnetservice.cpp
new file mode 100644
index 000000000..655a5b32a
--- /dev/null
+++ b/tdeio/misc/tdetelnetservice.cpp
@@ -0,0 +1,112 @@
+/*
+ Copyright (c) 2001 Malte Starostik <malte@kde.org>
+ based on tdemailservice.cpp,
+ Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
+
+ 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; see the file COPYING. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#include <kapplication.h>
+#include <kmessagebox.h>
+#include <kcmdlineargs.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kprocess.h>
+#include <ksimpleconfig.h>
+
+static const KCmdLineOptions options[] =
+{
+ {"+url", 0, 0},
+ KCmdLineLastOption
+};
+
+int main(int argc, char **argv)
+{
+ KLocale::setMainCatalogue("tdelibs");
+ TDECmdLineArgs::init(argc, argv, "tdetelnetservice", I18N_NOOP("telnet service"),
+ I18N_NOOP("telnet protocol handler"), "unknown");
+ TDECmdLineArgs::addCmdLineOptions(options);
+
+ TDEApplication app;
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ if (args->count() != 1)
+ return 1;
+
+ TDEConfig *config = new TDEConfig("kdeglobals", true);
+ config->setGroup("General");
+ TQString terminal = config->readPathEntry("TerminalApplication", "konsole");
+
+ KURL url(args->arg(0));
+ TQStringList cmd;
+ if (terminal == "konsole")
+ cmd << "--noclose";
+
+ cmd << "-e";
+ if ( url.protocol() == "telnet" )
+ cmd << "telnet";
+ else if ( url.protocol() == "ssh" )
+ cmd << "ssh";
+ else if ( url.protocol() == "rlogin" )
+ cmd << "rlogin";
+ else {
+ kdError() << "Invalid protocol " << url.protocol() << endl;
+ return 2;
+ }
+
+ if (!app.authorize("shell_access"))
+ {
+ KMessageBox::sorry(0,
+ i18n("You do not have permission to access the %1 protocol.").arg(url.protocol()));
+ return 3;
+ }
+
+ if (!url.user().isEmpty())
+ {
+ cmd << "-l";
+ cmd << url.user();
+ }
+
+ TQString host;
+ if (!url.host().isEmpty())
+ host = url.host(); // telnet://host
+ else if (!url.path().isEmpty())
+ host = url.path(); // telnet:host
+
+ if (host.isEmpty() || host.startsWith("-"))
+ {
+ kdError() << "Invalid hostname " << host << endl;
+ return 2;
+ }
+
+ cmd << host;
+
+ if (url.port()){
+ if ( url.protocol() == "ssh" )
+ cmd << "-p" << TQString::number(url.port());
+ else
+ cmd << TQString::number(url.port());
+ }
+
+ app.tdeinitExec(terminal, cmd);
+
+ return 0;
+}
+
+// vim: ts=4 sw=4 noet
diff --git a/tdeio/misc/tdewalletd/CMakeLists.txt b/tdeio/misc/tdewalletd/CMakeLists.txt
new file mode 100644
index 000000000..2d0d2ef28
--- /dev/null
+++ b/tdeio/misc/tdewalletd/CMakeLists.txt
@@ -0,0 +1,49 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdewallet/client
+ ${CMAKE_SOURCE_DIR}/tdewallet/backend
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install(FILES tdewalletd.desktop DESTINATION ${SERVICES_INSTALL_DIR}/kded )
+
+
+#### kded_tdewalletd ##############################
+
+set( target kded_tdewalletd )
+
+set( ${target}_SRCS
+ tdewalletd.cpp tdewalletd.skel ktimeout.cpp tdewalletwizard.ui
+ kbetterthankdialogbase.ui
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeinit_kded-shared tdewalletbackend-shared
+ DEPENDENCIES dcopidl
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/kio/misc/tdewalletd/Makefile.am b/tdeio/misc/tdewalletd/Makefile.am
index 5d52fa810..5d52fa810 100644
--- a/kio/misc/tdewalletd/Makefile.am
+++ b/tdeio/misc/tdewalletd/Makefile.am
diff --git a/kio/misc/tdewalletd/kbetterthankdialogbase.ui b/tdeio/misc/tdewalletd/kbetterthankdialogbase.ui
index a02d5def7..a02d5def7 100644
--- a/kio/misc/tdewalletd/kbetterthankdialogbase.ui
+++ b/tdeio/misc/tdewalletd/kbetterthankdialogbase.ui
diff --git a/kio/misc/tdewalletd/kbetterthankdialogbase.ui.h b/tdeio/misc/tdewalletd/kbetterthankdialogbase.ui.h
index 2b3e16b0d..2b3e16b0d 100644
--- a/kio/misc/tdewalletd/kbetterthankdialogbase.ui.h
+++ b/tdeio/misc/tdewalletd/kbetterthankdialogbase.ui.h
diff --git a/kio/misc/tdewalletd/ktimeout.cpp b/tdeio/misc/tdewalletd/ktimeout.cpp
index c431ecf69..c431ecf69 100644
--- a/kio/misc/tdewalletd/ktimeout.cpp
+++ b/tdeio/misc/tdewalletd/ktimeout.cpp
diff --git a/kio/misc/tdewalletd/ktimeout.h b/tdeio/misc/tdewalletd/ktimeout.h
index 441e4ed77..441e4ed77 100644
--- a/kio/misc/tdewalletd/ktimeout.h
+++ b/tdeio/misc/tdewalletd/ktimeout.h
diff --git a/tdeio/misc/tdewalletd/tdewalletd.cpp b/tdeio/misc/tdewalletd/tdewalletd.cpp
new file mode 100644
index 000000000..a8b3ade1a
--- /dev/null
+++ b/tdeio/misc/tdewalletd/tdewalletd.cpp
@@ -0,0 +1,1514 @@
+/*
+ This file is part of the KDE libraries
+
+ Copyright (c) 2002-2004 George Staikos <staikos@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+*/
+
+#include "kbetterthankdialogbase.h"
+#include "tdewalletwizard.h"
+#include "tdewalletd.h"
+#include "ktimeout.h"
+
+#include <dcopclient.h>
+#include <dcopref.h>
+#include <kactivelabel.h>
+#include <kapplication.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <kdirwatch.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kpassdlg.h>
+#include <kstandarddirs.h>
+#include <tdewalletentry.h>
+#include <twin.h>
+
+#include <tqdir.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqpushbutton.h>
+#include <tqregexp.h>
+#include <tqstylesheet.h>
+#include <tqvbox.h>
+
+#include <assert.h>
+
+extern "C" {
+ KDE_EXPORT KDEDModule *create_tdewalletd(const TQCString &name) {
+ return new KWalletD(name);
+ }
+}
+
+
+class KWalletTransaction {
+ public:
+ KWalletTransaction() {
+ tType = Unknown;
+ transaction = 0L;
+ client = 0L;
+ modal = false;
+ }
+
+ ~KWalletTransaction() {
+ // Don't delete these!
+ transaction = 0L;
+ client = 0L;
+ }
+
+ enum Type { Unknown, Open, ChangePassword, OpenFail };
+ DCOPClient *client;
+ DCOPClientTransaction *transaction;
+ Type tType;
+ TQCString rawappid, returnObject;
+ TQCString appid;
+ uint wId;
+ TQString wallet;
+ bool modal;
+};
+
+
+KWalletD::KWalletD(const TQCString &name)
+: KDEDModule(name), _failed(0) {
+ srand(time(0));
+ _showingFailureNotify = false;
+ _transactions.setAutoDelete(true);
+ _timeouts = new KTimeout(17);
+ _closeIdle = false;
+ _idleTime = 0;
+ connect(_timeouts, TQT_SIGNAL(timedOut(int)), this, TQT_SLOT(timedOut(int)));
+ reconfigure();
+ TDEGlobal::dirs()->addResourceType("tdewallet", "share/apps/tdewallet");
+ connect(TDEApplication::dcopClient(),
+ TQT_SIGNAL(applicationRemoved(const TQCString&)),
+ this,
+ TQT_SLOT(slotAppUnregistered(const TQCString&)));
+ _dw = new KDirWatch(this, "KWallet Directory Watcher");
+ _dw->addDir(TDEGlobal::dirs()->saveLocation("tdewallet"));
+ _dw->startScan(true);
+ connect(_dw, TQT_SIGNAL(dirty(const TQString&)), this, TQT_SLOT(emitWalletListDirty()));
+}
+
+
+KWalletD::~KWalletD() {
+ delete _timeouts;
+ _timeouts = 0;
+
+ closeAllWallets();
+ _transactions.clear();
+}
+
+
+int KWalletD::generateHandle() {
+ int rc;
+
+ // ASSUMPTION: RAND_MAX is fairly large.
+ do {
+ rc = rand();
+ } while (_wallets.find(rc) || rc == 0);
+
+ return rc;
+}
+
+
+void KWalletD::processTransactions() {
+ static bool processing = false;
+
+ if (processing) {
+ return;
+ }
+
+ processing = true;
+
+ // Process remaining transactions
+ KWalletTransaction *xact;
+ while (!_transactions.isEmpty()) {
+ xact = _transactions.first();
+ TQCString replyType;
+ int res;
+
+ assert(xact->tType != KWalletTransaction::Unknown);
+
+ switch (xact->tType) {
+ case KWalletTransaction::Open:
+ res = doTransactionOpen(xact->appid, xact->wallet, xact->wId, xact->modal);
+ replyType = "int";
+ if (!xact->returnObject.isEmpty()) {
+ DCOPRef(xact->rawappid, xact->returnObject).send("walletOpenResult", res);
+ }
+
+ // multiple requests from the same client
+ // should not produce multiple password
+ // dialogs on a failure
+ if (res < 0) {
+ TQPtrListIterator<KWalletTransaction> it(_transactions);
+ KWalletTransaction *x;
+ while ((x = it.current()) && x != xact) {
+ ++it;
+ }
+ if (x) {
+ ++it;
+ }
+ while ((x = it.current())) {
+ if (xact->appid == x->appid && x->tType == KWalletTransaction::Open && x->wallet == xact->wallet && x->wId == xact->wId) {
+ x->tType = KWalletTransaction::OpenFail;
+ }
+ ++it;
+ }
+ }
+ break;
+ case KWalletTransaction::OpenFail:
+ res = -1;
+ replyType = "int";
+ if (!xact->returnObject.isEmpty()) {
+ DCOPRef(xact->rawappid, xact->returnObject).send("walletOpenResult", res);
+ }
+ break;
+ case KWalletTransaction::ChangePassword:
+ doTransactionChangePassword(xact->appid, xact->wallet, xact->wId);
+ // fall through - no return
+ default:
+ _transactions.removeRef(xact);
+ continue;
+ }
+
+ if (xact->returnObject.isEmpty() && xact->tType != KWalletTransaction::ChangePassword) {
+ TQByteArray replyData;
+ TQDataStream stream(replyData, IO_WriteOnly);
+ stream << res;
+ xact->client->endTransaction(xact->transaction, replyType, replyData);
+ }
+ _transactions.removeRef(xact);
+ }
+
+ processing = false;
+}
+
+
+void KWalletD::openAsynchronous(const TQString& wallet, const TQCString& returnObject, uint wId) {
+ DCOPClient *dc = callingDcopClient();
+ if (!dc) {
+ return;
+ }
+
+ TQCString appid = dc->senderId();
+ if (!_enabled ||
+ !TQRegExp("^[A-Za-z0-9]+[A-Za-z0-9\\s\\-_]*$").exactMatch(wallet)) {
+ DCOPRef(appid, returnObject).send("walletOpenResult", -1);
+ return;
+ }
+
+ TQCString peerName = friendlyDCOPPeerName();
+
+ KWalletTransaction *xact = new KWalletTransaction;
+
+ xact->appid = peerName;
+ xact->rawappid = appid;
+ xact->client = callingDcopClient();
+ xact->wallet = wallet;
+ xact->wId = wId;
+ xact->tType = KWalletTransaction::Open;
+ xact->returnObject = returnObject;
+ _transactions.append(xact);
+
+ DCOPRef(appid, returnObject).send("walletOpenResult", 0);
+
+ TQTimer::singleShot(0, this, TQT_SLOT(processTransactions()));
+ checkActiveDialog();
+}
+
+
+int KWalletD::openPath(const TQString& path, uint wId) {
+ if (!_enabled) { // guard
+ return -1;
+ }
+
+ // FIXME: setup transaction
+ int rc = internalOpen(friendlyDCOPPeerName(), path, true, wId);
+ return rc;
+}
+
+
+int KWalletD::open(const TQString& wallet, uint wId) {
+ if (!_enabled) { // guard
+ return -1;
+ }
+
+ if (!TQRegExp("^[A-Za-z0-9]+[A-Za-z0-9\\s\\-_]*$").exactMatch(wallet)) {
+ return -1;
+ }
+
+ TQCString appid = friendlyDCOPPeerName();
+
+ KWalletTransaction *xact = new KWalletTransaction;
+ _transactions.append(xact);
+
+ xact->appid = appid;
+ xact->client = callingDcopClient();
+ xact->transaction = xact->client->beginTransaction();
+ xact->wallet = wallet;
+ xact->wId = wId;
+ xact->tType = KWalletTransaction::Open;
+ xact->modal = true; // mark dialogs as modal, the app has blocking wait
+ TQTimer::singleShot(0, this, TQT_SLOT(processTransactions()));
+ checkActiveDialog();
+ return 0; // process later
+}
+
+
+// Sets up a dialog that will be shown by tdewallet.
+void KWalletD::setupDialog( TQWidget* dialog, WId wId, const TQCString& appid, bool modal ) {
+ if( wId != 0 )
+ KWin::setMainWindow( dialog, wId ); // correct, set dialog parent
+ else {
+ if( appid.isEmpty())
+ kdWarning() << "Using tdewallet without parent window!" << endl;
+ else
+ kdWarning() << "Application '" << appid << "' using tdewallet without parent window!" << endl;
+ // allow dialog activation even if it interrupts, better than trying hacks
+ // with keeping the dialog on top or on all desktops
+ kapp->updateUserTimestamp();
+ }
+ if( modal )
+ KWin::setState( dialog->winId(), NET::Modal );
+ else
+ KWin::clearState( dialog->winId(), NET::Modal );
+ activeDialog = dialog;
+}
+
+// If there's a dialog already open and another application tries some operation that'd lead to
+// opening a dialog, that application will be blocked by this dialog. A proper solution would
+// be to set the second application's window also as a parent for the active dialog, so that
+// KWin properly handles focus changes and so on, but there's currently no support for multiple
+// dialog parents. Hopefully to be done in KDE4, for now just use all kinds of bad hacks to make
+// sure the user doesn't overlook the active dialog.
+void KWalletD::checkActiveDialog() {
+ if( !activeDialog || !activeDialog->isShown())
+ return;
+ kapp->updateUserTimestamp();
+ KWin::setState( activeDialog->winId(), NET::KeepAbove );
+ KWin::setOnAllDesktops( activeDialog->winId(), true );
+ KWin::forceActiveWindow( activeDialog->winId());
+}
+
+int KWalletD::doTransactionOpen(const TQCString& appid, const TQString& wallet, uint wId, bool modal) {
+ if (_firstUse && !wallets().contains(KWallet::Wallet::LocalWallet())) {
+ // First use wizard
+ KWalletWizard *wiz = new KWalletWizard(0);
+ setupDialog( wiz, wId, appid, modal );
+ int rc = wiz->exec();
+ if (rc == TQDialog::Accepted) {
+ TDEConfig cfg("tdewalletrc");
+ cfg.setGroup("Wallet");
+ cfg.writeEntry("First Use", false);
+ cfg.writeEntry("Enabled", wiz->_useWallet->isChecked());
+ cfg.writeEntry("Close When Idle", wiz->_closeIdle->isChecked());
+ cfg.writeEntry("Use One Wallet", !wiz->_networkWallet->isChecked());
+ cfg.sync();
+ reconfigure();
+
+ if (!wiz->_useWallet->isChecked()) {
+ delete wiz;
+ return -1;
+ }
+
+ // Create the wallet
+ KWallet::Backend *b = new KWallet::Backend(KWallet::Wallet::LocalWallet());
+ TQByteArray p;
+ p.duplicate(wiz->_pass1->text().utf8(), wiz->_pass1->text().length());
+ b->open(p);
+ b->createFolder(KWallet::Wallet::PasswordFolder());
+ b->createFolder(KWallet::Wallet::FormDataFolder());
+ b->close(p);
+ p.fill(0);
+ delete b;
+ delete wiz;
+ } else {
+ delete wiz;
+ return -1;
+ }
+ } else if (_firstUse) {
+ TDEConfig cfg("tdewalletrc");
+ _firstUse = false;
+ cfg.setGroup("Wallet");
+ cfg.writeEntry("First Use", false);
+ cfg.sync();
+ }
+
+ int rc = internalOpen(appid, wallet, false, wId, modal);
+ return rc;
+}
+
+int KWalletD::tryOpen(const TQString& wallet, const TQCString& password)
+{
+ if (isOpen(wallet))
+ return 0;
+
+ if (_tryOpenBlocked.isActive()) {
+ kdDebug() << "tryOpen is active.." << endl;
+ return -1;
+ }
+
+ if (!KWallet::Backend::exists(wallet))
+ return -2;
+
+ KWallet::Backend *b = new KWallet::Backend(wallet, false /*isPath*/);
+ int rc = b->open(TQByteArray().duplicate(password, strlen(password)));
+ if (rc == 0) {
+ _wallets.insert(rc = generateHandle(), b);
+ _passwords[wallet] = password;
+ b->ref();
+ _tryOpenBlocked.stop();
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << wallet;
+ emitDCOPSignal("walletOpened(TQString)", data);
+ }
+ else {
+ delete b;
+ // make sure that we're not bombed with a dictionary attack
+ _tryOpenBlocked.start (30 * 1000, true /*single shot*/);
+ if (++_failed > 5) {
+ _failed = 0;
+ TQTimer::singleShot(0, this, TQT_SLOT(notifyFailures()));
+ }
+
+ rc = -1;
+ }
+ return rc;
+}
+
+int KWalletD::internalOpen(const TQCString& appid, const TQString& wallet, bool isPath, WId w, bool modal) {
+ int rc = -1;
+ bool brandNew = false;
+
+ TQCString thisApp;
+ if (appid.isEmpty()) {
+ thisApp = "TDE System";
+ } else {
+ thisApp = appid;
+ }
+
+ if (implicitDeny(wallet, thisApp)) {
+ return -1;
+ }
+
+ for (TQIntDictIterator<KWallet::Backend> i(_wallets); i.current(); ++i) {
+ if (i.current()->walletName() == wallet) {
+ rc = i.currentKey();
+ break;
+ }
+ }
+
+ if (rc == -1) {
+ if (_wallets.count() > 20) {
+ kdDebug() << "Too many wallets open." << endl;
+ return -1;
+ }
+
+ KWallet::Backend *b = new KWallet::Backend(wallet, isPath);
+ KPasswordDialog *kpd = 0L;
+ bool emptyPass = false;
+ if ((isPath && TQFile::exists(wallet)) || (!isPath && KWallet::Backend::exists(wallet))) {
+ int pwless = b->open(TQByteArray());
+ if (0 != pwless || !b->isOpen()) {
+ if (pwless == 0) {
+ // release, start anew
+ delete b;
+ b = new KWallet::Backend(wallet, isPath);
+ }
+ kpd = new KPasswordDialog(KPasswordDialog::Password, false, 0);
+ if (appid.isEmpty()) {
+ kpd->setPrompt(i18n("<qt>TDE has requested to open the wallet '<b>%1</b>'. Please enter the password for this wallet below.").arg(TQStyleSheet::escape(wallet)));
+ } else {
+ kpd->setPrompt(i18n("<qt>The application '<b>%1</b>' has requested to open the wallet '<b>%2</b>'. Please enter the password for this wallet below.").arg(TQStyleSheet::escape(appid)).arg(TQStyleSheet::escape(wallet)));
+ }
+ brandNew = false;
+ kpd->setButtonOK(KGuiItem(i18n("&Open"),"fileopen"));
+ } else {
+ emptyPass = true;
+ }
+ } else if (wallet == KWallet::Wallet::LocalWallet() ||
+ wallet == KWallet::Wallet::NetworkWallet()) {
+ // Auto create these wallets.
+ kpd = new KPasswordDialog(KPasswordDialog::NewPassword, false, 0);
+ if (appid.isEmpty()) {
+ kpd->setPrompt(i18n("TDE has requested to open the wallet. This is used to store sensitive data in a secure fashion. Please enter a password to use with this wallet or click cancel to deny the application's request."));
+ } else {
+ kpd->setPrompt(i18n("<qt>The application '<b>%1</b>' has requested to open the TDE wallet. This is used to store sensitive data in a secure fashion. Please enter a password to use with this wallet or click cancel to deny the application's request.").arg(TQStyleSheet::escape(appid)));
+ }
+ brandNew = true;
+ kpd->setButtonOK(KGuiItem(i18n("&Open"),"fileopen"));
+ } else {
+ kpd = new KPasswordDialog(KPasswordDialog::NewPassword, false, 0);
+ if (appid.length() == 0) {
+ kpd->setPrompt(i18n("<qt>TDE has requested to create a new wallet named '<b>%1</b>'. Please choose a password for this wallet, or cancel to deny the application's request.").arg(TQStyleSheet::escape(wallet)));
+ } else {
+ kpd->setPrompt(i18n("<qt>The application '<b>%1</b>' has requested to create a new wallet named '<b>%2</b>'. Please choose a password for this wallet, or cancel to deny the application's request.").arg(TQStyleSheet::escape(appid)).arg(TQStyleSheet::escape(wallet)));
+ }
+ brandNew = true;
+ kpd->setButtonOK(KGuiItem(i18n("C&reate"),"filenew"));
+ }
+
+ if (kpd) {
+ kpd->setCaption(i18n("TDE Wallet Service"));
+ kpd->setAllowEmptyPasswords(true);
+ }
+
+ const char *p = 0L;
+ while (!b->isOpen()) {
+ assert(kpd); // kpd can't be null if isOpen() is false
+ setupDialog( kpd, w, appid, modal );
+ if (kpd->exec() == KDialog::Accepted) {
+ p = kpd->password();
+ int rc = b->open(TQByteArray().duplicate(p, strlen(p)));
+ if (!b->isOpen()) {
+ kpd->setPrompt(i18n("<qt>Error opening the wallet '<b>%1</b>'. Please try again.<br>(Error code %2: %3)").arg(TQStyleSheet::escape(wallet)).arg(rc).arg(KWallet::Backend::openRCToString(rc)));
+ kpd->clearPassword();
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (!emptyPass && (!p || !b->isOpen())) {
+ delete b;
+ delete kpd;
+ return -1;
+ }
+
+ if (emptyPass && _openPrompt && !isAuthorizedApp(appid, wallet, w)) {
+ delete b;
+ delete kpd;
+ return -1;
+ }
+
+ _wallets.insert(rc = generateHandle(), b);
+ if (emptyPass) {
+ _passwords[wallet] = "";
+ } else {
+ _passwords[wallet] = p;
+ }
+ _handles[appid].append(rc);
+
+ delete kpd; // don't refactor this!! Argh I hate KPassDlg
+
+ if (brandNew) {
+ createFolder(rc, KWallet::Wallet::PasswordFolder());
+ createFolder(rc, KWallet::Wallet::FormDataFolder());
+ }
+
+ b->ref();
+ if (_closeIdle && _timeouts) {
+ _timeouts->addTimer(rc, _idleTime);
+ }
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << wallet;
+ if (brandNew) {
+ emitDCOPSignal("walletCreated(TQString)", data);
+ }
+ emitDCOPSignal("walletOpened(TQString)", data);
+ if (_wallets.count() == 1 && _launchManager) {
+ TDEApplication::startServiceByDesktopName("tdewalletmanager-tdewalletd");
+ }
+ } else {
+ if (!_handles[appid].contains(rc) && _openPrompt && !isAuthorizedApp(appid, wallet, w)) {
+ return -1;
+ }
+ _handles[appid].append(rc);
+ _wallets.find(rc)->ref();
+ }
+
+ return rc;
+}
+
+
+bool KWalletD::isAuthorizedApp(const TQCString& appid, const TQString& wallet, WId w) {
+ int response = 0;
+
+ TQCString thisApp;
+ if (appid.isEmpty()) {
+ thisApp = "TDE System";
+ } else {
+ thisApp = appid;
+ }
+
+ if (!implicitAllow(wallet, thisApp)) {
+ KBetterThanKDialogBase *dialog = new KBetterThanKDialogBase;
+ if (appid.isEmpty()) {
+ dialog->setLabel(i18n("<qt>TDE has requested access to the open wallet '<b>%1</b>'.").arg(TQStyleSheet::escape(wallet)));
+ } else {
+ dialog->setLabel(i18n("<qt>The application '<b>%1</b>' has requested access to the open wallet '<b>%2</b>'.").arg(TQStyleSheet::escape(TQString(appid))).arg(TQStyleSheet::escape(wallet)));
+ }
+ setupDialog( dialog, w, appid, false );
+ response = dialog->exec();
+ delete dialog;
+ }
+
+ if (response == 0 || response == 1) {
+ if (response == 1) {
+ TDEConfig cfg("tdewalletrc");
+ cfg.setGroup("Auto Allow");
+ TQStringList apps = cfg.readListEntry(wallet);
+ if (!apps.contains(thisApp)) {
+ apps += thisApp;
+ _implicitAllowMap[wallet] += thisApp;
+ cfg.writeEntry(wallet, apps);
+ cfg.sync();
+ }
+ }
+ } else if (response == 3) {
+ TDEConfig cfg("tdewalletrc");
+ cfg.setGroup("Auto Deny");
+ TQStringList apps = cfg.readListEntry(wallet);
+ if (!apps.contains(thisApp)) {
+ apps += thisApp;
+ _implicitDenyMap[wallet] += thisApp;
+ cfg.writeEntry(wallet, apps);
+ cfg.sync();
+ }
+ return false;
+ } else {
+ return false;
+ }
+ return true;
+}
+
+
+int KWalletD::deleteWallet(const TQString& wallet) {
+ TQString path = TDEGlobal::dirs()->saveLocation("tdewallet") + TQDir::separator() + wallet + ".kwl";
+
+ if (TQFile::exists(path)) {
+ close(wallet, true);
+ TQFile::remove(path);
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << wallet;
+ emitDCOPSignal("walletDeleted(TQString)", data);
+ return 0;
+ }
+
+ return -1;
+}
+
+
+void KWalletD::changePassword(const TQString& wallet, uint wId) {
+ TQCString appid = friendlyDCOPPeerName();
+
+ KWalletTransaction *xact = new KWalletTransaction;
+
+ xact->appid = appid;
+ xact->client = callingDcopClient();
+ xact->wallet = wallet;
+ xact->wId = wId;
+ xact->tType = KWalletTransaction::ChangePassword;
+
+ _transactions.append(xact);
+
+ TQTimer::singleShot(0, this, TQT_SLOT(processTransactions()));
+ checkActiveDialog();
+}
+
+
+void KWalletD::doTransactionChangePassword(const TQCString& appid, const TQString& wallet, uint wId) {
+ TQIntDictIterator<KWallet::Backend> it(_wallets);
+ KWallet::Backend *w = 0L;
+ int handle = -1;
+ bool reclose = false;
+
+ for (; it.current(); ++it) {
+ if (it.current()->walletName() == wallet) {
+ break;
+ }
+ }
+
+ if (!it.current()) {
+ handle = doTransactionOpen(appid, wallet, wId,false);
+ if (-1 == handle) {
+ KMessageBox::sorryWId(wId, i18n("Unable to open wallet. The wallet must be opened in order to change the password."), i18n("TDE Wallet Service"));
+ return;
+ }
+
+ w = _wallets.find(handle);
+ reclose = true;
+ } else {
+ handle = it.currentKey();
+ w = it.current();
+ }
+
+ assert(w);
+
+ KPasswordDialog *kpd;
+ kpd = new KPasswordDialog(KPasswordDialog::NewPassword, false, 0);
+ kpd->setPrompt(i18n("<qt>Please choose a new password for the wallet '<b>%1</b>'.").arg(TQStyleSheet::escape(wallet)));
+ kpd->setCaption(i18n("TDE Wallet Service"));
+ kpd->setAllowEmptyPasswords(true);
+ setupDialog( kpd, wId, appid, false );
+ if (kpd->exec() == KDialog::Accepted) {
+ const char *p = kpd->password();
+ if (p) {
+ _passwords[wallet] = p;
+ TQByteArray pa;
+ pa.duplicate(p, strlen(p));
+ int rc = w->close(pa);
+ if (rc < 0) {
+ KMessageBox::sorryWId(wId, i18n("Error re-encrypting the wallet. Password was not changed."), i18n("TDE Wallet Service"));
+ reclose = true;
+ } else {
+ rc = w->open(pa);
+ if (rc < 0) {
+ KMessageBox::sorryWId(wId, i18n("Error reopening the wallet. Data may be lost."), i18n("TDE Wallet Service"));
+ reclose = true;
+ }
+ }
+ }
+ }
+
+ delete kpd;
+
+ if (reclose) {
+ close(handle, true);
+ }
+}
+
+
+int KWalletD::close(const TQString& wallet, bool force) {
+ int handle = -1;
+ KWallet::Backend *w = 0L;
+
+ for (TQIntDictIterator<KWallet::Backend> it(_wallets);
+ it.current();
+ ++it) {
+ if (it.current()->walletName() == wallet) {
+ handle = it.currentKey();
+ w = it.current();
+ break;
+ }
+ }
+
+ return closeWallet(w, handle, force);
+}
+
+
+int KWalletD::closeWallet(KWallet::Backend *w, int handle, bool force) {
+ if (w) {
+ const TQString& wallet = w->walletName();
+ assert(_passwords.contains(wallet));
+ if (w->refCount() == 0 || force) {
+ invalidateHandle(handle);
+ if (_closeIdle && _timeouts) {
+ _timeouts->removeTimer(handle);
+ }
+ _wallets.remove(handle);
+ if (_passwords.contains(wallet)) {
+ w->close(TQByteArray().duplicate(_passwords[wallet].data(), _passwords[wallet].length()));
+ _passwords[wallet].fill(0);
+ _passwords.remove(wallet);
+ }
+ doCloseSignals(handle, wallet);
+ delete w;
+ return 0;
+ }
+ return 1;
+ }
+
+ return -1;
+}
+
+
+int KWalletD::close(int handle, bool force) {
+ TQCString appid = friendlyDCOPPeerName();
+ KWallet::Backend *w = _wallets.find(handle);
+ bool contains = false;
+
+ if (w) { // the handle is valid
+ if (_handles.contains(appid)) { // we know this app
+ if (_handles[appid].contains(handle)) {
+ // the app owns this handle
+ _handles[appid].remove(_handles[appid].find(handle));
+ contains = true;
+ if (_handles[appid].isEmpty()) {
+ _handles.remove(appid);
+ }
+ }
+ }
+
+ // watch the side effect of the deref()
+ if ((contains && w->deref() == 0 && !_leaveOpen) || force) {
+ if (_closeIdle && _timeouts) {
+ _timeouts->removeTimer(handle);
+ }
+ _wallets.remove(handle);
+ if (force) {
+ invalidateHandle(handle);
+ }
+ if (_passwords.contains(w->walletName())) {
+ w->close(TQByteArray().duplicate(_passwords[w->walletName()].data(), _passwords[w->walletName()].length()));
+ _passwords[w->walletName()].fill(0);
+ _passwords.remove(w->walletName());
+ }
+ doCloseSignals(handle, w->walletName());
+ delete w;
+ return 0;
+ }
+ return 1; // not closed
+ }
+
+ return -1; // not open to begin with, or other error
+}
+
+
+bool KWalletD::isOpen(const TQString& wallet) const {
+ for (TQIntDictIterator<KWallet::Backend> it(_wallets);
+ it.current();
+ ++it) {
+ if (it.current()->walletName() == wallet) {
+ return true;
+ }
+ }
+ return false;
+}
+
+
+bool KWalletD::isOpen(int handle) {
+ if (handle == 0) {
+ return false;
+ }
+
+ KWallet::Backend *rc = _wallets.find(handle);
+
+ if (rc == 0 && ++_failed > 5) {
+ _failed = 0;
+ TQTimer::singleShot(0, this, TQT_SLOT(notifyFailures()));
+ } else if (rc != 0) {
+ _failed = 0;
+ }
+
+ return rc != 0;
+}
+
+
+TQStringList KWalletD::wallets() const {
+ TQString path = TDEGlobal::dirs()->saveLocation("tdewallet");
+ TQDir dir(path, "*.kwl");
+ TQStringList rc;
+
+ dir.setFilter(TQDir::Files | TQDir::NoSymLinks);
+
+ const TQFileInfoList *list = dir.entryInfoList();
+ TQFileInfoListIterator it(*list);
+ TQFileInfo *fi;
+ while ((fi = it.current()) != 0L) {
+ TQString fn = fi->fileName();
+ if (fn.endsWith(".kwl")) {
+ fn.truncate(fn.length()-4);
+ }
+ rc += fn;
+ ++it;
+ }
+ return rc;
+}
+
+
+void KWalletD::sync(int handle) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ }
+}
+
+
+TQStringList KWalletD::folderList(int handle) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ return b->folderList();
+ }
+
+ return TQStringList();
+}
+
+
+bool KWalletD::hasFolder(int handle, const TQString& f) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ return b->hasFolder(f);
+ }
+
+ return false;
+}
+
+
+bool KWalletD::removeFolder(int handle, const TQString& f) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ bool rc = b->removeFolder(f);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << b->walletName();
+ emitDCOPSignal("folderListUpdated(TQString)", data);
+ return rc;
+ }
+
+ return false;
+}
+
+
+bool KWalletD::createFolder(int handle, const TQString& f) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ bool rc = b->createFolder(f);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << b->walletName();
+ emitDCOPSignal("folderListUpdated(TQString)", data);
+ return rc;
+ }
+
+ return false;
+}
+
+
+TQByteArray KWalletD::readMap(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ KWallet::Entry *e = b->readEntry(key);
+ if (e && e->type() == KWallet::Wallet::Map) {
+ return e->map();
+ }
+ }
+
+ return TQByteArray();
+}
+
+
+TQMap<TQString,TQByteArray> KWalletD::readMapList(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ TQPtrList<KWallet::Entry> e = b->readEntryList(key);
+ TQMap<TQString, TQByteArray> rc;
+ TQPtrListIterator<KWallet::Entry> it(e);
+ KWallet::Entry *entry;
+ while ((entry = it.current())) {
+ if (entry->type() == KWallet::Wallet::Map) {
+ rc.insert(entry->key(), entry->map());
+ }
+ ++it;
+ }
+ return rc;
+ }
+
+ return TQMap<TQString, TQByteArray>();
+}
+
+
+TQByteArray KWalletD::readEntry(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ KWallet::Entry *e = b->readEntry(key);
+ if (e) {
+ return e->value();
+ }
+ }
+
+ return TQByteArray();
+}
+
+
+TQMap<TQString, TQByteArray> KWalletD::readEntryList(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ TQPtrList<KWallet::Entry> e = b->readEntryList(key);
+ TQMap<TQString, TQByteArray> rc;
+ TQPtrListIterator<KWallet::Entry> it(e);
+ KWallet::Entry *entry;
+ while ((entry = it.current())) {
+ rc.insert(entry->key(), entry->value());
+ ++it;
+ }
+ return rc;
+ }
+
+ return TQMap<TQString, TQByteArray>();
+}
+
+
+TQStringList KWalletD::entryList(int handle, const TQString& folder) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ return b->entryList();
+ }
+
+ return TQStringList();
+}
+
+
+TQString KWalletD::readPassword(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ KWallet::Entry *e = b->readEntry(key);
+ if (e && e->type() == KWallet::Wallet::Password) {
+ return e->password();
+ }
+ }
+
+ return TQString::null;
+}
+
+
+TQMap<TQString, TQString> KWalletD::readPasswordList(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ TQPtrList<KWallet::Entry> e = b->readEntryList(key);
+ TQMap<TQString, TQString> rc;
+ TQPtrListIterator<KWallet::Entry> it(e);
+ KWallet::Entry *entry;
+ while ((entry = it.current())) {
+ if (entry->type() == KWallet::Wallet::Password) {
+ rc.insert(entry->key(), entry->password());
+ }
+ ++it;
+ }
+ return rc;
+ }
+
+ return TQMap<TQString, TQString>();
+}
+
+
+int KWalletD::writeMap(int handle, const TQString& folder, const TQString& key, const TQByteArray& value) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ KWallet::Entry e;
+ e.setKey(key);
+ e.setValue(value);
+ e.setType(KWallet::Wallet::Map);
+ b->writeEntry(&e);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ emitFolderUpdated(b->walletName(), folder);
+ return 0;
+ }
+
+ return -1;
+}
+
+
+int KWalletD::writeEntry(int handle, const TQString& folder, const TQString& key, const TQByteArray& value, int entryType) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ KWallet::Entry e;
+ e.setKey(key);
+ e.setValue(value);
+ e.setType(KWallet::Wallet::EntryType(entryType));
+ b->writeEntry(&e);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ emitFolderUpdated(b->walletName(), folder);
+ return 0;
+ }
+
+ return -1;
+}
+
+
+int KWalletD::writeEntry(int handle, const TQString& folder, const TQString& key, const TQByteArray& value) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ KWallet::Entry e;
+ e.setKey(key);
+ e.setValue(value);
+ e.setType(KWallet::Wallet::Stream);
+ b->writeEntry(&e);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ emitFolderUpdated(b->walletName(), folder);
+ return 0;
+ }
+
+ return -1;
+}
+
+
+int KWalletD::writePassword(int handle, const TQString& folder, const TQString& key, const TQString& value) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ KWallet::Entry e;
+ e.setKey(key);
+ e.setValue(value);
+ e.setType(KWallet::Wallet::Password);
+ b->writeEntry(&e);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ emitFolderUpdated(b->walletName(), folder);
+ return 0;
+ }
+
+ return -1;
+}
+
+
+int KWalletD::entryType(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ if (!b->hasFolder(folder)) {
+ return KWallet::Wallet::Unknown;
+ }
+ b->setFolder(folder);
+ if (b->hasEntry(key)) {
+ return b->readEntry(key)->type();
+ }
+ }
+
+ return KWallet::Wallet::Unknown;
+}
+
+
+bool KWalletD::hasEntry(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ if (!b->hasFolder(folder)) {
+ return false;
+ }
+ b->setFolder(folder);
+ return b->hasEntry(key);
+ }
+
+ return false;
+}
+
+
+int KWalletD::removeEntry(int handle, const TQString& folder, const TQString& key) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ if (!b->hasFolder(folder)) {
+ return 0;
+ }
+ b->setFolder(folder);
+ bool rc = b->removeEntry(key);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ emitFolderUpdated(b->walletName(), folder);
+ return rc ? 0 : -3;
+ }
+
+ return -1;
+}
+
+
+void KWalletD::slotAppUnregistered(const TQCString& app) {
+ if (_handles.contains(app)) {
+ TQValueList<int> l = _handles[app];
+ for (TQValueList<int>::Iterator i = l.begin(); i != l.end(); ++i) {
+ _handles[app].remove(*i);
+ KWallet::Backend *w = _wallets.find(*i);
+ if (w && !_leaveOpen && 0 == w->deref()) {
+ close(w->walletName(), true);
+ }
+ }
+ _handles.remove(app);
+ }
+}
+
+
+void KWalletD::invalidateHandle(int handle) {
+ for (TQMap<TQCString,TQValueList<int> >::Iterator i = _handles.begin();
+ i != _handles.end();
+ ++i) {
+ i.data().remove(handle);
+ }
+}
+
+
+KWallet::Backend *KWalletD::getWallet(const TQCString& appid, int handle) {
+ if (handle == 0) {
+ return 0L;
+ }
+
+ KWallet::Backend *w = _wallets.find(handle);
+
+ if (w) { // the handle is valid
+ if (_handles.contains(appid)) { // we know this app
+ if (_handles[appid].contains(handle)) {
+ // the app owns this handle
+ _failed = 0;
+ if (_closeIdle && _timeouts) {
+ _timeouts->resetTimer(handle, _idleTime);
+ }
+ return w;
+ }
+ }
+ }
+
+ if (++_failed > 5) {
+ _failed = 0;
+ TQTimer::singleShot(0, this, TQT_SLOT(notifyFailures()));
+ }
+
+ return 0L;
+}
+
+
+void KWalletD::notifyFailures() {
+ if (!_showingFailureNotify) {
+ _showingFailureNotify = true;
+ KMessageBox::information(0, i18n("There have been repeated failed attempts to gain access to a wallet. An application may be misbehaving."), i18n("TDE Wallet Service"));
+ _showingFailureNotify = false;
+ }
+}
+
+
+void KWalletD::doCloseSignals(int handle, const TQString& wallet) {
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << handle;
+ emitDCOPSignal("walletClosed(int)", data);
+
+ TQByteArray data2;
+ TQDataStream ds2(data2, IO_WriteOnly);
+ ds2 << wallet;
+ emitDCOPSignal("walletClosed(TQString)", data2);
+
+ if (_wallets.isEmpty()) {
+ emitDCOPSignal("allWalletsClosed()", TQByteArray());
+ }
+}
+
+
+int KWalletD::renameEntry(int handle, const TQString& folder, const TQString& oldName, const TQString& newName) {
+ KWallet::Backend *b;
+
+ if ((b = getWallet(friendlyDCOPPeerName(), handle))) {
+ b->setFolder(folder);
+ int rc = b->renameEntry(oldName, newName);
+ // write changes to disk immediately
+ TQByteArray p;
+ TQString wallet = b->walletName();
+ p.duplicate(_passwords[wallet].data(), _passwords[wallet].length());
+ b->sync(p);
+ p.fill(0);
+ emitFolderUpdated(b->walletName(), folder);
+ return rc;
+ }
+
+ return -1;
+}
+
+
+TQStringList KWalletD::users(const TQString& wallet) const {
+ TQStringList rc;
+
+ for (TQIntDictIterator<KWallet::Backend> it(_wallets);
+ it.current();
+ ++it) {
+ if (it.current()->walletName() == wallet) {
+ for (TQMap<TQCString,TQValueList<int> >::ConstIterator hit = _handles.begin(); hit != _handles.end(); ++hit) {
+ if (hit.data().contains(it.currentKey())) {
+ rc += hit.key();
+ }
+ }
+ break;
+ }
+ }
+
+ return rc;
+}
+
+
+bool KWalletD::disconnectApplication(const TQString& wallet, const TQCString& application) {
+ for (TQIntDictIterator<KWallet::Backend> it(_wallets);
+ it.current();
+ ++it) {
+ if (it.current()->walletName() == wallet) {
+ if (_handles[application].contains(it.currentKey())) {
+ _handles[application].remove(it.currentKey());
+
+ if (_handles[application].isEmpty()) {
+ _handles.remove(application);
+ }
+
+ if (it.current()->deref() == 0) {
+ close(it.current()->walletName(), true);
+ }
+
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << wallet;
+ ds << application;
+ emitDCOPSignal("applicationDisconnected(TQString,TQCString)", data);
+
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+
+void KWalletD::emitFolderUpdated(const TQString& wallet, const TQString& folder) {
+ TQByteArray data;
+ TQDataStream ds(data, IO_WriteOnly);
+ ds << wallet;
+ ds << folder;
+ emitDCOPSignal("folderUpdated(TQString,TQString)", data);
+}
+
+
+void KWalletD::emitWalletListDirty() {
+ emitDCOPSignal("walletListDirty()", TQByteArray());
+}
+
+
+void KWalletD::reconfigure() {
+ TDEConfig cfg("tdewalletrc");
+ cfg.setGroup("Wallet");
+ _firstUse = cfg.readBoolEntry("First Use", true);
+ _enabled = cfg.readBoolEntry("Enabled", true);
+ _launchManager = cfg.readBoolEntry("Launch Manager", true);
+ _leaveOpen = cfg.readBoolEntry("Leave Open", false);
+ bool idleSave = _closeIdle;
+ _closeIdle = cfg.readBoolEntry("Close When Idle", false);
+ _openPrompt = cfg.readBoolEntry("Prompt on Open", true);
+ int timeSave = _idleTime;
+ // in minutes!
+ _idleTime = cfg.readNumEntry("Idle Timeout", 10) * 60 * 1000;
+
+ if (cfg.readBoolEntry("Close on Screensaver", false)) {
+ connectDCOPSignal("kdesktop", "KScreensaverIface", "KDE_start_screensaver()", "closeAllWallets()", false);
+ } else {
+ disconnectDCOPSignal("kdesktop", "KScreensaverIface", "KDE_start_screensaver()", "closeAllWallets()");
+ }
+
+ // Handle idle changes
+ if (_closeIdle) {
+ if (_idleTime != timeSave) { // Timer length changed
+ TQIntDictIterator<KWallet::Backend> it(_wallets);
+ for (; it.current(); ++it) {
+ _timeouts->resetTimer(it.currentKey(), _idleTime);
+ }
+ }
+
+ if (!idleSave) { // add timers for all the wallets
+ TQIntDictIterator<KWallet::Backend> it(_wallets);
+ for (; it.current(); ++it) {
+ _timeouts->addTimer(it.currentKey(), _idleTime);
+ }
+ }
+ } else {
+ _timeouts->clear();
+ }
+
+ // Update the implicit allow stuff
+ _implicitAllowMap.clear();
+ cfg.setGroup("Auto Allow");
+ TQStringList entries = cfg.entryMap("Auto Allow").keys();
+ for (TQStringList::Iterator i = entries.begin(); i != entries.end(); ++i) {
+ _implicitAllowMap[*i] = cfg.readListEntry(*i);
+ }
+
+ // Update the implicit allow stuff
+ _implicitDenyMap.clear();
+ cfg.setGroup("Auto Deny");
+ entries = cfg.entryMap("Auto Deny").keys();
+ for (TQStringList::Iterator i = entries.begin(); i != entries.end(); ++i) {
+ _implicitDenyMap[*i] = cfg.readListEntry(*i);
+ }
+
+ // Update if wallet was enabled/disabled
+ if (!_enabled) { // close all wallets
+ while (!_wallets.isEmpty()) {
+ TQIntDictIterator<KWallet::Backend> it(_wallets);
+ if (!it.current()) { // necessary?
+ break;
+ }
+ closeWallet(it.current(), it.currentKey(), true);
+ }
+ }
+}
+
+
+bool KWalletD::isEnabled() const {
+ return _enabled;
+}
+
+
+bool KWalletD::folderDoesNotExist(const TQString& wallet, const TQString& folder) {
+ if (!wallets().contains(wallet)) {
+ return true;
+ }
+
+ for (TQIntDictIterator<KWallet::Backend> it(_wallets); it.current(); ++it) {
+ if (it.current()->walletName() == wallet) {
+ return it.current()->folderDoesNotExist(folder);
+ }
+ }
+
+ KWallet::Backend *b = new KWallet::Backend(wallet);
+ b->open(TQByteArray());
+ bool rc = b->folderDoesNotExist(folder);
+ delete b;
+ return rc;
+}
+
+
+bool KWalletD::keyDoesNotExist(const TQString& wallet, const TQString& folder, const TQString& key) {
+ if (!wallets().contains(wallet)) {
+ return true;
+ }
+
+ for (TQIntDictIterator<KWallet::Backend> it(_wallets); it.current(); ++it) {
+ if (it.current()->walletName() == wallet) {
+ return it.current()->entryDoesNotExist(folder, key);
+ }
+ }
+
+ KWallet::Backend *b = new KWallet::Backend(wallet);
+ b->open(TQByteArray());
+ bool rc = b->entryDoesNotExist(folder, key);
+ delete b;
+ return rc;
+}
+
+
+bool KWalletD::implicitAllow(const TQString& wallet, const TQCString& app) {
+ return _implicitAllowMap[wallet].contains(TQString::fromLocal8Bit(app));
+}
+
+
+bool KWalletD::implicitDeny(const TQString& wallet, const TQCString& app) {
+ return _implicitDenyMap[wallet].contains(TQString::fromLocal8Bit(app));
+}
+
+
+TQCString KWalletD::friendlyDCOPPeerName() {
+ DCOPClient *dc = callingDcopClient();
+ if (!dc) {
+ return "";
+ }
+ return dc->senderId().replace(TQRegExp("-[0-9]+$"), "");
+}
+
+
+void KWalletD::timedOut(int id) {
+ KWallet::Backend *w = _wallets.find(id);
+ if (w) {
+ closeWallet(w, id, true);
+ }
+}
+
+
+void KWalletD::closeAllWallets() {
+ TQIntDict<KWallet::Backend> tw = _wallets;
+
+ for (TQIntDictIterator<KWallet::Backend> it(tw); it.current(); ++it) {
+ closeWallet(it.current(), it.currentKey(), true);
+ }
+
+ tw.clear();
+
+ // All of this should be basically noop. Let's just be safe.
+ _wallets.clear();
+
+ for (TQMap<TQString,TQCString>::Iterator it = _passwords.begin();
+ it != _passwords.end();
+ ++it) {
+ it.data().fill(0);
+ }
+ _passwords.clear();
+}
+
+
+TQString KWalletD::networkWallet() {
+ return KWallet::Wallet::NetworkWallet();
+}
+
+
+TQString KWalletD::localWallet() {
+ return KWallet::Wallet::LocalWallet();
+}
+
+
+#include "tdewalletd.moc"
diff --git a/kio/misc/tdewalletd/tdewalletd.desktop b/tdeio/misc/tdewalletd/tdewalletd.desktop
index 1e65fe0df..1e65fe0df 100644
--- a/kio/misc/tdewalletd/tdewalletd.desktop
+++ b/tdeio/misc/tdewalletd/tdewalletd.desktop
diff --git a/kio/misc/tdewalletd/tdewalletd.h b/tdeio/misc/tdewalletd/tdewalletd.h
index b3a315413..b3a315413 100644
--- a/kio/misc/tdewalletd/tdewalletd.h
+++ b/tdeio/misc/tdewalletd/tdewalletd.h
diff --git a/kio/misc/tdewalletd/tdewalletwizard.ui b/tdeio/misc/tdewalletd/tdewalletwizard.ui
index aa3a1c09d..aa3a1c09d 100644
--- a/kio/misc/tdewalletd/tdewalletwizard.ui
+++ b/tdeio/misc/tdewalletd/tdewalletwizard.ui
diff --git a/kio/misc/tdewalletd/tdewalletwizard.ui.h b/tdeio/misc/tdewalletd/tdewalletwizard.ui.h
index a42635e9b..a42635e9b 100644
--- a/kio/misc/tdewalletd/tdewalletwizard.ui.h
+++ b/tdeio/misc/tdewalletd/tdewalletwizard.ui.h
diff --git a/tdeio/misc/telnet.protocol b/tdeio/misc/telnet.protocol
new file mode 100644
index 000000000..062fb1d4f
--- /dev/null
+++ b/tdeio/misc/telnet.protocol
@@ -0,0 +1,13 @@
+[Protocol]
+exec=tdetelnetservice %u
+protocol=telnet
+input=none
+output=none
+helper=true
+listing=
+reading=false
+writing=false
+makedir=false
+deleting=false
+DocPath=tdeioslave/telnet.html
+Icon=konsole
diff --git a/tdeio/misc/uiserver.cpp b/tdeio/misc/uiserver.cpp
new file mode 100644
index 000000000..6ba92a6a2
--- /dev/null
+++ b/tdeio/misc/uiserver.cpp
@@ -0,0 +1,1413 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Matej Koss <koss@miesto.sk>
+ David Faure <faure@kde.org>
+ 2001 George Staikos <staikos@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+// -*- mode: c++; c-basic-offset: 4 -*-
+
+#include <tqtimer.h>
+
+#include <tqregexp.h>
+#include <tqheader.h>
+#include <tqevent.h>
+
+#include <ksqueezedtextlabel.h>
+#include <tdeconfig.h>
+#include <kstandarddirs.h>
+#include <kuniqueapplication.h>
+#include <kaboutdata.h>
+#include <kcmdlineargs.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <dcopclient.h>
+#include <kstatusbar.h>
+#include <kdebug.h>
+#include <kmessagebox.h>
+#include <tdesu/client.h>
+#include <twin.h>
+#include <kdialog.h>
+#include <ksystemtray.h>
+#include <kpopupmenu.h>
+#include <kaction.h>
+
+#include <tqcheckbox.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqpopupmenu.h>
+#include <tqheader.h>
+
+#include "observer_stub.h"
+#include "observer.h" // for static methods only
+#include "tdeio/defaultprogress.h"
+#include "tdeio/jobclasses.h"
+#include "uiserver.h"
+#include "passdlg.h"
+#include "tdeio/renamedlg.h"
+#include "tdeio/skipdlg.h"
+#include "slavebase.h" // for QuestionYesNo etc.
+#include <ksslinfodlg.h>
+#include <ksslcertdlg.h>
+#include <ksslcertificate.h>
+#include <ksslcertchain.h>
+
+
+// pointer for main instance of UIServer
+UIServer* uiserver;
+
+// ToolBar field IDs
+enum { TOOL_CANCEL, TOOL_CONFIGURE };
+
+// StatusBar field IDs
+enum { ID_TOTAL_FILES = 1, ID_TOTAL_SIZE, ID_TOTAL_TIME, ID_TOTAL_SPEED };
+
+//static
+int UIServer::s_jobId = 0;
+
+static const int defaultColumnWidth[] = { 70, // SIZE_OPERATION
+ 160, // LOCAL_FILENAME
+ 40, // RESUME
+ 60, // COUNT
+ 30, // PROGRESS
+ 65, // TOTAL
+ 70, // SPEED
+ 70, // REMAINING_TIME
+ 450 // URL
+};
+
+class UIServerSystemTray:public KSystemTray
+{
+ public:
+ UIServerSystemTray(UIServer* uis)
+ :KSystemTray(uis)
+ {
+ KPopupMenu* pop= contextMenu();
+ pop->insertItem(i18n("Settings..."), uis, TQT_SLOT(slotConfigure()));
+ pop->insertItem(i18n("Remove"), uis, TQT_SLOT(slotRemoveSystemTrayIcon()));
+ setPixmap(loadIcon("filesave"));
+ //actionCollection()->action("file_quit")->setEnabled(true);
+ KStdAction::quit(TQT_TQOBJECT(uis), TQT_SLOT(slotQuit()), actionCollection());
+ }
+};
+
+class ProgressConfigDialog:public KDialogBase
+{
+ public:
+ ProgressConfigDialog(TQWidget* parent);
+ ~ProgressConfigDialog() {}
+ void setChecked(int i, bool on);
+ bool isChecked(int i) const;
+ friend class UIServer;
+ private:
+ TQCheckBox *m_showSystemTrayCb;
+ TQCheckBox *m_keepOpenCb;
+ TQCheckBox *m_toolBarCb;
+ TQCheckBox *m_statusBarCb;
+ TQCheckBox *m_headerCb;
+ TQCheckBox *m_fixedWidthCb;
+ KListView *m_columns;
+ TQCheckListItem *(m_items[ListProgress::TB_MAX]);
+};
+
+ProgressConfigDialog::ProgressConfigDialog(TQWidget *parent)
+:KDialogBase(KDialogBase::Plain,i18n("Configure Network Operation Window"),KDialogBase::Ok|KDialogBase::Apply|KDialogBase::Cancel,
+ KDialogBase::Ok, parent, "configprog", false)
+{
+ TQVBoxLayout *layout=new TQVBoxLayout(plainPage(),spacingHint());
+ m_showSystemTrayCb=new TQCheckBox(i18n("Show system tray icon"), plainPage());
+ m_keepOpenCb=new TQCheckBox(i18n("Keep network operation window always open"), plainPage());
+ m_headerCb=new TQCheckBox(i18n("Show column headers"), plainPage());
+ m_toolBarCb=new TQCheckBox(i18n("Show toolbar"), plainPage());
+ m_statusBarCb=new TQCheckBox(i18n("Show statusbar"), plainPage());
+ m_fixedWidthCb=new TQCheckBox(i18n("Column widths are user adjustable"), plainPage());
+ TQLabel *label=new TQLabel(i18n("Show information:"), plainPage());
+ m_columns=new KListView(plainPage());
+
+ m_columns->addColumn("info");
+ m_columns->setSorting(-1);
+ m_columns->header()->hide();
+
+ m_items[ListProgress::TB_ADDRESS] =new TQCheckListItem(m_columns, i18n("URL"), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_REMAINING_TIME] =new TQCheckListItem(m_columns, i18n("Remaining Time", "Rem. Time"), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_SPEED] =new TQCheckListItem(m_columns, i18n("Speed"), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_TOTAL] =new TQCheckListItem(m_columns, i18n("Size"), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_PROGRESS] =new TQCheckListItem(m_columns, i18n("%"), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_COUNT] =new TQCheckListItem(m_columns, i18n("Count"), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_RESUME] =new TQCheckListItem(m_columns, i18n("Resume", "Res."), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_LOCAL_FILENAME] =new TQCheckListItem(m_columns, i18n("Local Filename"), TQCheckListItem::CheckBox);
+ m_items[ListProgress::TB_OPERATION] =new TQCheckListItem(m_columns, i18n("Operation"), TQCheckListItem::CheckBox);
+
+ layout->addWidget(m_showSystemTrayCb);
+ layout->addWidget(m_keepOpenCb);
+ layout->addWidget(m_headerCb);
+ layout->addWidget(m_toolBarCb);
+ layout->addWidget(m_statusBarCb);
+ layout->addWidget(m_fixedWidthCb);
+ layout->addWidget(label);
+ layout->addWidget(m_columns);
+}
+
+void ProgressConfigDialog::setChecked(int i, bool on)
+{
+ if (i>=ListProgress::TB_MAX)
+ return;
+ m_items[i]->setOn(on);
+}
+
+bool ProgressConfigDialog::isChecked(int i) const
+{
+ if (i>=ListProgress::TB_MAX)
+ return false;
+ return m_items[i]->isOn();
+}
+
+ProgressItem::ProgressItem( ListProgress* view, TQListViewItem *after, TQCString app_id, int job_id,
+ bool showDefault )
+ : TQListViewItem( view, after ) {
+
+ listProgress = view;
+
+ m_iTotalSize = 0;
+ m_iTotalFiles = 0;
+ m_iProcessedSize = 0;
+ m_iProcessedFiles = 0;
+ m_iSpeed = 0;
+
+ m_sAppId = app_id;
+ m_iJobId = job_id;
+ m_visible = true;
+ m_defaultProgressVisible = showDefault;
+
+ // create dialog, but don't show it
+ defaultProgress = new TDEIO::DefaultProgress( false );
+ defaultProgress->setOnlyClean( true );
+ connect ( defaultProgress, TQT_SIGNAL( stopped() ), this, TQT_SLOT( slotCanceled() ) );
+ connect ( &m_showTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT(slotShowDefaultProgress()) );
+
+ if ( showDefault ) {
+ m_showTimer.start( 500, true );
+ }
+}
+
+bool ProgressItem::keepOpen() const
+{
+ return defaultProgress->keepOpen();
+}
+
+void ProgressItem::finished()
+{
+ defaultProgress->finished();
+}
+
+ProgressItem::~ProgressItem() {
+ delete defaultProgress;
+}
+
+
+void ProgressItem::setTotalSize( TDEIO::filesize_t size ) {
+ m_iTotalSize = size;
+
+ // It's already in the % column...
+ //setText( listProgress->lv_total, TDEIO::convertSize( m_iTotalSize ) );
+
+ defaultProgress->slotTotalSize( 0, m_iTotalSize );
+}
+
+
+void ProgressItem::setTotalFiles( unsigned long files ) {
+ m_iTotalFiles = files;
+
+ defaultProgress->slotTotalFiles( 0, m_iTotalFiles );
+}
+
+
+void ProgressItem::setTotalDirs( unsigned long dirs ) {
+ defaultProgress->slotTotalDirs( 0, dirs );
+}
+
+
+void ProgressItem::setProcessedSize( TDEIO::filesize_t size ) {
+ m_iProcessedSize = size;
+
+ setText( ListProgress::TB_TOTAL, TDEIO::convertSize( size ) );
+
+ defaultProgress->slotProcessedSize( 0, size );
+}
+
+
+void ProgressItem::setProcessedFiles( unsigned long files ) {
+ m_iProcessedFiles = files;
+
+ TQString tmps = i18n("%1 / %2").arg( m_iProcessedFiles ).arg( m_iTotalFiles );
+ setText( ListProgress::TB_COUNT, tmps );
+
+ defaultProgress->slotProcessedFiles( 0, m_iProcessedFiles );
+}
+
+
+void ProgressItem::setProcessedDirs( unsigned long dirs ) {
+ defaultProgress->slotProcessedDirs( 0, dirs );
+}
+
+
+void ProgressItem::setPercent( unsigned long percent ) {
+ const TQString tmps = TDEIO::DefaultProgress::makePercentString( percent, m_iTotalSize, m_iTotalFiles );
+ setText( ListProgress::TB_PROGRESS, tmps );
+
+ defaultProgress->slotPercent( 0, percent );
+}
+
+void ProgressItem::setInfoMessage( const TQString & msg ) {
+ TQString plainTextMsg(msg);
+ plainTextMsg.replace( TQRegExp( "</?b>" ), TQString() );
+ plainTextMsg.replace( TQRegExp( "<img.*>" ), TQString() );
+ setText( ListProgress::TB_PROGRESS, plainTextMsg );
+
+ defaultProgress->slotInfoMessage( 0, msg );
+}
+
+void ProgressItem::setSpeed( unsigned long bytes_per_second ) {
+ m_iSpeed = bytes_per_second;
+ m_remainingSeconds = TDEIO::calculateRemainingSeconds( m_iTotalSize, m_iProcessedSize, m_iSpeed );
+
+ TQString tmps, tmps2;
+ if ( m_iSpeed == 0 ) {
+ tmps = i18n( "Stalled");
+ tmps2 = tmps;
+ } else {
+ tmps = i18n( "%1/s").arg( TDEIO::convertSize( m_iSpeed ));
+ tmps2 = TDEIO::convertSeconds( m_remainingSeconds );
+ }
+ setText( ListProgress::TB_SPEED, tmps );
+ setText( ListProgress::TB_REMAINING_TIME, tmps2 );
+
+ defaultProgress->slotSpeed( 0, m_iSpeed );
+}
+
+
+void ProgressItem::setCopying( const KURL& from, const KURL& to ) {
+ setText( ListProgress::TB_OPERATION, i18n("Copying") );
+ setText( ListProgress::TB_ADDRESS, from.url() );
+ setText( ListProgress::TB_LOCAL_FILENAME, to.fileName() );
+
+ defaultProgress->slotCopying( 0, from, to );
+}
+
+
+void ProgressItem::setMoving( const KURL& from, const KURL& to ) {
+ setText( ListProgress::TB_OPERATION, i18n("Moving") );
+ setText( ListProgress::TB_ADDRESS, from.url() );
+ setText( ListProgress::TB_LOCAL_FILENAME, to.fileName() );
+
+ defaultProgress->slotMoving( 0, from, to );
+}
+
+
+void ProgressItem::setCreatingDir( const KURL& dir ) {
+ setText( ListProgress::TB_OPERATION, i18n("Creating") );
+ setText( ListProgress::TB_ADDRESS, dir.url() );
+ setText( ListProgress::TB_LOCAL_FILENAME, dir.fileName() );
+
+ defaultProgress->slotCreatingDir( 0, dir );
+}
+
+
+void ProgressItem::setDeleting( const KURL& url ) {
+ setText( ListProgress::TB_OPERATION, i18n("Deleting") );
+ setText( ListProgress::TB_ADDRESS, url.url() );
+ setText( ListProgress::TB_LOCAL_FILENAME, url.fileName() );
+
+ defaultProgress->slotDeleting( 0, url );
+}
+
+void ProgressItem::setTransferring( const KURL& url ) {
+ setText( ListProgress::TB_OPERATION, i18n("Loading") );
+ setText( ListProgress::TB_ADDRESS, url.url() );
+ setText( ListProgress::TB_LOCAL_FILENAME, url.fileName() );
+
+ defaultProgress->slotTransferring( 0, url );
+}
+
+void ProgressItem::setText(ListProgress::ListProgressFields field, const TQString& text)
+{
+ if (listProgress->m_lpcc[field].enabled)
+ {
+ TQString t=text;
+ if ((field==ListProgress::TB_ADDRESS) && (listProgress->m_fixedColumnWidths))
+// if (((field==ListProgress::TB_LOCAL_FILENAME) || (field==ListProgress::TB_ADDRESS)) && (listProgress->m_fixedColumnWidths))
+ {
+ m_fullLengthAddress=text;
+ listProgress->m_squeezer->resize(listProgress->columnWidth(listProgress->m_lpcc[field].index),50);
+ listProgress->m_squeezer->setText(t);
+ t=listProgress->m_squeezer->text();
+ }
+ TQListViewItem::setText(listProgress->m_lpcc[field].index,t);
+ }
+}
+
+void ProgressItem::setStating( const KURL& url ) {
+ setText( ListProgress::TB_OPERATION, i18n("Examining") );
+ setText( ListProgress::TB_ADDRESS, url.url() );
+ setText( ListProgress::TB_LOCAL_FILENAME, url.fileName() );
+
+ defaultProgress->slotStating( 0, url );
+}
+
+void ProgressItem::setMounting( const TQString& dev, const TQString & point ) {
+ setText( ListProgress::TB_OPERATION, i18n("Mounting") );
+ setText( ListProgress::TB_ADDRESS, point ); // ?
+ setText( ListProgress::TB_LOCAL_FILENAME, dev ); // ?
+
+ defaultProgress->slotMounting( 0, dev, point );
+}
+
+void ProgressItem::setUnmounting( const TQString & point ) {
+ setText( ListProgress::TB_OPERATION, i18n("Unmounting") );
+ setText( ListProgress::TB_ADDRESS, point ); // ?
+ setText( ListProgress::TB_LOCAL_FILENAME, "" ); // ?
+
+ defaultProgress->slotUnmounting( 0, point );
+}
+
+void ProgressItem::setCanResume( TDEIO::filesize_t offset ) {
+ /*
+ TQString tmps;
+ // set canResume
+ if ( _resume ) {
+ tmps = i18n("Yes");
+ } else {
+ tmps = i18n("No");
+ }
+ setText( listProgress->lv_resume, tmps );
+ */
+ defaultProgress->slotCanResume( 0, offset );
+}
+
+
+void ProgressItem::slotCanceled() {
+ emit jobCanceled( this );
+}
+
+// Called 0.5s after the job has been started
+void ProgressItem::slotShowDefaultProgress() {
+ if (defaultProgress)
+ {
+ if ( m_visible && m_defaultProgressVisible )
+ defaultProgress->show();
+ else
+ defaultProgress->hide();
+ }
+}
+
+void ProgressItem::slotToggleDefaultProgress() {
+ setDefaultProgressVisible( !m_defaultProgressVisible );
+}
+
+// Called when a rename or skip dialog pops up
+// We want to prevent someone from killing the job in the uiserver then
+void ProgressItem::setVisible( bool visible ) {
+ if ( m_visible != visible )
+ {
+ m_visible = visible;
+ updateVisibility();
+ }
+}
+
+// Can be toggled by the user
+void ProgressItem::setDefaultProgressVisible( bool visible ) {
+ if ( m_defaultProgressVisible != visible )
+ {
+ m_defaultProgressVisible = visible;
+ updateVisibility();
+ }
+}
+
+// Update according to state
+void ProgressItem::updateVisibility()
+{
+ if (defaultProgress)
+ {
+ if ( m_visible && m_defaultProgressVisible )
+ {
+ m_showTimer.start(250, true); // Show delayed
+ }
+ else
+ {
+ m_showTimer.stop();
+ defaultProgress->hide();
+ }
+ }
+}
+
+
+//-----------------------------------------------------------------------------
+ListProgress::ListProgress (TQWidget *parent, const char *name)
+: KListView (parent, name)
+{
+
+ // enable selection of more than one item
+ setMultiSelection( true );
+
+ setAllColumnsShowFocus( true );
+
+ m_lpcc[TB_OPERATION].title=i18n("Operation");
+ m_lpcc[TB_LOCAL_FILENAME].title=i18n("Local Filename");
+ m_lpcc[TB_RESUME].title=i18n("Resume", "Res.");
+ m_lpcc[TB_COUNT].title=i18n("Count");
+ m_lpcc[TB_PROGRESS].title=i18n("%");
+ m_lpcc[TB_TOTAL].title=i18n("Size");
+ m_lpcc[TB_SPEED].title=i18n("Speed");
+ m_lpcc[TB_REMAINING_TIME].title=i18n("Remaining Time", "Rem. Time");
+ m_lpcc[TB_ADDRESS].title=i18n("URL");
+ readSettings();
+
+ applySettings();
+
+ //used for squeezing the text in local file name and url
+ m_squeezer=new KSqueezedTextLabel(this);
+ m_squeezer->hide();
+ connect(header(),TQT_SIGNAL(sizeChange(int,int,int)),this,TQT_SLOT(columnWidthChanged(int)));
+}
+
+
+ListProgress::~ListProgress() {
+}
+
+void ListProgress::applySettings()
+{
+ int iEnabledCols=0;
+
+ // Update listcolumns to show
+ for (int i=0; i<TB_MAX; i++)
+ {
+ if ( !m_lpcc[i].enabled )
+ continue;
+
+ iEnabledCols++;
+
+ // Add new or reuse existing column
+ if ( iEnabledCols > columns() )
+ m_lpcc[i].index=addColumn(m_lpcc[i].title, m_fixedColumnWidths?m_lpcc[i].width:-1);
+ else
+ {
+ m_lpcc[i].index = iEnabledCols - 1;
+ setColumnText(m_lpcc[i].index, m_lpcc[i].title);
+ }
+
+ setColumnWidth(m_lpcc[i].index, m_lpcc[i].width); //yes, this is required here, alexxx
+ if (m_fixedColumnWidths)
+ setColumnWidthMode(m_lpcc[i].index, Manual);
+ }
+
+ // Remove unused columns. However we must keep one column left
+ // Otherwise the listview will be emptied
+ while( iEnabledCols < columns() && columns() > 1 )
+ removeColumn( columns() - 1 );
+
+ if ( columns() == 0 )
+ addColumn( "" );
+
+ if ( !m_showHeader || iEnabledCols == 0 )
+ header()->hide();
+ else
+ header()->show();
+}
+
+void ListProgress::readSettings() {
+ TDEConfig config("uiserverrc");
+
+ // read listview geometry properties
+ config.setGroup( "ProgressList" );
+ for ( int i = 0; i < TB_MAX; i++ ) {
+ TQString tmps="Col"+TQString::number(i);
+ m_lpcc[i].width=config.readNumEntry( tmps, 0);
+ if (m_lpcc[i].width==0) m_lpcc[i].width=defaultColumnWidth[i];
+
+ tmps="Enabled"+TQString::number(i);
+ m_lpcc[i].enabled=config.readBoolEntry(tmps,true);
+ }
+ m_showHeader=config.readBoolEntry("ShowListHeader",true);
+ m_fixedColumnWidths=config.readBoolEntry("FixedColumnWidths",false);
+
+ m_lpcc[TB_RESUME].enabled=false;
+}
+
+void ListProgress::columnWidthChanged(int column)
+{
+ //resqueeze if necessary
+ if ((m_lpcc[TB_ADDRESS].enabled) && (column==m_lpcc[TB_ADDRESS].index))
+ {
+ for (TQListViewItem* lvi=firstChild(); lvi!=0; lvi=lvi->nextSibling())
+ {
+ ProgressItem *pi=(ProgressItem*)lvi;
+ pi->setText(TB_ADDRESS,pi->fullLengthAddress());
+ }
+ }
+ writeSettings();
+}
+
+void ListProgress::writeSettings() {
+ TDEConfig config("uiserverrc");
+
+ // write listview geometry properties
+ config.setGroup( "ProgressList" );
+ for ( int i = 0; i < TB_MAX; i++ ) {
+ if (!m_lpcc[i].enabled) {
+ TQString tmps= "Enabled" + TQString::number(i);
+ config.writeEntry( tmps, false );
+ continue;
+ }
+ m_lpcc[i].width=columnWidth(m_lpcc[i].index);
+ TQString tmps="Col"+TQString::number(i);
+ config.writeEntry( tmps, m_lpcc[i].width);
+ }
+ config.writeEntry("ShowListHeader", m_showHeader);
+ config.writeEntry("FixedColumnWidths", m_fixedColumnWidths);
+ config.sync();
+}
+
+
+//------------------------------------------------------------
+
+
+UIServer::UIServer()
+:KMainWindow(0, "")
+,DCOPObject("UIServer")
+,m_shuttingDown(false)
+,m_configDialog(0)
+,m_contextMenu(0)
+,m_systemTray(0)
+{
+
+ readSettings();
+
+ // setup toolbar
+ toolBar()->insertButton("editdelete", TOOL_CANCEL,
+ TQT_SIGNAL(clicked()), TQT_TQOBJECT(this),
+ TQT_SLOT(slotCancelCurrent()), FALSE, i18n("Cancel"));
+ toolBar()->insertButton("configure", TOOL_CONFIGURE,
+ TQT_SIGNAL(clicked()), TQT_TQOBJECT(this),
+ TQT_SLOT(slotConfigure()), true, i18n("Settings..."));
+
+ toolBar()->setBarPos( KToolBar::Left );
+
+ // setup statusbar
+ statusBar()->insertItem( i18n(" Files: %1 ").arg( 0 ), ID_TOTAL_FILES);
+ statusBar()->insertItem( i18n("Remaining Size", " Rem. Size: %1 kB ").arg( "0" ), ID_TOTAL_SIZE);
+ statusBar()->insertItem( i18n("Remaining Time", " Rem. Time: 00:00:00 "), ID_TOTAL_TIME);
+ statusBar()->insertItem( i18n(" %1 kB/s ").arg("0"), ID_TOTAL_SPEED);
+
+ // setup listview
+ listProgress = new ListProgress( this, "progresslist" );
+
+ setCentralWidget( listProgress );
+
+ connect( listProgress, TQT_SIGNAL( selectionChanged() ),
+ TQT_SLOT( slotSelection() ) );
+ connect( listProgress, TQT_SIGNAL( executed( TQListViewItem* ) ),
+ TQT_SLOT( slotToggleDefaultProgress( TQListViewItem* ) ) );
+ connect( listProgress, TQT_SIGNAL( contextMenu( KListView*, TQListViewItem *, const TQPoint &)),
+ TQT_SLOT(slotShowContextMenu(KListView*, TQListViewItem *, const TQPoint&)));
+
+
+ // setup animation timer
+ updateTimer = new TQTimer( this );
+ connect( updateTimer, TQT_SIGNAL( timeout() ),
+ TQT_SLOT( slotUpdate() ) );
+ m_bUpdateNewJob=false;
+
+ setCaption(i18n("Progress Dialog"));
+ setMinimumSize( 150, 50 );
+ resize( m_initWidth, m_initHeight);
+
+ applySettings();
+
+/* if ((m_bShowList) && (m_keepListOpen))
+ {
+ cerr<<"show() !"<<endl;
+ show();
+ }
+ else*/
+ hide();
+}
+
+UIServer::~UIServer() {
+ updateTimer->stop();
+}
+
+void UIServer::applySettings()
+{
+ if ((m_showSystemTray) && (m_systemTray==0))
+ {
+ m_systemTray=new UIServerSystemTray(this);
+ m_systemTray->show();
+ }
+ else if ((m_showSystemTray==false) && (m_systemTray!=0))
+ {
+ delete m_systemTray;
+ m_systemTray=0;
+ }
+
+ if (m_showStatusBar==false)
+ statusBar()->hide();
+ else
+ statusBar()->show();
+ if (m_showToolBar==false)
+ toolBar()->hide();
+ else
+ toolBar()->show();
+}
+
+void UIServer::slotShowContextMenu(KListView*, TQListViewItem* item, const TQPoint& pos)
+{
+ if (m_contextMenu==0)
+ {
+ m_contextMenu=new TQPopupMenu(this);
+ m_idCancelItem = m_contextMenu->insertItem(i18n("Cancel Job"), this, TQT_SLOT(slotCancelCurrent()));
+// m_contextMenu->insertItem(i18n("Toggle Progress"), this, TQT_SLOT(slotToggleDefaultProgress()));
+ m_contextMenu->insertSeparator();
+ m_contextMenu->insertItem(i18n("Settings..."), this, TQT_SLOT(slotConfigure()));
+ }
+ if ( item )
+ item->setSelected( true );
+ bool enabled = false;
+ TQListViewItemIterator it( listProgress );
+ for ( ; it.current(); ++it ) {
+ if ( it.current()->isSelected() ) {
+ enabled = true;
+ break;
+ }
+ }
+ m_contextMenu->setItemEnabled( m_idCancelItem, enabled);
+
+ m_contextMenu->popup(pos);
+}
+
+void UIServer::slotRemoveSystemTrayIcon()
+{
+ m_showSystemTray=false;
+ applySettings();
+ writeSettings();
+}
+
+void UIServer::slotConfigure()
+{
+ if (m_configDialog==0)
+ {
+ m_configDialog=new ProgressConfigDialog(0);
+// connect(m_configDialog,TQT_SIGNAL(cancelClicked()), this, TQT_SLOT(slotCancelConfig()));
+ connect(m_configDialog,TQT_SIGNAL(okClicked()), this, TQT_SLOT(slotApplyConfig()));
+ connect(m_configDialog,TQT_SIGNAL(applyClicked()), this, TQT_SLOT(slotApplyConfig()));
+ }
+ m_configDialog->m_showSystemTrayCb->setChecked(m_showSystemTray);
+ m_configDialog->m_keepOpenCb->setChecked(m_keepListOpen);
+ m_configDialog->m_toolBarCb->setChecked(m_showToolBar);
+ m_configDialog->m_statusBarCb->setChecked(m_showStatusBar);
+ m_configDialog->m_headerCb->setChecked(listProgress->m_showHeader);
+ m_configDialog->m_fixedWidthCb->setChecked(listProgress->m_fixedColumnWidths);
+ for (int i=0; i<ListProgress::TB_MAX; i++)
+ {
+ m_configDialog->setChecked(i, listProgress->m_lpcc[i].enabled);
+ }
+ m_configDialog->show();
+}
+
+void UIServer::slotApplyConfig()
+{
+ m_showSystemTray=m_configDialog->m_showSystemTrayCb->isChecked();
+ m_keepListOpen=m_configDialog->m_keepOpenCb->isChecked();
+ m_showToolBar=m_configDialog->m_toolBarCb->isChecked();
+ m_showStatusBar=m_configDialog->m_statusBarCb->isChecked();
+ listProgress->m_showHeader=m_configDialog->m_headerCb->isChecked();
+ listProgress->m_fixedColumnWidths=m_configDialog->m_fixedWidthCb->isChecked();
+ for (int i=0; i<ListProgress::TB_MAX; i++)
+ listProgress->m_lpcc[i].enabled=m_configDialog->isChecked(i);
+
+
+ applySettings();
+ listProgress->applySettings();
+ writeSettings();
+ listProgress->writeSettings();
+}
+
+int UIServer::newJob( TQCString observerAppId, bool showProgress )
+{
+ kdDebug(7024) << "UIServer::newJob observerAppId=" << observerAppId << ". "
+ << "Giving id=" << s_jobId+1 << endl;
+
+ TQListViewItemIterator it( listProgress );
+ for ( ; it.current(); ++it ) {
+ if ( it.current()->itemBelow() == 0L ) { // this will find the end of list
+ break;
+ }
+ }
+
+ // increment counter
+ s_jobId++;
+
+ bool show = !m_bShowList && showProgress;
+
+ ProgressItem *item = new ProgressItem( listProgress, it.current(), observerAppId, s_jobId, show );
+ connect( item, TQT_SIGNAL( jobCanceled( ProgressItem* ) ),
+ TQT_SLOT( slotJobCanceled( ProgressItem* ) ) );
+
+ if ( m_bShowList && !updateTimer->isActive() )
+ updateTimer->start( 1000 );
+
+ m_bUpdateNewJob=true;
+
+ return s_jobId;
+}
+
+
+ProgressItem* UIServer::findItem( int id )
+{
+ TQListViewItemIterator it( listProgress );
+
+ ProgressItem *item;
+
+ for ( ; it.current(); ++it ) {
+ item = (ProgressItem*) it.current();
+ if ( item->jobId() == id ) {
+ return item;
+ }
+ }
+
+ return 0L;
+}
+
+
+void UIServer::setItemVisible( ProgressItem * item, bool visible )
+{
+ item->setVisible( visible );
+ // Check if we were the last one to be visible
+ // or the first one -> hide/show the list in that case
+ // (Note that the user could have hidden the listview by hand yet, no time)
+ if ( m_bShowList ) {
+ m_bUpdateNewJob = true;
+ slotUpdate();
+ }
+}
+
+// Called by Observer when opening a skip or rename dialog
+void UIServer::setJobVisible( int id, bool visible )
+{
+ kdDebug(7024) << "UIServer::setJobVisible id=" << id << " visible=" << visible << endl;
+ ProgressItem *item = findItem( id );
+ Q_ASSERT( item );
+ if ( item )
+ setItemVisible( item, visible );
+}
+
+void UIServer::jobFinished( int id )
+{
+ kdDebug(7024) << "UIServer::jobFinished id=" << id << endl;
+ ProgressItem *item = findItem( id );
+
+ // remove item from the list and delete the corresponding defaultprogress
+ if ( item ) {
+ if ( item->keepOpen() )
+ item->finished();
+ else
+ delete item;
+ }
+}
+
+
+void UIServer::totalSize( int id, unsigned long size )
+{ totalSize64(id, size); }
+
+void UIServer::totalSize64( int id, TDEIO::filesize_t size )
+{
+// kdDebug(7024) << "UIServer::totalSize " << id << " " << TDEIO::number(size) << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setTotalSize( size );
+ }
+}
+
+void UIServer::totalFiles( int id, unsigned long files )
+{
+ kdDebug(7024) << "UIServer::totalFiles " << id << " " << (unsigned int) files << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setTotalFiles( files );
+ }
+}
+
+void UIServer::totalDirs( int id, unsigned long dirs )
+{
+ kdDebug(7024) << "UIServer::totalDirs " << id << " " << (unsigned int) dirs << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setTotalDirs( dirs );
+ }
+}
+
+void UIServer::processedSize( int id, unsigned long size )
+{ processedSize64(id, size); }
+
+void UIServer::processedSize64( int id, TDEIO::filesize_t size )
+{
+ //kdDebug(7024) << "UIServer::processedSize " << id << " " << TDEIO::number(size) << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setProcessedSize( size );
+ }
+}
+
+void UIServer::processedFiles( int id, unsigned long files )
+{
+ //kdDebug(7024) << "UIServer::processedFiles " << id << " " << (unsigned int) files << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setProcessedFiles( files );
+ }
+}
+
+void UIServer::processedDirs( int id, unsigned long dirs )
+{
+ kdDebug(7024) << "UIServer::processedDirs " << id << " " << (unsigned int) dirs << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setProcessedDirs( dirs );
+ }
+}
+
+void UIServer::percent( int id, unsigned long ipercent )
+{
+ //kdDebug(7024) << "UIServer::percent " << id << " " << (unsigned int) ipercent << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setPercent( ipercent );
+ }
+}
+
+void UIServer::speed( int id, unsigned long bytes_per_second )
+{
+ //kdDebug(7024) << "UIServer::speed " << id << " " << (unsigned int) bytes_per_second << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setSpeed( bytes_per_second );
+ }
+}
+
+void UIServer::infoMessage( int id, const TQString & msg )
+{
+ //kdDebug(7024) << "UIServer::infoMessage " << id << " " << msg << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setInfoMessage( msg );
+ }
+}
+
+void UIServer::canResume( int id, unsigned long offset )
+{ canResume64(id, offset); }
+
+void UIServer::canResume64( int id, TDEIO::filesize_t offset )
+{
+ //kdDebug(7024) << "UIServer::canResume " << id << " " << offset << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setCanResume( offset );
+ }
+}
+
+void UIServer::copying( int id, KURL from, KURL to )
+{
+ //kdDebug(7024) << "UIServer::copying " << id << " " << from.url() << " " << to.url() << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setCopying( from, to );
+ }
+}
+
+void UIServer::moving( int id, KURL from, KURL to )
+{
+ //kdDebug(7024) << "UIServer::moving " << id << " " << from.url() << " " << to.url() << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setMoving( from, to );
+ }
+}
+
+void UIServer::deleting( int id, KURL url )
+{
+ //kdDebug(7024) << "UIServer::deleting " << id << " " << url.url() << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setDeleting( url );
+ }
+}
+
+void UIServer::transferring( int id, KURL url )
+{
+ //kdDebug(7024) << "UIServer::transferring " << id << " " << url.url() << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setTransferring( url );
+ }
+}
+
+void UIServer::creatingDir( int id, KURL dir )
+{
+ kdDebug(7024) << "UIServer::creatingDir " << id << " " << dir.url() << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setCreatingDir( dir );
+ }
+}
+
+void UIServer::stating( int id, KURL url )
+{
+ kdDebug(7024) << "UIServer::stating " << id << " " << url.url() << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setStating( url );
+ }
+}
+
+void UIServer::mounting( int id, TQString dev, TQString point )
+{
+ kdDebug(7024) << "UIServer::mounting " << id << " " << dev << " " << point << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setMounting( dev, point );
+ }
+}
+
+void UIServer::unmounting( int id, TQString point )
+{
+ kdDebug(7024) << "UIServer::unmounting " << id << " " << point << endl;
+
+ ProgressItem *item = findItem( id );
+ if ( item ) {
+ item->setUnmounting( point );
+ }
+}
+
+void UIServer::killJob( TQCString observerAppId, int progressId )
+{
+ // Contact the object "TDEIO::Observer" in the application <appId>
+ Observer_stub observer( observerAppId, "TDEIO::Observer" );
+ // Tell it to kill the job
+ observer.killJob( progressId );
+}
+
+void UIServer::slotJobCanceled( ProgressItem *item ) {
+ kdDebug(7024) << "UIServer::slotJobCanceled appid=" << item->appId() << " jobid=" << item->jobId() << endl;
+ // kill the corresponding job
+ killJob( item->appId(), item->jobId() );
+
+ // TDEIO::Job, when killed, should call back jobFinished(), but we can't
+ // really rely on that - the app may have crashed
+ delete item;
+}
+
+
+void UIServer::slotQuit()
+{
+ m_shuttingDown = true;
+ kapp->quit();
+}
+
+void UIServer::slotUpdate() {
+ // don't do anything if we don't have any inserted progress item
+ // or if they're all hidden
+ TQListViewItemIterator lvit( listProgress );
+ bool visible = false;
+ for ( ; lvit.current(); ++lvit )
+ if ( ((ProgressItem*)lvit.current())->isVisible() ) {
+ visible = true;
+ break;
+ }
+
+ if ( !visible || !m_bShowList ) {
+ if (!m_keepListOpen) hide();
+ updateTimer->stop();
+ return;
+ }
+
+ // Calling show() is conditional, so that users can close the window
+ // and it only pops up back when a new job is started
+ if (m_bUpdateNewJob)
+ {
+ m_bUpdateNewJob=false;
+ show();
+
+ // Make sure we'll be called back
+ if ( m_bShowList && !updateTimer->isActive() )
+ updateTimer->start( 1000 );
+ }
+
+ int iTotalFiles = 0;
+ TDEIO::filesize_t iTotalSize = 0;
+ int iTotalSpeed = 0;
+ unsigned int totalRemTime = 0; // in seconds
+
+ ProgressItem *item;
+
+ // count totals for statusbar
+ TQListViewItemIterator it( listProgress );
+
+ for ( ; it.current(); ++it ) {
+ item = (ProgressItem*) it.current();
+ if ( item->totalSize() != 0 ) {
+ iTotalSize += ( item->totalSize() - item->processedSize() );
+ }
+ iTotalFiles += ( item->totalFiles() - item->processedFiles() );
+ iTotalSpeed += item->speed();
+
+ if ( item->remainingSeconds() > totalRemTime ) {
+ totalRemTime = item->remainingSeconds();
+ }
+ }
+
+ // update statusbar
+ statusBar()->changeItem( i18n( " Files: %1 ").arg( iTotalFiles ), ID_TOTAL_FILES);
+ statusBar()->changeItem( i18n( "Remaining Size", " Rem. Size: %1 ").arg( TDEIO::convertSize( iTotalSize ) ),
+ ID_TOTAL_SIZE);
+ statusBar()->changeItem( i18n( "Remaining Time", " Rem. Time: %1 ").arg( TDEIO::convertSeconds( totalRemTime ) ),
+ ID_TOTAL_TIME);
+ statusBar()->changeItem( i18n( " %1/s ").arg( TDEIO::convertSize( iTotalSpeed ) ),
+ ID_TOTAL_SPEED);
+
+}
+
+void UIServer::setListMode( bool list )
+{
+ m_bShowList = list;
+ TQListViewItemIterator it( listProgress );
+ for ( ; it.current(); ++it ) {
+ // When going to list mode -> hide all progress dialogs
+ // When going back to separate dialogs -> show them all
+ ((ProgressItem*) it.current())->setDefaultProgressVisible( !list );
+ }
+
+ if (m_bShowList)
+ {
+ show();
+ updateTimer->start( 1000 );
+ }
+ else
+ {
+ hide();
+ updateTimer->stop();
+ }
+}
+
+void UIServer::slotToggleDefaultProgress( TQListViewItem *item ) {
+ ((ProgressItem*) item )->slotToggleDefaultProgress();
+}
+
+
+void UIServer::slotSelection() {
+ TQListViewItemIterator it( listProgress );
+
+ for ( ; it.current(); ++it ) {
+ if ( it.current()->isSelected() ) {
+ toolBar()->setItemEnabled( TOOL_CANCEL, TRUE);
+ return;
+ }
+ }
+ toolBar()->setItemEnabled( TOOL_CANCEL, FALSE);
+}
+
+// This code is deprecated, slaves go to Observer::openPassDlg now,
+// but this is kept for compat (DCOP calls to tdeio_uiserver).
+TQByteArray UIServer::openPassDlg( const TDEIO::AuthInfo &info )
+{
+ kdDebug(7024) << "UIServer::openPassDlg: User= " << info.username
+ << ", Msg= " << info.prompt << endl;
+ TDEIO::AuthInfo inf(info);
+ int result = TDEIO::PasswordDialog::getNameAndPassword( inf.username, inf.password,
+ &inf.keepPassword, inf.prompt,
+ inf.readOnly, inf.caption,
+ inf.comment, inf.commentLabel );
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly );
+ if ( result == TQDialog::Accepted )
+ inf.setModified( true );
+ else
+ inf.setModified( false );
+ stream << inf;
+ return data;
+}
+
+int UIServer::messageBox( int progressId, int type, const TQString &text, const TQString &caption, const TQString &buttonYes, const TQString &buttonNo )
+{
+ return Observer::messageBox( progressId, type, text, caption, buttonYes, buttonNo );
+}
+
+void UIServer::showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &meta)
+{
+ return showSSLInfoDialog(url,meta,0);
+}
+
+void UIServer::showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &meta, int mainwindow)
+{
+ KSSLInfoDlg *kid = new KSSLInfoDlg(meta["ssl_in_use"].upper()=="TRUE", 0L /*parent?*/, 0L, true);
+ KSSLCertificate *x = KSSLCertificate::fromString(meta["ssl_peer_certificate"].local8Bit());
+ if (x) {
+ // Set the chain back onto the certificate
+ TQStringList cl =
+ TQStringList::split(TQString("\n"), meta["ssl_peer_chain"]);
+ TQPtrList<KSSLCertificate> ncl;
+
+ ncl.setAutoDelete(true);
+ for (TQStringList::Iterator it = cl.begin(); it != cl.end(); ++it) {
+ KSSLCertificate *y = KSSLCertificate::fromString((*it).local8Bit());
+ if (y) ncl.append(y);
+ }
+
+ if (ncl.count() > 0)
+ x->chain().setChain(ncl);
+
+ kdDebug(7024) << "ssl_cert_errors=" << meta["ssl_cert_errors"] << endl;
+ kid->setCertState(meta["ssl_cert_errors"]);
+ TQString ip = meta.contains("ssl_proxied") ? "" : meta["ssl_peer_ip"];
+ kid->setup( x,
+ ip,
+ url, // the URL
+ meta["ssl_cipher"],
+ meta["ssl_cipher_desc"],
+ meta["ssl_cipher_version"],
+ meta["ssl_cipher_used_bits"].toInt(),
+ meta["ssl_cipher_bits"].toInt(),
+ KSSLCertificate::KSSLValidation(meta["ssl_cert_state"].toInt()));
+ kdDebug(7024) << "Showing SSL Info dialog" << endl;
+#ifndef Q_WS_WIN
+ if( mainwindow != 0 )
+ KWin::setMainWindow( kid, mainwindow );
+#endif
+ kid->exec();
+ delete x;
+ kdDebug(7024) << "SSL Info dialog closed" << endl;
+ } else {
+ KMessageBox::information( 0L, // parent ?
+ i18n("The peer SSL certificate appears to be corrupt."), i18n("SSL") );
+ }
+ // Don't delete kid!!
+}
+
+KSSLCertDlgRet UIServer::showSSLCertDialog(const TQString& host, const TQStringList& certList)
+{
+ return showSSLCertDialog( host, certList, 0 );
+}
+
+KSSLCertDlgRet UIServer::showSSLCertDialog(const TQString& host, const TQStringList& certList, int mainwindow)
+{
+ KSSLCertDlgRet rc;
+ rc.ok = false;
+ if (!certList.isEmpty()) {
+ KSSLCertDlg *kcd = new KSSLCertDlg(0L, 0L, true);
+ kcd->setupDialog(certList);
+ kcd->setHost(host);
+ kdDebug(7024) << "Showing SSL certificate dialog" << endl;
+#ifndef Q_WS_WIN
+ if( mainwindow != 0 )
+ KWin::setMainWindow( kcd, mainwindow );
+#endif
+ kcd->exec();
+ rc.ok = true;
+ rc.choice = kcd->getChoice();
+ rc.save = kcd->saveChoice();
+ rc.send = kcd->wantsToSend();
+ kdDebug(7024) << "SSL certificate dialog closed" << endl;
+ delete kcd;
+ }
+ return rc;
+}
+
+
+TQByteArray UIServer::open_RenameDlg( int id,
+ const TQString & caption,
+ const TQString& src, const TQString & dest,
+ int mode,
+ unsigned long sizeSrc,
+ unsigned long sizeDest,
+ unsigned long ctimeSrc,
+ unsigned long ctimeDest,
+ unsigned long mtimeSrc,
+ unsigned long mtimeDest
+ )
+{ return open_RenameDlg64(id, caption, src, dest, mode, sizeSrc, sizeDest,
+ ctimeSrc, ctimeDest, mtimeSrc, mtimeDest); }
+
+
+TQByteArray UIServer::open_RenameDlg64( int id,
+ const TQString & caption,
+ const TQString& src, const TQString & dest,
+ int mode,
+ TDEIO::filesize_t sizeSrc,
+ TDEIO::filesize_t sizeDest,
+ unsigned long ctimeSrc,
+ unsigned long ctimeDest,
+ unsigned long mtimeSrc,
+ unsigned long mtimeDest
+ )
+{
+ // Hide existing dialog box if any
+ ProgressItem *item = findItem( id );
+ if ( item )
+ setItemVisible( item, false );
+ TQString newDest;
+ kdDebug(7024) << "Calling TDEIO::open_RenameDlg" << endl;
+ TDEIO::RenameDlg_Result result = TDEIO::open_RenameDlg( caption, src, dest,
+ (TDEIO::RenameDlg_Mode) mode, newDest,
+ sizeSrc, sizeDest,
+ (time_t)ctimeSrc, (time_t)ctimeDest,
+ (time_t)mtimeSrc, (time_t)mtimeDest );
+ kdDebug(7024) << "TDEIO::open_RenameDlg done" << endl;
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly );
+ stream << TQ_UINT8(result) << newDest;
+ if ( item && result != TDEIO::R_CANCEL )
+ setItemVisible( item, true );
+ return data;
+}
+
+int UIServer::open_SkipDlg( int id,
+ int /*bool*/ multi,
+ const TQString & error_text )
+{
+ // Hide existing dialog box if any
+ ProgressItem *item = findItem( id );
+ if ( item )
+ setItemVisible( item, false );
+ kdDebug(7024) << "Calling TDEIO::open_SkipDlg" << endl;
+ TDEIO::SkipDlg_Result result = TDEIO::open_SkipDlg( (bool)multi, error_text );
+ if ( item && result != TDEIO::S_CANCEL )
+ setItemVisible( item, true );
+ return (TDEIO::SkipDlg_Result) result;
+}
+
+
+void UIServer::readSettings() {
+ TDEConfig config("uiserverrc");
+ config.setGroup( "UIServer" );
+ m_showStatusBar=config.readBoolEntry("ShowStatusBar",false);
+ m_showToolBar=config.readBoolEntry("ShowToolBar",true);
+ m_keepListOpen=config.readBoolEntry("KeepListOpen",false);
+ m_initWidth=config.readNumEntry("InitialWidth",460);
+ m_initHeight=config.readNumEntry("InitialHeight",150);
+ m_bShowList = config.readBoolEntry( "ShowList", false );
+ m_showSystemTray=config.readBoolEntry("ShowSystemTray", false);
+}
+
+void UIServer::writeSettings() {
+ TDEConfig config("uiserverrc");
+ config.setGroup( "UIServer" );
+ config.writeEntry("InitialWidth",width());
+ config.writeEntry("InitialHeight",height());
+ config.writeEntry("ShowStatusBar", m_showStatusBar);
+ config.writeEntry("ShowToolBar", m_showToolBar);
+ config.writeEntry("KeepListOpen", m_keepListOpen);
+ config.writeEntry("ShowList", m_bShowList);
+ config.writeEntry("ShowSystemTray", m_showSystemTray);
+}
+
+
+void UIServer::slotCancelCurrent() {
+ TQListViewItemIterator it( listProgress );
+ ProgressItem *item;
+
+ // kill selected jobs
+ for ( ; it.current() ; ++it )
+ {
+ if ( it.current()->isSelected() ) {
+ item = (ProgressItem*) it.current();
+ killJob( item->appId(), item->jobId() );
+ return;
+ }
+ }
+}
+
+void UIServer::resizeEvent(TQResizeEvent* e)
+{
+ KMainWindow::resizeEvent(e);
+ writeSettings();
+}
+
+bool UIServer::queryClose()
+{
+ if (( !m_shuttingDown ) && !kapp->sessionSaving()) {
+ hide();
+ return false;
+ }
+ return true;
+}
+
+UIServer* UIServer::createInstance()
+{
+ return new UIServer;
+}
+
+//------------------------------------------------------------
+
+extern "C" KDE_EXPORT int kdemain(int argc, char **argv)
+{
+ KLocale::setMainCatalogue("tdelibs");
+ // GS 5/2001 - I changed the name to "TDE" to make it look better
+ // in the titles of dialogs which are displayed.
+ TDEAboutData aboutdata("tdeio_uiserver", I18N_NOOP("TDE"),
+ "0.8", I18N_NOOP("TDE Progress Information UI Server"),
+ TDEAboutData::License_GPL, "(C) 2000, David Faure & Matt Koss");
+ // Who's the maintainer ? :)
+ aboutdata.addAuthor("David Faure",I18N_NOOP("Developer"),"faure@kde.org");
+ aboutdata.addAuthor("Matej Koss",I18N_NOOP("Developer"),"koss@miesto.sk");
+
+ TDECmdLineArgs::init( argc, argv, &aboutdata );
+ // TDECmdLineArgs::addCmdLineOptions( options );
+ KUniqueApplication::addCmdLineOptions();
+
+ if (!KUniqueApplication::start())
+ {
+ kdDebug(7024) << "tdeio_uiserver is already running!" << endl;
+ return (0);
+ }
+
+ KUniqueApplication app;
+
+ // This app is started automatically, no need for session management
+ app.disableSessionManagement();
+ app.dcopClient()->setDaemonMode( true );
+
+ uiserver = UIServer::createInstance();
+
+// app.setMainWidget( uiserver );
+
+ return app.exec();
+}
+
+#include "uiserver.moc"
diff --git a/tdeio/misc/uiserver.h b/tdeio/misc/uiserver.h
new file mode 100644
index 000000000..baf495dfe
--- /dev/null
+++ b/tdeio/misc/uiserver.h
@@ -0,0 +1,430 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Matej Koss <koss@miesto.sk>
+ David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __tdeio_uiserver_h__
+#define __tdeio_uiserver_h__
+
+#include <tqintdict.h>
+#include <tqdatetime.h>
+#include <tqtimer.h>
+
+#include <dcopobject.h>
+#include <tdeio/global.h>
+#include <tdeio/authinfo.h>
+#include <kurl.h>
+#include <kmainwindow.h>
+#include <kdatastream.h>
+#include <klistview.h>
+#include <ksslcertdlg.h>
+
+class ListProgress;
+class KSqueezedTextLabel;
+class ProgressItem;
+class UIServer;
+
+namespace TDEIO {
+ class Job;
+ class DefaultProgress;
+}
+
+
+struct ListProgressColumnConfig
+{
+ TQString title;
+ int index;
+ int width;
+ bool enabled;
+};
+
+/**
+* List view in the UIServer.
+* @internal
+*/
+class TDEIO_EXPORT ListProgress : public KListView {
+
+ Q_OBJECT
+
+public:
+
+ ListProgress (TQWidget *parent = 0, const char *name = 0 );
+
+ virtual ~ListProgress();
+
+ /**
+ * Field constants
+ */
+ enum ListProgressFields {
+ TB_OPERATION = 0,
+ TB_LOCAL_FILENAME = 1,
+ TB_RESUME = 2,
+ TB_COUNT = 3, //lv_count
+ TB_PROGRESS = 4, // lv_progress
+ TB_TOTAL = 5,
+ TB_SPEED = 6,
+ TB_REMAINING_TIME = 7,
+ TB_ADDRESS = 8,
+ TB_MAX = 9
+ };
+
+ friend class ProgressItem;
+ friend class UIServer;
+protected slots:
+ void columnWidthChanged(int column);
+protected:
+
+ void writeSettings();
+ void readSettings();
+ void applySettings();
+ void createColumns();
+
+ bool m_showHeader;
+ bool m_fixedColumnWidths;
+ ListProgressColumnConfig m_lpcc[TB_MAX];
+ //hack, alexxx
+ KSqueezedTextLabel *m_squeezer;
+};
+
+/**
+* One item in the ListProgress
+* @internal
+*/
+class TDEIO_EXPORT ProgressItem : public TQObject, public TQListViewItem {
+
+ Q_OBJECT
+
+public:
+ ProgressItem( ListProgress* view, TQListViewItem *after, TQCString app_id, int job_id,
+ bool showDefault = true );
+ ~ProgressItem();
+
+ TQCString appId() { return m_sAppId; }
+ int jobId() { return m_iJobId; }
+
+ bool keepOpen() const;
+ void finished();
+
+ void setVisible( bool visible );
+ void setDefaultProgressVisible( bool visible );
+ bool isVisible() const { return m_visible; }
+
+ void setTotalSize( TDEIO::filesize_t bytes );
+ void setTotalFiles( unsigned long files );
+ void setTotalDirs( unsigned long dirs );
+
+ void setProcessedSize( TDEIO::filesize_t size );
+ void setProcessedFiles( unsigned long files );
+ void setProcessedDirs( unsigned long dirs );
+
+ void setPercent( unsigned long percent );
+ void setSpeed( unsigned long bytes_per_second );
+ void setInfoMessage( const TQString & msg );
+
+ void setCopying( const KURL& from, const KURL& to );
+ void setMoving( const KURL& from, const KURL& to );
+ void setDeleting( const KURL& url );
+ void setTransferring( const KURL& url );
+ void setCreatingDir( const KURL& dir );
+ void setStating( const KURL& url );
+ void setMounting( const TQString & dev, const TQString & point );
+ void setUnmounting( const TQString & point );
+
+ void setCanResume( TDEIO::filesize_t offset );
+
+ TDEIO::filesize_t totalSize() { return m_iTotalSize; }
+ unsigned long totalFiles() { return m_iTotalFiles; }
+ TDEIO::filesize_t processedSize() { return m_iProcessedSize; }
+ unsigned long processedFiles() { return m_iProcessedFiles; }
+ unsigned long speed() { return m_iSpeed; }
+ unsigned int remainingSeconds() { return m_remainingSeconds; }
+
+ const TQString& fullLengthAddress() const {return m_fullLengthAddress;}
+ void setText(ListProgress::ListProgressFields field, const TQString& text);
+public slots:
+ void slotShowDefaultProgress();
+ void slotToggleDefaultProgress();
+
+protected slots:
+ void slotCanceled();
+
+signals:
+ void jobCanceled( ProgressItem* );
+
+protected:
+ void updateVisibility();
+
+ // ids that uniquely identify this progress item
+ TQCString m_sAppId;
+ int m_iJobId;
+
+ // whether shown or not (it is hidden if a rename dialog pops up for the same job)
+ bool m_visible;
+ bool m_defaultProgressVisible;
+
+ // parent listview
+ ListProgress *listProgress;
+
+ // associated default progress dialog
+ TDEIO::DefaultProgress *defaultProgress;
+
+ // we store these values for calculation of totals ( for statusbar )
+ TDEIO::filesize_t m_iTotalSize;
+ unsigned long m_iTotalFiles;
+ TDEIO::filesize_t m_iProcessedSize;
+ unsigned long m_iProcessedFiles;
+ unsigned long m_iSpeed;
+ int m_remainingSeconds;
+ TQTimer m_showTimer;
+ TQString m_fullLengthAddress;
+};
+
+class TQResizeEvent;
+class TQHideEvent;
+class TQShowEvent;
+class ProgressConfigDialog;
+class TQPopupMenu;
+class UIServerSystemTray;
+
+/**
+ * It's purpose is to show progress of IO operations.
+ * There is only one instance of this window for all jobs.
+ *
+ * All IO operations ( jobs ) are displayed in this window, one line per operation.
+ * User can cancel operations with Cancel button on toolbar.
+ *
+ * Double clicking an item in the list opens a small download window ( DefaultProgress ).
+ *
+ * @short Graphical server for progress information with an optional all-in-one progress window.
+ * @author David Faure <faure@kde.org>
+ * @author Matej Koss <koss@miesto.sk>
+ *
+ * @internal
+ */
+class TDEIO_EXPORT UIServer : public KMainWindow, public DCOPObject {
+
+ K_DCOP
+ Q_OBJECT
+
+ UIServer();
+ virtual ~UIServer();
+
+public:
+ static UIServer* createInstance();
+
+k_dcop:
+
+ /**
+ * Signal a new job
+ * @param appId the DCOP application id of the job's parent application
+ * @see TDEIO::Observer::newJob
+ * @param showProgress whether to popup the progress for the job.
+ * Usually true, but may be false when we use tdeio_uiserver for
+ * other things, like SSL dialogs.
+ * @return the job id
+ */
+ int newJob( TQCString appId, bool showProgress );
+
+ ASYNC jobFinished( int id );
+
+ ASYNC totalSize( int id, unsigned long size );
+ ASYNC totalSize64( int id, TDEIO::filesize_t size );
+ ASYNC totalFiles( int id, unsigned long files );
+ ASYNC totalDirs( int id, unsigned long dirs );
+
+ ASYNC processedSize( int id, unsigned long bytes );
+ ASYNC processedSize64( int id, TDEIO::filesize_t bytes );
+ ASYNC processedFiles( int id, unsigned long files );
+ ASYNC processedDirs( int id, unsigned long dirs );
+
+ ASYNC percent( int id, unsigned long ipercent );
+ ASYNC speed( int id, unsigned long bytes_per_second );
+ ASYNC infoMessage( int id, const TQString & msg );
+
+ ASYNC copying( int id, KURL from, KURL to );
+ ASYNC moving( int id, KURL from, KURL to );
+ ASYNC deleting( int id, KURL url );
+ ASYNC transferring( int id, KURL url );
+ ASYNC creatingDir( int id, KURL dir );
+ ASYNC stating( int id, KURL url );
+
+ ASYNC mounting( int id, TQString dev, TQString point );
+ ASYNC unmounting( int id, TQString point );
+
+ ASYNC canResume( int id, unsigned long offset );
+ ASYNC canResume64( int id, TDEIO::filesize_t offset );
+
+ /**
+ * @deprecated (it blocks other apps).
+ * Use TDEIO::PasswordDialog::getNameAndPassword instead.
+ * To be removed in KDE 4.0.
+ */
+ TQByteArray openPassDlg( const TDEIO::AuthInfo &info );
+
+ /**
+ * Popup a message box.
+ * @param id The message identifier.
+ * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
+ * This enum is defined in slavebase.h, it currently is:
+ * QuestionYesNo = 1, WarningYesNo = 2, WarningContinueCancel = 3,
+ * WarningYesNoCancel = 4, Information = 5, SSLMessageBox = 6
+ * @param text Message string. May contain newlines.
+ * @param caption Message box title.
+ * @param buttonYes The text for the first button.
+ * The default is i18n("&Yes").
+ * @param buttonNo The text for the second button.
+ * The default is i18n("&No").
+ * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
+ * and for Information, none is used.
+ * @return a button code, as defined in KMessageBox, or 0 on communication error.
+ */
+ int messageBox( int id, int type, const TQString &text, const TQString &caption,
+ const TQString &buttonYes, const TQString &buttonNo );
+
+ /**
+ * @deprecated (it blocks other apps).
+ * Use TDEIO::open_RenameDlg instead.
+ * To be removed in KDE 4.0.
+ */
+ TQByteArray open_RenameDlg64( int id,
+ const TQString & caption,
+ const TQString& src, const TQString & dest,
+ int /* TDEIO::RenameDlg_Mode */ mode,
+ TDEIO::filesize_t sizeSrc,
+ TDEIO::filesize_t sizeDest,
+ unsigned long /* time_t */ ctimeSrc,
+ unsigned long /* time_t */ ctimeDest,
+ unsigned long /* time_t */ mtimeSrc,
+ unsigned long /* time_t */ mtimeDest
+ );
+ /**
+ * @deprecated (it blocks other apps).
+ * Use TDEIO::open_RenameDlg instead.
+ * To be removed in KDE 4.0.
+ */
+ TQByteArray open_RenameDlg( int id,
+ const TQString & caption,
+ const TQString& src, const TQString & dest,
+ int /* TDEIO::RenameDlg_Mode */ mode,
+ unsigned long sizeSrc,
+ unsigned long sizeDest,
+ unsigned long /* time_t */ ctimeSrc,
+ unsigned long /* time_t */ ctimeDest,
+ unsigned long /* time_t */ mtimeSrc,
+ unsigned long /* time_t */ mtimeDest
+ );
+
+ /**
+ * @deprecated (it blocks other apps).
+ * Use TDEIO::open_SkipDlg instead.
+ * To be removed in KDE 4.0.
+ */
+ int open_SkipDlg( int id,
+ int /*bool*/ multi,
+ const TQString & error_text );
+
+ /**
+ * Switch to or from list mode - called by the kcontrol module
+ */
+ void setListMode( bool list );
+
+ /**
+ * Hide or show a job. Typically, we hide a job while a "skip" or "rename" dialog
+ * is being shown for this job. This prevents killing it from the uiserver.
+ */
+ void setJobVisible( int id, bool visible );
+
+ /**
+ * Show a SSL Information Dialog
+ */
+ void showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &data, int mainwindow);
+
+ /**
+ * @deprecated
+ */
+ void showSSLInfoDialog(const TQString &url, const TDEIO::MetaData &data);
+
+ /*
+ * Show an SSL Certificate Selection Dialog
+ */
+ KSSLCertDlgRet showSSLCertDialog(const TQString& host, const TQStringList& certList, int mainwindow);
+
+ /*
+ * @deprecated
+ */
+ KSSLCertDlgRet showSSLCertDialog(const TQString& host, const TQStringList& certList);
+
+public slots:
+ void slotConfigure();
+ void slotRemoveSystemTrayIcon();
+protected slots:
+
+ void slotUpdate();
+ void slotQuit();
+
+ void slotCancelCurrent();
+
+ void slotToggleDefaultProgress( TQListViewItem * );
+ void slotSelection();
+
+ void slotJobCanceled( ProgressItem * );
+ void slotApplyConfig();
+ void slotShowContextMenu(KListView*, TQListViewItem *item, const TQPoint& pos);
+
+protected:
+
+ ProgressItem* findItem( int id );
+
+ virtual void resizeEvent(TQResizeEvent* e);
+ virtual bool queryClose();
+
+ void setItemVisible( ProgressItem * item, bool visible );
+
+ TQTimer* updateTimer;
+ ListProgress* listProgress;
+
+ KToolBar::BarPosition toolbarPos;
+ TQString properties;
+
+ void applySettings();
+ void readSettings();
+ void writeSettings();
+private:
+
+ void killJob( TQCString observerAppId, int progressId );
+
+ int m_initWidth;
+ int m_initHeight;
+ int m_idCancelItem;
+ bool m_bShowList;
+ bool m_showStatusBar;
+ bool m_showToolBar;
+ bool m_keepListOpen;
+ bool m_showSystemTray;
+ bool m_shuttingDown;
+
+ // true if there's a new job that hasn't been shown yet.
+ bool m_bUpdateNewJob;
+ ProgressConfigDialog *m_configDialog;
+ TQPopupMenu* m_contextMenu;
+ UIServerSystemTray *m_systemTray;
+
+ static int s_jobId;
+ friend class no_bogus_warning_from_gcc;
+};
+
+// -*- mode: c++; c-basic-offset: 2 -*-
+#endif
diff --git a/tdeio/pics/CMakeLists.txt b/tdeio/pics/CMakeLists.txt
new file mode 100644
index 000000000..b04b9c7d4
--- /dev/null
+++ b/tdeio/pics/CMakeLists.txt
@@ -0,0 +1,14 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+##### other data ################################
+
+tde_install_icons( DESTINATION ${DATA_INSTALL_DIR}/tdeio_uiserver/icons )
diff --git a/tdeio/pics/Makefile.am b/tdeio/pics/Makefile.am
new file mode 100644
index 000000000..ce10461b5
--- /dev/null
+++ b/tdeio/pics/Makefile.am
@@ -0,0 +1,3 @@
+kiouiservericonsdir = $(kde_datadir)/tdeio_uiserver/icons
+kiouiservericons_ICON = AUTO
+
diff --git a/kio/pics/cr16-app-kio_uiserver.png b/tdeio/pics/cr16-app-tdeio_uiserver.png
index 41b3f4367..41b3f4367 100644
--- a/kio/pics/cr16-app-kio_uiserver.png
+++ b/tdeio/pics/cr16-app-tdeio_uiserver.png
Binary files differ
diff --git a/kio/proxytype.pl b/tdeio/proxytype.pl
index 553db53f7..553db53f7 100755
--- a/kio/proxytype.pl
+++ b/tdeio/proxytype.pl
diff --git a/kio/renamedlgplugin.desktop b/tdeio/renamedlgplugin.desktop
index d6a9f8f1f..d6a9f8f1f 100644
--- a/kio/renamedlgplugin.desktop
+++ b/tdeio/renamedlgplugin.desktop
diff --git a/kio/tdecmodule.desktop b/tdeio/tdecmodule.desktop
index 5cbe9b786..5cbe9b786 100644
--- a/kio/tdecmodule.desktop
+++ b/tdeio/tdecmodule.desktop
diff --git a/tdeio/tdefile/CMakeLists.txt b/tdeio/tdefile/CMakeLists.txt
new file mode 100644
index 000000000..4fa7b3e82
--- /dev/null
+++ b/tdeio/tdefile/CMakeLists.txt
@@ -0,0 +1,76 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdefx
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/bookmarks
+ ${LIBART_INCLUDE_DIRS}
+)
+
+
+##### headers ###################################
+
+install( FILES
+ tdefiledialog.h kencodingfiledialog.h
+ kdiroperator.h tdefileview.h tdefilefiltercombo.h
+ tdefiledetailview.h kcombiview.h kdiskfreesp.h
+ tdefileiconview.h krecentdocument.h
+ kurlrequester.h tdefilepreview.h tdefile.h
+ kurlcombobox.h kurlrequesterdlg.h kopenwith.h kpropsdlg.h
+ kicondialog.h kdirsize.h kpreviewwidgetbase.h kimagefilepreview.h tdefilesharedlg.h
+ tdefiletreeview.h tdefiletreeviewitem.h tdefiletreebranch.h
+ kdirselectdialog.h kurlbar.h kpropertiesdialog.h knotifydialog.h
+ kcustommenueditor.h ${CMAKE_CURRENT_BINARY_DIR}/knotifywidgetbase.h
+ DESTINATION ${INCLUDE_INSTALL_DIR} )
+
+
+##### other data ################################
+
+install( FILES
+ kpropsdlgplugin.desktop
+ DESTINATION ${SERVICETYPES_INSTALL_DIR} )
+
+
+##### tdefile #####################################
+
+set( target tdefile )
+
+set( ${target}_SRCS
+ tdefilefiltercombo.cpp tdefileview.cpp tdefileiconview.cpp
+ krecentdocument.cpp tdefiledialog.cpp kdiroperator.cpp
+ tdefiledetailview.cpp kcombiview.cpp kurlrequester.cpp
+ tdefilepreview.cpp kurlcombobox.cpp kurlrequesterdlg.cpp
+ kopenwith.cpp kpropertiesdialog.cpp kicondialog.cpp
+ kdirsize.cpp krecentdirs.cpp kdiskfreesp.cpp kimagefilepreview.cpp
+ tdefilesharedlg.cpp kurlbar.cpp kmetaprops.cpp kpreviewprops.cpp
+ tdefiletreeview.cpp tdefiletreeviewitem.cpp tdefiletreebranch.cpp
+ kdirselectdialog.cpp tdefilebookmarkhandler.cpp tdefilemetainfowidget.cpp
+ kcustommenueditor.cpp knotifywidgetbase.ui knotifydialog.cpp
+ tdefilespeedbar.cpp kpreviewwidgetbase.cpp tdefilemetapreview.cpp
+ kpropertiesdesktopbase.ui kpropertiesdesktopadvbase.ui
+ kpropertiesmimetypebase.ui kencodingfiledialog.cpp
+ kacleditwidget.cpp
+)
+
+tde_add_library( ${target} STATIC_PIC AUTOMOC
+ SOURCES ${${target}_SRCS}
+)
diff --git a/tdeio/tdefile/ChangeLog b/tdeio/tdefile/ChangeLog
new file mode 100644
index 000000000..79ac59808
--- /dev/null
+++ b/tdeio/tdefile/ChangeLog
@@ -0,0 +1,725 @@
+Sat Feb 26 00:26:55 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * kdiroperator.cpp:
+ lottsa changes, e.g. action handling more clear now.
+ fixed completed item not clearning the previous selection
+
+ * tdefileviewitem.cpp:
+ fixed unreadable pixmap not shown, when files were deleted
+
+ * tdefiledialog.cpp (selectedURLs):
+ re-enabled the hack to support multi-selection, until we have something
+ better
+
+ * kcombiview.*:
+ forward the sorting to the right view (or should it apply to the dir-
+ view as well?) Sort of broken tho.
+
+Sun Feb 20 01:50:44 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * kdiroperator.*, tdefiledialog.* (saveConfig):
+ implemented loading, saving and applying configuration
+
+ * tdefiledialog.cpp (setURL):
+ KDirComboBox is now a combo for recent directories as well as the
+ root-dir, home-dir and Desktop-dir.
+ Recent dirs will be saved in kdeglobals.
+
+Fri Feb 18 23:35:04 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefilefilter.cpp (eventFilter):
+ intercept Key_Return and Key_Enter in the filter-combo and emit
+ filterChanged instead of letting the dialog close
+
+Thu Feb 17 19:09:54 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefiledialog.{cpp,h} (KDirComboBox):
+ Added KDirComboBox and replaced the directory combobox with it. It
+ even does something now :) Items need to be indented tho.
+
+ * tdefilereader.cpp, kdiroperator.{cpp,h}:
+ fixed showHidden default
+
+Tue Feb 15 14:21:41 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefile.h (class KFile):
+ added a small class that contains all the enums now.
+ cleaned up the enums (hope not too many apps will be broken)
+ added flags for "Existing files only" and "local files only"
+
+ * all views (setSelected()):
+ replaced highlightItem(item) with setSelected(item, bool) which makes
+ it more suitable and more consistent with Qt.
+ added selectionChanged() method (necessary for multiselection)
+
+ * tdefileview.*:
+ added invertSelection()
+
+ * tdefiledialog.cpp:
+ made it work with multiselection
+ added static methods for multiselection
+ added getOpenURL(), getOpenURLs and getSaveURL()
+
+ * kdiroperator.cpp (setSorting):
+ added setSorting() and sorting() to keep sorting when switching views
+ a few cosmetic and KAction changes
+
+Sun Feb 13 00:45:12 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefiledialog.cpp (completion):
+ small fix: completion and auto-directory following works also
+ without protocol-part in the location.
+
+Sat Feb 12 15:30:40 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefileview.h:
+ made setSorting() and sortReversed() virtual so that subclasses
+ can intercept that to show sorting order
+
+ * tdefiledetailview.cpp,h (setSortIndicator):
+ enable header-clicking again to set the sorting
+
+Fri Feb 11 12:17:59 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefiledialog.cpp (KFileDialog):
+ fixed filefilter not being applied in constructor
+
+Thu Feb 10 17:06:36 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * kdiroperator.cpp (connectView):
+ - Now that KToggleAction is fixed, I can commit the new stuff:
+ Offer Actions for all the common functionality, i.e. sorting, setting
+ the view, home(), cdUp(), back, forward, etc.
+ All actions are exposed through a QActionCollection
+
+ BTW, I'd really like to have a way to change the state of an action
+ without it calling the associated slot. For now I use blockSignals()
+ (thanks, Simon), but this sucks.
+
+ - renamed fileList to fileView (that was an old relic of KDE 1)
+
+ * tdefiledialog.*:
+ - make use of the new Actions and fill the toolbar again (up, back,
+ forward, reload, home).
+
+ - the combo in the toolbar is going to change, it does nothing now
+ (only shows the Root and Desktop dirs with a nice icon).
+
+Thu Feb 10 12:59:29 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * kdiroperator.cpp (insertNewFiles):
+ aahhh, finally fixed that infinite loop in KFileView::mergeLists
+ clear the view before calling view->addItemList( currentContents );
+
+ * tdefilereader.cpp (setURL):
+ don't disable dirWatch update (setAutoUpdate) when setting a remote URL
+
+Fri Feb 4 12:42:37 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefiledetailview.cpp (insertItem):
+ - don't let QListView sort the items
+ I disabled clicking at the headers for now, will fix that later
+ - don't flicker on mimetype-pixmap update
+
+Thu Feb 3 12:15:16 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefileview.h + all views where necessary
+ added selectAll()
+ added isSelected( const KFileViewItem * )
+ added const KFileViewItemList * selectedItems()
+ added const KFileViewItemList * items()
+
+ spiced up documentation of KFileView a bit
+
+Sun Jan 30 22:20:14 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefileviewitem.cpp (pixmap):
+ fixed some issues for different pixmap sizes
+
+ * tdefileiconview.{h,cpp} (setPixmapSize):
+ added configurability for different pixmap sizes
+
+Sun Jan 30 16:49:12 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefileview.h + all views:
+ A view can now have a name (setViewName() and viewName())
+ This is useful to differentiate views and to display the names in a
+ popupmenu for switching between views.
+
+Sun Jan 30 12:41:04 2000 Werner Trobin <wtrobin@carinthia.com>
+ The preview mode works again. It's very similar to the Qt-2.1 QFD
+ preview mode - but it's not totally the same. There are some rough
+ edges which have to be ironed out, but it works :)
+ For further information, see tdefilepreview.*
+ Note: kpreview and so on are obsolete (IMHO)
+
+Sat Jan 29 15:33:37 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ Time to add some changelogs again, all the recent hard work of the
+ restructuring is only in CVS-log...
+
+ * tdefileview.cpp (compareItems):
+ - added support to disable sorting directories first (QDir::DirsFirst)
+ - added support to sort by date and to sort reversed
+ - removed unused findCompletion method
+ - sort case insensitive by default
+ - some optimization for mergeList
+ - fixed infinite loop in mergeLists, when the lists are the same
+ (I think another one is still there, but I'm tired now)
+ - changed setSortMode stuff: Switching-mode replaced with
+ sortReversed(). The enum Switching will be removed, soon.
+ - made setSortMode public
+
+ * tdefileviewitem.cpp:
+ - added time_t mTime() to enable sorting by modification time
+
+ * kdiroperator.cpp:
+ - offer sorting options in popupmenu
+ - use checkAccess before creating directories. I guess this will again
+ change when the new kio will be used, tho.
+ - show progress widget at the bottom (otherwise the header of e.g.
+ the detail-view would be covered).
+ - Added LGPL copyright header
+
+ * tdefilewidget.cpp (connectSignals):
+ - connect to all signals of KDirOperator
+ - directly connect SIGNAL to SIGNAL -> removed slotFileHighlighted etc.
+ - fixed some sorting/merging bugs
+
+ * {tdefiledialog,kdiroperator}.{cpp,h};
+ - support for disabling chdir (some apps may not want KFileDialog /
+ KFileReader change the working directory under their feet)
+ - Added LGPL header in cpp-file
+
+ * tdefilereader.cpp (stat):
+ - fixed: some special files were recognized as directories
+
+ * kfstest.cpp:
+ - added test for KFileWidget (widget -> KFileWidget,
+ diroperator -> KDirOperator)
+
+Sun Oct 31 00:56:23 1999 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefileinfo.cpp (readUserInfo): Don't call getpwnam() and getgrgid()
+ all the time over and over again! This opens and parses /etc/passwd
+ or /etc/group with every call!
+ Now we load /etc/passwd and /etc/group once and store the interesting
+ stuff in static QMaps, which need to be freed with KFileInfo::cleanup()
+ cleanup() is called from KFileBaseDialog's destructor.
+
+ This speeds up KFileDialog a LOT!
+
+Sat Oct 23 01:55:00 1999 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefiledetaillist.cpp (key): hopefully implemented correct mapping
+ from KFileInfo to QListViewItem and back. I had a hard time convincing
+ QListView that KFileInfoContents knows best where to insert an item
+ Now the detaillist is even usable :)
+ Fixed a problem with selection and highlighting
+ Disable clicking on listview headers that can't be used for sorting
+
+ * tdefileinfocontents.cpp (setSorting): call insertItem() with a correct
+ (is it?) index, instead of -1
+
+Thu Oct 21 23:18:54 1999 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefiledialog.cpp (init): removed "[development only] from tooltip
+ (sorry to break the translations, but this HAD to go)
+
+ * don't update anything when leaving the configure-dialog with Cancel
+
+Wed Oct 20 15:07:16 1999 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefileinfo.cpp,h: implemented KFileInfo::filePath() and fixed
+ KFileInfo::absURL() not being set in some cases
+
+ * kdir.cpp: fixed a buglet in the path (double slashes)
+
+ * tdefiledetaillist.cpp (KFileDetailList): improved selecting files
+ (single click, double click, Return-key)
+ but the mapping from QListViewItem to KFileInfo is still quite broken
+
+1999-06-09 Woohyun JANG <louis@mizi.co.kr>
+
+ * kdir.cpp: used QString::local8Bit() instead of QString::ascii()
+ for file names and directory names.
+
+ * tdefiledialog.cpp: used QStringList instead of QStrIList.
+
+1999-01-14 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: fixed some GUI problems and moved all default
+ configurations into config-tdefile.h.
+ Changed some default values, so that users that never looked into
+ the config dialog gets a nice suprise with 1.1 ;-)
+
+ * tdefiledialog.cpp: changed selectedFile to return decoded path instead
+ of encoded one
+
+Thu Jan 7 23:14:39 1999 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefilesimpleview.cpp (keyPressEvent): fixed segfault on keypress,
+ when there were no files at all in the list
+
+1998-12-19 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: fixing an ugly bug when "." is used as argument
+
+Mon Dec 14 23:00:41 1998 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefilebookmark.cpp: renamed class KBookmark to KFileBookmark to
+ avoid problems with KFM's KBookmark class. Renamed bookmark.* to
+ tdefilebookmark.*, too and changed all occurrences of bookmark.* to
+ tdefilebookmark.* (especially all the .po-files)
+
+Wed Dec 2 15:59:13 1998 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ * tdefilesimpleview.cpp: Fixed some more keyboard navigation bugs.
+ Added method isColCompletelyVisible( int col ), now you can scroll
+ perfectly to make items completely visible.
+ Moreover, in resizeEvent() the number of columns was not calculated
+ correctly in a special case.
+ And the currently selected item is rehighlighted correctly after
+ resizing, now.
+
+1998-10-12 Jochen Küpper <jochen@uni-duesseldorf.de>
+
+ * tdefiledialog.cpp (okPressed): Changed okPressed to store the correct
+ filename before leaving the dialog.
+
+1998-06-07 Stephan Kulow <coolo@kde.org>
+
+ * tdefilesimpleview.cpp: added some checks to prevent division with
+ zero using the latest qt snapshots
+
+ * tdefilesimpleview.cpp: added a repaint call after a resize
+
+ * tdefiledialog.cpp: new experimental button order
+
+ * tdefiledialog.cpp: added lastDirectory to remember the last visited
+ directory for next open
+
+1998-05-24 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: use setSelection also for the initial filename
+ given
+
+ * tdefiledialog.cpp: introduced KFileFilter to make an abstraction
+ for the used filter widget. Currently only QComboBox is supported,
+ but this may change in the future
+
+1998-05-20 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: changed the accelerator for completion
+ to CTRL-T
+
+ * tdefiledialog.cpp: fixed the setSelection() feature
+
+1998-05-19 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.h: added setSelection
+
+1998-05-18 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: bugfixes
+
+1998-05-15 Stephan Kulow <coolo@kde.org>
+
+ * tdefileinfocontents.cpp: some more changes and speed ups
+ (caching and some other little things)
+
+1998-05-14 Stephan Kulow <coolo@kde.org>
+
+ * tdefileinfocontents.cpp: added addItemList
+
+ * tdefileinfocontents.h: introduced KFileInfoContentsSignaler
+
+ * tdefileinfocontents.cpp: some more speed improvment
+
+1998-05-10 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: tried to speed up the refresh
+
+1998-04-17 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledetaillist.cpp: implemented the date field
+
+ * tdefiledetaillist.cpp: made the columns wider
+
+ * tdefileinfocontents.cpp: use the new icons by Mark
+
+Thu Apr 16 10:51:24 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ * tdefiledialog.*: some small fixes concerning preview
+
+ * tdefileinfocontents.cpp: fixed sorting bug in preview
+
+ * tdefilepreview.*: small bug fixes
+
+ * kpreview.*: small bug fixes
+
+ * added some documentation
+
+1998-04-15 Stephan Kulow <coolo@kde.org>
+
+ * tdefilepreview.cpp: use a list box instead of simple view
+
+ * tdefiledialog.cpp: fixed an ugly bug
+
+1998-04-14 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialogconf.cpp: removed the width/height sliders
+
+ * tdefiledialog.cpp: save the width and height on exit
+
+ * tdefiledialogconf.cpp: added more guys to the about box
+
+ * tdefiledialog.h: removed init*Children. They were useless
+
+ * tdefiledialog.cpp: set the default size to a useful value
+
+Mon Apr 6 17:30:18 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ * tdefilepreview.*: restructured previewing, one can now easily
+ use custom previewers, dynamically
+
+ * kpreview.*: changes for allowing custom previewers, two previewers
+ are hardcoded so far
+
+ * tdefiledialog.*: changes changes for allowing custom previewers
+
+ * kfstest.cpp: changes to preview mode
+
+ * xview.*: QimageIO module allowing the visual-schnauzer generated
+ images to be loaded
+
+1998-04-06 Stephan Kulow <coolo@kde.org>
+
+ * debug.h: added debugC. An empty macro to hide debug output
+
+Thu Apr 2 19:39:37 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ * kpreview.*: widget which for now shows some info about a
+ file/folder along with the first 20-30 lines of it
+
+ * tdefilepreview.*: added a new view which has a preview of any text
+ file in the right part
+
+ * kfstest.cpp: added the new mode "preview" which shows the above
+ view
+
+1998-03-30 Stephan Kulow <coolo@kde.org>
+
+ * tdefilesimpleview.cpp: fixed highlightning
+
+ * tdefiledialog.cpp: some fixes for the dir selection
+
+ * tdefiledialog.h: Moved KFileDialog into KFileBaseDialog and made
+ KFileDialog and KDirDialog a derived class of KFileBaseDialog to
+ make this virtual functions work
+
+Mon Mar 30 17:53:20 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ * kcombiview.cpp: bug fixes for completion & corresponding
+ highlighting
+
+ * tdefiledialog.cpp: small bug fix, too much copying into location
+
+ * tdefileinfocontents.cpp: completion slightly remodeled, should
+ work in all views now
+
+ * tdefileinfocontents.h: changed nameList to case insensitive
+ list
+
+1998-03-28 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: changed the filter separator to \n.
+ This looks nicer in the source code of the call
+
+Sat Mar 28 14:49:00 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: changed the meaning of the dirName argument
+
+ * tdefiledialog.h: added getShowFilter
+
+Thu Mar 26 12:47:42 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefilesimpleview.cpp: improved scrolling in simple view
+
+ * tdefileinfocontents.cpp: add a / after a found dir
+
+ * tdefiledialog.cpp: fixed bug for !showFilter
+
+Wed Mar 25 18:39:09 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ * tdefileinfocontents.cpp: completion now working
+
+ * kcombiview.cpp: changed behavior for completion, it
+ now highlights completed directory and file
+
+Tue Mar 24 16:08:46 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ * tdefileinfocontents.cpp: sorting now fully working
+
+ * tdefiledialog.cpp: modifications for sorting in the on the
+ fly reconfiguration
+
+ * tdefileinfocontents.*: modification to the constructor
+ to pass along the sorting
+
+ * tdefiledetaillist.*: modification to the constructor
+ to pass along the sorting
+
+ * kcombiview.*: modification to the constructor
+ to pass along the sorting
+
+ * tdefilesimpleview.*: modification to the constructor
+ to pass along the sorting
+
+Tue Mar 24 10:45:15 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ * tdefileinfocontents.cpp: sorting fixed, the feature of keeping
+ directories grouped is still missing though
+
+Mon Mar 23 22:59:18 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledetaillist.h: added acceptsFiles() and acceptsDirs() to
+ make dirs-only views useful
+
+ * tdefileinfocontents.cpp: OK, completion is back again, but
+ currently not working, because the code is missing ;-)
+
+Mon Mar 23 00:08:02 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: moved all GM related things into initGUI() to
+ make recreation possible
+
+Sun Mar 22 00:22:46 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: use KShellProcess now
+
+ * tdefiledialog.h: added virtual function initFileList to made
+ KFileDialog customable
+
+ * tdefiledialog.cpp: show a combo box, in case more filters are given
+
+ * tdefiledialog.cpp: some bug fixes. I can't get the sorting to work
+
+ * Makefile.am: install some toolbar pixmaps
+
+ * tdefiledetailview.cpp: added pixmaps to the detail view
+
+ * Kfiledialog.cpp: made KComboView customable through virtual
+ functions
+
+ * kcombiview.cpp: took out the completion for now, added
+ kcombiview and some little changes in setCurrentItem
+
+ * kdirlistbox.cpp: fixed the use of single click
+
+ * kdir.h: moved the header files a little bit to remove
+ some dependencies
+
+ * kdirlistbox.cpp: KDirListBox is now a KFileInfoContents too
+
+ * tdefiledialog.cpp: another change in the API. It uses now QSignal.
+ I didn't liked the old way
+
+1998-03-21 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: implemented mixDirsAndFiles. Need some work and currently
+ only supported by the simple view
+
+Sat Mar 21 01:00:48 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefilesimpleview.cpp: added pixmaps to indicate access on the file
+
+ * tdefilesimpleview.cpp: improved keyboard navigation
+
+ * tdefilesimpleview.cpp: first almost working simple view
+
+ * tdefilesimpleview.cpp: started implementing a simple view. Needs
+ still some work
+
+
+Fri Mar 20 22:42:31 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefileinfocontents.h: bugfixes
+
+ * tdefileinfo.cpp: KFileInfo is no longer a derived class of
+ QFileInfo. This should reduce memory use too
+
+ * tdefileinfocontents.h: moved the actual sorting in
+ KFileInfoContents. Derived classes are for viewing only
+
+ * tdefiledialog.h: fixed some header files locations
+
+1998-03-20 Stephan Kulow <coolo@kde.org>
+
+ * tdefileinfo.cpp: show lockedfolder.xpm for folders, that are not
+ allowed to enter or read
+
+ * tdefiledialog.cpp: bug fixes
+
+Fri Mar 20 13:10:11 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ * kfilgdialog.*, remodeled the configuration dialog to reflect the
+ current possible settings
+ * tdefiledetailList.cpp: added the PageUp PageDown navigation
+
+1998-03-19 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: fixed the forward/back back reported by
+ Stefan Tafener
+
+1998-03-18 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: set the initial focus to the line edit
+
+ * tdefiledialog.cpp: use kapp->invokeHTMLHelp now
+
+ * tdefiledialog.h: removed treeList, since it's not implemented
+
+Wed Mar 18 02:56:32 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledetaillist.cpp: fixed sorting again
+
+1998-03-17 Stephan Kulow <coolo@kde.org>
+
+ * added a virtual class KInfoListContent to make an abstraction
+ for the file contents. Currently there is just one implementation
+ KFileDetailList
+
+1998-03-16 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: don't accept the first entry of the combo
+ box as a file name
+
+ * tdefiledialog.cpp: added an accelerator for completion, since
+ KCombo no longer emits such a thing (currently CTRL-A)
+
+ * kdir.cpp: disable parent button in /
+
+ * tdefiledialog.cpp: fixed layout of mkdir dialog
+
+ * kdir.cpp: use currentDir instead of homeDir as default
+
+ * tdefiledialog.cpp: added member acceptOnlyExisting and set it
+ for now to always false. I guess, we need an extra parameter for this
+
+ * tdefiledialog.cpp: changed dirList and fileList to fix the
+ focus handling
+
+ * tdefileinfolistwidget.cpp: added focus handling
+
+ * tdefileinfolistwidget.cpp: added keyevent handling to handle
+ cursor and enter
+
+ * tdefiledialog.cpp: changed the filter edit to a QLineEdit, since
+ we don't need the completion, but the tabing for focus changes
+
+Mon Mar 16 11:36:07 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ * added create directory, pops up a modal dialog, should add
+ a mkdir method to kdir in near future
+
+Mon Mar 16 20:04:00 1998 Martin Jones <mjones@kde.org>
+ * Added booktoken.* to remove dependancy on tdehtmlw and jscript
+
+Thu Mar 12 09:32:06 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ * worked on the dir and file completion, should do both now,
+ text in the location box will be added as much as possible
+ (right now it's the lowest denominator of dir&file&location-text)
+ * added sorting for the detailed list, so far only name and size
+ sorting implemented
+ * added single click selection for directories
+ * added a status line, which shows the number of directories and
+ files showed
+
+Thu Mar 12 00:36:05 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: made a library out of the file selector
+ * tdefiledialog.cpp: added an extra parameter acceptURLs to seperate
+ between getOpenFileName and getOpenFileURL
+
+Sun Feb 15 23:13:47 1998 Richard Moore <rich@kde.org>
+
+ * More work on the bookmarks - they should work properly now, you
+ must create the directory ~/.kde/share/apps/tdeui to store the
+ bookmarks in.
+
+ * Regenerated docs
+
+Thu Feb 12 17:27:51 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefileinfo.cpp: added determination of group and other things to
+ be display the correct values in the tdefileinfolistwidget
+
+Thu Feb 12 16:01:44 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: removed the #ifdef code. Now the combo box for
+ the path is the only option
+
+Tue Feb 10 01:09:16 1998 Richard Moore <rich@kde.org>
+
+ * Added details widget - this is currently selected by a config
+ file entry, but it there should be a toolbar button. Many changes
+ to tdefiledialog to allow the switch (need an abstract fileview class).
+
+Fri Feb 6 18:08:14 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: replaced the location lineedit with an combo
+ box. Currently configurable with a compiler define.
+
+Fri Feb 6 17:07:26 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: fixed the en- and decoding of URLs. Now it's
+ possible to move into directories called "sdasd#sdsd" for example
+
+Sat Jan 24 17:18:10 1998 Mario Weilguni <mweilguni@sime.com>
+
+ * fixed a bug in kdir.cpp/parsePermissions()
+
+ * implemented error handling for KFM URL errors
+
+Tue Jan 20 00:51:55 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: some fixes to make kfm support more robust
+
+Mon Jan 19 01:10:11 1998 Stephan Kulow <coolo@kde.org>
+
+ * kdir.cpp: re-added ftp support
+
+ * tdefiledialog.cpp: take care of the case, when the user enters a
+ complete filename
+
+ * kdir.cpp: added isReadable() to indicate, that the dir is not
+ correct
+
+ * tdefiledialog.cpp: played a little bit with the geometry management
+
+
+Sun Jan 18 15:00:06 1998 Stephan Kulow <coolo@kde.org>
+
+ * tdefiledialog.cpp: - back/forward work now as expected
+ - show the correct filter
+ - the combo box works now as expected
+
+ * kdir.cpp: check if the directory is correct (for local
+ files). If not, go back to the old value
+
+ * tdefiledialog.cpp: - disable parent button, when in root
+ - treat the case, that the URL ends with "/"
+ - strip white spaces out of the location text
+
+ * tdefileinfo.cpp: don't insert broken links
+
+ * tdefiledialog.cpp: just set the dir, if it's different
+ from the already set one
+
+Sun Jan 18 11:53:32 1998 Mario Weilguni <mweilguni@sime.com>
+
+ * symbolic links to subdirectories are now correctly reported as
+ directories
+
+ * symbolic links are show as italic text
+
+ * The toolbar button "Home" works now as expected
diff --git a/tdeio/tdefile/Makefile.am b/tdeio/tdefile/Makefile.am
new file mode 100644
index 000000000..ab8561e7c
--- /dev/null
+++ b/tdeio/tdefile/Makefile.am
@@ -0,0 +1,78 @@
+# This file is part of the KDE libraries
+# Copyright (C) 1997 Stephan Kulow (coolo@kde.org)
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this library; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+
+INCLUDES= -I$(srcdir)/../libltdl/ -I$(top_srcdir) -I$(top_srcdir)/tdefx \
+ -I$(top_builddir)/tdeio/tdeio -I$(top_srcdir)/tdeio/bookmarks $(all_includes) $(LIBART_CFLAGS)
+
+noinst_LTLIBRARIES = libtdefile.la
+
+METASOURCES = AUTO
+
+#SUBDIRS = . acl_prop_page
+
+include_HEADERS = tdefiledialog.h kencodingfiledialog.h\
+ kdiroperator.h tdefileview.h tdefilefiltercombo.h \
+ tdefiledetailview.h kcombiview.h kdiskfreesp.h \
+ tdefileiconview.h krecentdocument.h \
+ kurlrequester.h tdefilepreview.h tdefile.h \
+ kurlcombobox.h kurlrequesterdlg.h kopenwith.h kpropsdlg.h \
+ kicondialog.h kdirsize.h kpreviewwidgetbase.h kimagefilepreview.h tdefilesharedlg.h \
+ tdefiletreeview.h tdefiletreeviewitem.h tdefiletreebranch.h \
+ kdirselectdialog.h kurlbar.h kpropertiesdialog.h knotifydialog.h \
+ kcustommenueditor.h knotifywidgetbase.h
+
+noinst_HEADERS = config-tdefile.h krecentdirs.h kmetaprops.h \
+ tdefilebookmarkhandler.h tdefilemetainfowidget.h kopenwith_p.h \
+ tdefilespeedbar.h kpreviewprops.h kacleditwidget.h kacleditwidget_p.h images.h
+
+libtdefile_la_SOURCES = \
+ tdefilefiltercombo.cpp \
+ tdefileview.cpp tdefileiconview.cpp \
+ krecentdocument.cpp tdefiledialog.cpp kdiroperator.cpp \
+ tdefiledetailview.cpp kcombiview.cpp kurlrequester.cpp \
+ tdefilepreview.cpp kurlcombobox.cpp kurlrequesterdlg.cpp \
+ kopenwith.cpp kpropertiesdialog.cpp kicondialog.cpp kdirsize.cpp \
+ krecentdirs.cpp kdiskfreesp.cpp kimagefilepreview.cpp tdefilesharedlg.cpp \
+ kurlbar.cpp kmetaprops.cpp kpreviewprops.cpp \
+ tdefiletreeview.cpp tdefiletreeviewitem.cpp tdefiletreebranch.cpp \
+ kdirselectdialog.cpp tdefilebookmarkhandler.cpp \
+ tdefilemetainfowidget.cpp kcustommenueditor.cpp knotifywidgetbase.ui \
+ knotifydialog.cpp tdefilespeedbar.cpp kpreviewwidgetbase.cpp \
+ tdefilemetapreview.cpp kpropertiesdesktopbase.ui \
+ kpropertiesdesktopadvbase.ui kpropertiesmimetypebase.ui \
+ kencodingfiledialog.cpp kacleditwidget.cpp
+
+libtdefile_la_COMPILE_FIRST = $(srcdir)/../tdeio/kdirnotify_stub.h
+
+EXTRA_DIST = NOTES
+
+# convenience lib - no _LDFLAGS or _LIBADD !
+
+servicetype_DATA = kpropsdlgplugin.desktop
+servicetypedir = $(kde_servicetypesdir)
+
+
+#Can't be a module, we need to link to it for readConfig
+#kde_module_LTLIBRARIES = libtdefileshare.la
+#libtdefileshare_la_SOURCES = tdefileshare.cpp
+#libtdefileshare_la_LIBADD = libtdefile.la
+#libtdefileshare_la_LDFLAGS = -module $(KDE_PLUGIN)
+#kde_services_DATA = tdefilesharepropsplugin.desktop
+
+include $(top_srcdir)/admin/Doxyfile.am
diff --git a/tdeio/tdefile/NOTES b/tdeio/tdefile/NOTES
new file mode 100644
index 000000000..ad99065be
--- /dev/null
+++ b/tdeio/tdefile/NOTES
@@ -0,0 +1,100 @@
+Rewrite
+=======
+
+Here is the result of a long discussion between the tdefile developers
+(Carsten) and the konqueror developers (Simon and David), about the plans
+for more integration between tdefile and konqueror. 16/08/2000.
+
+
+
+ KDirLister -----(1)---------------------> KFileView (3)
+ <----(2)------ [Signaller] --- | |
+ | |
+ | |
+ | |
+ | |
+ KFileIconView KFileListView
+ (4) (5)
+
+
+(1) Gives items found when listing, and the key for each item
+ (KDirLister has all the sorting code)
+(2) KFileView inherited classes emit requests for listing a new
+ directory (with a bool for treeviews), and emit requests for
+ the mimetype of a given item. If all KFileView inherited classes
+ are QScrollViews, then it could even implement the "ask for mimetype
+ of the visible icons first" algorithm, currently in KonqIconView.
+(3) KFileView, the base class for any view, knows about KFileItem, has
+ signals for dropped(), popupMenu(list of actions provided by the view),
+ has a QWidget * canvas() method, xOffset() and yOffset()
+(4) KFileIconView holds a QPtrDict to look up a QIconViewItem quickly from a
+ given KFileItem. This will help for e.g. deleteItems and refreshItems.
+(5) KFileListView holds a QPtrDict to find the QListViewItem for a
+ KFileItem. It implements different modes if we want the tree view in
+ tdefile ?
+
+
+ KFileChooserWidget
+
+This (base) class is the container widget that can contain any tdefileview and
+switch between them. It is embeddable into an application that wants a widget
+for choosing a file or directory. Features listing, selecting, popupmenu for
+switching modes, and a virtual createView( viewmode ) method, which
+only knows about the builtin views, in this class.
+It knows the current URL, has setURL(), and triggers the listing, connecting
+KFileView's requests to KDirLister's methods.
+
+ KFileManagerWidget
+
+This class inherits from KFileChooserWidget and adds the file management
+operations. It uses a KFileOperations class (taken from the current
+KonqOperations) for all KIO operations, and it uses KFileUndo, taken from
+the KonqUndo stuff. The popupMenu method is reimplemented to add those
+operations to it.
+
+ KFileWidget
+
+This class is the full widget that can be seen in the dialog. It has the
+toolbar buttons, the combo, etc. It embeds a KFileChooserWidget or a
+KFileManagerWidget, the latter being a specialisation of the former.
+
+The Konqueror side of things
+============================
+
+ KonqFileIconView
+
+Inherits KFileIconView and adds image preview - unless we want it in
+KFileIconView, and the line-up-icons algorithm, etc.
+
+ KonqFileListView
+
+Inherits KFileListView to add more stuff if needed. The mc-like text view
+could be implemented here as well, unless we want it in tdefile. Same for the
+tree view.
+
+ KonqFileManagerWidget
+
+This class inherits KFileManagerWidget and adds the konqueror stuff, like
+the enableAction signal. It also reimplements createView to create the
+konqueror versions of the views.
+
+ KonqDirPart
+
+This class inherits KParts::ReadOnlyPart, and provides a BrowserExtension.
+It integrates KonqFileManagerWidget as its KParts widget, and provides
+KActions for it.
+
+Important :
+
+Make sure to take kfind into account. It would be nice if it could use the
+same views as konqueror, to have access to all the view modes, as well as
+image preview, etc.
+
+Unrelated:
+To Add
+======
+
+Mime Mappings?
+
+Filter= ( Mime Type | shell glob list )
+Mime Type -> shell glob list
diff --git a/kio/kfile/TODO b/tdeio/tdefile/TODO
index b7bf74ea5..b7bf74ea5 100644
--- a/kio/kfile/TODO
+++ b/tdeio/tdefile/TODO
diff --git a/tdeio/tdefile/config-tdefile.h b/tdeio/tdefile/config-tdefile.h
new file mode 100644
index 000000000..26a9ddb55
--- /dev/null
+++ b/tdeio/tdefile/config-tdefile.h
@@ -0,0 +1,32 @@
+#ifndef CONFIG_KFILE_H
+#define CONFIG_KFILE_H
+
+const int tdefile_area = 250;
+
+#define DefaultViewStyle TQString::fromLatin1("SimpleView")
+#define DefaultPannerPosition 40
+#define DefaultMixDirsAndFiles false
+#define DefaultShowStatusLine false
+#define DefaultShowHidden false
+#define DefaultCaseInsensitive true
+#define DefaultDirsFirst true
+#define DefaultSortReversed false
+#define DefaultRecentURLsNumber 15
+#define DefaultDirectoryFollowing true
+#define DefaultAutoSelectExtChecked true
+#define ConfigGroup TQString::fromLatin1("KFileDialog Settings")
+#define RecentURLs TQString::fromLatin1("Recent URLs")
+#define RecentFiles TQString::fromLatin1("Recent Files")
+#define RecentURLsNumber TQString::fromLatin1("Maximum of recent URLs")
+#define RecentFilesNumber TQString::fromLatin1("Maximum of recent files")
+#define DialogWidth TQString::fromLatin1("Width (%1)")
+#define DialogHeight TQString::fromLatin1("Height (%1)")
+#define ConfigShowStatusLine TQString::fromLatin1("ShowStatusLine")
+#define AutoDirectoryFollowing TQString::fromLatin1("Automatic directory following")
+#define PathComboCompletionMode TQString::fromLatin1("PathCombo Completionmode")
+#define LocationComboCompletionMode TQString::fromLatin1("LocationCombo Completionmode")
+#define ShowSpeedbar TQString::fromLatin1("Show Speedbar")
+#define ShowBookmarks TQString::fromLatin1("Show Bookmarks")
+#define AutoSelectExtChecked TQString::fromLatin1("Automatically select filename extension")
+
+#endif
diff --git a/kio/kfile/images.h b/tdeio/tdefile/images.h
index f544e2f0a..f544e2f0a 100644
--- a/kio/kfile/images.h
+++ b/tdeio/tdefile/images.h
diff --git a/tdeio/tdefile/kacleditwidget.cpp b/tdeio/tdefile/kacleditwidget.cpp
new file mode 100644
index 000000000..94ee0d4c4
--- /dev/null
+++ b/tdeio/tdefile/kacleditwidget.cpp
@@ -0,0 +1,1054 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Sean Harmer <sh@rama.homelinux.org> *
+ * Till Adam <adam@kde.org> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU Library 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., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+
+
+#include "kacleditwidget.h"
+#include "kacleditwidget_p.h"
+
+#ifdef USE_POSIX_ACL
+
+#include <tqpainter.h>
+#include <tqptrlist.h>
+#include <tqvbox.h>
+#include <tqhbox.h>
+#include <tqpushbutton.h>
+#include <tqvbuttongroup.h>
+#include <tqradiobutton.h>
+#include <tqcombobox.h>
+#include <tqlabel.h>
+#include <tqcheckbox.h>
+#include <tqlayout.h>
+#include <tqwidgetstack.h>
+#include <tqheader.h>
+
+#include <klocale.h>
+#include <tdefileitem.h>
+#include <kdebug.h>
+#include <kdialog.h>
+#include <kdialogbase.h>
+
+#ifdef HAVE_ACL_LIBACL_H
+# include <acl/libacl.h>
+#endif
+extern "C" {
+#include <pwd.h>
+#include <grp.h>
+}
+#include <assert.h>
+
+#include "images.h"
+
+static struct {
+ const char* label;
+ const char* pixmapName;
+ TQPixmap* pixmap;
+} s_itemAttributes[] = {
+ { I18N_NOOP( "Owner" ), "user-grey", 0 },
+ { I18N_NOOP( "Owning Group" ), "group-grey", 0 },
+ { I18N_NOOP( "Others" ), "others-grey", 0 },
+ { I18N_NOOP( "Mask" ), "mask", 0 },
+ { I18N_NOOP( "Named User" ), "user", 0 },
+ { I18N_NOOP( "Named Group" ), "group", 0 },
+};
+
+KACLEditWidget::KACLEditWidget( TQWidget *parent, const char *name )
+ :TQWidget( parent, name )
+{
+ TQHBox *hbox = new TQHBox( parent );
+ hbox->setSpacing( KDialog::spacingHint() );
+ m_listView = new KACLListView( hbox, "acl_listview" );
+ connect( m_listView, TQT_SIGNAL( selectionChanged() ),
+ this, TQT_SLOT( slotUpdateButtons() ) );
+ TQVBox *vbox = new TQVBox( hbox );
+ vbox->setSpacing( KDialog::spacingHint() );
+ m_AddBtn = new TQPushButton( i18n( "Add Entry..." ), vbox, "add_entry_button" );
+ connect( m_AddBtn, TQT_SIGNAL( clicked() ), m_listView, TQT_SLOT( slotAddEntry() ) );
+ m_EditBtn = new TQPushButton( i18n( "Edit Entry..." ), vbox, "edit_entry_button" );
+ connect( m_EditBtn, TQT_SIGNAL( clicked() ), m_listView, TQT_SLOT( slotEditEntry() ) );
+ m_DelBtn = new TQPushButton( i18n( "Delete Entry" ), vbox, "delete_entry_button" );
+ connect( m_DelBtn, TQT_SIGNAL( clicked() ), m_listView, TQT_SLOT( slotRemoveEntry() ) );
+ TQWidget *spacer = new TQWidget( vbox );
+ spacer->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::Expanding );
+ slotUpdateButtons();
+}
+
+void KACLEditWidget::slotUpdateButtons()
+{
+ bool atLeastOneIsNotDeletable = false;
+ bool atLeastOneIsNotAllowedToChangeType = false;
+ int selectedCount = 0;
+ TQListViewItemIterator it( m_listView, TQListViewItemIterator::Selected );
+ while ( KACLListViewItem *item = dynamic_cast<KACLListViewItem*>( it.current() ) ) {
+ ++it; ++selectedCount;
+ if ( !item->isDeletable() )
+ atLeastOneIsNotDeletable = true;
+ if ( !item->isAllowedToChangeType() )
+ atLeastOneIsNotAllowedToChangeType = true;
+ }
+ m_EditBtn->setEnabled( selectedCount && !atLeastOneIsNotAllowedToChangeType );
+ m_DelBtn->setEnabled( selectedCount && !atLeastOneIsNotDeletable );
+}
+
+KACL KACLEditWidget::getACL() const
+{
+ return m_listView->getACL();
+}
+
+KACL KACLEditWidget::getDefaultACL() const
+{
+ return m_listView->getDefaultACL();
+}
+
+void KACLEditWidget::setACL( const KACL &acl )
+{
+ return m_listView->setACL( acl );
+}
+
+void KACLEditWidget::setDefaultACL( const KACL &acl )
+{
+ return m_listView->setDefaultACL( acl );
+}
+
+void KACLEditWidget::setAllowDefaults( bool value )
+{
+ m_listView->setAllowDefaults( value );
+}
+
+void KACLEditWidget::setReadOnly( bool on )
+{
+ m_listView->setEnabled( !on );
+ m_AddBtn->setEnabled( !on );
+ if ( !on )
+ slotUpdateButtons();
+}
+
+KACLListViewItem::KACLListViewItem( TQListView* parent,
+ KACLListView::EntryType _type,
+ unsigned short _value, bool defaults,
+ const TQString& _qualifier )
+ : KListViewItem( parent, parent->lastItem() ), // we want to append
+ type( _type ), value( _value ), isDefault( defaults ),
+ qualifier( _qualifier ), isPartial( false )
+{
+ m_pACLListView = dynamic_cast<KACLListView*>( parent );
+ repaint();
+}
+
+
+KACLListViewItem::~ KACLListViewItem()
+{
+
+}
+
+TQString KACLListViewItem::key( int, bool ) const
+{
+ TQString key;
+ if ( !isDefault )
+ key = "A";
+ else
+ key = "B";
+ switch ( type )
+ {
+ case KACLListView::User:
+ key += "A";
+ break;
+ case KACLListView::Group:
+ key += "B";
+ break;
+ case KACLListView::Others:
+ key += "C";
+ break;
+ case KACLListView::Mask:
+ key += "D";
+ break;
+ case KACLListView::NamedUser:
+ key += "E" + text( 1 );
+ break;
+ case KACLListView::NamedGroup:
+ key += "F" + text( 1 );
+ break;
+ default:
+ key += text( 0 );
+ break;
+ }
+ return key;
+}
+
+void KACLListViewItem::paintCell( TQPainter* p, const TQColorGroup &cg,
+ int column, int width, int alignment )
+{
+ TQColorGroup mycg = cg;
+ if ( isDefault ) {
+ mycg.setColor( TQColorGroup::Text, TQColor( 0, 0, 255 ) );
+ }
+ if ( isPartial ) {
+ TQFont font = p->font();
+ font.setItalic( true );
+ mycg.setColor( TQColorGroup::Text, TQColor( 100, 100, 100 ) );
+ p->setFont( font );
+ }
+ KListViewItem::paintCell( p, mycg, column, width, alignment );
+
+ KACLListViewItem *below =0;
+ if ( itemBelow() )
+ below = static_cast<KACLListViewItem*>( itemBelow() );
+ const bool lastUser = type == KACLListView::NamedUser && below && below->type == KACLListView::NamedGroup;
+ const bool lastNonDefault = !isDefault && below && below->isDefault;
+ if ( type == KACLListView::Mask || lastUser || lastNonDefault )
+ {
+ p->setPen( TQPen( Qt::gray, 0, TQPen::DotLine ) );
+ if ( type == KACLListView::Mask )
+ p->drawLine( 0, 0, width - 1, 0 );
+ p->drawLine( 0, height() - 1, width - 1, height() - 1 );
+ }
+}
+
+
+void KACLListViewItem::updatePermPixmaps()
+{
+ unsigned int partialPerms = value;
+
+ if ( value & ACL_READ )
+ setPixmap( 2, m_pACLListView->getYesPixmap() );
+ else if ( partialPerms & ACL_READ )
+ setPixmap( 2, m_pACLListView->getYesPartialPixmap() );
+ else
+ setPixmap( 2, TQPixmap() );
+
+ if ( value & ACL_WRITE )
+ setPixmap( 3, m_pACLListView->getYesPixmap() );
+ else if ( partialPerms & ACL_WRITE )
+ setPixmap( 3, m_pACLListView->getYesPartialPixmap() );
+ else
+ setPixmap( 3, TQPixmap() );
+
+ if ( value & ACL_EXECUTE )
+ setPixmap( 4, m_pACLListView->getYesPixmap() );
+ else if ( partialPerms & ACL_EXECUTE )
+ setPixmap( 4, m_pACLListView->getYesPartialPixmap() );
+ else
+ setPixmap( 4, TQPixmap() );
+}
+
+void KACLListViewItem::repaint()
+{
+ int idx = 0;
+ switch ( type )
+ {
+ case KACLListView::User:
+ idx = KACLListView::OWNER_IDX;
+ break;
+ case KACLListView::Group:
+ idx = KACLListView::GROUP_IDX;
+ break;
+ case KACLListView::Others:
+ idx = KACLListView::OTHERS_IDX;
+ break;
+ case KACLListView::Mask:
+ idx = KACLListView::MASK_IDX;
+ break;
+ case KACLListView::NamedUser:
+ idx = KACLListView::NAMED_USER_IDX;
+ break;
+ case KACLListView::NamedGroup:
+ idx = KACLListView::NAMED_GROUP_IDX;
+ break;
+ default:
+ idx = KACLListView::OWNER_IDX;
+ break;
+ }
+ setText( 0, i18n(s_itemAttributes[idx].label) );
+ setPixmap( 0, *s_itemAttributes[idx].pixmap );
+ if ( isDefault )
+ setText( 0, text( 0 ) + i18n( " (Default)" ) );
+ setText( 1, qualifier );
+ // Set the pixmaps for which of the perms are set
+ updatePermPixmaps();
+}
+
+void KACLListViewItem::calcEffectiveRights()
+{
+ TQString strEffective = TQString( "---" );
+
+ // Do we need to worry about the mask entry? It applies to named users,
+ // owning group, and named groups
+ if ( m_pACLListView->hasMaskEntry()
+ && ( type == KACLListView::NamedUser
+ || type == KACLListView::Group
+ || type == KACLListView::NamedGroup )
+ && !isDefault )
+ {
+
+ strEffective[0] = ( m_pACLListView->maskPermissions() & value & ACL_READ ) ? 'r' : '-';
+ strEffective[1] = ( m_pACLListView->maskPermissions() & value & ACL_WRITE ) ? 'w' : '-';
+ strEffective[2] = ( m_pACLListView->maskPermissions() & value & ACL_EXECUTE ) ? 'x' : '-';
+/*
+ // What about any partial perms?
+ if ( maskPerms & partialPerms & ACL_READ || // Partial perms on entry
+ maskPartialPerms & perms & ACL_READ || // Partial perms on mask
+ maskPartialPerms & partialPerms & ACL_READ ) // Partial perms on mask and entry
+ strEffective[0] = 'R';
+ if ( maskPerms & partialPerms & ACL_WRITE || // Partial perms on entry
+ maskPartialPerms & perms & ACL_WRITE || // Partial perms on mask
+ maskPartialPerms & partialPerms & ACL_WRITE ) // Partial perms on mask and entry
+ strEffective[1] = 'W';
+ if ( maskPerms & partialPerms & ACL_EXECUTE || // Partial perms on entry
+ maskPartialPerms & perms & ACL_EXECUTE || // Partial perms on mask
+ maskPartialPerms & partialPerms & ACL_EXECUTE ) // Partial perms on mask and entry
+ strEffective[2] = 'X';
+*/
+ }
+ else
+ {
+ // No, the effective value are just the value in this entry
+ strEffective[0] = ( value & ACL_READ ) ? 'r' : '-';
+ strEffective[1] = ( value & ACL_WRITE ) ? 'w' : '-';
+ strEffective[2] = ( value & ACL_EXECUTE ) ? 'x' : '-';
+
+ /*
+ // What about any partial perms?
+ if ( partialPerms & ACL_READ )
+ strEffective[0] = 'R';
+ if ( partialPerms & ACL_WRITE )
+ strEffective[1] = 'W';
+ if ( partialPerms & ACL_EXECUTE )
+ strEffective[2] = 'X';
+ */
+ }
+ setText( 5, strEffective );
+}
+
+bool KACLListViewItem::isDeletable() const
+{
+ bool isMaskAndDeletable = false;
+ if (type == KACLListView::Mask ) {
+ if ( !isDefault && m_pACLListView->maskCanBeDeleted() )
+ isMaskAndDeletable = true;
+ else if ( isDefault && m_pACLListView->defaultMaskCanBeDeleted() )
+ isMaskAndDeletable = true;
+ }
+ return type != KACLListView::User &&
+ type != KACLListView::Group &&
+ type != KACLListView::Others &&
+ ( type != KACLListView::Mask || isMaskAndDeletable );
+}
+
+bool KACLListViewItem::isAllowedToChangeType() const
+{
+ return type != KACLListView::User &&
+ type != KACLListView::Group &&
+ type != KACLListView::Others &&
+ type != KACLListView::Mask;
+}
+
+void KACLListViewItem::togglePerm( acl_perm_t perm )
+{
+ value ^= perm; // Toggle the perm
+ if ( type == KACLListView::Mask && !isDefault ) {
+ m_pACLListView->setMaskPermissions( value );
+ }
+ calcEffectiveRights();
+ updatePermPixmaps();
+/*
+ // If the perm is in the partial perms then remove it. i.e. Once
+ // a user changes a partial perm it then applies to all selected files.
+ if ( m_pEntry->m_partialPerms & perm )
+ m_pEntry->m_partialPerms ^= perm;
+
+ m_pEntry->setPartialEntry( false );
+ // Make sure that all entries have their effective rights calculated if
+ // we are changing the ACL_MASK entry.
+ if ( type == Mask )
+ {
+ m_pACLListView->setMaskPartialPermissions( m_pEntry->m_partialPerms );
+ m_pACLListView->setMaskPermissions( value );
+ m_pACLListView->calculateEffectiveRights();
+ }
+*/
+}
+
+
+
+EditACLEntryDialog::EditACLEntryDialog( KACLListView *listView, KACLListViewItem *item,
+ const TQStringList &users,
+ const TQStringList &groups,
+ const TQStringList &defaultUsers,
+ const TQStringList &defaultGroups,
+ int allowedTypes, int allowedDefaultTypes,
+ bool allowDefaults )
+ : KDialogBase( listView, "edit_entry_dialog", true,
+ i18n( "Edit ACL Entry" ), KDialogBase::Ok|KDialogBase::Cancel,
+ KDialogBase::Ok, false ),
+ m_listView( listView ), m_item( item ), m_users( users ), m_groups( groups ),
+ m_defaultUsers( defaultUsers ), m_defaultGroups( defaultGroups ),
+ m_allowedTypes( allowedTypes ), m_allowedDefaultTypes( allowedDefaultTypes ),
+ m_defaultCB( 0 )
+{
+ TQWidget *page = new TQWidget( this );
+ setMainWidget( page );
+ TQVBoxLayout *mainLayout = new TQVBoxLayout( page, 0, spacingHint(), "mainLayout" );
+ m_buttonGroup = new TQVButtonGroup( i18n("Entry Type"), page, "bg" );
+
+ if ( allowDefaults ) {
+ m_defaultCB = new TQCheckBox( i18n("Default for new files in this folder"), page, "defaultCB" );
+ mainLayout->addWidget( m_defaultCB );
+ connect( m_defaultCB, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SLOT( slotUpdateAllowedUsersAndGroups() ) );
+ connect( m_defaultCB, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SLOT( slotUpdateAllowedTypes() ) );
+
+ }
+
+ mainLayout->addWidget( m_buttonGroup );
+
+ TQRadioButton *ownerType = new TQRadioButton( i18n("Owner"), m_buttonGroup, "ownerType" );
+ m_buttonGroup->insert( ownerType, KACLListView::User );
+ TQRadioButton *owningGroupType = new TQRadioButton( i18n("Owning Group"), m_buttonGroup, "owningGroupType" );
+ m_buttonGroup->insert( owningGroupType, KACLListView::Group );
+ TQRadioButton *othersType = new TQRadioButton( i18n("Others"), m_buttonGroup, "othersType" );
+ m_buttonGroup->insert( othersType, KACLListView::Others );
+ TQRadioButton *maskType = new TQRadioButton( i18n("Mask"), m_buttonGroup, "maskType" );
+ m_buttonGroup->insert( maskType, KACLListView::Mask );
+ TQRadioButton *namedUserType = new TQRadioButton( i18n("Named User"), m_buttonGroup, "namesUserType" );
+ m_buttonGroup->insert( namedUserType, KACLListView::NamedUser );
+ TQRadioButton *namedGroupType = new TQRadioButton( i18n("Named Group"), m_buttonGroup, "namedGroupType" );
+ m_buttonGroup->insert( namedGroupType, KACLListView::NamedGroup );
+
+ connect( m_buttonGroup, TQT_SIGNAL( clicked( int ) ),
+ this, TQT_SLOT( slotSelectionChanged( int ) ) );
+
+ m_widgetStack = new TQWidgetStack( page );
+ mainLayout->addWidget( m_widgetStack );
+
+ TQHBox *usersBox = new TQHBox( m_widgetStack );
+ m_widgetStack->addWidget( usersBox, KACLListView::NamedUser );
+
+ TQHBox *groupsBox = new TQHBox( m_widgetStack );
+ m_widgetStack->addWidget( groupsBox, KACLListView::NamedGroup );
+
+ TQLabel *usersLabel = new TQLabel( i18n( "User: " ), usersBox );
+ m_usersCombo = new TQComboBox( false, usersBox, "users" );
+ usersLabel->setBuddy( m_usersCombo );
+
+ TQLabel *groupsLabel = new TQLabel( i18n( "Group: " ), groupsBox );
+ m_groupsCombo = new TQComboBox( false, groupsBox, "groups" );
+ groupsLabel->setBuddy( m_groupsCombo );
+
+ if ( m_item ) {
+ m_buttonGroup->setButton( m_item->type );
+ if ( m_defaultCB )
+ m_defaultCB->setChecked( m_item->isDefault );
+ slotUpdateAllowedTypes();
+ slotSelectionChanged( m_item->type );
+ slotUpdateAllowedUsersAndGroups();
+ if ( m_item->type == KACLListView::NamedUser ) {
+ m_usersCombo->setCurrentText( m_item->qualifier );
+ } else if ( m_item->type == KACLListView::NamedGroup ) {
+ m_groupsCombo->setCurrentText( m_item->qualifier );
+ }
+ } else {
+ // new entry, preselect "named user", arguably the most common one
+ m_buttonGroup->setButton( KACLListView::NamedUser );
+ slotUpdateAllowedTypes();
+ slotSelectionChanged( KACLListView::NamedUser );
+ slotUpdateAllowedUsersAndGroups();
+ }
+ incInitialSize( TQSize( 100, 0 ) );
+}
+
+void EditACLEntryDialog::slotUpdateAllowedTypes()
+{
+ int allowedTypes = m_allowedTypes;
+ if ( m_defaultCB && m_defaultCB->isChecked() ) {
+ allowedTypes = m_allowedDefaultTypes;
+ }
+ for ( int i=1; i < KACLListView::AllTypes; i=i*2 ) {
+ if ( allowedTypes & i )
+ m_buttonGroup->find( i )->show();
+ else
+ m_buttonGroup->find( i )->hide();
+ }
+}
+
+void EditACLEntryDialog::slotUpdateAllowedUsersAndGroups()
+{
+ const TQString oldUser = m_usersCombo->currentText();
+ const TQString oldGroup = m_groupsCombo->currentText();
+ m_usersCombo->clear();
+ m_groupsCombo->clear();
+ if ( m_defaultCB && m_defaultCB->isChecked() ) {
+ m_usersCombo->insertStringList( m_defaultUsers );
+ if ( m_defaultUsers.find( oldUser ) != m_defaultUsers.end() )
+ m_usersCombo->setCurrentText( oldUser );
+ m_groupsCombo->insertStringList( m_defaultGroups );
+ if ( m_defaultGroups.find( oldGroup ) != m_defaultGroups.end() )
+ m_groupsCombo->setCurrentText( oldGroup );
+ } else {
+ m_usersCombo->insertStringList( m_users );
+ if ( m_users.find( oldUser ) != m_users.end() )
+ m_usersCombo->setCurrentText( oldUser );
+ m_groupsCombo->insertStringList( m_groups );
+ if ( m_groups.find( oldGroup ) != m_groups.end() )
+ m_groupsCombo->setCurrentText( oldGroup );
+ }
+}
+void EditACLEntryDialog::slotOk()
+{
+ KACLListView::EntryType type = static_cast<KACLListView::EntryType>( m_buttonGroup->selectedId() );
+
+ TQString qualifier;
+ if ( type == KACLListView::NamedUser )
+ qualifier = m_usersCombo->currentText();
+ if ( type == KACLListView::NamedGroup )
+ qualifier = m_groupsCombo->currentText();
+
+ if ( !m_item ) {
+ m_item = new KACLListViewItem( m_listView, type, ACL_READ | ACL_WRITE | ACL_EXECUTE, false, qualifier );
+ } else {
+ m_item->type = type;
+ m_item->qualifier = qualifier;
+ }
+ if ( m_defaultCB )
+ m_item->isDefault = m_defaultCB->isChecked();
+ m_item->repaint();
+
+ KDialogBase::slotOk();
+}
+
+void EditACLEntryDialog::slotSelectionChanged( int id )
+{
+ switch ( id ) {
+ case KACLListView::User:
+ case KACLListView::Group:
+ case KACLListView::Others:
+ case KACLListView::Mask:
+ m_widgetStack->setEnabled( false );
+ break;
+ case KACLListView::NamedUser:
+ m_widgetStack->setEnabled( true );
+ m_widgetStack->raiseWidget( KACLListView::NamedUser );
+ break;
+ case KACLListView::NamedGroup:
+ m_widgetStack->setEnabled( true );
+ m_widgetStack->raiseWidget( KACLListView::NamedGroup );
+ break;
+ default:
+ break;
+ }
+}
+
+
+KACLListView::KACLListView( TQWidget* parent, const char* name )
+ : KListView( parent, name ),
+ m_hasMask( false ), m_allowDefaults( false )
+{
+ // Add the columns
+ addColumn( i18n( "Type" ) );
+ addColumn( i18n( "Name" ) );
+ addColumn( i18n( "read permission", "r" ) );
+ addColumn( i18n( "write permission", "w" ) );
+ addColumn( i18n( "execute permission", "x" ) );
+ addColumn( i18n( "Effective" ) );
+
+ header()->setClickEnabled( false );
+
+ // Load the avatars
+ for ( int i=0; i < LAST_IDX; ++i ) {
+ s_itemAttributes[i].pixmap = new TQPixmap( qembed_findImage( s_itemAttributes[i].pixmapName ) );
+ }
+ m_yesPixmap = new TQPixmap( qembed_findImage( "yes" ) );
+ m_yesPartialPixmap = new TQPixmap( qembed_findImage( "yespartial" ) );
+
+ setSelectionMode( TQListView::Extended );
+
+ // fill the lists of all legal users and groups
+ struct passwd *user = 0;
+ setpwent();
+ while ( ( user = getpwent() ) != 0 ) {
+ m_allUsers << TQString::fromLatin1( user->pw_name );
+ }
+ endpwent();
+
+ struct group *gr = 0;
+ setgrent();
+ while ( ( gr = getgrent() ) != 0 ) {
+ m_allGroups << TQString::fromLatin1( gr->gr_name );
+ }
+ endgrent();
+ m_allUsers.sort();
+ m_allGroups.sort();
+}
+
+
+KACLListView::~KACLListView()
+{
+ for ( int i=0; i < LAST_IDX; ++i ) {
+ delete s_itemAttributes[i].pixmap;
+ }
+ delete m_yesPixmap;
+ delete m_yesPartialPixmap;
+}
+
+TQStringList KACLListView::allowedUsers( bool defaults, KACLListViewItem *allowedItem )
+{
+ TQStringList allowedUsers = m_allUsers;
+ TQListViewItemIterator it( this );
+ while ( it.current() ) {
+ const KACLListViewItem *item = static_cast<const KACLListViewItem*>( *it );
+ ++it;
+ if ( !item->type == NamedUser || item->isDefault != defaults ) continue;
+ if ( allowedItem && item == allowedItem && allowedItem->isDefault == defaults ) continue;
+ allowedUsers.remove( item->qualifier );
+ }
+ return allowedUsers;
+}
+
+TQStringList KACLListView::allowedGroups( bool defaults, KACLListViewItem *allowedItem )
+{
+ TQStringList allowedGroups = m_allGroups;
+ TQListViewItemIterator it( this );
+ while ( it.current() ) {
+ const KACLListViewItem *item = static_cast<const KACLListViewItem*>( *it );
+ ++it;
+ if ( !item->type == NamedGroup || item->isDefault != defaults ) continue;
+ if ( allowedItem && item == allowedItem && allowedItem->isDefault == defaults ) continue;
+ allowedGroups.remove( item->qualifier );
+ }
+ return allowedGroups;
+}
+
+void KACLListView::fillItemsFromACL( const KACL &pACL, bool defaults )
+{
+ // clear out old entries of that ilk
+ TQListViewItemIterator it( this );
+ while ( KACLListViewItem *item = static_cast<KACLListViewItem*>( it.current() ) ) {
+ ++it;
+ if ( item->isDefault == defaults )
+ delete item;
+ }
+ KACLListViewItem *item =
+ new KACLListViewItem( this, User, pACL.ownerPermissions(), defaults );
+
+ item = new KACLListViewItem( this, Group, pACL.owningGroupPermissions(), defaults );
+
+ item = new KACLListViewItem( this, Others, pACL.othersPermissions(), defaults );
+
+ bool hasMask = false;
+ unsigned short mask = pACL.maskPermissions( hasMask );
+ if ( hasMask ) {
+ item = new KACLListViewItem( this, Mask, mask, defaults );
+ }
+
+ // read all named user entries
+ const ACLUserPermissionsList &userList = pACL.allUserPermissions();
+ ACLUserPermissionsConstIterator itu = userList.begin();
+ while ( itu != userList.end() ) {
+ new KACLListViewItem( this, NamedUser, (*itu).second, defaults, (*itu).first );
+ ++itu;
+ }
+
+ // and now all named groups
+ const ACLUserPermissionsList &groupList = pACL.allGroupPermissions();
+ ACLUserPermissionsConstIterator itg = groupList.begin();
+ while ( itg != groupList.end() ) {
+ new KACLListViewItem( this, NamedGroup, (*itg).second, defaults, (*itg).first );
+ ++itg;
+ }
+}
+
+void KACLListView::setACL( const KACL &acl )
+{
+ if ( !acl.isValid() ) return;
+ // Remove any entries left over from displaying a previous ACL
+ m_ACL = acl;
+ fillItemsFromACL( m_ACL );
+
+ m_mask = acl.maskPermissions( m_hasMask );
+ calculateEffectiveRights();
+}
+
+void KACLListView::setDefaultACL( const KACL &acl )
+{
+ if ( !acl.isValid() ) return;
+ m_defaultACL = acl;
+ fillItemsFromACL( m_defaultACL, true );
+ calculateEffectiveRights();
+}
+
+KACL KACLListView::itemsToACL( bool defaults ) const
+{
+ KACL newACL( 0 );
+ bool atLeastOneEntry = false;
+ ACLUserPermissionsList users;
+ ACLGroupPermissionsList groups;
+ TQListViewItemIterator it( const_cast<KACLListView*>( this ) );
+ while ( TQListViewItem* qlvi = it.current() ) {
+ ++it;
+ const KACLListViewItem* item = static_cast<KACLListViewItem*>( qlvi );
+ if ( item->isDefault != defaults ) continue;
+ atLeastOneEntry = true;
+ switch ( item->type ) {
+ case User:
+ newACL.setOwnerPermissions( item->value );
+ break;
+ case Group:
+ newACL.setOwningGroupPermissions( item->value );
+ break;
+ case Others:
+ newACL.setOthersPermissions( item->value );
+ break;
+ case Mask:
+ newACL.setMaskPermissions( item->value );
+ break;
+ case NamedUser:
+ users.append( qMakePair( item->text( 1 ), item->value ) );
+ break;
+ case NamedGroup:
+ groups.append( qMakePair( item->text( 1 ), item->value ) );
+ break;
+ default:
+ break;
+ }
+ }
+ if ( atLeastOneEntry ) {
+ newACL.setAllUserPermissions( users );
+ newACL.setAllGroupPermissions( groups );
+ if ( newACL.isValid() )
+ return newACL;
+ }
+ return KACL();
+}
+
+KACL KACLListView::getACL()
+{
+ return itemsToACL( false );
+}
+
+
+KACL KACLListView::getDefaultACL()
+{
+ return itemsToACL( true );
+}
+
+void KACLListView::contentsMousePressEvent( TQMouseEvent * e )
+{
+ TQListViewItem *clickedItem = itemAt( contentsToViewport( e->pos() ) );
+ if ( !clickedItem ) return;
+ // if the click is on an as yet unselected item, select it first
+ if ( !clickedItem->isSelected() )
+ KListView::contentsMousePressEvent( e );
+
+ if ( !currentItem() ) return;
+ int column = header()->sectionAt( e->x() );
+ acl_perm_t perm;
+ switch ( column )
+ {
+ case 2:
+ perm = ACL_READ;
+ break;
+ case 3:
+ perm = ACL_WRITE;
+ break;
+ case 4:
+ perm = ACL_EXECUTE;
+ break;
+ default:
+ return KListView::contentsMousePressEvent( e );
+ }
+ KACLListViewItem* referenceItem = static_cast<KACLListViewItem*>( clickedItem );
+ unsigned short referenceHadItSet = referenceItem->value & perm;
+ TQListViewItemIterator it( this );
+ while ( KACLListViewItem* item = static_cast<KACLListViewItem*>( it.current() ) ) {
+ ++it;
+ if ( !item->isSelected() ) continue;
+ // toggle those with the same value as the clicked item, leave the others
+ if ( referenceHadItSet == ( item->value & perm ) )
+ item->togglePerm( perm );
+ }
+}
+
+void KACLListView::entryClicked( TQListViewItem* pItem, const TQPoint& /*pt*/, int col )
+{
+ if ( !pItem ) return;
+
+ TQListViewItemIterator it( this );
+ while ( KACLListViewItem* item = static_cast<KACLListViewItem*>( it.current() ) ) {
+ ++it;
+ if ( !item->isSelected() ) continue;
+ switch ( col )
+ {
+ case 2:
+ item->togglePerm( ACL_READ );
+ break;
+ case 3:
+ item->togglePerm( ACL_WRITE );
+ break;
+ case 4:
+ item->togglePerm( ACL_EXECUTE );
+ break;
+
+ default:
+ ; // Do nothing
+ }
+ }
+ /*
+ // Has the user changed one of the required entries in a default ACL?
+ if ( m_pACL->aclType() == ACL_TYPE_DEFAULT &&
+ ( col == 2 || col == 3 || col == 4 ) &&
+ ( pACLItem->entryType() == ACL_USER_OBJ ||
+ pACLItem->entryType() == ACL_GROUP_OBJ ||
+ pACLItem->entryType() == ACL_OTHER ) )
+ {
+ // Mark the required entries as no longer being partial entries.
+ // That is, they will get applied to all selected directories.
+ KACLListViewItem* pUserObj = findACLEntryByType( this, ACL_USER_OBJ );
+ pUserObj->entry()->setPartialEntry( false );
+
+ KACLListViewItem* pGroupObj = findACLEntryByType( this, ACL_GROUP_OBJ );
+ pGroupObj->entry()->setPartialEntry( false );
+
+ KACLListViewItem* pOther = findACLEntryByType( this, ACL_OTHER );
+ pOther->entry()->setPartialEntry( false );
+
+ update();
+ }
+ */
+}
+
+
+void KACLListView::calculateEffectiveRights()
+{
+ TQListViewItemIterator it( this );
+ KACLListViewItem* pItem;
+ while ( ( pItem = dynamic_cast<KACLListViewItem*>( it.current() ) ) != 0 )
+ {
+ ++it;
+ pItem->calcEffectiveRights();
+ }
+}
+
+
+unsigned short KACLListView::maskPermissions() const
+{
+ return m_mask;
+}
+
+
+void KACLListView::setMaskPermissions( unsigned short maskPerms )
+{
+ m_mask = maskPerms;
+ calculateEffectiveRights();
+}
+
+
+acl_perm_t KACLListView::maskPartialPermissions() const
+{
+ // return m_pMaskEntry->m_partialPerms;
+ return 0;
+}
+
+
+void KACLListView::setMaskPartialPermissions( acl_perm_t /*maskPartialPerms*/ )
+{
+ //m_pMaskEntry->m_partialPerms = maskPartialPerms;
+ calculateEffectiveRights();
+}
+
+bool KACLListView::hasDefaultEntries() const
+{
+ TQListViewItemIterator it( const_cast<KACLListView*>( this ) );
+ while ( it.current() ) {
+ const KACLListViewItem *item = static_cast<const KACLListViewItem*>( it.current() );
+ ++it;
+ if ( item->isDefault ) return true;
+ }
+ return false;
+}
+
+const KACLListViewItem* KACLListView::findDefaultItemByType( EntryType type ) const
+{
+ return findItemByType( type, true );
+}
+
+const KACLListViewItem* KACLListView::findItemByType( EntryType type, bool defaults ) const
+{
+ TQListViewItemIterator it( const_cast<KACLListView*>( this ) );
+ while ( it.current() ) {
+ const KACLListViewItem *item = static_cast<const KACLListViewItem*>( it.current() );
+ ++it;
+ if ( item->isDefault == defaults && item->type == type ) {
+ return item;
+ }
+ }
+ return 0;
+}
+
+
+unsigned short KACLListView::calculateMaskValue( bool defaults ) const
+{
+ // KACL auto-adds the relevant maks entries, so we can simply query
+ bool dummy;
+ return itemsToACL( defaults ).maskPermissions( dummy );
+}
+
+void KACLListView::slotAddEntry()
+{
+ int allowedTypes = NamedUser | NamedGroup;
+ if ( !m_hasMask )
+ allowedTypes |= Mask;
+ int allowedDefaultTypes = NamedUser | NamedGroup;
+ if ( !findDefaultItemByType( Mask ) )
+ allowedDefaultTypes |= Mask;
+ if ( !hasDefaultEntries() )
+ allowedDefaultTypes |= User | Group;
+ EditACLEntryDialog dlg( this, 0,
+ allowedUsers( false ), allowedGroups( false ),
+ allowedUsers( true ), allowedGroups( true ),
+ allowedTypes, allowedDefaultTypes, m_allowDefaults );
+ dlg.exec();
+ KACLListViewItem *item = dlg.item();
+ if ( !item ) return; // canceled
+ if ( item->type == Mask && !item->isDefault ) {
+ m_hasMask = true;
+ m_mask = item->value;
+ }
+ if ( item->isDefault && !hasDefaultEntries() ) {
+ // first default entry, fill in what is needed
+ if ( item->type != User ) {
+ unsigned short v = findDefaultItemByType( User )->value;
+ new KACLListViewItem( this, User, v, true );
+ }
+ if ( item->type != Group ) {
+ unsigned short v = findDefaultItemByType( Group )->value;
+ new KACLListViewItem( this, Group, v, true );
+ }
+ if ( item->type != Others ) {
+ unsigned short v = findDefaultItemByType( Others )->value;
+ new KACLListViewItem( this, Others, v, true );
+ }
+ }
+ const KACLListViewItem *defaultMaskItem = findDefaultItemByType( Mask );
+ if ( item->isDefault && !defaultMaskItem ) {
+ unsigned short v = calculateMaskValue( true );
+ new KACLListViewItem( this, Mask, v, true );
+ }
+ if ( !item->isDefault && !m_hasMask &&
+ ( item->type == Group
+ || item->type == NamedUser
+ || item->type == NamedGroup ) ) {
+ // auto-add a mask entry
+ unsigned short v = calculateMaskValue( false );
+ new KACLListViewItem( this, Mask, v, false );
+ m_hasMask = true;
+ m_mask = v;
+ }
+ calculateEffectiveRights();
+ sort();
+ setCurrentItem( item );
+ // TQListView doesn't seem to emit, in this case, and we need to update
+ // the buttons...
+ if ( childCount() == 1 )
+ emit currentChanged( item );
+}
+
+void KACLListView::slotEditEntry()
+{
+ TQListViewItem * current = currentItem();
+ if ( !current ) return;
+ KACLListViewItem *item = static_cast<KACLListViewItem*>( current );
+ int allowedTypes = item->type | NamedUser | NamedGroup;
+ bool itemWasMask = item->type == Mask;
+ if ( !m_hasMask || itemWasMask )
+ allowedTypes |= Mask;
+ int allowedDefaultTypes = item->type | NamedUser | NamedGroup;
+ if ( !findDefaultItemByType( Mask ) )
+ allowedDefaultTypes |= Mask;
+ if ( !hasDefaultEntries() )
+ allowedDefaultTypes |= User | Group;
+
+ EditACLEntryDialog dlg( this, item,
+ allowedUsers( false, item ), allowedGroups( false, item ),
+ allowedUsers( true, item ), allowedGroups( true, item ),
+ allowedTypes, allowedDefaultTypes, m_allowDefaults );
+ dlg.exec();
+ if ( itemWasMask && item->type != Mask ) {
+ m_hasMask = false;
+ m_mask = 0;
+ }
+ if ( !itemWasMask && item->type == Mask ) {
+ m_mask = item->value;
+ m_hasMask = true;
+ }
+ calculateEffectiveRights();
+ sort();
+}
+
+void KACLListView::slotRemoveEntry()
+{
+ TQListViewItemIterator it( this, TQListViewItemIterator::Selected );
+ while ( it.current() ) {
+ KACLListViewItem *item = static_cast<KACLListViewItem*>( it.current() );
+ ++it;
+ /* First check if it's a mask entry and if so, make sure that there is
+ * either no name user or group entry, which means the mask can be
+ * removed, or don't remove it, but reset it. That is allowed. */
+ if ( item->type == Mask ) {
+ bool itemWasDefault = item->isDefault;
+ if ( !itemWasDefault && maskCanBeDeleted() ) {
+ m_hasMask= false;
+ m_mask = 0;
+ delete item;
+ } else if ( itemWasDefault && defaultMaskCanBeDeleted() ) {
+ delete item;
+ } else {
+ item->value = 0;
+ item->repaint();
+ }
+ if ( !itemWasDefault )
+ calculateEffectiveRights();
+ } else {
+ // for the base permissions, disable them, which is what libacl does
+ if ( !item->isDefault &&
+ ( item->type == User
+ || item->type == Group
+ || item->type == Others ) ) {
+ item->value = 0;
+ item->repaint();
+ } else {
+ delete item;
+ }
+ }
+ }
+}
+
+bool KACLListView::maskCanBeDeleted() const
+{
+ return !findItemByType( NamedUser ) && !findItemByType( NamedGroup );
+}
+
+bool KACLListView::defaultMaskCanBeDeleted() const
+{
+ return !findDefaultItemByType( NamedUser ) && !findDefaultItemByType( NamedGroup );
+}
+
+#include "kacleditwidget.moc"
+#include "kacleditwidget_p.moc"
+#endif
+// vim:set ts=8 sw=4:
diff --git a/tdeio/tdefile/kacleditwidget.h b/tdeio/tdefile/kacleditwidget.h
new file mode 100644
index 000000000..c51cb94fc
--- /dev/null
+++ b/tdeio/tdefile/kacleditwidget.h
@@ -0,0 +1,65 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Sean Harmer <sh@rama.homelinux.org> *
+ * Till Adam <adam@kde.org> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU Library 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., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#ifndef KACLEDITWIDGET_H
+#define KACLEDITWIDGET_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef Q_MOC_RUN
+#define USE_POSIX_ACL
+#endif // Q_MOC_RUN
+
+#ifdef USE_POSIX_ACL
+
+#include <klistview.h>
+#include <kacl.h>
+#include <tdefileitem.h>
+
+class KACLListViewItem;
+class KACLListView;
+class TQPushButton;
+
+class KACLEditWidget : TQWidget
+{
+ Q_OBJECT
+
+public:
+ KACLEditWidget( TQWidget *parent = 0, const char *name = 0 );
+ KACL getACL() const;
+ KACL getDefaultACL() const;
+ void setACL( const KACL & );
+ void setDefaultACL( const KACL & );
+ void setAllowDefaults( bool value );
+ void setReadOnly( bool value );
+private slots:
+ void slotUpdateButtons();
+
+private:
+ KACLListView* m_listView;
+ TQPushButton *m_AddBtn;
+ TQPushButton *m_EditBtn;
+ TQPushButton *m_DelBtn;
+};
+
+
+#endif
+#endif
diff --git a/tdeio/tdefile/kacleditwidget_p.h b/tdeio/tdefile/kacleditwidget_p.h
new file mode 100644
index 000000000..dc7e4c811
--- /dev/null
+++ b/tdeio/tdefile/kacleditwidget_p.h
@@ -0,0 +1,206 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Sean Harmer <sh@rama.homelinux.org> *
+ * Till Adam <adam@kde.org> *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU Library 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., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#ifndef KACLEDITWIDGET_P_H
+#define KACLEDITWIDGET_P_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef Q_MOC_RUN
+#define USE_POSIX_ACL
+#endif // Q_MOC_RUN
+
+#ifdef USE_POSIX_ACL
+#include <klistview.h>
+#include <sys/acl.h>
+#include <kacl.h>
+#include <tdefileitem.h>
+#include <kdialogbase.h>
+#include <tqpixmap.h>
+#include <tqcombobox.h>
+
+class KACLListViewItem;
+class TQPushButton;
+class TQVButtonGroup;
+class KACLListView;
+class TQWidgetStack;
+class TQCheckBox;
+
+/**
+@author Sean Harmer
+*/
+class KACLListView : public KListView
+{
+ Q_OBJECT
+
+ friend class KACLListViewItem;
+public:
+ enum Types
+ {
+ OWNER_IDX = 0,
+ GROUP_IDX,
+ OTHERS_IDX,
+ MASK_IDX,
+ NAMED_USER_IDX,
+ NAMED_GROUP_IDX,
+ LAST_IDX
+ };
+ enum EntryType { User = 1,
+ Group = 2,
+ Others = 4,
+ Mask = 8,
+ NamedUser = 16,
+ NamedGroup = 32,
+ AllTypes = 63 };
+
+ KACLListView( TQWidget* parent = 0, const char* name = 0 );
+ ~KACLListView();
+
+ bool hasMaskEntry() const { return m_hasMask; }
+ bool hasDefaultEntries() const;
+ bool allowDefaults() const { return m_allowDefaults; }
+ void setAllowDefaults( bool v ) { m_allowDefaults = v; }
+ unsigned short maskPermissions() const;
+ void setMaskPermissions( unsigned short maskPerms );
+ acl_perm_t maskPartialPermissions() const;
+ void setMaskPartialPermissions( acl_perm_t maskPerms );
+
+ bool maskCanBeDeleted() const;
+ bool defaultMaskCanBeDeleted() const;
+
+ const KACLListViewItem* findDefaultItemByType( EntryType type ) const;
+ const KACLListViewItem* findItemByType( EntryType type,
+ bool defaults = false ) const;
+ unsigned short calculateMaskValue( bool defaults ) const;
+ void calculateEffectiveRights();
+
+ TQStringList allowedUsers( bool defaults, KACLListViewItem *allowedItem = 0 );
+ TQStringList allowedGroups( bool defaults, KACLListViewItem *allowedItem = 0 );
+
+ const KACL getACL() const { return getACL(); }
+ KACL getACL();
+
+ const KACL getDefaultACL() const { return getDefaultACL(); }
+ KACL getDefaultACL();
+
+ TQPixmap getYesPixmap() const { return *m_yesPixmap; }
+ TQPixmap getYesPartialPixmap() const { return *m_yesPartialPixmap; }
+
+public slots:
+ void slotAddEntry();
+ void slotEditEntry();
+ void slotRemoveEntry();
+ void setACL( const KACL &anACL );
+ void setDefaultACL( const KACL &anACL );
+
+protected slots:
+ void entryClicked( TQListViewItem* pItem, const TQPoint& pt, int col );
+protected:
+ void contentsMousePressEvent( TQMouseEvent * e );
+
+private:
+ void fillItemsFromACL( const KACL &pACL, bool defaults = false );
+ KACL itemsToACL( bool defaults ) const;
+
+ KACL m_ACL;
+ KACL m_defaultACL;
+ unsigned short m_mask;
+ bool m_hasMask;
+ bool m_allowDefaults;
+ TQStringList m_allUsers;
+ TQStringList m_allGroups;
+ TQPixmap* m_yesPixmap;
+ TQPixmap* m_yesPartialPixmap;
+};
+
+class EditACLEntryDialog : public KDialogBase
+{
+ Q_OBJECT
+
+public:
+ EditACLEntryDialog( KACLListView *listView, KACLListViewItem *item,
+ const TQStringList &users,
+ const TQStringList &groups,
+ const TQStringList &defaultUsers,
+ const TQStringList &defaultGroups,
+ int allowedTypes = KACLListView::AllTypes,
+ int allowedDefaultTypes = KACLListView::AllTypes,
+ bool allowDefault = false );
+ KACLListViewItem* item() const { return m_item; }
+public slots:
+ void slotOk();
+ void slotSelectionChanged( int id );
+private slots:
+ void slotUpdateAllowedUsersAndGroups();
+ void slotUpdateAllowedTypes();
+private:
+ KACLListView *m_listView;
+ KACLListViewItem *m_item;
+ TQStringList m_users;
+ TQStringList m_groups;
+ TQStringList m_defaultUsers;
+ TQStringList m_defaultGroups;
+ int m_allowedTypes;
+ int m_allowedDefaultTypes;
+ TQVButtonGroup *m_buttonGroup;
+ TQComboBox *m_usersCombo;
+ TQComboBox *m_groupsCombo;
+ TQWidgetStack *m_widgetStack;
+ TQCheckBox *m_defaultCB;
+};
+
+
+class KACLListViewItem : public KListViewItem
+{
+public:
+ KACLListViewItem( TQListView* parent, KACLListView::EntryType type,
+ unsigned short value,
+ bool defaultEntry,
+ const TQString& qualifier = TQString::null );
+ virtual ~KACLListViewItem();
+ virtual TQString key( int column, bool ascending ) const;
+
+ void calcEffectiveRights();
+
+ bool isDeletable() const;
+ bool isAllowedToChangeType() const;
+
+ void togglePerm( acl_perm_t perm );
+
+ virtual void paintCell( TQPainter *p, const TQColorGroup &cg,
+ int column, int width, int alignment );
+
+ void updatePermPixmaps();
+ void repaint();
+
+ KACLListView::EntryType type;
+ unsigned short value;
+ bool isDefault;
+ TQString qualifier;
+ bool isPartial;
+
+private:
+ KACLListView* m_pACLListView;
+};
+
+
+#endif
+#endif
diff --git a/tdeio/tdefile/kcombiview.cpp b/tdeio/tdefile/kcombiview.cpp
new file mode 100644
index 000000000..bc3d43384
--- /dev/null
+++ b/tdeio/tdefile/kcombiview.cpp
@@ -0,0 +1,371 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
+ 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#include <assert.h>
+
+#include "tdefileitem.h"
+#include "kcombiview.h"
+#include "tdefileiconview.h"
+#include "tdefiledetailview.h"
+#include "config-tdefile.h"
+
+#include <tqevent.h>
+
+#include <tqdir.h>
+
+#include <kapplication.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <kglobal.h>
+
+#include <tqvaluelist.h>
+
+KCombiView::KCombiView( TQWidget *parent, const char *name)
+ : TQSplitter( parent, name),
+ KFileView(),
+ right(0),
+ m_lastViewForNextItem(0),
+ m_lastViewForPrevItem(0)
+{
+ left = new KFileIconView( this, "left" );
+ left->setAcceptDrops(false);
+ left->viewport()->setAcceptDrops(false);
+ left->setGridX( 160 );
+ left->KFileView::setViewMode( Directories );
+ left->setArrangement( TQIconView::LeftToRight );
+ left->setParentView( this );
+ left->setAcceptDrops(false);
+ left->installEventFilter( this );
+
+ connect( sig, TQT_SIGNAL( sortingChanged( TQDir::SortSpec ) ),
+ TQT_SLOT( slotSortingChanged( TQDir::SortSpec ) ));
+}
+
+KCombiView::~KCombiView()
+{
+ delete right;
+}
+
+void KCombiView::setRight(KFileView *view)
+{
+ delete right;
+ right = view;
+ right->KFileView::setViewMode( Files );
+ setViewName( right->viewName() );
+
+ TQValueList<int> lst;
+ lst << left->gridX() + 2 * left->spacing();
+ setSizes( lst );
+ setResizeMode( left, TQSplitter::KeepSize );
+
+ right->setParentView( this );
+ right->widget()->setAcceptDrops(acceptDrops());
+ right->setDropOptions(dropOptions());
+ right->widget()->installEventFilter( this );
+}
+
+
+void KCombiView::insertItem( KFileItem *item )
+{
+ KFileView::insertItem( item );
+
+ if ( item->isDir() ) {
+ left->updateNumbers( item );
+ left->insertItem( item );
+ }
+ else {
+ right->updateNumbers( item );
+ right->insertItem( item );
+ }
+}
+
+void KCombiView::setSorting( TQDir::SortSpec sort )
+{
+ if ( !right )
+ kdFatal() << "You need to call setRight( someview ) before!" << endl;
+ right->setSorting( sort );
+ left->setSorting( sort );
+
+ KFileView::setSorting( right->sorting() );
+}
+
+void KCombiView::clearView()
+{
+ left->clearView();
+ if ( right )
+ right->clearView();
+}
+
+void KCombiView::updateView( bool b )
+{
+ left->updateView( b );
+ if ( right )
+ right->updateView( b );
+}
+
+void KCombiView::updateView( const KFileItem *i )
+{
+ left->updateView( i );
+ if ( right )
+ right->updateView( i );
+}
+
+void KCombiView::removeItem( const KFileItem *i )
+{
+ left->removeItem( i );
+ if ( right )
+ right->removeItem( i );
+ KFileView::removeItem( i );
+}
+
+void KCombiView::listingCompleted()
+{
+ left->listingCompleted();
+ if ( right )
+ right->listingCompleted();
+}
+
+void KCombiView::clear()
+{
+ KFileView::clear();
+ left->KFileView::clear();
+ if ( right )
+ right->clear();
+}
+
+void KCombiView::clearSelection()
+{
+ left->clearSelection();
+ if ( right )
+ right->clearSelection();
+}
+
+void KCombiView::selectAll()
+{
+ left->selectAll();
+ if ( right )
+ right->selectAll();
+}
+
+void KCombiView::invertSelection()
+{
+ left->invertSelection();
+ if ( right )
+ right->invertSelection();
+}
+
+bool KCombiView::isSelected( const KFileItem *item ) const
+{
+ assert( right ); // for performance reasons no if ( right ) check.
+ return (right->isSelected( item ) || left->isSelected( item ));
+}
+
+void KCombiView::setSelectionMode( KFile::SelectionMode sm )
+{
+ // I think the left view (directories should always be in
+ // Single-Mode, right?
+ // left->setSelectionMode( sm );
+ if ( !right )
+ kdFatal() << "You need to call setRight( someview ) before!" << endl;
+ right->setSelectionMode( sm );
+}
+
+void KCombiView::setSelected( const KFileItem *item, bool enable )
+{
+ left->setSelected( item, enable );
+ if ( right )
+ right->setSelected( item, enable );
+}
+
+void KCombiView::setCurrentItem( const KFileItem *item )
+{
+ left->setCurrentItem( item );
+ if ( right )
+ right->setCurrentItem( item );
+}
+
+KFileItem * KCombiView::currentFileItem() const
+{
+ // we can actually have two current items, one in each view. So we simply
+ // prefer the fileview's item over the directory's.
+ // Smarter: if the right view has focus, prefer that over the left.
+ if ( !right )
+ return left->currentFileItem();
+
+ KFileView *preferredView = focusView( right );
+ KFileItem *item = preferredView->currentFileItem();
+ if ( !item && preferredView != left )
+ item = left->currentFileItem();
+
+ return item;
+}
+
+void KCombiView::ensureItemVisible(const KFileItem *item)
+{
+ left->ensureItemVisible( item );
+ if ( right )
+ right->ensureItemVisible( item );
+}
+
+KFileItem * KCombiView::firstFileItem() const
+{
+ if ( !right )
+ return left->firstFileItem();
+
+ KFileView *preferredView = focusView( left );
+ KFileView *otherView = (preferredView == left) ? right : left;
+ KFileItem *item = preferredView->firstFileItem();
+ if ( !item )
+ item = otherView->firstFileItem();
+
+ return item;
+}
+
+KFileItem * KCombiView::nextItem( const KFileItem *fileItem ) const
+{
+ if ( !right )
+ return left->nextItem( fileItem );
+
+ KFileView *preferredView = focusView( left );
+ KFileView *otherView = (preferredView == left) ? right : left;
+ KFileItem *item = preferredView->nextItem( fileItem );
+
+ if ( item )
+ m_lastViewForNextItem = preferredView;
+ else { // no item, check other view
+ // when changing from one to another view, we need to continue
+ // with the next view's first item!
+ if ( m_lastViewForNextItem != otherView ) {
+ m_lastViewForNextItem = otherView;
+ return otherView->firstFileItem();
+ }
+
+ item = otherView->nextItem( fileItem );
+ m_lastViewForNextItem = otherView;
+ }
+
+ return item;
+}
+
+KFileItem * KCombiView::prevItem( const KFileItem *fileItem ) const
+{
+ if ( !right )
+ return left->nextItem( fileItem );
+
+ KFileView *preferredView = focusView( left );
+ KFileView *otherView = (preferredView == left) ? right : left;
+ KFileItem *item = preferredView->prevItem( fileItem );
+ if ( item )
+ m_lastViewForPrevItem = preferredView;
+
+ else { // no item, check other view
+ // when changing from one to another view, we need to continue
+ // with the next view's last item!
+ if ( m_lastViewForPrevItem != otherView ) {
+ fileItem = otherView->firstFileItem();
+ while ( otherView->nextItem( fileItem ) ) // find the last item
+ fileItem = otherView->nextItem( fileItem );
+ }
+
+ item = otherView->prevItem( fileItem );
+ m_lastViewForPrevItem = otherView;
+ }
+
+ return item;
+}
+
+void KCombiView::slotSortingChanged( TQDir::SortSpec sorting )
+{
+ KFileView::setSorting( sorting );
+}
+
+KFileView *KCombiView::focusView( KFileView *preferred ) const
+{
+ TQWidget *w = focusWidget();
+ KFileView *other = (right == preferred) ? left : right;
+ return (preferred && w == preferred->widget()) ? preferred : other;
+}
+
+void KCombiView::readConfig( TDEConfig *config, const TQString& group )
+{
+ left->readConfig( config, group );
+ if ( right )
+ right->readConfig( config, group );
+}
+
+void KCombiView::writeConfig( TDEConfig *config, const TQString& group )
+{
+ left->writeConfig( config, group );
+ if ( right )
+ right->writeConfig( config, group );
+}
+
+KActionCollection * KCombiView::actionCollection() const
+{
+ return focusView( right )->actionCollection();
+}
+
+void KCombiView::setAcceptDrops(bool b)
+{
+ left->setAcceptDrops(b);
+ if (right)
+ right->widget()->setAcceptDrops(b);
+ TQSplitter::setAcceptDrops(b);
+}
+
+void KCombiView::setDropOptions_impl(int options)
+{
+ KFileView::setDropOptions_impl(options);
+ left->setDropOptions(options);
+ if (right)
+ right->setDropOptions(options);
+}
+
+void KCombiView::virtual_hook( int id, void* data )
+{
+ switch(id) {
+ case VIRTUAL_SET_DROP_OPTIONS:
+ setDropOptions_impl(*(int *)data);
+ break;
+ default:
+ KFileView::virtual_hook( id, data );
+ }
+}
+
+bool KCombiView::eventFilter( TQObject *o, TQEvent *e )
+{
+ int type = e->type();
+
+ // only the focused view may have a selection
+ if ( type == TQEvent::FocusIn )
+ {
+ if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(left) )
+ right->clearSelection();
+ else if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(right->widget()) )
+ left->clearSelection();
+ }
+
+ return TQSplitter::eventFilter( o, e );
+}
+
+#include "kcombiview.moc"
+
diff --git a/tdeio/tdefile/kcombiview.h b/tdeio/tdefile/kcombiview.h
new file mode 100644
index 000000000..8da3da3fb
--- /dev/null
+++ b/tdeio/tdefile/kcombiview.h
@@ -0,0 +1,133 @@
+/* -*- c++ -*-
+ This file is part of the KDE libraries
+ Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
+ 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KCOMBIVIEW_H
+#define _KCOMBIVIEW_H
+
+#include <tqsplitter.h>
+#include <klocale.h>
+
+#include <tdefile.h>
+#include <tdefileview.h>
+
+class KFileIconView;
+class TQEvent;
+class TQIconViewItem;
+
+/**
+ * This view is designed to combine two KFileViews into one widget, to show
+ * directories on the left side and files on the right side.
+ *
+ * Methods like selectedItems() to query status _only_ work on the right side,
+ * i.e. on the files.
+ *
+ * After creating the KCombiView, you need to supply the view shown in the
+ * right, (see setRight()). Available KFileView implementations are
+ * KFileIconView and KFileDetailView.
+ *
+ * Most of the below methods are just implementations of the baseclass
+ * KFileView, so look there for documentation.
+ *
+ * @see KFileView
+ * @see KFileIconView
+ * @see KFileDetailView
+ * @see KDirOperator
+ */
+class TDEIO_EXPORT KCombiView : public TQSplitter,
+ public KFileView
+{
+ Q_OBJECT
+
+public:
+ KCombiView( TQWidget *parent, const char *name);
+ virtual ~KCombiView();
+
+ virtual TQWidget *widget() { return this; }
+ virtual void clearView();
+
+ virtual void updateView( bool );
+ virtual void updateView(const KFileItem*);
+ virtual void removeItem( const KFileItem * );
+ virtual void listingCompleted();
+
+ /**
+ * Sets the view to be shown in the right. You need to call this before
+ * doing anything else with this widget.
+ */
+ void setRight(KFileView *view);
+
+ virtual void setSelectionMode( KFile::SelectionMode sm );
+
+ virtual void setSelected(const KFileItem *, bool);
+ virtual bool isSelected( const KFileItem * ) const;
+ virtual void clearSelection();
+ virtual void selectAll();
+ virtual void invertSelection();
+
+ virtual void setCurrentItem( const KFileItem * );
+ virtual KFileItem * currentFileItem() const;
+ virtual KFileItem * firstFileItem() const;
+ virtual KFileItem * nextItem( const KFileItem * ) const;
+ virtual KFileItem * prevItem( const KFileItem * ) const;
+
+ virtual void insertItem( KFileItem *i );
+ virtual void clear();
+
+ virtual void setSorting( TQDir::SortSpec sort );
+
+ virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
+ virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
+
+ void ensureItemVisible( const KFileItem * );
+
+ virtual KActionCollection * actionCollection() const;
+
+ virtual void setAcceptDrops(bool b);
+
+protected:
+ KFileIconView *left;
+ KFileView *right;
+
+protected slots:
+ void slotSortingChanged( TQDir::SortSpec );
+
+private:
+ KFileView *focusView( KFileView *preferred ) const;
+
+ // in nextItem() and prevItem(), we have to switch views, when the first
+ // view returns 0L. So we need to remember which view was used in the
+ // previous call to next/prevItem(). Yes, it's a hack, but it works for
+ // some cases at least.
+ mutable KFileView *m_lastViewForNextItem;
+ mutable KFileView *m_lastViewForPrevItem;
+
+protected:
+ virtual bool eventFilter( TQObject *o, TQEvent *e );
+ void setDropOptions_impl(int options);
+
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KCombiViewPrivate;
+ KCombiViewPrivate *d;
+
+};
+
+#endif
diff --git a/tdeio/tdefile/kcustommenueditor.cpp b/tdeio/tdefile/kcustommenueditor.cpp
new file mode 100644
index 000000000..48c911e30
--- /dev/null
+++ b/tdeio/tdefile/kcustommenueditor.cpp
@@ -0,0 +1,242 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; version 2
+ of the License.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqhbox.h>
+#include <tqregexp.h>
+#include <tqimage.h>
+#include <tqpushbutton.h>
+#include <tqdir.h>
+
+#include <kbuttonbox.h>
+#include <klocale.h>
+#include <kglobal.h>
+#include <kiconloader.h>
+#include <klistview.h>
+#include <kservice.h>
+#include <kstandarddirs.h>
+#include <tdeconfigbase.h>
+#include <kopenwith.h>
+
+#include "kcustommenueditor.h"
+
+class KCustomMenuEditor::Item : public TQListViewItem
+{
+public:
+ Item(TQListView *parent, KService::Ptr service)
+ : TQListViewItem(parent),
+ s(service)
+ {
+ init();
+ }
+
+ Item(TQListViewItem *parent, KService::Ptr service)
+ : TQListViewItem(parent),
+ s(service)
+ {
+ init();
+ }
+
+ void init()
+ {
+ TQString serviceName = s->name();
+
+ // item names may contain ampersands. To avoid them being converted
+ // to accelators, replace them with two ampersands.
+ serviceName.replace("&", "&&");
+
+ TQPixmap normal = TDEGlobal::instance()->iconLoader()->loadIcon(s->icon(), KIcon::Small,
+ 0, KIcon::DefaultState, 0L, true);
+
+ // make sure they are not larger than 16x16
+ if (normal.width() > 16 || normal.height() > 16) {
+ TQImage tmp = normal.convertToImage();
+ tmp = tmp.smoothScale(16, 16);
+ normal.convertFromImage(tmp);
+ }
+ setText(0, serviceName);
+ setPixmap(0, normal);
+ }
+
+ KService::Ptr s;
+};
+
+class KCustomMenuEditor::KCustomMenuEditorPrivate
+{
+public:
+ TQPushButton * pbRemove;
+ TQPushButton * pbMoveUp;
+ TQPushButton * pbMoveDown;
+};
+
+KCustomMenuEditor::KCustomMenuEditor(TQWidget *parent)
+ : KDialogBase(parent, "custommenueditor", true, i18n("Menu Editor"), Ok|Cancel, Ok, true),
+ m_listView(0)
+{
+ d = new KCustomMenuEditorPrivate;
+ TQHBox *page = makeHBoxMainWidget();
+ m_listView = new KListView(page);
+ m_listView->addColumn(i18n("Menu"));
+ m_listView->setFullWidth(true);
+ m_listView->setSorting(-1);
+ KButtonBox *buttonBox = new KButtonBox(page, Qt::Vertical);
+ buttonBox->addButton(i18n("New..."), TQT_TQOBJECT(this), TQT_SLOT(slotNewItem()));
+ d->pbRemove=buttonBox->addButton(i18n("Remove"), TQT_TQOBJECT(this), TQT_SLOT(slotRemoveItem()));
+ d->pbMoveUp=buttonBox->addButton(i18n("Move Up"), TQT_TQOBJECT(this), TQT_SLOT(slotMoveUp()));
+ d->pbMoveDown=buttonBox->addButton(i18n("Move Down"), TQT_TQOBJECT(this), TQT_SLOT(slotMoveDown()));
+ buttonBox->layout();
+ connect( m_listView, TQT_SIGNAL( selectionChanged () ), this, TQT_SLOT( refreshButton() ) );
+ refreshButton();
+}
+
+KCustomMenuEditor::~KCustomMenuEditor()
+{
+ delete d;
+ d=0;
+}
+
+void KCustomMenuEditor::refreshButton()
+{
+ TQListViewItem *item = m_listView->currentItem();
+ d->pbRemove->setEnabled( item );
+ d->pbMoveUp->setEnabled( item && item->itemAbove() );
+ d->pbMoveDown->setEnabled( item && item->itemBelow() );
+}
+
+void
+KCustomMenuEditor::load(TDEConfigBase *cfg)
+{
+ cfg->setGroup(TQString::null);
+ int count = cfg->readNumEntry("NrOfItems");
+ TQListViewItem *last = 0;
+ for(int i = 0; i < count; i++)
+ {
+ TQString entry = cfg->readPathEntry(TQString("Item%1").arg(i+1));
+ if (entry.isEmpty())
+ continue;
+
+ // Try KSycoca first.
+ KService::Ptr menuItem = KService::serviceByDesktopPath( entry );
+ if (!menuItem)
+ menuItem = KService::serviceByDesktopName( entry );
+ if (!menuItem)
+ menuItem = new KService( entry );
+
+ if (!menuItem->isValid())
+ continue;
+
+ TQListViewItem *item = new Item(m_listView, menuItem);
+ item->moveItem(last);
+ last = item;
+ }
+}
+
+void
+KCustomMenuEditor::save(TDEConfigBase *cfg)
+{
+ // First clear the whole config file.
+ TQStringList groups = cfg->groupList();
+ for(TQStringList::ConstIterator it = groups.begin();
+ it != groups.end(); ++it)
+ {
+ cfg->deleteGroup(*it);
+ }
+
+ cfg->setGroup(TQString::null);
+ Item * item = (Item *) m_listView->firstChild();
+ int i = 0;
+ while(item)
+ {
+ i++;
+ TQString path = item->s->desktopEntryPath();
+ if (TQDir::isRelativePath(path) || TQDir::isRelativePath(TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path)))
+ path = item->s->desktopEntryName();
+ cfg->writePathEntry(TQString("Item%1").arg(i), path);
+ item = (Item *) item->nextSibling();
+ }
+ cfg->writeEntry("NrOfItems", i);
+}
+
+void
+KCustomMenuEditor::slotNewItem()
+{
+ TQListViewItem *item = m_listView->currentItem();
+
+ KOpenWithDlg dlg(this);
+ dlg.setSaveNewApplications(true);
+
+ if (dlg.exec())
+ {
+ KService::Ptr s = dlg.service();
+ if (s && s->isValid())
+ {
+ Item *newItem = new Item(m_listView, s);
+ newItem->moveItem(item);
+ }
+ refreshButton();
+ }
+}
+
+void
+KCustomMenuEditor::slotRemoveItem()
+{
+ TQListViewItem *item = m_listView->currentItem();
+ if (!item)
+ return;
+
+ delete item;
+ refreshButton();
+}
+
+void
+KCustomMenuEditor::slotMoveUp()
+{
+ TQListViewItem *item = m_listView->currentItem();
+ if (!item)
+ return;
+
+ TQListViewItem *searchItem = m_listView->firstChild();
+ while(searchItem)
+ {
+ TQListViewItem *next = searchItem->nextSibling();
+ if (next == item)
+ {
+ searchItem->moveItem(item);
+ break;
+ }
+ searchItem = next;
+ }
+ refreshButton();
+}
+
+void
+KCustomMenuEditor::slotMoveDown()
+{
+ TQListViewItem *item = m_listView->currentItem();
+ if (!item)
+ return;
+
+ TQListViewItem *after = item->nextSibling();
+ if (!after)
+ return;
+
+ item->moveItem( after );
+ refreshButton();
+}
+
+#include "kcustommenueditor.moc"
diff --git a/kio/kfile/kcustommenueditor.h b/tdeio/tdefile/kcustommenueditor.h
index 108e9c477..108e9c477 100644
--- a/kio/kfile/kcustommenueditor.h
+++ b/tdeio/tdefile/kcustommenueditor.h
diff --git a/tdeio/tdefile/kdiroperator.cpp b/tdeio/tdefile/kdiroperator.cpp
new file mode 100644
index 000000000..ea3183f78
--- /dev/null
+++ b/tdeio/tdefile/kdiroperator.cpp
@@ -0,0 +1,1740 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1999,2000 Stephan Kulow <coolo@kde.org>
+ 1999,2000,2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <unistd.h>
+
+#include <tqdir.h>
+#include <tqapplication.h>
+#include <tqdialog.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqpushbutton.h>
+#include <tqpopupmenu.h>
+#include <tqregexp.h>
+#include <tqtimer.h>
+#include <tqvbox.h>
+
+#include <kaction.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kdialog.h>
+#include <kdialogbase.h>
+#include <kdirlister.h>
+#include <kinputdialog.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kpopupmenu.h>
+#include <kprogress.h>
+#include <kstdaction.h>
+#include <tdeio/job.h>
+#include <tdeio/jobclasses.h>
+#include <tdeio/netaccess.h>
+#include <tdeio/previewjob.h>
+#include <tdeio/renamedlg.h>
+#include <kpropertiesdialog.h>
+#include <kservicetypefactory.h>
+#include <kstdaccel.h>
+#include <kde_file.h>
+
+#include "config-tdefile.h"
+#include "kcombiview.h"
+#include "kdiroperator.h"
+#include "tdefiledetailview.h"
+#include "tdefileiconview.h"
+#include "tdefilepreview.h"
+#include "tdefileview.h"
+#include "tdefileitem.h"
+#include "tdefilemetapreview.h"
+
+
+template class TQPtrStack<KURL>;
+template class TQDict<KFileItem>;
+
+
+class KDirOperator::KDirOperatorPrivate
+{
+public:
+ KDirOperatorPrivate() {
+ onlyDoubleClickSelectsFiles = false;
+ progressDelayTimer = 0L;
+ dirHighlighting = false;
+ config = 0L;
+ dropOptions = 0;
+ }
+
+ ~KDirOperatorPrivate() {
+ delete progressDelayTimer;
+ }
+
+ bool dirHighlighting;
+ TQString lastURL; // used for highlighting a directory on cdUp
+ bool onlyDoubleClickSelectsFiles;
+ TQTimer *progressDelayTimer;
+ KActionSeparator *viewActionSeparator;
+ int dropOptions;
+
+ TDEConfig *config;
+ TQString configGroup;
+};
+
+KDirOperator::KDirOperator(const KURL& _url,
+ TQWidget *parent, const char* _name)
+ : TQWidget(parent, _name),
+ dir(0),
+ m_fileView(0),
+ progress(0)
+{
+ myPreview = 0L;
+ myMode = KFile::File;
+ m_viewKind = KFile::Simple;
+ mySorting = static_cast<TQDir::SortSpec>(TQDir::Name | TQDir::DirsFirst);
+ d = new KDirOperatorPrivate;
+
+ if (_url.isEmpty()) { // no dir specified -> current dir
+ TQString strPath = TQDir::currentDirPath();
+ strPath.append('/');
+ currUrl = KURL();
+ currUrl.setProtocol(TQString::fromLatin1("file"));
+ currUrl.setPath(strPath);
+ }
+ else {
+ currUrl = _url;
+ if ( currUrl.protocol().isEmpty() )
+ currUrl.setProtocol(TQString::fromLatin1("file"));
+
+ currUrl.addPath("/"); // make sure we have a trailing slash!
+ }
+
+ setDirLister( new KDirLister( true ) );
+
+ connect(&myCompletion, TQT_SIGNAL(match(const TQString&)),
+ TQT_SLOT(slotCompletionMatch(const TQString&)));
+
+ progress = new KProgress(this, "progress");
+ progress->adjustSize();
+ progress->move(2, height() - progress->height() -2);
+
+ d->progressDelayTimer = new TQTimer( this, "progress delay timer" );
+ connect( d->progressDelayTimer, TQT_SIGNAL( timeout() ),
+ TQT_SLOT( slotShowProgress() ));
+
+ myCompleteListDirty = false;
+
+ backStack.setAutoDelete( true );
+ forwardStack.setAutoDelete( true );
+
+ // action stuff
+ setupActions();
+ setupMenu();
+
+ setFocusPolicy(TQ_WheelFocus);
+}
+
+KDirOperator::~KDirOperator()
+{
+ resetCursor();
+ if ( m_fileView )
+ {
+ if ( d->config )
+ m_fileView->writeConfig( d->config, d->configGroup );
+
+ delete m_fileView;
+ m_fileView = 0L;
+ }
+
+ delete myPreview;
+ delete dir;
+ delete d;
+}
+
+
+void KDirOperator::setSorting( TQDir::SortSpec spec )
+{
+ if ( m_fileView )
+ m_fileView->setSorting( spec );
+ mySorting = spec;
+ updateSortActions();
+}
+
+void KDirOperator::resetCursor()
+{
+ TQApplication::restoreOverrideCursor();
+ progress->hide();
+}
+
+void KDirOperator::insertViewDependentActions()
+{
+ // If we have a new view actionCollection(), insert its actions
+ // into viewActionMenu.
+
+ if( !m_fileView )
+ return;
+
+ if ( (viewActionMenu->popupMenu()->count() == 0) || // Not yet initialized or...
+ (viewActionCollection != m_fileView->actionCollection()) ) // ...changed since.
+ {
+ if (viewActionCollection)
+ {
+ disconnect( viewActionCollection, TQT_SIGNAL( inserted( KAction * )),
+ this, TQT_SLOT( slotViewActionAdded( KAction * )));
+ disconnect( viewActionCollection, TQT_SIGNAL( removed( KAction * )),
+ this, TQT_SLOT( slotViewActionRemoved( KAction * )));
+ }
+
+ viewActionMenu->popupMenu()->clear();
+// viewActionMenu->insert( shortAction );
+// viewActionMenu->insert( detailedAction );
+// viewActionMenu->insert( actionSeparator );
+ viewActionMenu->insert( myActionCollection->action( "short view" ) );
+ viewActionMenu->insert( myActionCollection->action( "detailed view" ) );
+ viewActionMenu->insert( actionSeparator );
+ viewActionMenu->insert( showHiddenAction );
+// viewActionMenu->insert( myActionCollection->action( "single" ));
+ viewActionMenu->insert( separateDirsAction );
+ // Warning: adjust slotViewActionAdded() and slotViewActionRemoved()
+ // when you add/remove actions here!
+
+ viewActionCollection = m_fileView->actionCollection();
+ if (!viewActionCollection)
+ return;
+
+ if ( !viewActionCollection->isEmpty() )
+ {
+ viewActionMenu->insert( d->viewActionSeparator );
+
+ // first insert the normal actions, then the grouped ones
+ TQStringList groups = viewActionCollection->groups();
+ groups.prepend( TQString::null ); // actions without group
+ TQStringList::ConstIterator git = groups.begin();
+ KActionPtrList list;
+ KAction *sep = actionCollection()->action("separator");
+ for ( ; git != groups.end(); ++git )
+ {
+ if ( git != groups.begin() )
+ viewActionMenu->insert( sep );
+
+ list = viewActionCollection->actions( *git );
+ KActionPtrList::ConstIterator it = list.begin();
+ for ( ; it != list.end(); ++it )
+ viewActionMenu->insert( *it );
+ }
+ }
+
+ connect( viewActionCollection, TQT_SIGNAL( inserted( KAction * )),
+ TQT_SLOT( slotViewActionAdded( KAction * )));
+ connect( viewActionCollection, TQT_SIGNAL( removed( KAction * )),
+ TQT_SLOT( slotViewActionRemoved( KAction * )));
+ }
+}
+
+void KDirOperator::activatedMenu( const KFileItem *, const TQPoint& pos )
+{
+ setupMenu();
+ updateSelectionDependentActions();
+
+ actionMenu->popup( pos );
+}
+
+void KDirOperator::updateSelectionDependentActions()
+{
+ bool hasSelection = m_fileView && m_fileView->selectedItems() &&
+ !m_fileView->selectedItems()->isEmpty();
+ myActionCollection->action( "trash" )->setEnabled( hasSelection );
+ myActionCollection->action( "delete" )->setEnabled( hasSelection );
+ myActionCollection->action( "properties" )->setEnabled( hasSelection );
+}
+
+void KDirOperator::setPreviewWidget(const TQWidget *w)
+{
+ if(w != 0L)
+ m_viewKind = (m_viewKind | KFile::PreviewContents);
+ else
+ m_viewKind = (m_viewKind & ~KFile::PreviewContents);
+
+ delete myPreview;
+ myPreview = w;
+
+ KToggleAction *preview = static_cast<KToggleAction*>(myActionCollection->action("preview"));
+ preview->setEnabled( w != 0L );
+ preview->setChecked( w != 0L );
+ setView( static_cast<KFile::FileView>(m_viewKind) );
+}
+
+int KDirOperator::numDirs() const
+{
+ return m_fileView ? m_fileView->numDirs() : 0;
+}
+
+int KDirOperator::numFiles() const
+{
+ return m_fileView ? m_fileView->numFiles() : 0;
+}
+
+void KDirOperator::slotDetailedView()
+{
+ KFile::FileView view = static_cast<KFile::FileView>( (m_viewKind & ~KFile::Simple) | KFile::Detail );
+ setView( view );
+}
+
+void KDirOperator::slotSimpleView()
+{
+ KFile::FileView view = static_cast<KFile::FileView>( (m_viewKind & ~KFile::Detail) | KFile::Simple );
+ setView( view );
+}
+
+void KDirOperator::slotToggleHidden( bool show )
+{
+ dir->setShowingDotFiles( show );
+ updateDir();
+ if ( m_fileView )
+ m_fileView->listingCompleted();
+}
+
+void KDirOperator::slotSeparateDirs()
+{
+ if (separateDirsAction->isChecked())
+ {
+ KFile::FileView view = static_cast<KFile::FileView>( m_viewKind | KFile::SeparateDirs );
+ setView( view );
+ }
+ else
+ {
+ KFile::FileView view = static_cast<KFile::FileView>( m_viewKind & ~KFile::SeparateDirs );
+ setView( view );
+ }
+}
+
+void KDirOperator::slotDefaultPreview()
+{
+ m_viewKind = m_viewKind | KFile::PreviewContents;
+ if ( !myPreview ) {
+ myPreview = new KFileMetaPreview( this );
+ (static_cast<KToggleAction*>( myActionCollection->action("preview") ))->setChecked(true);
+ }
+
+ setView( static_cast<KFile::FileView>(m_viewKind) );
+}
+
+void KDirOperator::slotSortByName()
+{
+ int sorting = (m_fileView->sorting()) & ~TQDir::SortByMask;
+ m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::Name ));
+ mySorting = m_fileView->sorting();
+ caseInsensitiveAction->setEnabled( true );
+}
+
+void KDirOperator::slotSortBySize()
+{
+ int sorting = (m_fileView->sorting()) & ~TQDir::SortByMask;
+ m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::Size ));
+ mySorting = m_fileView->sorting();
+ caseInsensitiveAction->setEnabled( false );
+}
+
+void KDirOperator::slotSortByDate()
+{
+ int sorting = (m_fileView->sorting()) & ~TQDir::SortByMask;
+ m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::Time ));
+ mySorting = m_fileView->sorting();
+ caseInsensitiveAction->setEnabled( false );
+}
+
+void KDirOperator::slotSortReversed()
+{
+ if ( m_fileView )
+ m_fileView->sortReversed();
+}
+
+void KDirOperator::slotToggleDirsFirst()
+{
+ TQDir::SortSpec sorting = m_fileView->sorting();
+ if ( !KFile::isSortDirsFirst( sorting ) )
+ m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::DirsFirst ));
+ else
+ m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting & ~TQDir::DirsFirst));
+ mySorting = m_fileView->sorting();
+}
+
+void KDirOperator::slotToggleIgnoreCase()
+{
+ TQDir::SortSpec sorting = m_fileView->sorting();
+ if ( !KFile::isSortCaseInsensitive( sorting ) )
+ m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting | TQDir::IgnoreCase ));
+ else
+ m_fileView->setSorting( static_cast<TQDir::SortSpec>( sorting & ~TQDir::IgnoreCase));
+ mySorting = m_fileView->sorting();
+}
+
+void KDirOperator::mkdir()
+{
+ bool ok;
+ TQString where = url().pathOrURL();
+ TQString name = i18n( "New Folder" );
+ if ( url().isLocalFile() && TQFileInfo( url().path(+1) + name ).exists() )
+ name = TDEIO::RenameDlg::suggestName( url(), name );
+
+ TQString dir = KInputDialog::getText( i18n( "New Folder" ),
+ i18n( "Create new folder in:\n%1" ).arg( where ),
+ name, &ok, this);
+ if (ok)
+ mkdir( TDEIO::encodeFileName( dir ), true );
+}
+
+bool KDirOperator::mkdir( const TQString& directory, bool enterDirectory )
+{
+ // Creates "directory", relative to the current directory (currUrl).
+ // The given path may contain any number directories, existant or not.
+ // They will all be created, if possible.
+
+ bool writeOk = false;
+ bool exists = false;
+ KURL url( currUrl );
+
+ TQStringList dirs = TQStringList::split( TQDir::separator(), directory );
+ TQStringList::ConstIterator it = dirs.begin();
+
+ for ( ; it != dirs.end(); ++it )
+ {
+ url.addPath( *it );
+ exists = TDEIO::NetAccess::exists( url, false, 0 );
+ writeOk = !exists && TDEIO::NetAccess::mkdir( url, topLevelWidget() );
+ }
+
+ if ( exists ) // url was already existant
+ {
+ KMessageBox::sorry(viewWidget(), i18n("A file or folder named %1 already exists.").arg(url.pathOrURL()));
+ enterDirectory = false;
+ }
+ else if ( !writeOk ) {
+ KMessageBox::sorry(viewWidget(), i18n("You do not have permission to "
+ "create that folder." ));
+ }
+ else if ( enterDirectory ) {
+ setURL( url, true );
+ }
+
+ return writeOk;
+}
+
+TDEIO::DeleteJob * KDirOperator::del( const KFileItemList& items,
+ bool ask, bool showProgress )
+{
+ return del( items, this, ask, showProgress );
+}
+
+TDEIO::DeleteJob * KDirOperator::del( const KFileItemList& items,
+ TQWidget *parent,
+ bool ask, bool showProgress )
+{
+ if ( items.isEmpty() ) {
+ KMessageBox::information( parent,
+ i18n("You did not select a file to delete."),
+ i18n("Nothing to Delete") );
+ return 0L;
+ }
+
+ KURL::List urls;
+ TQStringList files;
+ KFileItemListIterator it( items );
+
+ for ( ; it.current(); ++it ) {
+ KURL url = (*it)->url();
+ urls.append( url );
+ if ( url.isLocalFile() )
+ files.append( url.path() );
+ else
+ files.append( url.prettyURL() );
+ }
+
+ bool doIt = !ask;
+ if ( ask ) {
+ int ret;
+ if ( items.count() == 1 ) {
+ ret = KMessageBox::warningContinueCancel( parent,
+ i18n( "<qt>Do you really want to delete\n <b>'%1'</b>?</qt>" )
+ .arg( files.first() ),
+ i18n("Delete File"),
+ KStdGuiItem::del(), "AskForDelete" );
+ }
+ else
+ ret = KMessageBox::warningContinueCancelList( parent,
+ i18n("Do you really want to delete this item?", "Do you really want to delete these %n items?", items.count() ),
+ files,
+ i18n("Delete Files"),
+ KStdGuiItem::del(), "AskForDelete" );
+ doIt = (ret == KMessageBox::Continue);
+ }
+
+ if ( doIt ) {
+ TDEIO::DeleteJob *job = TDEIO::del( urls, false, showProgress );
+ job->setWindow (topLevelWidget());
+ job->setAutoErrorHandlingEnabled( true, parent );
+ return job;
+ }
+
+ return 0L;
+}
+
+void KDirOperator::deleteSelected()
+{
+ if ( !m_fileView )
+ return;
+
+ const KFileItemList *list = m_fileView->selectedItems();
+ if ( list )
+ del( *list );
+}
+
+TDEIO::CopyJob * KDirOperator::trash( const KFileItemList& items,
+ TQWidget *parent,
+ bool ask, bool showProgress )
+{
+ if ( items.isEmpty() ) {
+ KMessageBox::information( parent,
+ i18n("You did not select a file to trash."),
+ i18n("Nothing to Trash") );
+ return 0L;
+ }
+
+ KURL::List urls;
+ TQStringList files;
+ KFileItemListIterator it( items );
+
+ for ( ; it.current(); ++it ) {
+ KURL url = (*it)->url();
+ urls.append( url );
+ if ( url.isLocalFile() )
+ files.append( url.path() );
+ else
+ files.append( url.prettyURL() );
+ }
+
+ bool doIt = !ask;
+ if ( ask ) {
+ int ret;
+ if ( items.count() == 1 ) {
+ ret = KMessageBox::warningContinueCancel( parent,
+ i18n( "<qt>Do you really want to trash\n <b>'%1'</b>?</qt>" )
+ .arg( files.first() ),
+ i18n("Trash File"),
+ KGuiItem(i18n("to trash", "&Trash"),"edittrash"), "AskForTrash" );
+ }
+ else
+ ret = KMessageBox::warningContinueCancelList( parent,
+ i18n("translators: not called for n == 1", "Do you really want to trash these %n items?", items.count() ),
+ files,
+ i18n("Trash Files"),
+ KGuiItem(i18n("to trash", "&Trash"),"edittrash"), "AskForTrash" );
+ doIt = (ret == KMessageBox::Continue);
+ }
+
+ if ( doIt ) {
+ TDEIO::CopyJob *job = TDEIO::trash( urls, showProgress );
+ job->setWindow (topLevelWidget());
+ job->setAutoErrorHandlingEnabled( true, parent );
+ return job;
+ }
+
+ return 0L;
+}
+
+void KDirOperator::trashSelected(KAction::ActivationReason reason, TQt::ButtonState state)
+{
+ if ( !m_fileView )
+ return;
+
+ if ( reason == KAction::PopupMenuActivation && ( state & ShiftButton ) ) {
+ deleteSelected();
+ return;
+ }
+
+ const KFileItemList *list = m_fileView->selectedItems();
+ if ( list )
+ trash( *list, this );
+}
+
+void KDirOperator::close()
+{
+ resetCursor();
+ pendingMimeTypes.clear();
+ myCompletion.clear();
+ myDirCompletion.clear();
+ myCompleteListDirty = true;
+ dir->stop();
+}
+
+void KDirOperator::checkPath(const TQString &, bool /*takeFiles*/) // SLOT
+{
+#if 0
+ // copy the argument in a temporary string
+ TQString text = _txt;
+ // it's unlikely to happen, that at the beginning are spaces, but
+ // for the end, it happens quite often, I guess.
+ text = text.stripWhiteSpace();
+ // if the argument is no URL (the check is quite fragil) and it's
+ // no absolute path, we add the current directory to get a correct url
+ if (text.find(':') < 0 && text[0] != '/')
+ text.insert(0, currUrl);
+
+ // in case we have a selection defined and someone patched the file-
+ // name, we check, if the end of the new name is changed.
+ if (!selection.isNull()) {
+ int position = text.findRev('/');
+ ASSERT(position >= 0); // we already inserted the current dir in case
+ TQString filename = text.mid(position + 1, text.length());
+ if (filename != selection)
+ selection = TQString::null;
+ }
+
+ KURL u(text); // I have to take care of entered URLs
+ bool filenameEntered = false;
+
+ if (u.isLocalFile()) {
+ // the empty path is kind of a hack
+ KFileItem i("", u.path());
+ if (i.isDir())
+ setURL(text, true);
+ else {
+ if (takeFiles)
+ if (acceptOnlyExisting && !i.isFile())
+ warning("you entered an invalid URL");
+ else
+ filenameEntered = true;
+ }
+ } else
+ setURL(text, true);
+
+ if (filenameEntered) {
+ filename_ = u.url();
+ emit fileSelected(filename_);
+
+ TQApplication::restoreOverrideCursor();
+
+ accept();
+ }
+#endif
+ kdDebug(tdefile_area) << "TODO KDirOperator::checkPath()" << endl;
+}
+
+void KDirOperator::setURL(const KURL& _newurl, bool clearforward)
+{
+ KURL newurl;
+
+ if ( !_newurl.isValid() )
+ newurl.setPath( TQDir::homeDirPath() );
+ else
+ newurl = _newurl;
+
+ TQString pathstr = newurl.path(+1);
+ newurl.setPath(pathstr);
+
+ // already set
+ if ( newurl.equals( currUrl, true ) )
+ return;
+
+ if ( !isReadable( newurl ) ) {
+ // maybe newurl is a file? check its parent directory
+ newurl.cd(TQString::fromLatin1(".."));
+ if ( !isReadable( newurl ) ) {
+ resetCursor();
+ KMessageBox::error(viewWidget(),
+ i18n("The specified folder does not exist "
+ "or was not readable."));
+ return;
+ }
+ }
+
+ if (clearforward) {
+ // autodelete should remove this one
+ backStack.push(new KURL(currUrl));
+ forwardStack.clear();
+ }
+
+ d->lastURL = currUrl.url(-1);
+ currUrl = newurl;
+
+ pathChanged();
+ emit urlEntered(newurl);
+
+ // enable/disable actions
+ forwardAction->setEnabled( !forwardStack.isEmpty() );
+ backAction->setEnabled( !backStack.isEmpty() );
+ upAction->setEnabled( !isRoot() );
+
+ openURL( newurl );
+}
+
+void KDirOperator::updateDir()
+{
+ dir->emitChanges();
+ if ( m_fileView )
+ m_fileView->listingCompleted();
+}
+
+void KDirOperator::rereadDir()
+{
+ pathChanged();
+ openURL( currUrl, false, true );
+}
+
+
+bool KDirOperator::openURL( const KURL& url, bool keep, bool reload )
+{
+ bool result = dir->openURL( url, keep, reload );
+ if ( !result ) // in that case, neither completed() nor canceled() will be emitted by KDL
+ slotCanceled();
+
+ return result;
+}
+
+// Protected
+void KDirOperator::pathChanged()
+{
+ if (!m_fileView)
+ return;
+
+ pendingMimeTypes.clear();
+ m_fileView->clear();
+ myCompletion.clear();
+ myDirCompletion.clear();
+
+ // it may be, that we weren't ready at this time
+ TQApplication::restoreOverrideCursor();
+
+ // when TDEIO::Job emits finished, the slot will restore the cursor
+ TQApplication::setOverrideCursor( tqwaitCursor );
+
+ if ( !isReadable( currUrl )) {
+ KMessageBox::error(viewWidget(),
+ i18n("The specified folder does not exist "
+ "or was not readable."));
+ if (backStack.isEmpty())
+ home();
+ else
+ back();
+ }
+}
+
+void KDirOperator::slotRedirected( const KURL& newURL )
+{
+ currUrl = newURL;
+ pendingMimeTypes.clear();
+ myCompletion.clear();
+ myDirCompletion.clear();
+ myCompleteListDirty = true;
+ emit urlEntered( newURL );
+}
+
+// Code pinched from kfm then hacked
+void KDirOperator::back()
+{
+ if ( backStack.isEmpty() )
+ return;
+
+ forwardStack.push( new KURL(currUrl) );
+
+ KURL *s = backStack.pop();
+
+ setURL(*s, false);
+ delete s;
+}
+
+// Code pinched from kfm then hacked
+void KDirOperator::forward()
+{
+ if ( forwardStack.isEmpty() )
+ return;
+
+ backStack.push(new KURL(currUrl));
+
+ KURL *s = forwardStack.pop();
+ setURL(*s, false);
+ delete s;
+}
+
+KURL KDirOperator::url() const
+{
+ return currUrl;
+}
+
+void KDirOperator::cdUp()
+{
+ KURL tmp(currUrl);
+ tmp.cd(TQString::fromLatin1(".."));
+ setURL(tmp, true);
+}
+
+void KDirOperator::home()
+{
+ KURL u;
+ u.setPath( TQDir::homeDirPath() );
+ setURL(u, true);
+}
+
+void KDirOperator::clearFilter()
+{
+ dir->setNameFilter( TQString::null );
+ dir->clearMimeFilter();
+ checkPreviewSupport();
+}
+
+void KDirOperator::setNameFilter(const TQString& filter)
+{
+ dir->setNameFilter(filter);
+ checkPreviewSupport();
+}
+
+void KDirOperator::setMimeFilter( const TQStringList& mimetypes )
+{
+ dir->setMimeFilter( mimetypes );
+ checkPreviewSupport();
+}
+
+bool KDirOperator::checkPreviewSupport()
+{
+ KToggleAction *previewAction = static_cast<KToggleAction*>( myActionCollection->action( "preview" ));
+
+ bool hasPreviewSupport = false;
+ TDEConfig *kc = TDEGlobal::config();
+ TDEConfigGroupSaver cs( kc, ConfigGroup );
+ if ( kc->readBoolEntry( "Show Default Preview", true ) )
+ hasPreviewSupport = checkPreviewInternal();
+
+ previewAction->setEnabled( hasPreviewSupport );
+ return hasPreviewSupport;
+}
+
+bool KDirOperator::checkPreviewInternal() const
+{
+ TQStringList supported = TDEIO::PreviewJob::supportedMimeTypes();
+ // no preview support for directories?
+ if ( dirOnlyMode() && supported.findIndex( "inode/directory" ) == -1 )
+ return false;
+
+ TQStringList mimeTypes = dir->mimeFilters();
+ TQStringList nameFilter = TQStringList::split( " ", dir->nameFilter() );
+
+ if ( mimeTypes.isEmpty() && nameFilter.isEmpty() && !supported.isEmpty() )
+ return true;
+ else {
+ TQRegExp r;
+ r.setWildcard( true ); // the "mimetype" can be "image/*"
+
+ if ( !mimeTypes.isEmpty() ) {
+ TQStringList::Iterator it = supported.begin();
+
+ for ( ; it != supported.end(); ++it ) {
+ r.setPattern( *it );
+
+ TQStringList result = mimeTypes.grep( r );
+ if ( !result.isEmpty() ) { // matches! -> we want previews
+ return true;
+ }
+ }
+ }
+
+ if ( !nameFilter.isEmpty() ) {
+ // find the mimetypes of all the filter-patterns and
+ KServiceTypeFactory *fac = KServiceTypeFactory::self();
+ TQStringList::Iterator it1 = nameFilter.begin();
+ for ( ; it1 != nameFilter.end(); ++it1 ) {
+ if ( (*it1) == "*" ) {
+ return true;
+ }
+
+ KMimeType *mt = fac->findFromPattern( *it1 );
+ if ( !mt )
+ continue;
+ TQString mime = mt->name();
+ delete mt;
+
+ // the "mimetypes" we get from the PreviewJob can be "image/*"
+ // so we need to check in wildcard mode
+ TQStringList::Iterator it2 = supported.begin();
+ for ( ; it2 != supported.end(); ++it2 ) {
+ r.setPattern( *it2 );
+ if ( r.search( mime ) != -1 ) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+
+ return false;
+}
+
+KFileView* KDirOperator::createView( TQWidget* parent, KFile::FileView view )
+{
+ KFileView* new_view = 0L;
+ bool separateDirs = KFile::isSeparateDirs( view );
+ bool preview = ( KFile::isPreviewInfo(view) || KFile::isPreviewContents( view ) );
+
+ if ( separateDirs || preview ) {
+ KCombiView *combi = 0L;
+ if (separateDirs)
+ {
+ combi = new KCombiView( parent, "combi view" );
+ combi->setOnlyDoubleClickSelectsFiles(d->onlyDoubleClickSelectsFiles);
+ }
+
+ KFileView* v = 0L;
+ if ( KFile::isSimpleView( view ) )
+ v = createView( combi, KFile::Simple );
+ else
+ v = createView( combi, KFile::Detail );
+
+ v->setOnlyDoubleClickSelectsFiles(d->onlyDoubleClickSelectsFiles);
+
+ if (combi)
+ combi->setRight( v );
+
+ if (preview)
+ {
+ KFilePreview* pView = new KFilePreview( combi ? combi : v, parent, "preview" );
+ pView->setOnlyDoubleClickSelectsFiles(d->onlyDoubleClickSelectsFiles);
+ new_view = pView;
+ }
+ else
+ new_view = combi;
+ }
+ else if ( KFile::isDetailView( view ) && !preview ) {
+ new_view = new KFileDetailView( parent, "detail view");
+ new_view->setViewName( i18n("Detailed View") );
+ }
+ else /* if ( KFile::isSimpleView( view ) && !preview ) */ {
+ KFileIconView *iconView = new KFileIconView( parent, "simple view");
+ new_view = iconView;
+ new_view->setViewName( i18n("Short View") );
+ }
+
+ new_view->widget()->setAcceptDrops(acceptDrops());
+ return new_view;
+}
+
+void KDirOperator::setAcceptDrops(bool b)
+{
+ if (m_fileView)
+ m_fileView->widget()->setAcceptDrops(b);
+ TQWidget::setAcceptDrops(b);
+}
+
+void KDirOperator::setDropOptions(int options)
+{
+ d->dropOptions = options;
+ if (m_fileView)
+ m_fileView->setDropOptions(options);
+}
+
+void KDirOperator::setView( KFile::FileView view )
+{
+ bool separateDirs = KFile::isSeparateDirs( view );
+ bool preview=( KFile::isPreviewInfo(view) || KFile::isPreviewContents( view ) );
+
+ if (view == KFile::Default) {
+ if ( KFile::isDetailView( (KFile::FileView) defaultView ) )
+ view = KFile::Detail;
+ else
+ view = KFile::Simple;
+
+ separateDirs = KFile::isSeparateDirs( static_cast<KFile::FileView>(defaultView) );
+ preview = ( KFile::isPreviewInfo( static_cast<KFile::FileView>(defaultView) ) ||
+ KFile::isPreviewContents( static_cast<KFile::FileView>(defaultView) ) )
+ && myActionCollection->action("preview")->isEnabled();
+
+ if ( preview ) { // instantiates KFileMetaPreview and calls setView()
+ m_viewKind = defaultView;
+ slotDefaultPreview();
+ return;
+ }
+ else if ( !separateDirs )
+ separateDirsAction->setChecked(true);
+ }
+
+ // if we don't have any files, we can't separate dirs from files :)
+ if ( (mode() & KFile::File) == 0 &&
+ (mode() & KFile::Files) == 0 ) {
+ separateDirs = false;
+ separateDirsAction->setEnabled( false );
+ }
+
+ m_viewKind = static_cast<int>(view) | (separateDirs ? KFile::SeparateDirs : 0);
+ view = static_cast<KFile::FileView>(m_viewKind);
+
+ KFileView *new_view = createView( this, view );
+ if ( preview ) {
+ // we keep the preview-_widget_ around, but not the KFilePreview.
+ // KFilePreview::setPreviewWidget handles the reparenting for us
+ static_cast<KFilePreview*>(new_view)->setPreviewWidget(myPreview, url());
+ }
+
+ setView( new_view );
+}
+
+
+void KDirOperator::connectView(KFileView *view)
+{
+ // TODO: do a real timer and restart it after that
+ pendingMimeTypes.clear();
+ bool listDir = true;
+
+ if ( dirOnlyMode() )
+ view->setViewMode(KFileView::Directories);
+ else
+ view->setViewMode(KFileView::All);
+
+ if ( myMode & KFile::Files )
+ view->setSelectionMode( KFile::Extended );
+ else
+ view->setSelectionMode( KFile::Single );
+
+ if (m_fileView)
+ {
+ if ( d->config ) // save and restore the views' configuration
+ {
+ m_fileView->writeConfig( d->config, d->configGroup );
+ view->readConfig( d->config, d->configGroup );
+ }
+
+ // transfer the state from old view to new view
+ view->clear();
+ view->addItemList( *m_fileView->items() );
+ listDir = false;
+
+ if ( m_fileView->widget()->hasFocus() )
+ view->widget()->setFocus();
+
+ KFileItem *oldCurrentItem = m_fileView->currentFileItem();
+ if ( oldCurrentItem ) {
+ view->setCurrentItem( oldCurrentItem );
+ view->setSelected( oldCurrentItem, false );
+ view->ensureItemVisible( oldCurrentItem );
+ }
+
+ const KFileItemList *oldSelected = m_fileView->selectedItems();
+ if ( !oldSelected->isEmpty() ) {
+ KFileItemListIterator it( *oldSelected );
+ for ( ; it.current(); ++it )
+ view->setSelected( it.current(), true );
+ }
+
+ m_fileView->widget()->hide();
+ delete m_fileView;
+ }
+
+ else
+ {
+ if ( d->config )
+ view->readConfig( d->config, d->configGroup );
+ }
+
+ m_fileView = view;
+ m_fileView->setDropOptions(d->dropOptions);
+ viewActionCollection = 0L;
+ KFileViewSignaler *sig = view->signaler();
+
+ connect(sig, TQT_SIGNAL( activatedMenu(const KFileItem *, const TQPoint& ) ),
+ this, TQT_SLOT( activatedMenu(const KFileItem *, const TQPoint& )));
+ connect(sig, TQT_SIGNAL( dirActivated(const KFileItem *) ),
+ this, TQT_SLOT( selectDir(const KFileItem*) ) );
+ connect(sig, TQT_SIGNAL( fileSelected(const KFileItem *) ),
+ this, TQT_SLOT( selectFile(const KFileItem*) ) );
+ connect(sig, TQT_SIGNAL( fileHighlighted(const KFileItem *) ),
+ this, TQT_SLOT( highlightFile(const KFileItem*) ));
+ connect(sig, TQT_SIGNAL( sortingChanged( TQDir::SortSpec ) ),
+ this, TQT_SLOT( slotViewSortingChanged( TQDir::SortSpec )));
+ connect(sig, TQT_SIGNAL( dropped(const KFileItem *, TQDropEvent*, const KURL::List&) ),
+ this, TQT_SIGNAL( dropped(const KFileItem *, TQDropEvent*, const KURL::List&)) );
+
+ if ( reverseAction->isChecked() != m_fileView->isReversed() )
+ slotSortReversed();
+
+ updateViewActions();
+ m_fileView->widget()->resize(size());
+ m_fileView->widget()->show();
+
+ if ( listDir ) {
+ TQApplication::setOverrideCursor( tqwaitCursor );
+ openURL( currUrl );
+ }
+ else
+ view->listingCompleted();
+}
+
+KFile::Mode KDirOperator::mode() const
+{
+ return myMode;
+}
+
+void KDirOperator::setMode(KFile::Mode m)
+{
+ if (myMode == m)
+ return;
+
+ myMode = m;
+
+ dir->setDirOnlyMode( dirOnlyMode() );
+
+ // reset the view with the different mode
+ setView( static_cast<KFile::FileView>(m_viewKind) );
+}
+
+void KDirOperator::setView(KFileView *view)
+{
+ if ( view == m_fileView ) {
+ return;
+ }
+
+ setFocusProxy(view->widget());
+ view->setSorting( mySorting );
+ view->setOnlyDoubleClickSelectsFiles( d->onlyDoubleClickSelectsFiles );
+ connectView(view); // also deletes the old view
+
+ emit viewChanged( view );
+}
+
+void KDirOperator::setDirLister( KDirLister *lister )
+{
+ if ( lister == dir ) // sanity check
+ return;
+
+ delete dir;
+ dir = lister;
+
+ dir->setAutoUpdate( true );
+
+ TQWidget* mainWidget = topLevelWidget();
+ dir->setMainWindow (mainWidget);
+ kdDebug (tdefile_area) << "mainWidget=" << mainWidget << endl;
+
+ connect( dir, TQT_SIGNAL( percent( int )),
+ TQT_SLOT( slotProgress( int ) ));
+ connect( dir, TQT_SIGNAL(started( const KURL& )), TQT_SLOT(slotStarted()));
+ connect( dir, TQT_SIGNAL(newItems(const KFileItemList &)),
+ TQT_SLOT(insertNewFiles(const KFileItemList &)));
+ connect( dir, TQT_SIGNAL(completed()), TQT_SLOT(slotIOFinished()));
+ connect( dir, TQT_SIGNAL(canceled()), TQT_SLOT(slotCanceled()));
+ connect( dir, TQT_SIGNAL(deleteItem(KFileItem *)),
+ TQT_SLOT(itemDeleted(KFileItem *)));
+ connect( dir, TQT_SIGNAL(redirection( const KURL& )),
+ TQT_SLOT( slotRedirected( const KURL& )));
+ connect( dir, TQT_SIGNAL( clear() ), TQT_SLOT( slotClearView() ));
+ connect( dir, TQT_SIGNAL( refreshItems( const KFileItemList& ) ),
+ TQT_SLOT( slotRefreshItems( const KFileItemList& ) ) );
+}
+
+void KDirOperator::insertNewFiles(const KFileItemList &newone)
+{
+ if ( newone.isEmpty() || !m_fileView )
+ return;
+
+ myCompleteListDirty = true;
+ m_fileView->addItemList( newone );
+ emit updateInformation(m_fileView->numDirs(), m_fileView->numFiles());
+
+ KFileItem *item;
+ KFileItemListIterator it( newone );
+
+ while ( (item = it.current()) ) {
+ // highlight the dir we come from, if possible
+ if ( d->dirHighlighting && item->isDir() &&
+ item->url().url(-1) == d->lastURL ) {
+ m_fileView->setCurrentItem( item );
+ m_fileView->ensureItemVisible( item );
+ }
+
+ ++it;
+ }
+
+ TQTimer::singleShot(200, this, TQT_SLOT(resetCursor()));
+}
+
+void KDirOperator::selectDir(const KFileItem *item)
+{
+ setURL(item->url(), true);
+}
+
+void KDirOperator::itemDeleted(KFileItem *item)
+{
+ pendingMimeTypes.removeRef( item );
+ if ( m_fileView )
+ {
+ m_fileView->removeItem( static_cast<KFileItem *>( item ));
+ emit updateInformation(m_fileView->numDirs(), m_fileView->numFiles());
+ }
+}
+
+void KDirOperator::selectFile(const KFileItem *item)
+{
+ TQApplication::restoreOverrideCursor();
+
+ emit fileSelected( item );
+}
+
+void KDirOperator::setCurrentItem( const TQString& filename )
+{
+ if ( m_fileView ) {
+ const KFileItem *item = 0L;
+
+ if ( !filename.isNull() )
+ item = static_cast<KFileItem *>(dir->findByName( filename ));
+
+ m_fileView->clearSelection();
+ if ( item ) {
+ m_fileView->setCurrentItem( item );
+ m_fileView->setSelected( item, true );
+ m_fileView->ensureItemVisible( item );
+ }
+ }
+}
+
+TQString KDirOperator::makeCompletion(const TQString& string)
+{
+ if ( string.isEmpty() ) {
+ m_fileView->clearSelection();
+ return TQString::null;
+ }
+
+ prepareCompletionObjects();
+ return myCompletion.makeCompletion( string );
+}
+
+TQString KDirOperator::makeDirCompletion(const TQString& string)
+{
+ if ( string.isEmpty() ) {
+ m_fileView->clearSelection();
+ return TQString::null;
+ }
+
+ prepareCompletionObjects();
+ return myDirCompletion.makeCompletion( string );
+}
+
+void KDirOperator::prepareCompletionObjects()
+{
+ if ( !m_fileView )
+ return;
+
+ if ( myCompleteListDirty ) { // create the list of all possible completions
+ KFileItemListIterator it( *(m_fileView->items()) );
+ for( ; it.current(); ++it ) {
+ KFileItem *item = it.current();
+
+ myCompletion.addItem( item->name() );
+ if ( item->isDir() )
+ myDirCompletion.addItem( item->name() );
+ }
+ myCompleteListDirty = false;
+ }
+}
+
+void KDirOperator::slotCompletionMatch(const TQString& match)
+{
+ setCurrentItem( match );
+ emit completion( match );
+}
+
+void KDirOperator::setupActions()
+{
+ myActionCollection = new KActionCollection( topLevelWidget(), TQT_TQOBJECT(this), "KDirOperator::myActionCollection" );
+
+ actionMenu = new KActionMenu( i18n("Menu"), myActionCollection, "popupMenu" );
+ upAction = KStdAction::up( TQT_TQOBJECT(this), TQT_SLOT( cdUp() ), myActionCollection, "up" );
+ upAction->setText( i18n("Parent Folder") );
+ backAction = KStdAction::back( TQT_TQOBJECT(this), TQT_SLOT( back() ), myActionCollection, "back" );
+ forwardAction = KStdAction::forward( TQT_TQOBJECT(this), TQT_SLOT(forward()), myActionCollection, "forward" );
+ homeAction = KStdAction::home( TQT_TQOBJECT(this), TQT_SLOT( home() ), myActionCollection, "home" );
+ homeAction->setText(i18n("Home Folder"));
+ reloadAction = KStdAction::redisplay( TQT_TQOBJECT(this), TQT_SLOT(rereadDir()), myActionCollection, "reload" );
+ actionSeparator = new KActionSeparator( myActionCollection, "separator" );
+ d->viewActionSeparator = new KActionSeparator( myActionCollection,
+ "viewActionSeparator" );
+ mkdirAction = new KAction( i18n("New Folder..."), 0,
+ TQT_TQOBJECT(this), TQT_SLOT( mkdir() ), myActionCollection, "mkdir" );
+ KAction* trash = new KAction( i18n( "Move to Trash" ), "edittrash", Key_Delete, myActionCollection, "trash" );
+ connect( trash, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState ) ),
+ this, TQT_SLOT( trashSelected( KAction::ActivationReason, TQt::ButtonState ) ) );
+ new KAction( i18n( "Delete" ), "editdelete", SHIFT+Key_Delete, TQT_TQOBJECT(this),
+ TQT_SLOT( deleteSelected() ), myActionCollection, "delete" );
+ mkdirAction->setIcon( TQString::fromLatin1("folder_new") );
+ reloadAction->setText( i18n("Reload") );
+ reloadAction->setShortcut( KStdAccel::shortcut( KStdAccel::Reload ));
+
+
+ // the sort menu actions
+ sortActionMenu = new KActionMenu( i18n("Sorting"), myActionCollection, "sorting menu");
+ byNameAction = new KRadioAction( i18n("By Name"), 0,
+ TQT_TQOBJECT(this), TQT_SLOT( slotSortByName() ),
+ myActionCollection, "by name" );
+ byDateAction = new KRadioAction( i18n("By Date"), 0,
+ TQT_TQOBJECT(this), TQT_SLOT( slotSortByDate() ),
+ myActionCollection, "by date" );
+ bySizeAction = new KRadioAction( i18n("By Size"), 0,
+ TQT_TQOBJECT(this), TQT_SLOT( slotSortBySize() ),
+ myActionCollection, "by size" );
+ reverseAction = new KToggleAction( i18n("Reverse"), 0,
+ TQT_TQOBJECT(this), TQT_SLOT( slotSortReversed() ),
+ myActionCollection, "reversed" );
+
+ TQString sortGroup = TQString::fromLatin1("sort");
+ byNameAction->setExclusiveGroup( sortGroup );
+ byDateAction->setExclusiveGroup( sortGroup );
+ bySizeAction->setExclusiveGroup( sortGroup );
+
+
+ dirsFirstAction = new KToggleAction( i18n("Folders First"), 0,
+ myActionCollection, "dirs first");
+ caseInsensitiveAction = new KToggleAction(i18n("Case Insensitive"), 0,
+ myActionCollection, "case insensitive" );
+
+ connect( dirsFirstAction, TQT_SIGNAL( toggled( bool ) ),
+ TQT_SLOT( slotToggleDirsFirst() ));
+ connect( caseInsensitiveAction, TQT_SIGNAL( toggled( bool ) ),
+ TQT_SLOT( slotToggleIgnoreCase() ));
+
+
+
+ // the view menu actions
+ viewActionMenu = new KActionMenu( i18n("&View"), myActionCollection, "view menu" );
+ connect( viewActionMenu->popupMenu(), TQT_SIGNAL( aboutToShow() ),
+ TQT_SLOT( insertViewDependentActions() ));
+
+ shortAction = new KRadioAction( i18n("Short View"), "view_multicolumn",
+ KShortcut(), myActionCollection, "short view" );
+ detailedAction = new KRadioAction( i18n("Detailed View"), "view_detailed",
+ KShortcut(), myActionCollection, "detailed view" );
+
+ showHiddenAction = new KToggleAction( i18n("Show Hidden Files"), KShortcut(),
+ myActionCollection, "show hidden" );
+// showHiddenAction->setCheckedState( i18n("Hide Hidden Files") );
+ separateDirsAction = new KToggleAction( i18n("Separate Folders"), KShortcut(),
+ TQT_TQOBJECT(this),
+ TQT_SLOT(slotSeparateDirs()),
+ myActionCollection, "separate dirs" );
+ KToggleAction *previewAction = new KToggleAction(i18n("Show Preview"),
+ "thumbnail", KShortcut(),
+ myActionCollection,
+ "preview" );
+ previewAction->setCheckedState(i18n("Hide Preview"));
+ connect( previewAction, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( togglePreview( bool )));
+
+
+ TQString viewGroup = TQString::fromLatin1("view");
+ shortAction->setExclusiveGroup( viewGroup );
+ detailedAction->setExclusiveGroup( viewGroup );
+
+ connect( shortAction, TQT_SIGNAL( activated() ),
+ TQT_SLOT( slotSimpleView() ));
+ connect( detailedAction, TQT_SIGNAL( activated() ),
+ TQT_SLOT( slotDetailedView() ));
+ connect( showHiddenAction, TQT_SIGNAL( toggled( bool ) ),
+ TQT_SLOT( slotToggleHidden( bool ) ));
+
+ new KAction( i18n("Properties"), KShortcut(ALT+Key_Return), TQT_TQOBJECT(this),
+ TQT_SLOT(slotProperties()), myActionCollection, "properties" );
+}
+
+void KDirOperator::setupMenu()
+{
+ setupMenu(AllActions);
+}
+
+void KDirOperator::setupMenu(int whichActions)
+{
+ // first fill the submenus (sort and view)
+ sortActionMenu->popupMenu()->clear();
+ sortActionMenu->insert( byNameAction );
+ sortActionMenu->insert( byDateAction );
+ sortActionMenu->insert( bySizeAction );
+ sortActionMenu->insert( actionSeparator );
+ sortActionMenu->insert( reverseAction );
+ sortActionMenu->insert( dirsFirstAction );
+ sortActionMenu->insert( caseInsensitiveAction );
+
+ // now plug everything into the popupmenu
+ actionMenu->popupMenu()->clear();
+ if (whichActions & NavActions)
+ {
+ actionMenu->insert( upAction );
+ actionMenu->insert( backAction );
+ actionMenu->insert( forwardAction );
+ actionMenu->insert( homeAction );
+ actionMenu->insert( actionSeparator );
+ }
+
+ if (whichActions & FileActions)
+ {
+ actionMenu->insert( mkdirAction );
+ if (currUrl.isLocalFile() && !(TDEApplication::keyboardMouseState() & TQt::ShiftButton))
+ actionMenu->insert( myActionCollection->action( "trash" ) );
+ TDEConfig *globalconfig = TDEGlobal::config();
+ TDEConfigGroupSaver cs( globalconfig, TQString::fromLatin1("KDE") );
+ if (!currUrl.isLocalFile() || (TDEApplication::keyboardMouseState() & TQt::ShiftButton) ||
+ globalconfig->readBoolEntry("ShowDeleteCommand", false))
+ actionMenu->insert( myActionCollection->action( "delete" ) );
+ actionMenu->insert( actionSeparator );
+ }
+
+ if (whichActions & SortActions)
+ {
+ actionMenu->insert( sortActionMenu );
+ actionMenu->insert( actionSeparator );
+ }
+
+ if (whichActions & ViewActions)
+ {
+ actionMenu->insert( viewActionMenu );
+ actionMenu->insert( actionSeparator );
+ }
+
+ if (whichActions & FileActions)
+ {
+ actionMenu->insert( myActionCollection->action( "properties" ) );
+ }
+}
+
+void KDirOperator::updateSortActions()
+{
+ if ( KFile::isSortByName( mySorting ) )
+ byNameAction->setChecked( true );
+ else if ( KFile::isSortByDate( mySorting ) )
+ byDateAction->setChecked( true );
+ else if ( KFile::isSortBySize( mySorting ) )
+ bySizeAction->setChecked( true );
+
+ dirsFirstAction->setChecked( KFile::isSortDirsFirst( mySorting ) );
+ caseInsensitiveAction->setChecked( KFile::isSortCaseInsensitive(mySorting) );
+ caseInsensitiveAction->setEnabled( KFile::isSortByName( mySorting ) );
+
+ if ( m_fileView )
+ reverseAction->setChecked( m_fileView->isReversed() );
+}
+
+void KDirOperator::updateViewActions()
+{
+ KFile::FileView fv = static_cast<KFile::FileView>( m_viewKind );
+
+ separateDirsAction->setChecked( KFile::isSeparateDirs( fv ) &&
+ separateDirsAction->isEnabled() );
+
+ shortAction->setChecked( KFile::isSimpleView( fv ));
+ detailedAction->setChecked( KFile::isDetailView( fv ));
+}
+
+void KDirOperator::readConfig( TDEConfig *kc, const TQString& group )
+{
+ if ( !kc )
+ return;
+ TQString oldGroup = kc->group();
+ if ( !group.isEmpty() )
+ kc->setGroup( group );
+
+ defaultView = 0;
+ int sorting = 0;
+
+ TQString viewStyle = kc->readEntry( TQString::fromLatin1("View Style"),
+ TQString::fromLatin1("Simple") );
+ if ( viewStyle == TQString::fromLatin1("Detail") )
+ defaultView |= KFile::Detail;
+ else
+ defaultView |= KFile::Simple;
+ if ( kc->readBoolEntry( TQString::fromLatin1("Separate Directories"),
+ DefaultMixDirsAndFiles ) )
+ defaultView |= KFile::SeparateDirs;
+ if ( kc->readBoolEntry(TQString::fromLatin1("Show Preview"), false))
+ defaultView |= KFile::PreviewContents;
+
+ if ( kc->readBoolEntry( TQString::fromLatin1("Sort case insensitively"),
+ DefaultCaseInsensitive ) )
+ sorting |= TQDir::IgnoreCase;
+ if ( kc->readBoolEntry( TQString::fromLatin1("Sort directories first"),
+ DefaultDirsFirst ) )
+ sorting |= TQDir::DirsFirst;
+
+
+ TQString name = TQString::fromLatin1("Name");
+ TQString sortBy = kc->readEntry( TQString::fromLatin1("Sort by"), name );
+ if ( sortBy == name )
+ sorting |= TQDir::Name;
+ else if ( sortBy == TQString::fromLatin1("Size") )
+ sorting |= TQDir::Size;
+ else if ( sortBy == TQString::fromLatin1("Date") )
+ sorting |= TQDir::Time;
+
+ mySorting = static_cast<TQDir::SortSpec>( sorting );
+ setSorting( mySorting );
+
+
+ if ( kc->readBoolEntry( TQString::fromLatin1("Show hidden files"),
+ DefaultShowHidden ) ) {
+ showHiddenAction->setChecked( true );
+ dir->setShowingDotFiles( true );
+ }
+ if ( kc->readBoolEntry( TQString::fromLatin1("Sort reversed"),
+ DefaultSortReversed ) )
+ reverseAction->setChecked( true );
+
+ kc->setGroup( oldGroup );
+}
+
+void KDirOperator::writeConfig( TDEConfig *kc, const TQString& group )
+{
+ if ( !kc )
+ return;
+
+ const TQString oldGroup = kc->group();
+
+ if ( !group.isEmpty() )
+ kc->setGroup( group );
+
+ TQString sortBy = TQString::fromLatin1("Name");
+ if ( KFile::isSortBySize( mySorting ) )
+ sortBy = TQString::fromLatin1("Size");
+ else if ( KFile::isSortByDate( mySorting ) )
+ sortBy = TQString::fromLatin1("Date");
+ kc->writeEntry( TQString::fromLatin1("Sort by"), sortBy );
+
+ kc->writeEntry( TQString::fromLatin1("Sort reversed"),
+ reverseAction->isChecked() );
+ kc->writeEntry( TQString::fromLatin1("Sort case insensitively"),
+ caseInsensitiveAction->isChecked() );
+ kc->writeEntry( TQString::fromLatin1("Sort directories first"),
+ dirsFirstAction->isChecked() );
+
+ // don't save the separate dirs or preview when an application specific
+ // preview is in use.
+ bool appSpecificPreview = false;
+ if ( myPreview ) {
+ TQWidget *preview = const_cast<TQWidget*>( myPreview ); // grmbl
+ KFileMetaPreview *tmp = dynamic_cast<KFileMetaPreview*>( preview );
+ appSpecificPreview = (tmp == 0L);
+ }
+
+ if ( !appSpecificPreview ) {
+ if ( separateDirsAction->isEnabled() )
+ kc->writeEntry( TQString::fromLatin1("Separate Directories"),
+ separateDirsAction->isChecked() );
+
+ KToggleAction *previewAction = static_cast<KToggleAction*>(myActionCollection->action("preview"));
+ if ( previewAction->isEnabled() ) {
+ bool hasPreview = previewAction->isChecked();
+ kc->writeEntry( TQString::fromLatin1("Show Preview"), hasPreview );
+ }
+ }
+
+ kc->writeEntry( TQString::fromLatin1("Show hidden files"),
+ showHiddenAction->isChecked() );
+
+ KFile::FileView fv = static_cast<KFile::FileView>( m_viewKind );
+ TQString style;
+ if ( KFile::isDetailView( fv ) )
+ style = TQString::fromLatin1("Detail");
+ else if ( KFile::isSimpleView( fv ) )
+ style = TQString::fromLatin1("Simple");
+ kc->writeEntry( TQString::fromLatin1("View Style"), style );
+
+ kc->setGroup( oldGroup );
+}
+
+
+void KDirOperator::resizeEvent( TQResizeEvent * )
+{
+ if (m_fileView)
+ m_fileView->widget()->resize( size() );
+
+ if ( TQT_BASE_OBJECT(progress->parent()) == TQT_BASE_OBJECT(this) ) // might be reparented into a statusbar
+ progress->move(2, height() - progress->height() -2);
+}
+
+void KDirOperator::setOnlyDoubleClickSelectsFiles( bool enable )
+{
+ d->onlyDoubleClickSelectsFiles = enable;
+ if ( m_fileView )
+ m_fileView->setOnlyDoubleClickSelectsFiles( enable );
+}
+
+bool KDirOperator::onlyDoubleClickSelectsFiles() const
+{
+ return d->onlyDoubleClickSelectsFiles;
+}
+
+void KDirOperator::slotStarted()
+{
+ progress->setProgress( 0 );
+ // delay showing the progressbar for one second
+ d->progressDelayTimer->start( 1000, true );
+}
+
+void KDirOperator::slotShowProgress()
+{
+ progress->raise();
+ progress->show();
+ TQApplication::flushX();
+}
+
+void KDirOperator::slotProgress( int percent )
+{
+ progress->setProgress( percent );
+ // we have to redraw this as fast as possible
+ if ( progress->isVisible() )
+ TQApplication::flushX();
+}
+
+
+void KDirOperator::slotIOFinished()
+{
+ d->progressDelayTimer->stop();
+ slotProgress( 100 );
+ progress->hide();
+ emit finishedLoading();
+ resetCursor();
+
+ if ( m_fileView )
+ m_fileView->listingCompleted();
+}
+
+void KDirOperator::slotCanceled()
+{
+ emit finishedLoading();
+ resetCursor();
+
+ if ( m_fileView )
+ m_fileView->listingCompleted();
+}
+
+KProgress * KDirOperator::progressBar() const
+{
+ return progress;
+}
+
+void KDirOperator::clearHistory()
+{
+ backStack.clear();
+ backAction->setEnabled( false );
+ forwardStack.clear();
+ forwardAction->setEnabled( false );
+}
+
+void KDirOperator::slotViewActionAdded( KAction *action )
+{
+ if ( viewActionMenu->popupMenu()->count() == 5 ) // need to add a separator
+ viewActionMenu->insert( d->viewActionSeparator );
+
+ viewActionMenu->insert( action );
+}
+
+void KDirOperator::slotViewActionRemoved( KAction *action )
+{
+ viewActionMenu->remove( action );
+
+ if ( viewActionMenu->popupMenu()->count() == 6 ) // remove the separator
+ viewActionMenu->remove( d->viewActionSeparator );
+}
+
+void KDirOperator::slotViewSortingChanged( TQDir::SortSpec sort )
+{
+ mySorting = sort;
+ updateSortActions();
+}
+
+void KDirOperator::setEnableDirHighlighting( bool enable )
+{
+ d->dirHighlighting = enable;
+}
+
+bool KDirOperator::dirHighlighting() const
+{
+ return d->dirHighlighting;
+}
+
+void KDirOperator::slotProperties()
+{
+ if ( m_fileView ) {
+ const KFileItemList *list = m_fileView->selectedItems();
+ if ( !list->isEmpty() )
+ (void) new KPropertiesDialog( *list, this, "props dlg", true);
+ }
+}
+
+void KDirOperator::slotClearView()
+{
+ if ( m_fileView )
+ m_fileView->clearView();
+}
+
+// ### temporary code
+#include <dirent.h>
+bool KDirOperator::isReadable( const KURL& url )
+{
+ if ( !url.isLocalFile() )
+ return true; // what else can we say?
+
+ KDE_struct_stat buf;
+ TQString ts = url.path(+1);
+ bool readable = ( KDE_stat( TQFile::encodeName( ts ), &buf) == 0 );
+ if (readable) { // further checks
+ DIR *test;
+ test = opendir( TQFile::encodeName( ts )); // we do it just to test here
+ readable = (test != 0);
+ if (test)
+ closedir(test);
+ }
+ return readable;
+}
+
+void KDirOperator::togglePreview( bool on )
+{
+ if ( on )
+ slotDefaultPreview();
+ else
+ setView( (KFile::FileView) (m_viewKind & ~(KFile::PreviewContents|KFile::PreviewInfo)) );
+}
+
+void KDirOperator::slotRefreshItems( const KFileItemList& items )
+{
+ if ( !m_fileView )
+ return;
+
+ KFileItemListIterator it( items );
+ for ( ; it.current(); ++it )
+ m_fileView->updateView( it.current() );
+}
+
+void KDirOperator::setViewConfig( TDEConfig *config, const TQString& group )
+{
+ d->config = config;
+ d->configGroup = group;
+}
+
+TDEConfig * KDirOperator::viewConfig()
+{
+ return d->config;
+}
+
+TQString KDirOperator::viewConfigGroup() const
+{
+ return d->configGroup;
+}
+
+void KDirOperator::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+#include "kdiroperator.moc"
diff --git a/tdeio/tdefile/kdiroperator.h b/tdeio/tdefile/kdiroperator.h
new file mode 100644
index 000000000..418bb20c8
--- /dev/null
+++ b/tdeio/tdefile/kdiroperator.h
@@ -0,0 +1,950 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1999 Stephan Kulow <coolo@kde.org>
+ 2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef KDIROPERATOR_H_
+#define KDIROPERATOR_H_
+
+#include <tqwidget.h>
+#include <tqptrstack.h>
+
+#include <kaction.h>
+#include <kcompletion.h>
+#include <kdirlister.h>
+#include <tdefileview.h>
+#include <tdefileitem.h>
+#include <tdefile.h>
+
+class TQPopupMenu;
+class TQTimer;
+
+class KAction;
+class KDirLister;
+class KToggleAction;
+class KActionSeparator;
+class KActionMenu;
+class TQWidgetStack;
+class KProgress;
+namespace TDEIO {
+ class CopyJob;
+ class DeleteJob;
+}
+
+/**
+ * This widget works as a network transparent filebrowser. You specify a URL
+ * to display and this url will be loaded via KDirLister. The user can
+ * browse through directories, highlight and select files, delete or rename
+ * files.
+ *
+ * It supports different views, e.g. a detailed view (see KFileDetailView),
+ * a simple icon view (see KFileIconView), a combination of two views,
+ * separating directories and files ( KCombiView).
+ *
+ * Additionally, a preview view is available (see KFilePreview), which can
+ * show either a simple or detailed view and additionally a preview widget
+ * (see setPreviewWidget()). KImageFilePreview is one implementation
+ * of a preview widget, that displays previews for all supported filetypes
+ * utilizing TDEIO::PreviewJob.
+ *
+ * Currently, those classes don't support Drag&Drop out of the box -- there
+ * you have to use your own view-classes. You can use some DnD-aware views
+ * from Bj�n Sahlstr� <bjorn@kbear.org> until they will be integrated
+ * into this library. See http://devel-home.kde.org/~pfeiffer/DnD-classes.tar.gz
+ *
+ * This widget is the one used in the KFileDialog.
+ *
+ * Basic usage is like this:
+ * \code
+ * KDirOperator *op = new KDirOperator( KURL( "file:/home/gis" ), this );
+ * // some signals you might be interested in
+ * connect(op, TQT_SIGNAL(urlEntered(const KURL&)),
+ * TQT_SLOT(urlEntered(const KURL&)));
+ * connect(op, TQT_SIGNAL(fileHighlighted(const KFileItem *)),
+ * TQT_SLOT(fileHighlighted(const KFileItem *)));
+ * connect(op, TQT_SIGNAL(fileSelected(const KFileItem *)),
+ * TQT_SLOT(fileSelected(const KFileItem *)));
+ * connect(op, TQT_SIGNAL(finishedLoading()),
+ * TQT_SLOT(slotLoadingFinished()));
+ *
+ * op->readConfig( TDEGlobal::config(), "Your KDiroperator ConfigGroup" );
+ * op->setView(KFile::Default);
+ * \endcode
+ *
+ * This will create a childwidget of 'this' showing the directory contents
+ * of /home/gis in the default-view. The view is determined by the readConfig()
+ * call, which will read the KDirOperator settings, the user left your program
+ * with (and which you saved with op->writeConfig()).
+ *
+ * @short A widget for displaying files and browsing directories.
+ * @author Stephan Kulow <coolo@kde.org>, Carsten Pfeiffer <pfeiffer@kde.org>
+ */
+class TDEIO_EXPORT KDirOperator : public TQWidget
+{
+ Q_OBJECT
+
+ public:
+ /**
+ * The various action types. These values can be or'd together
+ * @since 3.1
+ */
+ enum ActionTypes { SortActions = 1,
+ ViewActions = 2,
+ NavActions = 4,
+ FileActions = 8,
+ AllActions = 15 };
+ /**
+ * Constructs the KDirOperator with no initial view. As the views are
+ * configurable, call readConfig() to load the user's configuration
+ * and then setView to explicitly set a view.
+ *
+ * This constructor doesn't start loading the url, setView will do it.
+ */
+ KDirOperator(const KURL& urlName = KURL(),
+ TQWidget *parent = 0, const char* name = 0);
+ /**
+ * Destroys the KDirOperator.
+ */
+ virtual ~KDirOperator();
+
+ /**
+ * Enables/disables showing hidden files.
+ */
+ // ### KDE4: make virtual
+ void setShowHiddenFiles ( bool s ) { showHiddenAction->setChecked( s ); }
+
+ /**
+ * @returns true when hidden files are shown or false otherwise.
+ */
+ bool showHiddenFiles () const { return showHiddenAction->isChecked(); }
+
+ /**
+ * Stops loading immediately. You don't need to call this, usually.
+ */
+ void close();
+ /// Reimplemented to avoid "hidden virtual" warnings
+ virtual bool close( bool alsoDelete ) { return TQWidget::close( alsoDelete ); }
+
+ /**
+ * Sets a filter like "*.cpp *.h *.o". Only files matching that filter
+ * will be shown. Call updateDir() to apply it.
+ *
+ * @see KDirLister::setNameFilter
+ * @see nameFilter
+ */
+ void setNameFilter(const TQString& filter);
+
+ /**
+ * @returns the current namefilter.
+ * @see setNameFilter
+ */
+ const TQString& nameFilter() const { return dir->nameFilter(); }
+
+ /**
+ * Sets a list of mimetypes as filter. Only files of those mimetypes
+ * will be shown.
+ *
+ * Example:
+ * \code
+ * TQStringList filter;
+ * filter << "text/html" << "image/png" << "inode/directory";
+ * dirOperator->setMimefilter( filter );
+ * \endcode
+ *
+ * Node: Without the mimetype inode/directory, only files would be shown.
+ * Call updateDir() to apply it.
+ *
+ * @see KDirLister::setMimeFilter
+ * @see mimeFilter
+ */
+ void setMimeFilter( const TQStringList& mimetypes );
+
+ /**
+ * @returns the current mime filter.
+ */
+ TQStringList mimeFilter() const { return dir->mimeFilters(); }
+
+ /**
+ * Clears both the namefilter and mimetype filter, so that all files and
+ * directories will be shown. Call updateDir() to apply it.
+ *
+ * @see setMimeFilter
+ * @see setNameFilter
+ */
+ void clearFilter();
+
+ /**
+ * @returns the current url
+ */
+ KURL url() const;
+
+ /**
+ * Sets a new url to list.
+ * @param clearforward specifies whether the "forward" history should be cleared.
+ * @param url the URL to set
+ */
+ // ### KDE4: make virtual
+ void setURL(const KURL& url, bool clearforward);
+
+ /**
+ * Clears the current selection and attempts to set @p filename
+ * the current file. filename is just the name, no path or url.
+ */
+ void setCurrentItem( const TQString& filename );
+
+ /**
+ * Sets a new KFileView to be used for showing and browsing files.
+ * Note: this will read the current url() to fill the view.
+ *
+ * @see KFileView
+ * @see KFileIconView
+ * @see KFileDetailView
+ * @see KCombiView
+ * @see view
+ */
+ // ### KDE4: make virtual
+ void setView(KFileView *view);
+
+ /**
+ * @returns the currently used view.
+ * @see setView
+ */
+ KFileView * view() const { return m_fileView; }
+
+ /**
+ * Returns the widget of the current view. 0L if there is no view/widget.
+ * (KFileView itself is not a widget.)
+ */
+ TQWidget * viewWidget() const { return m_fileView ? m_fileView->widget() : 0L; }
+
+ /**
+ * Sets one of the predefined fileviews
+ * @see KFile::FileView
+ */
+ // ### KDE4: make virtual
+ void setView(KFile::FileView view);
+
+ /**
+ * Sets the way to sort files and directories.
+ */
+ void setSorting( TQDir::SortSpec );
+
+ /**
+ * @returns the current way of sorting files and directories
+ */
+ TQDir::SortSpec sorting() const { return mySorting; }
+
+ /**
+ * @returns true if we are displaying the root directory of the current url
+ */
+ bool isRoot() const { return url().path() == TQChar('/'); }
+
+ /**
+ * @returns the object listing the directory
+ */
+ KDirLister *dirLister() const { return dir; }
+
+ /**
+ * @returns the progress widget, that is shown during directory listing.
+ * You can for example reparent() it to put it into a statusbar.
+ */
+ KProgress * progressBar() const;
+
+ /**
+ * Sets the listing/selection mode for the views, an OR'ed combination of
+ * @li File
+ * @li Directory
+ * @li Files
+ * @li ExistingOnly
+ * @li LocalOnly
+ *
+ * You cannot mix File and Files of course, as the former means
+ * single-selection mode, the latter multi-selection.
+ */
+ // ### KDE4: make virtual
+ void setMode( KFile::Mode m );
+ /**
+ * @returns the listing/selection mode.
+ */
+ KFile::Mode mode() const;
+
+ /**
+ * Sets a preview-widget to be shown next to the file-view.
+ * The ownership of @p w is transferred to KDirOperator, so don't
+ * delete it yourself!
+ */
+ // ### KDE4: make virtual
+ void setPreviewWidget(const TQWidget *w);
+
+ /**
+ * @returns a list of all currently selected items. If there is no view,
+ * then 0L is returned.
+ */
+ const KFileItemList * selectedItems() const {
+ return ( m_fileView ? m_fileView->selectedItems() : 0L );
+ }
+
+ /**
+ * @returns true if @p item is currently selected, or false otherwise.
+ */
+ inline bool isSelected( const KFileItem *item ) const {
+ return ( m_fileView ? m_fileView->isSelected( item ) : false );
+ }
+
+ /**
+ * @returns the number of directories in the currently listed url.
+ * Returns 0 if there is no view.
+ */
+ int numDirs() const;
+
+ /**
+ * @returns the number of files in the currently listed url.
+ * Returns 0 if there is no view.
+ */
+ int numFiles() const;
+
+ /**
+ * @returns a KCompletion object, containing all filenames and
+ * directories of the current directory/URL.
+ * You can use it to insert it into a KLineEdit or KComboBox
+ * Note: it will only contain files, after prepareCompletionObjects()
+ * has been called. It will be implicitly called from makeCompletion()
+ * or makeDirCompletion()
+ */
+ KCompletion * completionObject() const {
+ return const_cast<KCompletion *>( &myCompletion );
+ }
+
+ /**
+ * @returns a KCompletion object, containing only all directories of the
+ * current directory/URL.
+ * You can use it to insert it into a KLineEdit or KComboBox
+ * Note: it will only contain directories, after
+ * prepareCompletionObjects() has been called. It will be implicitly
+ * called from makeCompletion() or makeDirCompletion()
+ */
+ KCompletion *dirCompletionObject() const {
+ return const_cast<KCompletion *>( &myDirCompletion );
+ }
+
+ /**
+ * an accessor to a collection of all available Actions. The actions
+ * are static, they will be there all the time (no need to connect to
+ * the signals KActionCollection::inserted() or removed().
+ *
+ * There are the following actions:
+ *
+ * @li popupMenu : an ActionMenu presenting a popupmenu with all actions
+ * @li up : changes to the parent directory
+ * @li back : goes back to the previous directory
+ * @li forward : goes forward in the history
+ * @li home : changes to the user's home directory
+ * @li reload : reloads the current directory
+ * @li separator : a separator
+ * @li mkdir : opens a dialog box to create a directory
+ * @li delete : deletes the selected files/directories
+ * @li sorting menu : an ActionMenu containing all sort-options
+ * @li by name : sorts by name
+ * @li by date : sorts by date
+ * @li by size : sorts by size
+ * @li reversed : reverses the sort order
+ * @li dirs first : sorts directories before files
+ * @li case insensitive : sorts case insensitively
+ * @li view menu : an ActionMenu containing all actions concerning the view
+ * @li short view : shows a simple fileview
+ * @li detailed view : shows a detailed fileview (dates, permissions ,...)
+ * @li show hidden : shows hidden files
+ * @li separate dirs : shows directories in a separate pane
+ * @li preview : shows a preview next to the fileview
+ * @li single : hides the separate view for directories or the preview
+ * @li properties : shows a KPropertiesDialog for the selected files
+ *
+ * The short and detailed view are in an exclusive group. The sort-by
+ * actions are in an exclusive group as well. Also the "separate dirs",
+ * "preview" and "single" actions are in an exclusive group.
+ *
+ * You can e.g. use
+ * \code
+ * actionCollection()->action( "up" )->plug( someToolBar );
+ * \endcode
+ * to add a button into a toolbar, which makes the dirOperator change to
+ * its parent directory.
+ *
+ * @returns all available Actions
+ */
+ KActionCollection * actionCollection() const { return myActionCollection; }
+
+ /**
+ * Sets the config object and the to be used group in KDirOperator. This
+ * will be used to store the view's configuration via
+ * KFileView::writeConfig() (and for KFileView::readConfig()).
+ * If you don't set this, the views cannot save and restore their
+ * configuration.
+ *
+ * Usually you call this right after KDirOperator creation so that the view
+ * instantiation can make use of it already.
+ *
+ * Note that KDirOperator does NOT take ownership of that object (typically
+ * it's TDEGlobal::config() anyway.
+ *
+ * @see viewConfig
+ * @see viewConfigGroup
+ * @since 3.1
+ */
+ // ### KDE4: make virtual
+ void setViewConfig( TDEConfig *config, const TQString& group );
+
+ /**
+ * Returns the TDEConfig object used for saving and restoring view's
+ * configuration.
+ * @returns the TDEConfig object used for saving and restoring view's
+ * configuration.
+ * @since 3.1
+ */
+ TDEConfig *viewConfig();
+
+ /**
+ * Returns the group name used for saving and restoring view's
+ * configuration.
+ * @returns the group name used for saving and restoring view's
+ * configuration.
+ * @since 3.1
+ */
+ TQString viewConfigGroup() const;
+
+ /**
+ * Reads the default settings for a view, i.e. the default KFile::FileView.
+ * Also reads the sorting and whether hidden files should be shown.
+ * Note: the default view will not be set - you have to call
+ * \code
+ * setView( KFile::Default )
+ * \endcode
+ * to apply it.
+ *
+ * @see setView
+ * @see setViewConfig
+ * @see writeConfig
+ */
+ virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
+
+ /**
+ * Saves the current settings like sorting, simple or detailed view.
+ *
+ * @see readConfig
+ * @see setViewConfig
+ */
+ virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null );
+
+
+ /**
+ * This is a KFileDialog specific hack: we want to select directories with
+ * single click, but not files. But as a generic class, we have to be able
+ * to select files on single click as well.
+ *
+ * This gives us the opportunity to do both.
+ *
+ * The default is false, set it to true if you don't want files selected
+ * with single click.
+ */
+ void setOnlyDoubleClickSelectsFiles( bool enable );
+
+ /**
+ * @returns whether files (not directories) should only be select()ed by
+ * double-clicks.
+ * @see setOnlyDoubleClickSelectsFiles
+ */
+ bool onlyDoubleClickSelectsFiles() const;
+
+ /**
+ * Creates the given directory/url. If it is a relative path,
+ * it will be completed with the current directory.
+ * If enterDirectory is true, the directory will be entered after a
+ * successful operation. If unsuccessful, a messagebox will be presented
+ * to the user.
+ * @returns true if the directory could be created.
+ */
+ // ### KDE4: make virtual and turn TQString into KURL
+ bool mkdir( const TQString& directory, bool enterDirectory = true );
+
+ /**
+ * Starts and returns a TDEIO::DeleteJob to delete the given @p items.
+ *
+ * @param items the list of items to be deleted
+ * @param ask specifies whether a confirmation dialog should be shown
+ * @param showProgress passed to the DeleteJob to show a progress dialog
+ */
+ // ### KDE4: make virtual
+ TDEIO::DeleteJob * del( const KFileItemList& items,
+ bool ask = true, bool showProgress = true );
+
+ /**
+ * Starts and returns a TDEIO::DeleteJob to delete the given @p items.
+ *
+ * @param items the list of items to be deleted
+ * @param parent the parent widget used for the confirmation dialog
+ * @param ask specifies whether a confirmation dialog should be shown
+ * @param showProgress passed to the DeleteJob to show a progress dialog
+ * @since 3.1
+ */
+ // ### KDE4: make virtual
+ TDEIO::DeleteJob * del( const KFileItemList& items, TQWidget *parent,
+ bool ask = true, bool showProgress = true );
+
+ /**
+ * Clears the forward and backward history.
+ */
+ void clearHistory();
+
+ /**
+ * When going up in the directory hierarchy, KDirOperator can highlight
+ * the directory that was just left.
+ *
+ * I.e. when you go from /home/gis/src to /home/gis, the item "src" will
+ * be made the current item.
+ *
+ * Default is off, because this behavior introduces bug #136630.
+ * Don't enable until this bug is fixed.
+ */
+ // ### KDE4: make virtual
+ void setEnableDirHighlighting( bool enable );
+
+ /**
+ * @returns whether the last directory will be made the current item
+ * when going up in the directory hierarchy.
+ *
+ * Default is false.
+ */
+ bool dirHighlighting() const;
+
+ /**
+ * @returns true if we are in directory-only mode, that is, no files are
+ * shown.
+ */
+ bool dirOnlyMode() const { return dirOnlyMode( myMode ); }
+
+ static bool dirOnlyMode( uint mode ) {
+ return ( (mode & KFile::Directory) &&
+ (mode & (KFile::File | KFile::Files)) == 0 );
+ }
+
+ /**
+ * Sets up the action menu.
+ * @param whichActions is an value of OR'd ActionTypes that controls which actions to show in the action menu
+ */
+ void setupMenu(int whichActions);
+
+ /**
+ * Reimplemented - allow dropping of files if @p b is true
+ * @param b true if the widget should allow dropping of files
+ */
+ virtual void setAcceptDrops(bool b);
+
+ /**
+ * Sets the options for dropping files.
+ * @see KFileView::DropOptions
+ * @since 3.2
+ */
+ // ### KDE4: make virtual
+ void setDropOptions(int options);
+
+ /**
+ * Starts and returns a TDEIO::CopyJob to trash the given @p items.
+ *
+ * @param items the list of items to be trashed
+ * @param parent the parent widget used for the confirmation dialog
+ * @param ask specifies whether a confirmation dialog should be shown
+ * @param showProgress passed to the CopyJob to show a progress dialog
+ * @since 3.4
+ */
+ // ### KDE4: make virtual
+ TDEIO::CopyJob * trash( const KFileItemList& items, TQWidget *parent,
+ bool ask = true, bool showProgress = true );
+
+protected:
+ /**
+ * A view factory for creating predefined fileviews. Called internally by setView
+ * , but you can also call it directly. Reimplement this if you depend on self defined fileviews.
+ * @param parent is the TQWidget to be set as parent
+ * @param view is the predefined view to be set, note: this can be several ones OR:ed together.
+ * @returns the created KFileView
+ * @see KFileView
+ * @see KCombiView
+ * @see KFileDetailView
+ * @see KFileIconView
+ * @see KFilePreview
+ * @see KFile::FileView
+ * @see setView
+ */
+ virtual KFileView* createView( TQWidget* parent, KFile::FileView view );
+ /**
+ * Sets a custom KDirLister to list directories.
+ */
+ // ### KDE4: make virtual
+ void setDirLister( KDirLister *lister );
+
+ virtual void resizeEvent( TQResizeEvent * );
+
+ /**
+ * Sets up all the actions. Called from the constructor, you usually
+ * better not call this.
+ */
+ void setupActions();
+
+ /**
+ * Updates the sorting-related actions to comply with the current sorting
+ * @see sorting
+ */
+ void updateSortActions();
+
+ /**
+ * Updates the view-related actions to comply with the current
+ * KFile::FileView
+ */
+ void updateViewActions();
+
+ /**
+ * Sets up the context-menu with all the necessary actions. Called from the
+ * constructor, you usually don't need to call this.
+ * @since 3.1
+ */
+ void setupMenu();
+
+ /**
+ * Synchronizes the completion objects with the entries of the
+ * currently listed url.
+ *
+ * Automatically called from makeCompletion() and
+ * makeDirCompletion()
+ */
+ void prepareCompletionObjects();
+
+ /**
+ * Checks if there support from TDEIO::PreviewJob for the currently
+ * shown files, taking mimeFilter() and nameFilter() into account
+ * Enables/disables the preview-action accordingly.
+ */
+ bool checkPreviewSupport();
+
+public slots:
+ /**
+ * Goes one step back in the history and opens that url.
+ */
+ // ### KDE4: make virtual
+ void back();
+
+ /**
+ * Goes one step forward in the history and opens that url.
+ */
+ // ### KDE4: make virtual
+ void forward();
+
+ /**
+ * Enters the home directory.
+ */
+ // ### KDE4: make virtual
+ void home();
+
+ /**
+ * Goes one directory up from the current url.
+ */
+ // ### KDE4: make virtual
+ void cdUp();
+
+ /**
+ * to update the view after changing the settings
+ */
+ void updateDir();
+
+ /**
+ * Re-reads the current url.
+ */
+ // ### KDE4: make virtual
+ void rereadDir();
+
+ /**
+ * Opens a dialog to create a new directory.
+ */
+ // ### KDE4: make virtual
+ void mkdir();
+
+ /**
+ * Deletes the currently selected files/directories.
+ */
+ // ### KDE4: make virtual
+ void deleteSelected();
+
+ /**
+ * Enables/disables actions that are selection dependent. Call this e.g.
+ * when you are about to show a popup menu using some of KDirOperators
+ * actions.
+ */
+ void updateSelectionDependentActions();
+
+ /**
+ * Tries to complete the given string (only completes files).
+ */
+ TQString makeCompletion(const TQString&);
+
+ /**
+ * Tries to complete the given string (only completes directores).
+ */
+ TQString makeDirCompletion(const TQString&);
+
+ /**
+ * Trashes the currently selected files/directories.
+ * @since 3.4
+ */
+ // ### KDE4: make virtual
+ void trashSelected(KAction::ActivationReason, TQt::ButtonState);
+
+protected slots:
+ /**
+ * Restores the normal cursor after showing the busy-cursor. Also hides
+ * the progressbar.
+ */
+ void resetCursor();
+
+ /**
+ * Called after setURL() to load the directory, update the history,
+ * etc.
+ */
+ void pathChanged();
+
+ /**
+ * Adds a new list of KFileItems to the view
+ * (coming from KDirLister)
+ */
+ void insertNewFiles(const KFileItemList &newone);
+
+ /**
+ * Removes the given KFileItem item from the view (usually called from
+ * KDirLister).
+ */
+ void itemDeleted(KFileItem *);
+
+ /**
+ * Enters the directory specified by the given @p item.
+ */
+ // ### KDE4: make virtual
+ void selectDir(const KFileItem *item );
+
+ /**
+ * Emits fileSelected( item )
+ */
+ void selectFile(const KFileItem *item);
+
+ /**
+ * Emits fileHighlighted( i )
+ */
+ void highlightFile(const KFileItem* i) { emit fileHighlighted( i ); }
+
+ /**
+ * Called upon right-click to activate the popupmenu.
+ */
+ virtual void activatedMenu( const KFileItem *, const TQPoint& pos );
+
+ /**
+ * Changes sorting to sort by name
+ */
+ void sortByName() { byNameAction->setChecked( true ); }
+
+ /**
+ * Changes sorting to sort by size
+ */
+ void sortBySize() { bySizeAction->setChecked( true ); }
+
+ /**
+ * Changes sorting to sort by date
+ */
+ void sortByDate() { byDateAction->setChecked( true ); }
+
+ /**
+ * Changes sorting to reverse sorting
+ */
+ void sortReversed() { reverseAction->setChecked( !reverseAction->isChecked() ); }
+
+ /**
+ * Toggles showing directories first / having them sorted like files.
+ */
+ void toggleDirsFirst() { dirsFirstAction->setChecked( !dirsFirstAction->isChecked() ); }
+
+ /**
+ * Toggles case sensitive / case insensitive sorting
+ */
+ void toggleIgnoreCase() { caseInsensitiveAction->setChecked( !caseInsensitiveAction->isChecked() ); }
+
+ /**
+ * Tries to make the given @p match as current item in the view and emits
+ * completion( match )
+ */
+ void slotCompletionMatch(const TQString& match);
+
+signals:
+ void urlEntered(const KURL& );
+ void updateInformation(int files, int dirs);
+ void completion(const TQString&);
+ void finishedLoading();
+
+ /**
+ * Emitted whenever the current fileview is changed, either by an explicit
+ * call to setView() or by the user selecting a different view thru
+ * the GUI.
+ */
+ void viewChanged( KFileView * newView );
+
+ /**
+ * Emitted when a file is highlighted or generally the selection changes in
+ * multiselection mode. In the latter case, @p item is 0L. You can access
+ * the selected items with selectedItems().
+ */
+ void fileHighlighted( const KFileItem *item );
+ void dirActivated( const KFileItem *item );
+ void fileSelected( const KFileItem *item );
+ /**
+ * Emitted when files are dropped. Dropping files is disabled by
+ * default. You need to enable it with setAcceptDrops()
+ * @param item the item on which the drop occurred or 0.
+ * @param event the drop event itself.
+ * @param urls the urls that where dropped.
+ * @since 3.2
+ */
+ void dropped(const KFileItem *item, TQDropEvent*event, const KURL::List&urls);
+private:
+ /**
+ * Contains all URLs you can reach with the back button.
+ */
+ TQPtrStack<KURL> backStack;
+
+ /**
+ * Contains all URLs you can reach with the forward button.
+ */
+ TQPtrStack<KURL> forwardStack;
+
+ KDirLister *dir;
+ KURL currUrl;
+
+ KCompletion myCompletion;
+ KCompletion myDirCompletion;
+ bool myCompleteListDirty;
+ TQDir::SortSpec mySorting;
+
+ /**
+ * Checks whether we preview support is available for the current
+ * mimetype/namefilter
+ */
+ bool checkPreviewInternal() const;
+
+ /**
+ * takes action on the new location. If it's a directory, change
+ * into it, if it's a file, correct the name, etc.
+ */
+ void checkPath(const TQString& txt, bool takeFiles = false);
+
+ void connectView(KFileView *);
+
+ bool openURL( const KURL& url, bool keep = false, bool reload = false );
+
+ KFileView *m_fileView;
+ KFileItemList pendingMimeTypes;
+
+ // the enum KFile::FileView as an int
+ int m_viewKind;
+ int defaultView;
+
+ KFile::Mode myMode;
+ KProgress *progress;
+
+ const TQWidget *myPreview; // temporary pointer for the preview widget
+
+ // actions for the popupmenus
+ // ### clean up all those -- we have them all in the actionMenu!
+ KActionMenu *actionMenu;
+
+ KAction *backAction;
+ KAction *forwardAction;
+ KAction *homeAction;
+ KAction *upAction;
+ KAction *reloadAction;
+ KActionSeparator *actionSeparator;
+ KAction *mkdirAction;
+
+ KActionMenu *sortActionMenu;
+ KRadioAction *byNameAction;
+ KRadioAction *byDateAction;
+ KRadioAction *bySizeAction;
+ KToggleAction *reverseAction;
+ KToggleAction *dirsFirstAction;
+ KToggleAction *caseInsensitiveAction;
+
+ KActionMenu *viewActionMenu;
+ KRadioAction *shortAction;
+ KRadioAction *detailedAction;
+ KToggleAction *showHiddenAction;
+ KToggleAction *separateDirsAction;
+
+ KActionCollection *myActionCollection;
+ KActionCollection *viewActionCollection;
+
+private slots:
+ /**
+ * @internal
+ */
+ void slotDetailedView();
+ void slotSimpleView();
+ void slotToggleHidden( bool );
+
+ void slotSeparateDirs();
+ void slotDefaultPreview();
+ void togglePreview( bool );
+
+ void slotSortByName();
+ void slotSortBySize();
+ void slotSortByDate();
+ void slotSortReversed();
+ void slotToggleDirsFirst();
+ void slotToggleIgnoreCase();
+
+ void slotStarted();
+ void slotProgress( int );
+ void slotShowProgress();
+ void slotIOFinished();
+ void slotCanceled();
+ void slotRedirected( const KURL& );
+
+ void slotViewActionAdded( KAction * );
+ void slotViewActionRemoved( KAction * );
+ void slotViewSortingChanged( TQDir::SortSpec );
+
+ void slotClearView();
+ void slotRefreshItems( const KFileItemList& items );
+
+ void slotProperties();
+
+ void insertViewDependentActions();
+
+private:
+ static bool isReadable( const KURL& url );
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KDirOperatorPrivate;
+ KDirOperatorPrivate *d;
+};
+
+#endif
diff --git a/tdeio/tdefile/kdirselectdialog.cpp b/tdeio/tdefile/kdirselectdialog.cpp
new file mode 100644
index 000000000..6a13920fd
--- /dev/null
+++ b/tdeio/tdefile/kdirselectdialog.cpp
@@ -0,0 +1,481 @@
+/*
+ Copyright (C) 2001,2002 Carsten Pfeiffer <pfeiffer@kde.org>
+ Copyright (C) 2001 Michael Jarrett <michaelj@corel.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqdir.h>
+#include <tqlayout.h>
+#include <tqpopupmenu.h>
+#include <tqstringlist.h>
+#include <tqvaluestack.h>
+
+#include <kactionclasses.h>
+#include <kapplication.h>
+#include <kcombobox.h>
+#include <tdeconfig.h>
+#include <tdefiledialog.h>
+#include <tdefilespeedbar.h>
+#include <kglobalsettings.h>
+#include <kiconloader.h>
+#include <klocale.h>
+#include <kprotocolinfo.h>
+#include <krecentdirs.h>
+#include <kshell.h>
+#include <kurl.h>
+#include <kurlcompletion.h>
+#include <kurlpixmapprovider.h>
+#include <kinputdialog.h>
+#include <tdeio/netaccess.h>
+#include <tdeio/renamedlg.h>
+#include <kmessagebox.h>
+
+#include "tdefiletreeview.h"
+#include "kdirselectdialog.h"
+
+// ### add mutator for treeview!
+
+class KDirSelectDialog::KDirSelectDialogPrivate
+{
+public:
+ KDirSelectDialogPrivate()
+ {
+ urlCombo = 0L;
+ branch = 0L;
+ comboLocked = false;
+ }
+
+ KFileSpeedBar *speedBar;
+ KHistoryCombo *urlCombo;
+ KFileTreeBranch *branch;
+ TQString recentDirClass;
+ KURL startURL;
+ TQValueStack<KURL> dirsToList;
+
+ bool comboLocked : 1;
+};
+
+static KURL rootUrl(const KURL &url)
+{
+ KURL root = url;
+ root.setPath( "/" );
+
+ if (!kapp->authorizeURLAction("list", KURL(), root))
+ {
+ root = KURL::fromPathOrURL( TQDir::homeDirPath() );
+ if (!kapp->authorizeURLAction("list", KURL(), root))
+ {
+ root = url;
+ }
+ }
+ return root;
+}
+
+KDirSelectDialog::KDirSelectDialog(const TQString &startDir, bool localOnly,
+ TQWidget *parent, const char *name,
+ bool modal)
+ : KDialogBase( parent, name, modal, i18n("Select Folder"),
+ Ok|Cancel|User1, Ok, false,
+ KGuiItem( i18n("New Folder..."), "folder_new" ) ),
+ m_localOnly( localOnly )
+{
+ d = new KDirSelectDialogPrivate;
+ d->branch = 0L;
+
+ TQFrame *page = makeMainWidget();
+ TQHBoxLayout *hlay = new TQHBoxLayout( page, 0, spacingHint() );
+ m_mainLayout = new TQVBoxLayout();
+ d->speedBar = new KFileSpeedBar( page, "speedbar" );
+ connect( d->speedBar, TQT_SIGNAL( activated( const KURL& )),
+ TQT_SLOT( setCurrentURL( const KURL& )) );
+ hlay->addWidget( d->speedBar, 0 );
+ hlay->addLayout( m_mainLayout, 1 );
+
+ // Create dir list
+ m_treeView = new KFileTreeView( page );
+ m_treeView->addColumn( i18n("Folders") );
+ m_treeView->setColumnWidthMode( 0, TQListView::Maximum );
+ m_treeView->setResizeMode( TQListView::AllColumns );
+
+ d->urlCombo = new KHistoryCombo( page, "url combo" );
+ d->urlCombo->setTrapReturnKey( true );
+ d->urlCombo->setPixmapProvider( new KURLPixmapProvider() );
+ KURLCompletion *comp = new KURLCompletion();
+ comp->setMode( KURLCompletion::DirCompletion );
+ d->urlCombo->setCompletionObject( comp, true );
+ d->urlCombo->setAutoDeleteCompletionObject( true );
+ d->urlCombo->setDuplicatesEnabled( false );
+ connect( d->urlCombo, TQT_SIGNAL( textChanged( const TQString& ) ),
+ TQT_SLOT( slotComboTextChanged( const TQString& ) ));
+
+ m_contextMenu = new TQPopupMenu( this );
+ KAction* newFolder = new KAction( i18n("New Folder..."), "folder_new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotMkdir() ), TQT_TQOBJECT(this));
+ newFolder->plug(m_contextMenu);
+ m_contextMenu->insertSeparator();
+ m_showHiddenFolders = new KToggleAction ( i18n( "Show Hidden Folders" ), 0, TQT_TQOBJECT(this),
+ TQT_SLOT( slotShowHiddenFoldersToggled() ), TQT_TQOBJECT(this));
+ m_showHiddenFolders->plug(m_contextMenu);
+
+ d->startURL = KFileDialog::getStartURL( startDir, d->recentDirClass );
+ if ( localOnly && !d->startURL.isLocalFile() )
+ {
+ d->startURL = KURL();
+ TQString docPath = TDEGlobalSettings::documentPath();
+ if (TQDir(docPath).exists())
+ d->startURL.setPath( docPath );
+ else
+ d->startURL.setPath( TQDir::homeDirPath() );
+ }
+
+ KURL root = rootUrl(d->startURL);
+
+ m_startDir = d->startURL.url();
+
+ d->branch = createBranch( root );
+
+ readConfig( TDEGlobal::config(), "DirSelect Dialog" );
+
+ m_mainLayout->addWidget( m_treeView, 1 );
+ m_mainLayout->addWidget( d->urlCombo, 0 );
+
+ connect( m_treeView, TQT_SIGNAL( currentChanged( TQListViewItem * )),
+ TQT_SLOT( slotCurrentChanged() ));
+ connect( m_treeView, TQT_SIGNAL( contextMenu( KListView *, TQListViewItem *, const TQPoint & )),
+ TQT_SLOT( slotContextMenu( KListView *, TQListViewItem *, const TQPoint & )));
+
+ connect( d->urlCombo, TQT_SIGNAL( activated( const TQString& )),
+ TQT_SLOT( slotURLActivated( const TQString& )));
+ connect( d->urlCombo, TQT_SIGNAL( returnPressed( const TQString& )),
+ TQT_SLOT( slotURLActivated( const TQString& )));
+
+ setCurrentURL( d->startURL );
+}
+
+
+KDirSelectDialog::~KDirSelectDialog()
+{
+ delete d;
+}
+
+void KDirSelectDialog::setCurrentURL( const KURL& url )
+{
+ if ( !url.isValid() )
+ return;
+
+ KURL root = rootUrl(url);
+
+ d->startURL = url;
+ if ( !d->branch ||
+ url.protocol() != d->branch->url().protocol() ||
+ url.host() != d->branch->url().host() )
+ {
+ if ( d->branch )
+ {
+ // removing the root-item causes the currentChanged() signal to be
+ // emitted, but we don't want to update the location-combo yet.
+ d->comboLocked = true;
+ view()->removeBranch( d->branch );
+ d->comboLocked = false;
+ }
+
+ d->branch = createBranch( root );
+ }
+
+ d->branch->disconnect( TQT_SIGNAL( populateFinished( KFileTreeViewItem * )),
+ this, TQT_SLOT( slotNextDirToList( KFileTreeViewItem *)));
+ connect( d->branch, TQT_SIGNAL( populateFinished( KFileTreeViewItem * )),
+ TQT_SLOT( slotNextDirToList( KFileTreeViewItem * ) ));
+
+ KURL dirToList = root;
+ d->dirsToList.clear();
+ TQString path = url.path(+1);
+ int pos = path.length();
+
+ if ( path.isEmpty() ) // e.g. ftp://host.com/ -> just list the root dir
+ d->dirsToList.push( root );
+
+ else
+ {
+ while ( pos > 0 )
+ {
+ pos = path.findRev( '/', pos -1 );
+ if ( pos >= 0 )
+ {
+ dirToList.setPath( path.left( pos +1 ) );
+ d->dirsToList.push( dirToList );
+// tqDebug( "List: %s", dirToList.url().latin1());
+ }
+ }
+ }
+
+ if ( !d->dirsToList.isEmpty() )
+ openNextDir( d->branch->root() );
+}
+
+void KDirSelectDialog::openNextDir( KFileTreeViewItem * /*parent*/ )
+{
+ if ( !d->branch )
+ return;
+
+ KURL url = d->dirsToList.pop();
+
+ KFileTreeViewItem *item = view()->findItem( d->branch, url.path().mid(1));
+ if ( item )
+ {
+ if ( !item->isOpen() )
+ item->setOpen( true );
+ else // already open -> go to next one
+ slotNextDirToList( item );
+ }
+// else
+// tqDebug("###### openNextDir: item not found!");
+}
+
+void KDirSelectDialog::slotNextDirToList( KFileTreeViewItem *item )
+{
+ // scroll to make item the topmost item
+ view()->ensureItemVisible( item );
+ TQRect r = view()->itemRect( item );
+ if ( r.isValid() )
+ {
+ int x, y;
+ view()->viewportToContents( view()->contentsX(), r.y(), x, y );
+ view()->setContentsPos( x, y );
+ }
+
+ if ( !d->dirsToList.isEmpty() )
+ openNextDir( item );
+ else
+ {
+ d->branch->disconnect( TQT_SIGNAL( populateFinished( KFileTreeViewItem * )),
+ this, TQT_SLOT( slotNextDirToList( KFileTreeViewItem *)));
+ view()->setCurrentItem( item );
+ item->setSelected( true );
+ }
+}
+
+void KDirSelectDialog::readConfig( TDEConfig *config, const TQString& group )
+{
+ d->urlCombo->clear();
+
+ TDEConfigGroup conf( config, group );
+ d->urlCombo->setHistoryItems( conf.readPathListEntry( "History Items" ));
+
+ TQSize defaultSize( 400, 450 );
+ resize( conf.readSizeEntry( "DirSelectDialog Size", &defaultSize ));
+}
+
+void KDirSelectDialog::saveConfig( TDEConfig *config, const TQString& group )
+{
+ TDEConfigGroup conf( config, group );
+ conf.writePathEntry( "History Items", d->urlCombo->historyItems(), ',',
+ true, true);
+ conf.writeEntry( "DirSelectDialog Size", size(), true, true );
+
+ d->speedBar->save( config );
+
+ config->sync();
+}
+
+void KDirSelectDialog::slotUser1()
+{
+ slotMkdir();
+}
+
+void KDirSelectDialog::accept()
+{
+ KFileTreeViewItem *item = m_treeView->currentKFileTreeViewItem();
+ if ( !item )
+ return;
+
+ if ( !d->recentDirClass.isEmpty() )
+ {
+ KURL dir = item->url();
+ if ( !item->isDir() )
+ dir = dir.upURL();
+
+ KRecentDirs::add(d->recentDirClass, dir.url());
+ }
+
+ d->urlCombo->addToHistory( item->url().prettyURL() );
+ KFileDialog::setStartDir( url() );
+
+ KDialogBase::accept();
+ saveConfig( TDEGlobal::config(), "DirSelect Dialog" );
+}
+
+
+KURL KDirSelectDialog::url() const
+{
+ return m_treeView->currentURL();
+}
+
+void KDirSelectDialog::slotCurrentChanged()
+{
+ if ( d->comboLocked )
+ return;
+
+ KFileTreeViewItem *current = view()->currentKFileTreeViewItem();
+ KURL u = current ? current->url() : (d->branch ? d->branch->rootUrl() : KURL());
+
+ if ( u.isValid() )
+ {
+ if ( u.isLocalFile() )
+ d->urlCombo->setEditText( u.path() );
+
+ else // remote url
+ d->urlCombo->setEditText( u.prettyURL() );
+ }
+ else
+ d->urlCombo->setEditText( TQString::null );
+}
+
+void KDirSelectDialog::slotURLActivated( const TQString& text )
+{
+ if ( text.isEmpty() )
+ return;
+
+ KURL url = KURL::fromPathOrURL( text );
+ d->urlCombo->addToHistory( url.prettyURL() );
+
+ if ( localOnly() && !url.isLocalFile() )
+ return; // ### messagebox
+
+ KURL oldURL = m_treeView->currentURL();
+ if ( oldURL.isEmpty() )
+ oldURL = KURL::fromPathOrURL( m_startDir );
+
+ setCurrentURL( url );
+}
+
+KFileTreeBranch * KDirSelectDialog::createBranch( const KURL& url )
+{
+ TQString title = url.isLocalFile() ? url.path() : url.prettyURL();
+ KFileTreeBranch *branch = view()->addBranch( url, title, m_showHiddenFolders->isChecked() );
+ branch->setChildRecurse( false );
+ view()->setDirOnlyMode( branch, true );
+
+ return branch;
+}
+
+void KDirSelectDialog::slotComboTextChanged( const TQString& text )
+{
+ if ( d->branch )
+ {
+ KURL url = KURL::fromPathOrURL( KShell::tildeExpand( text ) );
+ KFileTreeViewItem *item = d->branch->findTVIByURL( url );
+ if ( item )
+ {
+ view()->setCurrentItem( item );
+ view()->setSelected( item, true );
+ view()->ensureItemVisible( item );
+ return;
+ }
+ }
+
+ TQListViewItem *item = view()->currentItem();
+ if ( item )
+ {
+ item->setSelected( false );
+ // 2002/12/27, deselected item is not repainted, so force it
+ item->repaint();
+ }
+}
+
+void KDirSelectDialog::slotContextMenu( KListView *, TQListViewItem *, const TQPoint& pos )
+{
+ m_contextMenu->popup( pos );
+}
+
+void KDirSelectDialog::slotMkdir()
+{
+ bool ok;
+ TQString where = url().pathOrURL();
+ TQString name = i18n( "New Folder" );
+ if ( url().isLocalFile() && TQFileInfo( url().path(+1) + name ).exists() )
+ name = TDEIO::RenameDlg::suggestName( url(), name );
+
+ TQString directory = TDEIO::encodeFileName( KInputDialog::getText( i18n( "New Folder" ),
+ i18n( "Create new folder in:\n%1" ).arg( where ),
+ name, &ok, this));
+ if (!ok)
+ return;
+
+ bool selectDirectory = true;
+ bool writeOk = false;
+ bool exists = false;
+ KURL folderurl( url() );
+
+ TQStringList dirs = TQStringList::split( TQDir::separator(), directory );
+ TQStringList::ConstIterator it = dirs.begin();
+
+ for ( ; it != dirs.end(); ++it )
+ {
+ folderurl.addPath( *it );
+ exists = TDEIO::NetAccess::exists( folderurl, false, 0 );
+ writeOk = !exists && TDEIO::NetAccess::mkdir( folderurl, topLevelWidget() );
+ }
+
+ if ( exists ) // url was already existant
+ {
+ TQString which = folderurl.isLocalFile() ? folderurl.path() : folderurl.prettyURL();
+ KMessageBox::sorry(this, i18n("A file or folder named %1 already exists.").arg(which));
+ selectDirectory = false;
+ }
+ else if ( !writeOk ) {
+ KMessageBox::sorry(this, i18n("You do not have permission to create that folder." ));
+ }
+ else if ( selectDirectory ) {
+ setCurrentURL( folderurl );
+ }
+}
+
+void KDirSelectDialog::slotShowHiddenFoldersToggled()
+{
+ KURL currentURL = url();
+
+ d->comboLocked = true;
+ view()->removeBranch( d->branch );
+ d->comboLocked = false;
+
+ KURL root = rootUrl(d->startURL);
+ d->branch = createBranch( root );
+
+ setCurrentURL( currentURL );
+}
+
+// static
+KURL KDirSelectDialog::selectDirectory( const TQString& startDir,
+ bool localOnly,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ KDirSelectDialog myDialog( startDir, localOnly, parent,
+ "kdirselect dialog", true );
+
+ if ( !caption.isNull() )
+ myDialog.setCaption( caption );
+
+ if ( myDialog.exec() == TQDialog::Accepted )
+ return TDEIO::NetAccess::mostLocalURL(myDialog.url(),parent);
+ else
+ return KURL();
+}
+
+void KDirSelectDialog::virtual_hook( int id, void* data )
+{ KDialogBase::virtual_hook( id, data ); }
+
+#include "kdirselectdialog.moc"
diff --git a/kio/kfile/kdirselectdialog.h b/tdeio/tdefile/kdirselectdialog.h
index 746064c68..746064c68 100644
--- a/kio/kfile/kdirselectdialog.h
+++ b/tdeio/tdefile/kdirselectdialog.h
diff --git a/tdeio/tdefile/kdirsize.cpp b/tdeio/tdefile/kdirsize.cpp
new file mode 100644
index 000000000..c2ea4079a
--- /dev/null
+++ b/tdeio/tdefile/kdirsize.cpp
@@ -0,0 +1,166 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kdirsize.h"
+#include <kdebug.h>
+#include <kglobal.h>
+#include <tqapplication.h>
+#include <tqtimer.h>
+#include <config-tdefile.h>
+
+using namespace TDEIO;
+
+KDirSize::KDirSize( const KURL & directory )
+ : TDEIO::Job(false /*No GUI*/), m_bAsync(true), m_totalSize(0L), m_totalFiles(0L), m_totalSubdirs(0L)
+{
+ startNextJob( directory );
+}
+
+KDirSize::KDirSize( const KFileItemList & lstItems )
+ : TDEIO::Job(false /*No GUI*/), m_bAsync(true), m_totalSize(0L), m_totalFiles(0L), m_totalSubdirs(0L), m_lstItems(lstItems)
+{
+ TQTimer::singleShot( 0, this, TQT_SLOT(processList()) );
+}
+
+void KDirSize::processList()
+{
+ while (!m_lstItems.isEmpty())
+ {
+ KFileItem * item = m_lstItems.first();
+ m_lstItems.removeFirst();
+ if ( !item->isLink() )
+ {
+ if ( item->isDir() )
+ {
+ kdDebug(tdefile_area) << "KDirSize::processList dir -> listing" << endl;
+ KURL url = item->url();
+ startNextJob( url );
+ return; // we'll come back later, when this one's finished
+ }
+ else
+ {
+ m_totalSize += item->size();
+// no long long with kdDebug()
+// kdDebug(tdefile_area) << "KDirSize::processList file -> " << m_totalSize << endl;
+ }
+ }
+ }
+ kdDebug(tdefile_area) << "KDirSize::processList finished" << endl;
+ if ( !m_bAsync )
+ tqApp->exit_loop();
+ emitResult();
+}
+
+void KDirSize::startNextJob( const KURL & url )
+{
+ TDEIO::ListJob * listJob = TDEIO::listRecursive( url, false /* no GUI */ );
+ connect( listJob, TQT_SIGNAL(entries( TDEIO::Job *,
+ const TDEIO::UDSEntryList& )),
+ TQT_SLOT( slotEntries( TDEIO::Job*,
+ const TDEIO::UDSEntryList& )));
+ addSubjob( listJob );
+}
+
+void KDirSize::slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList & list )
+{
+ static const TQString& dot = TDEGlobal::staticQString( "." );
+ static const TQString& dotdot = TDEGlobal::staticQString( ".." );
+ TDEIO::UDSEntryListConstIterator it = list.begin();
+ TDEIO::UDSEntryListConstIterator end = list.end();
+ for (; it != end; ++it) {
+ TDEIO::UDSEntry::ConstIterator it2 = (*it).begin();
+ TDEIO::filesize_t size = 0;
+ bool isLink = false;
+ bool isDir = false;
+ TQString name;
+ for( ; it2 != (*it).end(); it2++ ) {
+ switch( (*it2).m_uds ) {
+ case TDEIO::UDS_NAME:
+ name = (*it2).m_str;
+ break;
+ case TDEIO::UDS_LINK_DEST:
+ isLink = !(*it2).m_str.isEmpty();
+ break;
+ case TDEIO::UDS_SIZE:
+ size = ((*it2).m_long);
+ break;
+ case TDEIO::UDS_FILE_TYPE:
+ isDir = S_ISDIR((*it2).m_long);
+ break;
+ default:
+ break;
+ }
+ }
+ if ( name == dot )
+ m_totalSize += size;
+ else if ( name != dotdot )
+ {
+ if (!isLink)
+ m_totalSize += size;
+ if (!isDir)
+ m_totalFiles++;
+ else
+ m_totalSubdirs++;
+ //kdDebug(tdefile_area) << name << ":" << size << endl;
+ }
+ }
+}
+
+//static
+KDirSize * KDirSize::dirSizeJob( const KURL & directory )
+{
+ return new KDirSize( directory ); // useless - but consistent with other jobs
+}
+
+//static
+KDirSize * KDirSize::dirSizeJob( const KFileItemList & lstItems )
+{
+ return new KDirSize( lstItems );
+}
+
+//static
+TDEIO::filesize_t KDirSize::dirSize( const KURL & directory )
+{
+ KDirSize * dirSize = dirSizeJob( directory );
+ dirSize->setSync();
+ tqApp->enter_loop();
+ return dirSize->totalSize();
+}
+
+
+void KDirSize::slotResult( TDEIO::Job * job )
+{
+ kdDebug(tdefile_area) << " KDirSize::slotResult( TDEIO::Job * job ) m_lstItems:" << m_lstItems.count() << endl;
+ if ( !m_lstItems.isEmpty() )
+ {
+ subjobs.remove(job); // Remove job, but don't kill this job.
+ processList();
+ }
+ else
+ {
+ if ( !m_bAsync )
+ tqApp->exit_loop();
+ TDEIO::Job::slotResult( job );
+ }
+}
+
+void KDirSize::virtual_hook( int id, void* data )
+{ TDEIO::Job::virtual_hook( id, data ); }
+
+#include "kdirsize.moc"
diff --git a/tdeio/tdefile/kdirsize.h b/tdeio/tdefile/kdirsize.h
new file mode 100644
index 000000000..210080950
--- /dev/null
+++ b/tdeio/tdefile/kdirsize.h
@@ -0,0 +1,106 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __KDIRSIZE_H
+#define __KDIRSIZE_H
+
+#include <tdeio/job.h>
+#include <tdefileitem.h>
+
+/**
+ * Computes a directory size (similar to "du", but doesn't give the same results
+ * since we simply sum up the dir and file sizes, whereas du speaks disk blocks)
+ */
+class TDEIO_EXPORT KDirSize : public TDEIO::Job
+{
+ Q_OBJECT
+protected:
+ KDirSize( const KURL & directory );
+ KDirSize( const KFileItemList & lstItems );
+ ~KDirSize() {}
+
+public:
+ /**
+ * @return the size we found
+ */
+ TDEIO::filesize_t totalSize() const { return m_totalSize; }
+
+ /**
+ * @return the total number of files (counting symlinks to files, sockets
+ * and character devices as files) in this directory and all sub-directories
+ * @since 3.3
+ */
+ TDEIO::filesize_t totalFiles() const { return m_totalFiles; }
+
+ /**
+ * @return the total number of sub-directories found (not including the
+ * directory the search started from and treating symlinks to directories
+ * as directories)
+ * @since 3.3
+ */
+ TDEIO::filesize_t totalSubdirs() const { return m_totalSubdirs; }
+
+ /**
+ * Asynchronous method. Connect to the result signal.
+ * This one lists a single directory.
+ */
+ static KDirSize * dirSizeJob( const KURL & directory );
+
+ /**
+ * Asynchronous method. Connect to the result signal.
+ * This one lists the items from @p lstItems.
+ * The reason we asks for items instead of just urls, is so that
+ * we directly know if the item is a file or a directory,
+ * and in case of a file, we already have its size.
+ */
+ static KDirSize * dirSizeJob( const KFileItemList & lstItems );
+
+ /**
+ * Synchronous method - you get the result as soon as
+ * the call returns.
+ */
+ static TDEIO::filesize_t dirSize( const KURL & directory );
+
+protected:
+ /**
+ * @internal
+ */
+ void setSync() { m_bAsync = false; }
+
+ void startNextJob( const KURL & url );
+
+protected slots:
+
+ virtual void slotResult( TDEIO::Job *job );
+ void slotEntries( TDEIO::Job * , const TDEIO::UDSEntryList &);
+ void processList();
+
+private:
+ bool m_bAsync;
+ TDEIO::filesize_t m_totalSize;
+ TDEIO::filesize_t m_totalFiles;
+ TDEIO::filesize_t m_totalSubdirs;
+ KFileItemList m_lstItems;
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KDirSize* d;
+};
+
+#endif
diff --git a/tdeio/tdefile/kdiskfreesp.cpp b/tdeio/tdefile/kdiskfreesp.cpp
new file mode 100644
index 000000000..9a6959fdd
--- /dev/null
+++ b/tdeio/tdefile/kdiskfreesp.cpp
@@ -0,0 +1,169 @@
+/*
+ * kdiskfreesp.cpp
+ *
+ * Copyright (c) 1999 Michael Kropfberger <michael.kropfberger@gmx.net>
+ *
+ * Requires the Qt widget libraries, available at no cost at
+ * http://www.troll.no/
+ *
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "kdiskfreesp.h"
+#include <tqfile.h>
+#include <tqtextstream.h>
+
+#include <kdebug.h>
+#include <kprocess.h>
+#include <tdeio/global.h>
+#include <config-tdefile.h>
+
+#include "kdiskfreesp.moc"
+
+#define DF_COMMAND "df"
+#define DF_ARGS "-k"
+#define NO_FS_TYPE true
+
+#define BLANK ' '
+#define FULL_PERCENT 95.0
+
+/***************************************************************************
+ * constructor
+**/
+KDiskFreeSp::KDiskFreeSp(TQObject *parent, const char *name)
+ : TQObject(parent,name)
+{
+ dfProc = new TDEProcess(); TQ_CHECK_PTR(dfProc);
+ dfProc->setEnvironment("LANGUAGE", "C");
+ connect( dfProc, TQT_SIGNAL(receivedStdout(TDEProcess *, char *, int) ),
+ this, TQT_SLOT (receivedDFStdErrOut(TDEProcess *, char *, int)) );
+ connect(dfProc,TQT_SIGNAL(processExited(TDEProcess *) ),
+ this, TQT_SLOT(dfDone() ) );
+
+ readingDFStdErrOut=false;
+}
+
+
+/***************************************************************************
+ * destructor
+**/
+KDiskFreeSp::~KDiskFreeSp()
+{
+ delete dfProc;
+}
+
+/***************************************************************************
+ * is called, when the df-command writes on StdOut
+**/
+void KDiskFreeSp::receivedDFStdErrOut(TDEProcess *, char *data, int len)
+{
+ TQCString tmp(data,len+1); // adds a zero-byte
+ dfStringErrOut.append(tmp);
+}
+
+/***************************************************************************
+ * reads the df-commands results
+**/
+int KDiskFreeSp::readDF( const TQString & mountPoint )
+{
+ if (readingDFStdErrOut || dfProc->isRunning())
+ return -1;
+ m_mountPoint = mountPoint;
+ dfStringErrOut=""; // yet no data received
+ dfProc->clearArguments();
+ (*dfProc) << TQString::fromLocal8Bit(DF_COMMAND) << TQString::fromLocal8Bit(DF_ARGS);
+ if (!dfProc->start( TDEProcess::NotifyOnExit, TDEProcess::AllOutput ))
+ kdError() << "could not execute ["<< DF_COMMAND << "]" << endl;
+ return 1;
+}
+
+
+/***************************************************************************
+ * is called, when the df-command has finished
+**/
+void KDiskFreeSp::dfDone()
+{
+ readingDFStdErrOut=true;
+
+ TQTextStream t (dfStringErrOut, IO_ReadOnly);
+ TQString s=t.readLine();
+ if ( (s.isEmpty()) || ( s.left(10) != TQString::fromLatin1("Filesystem") ) )
+ kdError() << "Error running df command... got [" << s << "]" << endl;
+ while ( !t.eof() ) {
+ TQString u,v;
+ s=t.readLine();
+ s=s.simplifyWhiteSpace();
+ if ( !s.isEmpty() ) {
+ //kdDebug(tdefile_area) << "GOT: [" << s << "]" << endl;
+
+ if (s.find(BLANK)<0) // devicename was too long, rest in next line
+ if ( !t.eof() ) { // just appends the next line
+ v=t.readLine();
+ s=s.append(v);
+ s=s.simplifyWhiteSpace();
+ //kdDebug(tdefile_area) << "SPECIAL GOT: [" << s << "]" << endl;
+ }//if silly linefeed
+
+ //kdDebug(tdefile_area) << "[" << s << "]" << endl;
+
+ //TQString deviceName = s.left(s.find(BLANK));
+ s=s.remove(0,s.find(BLANK)+1 );
+ //kdDebug(tdefile_area) << " DeviceName: [" << deviceName << "]" << endl;
+
+ if (!NO_FS_TYPE)
+ s=s.remove(0,s.find(BLANK)+1 ); // eat fs type
+
+ u=s.left(s.find(BLANK));
+ unsigned long kBSize = u.toULong();
+ s=s.remove(0,s.find(BLANK)+1 );
+ //kdDebug(tdefile_area) << " Size: [" << kBSize << "]" << endl;
+
+ u=s.left(s.find(BLANK));
+ unsigned long kBUsed = u.toULong();
+ s=s.remove(0,s.find(BLANK)+1 );
+ //kdDebug(tdefile_area) << " Used: [" << kBUsed << "]" << endl;
+
+ u=s.left(s.find(BLANK));
+ unsigned long kBAvail = u.toULong();
+ s=s.remove(0,s.find(BLANK)+1 );
+ //kdDebug(tdefile_area) << " Avail: [" << kBAvail << "]" << endl;
+
+
+ s=s.remove(0,s.find(BLANK)+1 ); // delete the capacity 94%
+ TQString mountPoint = s.stripWhiteSpace();
+ //kdDebug(tdefile_area) << " MountPoint: [" << mountPoint << "]" << endl;
+
+ if ( mountPoint == m_mountPoint )
+ {
+ //kdDebug(tdefile_area) << "Found mount point. Emitting" << endl;
+ emit foundMountPoint( mountPoint, kBSize, kBUsed, kBAvail );
+ emit foundMountPoint( kBSize, kBUsed, kBAvail, mountPoint ); // sic!
+ }
+ }//if not header
+ }//while further lines available
+
+ readingDFStdErrOut=false;
+ emit done();
+ delete this;
+}
+
+KDiskFreeSp * KDiskFreeSp::findUsageInfo( const TQString & path )
+{
+ KDiskFreeSp * job = new KDiskFreeSp;
+ TQString mountPoint = TDEIO::findPathMountPoint( path );
+ job->readDF( mountPoint );
+ return job;
+}
diff --git a/kio/kfile/kdiskfreesp.h b/tdeio/tdefile/kdiskfreesp.h
index 5ffa47d9a..5ffa47d9a 100644
--- a/kio/kfile/kdiskfreesp.h
+++ b/tdeio/tdefile/kdiskfreesp.h
diff --git a/tdeio/tdefile/kencodingfiledialog.cpp b/tdeio/tdefile/kencodingfiledialog.cpp
new file mode 100644
index 000000000..b8c90f6ff
--- /dev/null
+++ b/tdeio/tdefile/kencodingfiledialog.cpp
@@ -0,0 +1,223 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2003 Joseph Wenninger <jowenn@kde.org>
+ 2003 Andras Mantia <amantia@freemail.hu>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "config-tdefile.h"
+
+#include "kencodingfiledialog.h"
+#include <kcombobox.h>
+#include <ktoolbar.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kcharsets.h>
+#include <tqtextcodec.h>
+#include <kdiroperator.h>
+#include <krecentdocument.h>
+
+struct KEncodingFileDialogPrivate
+{
+ KComboBox *encoding;
+};
+
+KEncodingFileDialog::KEncodingFileDialog(const TQString& startDir, const TQString& encoding , const TQString& filter,
+ const TQString& caption, KFileDialog::OperationMode type, TQWidget *parent, const char* name, bool modal)
+ : KFileDialog(startDir,filter,parent,name,modal), d(new KEncodingFileDialogPrivate)
+{
+ setCaption(caption);
+
+ setOperationMode( type );
+
+ KToolBar *tb = toolBar();
+ tb->insertSeparator();
+ int index = tb->insertCombo(TQStringList(), -1 /*id*/, false /*writable*/, 0 /*signal*/, 0 /*receiver*/, 0 /*slot*/ );
+ d->encoding = tb->getCombo( tb->idAt( index ) );
+ if ( !d->encoding )
+ return;
+
+ d->encoding->clear ();
+ TQString sEncoding = encoding;
+ if (sEncoding.isEmpty())
+ sEncoding = TQString::fromLatin1(TDEGlobal::locale()->encoding());
+
+ TQStringList encodings (TDEGlobal::charsets()->availableEncodingNames());
+ int insert = 0;
+ for (uint i=0; i < encodings.count(); i++)
+ {
+ bool found = false;
+ TQTextCodec *codecForEnc = TDEGlobal::charsets()->codecForName(encodings[i], found);
+
+ if (found)
+ {
+ d->encoding->insertItem (encodings[i]);
+ if ( (codecForEnc->name() == sEncoding) || (encodings[i] == sEncoding) )
+ {
+ d->encoding->setCurrentItem(insert);
+ }
+
+ insert++;
+ }
+ }
+
+
+}
+
+KEncodingFileDialog::~KEncodingFileDialog()
+{
+ delete d;
+}
+
+
+TQString KEncodingFileDialog::selectedEncoding() const
+{
+ if (d->encoding)
+ return d->encoding->currentText();
+ else
+ return TQString::null;
+}
+
+
+KEncodingFileDialog::Result KEncodingFileDialog::getOpenFileNameAndEncoding(const TQString& encoding,
+ const TQString& startDir,
+ const TQString& filter,
+ TQWidget *parent, const TQString& caption)
+{
+ KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
+ "filedialog", true);
+
+ dlg.setMode( KFile::File | KFile::LocalOnly );
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ Result res;
+ res.fileNames<<dlg.selectedFile();
+ res.encoding=dlg.selectedEncoding();
+ return res;
+}
+
+KEncodingFileDialog::Result KEncodingFileDialog::getOpenFileNamesAndEncoding(const TQString& encoding,
+ const TQString& startDir,
+ const TQString& filter,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
+ "filedialog", true);
+ dlg.setMode(KFile::Files | KFile::LocalOnly);
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ Result res;
+ res.fileNames=dlg.selectedFiles();
+ res.encoding=dlg.selectedEncoding();
+ return res;
+}
+
+KEncodingFileDialog::Result KEncodingFileDialog::getOpenURLAndEncoding(const TQString& encoding, const TQString& startDir,
+ const TQString& filter, TQWidget *parent, const TQString& caption)
+{
+ KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
+ "filedialog", true);
+
+ dlg.setMode( KFile::File );
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ Result res;
+ res.URLs<<dlg.selectedURL();
+ res.encoding=dlg.selectedEncoding();
+ return res;
+}
+
+KEncodingFileDialog::Result KEncodingFileDialog::getOpenURLsAndEncoding(const TQString& encoding, const TQString& startDir,
+ const TQString& filter,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ KEncodingFileDialog dlg(startDir, encoding,filter,caption.isNull() ? i18n("Open") : caption,Opening,parent,
+ "filedialog", true);
+
+ dlg.setMode(KFile::Files);
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ Result res;
+ res.URLs=dlg.selectedURLs();
+ res.encoding=dlg.selectedEncoding();
+ return res;
+}
+
+
+KEncodingFileDialog::Result KEncodingFileDialog::getSaveFileNameAndEncoding(const TQString& encoding,
+ const TQString& dir,
+ const TQString& filter,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ bool specialDir = dir.at(0) == ':';
+ KEncodingFileDialog dlg(specialDir?dir:TQString::null, encoding,filter,caption.isNull() ? i18n("Save As") : caption,
+ Saving,parent, "filedialog", true);
+
+ if ( !specialDir )
+ dlg.setSelection( dir ); // may also be a filename
+ dlg.exec();
+
+ TQString filename = dlg.selectedFile();
+ if (!filename.isEmpty())
+ KRecentDocument::add(filename);
+
+ Result res;
+ res.fileNames<<filename;
+ res.encoding=dlg.selectedEncoding();
+ return res;
+}
+
+
+KEncodingFileDialog::Result KEncodingFileDialog::getSaveURLAndEncoding(const TQString& encoding,
+ const TQString& dir, const TQString& filter,
+ TQWidget *parent, const TQString& caption)
+{
+ bool specialDir = dir.at(0) == ':';
+ KEncodingFileDialog dlg(specialDir?dir:TQString::null, encoding,filter,caption.isNull() ? i18n("Save As") :
+ caption, Saving,parent, "filedialog", true);
+
+ if ( !specialDir )
+ dlg.setSelection( dir ); // may also be a filename
+
+ dlg.exec();
+
+ KURL url = dlg.selectedURL();
+ if (url.isValid())
+ KRecentDocument::add( url );
+
+ Result res;
+ res.URLs<<url;
+ res.encoding=dlg.selectedEncoding();
+ return res;
+}
+
+
+
+void KEncodingFileDialog::virtual_hook( int id, void* data )
+{
+ KFileDialog::virtual_hook( id, data );
+}
+
+
+#include "kencodingfiledialog.moc"
diff --git a/tdeio/tdefile/kencodingfiledialog.h b/tdeio/tdefile/kencodingfiledialog.h
new file mode 100644
index 000000000..8659122fb
--- /dev/null
+++ b/tdeio/tdefile/kencodingfiledialog.h
@@ -0,0 +1,313 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2003 Joseph Wenninger <jowenn@kde.org>
+ 2003 Andras Mantia <amantia@freemail.hu>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __KENCODINGFILEDIALOG_H__
+#define __KENCODINGFILEDIALOG_H__
+
+#include <tdefiledialog.h>
+
+struct KEncodingFileDialogPrivate;
+
+/**
+ * Provides a user (and developer) friendly way to
+ * select files with support for choosing encoding
+ *
+ *
+ * The dialog has been designed to allow applications to customise it
+ * by subclassing. It uses geometry management to ensure that subclasses
+ * can easily add children that will be incorporated into the layout.
+ */
+
+class TDEIO_EXPORT KEncodingFileDialog : public KFileDialog
+{
+ Q_OBJECT
+
+public:
+ class Result {
+ public:
+ TQStringList fileNames;
+ KURL::List URLs;
+ TQString encoding;
+ };
+
+ /**
+ * Constructs a file dialog for text files with encoding selection possibility.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ *
+ * @param encoding The encoding shown in the encoding combo. If it's
+ * TQString::null, the global default encoding will be shown.
+ *
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ *
+ * @param caption The caption of the dialog
+ *
+ * @param type This can either be
+ * @li Opening (open dialog, the default setting)
+ * @li Saving
+ * @param parent The parent widget of this dialog
+ * @param name The name of this object
+ * @param modal Whether to create a modal dialog or not
+ *
+ * @since 3.2
+ */
+ KEncodingFileDialog (const TQString& startDir = TQString::null,
+ const TQString& encoding = TQString::null,
+ const TQString& filter = TQString::null,
+ const TQString& caption = TQString::null, KFileDialog::OperationMode type = KFileDialog::Opening,
+ TQWidget *parent= 0, const char *name="", bool modal = true);
+ /**
+ * Destructs the file dialog.
+ */
+ ~KEncodingFileDialog();
+
+
+ /**
+ * @returns The selected encoding if the constructor with the encoding parameter was used, otherwise TQString::null.
+ */
+ TQString selectedEncoding() const;
+
+
+ /**
+ * Creates a modal file dialog and return the selected
+ * filename or an empty string if none was chosen additionally a chosen
+ * encoding value is returned.
+ *
+ * Note that with
+ * this method the user must select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param encoding The encoding shown in the encoding combo.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static Result getOpenFileNameAndEncoding(const TQString& encoding=TQString::null,
+ const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+ /**
+ * Creates a modal file dialog and returns the selected encoding and the selected
+ * filenames or an empty list if none was chosen.
+ *
+ * Note that with
+ * this method the user must select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param encoding The encoding shown in the encoding combo.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this.
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static Result getOpenFileNamesAndEncoding(const TQString& encoding=TQString::null,
+ const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent = 0,
+ const TQString& caption= TQString::null);
+
+ /**
+ * Creates a modal file dialog and returns the selected encoding and
+ * URL or an empty string if none was chosen.
+ *
+ * Note that with
+ * this method the user must select an existing URL.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param encoding The encoding shown in the encoding combo.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static Result getOpenURLAndEncoding(const TQString& encoding=TQString::null,
+ const TQString& startDir = TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+
+
+
+ /**
+ * Creates a modal file dialog and returns the selected encoding
+ * URLs or an empty list if none was chosen.
+ *
+ * Note that with
+ * this method the user must select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param encoding The encoding shown in the encoding combo.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static Result getOpenURLsAndEncoding(const TQString& encoding=TQString::null,
+ const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent = 0,
+ const TQString& caption= TQString::null);
+
+
+
+ /**
+ * Creates a modal file dialog and returns the selected encoding and
+ * filename or an empty string if none was chosen.
+ *
+ * Note that with this
+ * method the user need not select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li a relative path or a filename determining the
+ * directory to start in and the file to be selected.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param encoding The encoding shown in the encoding combo.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static Result getSaveFileNameAndEncoding(const TQString& encoding=TQString::null,
+ const TQString& startDir=TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+
+ /**
+ * Creates a modal file dialog and returns the selected encoding and
+ * filename or an empty string if none was chosen.
+ *
+ * Note that with this
+ * method the user need not select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li a relative path or a filename determining the
+ * directory to start in and the file to be selected.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param encoding The encoding shown in the encoding combo.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static Result getSaveURLAndEncoding(const TQString& encoding=TQString::null,
+ const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ KEncodingFileDialogPrivate *d;
+};
+
+#endif
diff --git a/tdeio/tdefile/kicondialog.cpp b/tdeio/tdefile/kicondialog.cpp
new file mode 100644
index 000000000..da8745507
--- /dev/null
+++ b/tdeio/tdefile/kicondialog.cpp
@@ -0,0 +1,772 @@
+/* vi: ts=8 sts=4 sw=4
+ *
+ * This file is part of the KDE project, module tdefile.
+ * Copyright (C) 2000 Geert Jansen <jansen@kde.org>
+ * (C) 2000 Kurt Granroth <granroth@kde.org>
+ * (C) 1997 Christoph Neerfeld <chris@kde.org>
+ * (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
+ *
+ * This is free software; it comes under the GNU Library General
+ * Public License, version 2. See the file "COPYING.LIB" for the
+ * exact licensing terms.
+ */
+
+#include "kicondialog.h"
+
+#include <config.h>
+
+#include <assert.h>
+
+#include <kiconviewsearchline.h>
+
+#include <kapplication.h>
+#include <klocale.h>
+#include <kglobal.h>
+#include <kstandarddirs.h>
+#include <kiconloader.h>
+#include <kprogress.h>
+#include <kiconview.h>
+#include <tdefiledialog.h>
+#include <kimagefilepreview.h>
+
+#include <tqlayout.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqsortedlist.h>
+#include <tqimage.h>
+#include <tqpixmap.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+#include <tqtimer.h>
+#include <tqbuttongroup.h>
+#include <tqradiobutton.h>
+#include <tqfileinfo.h>
+#include <tqtoolbutton.h>
+#include <tqwhatsthis.h>
+
+#ifdef HAVE_LIBART
+#include <svgicons/ksvgiconengine.h>
+#include <svgicons/ksvgiconpainter.h>
+#endif
+
+class KIconCanvas::KIconCanvasPrivate
+{
+ public:
+ KIconCanvasPrivate() { m_bLoading = false; }
+ ~KIconCanvasPrivate() {}
+ bool m_bLoading;
+};
+
+/**
+ * Helper class for sorting icon paths by icon name
+ */
+class IconPath : public TQString
+{
+protected:
+ TQString m_iconName;
+
+public:
+ IconPath(const TQString &ip) : TQString (ip)
+ {
+ int n = findRev('/');
+ m_iconName = (n==-1) ? static_cast<TQString>(*this) : mid(n+1);
+ }
+
+
+ IconPath() : TQString ()
+ { }
+
+ bool operator== (const IconPath &ip) const
+ { return m_iconName == ip.m_iconName; }
+
+ bool operator< (const IconPath &ip) const
+ { return m_iconName < ip.m_iconName; }
+
+};
+
+/*
+ * KIconCanvas: Iconview for the iconloader dialog.
+ */
+
+KIconCanvas::KIconCanvas(TQWidget *parent, const char *name)
+ : KIconView(parent, name)
+{
+ d = new KIconCanvasPrivate;
+ mpTimer = new TQTimer(this);
+ connect(mpTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotLoadFiles()));
+ connect(this, TQT_SIGNAL(currentChanged(TQIconViewItem *)),
+ TQT_SLOT(slotCurrentChanged(TQIconViewItem *)));
+ setGridX(80);
+ setWordWrapIconText(false);
+ setShowToolTips(true);
+}
+
+KIconCanvas::~KIconCanvas()
+{
+ delete mpTimer;
+ delete d;
+}
+
+void KIconCanvas::loadFiles(const TQStringList& files)
+{
+ clear();
+ mFiles = files;
+ emit startLoading(mFiles.count());
+ mpTimer->start(10, true); // #86680
+ d->m_bLoading = false;
+}
+
+void KIconCanvas::slotLoadFiles()
+{
+ setResizeMode(Fixed);
+ TQApplication::setOverrideCursor(tqwaitCursor);
+
+ // disable updates to not trigger paint events when adding child items
+ setUpdatesEnabled( false );
+
+#ifdef HAVE_LIBART
+ KSVGIconEngine *svgEngine = new KSVGIconEngine();
+#endif
+
+ d->m_bLoading = true;
+ int i;
+ TQStringList::ConstIterator it;
+ uint emitProgress = 10; // so we will emit it once in the beginning
+ TQStringList::ConstIterator end(mFiles.end());
+ for (it=mFiles.begin(), i=0; it!=end; ++it, i++)
+ {
+ // Calling kapp->processEvents() makes the iconview flicker like hell
+ // (it's being repainted once for every new item), so we don't do this.
+ // Instead, we directly repaint the progress bar without going through
+ // the event-loop. We do that just once for every 10th item so that
+ // the progress bar doesn't flicker in turn. (pfeiffer)
+ if ( emitProgress >= 10 ) {
+ emit progress(i);
+ emitProgress = 0;
+ }
+
+ emitProgress++;
+// kapp->processEvents();
+ if ( !d->m_bLoading ) // user clicked on a button that will load another set of icons
+ break;
+ TQImage img;
+
+ // Use the extension as the format. Works for XPM and PNG, but not for SVG
+ TQString path= *it;
+ TQString ext = path.right(3).upper();
+
+ if (ext != "SVG" && ext != "VGZ")
+ img.load(*it);
+#ifdef HAVE_LIBART
+ else
+ if (svgEngine->load(60, 60, *it))
+ img = *svgEngine->painter()->image();
+#endif
+
+ if (img.isNull())
+ continue;
+ if (img.width() > 60 || img.height() > 60)
+ {
+ if (img.width() > img.height())
+ {
+ int height = (int) ((60.0 / img.width()) * img.height());
+ img = img.smoothScale(60, height);
+ } else
+ {
+ int width = (int) ((60.0 / img.height()) * img.width());
+ img = img.smoothScale(width, 60);
+ }
+ }
+ TQPixmap pm;
+ pm.convertFromImage(img);
+ TQFileInfo fi(*it);
+ TQIconViewItem *item = new TQIconViewItem(this, fi.baseName(), pm);
+ item->setKey(*it);
+ item->setDragEnabled(false);
+ item->setDropEnabled(false);
+ }
+
+#ifdef HAVE_LIBART
+ delete svgEngine;
+#endif
+
+ // enable updates since we have to draw the whole view now
+ setUpdatesEnabled( true );
+
+ TQApplication::restoreOverrideCursor();
+ d->m_bLoading = false;
+ emit finished();
+ setResizeMode(Adjust);
+}
+
+TQString KIconCanvas::getCurrent() const
+{
+ if (!currentItem())
+ return TQString::null;
+ return currentItem()->key();
+}
+
+void KIconCanvas::stopLoading()
+{
+ d->m_bLoading = false;
+}
+
+void KIconCanvas::slotCurrentChanged(TQIconViewItem *item)
+{
+ emit nameChanged((item != 0L) ? item->text() : TQString::null);
+}
+
+class KIconDialog::KIconDialogPrivate
+{
+ public:
+ KIconDialogPrivate() {
+ m_bStrictIconSize = true;
+ m_bLockUser = false;
+ m_bLockCustomDir = false;
+ searchLine = 0;
+ }
+ ~KIconDialogPrivate() {}
+ bool m_bStrictIconSize, m_bLockUser, m_bLockCustomDir;
+ TQString custom;
+ TQString customLocation;
+ KIconViewSearchLine *searchLine;
+};
+
+/*
+ * KIconDialog: Dialog for selecting icons. Both system and user
+ * specified icons can be chosen.
+ */
+
+KIconDialog::KIconDialog(TQWidget *parent, const char *name)
+ : KDialogBase(parent, name, true, i18n("Select Icon"), Ok|Cancel, Ok)
+{
+ d = new KIconDialogPrivate;
+ mpLoader = TDEGlobal::iconLoader();
+ init();
+}
+
+KIconDialog::KIconDialog(KIconLoader *loader, TQWidget *parent,
+ const char *name)
+ : KDialogBase(parent, name, true, i18n("Select Icon"), Ok|Cancel, Ok)
+{
+ d = new KIconDialogPrivate;
+ mpLoader = loader;
+ init();
+}
+
+void KIconDialog::init()
+{
+ mGroupOrSize = KIcon::Desktop;
+ mContext = KIcon::Any;
+ mType = 0;
+ mFileList = TDEGlobal::dirs()->findAllResources("appicon", TQString::fromLatin1("*.png"));
+
+ TQWidget *main = new TQWidget( this );
+ setMainWidget(main);
+
+ TQVBoxLayout *top = new TQVBoxLayout(main);
+ top->setSpacing( spacingHint() );
+
+ TQButtonGroup *bgroup = new TQButtonGroup(0, Qt::Vertical, i18n("Icon Source"), main);
+ bgroup->layout()->setSpacing(KDialog::spacingHint());
+ bgroup->layout()->setMargin(KDialog::marginHint());
+ top->addWidget(bgroup);
+ connect(bgroup, TQT_SIGNAL(clicked(int)), TQT_SLOT(slotButtonClicked(int)));
+ TQGridLayout *grid = new TQGridLayout(bgroup->layout(), 3, 2);
+ mpRb1 = new TQRadioButton(i18n("S&ystem icons:"), bgroup);
+ grid->addWidget(mpRb1, 1, 0);
+ mpCombo = new TQComboBox(bgroup);
+ connect(mpCombo, TQT_SIGNAL(activated(int)), TQT_SLOT(slotContext(int)));
+ grid->addWidget(mpCombo, 1, 1);
+ mpRb2 = new TQRadioButton(i18n("O&ther icons:"), bgroup);
+ grid->addWidget(mpRb2, 2, 0);
+ mpBrowseBut = new TQPushButton(i18n("&Browse..."), bgroup);
+ grid->addWidget(mpBrowseBut, 2, 1);
+
+ //
+ // ADD SEARCHLINE
+ //
+ TQHBoxLayout *searchLayout = new TQHBoxLayout(0, 0, KDialog::spacingHint());
+ top->addLayout(searchLayout);
+
+ TQToolButton *clearSearch = new TQToolButton(main);
+ clearSearch->setTextLabel(i18n("Clear Search"), true);
+ clearSearch->setIconSet(SmallIconSet(TQApplication::reverseLayout() ? "clear_left" :"locationbar_erase"));
+ searchLayout->addWidget(clearSearch);
+
+ TQLabel *searchLabel = new TQLabel(i18n("&Search:"), main);
+ searchLayout->addWidget(searchLabel);
+
+ d->searchLine = new KIconViewSearchLine(main, "searchLine");
+ searchLayout->addWidget(d->searchLine);
+ searchLabel->setBuddy(d->searchLine);
+
+
+ // signals and slots connections
+ connect(clearSearch, TQT_SIGNAL(clicked()), d->searchLine, TQT_SLOT(clear()));
+
+ TQString wtstr = i18n("Search interactively for icon names (e.g. folder).");
+ TQWhatsThis::add(searchLabel, wtstr);
+ TQWhatsThis::add(d->searchLine, wtstr);
+
+
+ mpCanvas = new KIconCanvas(main);
+ connect(mpCanvas, TQT_SIGNAL(executed(TQIconViewItem *)), TQT_SLOT(slotAcceptIcons()));
+ connect(mpCanvas, TQT_SIGNAL(returnPressed(TQIconViewItem *)), TQT_SLOT(slotAcceptIcons()));
+ mpCanvas->setMinimumSize(400, 125);
+ top->addWidget(mpCanvas);
+ d->searchLine->setIconView(mpCanvas);
+
+ mpProgress = new KProgress(main);
+ top->addWidget(mpProgress);
+ connect(mpCanvas, TQT_SIGNAL(startLoading(int)), TQT_SLOT(slotStartLoading(int)));
+ connect(mpCanvas, TQT_SIGNAL(progress(int)), TQT_SLOT(slotProgress(int)));
+ connect(mpCanvas, TQT_SIGNAL(finished()), TQT_SLOT(slotFinished()));
+
+ // When pressing Ok or Cancel, stop loading icons
+ connect(this, TQT_SIGNAL(hidden()), mpCanvas, TQT_SLOT(stopLoading()));
+
+ static const char* const context_text[] = {
+ I18N_NOOP( "Actions" ),
+ I18N_NOOP( "Animations" ),
+ I18N_NOOP( "Applications" ),
+ I18N_NOOP( "Categories" ),
+ I18N_NOOP( "Devices" ),
+ I18N_NOOP( "Emblems" ),
+ I18N_NOOP( "Emotes" ),
+ I18N_NOOP( "Filesystems" ),
+ I18N_NOOP( "International" ),
+ I18N_NOOP( "Mimetypes" ),
+ I18N_NOOP( "Places" ),
+ I18N_NOOP( "Status" ) };
+ static const KIcon::Context context_id[] = {
+ KIcon::Action,
+ KIcon::Animation,
+ KIcon::Application,
+ KIcon::Category,
+ KIcon::Device,
+ KIcon::Emblem,
+ KIcon::Emote,
+ KIcon::FileSystem,
+ KIcon::International,
+ KIcon::MimeType,
+ KIcon::Place,
+ KIcon::StatusIcon };
+ mNumContext = 0;
+ int cnt = sizeof( context_text ) / sizeof( context_text[ 0 ] );
+ // check all 3 arrays have same sizes
+ assert( cnt == sizeof( context_id ) / sizeof( context_id[ 0 ] )
+ && cnt == sizeof( mContextMap ) / sizeof( mContextMap[ 0 ] ));
+ for( int i = 0;
+ i < cnt;
+ ++i )
+ {
+ if( mpLoader->hasContext( context_id[ i ] ))
+ {
+ mpCombo->insertItem(i18n( context_text[ i ] ));
+ mContextMap[ mNumContext++ ] = context_id[ i ];
+ }
+ }
+ mpCombo->setFixedSize(mpCombo->sizeHint());
+
+ mpBrowseBut->setFixedWidth(mpCombo->width());
+
+ // Make the dialog a little taller
+ incInitialSize(TQSize(0,100));
+}
+
+
+KIconDialog::~KIconDialog()
+{
+ delete d;
+}
+
+void KIconDialog::slotAcceptIcons()
+{
+ d->custom=TQString::null;
+ slotOk();
+}
+
+void KIconDialog::showIcons()
+{
+ mpCanvas->clear();
+ TQStringList filelist;
+ if (mType == 0)
+ if (d->m_bStrictIconSize)
+ filelist=mpLoader->queryIcons(mGroupOrSize, mContext);
+ else
+ filelist=mpLoader->queryIconsByContext(mGroupOrSize, mContext);
+ else if ( !d->customLocation.isNull() )
+ filelist=mpLoader->queryIconsByDir( d->customLocation );
+ else
+ filelist=mFileList;
+
+ TQSortedList <IconPath>iconlist;
+ iconlist.setAutoDelete(true);
+ TQStringList::Iterator it;
+ for( it = filelist.begin(); it != filelist.end(); ++it )
+ iconlist.append(new IconPath(*it));
+
+ iconlist.sort();
+ filelist.clear();
+
+ for ( IconPath *ip=iconlist.first(); ip != 0; ip=iconlist.next() )
+ filelist.append(*ip);
+
+ d->searchLine->clear();
+ mpCanvas->loadFiles(filelist);
+}
+
+void KIconDialog::setStrictIconSize(bool b)
+{
+ d->m_bStrictIconSize=b;
+}
+
+bool KIconDialog::strictIconSize() const
+{
+ return d->m_bStrictIconSize;
+}
+
+void KIconDialog::setIconSize( int size )
+{
+ // see KIconLoader, if you think this is weird
+ if ( size == 0 )
+ mGroupOrSize = KIcon::Desktop; // default Group
+ else
+ mGroupOrSize = -size; // yes, KIconLoader::queryIconsByContext is weird
+}
+
+int KIconDialog::iconSize() const
+{
+ // 0 or any other value ==> mGroupOrSize is a group, so we return 0
+ return (mGroupOrSize < 0) ? -mGroupOrSize : 0;
+}
+
+#ifndef KDE_NO_COMPAT
+TQString KIconDialog::selectIcon(KIcon::Group group, KIcon::Context context, bool user)
+{
+ setup( group, context, false, 0, user );
+ return openDialog();
+}
+#endif
+
+void KIconDialog::setup(KIcon::Group group, KIcon::Context context,
+ bool strictIconSize, int iconSize, bool user )
+{
+ d->m_bStrictIconSize = strictIconSize;
+ mGroupOrSize = (iconSize == 0) ? group : -iconSize;
+ mType = user ? 1 : 0;
+ mpRb1->setChecked(!user);
+ mpRb2->setChecked(user);
+ mpCombo->setEnabled(!user);
+ mpBrowseBut->setEnabled(user);
+ setContext( context );
+}
+
+void KIconDialog::setup(KIcon::Group group, KIcon::Context context,
+ bool strictIconSize, int iconSize, bool user,
+ bool lockUser, bool lockCustomDir )
+{
+ d->m_bStrictIconSize = strictIconSize;
+ d->m_bLockUser = lockUser;
+ d->m_bLockCustomDir = lockCustomDir;
+ mGroupOrSize = (iconSize == 0) ? group : -iconSize;
+ mType = user ? 1 : 0;
+ mpRb1->setChecked(!user);
+ mpRb1->setEnabled( !lockUser || !user );
+ mpRb2->setChecked(user);
+ mpRb2->setEnabled( !lockUser || user );
+ mpCombo->setEnabled(!user);
+ mpBrowseBut->setEnabled( user && !lockCustomDir );
+ setContext( context );
+}
+
+void KIconDialog::setContext( KIcon::Context context )
+{
+ mContext = context;
+ for( int i = 0;
+ i < mNumContext;
+ ++i )
+ if( mContextMap[ i ] == context )
+ {
+ mpCombo->setCurrentItem( i );
+ return;
+ }
+}
+
+void KIconDialog::setCustomLocation( const TQString& location )
+{
+ d->customLocation = location;
+}
+
+TQString KIconDialog::openDialog()
+{
+ showIcons();
+
+ if ( exec() == Accepted )
+ {
+ if (!d->custom.isNull())
+ return d->custom;
+ TQString name = mpCanvas->getCurrent();
+ if (name.isEmpty() || (mType == 1))
+ return name;
+ TQFileInfo fi(name);
+ return fi.baseName();
+ }
+ return TQString::null;
+}
+
+void KIconDialog::showDialog()
+{
+ setModal(false);
+ showIcons();
+ show();
+}
+
+void KIconDialog::slotOk()
+{
+ TQString name;
+ if (!d->custom.isNull())
+ {
+ name = d->custom;
+ }
+ else
+ {
+ name = mpCanvas->getCurrent();
+ if (!name.isEmpty() && (mType != 1))
+ {
+ TQFileInfo fi(name);
+ name = fi.baseName();
+ }
+ }
+
+ emit newIconName(name);
+ KDialogBase::slotOk();
+}
+
+TQString KIconDialog::getIcon(KIcon::Group group, KIcon::Context context,
+ bool strictIconSize, int iconSize, bool user,
+ TQWidget *parent, const TQString &caption)
+{
+ KIconDialog dlg(parent, "icon dialog");
+ dlg.setup( group, context, strictIconSize, iconSize, user );
+ if (!caption.isNull())
+ dlg.setCaption(caption);
+
+ return dlg.openDialog();
+}
+
+void KIconDialog::slotButtonClicked(int id)
+{
+ TQString file;
+
+ switch (id)
+ {
+ case 0:
+ if(mType!=0)
+ {
+ mType = 0;
+ mpBrowseBut->setEnabled(false);
+ mpCombo->setEnabled(true);
+ showIcons();
+ }
+ break;
+
+ case 1:
+ if(mType!=1)
+ {
+ mType = 1;
+ mpBrowseBut->setEnabled( !d->m_bLockCustomDir );
+ mpCombo->setEnabled(false);
+ showIcons();
+ }
+ break;
+ case 2:
+ {
+ // Create a file dialog to select a PNG, XPM or SVG file,
+ // with the image previewer shown.
+ // KFileDialog::getImageOpenURL doesn't allow svg.
+ KFileDialog dlg(TQString::null, i18n("*.png *.xpm *.svg *.svgz|Icon Files (*.png *.xpm *.svg *.svgz)"),
+ this, "filedialog", true);
+ dlg.setOperationMode( KFileDialog::Opening );
+ dlg.setCaption( i18n("Open") );
+ dlg.setMode( KFile::File );
+
+ KImageFilePreview *ip = new KImageFilePreview( &dlg );
+ dlg.setPreviewWidget( ip );
+ dlg.exec();
+
+ file = dlg.selectedFile();
+ if (!file.isEmpty())
+ {
+ d->custom = file;
+ if ( mType == 1 )
+ d->customLocation = TQFileInfo( file ).dirPath( true );
+ slotOk();
+ }
+ }
+ break;
+ }
+}
+
+void KIconDialog::slotContext(int id)
+{
+ mContext = static_cast<KIcon::Context>( mContextMap[ id ] );
+ showIcons();
+}
+
+void KIconDialog::slotStartLoading(int steps)
+{
+ if (steps < 10)
+ mpProgress->hide();
+ else
+ {
+ mpProgress->setTotalSteps(steps);
+ mpProgress->setProgress(0);
+ mpProgress->show();
+ }
+}
+
+void KIconDialog::slotProgress(int p)
+{
+ mpProgress->setProgress(p);
+ // commented out the following since setProgress already paints ther
+ // progress bar. ->repaint() only makes it flicker
+ //mpProgress->repaint();
+}
+
+void KIconDialog::slotFinished()
+{
+ mpProgress->hide();
+}
+
+class KIconButton::KIconButtonPrivate
+{
+ public:
+ KIconButtonPrivate() {
+ m_bStrictIconSize = false;
+ iconSize = 0; // let KIconLoader choose the default
+ }
+ ~KIconButtonPrivate() {}
+ bool m_bStrictIconSize;
+ int iconSize;
+};
+
+
+/*
+ * KIconButton: A "choose icon" pushbutton.
+ */
+
+KIconButton::KIconButton(TQWidget *parent, const char *name)
+ : TQPushButton(parent, name)
+{
+ init( TDEGlobal::iconLoader() );
+}
+
+KIconButton::KIconButton(KIconLoader *loader,
+ TQWidget *parent, const char *name)
+ : TQPushButton(parent, name)
+{
+ init( loader );
+}
+
+void KIconButton::init( KIconLoader *loader )
+{
+ d = new KIconButtonPrivate;
+ mGroup = KIcon::Desktop;
+ mContext = KIcon::Application;
+ mbUser = false;
+
+ mpLoader = loader;
+ mpDialog = 0L;
+ connect(this, TQT_SIGNAL(clicked()), TQT_SLOT(slotChangeIcon()));
+}
+
+KIconButton::~KIconButton()
+{
+ delete mpDialog;
+ delete d;
+}
+
+void KIconButton::setStrictIconSize(bool b)
+{
+ d->m_bStrictIconSize=b;
+}
+
+bool KIconButton::strictIconSize() const
+{
+ return d->m_bStrictIconSize;
+}
+
+void KIconButton::setIconSize( int size )
+{
+ d->iconSize = size;
+}
+
+int KIconButton::iconSize() const
+{
+ return d->iconSize;
+}
+
+void KIconButton::setIconType(KIcon::Group group, KIcon::Context context, bool user)
+{
+ mGroup = group;
+ mContext = context;
+ mbUser = user;
+}
+
+void KIconButton::setIcon(const TQString& icon)
+{
+ mIcon = icon;
+ setIconSet(mpLoader->loadIconSet(mIcon, mGroup, d->iconSize));
+
+ if (!mpDialog)
+ {
+ mpDialog = new KIconDialog(mpLoader, this);
+ connect(mpDialog, TQT_SIGNAL(newIconName(const TQString&)), TQT_SLOT(newIconName(const TQString&)));
+ }
+
+ if ( mbUser )
+ mpDialog->setCustomLocation( TQFileInfo( mpLoader->iconPath(mIcon, mGroup, true) ).dirPath( true ) );
+}
+
+void KIconButton::resetIcon()
+{
+ mIcon = TQString::null;
+ setIconSet(TQIconSet());
+}
+
+void KIconButton::slotChangeIcon()
+{
+ if (!mpDialog)
+ {
+ mpDialog = new KIconDialog(mpLoader, this);
+ connect(mpDialog, TQT_SIGNAL(newIconName(const TQString&)), TQT_SLOT(newIconName(const TQString&)));
+ }
+
+ mpDialog->setup( mGroup, mContext, d->m_bStrictIconSize, d->iconSize, mbUser );
+ mpDialog->showDialog();
+}
+
+void KIconButton::newIconName(const TQString& name)
+{
+ if (name.isEmpty())
+ return;
+
+ TQIconSet iconset = mpLoader->loadIconSet(name, mGroup, d->iconSize);
+ setIconSet(iconset);
+ mIcon = name;
+
+ if ( mbUser )
+ mpDialog->setCustomLocation( TQFileInfo( mpLoader->iconPath(mIcon, mGroup, true) ).dirPath( true ) );
+
+ emit iconChanged(name);
+}
+
+void KIconCanvas::virtual_hook( int id, void* data )
+{ KIconView::virtual_hook( id, data ); }
+
+void KIconDialog::virtual_hook( int id, void* data )
+{ KDialogBase::virtual_hook( id, data ); }
+
+#include "kicondialog.moc"
diff --git a/tdeio/tdefile/kicondialog.h b/tdeio/tdefile/kicondialog.h
new file mode 100644
index 000000000..d7cb48f1c
--- /dev/null
+++ b/tdeio/tdefile/kicondialog.h
@@ -0,0 +1,350 @@
+/* vi: ts=8 sts=4 sw=4
+ *
+ * This file is part of the KDE project, module tdefile.
+ * Copyright (C) 2000 Geert Jansen <jansen@kde.org>
+ * (C) 2000 Kurt Granroth <granroth@kde.org>
+ * (C) 1997 Christoph Neerfeld <chris@kde.org>
+ * (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
+ *
+ * This is free software; it comes under the GNU Library General
+ * Public License, version 2. See the file "COPYING.LIB" for the
+ * exact licensing terms.
+ */
+
+#ifndef __KIconDialog_h__
+#define __KIconDialog_h__
+
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqpushbutton.h>
+
+#include <kicontheme.h>
+#include <kdialogbase.h>
+#include <kiconview.h>
+
+class TQComboBox;
+class TQTimer;
+class TQKeyEvent;
+class TQRadioButton;
+class KProgress;
+class KIconLoader;
+
+/**
+ * Icon canvas for KIconDialog.
+ */
+class TDEIO_EXPORT KIconCanvas: public KIconView
+{
+ Q_OBJECT
+
+public:
+ KIconCanvas(TQWidget *parent=0L, const char *name=0L);
+ ~KIconCanvas();
+
+ /**
+ * Load icons into the canvas.
+ */
+ void loadFiles(const TQStringList& files);
+
+ /**
+ * Returns the current icon.
+ */
+ TQString getCurrent() const;
+
+public slots:
+ void stopLoading();
+
+signals:
+ /**
+ * Emitted when the current icon has changed.
+ */
+ void nameChanged(TQString);
+ /* KDE 4: Make it const TQString & */
+
+ void startLoading(int);
+ void progress(int);
+ void finished();
+
+private slots:
+ void slotLoadFiles();
+ void slotCurrentChanged(TQIconViewItem *item);
+
+private:
+ TQStringList mFiles;
+ TQTimer *mpTimer;
+ KIconLoader *mpLoader; // unused
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+
+private:
+ class KIconCanvasPrivate;
+ KIconCanvasPrivate *d;
+};
+
+
+/**
+ * Dialog for interactive selection of icons. Use the function
+ * getIcon() let the user select an icon.
+ *
+ * @short An icon selection dialog.
+ */
+class TDEIO_EXPORT KIconDialog: public KDialogBase
+{
+ Q_OBJECT
+
+public:
+ /**
+ * Constructs an icon selection dialog using the global iconloader.
+ */
+ KIconDialog(TQWidget *parent=0L, const char *name=0L);
+ /**
+ * Constructs an icon selection dialog using a specific iconloader.
+ */
+ KIconDialog(KIconLoader *loader, TQWidget *parent=0,
+ const char *name=0);
+ /**
+ * Destructs the dialog.
+ */
+ ~KIconDialog();
+
+ /**
+ * Sets a strict icon size policy for allowed icons. When true,
+ * only icons of the specified group's size in getIcon() are shown.
+ * When false, icons not available at the desired group's size will
+ * also be selectable.
+ */
+ void setStrictIconSize(bool b);
+ /**
+ * Returns true if a strict icon size policy is set.
+ */
+ bool strictIconSize() const;
+ /**
+ * sets a custom icon directory
+ * @since 3.1
+ */
+ void setCustomLocation( const TQString& location );
+
+ /**
+ * Sets the size of the icons to be shown / selected.
+ * @see KIcon::StdSizes
+ * @see iconSize
+ */
+ void setIconSize(int size);
+
+ /**
+ * Returns the iconsize set via setIconSize() or 0, if the default
+ * iconsize will be used.
+ */
+ int iconSize() const;
+
+#ifndef KDE_NO_COMPAT
+ /**
+ * @deprecated in KDE 3.0, use the static method getIcon instead.
+ */
+ TQString selectIcon(KIcon::Group group=KIcon::Desktop, KIcon::Context
+ context=KIcon::Application, bool user=false);
+#endif
+
+ /**
+ * Allows you to set the same parameters as in the class method
+ * getIcon().
+ */
+ void setup( KIcon::Group group,
+ KIcon::Context context = KIcon::Application,
+ bool strictIconSize = false, int iconSize = 0,
+ bool user = false );
+
+ /**
+ * Allows you to set the same parameters as in the class method
+ * getIcon(), as well as two additional parameters to lock
+ * the choice between system and user dirs and to lock the custom user
+ * dir itself.
+ *
+ * @since 3.3
+ */
+
+ void setup( KIcon::Group group, KIcon::Context context,
+ bool strictIconSize, int iconSize, bool user, bool lockUser,
+ bool lockCustomDir );
+
+ /**
+ * exec()utes this modal dialog and returns the name of the selected icon,
+ * or TQString::null if the dialog was aborted.
+ * @returns the name of the icon, suitable for loading with KIconLoader.
+ * @see getIcon
+ */
+ TQString openDialog();
+
+ /**
+ * show()es this dialog and emits a newIcon(const TQString&) signal when
+ * successful. TQString::null will be emitted if the dialog was aborted.
+ */
+ void showDialog();
+
+ /**
+ * Pops up the dialog an lets the user select an icon.
+ *
+ * @param group The icon group this icon is intended for. Providing the
+ * group shows the icons in the dialog with the same appearance as when
+ * used outside the dialog.
+ * @param context The initial icon context. Initially, the icons having
+ * this context are shown in the dialog. The user can change this.
+ * @param strictIconSize When true, only icons of the specified group's size
+ * are shown, otherwise icon not available in the desired group's size
+ * will also be selectable.
+ * @param iconSize the size of the icons -- the default of the icongroup
+ * if set to 0
+ * @param user Begin with the "user icons" instead of "system icons".
+ * @param parent The parent widget of the dialog.
+ * @param caption The caption to use for the dialog.
+ * @return The name of the icon, suitable for loading with KIconLoader.
+ * @version New in 3.0
+ */
+ static TQString getIcon(KIcon::Group group=KIcon::Desktop,
+ KIcon::Context context=KIcon::Application,
+ bool strictIconSize=false, int iconSize = 0,
+ bool user=false, TQWidget *parent=0,
+ const TQString &caption=TQString::null);
+
+signals:
+ void newIconName(const TQString&);
+
+protected slots:
+ void slotOk();
+
+private slots:
+ void slotButtonClicked(int);
+ void slotContext(int);
+ void slotStartLoading(int);
+ void slotProgress(int);
+ void slotFinished();
+ void slotAcceptIcons();
+private:
+ void init();
+ void showIcons();
+ void setContext( KIcon::Context context );
+
+ int mGroupOrSize;
+ KIcon::Context mContext;
+ int mType;
+
+ TQStringList mFileList;
+ TQComboBox *mpCombo;
+ TQPushButton *mpBrowseBut;
+ TQRadioButton *mpRb1, *mpRb2;
+ KProgress *mpProgress;
+ KIconLoader *mpLoader;
+ KIconCanvas *mpCanvas;
+ int mNumContext;
+ KIcon::Context mContextMap[ 12 ]; // must match KIcon::Context size, code has assert
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KIconDialogPrivate;
+ KIconDialogPrivate *d;
+};
+
+
+/**
+ * A pushbutton for choosing an icon. Pressing on the button will open a
+ * KIconDialog for the user to select an icon. The current icon will be
+ * displayed on the button.
+ *
+ * @see KIconDialog
+ * @short A push button that allows selection of an icon.
+ */
+class TDEIO_EXPORT KIconButton: public TQPushButton
+{
+ Q_OBJECT
+ TQ_PROPERTY( TQString icon READ icon WRITE setIcon RESET resetIcon )
+ TQ_PROPERTY( int iconSize READ iconSize WRITE setIconSize)
+ TQ_PROPERTY( bool strictIconSize READ strictIconSize WRITE setStrictIconSize )
+
+public:
+ /**
+ * Constructs a KIconButton using the global iconloader.
+ */
+ KIconButton(TQWidget *parent=0L, const char *name=0L);
+
+ /**
+ * Constructs a KIconButton using a specific KIconLoader.
+ */
+ KIconButton(KIconLoader *loader, TQWidget *parent, const char *name=0L);
+ /**
+ * Destructs the button.
+ */
+ ~KIconButton();
+
+ /**
+ * Sets a strict icon size policy for allowed icons. When true,
+ * only icons of the specified group's size in setIconType are allowed,
+ * and only icons of that size will be shown in the icon dialog.
+ */
+ void setStrictIconSize(bool b);
+ /**
+ * Returns true if a strict icon size policy is set.
+ */
+ bool strictIconSize() const;
+
+ /**
+ * Sets the icon group and context. Use KIcon::NoGroup if you want to
+ * allow icons for any group in the given context.
+ */
+ void setIconType(KIcon::Group group, KIcon::Context context, bool user=false);
+
+ /**
+ * Sets the button's initial icon.
+ */
+ void setIcon(const TQString& icon);
+
+ /**
+ * Resets the icon (reverts to an empty button).
+ */
+ void resetIcon();
+
+ /**
+ * Returns the name of the selected icon.
+ */
+ TQString icon() const { return mIcon; }
+
+ /**
+ * Sets the size of the icon to be shown / selected.
+ * @see KIcon::StdSizes
+ * @see iconSize
+ */
+ void setIconSize( int size );
+
+ /**
+ * Returns the iconsize set via setIconSize() or 0, if the default
+ * iconsize will be used.
+ */
+ int iconSize() const;
+
+signals:
+ /**
+ * Emitted when the icon has changed.
+ */
+ void iconChanged(TQString icon);
+ /* KDE 4: Make it const TQString & */
+
+private slots:
+ void slotChangeIcon();
+ void newIconName(const TQString& name);
+
+private:
+ void init( KIconLoader *loader );
+
+ bool mbUser;
+ KIcon::Group mGroup;
+ KIcon::Context mContext;
+
+ TQString mIcon;
+ KIconDialog *mpDialog;
+ KIconLoader *mpLoader;
+ class KIconButtonPrivate;
+ KIconButtonPrivate *d;
+};
+
+
+#endif // __KIconDialog_h__
diff --git a/tdeio/tdefile/kimagefilepreview.cpp b/tdeio/tdefile/kimagefilepreview.cpp
new file mode 100644
index 000000000..f499f4580
--- /dev/null
+++ b/tdeio/tdefile/kimagefilepreview.cpp
@@ -0,0 +1,187 @@
+/*
+ * This file is part of the KDE project
+ * Copyright (C) 2001 Martin R. Jones <mjones@kde.org>
+ * 2001 Carsten Pfeiffer <pfeiffer@kde.org>
+ *
+ * You can Freely distribute this program under the GNU Library General Public
+ * License. See the file "COPYING" for the exact licensing terms.
+ */
+
+#include <tqlayout.h>
+#include <tqlabel.h>
+#include <tqcombobox.h>
+#include <tqcheckbox.h>
+#include <tqwhatsthis.h>
+#include <tqtimer.h>
+
+#include <kapplication.h>
+#include <tdeconfig.h>
+#include <kglobal.h>
+#include <kiconloader.h>
+#include <kpushbutton.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <tdefiledialog.h>
+#include <tdefileitem.h>
+#include <tdeio/previewjob.h>
+
+#include "kimagefilepreview.h"
+#include "config-tdefile.h"
+
+/**** KImageFilePreview ****/
+
+KImageFilePreview::KImageFilePreview( TQWidget *parent )
+ : KPreviewWidgetBase( parent ),
+ m_job( 0L )
+{
+ TDEConfig *config = TDEGlobal::config();
+ TDEConfigGroupSaver cs( config, ConfigGroup );
+ autoMode = config->readBoolEntry( "Automatic Preview", true );
+
+ TQVBoxLayout *vb = new TQVBoxLayout( this, 0, KDialog::spacingHint() );
+
+ imageLabel = new TQLabel( this );
+ imageLabel->setFrameStyle( TQFrame::NoFrame );
+ imageLabel->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
+ imageLabel->setSizePolicy( TQSizePolicy( TQSizePolicy::Expanding, TQSizePolicy::Expanding) );
+ vb->addWidget( imageLabel );
+
+ TQHBoxLayout *hb = new TQHBoxLayout( 0 );
+ vb->addLayout( hb );
+
+ autoPreview = new TQCheckBox( i18n("&Automatic preview"), this );
+ autoPreview->setChecked( autoMode );
+ hb->addWidget( autoPreview );
+ connect( autoPreview, TQT_SIGNAL(toggled(bool)), TQT_SLOT(toggleAuto(bool)) );
+
+ previewButton = new KPushButton( SmallIconSet("thumbnail"), i18n("&Preview"), this );
+ hb->addWidget( previewButton );
+ connect( previewButton, TQT_SIGNAL(clicked()), TQT_SLOT(showPreview()) );
+
+ timer = new TQTimer( this );
+ connect( timer, TQT_SIGNAL(timeout()), TQT_SLOT(showPreview()) );
+
+ setSupportedMimeTypes( TDEIO::PreviewJob::supportedMimeTypes() );
+}
+
+KImageFilePreview::~KImageFilePreview()
+{
+ if ( m_job )
+ m_job->kill();
+
+ TDEConfig *config = TDEGlobal::config();
+ TDEConfigGroupSaver cs( config, ConfigGroup );
+ config->writeEntry( "Automatic Preview", autoPreview->isChecked() );
+}
+
+void KImageFilePreview::showPreview()
+{
+ // Pass a copy since clearPreview() will clear currentURL
+ KURL url = currentURL;
+ showPreview( url, true );
+}
+
+// called via KPreviewWidgetBase interface
+void KImageFilePreview::showPreview( const KURL& url )
+{
+ showPreview( url, false );
+}
+
+void KImageFilePreview::showPreview( const KURL &url, bool force )
+{
+ if ( !url.isValid() ) {
+ clearPreview();
+ return;
+ }
+
+ if ( url != currentURL || force )
+ {
+ clearPreview();
+ currentURL = url;
+
+ if ( autoMode || force )
+ {
+ int w = imageLabel->contentsRect().width() - 4;
+ int h = imageLabel->contentsRect().height() - 4;
+
+ m_job = createJob( url, w, h );
+ if ( force ) // explicitly requested previews shall always be generated!
+ m_job->setIgnoreMaximumSize( true );
+
+ connect( m_job, TQT_SIGNAL( result( TDEIO::Job * )),
+ this, TQT_SLOT( slotResult( TDEIO::Job * )));
+ connect( m_job, TQT_SIGNAL( gotPreview( const KFileItem*,
+ const TQPixmap& )),
+ TQT_SLOT( gotPreview( const KFileItem*, const TQPixmap& ) ));
+
+ connect( m_job, TQT_SIGNAL( failed( const KFileItem* )),
+ this, TQT_SLOT( slotFailed( const KFileItem* ) ));
+ }
+ }
+}
+
+void KImageFilePreview::toggleAuto( bool a )
+{
+ autoMode = a;
+ if ( autoMode )
+ {
+ // Pass a copy since clearPreview() will clear currentURL
+ KURL url = currentURL;
+ showPreview( url, true );
+ }
+}
+
+void KImageFilePreview::resizeEvent( TQResizeEvent * )
+{
+ timer->start( 100, true ); // forces a new preview
+}
+
+TQSize KImageFilePreview::sizeHint() const
+{
+ return TQSize( 20, 200 ); // otherwise it ends up huge???
+}
+
+TDEIO::PreviewJob * KImageFilePreview::createJob( const KURL& url, int w, int h )
+{
+ KURL::List urls;
+ urls.append( url );
+ return TDEIO::filePreview( urls, w, h, 0, 0, true, false );
+}
+
+void KImageFilePreview::gotPreview( const KFileItem* item, const TQPixmap& pm )
+{
+ if ( item->url() == currentURL ) // should always be the case
+ imageLabel->setPixmap( pm );
+}
+
+void KImageFilePreview::slotFailed( const KFileItem* item )
+{
+ if ( item->isDir() )
+ imageLabel->clear();
+ else if ( item->url() == currentURL ) // should always be the case
+ imageLabel->setPixmap( SmallIcon( "file_broken", KIcon::SizeLarge,
+ KIcon::DisabledState ));
+}
+
+void KImageFilePreview::slotResult( TDEIO::Job *job )
+{
+ if ( job == m_job )
+ m_job = 0L;
+}
+
+void KImageFilePreview::clearPreview()
+{
+ if ( m_job ) {
+ m_job->kill();
+ m_job = 0L;
+ }
+
+ imageLabel->clear();
+ currentURL = KURL();
+}
+
+void KImageFilePreview::virtual_hook( int id, void* data )
+{ KPreviewWidgetBase::virtual_hook( id, data ); }
+
+#include "kimagefilepreview.moc"
diff --git a/kio/kfile/kimagefilepreview.h b/tdeio/tdefile/kimagefilepreview.h
index 0604e08f0..0604e08f0 100644
--- a/kio/kfile/kimagefilepreview.h
+++ b/tdeio/tdefile/kimagefilepreview.h
diff --git a/tdeio/tdefile/kmetaprops.cpp b/tdeio/tdefile/kmetaprops.cpp
new file mode 100644
index 000000000..ce6201177
--- /dev/null
+++ b/tdeio/tdefile/kmetaprops.cpp
@@ -0,0 +1,268 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001,2002 Rolf Magnus <ramagnus@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+ $Id$
+ */
+
+#include "kmetaprops.h"
+
+#include <kdebug.h>
+#include <tdefilemetainfowidget.h>
+#include <tdefilemetainfo.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <klocale.h>
+#include <kprotocolinfo.h>
+
+#include <tqvalidator.h>
+#include <tqlayout.h>
+#include <tqlabel.h>
+#include <tqfileinfo.h>
+#include <tqdatetime.h>
+#include <tqstylesheet.h>
+#include <tqvgroupbox.h>
+
+#undef Bool
+
+class MetaPropsScrollView : public TQScrollView
+{
+public:
+ MetaPropsScrollView(TQWidget* parent = 0, const char* name = 0)
+ : TQScrollView(parent, name)
+ {
+ setFrameStyle(TQFrame::NoFrame);
+ m_frame = new TQFrame(viewport(), "MetaPropsScrollView::m_frame");
+ m_frame->setFrameStyle(TQFrame::NoFrame);
+ addChild(m_frame, 0, 0);
+ };
+
+ TQFrame* frame() {return m_frame;};
+
+protected:
+ virtual void viewportResizeEvent(TQResizeEvent* ev)
+ {
+ TQScrollView::viewportResizeEvent(ev);
+ m_frame->resize( kMax(m_frame->sizeHint().width(), ev->size().width()),
+ kMax(m_frame->sizeHint().height(), ev->size().height()));
+ };
+
+private:
+ TQFrame* m_frame;
+};
+
+class KFileMetaPropsPlugin::KFileMetaPropsPluginPrivate
+{
+public:
+ KFileMetaPropsPluginPrivate() {}
+ ~KFileMetaPropsPluginPrivate() {}
+
+ TQFrame* m_frame;
+ TQGridLayout* m_framelayout;
+ KFileMetaInfo m_info;
+// TQPushButton* m_add;
+ TQPtrList<KFileMetaInfoWidget> m_editWidgets;
+};
+
+KFileMetaPropsPlugin::KFileMetaPropsPlugin(KPropertiesDialog* props)
+ : KPropsDlgPlugin(props)
+{
+ d = new KFileMetaPropsPluginPrivate;
+
+ KFileItem * fileitem = properties->item();
+ kdDebug(250) << "KFileMetaPropsPlugin constructor" << endl;
+
+ d->m_info = fileitem->metaInfo();
+ if (!d->m_info.isValid())
+ {
+ d->m_info = KFileMetaInfo(properties->kurl().path(-1));
+ fileitem->setMetaInfo(d->m_info);
+ }
+
+ if ( properties->items().count() > 1 )
+ {
+ // not yet supported
+ // we should allow setting values for a list of files. Itt makes sense
+ // in some cases, like the album of a list of mp3s
+ return;
+ }
+
+ createLayout();
+
+ setDirty(true);
+}
+
+void KFileMetaPropsPlugin::createLayout()
+{
+ TQFileInfo file_info(properties->item()->url().path());
+
+ kdDebug(250) << "KFileMetaPropsPlugin::createLayout" << endl;
+
+ // is there any valid and non-empty info at all?
+ if ( !d->m_info.isValid() || (d->m_info.preferredKeys()).isEmpty() )
+ return;
+
+ // now get a list of groups
+ KFileMetaInfoProvider* prov = KFileMetaInfoProvider::self();
+ TQStringList groupList = d->m_info.preferredGroups();
+
+ const KFileMimeTypeInfo* mtinfo = prov->mimeTypeInfo(d->m_info.mimeType());
+ if (!mtinfo)
+ {
+ kdDebug(7034) << "no mimetype info there\n";
+ return;
+ }
+
+ // let the dialog create the page frame
+ TQFrame* topframe = properties->addPage(i18n("&Meta Info"));
+ topframe->setFrameStyle(TQFrame::NoFrame);
+ TQVBoxLayout* tmp = new TQVBoxLayout(topframe);
+
+ // create a scroll view in the page
+ MetaPropsScrollView* view = new MetaPropsScrollView(topframe);
+
+ tmp->addWidget(view);
+
+ d->m_frame = view->frame();
+
+ TQVBoxLayout *toplayout = new TQVBoxLayout(d->m_frame);
+ toplayout->setSpacing(KDialog::spacingHint());
+
+ for (TQStringList::Iterator git=groupList.begin();
+ git!=groupList.end(); ++git)
+ {
+ kdDebug(7033) << *git << endl;
+
+ TQStringList itemList = d->m_info.group(*git).preferredKeys();
+ if (itemList.isEmpty())
+ continue;
+
+ TQGroupBox *groupBox = new TQGroupBox(2, Qt::Horizontal,
+ TQStyleSheet::escape(mtinfo->groupInfo(*git)->translatedName()),
+ d->m_frame);
+
+ toplayout->addWidget(groupBox);
+
+ TQValueList<KFileMetaInfoItem> readItems;
+ TQValueList<KFileMetaInfoItem> editItems;
+
+ for (TQStringList::Iterator iit = itemList.begin();
+ iit!=itemList.end(); ++iit)
+ {
+ KFileMetaInfoItem item = d->m_info[*git][*iit];
+ if ( !item.isValid() ) continue;
+
+ bool editable = file_info.isWritable() && item.isEditable();
+
+ if (editable)
+ editItems.append( item );
+ else
+ readItems.append( item );
+ }
+
+ KFileMetaInfoWidget* w = 0L;
+ // then first add the editable items to the layout
+ for (TQValueList<KFileMetaInfoItem>::Iterator iit= editItems.begin();
+ iit!=editItems.end(); ++iit)
+ {
+ TQLabel* l = new TQLabel((*iit).translatedKey() + ":", groupBox);
+ l->setAlignment( AlignAuto | AlignTop | ExpandTabs );
+ TQValidator* val = mtinfo->createValidator(*git, (*iit).key());
+ if (!val) kdDebug(7033) << "didn't get a validator for " << *git << "/" << (*iit).key() << endl;
+ w = new KFileMetaInfoWidget(*iit, val, groupBox);
+ d->m_editWidgets.append( w );
+ connect(w, TQT_SIGNAL(valueChanged(const TQVariant&)), this, TQT_SIGNAL(changed()));
+ }
+
+ // and then the read only items
+ for (TQValueList<KFileMetaInfoItem>::Iterator iit= readItems.begin();
+ iit!=readItems.end(); ++iit)
+ {
+ TQLabel* l = new TQLabel((*iit).translatedKey() + ":", groupBox);
+ l->setAlignment( AlignAuto | AlignTop | ExpandTabs );
+ (new KFileMetaInfoWidget(*iit, KFileMetaInfoWidget::ReadOnly, 0L, groupBox));
+ }
+ }
+
+ toplayout->addStretch(1);
+
+ // the add key (disabled until fully implemented)
+/* d->m_add = new TQPushButton(i18n("&Add"), topframe);
+ d->m_add->setSizePolicy(TQSizePolicy(TQSizePolicy::Fixed,
+ TQSizePolicy::Fixed));
+ connect(d->m_add, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotAdd()));
+ tmp->addWidget(d->m_add);
+
+ // if nothing can be added, deactivate it
+ if ( !d->m_info.supportsVariableKeys() )
+ {
+ // if supportedKeys() does contain anything not in preferredKeys,
+ // we have something addable
+
+ TQStringList sk = d->m_info.supportedKeys();
+ d->m_add->setEnabled(false);
+ for (TQStringList::Iterator it = sk.begin(); it!=sk.end(); ++it)
+ {
+ if ( l.find(*it)==l.end() )
+ {
+ d->m_add->setEnabled(true);
+ kdDebug(250) << "**first addable key is " << (*it).latin1() << "**" <<endl;
+ break;
+ }
+ kdDebug(250) << "**already existing key is " << (*it).latin1() << "**" <<endl;
+ }
+ } */
+}
+
+/*void KFileMetaPropsPlugin::slotAdd()
+{
+ // add a lineedit for the name
+
+
+
+ // insert the item in the list
+
+}*/
+
+KFileMetaPropsPlugin::~KFileMetaPropsPlugin()
+{
+ delete d;
+}
+
+bool KFileMetaPropsPlugin::supports( KFileItemList _items )
+{
+#ifdef _GNUC
+#warning TODO: Add support for more than one item
+#endif
+ if (KExecPropsPlugin::supports(_items) || KURLPropsPlugin::supports(_items))
+ return false; // Having both is redundant.
+
+ bool metaDataEnabled = TDEGlobalSettings::showFilePreview(_items.first()->url());
+ return _items.count() == 1 && metaDataEnabled;
+}
+
+void KFileMetaPropsPlugin::applyChanges()
+{
+ kdDebug(250) << "applying changes" << endl;
+ // insert the fields that changed into the info object
+
+ TQPtrListIterator<KFileMetaInfoWidget> it( d->m_editWidgets );
+ KFileMetaInfoWidget* w;
+ for (; (w = it.current()); ++it) w->apply();
+ d->m_info.applyChanges(properties->kurl().path());
+}
+
+#include "kmetaprops.moc"
diff --git a/kio/kfile/kmetaprops.h b/tdeio/tdefile/kmetaprops.h
index c842499dd..c842499dd 100644
--- a/kio/kfile/kmetaprops.h
+++ b/tdeio/tdefile/kmetaprops.h
diff --git a/tdeio/tdefile/knotifydialog.cpp b/tdeio/tdefile/knotifydialog.cpp
new file mode 100644
index 000000000..a9639ae3d
--- /dev/null
+++ b/tdeio/tdefile/knotifydialog.cpp
@@ -0,0 +1,1191 @@
+/*
+ Copyright (C) 2000,2002 Carsten Pfeiffer <pfeiffer@kde.org>
+ Copyright (C) 2002 Neil Stevens <neil@qualityassistant.com>
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation;
+
+ 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 Library General Public License
+ along with this library, If not, write to the Free Software Foundation,
+ Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include <dcopclient.h>
+
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kaudioplayer.h>
+#include <kcombobox.h>
+#include <tdeconfig.h>
+#include <kcursor.h>
+#include <kdebug.h>
+#include <tdefiledialog.h>
+#include <kiconloader.h>
+#include <kicontheme.h>
+#include <klineedit.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <knotifyclient.h>
+#include <knotifydialog.h>
+#include <kstandarddirs.h>
+#include <kurlrequester.h>
+#include <tdeio/netaccess.h>
+
+#include <tqcheckbox.h>
+#include <tqgroupbox.h>
+#include <tqheader.h>
+#include <tqlabel.h>
+#include <tqlistview.h>
+#include <tqlayout.h>
+#include <tqptrlist.h>
+#include <tqpushbutton.h>
+#include <tqstring.h>
+#include <tqtooltip.h>
+#include <tqtimer.h>
+#include <tqvbox.h>
+#include <tqwhatsthis.h>
+
+using namespace KNotify;
+
+enum
+{
+ COL_EXECUTE = 0,
+ COL_STDERR = 1,
+ COL_MESSAGE = 2,
+ COL_LOGFILE = 3,
+ COL_SOUND = 4,
+ COL_TASKBAR = 5,
+ COL_EVENT = 6
+};
+
+//
+// I don't feel like subclassing KComboBox and find ways to insert that into
+// the .ui file...
+//
+namespace KNotify
+{
+ class SelectionCombo
+ {
+ public:
+ //
+ // Mind the order in fill() and type()
+ //
+ static void fill( KComboBox *combo )
+ {
+ combo->insertItem( i18n("Sounds") );
+ combo->insertItem( i18n("Logging") );
+ combo->insertItem( i18n("Program Execution") );
+ combo->insertItem( i18n("Message Windows") );
+ combo->insertItem( i18n("Passive Windows") );
+ combo->insertItem( i18n("Standard Error Output") );
+ combo->insertItem( i18n("Taskbar") );
+ }
+
+ static int type( KComboBox *combo )
+ {
+ switch( combo->currentItem() )
+ {
+ case 0:
+ return KNotifyClient::Sound;
+ case 1:
+ return KNotifyClient::Logfile;
+ case 2:
+ return KNotifyClient::Execute;
+ case 3:
+ return KNotifyClient::Messagebox;
+ case 4:
+ return KNotifyClient::PassivePopup;
+ case 5:
+ return KNotifyClient::Stderr;
+ case 6:
+ return KNotifyClient::Taskbar;
+ }
+
+ return KNotifyClient::None;
+ }
+ };
+
+ // Needed for displaying tooltips in the listview's QHeader
+ class KNotifyToolTip : public TQToolTip
+ {
+ public:
+ KNotifyToolTip( TQHeader *header )
+ : TQToolTip( header )
+ {
+ m_tips[COL_EXECUTE] = i18n("Execute a program");
+ m_tips[COL_STDERR] = i18n("Print to Standard error output");
+ m_tips[COL_MESSAGE] = i18n("Display a messagebox");
+ m_tips[COL_LOGFILE] = i18n("Log to a file");
+ m_tips[COL_SOUND] = i18n("Play a sound");
+ m_tips[COL_TASKBAR] = i18n("Flash the taskbar entry");
+ }
+ virtual ~KNotifyToolTip() {}
+
+ protected:
+ virtual void maybeTip ( const TQPoint& p )
+ {
+ TQHeader *header = static_cast<TQHeader*>( parentWidget() );
+ int section = 0;
+
+ if ( header->orientation() == Qt::Horizontal )
+ section= header->sectionAt( p.x() );
+ else
+ section= header->sectionAt( p.y() );
+
+ if ( ( section < 0 ) || ( static_cast<uint>( section ) >= (sizeof(m_tips) / sizeof(TQString)) ) )
+ return;
+
+ tip( header->sectionRect( section ), m_tips[section] );
+ }
+
+ private:
+ TQString m_tips[6];
+ };
+
+}
+
+
+int KNotifyDialog::configure( TQWidget *parent, const char *name,
+ const TDEAboutData *aboutData )
+{
+ KNotifyDialog dialog( parent, name, true, aboutData );
+ return dialog.exec();
+}
+
+KNotifyDialog::KNotifyDialog( TQWidget *parent, const char *name, bool modal,
+ const TDEAboutData *aboutData )
+ : KDialogBase(parent, name, modal, i18n("Notification Settings"),
+ Ok | Apply | Cancel | Default, Ok, true )
+{
+ TQVBox *box = makeVBoxMainWidget();
+
+ m_notifyWidget = new KNotifyWidget( box, "knotify widget" );
+
+ if ( aboutData )
+ addApplicationEvents( aboutData->appName() );
+
+ connect( this, TQT_SIGNAL( okClicked() ), m_notifyWidget, TQT_SLOT( save() ));
+ connect( this, TQT_SIGNAL( applyClicked() ), m_notifyWidget, TQT_SLOT( save() ));
+}
+
+KNotifyDialog::~KNotifyDialog()
+{
+}
+
+void KNotifyDialog::addApplicationEvents( const char *appName )
+{
+ addApplicationEvents( TQString::fromUtf8( appName ) +
+ TQString::fromLatin1( "/eventsrc" ) );
+}
+
+void KNotifyDialog::addApplicationEvents( const TQString& path )
+{
+ Application *app = m_notifyWidget->addApplicationEvents( path );
+ if ( app )
+ {
+ m_notifyWidget->addVisibleApp( app );
+ m_notifyWidget->sort();
+ }
+}
+
+void KNotifyDialog::clearApplicationEvents()
+{
+ m_notifyWidget->clear();
+}
+
+void KNotifyDialog::slotDefault()
+{
+ m_notifyWidget->resetDefaults( true ); // ask user
+}
+
+
+//////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////
+
+
+class KNotifyWidget::Private
+{
+public:
+ TQPixmap pixmaps[6];
+ KNotifyToolTip *toolTip;
+};
+
+// simple access to all knotify-handled applications
+KNotifyWidget::KNotifyWidget( TQWidget *parent, const char *name,
+ bool handleAllApps )
+ : KNotifyWidgetBase( parent, name ? name : "KNotifyWidget" )
+{
+ d = new Private;
+
+ m_allApps.setAutoDelete( true );
+
+ if ( !handleAllApps )
+ {
+ m_affectAllApps->hide();
+ m_playerButton->hide();
+ }
+
+ SelectionCombo::fill( m_comboEnable );
+ SelectionCombo::fill( m_comboDisable );
+
+ m_listview->setFullWidth( true );
+ m_listview->setAllColumnsShowFocus( true );
+
+ TQPixmap pexec = SmallIcon("exec");
+ TQPixmap pstderr = SmallIcon("terminal");
+ TQPixmap pmessage = SmallIcon("info");
+ TQPixmap plogfile = SmallIcon("log");
+ TQPixmap psound = SmallIcon("sound");
+ TQPixmap ptaskbar = SmallIcon("kicker");
+
+ d->pixmaps[COL_EXECUTE] = pexec;
+ d->pixmaps[COL_STDERR] = pstderr;
+ d->pixmaps[COL_MESSAGE] = pmessage;
+ d->pixmaps[COL_LOGFILE] = plogfile;
+ d->pixmaps[COL_SOUND] = psound;
+ d->pixmaps[COL_TASKBAR] = ptaskbar;
+
+ int w = KIcon::SizeSmall + 6;
+
+ TQHeader *header = m_listview->header();
+ header->setLabel( COL_EXECUTE, pexec, TQString::null, w );
+ header->setLabel( COL_STDERR, pstderr, TQString::null, w );
+ header->setLabel( COL_MESSAGE, pmessage, TQString::null, w );
+ header->setLabel( COL_LOGFILE, plogfile, TQString::null, w );
+ header->setLabel( COL_SOUND, psound, TQString::null, w );
+ header->setLabel( COL_TASKBAR, ptaskbar, TQString::null, w );
+
+ d->toolTip = new KNotifyToolTip( header );
+
+ m_playButton->setIconSet( SmallIconSet( "player_play" ) );
+ connect( m_playButton, TQT_SIGNAL( clicked() ), TQT_SLOT( playSound() ));
+
+ connect( m_listview, TQT_SIGNAL( currentChanged( TQListViewItem * ) ),
+ TQT_SLOT( slotEventChanged( TQListViewItem * ) ));
+ connect( m_listview, TQT_SIGNAL(clicked( TQListViewItem *, const TQPoint&, int)),
+ TQT_SLOT( slotItemClicked( TQListViewItem *, const TQPoint&, int )));
+
+ connect( m_playSound, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( soundToggled( bool )) );
+ connect( m_logToFile, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( loggingToggled( bool )) );
+ connect( m_execute, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( executeToggled( bool )) );
+ connect( m_messageBox, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( messageBoxChanged() ) );
+ connect( m_passivePopup, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( messageBoxChanged() ) );
+ connect( m_stderr, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( stderrToggled( bool ) ) );
+ connect( m_taskbar, TQT_SIGNAL( toggled( bool )),
+ TQT_SLOT( taskbarToggled( bool ) ) );
+
+ connect( m_soundPath, TQT_SIGNAL( textChanged( const TQString& )),
+ TQT_SLOT( soundFileChanged( const TQString& )));
+ connect( m_logfilePath, TQT_SIGNAL( textChanged( const TQString& )),
+ TQT_SLOT( logfileChanged( const TQString& ) ));
+ connect( m_executePath, TQT_SIGNAL( textChanged( const TQString& )),
+ TQT_SLOT( commandlineChanged( const TQString& ) ));
+
+ connect( m_soundPath, TQT_SIGNAL( openFileDialog( KURLRequester * )),
+ TQT_SLOT( openSoundDialog( KURLRequester * )));
+ connect( m_logfilePath, TQT_SIGNAL( openFileDialog( KURLRequester * )),
+ TQT_SLOT( openLogDialog( KURLRequester * )));
+ connect( m_executePath, TQT_SIGNAL( openFileDialog( KURLRequester * )),
+ TQT_SLOT( openExecDialog( KURLRequester * )));
+
+ connect( m_extension, TQT_SIGNAL( clicked() ),
+ TQT_SLOT( toggleAdvanced()) );
+
+ connect( m_buttonEnable, TQT_SIGNAL( clicked() ), TQT_SLOT( enableAll() ));
+ connect( m_buttonDisable, TQT_SIGNAL( clicked() ), TQT_SLOT( enableAll() ));
+
+ TQString whatsThis = i18n("<qt>You may use the following macros<br>"
+ "in the commandline:<br>"
+ "<b>%e</b>: for the event name,<br>"
+ "<b>%a</b>: for the name of the application that sent the event,<br>"
+ "<b>%s</b>: for the notification message,<br>"
+ "<b>%w</b>: for the numeric window ID where the event originated,<br>"
+ "<b>%i</b>: for the numeric event ID.");
+ TQWhatsThis::add( m_execute, whatsThis );
+ TQWhatsThis::add( m_executePath, whatsThis );
+
+ showAdvanced( false );
+
+ slotEventChanged( 0L ); // disable widgets by default
+}
+
+KNotifyWidget::~KNotifyWidget()
+{
+ delete d->toolTip;
+ delete d;
+}
+
+void KNotifyWidget::toggleAdvanced()
+{
+ showAdvanced( m_logToFile->isHidden() );
+}
+
+void KNotifyWidget::showAdvanced( bool show )
+{
+ if ( show )
+ {
+ m_extension->setText( i18n("Advanced <<") );
+ TQToolTip::add( m_extension, i18n("Hide advanced options") );
+
+ m_logToFile->show();
+ m_logfilePath->show();
+ m_execute->show();
+ m_executePath->show();
+ m_messageBox->show();
+ m_passivePopup->show();
+ m_stderr->show();
+ m_taskbar->show();
+
+ m_passivePopup->setEnabled( m_messageBox->isChecked() );
+ m_actionsBoxLayout->setSpacing( KDialog::spacingHint() );
+ }
+ else
+ {
+ m_extension->setText( i18n("Advanced >>") );
+ TQToolTip::add( m_extension, i18n("Show advanced options") );
+
+ m_logToFile->hide();
+ m_logfilePath->hide();
+ m_execute->hide();
+ m_executePath->hide();
+ m_messageBox->hide();
+ m_passivePopup->hide();
+ m_stderr->hide();
+ m_taskbar->hide();
+
+ m_actionsBoxLayout->setSpacing( 0 );
+ }
+}
+
+Application * KNotifyWidget::addApplicationEvents( const TQString& path )
+{
+ kdDebug() << "**** knotify: adding path: " << path << endl;
+ TQString relativePath = path;
+
+ if ( path.at(0) == '/' && KStandardDirs::exists( path ) )
+ relativePath = makeRelative( path );
+
+ if ( !relativePath.isEmpty() )
+ {
+ Application *app = new Application( relativePath );
+ m_allApps.append( app );
+ return app;
+ }
+
+ return 0L;
+}
+
+void KNotifyWidget::clear()
+{
+ clearVisible();
+ m_allApps.clear();
+}
+
+void KNotifyWidget::clearVisible()
+{
+ m_visibleApps.clear();
+ m_listview->clear();
+ slotEventChanged( 0L ); // disable widgets
+}
+
+void KNotifyWidget::showEvent( TQShowEvent *e )
+{
+ selectItem( m_listview->firstChild() );
+ KNotifyWidgetBase::showEvent( e );
+}
+
+void KNotifyWidget::slotEventChanged( TQListViewItem *item )
+{
+ bool on = (item != 0L);
+
+ m_actionsBox->setEnabled( on );
+ m_controlsBox->setEnabled( on );
+
+ if ( !on )
+ return;
+
+ ListViewItem *lit = static_cast<ListViewItem*>( item );
+ updateWidgets( lit );
+}
+
+void KNotifyWidget::updateWidgets( ListViewItem *item )
+{
+ bool enable;
+ bool checked;
+
+ blockSignals( true ); // don't emit changed() signals
+
+ const Event& event = item->event();
+
+ // sound settings
+ m_playButton->setEnabled( !event.soundfile.isEmpty() );
+ m_soundPath->setURL( event.soundfile );
+ enable = (event.dontShow & KNotifyClient::Sound) == 0;
+ checked = enable && !event.soundfile.isEmpty() &&
+ (event.presentation & KNotifyClient::Sound);
+ m_playSound->setEnabled( enable );
+ m_playSound->setChecked( checked );
+ m_soundPath->setEnabled( checked );
+
+
+ // logfile settings
+ m_logfilePath->setURL( event.logfile );
+ enable = (event.dontShow & KNotifyClient::Logfile) == 0;
+ checked = enable && !event.logfile.isEmpty() &&
+ (event.presentation & KNotifyClient::Logfile);
+ m_logToFile->setEnabled( enable );
+ m_logToFile->setChecked( checked );
+ m_logfilePath->setEnabled( checked );
+
+
+ // execute program settings
+ m_executePath->setURL( event.commandline );
+ enable = (event.dontShow & KNotifyClient::Execute) == 0;
+ checked = enable && !event.commandline.isEmpty() &&
+ (event.presentation & KNotifyClient::Execute);
+ m_execute->setEnabled( enable );
+ m_execute->setChecked( checked );
+ m_executePath->setEnabled( checked );
+
+
+ // other settings
+ m_messageBox->setChecked(event.presentation & (KNotifyClient::Messagebox | KNotifyClient::PassivePopup));
+ enable = (event.dontShow & KNotifyClient::Messagebox) == 0;
+ m_messageBox->setEnabled( enable );
+
+ m_passivePopup->setChecked(event.presentation & KNotifyClient::PassivePopup);
+ enable = (event.dontShow & KNotifyClient::PassivePopup) == 0;
+ m_passivePopup->setEnabled( enable );
+
+ m_stderr->setChecked( event.presentation & KNotifyClient::Stderr );
+ enable = (event.dontShow & KNotifyClient::Stderr) == 0;
+ m_stderr->setEnabled( enable );
+
+ m_taskbar->setChecked(event.presentation & KNotifyClient::Taskbar);
+ enable = (event.dontShow & KNotifyClient::Taskbar) == 0;
+ m_taskbar->setEnabled( enable );
+
+ updatePixmaps( item );
+
+ blockSignals( false );
+}
+
+void KNotifyWidget::updatePixmaps( ListViewItem *item )
+{
+ TQPixmap emptyPix;
+ Event &event = item->event();
+
+ bool doIt = (event.presentation & KNotifyClient::Execute) &&
+ !event.commandline.isEmpty();
+ item->setPixmap( COL_EXECUTE, doIt ? d->pixmaps[COL_EXECUTE] : emptyPix );
+
+ doIt = (event.presentation & KNotifyClient::Sound) &&
+ !event.soundfile.isEmpty();
+ item->setPixmap( COL_SOUND, doIt ? d->pixmaps[COL_SOUND] : emptyPix );
+
+ doIt = (event.presentation & KNotifyClient::Logfile) &&
+ !event.logfile.isEmpty();
+ item->setPixmap( COL_LOGFILE, doIt ? d->pixmaps[COL_LOGFILE] : emptyPix );
+
+ item->setPixmap( COL_MESSAGE,
+ (event.presentation &
+ (KNotifyClient::Messagebox | KNotifyClient::PassivePopup)) ?
+ d->pixmaps[COL_MESSAGE] : emptyPix );
+
+ item->setPixmap( COL_STDERR,
+ (event.presentation & KNotifyClient::Stderr) ?
+ d->pixmaps[COL_STDERR] : emptyPix );
+ item->setPixmap( COL_TASKBAR,
+ (event.presentation & KNotifyClient::Taskbar) ?
+ d->pixmaps[COL_TASKBAR] : emptyPix );
+}
+
+void KNotifyWidget::addVisibleApp( Application *app )
+{
+ if ( !app || (m_visibleApps.findRef( app ) != -1) )
+ return;
+
+ m_visibleApps.append( app );
+ addToView( app->eventList() );
+
+ TQListViewItem *item = m_listview->selectedItem();
+ if ( !item )
+ item = m_listview->firstChild();
+
+ selectItem( item );
+}
+
+void KNotifyWidget::addToView( const EventList& events )
+{
+ ListViewItem *item = 0L;
+
+ EventListIterator it( events );
+
+ for ( ; it.current(); ++it )
+ {
+ Event *event = it.current();
+ item = new ListViewItem( m_listview, event );
+
+ if ( (event->presentation & KNotifyClient::Execute) &&
+ !event->commandline.isEmpty() )
+ item->setPixmap( COL_EXECUTE, d->pixmaps[COL_EXECUTE] );
+ if ( (event->presentation & KNotifyClient::Sound) &&
+ !event->soundfile.isEmpty() )
+ item->setPixmap( COL_SOUND, d->pixmaps[COL_SOUND] );
+ if ( (event->presentation & KNotifyClient::Logfile) &&
+ !event->logfile.isEmpty() )
+ item->setPixmap( COL_LOGFILE, d->pixmaps[COL_LOGFILE] );
+ if ( event->presentation & (KNotifyClient::Messagebox|KNotifyClient::PassivePopup) )
+ item->setPixmap( COL_MESSAGE, d->pixmaps[COL_MESSAGE] );
+ if ( event->presentation & KNotifyClient::Stderr )
+ item->setPixmap( COL_STDERR, d->pixmaps[COL_STDERR] );
+ if ( event->presentation & KNotifyClient::Taskbar )
+ item->setPixmap( COL_TASKBAR, d->pixmaps[COL_TASKBAR] );
+ }
+}
+
+void KNotifyWidget::widgetChanged( TQListViewItem *item,
+ int what, bool on, TQWidget *buddy )
+{
+ if ( signalsBlocked() )
+ return;
+
+ if ( buddy )
+ buddy->setEnabled( on );
+
+ Event &e = static_cast<ListViewItem*>( item )->event();
+ if ( on )
+ {
+ e.presentation |= what;
+ if ( buddy )
+ buddy->setFocus();
+ }
+ else
+ e.presentation &= ~what;
+
+ emit changed( true );
+}
+
+void KNotifyWidget::soundToggled( bool on )
+{
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+ bool doIcon = on && !m_soundPath->url().isEmpty();
+ item->setPixmap( COL_SOUND, doIcon ? d->pixmaps[COL_SOUND] : TQPixmap() );
+ widgetChanged( item, KNotifyClient::Sound, on, m_soundPath );
+}
+
+void KNotifyWidget::loggingToggled( bool on )
+{
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+ bool doIcon = on && !m_logfilePath->url().isEmpty();
+ item->setPixmap(COL_LOGFILE, doIcon ? d->pixmaps[COL_LOGFILE] : TQPixmap());
+ widgetChanged( item, KNotifyClient::Logfile, on, m_logfilePath );
+}
+
+void KNotifyWidget::executeToggled( bool on )
+{
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+ bool doIcon = on && !m_executePath->url().isEmpty();
+ item->setPixmap(COL_EXECUTE, doIcon ? d->pixmaps[COL_EXECUTE] : TQPixmap());
+ widgetChanged( item, KNotifyClient::Execute, on, m_executePath );
+}
+
+void KNotifyWidget::messageBoxChanged()
+{
+ if ( signalsBlocked() )
+ return;
+
+ m_passivePopup->setEnabled( m_messageBox->isChecked() );
+
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+
+ bool on = m_passivePopup->isEnabled();
+ item->setPixmap( COL_MESSAGE, on ? d->pixmaps[COL_MESSAGE] : TQPixmap() );
+
+ Event &e = static_cast<ListViewItem*>( item )->event();
+
+ if ( m_messageBox->isChecked() ) {
+ if ( m_passivePopup->isChecked() ) {
+ e.presentation |= KNotifyClient::PassivePopup;
+ e.presentation &= ~KNotifyClient::Messagebox;
+ }
+ else {
+ e.presentation &= ~KNotifyClient::PassivePopup;
+ e.presentation |= KNotifyClient::Messagebox;
+ }
+ }
+ else {
+ e.presentation &= ~KNotifyClient::Messagebox;
+ e.presentation &= ~KNotifyClient::PassivePopup;
+ }
+
+ emit changed( true );
+}
+
+void KNotifyWidget::stderrToggled( bool on )
+{
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+ item->setPixmap( COL_STDERR, on ? d->pixmaps[COL_STDERR] : TQPixmap() );
+ widgetChanged( item, KNotifyClient::Stderr, on );
+}
+
+void KNotifyWidget::taskbarToggled( bool on )
+{
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+ item->setPixmap( COL_TASKBAR, on ? d->pixmaps[COL_TASKBAR] : TQPixmap() );
+ widgetChanged( item, KNotifyClient::Taskbar, on );
+}
+
+void KNotifyWidget::soundFileChanged( const TQString& text )
+{
+ if ( signalsBlocked() )
+ return;
+
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+
+ m_playButton->setEnabled( !text.isEmpty() );
+
+ currentEvent()->soundfile = text;
+ bool ok = !text.isEmpty() && m_playSound->isChecked();
+ item->setPixmap( COL_SOUND, ok ? d->pixmaps[COL_SOUND] : TQPixmap() );
+
+ emit changed( true );
+}
+
+void KNotifyWidget::logfileChanged( const TQString& text )
+{
+ if ( signalsBlocked() )
+ return;
+
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+
+ currentEvent()->logfile = text;
+ bool ok = !text.isEmpty() && m_logToFile->isChecked();
+ item->setPixmap( COL_LOGFILE, ok ? d->pixmaps[COL_LOGFILE] : TQPixmap() );
+
+ emit changed( true );
+}
+
+void KNotifyWidget::commandlineChanged( const TQString& text )
+{
+ if ( signalsBlocked() )
+ return;
+
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ return;
+
+ currentEvent()->commandline = text;
+ bool ok = !text.isEmpty() && m_execute->isChecked();
+ item->setPixmap( COL_EXECUTE, ok ? d->pixmaps[COL_EXECUTE] : TQPixmap() );
+
+ emit changed( true );
+}
+
+void KNotifyWidget::slotItemClicked( TQListViewItem *item, const TQPoint&,
+ int col )
+{
+ if ( !item || !item->isSelected() )
+ return;
+
+ Event *event = currentEvent();
+ if ( !event )
+ return; // very unlikely, but safety first
+
+ bool doShowAdvanced = false;
+
+ switch( col )
+ {
+ case COL_EXECUTE:
+ m_execute->toggle();
+ m_executePath->setFocus();
+ doShowAdvanced = true;
+ break;
+ case COL_STDERR:
+ m_stderr->toggle();
+ break;
+ case COL_TASKBAR:
+ m_taskbar->toggle();
+ break;
+ case COL_MESSAGE:
+ m_passivePopup->setChecked( true ); // default to passive popups
+ m_messageBox->toggle();
+ break;
+ case COL_LOGFILE:
+ m_logToFile->toggle();
+ m_logfilePath->setFocus();
+ doShowAdvanced = true;
+ break;
+ case COL_SOUND:
+ m_playSound->toggle();
+ break;
+ default: // do nothing
+ break;
+ }
+
+ if ( doShowAdvanced && !m_logToFile->isVisible() )
+ {
+ showAdvanced( true );
+ m_listview->ensureItemVisible( m_listview->currentItem() );
+ }
+}
+
+void KNotifyWidget::sort( bool ascending )
+{
+ m_listview->setSorting( COL_EVENT, ascending );
+ m_listview->sort();
+}
+
+void KNotifyWidget::selectItem( TQListViewItem *item )
+{
+ if ( item )
+ {
+ m_listview->setCurrentItem( item );
+ item->setSelected( true );
+ slotEventChanged( item );
+ }
+}
+
+void KNotifyWidget::resetDefaults( bool ask )
+{
+ if ( ask )
+ {
+ if ( KMessageBox::warningContinueCancel(this,
+ i18n("This will cause the notifications "
+ "to be reset to their defaults."),
+ i18n("Are You Sure?"),
+ i18n("&Reset"))
+ != KMessageBox::Continue)
+ return;
+ }
+
+ reload( true ); // defaults
+ emit changed( true );
+}
+
+void KNotifyWidget::reload( bool revertToDefaults )
+{
+ m_listview->clear();
+ ApplicationListIterator it( m_visibleApps );
+ for ( ; it.current(); ++it )
+ {
+ it.current()->reloadEvents( revertToDefaults );
+ addToView( it.current()->eventList() );
+ }
+
+ m_listview->sort();
+ selectItem( m_listview->firstChild() );
+}
+
+void KNotifyWidget::save()
+{
+ kdDebug() << "save\n";
+
+ ApplicationListIterator it( m_allApps );
+ while ( it.current() )
+ {
+ (*it)->save();
+ ++it;
+ }
+
+ if ( kapp )
+ {
+ if ( !kapp->dcopClient()->isAttached() )
+ kapp->dcopClient()->attach();
+ kapp->dcopClient()->send("knotify", "", "reconfigure()", TQString(""));
+ }
+
+ emit changed( false );
+}
+
+// returns e.g. "twin/eventsrc" from a given path
+// "/opt/trinity/share/apps/twin/eventsrc"
+TQString KNotifyWidget::makeRelative( const TQString& fullPath )
+{
+ int slash = fullPath.findRev( '/' ) - 1;
+ slash = fullPath.findRev( '/', slash );
+
+ if ( slash < 0 )
+ return TQString::null;
+
+ return fullPath.mid( slash+1 );
+}
+
+Event * KNotifyWidget::currentEvent()
+{
+ TQListViewItem *current = m_listview->currentItem();
+ if ( !current )
+ return 0L;
+
+ return &static_cast<ListViewItem*>( current )->event();
+}
+
+void KNotifyWidget::openSoundDialog( KURLRequester *requester )
+{
+ // only need to init this once
+ requester->disconnect( TQT_SIGNAL( openFileDialog( KURLRequester * )),
+ this, TQT_SLOT( openSoundDialog( KURLRequester * )));
+
+ KFileDialog *fileDialog = requester->fileDialog();
+ fileDialog->setCaption( i18n("Select Sound File") );
+ TQStringList filters;
+ filters << "audio/x-wav" << "audio/x-mp3" << "application/ogg"
+ << "audio/x-adpcm";
+ fileDialog->setMimeFilter( filters );
+
+ // find the first "sound"-resource that contains files
+ const Application *app = currentEvent()->application();
+ TQStringList soundDirs =
+ TDEGlobal::dirs()->findDirs("data", app->appName() + "/sounds");
+ soundDirs += TDEGlobal::dirs()->resourceDirs( "sound" );
+
+ if ( !soundDirs.isEmpty() ) {
+ KURL soundURL;
+ TQDir dir;
+ dir.setFilter( TQDir::Files | TQDir::Readable );
+ TQStringList::ConstIterator it = soundDirs.begin();
+ while ( it != soundDirs.end() ) {
+ dir = *it;
+ if ( dir.isReadable() && dir.count() > 2 ) {
+ soundURL.setPath( *it );
+ fileDialog->setURL( soundURL );
+ break;
+ }
+ ++it;
+ }
+ }
+}
+
+void KNotifyWidget::openLogDialog( KURLRequester *requester )
+{
+ // only need to init this once
+ requester->disconnect( TQT_SIGNAL( openFileDialog( KURLRequester * )),
+ this, TQT_SLOT( openLogDialog( KURLRequester * )));
+
+ KFileDialog *fileDialog = requester->fileDialog();
+ fileDialog->setCaption( i18n("Select Log File") );
+ TQStringList filters;
+ filters << "text/x-log" << "text/plain";
+ fileDialog->setMimeFilter( filters );
+}
+
+void KNotifyWidget::openExecDialog( KURLRequester *requester )
+{
+ // only need to init this once
+ requester->disconnect( TQT_SIGNAL( openFileDialog( KURLRequester * )),
+ this, TQT_SLOT( openExecDialog( KURLRequester * )));
+
+
+ KFileDialog *fileDialog = requester->fileDialog();
+ fileDialog->setCaption( i18n("Select File to Execute") );
+ TQStringList filters;
+ filters << "application/x-executable" << "application/x-shellscript"
+ << "application/x-perl" << "application/x-python";
+ fileDialog->setMimeFilter( filters );
+}
+
+void KNotifyWidget::playSound()
+{
+ TQString soundPath = m_soundPath->url();
+ if (!TDEIO::NetAccess::exists( m_soundPath->url(), true, 0 )) {
+ bool foundSound=false;
+
+ // find the first "sound"-resource that contains files
+ const Application *app = currentEvent()->application();
+ TQStringList soundDirs = TDEGlobal::dirs()->findDirs("data", app->appName() + "/sounds");
+ soundDirs += TDEGlobal::dirs()->resourceDirs( "sound" );
+
+ if ( !soundDirs.isEmpty() ) {
+ TQDir dir;
+ dir.setFilter( TQDir::Files | TQDir::Readable );
+ TQStringList::ConstIterator it = soundDirs.begin();
+ while ( it != soundDirs.end() ) {
+ dir = *it;
+ if ( dir.isReadable() && dir.count() > 2 &&
+ TDEIO::NetAccess::exists( *it + m_soundPath->url(), true, 0 )) {
+ foundSound=true;
+ soundPath = *it + m_soundPath->url();
+ break;
+ }
+ ++it;
+ }
+ }
+ if ( !foundSound ) {
+ KMessageBox::sorry(this, i18n("The specified file does not exist." ));
+ return;
+ }
+ }
+ KAudioPlayer::play( soundPath );
+}
+
+void KNotifyWidget::enableAll()
+{
+ bool enable = (sender() == m_buttonEnable);
+ enableAll( SelectionCombo::type(enable ? m_comboEnable : m_comboDisable),
+ enable );
+}
+
+void KNotifyWidget::enableAll( int what, bool enable )
+{
+ if ( m_listview->childCount() == 0 )
+ return;
+
+ bool affectAll = m_affectAllApps->isChecked(); // multi-apps mode
+
+ ApplicationListIterator appIt( affectAll ? m_allApps : m_visibleApps );
+ for ( ; appIt.current(); ++appIt )
+ {
+ const EventList& events = appIt.current()->eventList();
+ EventListIterator it( events );
+ for ( ; it.current(); ++it )
+ {
+ if ( enable )
+ it.current()->presentation |= what;
+ else
+ it.current()->presentation &= ~what;
+ }
+ }
+
+ // now make the listview reflect the changes
+ TQListViewItemIterator it( m_listview->firstChild() );
+ for ( ; it.current(); ++it )
+ {
+ ListViewItem *item = static_cast<ListViewItem*>( it.current() );
+ updatePixmaps( item );
+ }
+
+ TQListViewItem *item = m_listview->currentItem();
+ if ( !item )
+ item = m_listview->firstChild();
+ selectItem( item );
+
+ emit changed( true );
+}
+
+
+//////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////
+
+
+//
+// path must be "appname/eventsrc", i.e. a relative path
+//
+Application::Application( const TQString &path )
+{
+ TQString config_file = path;
+ config_file[config_file.find('/')] = '.';
+ m_events = 0L;
+ config = new TDEConfig(config_file, false, false);
+ kc = new TDEConfig(path, true, false, "data");
+ kc->setGroup( TQString::fromLatin1("!Global!") );
+ m_icon = kc->readEntry(TQString::fromLatin1("IconName"),
+ TQString::fromLatin1("misc"));
+ m_description = kc->readEntry( TQString::fromLatin1("Comment"),
+ i18n("No description available") );
+
+ int index = path.find( '/' );
+ if ( index >= 0 )
+ m_appname = path.left( index );
+ else
+ kdDebug() << "Cannot determine application name from path: " << path << endl;
+}
+
+Application::~Application()
+{
+ delete config;
+ delete kc;
+ delete m_events;
+}
+
+
+const EventList& Application::eventList()
+{
+ if ( !m_events ) {
+ m_events = new EventList;
+ m_events->setAutoDelete( true );
+ reloadEvents();
+ }
+
+ return *m_events;
+}
+
+
+void Application::save()
+{
+ if ( !m_events )
+ return;
+
+ EventListIterator it( *m_events );
+ Event *e;
+ while ( (e = it.current()) ) {
+ config->setGroup( e->configGroup );
+ config->writeEntry( "presentation", e->presentation );
+ config->writePathEntry( "soundfile", e->soundfile );
+ config->writePathEntry( "logfile", e->logfile );
+ config->writePathEntry( "commandline", e->commandline );
+
+ ++it;
+ }
+ config->sync();
+}
+
+
+void Application::reloadEvents( bool revertToDefaults )
+{
+ if ( m_events )
+ m_events->clear();
+ else
+ {
+ m_events = new EventList;
+ m_events->setAutoDelete( true );
+ }
+
+ Event *e = 0L;
+
+ TQString global = TQString::fromLatin1("!Global!");
+ TQString default_group = TQString::fromLatin1("<default>");
+ TQString name = TQString::fromLatin1("Name");
+ TQString comment = TQString::fromLatin1("Comment");
+
+ TQStringList conflist = kc->groupList();
+ TQStringList::ConstIterator it = conflist.begin();
+
+ while ( it != conflist.end() ) {
+ if ( (*it) != global && (*it) != default_group ) { // event group
+ kc->setGroup( *it );
+
+ e = new Event( this );
+ e->name = kc->readEntry( name );
+ e->description = kc->readEntry( comment );
+ e->dontShow = kc->readNumEntry("nopresentation", 0 );
+ e->configGroup = *it;
+ if ( e->name.isEmpty() && e->description.isEmpty() )
+ delete e;
+ else { // load the event
+ if( !e->name.isEmpty() && e->description.isEmpty() )
+ e->description = e->name;
+ // default to passive popups over plain messageboxes
+ int default_rep = kc->readNumEntry("default_presentation",
+ 0 | KNotifyClient::PassivePopup);
+ TQString default_logfile = kc->readPathEntry("default_logfile");
+ TQString default_soundfile = kc->readPathEntry("default_sound");
+ TQString default_commandline = kc->readPathEntry("default_commandline");
+
+ config->setGroup(*it);
+
+ if ( revertToDefaults )
+ {
+ e->presentation = default_rep;
+ e->logfile = default_logfile;
+ e->soundfile = default_soundfile;
+ e->commandline = default_commandline;
+ }
+
+ else
+ {
+ e->presentation = config->readNumEntry("presentation",
+ default_rep);
+ e->logfile = config->readPathEntry("logfile",
+ default_logfile);
+ e->soundfile = config->readPathEntry("soundfile",
+ default_soundfile);
+ e->commandline = config->readPathEntry("commandline",
+ default_commandline);
+ }
+
+ m_events->append( e );
+ }
+ }
+
+ ++it;
+ }
+
+ return;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+ListViewItem::ListViewItem( TQListView *view, Event *event )
+ : TQListViewItem( view ),
+ m_event( event )
+{
+ setText( COL_EVENT, event->text() );
+}
+
+int ListViewItem::compare ( TQListViewItem * i, int col, bool ascending ) const
+{
+ ListViewItem *item = static_cast<ListViewItem*>( i );
+ int myPres = m_event->presentation;
+ int otherPres = item->event().presentation;
+
+ int action = 0;
+
+ switch ( col )
+ {
+ case COL_EVENT: // use default sorting
+ return TQListViewItem::compare( i, col, ascending );
+
+ case COL_EXECUTE:
+ action = KNotifyClient::Execute;
+ break;
+ case COL_LOGFILE:
+ action = KNotifyClient::Logfile;
+ break;
+ case COL_MESSAGE:
+ action = (KNotifyClient::Messagebox | KNotifyClient::PassivePopup);
+ break;
+ case COL_SOUND:
+ action = KNotifyClient::Sound;
+ break;
+ case COL_STDERR:
+ action = KNotifyClient::Stderr;
+ break;
+ case COL_TASKBAR:
+ action = KNotifyClient::Taskbar;
+ break;
+ }
+
+ if ( (myPres & action) == (otherPres & action) )
+ {
+ // default sorting by event
+ return TQListViewItem::compare( i, COL_EVENT, true );
+ }
+
+ if ( myPres & action )
+ return -1;
+ if ( otherPres & action )
+ return 1;
+
+ return 0;
+}
+
+#include "knotifydialog.moc"
diff --git a/kio/kfile/knotifydialog.h b/tdeio/tdefile/knotifydialog.h
index 9bb3210ea..9bb3210ea 100644
--- a/kio/kfile/knotifydialog.h
+++ b/tdeio/tdefile/knotifydialog.h
diff --git a/kio/kfile/knotifywidgetbase.ui b/tdeio/tdefile/knotifywidgetbase.ui
index d3c3103ff..d3c3103ff 100644
--- a/kio/kfile/knotifywidgetbase.ui
+++ b/tdeio/tdefile/knotifywidgetbase.ui
diff --git a/kio/kfile/kopenwith.cpp b/tdeio/tdefile/kopenwith.cpp
index 691487730..691487730 100644
--- a/kio/kfile/kopenwith.cpp
+++ b/tdeio/tdefile/kopenwith.cpp
diff --git a/kio/kfile/kopenwith.h b/tdeio/tdefile/kopenwith.h
index 90c43ceb1..90c43ceb1 100644
--- a/kio/kfile/kopenwith.h
+++ b/tdeio/tdefile/kopenwith.h
diff --git a/kio/kfile/kopenwith_p.h b/tdeio/tdefile/kopenwith_p.h
index 8231da27d..8231da27d 100644
--- a/kio/kfile/kopenwith_p.h
+++ b/tdeio/tdefile/kopenwith_p.h
diff --git a/tdeio/tdefile/kpreviewprops.cpp b/tdeio/tdefile/kpreviewprops.cpp
new file mode 100644
index 000000000..a053d5627
--- /dev/null
+++ b/tdeio/tdefile/kpreviewprops.cpp
@@ -0,0 +1,89 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2005 Stephan Binner <binner@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+ */
+
+#include "kpreviewprops.h"
+
+#include <tqlayout.h>
+
+#include <tdefilemetapreview.h>
+#include <kglobalsettings.h>
+#include <klocale.h>
+
+class KPreviewPropsPlugin::KPreviewPropsPluginPrivate
+{
+public:
+ KPreviewPropsPluginPrivate() {}
+ ~KPreviewPropsPluginPrivate() {}
+};
+
+KPreviewPropsPlugin::KPreviewPropsPlugin(KPropertiesDialog* props)
+ : KPropsDlgPlugin(props)
+{
+ d = new KPreviewPropsPluginPrivate;
+
+ if (properties->items().count()>1)
+ return;
+
+ createLayout();
+}
+
+void KPreviewPropsPlugin::createLayout()
+{
+ // let the dialog create the page frame
+ TQFrame* topframe = properties->addPage(i18n("P&review"));
+ topframe->setFrameStyle(TQFrame::NoFrame);
+
+ TQVBoxLayout* tmp = new TQVBoxLayout(topframe, 0, 0);
+
+ preview = new KFileMetaPreview(topframe);
+
+ tmp->addWidget(preview) ;
+ connect( properties, TQT_SIGNAL( aboutToShowPage( TQWidget * ) ), TQT_SLOT( aboutToShowPage( TQWidget* ) ) );
+}
+
+KPreviewPropsPlugin::~KPreviewPropsPlugin()
+{
+ delete d;
+}
+
+bool KPreviewPropsPlugin::supports( KFileItemList _items )
+{
+ if ( _items.count() != 1)
+ return false;
+ if( !TDEGlobalSettings::showFilePreview(_items.first()->url()))
+ return false;
+ KMimeType::Ptr mt = KMimeType::findByURL( _items.first()->url() );
+ if ( mt->inherits("inode/directory") || mt->name() == "application/octet-stream" )
+ return false;
+
+ //TODO Copy everything of KFileMetaPreview::previewProviderFor() ?
+
+ return true;
+}
+
+void KPreviewPropsPlugin::aboutToShowPage( TQWidget* widget )
+{
+ if ( TQT_TQOBJECT(widget) != TQT_TQOBJECT(preview->parent()) )
+ return;
+
+ disconnect( properties, TQT_SIGNAL( aboutToShowPage( TQWidget * ) ), this, TQT_SLOT( aboutToShowPage( TQWidget* ) ) );
+ preview->showPreview(properties->item()->url());
+}
+
+#include "kpreviewprops.moc"
diff --git a/kio/kfile/kpreviewprops.h b/tdeio/tdefile/kpreviewprops.h
index d934af22a..d934af22a 100644
--- a/kio/kfile/kpreviewprops.h
+++ b/tdeio/tdefile/kpreviewprops.h
diff --git a/kio/kfile/kpreviewwidgetbase.cpp b/tdeio/tdefile/kpreviewwidgetbase.cpp
index 979da919e..979da919e 100644
--- a/kio/kfile/kpreviewwidgetbase.cpp
+++ b/tdeio/tdefile/kpreviewwidgetbase.cpp
diff --git a/kio/kfile/kpreviewwidgetbase.h b/tdeio/tdefile/kpreviewwidgetbase.h
index 3597070ee..3597070ee 100644
--- a/kio/kfile/kpreviewwidgetbase.h
+++ b/tdeio/tdefile/kpreviewwidgetbase.h
diff --git a/kio/kfile/kpropertiesdesktopadvbase.ui b/tdeio/tdefile/kpropertiesdesktopadvbase.ui
index fd8e39781..fd8e39781 100644
--- a/kio/kfile/kpropertiesdesktopadvbase.ui
+++ b/tdeio/tdefile/kpropertiesdesktopadvbase.ui
diff --git a/kio/kfile/kpropertiesdesktopbase.ui b/tdeio/tdefile/kpropertiesdesktopbase.ui
index a0894dc70..a0894dc70 100644
--- a/kio/kfile/kpropertiesdesktopbase.ui
+++ b/tdeio/tdefile/kpropertiesdesktopbase.ui
diff --git a/tdeio/tdefile/kpropertiesdialog.cpp b/tdeio/tdefile/kpropertiesdialog.cpp
new file mode 100644
index 000000000..a76fdc336
--- /dev/null
+++ b/tdeio/tdefile/kpropertiesdialog.cpp
@@ -0,0 +1,4170 @@
+/* This file is part of the KDE project
+
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+ Copyright (c) 1999, 2000 Preston Brown <pbrown@kde.org>
+ Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
+ Copyright (c) 2000 David Faure <faure@kde.org>
+ Copyright (c) 2003 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+/*
+ * kpropertiesdialog.cpp
+ * View/Edit Properties of files, locally or remotely
+ *
+ * some FilePermissionsPropsPlugin-changes by
+ * Henner Zeller <zeller@think.de>
+ * some layout management by
+ * Bertrand Leconte <B.Leconte@mail.dotcom.fr>
+ * the rest of the layout management, bug fixes, adaptation to libtdeio,
+ * template feature by
+ * David Faure <faure@kde.org>
+ * More layout, cleanups, and fixes by
+ * Preston Brown <pbrown@kde.org>
+ * Plugin capability, cleanups and port to KDialogBase by
+ * Simon Hausmann <hausmann@kde.org>
+ * KDesktopPropsPlugin by
+ * Waldo Bastian <bastian@kde.org>
+ */
+
+#include <config.h>
+extern "C" {
+#include <pwd.h>
+#include <grp.h>
+#include <time.h>
+#include <sys/types.h>
+}
+#include <unistd.h>
+#include <errno.h>
+#include <assert.h>
+#include <algorithm>
+#include <functional>
+
+#include <tqfile.h>
+#include <tqdir.h>
+#include <tqlabel.h>
+#include <tqpushbutton.h>
+#include <tqcheckbox.h>
+#include <tqstrlist.h>
+#include <tqstringlist.h>
+#include <tqtextstream.h>
+#include <tqpainter.h>
+#include <tqlayout.h>
+#include <tqcombobox.h>
+#include <tqgroupbox.h>
+#include <tqwhatsthis.h>
+#include <tqtooltip.h>
+#include <tqstyle.h>
+#include <tqprogressbar.h>
+#include <tqvbox.h>
+#include <tqvaluevector.h>
+
+#ifdef USE_POSIX_ACL
+extern "C" {
+#include <sys/param.h>
+#ifdef HAVE_SYS_MOUNT_H
+#include <sys/mount.h>
+#endif
+#ifdef HAVE_SYS_XATTR_H
+#include <sys/xattr.h>
+#endif
+}
+#endif
+
+#include <kapplication.h>
+#include <kdialog.h>
+#include <kdirsize.h>
+#include <kdirwatch.h>
+#include <kdirnotify_stub.h>
+#include <kdiskfreesp.h>
+#include <kdebug.h>
+#include <kdesktopfile.h>
+#include <kicondialog.h>
+#include <kurl.h>
+#include <kurlrequester.h>
+#include <klocale.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <kstandarddirs.h>
+#include <tdeio/job.h>
+#include <tdeio/chmodjob.h>
+#include <tdeio/renamedlg.h>
+#include <tdeio/netaccess.h>
+#include <tdeio/kservicetypefactory.h>
+#include <tdefiledialog.h>
+#include <kmimetype.h>
+#include <kmountpoint.h>
+#include <kiconloader.h>
+#include <kmessagebox.h>
+#include <kservice.h>
+#include <kcompletion.h>
+#include <klineedit.h>
+#include <kseparator.h>
+#include <ksqueezedtextlabel.h>
+#include <klibloader.h>
+#include <ktrader.h>
+#include <tdeparts/componentfactory.h>
+#include <kmetaprops.h>
+#include <kpreviewprops.h>
+#include <kprocess.h>
+#include <krun.h>
+#include <klistview.h>
+#include <kacl.h>
+#include "tdefilesharedlg.h"
+
+#include "kpropertiesdesktopbase.h"
+#include "kpropertiesdesktopadvbase.h"
+#include "kpropertiesmimetypebase.h"
+#ifdef USE_POSIX_ACL
+#include "kacleditwidget.h"
+#endif
+
+#include "kpropertiesdialog.h"
+
+#ifdef Q_WS_WIN
+# include <win32_utils.h>
+#endif
+
+static TQString nameFromFileName(TQString nameStr)
+{
+ if ( nameStr.endsWith(".desktop") )
+ nameStr.truncate( nameStr.length() - 8 );
+ if ( nameStr.endsWith(".kdelnk") )
+ nameStr.truncate( nameStr.length() - 7 );
+ // Make it human-readable (%2F => '/', ...)
+ nameStr = TDEIO::decodeFileName( nameStr );
+ return nameStr;
+}
+
+mode_t KFilePermissionsPropsPlugin::fperm[3][4] = {
+ {S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID},
+ {S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID},
+ {S_IROTH, S_IWOTH, S_IXOTH, S_ISVTX}
+ };
+
+class KPropertiesDialog::KPropertiesDialogPrivate
+{
+public:
+ KPropertiesDialogPrivate()
+ {
+ m_aborted = false;
+ fileSharePage = 0;
+ }
+ ~KPropertiesDialogPrivate()
+ {
+ }
+ bool m_aborted:1;
+ TQWidget* fileSharePage;
+};
+
+KPropertiesDialog::KPropertiesDialog (KFileItem* item,
+ TQWidget* parent, const char* name,
+ bool modal, bool autoShow)
+ : KDialogBase (KDialogBase::Tabbed, i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(item->url().fileName())),
+ KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
+ parent, name, modal)
+{
+ d = new KPropertiesDialogPrivate;
+ assert( item );
+ m_items.append( new KFileItem(*item) ); // deep copy
+
+ m_singleUrl = item->url();
+ assert(!m_singleUrl.isEmpty());
+
+ init (modal, autoShow);
+}
+
+KPropertiesDialog::KPropertiesDialog (const TQString& title,
+ TQWidget* parent, const char* name, bool modal)
+ : KDialogBase (KDialogBase::Tabbed, i18n ("Properties for %1").arg(title),
+ KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
+ parent, name, modal)
+{
+ d = new KPropertiesDialogPrivate;
+
+ init (modal, false);
+}
+
+KPropertiesDialog::KPropertiesDialog (KFileItemList _items,
+ TQWidget* parent, const char* name,
+ bool modal, bool autoShow)
+ : KDialogBase (KDialogBase::Tabbed,
+ // TODO: replace <never used> with "Properties for 1 item". It's very confusing how it has to be translated otherwise
+ // (empty translation before the "\n" is not allowed by msgfmt...)
+ _items.count()>1 ? i18n( "<never used>","Properties for %n Selected Items",_items.count()) :
+ i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_items.first()->url().fileName())),
+ KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
+ parent, name, modal)
+{
+ d = new KPropertiesDialogPrivate;
+
+ assert( !_items.isEmpty() );
+ m_singleUrl = _items.first()->url();
+ assert(!m_singleUrl.isEmpty());
+
+ KFileItemListIterator it ( _items );
+ // Deep copy
+ for ( ; it.current(); ++it )
+ m_items.append( new KFileItem( **it ) );
+
+ init (modal, autoShow);
+}
+
+#ifndef KDE_NO_COMPAT
+KPropertiesDialog::KPropertiesDialog (const KURL& _url, mode_t /* _mode is now unused */,
+ TQWidget* parent, const char* name,
+ bool modal, bool autoShow)
+ : KDialogBase (KDialogBase::Tabbed,
+ i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_url.fileName())),
+ KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
+ parent, name, modal),
+ m_singleUrl( _url )
+{
+ d = new KPropertiesDialogPrivate;
+
+ TDEIO::UDSEntry entry;
+
+ TDEIO::NetAccess::stat(_url, entry, parent);
+
+ m_items.append( new KFileItem( entry, _url ) );
+ init (modal, autoShow);
+}
+#endif
+
+KPropertiesDialog::KPropertiesDialog (const KURL& _url,
+ TQWidget* parent, const char* name,
+ bool modal, bool autoShow)
+ : KDialogBase (KDialogBase::Tabbed,
+ i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_url.fileName())),
+ KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
+ parent, name, modal),
+ m_singleUrl( _url )
+{
+ d = new KPropertiesDialogPrivate;
+
+ TDEIO::UDSEntry entry;
+
+ TDEIO::NetAccess::stat(_url, entry, parent);
+
+ m_items.append( new KFileItem( entry, _url ) );
+ init (modal, autoShow);
+}
+
+KPropertiesDialog::KPropertiesDialog (const KURL& _tempUrl, const KURL& _currentDir,
+ const TQString& _defaultName,
+ TQWidget* parent, const char* name,
+ bool modal, bool autoShow)
+ : KDialogBase (KDialogBase::Tabbed,
+ i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_tempUrl.fileName())),
+ KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
+ parent, name, modal),
+
+ m_singleUrl( _tempUrl ),
+ m_defaultName( _defaultName ),
+ m_currentDir( _currentDir )
+{
+ d = new KPropertiesDialogPrivate;
+
+ assert(!m_singleUrl.isEmpty());
+
+ // Create the KFileItem for the _template_ file, in order to read from it.
+ m_items.append( new KFileItem( KFileItem::Unknown, KFileItem::Unknown, m_singleUrl ) );
+ init (modal, autoShow);
+}
+
+bool KPropertiesDialog::showDialog(KFileItem* item, TQWidget* parent,
+ const char* name, bool modal)
+{
+#ifdef Q_WS_WIN
+ TQString localPath = item->localPath();
+ if (!localPath.isEmpty())
+ return showWin32FilePropertyDialog(localPath);
+#endif
+ new KPropertiesDialog(item, parent, name, modal);
+ return true;
+}
+
+bool KPropertiesDialog::showDialog(const KURL& _url, TQWidget* parent,
+ const char* name, bool modal)
+{
+#ifdef Q_WS_WIN
+ if (_url.isLocalFile())
+ return showWin32FilePropertyDialog( _url.path() );
+#endif
+ new KPropertiesDialog(_url, parent, name, modal);
+ return true;
+}
+
+bool KPropertiesDialog::showDialog(const KFileItemList& _items, TQWidget* parent,
+ const char* name, bool modal)
+{
+ if (_items.count()==1)
+ return KPropertiesDialog::showDialog(_items.getFirst(), parent, name, modal);
+ new KPropertiesDialog(_items, parent, name, modal);
+ return true;
+}
+
+void KPropertiesDialog::init (bool modal, bool autoShow)
+{
+ m_pageList.setAutoDelete( true );
+ m_items.setAutoDelete( true );
+
+ insertPages();
+
+ if (autoShow)
+ {
+ if (!modal)
+ show();
+ else
+ exec();
+ }
+}
+
+void KPropertiesDialog::showFileSharingPage()
+{
+ if (d->fileSharePage) {
+ showPage( pageIndex( d->fileSharePage));
+ }
+}
+
+void KPropertiesDialog::setFileSharingPage(TQWidget* page) {
+ d->fileSharePage = page;
+}
+
+
+void KPropertiesDialog::setFileNameReadOnly( bool ro )
+{
+ KPropsDlgPlugin *it;
+
+ for ( it=m_pageList.first(); it != 0L; it=m_pageList.next() )
+ {
+ KFilePropsPlugin* plugin = dynamic_cast<KFilePropsPlugin*>(it);
+ if ( plugin ) {
+ plugin->setFileNameReadOnly( ro );
+ break;
+ }
+ }
+}
+
+void KPropertiesDialog::slotStatResult( TDEIO::Job * )
+{
+}
+
+KPropertiesDialog::~KPropertiesDialog()
+{
+ m_pageList.clear();
+ delete d;
+}
+
+void KPropertiesDialog::insertPlugin (KPropsDlgPlugin* plugin)
+{
+ connect (plugin, TQT_SIGNAL (changed ()),
+ plugin, TQT_SLOT (setDirty ()));
+
+ m_pageList.append (plugin);
+}
+
+bool KPropertiesDialog::canDisplay( KFileItemList _items )
+{
+ // TODO: cache the result of those calls. Currently we parse .desktop files far too many times
+ return KFilePropsPlugin::supports( _items ) ||
+ KFilePermissionsPropsPlugin::supports( _items ) ||
+ KDesktopPropsPlugin::supports( _items ) ||
+ KBindingPropsPlugin::supports( _items ) ||
+ KURLPropsPlugin::supports( _items ) ||
+ KDevicePropsPlugin::supports( _items ) ||
+ KFileMetaPropsPlugin::supports( _items ) ||
+ KPreviewPropsPlugin::supports( _items );
+}
+
+void KPropertiesDialog::slotOk()
+{
+ KPropsDlgPlugin *page;
+ d->m_aborted = false;
+
+ KFilePropsPlugin * filePropsPlugin = 0L;
+ if ( m_pageList.first()->isA("KFilePropsPlugin") )
+ filePropsPlugin = static_cast<KFilePropsPlugin *>(m_pageList.first());
+
+ // If any page is dirty, then set the main one (KFilePropsPlugin) as
+ // dirty too. This is what makes it possible to save changes to a global
+ // desktop file into a local one. In other cases, it doesn't hurt.
+ for ( page = m_pageList.first(); page != 0L; page = m_pageList.next() )
+ if ( page->isDirty() && filePropsPlugin )
+ {
+ filePropsPlugin->setDirty();
+ break;
+ }
+
+ // Apply the changes in the _normal_ order of the tabs now
+ // This is because in case of renaming a file, KFilePropsPlugin will call
+ // KPropertiesDialog::rename, so other tab will be ok with whatever order
+ // BUT for file copied from templates, we need to do the renaming first !
+ for ( page = m_pageList.first(); page != 0L && !d->m_aborted; page = m_pageList.next() )
+ if ( page->isDirty() )
+ {
+ kdDebug( 250 ) << "applying changes for " << page->className() << endl;
+ page->applyChanges();
+ // applyChanges may change d->m_aborted.
+ }
+ else
+ kdDebug( 250 ) << "skipping page " << page->className() << endl;
+
+ if ( !d->m_aborted && filePropsPlugin )
+ filePropsPlugin->postApplyChanges();
+
+ if ( !d->m_aborted )
+ {
+ emit applied();
+ emit propertiesClosed();
+ deleteLater();
+ accept();
+ } // else, keep dialog open for user to fix the problem.
+}
+
+void KPropertiesDialog::slotCancel()
+{
+ emit canceled();
+ emit propertiesClosed();
+
+ deleteLater();
+ done( Rejected );
+}
+
+void KPropertiesDialog::insertPages()
+{
+ if (m_items.isEmpty())
+ return;
+
+ if ( KFilePropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KFilePropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( KFilePermissionsPropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KFilePermissionsPropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( KDesktopPropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KDesktopPropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( KBindingPropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KBindingPropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( KURLPropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KURLPropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( KDevicePropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KDevicePropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( KFileMetaPropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KFileMetaPropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( KPreviewPropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KPreviewPropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ if ( kapp->authorizeKAction("sharefile") &&
+ KFileSharePropsPlugin::supports( m_items ) )
+ {
+ KPropsDlgPlugin *p = new KFileSharePropsPlugin( this );
+ insertPlugin (p);
+ }
+
+ //plugins
+
+ if ( m_items.count() != 1 )
+ return;
+
+ KFileItem *item = m_items.first();
+ TQString mimetype = item->mimetype();
+
+ if ( mimetype.isEmpty() )
+ return;
+
+ TQString query = TQString::fromLatin1(
+ "('KPropsDlg/Plugin' in ServiceTypes) and "
+ "((not exist [X-TDE-Protocol]) or "
+ " ([X-TDE-Protocol] == '%1' ) )" ).arg(item->url().protocol());
+
+ kdDebug( 250 ) << "trader query: " << query << endl;
+ KTrader::OfferList offers = KTrader::self()->query( mimetype, query );
+ KTrader::OfferList::ConstIterator it = offers.begin();
+ KTrader::OfferList::ConstIterator end = offers.end();
+ for (; it != end; ++it )
+ {
+ KPropsDlgPlugin *plugin = KParts::ComponentFactory
+ ::createInstanceFromLibrary<KPropsDlgPlugin>( (*it)->library().local8Bit().data(),
+ TQT_TQOBJECT(this),
+ (*it)->name().latin1() );
+ if ( !plugin )
+ continue;
+
+ insertPlugin( plugin );
+ }
+}
+
+void KPropertiesDialog::updateUrl( const KURL& _newUrl )
+{
+ Q_ASSERT( m_items.count() == 1 );
+ kdDebug(250) << "KPropertiesDialog::updateUrl (pre)" << _newUrl.url() << endl;
+ KURL newUrl = _newUrl;
+ emit saveAs(m_singleUrl, newUrl);
+ kdDebug(250) << "KPropertiesDialog::updateUrl (post)" << newUrl.url() << endl;
+
+ m_singleUrl = newUrl;
+ m_items.first()->setURL( newUrl );
+ assert(!m_singleUrl.isEmpty());
+ // If we have an Desktop page, set it dirty, so that a full file is saved locally
+ // Same for a URL page (because of the Name= hack)
+ for ( TQPtrListIterator<KPropsDlgPlugin> it(m_pageList); it.current(); ++it )
+ if ( it.current()->isA("KExecPropsPlugin") || // KDE4 remove me
+ it.current()->isA("KURLPropsPlugin") ||
+ it.current()->isA("KDesktopPropsPlugin"))
+ {
+ //kdDebug(250) << "Setting page dirty" << endl;
+ it.current()->setDirty();
+ break;
+ }
+}
+
+void KPropertiesDialog::rename( const TQString& _name )
+{
+ Q_ASSERT( m_items.count() == 1 );
+ kdDebug(250) << "KPropertiesDialog::rename " << _name << endl;
+ KURL newUrl;
+ // if we're creating from a template : use currentdir
+ if ( !m_currentDir.isEmpty() )
+ {
+ newUrl = m_currentDir;
+ newUrl.addPath( _name );
+ }
+ else
+ {
+ TQString tmpurl = m_singleUrl.url();
+ if ( tmpurl.at(tmpurl.length() - 1) == '/')
+ // It's a directory, so strip the trailing slash first
+ tmpurl.truncate( tmpurl.length() - 1);
+ newUrl = tmpurl;
+ newUrl.setFileName( _name );
+ }
+ updateUrl( newUrl );
+}
+
+void KPropertiesDialog::abortApplying()
+{
+ d->m_aborted = true;
+}
+
+class KPropsDlgPlugin::KPropsDlgPluginPrivate
+{
+public:
+ KPropsDlgPluginPrivate()
+ {
+ }
+ ~KPropsDlgPluginPrivate()
+ {
+ }
+
+ bool m_bDirty;
+};
+
+KPropsDlgPlugin::KPropsDlgPlugin( KPropertiesDialog *_props )
+: TQObject( _props, 0L )
+{
+ d = new KPropsDlgPluginPrivate;
+ properties = _props;
+ fontHeight = 2*properties->fontMetrics().height();
+ d->m_bDirty = false;
+}
+
+KPropsDlgPlugin::~KPropsDlgPlugin()
+{
+ delete d;
+}
+
+bool KPropsDlgPlugin::isDesktopFile( KFileItem * _item )
+{
+ // only local files
+ bool isLocal;
+ KURL url = _item->mostLocalURL( isLocal );
+ if ( !isLocal )
+ return false;
+
+ // only regular files
+ if ( !S_ISREG( _item->mode() ) )
+ return false;
+
+ TQString t( url.path() );
+
+ // only if readable
+ FILE *f = fopen( TQFile::encodeName(t), "r" );
+ if ( f == 0L )
+ return false;
+ fclose(f);
+
+ // return true if desktop file
+ return ( (_item->mimetype() == "application/x-desktop")
+ || (_item->mimetype() == "media/builtin-mydocuments")
+ || (_item->mimetype() == "media/builtin-mycomputer")
+ || (_item->mimetype() == "media/builtin-mynetworkplaces")
+ || (_item->mimetype() == "media/builtin-printers")
+ || (_item->mimetype() == "media/builtin-trash")
+ || (_item->mimetype() == "media/builtin-webbrowser") );
+}
+
+void KPropsDlgPlugin::setDirty( bool b )
+{
+ d->m_bDirty = b;
+}
+
+void KPropsDlgPlugin::setDirty()
+{
+ d->m_bDirty = true;
+}
+
+bool KPropsDlgPlugin::isDirty() const
+{
+ return d->m_bDirty;
+}
+
+void KPropsDlgPlugin::applyChanges()
+{
+ kdWarning(250) << "applyChanges() not implemented in page !" << endl;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+class KFilePropsPlugin::KFilePropsPluginPrivate
+{
+public:
+ KFilePropsPluginPrivate()
+ {
+ dirSizeJob = 0L;
+ dirSizeUpdateTimer = 0L;
+ m_lined = 0;
+ m_freeSpaceLabel = 0;
+ }
+ ~KFilePropsPluginPrivate()
+ {
+ if ( dirSizeJob )
+ dirSizeJob->kill();
+ }
+
+ KDirSize * dirSizeJob;
+ TQTimer *dirSizeUpdateTimer;
+ TQFrame *m_frame;
+ bool bMultiple;
+ bool bIconChanged;
+ bool bKDesktopMode;
+ bool bDesktopFile;
+ TQLabel *m_freeSpaceLabel;
+ TQString mimeType;
+ TQString oldFileName;
+ KLineEdit* m_lined;
+};
+
+KFilePropsPlugin::KFilePropsPlugin( KPropertiesDialog *_props )
+ : KPropsDlgPlugin( _props )
+{
+ d = new KFilePropsPluginPrivate;
+ d->bMultiple = (properties->items().count() > 1);
+ d->bIconChanged = false;
+ d->bKDesktopMode = (TQCString(tqApp->name()) == "kdesktop"); // nasty heh?
+ d->bDesktopFile = KDesktopPropsPlugin::supports(properties->items());
+ kdDebug(250) << "KFilePropsPlugin::KFilePropsPlugin bMultiple=" << d->bMultiple << endl;
+
+ // We set this data from the first item, and we'll
+ // check that the other items match against it, resetting when not.
+ bool isLocal;
+ KFileItem * item = properties->item();
+ KURL url = item->mostLocalURL( isLocal );
+ bool isReallyLocal = item->url().isLocalFile();
+ bool bDesktopFile = isDesktopFile(item);
+ kdDebug() << "url=" << url << " bDesktopFile=" << bDesktopFile << " isLocal=" << isLocal << " isReallyLocal=" << isReallyLocal << endl;
+ mode_t mode = item->mode();
+ bool hasDirs = item->isDir() && !item->isLink();
+ bool hasRoot = url.path() == TQString::fromLatin1("/");
+ TQString iconStr = KMimeType::iconForURL(url, mode);
+ TQString directory = properties->kurl().directory();
+ TQString protocol = properties->kurl().protocol();
+ TQString mimeComment = item->mimeComment();
+ d->mimeType = item->mimetype();
+ bool hasTotalSize;
+ TDEIO::filesize_t totalSize = item->size(hasTotalSize);
+ TQString magicMimeComment;
+ if ( isLocal ) {
+ KMimeType::Ptr magicMimeType = KMimeType::findByFileContent( url.path() );
+ if ( magicMimeType->name() != KMimeType::defaultMimeType() )
+ magicMimeComment = magicMimeType->comment();
+ }
+
+ // Those things only apply to 'single file' mode
+ TQString filename = TQString::null;
+ bool isTrash = false;
+ bool isDevice = false;
+ m_bFromTemplate = false;
+
+ // And those only to 'multiple' mode
+ uint iDirCount = hasDirs ? 1 : 0;
+ uint iFileCount = 1-iDirCount;
+
+ d->m_frame = properties->addPage (i18n("&General"));
+
+ TQVBoxLayout *vbl = new TQVBoxLayout( d->m_frame, 0,
+ KDialog::spacingHint(), "vbl");
+ TQGridLayout *grid = new TQGridLayout(0, 3); // unknown rows
+ grid->setColStretch(0, 0);
+ grid->setColStretch(1, 0);
+ grid->setColStretch(2, 1);
+ grid->addColSpacing(1, KDialog::spacingHint());
+ vbl->addLayout(TQT_TQLAYOUT(grid));
+ int curRow = 0;
+
+ if ( !d->bMultiple )
+ {
+ TQString path;
+ if ( !m_bFromTemplate ) {
+ isTrash = ( properties->kurl().protocol().find( "trash", 0, false)==0 );
+ if ( properties->kurl().protocol().find("device", 0, false)==0)
+ isDevice = true;
+ // Extract the full name, but without file: for local files
+ if ( isReallyLocal )
+ path = properties->kurl().path();
+ else
+ path = properties->kurl().prettyURL();
+ } else {
+ path = properties->currentDir().path(1) + properties->defaultName();
+ directory = properties->currentDir().prettyURL();
+ }
+
+ if (KExecPropsPlugin::supports(properties->items()) || // KDE4 remove me
+ d->bDesktopFile ||
+ KBindingPropsPlugin::supports(properties->items())) {
+ determineRelativePath( path );
+ }
+
+ // Extract the file name only
+ filename = properties->defaultName();
+ if ( filename.isEmpty() ) { // no template
+ filename = item->name(); // this gives support for UDS_NAME, e.g. for kio_trash or kio_system
+ } else {
+ m_bFromTemplate = true;
+ setDirty(); // to enforce that the copy happens
+ }
+ d->oldFileName = filename;
+
+ // Make it human-readable
+ filename = nameFromFileName( filename );
+
+ if ( d->bKDesktopMode && d->bDesktopFile ) {
+ KDesktopFile config( url.path(), true /* readonly */ );
+ if ( config.hasKey( "Name" ) ) {
+ filename = config.readName();
+ }
+ }
+
+ oldName = filename;
+ }
+ else
+ {
+ // Multiple items: see what they have in common
+ KFileItemList items = properties->items();
+ KFileItemListIterator it( items );
+ for ( ++it /*no need to check the first one again*/ ; it.current(); ++it )
+ {
+ KURL url = (*it)->url();
+ kdDebug(250) << "KFilePropsPlugin::KFilePropsPlugin " << url.prettyURL() << endl;
+ // The list of things we check here should match the variables defined
+ // at the beginning of this method.
+ if ( url.isLocalFile() != isLocal )
+ isLocal = false; // not all local
+ if ( bDesktopFile && isDesktopFile(*it) != bDesktopFile )
+ bDesktopFile = false; // not all desktop files
+ if ( (*it)->mode() != mode )
+ mode = (mode_t)0;
+ if ( KMimeType::iconForURL(url, mode) != iconStr )
+ iconStr = "tdemultiple";
+ if ( url.directory() != directory )
+ directory = TQString::null;
+ if ( url.protocol() != protocol )
+ protocol = TQString::null;
+ if ( !mimeComment.isNull() && (*it)->mimeComment() != mimeComment )
+ mimeComment = TQString::null;
+ if ( isLocal && !magicMimeComment.isNull() ) {
+ KMimeType::Ptr magicMimeType = KMimeType::findByFileContent( url.path() );
+ if ( magicMimeType->comment() != magicMimeComment )
+ magicMimeComment = TQString::null;
+ }
+
+ if ( url.path() == TQString::fromLatin1("/") )
+ hasRoot = true;
+ if ( (*it)->isDir() && !(*it)->isLink() )
+ {
+ iDirCount++;
+ hasDirs = true;
+ }
+ else
+ {
+ iFileCount++;
+ bool hasSize;
+ totalSize += (*it)->size(hasSize);
+ hasTotalSize = hasTotalSize || hasSize;
+ }
+ }
+ }
+
+ if (!isReallyLocal && !protocol.isEmpty())
+ {
+ directory += ' ';
+ directory += '(';
+ directory += protocol;
+ directory += ')';
+ }
+
+ if ( !isDevice && !isTrash && (bDesktopFile || S_ISDIR(mode)) && !d->bMultiple /*not implemented for multiple*/ )
+ {
+ KIconButton *iconButton = new KIconButton( d->m_frame );
+ int bsize = 66 + 2 * iconButton->style().pixelMetric(TQStyle::PM_ButtonMargin);
+ iconButton->setFixedSize(bsize, bsize);
+ iconButton->setIconSize(48);
+ iconButton->setStrictIconSize(false);
+ // This works for everything except Device icons on unmounted devices
+ // So we have to really open .desktop files
+ TQString iconStr = KMimeType::findByURL( url, mode )->icon( url, isLocal );
+ if ( bDesktopFile && isLocal )
+ {
+ KDesktopFile config( url.path(), true );
+ config.setDesktopGroup();
+ iconStr = config.readEntry( "Icon" );
+ if ( config.hasDeviceType() )
+ iconButton->setIconType( KIcon::Desktop, KIcon::Device );
+ else
+ iconButton->setIconType( KIcon::Desktop, KIcon::Application );
+ } else
+ iconButton->setIconType( KIcon::Desktop, KIcon::Place );
+ iconButton->setIcon(iconStr);
+ iconArea = iconButton;
+ connect( iconButton, TQT_SIGNAL( iconChanged(TQString) ),
+ this, TQT_SLOT( slotIconChanged() ) );
+ } else {
+ TQLabel *iconLabel = new TQLabel( d->m_frame );
+ int bsize = 66 + 2 * iconLabel->style().pixelMetric(TQStyle::PM_ButtonMargin);
+ iconLabel->setFixedSize(bsize, bsize);
+ iconLabel->setPixmap( TDEGlobal::iconLoader()->loadIcon( iconStr, KIcon::Desktop, 48) );
+ iconArea = iconLabel;
+ }
+ grid->addWidget(iconArea, curRow, 0, Qt::AlignLeft);
+
+ if (d->bMultiple || isTrash || isDevice || hasRoot)
+ {
+ TQLabel *lab = new TQLabel(d->m_frame );
+ if ( d->bMultiple )
+ lab->setText( TDEIO::itemsSummaryString( iFileCount + iDirCount, iFileCount, iDirCount, 0, false ) );
+ else
+ lab->setText( filename );
+ nameArea = lab;
+ } else
+ {
+ d->m_lined = new KLineEdit( d->m_frame );
+ d->m_lined->setText(filename);
+ nameArea = d->m_lined;
+ d->m_lined->setFocus();
+
+ // Enhanced rename: Don't highlight the file extension.
+ TQString pattern;
+ KServiceTypeFactory::self()->findFromPattern( filename, &pattern );
+ if (!pattern.isEmpty() && pattern.at(0)=='*' && pattern.find('*',1)==-1)
+ d->m_lined->setSelection(0, filename.length()-pattern.stripWhiteSpace().length()+1);
+ else
+ {
+ int lastDot = filename.findRev('.');
+ if (lastDot > 0)
+ d->m_lined->setSelection(0, lastDot);
+ }
+
+ connect( d->m_lined, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SLOT( nameFileChanged(const TQString & ) ) );
+ }
+
+ grid->addWidget(nameArea, curRow++, 2);
+
+ KSeparator* sep = new KSeparator( KSeparator::HLine, d->m_frame);
+ grid->addMultiCellWidget(sep, curRow, curRow, 0, 2);
+ ++curRow;
+
+ TQLabel *l;
+ if ( !mimeComment.isEmpty() && !isDevice && !isTrash)
+ {
+ l = new TQLabel(i18n("Type:"), d->m_frame );
+
+ grid->addWidget(l, curRow, 0);
+
+ TQHBox *box = new TQHBox(d->m_frame);
+ box->setSpacing(20);
+ l = new TQLabel(mimeComment, box );
+
+#ifdef Q_WS_X11
+ //TODO: wrap for win32 or mac?
+ TQPushButton *button = new TQPushButton(box);
+
+ TQIconSet iconSet = SmallIconSet(TQString::fromLatin1("configure"));
+ TQPixmap pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
+ button->setIconSet( iconSet );
+ button->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
+ if ( d->mimeType == KMimeType::defaultMimeType() )
+ TQToolTip::add(button, i18n("Create new file type"));
+ else
+ TQToolTip::add(button, i18n("Edit file type"));
+
+ connect( button, TQT_SIGNAL( clicked() ), TQT_SLOT( slotEditFileType() ));
+
+ if (!kapp->authorizeKAction("editfiletype"))
+ button->hide();
+#endif
+
+ grid->addWidget(box, curRow++, 2);
+ }
+
+ if ( !magicMimeComment.isEmpty() && magicMimeComment != mimeComment )
+ {
+ l = new TQLabel(i18n("Contents:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ l = new TQLabel(magicMimeComment, d->m_frame );
+ grid->addWidget(l, curRow++, 2);
+ }
+
+ if ( !directory.isEmpty() )
+ {
+ l = new TQLabel( i18n("Location:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ l = new KSqueezedTextLabel( d->m_frame );
+ l->setText( directory );
+ grid->addWidget(l, curRow++, 2);
+ }
+
+ if( hasDirs || hasTotalSize ) {
+ l = new TQLabel(i18n("Size:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ m_sizeLabel = new TQLabel( d->m_frame );
+ grid->addWidget( m_sizeLabel, curRow++, 2 );
+ } else {
+ m_sizeLabel = 0;
+ }
+
+ if ( !hasDirs ) // Only files [and symlinks]
+ {
+ if(hasTotalSize) {
+ m_sizeLabel->setText(TDEIO::convertSizeWithBytes(totalSize));
+ }
+
+ m_sizeDetermineButton = 0L;
+ m_sizeStopButton = 0L;
+ }
+ else // Directory
+ {
+ TQHBoxLayout * sizelay = new TQHBoxLayout(KDialog::spacingHint());
+ grid->addLayout( sizelay, curRow++, 2 );
+
+ // buttons
+ m_sizeDetermineButton = new TQPushButton( i18n("Calculate"), d->m_frame );
+ m_sizeStopButton = new TQPushButton( i18n("Stop"), d->m_frame );
+ connect( m_sizeDetermineButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotSizeDetermine() ) );
+ connect( m_sizeStopButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotSizeStop() ) );
+ sizelay->addWidget(m_sizeDetermineButton, 0);
+ sizelay->addWidget(m_sizeStopButton, 0);
+ sizelay->addStretch(10); // so that the buttons don't grow horizontally
+
+ // auto-launch for local dirs only, and not for '/'
+ if ( isLocal && !hasRoot )
+ {
+ m_sizeDetermineButton->setText( i18n("Refresh") );
+ slotSizeDetermine();
+ }
+ else
+ m_sizeStopButton->setEnabled( false );
+ }
+
+ if (!d->bMultiple && item->isLink()) {
+ l = new TQLabel(i18n("Points to:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ l = new KSqueezedTextLabel(item->linkDest(), d->m_frame );
+ grid->addWidget(l, curRow++, 2);
+ }
+
+ if (!d->bMultiple) // Dates for multiple don't make much sense...
+ {
+ TQDateTime dt;
+ bool hasTime;
+ time_t tim = item->time(TDEIO::UDS_CREATION_TIME, hasTime);
+ if ( hasTime )
+ {
+ l = new TQLabel(i18n("Created:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ dt.setTime_t( tim );
+ l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
+ grid->addWidget(l, curRow++, 2);
+ }
+
+ tim = item->time(TDEIO::UDS_MODIFICATION_TIME, hasTime);
+ if ( hasTime )
+ {
+ l = new TQLabel(i18n("Modified:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ dt.setTime_t( tim );
+ l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
+ grid->addWidget(l, curRow++, 2);
+ }
+
+ tim = item->time(TDEIO::UDS_ACCESS_TIME, hasTime);
+ if ( hasTime )
+ {
+ l = new TQLabel(i18n("Accessed:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ dt.setTime_t( tim );
+ l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
+ grid->addWidget(l, curRow++, 2);
+ }
+ }
+
+ if ( isLocal && hasDirs ) // only for directories
+ {
+ sep = new KSeparator( KSeparator::HLine, d->m_frame);
+ grid->addMultiCellWidget(sep, curRow, curRow, 0, 2);
+ ++curRow;
+
+ TQString mountPoint = TDEIO::findPathMountPoint( url.path() );
+
+ if (mountPoint != "/")
+ {
+ l = new TQLabel(i18n("Mounted on:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ l = new KSqueezedTextLabel( mountPoint, d->m_frame );
+ grid->addWidget( l, curRow++, 2 );
+ }
+
+ l = new TQLabel(i18n("Free disk space:"), d->m_frame );
+ grid->addWidget(l, curRow, 0);
+
+ d->m_freeSpaceLabel = new TQLabel( d->m_frame );
+ grid->addWidget( d->m_freeSpaceLabel, curRow++, 2 );
+
+ KDiskFreeSp * job = new KDiskFreeSp;
+ connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
+ const unsigned long&, const TQString& ) ),
+ this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
+ const unsigned long&, const TQString& ) ) );
+ job->readDF( mountPoint );
+ }
+
+ vbl->addStretch(1);
+}
+
+// TQString KFilePropsPlugin::tabName () const
+// {
+// return i18n ("&General");
+// }
+
+void KFilePropsPlugin::setFileNameReadOnly( bool ro )
+{
+ if ( d->m_lined )
+ {
+ d->m_lined->setReadOnly( ro );
+ if (ro)
+ {
+ // Don't put the initial focus on the line edit when it is ro
+ TQPushButton *button = properties->actionButton(KDialogBase::Ok);
+ if (button)
+ button->setFocus();
+ }
+ }
+}
+
+void KFilePropsPlugin::slotEditFileType()
+{
+#ifdef Q_WS_X11
+ TQString mime;
+ if ( d->mimeType == KMimeType::defaultMimeType() ) {
+ int pos = d->oldFileName.findRev( '.' );
+ if ( pos != -1 )
+ mime = "*" + d->oldFileName.mid(pos);
+ else
+ mime = "*";
+ }
+ else
+ mime = d->mimeType;
+ //TODO: wrap for win32 or mac?
+ TQString keditfiletype = TQString::fromLatin1("keditfiletype");
+ KRun::runCommand( keditfiletype
+ + " --parent " + TQString::number( (ulong)properties->topLevelWidget()->winId())
+ + " " + TDEProcess::quote(mime),
+ keditfiletype, keditfiletype /*unused*/);
+#endif
+}
+
+void KFilePropsPlugin::slotIconChanged()
+{
+ d->bIconChanged = true;
+ emit changed();
+}
+
+void KFilePropsPlugin::nameFileChanged(const TQString &text )
+{
+ properties->enableButtonOK(!text.isEmpty());
+ emit changed();
+}
+
+void KFilePropsPlugin::determineRelativePath( const TQString & path )
+{
+ // now let's make it relative
+ TQStringList dirs;
+ if (KBindingPropsPlugin::supports(properties->items()))
+ {
+ m_sRelativePath =TDEGlobal::dirs()->relativeLocation("mime", path);
+ if (m_sRelativePath.startsWith("/"))
+ m_sRelativePath = TQString::null;
+ }
+ else
+ {
+ m_sRelativePath =TDEGlobal::dirs()->relativeLocation("apps", path);
+ if (m_sRelativePath.startsWith("/"))
+ {
+ m_sRelativePath =TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path);
+ if (m_sRelativePath.startsWith("/"))
+ m_sRelativePath = TQString::null;
+ else
+ m_sRelativePath = path;
+ }
+ }
+ if ( m_sRelativePath.isEmpty() )
+ {
+ if (KBindingPropsPlugin::supports(properties->items()))
+ kdWarning(250) << "Warning : editing a mimetype file out of the mimetype dirs!" << endl;
+ }
+}
+
+void KFilePropsPlugin::slotFoundMountPoint( const TQString&,
+ unsigned long kBSize,
+ unsigned long /*kBUsed*/,
+ unsigned long kBAvail )
+{
+ d->m_freeSpaceLabel->setText(
+ // xgettext:no-c-format -- Don't warn about translating the %1 out of %2 part.
+ i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
+ .arg(TDEIO::convertSizeFromKB(kBAvail))
+ .arg(TDEIO::convertSizeFromKB(kBSize))
+ .arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
+}
+
+// attention: copy&paste below, due to compiler bug
+// it doesn't like those unsigned long parameters -- unsigned long& are ok :-/
+void KFilePropsPlugin::slotFoundMountPoint( const unsigned long& kBSize,
+ const unsigned long& /*kBUsed*/,
+ const unsigned long& kBAvail,
+ const TQString& )
+{
+ d->m_freeSpaceLabel->setText(
+ // xgettext:no-c-format -- Don't warn about translating the %1 out of %2 part.
+ i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
+ .arg(TDEIO::convertSizeFromKB(kBAvail))
+ .arg(TDEIO::convertSizeFromKB(kBSize))
+ .arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
+}
+
+void KFilePropsPlugin::slotDirSizeUpdate()
+{
+ TDEIO::filesize_t totalSize = d->dirSizeJob->totalSize();
+ TDEIO::filesize_t totalFiles = d->dirSizeJob->totalFiles();
+ TDEIO::filesize_t totalSubdirs = d->dirSizeJob->totalSubdirs();
+ m_sizeLabel->setText( i18n("Calculating... %1 (%2)\n%3, %4")
+ .arg(TDEIO::convertSize(totalSize))
+ .arg(TDEGlobal::locale()->formatNumber(totalSize, 0))
+ .arg(i18n("1 file","%n files",totalFiles))
+ .arg(i18n("1 sub-folder","%n sub-folders",totalSubdirs)));
+}
+
+void KFilePropsPlugin::slotDirSizeFinished( TDEIO::Job * job )
+{
+ if (job->error())
+ m_sizeLabel->setText( job->errorString() );
+ else
+ {
+ TDEIO::filesize_t totalSize = static_cast<KDirSize*>(job)->totalSize();
+ TDEIO::filesize_t totalFiles = static_cast<KDirSize*>(job)->totalFiles();
+ TDEIO::filesize_t totalSubdirs = static_cast<KDirSize*>(job)->totalSubdirs();
+ m_sizeLabel->setText( TQString::fromLatin1("%1 (%2)\n%3, %4")
+ .arg(TDEIO::convertSize(totalSize))
+ .arg(TDEGlobal::locale()->formatNumber(totalSize, 0))
+ .arg(i18n("1 file","%n files",totalFiles))
+ .arg(i18n("1 sub-folder","%n sub-folders",totalSubdirs)));
+ }
+ m_sizeStopButton->setEnabled(false);
+ // just in case you change something and try again :)
+ m_sizeDetermineButton->setText( i18n("Refresh") );
+ m_sizeDetermineButton->setEnabled(true);
+ d->dirSizeJob = 0L;
+ delete d->dirSizeUpdateTimer;
+ d->dirSizeUpdateTimer = 0L;
+}
+
+void KFilePropsPlugin::slotSizeDetermine()
+{
+ m_sizeLabel->setText( i18n("Calculating...") );
+ kdDebug(250) << " KFilePropsPlugin::slotSizeDetermine() properties->item()=" << properties->item() << endl;
+ kdDebug(250) << " URL=" << properties->item()->url().url() << endl;
+ d->dirSizeJob = KDirSize::dirSizeJob( properties->items() );
+ d->dirSizeUpdateTimer = new TQTimer(this);
+ connect( d->dirSizeUpdateTimer, TQT_SIGNAL( timeout() ),
+ TQT_SLOT( slotDirSizeUpdate() ) );
+ d->dirSizeUpdateTimer->start(500);
+ connect( d->dirSizeJob, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ TQT_SLOT( slotDirSizeFinished( TDEIO::Job * ) ) );
+ m_sizeStopButton->setEnabled(true);
+ m_sizeDetermineButton->setEnabled(false);
+
+ // also update the "Free disk space" display
+ if ( d->m_freeSpaceLabel )
+ {
+ bool isLocal;
+ KFileItem * item = properties->item();
+ KURL url = item->mostLocalURL( isLocal );
+ TQString mountPoint = TDEIO::findPathMountPoint( url.path() );
+
+ KDiskFreeSp * job = new KDiskFreeSp;
+ connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
+ const unsigned long&, const TQString& ) ),
+ this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
+ const unsigned long&, const TQString& ) ) );
+ job->readDF( mountPoint );
+ }
+}
+
+void KFilePropsPlugin::slotSizeStop()
+{
+ if ( d->dirSizeJob )
+ {
+ m_sizeLabel->setText( i18n("Stopped") );
+ d->dirSizeJob->kill();
+ d->dirSizeJob = 0;
+ }
+ if ( d->dirSizeUpdateTimer )
+ d->dirSizeUpdateTimer->stop();
+
+ m_sizeStopButton->setEnabled(false);
+ m_sizeDetermineButton->setEnabled(true);
+}
+
+KFilePropsPlugin::~KFilePropsPlugin()
+{
+ delete d;
+}
+
+bool KFilePropsPlugin::supports( KFileItemList /*_items*/ )
+{
+ return true;
+}
+
+// Don't do this at home
+void tqt_enter_modal( TQWidget *widget );
+void tqt_leave_modal( TQWidget *widget );
+
+void KFilePropsPlugin::applyChanges()
+{
+ if ( d->dirSizeJob )
+ slotSizeStop();
+
+ kdDebug(250) << "KFilePropsPlugin::applyChanges" << endl;
+
+ if (nameArea->inherits(TQLINEEDIT_OBJECT_NAME_STRING))
+ {
+ TQString n = ((TQLineEdit *) nameArea)->text();
+ // Remove trailing spaces (#4345)
+ while ( n[n.length()-1].isSpace() )
+ n.truncate( n.length() - 1 );
+ if ( n.isEmpty() )
+ {
+ KMessageBox::sorry( properties, i18n("The new file name is empty."));
+ properties->abortApplying();
+ return;
+ }
+
+ // Do we need to rename the file ?
+ kdDebug(250) << "oldname = " << oldName << endl;
+ kdDebug(250) << "newname = " << n << endl;
+ if ( oldName != n || m_bFromTemplate ) { // true for any from-template file
+ TDEIO::Job * job = 0L;
+ KURL oldurl = properties->kurl();
+
+ TQString newFileName = TDEIO::encodeFileName(n);
+ if (d->bDesktopFile && !newFileName.endsWith(".desktop") && !newFileName.endsWith(".kdelnk"))
+ newFileName += ".desktop";
+
+ // Tell properties. Warning, this changes the result of properties->kurl() !
+ properties->rename( newFileName );
+
+ // Update also relative path (for apps and mimetypes)
+ if ( !m_sRelativePath.isEmpty() )
+ determineRelativePath( properties->kurl().path() );
+
+ kdDebug(250) << "New URL = " << properties->kurl().url() << endl;
+ kdDebug(250) << "old = " << oldurl.url() << endl;
+
+ // Don't remove the template !!
+ if ( !m_bFromTemplate ) // (normal renaming)
+ job = TDEIO::move( oldurl, properties->kurl() );
+ else // Copying a template
+ job = TDEIO::copy( oldurl, properties->kurl() );
+
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ TQT_SLOT( slotCopyFinished( TDEIO::Job * ) ) );
+ connect( job, TQT_SIGNAL( renamed( TDEIO::Job *, const KURL &, const KURL & ) ),
+ TQT_SLOT( slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & ) ) );
+ // wait for job
+ TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
+ tqt_enter_modal(&dummy);
+ tqApp->enter_loop();
+ tqt_leave_modal(&dummy);
+ return;
+ }
+ properties->updateUrl(properties->kurl());
+ // Update also relative path (for apps and mimetypes)
+ if ( !m_sRelativePath.isEmpty() )
+ determineRelativePath( properties->kurl().path() );
+ }
+
+ // No job, keep going
+ slotCopyFinished( 0L );
+}
+
+void KFilePropsPlugin::slotCopyFinished( TDEIO::Job * job )
+{
+ kdDebug(250) << "KFilePropsPlugin::slotCopyFinished" << endl;
+ if (job)
+ {
+ // allow apply() to return
+ tqApp->exit_loop();
+ if ( job->error() )
+ {
+ job->showErrorDialog( d->m_frame );
+ // Didn't work. Revert the URL to the old one
+ properties->updateUrl( static_cast<TDEIO::CopyJob*>(job)->srcURLs().first() );
+ properties->abortApplying(); // Don't apply the changes to the wrong file !
+ return;
+ }
+ }
+
+ assert( properties->item() );
+ assert( !properties->item()->url().isEmpty() );
+
+ // Save the file where we can -> usually in ~/.trinity/...
+ if (KBindingPropsPlugin::supports(properties->items()) && !m_sRelativePath.isEmpty())
+ {
+ KURL newURL;
+ newURL.setPath( locateLocal("mime", m_sRelativePath) );
+ properties->updateUrl( newURL );
+ }
+ else if (d->bDesktopFile && !m_sRelativePath.isEmpty())
+ {
+ kdDebug(250) << "KFilePropsPlugin::slotCopyFinished " << m_sRelativePath << endl;
+ KURL newURL;
+ newURL.setPath( KDesktopFile::locateLocal(m_sRelativePath) );
+ kdDebug(250) << "KFilePropsPlugin::slotCopyFinished path=" << newURL.path() << endl;
+ properties->updateUrl( newURL );
+ }
+
+ if ( d->bKDesktopMode && d->bDesktopFile ) {
+ // Renamed? Update Name field
+ if ( d->oldFileName != properties->kurl().fileName() || m_bFromTemplate ) {
+ KDesktopFile config( properties->kurl().path() );
+ TQString nameStr = nameFromFileName(properties->kurl().fileName());
+ config.writeEntry( "Name", nameStr );
+ config.writeEntry( "Name", nameStr, true, false, true );
+ }
+ }
+}
+
+void KFilePropsPlugin::applyIconChanges()
+{
+ KIconButton *iconButton = ::tqqt_cast<KIconButton *>( iconArea );
+ if ( !iconButton || !d->bIconChanged )
+ return;
+ // handle icon changes - only local files (or pseudo-local) for now
+ // TODO: Use KTempFile and TDEIO::file_copy with overwrite = true
+ KURL url = properties->kurl();
+ url = TDEIO::NetAccess::mostLocalURL( url, properties );
+ if (url.isLocalFile()) {
+ TQString path;
+
+ if (S_ISDIR(properties->item()->mode()))
+ {
+ path = url.path(1) + TQString::fromLatin1(".directory");
+ // don't call updateUrl because the other tabs (i.e. permissions)
+ // apply to the directory, not the .directory file.
+ }
+ else
+ path = url.path();
+
+ // Get the default image
+ TQString str = KMimeType::findByURL( url,
+ properties->item()->mode(),
+ true )->KServiceType::icon();
+ // Is it another one than the default ?
+ TQString sIcon;
+ if ( str != iconButton->icon() )
+ sIcon = iconButton->icon();
+ // (otherwise write empty value)
+
+ kdDebug(250) << "**" << path << "**" << endl;
+ TQFile f( path );
+
+ // If default icon and no .directory file -> don't create one
+ if ( !sIcon.isEmpty() || f.exists() )
+ {
+ if ( !f.open( IO_ReadWrite ) ) {
+ KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not "
+ "have sufficient access to write to <b>%1</b>.</qt>").arg(path));
+ return;
+ }
+ f.close();
+
+ KDesktopFile cfg(path);
+ kdDebug(250) << "sIcon = " << (sIcon) << endl;
+ kdDebug(250) << "str = " << (str) << endl;
+ cfg.writeEntry( "Icon", sIcon );
+ cfg.sync();
+ }
+ }
+}
+
+void KFilePropsPlugin::slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & newUrl )
+{
+ // This is called in case of an existing local file during the copy/move operation,
+ // if the user chooses Rename.
+ properties->updateUrl( newUrl );
+}
+
+void KFilePropsPlugin::postApplyChanges()
+{
+ // Save the icon only after applying the permissions changes (#46192)
+ applyIconChanges();
+
+ KURL::List lst;
+ KFileItemList items = properties->items();
+ for ( KFileItemListIterator it( items ); it.current(); ++it )
+ lst.append((*it)->url());
+ KDirNotify_stub allDirNotify("*", "KDirNotify*");
+ allDirNotify.FilesChanged( lst );
+}
+
+class KFilePermissionsPropsPlugin::KFilePermissionsPropsPluginPrivate
+{
+public:
+ KFilePermissionsPropsPluginPrivate()
+ {
+ }
+ ~KFilePermissionsPropsPluginPrivate()
+ {
+ }
+
+ TQFrame *m_frame;
+ TQCheckBox *cbRecursive;
+ TQLabel *explanationLabel;
+ TQComboBox *ownerPermCombo, *groupPermCombo, *othersPermCombo;
+ TQCheckBox *extraCheckbox;
+ mode_t partialPermissions;
+ KFilePermissionsPropsPlugin::PermissionsMode pmode;
+ bool canChangePermissions;
+ bool isIrregular;
+ bool hasExtendedACL;
+ KACL extendedACL;
+ KACL defaultACL;
+ bool fileSystemSupportsACLs;
+};
+
+#define UniOwner (S_IRUSR|S_IWUSR|S_IXUSR)
+#define UniGroup (S_IRGRP|S_IWGRP|S_IXGRP)
+#define UniOthers (S_IROTH|S_IWOTH|S_IXOTH)
+#define UniRead (S_IRUSR|S_IRGRP|S_IROTH)
+#define UniWrite (S_IWUSR|S_IWGRP|S_IWOTH)
+#define UniExec (S_IXUSR|S_IXGRP|S_IXOTH)
+#define UniSpecial (S_ISUID|S_ISGID|S_ISVTX)
+
+// synced with PermissionsTarget
+const mode_t KFilePermissionsPropsPlugin::permissionsMasks[3] = {UniOwner, UniGroup, UniOthers};
+const mode_t KFilePermissionsPropsPlugin::standardPermissions[4] = { 0, UniRead, UniRead|UniWrite, (mode_t)-1 };
+
+// synced with PermissionsMode and standardPermissions
+const char *KFilePermissionsPropsPlugin::permissionsTexts[4][4] = {
+ { I18N_NOOP("Forbidden"),
+ I18N_NOOP("Can Read"),
+ I18N_NOOP("Can Read & Write"),
+ 0 },
+ { I18N_NOOP("Forbidden"),
+ I18N_NOOP("Can View Content"),
+ I18N_NOOP("Can View & Modify Content"),
+ 0 },
+ { 0, 0, 0, 0}, // no texts for links
+ { I18N_NOOP("Forbidden"),
+ I18N_NOOP("Can View Content & Read"),
+ I18N_NOOP("Can View/Read & Modify/Write"),
+ 0 }
+};
+
+
+KFilePermissionsPropsPlugin::KFilePermissionsPropsPlugin( KPropertiesDialog *_props )
+ : KPropsDlgPlugin( _props )
+{
+ d = new KFilePermissionsPropsPluginPrivate;
+ d->cbRecursive = 0L;
+ grpCombo = 0L; grpEdit = 0;
+ usrEdit = 0L;
+ TQString path = properties->kurl().path(-1);
+ TQString fname = properties->kurl().fileName();
+ bool isLocal = properties->kurl().isLocalFile();
+ bool isTrash = ( properties->kurl().protocol().find("trash", 0, false)==0 );
+ bool IamRoot = (geteuid() == 0);
+
+ KFileItem * item = properties->item();
+ bool isLink = item->isLink();
+ bool isDir = item->isDir(); // all dirs
+ bool hasDir = item->isDir(); // at least one dir
+ permissions = item->permissions(); // common permissions to all files
+ d->partialPermissions = permissions; // permissions that only some files have (at first we take everything)
+ d->isIrregular = isIrregular(permissions, isDir, isLink);
+ strOwner = item->user();
+ strGroup = item->group();
+ d->hasExtendedACL = item->ACL().isExtended() || item->defaultACL().isValid();
+ d->extendedACL = item->ACL();
+ d->defaultACL = item->defaultACL();
+ d->fileSystemSupportsACLs = false;
+
+ if ( properties->items().count() > 1 )
+ {
+ // Multiple items: see what they have in common
+ KFileItemList items = properties->items();
+ KFileItemListIterator it( items );
+ for ( ++it /*no need to check the first one again*/ ; it.current(); ++it )
+ {
+ if (!d->isIrregular)
+ d->isIrregular |= isIrregular((*it)->permissions(),
+ (*it)->isDir() == isDir,
+ (*it)->isLink() == isLink);
+ d->hasExtendedACL = d->hasExtendedACL || (*it)->hasExtendedACL();
+ if ( (*it)->isLink() != isLink )
+ isLink = false;
+ if ( (*it)->isDir() != isDir )
+ isDir = false;
+ hasDir |= (*it)->isDir();
+ if ( (*it)->permissions() != permissions )
+ {
+ permissions &= (*it)->permissions();
+ d->partialPermissions |= (*it)->permissions();
+ }
+ if ( (*it)->user() != strOwner )
+ strOwner = TQString::null;
+ if ( (*it)->group() != strGroup )
+ strGroup = TQString::null;
+ }
+ }
+
+ if (isLink)
+ d->pmode = PermissionsOnlyLinks;
+ else if (isDir)
+ d->pmode = PermissionsOnlyDirs;
+ else if (hasDir)
+ d->pmode = PermissionsMixed;
+ else
+ d->pmode = PermissionsOnlyFiles;
+
+ // keep only what's not in the common permissions
+ d->partialPermissions = d->partialPermissions & ~permissions;
+
+ bool isMyFile = false;
+
+ if (isLocal && !strOwner.isEmpty()) { // local files, and all owned by the same person
+ struct passwd *myself = getpwuid( geteuid() );
+ if ( myself != 0L )
+ {
+ isMyFile = (strOwner == TQString::fromLocal8Bit(myself->pw_name));
+ } else
+ kdWarning() << "I don't exist ?! geteuid=" << geteuid() << endl;
+ } else {
+ //We don't know, for remote files, if they are ours or not.
+ //So we let the user change permissions, and
+ //TDEIO::chmod will tell, if he had no right to do it.
+ isMyFile = true;
+ }
+
+ d->canChangePermissions = (isMyFile || IamRoot) && (!isLink);
+
+
+ // create GUI
+
+ d->m_frame = properties->addPage(i18n("&Permissions"));
+
+ TQBoxLayout *box = new TQVBoxLayout( d->m_frame, 0, KDialog::spacingHint() );
+
+ TQWidget *l;
+ TQLabel *lbl;
+ TQGroupBox *gb;
+ TQGridLayout *gl;
+ TQPushButton* pbAdvancedPerm = 0;
+
+ /* Group: Access Permissions */
+ gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Access Permissions"), d->m_frame );
+ gb->layout()->setSpacing(KDialog::spacingHint());
+ gb->layout()->setMargin(KDialog::marginHint());
+ box->addWidget (gb);
+
+ gl = new TQGridLayout (gb->layout(), 7, 2);
+ gl->setColStretch(1, 1);
+
+ l = d->explanationLabel = new TQLabel( "", gb );
+ if (isLink)
+ d->explanationLabel->setText(i18n("This file is a link and does not have permissions.",
+ "All files are links and do not have permissions.",
+ properties->items().count()));
+ else if (!d->canChangePermissions)
+ d->explanationLabel->setText(i18n("Only the owner can change permissions."));
+ gl->addMultiCellWidget(l, 0, 0, 0, 1);
+
+ lbl = new TQLabel( i18n("O&wner:"), gb);
+ gl->addWidget(lbl, 1, 0);
+ l = d->ownerPermCombo = new TQComboBox(gb);
+ lbl->setBuddy(l);
+ gl->addWidget(l, 1, 1);
+ connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
+ TQWhatsThis::add(l, i18n("Specifies the actions that the owner is allowed to do."));
+
+ lbl = new TQLabel( i18n("Gro&up:"), gb);
+ gl->addWidget(lbl, 2, 0);
+ l = d->groupPermCombo = new TQComboBox(gb);
+ lbl->setBuddy(l);
+ gl->addWidget(l, 2, 1);
+ connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
+ TQWhatsThis::add(l, i18n("Specifies the actions that the members of the group are allowed to do."));
+
+ lbl = new TQLabel( i18n("O&thers:"), gb);
+ gl->addWidget(lbl, 3, 0);
+ l = d->othersPermCombo = new TQComboBox(gb);
+ lbl->setBuddy(l);
+ gl->addWidget(l, 3, 1);
+ connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
+ TQWhatsThis::add(l, i18n("Specifies the actions that all users, who are neither "
+ "owner nor in the group, are allowed to do."));
+
+ if (!isLink) {
+ l = d->extraCheckbox = new TQCheckBox(hasDir ?
+ i18n("Only own&er can rename and delete folder content") :
+ i18n("Is &executable"),
+ gb );
+ connect( d->extraCheckbox, TQT_SIGNAL( clicked() ), this, TQT_SIGNAL( changed() ) );
+ gl->addWidget(l, 4, 1);
+ TQWhatsThis::add(l, hasDir ? i18n("Enable this option to allow only the folder's owner to "
+ "delete or rename the contained files and folders. Other "
+ "users can only add new files, which requires the 'Modify "
+ "Content' permission.")
+ : i18n("Enable this option to mark the file as executable. This only makes "
+ "sense for programs and scripts. It is required when you want to "
+ "execute them."));
+
+ TQLayoutItem *spacer = TQT_TQLAYOUTITEM(new TQSpacerItem(0, 20, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
+ gl->addMultiCell(spacer, 5, 5, 0, 1);
+
+ pbAdvancedPerm = new TQPushButton(i18n("A&dvanced Permissions"), gb);
+ gl->addMultiCellWidget(pbAdvancedPerm, 6, 6, 0, 1, Qt::AlignRight);
+ connect(pbAdvancedPerm, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotShowAdvancedPermissions() ));
+ }
+ else
+ d->extraCheckbox = 0;
+
+
+ /**** Group: Ownership ****/
+ gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Ownership"), d->m_frame );
+ gb->layout()->setSpacing(KDialog::spacingHint());
+ gb->layout()->setMargin(KDialog::marginHint());
+ box->addWidget (gb);
+
+ gl = new TQGridLayout (gb->layout(), 4, 3);
+ gl->addRowSpacing(0, 10);
+
+ /*** Set Owner ***/
+ l = new TQLabel( i18n("User:"), gb );
+ gl->addWidget (l, 1, 0);
+
+ /* GJ: Don't autocomplete more than 1000 users. This is a kind of random
+ * value. Huge sites having 10.000+ user have a fair chance of using NIS,
+ * (possibly) making this unacceptably slow.
+ * OTOH, it is nice to offer this functionality for the standard user.
+ */
+ int i, maxEntries = 1000;
+ struct passwd *user;
+ struct group *ge;
+
+ /* File owner: For root, offer a KLineEdit with autocompletion.
+ * For a user, who can never chown() a file, offer a TQLabel.
+ */
+ if (IamRoot && isLocal)
+ {
+ usrEdit = new KLineEdit( gb );
+ KCompletion *kcom = usrEdit->completionObject();
+ kcom->setOrder(KCompletion::Sorted);
+ setpwent();
+ for (i=0; ((user = getpwent()) != 0L) && (i < maxEntries); i++)
+ kcom->addItem(TQString::fromLatin1(user->pw_name));
+ endpwent();
+ usrEdit->setCompletionMode((i < maxEntries) ? TDEGlobalSettings::CompletionAuto :
+ TDEGlobalSettings::CompletionNone);
+ usrEdit->setText(strOwner);
+ gl->addWidget(usrEdit, 1, 1);
+ connect( usrEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ }
+ else
+ {
+ l = new TQLabel(strOwner, gb);
+ gl->addWidget(l, 1, 1);
+ }
+
+ /*** Set Group ***/
+
+ TQStringList groupList;
+ TQCString strUser;
+ user = getpwuid(geteuid());
+ if (user != 0L)
+ strUser = user->pw_name;
+
+#ifdef Q_OS_UNIX
+ setgrent();
+ for (i=0; ((ge = getgrent()) != 0L) && (i < maxEntries); i++)
+ {
+ if (IamRoot)
+ groupList += TQString::fromLatin1(ge->gr_name);
+ else
+ {
+ /* pick the groups to which the user belongs */
+ char ** members = ge->gr_mem;
+ char * member;
+ while ((member = *members) != 0L) {
+ if (strUser == member) {
+ groupList += TQString::fromLocal8Bit(ge->gr_name);
+ break;
+ }
+ ++members;
+ }
+ }
+ }
+ endgrent();
+#endif //Q_OS_UNIX
+
+ /* add the effective Group to the list .. */
+ ge = getgrgid (getegid());
+ if (ge) {
+ TQString name = TQString::fromLatin1(ge->gr_name);
+ if (name.isEmpty())
+ name.setNum(ge->gr_gid);
+ if (groupList.find(name) == groupList.end())
+ groupList += name;
+ }
+
+ bool isMyGroup = groupList.contains(strGroup);
+
+ /* add the group the file currently belongs to ..
+ * .. if its not there already
+ */
+ if (!isMyGroup)
+ groupList += strGroup;
+
+ l = new TQLabel( i18n("Group:"), gb );
+ gl->addWidget (l, 2, 0);
+
+ /* Set group: if possible to change:
+ * - Offer a KLineEdit for root, since he can change to any group.
+ * - Offer a TQComboBox for a normal user, since he can change to a fixed
+ * (small) set of groups only.
+ * If not changeable: offer a TQLabel.
+ */
+ if (IamRoot && isLocal)
+ {
+ grpEdit = new KLineEdit(gb);
+ KCompletion *kcom = new KCompletion;
+ kcom->setItems(groupList);
+ grpEdit->setCompletionObject(kcom, true);
+ grpEdit->setAutoDeleteCompletionObject( true );
+ grpEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
+ grpEdit->setText(strGroup);
+ gl->addWidget(grpEdit, 2, 1);
+ connect( grpEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ }
+ else if ((groupList.count() > 1) && isMyFile && isLocal)
+ {
+ grpCombo = new TQComboBox(gb, "combogrouplist");
+ grpCombo->insertStringList(groupList);
+ grpCombo->setCurrentItem(groupList.findIndex(strGroup));
+ gl->addWidget(grpCombo, 2, 1);
+ connect( grpCombo, TQT_SIGNAL( activated( int ) ),
+ this, TQT_SIGNAL( changed() ) );
+ }
+ else
+ {
+ l = new TQLabel(strGroup, gb);
+ gl->addWidget(l, 2, 1);
+ }
+
+ gl->setColStretch(2, 10);
+
+ // "Apply recursive" checkbox
+ if ( hasDir && !isLink && !isTrash )
+ {
+ d->cbRecursive = new TQCheckBox( i18n("Apply changes to all subfolders and their contents"), d->m_frame );
+ connect( d->cbRecursive, TQT_SIGNAL( clicked() ), this, TQT_SIGNAL( changed() ) );
+ box->addWidget( d->cbRecursive );
+ }
+
+ updateAccessControls();
+
+
+ if ( isTrash || !d->canChangePermissions )
+ {
+ //don't allow to change properties for file into trash
+ enableAccessControls(false);
+ if ( pbAdvancedPerm && !d->hasExtendedACL )
+ pbAdvancedPerm->setEnabled(false);
+ }
+
+ box->addStretch (10);
+}
+
+#ifdef USE_POSIX_ACL
+static bool fileSystemSupportsACL( const TQCString& pathCString )
+{
+ bool fileSystemSupportsACLs = false;
+#ifdef Q_OS_FREEBSD
+ struct statfs buf;
+ fileSystemSupportsACLs = ( statfs( pathCString.data(), &buf ) == 0 ) && ( buf.f_flags & MNT_ACLS );
+#else
+ fileSystemSupportsACLs =
+ getxattr( pathCString.data(), "system.posix_acl_access", NULL, 0 ) >= 0
+#ifdef ENODATA
+ || (errno == ENODATA)
+#endif
+#ifdef ENOATTR
+ || (errno == ENOATTR)
+#endif
+ ;
+#endif
+ return fileSystemSupportsACLs;
+}
+#endif
+
+
+void KFilePermissionsPropsPlugin::slotShowAdvancedPermissions() {
+
+ bool isDir = (d->pmode == PermissionsOnlyDirs) || (d->pmode == PermissionsMixed);
+ KDialogBase dlg(properties, 0, true, i18n("Advanced Permissions"),
+ KDialogBase::Ok|KDialogBase::Cancel);
+
+ TQLabel *l, *cl[3];
+ TQGroupBox *gb;
+ TQGridLayout *gl;
+
+ TQVBox *mainVBox = dlg.makeVBoxMainWidget();
+
+ // Group: Access Permissions
+ gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Access Permissions"), mainVBox );
+ gb->layout()->setSpacing(KDialog::spacingHint());
+ gb->layout()->setMargin(KDialog::marginHint());
+
+ gl = new TQGridLayout (gb->layout(), 6, 6);
+ gl->addRowSpacing(0, 10);
+
+ TQValueVector<TQWidget*> theNotSpecials;
+
+ l = new TQLabel(i18n("Class"), gb );
+ gl->addWidget(l, 1, 0);
+ theNotSpecials.append( l );
+
+ if (isDir)
+ l = new TQLabel( i18n("Show\nEntries"), gb );
+ else
+ l = new TQLabel( i18n("Read"), gb );
+ gl->addWidget (l, 1, 1);
+ theNotSpecials.append( l );
+ TQString readWhatsThis;
+ if (isDir)
+ readWhatsThis = i18n("This flag allows viewing the content of the folder.");
+ else
+ readWhatsThis = i18n("The Read flag allows viewing the content of the file.");
+ TQWhatsThis::add(l, readWhatsThis);
+
+ if (isDir)
+ l = new TQLabel( i18n("Write\nEntries"), gb );
+ else
+ l = new TQLabel( i18n("Write"), gb );
+ gl->addWidget (l, 1, 2);
+ theNotSpecials.append( l );
+ TQString writeWhatsThis;
+ if (isDir)
+ writeWhatsThis = i18n("This flag allows adding, renaming and deleting of files. "
+ "Note that deleting and renaming can be limited using the Sticky flag.");
+ else
+ writeWhatsThis = i18n("The Write flag allows modifying the content of the file.");
+ TQWhatsThis::add(l, writeWhatsThis);
+
+ TQString execWhatsThis;
+ if (isDir) {
+ l = new TQLabel( i18n("Enter folder", "Enter"), gb );
+ execWhatsThis = i18n("Enable this flag to allow entering the folder.");
+ }
+ else {
+ l = new TQLabel( i18n("Exec"), gb );
+ execWhatsThis = i18n("Enable this flag to allow executing the file as a program.");
+ }
+ TQWhatsThis::add(l, execWhatsThis);
+ theNotSpecials.append( l );
+ // GJ: Add space between normal and special modes
+ TQSize size = l->sizeHint();
+ size.setWidth(size.width() + 15);
+ l->setFixedSize(size);
+ gl->addWidget (l, 1, 3);
+
+ l = new TQLabel( i18n("Special"), gb );
+ gl->addMultiCellWidget(l, 1, 1, 4, 5);
+ TQString specialWhatsThis;
+ if (isDir)
+ specialWhatsThis = i18n("Special flag. Valid for the whole folder, the exact "
+ "meaning of the flag can be seen in the right hand column.");
+ else
+ specialWhatsThis = i18n("Special flag. The exact meaning of the flag can be seen "
+ "in the right hand column.");
+ TQWhatsThis::add(l, specialWhatsThis);
+
+ cl[0] = new TQLabel( i18n("User"), gb );
+ gl->addWidget (cl[0], 2, 0);
+ theNotSpecials.append( cl[0] );
+
+ cl[1] = new TQLabel( i18n("Group"), gb );
+ gl->addWidget (cl[1], 3, 0);
+ theNotSpecials.append( cl[1] );
+
+ cl[2] = new TQLabel( i18n("Others"), gb );
+ gl->addWidget (cl[2], 4, 0);
+ theNotSpecials.append( cl[2] );
+
+ l = new TQLabel(i18n("Set UID"), gb);
+ gl->addWidget(l, 2, 5);
+ TQString setUidWhatsThis;
+ if (isDir)
+ setUidWhatsThis = i18n("If this flag is set, the owner of this folder will be "
+ "the owner of all new files.");
+ else
+ setUidWhatsThis = i18n("If this file is an executable and the flag is set, it will "
+ "be executed with the permissions of the owner.");
+ TQWhatsThis::add(l, setUidWhatsThis);
+
+ l = new TQLabel(i18n("Set GID"), gb);
+ gl->addWidget(l, 3, 5);
+ TQString setGidWhatsThis;
+ if (isDir)
+ setGidWhatsThis = i18n("If this flag is set, the group of this folder will be "
+ "set for all new files.");
+ else
+ setGidWhatsThis = i18n("If this file is an executable and the flag is set, it will "
+ "be executed with the permissions of the group.");
+ TQWhatsThis::add(l, setGidWhatsThis);
+
+ l = new TQLabel(i18n("File permission", "Sticky"), gb);
+ gl->addWidget(l, 4, 5);
+ TQString stickyWhatsThis;
+ if (isDir)
+ stickyWhatsThis = i18n("If the Sticky flag is set on a folder, only the owner "
+ "and root can delete or rename files. Otherwise everybody "
+ "with write permissions can do this.");
+ else
+ stickyWhatsThis = i18n("The Sticky flag on a file is ignored on Linux, but may "
+ "be used on some systems");
+ TQWhatsThis::add(l, stickyWhatsThis);
+
+ mode_t aPermissions, aPartialPermissions;
+ mode_t dummy1, dummy2;
+
+ if (!d->isIrregular) {
+ switch (d->pmode) {
+ case PermissionsOnlyFiles:
+ getPermissionMasks(aPartialPermissions,
+ dummy1,
+ aPermissions,
+ dummy2);
+ break;
+ case PermissionsOnlyDirs:
+ case PermissionsMixed:
+ getPermissionMasks(dummy1,
+ aPartialPermissions,
+ dummy2,
+ aPermissions);
+ break;
+ case PermissionsOnlyLinks:
+ aPermissions = UniRead | UniWrite | UniExec | UniSpecial;
+ aPartialPermissions = 0;
+ break;
+ }
+ }
+ else {
+ aPermissions = permissions;
+ aPartialPermissions = d->partialPermissions;
+ }
+
+ // Draw Checkboxes
+ TQCheckBox *cba[3][4];
+ for (int row = 0; row < 3 ; ++row) {
+ for (int col = 0; col < 4; ++col) {
+ TQCheckBox *cb = new TQCheckBox( gb );
+ if ( col != 3 ) theNotSpecials.append( cb );
+ cba[row][col] = cb;
+ cb->setChecked(aPermissions & fperm[row][col]);
+ if ( aPartialPermissions & fperm[row][col] )
+ {
+ cb->setTristate();
+ cb->setNoChange();
+ }
+ else if (d->cbRecursive && d->cbRecursive->isChecked())
+ cb->setTristate();
+
+ cb->setEnabled( d->canChangePermissions );
+ gl->addWidget (cb, row+2, col+1);
+ switch(col) {
+ case 0:
+ TQWhatsThis::add(cb, readWhatsThis);
+ break;
+ case 1:
+ TQWhatsThis::add(cb, writeWhatsThis);
+ break;
+ case 2:
+ TQWhatsThis::add(cb, execWhatsThis);
+ break;
+ case 3:
+ switch(row) {
+ case 0:
+ TQWhatsThis::add(cb, setUidWhatsThis);
+ break;
+ case 1:
+ TQWhatsThis::add(cb, setGidWhatsThis);
+ break;
+ case 2:
+ TQWhatsThis::add(cb, stickyWhatsThis);
+ break;
+ }
+ break;
+ }
+ }
+ }
+ gl->setColStretch(6, 10);
+
+#ifdef USE_POSIX_ACL
+ KACLEditWidget *extendedACLs = 0;
+
+ // FIXME make it work with partial entries
+ if ( properties->items().count() == 1 ) {
+ TQCString pathCString = TQFile::encodeName( properties->item()->url().path() );
+ d->fileSystemSupportsACLs = fileSystemSupportsACL( pathCString );
+ }
+ if ( d->fileSystemSupportsACLs ) {
+ std::for_each( theNotSpecials.begin(), theNotSpecials.end(), std::mem_fun( &TQWidget::hide ) );
+ extendedACLs = new KACLEditWidget( mainVBox );
+ if ( d->extendedACL.isValid() && d->extendedACL.isExtended() )
+ extendedACLs->setACL( d->extendedACL );
+ else
+ extendedACLs->setACL( KACL( aPermissions ) );
+
+ if ( d->defaultACL.isValid() )
+ extendedACLs->setDefaultACL( d->defaultACL );
+
+ if ( properties->items().first()->isDir() )
+ extendedACLs->setAllowDefaults( true );
+ if ( !d->canChangePermissions )
+ extendedACLs->setReadOnly( true );
+
+ }
+#endif
+ if (dlg.exec() != KDialogBase::Accepted)
+ return;
+
+ mode_t andPermissions = mode_t(~0);
+ mode_t orPermissions = 0;
+ for (int row = 0; row < 3; ++row)
+ for (int col = 0; col < 4; ++col) {
+ switch (cba[row][col]->state())
+ {
+ case TQCheckBox::On:
+ orPermissions |= fperm[row][col];
+ //fall through
+ case TQCheckBox::Off:
+ andPermissions &= ~fperm[row][col];
+ break;
+ default: // NoChange
+ break;
+ }
+ }
+
+ d->isIrregular = false;
+ KFileItemList items = properties->items();
+ for (KFileItemListIterator it(items); it.current(); ++it) {
+ if (isIrregular(((*it)->permissions() & andPermissions) | orPermissions,
+ (*it)->isDir(), (*it)->isLink())) {
+ d->isIrregular = true;
+ break;
+ }
+ }
+
+ permissions = orPermissions;
+ d->partialPermissions = andPermissions;
+
+#ifdef USE_POSIX_ACL
+ // override with the acls, if present
+ if ( extendedACLs ) {
+ d->extendedACL = extendedACLs->getACL();
+ d->defaultACL = extendedACLs->getDefaultACL();
+ d->hasExtendedACL = d->extendedACL.isExtended() || d->defaultACL.isValid();
+ permissions = d->extendedACL.basePermissions();
+ permissions |= ( andPermissions | orPermissions ) & ( S_ISUID|S_ISGID|S_ISVTX );
+ }
+#endif
+
+ updateAccessControls();
+ emit changed();
+}
+
+// TQString KFilePermissionsPropsPlugin::tabName () const
+// {
+// return i18n ("&Permissions");
+// }
+
+KFilePermissionsPropsPlugin::~KFilePermissionsPropsPlugin()
+{
+ delete d;
+}
+
+bool KFilePermissionsPropsPlugin::supports( KFileItemList _items )
+{
+ KFileItemList::const_iterator it = _items.constBegin();
+ for ( ; it != _items.constEnd(); ++it ) {
+ KFileItem *item = *it;
+ if( !item->user().isEmpty() || !item->group().isEmpty() )
+ return true;
+ }
+ return false;
+}
+
+// sets a combo box in the Access Control frame
+void KFilePermissionsPropsPlugin::setComboContent(TQComboBox *combo, PermissionsTarget target,
+ mode_t permissions, mode_t partial) {
+ combo->clear();
+ if (d->pmode == PermissionsOnlyLinks) {
+ combo->insertItem(i18n("Link"));
+ combo->setCurrentItem(0);
+ return;
+ }
+
+ mode_t tMask = permissionsMasks[target];
+ int textIndex;
+ for (textIndex = 0; standardPermissions[textIndex] != (mode_t)-1; textIndex++)
+ if ((standardPermissions[textIndex]&tMask) == (permissions&tMask&(UniRead|UniWrite)))
+ break;
+ Q_ASSERT(standardPermissions[textIndex] != (mode_t)-1); // must not happen, would be irreglar
+
+ for (int i = 0; permissionsTexts[(int)d->pmode][i]; i++)
+ combo->insertItem(i18n(permissionsTexts[(int)d->pmode][i]));
+
+ if (partial & tMask & ~UniExec) {
+ combo->insertItem(i18n("Varying (No Change)"));
+ combo->setCurrentItem(3);
+ }
+ else
+ combo->setCurrentItem(textIndex);
+}
+
+// permissions are irregular if they cant be displayed in a combo box.
+bool KFilePermissionsPropsPlugin::isIrregular(mode_t permissions, bool isDir, bool isLink) {
+ if (isLink) // links are always ok
+ return false;
+
+ mode_t p = permissions;
+ if (p & (S_ISUID | S_ISGID)) // setuid/setgid -> irregular
+ return true;
+ if (isDir) {
+ p &= ~S_ISVTX; // ignore sticky on dirs
+
+ // check supported flag combinations
+ mode_t p0 = p & UniOwner;
+ if ((p0 != 0) && (p0 != (S_IRUSR | S_IXUSR)) && (p0 != UniOwner))
+ return true;
+ p0 = p & UniGroup;
+ if ((p0 != 0) && (p0 != (S_IRGRP | S_IXGRP)) && (p0 != UniGroup))
+ return true;
+ p0 = p & UniOthers;
+ if ((p0 != 0) && (p0 != (S_IROTH | S_IXOTH)) && (p0 != UniOthers))
+ return true;
+ return false;
+ }
+ if (p & S_ISVTX) // sticky on file -> irregular
+ return true;
+
+ // check supported flag combinations
+ mode_t p0 = p & UniOwner;
+ bool usrXPossible = !p0; // true if this file could be an executable
+ if (p0 & S_IXUSR) {
+ if ((p0 == S_IXUSR) || (p0 == (S_IWUSR | S_IXUSR)))
+ return true;
+ usrXPossible = true;
+ }
+ else if (p0 == S_IWUSR)
+ return true;
+
+ p0 = p & UniGroup;
+ bool grpXPossible = !p0; // true if this file could be an executable
+ if (p0 & S_IXGRP) {
+ if ((p0 == S_IXGRP) || (p0 == (S_IWGRP | S_IXGRP)))
+ return true;
+ grpXPossible = true;
+ }
+ else if (p0 == S_IWGRP)
+ return true;
+ if (p0 == 0)
+ grpXPossible = true;
+
+ p0 = p & UniOthers;
+ bool othXPossible = !p0; // true if this file could be an executable
+ if (p0 & S_IXOTH) {
+ if ((p0 == S_IXOTH) || (p0 == (S_IWOTH | S_IXOTH)))
+ return true;
+ othXPossible = true;
+ }
+ else if (p0 == S_IWOTH)
+ return true;
+
+ // check that there either all targets are executable-compatible, or none
+ return (p & UniExec) && !(usrXPossible && grpXPossible && othXPossible);
+}
+
+// enables/disabled the widgets in the Access Control frame
+void KFilePermissionsPropsPlugin::enableAccessControls(bool enable) {
+ d->ownerPermCombo->setEnabled(enable);
+ d->groupPermCombo->setEnabled(enable);
+ d->othersPermCombo->setEnabled(enable);
+ if (d->extraCheckbox)
+ d->extraCheckbox->setEnabled(enable);
+ if ( d->cbRecursive )
+ d->cbRecursive->setEnabled(enable);
+}
+
+// updates all widgets in the Access Control frame
+void KFilePermissionsPropsPlugin::updateAccessControls() {
+ setComboContent(d->ownerPermCombo, PermissionsOwner,
+ permissions, d->partialPermissions);
+ setComboContent(d->groupPermCombo, PermissionsGroup,
+ permissions, d->partialPermissions);
+ setComboContent(d->othersPermCombo, PermissionsOthers,
+ permissions, d->partialPermissions);
+
+ switch(d->pmode) {
+ case PermissionsOnlyLinks:
+ enableAccessControls(false);
+ break;
+ case PermissionsOnlyFiles:
+ enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
+ if (d->canChangePermissions)
+ d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
+ i18n("This file uses advanced permissions",
+ "These files use advanced permissions.",
+ properties->items().count()) : "");
+ if (d->partialPermissions & UniExec) {
+ d->extraCheckbox->setTristate();
+ d->extraCheckbox->setNoChange();
+ }
+ else {
+ d->extraCheckbox->setTristate(false);
+ d->extraCheckbox->setChecked(permissions & UniExec);
+ }
+ break;
+ case PermissionsOnlyDirs:
+ enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
+ // if this is a dir, and we can change permissions, don't dis-allow
+ // recursive, we can do that for ACL setting.
+ if ( d->cbRecursive )
+ d->cbRecursive->setEnabled( d->canChangePermissions && !d->isIrregular );
+
+ if (d->canChangePermissions)
+ d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
+ i18n("This folder uses advanced permissions.",
+ "These folders use advanced permissions.",
+ properties->items().count()) : "");
+ if (d->partialPermissions & S_ISVTX) {
+ d->extraCheckbox->setTristate();
+ d->extraCheckbox->setNoChange();
+ }
+ else {
+ d->extraCheckbox->setTristate(false);
+ d->extraCheckbox->setChecked(permissions & S_ISVTX);
+ }
+ break;
+ case PermissionsMixed:
+ enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
+ if (d->canChangePermissions)
+ d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
+ i18n("These files use advanced permissions.") : "");
+ break;
+ if (d->partialPermissions & S_ISVTX) {
+ d->extraCheckbox->setTristate();
+ d->extraCheckbox->setNoChange();
+ }
+ else {
+ d->extraCheckbox->setTristate(false);
+ d->extraCheckbox->setChecked(permissions & S_ISVTX);
+ }
+ break;
+ }
+}
+
+// gets masks for files and dirs from the Access Control frame widgets
+void KFilePermissionsPropsPlugin::getPermissionMasks(mode_t &andFilePermissions,
+ mode_t &andDirPermissions,
+ mode_t &orFilePermissions,
+ mode_t &orDirPermissions) {
+ andFilePermissions = mode_t(~UniSpecial);
+ andDirPermissions = mode_t(~(S_ISUID|S_ISGID));
+ orFilePermissions = 0;
+ orDirPermissions = 0;
+ if (d->isIrregular)
+ return;
+
+ mode_t m = standardPermissions[d->ownerPermCombo->currentItem()];
+ if (m != (mode_t) -1) {
+ orFilePermissions |= m & UniOwner;
+ if ((m & UniOwner) &&
+ ((d->pmode == PermissionsMixed) ||
+ ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
+ andFilePermissions &= ~(S_IRUSR | S_IWUSR);
+ else {
+ andFilePermissions &= ~(S_IRUSR | S_IWUSR | S_IXUSR);
+ if ((m & S_IRUSR) && (d->extraCheckbox->state() == TQButton::On))
+ orFilePermissions |= S_IXUSR;
+ }
+
+ orDirPermissions |= m & UniOwner;
+ if (m & S_IRUSR)
+ orDirPermissions |= S_IXUSR;
+ andDirPermissions &= ~(S_IRUSR | S_IWUSR | S_IXUSR);
+ }
+
+ m = standardPermissions[d->groupPermCombo->currentItem()];
+ if (m != (mode_t) -1) {
+ orFilePermissions |= m & UniGroup;
+ if ((m & UniGroup) &&
+ ((d->pmode == PermissionsMixed) ||
+ ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
+ andFilePermissions &= ~(S_IRGRP | S_IWGRP);
+ else {
+ andFilePermissions &= ~(S_IRGRP | S_IWGRP | S_IXGRP);
+ if ((m & S_IRGRP) && (d->extraCheckbox->state() == TQButton::On))
+ orFilePermissions |= S_IXGRP;
+ }
+
+ orDirPermissions |= m & UniGroup;
+ if (m & S_IRGRP)
+ orDirPermissions |= S_IXGRP;
+ andDirPermissions &= ~(S_IRGRP | S_IWGRP | S_IXGRP);
+ }
+
+ m = standardPermissions[d->othersPermCombo->currentItem()];
+ if (m != (mode_t) -1) {
+ orFilePermissions |= m & UniOthers;
+ if ((m & UniOthers) &&
+ ((d->pmode == PermissionsMixed) ||
+ ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
+ andFilePermissions &= ~(S_IROTH | S_IWOTH);
+ else {
+ andFilePermissions &= ~(S_IROTH | S_IWOTH | S_IXOTH);
+ if ((m & S_IROTH) && (d->extraCheckbox->state() == TQButton::On))
+ orFilePermissions |= S_IXOTH;
+ }
+
+ orDirPermissions |= m & UniOthers;
+ if (m & S_IROTH)
+ orDirPermissions |= S_IXOTH;
+ andDirPermissions &= ~(S_IROTH | S_IWOTH | S_IXOTH);
+ }
+
+ if (((d->pmode == PermissionsMixed) || (d->pmode == PermissionsOnlyDirs)) &&
+ (d->extraCheckbox->state() != TQButton::NoChange)) {
+ andDirPermissions &= ~S_ISVTX;
+ if (d->extraCheckbox->state() == TQButton::On)
+ orDirPermissions |= S_ISVTX;
+ }
+}
+
+void KFilePermissionsPropsPlugin::applyChanges()
+{
+ mode_t orFilePermissions;
+ mode_t orDirPermissions;
+ mode_t andFilePermissions;
+ mode_t andDirPermissions;
+
+ if (!d->canChangePermissions)
+ return;
+
+ if (!d->isIrregular)
+ getPermissionMasks(andFilePermissions,
+ andDirPermissions,
+ orFilePermissions,
+ orDirPermissions);
+ else {
+ orFilePermissions = permissions;
+ andFilePermissions = d->partialPermissions;
+ orDirPermissions = permissions;
+ andDirPermissions = d->partialPermissions;
+ }
+
+ TQString owner, group;
+ if (usrEdit)
+ owner = usrEdit->text();
+ if (grpEdit)
+ group = grpEdit->text();
+ else if (grpCombo)
+ group = grpCombo->currentText();
+
+ if (owner == strOwner)
+ owner = TQString::null; // no change
+
+ if (group == strGroup)
+ group = TQString::null;
+
+ bool recursive = d->cbRecursive && d->cbRecursive->isChecked();
+ bool permissionChange = false;
+
+ KFileItemList files, dirs;
+ KFileItemList items = properties->items();
+ for (KFileItemListIterator it(items); it.current(); ++it) {
+ if ((*it)->isDir()) {
+ dirs.append(*it);
+ if ((*it)->permissions() != (((*it)->permissions() & andDirPermissions) | orDirPermissions))
+ permissionChange = true;
+ }
+ else if ((*it)->isFile()) {
+ files.append(*it);
+ if ((*it)->permissions() != (((*it)->permissions() & andFilePermissions) | orFilePermissions))
+ permissionChange = true;
+ }
+ }
+
+ const bool ACLChange = ( d->extendedACL != properties->item()->ACL() );
+ const bool defaultACLChange = ( d->defaultACL != properties->item()->defaultACL() );
+
+ if ( owner.isEmpty() && group.isEmpty() && !recursive
+ && !permissionChange && !ACLChange && !defaultACLChange )
+ return;
+
+ TDEIO::Job * job;
+ if (files.count() > 0) {
+ job = TDEIO::chmod( files, orFilePermissions, ~andFilePermissions,
+ owner, group, false );
+ if ( ACLChange && d->fileSystemSupportsACLs )
+ job->addMetaData( "ACL_STRING", d->extendedACL.isValid()?d->extendedACL.asString():"ACL_DELETE" );
+ if ( defaultACLChange && d->fileSystemSupportsACLs )
+ job->addMetaData( "DEFAULT_ACL_STRING", d->defaultACL.isValid()?d->defaultACL.asString():"ACL_DELETE" );
+
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ TQT_SLOT( slotChmodResult( TDEIO::Job * ) ) );
+ // Wait for job
+ TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
+ tqt_enter_modal(&dummy);
+ tqApp->enter_loop();
+ tqt_leave_modal(&dummy);
+ }
+ if (dirs.count() > 0) {
+ job = TDEIO::chmod( dirs, orDirPermissions, ~andDirPermissions,
+ owner, group, recursive );
+ if ( ACLChange && d->fileSystemSupportsACLs )
+ job->addMetaData( "ACL_STRING", d->extendedACL.isValid()?d->extendedACL.asString():"ACL_DELETE" );
+ if ( defaultACLChange && d->fileSystemSupportsACLs )
+ job->addMetaData( "DEFAULT_ACL_STRING", d->defaultACL.isValid()?d->defaultACL.asString():"ACL_DELETE" );
+
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ TQT_SLOT( slotChmodResult( TDEIO::Job * ) ) );
+ // Wait for job
+ TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
+ tqt_enter_modal(&dummy);
+ tqApp->enter_loop();
+ tqt_leave_modal(&dummy);
+ }
+}
+
+void KFilePermissionsPropsPlugin::slotChmodResult( TDEIO::Job * job )
+{
+ kdDebug(250) << "KFilePermissionsPropsPlugin::slotChmodResult" << endl;
+ if (job->error())
+ job->showErrorDialog( d->m_frame );
+ // allow apply() to return
+ tqApp->exit_loop();
+}
+
+
+
+
+class KURLPropsPlugin::KURLPropsPluginPrivate
+{
+public:
+ KURLPropsPluginPrivate()
+ {
+ }
+ ~KURLPropsPluginPrivate()
+ {
+ }
+
+ TQFrame *m_frame;
+};
+
+KURLPropsPlugin::KURLPropsPlugin( KPropertiesDialog *_props )
+ : KPropsDlgPlugin( _props )
+{
+ d = new KURLPropsPluginPrivate;
+ d->m_frame = properties->addPage(i18n("U&RL"));
+ TQVBoxLayout *layout = new TQVBoxLayout(d->m_frame, 0, KDialog::spacingHint());
+
+ TQLabel *l;
+ l = new TQLabel( d->m_frame, "Label_1" );
+ l->setText( i18n("URL:") );
+ layout->addWidget(l);
+
+ URLEdit = new KURLRequester( d->m_frame, "URL Requester" );
+ layout->addWidget(URLEdit);
+
+ TQString path = properties->kurl().path();
+
+ TQFile f( path );
+ if ( !f.open( IO_ReadOnly ) )
+ return;
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ URLStr = config.readPathEntry( "URL" );
+
+ if ( !URLStr.isNull() )
+ URLEdit->setURL( URLStr );
+
+ connect( URLEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+
+ layout->addStretch (1);
+}
+
+KURLPropsPlugin::~KURLPropsPlugin()
+{
+ delete d;
+}
+
+// TQString KURLPropsPlugin::tabName () const
+// {
+// return i18n ("U&RL");
+// }
+
+bool KURLPropsPlugin::supports( KFileItemList _items )
+{
+ if ( _items.count() != 1 )
+ return false;
+ KFileItem * item = _items.first();
+ // check if desktop file
+ if ( !KPropsDlgPlugin::isDesktopFile( item ) )
+ return false;
+
+ // open file and check type
+ KDesktopFile config( item->url().path(), true /* readonly */ );
+ return config.hasLinkType();
+}
+
+void KURLPropsPlugin::applyChanges()
+{
+ TQString path = properties->kurl().path();
+
+ TQFile f( path );
+ if ( !f.open( IO_ReadWrite ) ) {
+ KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
+ "sufficient access to write to <b>%1</b>.</qt>").arg(path));
+ return;
+ }
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ config.writeEntry( "Type", TQString::fromLatin1("Link"));
+ config.writePathEntry( "URL", URLEdit->url() );
+ // Users can't create a Link .desktop file with a Name field,
+ // but distributions can. Update the Name field in that case.
+ if ( config.hasKey("Name") )
+ {
+ TQString nameStr = nameFromFileName(properties->kurl().fileName());
+ config.writeEntry( "Name", nameStr );
+ config.writeEntry( "Name", nameStr, true, false, true );
+
+ }
+}
+
+
+/* ----------------------------------------------------
+ *
+ * KBindingPropsPlugin
+ *
+ * -------------------------------------------------- */
+
+class KBindingPropsPlugin::KBindingPropsPluginPrivate
+{
+public:
+ KBindingPropsPluginPrivate()
+ {
+ }
+ ~KBindingPropsPluginPrivate()
+ {
+ }
+
+ TQFrame *m_frame;
+};
+
+KBindingPropsPlugin::KBindingPropsPlugin( KPropertiesDialog *_props ) : KPropsDlgPlugin( _props )
+{
+ d = new KBindingPropsPluginPrivate;
+ d->m_frame = properties->addPage(i18n("A&ssociation"));
+ patternEdit = new KLineEdit( d->m_frame, "LineEdit_1" );
+ commentEdit = new KLineEdit( d->m_frame, "LineEdit_2" );
+ mimeEdit = new KLineEdit( d->m_frame, "LineEdit_3" );
+
+ TQBoxLayout *mainlayout = new TQVBoxLayout(d->m_frame, 0, KDialog::spacingHint());
+ TQLabel* tmpQLabel;
+
+ tmpQLabel = new TQLabel( d->m_frame, "Label_1" );
+ tmpQLabel->setText( i18n("Pattern ( example: *.html;*.htm )") );
+ tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
+ mainlayout->addWidget(tmpQLabel, 1);
+
+ //patternEdit->setGeometry( 10, 40, 210, 30 );
+ //patternEdit->setText( "" );
+ patternEdit->setMaxLength( 512 );
+ patternEdit->setMinimumSize( patternEdit->sizeHint() );
+ patternEdit->setFixedHeight( fontHeight );
+ mainlayout->addWidget(patternEdit, 1);
+
+ tmpQLabel = new TQLabel( d->m_frame, "Label_2" );
+ tmpQLabel->setText( i18n("Mime Type") );
+ tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
+ mainlayout->addWidget(tmpQLabel, 1);
+
+ //mimeEdit->setGeometry( 10, 160, 210, 30 );
+ mimeEdit->setMaxLength( 256 );
+ mimeEdit->setMinimumSize( mimeEdit->sizeHint() );
+ mimeEdit->setFixedHeight( fontHeight );
+ mainlayout->addWidget(mimeEdit, 1);
+
+ tmpQLabel = new TQLabel( d->m_frame, "Label_3" );
+ tmpQLabel->setText( i18n("Comment") );
+ tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
+ mainlayout->addWidget(tmpQLabel, 1);
+
+ //commentEdit->setGeometry( 10, 100, 210, 30 );
+ commentEdit->setMaxLength( 256 );
+ commentEdit->setMinimumSize( commentEdit->sizeHint() );
+ commentEdit->setFixedHeight( fontHeight );
+ mainlayout->addWidget(commentEdit, 1);
+
+ cbAutoEmbed = new TQCheckBox( i18n("Left click previews"), d->m_frame, "cbAutoEmbed" );
+ mainlayout->addWidget(cbAutoEmbed, 1);
+
+ mainlayout->addStretch (10);
+ mainlayout->activate();
+
+ TQFile f( _props->kurl().path() );
+ if ( !f.open( IO_ReadOnly ) )
+ return;
+ f.close();
+
+ KSimpleConfig config( _props->kurl().path() );
+ config.setDesktopGroup();
+ TQString patternStr = config.readEntry( "Patterns" );
+ TQString iconStr = config.readEntry( "Icon" );
+ TQString commentStr = config.readEntry( "Comment" );
+ m_sMimeStr = config.readEntry( "MimeType" );
+
+ if ( !patternStr.isEmpty() )
+ patternEdit->setText( patternStr );
+ if ( !commentStr.isEmpty() )
+ commentEdit->setText( commentStr );
+ if ( !m_sMimeStr.isEmpty() )
+ mimeEdit->setText( m_sMimeStr );
+ cbAutoEmbed->setTristate();
+ if ( config.hasKey( "X-TDE-AutoEmbed" ) )
+ cbAutoEmbed->setChecked( config.readBoolEntry( "X-TDE-AutoEmbed" ) );
+ else
+ cbAutoEmbed->setNoChange();
+
+ connect( patternEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( mimeEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( cbAutoEmbed, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+}
+
+KBindingPropsPlugin::~KBindingPropsPlugin()
+{
+ delete d;
+}
+
+// TQString KBindingPropsPlugin::tabName () const
+// {
+// return i18n ("A&ssociation");
+// }
+
+bool KBindingPropsPlugin::supports( KFileItemList _items )
+{
+ if ( _items.count() != 1 )
+ return false;
+ KFileItem * item = _items.first();
+ // check if desktop file
+ if ( !KPropsDlgPlugin::isDesktopFile( item ) )
+ return false;
+
+ // open file and check type
+ KDesktopFile config( item->url().path(), true /* readonly */ );
+ return config.hasMimeTypeType();
+}
+
+void KBindingPropsPlugin::applyChanges()
+{
+ TQString path = properties->kurl().path();
+ TQFile f( path );
+
+ if ( !f.open( IO_ReadWrite ) )
+ {
+ KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
+ "sufficient access to write to <b>%1</b>.</qt>").arg(path));
+ return;
+ }
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ config.writeEntry( "Type", TQString::fromLatin1("MimeType") );
+
+ config.writeEntry( "Patterns", patternEdit->text() );
+ config.writeEntry( "Comment", commentEdit->text() );
+ config.writeEntry( "Comment",
+ commentEdit->text(), true, false, true ); // for compat
+ config.writeEntry( "MimeType", mimeEdit->text() );
+ if ( cbAutoEmbed->state() == TQButton::NoChange )
+ config.deleteEntry( "X-TDE-AutoEmbed", false );
+ else
+ config.writeEntry( "X-TDE-AutoEmbed", cbAutoEmbed->isChecked() );
+ config.sync();
+}
+
+/* ----------------------------------------------------
+ *
+ * KDevicePropsPlugin
+ *
+ * -------------------------------------------------- */
+
+class KDevicePropsPlugin::KDevicePropsPluginPrivate
+{
+public:
+ KDevicePropsPluginPrivate()
+ {
+ }
+ ~KDevicePropsPluginPrivate()
+ {
+ }
+
+ TQFrame *m_frame;
+ TQStringList mountpointlist;
+ TQLabel *m_freeSpaceText;
+ TQLabel *m_freeSpaceLabel;
+ TQProgressBar *m_freeSpaceBar;
+};
+
+KDevicePropsPlugin::KDevicePropsPlugin( KPropertiesDialog *_props ) : KPropsDlgPlugin( _props )
+{
+ d = new KDevicePropsPluginPrivate;
+ d->m_frame = properties->addPage(i18n("De&vice"));
+
+ TQStringList devices;
+ KMountPoint::List mountPoints = KMountPoint::possibleMountPoints();
+
+ for(KMountPoint::List::ConstIterator it = mountPoints.begin();
+ it != mountPoints.end(); ++it)
+ {
+ KMountPoint *mp = *it;
+ TQString mountPoint = mp->mountPoint();
+ TQString device = mp->mountedFrom();
+ kdDebug()<<"mountPoint :"<<mountPoint<<" device :"<<device<<" mp->mountType() :"<<mp->mountType()<<endl;
+
+ if ((mountPoint != "-") && (mountPoint != "none") && !mountPoint.isEmpty()
+ && device != "none")
+ {
+ devices.append( device + TQString::fromLatin1(" (")
+ + mountPoint + TQString::fromLatin1(")") );
+ m_devicelist.append(device);
+ d->mountpointlist.append(mountPoint);
+ }
+ }
+
+ TQGridLayout *layout = new TQGridLayout( d->m_frame, 0, 2, 0,
+ KDialog::spacingHint());
+ layout->setColStretch(1, 1);
+
+ TQLabel* label;
+ label = new TQLabel( d->m_frame );
+ label->setText( devices.count() == 0 ?
+ i18n("Device (/dev/fd0):") : // old style
+ i18n("Device:") ); // new style (combobox)
+ layout->addWidget(label, 0, 0);
+
+ device = new TQComboBox( true, d->m_frame, "ComboBox_device" );
+ device->insertStringList( devices );
+ layout->addWidget(device, 0, 1);
+ connect( device, TQT_SIGNAL( activated( int ) ),
+ this, TQT_SLOT( slotActivated( int ) ) );
+
+ readonly = new TQCheckBox( d->m_frame, "CheckBox_readonly" );
+ readonly->setText( i18n("Read only") );
+ layout->addWidget(readonly, 1, 1);
+
+ label = new TQLabel( d->m_frame );
+ label->setText( i18n("File system:") );
+ layout->addWidget(label, 2, 0);
+
+ TQLabel *fileSystem = new TQLabel( d->m_frame );
+ layout->addWidget(fileSystem, 2, 1);
+
+ label = new TQLabel( d->m_frame );
+ label->setText( devices.count()==0 ?
+ i18n("Mount point (/mnt/floppy):") : // old style
+ i18n("Mount point:")); // new style (combobox)
+ layout->addWidget(label, 3, 0);
+
+ mountpoint = new TQLabel( d->m_frame, "LineEdit_mountpoint" );
+
+ layout->addWidget(mountpoint, 3, 1);
+
+ // show disk free
+ d->m_freeSpaceText = new TQLabel(i18n("Free disk space:"), d->m_frame );
+ layout->addWidget(d->m_freeSpaceText, 4, 0);
+
+ d->m_freeSpaceLabel = new TQLabel( d->m_frame );
+ layout->addWidget( d->m_freeSpaceLabel, 4, 1 );
+
+ d->m_freeSpaceBar = new TQProgressBar( d->m_frame, "freeSpaceBar" );
+ layout->addMultiCellWidget(d->m_freeSpaceBar, 5, 5, 0, 1);
+
+ // we show it in the slot when we know the values
+ d->m_freeSpaceText->hide();
+ d->m_freeSpaceLabel->hide();
+ d->m_freeSpaceBar->hide();
+
+ KSeparator* sep = new KSeparator( KSeparator::HLine, d->m_frame);
+ layout->addMultiCellWidget(sep, 6, 6, 0, 1);
+
+ unmounted = new KIconButton( d->m_frame );
+ int bsize = 66 + 2 * unmounted->style().pixelMetric(TQStyle::PM_ButtonMargin);
+ unmounted->setFixedSize(bsize, bsize);
+ unmounted->setIconType(KIcon::Desktop, KIcon::Device);
+ layout->addWidget(unmounted, 7, 0);
+
+ label = new TQLabel( i18n("Unmounted Icon"), d->m_frame );
+ layout->addWidget(label, 7, 1);
+
+ layout->setRowStretch(8, 1);
+
+ TQString path( _props->kurl().path() );
+
+ TQFile f( path );
+ if ( !f.open( IO_ReadOnly ) )
+ return;
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ TQString deviceStr = config.readEntry( "Dev" );
+ TQString mountPointStr = config.readEntry( "MountPoint" );
+ bool ro = config.readBoolEntry( "ReadOnly", false );
+ TQString unmountedStr = config.readEntry( "UnmountIcon" );
+
+ fileSystem->setText( i18n(config.readEntry("FSType").local8Bit()) );
+
+ device->setEditText( deviceStr );
+ if ( !deviceStr.isEmpty() ) {
+ // Set default options for this device (first matching entry)
+ int index = m_devicelist.findIndex(deviceStr);
+ if (index != -1)
+ {
+ //kdDebug(250) << "found it " << index << endl;
+ slotActivated( index );
+ }
+ }
+
+ if ( !mountPointStr.isEmpty() )
+ {
+ mountpoint->setText( mountPointStr );
+ updateInfo();
+ }
+
+ readonly->setChecked( ro );
+
+ if ( unmountedStr.isEmpty() )
+ unmountedStr = KMimeType::defaultMimeTypePtr()->KServiceType::icon(); // default icon
+
+ unmounted->setIcon( unmountedStr );
+
+ connect( device, TQT_SIGNAL( activated( int ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( device, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( readonly, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( unmounted, TQT_SIGNAL( iconChanged( TQString ) ),
+ this, TQT_SIGNAL( changed() ) );
+
+ connect( device, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SLOT( slotDeviceChanged() ) );
+}
+
+KDevicePropsPlugin::~KDevicePropsPlugin()
+{
+ delete d;
+}
+
+// TQString KDevicePropsPlugin::tabName () const
+// {
+// return i18n ("De&vice");
+// }
+
+void KDevicePropsPlugin::updateInfo()
+{
+ // we show it in the slot when we know the values
+ d->m_freeSpaceText->hide();
+ d->m_freeSpaceLabel->hide();
+ d->m_freeSpaceBar->hide();
+
+ if ( !mountpoint->text().isEmpty() )
+ {
+ KDiskFreeSp * job = new KDiskFreeSp;
+ connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
+ const unsigned long&, const TQString& ) ),
+ this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
+ const unsigned long&, const TQString& ) ) );
+
+ job->readDF( mountpoint->text() );
+ }
+}
+
+void KDevicePropsPlugin::slotActivated( int index )
+{
+ // Update mountpoint so that it matches the device that was selected in the combo
+ device->setEditText( m_devicelist[index] );
+ mountpoint->setText( d->mountpointlist[index] );
+
+ updateInfo();
+}
+
+void KDevicePropsPlugin::slotDeviceChanged()
+{
+ // Update mountpoint so that it matches the typed device
+ int index = m_devicelist.findIndex( device->currentText() );
+ if ( index != -1 )
+ mountpoint->setText( d->mountpointlist[index] );
+ else
+ mountpoint->setText( TQString::null );
+
+ updateInfo();
+}
+
+void KDevicePropsPlugin::slotFoundMountPoint( const unsigned long& kBSize,
+ const unsigned long& /*kBUsed*/,
+ const unsigned long& kBAvail,
+ const TQString& )
+{
+ d->m_freeSpaceText->show();
+ d->m_freeSpaceLabel->show();
+
+ int percUsed = 100 - (int)(100.0 * kBAvail / kBSize);
+
+ d->m_freeSpaceLabel->setText(
+ // xgettext:no-c-format -- Don't warn about translating the %1 out of %2 part.
+ i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
+ .arg(TDEIO::convertSizeFromKB(kBAvail))
+ .arg(TDEIO::convertSizeFromKB(kBSize))
+ .arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
+
+ d->m_freeSpaceBar->setProgress(percUsed, 100);
+ d->m_freeSpaceBar->show();
+}
+
+bool KDevicePropsPlugin::supports( KFileItemList _items )
+{
+ if ( _items.count() != 1 )
+ return false;
+ KFileItem * item = _items.first();
+ // check if desktop file
+ if ( !KPropsDlgPlugin::isDesktopFile( item ) )
+ return false;
+ // open file and check type
+ KDesktopFile config( item->url().path(), true /* readonly */ );
+ return config.hasDeviceType();
+}
+
+void KDevicePropsPlugin::applyChanges()
+{
+ TQString path = properties->kurl().path();
+ TQFile f( path );
+ if ( !f.open( IO_ReadWrite ) )
+ {
+ KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have sufficient "
+ "access to write to <b>%1</b>.</qt>").arg(path));
+ return;
+ }
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ config.writeEntry( "Type", TQString::fromLatin1("FSDevice") );
+
+ config.writeEntry( "Dev", device->currentText() );
+ config.writeEntry( "MountPoint", mountpoint->text() );
+
+ config.writeEntry( "UnmountIcon", unmounted->icon() );
+ kdDebug(250) << "unmounted->icon() = " << unmounted->icon() << endl;
+
+ config.writeEntry( "ReadOnly", readonly->isChecked() );
+
+ config.sync();
+}
+
+
+/* ----------------------------------------------------
+ *
+ * KDesktopPropsPlugin
+ *
+ * -------------------------------------------------- */
+
+
+KDesktopPropsPlugin::KDesktopPropsPlugin( KPropertiesDialog *_props )
+ : KPropsDlgPlugin( _props )
+{
+ TQFrame *frame = properties->addPage(i18n("&Application"));
+ TQVBoxLayout *mainlayout = new TQVBoxLayout( frame, 0, KDialog::spacingHint() );
+
+ w = new KPropertiesDesktopBase(frame);
+ mainlayout->addWidget(w);
+
+ bool bKDesktopMode = (TQCString(tqApp->name()) == "kdesktop"); // nasty heh?
+
+ if (bKDesktopMode)
+ {
+ // Hide Name entry
+ w->nameEdit->hide();
+ w->nameLabel->hide();
+ }
+
+ w->pathEdit->setMode(KFile::Directory | KFile::LocalOnly);
+ w->pathEdit->lineEdit()->setAcceptDrops(false);
+
+ connect( w->nameEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
+ connect( w->genNameEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
+ connect( w->commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
+ connect( w->commandEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
+ connect( w->pathEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
+
+ connect( w->browseButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotBrowseExec() ) );
+ connect( w->addFiletypeButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotAddFiletype() ) );
+ connect( w->delFiletypeButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotDelFiletype() ) );
+ connect( w->advancedButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotAdvanced() ) );
+
+ // now populate the page
+ TQString path = _props->kurl().path();
+ TQFile f( path );
+ if ( !f.open( IO_ReadOnly ) )
+ return;
+ f.close();
+
+ KDesktopFile config( path );
+ TQString nameStr = config.readName();
+ TQString genNameStr = config.readGenericName();
+ TQString commentStr = config.readComment();
+ TQString commandStr = config.readPathEntry( "Exec" );
+ if (commandStr.left(12) == "ksystraycmd ")
+ {
+ commandStr.remove(0, 12);
+ m_systrayBool = true;
+ }
+ else
+ m_systrayBool = false;
+
+ m_origCommandStr = commandStr;
+ TQString pathStr = config.readPathEntry( "Path" );
+ m_terminalBool = config.readBoolEntry( "Terminal" );
+ m_terminalOptionStr = config.readEntry( "TerminalOptions" );
+ m_suidBool = config.readBoolEntry( "X-TDE-SubstituteUID" );
+ m_suidUserStr = config.readEntry( "X-TDE-Username" );
+ if( config.hasKey( "StartupNotify" ))
+ m_startupBool = config.readBoolEntry( "StartupNotify", true );
+ else
+ m_startupBool = config.readBoolEntry( "X-TDE-StartupNotify", true );
+ m_dcopServiceType = config.readEntry("X-DCOP-ServiceType").lower();
+
+ TQStringList mimeTypes = config.readListEntry( "MimeType", ';' );
+
+ if ( nameStr.isEmpty() || bKDesktopMode ) {
+ // We'll use the file name if no name is specified
+ // because we _need_ a Name for a valid file.
+ // But let's do it in apply, not here, so that we pick up the right name.
+ setDirty();
+ }
+ if ( !bKDesktopMode )
+ w->nameEdit->setText(nameStr);
+
+ w->genNameEdit->setText( genNameStr );
+ w->commentEdit->setText( commentStr );
+ w->commandEdit->setText( commandStr );
+ w->pathEdit->lineEdit()->setText( pathStr );
+ w->filetypeList->setAllColumnsShowFocus(true);
+
+ KMimeType::Ptr defaultMimetype = KMimeType::defaultMimeTypePtr();
+ for(TQStringList::ConstIterator it = mimeTypes.begin();
+ it != mimeTypes.end(); )
+ {
+ KMimeType::Ptr p = KMimeType::mimeType(*it);
+ ++it;
+ TQString preference;
+ if (it != mimeTypes.end())
+ {
+ bool numeric;
+ (*it).toInt(&numeric);
+ if (numeric)
+ {
+ preference = *it;
+ ++it;
+ }
+ }
+ if (p && (p != defaultMimetype))
+ {
+ new TQListViewItem(w->filetypeList, p->name(), p->comment(), preference);
+ }
+ }
+
+}
+
+KDesktopPropsPlugin::~KDesktopPropsPlugin()
+{
+}
+
+void KDesktopPropsPlugin::slotSelectMimetype()
+{
+ TQListView *w = (TQListView*)sender();
+ TQListViewItem *item = w->firstChild();
+ while(item)
+ {
+ if (item->isSelected())
+ w->setSelected(item, false);
+ item = item->nextSibling();
+ }
+}
+
+void KDesktopPropsPlugin::slotAddFiletype()
+{
+ KDialogBase dlg(w, "KPropertiesMimetypes", true,
+ i18n("Add File Type for %1").arg(properties->kurl().fileName()),
+ KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);
+
+ KGuiItem okItem(i18n("&Add"), TQString::null /* no icon */,
+ i18n("Add the selected file types to\nthe list of supported file types."),
+ i18n("Add the selected file types to\nthe list of supported file types."));
+ dlg.setButtonOK(okItem);
+
+ KPropertiesMimetypeBase *mw = new KPropertiesMimetypeBase(&dlg);
+
+ dlg.setMainWidget(mw);
+
+ {
+ mw->listView->setRootIsDecorated(true);
+ mw->listView->setSelectionMode(TQListView::Extended);
+ mw->listView->setAllColumnsShowFocus(true);
+ mw->listView->setFullWidth(true);
+ mw->listView->setMinimumSize(500,400);
+
+ connect(mw->listView, TQT_SIGNAL(selectionChanged()),
+ this, TQT_SLOT(slotSelectMimetype()));
+ connect(mw->listView, TQT_SIGNAL(doubleClicked( TQListViewItem *, const TQPoint &, int )),
+ &dlg, TQT_SLOT( slotOk()));
+
+ TQMap<TQString,TQListViewItem*> majorMap;
+ TQListViewItem *majorGroup;
+ KMimeType::List mimetypes = KMimeType::allMimeTypes();
+ TQValueListIterator<KMimeType::Ptr> it(mimetypes.begin());
+ for (; it != mimetypes.end(); ++it) {
+ TQString mimetype = (*it)->name();
+ if (mimetype == KMimeType::defaultMimeType())
+ continue;
+ int index = mimetype.find("/");
+ TQString maj = mimetype.left(index);
+ TQString min = mimetype.mid(index+1);
+
+ TQMapIterator<TQString,TQListViewItem*> mit = majorMap.find( maj );
+ if ( mit == majorMap.end() ) {
+ majorGroup = new TQListViewItem( mw->listView, maj );
+ majorGroup->setExpandable(true);
+ mw->listView->setOpen(majorGroup, true);
+ majorMap.insert( maj, majorGroup );
+ }
+ else
+ {
+ majorGroup = mit.data();
+ }
+
+ TQListViewItem *item = new TQListViewItem(majorGroup, min, (*it)->comment());
+ item->setPixmap(0, (*it)->pixmap(KIcon::Small, IconSize(KIcon::Small)));
+ }
+ TQMapIterator<TQString,TQListViewItem*> mit = majorMap.find( "all" );
+ if ( mit != majorMap.end())
+ {
+ mw->listView->setCurrentItem(mit.data());
+ mw->listView->ensureItemVisible(mit.data());
+ }
+ }
+
+ if (dlg.exec() == KDialogBase::Accepted)
+ {
+ KMimeType::Ptr defaultMimetype = KMimeType::defaultMimeTypePtr();
+ TQListViewItem *majorItem = mw->listView->firstChild();
+ while(majorItem)
+ {
+ TQString major = majorItem->text(0);
+
+ TQListViewItem *minorItem = majorItem->firstChild();
+ while(minorItem)
+ {
+ if (minorItem->isSelected())
+ {
+ TQString mimetype = major + "/" + minorItem->text(0);
+ KMimeType::Ptr p = KMimeType::mimeType(mimetype);
+ if (p && (p != defaultMimetype))
+ {
+ mimetype = p->name();
+ bool found = false;
+ TQListViewItem *item = w->filetypeList->firstChild();
+ while (item)
+ {
+ if (mimetype == item->text(0))
+ {
+ found = true;
+ break;
+ }
+ item = item->nextSibling();
+ }
+ if (!found) {
+ new TQListViewItem(w->filetypeList, p->name(), p->comment());
+ emit changed();
+ }
+ }
+ }
+ minorItem = minorItem->nextSibling();
+ }
+
+ majorItem = majorItem->nextSibling();
+ }
+
+ }
+}
+
+void KDesktopPropsPlugin::slotDelFiletype()
+{
+ delete w->filetypeList->currentItem();
+ emit changed();
+}
+
+void KDesktopPropsPlugin::checkCommandChanged()
+{
+ if (KRun::binaryName(w->commandEdit->text(), true) !=
+ KRun::binaryName(m_origCommandStr, true))
+ {
+ TQString m_origCommandStr = w->commandEdit->text();
+ m_dcopServiceType= TQString::null; // Reset
+ }
+}
+
+void KDesktopPropsPlugin::applyChanges()
+{
+ kdDebug(250) << "KDesktopPropsPlugin::applyChanges" << endl;
+ TQString path = properties->kurl().path();
+
+ TQFile f( path );
+
+ if ( !f.open( IO_ReadWrite ) ) {
+ KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
+ "sufficient access to write to <b>%1</b>.</qt>").arg(path));
+ return;
+ }
+ f.close();
+
+ // If the command is changed we reset certain settings that are strongly
+ // coupled to the command.
+ checkCommandChanged();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ config.writeEntry( "Type", TQString::fromLatin1("Application"));
+ config.writeEntry( "Comment", w->commentEdit->text() );
+ config.writeEntry( "Comment", w->commentEdit->text(), true, false, true ); // for compat
+ config.writeEntry( "GenericName", w->genNameEdit->text() );
+ config.writeEntry( "GenericName", w->genNameEdit->text(), true, false, true ); // for compat
+
+ if (m_systrayBool)
+ config.writePathEntry( "Exec", w->commandEdit->text().prepend("ksystraycmd ") );
+ else
+ config.writePathEntry( "Exec", w->commandEdit->text() );
+ config.writePathEntry( "Path", w->pathEdit->lineEdit()->text() );
+
+ // Write mimeTypes
+ TQStringList mimeTypes;
+ for( TQListViewItem *item = w->filetypeList->firstChild();
+ item; item = item->nextSibling() )
+ {
+ TQString preference = item->text(2);
+ mimeTypes.append(item->text(0));
+ if (!preference.isEmpty())
+ mimeTypes.append(preference);
+ }
+
+ config.writeEntry( "MimeType", mimeTypes, ';' );
+
+ if ( !w->nameEdit->isHidden() ) {
+ TQString nameStr = w->nameEdit->text();
+ config.writeEntry( "Name", nameStr );
+ config.writeEntry( "Name", nameStr, true, false, true );
+ }
+
+ config.writeEntry("Terminal", m_terminalBool);
+ config.writeEntry("TerminalOptions", m_terminalOptionStr);
+ config.writeEntry("X-TDE-SubstituteUID", m_suidBool);
+ config.writeEntry("X-TDE-Username", m_suidUserStr);
+ config.writeEntry("StartupNotify", m_startupBool);
+ config.writeEntry("X-DCOP-ServiceType", m_dcopServiceType);
+ config.sync();
+
+ // KSycoca update needed?
+ TQString sycocaPath = TDEGlobal::dirs()->relativeLocation("apps", path);
+ bool updateNeeded = !sycocaPath.startsWith("/");
+ if (!updateNeeded)
+ {
+ sycocaPath = TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path);
+ updateNeeded = !sycocaPath.startsWith("/");
+ }
+ if (updateNeeded)
+ KService::rebuildKSycoca(w);
+}
+
+
+void KDesktopPropsPlugin::slotBrowseExec()
+{
+ KURL f = KFileDialog::getOpenURL( TQString::null,
+ TQString::null, w );
+ if ( f.isEmpty() )
+ return;
+
+ if ( !f.isLocalFile()) {
+ KMessageBox::sorry(w, i18n("Only executables on local file systems are supported."));
+ return;
+ }
+
+ TQString path = f.path();
+ KRun::shellQuote( path );
+ w->commandEdit->setText( path );
+}
+
+void KDesktopPropsPlugin::slotAdvanced()
+{
+ KDialogBase dlg(w, "KPropertiesDesktopAdv", true,
+ i18n("Advanced Options for %1").arg(properties->kurl().fileName()),
+ KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);
+ KPropertiesDesktopAdvBase *w = new KPropertiesDesktopAdvBase(&dlg);
+
+ dlg.setMainWidget(w);
+
+ // If the command is changed we reset certain settings that are strongly
+ // coupled to the command.
+ checkCommandChanged();
+
+ // check to see if we use konsole if not do not add the nocloseonexit
+ // because we don't know how to do this on other terminal applications
+ TDEConfigGroup confGroup( TDEGlobal::config(), TQString::fromLatin1("General") );
+ TQString preferredTerminal = confGroup.readPathEntry("TerminalApplication",
+ TQString::fromLatin1("konsole"));
+
+ bool terminalCloseBool = false;
+
+ if (preferredTerminal == "konsole")
+ {
+ terminalCloseBool = (m_terminalOptionStr.contains( "--noclose" ) > 0);
+ w->terminalCloseCheck->setChecked(terminalCloseBool);
+ m_terminalOptionStr.replace( "--noclose", "");
+ }
+ else
+ {
+ w->terminalCloseCheck->hide();
+ }
+
+ w->terminalCheck->setChecked(m_terminalBool);
+ w->terminalEdit->setText(m_terminalOptionStr);
+ w->terminalCloseCheck->setEnabled(m_terminalBool);
+ w->terminalEdit->setEnabled(m_terminalBool);
+ w->terminalEditLabel->setEnabled(m_terminalBool);
+
+ w->suidCheck->setChecked(m_suidBool);
+ w->suidEdit->setText(m_suidUserStr);
+ w->suidEdit->setEnabled(m_suidBool);
+ w->suidEditLabel->setEnabled(m_suidBool);
+
+ w->startupInfoCheck->setChecked(m_startupBool);
+ w->systrayCheck->setChecked(m_systrayBool);
+
+ if (m_dcopServiceType == "unique")
+ w->dcopCombo->setCurrentItem(2);
+ else if (m_dcopServiceType == "multi")
+ w->dcopCombo->setCurrentItem(1);
+ else if (m_dcopServiceType == "wait")
+ w->dcopCombo->setCurrentItem(3);
+ else
+ w->dcopCombo->setCurrentItem(0);
+
+ // Provide username completion up to 1000 users.
+ KCompletion *kcom = new KCompletion;
+ kcom->setOrder(KCompletion::Sorted);
+ struct passwd *pw;
+ int i, maxEntries = 1000;
+ setpwent();
+ for (i=0; ((pw = getpwent()) != 0L) && (i < maxEntries); i++)
+ kcom->addItem(TQString::fromLatin1(pw->pw_name));
+ endpwent();
+ if (i < maxEntries)
+ {
+ w->suidEdit->setCompletionObject(kcom, true);
+ w->suidEdit->setAutoDeleteCompletionObject( true );
+ w->suidEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
+ }
+ else
+ {
+ delete kcom;
+ }
+
+ connect( w->terminalEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( w->terminalCloseCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( w->terminalCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( w->suidCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( w->suidEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( w->startupInfoCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( w->systrayCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( w->dcopCombo, TQT_SIGNAL( highlighted( int ) ),
+ this, TQT_SIGNAL( changed() ) );
+
+ if ( dlg.exec() == TQDialog::Accepted )
+ {
+ m_terminalOptionStr = w->terminalEdit->text().stripWhiteSpace();
+ m_terminalBool = w->terminalCheck->isChecked();
+ m_suidBool = w->suidCheck->isChecked();
+ m_suidUserStr = w->suidEdit->text().stripWhiteSpace();
+ m_startupBool = w->startupInfoCheck->isChecked();
+ m_systrayBool = w->systrayCheck->isChecked();
+
+ if (w->terminalCloseCheck->isChecked())
+ {
+ m_terminalOptionStr.append(" --noclose");
+ }
+
+ switch(w->dcopCombo->currentItem())
+ {
+ case 1: m_dcopServiceType = "multi"; break;
+ case 2: m_dcopServiceType = "unique"; break;
+ case 3: m_dcopServiceType = "wait"; break;
+ default: m_dcopServiceType = "none"; break;
+ }
+ }
+}
+
+bool KDesktopPropsPlugin::supports( KFileItemList _items )
+{
+ if ( _items.count() != 1 )
+ return false;
+ KFileItem * item = _items.first();
+ // check if desktop file
+ if ( !KPropsDlgPlugin::isDesktopFile( item ) )
+ return false;
+ // open file and check type
+ KDesktopFile config( item->url().path(), true /* readonly */ );
+ return config.hasApplicationType() && kapp->authorize("run_desktop_files") && kapp->authorize("shell_access");
+}
+
+void KPropertiesDialog::virtual_hook( int id, void* data )
+{ KDialogBase::virtual_hook( id, data ); }
+
+void KPropsDlgPlugin::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+
+
+
+
+/**
+ * The following code is obsolete and only kept for binary compatibility
+ * To be removed in KDE 4
+ */
+
+class KExecPropsPlugin::KExecPropsPluginPrivate
+{
+public:
+ KExecPropsPluginPrivate()
+ {
+ }
+ ~KExecPropsPluginPrivate()
+ {
+ }
+
+ TQFrame *m_frame;
+ TQCheckBox *nocloseonexitCheck;
+};
+
+KExecPropsPlugin::KExecPropsPlugin( KPropertiesDialog *_props )
+ : KPropsDlgPlugin( _props )
+{
+ d = new KExecPropsPluginPrivate;
+ d->m_frame = properties->addPage(i18n("E&xecute"));
+ TQVBoxLayout * mainlayout = new TQVBoxLayout( d->m_frame, 0,
+ KDialog::spacingHint());
+
+ // Now the widgets in the top layout
+
+ TQLabel* l;
+ l = new TQLabel( i18n( "Comman&d:" ), d->m_frame );
+ mainlayout->addWidget(l);
+
+ TQHBoxLayout * hlayout;
+ hlayout = new TQHBoxLayout(KDialog::spacingHint());
+ mainlayout->addLayout(hlayout);
+
+ execEdit = new KLineEdit( d->m_frame );
+ TQWhatsThis::add(execEdit,i18n(
+ "Following the command, you can have several place holders which will be replaced "
+ "with the actual values when the actual program is run:\n"
+ "%f - a single file name\n"
+ "%F - a list of files; use for applications that can open several local files at once\n"
+ "%u - a single URL\n"
+ "%U - a list of URLs\n"
+ "%d - the folder of the file to open\n"
+ "%D - a list of folders\n"
+ "%i - the icon\n"
+ "%m - the mini-icon\n"
+ "%c - the caption"));
+ hlayout->addWidget(execEdit, 1);
+
+ l->setBuddy( execEdit );
+
+ execBrowse = new TQPushButton( d->m_frame );
+ execBrowse->setText( i18n("&Browse...") );
+ hlayout->addWidget(execBrowse);
+
+ // The groupbox about swallowing
+ TQGroupBox* tmpQGroupBox;
+ tmpQGroupBox = new TQGroupBox( i18n("Panel Embedding"), d->m_frame );
+ tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );
+
+ mainlayout->addWidget(tmpQGroupBox);
+
+ TQGridLayout *grid = new TQGridLayout(tmpQGroupBox->layout(), 2, 2);
+ grid->setSpacing( KDialog::spacingHint() );
+ grid->setColStretch(1, 1);
+
+ l = new TQLabel( i18n( "&Execute on click:" ), tmpQGroupBox );
+ grid->addWidget(l, 0, 0);
+
+ swallowExecEdit = new KLineEdit( tmpQGroupBox );
+ grid->addWidget(swallowExecEdit, 0, 1);
+
+ l->setBuddy( swallowExecEdit );
+
+ l = new TQLabel( i18n( "&Window title:" ), tmpQGroupBox );
+ grid->addWidget(l, 1, 0);
+
+ swallowTitleEdit = new KLineEdit( tmpQGroupBox );
+ grid->addWidget(swallowTitleEdit, 1, 1);
+
+ l->setBuddy( swallowTitleEdit );
+
+ // The groupbox about run in terminal
+
+ tmpQGroupBox = new TQGroupBox( d->m_frame );
+ tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );
+
+ mainlayout->addWidget(tmpQGroupBox);
+
+ grid = new TQGridLayout(tmpQGroupBox->layout(), 3, 2);
+ grid->setSpacing( KDialog::spacingHint() );
+ grid->setColStretch(1, 1);
+
+ terminalCheck = new TQCheckBox( tmpQGroupBox );
+ terminalCheck->setText( i18n("&Run in terminal") );
+ grid->addMultiCellWidget(terminalCheck, 0, 0, 0, 1);
+
+ // check to see if we use konsole if not do not add the nocloseonexit
+ // because we don't know how to do this on other terminal applications
+ TDEConfigGroup confGroup( TDEGlobal::config(), TQString::fromLatin1("General") );
+ TQString preferredTerminal = confGroup.readPathEntry("TerminalApplication",
+ TQString::fromLatin1("konsole"));
+
+ int posOptions = 1;
+ d->nocloseonexitCheck = 0L;
+ if (preferredTerminal == "konsole")
+ {
+ posOptions = 2;
+ d->nocloseonexitCheck = new TQCheckBox( tmpQGroupBox );
+ d->nocloseonexitCheck->setText( i18n("Do not &close when command exits") );
+ grid->addMultiCellWidget(d->nocloseonexitCheck, 1, 1, 0, 1);
+ }
+
+ terminalLabel = new TQLabel( i18n( "&Terminal options:" ), tmpQGroupBox );
+ grid->addWidget(terminalLabel, posOptions, 0);
+
+ terminalEdit = new KLineEdit( tmpQGroupBox );
+ grid->addWidget(terminalEdit, posOptions, 1);
+
+ terminalLabel->setBuddy( terminalEdit );
+
+ // The groupbox about run with substituted uid.
+
+ tmpQGroupBox = new TQGroupBox( d->m_frame );
+ tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );
+
+ mainlayout->addWidget(tmpQGroupBox);
+
+ grid = new TQGridLayout(tmpQGroupBox->layout(), 2, 2);
+ grid->setSpacing(KDialog::spacingHint());
+ grid->setColStretch(1, 1);
+
+ suidCheck = new TQCheckBox(tmpQGroupBox);
+ suidCheck->setText(i18n("Ru&n as a different user"));
+ grid->addMultiCellWidget(suidCheck, 0, 0, 0, 1);
+
+ suidLabel = new TQLabel(i18n( "&Username:" ), tmpQGroupBox);
+ grid->addWidget(suidLabel, 1, 0);
+
+ suidEdit = new KLineEdit(tmpQGroupBox);
+ grid->addWidget(suidEdit, 1, 1);
+
+ suidLabel->setBuddy( suidEdit );
+
+ mainlayout->addStretch(1);
+
+ // now populate the page
+ TQString path = _props->kurl().path();
+ TQFile f( path );
+ if ( !f.open( IO_ReadOnly ) )
+ return;
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDollarExpansion( false );
+ config.setDesktopGroup();
+ execStr = config.readPathEntry( "Exec" );
+ swallowExecStr = config.readPathEntry( "SwallowExec" );
+ swallowTitleStr = config.readEntry( "SwallowTitle" );
+ termBool = config.readBoolEntry( "Terminal" );
+ termOptionsStr = config.readEntry( "TerminalOptions" );
+ suidBool = config.readBoolEntry( "X-TDE-SubstituteUID" );
+ suidUserStr = config.readEntry( "X-TDE-Username" );
+
+ if ( !swallowExecStr.isNull() )
+ swallowExecEdit->setText( swallowExecStr );
+ if ( !swallowTitleStr.isNull() )
+ swallowTitleEdit->setText( swallowTitleStr );
+
+ if ( !execStr.isNull() )
+ execEdit->setText( execStr );
+
+ if ( d->nocloseonexitCheck )
+ {
+ d->nocloseonexitCheck->setChecked( (termOptionsStr.contains( "--noclose" ) > 0) );
+ termOptionsStr.replace( "--noclose", "");
+ }
+ if ( !termOptionsStr.isNull() )
+ terminalEdit->setText( termOptionsStr );
+
+ terminalCheck->setChecked( termBool );
+ enableCheckedEdit();
+
+ suidCheck->setChecked( suidBool );
+ suidEdit->setText( suidUserStr );
+ enableSuidEdit();
+
+ // Provide username completion up to 1000 users.
+ KCompletion *kcom = new KCompletion;
+ kcom->setOrder(KCompletion::Sorted);
+ struct passwd *pw;
+ int i, maxEntries = 1000;
+ setpwent();
+ for (i=0; ((pw = getpwent()) != 0L) && (i < maxEntries); i++)
+ kcom->addItem(TQString::fromLatin1(pw->pw_name));
+ endpwent();
+ if (i < maxEntries)
+ {
+ suidEdit->setCompletionObject(kcom, true);
+ suidEdit->setAutoDeleteCompletionObject( true );
+ suidEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
+ }
+ else
+ {
+ delete kcom;
+ }
+
+ connect( swallowExecEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( swallowTitleEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( execEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( terminalEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ if (d->nocloseonexitCheck)
+ connect( d->nocloseonexitCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( terminalCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( suidCheck, TQT_SIGNAL( toggled( bool ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( suidEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+
+ connect( execBrowse, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotBrowseExec() ) );
+ connect( terminalCheck, TQT_SIGNAL( clicked() ), this, TQT_SLOT( enableCheckedEdit() ) );
+ connect( suidCheck, TQT_SIGNAL( clicked() ), this, TQT_SLOT( enableSuidEdit() ) );
+
+}
+
+KExecPropsPlugin::~KExecPropsPlugin()
+{
+ delete d;
+}
+
+void KExecPropsPlugin::enableCheckedEdit()
+{
+ bool checked = terminalCheck->isChecked();
+ terminalLabel->setEnabled( checked );
+ if (d->nocloseonexitCheck)
+ d->nocloseonexitCheck->setEnabled( checked );
+ terminalEdit->setEnabled( checked );
+}
+
+void KExecPropsPlugin::enableSuidEdit()
+{
+ bool checked = suidCheck->isChecked();
+ suidLabel->setEnabled( checked );
+ suidEdit->setEnabled( checked );
+}
+
+bool KExecPropsPlugin::supports( KFileItemList _items )
+{
+ if ( _items.count() != 1 )
+ return false;
+ KFileItem * item = _items.first();
+ // check if desktop file
+ if ( !KPropsDlgPlugin::isDesktopFile( item ) )
+ return false;
+ // open file and check type
+ KDesktopFile config( item->url().path(), true /* readonly */ );
+ return config.hasApplicationType() && kapp->authorize("run_desktop_files") && kapp->authorize("shell_access");
+}
+
+void KExecPropsPlugin::applyChanges()
+{
+ kdDebug(250) << "KExecPropsPlugin::applyChanges" << endl;
+ TQString path = properties->kurl().path();
+
+ TQFile f( path );
+
+ if ( !f.open( IO_ReadWrite ) ) {
+ KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
+ "sufficient access to write to <b>%1</b>.</qt>").arg(path));
+ return;
+ }
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ config.writeEntry( "Type", TQString::fromLatin1("Application"));
+ config.writePathEntry( "Exec", execEdit->text() );
+ config.writePathEntry( "SwallowExec", swallowExecEdit->text() );
+ config.writeEntry( "SwallowTitle", swallowTitleEdit->text() );
+ config.writeEntry( "Terminal", terminalCheck->isChecked() );
+ TQString temp = terminalEdit->text();
+ if (d->nocloseonexitCheck )
+ if ( d->nocloseonexitCheck->isChecked() )
+ temp += TQString::fromLatin1("--noclose ");
+ temp = temp.stripWhiteSpace();
+ config.writeEntry( "TerminalOptions", temp );
+ config.writeEntry( "X-TDE-SubstituteUID", suidCheck->isChecked() );
+ config.writeEntry( "X-TDE-Username", suidEdit->text() );
+}
+
+
+void KExecPropsPlugin::slotBrowseExec()
+{
+ KURL f = KFileDialog::getOpenURL( TQString::null,
+ TQString::null, d->m_frame );
+ if ( f.isEmpty() )
+ return;
+
+ if ( !f.isLocalFile()) {
+ KMessageBox::sorry(d->m_frame, i18n("Only executables on local file systems are supported."));
+ return;
+ }
+
+ TQString path = f.path();
+ KRun::shellQuote( path );
+ execEdit->setText( path );
+}
+
+class TDEApplicationPropsPlugin::TDEApplicationPropsPluginPrivate
+{
+public:
+ TDEApplicationPropsPluginPrivate()
+ {
+ m_kdesktopMode = TQCString(tqApp->name()) == "kdesktop"; // nasty heh?
+ }
+ ~TDEApplicationPropsPluginPrivate()
+ {
+ }
+
+ TQFrame *m_frame;
+ bool m_kdesktopMode;
+};
+
+TDEApplicationPropsPlugin::TDEApplicationPropsPlugin( KPropertiesDialog *_props )
+ : KPropsDlgPlugin( _props )
+{
+ d = new TDEApplicationPropsPluginPrivate;
+ d->m_frame = properties->addPage(i18n("&Application"));
+ TQVBoxLayout *toplayout = new TQVBoxLayout( d->m_frame, 0, KDialog::spacingHint());
+
+ TQIconSet iconSet;
+ TQPixmap pixMap;
+
+ addExtensionButton = new TQPushButton( TQString::null, d->m_frame );
+ iconSet = SmallIconSet( "back" );
+ addExtensionButton->setIconSet( iconSet );
+ pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
+ addExtensionButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
+ connect( addExtensionButton, TQT_SIGNAL( clicked() ),
+ TQT_SLOT( slotAddExtension() ) );
+
+ delExtensionButton = new TQPushButton( TQString::null, d->m_frame );
+ iconSet = SmallIconSet( "forward" );
+ delExtensionButton->setIconSet( iconSet );
+ delExtensionButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
+ connect( delExtensionButton, TQT_SIGNAL( clicked() ),
+ TQT_SLOT( slotDelExtension() ) );
+
+ TQLabel *l;
+
+ TQGridLayout *grid = new TQGridLayout(2, 2);
+ grid->setColStretch(1, 1);
+ toplayout->addLayout(TQT_TQLAYOUT(grid));
+
+ if ( d->m_kdesktopMode )
+ {
+ // in kdesktop the name field comes from the first tab
+ nameEdit = 0L;
+ }
+ else
+ {
+ l = new TQLabel(i18n("Name:"), d->m_frame, "Label_4" );
+ grid->addWidget(l, 0, 0);
+
+ nameEdit = new KLineEdit( d->m_frame, "LineEdit_3" );
+ grid->addWidget(nameEdit, 0, 1);
+ }
+
+ l = new TQLabel(i18n("Description:"), d->m_frame, "Label_5" );
+ grid->addWidget(l, 1, 0);
+
+ genNameEdit = new KLineEdit( d->m_frame, "LineEdit_4" );
+ grid->addWidget(genNameEdit, 1, 1);
+
+ l = new TQLabel(i18n("Comment:"), d->m_frame, "Label_3" );
+ grid->addWidget(l, 2, 0);
+
+ commentEdit = new KLineEdit( d->m_frame, "LineEdit_2" );
+ grid->addWidget(commentEdit, 2, 1);
+
+ l = new TQLabel(i18n("File types:"), d->m_frame);
+ toplayout->addWidget(l, 0, AlignLeft);
+
+ grid = new TQGridLayout(4, 3);
+ grid->setColStretch(0, 1);
+ grid->setColStretch(2, 1);
+ grid->setRowStretch( 0, 1 );
+ grid->setRowStretch( 3, 1 );
+ toplayout->addLayout(TQT_TQLAYOUT(grid), 2);
+
+ extensionsList = new TQListBox( d->m_frame );
+ extensionsList->setSelectionMode( TQListBox::Extended );
+ grid->addMultiCellWidget(extensionsList, 0, 3, 0, 0);
+
+ grid->addWidget(addExtensionButton, 1, 1);
+ grid->addWidget(delExtensionButton, 2, 1);
+
+ availableExtensionsList = new TQListBox( d->m_frame );
+ availableExtensionsList->setSelectionMode( TQListBox::Extended );
+ grid->addMultiCellWidget(availableExtensionsList, 0, 3, 2, 2);
+
+ TQString path = properties->kurl().path() ;
+ TQFile f( path );
+ if ( !f.open( IO_ReadOnly ) )
+ return;
+ f.close();
+
+ KDesktopFile config( path );
+ TQString commentStr = config.readComment();
+ TQString genNameStr = config.readGenericName();
+
+ TQStringList selectedTypes = config.readListEntry( "ServiceTypes" );
+ // For compatibility with KDE 1.x
+ selectedTypes += config.readListEntry( "MimeType", ';' );
+
+ TQString nameStr = config.readName();
+ if ( nameStr.isEmpty() || d->m_kdesktopMode ) {
+ // We'll use the file name if no name is specified
+ // because we _need_ a Name for a valid file.
+ // But let's do it in apply, not here, so that we pick up the right name.
+ setDirty();
+ }
+
+ commentEdit->setText( commentStr );
+ genNameEdit->setText( genNameStr );
+ if ( nameEdit )
+ nameEdit->setText( nameStr );
+
+ selectedTypes.sort();
+ TQStringList::Iterator sit = selectedTypes.begin();
+ for( ; sit != selectedTypes.end(); ++sit ) {
+ if ( !((*sit).isEmpty()) )
+ extensionsList->insertItem( *sit );
+ }
+
+ KMimeType::List mimeTypes = KMimeType::allMimeTypes();
+ TQValueListIterator<KMimeType::Ptr> it2 = mimeTypes.begin();
+ for ( ; it2 != mimeTypes.end(); ++it2 )
+ addMimeType ( (*it2)->name() );
+
+ updateButton();
+
+ connect( extensionsList, TQT_SIGNAL( highlighted( int ) ),
+ this, TQT_SLOT( updateButton() ) );
+ connect( availableExtensionsList, TQT_SIGNAL( highlighted( int ) ),
+ this, TQT_SLOT( updateButton() ) );
+
+ connect( addExtensionButton, TQT_SIGNAL( clicked() ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( delExtensionButton, TQT_SIGNAL( clicked() ),
+ this, TQT_SIGNAL( changed() ) );
+ if ( nameEdit )
+ connect( nameEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( genNameEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( availableExtensionsList, TQT_SIGNAL( selected( int ) ),
+ this, TQT_SIGNAL( changed() ) );
+ connect( extensionsList, TQT_SIGNAL( selected( int ) ),
+ this, TQT_SIGNAL( changed() ) );
+}
+
+TDEApplicationPropsPlugin::~TDEApplicationPropsPlugin()
+{
+ delete d;
+}
+
+// TQString TDEApplicationPropsPlugin::tabName () const
+// {
+// return i18n ("&Application");
+// }
+
+void TDEApplicationPropsPlugin::updateButton()
+{
+ addExtensionButton->setEnabled(availableExtensionsList->currentItem()>-1);
+ delExtensionButton->setEnabled(extensionsList->currentItem()>-1);
+}
+
+void TDEApplicationPropsPlugin::addMimeType( const TQString & name )
+{
+ // Add a mimetype to the list of available mime types if not in the extensionsList
+
+ bool insert = true;
+
+ for ( uint i = 0; i < extensionsList->count(); i++ )
+ if ( extensionsList->text( i ) == name )
+ insert = false;
+
+ if ( insert )
+ {
+ availableExtensionsList->insertItem( name );
+ availableExtensionsList->sort();
+ }
+}
+
+bool TDEApplicationPropsPlugin::supports( KFileItemList _items )
+{
+ // same constraints as KExecPropsPlugin : desktop file with Type = Application
+ return KExecPropsPlugin::supports( _items );
+}
+
+void TDEApplicationPropsPlugin::applyChanges()
+{
+ TQString path = properties->kurl().path();
+
+ TQFile f( path );
+
+ if ( !f.open( IO_ReadWrite ) ) {
+ KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not "
+ "have sufficient access to write to <b>%1</b>.</qt>").arg(path));
+ return;
+ }
+ f.close();
+
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ config.writeEntry( "Type", TQString::fromLatin1("Application"));
+ config.writeEntry( "Comment", commentEdit->text() );
+ config.writeEntry( "Comment", commentEdit->text(), true, false, true ); // for compat
+ config.writeEntry( "GenericName", genNameEdit->text() );
+ config.writeEntry( "GenericName", genNameEdit->text(), true, false, true ); // for compat
+
+ TQStringList selectedTypes;
+ for ( uint i = 0; i < extensionsList->count(); i++ )
+ selectedTypes.append( extensionsList->text( i ) );
+
+ config.writeEntry( "MimeType", selectedTypes, ';' );
+ config.writeEntry( "ServiceTypes", "" );
+ // hmm, actually it should probably be the contrary (but see also typeslistitem.cpp)
+
+ TQString nameStr = nameEdit ? nameEdit->text() : TQString::null;
+ if ( nameStr.isEmpty() ) // nothing entered, or widget not existing at all (kdesktop mode)
+ nameStr = nameFromFileName(properties->kurl().fileName());
+
+ config.writeEntry( "Name", nameStr );
+ config.writeEntry( "Name", nameStr, true, false, true );
+
+ config.sync();
+}
+
+void TDEApplicationPropsPlugin::slotAddExtension()
+{
+ TQListBoxItem *item = availableExtensionsList->firstItem();
+ TQListBoxItem *nextItem;
+
+ while ( item )
+ {
+ nextItem = item->next();
+
+ if ( item->isSelected() )
+ {
+ extensionsList->insertItem( item->text() );
+ availableExtensionsList->removeItem( availableExtensionsList->index( item ) );
+ }
+
+ item = nextItem;
+ }
+
+ extensionsList->sort();
+ updateButton();
+}
+
+void TDEApplicationPropsPlugin::slotDelExtension()
+{
+ TQListBoxItem *item = extensionsList->firstItem();
+ TQListBoxItem *nextItem;
+
+ while ( item )
+ {
+ nextItem = item->next();
+
+ if ( item->isSelected() )
+ {
+ availableExtensionsList->insertItem( item->text() );
+ extensionsList->removeItem( extensionsList->index( item ) );
+ }
+
+ item = nextItem;
+ }
+
+ availableExtensionsList->sort();
+ updateButton();
+}
+
+
+
+#include "kpropertiesdialog.moc"
diff --git a/tdeio/tdefile/kpropertiesdialog.h b/tdeio/tdefile/kpropertiesdialog.h
new file mode 100644
index 000000000..db89487a8
--- /dev/null
+++ b/tdeio/tdefile/kpropertiesdialog.h
@@ -0,0 +1,918 @@
+/* This file is part of the KDE project
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+ Copyright (c) 1999, 2000 Preston Brown <pbrown@kde.org>
+ Copyright (c) 2000 Simon Hausmann <hausmann@kde.org>
+ Copyright (c) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+/*
+ * This file holds the definitions for all classes used to
+ * display a properties dialog.
+ */
+
+#ifndef __propsdlg_h
+#define __propsdlg_h
+
+#include <tqstring.h>
+#include <tqptrlist.h>
+
+#include <kdemacros.h>
+#include <kurl.h>
+#include <tdefileitem.h>
+#include <kdialogbase.h>
+
+class TQLineEdit;
+class TQCheckBox;
+class TQPushButton;
+class KLineEdit;
+class KURLRequester;
+class TQButton;
+class KIconButton;
+class KPropsDlgPlugin;
+class TQComboBox;
+
+#define KPropsPage KPropsDlgPlugin
+
+namespace TDEIO { class Job; }
+
+/**
+ * The main properties dialog class.
+ * A Properties Dialog is a dialog which displays various information
+ * about a particular file or URL, or several files or URLs.
+ * This main class holds various related classes, which are instantiated in
+ * the form of tab entries in the tabbed dialog that this class provides.
+ * The various tabs themselves will let the user view, and sometimes change,
+ * information about the file or URL.
+ *
+ * \image html kpropertiesdialog.png "Typical KProperties Dialog"
+ *
+ * This class must be created with (void)new KPropertiesDialog(...)
+ * It will take care of deleting itself.
+ *
+ * If you are looking for more flexibility, see KFileMetaInfo and
+ * KFileMetaInfoWidget.
+ */
+class TDEIO_EXPORT KPropertiesDialog : public KDialogBase
+{
+ Q_OBJECT
+
+public:
+
+ /**
+ * Determine whether there are any property pages available for the
+ * given file items.
+ * @param _items the list of items to check.
+ * @return true if there are any property pages, otherwise false.
+ */
+ static bool canDisplay( KFileItemList _items );
+
+ /**
+ * Brings up a Properties dialog, as shown above.
+ * This is the normal constructor for
+ * file-manager type applications, where you have a KFileItem instance
+ * to work with. Normally you will use this
+ * method rather than the one below.
+ *
+ * @param item file item whose properties should be displayed.
+ * @param parent is the parent of the dialog widget.
+ * @param name is the internal name.
+ * @param modal tells the dialog whether it should be modal.
+ * @param autoShow tells the dialog whether it should show itself automatically.
+ */
+ KPropertiesDialog( KFileItem * item,
+ TQWidget* parent = 0L, const char* name = 0L,
+ bool modal = false, bool autoShow = true);
+
+ /**
+ * \overload
+ *
+ * You use this constructor for cases where you have a number of items,
+ * rather than a single item. Be careful which methods you use
+ * when passing a list of files or URLs, since some of them will only
+ * work on the first item in a list.
+ *
+ * @param _items list of file items whose properties should be displayed.
+ * @param parent is the parent of the dialog widget.
+ * @param name is the internal name.
+ * @param modal tells the dialog whether it should be modal.
+ * @param autoShow tells the dialog whether it should show itself automatically.
+ */
+ KPropertiesDialog( KFileItemList _items,
+ TQWidget *parent = 0L, const char* name = 0L,
+ bool modal = false, bool autoShow = true);
+
+#ifndef KDE_NO_COMPAT
+ /**
+ * @deprecated You should use the following constructor instead of this one.
+ * The only change that is required is to delete the _mode argument.
+ *
+ * @param _url the URL whose properties should be displayed
+ * @param _mode unused.
+ * @param parent is the parent of the dialog widget.
+ * @param name is the internal name.
+ * @param modal tells the dialog whether it should be modal.
+ * @param autoShow tells the dialog whether it should show itself automatically. */
+ KPropertiesDialog( const KURL& _url, mode_t _mode,
+ TQWidget* parent = 0L, const char* name = 0L,
+ bool modal = false, bool autoShow = true) KDE_DEPRECATED;
+#endif
+
+ /**
+ * Brings up a Properties dialog. Convenience constructor for
+ * non-file-manager applications, where you have a KURL rather than a
+ * KFileItem or KFileItemList.
+ *
+ * @param _url the URL whose properties should be displayed
+ * @param parent is the parent of the dialog widget.
+ * @param name is the internal name.
+ * @param modal tells the dialog whether it should be modal.
+ * IMPORTANT: This constructor, together with modal=true, leads to a grave
+ * display bug (due to TDEIO::stat() being run before the dialog has all the
+ * necessary information). Do not use this combination for now.
+ * For local files with a known mimetype, simply create a KFileItem and pass
+ * it to the other constructor.
+ *
+ * @param autoShow tells the dialog whethr it should show itself automatically.
+ */
+ KPropertiesDialog( const KURL& _url,
+ TQWidget* parent = 0L, const char* name = 0L,
+ bool modal = false, bool autoShow = true);
+
+ /**
+ * Creates a properties dialog for a new .desktop file (whose name
+ * is not known yet), based on a template. Special constructor for
+ * "File / New" in file-manager type applications.
+ *
+ * @param _tempUrl template used for reading only
+ * @param _currentDir directory where the file will be written to
+ * @param _defaultName something to put in the name field,
+ * like mimetype.desktop
+ * @param parent is the parent of the dialog widget.
+ * @param name is the internal name.
+ * @param modal tells the dialog whether it should be modal.
+ * @param autoShow tells the dialog whethr it should show itself automatically.
+ */
+ KPropertiesDialog( const KURL& _tempUrl, const KURL& _currentDir,
+ const TQString& _defaultName,
+ TQWidget* parent = 0L, const char* name = 0L,
+ bool modal = false, bool autoShow = true);
+
+ /**
+ * Creates an empty properties dialog (for applications that want use
+ * a standard dialog, but for things not doable via the plugin-mechanism).
+ *
+ * @param title is the string display as the "filename" in the caption of the dialog.
+ * @param parent is the parent of the dialog widget.
+ * @param name is the internal name.
+ * @param modal tells the dialog whether it should be modal.
+ */
+ KPropertiesDialog (const TQString& title,
+ TQWidget* parent = 0L, const char* name = 0L, bool modal = false);
+
+ /**
+ * Cleans up the properties dialog and frees any associated resources,
+ * including the dialog itself. Note that when a properties dialog is
+ * closed it cleans up and deletes itself.
+ */
+ virtual ~KPropertiesDialog();
+
+ /**
+ * Immediately displays a Properties dialog using constructor with
+ * the same parameters.
+ * On MS Windows, if @p item points to a local file, native (non modal) property
+ * dialog is displayed (@p parent and @p modal are ignored in this case).
+ *
+ * @return true on succesfull dialog displaying (can be false on win32).
+ * @since 3.4
+ */
+ static bool showDialog(KFileItem* item, TQWidget* parent = 0,
+ const char* name = 0, bool modal = false);
+
+ /**
+ * Immediately displays a Properties dialog using constructor with
+ * the same parameters.
+ * On MS Windows, if @p _url points to a local file, native (non modal) property
+ * dialog is displayed (@p parent and @p modal are ignored in this case).
+ *
+ * @return true on succesfull dialog displaying (can be false on win32).
+ * @since 3.4
+ */
+ static bool showDialog(const KURL& _url, TQWidget* parent = 0,
+ const char* name = 0, bool modal = false);
+
+ /**
+ * Immediately displays a Properties dialog using constructor with
+ * the same parameters.
+ * On MS Windows, if @p _items has one element and this element points
+ * to a local file, native (non modal) property dialog is displayed
+ * (@p parent and @p modal are ignored in this case).
+ *
+ * @return true on succesfull dialog displaying (can be false on win32).
+ * @since 3.4
+ */
+ static bool showDialog(const KFileItemList& _items, TQWidget* parent = 0,
+ const char* name = 0, bool modal = false);
+
+ /**
+ * Adds a "3rd party" properties plugin to the dialog. Useful
+ * for extending the properties mechanism.
+ *
+ * To create a new plugin type, inherit from the base class KPropsDlgPlugin
+ * and implement all the methods. If you define a service .desktop file
+ * for your plugin, you do not need to call insertPlugin().
+ *
+ * @param plugin is a pointer to the KPropsDlgPlugin. The Properties
+ * dialog will do destruction for you. The KPropsDlgPlugin \b must
+ * have been created with the KPropertiesDialog as its parent.
+ * @see KPropsDlgPlugin
+ */
+ void insertPlugin (KPropsDlgPlugin *plugin);
+
+ /**
+ * The URL of the file that has its properties being displayed.
+ * This is only valid if the KPropertiesDialog was created/shown
+ * for one file or URL.
+ *
+ * @return a parsed URL.
+ */
+ const KURL& kurl() const { return m_singleUrl; }
+
+ /**
+ * @return the file item for which the dialog is shown
+ *
+ * Warning: this method returns the first item of the list.
+ * This means that you should use this only if you are sure the dialog is used
+ * for a single item. Otherwise, you probably want items() instead.
+ */
+ KFileItem *item() { return m_items.first(); }
+
+ /**
+ * @return the items for which the dialog is shown
+ */
+ KFileItemList items() const { return m_items; }
+
+ /**
+ * @return a pointer to the dialog
+ * @deprecated KPropertiesDialog directly inherits from KDialogBase, so use \a this instead
+ */
+ KDE_DEPRECATED KDialogBase* dialog() { return this; }
+ /**
+ * @return a pointer to the dialog
+ * @deprecated KPropertiesDialog directly inherits from KDialogBase, so use \a this instead
+ */
+ KDE_DEPRECATED const KDialogBase* dialog() const { return this; }
+
+ /**
+ * If the dialog is being built from a template, this method
+ * returns the current directory. If no template, it returns TQString::null.
+ * See the template form of the constructor.
+ *
+ * @return the current directory or TQString::null
+ */
+ const KURL& currentDir() const { return m_currentDir; }
+
+ /**
+ * If the dialog is being built from a template, this method
+ * returns the default name. If no template, it returns TQString::null.
+ * See the template form of the constructor.
+ * @return the default name or TQString::null
+ */
+ const TQString& defaultName() const { return m_defaultName; }
+
+ /**
+ * Updates the item URL (either called by rename or because
+ * a global apps/mimelnk desktop file is being saved)
+ * Can only be called if the dialog applies to a single file or URL.
+ * @param _newUrl the new URL
+ */
+ void updateUrl( const KURL& _newUrl );
+
+ /**
+ * Renames the item to the specified name. This can only be called if
+ * the dialog applies to a single file or URL.
+ * @param _name new filename, encoded.
+ * \see FilePropsDlgPlugin::applyChanges
+ */
+ void rename( const TQString& _name );
+
+ /**
+ * To abort applying changes.
+ */
+ void abortApplying();
+
+ /**
+ * Shows the page that was previously set by
+ * setFileSharingPage(), or does nothing if no page
+ * was set yet.
+ * \see setFileSharingPage
+ * @since 3.1
+ */
+ void showFileSharingPage();
+
+ /**
+ * Sets the file sharing page.
+ * This page is shown when calling showFileSharingPage().
+ *
+ * @param page the page to set
+ * \see showFileSharingPage
+ * @since 3.3
+ */
+ void setFileSharingPage(TQWidget* page);
+
+ /**
+ * Call this to make the filename lineedit readonly, to prevent the user
+ * from renaming the file.
+ * \param ro true if the lineedit should be read only
+ * @since 3.2
+ */
+ void setFileNameReadOnly( bool ro );
+
+public slots:
+ /**
+ * Called when the user presses 'Ok'.
+ */
+ virtual void slotOk(); // Deletes the PropertiesDialog instance
+ /**
+ * Called when the user presses 'Cancel'.
+ */
+ virtual void slotCancel(); // Deletes the PropertiesDialog instance
+
+signals:
+ /**
+ * This signal is emitted when the Properties Dialog is closed (for
+ * example, with OK or Cancel buttons)
+ */
+ void propertiesClosed();
+
+ /**
+ * This signal is emitted when the properties changes are applied (for
+ * example, with the OK button)
+ */
+ void applied();
+
+ /**
+ * This signal is emitted when the properties changes are aborted (for
+ * example, with the Cancel button)
+ */
+
+ void canceled();
+ /**
+ * Emitted before changes to @p oldUrl are saved as @p newUrl.
+ * The receiver may change @p newUrl to point to an alternative
+ * save location.
+ */
+ void saveAs(const KURL &oldUrl, KURL &newUrl);
+
+private:
+
+ /**
+ * Common initialization for all constructors
+ */
+ void init (bool modal = false, bool autoShow = true);
+
+ /**
+ * Inserts all pages in the dialog.
+ */
+ void insertPages();
+
+ /**
+ * The URL of the props dialog (when shown for only one file)
+ */
+ KURL m_singleUrl;
+
+ /**
+ * List of items this props dialog is shown for
+ */
+ KFileItemList m_items;
+
+ /**
+ * For templates
+ */
+ TQString m_defaultName;
+ KURL m_currentDir;
+
+ /**
+ * List of all plugins inserted ( first one first )
+ */
+ TQPtrList<KPropsDlgPlugin> m_pageList;
+
+private slots:
+ void slotStatResult( TDEIO::Job * ); // No longer used
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KPropertiesDialogPrivate;
+ KPropertiesDialogPrivate *d;
+};
+
+/**
+ * A Plugin in the Properties dialog
+ * This is an abstract class. You must inherit from this class
+ * to build a new kind of tabbed page for the KPropertiesDialog.
+ * A plugin in itself is just a library containing code, not a dialog's page.
+ * It's up to the plugin to insert pages into the parent dialog.
+ *
+ * To make a plugin available, define a service that implements the KPropsDlg/Plugin
+ * servicetype, as well as the mimetypes for which the plugin should be created.
+ * For instance, ServiceTypes=KPropsDlg/Plugin,text/html,application/x-mymimetype.
+ *
+ * You can also include X-TDE-Protocol=file if you want that plugin
+ * to be loaded only for local files, for instance.
+ */
+class TDEIO_EXPORT KPropsDlgPlugin : public TQObject
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructor
+ * To insert tabs into the properties dialog, use the add methods provided by
+ * KDialogBase (the properties dialog is a KDialogBase).
+ */
+ KPropsDlgPlugin( KPropertiesDialog *_props );
+ virtual ~KPropsDlgPlugin();
+
+ /**
+ * Applies all changes to the file.
+ * This function is called when the user presses 'Ok'. The last plugin inserted
+ * is called first.
+ */
+ virtual void applyChanges();
+
+ /**
+ * Convenience method for most ::supports methods
+ * @return true if the file is a local, regular, readable, desktop file
+ */
+ static bool isDesktopFile( KFileItem * _item );
+
+ void setDirty( bool b );
+ bool isDirty() const;
+
+public slots:
+ void setDirty(); // same as setDirty( true )
+
+signals:
+ /**
+ * Emit this signal when the user changed anything in the plugin's tabs.
+ * The hosting PropertiesDialog will call applyChanges only if the
+ * PropsPlugin has emitted this signal before.
+ */
+ void changed();
+
+protected:
+ /**
+ * Pointer to the dialog
+ */
+ KPropertiesDialog *properties;
+
+ int fontHeight;
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KPropsDlgPluginPrivate;
+ KPropsDlgPluginPrivate *d;
+};
+
+/**
+ * 'General' plugin
+ * This plugin displays the name of the file, its size and access times.
+ * @internal
+ */
+class TDEIO_EXPORT KFilePropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructor
+ */
+ KFilePropsPlugin( KPropertiesDialog *_props );
+ virtual ~KFilePropsPlugin();
+
+ /**
+ * Applies all changes made. This plugin must be always the first
+ * plugin in the dialog, since this function may rename the file which
+ * may confuse other applyChanges functions.
+ */
+ virtual void applyChanges();
+
+ /**
+ * Tests whether the files specified by _items need a 'General' plugin.
+ */
+ static bool supports( KFileItemList _items );
+
+ /**
+ * Called after all plugins applied their changes
+ */
+ void postApplyChanges();
+
+ void setFileNameReadOnly( bool ro );
+
+protected slots:
+ void slotEditFileType();
+ void slotCopyFinished( TDEIO::Job * );
+ void slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & );
+ void slotDirSizeUpdate();
+ void slotDirSizeFinished( TDEIO::Job * );
+ void slotFoundMountPoint( const TQString& mp, unsigned long kBSize,
+ unsigned long kBUsed, unsigned long kBAvail );
+ void slotSizeStop();
+ void slotSizeDetermine();
+
+private slots:
+ // workaround for compiler bug
+ void slotFoundMountPoint( const unsigned long& kBSize, const unsigned long&
+ kBUsed, const unsigned long& kBAvail, const TQString& mp );
+ void nameFileChanged(const TQString &text );
+ void slotIconChanged();
+
+private:
+ void determineRelativePath( const TQString & path );
+ void applyIconChanges();
+
+ TQWidget *iconArea;
+ TQWidget *nameArea;
+
+ TQLabel *m_sizeLabel;
+ TQPushButton *m_sizeDetermineButton;
+ TQPushButton *m_sizeStopButton;
+
+ TQString m_sRelativePath;
+ bool m_bFromTemplate;
+
+ /**
+ * The initial filename
+ */
+ TQString oldName;
+
+ class KFilePropsPluginPrivate;
+ KFilePropsPluginPrivate *d;
+};
+
+/**
+ * 'Permissions' plugin
+ * In this plugin you can modify permissions and change
+ * the owner of a file.
+ * @internal
+ */
+class TDEIO_EXPORT KFilePermissionsPropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ enum PermissionsMode {
+ PermissionsOnlyFiles = 0,
+ PermissionsOnlyDirs = 1,
+ PermissionsOnlyLinks = 2,
+ PermissionsMixed = 3
+ };
+
+ enum PermissionsTarget {
+ PermissionsOwner = 0,
+ PermissionsGroup = 1,
+ PermissionsOthers = 2
+ };
+
+ /**
+ * Constructor
+ */
+ KFilePermissionsPropsPlugin( KPropertiesDialog *_props );
+ virtual ~KFilePermissionsPropsPlugin();
+
+ virtual void applyChanges();
+
+ /**
+ * Tests whether the file specified by _items needs a 'Permissions' plugin.
+ */
+ static bool supports( KFileItemList _items );
+
+private slots:
+
+ void slotChmodResult( TDEIO::Job * );
+ void slotShowAdvancedPermissions();
+
+private:
+ void setComboContent(TQComboBox *combo, PermissionsTarget target,
+ mode_t permissions, mode_t partial);
+ bool isIrregular(mode_t permissions, bool isDir, bool isLink);
+ void enableAccessControls(bool enable);
+ void updateAccessControls();
+ void getPermissionMasks(mode_t &andFilePermissions,
+ mode_t &andDirPermissions,
+ mode_t &orFilePermissions,
+ mode_t &orDirPermissions);
+
+ static const mode_t permissionsMasks[3];
+ static const mode_t standardPermissions[4];
+ static const char *permissionsTexts[4][4];
+
+ // unused, for binary compatibility!
+ TQCheckBox *permBox[3][4];
+
+ TQComboBox *grpCombo;
+
+ KLineEdit *usrEdit, *grpEdit;
+
+ /**
+ * Old permissions
+ */
+ mode_t permissions;
+ /**
+ * Old group
+ */
+ TQString strGroup;
+ /**
+ * Old owner
+ */
+ TQString strOwner;
+
+ // unused, for compatibility
+ static mode_t fperm[3][4];
+
+ class KFilePermissionsPropsPluginPrivate;
+ KFilePermissionsPropsPluginPrivate *d;
+};
+
+
+/**
+ * Used to edit the files containing
+ * [Desktop Entry]
+ * URL=....
+ *
+ * Such files are used to represent a program in kicker and konqueror.
+ * @internal
+ */
+class TDEIO_EXPORT KURLPropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructor
+ */
+ KURLPropsPlugin( KPropertiesDialog *_props );
+ virtual ~KURLPropsPlugin();
+
+ virtual void applyChanges();
+
+ static bool supports( KFileItemList _items );
+
+private:
+ KURLRequester *URLEdit;
+ KIconButton *iconBox;
+
+ TQString URLStr;
+ TQString iconStr;
+
+ TQPixmap pixmap;
+ TQString pixmapFile;
+private:
+ class KURLPropsPluginPrivate;
+ KURLPropsPluginPrivate *d;
+};
+
+
+/**
+ * Used to edit the files containing
+ * [Desktop Entry]
+ * Type=MimeType
+ * @internal
+ */
+class TDEIO_EXPORT KBindingPropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructor
+ */
+ KBindingPropsPlugin( KPropertiesDialog *_props );
+ virtual ~KBindingPropsPlugin();
+
+ virtual void applyChanges();
+ static bool supports( KFileItemList _items );
+
+private:
+
+ TQLineEdit *commentEdit;
+ TQLineEdit *patternEdit;
+ TQLineEdit *mimeEdit;
+ TQString m_sMimeStr;
+
+ TQCheckBox * cbAutoEmbed;
+
+ class KBindingPropsPluginPrivate;
+ KBindingPropsPluginPrivate *d;
+};
+
+/**
+ * Properties plugin for device .desktop files
+ * @internal
+ */
+class TDEIO_EXPORT KDevicePropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ KDevicePropsPlugin( KPropertiesDialog *_props );
+ virtual ~KDevicePropsPlugin();
+
+ virtual void applyChanges();
+
+ static bool supports( KFileItemList _items );
+
+private slots:
+ void slotActivated( int );
+ void slotDeviceChanged();
+ void slotFoundMountPoint( const unsigned long& kBSize,
+ const unsigned long& /*kBUsed*/,
+ const unsigned long& kBAvail,
+ const TQString& );
+
+private:
+ void updateInfo();
+
+private:
+ TQComboBox* device;
+ TQLabel* mountpoint;
+ TQCheckBox* readonly;
+ void* unused;
+ //KIconButton* mounted;
+ KIconButton* unmounted;
+
+ TQStringList m_devicelist;
+ int indexDevice;
+ int indexMountPoint;
+ int indexFSType;
+
+ TQPixmap pixmap;
+ TQString pixmapFile;
+
+ class KDevicePropsPluginPrivate;
+ KDevicePropsPluginPrivate *d;
+};
+
+class KPropertiesDesktopBase;
+
+/**
+ * Used to edit the files containing
+ * [Desktop Entry]
+ * Type=Application
+ *
+ * Such files are used to represent a program in kicker and konqueror.
+ * @internal
+ */
+class TDEIO_EXPORT KDesktopPropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructor
+ */
+ KDesktopPropsPlugin( KPropertiesDialog *_props );
+ virtual ~KDesktopPropsPlugin();
+
+ virtual void applyChanges();
+
+ static bool supports( KFileItemList _items );
+
+public slots:
+ void slotAddFiletype();
+ void slotDelFiletype();
+ void slotBrowseExec();
+ void slotAdvanced();
+ void slotSelectMimetype();
+
+private:
+ void checkCommandChanged();
+
+private:
+ KPropertiesDesktopBase* w;
+
+ TQString m_origCommandStr;
+ TQString m_terminalOptionStr;
+ TQString m_suidUserStr;
+ TQString m_dcopServiceType;
+ bool m_terminalBool;
+ bool m_terminalCloseBool;
+ bool m_suidBool;
+ bool m_startupBool;
+ bool m_systrayBool;
+
+ class KDesktopPropsPluginPrivate;
+ KDesktopPropsPluginPrivate *d;
+};
+
+/**
+ * Used to edit the files containing
+ * [Desktop Entry]
+ * Type=Application
+ *
+ * Such files are used to represent a program in kicker and konqueror.
+ * @internal
+ * @deprecated replaced with KDesktopPropsPlugin
+ */
+ /// Remove in KDE4
+class TDEIO_EXPORT_DEPRECATED KExecPropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructor
+ */
+ KExecPropsPlugin( KPropertiesDialog *_props );
+ virtual ~KExecPropsPlugin();
+
+ virtual void applyChanges();
+
+ static bool supports( KFileItemList _items );
+
+public slots:
+ void slotBrowseExec();
+
+private slots:
+ void enableCheckedEdit();
+ void enableSuidEdit();
+
+private:
+
+ TQLabel *terminalLabel;
+ TQLabel *suidLabel;
+ KLineEdit *execEdit;
+ TQCheckBox *terminalCheck;
+ TQCheckBox *suidCheck;
+ KLineEdit *terminalEdit;
+ KLineEdit *suidEdit;
+ KLineEdit *swallowExecEdit;
+ KLineEdit *swallowTitleEdit;
+ TQButton *execBrowse;
+
+ TQString execStr;
+ TQString swallowExecStr;
+ TQString swallowTitleStr;
+ TQString termOptionsStr;
+ bool termBool;
+ bool suidBool;
+ TQString suidUserStr;
+
+ class KExecPropsPluginPrivate;
+ KExecPropsPluginPrivate *d;
+};
+
+/**
+ * Used to edit the files containing
+ * [Desktop Entry]
+ * Type=Application
+ *
+ * Such files are used to represent a program in kicker and konqueror.
+ * @internal
+ * @deprecated replaced with KDesktopPropsPlugin
+ */
+ /// Remove in KDE4
+class TDEIO_EXPORT_DEPRECATED TDEApplicationPropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructor
+ */
+ TDEApplicationPropsPlugin( KPropertiesDialog *_props );
+ virtual ~TDEApplicationPropsPlugin();
+
+ virtual void applyChanges();
+
+ static bool supports( KFileItemList _items );
+
+public slots:
+ void slotDelExtension();
+ void slotAddExtension();
+
+private slots:
+ void updateButton();
+
+private:
+ void addMimeType( const TQString & name );
+
+ TQLineEdit *commentEdit;
+ TQLineEdit *genNameEdit;
+ TQLineEdit *nameEdit;
+ TQListBox *extensionsList;
+ TQListBox *availableExtensionsList;
+ TQPushButton *addExtensionButton;
+ TQPushButton *delExtensionButton;
+
+ class TDEApplicationPropsPluginPrivate;
+ TDEApplicationPropsPluginPrivate *d;
+};
+
+#endif
+
diff --git a/kio/kfile/kpropertiesmimetypebase.ui b/tdeio/tdefile/kpropertiesmimetypebase.ui
index df7c796da..df7c796da 100644
--- a/kio/kfile/kpropertiesmimetypebase.ui
+++ b/tdeio/tdefile/kpropertiesmimetypebase.ui
diff --git a/kio/kfile/kpropsdlg.h b/tdeio/tdefile/kpropsdlg.h
index 502a346e9..502a346e9 100644
--- a/kio/kfile/kpropsdlg.h
+++ b/tdeio/tdefile/kpropsdlg.h
diff --git a/kio/kfile/kpropsdlgplugin.desktop b/tdeio/tdefile/kpropsdlgplugin.desktop
index f74e3895e..f74e3895e 100644
--- a/kio/kfile/kpropsdlgplugin.desktop
+++ b/tdeio/tdefile/kpropsdlgplugin.desktop
diff --git a/kio/kfile/krecentdirs.cpp b/tdeio/tdefile/krecentdirs.cpp
index 6f4a01f3b..6f4a01f3b 100644
--- a/kio/kfile/krecentdirs.cpp
+++ b/tdeio/tdefile/krecentdirs.cpp
diff --git a/kio/kfile/krecentdirs.h b/tdeio/tdefile/krecentdirs.h
index 774655e51..774655e51 100644
--- a/kio/kfile/krecentdirs.h
+++ b/tdeio/tdefile/krecentdirs.h
diff --git a/kio/kfile/krecentdocument.cpp b/tdeio/tdefile/krecentdocument.cpp
index 1ec4a98c8..1ec4a98c8 100644
--- a/kio/kfile/krecentdocument.cpp
+++ b/tdeio/tdefile/krecentdocument.cpp
diff --git a/kio/kfile/krecentdocument.h b/tdeio/tdefile/krecentdocument.h
index 968559968..968559968 100644
--- a/kio/kfile/krecentdocument.h
+++ b/tdeio/tdefile/krecentdocument.h
diff --git a/tdeio/tdefile/kurlbar.cpp b/tdeio/tdefile/kurlbar.cpp
new file mode 100644
index 000000000..e142845e1
--- /dev/null
+++ b/tdeio/tdefile/kurlbar.cpp
@@ -0,0 +1,1049 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation, version 2.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <unistd.h>
+
+#include <tqapplication.h>
+#include <tqcheckbox.h>
+#include <tqdrawutil.h>
+#include <tqfontmetrics.h>
+#include <tqlabel.h>
+#include <tqgrid.h>
+#include <tqpainter.h>
+#include <tqpopupmenu.h>
+#include <tqstyle.h>
+#include <tqvbox.h>
+#include <tqwhatsthis.h>
+
+#include <kaboutdata.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <kglobal.h>
+#include <kicondialog.h>
+#include <kiconloader.h>
+#include <kinstance.h>
+#include <klineedit.h>
+#include <klocale.h>
+#include <kmimetype.h>
+#include <kprotocolinfo.h>
+#include <kstringhandler.h>
+#include <kurldrag.h>
+#include <kurlrequester.h>
+#include <tdeio/global.h>
+#include <tdeio/netaccess.h>
+
+#include "kurlbar.h"
+
+/**
+ * Handles tooltips in the KURLBar
+ * @internal
+ */
+class KURLBarToolTip : public TQToolTip
+{
+public:
+ KURLBarToolTip( TQListBox *view ) : TQToolTip( view ), m_view( view ) {}
+
+protected:
+ virtual void maybeTip( const TQPoint& point ) {
+ TQListBoxItem *item = m_view->itemAt( point );
+ if ( item ) {
+ TQString text = static_cast<KURLBarItem*>( item )->toolTip();
+ if ( !text.isEmpty() )
+ tip( m_view->itemRect( item ), text );
+ }
+ }
+
+private:
+ TQListBox *m_view;
+};
+
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+class KURLBarItem::KURLBarItemPrivate
+{
+public:
+ KURLBarItemPrivate()
+ {
+ isPersistent = true;
+ }
+
+ bool isPersistent;
+};
+
+KURLBarItem::KURLBarItem( KURLBar *parent,
+ const KURL& url, bool persistent, const TQString& description,
+ const TQString& icon, KIcon::Group group )
+ : TQListBoxPixmap( KIconLoader::unknown() /*, parent->listBox()*/ ),
+ m_url( url ),
+ m_pixmap( 0L ),
+ m_parent( parent ),
+ m_appLocal( true )
+{
+ init( icon, group, description, persistent );
+}
+
+KURLBarItem::KURLBarItem( KURLBar *parent,
+ const KURL& url, const TQString& description,
+ const TQString& icon, KIcon::Group group )
+ : TQListBoxPixmap( KIconLoader::unknown() /*, parent->listBox()*/ ),
+ m_url( url ),
+ m_pixmap( 0L ),
+ m_parent( parent ),
+ m_appLocal( true )
+{
+ init( icon, group, description, true /*persistent*/ );
+}
+
+void KURLBarItem::init( const TQString& icon, KIcon::Group group,
+ const TQString& description, bool persistent )
+{
+ d = new KURLBarItemPrivate;
+ d->isPersistent = persistent;
+
+ setCustomHighlighting( true );
+ setIcon( icon, group );
+ setDescription( description );
+}
+
+KURLBarItem::~KURLBarItem()
+{
+ delete d;
+}
+
+void KURLBarItem::setURL( const KURL& url )
+{
+ m_url = url;
+ if ( m_description.isEmpty() )
+ setText( url.fileName() );
+}
+
+void KURLBarItem::setIcon( const TQString& icon, KIcon::Group group )
+{
+ m_icon = icon;
+ m_group = group;
+
+ if ( icon.isEmpty() )
+ m_pixmap = KMimeType::pixmapForURL( m_url, 0, group, iconSize() );
+ else
+ m_pixmap = TDEGlobal::iconLoader()->loadIcon( icon, group, iconSize(),
+ KIcon::DefaultState );
+}
+
+void KURLBarItem::setDescription( const TQString& desc )
+{
+ m_description = desc;
+ setText( desc.isEmpty() ? m_url.fileName() : desc );
+}
+
+void KURLBarItem::setApplicationLocal( bool local )
+{
+ if ( !local && !isPersistent() )
+ {
+ kdWarning() << "KURLBar: dynamic (non-persistent) items can not be global." << endl;
+ return;
+ }
+
+ m_appLocal = local;
+}
+
+void KURLBarItem::setToolTip( const TQString& tip )
+{
+ m_toolTip = tip;
+}
+
+TQString KURLBarItem::toolTip() const
+{
+ return m_toolTip.isEmpty() ? m_url.prettyURL() : m_toolTip;
+}
+
+int KURLBarItem::iconSize() const
+{
+ return m_parent->iconSize();
+}
+
+void KURLBarItem::paint( TQPainter *p )
+{
+ TQListBox *box = listBox();
+ int w = width( box );
+ static const int margin = KDialog::spacingHint();
+
+ // draw sunken selection
+ if ( isCurrent() || isSelected() ) {
+ int h = height( box );
+
+ TQBrush brush = box->colorGroup().brush( TQColorGroup::Highlight );
+ p->fillRect( 0, 0, w, h, brush );
+ TQPen pen = p->pen();
+ TQPen oldPen = pen;
+ pen.setColor( box->colorGroup().mid() );
+ p->setPen( pen );
+
+ p->drawPoint( 0, 0 );
+ p->drawPoint( 0, h - 1 );
+ p->drawPoint( w - 1, 0 );
+ p->drawPoint( w - 1, h - 1 );
+
+ p->setPen( oldPen );
+ }
+
+ if ( m_parent->iconSize() < KIcon::SizeMedium ) {
+ // small icon -> draw icon next to text
+
+ // ### mostly cut & paste of TQListBoxPixmap::paint() until Qt 3.1
+ // (where it will properly use pixmap() instead of the internal pixmap)
+ const TQPixmap *pm = pixmap();
+ int yPos = QMAX( 0, (height(box) - pm->height())/2 );
+
+ p->drawPixmap( margin, yPos, *pm );
+ if ( !text().isEmpty() ) {
+ TQFontMetrics fm = p->fontMetrics();
+ if ( pm->height() < fm.height() )
+ yPos = fm.ascent() + fm.leading()/2;
+ else
+ yPos = pm->height()/2 - fm.height()/2 + fm.ascent();
+
+ yPos += margin;
+ int stringWidth = box->width() - pm->width() - 2 - (margin * 2);
+ TQString visibleText = KStringHandler::rPixelSqueeze( text(), fm, stringWidth );
+ int xPos = pm->width() + margin + 2;
+
+ if ( isCurrent() || isSelected() ) {
+ p->setPen( box->colorGroup().highlight().dark(115) );
+ p->drawText( xPos + ( TQApplication::reverseLayout() ? -1 : 1),
+ yPos + 1, visibleText );
+ p->setPen( box->colorGroup().highlightedText() );
+ }
+
+ p->drawText( xPos, yPos, visibleText );
+ }
+ // end cut & paste (modulo pixmap centering)
+ }
+
+ else {
+ // big icons -> draw text below icon
+ int y = margin;
+ const TQPixmap *pm = pixmap();
+
+ if ( !pm->isNull() ) {
+ int x = (w - pm->width()) / 2;
+ x = QMAX( x, margin );
+ p->drawPixmap( x, y, *pm );
+ }
+
+ if ( !text().isEmpty() ) {
+ TQFontMetrics fm = p->fontMetrics();
+ y += pm->height() + fm.height() - fm.descent();
+
+ int stringWidth = box->width() - (margin * 2);
+ TQString visibleText = KStringHandler::rPixelSqueeze( text(), fm, stringWidth );
+ int x = (w - fm.width( visibleText )) / 2;
+ x = QMAX( x, margin );
+
+ if ( isCurrent() || isSelected() ) {
+ p->setPen( box->colorGroup().highlight().dark(115) );
+ p->drawText( x + ( TQApplication::reverseLayout() ? -1 : 1),
+ y + 1, visibleText );
+ p->setPen( box->colorGroup().highlightedText() );
+ }
+
+ p->drawText( x, y, visibleText );
+ }
+ }
+}
+
+TQSize KURLBarItem::sizeHint() const
+{
+ int wmin = 0;
+ int hmin = 0;
+ const KURLBarListBox *lb =static_cast<const KURLBarListBox*>(listBox());
+
+ if ( m_parent->iconSize() < KIcon::SizeMedium ) {
+ wmin = TQListBoxPixmap::width( lb ) + KDialog::spacingHint() * 2;
+ hmin = TQListBoxPixmap::height( lb ) + KDialog::spacingHint() * 2;
+ }
+ else {
+ wmin = QMAX(lb->fontMetrics().width(text()), pixmap()->width()) + KDialog::spacingHint() * 2;
+ hmin = lb->fontMetrics().lineSpacing() + pixmap()->height() + KDialog::spacingHint() * 2;
+ }
+
+ if ( lb->isVertical() )
+ wmin = QMIN( wmin, lb->viewport()->sizeHint().width() );
+ else
+ hmin = QMIN( hmin, lb->viewport()->sizeHint().height() );
+
+ return TQSize( wmin, hmin );
+}
+
+int KURLBarItem::width( const TQListBox *lb ) const
+{
+ if ( static_cast<const KURLBarListBox *>( lb )->isVertical() )
+ return QMAX( sizeHint().width(), lb->viewport()->width() );
+ else
+ return sizeHint().width();
+}
+
+int KURLBarItem::height( const TQListBox *lb ) const
+{
+ if ( static_cast<const KURLBarListBox *>( lb )->isVertical() )
+ return sizeHint().height();
+ else
+ return QMAX( sizeHint().height(), lb->viewport()->height() );
+}
+
+bool KURLBarItem::isPersistent() const
+{
+ return d->isPersistent;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+class KURLBar::KURLBarPrivate
+{
+public:
+ KURLBarPrivate()
+ {
+ currentURL.setPath( TQDir::homeDirPath() );
+ defaultIconSize = 0;
+ }
+
+ int defaultIconSize;
+ KURL currentURL;
+};
+
+
+KURLBar::KURLBar( bool useGlobalItems, TQWidget *parent, const char *name, WFlags f )
+ : TQFrame( parent, name, f ),
+ m_activeItem( 0L ),
+ m_useGlobal( useGlobalItems ),
+ m_isModified( false ),
+ m_isImmutable( false ),
+ m_listBox( 0L ),
+ m_iconSize( KIcon::SizeMedium )
+{
+ d = new KURLBarPrivate();
+
+ setListBox( 0L );
+ setSizePolicy( TQSizePolicy( isVertical() ?
+ TQSizePolicy::Maximum :
+ TQSizePolicy::Preferred,
+ isVertical() ?
+ TQSizePolicy::Preferred :
+ TQSizePolicy::Maximum ));
+ TQWhatsThis::add(this, i18n("<qt>The <b>Quick Access</b> panel provides easy access to commonly used file locations.<p>"
+ "Clicking on one of the shortcut entries will take you to that location.<p>"
+ "By right clicking on an entry you can add, edit and remove shortcuts.</qt>"));
+}
+
+KURLBar::~KURLBar()
+{
+ delete d;
+}
+
+KURLBarItem * KURLBar::insertItem(const KURL& url, const TQString& description,
+ bool applicationLocal,
+ const TQString& icon, KIcon::Group group )
+{
+ KURLBarItem *item = new KURLBarItem(this, url, description, icon, group);
+ item->setApplicationLocal( applicationLocal );
+ m_listBox->insertItem( item );
+ return item;
+}
+
+KURLBarItem * KURLBar::insertDynamicItem(const KURL& url, const TQString& description,
+ const TQString& icon, KIcon::Group group )
+{
+ KURLBarItem *item = new KURLBarItem(this, url, false, description, icon, group);
+ m_listBox->insertItem( item );
+ return item;
+}
+
+void KURLBar::setOrientation( Qt::Orientation orient )
+{
+ m_listBox->setOrientation( orient );
+ setSizePolicy( TQSizePolicy( isVertical() ?
+ TQSizePolicy::Maximum :
+ TQSizePolicy::Preferred,
+ isVertical() ?
+ TQSizePolicy::Preferred :
+ TQSizePolicy::Maximum ));
+}
+
+Qt::Orientation KURLBar::orientation() const
+{
+ return m_listBox->orientation();
+}
+
+void KURLBar::setListBox( KURLBarListBox *view )
+{
+ delete m_listBox;
+
+ if ( !view ) {
+ m_listBox = new KURLBarListBox( this, "urlbar listbox" );
+ setOrientation( Qt::Vertical );
+ }
+ else {
+ m_listBox = view;
+ if ( m_listBox->parentWidget() != this )
+ m_listBox->reparent( this, TQPoint(0,0) );
+ m_listBox->resize( width(), height() );
+ }
+
+ m_listBox->setSelectionMode( KListBox::Single );
+ paletteChange( palette() );
+ m_listBox->setFocusPolicy( TQ_TabFocus );
+
+ connect( m_listBox, TQT_SIGNAL( mouseButtonClicked( int, TQListBoxItem *, const TQPoint & ) ),
+ TQT_SLOT( slotSelected( int, TQListBoxItem * )));
+ connect( m_listBox, TQT_SIGNAL( dropped( TQDropEvent * )),
+ this, TQT_SLOT( slotDropped( TQDropEvent * )));
+ connect( m_listBox, TQT_SIGNAL( contextMenuRequested( TQListBoxItem *,
+ const TQPoint& )),
+ TQT_SLOT( slotContextMenuRequested( TQListBoxItem *, const TQPoint& )));
+ connect( m_listBox, TQT_SIGNAL( returnPressed( TQListBoxItem * ) ),
+ TQT_SLOT( slotSelected( TQListBoxItem * ) ));
+}
+
+void KURLBar::setIconSize( int size )
+{
+ if ( size == m_iconSize )
+ return;
+
+ m_iconSize = size;
+
+ // reload the icons with the new size
+ KURLBarItem *item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
+ while ( item ) {
+ item->setIcon( item->icon(), item->iconGroup() );
+ item = static_cast<KURLBarItem*>( item->next() );
+ }
+
+ resize( sizeHint() );
+ updateGeometry();
+}
+
+void KURLBar::clear()
+{
+ m_listBox->clear();
+}
+
+void KURLBar::resizeEvent( TQResizeEvent *e )
+{
+ TQFrame::resizeEvent( e );
+ m_listBox->resize( width(), height() );
+}
+
+void KURLBar::paletteChange( const TQPalette & )
+{
+ TQPalette pal = palette();
+ TQColor gray = pal.color( TQPalette::Normal, TQColorGroup::Background );
+ TQColor selectedTextColor = pal.color( TQPalette::Normal, TQColorGroup::BrightText );
+ TQColor foreground = pal.color( TQPalette::Normal, TQColorGroup::Foreground );
+ pal.setColor( TQPalette::Normal, TQColorGroup::Base, gray );
+ pal.setColor( TQPalette::Normal, TQColorGroup::HighlightedText, selectedTextColor );
+ pal.setColor( TQPalette::Normal, TQColorGroup::Text, foreground );
+ pal.setColor( TQPalette::Inactive, TQColorGroup::Base, gray );
+ pal.setColor( TQPalette::Inactive, TQColorGroup::HighlightedText, selectedTextColor );
+ pal.setColor( TQPalette::Inactive, TQColorGroup::Text, foreground );
+
+ setPalette( pal );
+}
+
+TQSize KURLBar::sizeHint() const
+{
+ return m_listBox->sizeHint();
+
+#if 0
+ // this code causes vertical and or horizontal scrollbars appearing
+ // depending on the text, font, moonphase and earth rotation. Just using
+ // m_listBox->sizeHint() fixes this (although the widget can then be
+ // resized to a smaller size so that scrollbars appear).
+ int w = 0;
+ int h = 0;
+ KURLBarItem *item;
+ bool vertical = isVertical();
+
+ for ( item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
+ item;
+ item = static_cast<KURLBarItem*>( item->next() ) ) {
+
+ TQSize sh = item->sizeHint();
+
+ if ( vertical ) {
+ w = QMAX( w, sh.width() );
+ h += sh.height();
+ }
+ else {
+ w += sh.width();
+ h = QMAX( h, sh.height() );
+ }
+ }
+
+// if ( vertical && m_listBox->verticalScrollBar()->isVisible() )
+// w += m_listBox->verticalScrollBar()->width();
+// else if ( !vertical && m_listBox->horizontalScrollBar()->isVisible() )
+// h += m_listBox->horizontalScrollBar()->height();
+
+ if ( w == 0 && h == 0 )
+ return TQSize( 100, 200 );
+ else
+ return TQSize( 6 + w, h );
+#endif
+}
+
+TQSize KURLBar::minimumSizeHint() const
+{
+ TQSize s = sizeHint(); // ###
+ int w = s.width() + m_listBox->verticalScrollBar()->width();
+ int h = s.height() + m_listBox->horizontalScrollBar()->height();
+ return TQSize( w, h );
+}
+
+void KURLBar::slotSelected( int button, TQListBoxItem *item )
+{
+ if ( button != Qt::LeftButton )
+ return;
+
+ slotSelected( item );
+}
+
+void KURLBar::slotSelected( TQListBoxItem *item )
+{
+ if ( item && item != m_activeItem )
+ m_activeItem = static_cast<KURLBarItem*>( item );
+
+ if ( m_activeItem ) {
+ m_listBox->setCurrentItem( m_activeItem );
+ emit activated( m_activeItem->url() );
+ }
+}
+
+void KURLBar::setCurrentItem( const KURL& url )
+{
+ d->currentURL = url;
+
+ TQString u = url.url(-1);
+
+ if ( m_activeItem && m_activeItem->url().url(-1) == u )
+ return;
+
+ bool hasURL = false;
+ TQListBoxItem *item = m_listBox->firstItem();
+ while ( item ) {
+ if ( static_cast<KURLBarItem*>( item )->url().url(-1) == u ) {
+ m_activeItem = static_cast<KURLBarItem*>( item );
+ m_listBox->setCurrentItem( item );
+ m_listBox->setSelected( item, true );
+ hasURL = true;
+ break;
+ }
+ item = item->next();
+ }
+
+ if ( !hasURL ) {
+ m_activeItem = 0L;
+ m_listBox->clearSelection();
+ }
+}
+
+KURLBarItem * KURLBar::currentItem() const
+{
+ TQListBoxItem *item = m_listBox->item( m_listBox->currentItem() );
+ if ( item )
+ return static_cast<KURLBarItem *>( item );
+ return 0L;
+}
+
+KURL KURLBar::currentURL() const
+{
+ KURLBarItem *item = currentItem();
+ return item ? item->url() : KURL();
+}
+
+void KURLBar::readConfig( TDEConfig *appConfig, const TQString& itemGroup )
+{
+ m_isImmutable = appConfig->groupIsImmutable( itemGroup );
+ TDEConfigGroupSaver cs( appConfig, itemGroup );
+ d->defaultIconSize = m_iconSize;
+ m_iconSize = appConfig->readNumEntry( "Speedbar IconSize", m_iconSize );
+
+ if ( m_useGlobal ) { // read global items
+ TDEConfig *globalConfig = TDEGlobal::config();
+ TDEConfigGroupSaver cs( globalConfig, (TQString)(itemGroup +" (Global)"));
+ int num = globalConfig->readNumEntry( "Number of Entries" );
+ for ( int i = 0; i < num; i++ ) {
+ readItem( i, globalConfig, false );
+ }
+ }
+
+ // read application local items
+ int num = appConfig->readNumEntry( "Number of Entries" );
+ for ( int i = 0; i < num; i++ ) {
+ readItem( i, appConfig, true );
+ }
+}
+
+void KURLBar::readItem( int i, TDEConfig *config, bool applicationLocal )
+{
+ TQString number = TQString::number( i );
+ KURL url = KURL::fromPathOrURL( config->readPathEntry( TQString("URL_") + number ));
+ if ( !url.isValid() || !KProtocolInfo::isKnownProtocol( url ))
+ return; // nothing we could do.
+
+ TQString description = config->readEntry( TQString("Description_") + number );
+
+ if (description.isEmpty() && url.protocol()=="beagle") {
+ TDEIO::UDSEntry uds;
+ const KURL kurl("beagle:?beagled-status");
+ if (!TDEIO::NetAccess::stat(kurl, uds))
+ return;
+
+ description = i18n("Desktop Search");
+ }
+
+ insertItem( url,
+ description,
+ applicationLocal,
+ config->readEntry( TQString("Icon_") + number ),
+ static_cast<KIcon::Group>(
+ config->readNumEntry( TQString("IconGroup_") + number )) );
+}
+
+void KURLBar::writeConfig( TDEConfig *config, const TQString& itemGroup )
+{
+ TDEConfigGroupSaver cs1( config, itemGroup );
+ if(!config->hasDefault("Speedbar IconSize") && m_iconSize == d->defaultIconSize )
+ config->revertToDefault("Speedbar IconSize");
+ else
+ config->writeEntry( "Speedbar IconSize", m_iconSize );
+
+ if ( !m_isModified )
+ return;
+
+ int i = 0;
+ int numLocal = 0;
+ KURLBarItem *item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
+
+ while ( item )
+ {
+ if ( item->isPersistent() ) // we only save persistent items
+ {
+ if ( item->applicationLocal() )
+ {
+ writeItem( item, numLocal, config, false );
+ numLocal++;
+ }
+
+ i++;
+ }
+ item = static_cast<KURLBarItem*>( item->next() );
+ }
+ config->writeEntry("Number of Entries", numLocal);
+
+
+ // write the global entries to kdeglobals, if any
+ bool haveGlobalEntries = (i > numLocal);
+ if ( m_useGlobal && haveGlobalEntries ) {
+ config->setGroup( itemGroup + " (Global)" );
+
+ int numGlobals = 0;
+ item = static_cast<KURLBarItem*>( m_listBox->firstItem() );
+
+ while ( item )
+ {
+ if ( item->isPersistent() ) // we only save persistent items
+ {
+ if ( !item->applicationLocal() )
+ {
+ writeItem( item, numGlobals, config, true );
+ numGlobals++;
+ }
+ }
+
+ item = static_cast<KURLBarItem*>( item->next() );
+ }
+ config->writeEntry("Number of Entries", numGlobals, true, true);
+ }
+
+ m_isModified = false;
+}
+
+void KURLBar::writeItem( KURLBarItem *item, int i, TDEConfig *config,
+ bool global )
+{
+ if ( !item->isPersistent() )
+ return;
+
+ TQString Description = "Description_";
+ TQString URL = "URL_";
+ TQString Icon = "Icon_";
+ TQString IconGroup = "IconGroup_";
+
+ TQString number = TQString::number( i );
+ config->writePathEntry( URL + number, item->url().prettyURL(), true, global );
+
+ config->writeEntry( Description + number, item->description(),true,global);
+ config->writeEntry( Icon + number, item->icon(), true, global );
+ config->writeEntry( IconGroup + number, item->iconGroup(), true, global );
+}
+
+
+void KURLBar::slotDropped( TQDropEvent *e )
+{
+ KURL::List urls;
+ if ( KURLDrag::decode( e, urls ) ) {
+ KURL url;
+ TQString description;
+ TQString icon;
+ bool appLocal = false;
+
+ KURL::List::Iterator it = urls.begin();
+ for ( ; it != urls.end(); ++it ) {
+ (void) insertItem( *it, description, appLocal, icon );
+ m_isModified = true;
+ updateGeometry();
+ }
+ }
+}
+
+void KURLBar::slotContextMenuRequested( TQListBoxItem *_item, const TQPoint& pos )
+{
+ if (m_isImmutable)
+ return;
+
+ KURLBarItem *item = dynamic_cast<KURLBarItem*>( _item );
+
+ static const int IconSize = 10;
+ static const int AddItem = 20;
+ static const int EditItem = 30;
+ static const int RemoveItem = 40;
+
+ KURL lastURL = m_activeItem ? m_activeItem->url() : KURL();
+
+ bool smallIcons = m_iconSize < KIcon::SizeMedium;
+ TQPopupMenu *popup = new TQPopupMenu();
+ popup->insertItem( smallIcons ?
+ i18n("&Large Icons") : i18n("&Small Icons"),
+ IconSize );
+ popup->insertSeparator();
+
+ if (item != 0L && item->isPersistent())
+ {
+ popup->insertItem(SmallIconSet("edit"), i18n("&Edit Entry..."), EditItem);
+ popup->insertSeparator();
+ }
+
+ popup->insertItem(SmallIconSet("filenew"), i18n("&Add Entry..."), AddItem);
+
+ if (item != 0L && item->isPersistent())
+ {
+ popup->insertItem( SmallIconSet("editdelete"), i18n("&Remove Entry"),
+ RemoveItem );
+ }
+
+ int result = popup->exec( pos );
+ switch ( result ) {
+ case IconSize:
+ setIconSize( smallIcons ? KIcon::SizeMedium : KIcon::SizeSmallMedium );
+ m_listBox->triggerUpdate( true );
+ break;
+ case AddItem:
+ addNewItem();
+ break;
+ case EditItem:
+ editItem( static_cast<KURLBarItem *>( item ) );
+ break;
+ case RemoveItem:
+ delete item;
+ m_isModified = true;
+ break;
+ default: // abort
+ break;
+ }
+
+ // reset current item
+ m_activeItem = 0L;
+ setCurrentItem( lastURL );
+}
+
+bool KURLBar::addNewItem()
+{
+ KURLBarItem *item = new KURLBarItem( this, d->currentURL,
+ i18n("Enter a description") );
+ if ( editItem( item ) ) {
+ m_listBox->insertItem( item );
+ return true;
+ }
+
+ delete item;
+ return false;
+}
+
+bool KURLBar::editItem( KURLBarItem *item )
+{
+ if ( !item || !item->isPersistent() ) // should never happen tho
+ return false;
+
+ KURL url = item->url();
+ TQString description = item->description();
+ TQString icon = item->icon();
+ bool appLocal = item->applicationLocal();
+
+ if ( KURLBarItemDialog::getInformation( m_useGlobal,
+ url, description,
+ icon, appLocal,
+ m_iconSize, this ))
+ {
+ item->setURL( url );
+ item->setDescription( description );
+ item->setIcon( icon );
+ item->setApplicationLocal( appLocal );
+ m_listBox->triggerUpdate( true );
+ m_isModified = true;
+ updateGeometry();
+ return true;
+ }
+
+ return false;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+KURLBarListBox::KURLBarListBox( TQWidget *parent, const char *name )
+ : KListBox( parent, name )
+{
+ m_toolTip = new KURLBarToolTip( this );
+ setAcceptDrops( true );
+ viewport()->setAcceptDrops( true );
+}
+
+KURLBarListBox::~KURLBarListBox()
+{
+ delete m_toolTip;
+}
+
+void KURLBarListBox::paintEvent( TQPaintEvent* )
+{
+ TQPainter p(this);
+ p.setPen( colorGroup().mid() );
+ p.drawRect( 0, 0, width(), height() );
+}
+
+TQDragObject * KURLBarListBox::dragObject()
+{
+ KURL::List urls;
+ KURLBarItem *item = static_cast<KURLBarItem*>( firstItem() );
+
+ while ( item ) {
+ if ( item->isSelected() )
+ urls.append( item->url() );
+ item = static_cast<KURLBarItem*>( item->next() );
+ }
+
+ if ( !urls.isEmpty() ) // ### use custom drag-object with description etc.?
+ return new KURLDrag( urls, this, "urlbar drag" );
+
+ return 0L;
+}
+
+void KURLBarListBox::contentsDragEnterEvent( TQDragEnterEvent *e )
+{
+ e->accept( KURLDrag::canDecode( e ));
+}
+
+void KURLBarListBox::contentsDropEvent( TQDropEvent *e )
+{
+ emit dropped( e );
+}
+
+void KURLBarListBox::contextMenuEvent( TQContextMenuEvent *e )
+{
+ if (e)
+ {
+ emit contextMenuRequested( itemAt( e->globalPos() ), e->globalPos() );
+ e->consume(); // Consume the event to avoid multiple contextMenuEvent calls...
+ }
+}
+
+void KURLBarListBox::setOrientation( Qt::Orientation orient )
+{
+ if ( orient == Qt::Vertical ) {
+ setColumnMode( 1 );
+ setRowMode( Variable );
+ }
+ else {
+ setRowMode( 1 );
+ setColumnMode( Variable );
+ }
+
+ m_orientation = orient;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+bool KURLBarItemDialog::getInformation( bool allowGlobal, KURL& url,
+ TQString& description, TQString& icon,
+ bool& appLocal, int iconSize,
+ TQWidget *parent )
+{
+ KURLBarItemDialog *dialog = new KURLBarItemDialog( allowGlobal, url,
+ description, icon,
+ appLocal,
+ iconSize, parent );
+ if ( dialog->exec() == TQDialog::Accepted ) {
+ // set the return parameters
+ url = dialog->url();
+ description = dialog->description();
+ icon = dialog->icon();
+ appLocal = dialog->applicationLocal();
+
+ delete dialog;
+ return true;
+ }
+
+ delete dialog;
+ return false;
+}
+
+KURLBarItemDialog::KURLBarItemDialog( bool allowGlobal, const KURL& url,
+ const TQString& description,
+ TQString icon, bool appLocal,
+ int iconSize,
+ TQWidget *parent, const char *name )
+ : KDialogBase( parent, name, true,
+ i18n("Edit Quick Access Entry"), Ok | Cancel, Ok, true )
+{
+ TQVBox *box = new TQVBox( this );
+ TQString text = i18n("<qt><b>Please provide a description, URL and icon for this Quick Access entry.</b></br></qt>");
+ TQLabel *label = new TQLabel( text, box );
+ box->setSpacing( spacingHint() );
+
+ TQGrid *grid = new TQGrid( 2, box );
+ grid->setSpacing( spacingHint() );
+
+ TQString whatsThisText = i18n("<qt>This is the text that will appear in the Quick Access panel.<p>"
+ "The description should consist of one or two words "
+ "that will help you remember what this entry refers to.</qt>");
+ label = new TQLabel( i18n("&Description:"), grid );
+ m_edit = new KLineEdit( grid, "description edit" );
+ m_edit->setText( description.isEmpty() ? url.fileName() : description );
+ label->setBuddy( m_edit );
+ TQWhatsThis::add( label, whatsThisText );
+ TQWhatsThis::add( m_edit, whatsThisText );
+
+ whatsThisText = i18n("<qt>This is the location associated with the entry. Any valid URL may be used. For example:<p>"
+ "%1<br>http://www.kde.org<br>ftp://ftp.kde.org/pub/kde/stable<p>"
+ "By clicking on the button next to the text edit box you can browse to an "
+ "appropriate URL.</qt>").arg(TQDir::homeDirPath());
+ label = new TQLabel( i18n("&URL:"), grid );
+ m_urlEdit = new KURLRequester( url.prettyURL(), grid );
+ m_urlEdit->setMode( KFile::Directory );
+ label->setBuddy( m_urlEdit );
+ TQWhatsThis::add( label, whatsThisText );
+ TQWhatsThis::add( m_urlEdit, whatsThisText );
+
+ whatsThisText = i18n("<qt>This is the icon that will appear in the Quick Access panel.<p>"
+ "Click on the button to select a different icon.</qt>");
+ label = new TQLabel( i18n("Choose an &icon:"), grid );
+ m_iconButton = new KIconButton( grid, "icon button" );
+ m_iconButton->setIconSize( iconSize );
+ if ( icon.isEmpty() )
+ icon = KMimeType::iconForURL( url );
+ m_iconButton->setIcon( icon );
+ label->setBuddy( m_iconButton );
+ TQWhatsThis::add( label, whatsThisText );
+ TQWhatsThis::add( m_iconButton, whatsThisText );
+
+ if ( allowGlobal ) {
+ TQString appName;
+ if ( TDEGlobal::instance()->aboutData() )
+ appName = TDEGlobal::instance()->aboutData()->programName();
+ if ( appName.isEmpty() )
+ appName = TQString::fromLatin1( TDEGlobal::instance()->instanceName() );
+ m_appLocal = new TQCheckBox( i18n("&Only show when using this application (%1)").arg( appName ), box );
+ m_appLocal->setChecked( appLocal );
+ TQWhatsThis::add( m_appLocal,
+ i18n("<qt>Select this setting if you want this "
+ "entry to show only when using the current application (%1).<p>"
+ "If this setting is not selected, the entry will be available in all "
+ "applications.</qt>")
+ .arg(appName));
+ }
+ else
+ m_appLocal = 0L;
+ connect(m_urlEdit->lineEdit(),TQT_SIGNAL(textChanged ( const TQString & )),this,TQT_SLOT(urlChanged(const TQString & )));
+ m_edit->setFocus();
+ setMainWidget( box );
+}
+
+KURLBarItemDialog::~KURLBarItemDialog()
+{
+}
+
+void KURLBarItemDialog::urlChanged(const TQString & text )
+{
+ enableButtonOK( !text.isEmpty() );
+}
+
+KURL KURLBarItemDialog::url() const
+{
+ TQString text = m_urlEdit->url();
+ KURL u;
+ if ( text.at(0) == '/' )
+ u.setPath( text );
+ else
+ u = text;
+
+ return u;
+}
+
+TQString KURLBarItemDialog::description() const
+{
+ return m_edit->text();
+}
+
+TQString KURLBarItemDialog::icon() const
+{
+ return m_iconButton->icon();
+}
+
+bool KURLBarItemDialog::applicationLocal() const
+{
+ if ( !m_appLocal )
+ return true;
+
+ return m_appLocal->isChecked();
+}
+
+void KURLBarItem::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+void KURLBar::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+void KURLBarListBox::virtual_hook( int id, void* data )
+{ KListBox::virtual_hook( id, data ); }
+
+
+#include "kurlbar.moc"
diff --git a/kio/kfile/kurlbar.h b/tdeio/tdefile/kurlbar.h
index 32c05ec58..32c05ec58 100644
--- a/kio/kfile/kurlbar.h
+++ b/tdeio/tdefile/kurlbar.h
diff --git a/kio/kfile/kurlcombobox.cpp b/tdeio/tdefile/kurlcombobox.cpp
index e01be4548..e01be4548 100644
--- a/kio/kfile/kurlcombobox.cpp
+++ b/tdeio/tdefile/kurlcombobox.cpp
diff --git a/kio/kfile/kurlcombobox.h b/tdeio/tdefile/kurlcombobox.h
index a1fd9182d..a1fd9182d 100644
--- a/kio/kfile/kurlcombobox.h
+++ b/tdeio/tdefile/kurlcombobox.h
diff --git a/tdeio/tdefile/kurlrequester.cpp b/tdeio/tdefile/kurlrequester.cpp
new file mode 100644
index 000000000..cca8c0529
--- /dev/null
+++ b/tdeio/tdefile/kurlrequester.cpp
@@ -0,0 +1,430 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1999,2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2, as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <tqstring.h>
+#include <tqtooltip.h>
+#include <tqapplication.h>
+
+#include <kaccel.h>
+#include <kcombobox.h>
+#include <kdebug.h>
+#include <kdialog.h>
+#include <kdirselectdialog.h>
+#include <tdefiledialog.h>
+#include <kglobal.h>
+#include <kiconloader.h>
+#include <klineedit.h>
+#include <klocale.h>
+#include <kurlcompletion.h>
+#include <kurldrag.h>
+#include <kprotocolinfo.h>
+
+#include "kurlrequester.h"
+
+
+class KURLDragPushButton : public KPushButton
+{
+public:
+ KURLDragPushButton( TQWidget *parent, const char *name=0 )
+ : KPushButton( parent, name ) {
+ setDragEnabled( true );
+ }
+ ~KURLDragPushButton() {}
+
+ void setURL( const KURL& url ) {
+ m_urls.clear();
+ m_urls.append( url );
+ }
+
+ /* not needed so far
+ void setURLs( const KURL::List& urls ) {
+ m_urls = urls;
+ }
+ const KURL::List& urls() const { return m_urls; }
+ */
+
+protected:
+ virtual TQDragObject *dragObject() {
+ if ( m_urls.isEmpty() )
+ return 0L;
+
+ TQDragObject *drag = new KURLDrag( m_urls, this, "url drag" );
+ return drag;
+ }
+
+private:
+ KURL::List m_urls;
+
+};
+
+
+/*
+*************************************************************************
+*/
+
+class KURLRequester::KURLRequesterPrivate
+{
+public:
+ KURLRequesterPrivate() {
+ edit = 0L;
+ combo = 0L;
+ fileDialogMode = KFile::File | KFile::ExistingOnly | KFile::LocalOnly;
+ }
+
+ void setText( const TQString& text ) {
+ if ( combo )
+ {
+ if (combo->editable())
+ {
+ combo->setEditText( text );
+ }
+ else
+ {
+ combo->insertItem( text );
+ combo->setCurrentItem( combo->count()-1 );
+ }
+ }
+ else
+ {
+ edit->setText( text );
+ }
+ }
+
+ void connectSignals( TQObject *receiver ) {
+ TQObject *sender;
+ if ( combo )
+ sender = TQT_TQOBJECT(combo);
+ else
+ sender = TQT_TQOBJECT(edit);
+
+ connect( sender, TQT_SIGNAL( textChanged( const TQString& )),
+ receiver, TQT_SIGNAL( textChanged( const TQString& )));
+ connect( sender, TQT_SIGNAL( returnPressed() ),
+ receiver, TQT_SIGNAL( returnPressed() ));
+ connect( sender, TQT_SIGNAL( returnPressed( const TQString& ) ),
+ receiver, TQT_SIGNAL( returnPressed( const TQString& ) ));
+ }
+
+ void setCompletionObject( KCompletion *comp ) {
+ if ( combo )
+ combo->setCompletionObject( comp );
+ else
+ edit->setCompletionObject( comp );
+ }
+
+ /**
+ * replaces ~user or $FOO, if necessary
+ */
+ TQString url() {
+ TQString txt = combo ? combo->currentText() : edit->text();
+ KURLCompletion *comp;
+ if ( combo )
+ comp = dynamic_cast<KURLCompletion*>(combo->completionObject());
+ else
+ comp = dynamic_cast<KURLCompletion*>(edit->completionObject());
+
+ if ( comp )
+ return comp->replacedPath( txt );
+ else
+ return txt;
+ }
+
+ KLineEdit *edit;
+ KComboBox *combo;
+ int fileDialogMode;
+ TQString fileDialogFilter;
+};
+
+
+
+KURLRequester::KURLRequester( TQWidget *editWidget, TQWidget *parent,
+ const char *name )
+ : TQHBox( parent, name )
+{
+ d = new KURLRequesterPrivate;
+
+ // must have this as parent
+ editWidget->reparent( this, 0, TQPoint(0,0) );
+ d->edit = dynamic_cast<KLineEdit*>( editWidget );
+ d->combo = dynamic_cast<KComboBox*>( editWidget );
+
+ init();
+}
+
+
+KURLRequester::KURLRequester( TQWidget *parent, const char *name )
+ : TQHBox( parent, name )
+{
+ d = new KURLRequesterPrivate;
+ init();
+}
+
+
+KURLRequester::KURLRequester( const TQString& url, TQWidget *parent,
+ const char *name )
+ : TQHBox( parent, name )
+{
+ d = new KURLRequesterPrivate;
+ init();
+ setKURL( KURL::fromPathOrURL( url ) );
+}
+
+
+KURLRequester::~KURLRequester()
+{
+ delete myCompletion;
+ delete myFileDialog;
+ delete d;
+}
+
+
+void KURLRequester::init()
+{
+ myFileDialog = 0L;
+ myShowLocalProt = false;
+
+ if ( !d->combo && !d->edit )
+ d->edit = new KLineEdit( this, "line edit" );
+
+ myButton = new KURLDragPushButton( this, "tdefile button");
+ TQIconSet iconSet = SmallIconSet(TQString::fromLatin1("fileopen"));
+ TQPixmap pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
+ myButton->setIconSet( iconSet );
+ myButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
+ TQToolTip::add(myButton, i18n("Open file dialog"));
+
+ connect( myButton, TQT_SIGNAL( pressed() ), TQT_SLOT( slotUpdateURL() ));
+
+ setSpacing( KDialog::spacingHint() );
+
+ TQWidget *widget = d->combo ? (TQWidget*) d->combo : (TQWidget*) d->edit;
+ widget->installEventFilter( this );
+ setFocusProxy( widget );
+
+ d->connectSignals( TQT_TQOBJECT(this) );
+ connect( myButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotOpenDialog() ));
+
+ myCompletion = new KURLCompletion();
+ d->setCompletionObject( myCompletion );
+
+ KAccel *accel = new KAccel( this );
+ accel->insert( KStdAccel::Open, TQT_TQOBJECT(this), TQT_SLOT( slotOpenDialog() ));
+ accel->readSettings();
+}
+
+
+void KURLRequester::setURL( const TQString& url )
+{
+ if ( myShowLocalProt )
+ {
+ d->setText( url );
+ }
+ else
+ {
+ // ### This code is broken (e.g. for paths with '#')
+ if ( url.startsWith("file://") )
+ d->setText( url.mid( 7 ) );
+ else if ( url.startsWith("file:") )
+ d->setText( url.mid( 5 ) );
+ else
+ d->setText( url );
+ }
+}
+
+void KURLRequester::setKURL( const KURL& url )
+{
+ if ( myShowLocalProt )
+ d->setText( url.url() );
+ else
+ d->setText( url.pathOrURL() );
+}
+
+void KURLRequester::setCaption( const TQString& caption )
+{
+ TQWidget::setCaption( caption );
+ if (myFileDialog)
+ myFileDialog->setCaption( caption );
+}
+
+TQString KURLRequester::url() const
+{
+ return d->url();
+}
+
+void KURLRequester::slotOpenDialog()
+{
+ KURL newurl;
+ if ( (d->fileDialogMode & KFile::Directory) && !(d->fileDialogMode & KFile::File) ||
+ /* catch possible fileDialog()->setMode( KFile::Directory ) changes */
+ (myFileDialog && ( (myFileDialog->mode() & KFile::Directory) &&
+ (myFileDialog->mode() & (KFile::File | KFile::Files)) == 0 ) ) )
+ {
+ newurl = KDirSelectDialog::selectDirectory(url(), d->fileDialogMode & KFile::LocalOnly);
+ if ( !newurl.isValid() )
+ {
+ return;
+ }
+ }
+ else
+ {
+ emit openFileDialog( this );
+
+ KFileDialog *dlg = fileDialog();
+ if ( !d->url().isEmpty() ) {
+ KURL u( url() );
+ // If we won't be able to list it (e.g. http), then don't try :)
+ if ( KProtocolInfo::supportsListing( u ) )
+ dlg->setSelection( u.url() );
+ }
+
+ if ( dlg->exec() != TQDialog::Accepted )
+ {
+ return;
+ }
+
+ newurl = dlg->selectedURL();
+ }
+
+ setKURL( newurl );
+ emit urlSelected( d->url() );
+}
+
+void KURLRequester::setMode(uint mode)
+{
+ Q_ASSERT( (mode & KFile::Files) == 0 );
+ d->fileDialogMode = mode;
+ if ( (mode & KFile::Directory) && !(mode & KFile::File) )
+ myCompletion->setMode( KURLCompletion::DirCompletion );
+
+ if (myFileDialog)
+ myFileDialog->setMode( d->fileDialogMode );
+}
+
+unsigned int KURLRequester::mode() const
+{
+ return d->fileDialogMode;
+}
+
+void KURLRequester::setFilter(const TQString &filter)
+{
+ d->fileDialogFilter = filter;
+ if (myFileDialog)
+ myFileDialog->setFilter( d->fileDialogFilter );
+}
+
+TQString KURLRequester::filter( ) const
+{
+ return d->fileDialogFilter;
+}
+
+
+KFileDialog * KURLRequester::fileDialog() const
+{
+ if ( !myFileDialog ) {
+ TQWidget *p = parentWidget();
+ myFileDialog = new KFileDialog( TQString::null, d->fileDialogFilter, p,
+ "file dialog", true );
+
+ myFileDialog->setMode( d->fileDialogMode );
+ myFileDialog->setCaption( caption() );
+ }
+
+ return myFileDialog;
+}
+
+
+void KURLRequester::setShowLocalProtocol( bool b )
+{
+ if ( myShowLocalProt == b )
+ return;
+
+ myShowLocalProt = b;
+ setKURL( url() );
+}
+
+void KURLRequester::clear()
+{
+ d->setText( TQString::null );
+}
+
+KLineEdit * KURLRequester::lineEdit() const
+{
+ return d->edit;
+}
+
+KComboBox * KURLRequester::comboBox() const
+{
+ return d->combo;
+}
+
+void KURLRequester::slotUpdateURL()
+{
+ // bin compat, myButton is declared as QPushButton
+ KURL u;
+ u = KURL( KURL( TQDir::currentDirPath() + '/' ), url() );
+ (static_cast<KURLDragPushButton *>( myButton ))->setURL( u );
+}
+
+bool KURLRequester::eventFilter( TQObject *obj, TQEvent *ev )
+{
+ if ( ( TQT_BASE_OBJECT(d->edit) == TQT_BASE_OBJECT(obj) ) || ( TQT_BASE_OBJECT(d->combo) == TQT_BASE_OBJECT(obj) ) )
+ {
+ if (( ev->type() == TQEvent::FocusIn ) || ( ev->type() == TQEvent::FocusOut ))
+ // Forward focusin/focusout events to the urlrequester; needed by file form element in tdehtml
+ TQApplication::sendEvent( this, ev );
+ }
+ return TQWidget::eventFilter( obj, ev );
+}
+
+KPushButton * KURLRequester::button() const
+{
+ return myButton;
+}
+
+KEditListBox::CustomEditor KURLRequester::customEditor()
+{
+ setSizePolicy(TQSizePolicy( TQSizePolicy::Preferred,
+ TQSizePolicy::Fixed));
+
+ KLineEdit *edit = d->edit;
+ if ( !edit && d->combo )
+ edit = dynamic_cast<KLineEdit*>( d->combo->lineEdit() );
+
+#ifndef NDEBUG
+ if ( !edit )
+ kdWarning() << "KURLRequester's lineedit is not a KLineEdit!??\n";
+#endif
+
+ KEditListBox::CustomEditor editor( this, edit );
+ return editor;
+}
+
+void KURLRequester::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+KURLComboRequester::KURLComboRequester( TQWidget *parent,
+ const char *name )
+ : KURLRequester( new KComboBox(false), parent, name)
+{
+}
+
+#include "kurlrequester.moc"
diff --git a/tdeio/tdefile/kurlrequester.h b/tdeio/tdefile/kurlrequester.h
new file mode 100644
index 000000000..55bc0fd83
--- /dev/null
+++ b/tdeio/tdefile/kurlrequester.h
@@ -0,0 +1,301 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1999,2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2, as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+
+#ifndef KURLREQUESTER_H
+#define KURLREQUESTER_H
+
+#include <tqhbox.h>
+
+#include <keditlistbox.h>
+#include <tdefile.h>
+#include <kpushbutton.h>
+#include <kurl.h>
+
+class KComboBox;
+class KFileDialog;
+class KLineEdit;
+class KURLCompletion;
+class KURLDragPushButton;
+
+class TQString;
+class TQTimer;
+
+/**
+ * This class is a widget showing a lineedit and a button, which invokes a
+ * filedialog. File name completion is available in the lineedit.
+ *
+ * The defaults for the filedialog are to ask for one existing local file, i.e.
+ * KFileDialog::setMode( KFile::File | KFile::ExistingOnly | KFile::LocalOnly )
+ * The default filter is "*", i.e. show all files, and the start directory is
+ * the current working directory, or the last directory where a file has been
+ * selected.
+ *
+ * You can change this behavior by using setMode() or setFilter().
+ *
+ * \image html kurlrequester.png "KDE URL Requester"
+ *
+ * @short A widget to request a filename/url from the user
+ * @author Carsten Pfeiffer <pfeiffer@kde.org>
+ */
+class TDEIO_EXPORT KURLRequester : public TQHBox
+{
+ Q_OBJECT
+ TQ_PROPERTY( TQString url READ url WRITE setURL )
+ TQ_PROPERTY( bool showLocalProtocol READ showLocalProtocol WRITE setShowLocalProtocol )
+ TQ_PROPERTY( TQString filter READ filter WRITE setFilter )
+ TQ_PROPERTY( uint mode READ mode WRITE setMode )
+
+public:
+ /**
+ * Constructs a KURLRequester widget.
+ */
+ KURLRequester( TQWidget *parent=0, const char *name=0 );
+
+ /**
+ * Constructs a KURLRequester widget with the initial URL @p url.
+ * // TODO KDE4: Use KURL instead
+ */
+ KURLRequester( const TQString& url, TQWidget *parent=0, const char *name=0 );
+
+ /**
+ * Special constructor, which creates a KURLRequester widget with a custom
+ * edit-widget. The edit-widget can be either a KComboBox or a KLineEdit
+ * (or inherited thereof). Note: for geometry management reasons, the
+ * edit-widget is reparented to have the KURLRequester as parent.
+ */
+ KURLRequester( TQWidget *editWidget, TQWidget *parent, const char *name=0 );
+ /**
+ * Destructs the KURLRequester.
+ */
+ ~KURLRequester();
+
+ /**
+ * @returns the current url in the lineedit. May be malformed, if the user
+ * entered something weird. ~user or environment variables are substituted
+ * for local files.
+ * // TODO KDE4: Use KURL so that the result is properly defined
+ */
+ TQString url() const;
+
+ /**
+ * Enables/disables showing file:/ in the lineedit, when a local file has
+ * been selected in the filedialog or was set via setURL().
+ * Default is false, not showing file:/
+ * @see showLocalProtocol
+ */
+ void setShowLocalProtocol( bool b );
+
+ /**
+ * Sets the mode of the file dialog.
+ * Note: you can only select one file with the filedialog,
+ * so KFile::Files doesn't make much sense.
+ * @see KFileDialog::setMode()
+ */
+ void setMode( uint m );
+
+ /**
+ * Returns the current mode
+ * @see KFileDialog::mode()
+ * @since 3.3
+ */
+ uint mode() const;
+
+
+ /**
+ * Sets the filter for the file dialog.
+ * @see KFileDialog::setFilter()
+ */
+ void setFilter( const TQString& filter );
+
+ /**
+ * Returns the current filter for the file dialog.
+ * @see KFileDialog::filter()
+ * @since 3.3
+ */
+ TQString filter() const;
+
+ /**
+ * @returns whether local files will be prefixed with file:/ in the
+ * lineedit
+ * @see setShowLocalProtocol
+ */
+ bool showLocalProtocol() const { return myShowLocalProt; }
+ // ## KDE4: there's no reason to keep this, it should always be false
+
+ /**
+ * @returns a pointer to the filedialog
+ * You can use this to customize the dialog, e.g. to specify a filter.
+ * Never returns 0L.
+ *
+ * Remove in KDE4? KURLRequester should use KDirSelectDialog for
+ * (mode & KFile::Directory) && !(mode & KFile::File)
+ */
+ virtual KFileDialog * fileDialog() const;
+
+ /**
+ * @returns a pointer to the lineedit, either the default one, or the
+ * special one, if you used the special constructor.
+ *
+ * It is provided so that you can e.g. set an own completion object
+ * (e.g. KShellCompletion) into it.
+ */
+ KLineEdit * lineEdit() const;
+
+ /**
+ * @returns a pointer to the combobox, in case you have set one using the
+ * special constructor. Returns 0L otherwise.
+ */
+ KComboBox * comboBox() const;
+
+ /**
+ * @returns a pointer to the pushbutton. It is provided so that you can
+ * specify an own pixmap or a text, if you really need to.
+ */
+ KPushButton * button() const;
+
+ /**
+ * @returns the KURLCompletion object used in the lineedit/combobox.
+ */
+ KURLCompletion *completionObject() const { return myCompletion; }
+
+ /**
+ * @returns an object, suitable for use with KEditListBox. It allows you
+ * to put this KURLRequester into a KEditListBox.
+ * Basically, do it like this:
+ * \code
+ * KURLRequester *req = new KURLRequester( someWidget );
+ * [...]
+ * KEditListBox *editListBox = new KEditListBox( i18n("Some Title"), req->customEditor(), someWidget );
+ * \endcode
+ * @since 3.1
+ */
+ KEditListBox::CustomEditor customEditor();
+
+public slots:
+ /**
+ * Sets the url in the lineedit to @p url. Depending on the state of
+ * showLocalProtocol(), file:/ on local files will be shown or not.
+ * @since 3.1
+ * // TODO KDE4: Use KURL instead
+ */
+ void setURL( const TQString& url );
+
+ /**
+ * Sets the url in the lineedit to @p url.
+ * @since 3.4
+ * // TODO KDE4: rename to setURL
+ */
+ void setKURL( const KURL& url );
+
+ /**
+ * Sets the caption of the file dialog.
+ * @since 3.1
+ */
+ virtual void setCaption( const TQString& caption );
+
+ /**
+ * Clears the lineedit/combobox.
+ */
+ void clear();
+
+signals:
+ // forwards from LineEdit
+ /**
+ * Emitted when the text in the lineedit changes.
+ * The parameter contains the contents of the lineedit.
+ * @since 3.1
+ */
+ void textChanged( const TQString& );
+
+ /**
+ * Emitted when return or enter was pressed in the lineedit.
+ */
+ void returnPressed();
+
+ /**
+ * Emitted when return or enter was pressed in the lineedit.
+ * The parameter contains the contents of the lineedit.
+ */
+ void returnPressed( const TQString& );
+
+ /**
+ * Emitted before the filedialog is going to open. Connect
+ * to this signal to "configure" the filedialog, e.g. set the
+ * filefilter, the mode, a preview-widget, etc. It's usually
+ * not necessary to set a URL for the filedialog, as it will
+ * get set properly from the editfield contents.
+ *
+ * If you use multiple KURLRequesters, you can connect all of them
+ * to the same slot and use the given KURLRequester pointer to know
+ * which one is going to open.
+ */
+ void openFileDialog( KURLRequester * );
+
+ /**
+ * Emitted when the user changed the URL via the file dialog.
+ * The parameter contains the contents of the lineedit.
+ * // TODO KDE4: Use KURL instead
+ */
+ void urlSelected( const TQString& );
+
+protected:
+ void init();
+
+ KURLCompletion * myCompletion;
+
+
+private:
+ KURLDragPushButton * myButton;
+ bool myShowLocalProt;
+ mutable KFileDialog * myFileDialog;
+
+
+protected slots:
+ /**
+ * Called when the button is pressed to open the filedialog.
+ * Also called when KStdAccel::Open (default is Ctrl-O) is pressed.
+ */
+ void slotOpenDialog();
+
+private slots:
+ void slotUpdateURL();
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+ bool eventFilter( TQObject *obj, TQEvent *ev );
+private:
+ class KURLRequesterPrivate;
+ KURLRequesterPrivate *d;
+};
+
+/**
+ * URL requester with a combo box, for use in Designer
+ */
+class TDEIO_EXPORT KURLComboRequester : public KURLRequester
+{
+ Q_OBJECT
+public:
+ /**
+ * Constructs a KURLRequester widget with a combobox.
+ */
+ KURLComboRequester( TQWidget *parent=0, const char *name=0 );
+};
+
+
+#endif // KURLREQUESTER_H
diff --git a/tdeio/tdefile/kurlrequesterdlg.cpp b/tdeio/tdefile/kurlrequesterdlg.cpp
new file mode 100644
index 000000000..7524ea149
--- /dev/null
+++ b/tdeio/tdefile/kurlrequesterdlg.cpp
@@ -0,0 +1,135 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Wilco Greven <greven@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqstring.h>
+#include <tqtoolbutton.h>
+
+#include <kaccel.h>
+#include <tdefiledialog.h>
+#include <kglobal.h>
+#include <kiconloader.h>
+#include <klineedit.h>
+#include <klocale.h>
+#include <krecentdocument.h>
+#include <kurl.h>
+#include <kurlrequester.h>
+
+#include "kurlrequesterdlg.h"
+
+
+KURLRequesterDlg::KURLRequesterDlg( const TQString& urlName, TQWidget *parent,
+ const char *name, bool modal )
+ : KDialogBase( Plain, TQString::null, Ok|Cancel|User1, Ok, parent, name,
+ modal, true, KStdGuiItem::clear() )
+{
+ initDialog(i18n( "Location:" ), urlName);
+}
+
+KURLRequesterDlg::KURLRequesterDlg( const TQString& urlName, const TQString& _text, TQWidget *parent, const char *name, bool modal )
+ : KDialogBase( Plain, TQString::null, Ok|Cancel|User1, Ok, parent, name,
+ modal, true, KStdGuiItem::clear() )
+{
+ initDialog(_text, urlName);
+}
+
+KURLRequesterDlg::~KURLRequesterDlg()
+{
+}
+
+void KURLRequesterDlg::initDialog(const TQString &text,const TQString &urlName)
+{
+ TQVBoxLayout * topLayout = new TQVBoxLayout( plainPage(), 0,
+ spacingHint() );
+
+ TQLabel * label = new TQLabel( text , plainPage() );
+ topLayout->addWidget( label );
+
+ urlRequester_ = new KURLRequester( urlName, plainPage(), "urlRequester" );
+ urlRequester_->setMinimumWidth( urlRequester_->sizeHint().width() * 3 );
+ topLayout->addWidget( urlRequester_ );
+ urlRequester_->setFocus();
+ connect( urlRequester_->lineEdit(), TQT_SIGNAL(textChanged(const TQString&)),
+ TQT_SLOT(slotTextChanged(const TQString&)) );
+ bool state = !urlName.isEmpty();
+ enableButtonOK( state );
+ enableButton( KDialogBase::User1, state );
+ /*
+ KFile::Mode mode = static_cast<KFile::Mode>( KFile::File |
+ KFile::ExistingOnly );
+ urlRequester_->setMode( mode );
+ */
+ connect( this, TQT_SIGNAL( user1Clicked() ), TQT_SLOT( slotClear() ) );
+}
+
+void KURLRequesterDlg::slotTextChanged(const TQString & text)
+{
+ bool state = !text.stripWhiteSpace().isEmpty();
+ enableButtonOK( state );
+ enableButton( KDialogBase::User1, state );
+}
+
+void KURLRequesterDlg::slotClear()
+{
+ urlRequester_->clear();
+}
+
+KURL KURLRequesterDlg::selectedURL() const
+{
+ if ( result() == TQDialog::Accepted )
+ return KURL::fromPathOrURL( urlRequester_->url() );
+ else
+ return KURL();
+}
+
+
+KURL KURLRequesterDlg::getURL(const TQString& dir, TQWidget *parent,
+ const TQString& caption)
+{
+ KURLRequesterDlg dlg(dir, parent, "filedialog", true);
+
+ dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
+
+ dlg.exec();
+
+ const KURL& url = dlg.selectedURL();
+ if (url.isValid())
+ KRecentDocument::add(url);
+
+ return url;
+}
+
+KFileDialog * KURLRequesterDlg::fileDialog()
+{
+ return urlRequester_->fileDialog();
+}
+
+KURLRequester * KURLRequesterDlg::urlRequester()
+{
+ return urlRequester_;
+}
+
+#include "kurlrequesterdlg.moc"
+
+// vim:ts=4:sw=4:tw=78
diff --git a/kio/kfile/kurlrequesterdlg.h b/tdeio/tdefile/kurlrequesterdlg.h
index 07b70d745..07b70d745 100644
--- a/kio/kfile/kurlrequesterdlg.h
+++ b/tdeio/tdefile/kurlrequesterdlg.h
diff --git a/tdeio/tdefile/tdefile.h b/tdeio/tdefile/tdefile.h
new file mode 100644
index 000000000..d4616b642
--- /dev/null
+++ b/tdeio/tdefile/tdefile.h
@@ -0,0 +1,129 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ version 2, License as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef KFILE_H
+#define KFILE_H
+
+#include <tqdir.h>
+
+#include "tdelibs_export.h"
+
+/**
+ * KFile is a class which provides a namespace for some enumerated
+ * values associated with the tdefile library. You will never need to
+ * construct a KFile object itself.
+ */
+
+class TDEIO_EXPORT KFile
+{
+public:
+ /**
+ * Modes of operation for the dialog.
+ * @li @p File - Get a single file name from the user.
+ * @li @p Directory - Get a directory name from the user.
+ * @li @p Files - Get multiple file names from the user.
+ * @li @p ExistingOnly - Never return a filename which does not exist yet
+ * @li @p LocalOnly - Don't return remote filenames
+ */
+ enum Mode {
+ File = 1,
+ Directory = 2,
+ Files = 4,
+ ExistingOnly = 8,
+ LocalOnly = 16,
+ ModeMax = 65536
+ };
+
+ enum FileView {
+ Default = 0,
+ Simple = 1,
+ Detail = 2,
+ SeparateDirs = 4,
+ PreviewContents = 8,
+ PreviewInfo = 16,
+ FileViewMax = 65536
+ };
+
+ enum SelectionMode {
+ Single = 1,
+ Multi = 2,
+ Extended = 4,
+ NoSelection = 8
+ };
+
+
+ //
+ // some bittests
+ //
+
+
+ // sorting specific
+
+ // grr, who had the idea to set TQDir::Name to 0x0?
+ static bool isSortByName( const TQDir::SortSpec& sort ) {
+ return (sort & TQDir::Time) != TQDir::Time &&
+ (sort & TQDir::Size) != TQDir::Size;
+ }
+
+ static bool isSortBySize( const TQDir::SortSpec& sort ) {
+ return (sort & TQDir::Size) == TQDir::Size;
+ }
+
+ static bool isSortByDate( const TQDir::SortSpec& sort ) {
+ return (sort & TQDir::Time) == TQDir::Time;
+ }
+
+ static bool isSortDirsFirst( const TQDir::SortSpec& sort ) {
+ return (sort & TQDir::DirsFirst) == TQDir::DirsFirst;
+ }
+
+ static bool isSortCaseInsensitive( const TQDir::SortSpec& sort ) {
+ return (sort & TQDir::IgnoreCase) == TQDir::IgnoreCase;
+ }
+
+
+ // view specific
+ static bool isDefaultView( const FileView& view ) {
+ return (view & Default) == Default;
+ }
+
+ static bool isSimpleView( const FileView& view ) {
+ return (view & Simple) == Simple;
+ }
+
+ static bool isDetailView( const FileView& view ) {
+ return (view & Detail) == Detail;
+ }
+
+ static bool isSeparateDirs( const FileView& view ) {
+ return (view & SeparateDirs) == SeparateDirs;
+ }
+
+ static bool isPreviewContents( const FileView& view ) {
+ return (view & PreviewContents) == PreviewContents;
+ }
+
+ /**
+ * @since 3.1
+ */
+ static bool isPreviewInfo( const FileView& view ) {
+ return (view & PreviewInfo) == PreviewInfo;
+ }
+
+};
+
+#endif // KFILE_H
diff --git a/tdeio/tdefile/tdefilebookmarkhandler.cpp b/tdeio/tdefile/tdefilebookmarkhandler.cpp
new file mode 100644
index 000000000..d05a94541
--- /dev/null
+++ b/tdeio/tdefile/tdefilebookmarkhandler.cpp
@@ -0,0 +1,81 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation, version 2.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <kbookmarkimporter.h>
+#include <kbookmarkdombuilder.h>
+#include <kpopupmenu.h>
+#include <kstandarddirs.h>
+
+#include "tdefiledialog.h"
+#include "tdefilebookmarkhandler.h"
+
+KFileBookmarkHandler::KFileBookmarkHandler( KFileDialog *dialog )
+ : TQObject( dialog, "KFileBookmarkHandler" ),
+ KBookmarkOwner(),
+ m_dialog( dialog )
+{
+ m_menu = new KPopupMenu( dialog, "bookmark menu" );
+
+ TQString file = locate( "data", "tdefile/bookmarks.xml" );
+ if ( file.isEmpty() )
+ file = locateLocal( "data", "tdefile/bookmarks.xml" );
+
+ KBookmarkManager *manager = KBookmarkManager::managerForFile( file, false);
+
+ // import old bookmarks
+ if ( !KStandardDirs::exists( file ) ) {
+ TQString oldFile = locate( "data", "tdefile/bookmarks.html" );
+ if ( !oldFile.isEmpty() )
+ importOldBookmarks( oldFile, manager );
+ }
+
+ manager->setUpdate( true );
+ manager->setShowNSBookmarks( false );
+
+ m_bookmarkMenu = new KBookmarkMenu( manager, this, m_menu,
+ dialog->actionCollection(), true );
+}
+
+KFileBookmarkHandler::~KFileBookmarkHandler()
+{
+ delete m_bookmarkMenu;
+}
+
+TQString KFileBookmarkHandler::currentURL() const
+{
+ return m_dialog->baseURL().url();
+}
+
+void KFileBookmarkHandler::importOldBookmarks( const TQString& path,
+ KBookmarkManager *manager )
+{
+ KBookmarkDomBuilder *builder = new KBookmarkDomBuilder( manager->root(), manager );
+ KNSBookmarkImporter importer( path );
+ builder->connectImporter( &importer );
+ importer.parseNSBookmarks();
+ delete builder;
+ manager->save();
+}
+
+void KFileBookmarkHandler::virtual_hook( int id, void* data )
+{ KBookmarkOwner::virtual_hook( id, data ); }
+
+#include "tdefilebookmarkhandler.moc"
diff --git a/kio/kfile/kfilebookmarkhandler.h b/tdeio/tdefile/tdefilebookmarkhandler.h
index 9b615c87e..9b615c87e 100644
--- a/kio/kfile/kfilebookmarkhandler.h
+++ b/tdeio/tdefile/tdefilebookmarkhandler.h
diff --git a/tdeio/tdefile/tdefiledetailview.cpp b/tdeio/tdefile/tdefiledetailview.cpp
new file mode 100644
index 000000000..b989104e8
--- /dev/null
+++ b/tdeio/tdefile/tdefiledetailview.cpp
@@ -0,0 +1,686 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
+ 2000, 2001 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqevent.h>
+#include <tqkeycode.h>
+#include <tqheader.h>
+#include <tqpainter.h>
+#include <tqpixmap.h>
+
+#include <kapplication.h>
+#include <tdefileitem.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <kiconloader.h>
+#include <kicontheme.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <kurldrag.h>
+
+#include "tdefiledetailview.h"
+#include "config-tdefile.h"
+
+#define COL_NAME 0
+#define COL_SIZE 1
+#define COL_DATE 2
+#define COL_PERM 3
+#define COL_OWNER 4
+#define COL_GROUP 5
+
+class KFileDetailView::KFileDetailViewPrivate
+{
+public:
+ KFileDetailViewPrivate() : dropItem(0)
+ { }
+
+ KFileListViewItem *dropItem;
+ TQTimer autoOpenTimer;
+};
+
+KFileDetailView::KFileDetailView(TQWidget *parent, const char *name)
+ : KListView(parent, name), KFileView(), d(new KFileDetailViewPrivate())
+{
+ // this is always the static section, not the index depending on column order
+ m_sortingCol = COL_NAME;
+ m_blockSortingSignal = false;
+ setViewName( i18n("Detailed View") );
+
+ addColumn( i18n( "Name" ) );
+ addColumn( i18n( "Size" ) );
+ addColumn( i18n( "Date" ) );
+ addColumn( i18n( "Permissions" ) );
+ addColumn( i18n( "Owner" ) );
+ addColumn( i18n( "Group" ) );
+ setShowSortIndicator( true );
+ setAllColumnsShowFocus( true );
+ setDragEnabled(true);
+
+ connect( header(), TQT_SIGNAL( clicked(int)),
+ TQT_SLOT(slotSortingChanged(int) ));
+
+
+ connect( this, TQT_SIGNAL( returnPressed(TQListViewItem *) ),
+ TQT_SLOT( slotActivate( TQListViewItem *) ) );
+
+ connect( this, TQT_SIGNAL( clicked(TQListViewItem *, const TQPoint&, int)),
+ TQT_SLOT( selected( TQListViewItem *) ) );
+ connect( this, TQT_SIGNAL( doubleClicked(TQListViewItem *, const TQPoint&, int)),
+ TQT_SLOT( slotActivate( TQListViewItem *) ) );
+
+ connect( this, TQT_SIGNAL(contextMenuRequested( TQListViewItem *,
+ const TQPoint &, int )),
+ this, TQT_SLOT( slotActivateMenu( TQListViewItem *, const TQPoint& )));
+
+ KFile::SelectionMode sm = KFileView::selectionMode();
+ switch ( sm ) {
+ case KFile::Multi:
+ TQListView::setSelectionMode( TQListView::Multi );
+ break;
+ case KFile::Extended:
+ TQListView::setSelectionMode( TQListView::Extended );
+ break;
+ case KFile::NoSelection:
+ TQListView::setSelectionMode( TQListView::NoSelection );
+ break;
+ default: // fall through
+ case KFile::Single:
+ TQListView::setSelectionMode( TQListView::Single );
+ break;
+ }
+
+ // for highlighting
+ if ( sm == KFile::Multi || sm == KFile::Extended )
+ connect( this, TQT_SIGNAL( selectionChanged() ),
+ TQT_SLOT( slotSelectionChanged() ));
+ else
+ connect( this, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ),
+ TQT_SLOT( highlighted( TQListViewItem * ) ));
+
+ // DND
+ connect( &(d->autoOpenTimer), TQT_SIGNAL( timeout() ),
+ this, TQT_SLOT( slotAutoOpen() ));
+
+ setSorting( sorting() );
+
+ m_resolver =
+ new KMimeTypeResolver<KFileListViewItem,KFileDetailView>( this );
+}
+
+KFileDetailView::~KFileDetailView()
+{
+ delete m_resolver;
+ delete d;
+}
+
+void KFileDetailView::readConfig( TDEConfig *config, const TQString& group )
+{
+ restoreLayout( config, group );
+}
+
+void KFileDetailView::writeConfig( TDEConfig *config, const TQString& group )
+{
+ saveLayout( config, group );
+}
+
+void KFileDetailView::setSelected( const KFileItem *info, bool enable )
+{
+ if ( !info )
+ return;
+
+ // we can only hope that this casts works
+ KFileListViewItem *item = (KFileListViewItem*)info->extraData( this );
+
+ if ( item )
+ KListView::setSelected( item, enable );
+}
+
+void KFileDetailView::setCurrentItem( const KFileItem *item )
+{
+ if ( !item )
+ return;
+ KFileListViewItem *it = (KFileListViewItem*) item->extraData( this );
+ if ( it )
+ KListView::setCurrentItem( it );
+}
+
+KFileItem * KFileDetailView::currentFileItem() const
+{
+ KFileListViewItem *current = static_cast<KFileListViewItem*>( currentItem() );
+ if ( current )
+ return current->fileInfo();
+
+ return 0L;
+}
+
+void KFileDetailView::clearSelection()
+{
+ KListView::clearSelection();
+}
+
+void KFileDetailView::selectAll()
+{
+ if (KFileView::selectionMode() == KFile::NoSelection ||
+ KFileView::selectionMode() == KFile::Single)
+ return;
+
+ KListView::selectAll( true );
+}
+
+void KFileDetailView::invertSelection()
+{
+ KListView::invertSelection();
+}
+
+void KFileDetailView::slotActivateMenu (TQListViewItem *item,const TQPoint& pos )
+{
+ if ( !item ) {
+ sig->activateMenu( 0, pos );
+ return;
+ }
+ KFileListViewItem *i = (KFileListViewItem*) item;
+ sig->activateMenu( i->fileInfo(), pos );
+}
+
+void KFileDetailView::clearView()
+{
+ m_resolver->m_lstPendingMimeIconItems.clear();
+ KListView::clear();
+}
+
+void KFileDetailView::insertItem( KFileItem *i )
+{
+ KFileView::insertItem( i );
+
+ KFileListViewItem *item = new KFileListViewItem( (TQListView*) this, i );
+
+ setSortingKey( item, i );
+
+ i->setExtraData( this, item );
+
+ if ( !i->isMimeTypeKnown() )
+ m_resolver->m_lstPendingMimeIconItems.append( item );
+}
+
+void KFileDetailView::slotActivate( TQListViewItem *item )
+{
+ if ( !item )
+ return;
+
+ const KFileItem *fi = ( (KFileListViewItem*)item )->fileInfo();
+ if ( fi )
+ sig->activate( fi );
+}
+
+void KFileDetailView::selected( TQListViewItem *item )
+{
+ if ( !item )
+ return;
+
+ if ( TDEGlobalSettings::singleClick() ) {
+ const KFileItem *fi = ( (KFileListViewItem*)item )->fileInfo();
+ if ( fi && (fi->isDir() || !onlyDoubleClickSelectsFiles()) )
+ sig->activate( fi );
+ }
+}
+
+void KFileDetailView::highlighted( TQListViewItem *item )
+{
+ if ( !item )
+ return;
+
+ const KFileItem *fi = ( (KFileListViewItem*)item )->fileInfo();
+ if ( fi )
+ sig->highlightFile( fi );
+}
+
+
+void KFileDetailView::setSelectionMode( KFile::SelectionMode sm )
+{
+ disconnect( this, TQT_SIGNAL( selectionChanged() ));
+ disconnect( this, TQT_SIGNAL( selectionChanged( TQListViewItem * ) ));
+
+ KFileView::setSelectionMode( sm );
+
+ switch ( KFileView::selectionMode() ) {
+ case KFile::Multi:
+ TQListView::setSelectionMode( TQListView::Multi );
+ break;
+ case KFile::Extended:
+ TQListView::setSelectionMode( TQListView::Extended );
+ break;
+ case KFile::NoSelection:
+ TQListView::setSelectionMode( TQListView::NoSelection );
+ break;
+ default: // fall through
+ case KFile::Single:
+ TQListView::setSelectionMode( TQListView::Single );
+ break;
+ }
+
+ if ( sm == KFile::Multi || sm == KFile::Extended )
+ connect( this, TQT_SIGNAL( selectionChanged() ),
+ TQT_SLOT( slotSelectionChanged() ));
+ else
+ connect( this, TQT_SIGNAL( selectionChanged( TQListViewItem * )),
+ TQT_SLOT( highlighted( TQListViewItem * )));
+}
+
+bool KFileDetailView::isSelected( const KFileItem *i ) const
+{
+ if ( !i )
+ return false;
+
+ KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
+ return (item && item->isSelected());
+}
+
+
+void KFileDetailView::updateView( bool b )
+{
+ if ( !b )
+ return;
+
+ TQListViewItemIterator it( (TQListView*)this );
+ for ( ; it.current(); ++it ) {
+ KFileListViewItem *item=static_cast<KFileListViewItem *>(it.current());
+ item->setPixmap( 0, item->fileInfo()->pixmap(KIcon::SizeSmall) );
+ }
+}
+
+void KFileDetailView::updateView( const KFileItem *i )
+{
+ if ( !i )
+ return;
+
+ KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
+ if ( !item )
+ return;
+
+ item->init();
+ setSortingKey( item, i );
+
+ //item->repaint(); // only repaints if visible
+}
+
+void KFileDetailView::setSortingKey( KFileListViewItem *item,
+ const KFileItem *i )
+{
+ // see also setSorting()
+ TQDir::SortSpec spec = KFileView::sorting();
+
+ if ( spec & TQDir::Time )
+ item->setKey( sortingKey( i->time( TDEIO::UDS_MODIFICATION_TIME ),
+ i->isDir(), spec ));
+ else if ( spec & TQDir::Size )
+ item->setKey( sortingKey( i->size(), i->isDir(), spec ));
+
+ else // Name or Unsorted
+ item->setKey( sortingKey( i->text(), i->isDir(), spec ));
+}
+
+
+void KFileDetailView::removeItem( const KFileItem *i )
+{
+ if ( !i )
+ return;
+
+ KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
+ m_resolver->m_lstPendingMimeIconItems.remove( item );
+ delete item;
+
+ KFileView::removeItem( i );
+}
+
+void KFileDetailView::slotSortingChanged( int col )
+{
+ // col is the section here, not the index!
+
+ TQDir::SortSpec sort = sorting();
+ int sortSpec = -1;
+ bool reversed = (col == m_sortingCol) && (sort & TQDir::Reversed) == 0;
+ m_sortingCol = col;
+
+ switch( col ) {
+ case COL_NAME:
+ sortSpec = (sort & ~TQDir::SortByMask | TQDir::Name);
+ break;
+ case COL_SIZE:
+ sortSpec = (sort & ~TQDir::SortByMask | TQDir::Size);
+ break;
+ case COL_DATE:
+ sortSpec = (sort & ~TQDir::SortByMask | TQDir::Time);
+ break;
+
+ // the following columns have no equivalent in TQDir, so we set it
+ // to TQDir::Unsorted and remember the column (m_sortingCol)
+ case COL_OWNER:
+ case COL_GROUP:
+ case COL_PERM:
+ // grmbl, TQDir::Unsorted == SortByMask.
+ sortSpec = (sort & ~TQDir::SortByMask);// | TQDir::Unsorted;
+ break;
+ default:
+ break;
+ }
+
+ if ( reversed )
+ sortSpec |= TQDir::Reversed;
+ else
+ sortSpec &= ~TQDir::Reversed;
+
+ if ( sort & TQDir::IgnoreCase )
+ sortSpec |= TQDir::IgnoreCase;
+ else
+ sortSpec &= ~TQDir::IgnoreCase;
+
+
+ KFileView::setSorting( static_cast<TQDir::SortSpec>( sortSpec ) );
+
+ KFileItem *item;
+ KFileItemListIterator it( *items() );
+
+ if ( sortSpec & TQDir::Time ) {
+ for ( ; (item = it.current()); ++it )
+ viewItem(item)->setKey( sortingKey( item->time( TDEIO::UDS_MODIFICATION_TIME ), item->isDir(), sortSpec ));
+ }
+
+ else if ( sortSpec & TQDir::Size ) {
+ for ( ; (item = it.current()); ++it )
+ viewItem(item)->setKey( sortingKey( item->size(), item->isDir(),
+ sortSpec ));
+ }
+ else { // Name or Unsorted -> use column text
+ for ( ; (item = it.current()); ++it ) {
+ KFileListViewItem *i = viewItem( item );
+ i->setKey( sortingKey( i->text(m_sortingCol), item->isDir(),
+ sortSpec ));
+ }
+ }
+
+ KListView::setSorting( m_sortingCol, !reversed );
+ KListView::sort();
+
+ if ( !m_blockSortingSignal )
+ sig->changeSorting( static_cast<TQDir::SortSpec>( sortSpec ) );
+}
+
+
+void KFileDetailView::setSorting( TQDir::SortSpec spec )
+{
+ int col = 0;
+ if ( spec & TQDir::Time )
+ col = COL_DATE;
+ else if ( spec & TQDir::Size )
+ col = COL_SIZE;
+ else if ( spec & TQDir::Unsorted )
+ col = m_sortingCol;
+ else
+ col = COL_NAME;
+
+ // inversed, because slotSortingChanged will reverse it
+ if ( spec & TQDir::Reversed )
+ spec = (TQDir::SortSpec) (spec & ~TQDir::Reversed);
+ else
+ spec = (TQDir::SortSpec) (spec | TQDir::Reversed);
+
+ m_sortingCol = col;
+ KFileView::setSorting( (TQDir::SortSpec) spec );
+
+
+ // don't emit sortingChanged() when called via setSorting()
+ m_blockSortingSignal = true; // can't use blockSignals()
+ slotSortingChanged( col );
+ m_blockSortingSignal = false;
+}
+
+void KFileDetailView::ensureItemVisible( const KFileItem *i )
+{
+ if ( !i )
+ return;
+
+ KFileListViewItem *item = (KFileListViewItem*) i->extraData( this );
+
+ if ( item )
+ KListView::ensureItemVisible( item );
+}
+
+// we're in multiselection mode
+void KFileDetailView::slotSelectionChanged()
+{
+ sig->highlightFile( 0L );
+}
+
+KFileItem * KFileDetailView::firstFileItem() const
+{
+ KFileListViewItem *item = static_cast<KFileListViewItem*>( firstChild() );
+ if ( item )
+ return item->fileInfo();
+ return 0L;
+}
+
+KFileItem * KFileDetailView::nextItem( const KFileItem *fileItem ) const
+{
+ if ( fileItem ) {
+ KFileListViewItem *item = viewItem( fileItem );
+ if ( item && item->itemBelow() )
+ return ((KFileListViewItem*) item->itemBelow())->fileInfo();
+ else
+ return 0L;
+ }
+ else
+ return firstFileItem();
+}
+
+KFileItem * KFileDetailView::prevItem( const KFileItem *fileItem ) const
+{
+ if ( fileItem ) {
+ KFileListViewItem *item = viewItem( fileItem );
+ if ( item && item->itemAbove() )
+ return ((KFileListViewItem*) item->itemAbove())->fileInfo();
+ else
+ return 0L;
+ }
+ else
+ return firstFileItem();
+}
+
+void KFileDetailView::keyPressEvent( TQKeyEvent *e )
+{
+ KListView::keyPressEvent( e );
+
+ if ( e->key() == Key_Return || e->key() == Key_Enter ) {
+ if ( e->state() & ControlButton )
+ e->ignore();
+ else
+ e->accept();
+ }
+}
+
+//
+// mimetype determination on demand
+//
+void KFileDetailView::mimeTypeDeterminationFinished()
+{
+ // anything to do?
+}
+
+void KFileDetailView::determineIcon( KFileListViewItem *item )
+{
+ (void) item->fileInfo()->determineMimeType();
+ updateView( item->fileInfo() );
+}
+
+void KFileDetailView::listingCompleted()
+{
+ m_resolver->start();
+}
+
+TQDragObject *KFileDetailView::dragObject()
+{
+ // create a list of the URL:s that we want to drag
+ KURL::List urls;
+ KFileItemListIterator it( * KFileView::selectedItems() );
+ for ( ; it.current(); ++it ){
+ urls.append( (*it)->url() );
+ }
+ TQPixmap pixmap;
+ if( urls.count() > 1 )
+ pixmap = DesktopIcon( "tdemultiple", KIcon::SizeSmall );
+ if( pixmap.isNull() )
+ pixmap = currentFileItem()->pixmap( KIcon::SizeSmall );
+
+ TQPoint hotspot;
+ hotspot.setX( pixmap.width() / 2 );
+ hotspot.setY( pixmap.height() / 2 );
+ TQDragObject* myDragObject = new KURLDrag( urls, widget() );
+ myDragObject->setPixmap( pixmap, hotspot );
+ return myDragObject;
+}
+
+void KFileDetailView::slotAutoOpen()
+{
+ d->autoOpenTimer.stop();
+ if( !d->dropItem )
+ return;
+
+ KFileItem *fileItem = d->dropItem->fileInfo();
+ if (!fileItem)
+ return;
+
+ if( fileItem->isFile() )
+ return;
+
+ if ( fileItem->isDir() || fileItem->isLink())
+ sig->activate( fileItem );
+}
+
+bool KFileDetailView::acceptDrag(TQDropEvent* e) const
+{
+ return KURLDrag::canDecode( e ) &&
+ (e->source()!= const_cast<KFileDetailView*>(this)) &&
+ ( e->action() == TQDropEvent::Copy
+ || e->action() == TQDropEvent::Move
+ || e->action() == TQDropEvent::Link );
+}
+
+void KFileDetailView::contentsDragEnterEvent( TQDragEnterEvent *e )
+{
+ if ( ! acceptDrag( e ) ) { // can we decode this ?
+ e->ignore(); // No
+ return;
+ }
+ e->acceptAction(); // Yes
+
+ if ((dropOptions() & AutoOpenDirs) == 0)
+ return;
+
+ KFileListViewItem *item = dynamic_cast<KFileListViewItem*>(itemAt( contentsToViewport( e->pos() ) ));
+ if ( item ) { // are we over an item ?
+ d->dropItem = item;
+ d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
+ }
+ else
+ {
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+ }
+}
+
+void KFileDetailView::contentsDragMoveEvent( TQDragMoveEvent *e )
+{
+ if ( ! acceptDrag( e ) ) { // can we decode this ?
+ e->ignore(); // No
+ return;
+ }
+ e->acceptAction(); // Yes
+
+ if ((dropOptions() & AutoOpenDirs) == 0)
+ return;
+
+ KFileListViewItem *item = dynamic_cast<KFileListViewItem*>(itemAt( contentsToViewport( e->pos() ) ));
+ if ( item ) { // are we over an item ?
+ if (d->dropItem != item)
+ {
+ d->dropItem = item;
+ d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
+ }
+ }
+ else
+ {
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+ }
+}
+
+void KFileDetailView::contentsDragLeaveEvent( TQDragLeaveEvent * )
+{
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+}
+
+void KFileDetailView::contentsDropEvent( TQDropEvent *e )
+{
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+
+ if ( ! acceptDrag( e ) ) { // can we decode this ?
+ e->ignore(); // No
+ return;
+ }
+ e->acceptAction(); // Yes
+
+ KFileListViewItem *item = dynamic_cast<KFileListViewItem*>(itemAt( contentsToViewport( e->pos() ) ));
+ KFileItem * fileItem = 0;
+ if (item)
+ fileItem = item->fileInfo();
+
+ emit dropped(e, fileItem);
+
+ KURL::List urls;
+ if (KURLDrag::decode( e, urls ) && !urls.isEmpty())
+ {
+ emit dropped(e, urls, fileItem ? fileItem->url() : KURL());
+ sig->dropURLs(fileItem, e, urls);
+ }
+}
+
+
+/////////////////////////////////////////////////////////////////
+
+
+void KFileListViewItem::init()
+{
+ KFileListViewItem::setPixmap( COL_NAME, inf->pixmap(KIcon::SizeSmall));
+
+ setText( COL_NAME, inf->text() );
+ setText( COL_SIZE, TDEGlobal::locale()->formatNumber( inf->size(), 0));
+ setText( COL_DATE, inf->timeString() );
+ setText( COL_PERM, inf->permissionsString() );
+ setText( COL_OWNER, inf->user() );
+ setText( COL_GROUP, inf->group() );
+}
+
+
+void KFileDetailView::virtual_hook( int id, void* data )
+{ KListView::virtual_hook( id, data );
+ KFileView::virtual_hook( id, data ); }
+
+#include "tdefiledetailview.moc"
diff --git a/tdeio/tdefile/tdefiledetailview.h b/tdeio/tdefile/tdefiledetailview.h
new file mode 100644
index 000000000..114b10dec
--- /dev/null
+++ b/tdeio/tdefile/tdefiledetailview.h
@@ -0,0 +1,219 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef KFILEDETAILVIEW_H
+#define KFILEDETAILVIEW_H
+
+class KFileItem;
+class TQWidget;
+class TQKeyEvent;
+
+#include <klistview.h>
+#include <kmimetyperesolver.h>
+
+#include "tdefileview.h"
+
+/**
+ * An item for the listiew, that has a reference to its corresponding
+ * KFileItem.
+ */
+class TDEIO_EXPORT KFileListViewItem : public KListViewItem
+{
+public:
+ KFileListViewItem( TQListView *parent, const TQString &text,
+ const TQPixmap &icon, KFileItem *fi )
+ : KListViewItem( parent, text ), inf( fi ) {
+ setPixmap( 0, icon );
+ setText( 0, text );
+ }
+
+ /**
+ * @since 3.1
+ */
+ KFileListViewItem( TQListView *parent, KFileItem *fi )
+ : KListViewItem( parent ), inf( fi ) {
+ init();
+ }
+
+ KFileListViewItem( TQListView *parent, const TQString &text,
+ const TQPixmap &icon, KFileItem *fi,
+ TQListViewItem *after)
+ : KListViewItem( parent, after ), inf( fi ) {
+ setPixmap( 0, icon );
+ setText( 0, text );
+ }
+ ~KFileListViewItem() {
+ inf->removeExtraData( listView() );
+ }
+
+ /**
+ * @returns the corresponding KFileItem
+ */
+ KFileItem *fileInfo() const {
+ return inf;
+ }
+
+ virtual TQString key( int /*column*/, bool /*ascending*/ ) const {
+ return m_key;
+ }
+
+ void setKey( const TQString& key ) { m_key = key; }
+
+ TQRect rect() const
+ {
+ TQRect r = listView()->itemRect(this);
+ return TQRect( listView()->viewportToContents( r.topLeft() ),
+ TQSize( r.width(), r.height() ) );
+ }
+
+ /**
+ * @since 3.1
+ */
+ void init();
+
+private:
+ KFileItem *inf;
+ TQString m_key;
+
+private:
+ class KFileListViewItemPrivate;
+ KFileListViewItemPrivate *d;
+
+};
+
+/**
+ * A list-view capable of showing KFileItem'. Used in the filedialog
+ * for example. Most of the documentation is in KFileView class.
+ *
+ * @see KDirOperator
+ * @see KCombiView
+ * @see KFileIconView
+ */
+class TDEIO_EXPORT KFileDetailView : public KListView, public KFileView
+{
+ Q_OBJECT
+
+public:
+ KFileDetailView(TQWidget *parent, const char *name);
+ virtual ~KFileDetailView();
+
+ virtual TQWidget *widget() { return this; }
+ virtual void clearView();
+ virtual void setAutoUpdate( bool ) {} // ### unused. remove in KDE4
+
+ virtual void setSelectionMode( KFile::SelectionMode sm );
+
+ virtual void updateView( bool );
+ virtual void updateView(const KFileItem*);
+ virtual void removeItem( const KFileItem *);
+ virtual void listingCompleted();
+
+ virtual void setSelected(const KFileItem *, bool);
+ virtual bool isSelected(const KFileItem *i) const;
+ virtual void clearSelection();
+ virtual void selectAll();
+ virtual void invertSelection();
+
+ virtual void setCurrentItem( const KFileItem * );
+ virtual KFileItem * currentFileItem() const;
+ virtual KFileItem * firstFileItem() const;
+ virtual KFileItem * nextItem( const KFileItem * ) const;
+ virtual KFileItem * prevItem( const KFileItem * ) const;
+
+ virtual void insertItem( KFileItem *i );
+
+ // implemented to get noticed about sorting changes (for sortingIndicator)
+ virtual void setSorting( TQDir::SortSpec );
+
+ void ensureItemVisible( const KFileItem * );
+
+ // for KMimeTypeResolver
+ void mimeTypeDeterminationFinished();
+ void determineIcon( KFileListViewItem *item );
+ TQScrollView *scrollWidget() const { return (TQScrollView*) this; }
+
+ virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
+ virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
+
+signals:
+ /**
+ * The user dropped something.
+ * @p fileItem points to the item dropped on or can be 0 if the
+ * user dropped on empty space.
+ * @since 3.2
+ */
+ void dropped(TQDropEvent *event, KFileItem *fileItem);
+ /**
+ * The user dropped the URLs @p urls.
+ * @p url points to the item dropped on or can be empty if the
+ * user dropped on empty space.
+ * @since 3.2
+ */
+ void dropped(TQDropEvent *event, const KURL::List &urls, const KURL &url);
+
+protected:
+ virtual void keyPressEvent( TQKeyEvent * );
+
+ // DND support
+ virtual TQDragObject *dragObject();
+ virtual void contentsDragEnterEvent( TQDragEnterEvent *e );
+ virtual void contentsDragMoveEvent( TQDragMoveEvent *e );
+ virtual void contentsDragLeaveEvent( TQDragLeaveEvent *e );
+ virtual void contentsDropEvent( TQDropEvent *ev );
+ virtual bool acceptDrag(TQDropEvent* e ) const;
+
+ int m_sortingCol;
+
+protected slots:
+ void slotSelectionChanged();
+
+private slots:
+ void slotSortingChanged( int );
+ void selected( TQListViewItem *item );
+ void slotActivate( TQListViewItem *item );
+ void highlighted( TQListViewItem *item );
+ void slotActivateMenu ( TQListViewItem *item, const TQPoint& pos );
+ void slotAutoOpen();
+
+private:
+ virtual void insertItem(TQListViewItem *i) { KListView::insertItem(i); }
+ virtual void setSorting(int i, bool b) { KListView::setSorting(i, b); }
+ virtual void setSelected(TQListViewItem *i, bool b) { KListView::setSelected(i, b); }
+
+ inline KFileListViewItem * viewItem( const KFileItem *item ) const {
+ if ( item )
+ return (KFileListViewItem *) item->extraData( this );
+ return 0L;
+ }
+
+ void setSortingKey( KFileListViewItem *item, const KFileItem *i );
+
+
+ bool m_blockSortingSignal;
+ KMimeTypeResolver<KFileListViewItem,KFileDetailView> *m_resolver;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KFileDetailViewPrivate;
+ KFileDetailViewPrivate *d;
+};
+
+#endif // KFILEDETAILVIEW_H
diff --git a/tdeio/tdefile/tdefiledialog.cpp b/tdeio/tdefile/tdefiledialog.cpp
new file mode 100644
index 000000000..4fb399716
--- /dev/null
+++ b/tdeio/tdefile/tdefiledialog.cpp
@@ -0,0 +1,2380 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1997, 1998 Richard Moore <rich@kde.org>
+ 1998 Stephan Kulow <coolo@kde.org>
+ 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ 1999,2000,2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2003 Clarence Dang <dang@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdefiledialog.h"
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#include <tqptrcollection.h>
+#include <tqcheckbox.h>
+#include <tqcombobox.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqlineedit.h>
+#include <tqptrlist.h>
+#include <tqpixmap.h>
+#include <tqtextcodec.h>
+#include <tqtooltip.h>
+#include <tqtimer.h>
+#include <tqwhatsthis.h>
+#include <tqfiledialog.h>
+
+#include <kaccel.h>
+#include <kaction.h>
+#include <kapplication.h>
+#include <kcharsets.h>
+#include <kcmdlineargs.h>
+#include <kcompletionbox.h>
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <kiconloader.h>
+#include <kimageio.h>
+#include <tdeio/job.h>
+#include <tdeio/netaccess.h>
+#include <tdeio/scheduler.h>
+#include <tdeio/kservicetypefactory.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kmimetype.h>
+#include <kpopupmenu.h>
+#include <kprotocolinfo.h>
+#include <kpushbutton.h>
+#include <krecentdirs.h>
+#include <kshell.h>
+#include <kstandarddirs.h>
+#include <kstdguiitem.h>
+#include <kstaticdeleter.h>
+#include <ktoolbar.h>
+#include <ktoolbarbutton.h>
+#include <kurl.h>
+#include <kurlcombobox.h>
+#include <kurlcompletion.h>
+#include <kuser.h>
+
+#include "config-tdefile.h"
+#include "kpreviewwidgetbase.h"
+
+#include <kdirselectdialog.h>
+#include <tdefileview.h>
+#include <krecentdocument.h>
+#include <tdefilefiltercombo.h>
+#include <kdiroperator.h>
+#include <kimagefilepreview.h>
+
+#include <tdefilespeedbar.h>
+#include <tdefilebookmarkhandler.h>
+
+#ifdef Q_WS_X11
+#include <X11/Xlib.h>
+#include <fixx11h.h>
+#endif
+
+enum Buttons { HOTLIST_BUTTON,
+ PATH_COMBO, CONFIGURE_BUTTON };
+
+template class TQPtrList<TDEIO::StatJob>;
+
+namespace {
+ static void silenceQToolBar(TQtMsgType, const char *)
+ {
+ }
+}
+
+struct KFileDialogPrivate
+{
+ // the last selected url
+ KURL url;
+
+ // the selected filenames in multiselection mode -- FIXME
+ TQString filenames;
+
+ // the name of the filename set by setSelection
+ TQString selection;
+
+ // now following all kind of widgets, that I need to rebuild
+ // the geometry management
+ TQBoxLayout *boxLayout;
+ TQWidget *mainWidget;
+
+ TQLabel *locationLabel;
+
+ // @deprecated remove in KDE4
+ TQLabel *filterLabel;
+ KURLComboBox *pathCombo;
+ KPushButton *okButton, *cancelButton;
+ KFileSpeedBar *urlBar;
+ TQHBoxLayout *urlBarLayout;
+ TQWidget *customWidget;
+
+ // Automatically Select Extension stuff
+ TQCheckBox *autoSelectExtCheckBox;
+ bool autoSelectExtChecked; // whether or not the _user_ has checked the above box
+ TQString extension; // current extension for this filter
+
+ TQPtrList<TDEIO::StatJob> statJobs;
+
+ KURL::List urlList; //the list of selected urls
+
+ TQStringList mimetypes; //the list of possible mimetypes to save as
+
+ // indicates if the location edit should be kept or cleared when changing
+ // directories
+ bool keepLocation :1;
+
+ // the KDirOperators view is set in KFileDialog::show(), so to avoid
+ // setting it again and again, we have this nice little boolean :)
+ bool hasView :1;
+
+ bool hasDefaultFilter :1; // necessary for the operationMode
+ KFileDialog::OperationMode operationMode;
+
+ // The file class used for KRecentDirs
+ TQString fileClass;
+
+ KFileBookmarkHandler *bookmarkHandler;
+
+ // the ID of the path drop down so subclasses can place their custom widgets properly
+ int m_pathComboIndex;
+};
+
+KURL *KFileDialog::lastDirectory; // to set the start path
+
+static KStaticDeleter<KURL> ldd;
+
+KFileDialog::KFileDialog(const TQString& startDir, const TQString& filter,
+ TQWidget *parent, const char* name, bool modal)
+ : KDialogBase( parent, name, modal, TQString::null, 0 )
+{
+ init( startDir, filter, 0 );
+}
+
+KFileDialog::KFileDialog(const TQString& startDir, const TQString& filter,
+ TQWidget *parent, const char* name, bool modal, TQWidget* widget)
+ : KDialogBase( parent, name, modal, TQString::null, 0 )
+{
+ init( startDir, filter, widget );
+}
+
+
+KFileDialog::~KFileDialog()
+{
+ hide();
+
+ TDEConfig *config = TDEGlobal::config();
+
+ if (d->urlBar)
+ d->urlBar->save( config );
+
+ config->sync();
+
+ delete d->bookmarkHandler; // Should be deleted before ops!
+ delete ops;
+ delete d;
+}
+
+void KFileDialog::setLocationLabel(const TQString& text)
+{
+ d->locationLabel->setText(text);
+}
+
+void KFileDialog::setFilter(const TQString& filter)
+{
+ int pos = filter.find('/');
+
+ // Check for an un-escaped '/', if found
+ // interpret as a MIME filter.
+
+ if (pos > 0 && filter[pos - 1] != '\\') {
+ TQStringList filters = TQStringList::split( " ", filter );
+ setMimeFilter( filters );
+ return;
+ }
+
+ // Strip the escape characters from
+ // escaped '/' characters.
+
+ TQString copy (filter);
+ for (pos = 0; (pos = copy.find("\\/", pos)) != -1; ++pos)
+ copy.remove(pos, 1);
+
+ ops->clearFilter();
+ filterWidget->setFilter(copy);
+ ops->setNameFilter(filterWidget->currentFilter());
+ d->hasDefaultFilter = false;
+ filterWidget->setEditable( true );
+
+ updateAutoSelectExtension ();
+}
+
+TQString KFileDialog::currentFilter() const
+{
+ return filterWidget->currentFilter();
+}
+
+// deprecated
+void KFileDialog::setFilterMimeType(const TQString &label,
+ const KMimeType::List &types,
+ const KMimeType::Ptr &defaultType)
+{
+ d->mimetypes.clear();
+ d->filterLabel->setText(label);
+
+ KMimeType::List::ConstIterator it;
+ for( it = types.begin(); it != types.end(); ++it)
+ d->mimetypes.append( (*it)->name() );
+
+ setMimeFilter( d->mimetypes, defaultType->name() );
+}
+
+void KFileDialog::setMimeFilter( const TQStringList& mimeTypes,
+ const TQString& defaultType )
+{
+ d->mimetypes = mimeTypes;
+ filterWidget->setMimeFilter( mimeTypes, defaultType );
+
+ TQStringList types = TQStringList::split(" ", filterWidget->currentFilter());
+ types.append( TQString::fromLatin1( "inode/directory" ));
+ ops->clearFilter();
+ ops->setMimeFilter( types );
+ d->hasDefaultFilter = !defaultType.isEmpty();
+ filterWidget->setEditable( !d->hasDefaultFilter ||
+ d->operationMode != Saving );
+
+ updateAutoSelectExtension ();
+}
+
+void KFileDialog::clearFilter()
+{
+ d->mimetypes.clear();
+ filterWidget->setFilter( TQString::null );
+ ops->clearFilter();
+ d->hasDefaultFilter = false;
+ filterWidget->setEditable( true );
+
+ updateAutoSelectExtension ();
+}
+
+TQString KFileDialog::currentMimeFilter() const
+{
+ int i = filterWidget->currentItem();
+ if (filterWidget->showsAllTypes())
+ i--;
+
+ if ((i >= 0) && (i < (int) d->mimetypes.count()))
+ return d->mimetypes[i];
+ return TQString::null; // The "all types" item has no mimetype
+}
+
+KMimeType::Ptr KFileDialog::currentFilterMimeType()
+{
+ return KMimeType::mimeType( currentMimeFilter() );
+}
+
+void KFileDialog::setPreviewWidget(const TQWidget *w) {
+ ops->setPreviewWidget(w);
+ ops->clearHistory();
+ d->hasView = true;
+}
+
+void KFileDialog::setPreviewWidget(const KPreviewWidgetBase *w) {
+ ops->setPreviewWidget(w);
+ ops->clearHistory();
+ d->hasView = true;
+}
+
+KURL KFileDialog::getCompleteURL(const TQString &_url)
+{
+ TQString url = KShell::tildeExpand(_url);
+ KURL u;
+
+ if ( KURL::isRelativeURL(url) ) // only a full URL isn't relative. Even /path is.
+ {
+ if (!url.isEmpty() && !TQDir::isRelativePath(url) ) // absolute path
+ u.setPath( url );
+ else
+ {
+ u = ops->url();
+ u.addPath( url ); // works for filenames and relative paths
+ u.cleanPath(); // fix "dir/.."
+ }
+ }
+ else // complete URL
+ u = url;
+
+ return u;
+}
+
+// FIXME: check for "existing" flag here?
+void KFileDialog::slotOk()
+{
+ kdDebug(tdefile_area) << "slotOK\n";
+
+ // a list of all selected files/directories (if any)
+ // can only be used if the user didn't type any filenames/urls himself
+ const KFileItemList *items = ops->selectedItems();
+
+ if ( (mode() & KFile::Directory) != KFile::Directory ) {
+ if ( locationEdit->currentText().stripWhiteSpace().isEmpty() ) {
+ if ( !items || items->isEmpty() )
+ {
+ TQString msg;
+ if ( d->operationMode == Saving )
+ msg = i18n("Please specify the filename to save to.");
+ else
+ msg = i18n("Please select the file to open.");
+ KMessageBox::information(this, msg);
+ return;
+ }
+
+ // weird case: the location edit is empty, but there are
+ // highlighted files
+ else {
+
+ bool multi = (mode() & KFile::Files) != 0;
+ KFileItemListIterator it( *items );
+ TQString endQuote = TQString::fromLatin1("\" ");
+ TQString name, files;
+ while ( it.current() ) {
+ name = (*it)->name();
+ if ( multi ) {
+ name.prepend( '"' );
+ name.append( endQuote );
+ }
+
+ files.append( name );
+ ++it;
+ }
+ setLocationText( files );
+ return;
+ }
+ }
+ }
+
+ bool dirOnly = ops->dirOnlyMode();
+
+ // we can use our tdefileitems, no need to parse anything
+ if ( items && !locationEdit->lineEdit()->edited() &&
+ !(items->isEmpty() && !dirOnly) ) {
+
+ d->urlList.clear();
+ d->filenames = TQString::null;
+
+ if ( dirOnly ) {
+ d->url = ops->url();
+ }
+ else {
+ if ( !(mode() & KFile::Files) ) {// single selection
+ d->url = items->getFirst()->url();
+ }
+
+ else { // multi (dirs and/or files)
+ d->url = ops->url();
+ KFileItemListIterator it( *items );
+ while ( it.current() ) {
+ d->urlList.append( (*it)->url() );
+ ++it;
+ }
+ }
+ }
+
+ KURL url = TDEIO::NetAccess::mostLocalURL(d->url,topLevelWidget());
+ if ( (mode() & KFile::LocalOnly) == KFile::LocalOnly &&
+ !url.isLocalFile() ) {
+// ### after message freeze, add message for directories!
+ KMessageBox::sorry( d->mainWidget,
+ i18n("You can only select local files."),
+ i18n("Remote Files Not Accepted") );
+ return;
+ }
+
+ d->url = url;
+ accept();
+ return;
+ }
+
+
+ KURL selectedURL;
+
+ if ( (mode() & KFile::Files) == KFile::Files ) {// multiselection mode
+ TQString locationText = locationEdit->currentText();
+ if ( locationText.contains( '/' )) {
+ // relative path? -> prepend the current directory
+ KURL u( ops->url(), KShell::tildeExpand(locationText));
+ if ( u.isValid() )
+ selectedURL = u;
+ else
+ selectedURL = ops->url();
+ }
+ else // simple filename -> just use the current URL
+ selectedURL = ops->url();
+ }
+
+ else {
+ selectedURL = getCompleteURL(locationEdit->currentText());
+
+ // appendExtension() may change selectedURL
+ appendExtension (selectedURL);
+ }
+
+ if ( !selectedURL.isValid() ) {
+ KMessageBox::sorry( d->mainWidget, i18n("%1\ndoes not appear to be a valid URL.\n").arg(d->url.url()), i18n("Invalid URL") );
+ return;
+ }
+
+ KURL url = TDEIO::NetAccess::mostLocalURL(selectedURL,topLevelWidget());
+ if ( (mode() & KFile::LocalOnly) == KFile::LocalOnly &&
+ !url.isLocalFile() ) {
+ KMessageBox::sorry( d->mainWidget,
+ i18n("You can only select local files."),
+ i18n("Remote Files Not Accepted") );
+ return;
+ }
+
+ d->url = url;
+
+ // d->url is a correct URL now
+
+ if ( (mode() & KFile::Directory) == KFile::Directory ) {
+ kdDebug(tdefile_area) << "Directory" << endl;
+ bool done = true;
+ if ( d->url.isLocalFile() ) {
+ if ( locationEdit->currentText().stripWhiteSpace().isEmpty() ) {
+ TQFileInfo info( d->url.path() );
+ if ( info.isDir() ) {
+ d->filenames = TQString::null;
+ d->urlList.clear();
+ d->urlList.append( d->url );
+ accept();
+ }
+ else if (!info.exists() && (mode() & KFile::File) != KFile::File) {
+ // directory doesn't exist, create and enter it
+ if ( ops->mkdir( d->url.url(), true ))
+ return;
+ else
+ accept();
+ }
+ else { // d->url is not a directory,
+ // maybe we are in File(s) | Directory mode
+ if ( (mode() & KFile::File) == KFile::File ||
+ (mode() & KFile::Files) == KFile::Files )
+ done = false;
+ }
+ }
+ else // Directory mode, with file[s]/dir[s] selected
+ {
+ if ( mode() & KFile::ExistingOnly )
+ {
+ if ( ops->dirOnlyMode() )
+ {
+ KURL fullURL(d->url, locationEdit->currentText());
+ if ( TQFile::exists( fullURL.path() ) )
+ {
+ d->url = fullURL;
+ d->filenames = TQString::null;
+ d->urlList.clear();
+ accept();
+ return;
+ }
+ else // doesn't exist -> reject
+ return;
+ }
+ }
+
+ d->filenames = locationEdit->currentText();
+ accept(); // what can we do?
+ }
+
+ }
+ else { // FIXME: remote directory, should we allow that?
+// tqDebug( "**** Selected remote directory: %s", d->url.url().latin1());
+ d->filenames = TQString::null;
+ d->urlList.clear();
+ d->urlList.append( d->url );
+
+ if ( mode() & KFile::ExistingOnly )
+ done = false;
+ else
+ accept();
+ }
+
+ if ( done )
+ return;
+ }
+
+ if (!kapp->authorizeURLAction("open", KURL(), d->url))
+ {
+ TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, d->url.prettyURL());
+ KMessageBox::error( d->mainWidget, msg);
+ return;
+ }
+
+ TDEIO::StatJob *job = 0L;
+ d->statJobs.clear();
+ d->filenames = KShell::tildeExpand(locationEdit->currentText());
+
+ if ( (mode() & KFile::Files) == KFile::Files &&
+ !locationEdit->currentText().contains( '/' )) {
+ kdDebug(tdefile_area) << "Files\n";
+ KURL::List list = parseSelectedURLs();
+ for ( KURL::List::ConstIterator it = list.begin();
+ it != list.end(); ++it )
+ {
+ if (!kapp->authorizeURLAction("open", KURL(), *it))
+ {
+ TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, (*it).prettyURL());
+ KMessageBox::error( d->mainWidget, msg);
+ return;
+ }
+ }
+ for ( KURL::List::ConstIterator it = list.begin();
+ it != list.end(); ++it )
+ {
+ job = TDEIO::stat( *it, !(*it).isLocalFile() );
+ job->setWindow (topLevelWidget());
+ TDEIO::Scheduler::scheduleJob( job );
+ d->statJobs.append( job );
+ connect( job, TQT_SIGNAL( result(TDEIO::Job *) ),
+ TQT_SLOT( slotStatResult( TDEIO::Job *) ));
+ }
+ return;
+ }
+
+ job = TDEIO::stat(d->url,!d->url.isLocalFile());
+ job->setWindow (topLevelWidget());
+ d->statJobs.append( job );
+ connect(job, TQT_SIGNAL(result(TDEIO::Job*)), TQT_SLOT(slotStatResult(TDEIO::Job*)));
+}
+
+
+static bool isDirectory (const TDEIO::UDSEntry &t)
+{
+ bool isDir = false;
+
+ for (TDEIO::UDSEntry::ConstIterator it = t.begin();
+ it != t.end();
+ it++)
+ {
+ if ((*it).m_uds == TDEIO::UDS_FILE_TYPE)
+ {
+ isDir = S_ISDIR ((mode_t) ((*it).m_long));
+ break;
+ }
+ }
+
+ return isDir;
+}
+
+// FIXME : count all errors and show messagebox when d->statJobs.count() == 0
+// in case of an error, we cancel the whole operation (clear d->statJobs and
+// don't call accept)
+void KFileDialog::slotStatResult(TDEIO::Job* job)
+{
+ kdDebug(tdefile_area) << "slotStatResult" << endl;
+ TDEIO::StatJob *sJob = static_cast<TDEIO::StatJob *>( job );
+
+ if ( !d->statJobs.removeRef( sJob ) ) {
+ return;
+ }
+
+ int count = d->statJobs.count();
+
+ // errors mean in general, the location is no directory ;/
+ // Can we be sure that it is exististant at all? (pfeiffer)
+ if (sJob->error() && count == 0 && !ops->dirOnlyMode())
+ {
+ accept();
+ return;
+ }
+
+ TDEIO::UDSEntry t = sJob->statResult();
+ if (isDirectory (t))
+ {
+ if ( ops->dirOnlyMode() )
+ {
+ d->filenames = TQString::null;
+ d->urlList.clear();
+ accept();
+ }
+ else // in File[s] mode, directory means error -> cd into it
+ {
+ if ( count == 0 ) {
+ locationEdit->clearEdit();
+ locationEdit->lineEdit()->setEdited( false );
+ setURL( sJob->url() );
+ }
+ }
+ d->statJobs.clear();
+ return;
+ }
+ else if ( ops->dirOnlyMode() )
+ {
+ return; // ### error message?
+ }
+
+ kdDebug(tdefile_area) << "filename " << sJob->url().url() << endl;
+
+ if ( count == 0 )
+ accept();
+}
+
+void KFileDialog::accept()
+{
+ setResult( TQDialog::Accepted ); // parseSelectedURLs() checks that
+
+ *lastDirectory = ops->url();
+ if (!d->fileClass.isEmpty())
+ KRecentDirs::add(d->fileClass, ops->url().url());
+
+ // clear the topmost item, we insert it as full path later on as item 1
+ locationEdit->changeItem( TQString::null, 0 );
+
+ KURL::List list = selectedURLs();
+ TQValueListConstIterator<KURL> it = list.begin();
+ for ( ; it != list.end(); ++it ) {
+ const KURL& url = *it;
+ // we strip the last slash (-1) because KURLComboBox does that as well
+ // when operating in file-mode. If we wouldn't , dupe-finding wouldn't
+ // work.
+ TQString file = url.isLocalFile() ? url.path(-1) : url.prettyURL(-1);
+
+ // remove dupes
+ for ( int i = 1; i < locationEdit->count(); i++ ) {
+ if ( locationEdit->text( i ) == file ) {
+ locationEdit->removeItem( i-- );
+ break;
+ }
+ }
+ locationEdit->insertItem( file, 1 );
+ }
+
+ TDEConfig *config = TDEGlobal::config();
+ config->setForceGlobal( true );
+ writeConfig( config, ConfigGroup );
+ config->setForceGlobal( false );
+
+ saveRecentFiles( config );
+ config->sync();
+
+ KDialogBase::accept();
+
+ addToRecentDocuments();
+
+ if ( (mode() & KFile::Files) != KFile::Files ) // single selection
+ emit fileSelected(d->url.url());
+
+ ops->close();
+ emit okClicked();
+}
+
+
+void KFileDialog::fileHighlighted(const KFileItem *i)
+{
+ if (i && i->isDir())
+ return;
+
+
+ if ( (ops->mode() & KFile::Files) != KFile::Files ) {
+ if ( !i )
+ return;
+
+ d->url = i->url();
+
+ if ( !locationEdit->hasFocus() ) { // don't disturb while editing
+ setLocationText( i->name() );
+ }
+ emit fileHighlighted(d->url.url());
+ }
+
+ else {
+ multiSelectionChanged();
+ emit selectionChanged();
+ }
+}
+
+void KFileDialog::fileSelected(const KFileItem *i)
+{
+ if (i && i->isDir())
+ return;
+
+ if ( (ops->mode() & KFile::Files) != KFile::Files ) {
+ if ( !i )
+ return;
+
+ d->url = i->url();
+ setLocationText( i->name() );
+ }
+ else {
+ multiSelectionChanged();
+ emit selectionChanged();
+ }
+ slotOk();
+}
+
+
+// I know it's slow to always iterate thru the whole filelist
+// (ops->selectedItems()), but what can we do?
+void KFileDialog::multiSelectionChanged()
+{
+ if ( locationEdit->hasFocus() ) // don't disturb
+ return;
+
+ locationEdit->lineEdit()->setEdited( false );
+ KFileItem *item;
+ const KFileItemList *list = ops->selectedItems();
+ if ( !list ) {
+ locationEdit->clearEdit();
+ return;
+ }
+
+ static const TQString &begin = TDEGlobal::staticQString(" \"");
+ KFileItemListIterator it ( *list );
+ TQString text;
+ while ( (item = it.current()) ) {
+ text.append( begin ).append( item->name() ).append( '\"' );
+ ++it;
+ }
+
+ setLocationText( text.stripWhiteSpace() );
+}
+
+void KFileDialog::setLocationText( const TQString& text )
+{
+ // setCurrentItem() will cause textChanged() being emitted,
+ // so slotLocationChanged() will be called. Make sure we don't clear
+ // the KDirOperator's view-selection in there
+ disconnect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
+ this, TQT_SLOT( slotLocationChanged( const TQString& ) ) );
+ locationEdit->setCurrentItem( 0 );
+ connect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
+ TQT_SLOT( slotLocationChanged( const TQString& )) );
+ locationEdit->setEditText( text );
+
+ // don't change selection when user has clicked on an item
+ if ( d->operationMode == Saving && !locationEdit->isVisible())
+ setNonExtSelection();
+}
+
+static const char autocompletionWhatsThisText[] = I18N_NOOP("<p>While typing in the text area, you may be presented "
+ "with possible matches. "
+ "This feature can be controlled by clicking with the right mouse button "
+ "and selecting a preferred mode from the <b>Text Completion</b> menu.") "</qt>";
+void KFileDialog::updateLocationWhatsThis (void)
+{
+ TQString whatsThisText;
+ if (d->operationMode == KFileDialog::Saving)
+ {
+ whatsThisText = "<qt>" + i18n("This is the name to save the file as.") +
+ i18n (autocompletionWhatsThisText);
+ }
+ else if (ops->mode() & KFile::Files)
+ {
+ whatsThisText = "<qt>" + i18n("This is the list of files to open. More than "
+ "one file can be specified by listing several "
+ "files, separated by spaces.") +
+ i18n (autocompletionWhatsThisText);
+ }
+ else
+ {
+ whatsThisText = "<qt>" + i18n("This is the name of the file to open.") +
+ i18n (autocompletionWhatsThisText);
+ }
+
+ TQWhatsThis::add(d->locationLabel, whatsThisText);
+ TQWhatsThis::add(locationEdit, whatsThisText);
+}
+
+void KFileDialog::init(const TQString& startDir, const TQString& filter, TQWidget* widget)
+{
+ initStatic();
+ d = new KFileDialogPrivate();
+
+ d->boxLayout = 0;
+ d->keepLocation = false;
+ d->operationMode = Opening;
+ d->bookmarkHandler = 0;
+ d->hasDefaultFilter = false;
+ d->hasView = false;
+ d->mainWidget = new TQWidget( this, "KFileDialog::mainWidget");
+ setMainWidget( d->mainWidget );
+ d->okButton = new KPushButton( KStdGuiItem::ok(), d->mainWidget );
+ d->okButton->setDefault( true );
+ d->cancelButton = new KPushButton(KStdGuiItem::cancel(), d->mainWidget);
+ connect( d->okButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOk() ));
+ connect( d->cancelButton, TQT_SIGNAL( clicked() ), TQT_SLOT( slotCancel() ));
+ d->customWidget = widget;
+ d->autoSelectExtCheckBox = 0; // delayed loading
+ d->autoSelectExtChecked = false;
+ d->urlBar = 0; // delayed loading
+
+ TQtMsgHandler oldHandler = tqInstallMsgHandler( silenceQToolBar );
+ toolbar = new KToolBar( d->mainWidget, "KFileDialog::toolbar", true);
+ toolbar->setFlat(true);
+ tqInstallMsgHandler( oldHandler );
+
+ d->pathCombo = new KURLComboBox( KURLComboBox::Directories, true,
+ toolbar, "path combo" );
+ TQToolTip::add( d->pathCombo, i18n("Current location") );
+ TQWhatsThis::add( d->pathCombo, "<qt>" + i18n("This is the currently listed location. "
+ "The drop-down list also lists commonly used locations. "
+ "This includes standard locations, such as your home folder, as well as "
+ "locations that have been visited recently.") + i18n (autocompletionWhatsThisText));
+
+ KURL u;
+ u.setPath( TQDir::rootDirPath() );
+ TQString text = i18n("Root Folder: %1").arg( u.path() );
+ d->pathCombo->addDefaultURL( u,
+ KMimeType::pixmapForURL( u, 0, KIcon::Small ),
+ text );
+
+ u.setPath( TQDir::homeDirPath() );
+ text = i18n("Home Folder: %1").arg( u.path( +1 ) );
+ d->pathCombo->addDefaultURL( u, KMimeType::pixmapForURL( u, 0, KIcon::Small ),
+ text );
+
+ KURL docPath;
+ docPath.setPath( TDEGlobalSettings::documentPath() );
+ if ( (u.path(+1) != docPath.path(+1)) &&
+ TQDir(docPath.path(+1)).exists() )
+ {
+ text = i18n("Documents: %1").arg( docPath.path( +1 ) );
+ d->pathCombo->addDefaultURL( docPath,
+ KMimeType::pixmapForURL( docPath, 0, KIcon::Small ),
+ text );
+ }
+
+ u.setPath( TDEGlobalSettings::desktopPath() );
+ text = i18n("Desktop: %1").arg( u.path( +1 ) );
+ d->pathCombo->addDefaultURL( u,
+ KMimeType::pixmapForURL( u, 0, KIcon::Small ),
+ text );
+
+ d->url = getStartURL( startDir, d->fileClass );
+ d->selection = d->url.url();
+
+ // If local, check it exists. If not, go up until it exists.
+ if ( d->url.isLocalFile() )
+ {
+ if ( !TQFile::exists( d->url.path() ) )
+ {
+ d->url = d->url.upURL();
+ TQDir dir( d->url.path() );
+ while ( !dir.exists() )
+ {
+ d->url = d->url.upURL();
+ dir.setPath( d->url.path() );
+ }
+ }
+ }
+
+ ops = new KDirOperator(d->url, d->mainWidget, "KFileDialog::ops");
+ ops->setOnlyDoubleClickSelectsFiles( true );
+ connect(ops, TQT_SIGNAL(urlEntered(const KURL&)),
+ TQT_SLOT(urlEntered(const KURL&)));
+ connect(ops, TQT_SIGNAL(fileHighlighted(const KFileItem *)),
+ TQT_SLOT(fileHighlighted(const KFileItem *)));
+ connect(ops, TQT_SIGNAL(fileSelected(const KFileItem *)),
+ TQT_SLOT(fileSelected(const KFileItem *)));
+ connect(ops, TQT_SIGNAL(finishedLoading()),
+ TQT_SLOT(slotLoadingFinished()));
+
+ ops->setupMenu(KDirOperator::SortActions |
+ KDirOperator::FileActions |
+ KDirOperator::ViewActions);
+ KActionCollection *coll = ops->actionCollection();
+
+ // plug nav items into the toolbar
+ coll->action( "up" )->plug( toolbar );
+ coll->action( "up" )->setWhatsThis(i18n("<qt>Click this button to enter the parent folder.<p>"
+ "For instance, if the current location is file:/home/%1 clicking this "
+ "button will take you to file:/home.</qt>").arg( KUser().loginName() ));
+ coll->action( "back" )->plug( toolbar );
+ coll->action( "back" )->setWhatsThis(i18n("Click this button to move backwards one step in the browsing history."));
+ coll->action( "forward" )->plug( toolbar );
+ coll->action( "forward" )->setWhatsThis(i18n("Click this button to move forward one step in the browsing history."));
+ coll->action( "reload" )->plug( toolbar );
+ coll->action( "reload" )->setWhatsThis(i18n("Click this button to reload the contents of the current location."));
+ coll->action( "mkdir" )->setShortcut(Key_F10);
+ coll->action( "mkdir" )->plug( toolbar );
+ coll->action( "mkdir" )->setWhatsThis(i18n("Click this button to create a new folder."));
+
+ KToggleAction *showSidebarAction =
+ new KToggleAction(i18n("Show Quick Access Navigation Panel"), Key_F9, coll,"toggleSpeedbar");
+ showSidebarAction->setCheckedState(i18n("Hide Quick Access Navigation Panel"));
+ connect( showSidebarAction, TQT_SIGNAL( toggled( bool ) ),
+ TQT_SLOT( toggleSpeedbar( bool )) );
+
+ KToggleAction *showBookmarksAction =
+ new KToggleAction(i18n("Show Bookmarks"), 0, coll, "toggleBookmarks");
+ showBookmarksAction->setCheckedState(i18n("Hide Bookmarks"));
+ connect( showBookmarksAction, TQT_SIGNAL( toggled( bool ) ),
+ TQT_SLOT( toggleBookmarks( bool )) );
+
+ KActionMenu *menu = new KActionMenu( i18n("Configure"), "configure", TQT_TQOBJECT(this), "extra menu" );
+ menu->setWhatsThis(i18n("<qt>This is the configuration menu for the file dialog. "
+ "Various options can be accessed from this menu including: <ul>"
+ "<li>how files are sorted in the list</li>"
+ "<li>types of view, including icon and list</li>"
+ "<li>showing of hidden files</li>"
+ "<li>the Quick Access navigation panel</li>"
+ "<li>file previews</li>"
+ "<li>separating folders from files</li></ul></qt>"));
+ menu->insert( coll->action( "sorting menu" ));
+ menu->insert( coll->action( "separator" ));
+ coll->action( "short view" )->setShortcut(Key_F6);
+ menu->insert( coll->action( "short view" ));
+ coll->action( "detailed view" )->setShortcut(Key_F7);
+ menu->insert( coll->action( "detailed view" ));
+ menu->insert( coll->action( "separator" ));
+ coll->action( "show hidden" )->setShortcut(Key_F8);
+ menu->insert( coll->action( "show hidden" ));
+ menu->insert( showSidebarAction );
+ menu->insert( showBookmarksAction );
+ coll->action( "preview" )->setShortcut(Key_F11);
+ menu->insert( coll->action( "preview" ));
+ coll->action( "separate dirs" )->setShortcut(Key_F12);
+ menu->insert( coll->action( "separate dirs" ));
+
+ menu->setDelayed( false );
+ connect( menu->popupMenu(), TQT_SIGNAL( aboutToShow() ),
+ ops, TQT_SLOT( updateSelectionDependentActions() ));
+ menu->plug( toolbar );
+
+ //Insert a separator.
+ KToolBarSeparator* spacerWidget = new KToolBarSeparator(Qt::Horizontal, false /*no line*/,
+ toolbar);
+ d->m_pathComboIndex = toolbar->insertWidget(-1, -1, spacerWidget);
+ toolbar->insertWidget(PATH_COMBO, 0, d->pathCombo);
+
+
+ toolbar->setItemAutoSized (PATH_COMBO);
+ toolbar->setIconText(KToolBar::IconOnly);
+ toolbar->setBarPos(KToolBar::Top);
+ toolbar->setMovingEnabled(false);
+ toolbar->adjustSize();
+
+ KURLCompletion *pathCompletionObj = new KURLCompletion( KURLCompletion::DirCompletion );
+ d->pathCombo->setCompletionObject( pathCompletionObj );
+ d->pathCombo->setAutoDeleteCompletionObject( true );
+
+ connect( d->pathCombo, TQT_SIGNAL( urlActivated( const KURL& )),
+ this, TQT_SLOT( enterURL( const KURL& ) ));
+ connect( d->pathCombo, TQT_SIGNAL( returnPressed( const TQString& )),
+ this, TQT_SLOT( enterURL( const TQString& ) ));
+
+ TQString whatsThisText;
+
+ // the Location label/edit
+ d->locationLabel = new TQLabel(i18n("&Location:"), d->mainWidget);
+ locationEdit = new KURLComboBox(KURLComboBox::Files, true,
+ d->mainWidget, "LocationEdit");
+ locationEdit->setSizePolicy(TQSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Fixed));
+ connect( locationEdit, TQT_SIGNAL( textChanged( const TQString& ) ),
+ TQT_SLOT( slotLocationChanged( const TQString& )) );
+
+ updateLocationWhatsThis ();
+ d->locationLabel->setBuddy(locationEdit);
+
+ locationEdit->setFocus();
+ KURLCompletion *fileCompletionObj = new KURLCompletion( KURLCompletion::FileCompletion );
+ TQString dir = d->url.url(+1);
+ pathCompletionObj->setDir( dir );
+ fileCompletionObj->setDir( dir );
+ locationEdit->setCompletionObject( fileCompletionObj );
+ locationEdit->setAutoDeleteCompletionObject( true );
+ connect( fileCompletionObj, TQT_SIGNAL( match( const TQString& ) ),
+ TQT_SLOT( fileCompletion( const TQString& )) );
+
+ connect( locationEdit, TQT_SIGNAL( returnPressed() ),
+ this, TQT_SLOT( slotOk()));
+ connect(locationEdit, TQT_SIGNAL( activated( const TQString& )),
+ this, TQT_SLOT( locationActivated( const TQString& ) ));
+
+ // the Filter label/edit
+ whatsThisText = i18n("<qt>This is the filter to apply to the file list. "
+ "File names that do not match the filter will not be shown.<p>"
+ "You may select from one of the preset filters in the "
+ "drop down menu, or you may enter a custom filter "
+ "directly into the text area.<p>"
+ "Wildcards such as * and ? are allowed.</qt>");
+ d->filterLabel = new TQLabel(i18n("&Filter:"), d->mainWidget);
+ TQWhatsThis::add(d->filterLabel, whatsThisText);
+ filterWidget = new KFileFilterCombo(d->mainWidget,
+ "KFileDialog::filterwidget");
+ filterWidget->setSizePolicy(TQSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Fixed));
+ TQWhatsThis::add(filterWidget, whatsThisText);
+ setFilter(filter);
+ d->filterLabel->setBuddy(filterWidget);
+ connect(filterWidget, TQT_SIGNAL(filterChanged()), TQT_SLOT(slotFilterChanged()));
+
+ // the Automatically Select Extension checkbox
+ // (the text, visibility etc. is set in updateAutoSelectExtension(), which is called by readConfig())
+ d->autoSelectExtCheckBox = new TQCheckBox (d->mainWidget);
+ connect(d->autoSelectExtCheckBox, TQT_SIGNAL(clicked()), TQT_SLOT(slotAutoSelectExtClicked()));
+
+ initGUI(); // activate GM
+
+ TDEConfig* config = TDEGlobal::config();
+ readRecentFiles( config );
+
+ adjustSize();
+
+ ops->setViewConfig( config, ConfigGroup );
+ readConfig( config, ConfigGroup );
+ setSelection(d->selection);
+}
+
+void KFileDialog::initSpeedbar()
+{
+ d->urlBar = new KFileSpeedBar( d->mainWidget, "url bar" );
+ connect( d->urlBar, TQT_SIGNAL( activated( const KURL& )),
+ TQT_SLOT( enterURL( const KURL& )) );
+
+ // need to set the current url of the urlbar manually (not via urlEntered()
+ // here, because the initial url of KDirOperator might be the same as the
+ // one that will be set later (and then urlEntered() won't be emitted).
+ // ### REMOVE THIS when KDirOperator's initial URL (in the c'tor) is gone.
+ d->urlBar->setCurrentItem( d->url );
+
+ d->urlBarLayout->insertWidget( 0, d->urlBar );
+}
+
+void KFileDialog::initGUI()
+{
+ delete d->boxLayout; // deletes all sub layouts
+
+ d->boxLayout = new TQVBoxLayout( d->mainWidget, 0, KDialog::spacingHint());
+ d->boxLayout->addWidget(toolbar, AlignTop);
+
+ d->urlBarLayout = new TQHBoxLayout( d->boxLayout ); // needed for the urlBar that may appear
+ TQVBoxLayout *vbox = new TQVBoxLayout( d->urlBarLayout );
+
+ vbox->addWidget(ops, 4);
+ vbox->addSpacing(3);
+
+ TQGridLayout* lafBox= new TQGridLayout(2, 3, KDialog::spacingHint());
+
+ lafBox->addWidget(d->locationLabel, 0, 0, Qt::AlignVCenter);
+ lafBox->addWidget(locationEdit, 0, 1, Qt::AlignVCenter);
+ lafBox->addWidget(d->okButton, 0, 2, Qt::AlignVCenter);
+
+ lafBox->addWidget(d->filterLabel, 1, 0, Qt::AlignVCenter);
+ lafBox->addWidget(filterWidget, 1, 1, Qt::AlignVCenter);
+ lafBox->addWidget(d->cancelButton, 1, 2, Qt::AlignVCenter);
+
+ lafBox->setColStretch(1, 4);
+
+ vbox->addLayout(TQT_TQLAYOUT(lafBox), 0);
+ vbox->addSpacing(3);
+
+ // add the Automatically Select Extension checkbox
+ vbox->addWidget (d->autoSelectExtCheckBox);
+ vbox->addSpacing (3);
+
+ setTabOrder(ops, d->autoSelectExtCheckBox);
+ setTabOrder (d->autoSelectExtCheckBox, locationEdit);
+ setTabOrder(locationEdit, filterWidget);
+ setTabOrder(filterWidget, d->okButton);
+ setTabOrder(d->okButton, d->cancelButton);
+ setTabOrder(d->cancelButton, d->pathCombo);
+ setTabOrder(d->pathCombo, ops);
+
+ // If a custom widget was specified...
+ if ( d->customWidget != 0 )
+ {
+ // ...add it to the dialog, below the filter list box.
+
+ // Change the parent so that this widget is a child of the main widget
+ d->customWidget->reparent( d->mainWidget, TQPoint() );
+
+ vbox->addWidget( d->customWidget );
+ vbox->addSpacing(3);
+
+ // FIXME: This should adjust the tab orders so that the custom widget
+ // comes after the Cancel button. The code appears to do this, but the result
+ // somehow screws up the tab order of the file path combo box. Not a major
+ // problem, but ideally the tab order with a custom widget should be
+ // the same as the order without one.
+ setTabOrder(d->cancelButton, d->customWidget);
+ setTabOrder(d->customWidget, d->pathCombo);
+ }
+ else
+ {
+ setTabOrder(d->cancelButton, d->pathCombo);
+ }
+
+ setTabOrder(d->pathCombo, ops);
+}
+
+void KFileDialog::slotFilterChanged()
+{
+ TQString filter = filterWidget->currentFilter();
+ ops->clearFilter();
+
+ if ( filter.find( '/' ) > -1 ) {
+ TQStringList types = TQStringList::split( " ", filter );
+ types.prepend( "inode/directory" );
+ ops->setMimeFilter( types );
+ }
+ else
+ ops->setNameFilter( filter );
+
+ ops->updateDir();
+
+ updateAutoSelectExtension ();
+
+ emit filterChanged( filter );
+}
+
+
+void KFileDialog::setURL(const KURL& url, bool clearforward)
+{
+ d->selection = TQString::null;
+ ops->setURL( url, clearforward);
+}
+
+// Protected
+void KFileDialog::urlEntered(const KURL& url)
+{
+ TQString filename = locationEdit->currentText();
+ d->selection = TQString::null;
+
+ if ( d->pathCombo->count() != 0 ) { // little hack
+ d->pathCombo->setURL( url );
+ }
+
+ if (url.protocol()=="beagle" && url.path()=="/") {
+ d->pathCombo->setEditText("beagle:/<"+i18n("search term")+">");
+ d->pathCombo->lineEdit()->setSelection(8,255);
+ d->pathCombo->setFocus();
+ }
+
+ locationEdit->blockSignals( true );
+ locationEdit->setCurrentItem( 0 );
+ if ( d->keepLocation )
+ locationEdit->setEditText( filename );
+
+ locationEdit->blockSignals( false );
+
+ TQString dir = url.url(+1);
+ static_cast<KURLCompletion*>( d->pathCombo->completionObject() )->setDir( dir );
+ static_cast<KURLCompletion*>( locationEdit->completionObject() )->setDir( dir );
+
+ if ( d->urlBar )
+ d->urlBar->setCurrentItem( url );
+}
+
+void KFileDialog::locationActivated( const TQString& url )
+{
+ // This guard prevents any URL _typed_ by the user from being interpreted
+ // twice (by returnPressed/slotOk and here, activated/locationActivated)
+ // after the user presses Enter. Without this, _both_ setSelection and
+ // slotOk would "u.addPath( url )" ...so instead we leave it up to just
+ // slotOk....
+ if (!locationEdit->lineEdit()->edited())
+ setSelection( url );
+}
+
+void KFileDialog::enterURL( const KURL& url)
+{
+ setURL( url );
+}
+
+void KFileDialog::enterURL( const TQString& url )
+{
+ setURL( KURL::fromPathOrURL( KURLCompletion::replacedPath( url, true, true )) );
+}
+
+void KFileDialog::toolbarCallback(int) // SLOT
+{
+ /*
+ * yes, nothing uses this anymore.
+ * it used to be used to show the configure dialog
+ */
+}
+
+
+void KFileDialog::setSelection(const TQString& url)
+{
+ kdDebug(tdefile_area) << "setSelection " << url << endl;
+
+ if (url.isEmpty()) {
+ d->selection = TQString::null;
+ return;
+ }
+
+ KURL u = getCompleteURL(url);
+ if (!u.isValid()) { // if it still is
+ kdWarning() << url << " is not a correct argument for setSelection!" << endl;
+ return;
+ }
+
+ if (!KProtocolInfo::supportsListing(u)) {
+ locationEdit->lineEdit()->setEdited( true );
+ return;
+ }
+
+ /* we strip the first / from the path to avoid file://usr which means
+ * / on host usr
+ */
+ KFileItem i(KFileItem::Unknown, KFileItem::Unknown, u, true );
+ // KFileItem i(u.path());
+ if ( i.isDir() && u.isLocalFile() && TQFile::exists( u.path() ) ) {
+ // trust isDir() only if the file is
+ // local (we cannot stat non-local urls) and if it exists!
+ // (as KFileItem does not check if the file exists or not
+ // -> the statbuffer is undefined -> isDir() is unreliable) (Simon)
+ setURL(u, true);
+ }
+ else {
+ TQString filename = u.url();
+ int sep = filename.findRev('/');
+ if (sep >= 0) { // there is a / in it
+ if ( KProtocolInfo::supportsListing( u )) {
+ KURL dir(u);
+ dir.setQuery( TQString::null );
+ dir.setFileName( TQString::null );
+ setURL(dir, true );
+ }
+
+ // filename must be decoded, or "name with space" would become
+ // "name%20with%20space", so we use KURL::fileName()
+ filename = u.fileName();
+ kdDebug(tdefile_area) << "filename " << filename << endl;
+ d->selection = filename;
+ setLocationText( filename );
+
+ // tell the line edit that it has been edited
+ // otherwise we won't know this was set by the user
+ // and it will be ignored if there has been an
+ // auto completion. this caused bugs where automcompletion
+ // would start, the user would pick something from the
+ // history and then hit Ok only to get the autocompleted
+ // selection. OOOPS.
+ locationEdit->lineEdit()->setEdited( true );
+ }
+
+ d->url = ops->url();
+ d->url.addPath(filename);
+ }
+}
+
+void KFileDialog::slotLoadingFinished()
+{
+ if ( !d->selection.isNull() )
+ ops->setCurrentItem( d->selection );
+}
+
+// ### remove in KDE4
+void KFileDialog::pathComboChanged( const TQString& )
+{
+}
+void KFileDialog::dirCompletion( const TQString& ) // SLOT
+{
+}
+void KFileDialog::fileCompletion( const TQString& match )
+{
+ if ( match.isEmpty() && ops->view() )
+ ops->view()->clearSelection();
+ else
+ ops->setCurrentItem( match );
+}
+
+void KFileDialog::slotLocationChanged( const TQString& text )
+{
+ if ( text.isEmpty() && ops->view() )
+ ops->view()->clearSelection();
+
+ updateFilter();
+}
+
+void KFileDialog::updateStatusLine(int /* dirs */, int /* files */)
+{
+ kdWarning() << "KFileDialog::updateStatusLine is deprecated! The status line no longer exists. Do not try and use it!" << endl;
+}
+
+TQString KFileDialog::getOpenFileName(const TQString& startDir,
+ const TQString& filter,
+ TQWidget *parent, const TQString& caption)
+{
+ KFileDialog dlg(startDir, filter, parent, "filedialog", true);
+ dlg.setOperationMode( Opening );
+
+ dlg.setMode( KFile::File | KFile::LocalOnly );
+ dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
+
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ return dlg.selectedFile();
+}
+
+TQString KFileDialog::getOpenFileNameWId(const TQString& startDir,
+ const TQString& filter,
+ WId parent_id, const TQString& caption)
+{
+ TQWidget* parent = TQT_TQWIDGET(TQWidget::find( parent_id ));
+ KFileDialog dlg(startDir, filter, parent, "filedialog", true);
+#ifdef Q_WS_X11
+ if( parent == NULL && parent_id != 0 )
+ XSetTransientForHint( tqt_xdisplay(), dlg.winId(), parent_id );
+#else
+ // TODO
+#endif
+
+ dlg.setOperationMode( KFileDialog::Opening );
+
+ dlg.setMode( KFile::File | KFile::LocalOnly );
+ dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
+
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ return dlg.selectedFile();
+}
+
+TQStringList KFileDialog::getOpenFileNames(const TQString& startDir,
+ const TQString& filter,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ KFileDialog dlg(startDir, filter, parent, "filedialog", true);
+ dlg.setOperationMode( Opening );
+
+ dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
+ dlg.setMode(KFile::Files | KFile::LocalOnly);
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ return dlg.selectedFiles();
+}
+
+KURL KFileDialog::getOpenURL(const TQString& startDir, const TQString& filter,
+ TQWidget *parent, const TQString& caption)
+{
+ KFileDialog dlg(startDir, filter, parent, "filedialog", true);
+ dlg.setOperationMode( Opening );
+
+ dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
+ dlg.setMode( KFile::File );
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ return dlg.selectedURL();
+}
+
+KURL::List KFileDialog::getOpenURLs(const TQString& startDir,
+ const TQString& filter,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ KFileDialog dlg(startDir, filter, parent, "filedialog", true);
+ dlg.setOperationMode( Opening );
+
+ dlg.setCaption(caption.isNull() ? i18n("Open") : caption);
+ dlg.setMode(KFile::Files);
+ dlg.ops->clearHistory();
+ dlg.exec();
+
+ return dlg.selectedURLs();
+}
+
+KURL KFileDialog::getExistingURL(const TQString& startDir,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ return KDirSelectDialog::selectDirectory(startDir, false, parent, caption);
+}
+
+TQString KFileDialog::getExistingDirectory(const TQString& startDir,
+ TQWidget *parent,
+ const TQString& caption)
+{
+#ifdef Q_WS_WIN
+ return TQFileDialog::getExistingDirectory(startDir, parent, "getExistingDirectory",
+ caption, true, true);
+#else
+ KURL url = KDirSelectDialog::selectDirectory(startDir, true, parent,
+ caption);
+ if ( url.isValid() )
+ return url.path();
+
+ return TQString::null;
+#endif
+}
+
+KURL KFileDialog::getImageOpenURL( const TQString& startDir, TQWidget *parent,
+ const TQString& caption)
+{
+ TQStringList mimetypes = KImageIO::mimeTypes( KImageIO::Reading );
+ KFileDialog dlg(startDir,
+ mimetypes.join(" "),
+ parent, "filedialog", true);
+ dlg.setOperationMode( Opening );
+ dlg.setCaption( caption.isNull() ? i18n("Open") : caption );
+ dlg.setMode( KFile::File );
+
+ KImageFilePreview *ip = new KImageFilePreview( &dlg );
+ dlg.setPreviewWidget( ip );
+ dlg.exec();
+
+ return dlg.selectedURL();
+}
+
+KURL KFileDialog::selectedURL() const
+{
+ if ( result() == TQDialog::Accepted )
+ return d->url;
+ else
+ return KURL();
+}
+
+KURL::List KFileDialog::selectedURLs() const
+{
+ KURL::List list;
+ if ( result() == TQDialog::Accepted ) {
+ if ( (ops->mode() & KFile::Files) == KFile::Files )
+ list = parseSelectedURLs();
+ else
+ list.append( d->url );
+ }
+ return list;
+}
+
+
+KURL::List& KFileDialog::parseSelectedURLs() const
+{
+ if ( d->filenames.isEmpty() ) {
+ return d->urlList;
+ }
+
+ d->urlList.clear();
+ if ( d->filenames.contains( '/' )) { // assume _one_ absolute filename
+ static const TQString &prot = TDEGlobal::staticQString(":/");
+ KURL u;
+ if ( d->filenames.find( prot ) != -1 )
+ u = d->filenames;
+ else
+ u.setPath( d->filenames );
+
+ if ( u.isValid() )
+ d->urlList.append( u );
+ else
+ KMessageBox::error( d->mainWidget,
+ i18n("The chosen filenames do not\n"
+ "appear to be valid."),
+ i18n("Invalid Filenames") );
+ }
+
+ else
+ d->urlList = tokenize( d->filenames );
+
+ d->filenames = TQString::null; // indicate that we parsed that one
+
+ return d->urlList;
+}
+
+
+// FIXME: current implementation drawback: a filename can't contain quotes
+KURL::List KFileDialog::tokenize( const TQString& line ) const
+{
+ KURL::List urls;
+ KURL u( ops->url() );
+ TQString name;
+
+ int count = line.contains( '"' );
+ if ( count == 0 ) { // no " " -> assume one single file
+ u.setFileName( line );
+ if ( u.isValid() )
+ urls.append( u );
+
+ return urls;
+ }
+
+ if ( (count % 2) == 1 ) { // odd number of " -> error
+ TQWidget *that = const_cast<KFileDialog *>(this);
+ KMessageBox::sorry(that, i18n("The requested filenames\n"
+ "%1\n"
+ "do not appear to be valid;\n"
+ "make sure every filename is enclosed in double quotes.").arg(line),
+ i18n("Filename Error"));
+ return urls;
+ }
+
+ int start = 0;
+ int index1 = -1, index2 = -1;
+ while ( true ) {
+ index1 = line.find( '"', start );
+ index2 = line.find( '"', index1 + 1 );
+
+ if ( index1 < 0 )
+ break;
+
+ // get everything between the " "
+ name = line.mid( index1 + 1, index2 - index1 - 1 );
+ u.setFileName( name );
+ if ( u.isValid() )
+ urls.append( u );
+
+ start = index2 + 1;
+ }
+ return urls;
+}
+
+
+TQString KFileDialog::selectedFile() const
+{
+ if ( result() == TQDialog::Accepted )
+ {
+ KURL url = TDEIO::NetAccess::mostLocalURL(d->url,topLevelWidget());
+ if (url.isLocalFile())
+ return url.path();
+ else {
+ KMessageBox::sorry( d->mainWidget,
+ i18n("You can only select local files."),
+ i18n("Remote Files Not Accepted") );
+ }
+ }
+ return TQString::null;
+}
+
+TQStringList KFileDialog::selectedFiles() const
+{
+ TQStringList list;
+ KURL url;
+
+ if ( result() == TQDialog::Accepted ) {
+ if ( (ops->mode() & KFile::Files) == KFile::Files ) {
+ KURL::List urls = parseSelectedURLs();
+ TQValueListConstIterator<KURL> it = urls.begin();
+ while ( it != urls.end() ) {
+ url = TDEIO::NetAccess::mostLocalURL(*it,topLevelWidget());
+ if ( url.isLocalFile() )
+ list.append( url.path() );
+ ++it;
+ }
+ }
+
+ else { // single-selection mode
+ if ( d->url.isLocalFile() )
+ list.append( d->url.path() );
+ }
+ }
+
+ return list;
+}
+
+KURL KFileDialog::baseURL() const
+{
+ return ops->url();
+}
+
+TQString KFileDialog::getSaveFileName(const TQString& dir, const TQString& filter,
+ TQWidget *parent,
+ const TQString& caption)
+{
+ bool specialDir = dir.at(0) == ':';
+ KFileDialog dlg( specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
+ if ( !specialDir )
+ dlg.setSelection( dir ); // may also be a filename
+
+ dlg.setOperationMode( Saving );
+ dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
+
+ dlg.exec();
+
+ TQString filename = dlg.selectedFile();
+ if (!filename.isEmpty())
+ KRecentDocument::add(filename);
+
+ return filename;
+}
+
+TQString KFileDialog::getSaveFileNameWId(const TQString& dir, const TQString& filter,
+ WId parent_id,
+ const TQString& caption)
+{
+ bool specialDir = dir.at(0) == ':';
+ TQWidget* parent = TQT_TQWIDGET(TQWidget::find( parent_id ));
+ KFileDialog dlg( specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
+#ifdef Q_WS_X11
+ if( parent == NULL && parent_id != 0 )
+ XSetTransientForHint(tqt_xdisplay(), dlg.winId(), parent_id);
+#else
+ // TODO
+#endif
+
+ if ( !specialDir )
+ dlg.setSelection( dir ); // may also be a filename
+
+ dlg.setOperationMode( KFileDialog::Saving);
+ dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
+
+ dlg.exec();
+
+ TQString filename = dlg.selectedFile();
+ if (!filename.isEmpty())
+ KRecentDocument::add(filename);
+
+ return filename;
+}
+
+KURL KFileDialog::getSaveURL(const TQString& dir, const TQString& filter,
+ TQWidget *parent, const TQString& caption)
+{
+ bool specialDir = dir.at(0) == ':';
+ KFileDialog dlg(specialDir ? dir : TQString::null, filter, parent, "filedialog", true);
+ if ( !specialDir )
+ dlg.setSelection( dir ); // may also be a filename
+
+ dlg.setCaption(caption.isNull() ? i18n("Save As") : caption);
+ dlg.setOperationMode( Saving );
+
+ dlg.exec();
+
+ KURL url = dlg.selectedURL();
+ if (url.isValid())
+ KRecentDocument::add( url );
+
+ return url;
+}
+
+void KFileDialog::show()
+{
+ if ( !d->hasView ) { // delayed view-creation
+ ops->setView(KFile::Default);
+ ops->clearHistory();
+ d->hasView = true;
+ }
+
+ KDialogBase::show();
+}
+
+void KFileDialog::setMode( KFile::Mode m )
+{
+ ops->setMode(m);
+ if ( ops->dirOnlyMode() ) {
+ filterWidget->setDefaultFilter( i18n("*|All Folders") );
+ }
+ else {
+ filterWidget->setDefaultFilter( i18n("*|All Files") );
+ }
+
+ updateAutoSelectExtension ();
+}
+
+void KFileDialog::setMode( unsigned int m )
+{
+ setMode(static_cast<KFile::Mode>( m ));
+}
+
+KFile::Mode KFileDialog::mode() const
+{
+ return ops->mode();
+}
+
+
+void KFileDialog::readConfig( TDEConfig *kc, const TQString& group )
+{
+ if ( !kc )
+ return;
+
+ TQString oldGroup = kc->group();
+ if ( !group.isEmpty() )
+ kc->setGroup( group );
+
+ ops->readConfig( kc, group );
+
+ KURLComboBox *combo = d->pathCombo;
+ combo->setURLs( kc->readPathListEntry( RecentURLs ), KURLComboBox::RemoveTop );
+ combo->setMaxItems( kc->readNumEntry( RecentURLsNumber,
+ DefaultRecentURLsNumber ) );
+ combo->setURL( ops->url() );
+ autoDirectoryFollowing = kc->readBoolEntry( AutoDirectoryFollowing,
+ DefaultDirectoryFollowing );
+
+ TDEGlobalSettings::Completion cm = (TDEGlobalSettings::Completion)
+ kc->readNumEntry( PathComboCompletionMode,
+ TDEGlobalSettings::completionMode() );
+ if ( cm != TDEGlobalSettings::completionMode() )
+ combo->setCompletionMode( cm );
+
+ cm = (TDEGlobalSettings::Completion)
+ kc->readNumEntry( LocationComboCompletionMode,
+ TDEGlobalSettings::completionMode() );
+ if ( cm != TDEGlobalSettings::completionMode() )
+ locationEdit->setCompletionMode( cm );
+
+ // show or don't show the speedbar
+ toggleSpeedbar( kc->readBoolEntry(ShowSpeedbar, true) );
+
+ // show or don't show the bookmarks
+ toggleBookmarks( kc->readBoolEntry(ShowBookmarks, false) );
+
+ // does the user want Automatically Select Extension?
+ d->autoSelectExtChecked = kc->readBoolEntry (AutoSelectExtChecked, DefaultAutoSelectExtChecked);
+ updateAutoSelectExtension ();
+
+ int w1 = minimumSize().width();
+ int w2 = toolbar->sizeHint().width() + 10;
+ if (w1 < w2)
+ setMinimumWidth(w2);
+
+ TQSize size = configDialogSize( group );
+ resize( size );
+ kc->setGroup( oldGroup );
+}
+
+void KFileDialog::writeConfig( TDEConfig *kc, const TQString& group )
+{
+ if ( !kc )
+ return;
+
+ TQString oldGroup = kc->group();
+ if ( !group.isEmpty() )
+ kc->setGroup( group );
+
+ kc->writePathEntry( RecentURLs, d->pathCombo->urls() );
+ saveDialogSize( group, true );
+ kc->writeEntry( PathComboCompletionMode, static_cast<int>(d->pathCombo->completionMode()) );
+ kc->writeEntry( LocationComboCompletionMode, static_cast<int>(locationEdit->completionMode()) );
+ kc->writeEntry( ShowSpeedbar, d->urlBar && !d->urlBar->isHidden() );
+ kc->writeEntry( ShowBookmarks, d->bookmarkHandler != 0 );
+ kc->writeEntry( AutoSelectExtChecked, d->autoSelectExtChecked );
+
+ ops->writeConfig( kc, group );
+ kc->setGroup( oldGroup );
+}
+
+
+void KFileDialog::readRecentFiles( TDEConfig *kc )
+{
+ TQString oldGroup = kc->group();
+ kc->setGroup( ConfigGroup );
+
+ locationEdit->setMaxItems( kc->readNumEntry( RecentFilesNumber,
+ DefaultRecentURLsNumber ) );
+ locationEdit->setURLs( kc->readPathListEntry( RecentFiles ),
+ KURLComboBox::RemoveBottom );
+ locationEdit->insertItem( TQString::null, 0 ); // dummy item without pixmap
+ locationEdit->setCurrentItem( 0 );
+
+ kc->setGroup( oldGroup );
+}
+
+void KFileDialog::saveRecentFiles( TDEConfig *kc )
+{
+ TQString oldGroup = kc->group();
+ kc->setGroup( ConfigGroup );
+
+ kc->writePathEntry( RecentFiles, locationEdit->urls() );
+
+ kc->setGroup( oldGroup );
+}
+
+KPushButton * KFileDialog::okButton() const
+{
+ return d->okButton;
+}
+
+KPushButton * KFileDialog::cancelButton() const
+{
+ return d->cancelButton;
+}
+
+KURLBar * KFileDialog::speedBar()
+{
+ return d->urlBar;
+}
+
+void KFileDialog::slotCancel()
+{
+ ops->close();
+ KDialogBase::slotCancel();
+
+ TDEConfig *config = TDEGlobal::config();
+ config->setForceGlobal( true );
+ writeConfig( config, ConfigGroup );
+ config->setForceGlobal( false );
+}
+
+void KFileDialog::setKeepLocation( bool keep )
+{
+ d->keepLocation = keep;
+}
+
+bool KFileDialog::keepsLocation() const
+{
+ return d->keepLocation;
+}
+
+void KFileDialog::setOperationMode( OperationMode mode )
+{
+ d->operationMode = mode;
+ d->keepLocation = (mode == Saving);
+ filterWidget->setEditable( !d->hasDefaultFilter || mode != Saving );
+ if ( mode == Opening )
+ d->okButton->setGuiItem( KGuiItem( i18n("&Open"), "fileopen") );
+ else if ( mode == Saving ) {
+ d->okButton->setGuiItem( KStdGuiItem::save() );
+ setNonExtSelection();
+ }
+ else
+ d->okButton->setGuiItem( KStdGuiItem::ok() );
+ updateLocationWhatsThis ();
+ updateAutoSelectExtension ();
+}
+
+KFileDialog::OperationMode KFileDialog::operationMode() const
+{
+ return d->operationMode;
+}
+
+void KFileDialog::slotAutoSelectExtClicked()
+{
+ kdDebug (tdefile_area) << "slotAutoSelectExtClicked(): "
+ << d->autoSelectExtCheckBox->isChecked () << endl;
+
+ // whether the _user_ wants it on/off
+ d->autoSelectExtChecked = d->autoSelectExtCheckBox->isChecked ();
+
+ // update the current filename's extension
+ updateLocationEditExtension (d->extension /* extension hasn't changed */);
+}
+
+static TQString getExtensionFromPatternList (const TQStringList &patternList)
+{
+ TQString ret;
+ kdDebug (tdefile_area) << "\tgetExtension " << patternList << endl;
+
+ TQStringList::ConstIterator patternListEnd = patternList.end ();
+ for (TQStringList::ConstIterator it = patternList.begin ();
+ it != patternListEnd;
+ it++)
+ {
+ kdDebug (tdefile_area) << "\t\ttry: \'" << (*it) << "\'" << endl;
+
+ // is this pattern like "*.BMP" rather than useless things like:
+ //
+ // README
+ // *.
+ // *.*
+ // *.JP*G
+ // *.JP?
+ if ((*it).startsWith ("*.") &&
+ (*it).length () > 2 &&
+ (*it).find ('*', 2) < 0 && (*it).find ('?', 2) < 0)
+ {
+ ret = (*it).mid (1);
+ break;
+ }
+ }
+
+ return ret;
+}
+
+static TQString stripUndisplayable (const TQString &string)
+{
+ TQString ret = string;
+
+ ret.remove (':');
+ ret.remove ('&');
+
+ return ret;
+}
+
+
+TQString KFileDialog::currentFilterExtension (void)
+{
+ return d->extension;
+}
+
+void KFileDialog::updateAutoSelectExtension (void)
+{
+ if (!d->autoSelectExtCheckBox) return;
+
+ //
+ // Figure out an extension for the Automatically Select Extension thing
+ // (some Windows users apparently don't know what to do when confronted
+ // with a text file called "COPYING" but do know what to do with
+ // COPYING.txt ...)
+ //
+
+ kdDebug (tdefile_area) << "Figure out an extension: " << endl;
+ TQString lastExtension = d->extension;
+ d->extension = TQString::null;
+
+ // Automatically Select Extension is only valid if the user is _saving_ a _file_
+ if ((operationMode () == Saving) && (mode () & KFile::File))
+ {
+ //
+ // Get an extension from the filter
+ //
+
+ TQString filter = currentFilter ();
+ if (!filter.isEmpty ())
+ {
+ // e.g. "*.cpp"
+ if (filter.find ('/') < 0)
+ {
+ d->extension = getExtensionFromPatternList (TQStringList::split (" ", filter)).lower ();
+ kdDebug (tdefile_area) << "\tsetFilter-style: pattern ext=\'"
+ << d->extension << "\'" << endl;
+ }
+ // e.g. "text/html"
+ else
+ {
+ KMimeType::Ptr mime = KMimeType::mimeType (filter);
+
+ // first try X-TDE-NativeExtension
+ TQString nativeExtension = mime->property ("X-TDE-NativeExtension").toString ();
+ if (nativeExtension.at (0) == '.')
+ {
+ d->extension = nativeExtension.lower ();
+ kdDebug (tdefile_area) << "\tsetMimeFilter-style: native ext=\'"
+ << d->extension << "\'" << endl;
+ }
+
+ // no X-TDE-NativeExtension
+ if (d->extension.isEmpty ())
+ {
+ d->extension = getExtensionFromPatternList (mime->patterns ()).lower ();
+ kdDebug (tdefile_area) << "\tsetMimeFilter-style: pattern ext=\'"
+ << d->extension << "\'" << endl;
+ }
+ }
+ }
+
+
+ //
+ // GUI: checkbox
+ //
+
+ TQString whatsThisExtension;
+ if (!d->extension.isEmpty ())
+ {
+ // remember: sync any changes to the string with below
+ d->autoSelectExtCheckBox->setText (i18n ("Automatically select filename e&xtension (%1)").arg (d->extension));
+ whatsThisExtension = i18n ("the extension <b>%1</b>").arg (d->extension);
+
+ d->autoSelectExtCheckBox->setEnabled (true);
+ d->autoSelectExtCheckBox->setChecked (d->autoSelectExtChecked);
+ }
+ else
+ {
+ // remember: sync any changes to the string with above
+ d->autoSelectExtCheckBox->setText (i18n ("Automatically select filename e&xtension"));
+ whatsThisExtension = i18n ("a suitable extension");
+
+ d->autoSelectExtCheckBox->setChecked (false);
+ d->autoSelectExtCheckBox->setEnabled (false);
+ }
+
+ const TQString locationLabelText = stripUndisplayable (d->locationLabel->text ());
+ const TQString filterLabelText = stripUndisplayable (d->filterLabel->text ());
+ TQWhatsThis::add (d->autoSelectExtCheckBox,
+ "<qt>" +
+ i18n (
+ "This option enables some convenient features for "
+ "saving files with extensions:<br>"
+ "<ol>"
+ "<li>Any extension specified in the <b>%1</b> text "
+ "area will be updated if you change the file type "
+ "to save in.<br>"
+ "<br></li>"
+ "<li>If no extension is specified in the <b>%2</b> "
+ "text area when you click "
+ "<b>Save</b>, %3 will be added to the end of the "
+ "filename (if the filename does not already exist). "
+ "This extension is based on the file type that you "
+ "have chosen to save in.<br>"
+ "<br>"
+ "If you do not want TDE to supply an extension for the "
+ "filename, you can either turn this option off or you "
+ "can suppress it by adding a period (.) to the end of "
+ "the filename (the period will be automatically "
+ "removed)."
+ "</li>"
+ "</ol>"
+ "If unsure, keep this option enabled as it makes your "
+ "files more manageable."
+ )
+ .arg (locationLabelText)
+ .arg (locationLabelText)
+ .arg (whatsThisExtension)
+ + "</qt>"
+ );
+
+ d->autoSelectExtCheckBox->show ();
+
+
+ // update the current filename's extension
+ updateLocationEditExtension (lastExtension);
+ }
+ // Automatically Select Extension not valid
+ else
+ {
+ d->autoSelectExtCheckBox->setChecked (false);
+ d->autoSelectExtCheckBox->hide ();
+ }
+}
+
+// Updates the extension of the filename specified in locationEdit if the
+// Automatically Select Extension feature is enabled.
+// (this prevents you from accidently saving "file.kwd" as RTF, for example)
+void KFileDialog::updateLocationEditExtension (const TQString &lastExtension)
+{
+ if (!d->autoSelectExtCheckBox->isChecked () || d->extension.isEmpty ())
+ return;
+
+ TQString urlStr = locationEdit->currentText ();
+ if (urlStr.isEmpty ())
+ return;
+
+ KURL url = getCompleteURL (urlStr);
+ kdDebug (tdefile_area) << "updateLocationEditExtension (" << url << ")" << endl;
+
+ const int fileNameOffset = urlStr.findRev ('/') + 1;
+ TQString fileName = urlStr.mid (fileNameOffset);
+
+ const int dot = fileName.findRev ('.');
+ const int len = fileName.length ();
+ if (dot > 0 && // has an extension already and it's not a hidden file
+ // like ".hidden" (but we do accept ".hidden.ext")
+ dot != len - 1 // and not deliberately suppressing extension
+ )
+ {
+ // exists?
+ TDEIO::UDSEntry t;
+ if (TDEIO::NetAccess::stat (url, t, topLevelWidget()))
+ {
+ kdDebug (tdefile_area) << "\tfile exists" << endl;
+
+ if (isDirectory (t))
+ {
+ kdDebug (tdefile_area) << "\tisDir - won't alter extension" << endl;
+ return;
+ }
+
+ // --- fall through ---
+ }
+
+
+ //
+ // try to get rid of the current extension
+ //
+
+ // catch "double extensions" like ".tar.gz"
+ if (lastExtension.length () && fileName.endsWith (lastExtension))
+ fileName.truncate (len - lastExtension.length ());
+ // can only handle "single extensions"
+ else
+ fileName.truncate (dot);
+
+ // add extension
+ const TQString newText = urlStr.left (fileNameOffset) + fileName + d->extension;
+ if ( newText != locationEdit->currentText() )
+ {
+ locationEdit->setCurrentText (urlStr.left (fileNameOffset) + fileName + d->extension);
+ locationEdit->lineEdit()->setEdited (true);
+ }
+ }
+}
+
+// Updates the filter if the extension of the filename specified in locationEdit is changed
+// (this prevents you from accidently saving "file.kwd" as RTF, for example)
+void KFileDialog::updateFilter ()
+{
+ if ((operationMode() == Saving) && (mode() & KFile::File) ) {
+ const TQString urlStr = locationEdit->currentText ();
+ if (urlStr.isEmpty ())
+ return;
+
+ KMimeType::Ptr mime = KMimeType::findByPath(urlStr, 0, true);
+ if (mime && mime->name() != KMimeType::defaultMimeType()) {
+ if (filterWidget->currentFilter() != mime->name() &&
+ filterWidget->filters.findIndex(mime->name()) != -1) {
+ filterWidget->setCurrentFilter(mime->name());
+ }
+ }
+ }
+}
+
+// applies only to a file that doesn't already exist
+void KFileDialog::appendExtension (KURL &url)
+{
+ if (!d->autoSelectExtCheckBox->isChecked () || d->extension.isEmpty ())
+ return;
+
+ TQString fileName = url.fileName ();
+ if (fileName.isEmpty ())
+ return;
+
+ kdDebug (tdefile_area) << "appendExtension(" << url << ")" << endl;
+
+ const int len = fileName.length ();
+ const int dot = fileName.findRev ('.');
+
+ const bool suppressExtension = (dot == len - 1);
+ const bool unspecifiedExtension = (dot <= 0);
+
+ // don't TDEIO::NetAccess::Stat if unnecessary
+ if (!(suppressExtension || unspecifiedExtension))
+ return;
+
+ // exists?
+ TDEIO::UDSEntry t;
+ if (TDEIO::NetAccess::stat (url, t, topLevelWidget()))
+ {
+ kdDebug (tdefile_area) << "\tfile exists - won't append extension" << endl;
+ return;
+ }
+
+ // suppress automatically append extension?
+ if (suppressExtension)
+ {
+ //
+ // Strip trailing dot
+ // This allows lazy people to have autoSelectExtCheckBox->isChecked
+ // but don't want a file extension to be appended
+ // e.g. "README." will make a file called "README"
+ //
+ // If you really want a name like "README.", then type "README.."
+ // and the trailing dot will be removed (or just stop being lazy and
+ // turn off this feature so that you can type "README.")
+ //
+ kdDebug (tdefile_area) << "\tstrip trailing dot" << endl;
+ url.setFileName (fileName.left (len - 1));
+ }
+ // evilmatically append extension :) if the user hasn't specified one
+ else if (unspecifiedExtension)
+ {
+ kdDebug (tdefile_area) << "\tappending extension \'" << d->extension << "\'..." << endl;
+ url.setFileName (fileName + d->extension);
+ kdDebug (tdefile_area) << "\tsaving as \'" << url << "\'" << endl;
+ }
+}
+
+
+// adds the selected files/urls to 'recent documents'
+void KFileDialog::addToRecentDocuments()
+{
+ int m = ops->mode();
+
+ if ( m & KFile::LocalOnly ) {
+ TQStringList files = selectedFiles();
+ TQStringList::ConstIterator it = files.begin();
+ for ( ; it != files.end(); ++it )
+ KRecentDocument::add( *it );
+ }
+
+ else { // urls
+ KURL::List urls = selectedURLs();
+ KURL::List::ConstIterator it = urls.begin();
+ for ( ; it != urls.end(); ++it ) {
+ if ( (*it).isValid() )
+ KRecentDocument::add( *it );
+ }
+ }
+}
+
+KActionCollection * KFileDialog::actionCollection() const
+{
+ return ops->actionCollection();
+}
+
+void KFileDialog::keyPressEvent( TQKeyEvent *e )
+{
+ if ( e->key() == Key_Escape )
+ {
+ e->accept();
+ d->cancelButton->animateClick();
+ }
+ else
+ KDialogBase::keyPressEvent( e );
+}
+
+void KFileDialog::toggleSpeedbar( bool show )
+{
+ if ( show )
+ {
+ if ( !d->urlBar )
+ initSpeedbar();
+
+ d->urlBar->show();
+
+ // check to see if they have a home item defined, if not show the home button
+ KURLBarItem *urlItem = static_cast<KURLBarItem*>( d->urlBar->listBox()->firstItem() );
+ KURL homeURL;
+ homeURL.setPath( TQDir::homeDirPath() );
+ while ( urlItem )
+ {
+ if ( homeURL.equals( urlItem->url(), true ) )
+ {
+ ops->actionCollection()->action( "home" )->unplug( toolbar );
+ break;
+ }
+
+ urlItem = static_cast<KURLBarItem*>( urlItem->next() );
+ }
+ }
+ else
+ {
+ if (d->urlBar)
+ d->urlBar->hide();
+
+ if ( !ops->actionCollection()->action( "home" )->isPlugged( toolbar ) )
+ ops->actionCollection()->action( "home" )->plug( toolbar, 3 );
+ }
+
+ static_cast<KToggleAction *>(actionCollection()->action("toggleSpeedbar"))->setChecked( show );
+}
+
+void KFileDialog::toggleBookmarks(bool show)
+{
+ if (show)
+ {
+ if (d->bookmarkHandler)
+ {
+ return;
+ }
+
+ d->bookmarkHandler = new KFileBookmarkHandler( this );
+ connect( d->bookmarkHandler, TQT_SIGNAL( openURL( const TQString& )),
+ TQT_SLOT( enterURL( const TQString& )));
+
+ toolbar->insertButton(TQString::fromLatin1("bookmark"),
+ (int)HOTLIST_BUTTON, true,
+ i18n("Bookmarks"), 5);
+ toolbar->getButton(HOTLIST_BUTTON)->setPopup(d->bookmarkHandler->menu(),
+ true);
+ TQWhatsThis::add(toolbar->getButton(HOTLIST_BUTTON),
+ i18n("<qt>This button allows you to bookmark specific locations. "
+ "Click on this button to open the bookmark menu where you may add, "
+ "edit or select a bookmark.<p>"
+ "These bookmarks are specific to the file dialog, but otherwise operate "
+ "like bookmarks elsewhere in TDE.</qt>"));
+ }
+ else if (d->bookmarkHandler)
+ {
+ delete d->bookmarkHandler;
+ d->bookmarkHandler = 0;
+ toolbar->removeItem(HOTLIST_BUTTON);
+ }
+
+ static_cast<KToggleAction *>(actionCollection()->action("toggleBookmarks"))->setChecked( show );
+}
+
+int KFileDialog::pathComboIndex()
+{
+ return d->m_pathComboIndex;
+}
+
+// static
+void KFileDialog::initStatic()
+{
+ if ( lastDirectory )
+ return;
+
+ lastDirectory = ldd.setObject(lastDirectory, new KURL());
+}
+
+// static
+KURL KFileDialog::getStartURL( const TQString& startDir,
+ TQString& recentDirClass )
+{
+ initStatic();
+
+ recentDirClass = TQString::null;
+ KURL ret;
+
+ bool useDefaultStartDir = startDir.isEmpty();
+ if ( !useDefaultStartDir )
+ {
+ if (startDir[0] == ':')
+ {
+ recentDirClass = startDir;
+ ret = KURL::fromPathOrURL( KRecentDirs::dir(recentDirClass) );
+ }
+ else
+ {
+ ret = TDECmdLineArgs::makeURL( TQFile::encodeName(startDir) );
+ // If we won't be able to list it (e.g. http), then use default
+ if ( !KProtocolInfo::supportsListing( ret ) )
+ useDefaultStartDir = true;
+ }
+ }
+
+ if ( useDefaultStartDir )
+ {
+ if (lastDirectory->isEmpty()) {
+ lastDirectory->setPath(TDEGlobalSettings::documentPath());
+ KURL home;
+ home.setPath( TQDir::homeDirPath() );
+ // if there is no docpath set (== home dir), we prefer the current
+ // directory over it. We also prefer the homedir when our CWD is
+ // different from our homedirectory or when the document dir
+ // does not exist
+ if ( lastDirectory->path(+1) == home.path(+1) ||
+ TQDir::currentDirPath() != TQDir::homeDirPath() ||
+ !TQDir(lastDirectory->path(+1)).exists() )
+ lastDirectory->setPath(TQDir::currentDirPath());
+ }
+ ret = *lastDirectory;
+ }
+
+ return ret;
+}
+
+void KFileDialog::setStartDir( const KURL& directory )
+{
+ initStatic();
+ if ( directory.isValid() )
+ *lastDirectory = directory;
+}
+
+void KFileDialog::setNonExtSelection()
+{
+ // Enhanced rename: Don't highlight the file extension.
+ TQString pattern, filename = locationEdit->currentText().stripWhiteSpace();
+ KServiceTypeFactory::self()->findFromPattern( filename, &pattern );
+
+ if ( !pattern.isEmpty() && pattern.at( 0 ) == '*' && pattern.find( '*' , 1 ) == -1 )
+ locationEdit->lineEdit()->setSelection( 0, filename.length() - pattern.stripWhiteSpace().length()+1 );
+ else
+ {
+ int lastDot = filename.findRev( '.' );
+ if ( lastDot > 0 )
+ locationEdit->lineEdit()->setSelection( 0, lastDot );
+ }
+}
+
+void KFileDialog::virtual_hook( int id, void* data )
+{ KDialogBase::virtual_hook( id, data ); }
+
+
+#include "tdefiledialog.moc"
diff --git a/tdeio/tdefile/tdefiledialog.h b/tdeio/tdefile/tdefiledialog.h
new file mode 100644
index 000000000..28b04aff6
--- /dev/null
+++ b/tdeio/tdefile/tdefiledialog.h
@@ -0,0 +1,989 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1997, 1998 Richard Moore <rich@kde.org>
+ 1998 Stephan Kulow <coolo@kde.org>
+ 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ 2000,2001 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2001 Frerich Raabe <raabe@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __KFILEDIALOG_H__
+#define __KFILEDIALOG_H__
+
+#include <tqstring.h>
+
+#include <kdialogbase.h>
+#include <tdefile.h>
+#include <kurl.h>
+#include <kmimetype.h>
+#include <tdeio/jobclasses.h>
+
+class TQCheckBox;
+class TQHBoxLayout;
+class TQGridLayout;
+class TQLabel;
+class TQPopupMenu;
+class TQVBoxLayout;
+
+class KActionCollection;
+class KDirOperator;
+class KURLBar;
+class KURLComboBox;
+class KFileFilterCombo;
+class KFileView;
+class KFileItem;
+class KPushButton;
+class KToolBar;
+class KPreviewWidgetBase;
+
+struct KFileDialogPrivate;
+
+/**
+ * Provides a user (and developer) friendly way to
+ * select files and directories.
+ *
+ * The widget can be used as a drop in replacement for the
+ * TQFileDialog widget, but has greater functionality and a nicer GUI.
+ *
+ * You will usually want to use one of the static methods
+ * getOpenFileName(), getSaveFileName(), getOpenURL()
+ * or for multiple files getOpenFileNames() or getOpenURLs().
+ *
+ * The dialog has been designed to allow applications to customise it
+ * by subclassing. It uses geometry management to ensure that subclasses
+ * can easily add children that will be incorporated into the layout.
+ *
+ * \image html tdefiledialog.png "KDE File Dialog"
+ *
+ * @short A file selection dialog.
+ *
+ * @author Richard J. Moore <rich@kde.org>, Carsten Pfeiffer <pfeiffer@kde.org>
+ */
+class TDEIO_EXPORT KFileDialog : public KDialogBase
+{
+ Q_OBJECT
+
+public:
+
+ /**
+ * Defines some default behavior of the filedialog.
+ * E.g. in mode @p Opening and @p Saving, the selected files/urls will
+ * be added to the "recent documents" list. The Saving mode also implies
+ * setKeepLocation() being set.
+ *
+ * @p Other means that no default actions are performed.
+ *
+ * @see setOperationMode
+ * @see operationMode
+ */
+ enum OperationMode { Other = 0, Opening, Saving };
+
+ /**
+ * Constructs a file dialog.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ *
+ * @param filter A shell glob or a mime-type-filter that specifies
+ * which files to display.
+ * @param parent The parent widget of this dialog
+ * @param name The name of this object
+ * @param modal Whether to create a modal dialog or not
+ * See setFilter() for details on how to use this argument.
+ *
+ */
+ KFileDialog(const TQString& startDir, const TQString& filter,
+ TQWidget *parent, const char *name,
+ bool modal);
+
+ /**
+ * Constructs a file dialog.
+ *
+ * The parameters here are identical to the first constructor except
+ * for the addition of a TQWidget parameter.
+ *
+ * Historical note: The original version of KFileDialog did not have this extra
+ * parameter. It was added later, and, in order to maintain binary compatibility,
+ * it was placed in a new constructor instead of added to the original one.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ *
+ * @param filter A shell glob or a mime-type-filter that specifies
+ * which files to display.
+ * See setFilter() for details on how to use this argument.
+ *
+ * @param widget A widget, or a widget of widgets, for displaying custom
+ * data in the dialog. This can be used, for example, to
+ * display a check box with the caption "Open as read-only".
+ * When creating this widget, you don't need to specify a parent,
+ * since the widget's parent will be set automatically by KFileDialog.
+ * @param parent The parent widget of this dialog
+ * @param name The name of this object
+ * @param modal Whether to create a modal dialog or not
+ * @since 3.1
+ */
+ KFileDialog(const TQString& startDir, const TQString& filter,
+ TQWidget *parent, const char *name,
+ bool modal, TQWidget* widget);
+
+
+ /**
+ * Destructs the file dialog.
+ */
+ ~KFileDialog();
+
+ /**
+ * @returns The selected fully qualified filename.
+ */
+ KURL selectedURL() const;
+
+ /**
+ * @returns The list of selected URLs.
+ */
+ KURL::List selectedURLs() const;
+
+ /**
+ * @returns the currently shown directory.
+ */
+ KURL baseURL() const;
+
+ /**
+ * Returns the full path of the selected file in the local filesystem.
+ * (Local files only)
+ */
+ TQString selectedFile() const;
+
+ /**
+ * Returns a list of all selected local files.
+ */
+ TQStringList selectedFiles() const;
+
+ /**
+ * Sets the directory to view.
+ *
+ * @param url URL to show.
+ * @param clearforward Indicates whether the forward queue
+ * should be cleared.
+ */
+ void setURL(const KURL &url, bool clearforward = true);
+
+ /**
+ * Sets the file name to preselect to @p name
+ *
+ * This takes absolute URLs and relative file names.
+ */
+ void setSelection(const TQString& name);
+
+ /**
+ * Sets the operational mode of the filedialog to @p Saving, @p Opening
+ * or @p Other. This will set some flags that are specific to loading
+ * or saving files. E.g. setKeepLocation() makes mostly sense for
+ * a save-as dialog. So setOperationMode( KFileDialog::Saving ); sets
+ * setKeepLocation for example.
+ *
+ * The mode @p Saving, together with a default filter set via
+ * setMimeFilter() will make the filter combobox read-only.
+ *
+ * The default mode is @p Opening.
+ *
+ * Call this method right after instantiating KFileDialog.
+ *
+ * @see operationMode
+ * @see KFileDialog::OperationMode
+ */
+ void setOperationMode( KFileDialog::OperationMode );
+
+ /**
+ * @returns the current operation mode, Opening, Saving or Other. Default
+ * is Other.
+ *
+ * @see operationMode
+ * @see KFileDialog::OperationMode
+ */
+ OperationMode operationMode() const;
+
+ /**
+ * Sets whether the filename/url should be kept when changing directories.
+ * This is for example useful when having a predefined filename where
+ * the full path for that file is searched.
+ *
+ * This is implicitly set when operationMode() is KFileDialog::Saving
+ *
+ * getSaveFileName() and getSaveURL() set this to true by default, so that
+ * you can type in the filename and change the directory without having
+ * to type the name again.
+ */
+ void setKeepLocation( bool keep );
+
+ /**
+ * @returns whether the contents of the location edit are kept when
+ * changing directories.
+ */
+ bool keepsLocation() const;
+
+ /**
+ * Sets the filter to be used to @p filter.
+ *
+ * You can set more
+ * filters for the user to select separated by '\n'. Every
+ * filter entry is defined through namefilter|text to diplay.
+ * If no | is found in the expression, just the namefilter is
+ * shown. Examples:
+ *
+ * \code
+ * tdefile->setFilter("*.cpp|C++ Source Files\n*.h|Header files");
+ * tdefile->setFilter("*.cpp");
+ * tdefile->setFilter("*.cpp|Sources (*.cpp)");
+ * tdefile->setFilter("*.cpp|" + i18n("Sources (*.cpp)"));
+ * tdefile->setFilter("*.cpp *.cc *.C|C++ Source Files\n*.h *.H|Header files");
+ * \endcode
+ *
+ * Note: The text to display is not parsed in any way. So, if you
+ * want to show the suffix to select by a specific filter, you must
+ * repeat it.
+ *
+ * If the filter contains an unescaped '/', a mimetype-filter is assumed.
+ * If you would like a '/' visible in your filter it can be escaped with
+ * a '\'. You can specify multiple mimetypes like this (separated with
+ * space):
+ *
+ * \code
+ * tdefile->setFilter( "image/png text/html text/plain" );
+ * tdefile->setFilter( "*.cue|CUE\\/BIN Files (*.cue)" );
+ * \endcode
+ *
+ * @see filterChanged
+ * @see setMimeFilter
+ */
+ void setFilter(const TQString& filter);
+
+ /**
+ * Returns the current filter as entered by the user or one of the
+ * predefined set via setFilter().
+ *
+ * @see setFilter()
+ * @see filterChanged()
+ */
+ TQString currentFilter() const;
+
+ /**
+ * Sets the filter up to specify the output type.
+ *
+ * @param label the label to use instead of "Filter:"
+ * @param types a list of mimetypes that can be used as output format
+ * @param defaultType the default mimetype to use as output format.
+ *
+ * Do not use in conjunction with setFilter()
+ * @deprecated
+ */
+ void setFilterMimeType(const TQString &label, const KMimeType::List &types, const KMimeType::Ptr &defaultType) KDE_DEPRECATED;
+
+ /**
+ * Returns the mimetype for the desired output format.
+ *
+ * This is only valid if setFilterMimeType() has been called
+ * previously.
+ *
+ * @see setFilterMimeType()
+ */
+ KMimeType::Ptr currentFilterMimeType();
+
+ /**
+ * Sets the filter up to specify the output type.
+ *
+ * @param types a list of mimetypes that can be used as output format
+ * @param defaultType the default mimetype to use as output format, if any.
+ * If @p defaultType is set, it will be set as the current item.
+ * Otherwise, a first item showing all the mimetypes will be created.
+ * Typically, @p defaultType should be empty for loading and set for saving.
+ *
+ * Do not use in conjunction with setFilter()
+ */
+ void setMimeFilter( const TQStringList& types,
+ const TQString& defaultType = TQString::null );
+
+ /**
+ * The mimetype for the desired output format.
+ *
+ * This is only valid if setMimeFilter() has been called
+ * previously.
+ *
+ * @see setMimeFilter()
+ */
+ TQString currentMimeFilter() const;
+
+ /**
+ * Clears any mime- or namefilter. Does not reload the directory.
+ */
+ void clearFilter();
+
+ /**
+ * @deprecated
+ * Add a preview widget and enter the preview mode.
+ *
+ * In this mode
+ * the dialog is split and the right part contains your widget.
+ * This widget has to inherit TQWidget and it has to implement
+ * a slot showPreview(const KURL &); which is called
+ * every time the file changes. You may want to look at
+ * koffice/lib/kofficecore/koFilterManager.cc for some hints :)
+ *
+ * Ownership is transferred to KFileDialog. You need to create the
+ * preview-widget with "new", i.e. on the heap.
+ */
+ void setPreviewWidget(const TQWidget *w) KDE_DEPRECATED;
+
+ /**
+ * Adds a preview widget and enters the preview mode.
+ *
+ * In this mode the dialog is split and the right part contains your
+ * preview widget.
+ *
+ * Ownership is transferred to KFileDialog. You need to create the
+ * preview-widget with "new", i.e. on the heap.
+ *
+ * @param w The widget to be used for the preview.
+ */
+ void setPreviewWidget(const KPreviewWidgetBase *w);
+
+ /**
+ * Creates a modal file dialog and return the selected
+ * filename or an empty string if none was chosen.
+ *
+ * Note that with
+ * this method the user must select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static TQString getOpenFileName(const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+
+ /**
+ * Use this version only if you have no TQWidget available as
+ * parent widget. This can be the case if the parent widget is
+ * a widget in another process or if the parent widget is a
+ * non-Qt widget. For example, in a GTK program.
+ *
+ * @since 3.4
+ */
+ static TQString getOpenFileNameWId(const TQString& startDir,
+ const TQString& filter,
+ WId parent_id, const TQString& caption);
+
+ /**
+ * Creates a modal file dialog and returns the selected
+ * filenames or an empty list if none was chosen.
+ *
+ * Note that with
+ * this method the user must select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static TQStringList getOpenFileNames(const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent = 0,
+ const TQString& caption= TQString::null);
+
+
+
+ /**
+ * Creates a modal file dialog and returns the selected
+ * URL or an empty string if none was chosen.
+ *
+ * Note that with
+ * this method the user must select an existing URL.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static KURL getOpenURL(const TQString& startDir = TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+
+
+ /**
+ * Creates a modal file dialog and returns the selected
+ * URLs or an empty list if none was chosen.
+ *
+ * Note that with
+ * this method the user must select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static KURL::List getOpenURLs(const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent = 0,
+ const TQString& caption= TQString::null);
+
+
+
+ /**
+ * Creates a modal file dialog and returns the selected
+ * filename or an empty string if none was chosen.
+ *
+ * Note that with this
+ * method the user need not select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li a relative path or a filename determining the
+ * directory to start in and the file to be selected.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static TQString getSaveFileName(const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+
+ /**
+ * This function accepts the window id of the parent window, instead
+ * of TQWidget*. It should be used only when necessary.
+ * @since 3.4
+ */
+ static TQString getSaveFileNameWId(const TQString& dir, const TQString& filter,
+ WId parent_id,
+ const TQString& caption);
+
+ /**
+ * Creates a modal file dialog and returns the selected
+ * filename or an empty string if none was chosen.
+ *
+ * Note that with this
+ * method the user need not select an existing filename.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li a relative path or a filename determining the
+ * directory to start in and the file to be selected.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param filter This is a space separated list of shell globs.
+ * You can set the text to be displayed for the glob, and
+ * provide multiple globs. See setFilter() for details on
+ * how to do this...
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static KURL getSaveURL(const TQString& startDir= TQString::null,
+ const TQString& filter= TQString::null,
+ TQWidget *parent= 0,
+ const TQString& caption = TQString::null);
+
+
+ /**
+ * Creates a modal file dialog and returns the selected
+ * directory or an empty string if none was chosen.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static TQString getExistingDirectory(const TQString & startDir = TQString::null,
+ TQWidget * parent = 0,
+ const TQString& caption= TQString::null);
+
+ /**
+ * Creates a modal file dialog and returns the selected
+ * directory or an empty string if none was chosen.
+ *
+ * Contrary to getExistingDirectory(), this method allows the
+ * selection of a remote directory.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ * @since 3.1
+ */
+ static KURL getExistingURL(const TQString & startDir = TQString::null,
+ TQWidget * parent = 0,
+ const TQString& caption= TQString::null);
+ /**
+ * Creates a modal file dialog with an image previewer and returns the
+ * selected url or an empty string if none was chosen.
+ *
+ * @param startDir This can either be
+ * @li The URL of the directory to start in.
+ * @li TQString::null to start in the current working
+ * directory, or the last directory where a file has been
+ * selected.
+ * @li ':&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in the same application that specified
+ * the same keyword.
+ * @li '::&lt;keyword&gt;' to start in the directory last used
+ * by a filedialog in any application that specified the
+ * same keyword.
+ * @param parent The widget the dialog will be centered on initially.
+ * @param caption The name of the dialog widget.
+ */
+ static KURL getImageOpenURL( const TQString& startDir = TQString::null,
+ TQWidget *parent = 0,
+ const TQString& caption = TQString::null );
+ virtual void show();
+
+ /**
+ * Convenient overload of the other setMode(unsigned int) method.
+ */
+ void setMode( KFile::Mode m );
+
+ /**
+ * Sets the mode of the dialog.
+ *
+ * The mode is defined as (in tdefile.h):
+ * \code
+ * enum Mode {
+ * File = 1,
+ * Directory = 2,
+ * Files = 4,
+ * ExistingOnly = 8,
+ * LocalOnly = 16
+ * };
+ * \endcode
+ * You can OR the values, e.g.
+ * \code
+ * KFile::Mode mode = static_cast<KFile::Mode>( KFile::Files |
+ * KFile::ExistingOnly |
+ * KFile::LocalOnly );
+ * setMode( mode );
+ * \endcode
+ */
+ void setMode( unsigned int m );
+
+ /**
+ * Returns the mode of the filedialog.
+ * @see setMode()
+ */
+ KFile::Mode mode() const;
+
+ /**
+ * Sets the text to be displayed in front of the selection.
+ *
+ * The default is "Location".
+ * Most useful if you want to make clear what
+ * the location is used for.
+ */
+ void setLocationLabel(const TQString& text);
+
+ /**
+ * Returns a pointer to the toolbar.
+ *
+ * You can use this to insert custom
+ * items into it, e.g.:
+ * \code
+ * yourAction = new KAction( i18n("Your Action"), 0,
+ * this, TQT_SLOT( yourSlot() ),
+ * this, "action name" );
+ * yourAction->plug( tdefileDialog->toolBar() );
+ * \endcode
+ */
+ KToolBar *toolBar() const { return toolbar; }
+
+ /**
+ * @returns a pointer to the OK-Button in the filedialog. You may use it
+ * e.g. to set a custom text to it.
+ */
+ KPushButton *okButton() const;
+
+ /**
+ * @returns a pointer to the Cancel-Button in the filedialog. You may use
+ * it e.g. to set a custom text to it.
+ */
+ KPushButton *cancelButton() const;
+
+ /**
+ * @returns the KURLBar object used as the "speed bar". You can add custom
+ * entries to it like that:
+ * \code
+ * KURLBar *urlBar = fileDialog->speedBar();
+ * if ( urlBar )
+ * urlBar->insertDynamicItem( someURL, i18n("The URL's description") );
+ * \endcode
+ *
+ * Note that this method may return a null-pointer if the user configured
+ * to not use the speed-bar.
+ * @see KURLBar
+ * @see KURLBar::insertDynamicItem
+ * @since 3.2
+ */
+ KURLBar *speedBar();
+
+ /**
+ * @returns a pointer to the action collection, holding all the used
+ * KActions.
+ */
+ KActionCollection *actionCollection() const;
+
+ /**
+ * @returns the index of the path combobox so when inserting widgets into
+ * the dialog (e.g. subclasses) they can do so without hardcoding in an index
+ */
+ int pathComboIndex();
+
+ /**
+ * This method implements the logic to determine the user's default directory
+ * to be listed. E.g. the documents direcory, home directory or a recently
+ * used directory.
+ * @param startDir A url/directory, to be used. May use the ':' and '::' syntax
+ * as documented in the KFileDialog() constructor.
+ * @param recentDirClass If the ':' or '::' syntax is used, recentDirClass
+ * will contain the string to be used later for KRecentDir::dir()
+ * @return The URL that should be listed by default (e.g. by KFileDialog or
+ * KDirSelectDialog).
+ * @since 3.1
+ */
+ static KURL getStartURL( const TQString& startDir, TQString& recentDirClass );
+
+ /**
+ * @internal
+ * Used by KDirSelectDialog to share the dialog's start directory.
+ */
+ static void setStartDir( const KURL& directory );
+
+signals:
+ /**
+ * Emitted when the user selects a file. It is only emitted in single-
+ * selection mode. The best way to get notified about selected file(s)
+ * is to connect to the okClicked() signal inherited from KDialogBase
+ * and call selectedFile(), selectedFiles(),
+ * selectedURL() or selectedURLs().
+ */
+ void fileSelected(const TQString&);
+
+ /**
+ * Emitted when the user highlights a file.
+ */
+ void fileHighlighted(const TQString&);
+
+ /**
+ * Emitted when the user hilights one or more files in multiselection mode.
+ *
+ * Note: fileHighlighted() or fileSelected() are @em not
+ * emitted in multiselection mode. You may use selectedItems() to
+ * ask for the current highlighted items.
+ * @see fileSelected
+ */
+ void selectionChanged();
+
+ /**
+ * Emitted when the filter changed, i.e. the user entered an own filter
+ * or chose one of the predefined set via setFilter().
+ *
+ * @param filter contains the new filter (only the extension part,
+ * not the explanation), i.e. "*.cpp" or "*.cpp *.cc".
+ *
+ * @see setFilter()
+ * @see currentFilter()
+ */
+ void filterChanged( const TQString& filter );
+
+protected:
+ KToolBar *toolbar;
+
+ static KURL *lastDirectory;
+
+ KURLComboBox *locationEdit;
+
+ KFileFilterCombo *filterWidget;
+
+ /**
+ * Reimplemented to animate the cancel button.
+ */
+ virtual void keyPressEvent( TQKeyEvent *e );
+
+ /**
+ * Perform basic initialization tasks. Called by constructors.
+ * @since 3.1
+ */
+ void init(const TQString& startDir, const TQString& filter, TQWidget* widget);
+
+ /**
+ * rebuild geometry management.
+ *
+ */
+ virtual void initGUI();
+
+ /**
+ * called when an item is highlighted/selected in multiselection mode.
+ * handles setting the locationEdit.
+ */
+ void multiSelectionChanged();
+
+ /**
+ * Reads configuration and applies it (size, recent directories, ...)
+ */
+ virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
+
+ /**
+ * Saves the current configuration
+ */
+ virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null );
+
+ /**
+ * Reads the recent used files and inserts them into the location combobox
+ */
+ virtual void readRecentFiles( TDEConfig * );
+
+ /**
+ * Saves the entries from the location combobox.
+ */
+ virtual void saveRecentFiles( TDEConfig * );
+
+ /**
+ * Parses the string "line" for files. If line doesn't contain any ", the
+ * whole line will be interpreted as one file. If the number of " is odd,
+ * an empty list will be returned. Otherwise, all items enclosed in " "
+ * will be returned as correct urls.
+ */
+ KURL::List tokenize(const TQString& line) const;
+
+ /**
+ * Returns the absolute version of the URL specified in locationEdit.
+ * @since 3.2
+ */
+ KURL getCompleteURL(const TQString&);
+
+ /**
+ * Returns the filename extension associated with the currentFilter().
+ * TQString::null is returned if an extension is not available or if
+ * operationMode() != Saving.
+ * @since 3.2
+ */
+ TQString currentFilterExtension();
+
+ /**
+ * Updates the currentFilterExtension and the availability of the
+ * Automatically Select Extension Checkbox (visible if operationMode()
+ * == Saving and enabled if an extension _will_ be associated with the
+ * currentFilter(), _after_ this call). You should call this after
+ * filterWidget->setCurrentItem().
+ * @since 3.2
+ */
+ void updateAutoSelectExtension();
+
+
+protected slots:
+ void urlEntered( const KURL& );
+ void enterURL( const KURL& url );
+ void enterURL( const TQString& url );
+ void locationActivated( const TQString& url );
+
+ /**
+ * @deprecated,
+ */
+ // ### remove in KDE4
+ void toolbarCallback(int);
+ /**
+ * @deprecated
+ */
+ // ### remove in KDE4
+ void pathComboChanged( const TQString& );
+ /**
+ * @deprecated
+ */
+ // ### remove in KDE4
+ void dirCompletion( const TQString& );
+
+ void slotFilterChanged();
+ void fileHighlighted(const KFileItem *i);
+ void fileSelected(const KFileItem *i);
+ void slotStatResult(TDEIO::Job* job);
+ void slotLoadingFinished();
+
+ void fileCompletion( const TQString& );
+ /**
+ * @since 3.1
+ */
+ void toggleSpeedbar( bool );
+
+ /**
+ * @since 3.4
+ */
+ void toggleBookmarks(bool show);
+
+ /**
+ * @deprecated
+ */
+ virtual void updateStatusLine(int dirs, int files);
+
+ virtual void slotOk();
+ virtual void accept();
+ virtual void slotCancel();
+
+ void slotAutoSelectExtClicked();
+ void addToRecentDocuments();
+ void initSpeedbar();
+
+private slots:
+ void slotLocationChanged( const TQString& text );
+
+private:
+ KFileDialog(const KFileDialog&);
+ KFileDialog operator=(const KFileDialog&);
+
+ void setLocationText( const TQString& text );
+ void updateLocationWhatsThis();
+
+ void appendExtension(KURL &url);
+ void updateLocationEditExtension(const TQString &);
+ void updateFilter();
+
+ static void initStatic();
+
+ void setNonExtSelection();
+
+protected:
+ KDirOperator *ops;
+ bool autoDirectoryFollowing;
+
+ KURL::List& parseSelectedURLs() const;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ KFileDialogPrivate *d;
+};
+
+#endif
diff --git a/tdeio/tdefile/tdefilefiltercombo.cpp b/tdeio/tdefile/tdefilefiltercombo.cpp
new file mode 100644
index 000000000..cd7bd54d3
--- /dev/null
+++ b/tdeio/tdefile/tdefilefiltercombo.cpp
@@ -0,0 +1,203 @@
+/* This file is part of the KDE libraries
+ Copyright (C) Stephan Kulow <coolo@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <klocale.h>
+#include <kdebug.h>
+#include <kstaticdeleter.h>
+#include <config-tdefile.h>
+
+#include "tdefilefiltercombo.h"
+
+class KFileFilterCombo::KFileFilterComboPrivate
+{
+public:
+ KFileFilterComboPrivate() {
+ hasAllSupportedFiles = false;
+ defaultFilter = i18n("*|All Files");
+ isMimeFilter = false;
+ }
+
+ // when we have more than 3 mimefilters and no default-filter,
+ // we don't show the comments of all mimefilters in one line,
+ // instead we show "All supported files". We have to translate
+ // that back to the list of mimefilters in currentFilter() tho.
+ bool hasAllSupportedFiles;
+ // true when setMimeFilter was called
+ bool isMimeFilter;
+ TQString lastFilter;
+ TQString defaultFilter;
+};
+
+KFileFilterCombo::KFileFilterCombo( TQWidget *parent, const char *name)
+ : KComboBox(true, parent, name), d( new KFileFilterComboPrivate )
+{
+ setTrapReturnKey( true );
+ setInsertionPolicy(NoInsertion);
+ connect( this, TQT_SIGNAL( activated( int )), this, TQT_SIGNAL( filterChanged() ));
+ connect( this, TQT_SIGNAL( returnPressed() ), this, TQT_SIGNAL( filterChanged() ));
+ connect( this, TQT_SIGNAL( filterChanged() ), TQT_SLOT( slotFilterChanged() ));
+ m_allTypes = false;
+}
+
+KFileFilterCombo::~KFileFilterCombo()
+{
+ delete d;
+}
+
+void KFileFilterCombo::setFilter(const TQString& filter)
+{
+ clear();
+ filters.clear();
+ d->hasAllSupportedFiles = false;
+
+ if (!filter.isEmpty()) {
+ TQString tmp = filter;
+ int index = tmp.find('\n');
+ while (index > 0) {
+ filters.append(tmp.left(index));
+ tmp = tmp.mid(index + 1);
+ index = tmp.find('\n');
+ }
+ filters.append(tmp);
+ }
+ else
+ filters.append( d->defaultFilter );
+
+ TQStringList::ConstIterator it;
+ TQStringList::ConstIterator end(filters.end());
+ for (it = filters.begin(); it != end; ++it) {
+ int tab = (*it).find('|');
+ insertItem((tab < 0) ? *it :
+ (*it).mid(tab + 1));
+ }
+
+ d->lastFilter = currentText();
+ d->isMimeFilter = false;
+}
+
+TQString KFileFilterCombo::currentFilter() const
+{
+ TQString f = currentText();
+ if (f == text(currentItem())) { // user didn't edit the text
+ f = *filters.at(currentItem());
+ if ( d->isMimeFilter || (currentItem() == 0 && d->hasAllSupportedFiles) ) {
+ return f; // we have a mimetype as filter
+ }
+ }
+
+ int tab = f.find('|');
+ if (tab < 0)
+ return f;
+ else
+ return f.left(tab);
+}
+
+void KFileFilterCombo::setCurrentFilter( const TQString& filter )
+{
+ int pos = 0;
+ for( TQStringList::ConstIterator it = filters.begin();
+ it != filters.end();
+ ++it, ++pos ) {
+ if( *it == filter ) {
+ setCurrentItem( pos );
+ filterChanged();
+ return;
+ }
+ }
+ setCurrentText( filter );
+ filterChanged();
+}
+
+void KFileFilterCombo::setMimeFilter( const TQStringList& types,
+ const TQString& defaultType )
+{
+ clear();
+ filters.clear();
+ TQString delim = TQString::fromLatin1(", ");
+ d->hasAllSupportedFiles = false;
+
+ m_allTypes = defaultType.isEmpty() && (types.count() > 1);
+
+ TQString allComments, allTypes;
+ int i = 0;
+ for(TQStringList::ConstIterator it = types.begin(); it != types.end(); ++it, ++i)
+ {
+ if ( m_allTypes && it != types.begin() ) {
+ allComments += delim;
+ allTypes += ' ';
+ }
+
+ kdDebug(tdefile_area) << *it << endl;
+ KMimeType::Ptr type = KMimeType::mimeType( *it );
+ filters.append( type->name() );
+ if ( m_allTypes )
+ {
+ allTypes += type->name();
+ allComments += type->comment();
+ }
+ insertItem( type->comment() );
+ if ( type->name() == defaultType )
+ setCurrentItem( i );
+ }
+
+ if ( m_allTypes )
+ {
+ if ( i < 3 ) // show the mime-comments of at max 3 types
+ insertItem( allComments, 0 );
+ else {
+ insertItem( i18n("All Supported Files"), 0 );
+ d->hasAllSupportedFiles = true;
+ }
+
+ filters.prepend( allTypes );
+ }
+
+ d->lastFilter = currentText();
+ d->isMimeFilter = true;
+}
+
+void KFileFilterCombo::slotFilterChanged()
+{
+ d->lastFilter = currentText();
+}
+
+bool KFileFilterCombo::eventFilter( TQObject *o, TQEvent *e )
+{
+ if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(lineEdit()) && e->type() == TQEvent::FocusOut ) {
+ if ( currentText() != d->lastFilter )
+ emit filterChanged();
+ }
+
+ return KComboBox::eventFilter( o, e );
+}
+
+void KFileFilterCombo::setDefaultFilter( const TQString& filter )
+{
+ d->defaultFilter = filter;
+}
+
+TQString KFileFilterCombo::defaultFilter() const
+{
+ return d->defaultFilter;
+}
+
+void KFileFilterCombo::virtual_hook( int id, void* data )
+{ KComboBox::virtual_hook( id, data ); }
+
+#include "tdefilefiltercombo.moc"
diff --git a/kio/kfile/kfilefiltercombo.h b/tdeio/tdefile/tdefilefiltercombo.h
index 589376d0c..589376d0c 100644
--- a/kio/kfile/kfilefiltercombo.h
+++ b/tdeio/tdefile/tdefilefiltercombo.h
diff --git a/tdeio/tdefile/tdefileiconview.cpp b/tdeio/tdefile/tdefileiconview.cpp
new file mode 100644
index 000000000..474364042
--- /dev/null
+++ b/tdeio/tdefile/tdefileiconview.cpp
@@ -0,0 +1,943 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
+ 2000,2001,2002 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#include <tqt.h>
+
+#include <tqfontmetrics.h>
+#include <tqkeycode.h>
+#include <tqlabel.h>
+#include <tqpainter.h>
+#include <tqpixmap.h>
+#include <tqregexp.h>
+#include <tqtimer.h>
+#include <tqtooltip.h>
+
+#include <kaction.h>
+#include <kapplication.h>
+#include <klocale.h>
+#include <tdefileitem.h>
+#include <kiconeffect.h>
+#include <kglobalsettings.h>
+#include <kurldrag.h>
+#include <tdeio/previewjob.h>
+
+#include "tdefileiconview.h"
+#include "config-tdefile.h"
+
+#define DEFAULT_PREVIEW_SIZE 60
+#define DEFAULT_SHOW_PREVIEWS false
+#define DEFAULT_VIEW_MODE "SmallColumns"
+
+KFileIconViewItem::~KFileIconViewItem()
+{
+ fileInfo()->removeExtraData( iconView() );
+}
+
+class KFileIconView::KFileIconViewPrivate
+{
+public:
+ KFileIconViewPrivate( KFileIconView *parent ) {
+ previewIconSize = 60;
+ job = 0;
+ dropItem = 0;
+
+ noArrangement = false;
+ ignoreMaximumSize = false;
+ smallColumns = new KRadioAction( i18n("Small Icons"), 0, TQT_TQOBJECT(parent),
+ TQT_SLOT( slotSmallColumns() ),
+ parent->actionCollection(),
+ "small columns" );
+
+ largeRows = new KRadioAction( i18n("Large Icons"), 0, TQT_TQOBJECT(parent),
+ TQT_SLOT( slotLargeRows() ),
+ parent->actionCollection(),
+ "large rows" );
+
+ smallColumns->setExclusiveGroup(TQString::fromLatin1("IconView mode"));
+ largeRows->setExclusiveGroup(TQString::fromLatin1("IconView mode"));
+
+ previews = new KToggleAction( i18n("Thumbnail Previews"), 0,
+ parent->actionCollection(),
+ "show previews" );
+ zoomIn = KStdAction::zoomIn( TQT_TQOBJECT(parent), TQT_SLOT( zoomIn() ),
+ parent->actionCollection(), "zoomIn" );
+ zoomOut = KStdAction::zoomOut( TQT_TQOBJECT(parent), TQT_SLOT( zoomOut() ),
+ parent->actionCollection(), "zoomOut" );
+
+ previews->setGroup("previews");
+ zoomIn->setGroup("previews");
+ zoomOut->setGroup("previews");
+
+ connect( previews, TQT_SIGNAL( toggled( bool )),
+ parent, TQT_SLOT( slotPreviewsToggled( bool )));
+
+ connect( &previewTimer, TQT_SIGNAL( timeout() ),
+ parent, TQT_SLOT( showPreviews() ));
+ connect( &autoOpenTimer, TQT_SIGNAL( timeout() ),
+ parent, TQT_SLOT( slotAutoOpen() ));
+ }
+
+ ~KFileIconViewPrivate() {
+ if ( job )
+ job->kill();
+ }
+
+ KRadioAction *smallColumns, *largeRows;
+ KAction *zoomIn, *zoomOut;
+ KToggleAction *previews;
+ TDEIO::PreviewJob *job;
+ KFileIconViewItem *dropItem;
+ TQTimer previewTimer;
+ TQTimer autoOpenTimer;
+ TQStringList previewMimeTypes;
+ int previewIconSize;
+ bool noArrangement :1;
+ bool ignoreMaximumSize :1;
+};
+
+KFileIconView::KFileIconView(TQWidget *parent, const char *name)
+ : KIconView(parent, name), KFileView()
+{
+ d = new KFileIconViewPrivate( this );
+
+ setViewName( i18n("Icon View") );
+
+ toolTip = 0;
+ setResizeMode( Adjust );
+ setMaxItemWidth( 300 );
+ setWordWrapIconText( false );
+ setArrangement( TopToBottom );
+ setAutoArrange( true );
+ setItemsMovable( false );
+ setMode( KIconView::Select );
+ KIconView::setSorting( true );
+ // as long as TQIconView only shows tooltips when the cursor is over the
+ // icon (and not the text), we have to create our own tooltips
+ setShowToolTips( false );
+ slotSmallColumns();
+ d->smallColumns->setChecked( true );
+
+ connect( this, TQT_SIGNAL( returnPressed(TQIconViewItem *) ),
+ TQT_SLOT( slotActivate( TQIconViewItem *) ) );
+
+ // we want single click _and_ double click (as convenience)
+ connect( this, TQT_SIGNAL( clicked(TQIconViewItem *, const TQPoint&) ),
+ TQT_SLOT( selected( TQIconViewItem *) ) );
+ connect( this, TQT_SIGNAL( doubleClicked(TQIconViewItem *, const TQPoint&) ),
+ TQT_SLOT( slotActivate( TQIconViewItem *) ) );
+
+ connect( this, TQT_SIGNAL( onItem( TQIconViewItem * ) ),
+ TQT_SLOT( showToolTip( TQIconViewItem * ) ) );
+ connect( this, TQT_SIGNAL( onViewport() ),
+ TQT_SLOT( removeToolTip() ) );
+ connect( this, TQT_SIGNAL( contextMenuRequested(TQIconViewItem*,const TQPoint&)),
+ TQT_SLOT( slotActivateMenu( TQIconViewItem*, const TQPoint& ) ) );
+
+ KFile::SelectionMode sm = KFileView::selectionMode();
+ switch ( sm ) {
+ case KFile::Multi:
+ TQIconView::setSelectionMode( TQIconView::Multi );
+ break;
+ case KFile::Extended:
+ TQIconView::setSelectionMode( TQIconView::Extended );
+ break;
+ case KFile::NoSelection:
+ TQIconView::setSelectionMode( TQIconView::NoSelection );
+ break;
+ default: // fall through
+ case KFile::Single:
+ TQIconView::setSelectionMode( TQIconView::Single );
+ break;
+ }
+
+ if ( sm == KFile::Multi || sm == KFile::Extended )
+ connect( this, TQT_SIGNAL( selectionChanged() ),
+ TQT_SLOT( slotSelectionChanged() ));
+ else
+ connect( this, TQT_SIGNAL( selectionChanged( TQIconViewItem * )),
+ TQT_SLOT( highlighted( TQIconViewItem * )));
+
+ viewport()->installEventFilter( this );
+
+ // for mimetype resolving
+ m_resolver = new KMimeTypeResolver<KFileIconViewItem,KFileIconView>(this);
+}
+
+KFileIconView::~KFileIconView()
+{
+ delete m_resolver;
+ removeToolTip();
+ delete d;
+}
+
+void KFileIconView::readConfig( TDEConfig *kc, const TQString& group )
+{
+ TQString gr = group.isEmpty() ? TQString("KFileIconView") : group;
+ TDEConfigGroupSaver cs( kc, gr );
+ TQString small = TQString::fromLatin1("SmallColumns");
+ d->previewIconSize = kc->readNumEntry( "Preview Size", DEFAULT_PREVIEW_SIZE );
+ d->previews->setChecked( kc->readBoolEntry( "ShowPreviews", DEFAULT_SHOW_PREVIEWS ) );
+
+ if ( kc->readEntry("ViewMode", DEFAULT_VIEW_MODE ) == small ) {
+ d->smallColumns->setChecked( true );
+ slotSmallColumns();
+ }
+ else {
+ d->largeRows->setChecked( true );
+ slotLargeRows();
+ }
+
+ if ( d->previews->isChecked() )
+ showPreviews();
+}
+
+void KFileIconView::writeConfig( TDEConfig *kc, const TQString& group )
+{
+ TQString gr = group.isEmpty() ? TQString("KFileIconView") : group;
+ TDEConfigGroupSaver cs( kc, gr );
+
+ TQString viewMode = d->smallColumns->isChecked() ?
+ TQString::fromLatin1("SmallColumns") :
+ TQString::fromLatin1("LargeRows");
+ if(!kc->hasDefault( "ViewMode" ) && viewMode == DEFAULT_VIEW_MODE )
+ kc->revertToDefault( "ViewMode" );
+ else
+ kc->writeEntry( "ViewMode", viewMode );
+
+ int previewsIconSize = d->previewIconSize;
+ if(!kc->hasDefault( "Preview Size" ) && previewsIconSize == DEFAULT_PREVIEW_SIZE )
+ kc->revertToDefault( "Preview Size" );
+ else
+ kc->writeEntry( "Preview Size", previewsIconSize );
+
+ bool showPreviews = d->previews->isChecked();
+ if(!kc->hasDefault( "ShowPreviews" ) && showPreviews == DEFAULT_SHOW_PREVIEWS )
+ kc->revertToDefault( "ShowPreviews" );
+ else
+ kc->writeEntry( "ShowPreviews", showPreviews );
+}
+
+void KFileIconView::removeToolTip()
+{
+ delete toolTip;
+ toolTip = 0;
+}
+
+void KFileIconView::showToolTip( TQIconViewItem *item )
+{
+ delete toolTip;
+ toolTip = 0;
+
+ if ( !item )
+ return;
+
+ int w = maxItemWidth() - ( itemTextPos() == TQIconView::Bottom ? 0 :
+ item->pixmapRect().width() ) - 4;
+ if ( fontMetrics().width( item->text() ) >= w ) {
+ toolTip = new TQLabel( TQString::fromLatin1(" %1 ").arg(item->text()), 0,
+ "myToolTip",
+ (WFlags)(WStyle_StaysOnTop | WStyle_Customize | WStyle_NoBorder | WStyle_Tool | WX11BypassWM) );
+ toolTip->setFrameStyle( TQFrame::Plain | TQFrame::Box );
+ toolTip->setLineWidth( 1 );
+ toolTip->setAlignment( AlignLeft | AlignTop );
+ toolTip->move( TQCursor::pos() + TQPoint( 14, 14 ) );
+ toolTip->adjustSize();
+ TQRect screen = TQApplication::desktop()->screenGeometry(
+ TQApplication::desktop()->screenNumber(TQCursor::pos()));
+ if (toolTip->x()+toolTip->width() > screen.right()) {
+ toolTip->move(toolTip->x()+screen.right()-toolTip->x()-toolTip->width(), toolTip->y());
+ }
+ if (toolTip->y()+toolTip->height() > screen.bottom()) {
+ toolTip->move(toolTip->x(), screen.bottom()-toolTip->y()-toolTip->height()+toolTip->y());
+ }
+ toolTip->setFont( TQToolTip::font() );
+ toolTip->setPalette( TQToolTip::palette(), true );
+ toolTip->show();
+ }
+}
+
+void KFileIconView::slotActivateMenu( TQIconViewItem* item, const TQPoint& pos )
+{
+ if ( !item ) {
+ sig->activateMenu( 0, pos );
+ return;
+ }
+ KFileIconViewItem *i = (KFileIconViewItem*) item;
+ sig->activateMenu( i->fileInfo(), pos );
+}
+
+void KFileIconView::hideEvent( TQHideEvent *e )
+{
+ removeToolTip();
+ KIconView::hideEvent( e );
+}
+
+void KFileIconView::keyPressEvent( TQKeyEvent *e )
+{
+ KIconView::keyPressEvent( e );
+
+ // ignore Ctrl-Return so that the dialog can catch it.
+ if ( (e->state() & ControlButton) &&
+ (e->key() == Key_Return || e->key() == Key_Enter) )
+ e->ignore();
+}
+
+void KFileIconView::setSelected( const KFileItem *info, bool enable )
+{
+ KFileIconViewItem *item = viewItem( info );
+ if ( item )
+ KIconView::setSelected( item, enable, true );
+}
+
+void KFileIconView::selectAll()
+{
+ if (KFileView::selectionMode() == KFile::NoSelection ||
+ KFileView::selectionMode() == KFile::Single)
+ return;
+
+ KIconView::selectAll( true );
+}
+
+void KFileIconView::clearSelection()
+{
+ KIconView::clearSelection();
+}
+
+void KFileIconView::invertSelection()
+{
+ KIconView::invertSelection();
+}
+
+void KFileIconView::clearView()
+{
+ m_resolver->m_lstPendingMimeIconItems.clear();
+
+ KIconView::clear();
+ stopPreview();
+}
+
+void KFileIconView::insertItem( KFileItem *i )
+{
+ KFileView::insertItem( i );
+
+ TQIconView* qview = static_cast<TQIconView*>( this );
+ // Since creating and initializing an item leads to a repaint,
+ // we disable updates on the IconView for a while.
+ qview->setUpdatesEnabled( false );
+ KFileIconViewItem *item = new KFileIconViewItem( qview, i );
+ initItem( item, i, true );
+ qview->setUpdatesEnabled( true );
+
+ if ( !i->isMimeTypeKnown() )
+ m_resolver->m_lstPendingMimeIconItems.append( item );
+
+ i->setExtraData( this, item );
+}
+
+void KFileIconView::slotActivate( TQIconViewItem *item )
+{
+ if ( !item )
+ return;
+ const KFileItem *fi = ( (KFileIconViewItem*)item )->fileInfo();
+ if ( fi )
+ sig->activate( fi );
+}
+
+void KFileIconView::selected( TQIconViewItem *item )
+{
+ if ( !item || (TDEApplication::keyboardMouseState() & (ShiftButton | ControlButton)) != 0 )
+ return;
+
+ if ( TDEGlobalSettings::singleClick() ) {
+ const KFileItem *fi = ( (KFileIconViewItem*)item )->fileInfo();
+ if ( fi && (fi->isDir() || !onlyDoubleClickSelectsFiles()) )
+ sig->activate( fi );
+ }
+}
+
+void KFileIconView::setCurrentItem( const KFileItem *item )
+{
+ KFileIconViewItem *it = viewItem( item );
+ if ( it )
+ KIconView::setCurrentItem( it );
+}
+
+KFileItem * KFileIconView::currentFileItem() const
+{
+ KFileIconViewItem *current = static_cast<KFileIconViewItem*>( currentItem() );
+ if ( current )
+ return current->fileInfo();
+
+ return 0L;
+}
+
+void KFileIconView::highlighted( TQIconViewItem *item )
+{
+ if ( !item )
+ return;
+ const KFileItem *fi = ( (KFileIconViewItem*)item )->fileInfo();
+ if ( fi )
+ sig->highlightFile( fi );
+}
+
+void KFileIconView::setSelectionMode( KFile::SelectionMode sm )
+{
+ disconnect( TQT_SIGNAL( selectionChanged() ), this );
+ disconnect( TQT_SIGNAL( selectionChanged( TQIconViewItem * )), this );
+
+ KFileView::setSelectionMode( sm );
+ switch ( KFileView::selectionMode() ) {
+ case KFile::Multi:
+ TQIconView::setSelectionMode( TQIconView::Multi );
+ break;
+ case KFile::Extended:
+ TQIconView::setSelectionMode( TQIconView::Extended );
+ break;
+ case KFile::NoSelection:
+ TQIconView::setSelectionMode( TQIconView::NoSelection );
+ break;
+ default: // fall through
+ case KFile::Single:
+ TQIconView::setSelectionMode( TQIconView::Single );
+ break;
+ }
+
+ if ( sm == KFile::Multi || sm == KFile::Extended )
+ connect( this, TQT_SIGNAL( selectionChanged() ),
+ TQT_SLOT( slotSelectionChanged() ));
+ else
+ connect( this, TQT_SIGNAL( selectionChanged( TQIconViewItem * )),
+ TQT_SLOT( highlighted( TQIconViewItem * )));
+}
+
+bool KFileIconView::isSelected( const KFileItem *i ) const
+{
+ KFileIconViewItem *item = viewItem( i );
+ return (item && item->isSelected());
+}
+
+void KFileIconView::updateView( bool b )
+{
+ if ( !b )
+ return; // eh?
+
+ KFileIconViewItem *item = static_cast<KFileIconViewItem*>(TQIconView::firstItem());
+ if ( item ) {
+ do {
+ if ( d->previews->isChecked() ) {
+ if ( canPreview( item->fileInfo() ) )
+ item->setPixmapSize( TQSize( d->previewIconSize, d->previewIconSize ) );
+ }
+ else {
+ // unset pixmap size (used for previews)
+ if ( !item->pixmapSize().isNull() )
+ item->setPixmapSize( TQSize( 0, 0 ) );
+ }
+ // recalculate item parameters but avoid an in-place repaint
+ item->setPixmap( (item->fileInfo())->pixmap( myIconSize ), true, false );
+ item = static_cast<KFileIconViewItem *>(item->nextItem());
+ } while ( item != 0L );
+ }
+}
+
+void KFileIconView::updateView( const KFileItem *i )
+{
+ KFileIconViewItem *item = viewItem( i );
+ if ( item )
+ initItem( item, i, true );
+}
+
+void KFileIconView::removeItem( const KFileItem *i )
+{
+ if ( !i )
+ return;
+
+ if ( d->job )
+ d->job->removeItem( i );
+
+ KFileIconViewItem *item = viewItem( i );
+ m_resolver->m_lstPendingMimeIconItems.remove( item );
+ delete item;
+
+ KFileView::removeItem( i );
+}
+
+void KFileIconView::setIconSize( int size )
+{
+ myIconSize = size;
+ updateIcons();
+}
+
+void KFileIconView::setPreviewSize( int size )
+{
+ if ( size < 30 )
+ size = 30; // minimum
+
+ d->previewIconSize = size;
+ if ( d->previews->isChecked() )
+ showPreviews();
+}
+
+void KFileIconView::setIgnoreMaximumSize(bool ignoreSize)
+{
+ d->ignoreMaximumSize = ignoreSize;
+}
+
+void KFileIconView::updateIcons()
+{
+ updateView( true );
+ arrangeItemsInGrid();
+}
+
+void KFileIconView::ensureItemVisible( const KFileItem *i )
+{
+ KFileIconViewItem *item = viewItem( i );
+ if ( item )
+ KIconView::ensureItemVisible( item );
+}
+
+void KFileIconView::slotSelectionChanged()
+{
+ sig->highlightFile( 0L );
+}
+
+void KFileIconView::slotSmallColumns()
+{
+ // setItemTextPos(), setArrangement(), setWordWrapIconText() and
+ // setIconSize() all call arrangeItemsInGrid() :( Prevent this.
+ d->noArrangement = true; // stop arrangeItemsInGrid()!
+
+ // Make sure to uncheck previews if selected
+ if ( d->previews->isChecked() )
+ {
+ stopPreview();
+ d->previews->setChecked( false );
+ }
+ setGridX( -1 );
+ setMaxItemWidth( 300 );
+ setItemTextPos( Right );
+ setArrangement( TopToBottom );
+ setWordWrapIconText( false );
+ setSpacing( 0 );
+
+ d->noArrangement = false; // now we can arrange
+ setIconSize( KIcon::SizeSmall );
+}
+
+void KFileIconView::slotLargeRows()
+{
+ // setItemTextPos(), setArrangement(), setWordWrapIconText() and
+ // setIconSize() all call arrangeItemsInGrid() :( Prevent this.
+ d->noArrangement = true; // stop arrangeItemsInGrid()!
+
+ setGridX( TDEGlobal::iconLoader()->currentSize( KIcon::Desktop ) + 50 );
+ setItemTextPos( Bottom );
+ setArrangement( LeftToRight );
+ setWordWrapIconText( true );
+ setSpacing( 5 ); // default in QIconView
+
+ d->noArrangement = false; // now we can arrange
+ setIconSize( KIcon::SizeMedium );
+}
+
+void KFileIconView::stopPreview()
+{
+ if ( d->job ) {
+ d->job->kill();
+ d->job = 0L;
+ }
+}
+
+void KFileIconView::slotPreviewsToggled( bool on )
+{
+ if ( on )
+ showPreviews();
+ else {
+ stopPreview();
+ slotLargeRows();
+ }
+}
+
+void KFileIconView::showPreviews()
+{
+ if ( d->previewMimeTypes.isEmpty() )
+ d->previewMimeTypes = TDEIO::PreviewJob::supportedMimeTypes();
+
+ stopPreview();
+ d->previews->setChecked( true );
+
+ if ( !d->largeRows->isChecked() ) {
+ d->largeRows->setChecked( true );
+ slotLargeRows(); // also sets the icon size and updates the grid
+ }
+ else {
+ updateIcons();
+ }
+
+ d->job = TDEIO::filePreview(*items(), d->previewIconSize,d->previewIconSize);
+ d->job->setIgnoreMaximumSize(d->ignoreMaximumSize);
+
+ connect( d->job, TQT_SIGNAL( result( TDEIO::Job * )),
+ this, TQT_SLOT( slotPreviewResult( TDEIO::Job * )));
+ connect( d->job, TQT_SIGNAL( gotPreview( const KFileItem*, const TQPixmap& )),
+ TQT_SLOT( gotPreview( const KFileItem*, const TQPixmap& ) ));
+// connect( d->job, TQT_SIGNAL( failed( const KFileItem* )),
+// this, TQT_SLOT( slotFailed( const KFileItem* ) ));
+}
+
+void KFileIconView::slotPreviewResult( TDEIO::Job *job )
+{
+ if ( job == d->job )
+ d->job = 0L;
+}
+
+void KFileIconView::gotPreview( const KFileItem *item, const TQPixmap& pix )
+{
+ KFileIconViewItem *it = viewItem( item );
+ if ( it )
+ if( item->overlays() & KIcon::HiddenOverlay )
+ {
+ TQPixmap p( pix );
+
+ KIconEffect::semiTransparent( p );
+ it->setPixmap( p );
+ }
+ else
+ it->setPixmap( pix );
+}
+
+bool KFileIconView::canPreview( const KFileItem *item ) const
+{
+ TQStringList::Iterator it = d->previewMimeTypes.begin();
+ TQRegExp r;
+ r.setWildcard( true );
+
+ for ( ; it != d->previewMimeTypes.end(); ++it ) {
+ TQString type = *it;
+ // the "mimetype" can be "image/*"
+ if ( type.at( type.length() - 1 ) == '*' ) {
+ r.setPattern( type );
+ if ( r.search( item->mimetype() ) != -1 )
+ return true;
+ }
+ else
+ if ( item->mimetype() == type )
+ return true;
+ }
+
+ return false;
+}
+
+KFileItem * KFileIconView::firstFileItem() const
+{
+ KFileIconViewItem *item = static_cast<KFileIconViewItem*>( firstItem() );
+ if ( item )
+ return item->fileInfo();
+ return 0L;
+}
+
+KFileItem * KFileIconView::nextItem( const KFileItem *fileItem ) const
+{
+ if ( fileItem ) {
+ KFileIconViewItem *item = viewItem( fileItem );
+ if ( item && item->nextItem() )
+ return ((KFileIconViewItem*) item->nextItem())->fileInfo();
+ }
+ return 0L;
+}
+
+KFileItem * KFileIconView::prevItem( const KFileItem *fileItem ) const
+{
+ if ( fileItem ) {
+ KFileIconViewItem *item = viewItem( fileItem );
+ if ( item && item->prevItem() )
+ return ((KFileIconViewItem*) item->prevItem())->fileInfo();
+ }
+ return 0L;
+}
+
+void KFileIconView::setSorting( TQDir::SortSpec spec )
+{
+ KFileView::setSorting( spec );
+ KFileItemListIterator it( *items() );
+
+ KFileItem *item;
+
+ if ( spec & TQDir::Time ) {
+ for ( ; (item = it.current()); ++it )
+ // warning, time_t is often signed -> cast it
+ viewItem(item)->setKey( sortingKey( (unsigned long)item->time( TDEIO::UDS_MODIFICATION_TIME ), item->isDir(), spec ));
+ }
+
+ else if ( spec & TQDir::Size ) {
+ for ( ; (item = it.current()); ++it )
+ viewItem(item)->setKey( sortingKey( item->size(), item->isDir(),
+ spec ));
+ }
+ else { // Name or Unsorted
+ for ( ; (item = it.current()); ++it )
+ viewItem(item)->setKey( sortingKey( item->text(), item->isDir(),
+ spec ));
+ }
+
+ KIconView::setSorting( true, !isReversed() );
+ sort( !isReversed() );
+}
+
+//
+// mimetype determination on demand
+//
+void KFileIconView::mimeTypeDeterminationFinished()
+{
+ // anything to do?
+}
+
+void KFileIconView::determineIcon( KFileIconViewItem *item )
+{
+ (void) item->fileInfo()->determineMimeType();
+ updateView( item->fileInfo() );
+}
+
+void KFileIconView::listingCompleted()
+{
+ arrangeItemsInGrid();
+
+ // TQIconView doesn't set the current item automatically, so we have to do
+ // that. We don't want to emit selectionChanged() tho.
+ if ( !currentItem() ) {
+ bool block = signalsBlocked();
+ blockSignals( true );
+ TQIconViewItem *item = viewItem( firstFileItem() );
+ KIconView::setCurrentItem( item );
+ KIconView::setSelected( item, false );
+ blockSignals( block );
+ }
+
+ m_resolver->start( d->previews->isChecked() ? 0 : 10 );
+}
+
+// need to remove our tooltip, eventually
+bool KFileIconView::eventFilter( TQObject *o, TQEvent *e )
+{
+ if ( TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(viewport()) || TQT_BASE_OBJECT(o) == TQT_BASE_OBJECT(this) ) {
+ int type = e->type();
+ if ( type == TQEvent::Leave ||
+ type == TQEvent::FocusOut )
+ removeToolTip();
+ }
+
+ return KIconView::eventFilter( o, e );
+}
+
+/////////////////////////////////////////////////////////////////
+
+// ### workaround for Qt3 Bug
+void KFileIconView::showEvent( TQShowEvent *e )
+{
+ KIconView::showEvent( e );
+}
+
+
+void KFileIconView::initItem( KFileIconViewItem *item, const KFileItem *i,
+ bool updateTextAndPixmap )
+{
+ if ( d->previews->isChecked() && canPreview( i ) )
+ item->setPixmapSize( TQSize( d->previewIconSize, d->previewIconSize ) );
+
+ if ( updateTextAndPixmap )
+ {
+ // this causes a repaint of the item, which we want to avoid during
+ // directory listing, when all items are created. We want to paint all
+ // items at once, not every single item in that case.
+ item->setText( i->text() , false, false );
+ item->setPixmap( i->pixmap( myIconSize ) );
+ }
+
+ // see also setSorting()
+ TQDir::SortSpec spec = KFileView::sorting();
+
+ if ( spec & TQDir::Time )
+ // warning, time_t is often signed -> cast it
+ item->setKey( sortingKey( (unsigned long) i->time( TDEIO::UDS_MODIFICATION_TIME ),
+ i->isDir(), spec ));
+ else if ( spec & TQDir::Size )
+ item->setKey( sortingKey( i->size(), i->isDir(), spec ));
+
+ else // Name or Unsorted
+ item->setKey( sortingKey( i->text(), i->isDir(), spec ));
+
+ //tqDebug("** key for: %s: %s", i->text().latin1(), item->key().latin1());
+
+ if ( d->previews->isChecked() )
+ d->previewTimer.start( 10, true );
+}
+
+void KFileIconView::arrangeItemsInGrid( bool update )
+{
+ if ( d->noArrangement )
+ return;
+
+ KIconView::arrangeItemsInGrid( update );
+}
+
+void KFileIconView::zoomIn()
+{
+ setPreviewSize( d->previewIconSize + 30 );
+}
+
+void KFileIconView::zoomOut()
+{
+ setPreviewSize( d->previewIconSize - 30 );
+}
+
+TQDragObject *KFileIconView::dragObject()
+{
+ // create a list of the URL:s that we want to drag
+ KURL::List urls;
+ KFileItemListIterator it( * KFileView::selectedItems() );
+ for ( ; it.current(); ++it ){
+ urls.append( (*it)->url() );
+ }
+ TQPixmap pixmap;
+ if( urls.count() > 1 )
+ pixmap = DesktopIcon( "tdemultiple", iconSize() );
+ if( pixmap.isNull() )
+ pixmap = currentFileItem()->pixmap( iconSize() );
+
+ TQPoint hotspot;
+ hotspot.setX( pixmap.width() / 2 );
+ hotspot.setY( pixmap.height() / 2 );
+ TQDragObject* myDragObject = new KURLDrag( urls, widget() );
+ myDragObject->setPixmap( pixmap, hotspot );
+ return myDragObject;
+}
+
+void KFileIconView::slotAutoOpen()
+{
+ d->autoOpenTimer.stop();
+ if( !d->dropItem )
+ return;
+
+ KFileItem *fileItem = d->dropItem->fileInfo();
+ if (!fileItem)
+ return;
+
+ if( fileItem->isFile() )
+ return;
+
+ if ( fileItem->isDir() || fileItem->isLink())
+ sig->activate( fileItem );
+}
+
+bool KFileIconView::acceptDrag(TQDropEvent* e) const
+{
+ return KURLDrag::canDecode( e ) &&
+ (e->source()!=const_cast<KFileIconView*>(this)) &&
+ ( e->action() == TQDropEvent::Copy
+ || e->action() == TQDropEvent::Move
+ || e->action() == TQDropEvent::Link );
+}
+
+void KFileIconView::contentsDragEnterEvent( TQDragEnterEvent *e )
+{
+ if ( ! acceptDrag( e ) ) { // can we decode this ?
+ e->ignore(); // No
+ return;
+ }
+ e->acceptAction(); // Yes
+
+ if ((dropOptions() & AutoOpenDirs) == 0)
+ return;
+
+ KFileIconViewItem *item = dynamic_cast<KFileIconViewItem*>(findItem( contentsToViewport( e->pos() ) ));
+ if ( item ) { // are we over an item ?
+ d->dropItem = item;
+ d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
+ }
+ else
+ {
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+ }
+}
+
+void KFileIconView::contentsDragMoveEvent( TQDragMoveEvent *e )
+{
+ if ( ! acceptDrag( e ) ) { // can we decode this ?
+ e->ignore(); // No
+ return;
+ }
+ e->acceptAction(); // Yes
+
+ if ((dropOptions() & AutoOpenDirs) == 0)
+ return;
+
+ KFileIconViewItem *item = dynamic_cast<KFileIconViewItem*>(findItem( contentsToViewport( e->pos() ) ));
+ if ( item ) { // are we over an item ?
+ if (d->dropItem != item)
+ {
+ d->dropItem = item;
+ d->autoOpenTimer.start( autoOpenDelay() ); // restart timer
+ }
+ }
+ else
+ {
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+ }
+}
+
+void KFileIconView::contentsDragLeaveEvent( TQDragLeaveEvent * )
+{
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+}
+
+void KFileIconView::contentsDropEvent( TQDropEvent *e )
+{
+ d->dropItem = 0;
+ d->autoOpenTimer.stop();
+
+ if ( ! acceptDrag( e ) ) { // can we decode this ?
+ e->ignore(); // No
+ return;
+ }
+ e->acceptAction(); // Yes
+
+ KFileIconViewItem *item = dynamic_cast<KFileIconViewItem*>(findItem( contentsToViewport( e->pos() ) ));
+ KFileItem * fileItem = 0;
+ if (item)
+ fileItem = item->fileInfo();
+
+ emit dropped(e, fileItem);
+
+ KURL::List urls;
+ if (KURLDrag::decode( e, urls ) && !urls.isEmpty())
+ {
+ emit dropped(e, urls, fileItem ? fileItem->url() : KURL());
+ sig->dropURLs(fileItem, e, urls);
+ }
+}
+
+void KFileIconView::virtual_hook( int id, void* data )
+{ KIconView::virtual_hook( id, data );
+ KFileView::virtual_hook( id, data ); }
+
+#include "tdefileiconview.moc"
diff --git a/tdeio/tdefile/tdefileiconview.h b/tdeio/tdefile/tdefileiconview.h
new file mode 100644
index 000000000..0b7c7877e
--- /dev/null
+++ b/tdeio/tdefile/tdefileiconview.h
@@ -0,0 +1,267 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef KFILEICONVIEW_H
+#define KFILEICONVIEW_H
+
+#include <tqt.h>
+
+#include <kiconview.h>
+#include <kiconloader.h>
+#include <tdefileview.h>
+#include <kmimetyperesolver.h>
+#include <tdefile.h>
+
+class KFileItem;
+class TQWidget;
+class TQLabel;
+
+/**
+ * An item for the iconview, that has a reference to its corresponding
+ * KFileItem.
+ */
+class TDEIO_EXPORT KFileIconViewItem : public KIconViewItem
+{
+public:
+ KFileIconViewItem( TQIconView *parent, const TQString &text,
+ const TQPixmap &pixmap,
+ KFileItem *fi )
+ : KIconViewItem( parent, text, pixmap ), inf( fi ) {}
+ /**
+ * @since 3.1
+ */
+ KFileIconViewItem( TQIconView *parent, KFileItem *fi )
+ : KIconViewItem( parent ), inf( fi ) {}
+
+ virtual ~KFileIconViewItem();
+
+ /**
+ * @returns the corresponding KFileItem
+ */
+ KFileItem *fileInfo() const {
+ return inf;
+ }
+
+private:
+ KFileItem *inf;
+
+private:
+ class KFileIconViewItemPrivate;
+ KFileIconViewItemPrivate *d;
+
+};
+
+namespace TDEIO {
+ class Job;
+}
+
+/**
+ * An icon-view capable of showing KFileItem's. Used in the filedialog
+ * for example. Most of the documentation is in KFileView class.
+ *
+ * @see KDirOperator
+ * @see KCombiView
+ * @see KFileDetailView
+ */
+class TDEIO_EXPORT KFileIconView : public KIconView, public KFileView
+{
+ Q_OBJECT
+
+public:
+ KFileIconView(TQWidget *parent, const char *name);
+ virtual ~KFileIconView();
+
+ virtual TQWidget *widget() { return this; }
+ virtual void clearView();
+ virtual void setAutoUpdate( bool ) {} // ### unused. remove in KDE4
+
+ virtual void updateView( bool );
+ virtual void updateView(const KFileItem*);
+ virtual void removeItem(const KFileItem*);
+
+ virtual void listingCompleted();
+
+ virtual void insertItem( KFileItem *i );
+ virtual void setSelectionMode( KFile::SelectionMode sm );
+
+ virtual void setSelected(const KFileItem *, bool);
+ virtual bool isSelected(const KFileItem *i) const;
+ virtual void clearSelection();
+ virtual void selectAll();
+ virtual void invertSelection();
+
+ virtual void setCurrentItem( const KFileItem * );
+ virtual KFileItem * currentFileItem() const;
+ virtual KFileItem * firstFileItem() const;
+ virtual KFileItem * nextItem( const KFileItem * ) const;
+ virtual KFileItem * prevItem( const KFileItem * ) const;
+
+ /**
+ * Sets the size of the icons to show. Defaults to KIcon::SizeSmall.
+ */
+ void setIconSize( int size );
+
+ /**
+ * Sets the size of the previews. Defaults to KIcon::SizeLarge.
+ */
+ void setPreviewSize( int size );
+
+ /**
+ * Disables the "Maximum file size" configuration option for previews
+ *
+ * Set this before calling showPreviews()
+ *
+ * @since 3.4
+ **/
+ void setIgnoreMaximumSize(bool ignoreSize=true);
+
+ /**
+ * @returns the current size used for icons.
+ */
+ int iconSize() const { return myIconSize; }
+
+ void ensureItemVisible( const KFileItem * );
+
+ virtual void setSorting(TQDir::SortSpec sort);
+
+ virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
+ virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
+
+ // for KMimeTypeResolver
+ void mimeTypeDeterminationFinished();
+ void determineIcon( KFileIconViewItem *item );
+ TQScrollView *scrollWidget() const { return (TQScrollView*) this; }
+ void setAcceptDrops(bool b)
+ {
+ KIconView::setAcceptDrops(b);
+ viewport()->setAcceptDrops(b);
+ }
+
+public slots:
+ /**
+ * Starts loading previews for all files shown and shows them. Switches
+ * into 'large rows' mode, if that isn't the current mode yet.
+ *
+ * @sa setIgnoreMaximumSize
+ */
+ void showPreviews();
+
+ void zoomIn();
+
+ void zoomOut();
+
+ /**
+ * Reimplemented for performance reasons.
+ * @since 3.1
+ */
+ virtual void arrangeItemsInGrid( bool updated = true );
+
+protected:
+ /**
+ * Reimplemented to not let TQIconView eat return-key events
+ */
+ virtual void keyPressEvent( TQKeyEvent * );
+
+ /**
+ * Reimplemented to remove an eventual tooltip
+ */
+ virtual void hideEvent( TQHideEvent * );
+
+ // ### workaround for Qt3 bug (see #35080)
+ virtual void showEvent( TQShowEvent * );
+
+ virtual bool eventFilter( TQObject *o, TQEvent *e );
+
+ // DND support
+ virtual TQDragObject *dragObject();
+ virtual void contentsDragEnterEvent( TQDragEnterEvent *e );
+ virtual void contentsDragMoveEvent( TQDragMoveEvent *e );
+ virtual void contentsDragLeaveEvent( TQDragLeaveEvent *e );
+ virtual void contentsDropEvent( TQDropEvent *ev );
+
+ // KDE4: Make virtual
+ bool acceptDrag(TQDropEvent* e ) const;
+
+private slots:
+ void selected( TQIconViewItem *item );
+ void slotActivate( TQIconViewItem * );
+ void highlighted( TQIconViewItem *item );
+ void showToolTip( TQIconViewItem *item );
+ void removeToolTip();
+ void slotActivateMenu( TQIconViewItem *, const TQPoint& );
+ void slotSelectionChanged();
+
+ void slotSmallColumns();
+ void slotLargeRows();
+ void slotPreviewsToggled( bool );
+
+ void slotPreviewResult( TDEIO::Job * );
+ void gotPreview( const KFileItem *item, const TQPixmap& pix );
+ void slotAutoOpen();
+
+signals:
+ /**
+ * The user dropped something.
+ * @p fileItem points to the item dropped on or can be 0 if the
+ * user dropped on empty space.
+ * @since 3.2
+ */
+ void dropped(TQDropEvent *event, KFileItem *fileItem);
+ /**
+ * The user dropped the URLs @p urls.
+ * @p url points to the item dropped on or can be empty if the
+ * user dropped on empty space.
+ * @since 3.2
+ */
+ void dropped(TQDropEvent *event, const KURL::List &urls, const KURL &url);
+
+private:
+ KMimeTypeResolver<KFileIconViewItem,KFileIconView> *m_resolver;
+
+ TQLabel *toolTip;
+ int th;
+ int myIconSize;
+
+ virtual void insertItem(TQIconViewItem *a, TQIconViewItem *b) { KIconView::insertItem(a, b); }
+ virtual void setSelectionMode(TQIconView::SelectionMode m) { KIconView::setSelectionMode(m); }
+ virtual void setSelected(TQIconViewItem *i, bool a, bool b) { KIconView::setSelected(i, a, b); }
+
+ bool canPreview( const KFileItem * ) const;
+ void stopPreview();
+
+ void updateIcons();
+
+ inline KFileIconViewItem * viewItem( const KFileItem *item ) const {
+ if ( item )
+ return (KFileIconViewItem *) item->extraData( this );
+ return 0L;
+ }
+
+ void initItem(KFileIconViewItem *item, const KFileItem *i,
+ bool updateTextAndPixmap );
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KFileIconViewPrivate;
+ KFileIconViewPrivate *d;
+};
+
+#endif // KFILESIMPLEVIEW_H
diff --git a/tdeio/tdefile/tdefilemetainfowidget.cpp b/tdeio/tdefile/tdefilemetainfowidget.cpp
new file mode 100644
index 000000000..dea9ea353
--- /dev/null
+++ b/tdeio/tdefile/tdefilemetainfowidget.cpp
@@ -0,0 +1,375 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001,2002 Rolf Magnus <ramagnus@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+ $Id$
+ */
+
+#include "tdefilemetainfowidget.h"
+
+#include <keditcl.h>
+#include <klocale.h>
+#include <knuminput.h>
+#include <kcombobox.h>
+#include <klineedit.h>
+#include <kstringvalidator.h>
+#include <kdebug.h>
+
+#include <tqlabel.h>
+#include <tqcheckbox.h>
+#include <tqspinbox.h>
+#include <tqdatetimeedit.h>
+#include <tqpixmap.h>
+#include <tqimage.h>
+#include <tqlayout.h>
+#include <tqvalidator.h>
+
+/*
+ Widgets used for different types:
+
+ bool : QCheckBox
+ int : QSpinBox
+ TQString : KComboBox if the validator is a KStringListValidator, else lineedit
+ TQDateTime : QDateTimeEdit
+
+*/
+
+KFileMetaInfoWidget::KFileMetaInfoWidget(KFileMetaInfoItem item,
+ TQValidator* val,
+ TQWidget* parent, const char* name)
+ : TQWidget(parent, name),
+ m_value(item.value()),
+ m_item(item),
+ m_validator(val)
+{
+ init(item, ReadWrite);
+}
+
+KFileMetaInfoWidget::KFileMetaInfoWidget(KFileMetaInfoItem item,
+ Mode mode,
+ TQValidator* val,
+ TQWidget* parent, const char* name)
+ : TQWidget(parent, name),
+ m_value(item.value()),
+ m_item(item),
+ m_validator(val)
+{
+ init(item, mode);
+}
+
+void KFileMetaInfoWidget::init(KFileMetaInfoItem item, Mode mode)
+{
+ kdDebug(7033) << "*** item " << m_item.key()
+ << " is a " << value().typeName() << endl;
+
+ if (m_item.isEditable() && !(mode & ReadOnly))
+ m_widget = makeWidget();
+ else
+ switch (m_value.type())
+ {
+ case TQVariant::Image :
+ m_widget = new TQLabel(this, "info image");
+ static_cast<TQLabel*>(m_widget)->setPixmap(TQPixmap(m_value.toImage()));
+ break;
+ case TQVariant::Pixmap :
+ m_widget = new TQLabel(this, "info pixmap");
+ static_cast<TQLabel*>(m_widget)->setPixmap(m_value.toPixmap());
+ break;
+ default:
+ m_widget = new TQLabel(item.string(true), this, "info label");
+ }
+
+ (new TQHBoxLayout(this))->addWidget(m_widget);
+}
+
+KFileMetaInfoWidget::~KFileMetaInfoWidget()
+{
+}
+
+TQWidget* KFileMetaInfoWidget::makeWidget()
+{
+ TQString valClass;
+ TQWidget* w;
+
+ switch (m_value.type())
+ {
+ case TQVariant::Invalid: // no type
+ // just make a label
+ w = new TQLabel(i18n("<Error>"), this, "label");
+ break;
+
+ case TQVariant::Int: // an int
+ case TQVariant::UInt: // an unsigned int
+ w = makeIntWidget();
+ break;
+
+ case TQVariant::Bool: // a bool
+ w = makeBoolWidget();
+ break;
+
+ case TQVariant::Double: // a double
+ w = makeDoubleWidget();
+ break;
+
+
+ case TQVariant::Date: // a QDate
+ w = makeDateWidget();
+ break;
+
+ case TQVariant::Time: // a QTime
+ w = makeTimeWidget();
+ break;
+
+ case TQVariant::DateTime: // a QDateTime
+ w = makeDateTimeWidget();
+ break;
+
+#if 0
+ case TQVariant::Size: // a QSize
+ case TQVariant::String: // a QString
+ case TQVariant::List: // a QValueList
+ case TQVariant::Map: // a QMap
+ case TQVariant::StringList: // a QStringList
+ case TQVariant::Font: // a QFont
+ case TQVariant::Pixmap: // a QPixmap
+ case TQVariant::Brush: // a QBrush
+ case TQVariant::Rect: // a QRect
+ case TQVariant::Color: // a QColor
+ case TQVariant::Palette: // a QPalette
+ case TQVariant::ColorGroup: // a QColorGroup
+ case TQVariant::IconSet: // a QIconSet
+ case TQVariant::Point: // a QPoint
+ case TQVariant::Image: // a QImage
+ case TQVariant::CString: // a QCString
+ case TQVariant::PointArray: // a QPointArray
+ case TQVariant::Region: // a QRegion
+ case TQVariant::Bitmap: // a QBitmap
+ case TQVariant::Cursor: // a QCursor
+ case TQVariant::ByteArray: // a QByteArray
+ case TQVariant::BitArray: // a QBitArray
+ case TQVariant::SizePolicy: // a QSizePolicy
+ case TQVariant::KeySequence: // a QKeySequence
+#endif
+ default:
+ w = makeStringWidget();
+ }
+
+ kdDebug(7033) << "*** item " << m_item.key()
+ << "is a " << m_item.value().typeName() << endl;
+ if (m_validator)
+ kdDebug(7033) << " and validator is a " << m_validator->className() << endl;
+
+ kdDebug(7033) << "*** created a " << w->className() << " for it\n";
+
+ return w;
+}
+
+// ****************************************************************
+// now the different methods to make the widgets for specific types
+// ****************************************************************
+
+TQWidget* KFileMetaInfoWidget::makeBoolWidget()
+{
+ TQCheckBox* cb = new TQCheckBox(this, "metainfo bool widget");
+ cb->setChecked(m_item.value().toBool());
+ connect(cb, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(slotChanged(bool)));
+ return cb;
+}
+
+TQWidget* KFileMetaInfoWidget::makeIntWidget()
+{
+ TQSpinBox* sb = new TQSpinBox(this, "metainfo integer widget");
+ sb->setValue(m_item.value().toInt());
+
+ if (m_validator)
+ {
+ if (m_validator->inherits(TQINTVALIDATOR_OBJECT_NAME_STRING))
+ {
+ sb->setMinValue(static_cast<TQIntValidator*>(m_validator)->bottom());
+ sb->setMaxValue(static_cast<TQIntValidator*>(m_validator)->top());
+ }
+ reparentValidator(sb, m_validator);
+ sb->setValidator(m_validator);
+ }
+
+ // make sure that an uint cannot be set to a value < 0
+ if (m_item.type() == TQVariant::UInt)
+ sb->setMinValue(QMAX(sb->minValue(), 0));
+
+ connect(sb, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(slotChanged(int)));
+ return sb;
+}
+
+TQWidget* KFileMetaInfoWidget::makeDoubleWidget()
+{
+ KDoubleNumInput* dni = new KDoubleNumInput(m_item.value().toDouble(),
+ this, "metainfo double widget");
+
+
+ if (m_validator)
+ {
+ if (m_validator->inherits("QDoubleValidator"))
+ {
+ dni->setMinValue(static_cast<TQDoubleValidator*>(m_validator)->bottom());
+ dni->setMaxValue(static_cast<TQDoubleValidator*>(m_validator)->top());
+ }
+ reparentValidator(dni, m_validator);
+ }
+
+ connect(dni, TQT_SIGNAL(valueChanged(double)), this, TQT_SLOT(slotChanged(double)));
+ return dni;
+}
+
+TQWidget* KFileMetaInfoWidget::makeStringWidget()
+{
+ if (m_validator && m_validator->inherits("KStringListValidator"))
+ {
+ KComboBox* b = new KComboBox(true, this, "metainfo combobox");
+ KStringListValidator* val = static_cast<KStringListValidator*>
+ (m_validator);
+ b->insertStringList(val->stringList());
+ b->setCurrentText(m_item.value().toString());
+ connect(b, TQT_SIGNAL(activated(const TQString &)), this, TQT_SLOT(slotComboChanged(const TQString &)));
+ b->setValidator(val);
+ reparentValidator(b, val);
+ return b;
+ }
+
+ if ( m_item.attributes() & KFileMimeTypeInfo::MultiLine ) {
+ KEdit *edit = new KEdit( this );
+ edit->setText( m_item.value().toString() );
+ connect( edit, TQT_SIGNAL( textChanged() ),
+ this, TQT_SLOT( slotMultiLineEditChanged() ));
+ // can't use a validator with a TQTextEdit, but we may need to delete it
+ if ( m_validator )
+ reparentValidator( edit, m_validator );
+ return edit;
+ }
+
+ KLineEdit* e = new KLineEdit(m_item.value().toString(), this);
+ if (m_validator)
+ {
+ e->setValidator(m_validator);
+ reparentValidator(e, m_validator);
+ }
+ connect(e, TQT_SIGNAL(textChanged(const TQString&)),
+ this, TQT_SLOT(slotLineEditChanged(const TQString&)));
+ return e;
+}
+
+TQWidget* KFileMetaInfoWidget::makeDateWidget()
+{
+ TQWidget *e = new TQDateEdit(m_item.value().toDate(), this);
+ connect(e, TQT_SIGNAL(valueChanged(const TQDate&)),
+ this, TQT_SLOT(slotDateChanged(const TQDate&)));
+ return e;
+}
+
+TQWidget* KFileMetaInfoWidget::makeTimeWidget()
+{
+ return new TQTimeEdit(m_item.value().toTime(), this);
+}
+
+TQWidget* KFileMetaInfoWidget::makeDateTimeWidget()
+{
+ return new TQDateTimeEdit(m_item.value().toDateTime(), this);
+}
+
+void KFileMetaInfoWidget::reparentValidator( TQWidget *widget,
+ TQValidator *validator )
+{
+ if ( !validator->parent() )
+ widget->insertChild( validator );
+}
+
+// ****************************************************************
+// now the slots that let us get notified if the value changed in the child
+// ****************************************************************
+
+void KFileMetaInfoWidget::slotChanged(bool value)
+{
+ Q_ASSERT(m_widget->inherits(TQCOMBOBOX_OBJECT_NAME_STRING));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+void KFileMetaInfoWidget::slotChanged(int value)
+{
+ Q_ASSERT(m_widget->inherits(TQSPINBOX_OBJECT_NAME_STRING));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+void KFileMetaInfoWidget::slotChanged(double value)
+{
+ Q_ASSERT(m_widget->inherits("KDoubleNumInput"));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+void KFileMetaInfoWidget::slotComboChanged(const TQString &value)
+{
+ Q_ASSERT(m_widget->inherits("KComboBox"));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+void KFileMetaInfoWidget::slotLineEditChanged(const TQString& value)
+{
+ Q_ASSERT(m_widget->inherits("KLineEdit"));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+// that may be a little expensive for long texts, but what can we do?
+void KFileMetaInfoWidget::slotMultiLineEditChanged()
+{
+ Q_ASSERT(m_widget->inherits(TQTEXTEDIT_OBJECT_NAME_STRING));
+ m_value = TQVariant( static_cast<const TQTextEdit*>( sender() )->text() );
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+void KFileMetaInfoWidget::slotDateChanged(const TQDate& value)
+{
+ Q_ASSERT(m_widget->inherits(TQDATEEDIT_OBJECT_NAME_STRING));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+void KFileMetaInfoWidget::slotTimeChanged(const TQTime& value)
+{
+ Q_ASSERT(m_widget->inherits(TQTIMEEDIT_OBJECT_NAME_STRING));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+void KFileMetaInfoWidget::slotDateTimeChanged(const TQDateTime& value)
+{
+ Q_ASSERT(m_widget->inherits(TQDATETIMEEDIT_OBJECT_NAME_STRING));
+ m_value = TQVariant(value);
+ emit valueChanged(m_value);
+ m_dirty = true;
+}
+
+#include "tdefilemetainfowidget.moc"
diff --git a/tdeio/tdefile/tdefilemetainfowidget.h b/tdeio/tdefile/tdefilemetainfowidget.h
new file mode 100644
index 000000000..8f1d2b5b7
--- /dev/null
+++ b/tdeio/tdefile/tdefilemetainfowidget.h
@@ -0,0 +1,95 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001,2002 Rolf Magnus <ramagnus@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+ */
+
+#ifndef __KFILEMETAINFOWIDGET_H__
+#define __KFILEMETAINFOWIDGET_H__
+
+#include <tqwidget.h>
+#include <tqvariant.h>
+#include <tdefilemetainfo.h>
+
+/*!
+ * A widget to display file meta infos (like id3 for mp3)
+ */
+class TDEIO_EXPORT KFileMetaInfoWidget: public TQWidget
+{
+ Q_OBJECT
+public:
+ enum Mode
+ {
+ ReadOnly = 1, ///Only display the meta infos, and do not permit the user to edit them
+ ReadWrite = 0, ///Permits user to edit the displayed meta-info
+ Reserve = 0xff
+ };
+
+ KFileMetaInfoWidget(KFileMetaInfoItem item, TQValidator* val = 0,
+ TQWidget* parent = 0, const char* name = 0);
+
+ KFileMetaInfoWidget(KFileMetaInfoItem item, Mode mode, TQValidator* val = 0,
+ TQWidget* parent = 0, const char* name = 0);
+
+ virtual ~KFileMetaInfoWidget();
+
+ bool apply()
+ {
+ return m_item.isEditable() && m_item.setValue(m_value);
+ }
+
+ void setValue(const TQVariant& value) { m_value = value; }
+ TQVariant value()const { return m_value; }
+ TQValidator* validator() const { return m_validator; }
+ KFileMetaInfoItem item()const { return m_item; }
+
+signals:
+ void valueChanged(const TQVariant& value);
+
+protected:
+ void reparentValidator(TQWidget *widget, TQValidator *validator);
+ virtual TQWidget* makeWidget();
+
+ TQWidget* makeBoolWidget();
+ TQWidget* makeIntWidget();
+ TQWidget* makeDoubleWidget();
+ TQWidget* makeStringWidget();
+ TQWidget* makeDateWidget();
+ TQWidget* makeTimeWidget();
+ TQWidget* makeDateTimeWidget();
+
+private slots:
+ void slotChanged(bool value);
+ void slotChanged(int value);
+ void slotChanged(double value);
+ void slotComboChanged(const TQString &value);
+ void slotLineEditChanged(const TQString& value);
+ void slotMultiLineEditChanged();
+ void slotDateChanged(const TQDate& value);
+ void slotTimeChanged(const TQTime& value);
+ void slotDateTimeChanged(const TQDateTime& value);
+
+private:
+ void init(KFileMetaInfoItem item, Mode mode);
+
+ TQVariant m_value; // the value will be saved here until apply() is called
+ KFileMetaInfoItem m_item;
+ TQWidget* m_widget;
+ TQValidator* m_validator;
+ bool m_dirty : 1;
+};
+
+#endif
diff --git a/tdeio/tdefile/tdefilemetapreview.cpp b/tdeio/tdefile/tdefilemetapreview.cpp
new file mode 100644
index 000000000..d587511e4
--- /dev/null
+++ b/tdeio/tdefile/tdefilemetapreview.cpp
@@ -0,0 +1,196 @@
+/*
+ * This file is part of the KDE project.
+ * Copyright (C) 2003 Carsten Pfeiffer <pfeiffer@kde.org>
+ *
+ * You can Freely distribute this program under the GNU Library General Public
+ * License. See the file "COPYING" for the exact licensing terms.
+ */
+
+#include "tdefilemetapreview.h"
+
+#include <tqlayout.h>
+
+#include <tdeio/previewjob.h>
+#include <klibloader.h>
+#include <kimagefilepreview.h>
+#include <kmimetype.h>
+
+bool KFileMetaPreview::s_tryAudioPreview = true;
+
+KFileMetaPreview::KFileMetaPreview( TQWidget *parent, const char *name )
+ : KPreviewWidgetBase( parent, name ),
+ haveAudioPreview( false )
+{
+ TQHBoxLayout *layout = new TQHBoxLayout( this, 0, 0 );
+ m_stack = new TQWidgetStack( this );
+ layout->addWidget( m_stack );
+
+ // ###
+// m_previewProviders.setAutoDelete( true );
+ initPreviewProviders();
+}
+
+KFileMetaPreview::~KFileMetaPreview()
+{
+}
+
+void KFileMetaPreview::initPreviewProviders()
+{
+ m_previewProviders.clear();
+ // hardcoded so far
+
+ // image previews
+ KImageFilePreview *imagePreview = new KImageFilePreview( m_stack );
+ (void) m_stack->addWidget( imagePreview );
+ m_stack->raiseWidget( imagePreview );
+ resize( imagePreview->sizeHint() );
+
+ TQStringList mimeTypes = imagePreview->supportedMimeTypes();
+ TQStringList::ConstIterator it = mimeTypes.begin();
+ for ( ; it != mimeTypes.end(); ++it )
+ {
+// tqDebug(".... %s", (*it).latin1());
+ m_previewProviders.insert( *it, imagePreview );
+ }
+}
+
+KPreviewWidgetBase * KFileMetaPreview::previewProviderFor( const TQString& mimeType )
+{
+// tqDebug("### looking for: %s", mimeType.latin1());
+ // often the first highlighted item, where we can be sure, there is no plugin
+ // (this "folders reflect icons" is a konq-specific thing, right?)
+ if ( mimeType == "inode/directory" )
+ return 0L;
+
+ KPreviewWidgetBase *provider = m_previewProviders.find( mimeType );
+ if ( provider )
+ return provider;
+
+//tqDebug("#### didn't find anything for: %s", mimeType.latin1());
+
+ if ( s_tryAudioPreview &&
+ !mimeType.startsWith("text/") && !mimeType.startsWith("image/") )
+ {
+ if ( !haveAudioPreview )
+ {
+ KPreviewWidgetBase *audioPreview = createAudioPreview( m_stack );
+ if ( audioPreview )
+ {
+ haveAudioPreview = true;
+ (void) m_stack->addWidget( audioPreview );
+ TQStringList mimeTypes = audioPreview->supportedMimeTypes();
+ TQStringList::ConstIterator it = mimeTypes.begin();
+ for ( ; it != mimeTypes.end(); ++it )
+ m_previewProviders.insert( *it, audioPreview );
+ }
+ }
+ }
+
+ // with the new mimetypes from the audio-preview, try again
+ provider = m_previewProviders.find( mimeType );
+ if ( provider )
+ return provider;
+
+ // ### mimetype may be image/* for example, try that
+ int index = mimeType.find( '/' );
+ if ( index > 0 )
+ {
+ provider = m_previewProviders.find( mimeType.left( index + 1 ) + "*" );
+ if ( provider )
+ return provider;
+ }
+
+ KMimeType::Ptr mimeInfo = KMimeType::mimeType( mimeType );
+ if ( mimeInfo )
+ {
+ // check mime type inheritance
+ TQString parentMimeType = mimeInfo->parentMimeType();
+ while ( !parentMimeType.isEmpty() )
+ {
+ provider = m_previewProviders.find( parentMimeType );
+ if ( provider )
+ return provider;
+
+ KMimeType::Ptr parentMimeInfo = KMimeType::mimeType( parentMimeType );
+ if ( !parentMimeInfo ) break;
+
+ parentMimeType = parentMimeInfo->parentMimeType();
+ }
+
+ // check X-TDE-Text property
+ TQVariant textProperty = mimeInfo->property( "X-TDE-text" );
+ if ( textProperty.isValid() && textProperty.type() == TQVariant::Bool )
+ {
+ if ( textProperty.toBool() )
+ {
+ provider = m_previewProviders.find( "text/plain" );
+ if ( provider )
+ return provider;
+
+ provider = m_previewProviders.find( "text/*" );
+ if ( provider )
+ return provider;
+ }
+ }
+ }
+
+ return 0L;
+}
+
+void KFileMetaPreview::showPreview(const KURL &url)
+{
+ KMimeType::Ptr mt = KMimeType::findByURL( url );
+ KPreviewWidgetBase *provider = previewProviderFor( mt->name() );
+ if ( provider )
+ {
+ if ( provider != m_stack->visibleWidget() ) // stop the previous preview
+ clearPreview();
+
+ m_stack->setEnabled( true );
+ m_stack->raiseWidget( provider );
+ provider->showPreview( url );
+ }
+ else
+ {
+ clearPreview();
+ m_stack->setEnabled( false );
+ }
+}
+
+void KFileMetaPreview::clearPreview()
+{
+ if ( m_stack->visibleWidget() )
+ static_cast<KPreviewWidgetBase*>( m_stack->visibleWidget() )->clearPreview();
+}
+
+void KFileMetaPreview::addPreviewProvider( const TQString& mimeType,
+ KPreviewWidgetBase *provider )
+{
+ m_previewProviders.insert( mimeType, provider );
+}
+
+void KFileMetaPreview::clearPreviewProviders()
+{
+ TQDictIterator<KPreviewWidgetBase> it( m_previewProviders );
+ for ( ; it.current(); ++it )
+ m_stack->removeWidget( it.current() );
+
+ m_previewProviders.clear();
+}
+
+// static
+KPreviewWidgetBase * KFileMetaPreview::createAudioPreview( TQWidget *parent )
+{
+ KLibFactory *factory = KLibLoader::self()->factory( "tdefileaudiopreview" );
+ if ( !factory )
+ {
+ s_tryAudioPreview = false;
+ return 0L;
+ }
+
+ return dynamic_cast<KPreviewWidgetBase*>( factory->create( TQT_TQOBJECT(parent), "tdefileaudiopreview" ));
+}
+
+void KFileMetaPreview::virtual_hook( int, void* ) {}
+
+#include "tdefilemetapreview.moc"
diff --git a/kio/kfile/kfilemetapreview.h b/tdeio/tdefile/tdefilemetapreview.h
index f26cd29b5..f26cd29b5 100644
--- a/kio/kfile/kfilemetapreview.h
+++ b/tdeio/tdefile/tdefilemetapreview.h
diff --git a/tdeio/tdefile/tdefilepreview.cpp b/tdeio/tdefile/tdefilepreview.cpp
new file mode 100644
index 000000000..4e9365361
--- /dev/null
+++ b/tdeio/tdefile/tdefilepreview.cpp
@@ -0,0 +1,279 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
+ 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ 2000 Werner Trobin <wtrobin@carinthia.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <kaction.h>
+#include <tdefilepreview.h>
+#include <tdefilepreview.moc>
+#include <klocale.h>
+
+#include <tqlabel.h>
+
+#include "config-tdefile.h"
+
+KFilePreview::KFilePreview(KFileView *view, TQWidget *parent, const char *name)
+ : TQSplitter(parent, name), KFileView()
+{
+ if ( view )
+ init( view );
+ else
+ init( new KFileIconView( (TQSplitter*) this, "left" ));
+}
+
+
+KFilePreview::KFilePreview(TQWidget *parent, const char *name) :
+ TQSplitter(parent, name), KFileView()
+{
+ init( new KFileIconView((TQSplitter*)this, "left") );
+}
+
+KFilePreview::~KFilePreview()
+{
+ // Why copy the actions in the first place? --ellis, 13 Jan 02.
+ //// don't delete the view's actions (inserted into our collection)!
+ //for ( uint i = 0; i < left->actionCollection()->count(); i++ )
+ // actionCollection()->take( left->actionCollection()->action( i ));
+
+ // don't delete the preview, we can reuse it
+ // (it will get deleted by ~KDirOperator)
+ if ( preview && preview->parentWidget() == this ) {
+ preview->reparent(0L, 0, TQPoint(0, 0), false);
+ }
+}
+
+void KFilePreview::init( KFileView *view )
+{
+ setViewName( i18n("Preview") );
+
+ left = 0L;
+ setFileView( view );
+
+ preview = new TQWidget((TQSplitter*)this, "preview");
+ TQString tmp = i18n("No preview available.");
+ TQLabel *l = new TQLabel(tmp, preview);
+ l->setMinimumSize(l->sizeHint());
+ l->move(10, 5);
+ preview->setMinimumWidth(l->sizeHint().width()+20);
+ setResizeMode(preview, TQSplitter::KeepSize);
+
+ // Why copy the actions? --ellis, 13 Jan 02.
+ //for ( uint i = 0; i < view->actionCollection()->count(); i++ )
+ // actionCollection()->insert( view->actionCollection()->action( i ));
+}
+
+void KFilePreview::setFileView( KFileView *view )
+{
+ Q_ASSERT( view );
+
+ // Why copy the actions? --ellis, 13 Jan 02.
+ //if ( left ) { // remove any previous actions
+ // for ( uint i = 0; i < left->actionCollection()->count(); i++ )
+ // actionCollection()->take( left->actionCollection()->action( i ));
+ //}
+
+ delete left;
+ view->widget()->reparent( this, TQPoint(0,0) );
+ view->KFileView::setViewMode(All);
+ view->setParentView(this);
+ view->setSorting( sorting() );
+ left = view;
+
+ connect( left->signaler(), TQT_SIGNAL( fileHighlighted(const KFileItem*) ),
+ TQT_SLOT( slotHighlighted( const KFileItem * )));
+
+ // Why copy the actions? --ellis, 13 Jan 02.
+ //for ( uint i = 0; i < view->actionCollection()->count(); i++ )
+ // actionCollection()->insert( view->actionCollection()->action( i ));
+}
+
+// this url parameter is useless... it's the url of the current directory.
+// what for?
+void KFilePreview::setPreviewWidget(const TQWidget *w, const KURL &)
+{
+ left->setOnlyDoubleClickSelectsFiles( onlyDoubleClickSelectsFiles() );
+
+ if (w) {
+ connect(this, TQT_SIGNAL( showPreview(const KURL &) ),
+ w, TQT_SLOT( showPreview(const KURL &) ));
+ connect( this, TQT_SIGNAL( clearPreview() ),
+ w, TQT_SLOT( clearPreview() ));
+ }
+ else {
+ preview->hide();
+ return;
+ }
+
+ delete preview;
+ preview = const_cast<TQWidget*>(w);
+ preview->reparent((TQSplitter*)this, 0, TQPoint(0, 0), true);
+ preview->resize(preview->sizeHint());
+ preview->show();
+}
+
+void KFilePreview::insertItem(KFileItem *item)
+{
+ KFileView::insertItem( item );
+ left->insertItem(item);
+}
+
+void KFilePreview::setSorting( TQDir::SortSpec sort )
+{
+ left->setSorting( sort );
+ KFileView::setSorting( left->sorting() );
+}
+
+void KFilePreview::clearView()
+{
+ left->clearView();
+ emit clearPreview();
+}
+
+void KFilePreview::updateView(bool b)
+{
+ left->updateView(b);
+ if(preview)
+ preview->repaint(b);
+}
+
+void KFilePreview::updateView(const KFileItem *i)
+{
+ left->updateView(i);
+}
+
+void KFilePreview::removeItem(const KFileItem *i)
+{
+ if ( left->isSelected( i ) )
+ emit clearPreview();
+
+ left->removeItem(i);
+ KFileView::removeItem( i );
+}
+
+void KFilePreview::listingCompleted()
+{
+ left->listingCompleted();
+}
+
+void KFilePreview::clear()
+{
+ KFileView::clear();
+ left->KFileView::clear();
+}
+
+void KFilePreview::clearSelection()
+{
+ left->clearSelection();
+ emit clearPreview();
+}
+
+void KFilePreview::selectAll()
+{
+ left->selectAll();
+}
+
+void KFilePreview::invertSelection()
+{
+ left->invertSelection();
+}
+
+bool KFilePreview::isSelected( const KFileItem *i ) const
+{
+ return left->isSelected( i );
+}
+
+void KFilePreview::setSelectionMode(KFile::SelectionMode sm) {
+ left->setSelectionMode( sm );
+}
+
+void KFilePreview::setSelected(const KFileItem *item, bool enable) {
+ left->setSelected( item, enable );
+}
+
+void KFilePreview::setCurrentItem( const KFileItem *item )
+{
+ left->setCurrentItem( item );
+}
+
+KFileItem * KFilePreview::currentFileItem() const
+{
+ return left->currentFileItem();
+}
+
+void KFilePreview::slotHighlighted(const KFileItem* item)
+{
+ if ( item )
+ emit showPreview( item->url() );
+
+ else { // item = 0 -> multiselection mode
+ const KFileItemList *items = selectedItems();
+ if ( items->count() == 1 )
+ emit showPreview( items->getFirst()->url() );
+ else
+ emit clearPreview();
+ }
+
+ // the preview widget appears and takes some space of the left view,
+ // so we may have to scroll to make the current item visible
+ left->ensureItemVisible(item);
+ }
+
+void KFilePreview::ensureItemVisible(const KFileItem *item)
+{
+ left->ensureItemVisible(item);
+}
+
+KFileItem * KFilePreview::firstFileItem() const
+{
+ return left->firstFileItem();
+}
+
+KFileItem * KFilePreview::nextItem( const KFileItem *item ) const
+{
+ return left->nextItem( item );
+}
+
+KFileItem * KFilePreview::prevItem( const KFileItem *item ) const
+{
+ return left->prevItem( item );
+}
+
+KActionCollection * KFilePreview::actionCollection() const
+{
+ if ( left )
+ return left->actionCollection();
+ else {
+ kdWarning() << "KFilePreview::actionCollection(): called before setFileView()." << endl; //ellis
+ return KFileView::actionCollection();
+ }
+}
+
+void KFilePreview::readConfig( TDEConfig *config, const TQString& group )
+{
+ left->readConfig( config, group );
+}
+
+void KFilePreview::writeConfig( TDEConfig *config, const TQString& group )
+{
+ left->writeConfig( config, group );
+}
+
+void KFilePreview::virtual_hook( int id, void* data )
+{ KFileView::virtual_hook( id, data ); }
+
diff --git a/tdeio/tdefile/tdefilepreview.h b/tdeio/tdefile/tdefilepreview.h
new file mode 100644
index 000000000..38db862ac
--- /dev/null
+++ b/tdeio/tdefile/tdefilepreview.h
@@ -0,0 +1,122 @@
+/* -*- c++ -*-
+ This file is part of the KDE libraries
+ Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
+ 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ 2000 Werner Trobin <wtrobin@carinthia.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KFILEPREVIEW_H
+#define _KFILEPREVIEW_H
+
+#include <tqsplitter.h>
+#include <tqwidget.h>
+#include <tqstring.h>
+
+#include <kurl.h>
+#include <tdefileitem.h>
+#include <tdefileiconview.h>
+#include <tdefiledetailview.h>
+#include <tdefile.h>
+
+/*!
+ * This KFileView is an empbedded preview for some file types.
+ */
+class TDEIO_EXPORT KFilePreview : public TQSplitter, public KFileView
+{
+ Q_OBJECT
+
+public:
+ KFilePreview(TQWidget *parent, const char *name);
+ KFilePreview(KFileView *view, TQWidget *parent, const char *name);
+ virtual ~KFilePreview();
+
+ virtual TQWidget *widget() { return this; }
+ virtual void clearView();
+
+ /**
+ * Delets the current view and sets the view to the given @p view.
+ * The view is reparented to have this as parent, if necessary.
+ */
+ void setFileView(KFileView *view);
+
+ /**
+ * @returns the current fileview
+ */
+ KFileView* fileView() const { return left; }
+
+ virtual void updateView( bool );
+ virtual void updateView(const KFileItem*);
+ virtual void removeItem(const KFileItem*);
+ virtual void listingCompleted();
+
+ virtual void setSelectionMode( KFile::SelectionMode sm );
+
+ virtual void setSelected(const KFileItem *, bool);
+ virtual bool isSelected( const KFileItem * ) const;
+ virtual void clearSelection();
+ virtual void selectAll();
+ virtual void invertSelection();
+
+ virtual void insertItem(KFileItem *);
+ virtual void clear();
+
+ virtual void setCurrentItem( const KFileItem * );
+ virtual KFileItem * currentFileItem() const;
+ virtual KFileItem * firstFileItem() const;
+ virtual KFileItem * nextItem( const KFileItem * ) const;
+ virtual KFileItem * prevItem( const KFileItem * ) const;
+
+ virtual void setSorting( TQDir::SortSpec sort );
+
+ virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
+ virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
+
+ /**
+ * This overrides KFileView::actionCollection() by returning
+ * the actionCollection() of the KFileView (member left) it contains.
+ * This means that KFilePreview will never create a KActionCollection
+ * object of its own.
+ */
+ virtual KActionCollection * actionCollection() const;
+
+ void ensureItemVisible(const KFileItem *);
+
+ void setPreviewWidget(const TQWidget *w, const KURL &u);
+
+protected slots:
+ virtual void slotHighlighted( const KFileItem * );
+
+signals:
+ void showPreview(const KURL &);
+ void clearPreview();
+
+private:
+ void init( KFileView *view );
+
+ KFileView *left;
+ TQWidget *preview;
+ TQString viewname;
+
+protected:
+ /** \internal */
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KFilePreviewPrivate;
+ KFilePreviewPrivate *d;
+};
+#endif
diff --git a/tdeio/tdefile/tdefilesharedlg.cpp b/tdeio/tdefile/tdefilesharedlg.cpp
new file mode 100644
index 000000000..8e6f9e650
--- /dev/null
+++ b/tdeio/tdefile/tdefilesharedlg.cpp
@@ -0,0 +1,325 @@
+/* This file is part of the KDE project
+ Copyright (c) 2001 David Faure <david@mandrakesoft.com>
+ Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdefilesharedlg.h"
+#include <tqvbox.h>
+#include <tqlabel.h>
+#include <tqdir.h>
+#include <tqradiobutton.h>
+#include <tqbuttongroup.h>
+#include <tqlayout.h>
+#include <tqlineedit.h>
+#include <kprocess.h>
+#include <kprocio.h>
+#include <klocale.h>
+#include <kglobalsettings.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <tdeio/tdefileshare.h>
+#include <kseparator.h>
+#include <tqpushbutton.h>
+#include <kapplication.h>
+#include <ksimpleconfig.h>
+#include <kmessagebox.h>
+
+class KFileSharePropsPlugin::Private
+{
+public:
+ TQVBox *m_vBox;
+ TDEProcess *m_configProc;
+ bool m_bAllShared;
+ bool m_bAllUnshared;
+ bool m_bAllReadOnly;
+};
+
+KFileSharePropsPlugin::KFileSharePropsPlugin( KPropertiesDialog *_props )
+ : KPropsDlgPlugin( _props )
+{
+ d = new Private;
+ d->m_vBox = _props->addVBoxPage( i18n("&Share") );
+ d->m_configProc = 0;
+ properties->setFileSharingPage(d->m_vBox);
+ m_widget = 0L;
+ init();
+}
+
+KFileSharePropsPlugin::~KFileSharePropsPlugin()
+{
+ if (d->m_configProc)
+ d->m_configProc->detach(); // Detach to prevent that we kill the process
+ delete d;
+}
+
+bool KFileSharePropsPlugin::supports( const KFileItemList& items )
+{
+ // Do not show dialog if in advanced mode,
+ // because the advanced dialog is shown already.
+ if (KFileShare::shareMode() == KFileShare::Advanced) {
+ kdDebug() << "KFileSharePropsPlugin::supports: false because sharemode is advanced" << endl;
+ return false;
+ }
+
+ KFileItemListIterator it( items );
+ for ( ; it.current(); ++it )
+ {
+ bool isLocal = ( *it )->isLocalFile();
+ // We only support local dirs
+ if ( !(*it)->isDir() || !isLocal )
+ return false;
+ // And sharing the trash doesn't make sense
+ if ( isLocal && (*it)->url().path( 1 ) == TDEGlobalSettings::trashPath() )
+ return false;
+ }
+ return true;
+}
+
+void KFileSharePropsPlugin::init()
+{
+ // We store the main widget, so that it's possible (later) to call init()
+ // more than once, to update the page if something changed (e.g. after
+ // the user has been authorized)
+ delete m_widget;
+ m_rbShare = 0L;
+ m_rbUnShare = 0L;
+ m_rbSharerw = 0L;
+ m_widget = new TQWidget( d->m_vBox );
+ TQVBoxLayout * vbox = new TQVBoxLayout( m_widget );
+ //TQHBoxLayout * hbox = new TQHBoxLayout( vbox );
+
+ switch ( KFileShare::authorization() ) {
+ case KFileShare::Authorized:
+ {
+ // Check if all selected dirs are in $HOME
+ TQString home = TQDir::homeDirPath();
+ if ( home[home.length()-1] != '/' )
+ home += '/';
+ bool ok = true;
+ KFileItemList items = properties->items();
+ // We have 3 possibilities: all shared, all unshared (ro,rw), or mixed.
+ d->m_bAllShared = true;
+ d->m_bAllUnshared = true;
+ d->m_bAllReadOnly = true;
+ KFileItemListIterator it( items );
+ for ( ; it.current() && ok; ++it ) {
+ TQString path = (*it)->url().path();
+ // 0 => not shared
+ // 1 => shared read only
+ // 3 => shared writeable
+ int dirStatus = KFileShare::isDirectoryShared( path );
+ if ( !path.startsWith( home ) )
+ ok = false;
+ if ( dirStatus == 1 ) {
+ d->m_bAllUnshared = false;
+ }
+ else if ( dirStatus == 3 ) {
+ d->m_bAllUnshared = false;
+ d->m_bAllReadOnly = false;
+ }
+ else {
+ d->m_bAllReadOnly = false;
+ }
+ }
+ if ( !ok )
+ {
+ vbox->addWidget( new TQLabel( i18n( "Only folders in your home folder can be shared."),
+ m_widget ), 0 );
+ }
+ else
+ {
+ // Everything ok, show the share/unshare GUI
+ vbox->setSpacing( KDialog::spacingHint() );
+ vbox->setMargin( KDialog::marginHint() );
+
+ TQButtonGroup *rbGroup = new TQButtonGroup( m_widget );
+ rbGroup->hide();
+ m_rbUnShare = new TQRadioButton( i18n("Not shared"), m_widget );
+ connect( m_rbUnShare, TQT_SIGNAL( toggled(bool) ), TQT_SIGNAL( changed() ) );
+ vbox->addWidget( m_rbUnShare, 0 );
+ rbGroup->insert( m_rbUnShare );
+
+ m_rbShare = new TQRadioButton( i18n("Shared - read only for others"), m_widget );
+ connect( m_rbShare, TQT_SIGNAL( toggled(bool) ), TQT_SIGNAL( changed() ) );
+ vbox->addWidget( m_rbShare, 0 );
+ rbGroup->insert( m_rbShare );
+
+ m_rbSharerw = new TQRadioButton( i18n("Shared - writeable for others"), m_widget );
+ connect( m_rbSharerw, TQT_SIGNAL( toggled(bool) ), TQT_SIGNAL( changed() ) );
+ vbox->addWidget( m_rbSharerw, 0 );
+ rbGroup->insert( m_rbSharerw );
+
+ //TQLabel *testlabel1 = new TQLabel(i18n("Enter Samba Share Name here"),m_widget);
+ //m_leSmbShareName = new TQLineEdit(m_widget);
+ //m_leSmbShareName->setMaxLength(12);
+
+ //hbox->addWidget( testlabel1, 0 );
+ //hbox->addWidget( m_leSmbShareName );
+ //vbox->addLayout( hbox );
+
+ // Activate depending on status
+ if ( d->m_bAllShared )
+ m_rbSharerw->setChecked(true);
+ if ( d->m_bAllUnshared )
+ m_rbUnShare->setChecked(true);
+ if ( d->m_bAllReadOnly )
+ m_rbShare->setChecked(true);
+
+ // Some help text
+ TQLabel *label = new TQLabel( i18n("Sharing this folder makes it available under Linux/UNIX (NFS) and Windows (Samba).") , m_widget );
+ label->setAlignment( TQt::AlignAuto | TQt::AlignVCenter | TQt::WordBreak );
+ vbox->addWidget( label, 0 );
+
+ KSeparator* sep=new KSeparator(m_widget);
+ vbox->addWidget( sep, 0 );
+ label = new TQLabel( i18n("You can also reconfigure file sharing authorization.") , m_widget );
+ label->setAlignment( TQt::AlignAuto | TQt::AlignVCenter | TQt::WordBreak );
+ vbox->addWidget( label, 0 );
+ m_pbConfig = new TQPushButton( i18n("Configure File Sharing..."), m_widget );
+ connect( m_pbConfig, TQT_SIGNAL( clicked() ), TQT_SLOT( slotConfigureFileSharing() ) );
+ vbox->addWidget( m_pbConfig, 0, Qt::AlignHCenter );
+
+ vbox->addStretch( 10 );
+
+ if( !KFileShare::sambaActive() && !KFileShare::nfsActive())
+ m_widget->setEnabled( false );
+ }
+ }
+ break;
+ case KFileShare::ErrorNotFound:
+ vbox->addWidget( new TQLabel( i18n("Error running 'filesharelist'. Check if installed and in $PATH or /usr/sbin."),
+ m_widget ), 0 );
+ break;
+ case KFileShare::UserNotAllowed:
+ {
+ vbox->setSpacing( 10 );
+ if (KFileShare::sharingEnabled()) {
+ vbox->addWidget( new TQLabel( i18n("You need to be authorized to share folders."),
+ m_widget ), 0 );
+ } else {
+ vbox->addWidget( new TQLabel( i18n("File sharing is disabled."),
+ m_widget ), 0 );
+ }
+ TQHBoxLayout* hBox = new TQHBoxLayout( (TQWidget *)0L );
+ vbox->addLayout( hBox, 0 );
+ m_pbConfig = new TQPushButton( i18n("Configure File Sharing..."), m_widget );
+ connect( m_pbConfig, TQT_SIGNAL( clicked() ), TQT_SLOT( slotConfigureFileSharing() ) );
+ hBox->addWidget( m_pbConfig, 0, Qt::AlignHCenter );
+ vbox->addStretch( 10 ); // align items on top
+ break;
+ }
+ case KFileShare::NotInitialized:
+ kdWarning() << "KFileShare Authorization still NotInitialized after calling authorization() - impossible" << endl;
+ break;
+ }
+ m_widget->show(); // In case the dialog was shown already.
+}
+
+void KFileSharePropsPlugin::slotConfigureFileSharing()
+{
+ if (d->m_configProc) return;
+
+ d->m_configProc = new TDEProcess(this);
+ (*d->m_configProc) << KStandardDirs::findExe("tdesu") << locate("exe", "tdecmshell") << "fileshare";
+ if (!d->m_configProc->start( TDEProcess::NotifyOnExit ))
+ {
+ delete d->m_configProc;
+ d->m_configProc = 0;
+ return;
+ }
+ connect(d->m_configProc, TQT_SIGNAL(processExited(TDEProcess *)),
+ this, TQT_SLOT(slotConfigureFileSharingDone()));
+ m_pbConfig->setEnabled(false);
+}
+
+void KFileSharePropsPlugin::slotConfigureFileSharingDone()
+{
+ delete d->m_configProc;
+ d->m_configProc = 0;
+ KFileShare::readConfig();
+ KFileShare::readShareList();
+ init();
+}
+
+void KFileSharePropsPlugin::applyChanges()
+{
+ kdDebug() << "KFileSharePropsPlugin::applyChanges" << endl;
+ if ( m_rbShare && m_rbUnShare && m_rbSharerw )
+ {
+ bool share = m_rbShare->isChecked();
+
+ if (share && d->m_bAllShared)
+ return; // Nothing to do
+ if (!share && d->m_bAllUnshared)
+ return; // Nothing to do
+
+ KFileItemList items = properties->items();
+ KFileItemListIterator it( items );
+ bool ok = true;
+ for ( ; it.current() && ok; ++it ) {
+ TQString path = (*it)->url().path();
+ ok = SuSEsetShared( path, share, m_rbSharerw->isChecked() );
+ if (!ok) {
+ if (share)
+ KMessageBox::detailedError(properties,
+ i18n("Sharing folder '%1' failed.").arg(path),
+ i18n("An error occurred while trying to share folder '%1'. "
+ "Make sure that the Perl script 'fileshareset' is set suid root.")
+ .arg(path));
+ else
+ KMessageBox::error(properties,
+ i18n("Unsharing folder '%1' failed.").arg(path),
+ i18n("An error occurred while trying to unshare folder '%1'. "
+ "Make sure that the Perl script 'fileshareset' is set suid root.")
+ .arg(path));
+
+ properties->abortApplying();
+ break;
+ }
+ }
+
+ // Get the change back into our cached info
+ KFileShare::readShareList();
+ }
+}
+
+bool KFileSharePropsPlugin::setShared( const TQString& path, bool shared )
+{
+ return SuSEsetShared( path, shared, true );
+}
+
+bool KFileSharePropsPlugin::SuSEsetShared( const TQString& path, bool shared, bool readonly )
+{
+ kdDebug() << "KFileSharePropsPlugin::setShared " << path << ","
+ << shared << readonly << endl;
+ return KFileShare::SuSEsetShared( path, shared, readonly );
+}
+
+TQWidget* KFileSharePropsPlugin::page() const
+{
+ return d->m_vBox;
+}
+
+#include "tdefilesharedlg.moc"
+
+//TODO: do we need to monitor /etc/security/fileshare.conf ?
+// if the user is added to the 'fileshare' group, we wouldn't be notified
+// Of course the config module can notify us.
+// TODO: listen to such notifications ;)
diff --git a/tdeio/tdefile/tdefilesharedlg.h b/tdeio/tdefile/tdefilesharedlg.h
new file mode 100644
index 000000000..aa818db64
--- /dev/null
+++ b/tdeio/tdefile/tdefilesharedlg.h
@@ -0,0 +1,70 @@
+/* This file is part of the KDE project
+ Copyright (c) 2001 David Faure <david@mandrakesoft.com>
+ Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef tdefilesharedlg_h
+#define tdefilesharedlg_h
+
+#include <kpropertiesdialog.h>
+class TQVBoxLayout;
+class TQRadioButton;
+class TQPushButton;
+
+/**
+ * This plugin provides a page to KPropsDlg, showing the "file sharing" options
+ * @author David Faure <david@mandrakesoft.com>
+ * @since 3.1
+ */
+class TDEIO_EXPORT KFileSharePropsPlugin : public KPropsDlgPlugin
+{
+ Q_OBJECT
+public:
+ KFileSharePropsPlugin( KPropertiesDialog *_props );
+ virtual ~KFileSharePropsPlugin();
+
+ /**
+ * Apply all changes to the file.
+ * This function is called when the user presses 'Ok'. The last plugin inserted
+ * is called first.
+ */
+ virtual void applyChanges();
+
+ static bool supports( const KFileItemList& items );
+
+ TQWidget* page() const;
+
+protected slots:
+ void slotConfigureFileSharing();
+ void slotConfigureFileSharingDone();
+
+private:
+ void init();
+ bool setShared( const TQString&path, bool shared );
+ bool SuSEsetShared( const TQString&path, bool shared, bool readonly );
+
+ TQWidget *m_widget;
+ TQRadioButton *m_rbShare;
+ TQRadioButton *m_rbSharerw;
+ TQRadioButton *m_rbUnShare;
+ //TQLineEdit *m_leSmbShareName;
+ TQPushButton *m_pbConfig;
+ class Private;
+ Private *d;
+};
+
+#endif
diff --git a/tdeio/tdefile/tdefilespeedbar.cpp b/tdeio/tdefile/tdefilespeedbar.cpp
new file mode 100644
index 000000000..ca7e19003
--- /dev/null
+++ b/tdeio/tdefile/tdefilespeedbar.cpp
@@ -0,0 +1,147 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation, version 2.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdefilespeedbar.h"
+#include "config-tdefile.h"
+
+#include <tqdir.h>
+#include <tqfile.h>
+#include <tqtextcodec.h>
+#include <tqtextstream.h>
+
+#include <tdeconfig.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <klocale.h>
+#include <kprotocolinfo.h>
+#include <kstandarddirs.h>
+#include <kurl.h>
+
+KFileSpeedBar::KFileSpeedBar( TQWidget *parent, const char *name )
+ : KURLBar( true, parent, name )
+{
+ TDEConfig *config = TDEGlobal::config();
+ TDEConfigGroupSaver cs( config, ConfigGroup );
+ m_initializeSpeedbar = config->readBoolEntry( "Set speedbar defaults",
+ true );
+ setIconSize(KIcon::SizeSmallMedium);
+ readConfig( TDEGlobal::config(), "KFileDialog Speedbar" );
+
+ if ( m_initializeSpeedbar )
+ {
+ KURL u;
+ u.setPath( TDEGlobalSettings::desktopPath() );
+ insertItem( u, i18n("Desktop"), false );
+
+//TODO: win32
+ if ((TDEGlobalSettings::documentPath() != (TQDir::homeDirPath()+"/")) &&
+ TQDir(TDEGlobalSettings::documentPath()).exists())
+ {
+ u.setPath( TDEGlobalSettings::documentPath() );
+ insertItem( u, i18n("Documents"), false, "folder_txt" );
+ }
+
+ u.setPath( TQDir::homeDirPath() );
+ insertItem( u, i18n("Home Folder"), false,
+ "folder_home" );
+
+ u = "media:/";
+ if ( KProtocolInfo::isKnownProtocol( u ) )
+ insertItem( u, i18n("Storage Media"), false,
+ KProtocolInfo::icon( "media" ) );
+
+ if ( TQFile::exists( TQDir::homeDirPath()+"/.config/user-dirs.dirs" ) )
+ {
+ TQString download, music, pictures, videos, templates, publicShares;
+
+ TQFile f( TQDir::homeDirPath()+"/.config/user-dirs.dirs" );
+ if (!f.open(IO_ReadOnly))
+ return;
+
+ TQTextStream s( &f );
+ s.setCodec( TQTextCodec::codecForLocale() );
+
+ // read the xdg user dirs
+ TQString line = s.readLine();
+ while (!line.isNull())
+ {
+ if (line.startsWith("XDG_DOWNLOAD_DIR="))
+ download = line.remove("XDG_DOWNLOAD_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
+ else if (line.startsWith("XDG_MUSIC_DIR="))
+ music = line.remove("XDG_MUSIC_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
+ else if (line.startsWith("XDG_PICTURES_DIR="))
+ pictures = line.remove("XDG_PICTURES_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
+ else if (line.startsWith("XDG_VIDEOS_DIR="))
+ videos = line.remove("XDG_VIDEOS_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
+ else if (line.startsWith("XDG_TEMPLATES_DIR="))
+ templates = line.remove("XDG_TEMPLATES_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
+ else if (line.startsWith("XDG_PUBLICSHARES_DIR="))
+ publicShares = line.remove("XDG_PUBLICSHARES_DIR=").remove("\"").replace("$HOME", TQDir::homeDirPath());
+
+ line = s.readLine();
+ }
+ // now add in the speedbar
+ if (!download.isEmpty())
+ insertItem( download, i18n( "Download" ), false, "folder_html" );
+ if (!music.isEmpty())
+ insertItem( music, i18n( "Music" ), false, "folder_sound" );
+ if (!pictures.isEmpty())
+ insertItem( pictures, i18n( "Pictures" ), false, "folder_image" );
+ if (!videos.isEmpty())
+ insertItem( videos, i18n( "Videos" ), false, "folder_video" );
+ if (!templates.isEmpty())
+ insertItem( templates, i18n( "Templates" ), false, "folder_video" );
+ if (!publicShares.isEmpty())
+ insertItem( publicShares, i18n( "Public" ), false, "folder_video" );
+ }
+
+ u = "remote:/";
+ if ( KProtocolInfo::isKnownProtocol( u ) )
+ insertItem( u, i18n("Network Folders"), false,
+ KProtocolInfo::icon( "remote" ) );
+ }
+}
+
+KFileSpeedBar::~KFileSpeedBar()
+{
+}
+
+void KFileSpeedBar::save( TDEConfig *config )
+{
+ if ( m_initializeSpeedbar && isModified() )
+ {
+ TDEConfigGroup conf( config, ConfigGroup );
+ // write to kdeglobals
+ conf.writeEntry( "Set speedbar defaults", false, true, true );
+ }
+
+ writeConfig( config, "KFileDialog Speedbar" );
+}
+
+TQSize KFileSpeedBar::sizeHint() const
+{
+ TQSize sizeHint = KURLBar::sizeHint();
+ int ems = fontMetrics().width("mmmmmmmmmmmm");
+ if (sizeHint.width() < ems)
+ {
+ sizeHint.setWidth(ems);
+ }
+ return sizeHint;
+}
+
+#include "tdefilespeedbar.moc"
diff --git a/kio/kfile/kfilespeedbar.h b/tdeio/tdefile/tdefilespeedbar.h
index d1c2a689e..d1c2a689e 100644
--- a/kio/kfile/kfilespeedbar.h
+++ b/tdeio/tdefile/tdefilespeedbar.h
diff --git a/tdeio/tdefile/tdefiletreebranch.cpp b/tdeio/tdefile/tdefiletreebranch.cpp
new file mode 100644
index 000000000..f95cb4d47
--- /dev/null
+++ b/tdeio/tdefile/tdefiletreebranch.cpp
@@ -0,0 +1,528 @@
+/* This file is part of the KDEproject
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2002 Klaas Freitag <freitag@suse.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqfile.h>
+
+#include <tdefileitem.h>
+#include <kdebug.h>
+#include <kde_file.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "tdefiletreeviewitem.h"
+#include "tdefiletreebranch.h"
+
+
+/* --- KFileTreeViewToplevelItem --- */
+KFileTreeBranch::KFileTreeBranch( KFileTreeView *parent, const KURL& url,
+ const TQString& name,
+ const TQPixmap& pix, bool showHidden,
+ KFileTreeViewItem *branchRoot )
+
+ : KDirLister( false ),
+ m_root( branchRoot ),
+ m_startURL( url ),
+ m_name ( name ),
+ m_rootIcon( pix ),
+ m_openRootIcon( pix ),
+ m_recurseChildren(true),
+ m_showExtensions(true)
+{
+ kdDebug( 250) << "Creating branch for url " << url.prettyURL() << endl;
+
+ /* if non exists, create one */
+ if( ! branchRoot )
+ {
+ m_root = new KFileTreeViewItem( parent,
+ new KFileItem( url, "inode/directory",
+ S_IFDIR ),
+ this );
+ }
+
+ m_root->setExpandable( true );
+ m_root->setPixmap( 0, pix );
+ m_root->setText( 0, name );
+
+ setShowingDotFiles( showHidden );
+
+ connect( this, TQT_SIGNAL( refreshItems(const KFileItemList&)),
+ this, TQT_SLOT ( slotRefreshItems( const KFileItemList& )));
+
+ connect( this, TQT_SIGNAL( newItems(const KFileItemList&)),
+ this, TQT_SLOT ( addItems( const KFileItemList& )));
+
+ connect( this, TQT_SIGNAL( completed(const KURL& )),
+ this, TQT_SLOT(slCompleted(const KURL&)));
+
+ connect( this, TQT_SIGNAL( started( const KURL& )),
+ this, TQT_SLOT( slotListerStarted( const KURL& )));
+
+ connect( this, TQT_SIGNAL( deleteItem( KFileItem* )),
+ this, TQT_SLOT( slotDeleteItem( KFileItem* )));
+
+ connect( this, TQT_SIGNAL( canceled(const KURL&) ),
+ this, TQT_SLOT( slotCanceled(const KURL&) ));
+
+ connect( this, TQT_SIGNAL( clear()),
+ this, TQT_SLOT( slotDirlisterClear()));
+
+ connect( this, TQT_SIGNAL( clear(const KURL&)),
+ this, TQT_SLOT( slotDirlisterClearURL(const KURL&)));
+
+ connect( this, TQT_SIGNAL( redirection( const KURL& , const KURL& ) ),
+ this, TQT_SLOT( slotRedirect( const KURL&, const KURL& )));
+
+ m_openChildrenURLs.append( url );
+}
+
+void KFileTreeBranch::setOpenPixmap( const TQPixmap& pix )
+{
+ m_openRootIcon = pix;
+
+ if( root()->isOpen())
+ {
+ root()->setPixmap( 0, pix );
+ }
+}
+
+void KFileTreeBranch::slotListerStarted( const KURL &url )
+{
+ /* set the parent correct if it is zero. */
+ kdDebug( 250) << "Starting to list " << url.prettyURL() << endl;
+}
+
+
+KFileTreeViewItem *KFileTreeBranch::parentKFTVItem( KFileItem *item )
+{
+ KFileTreeViewItem *parent = 0;
+
+ if( ! item ) return 0;
+
+ /* If it is a directory, check, if it exists in the dict. If not, go one up
+ * and check again.
+ */
+ KURL url = item->url();
+ // kdDebug(250) << "Item's url is " << url.prettyURL() << endl;
+ KURL dirUrl( url );
+ dirUrl.setFileName( TQString::null );
+ // kdDebug(250) << "Directory url is " << dirUrl.prettyURL() << endl;
+
+ parent = findTVIByURL( dirUrl );
+ // kdDebug(250) << "Returning as parent item <" << parent << ">" << endl;
+ return( parent );
+}
+
+
+void KFileTreeBranch::slotRefreshItems( const KFileItemList& list )
+{
+ KFileItemListIterator it( list );
+ kdDebug(250) << "Refreshing " << list.count() << " items !" << endl;
+ KFileItem *currItem;
+ KFileTreeViewItem *item = 0;
+
+ while ( (currItem = it.current()) != 0 )
+ {
+ item = findTVIByURL(currItem->url());
+ if (item) {
+ item->setPixmap(0, item->fileItem()->pixmap( KIcon::SizeSmall ));
+ item->setText( 0, item->fileItem()->text());
+ }
+ ++it;
+ }
+}
+
+void KFileTreeBranch::addItems( const KFileItemList& list )
+{
+ KFileItemListIterator it( list );
+ kdDebug(250) << "Adding " << list.count() << " items !" << endl;
+ KFileItem *currItem;
+ KFileTreeViewItemList treeViewItList;
+ KFileTreeViewItem *parentItem = 0;
+
+ while ( (currItem = it.current()) != 0 )
+ {
+ parentItem = parentKFTVItem( currItem );
+
+
+ /* Only create a new KFileTreeViewItem if it does not yet exist */
+ KFileTreeViewItem *newKFTVI =
+ static_cast<KFileTreeViewItem *>(currItem->extraData( this ));
+
+ if( ! newKFTVI )
+ {
+ newKFTVI = createTreeViewItem( parentItem, currItem );
+ if (!newKFTVI)
+ {
+ // TODO: Don't fail if parentItem == 0
+ ++it;
+ continue;
+ }
+ currItem->setExtraData( this, newKFTVI );
+
+ /* Cut off the file extension in case it is not a directory */
+ if( !m_showExtensions && !currItem->isDir() ) /* Need to cut the extension */
+ {
+ TQString name = currItem->text();
+ int mPoint = name.findRev( '.' );
+ if( mPoint > 0 )
+ name = name.left( mPoint );
+ newKFTVI->setText( 0, name );
+ }
+ }
+
+ /* Now try to find out if there are children for dirs in the treeview */
+ /* This stats a directory on the local file system and checks the */
+ /* hardlink entry in the stat-buf. This works only for local directories. */
+ if( dirOnlyMode() && !m_recurseChildren && currItem->isLocalFile( ) && currItem->isDir() )
+ {
+ KURL url = currItem->url();
+ TQString filename = url.directory( false, true ) + url.fileName();
+ /* do the stat trick of Carsten. The problem is, that the hardlink
+ * count only contains directory links. Thus, this method only seem
+ * to work in dir-only mode */
+ kdDebug(250) << "Doing stat on " << filename << endl;
+ KDE_struct_stat statBuf;
+ if( KDE_stat( TQFile::encodeName( filename ), &statBuf ) == 0 )
+ {
+ int hardLinks = statBuf.st_nlink; /* Count of dirs */
+ kdDebug(250) << "stat succeeded, hardlinks: " << hardLinks << endl;
+ // If the link count is > 2, the directory likely has subdirs. If it's < 2
+ // it's something weird like a mounted SMB share. In that case we don't know
+ // if there are subdirs, thus show it as expandable.
+
+ if( hardLinks != 2 )
+ {
+ newKFTVI->setExpandable(true);
+ }
+ else
+ {
+ newKFTVI->setExpandable(false);
+ }
+ if( hardLinks >= 2 ) // "Normal" directory with subdirs
+ {
+ kdDebug(250) << "Emitting for " << url.prettyURL() << endl;
+ emit( directoryChildCount( newKFTVI, hardLinks-2)); // parentItem, hardLinks-1 ));
+ }
+ }
+ else
+ {
+ kdDebug(250) << "stat of " << filename << " failed !" << endl;
+ }
+ }
+ ++it;
+
+ treeViewItList.append( newKFTVI );
+ }
+
+ emit newTreeViewItems( this, treeViewItList );
+}
+
+KFileTreeViewItem* KFileTreeBranch::createTreeViewItem( KFileTreeViewItem *parent,
+ KFileItem *fileItem )
+{
+ KFileTreeViewItem *tvi = 0;
+ if( parent && fileItem )
+ {
+ tvi = new KFileTreeViewItem( parent,
+ fileItem,
+ this );
+ }
+ else
+ {
+ kdDebug(250) << "createTreeViewItem: Have no parent" << endl;
+ }
+ return( tvi );
+}
+
+void KFileTreeBranch::setChildRecurse( bool t )
+{
+ m_recurseChildren = t;
+ if( t == false )
+ m_openChildrenURLs.clear();
+}
+
+
+void KFileTreeBranch::setShowExtensions( bool visible )
+{
+ m_showExtensions = visible;
+}
+
+bool KFileTreeBranch::showExtensions( ) const
+{
+ return( m_showExtensions );
+}
+
+/*
+ * The signal that tells that a directory was deleted may arrive before the signal
+ * for its children arrive. Thus, we must walk through the children of a dir and
+ * remove them before removing the dir itself.
+ */
+void KFileTreeBranch::slotDeleteItem( KFileItem *it )
+{
+ if( !it ) return;
+ kdDebug(250) << "Slot Delete Item hitted for " << it->url().prettyURL() << endl;
+
+ KFileTreeViewItem *kfti = static_cast<KFileTreeViewItem*>(it->extraData(this));
+
+ if( kfti )
+ {
+ kdDebug( 250 ) << "Child count: " << kfti->childCount() << endl;
+ if( kfti->childCount() > 0 )
+ {
+ KFileTreeViewItem *child = static_cast<KFileTreeViewItem*>(kfti->firstChild());
+
+ while( child )
+ {
+ kdDebug(250) << "Calling child to be deleted !" << endl;
+ KFileTreeViewItem *nextChild = static_cast<KFileTreeViewItem*>(child->nextSibling());
+ slotDeleteItem( child->fileItem());
+ child = nextChild;
+ }
+ }
+
+ kdDebug(250) << "Found corresponding KFileTreeViewItem" << endl;
+ if( m_lastFoundURL.equals(it->url(), true ))
+ {
+ m_lastFoundURL = KURL();
+ m_lastFoundItem = 0L;
+ }
+ delete( kfti );
+ }
+ else
+ {
+ kdDebug(250) << "Error: tdefiletreeviewitem: "<< kfti << endl;
+ }
+}
+
+
+void KFileTreeBranch::slotCanceled( const KURL& url )
+{
+ // ### anything else to do?
+ // remove the url from the childrento-recurse-list
+ m_openChildrenURLs.remove( url);
+
+ // stop animations etc.
+ KFileTreeViewItem *item = findTVIByURL(url);
+ if (!item) return; // Uh oh...
+ emit populateFinished(item);
+}
+
+void KFileTreeBranch::slotDirlisterClear()
+{
+ kdDebug(250)<< "*** Clear all !" << endl;
+ /* this slots needs to clear all listed items, but NOT the root item */
+ if( m_root )
+ deleteChildrenOf( m_root );
+}
+
+void KFileTreeBranch::slotDirlisterClearURL( const KURL& url )
+{
+ kdDebug(250)<< "*** Clear for URL !" << url.prettyURL() << endl;
+ KFileItem *item = findByURL( url );
+ if( item )
+ {
+ KFileTreeViewItem *ftvi =
+ static_cast<KFileTreeViewItem *>(item->extraData( this ));
+ deleteChildrenOf( ftvi );
+ }
+}
+
+void KFileTreeBranch::deleteChildrenOf( TQListViewItem *parent )
+{
+ // for some strange reason, slotDirlisterClearURL() sometimes calls us
+ // with a 0L parent.
+ if ( !parent )
+ return;
+
+ while ( parent->firstChild() )
+ delete parent->firstChild();
+}
+
+void KFileTreeBranch::slotRedirect( const KURL& oldUrl, const KURL&newUrl )
+{
+ if( oldUrl.equals( m_startURL, true ))
+ {
+ m_startURL = newUrl;
+ }
+}
+
+KFileTreeViewItem* KFileTreeBranch::findTVIByURL( const KURL& url )
+{
+ KFileTreeViewItem *resultItem = 0;
+
+ if( m_startURL.equals(url, true) )
+ {
+ kdDebug(250) << "findByURL: Returning root as a parent !" << endl;
+ resultItem = m_root;
+ }
+ else if( m_lastFoundURL.equals( url, true ))
+ {
+ kdDebug(250) << "findByURL: Returning from lastFoundURL!" << endl;
+ resultItem = m_lastFoundItem;
+ }
+ else
+ {
+ kdDebug(250) << "findByURL: searching by dirlister: " << url.url() << endl;
+
+ KFileItem *it = findByURL( url );
+
+ if( it )
+ {
+ resultItem = static_cast<KFileTreeViewItem*>(it->extraData(this));
+ m_lastFoundItem = resultItem;
+ m_lastFoundURL = url;
+ }
+ }
+
+ return( resultItem );
+}
+
+
+void KFileTreeBranch::slCompleted( const KURL& url )
+{
+ kdDebug(250) << "SlotCompleted hit for " << url.prettyURL() << endl;
+ KFileTreeViewItem *currParent = findTVIByURL( url );
+ if( ! currParent ) return;
+
+ kdDebug(250) << "current parent " << currParent << " is already listed: "
+ << currParent->alreadyListed() << endl;
+
+ emit( populateFinished(currParent));
+ emit( directoryChildCount(currParent, currParent->childCount()));
+
+ /* This is a walk through the children of the last populated directory.
+ * Here we start the dirlister on every child of the dir and wait for its
+ * finish. When it has finished, we go to the next child.
+ * This must be done for non local file systems in dirOnly- and Full-Mode
+ * and for local file systems only in full mode, because the stat trick
+ * (see addItem-Method) does only work for dirs, not for files in the directory.
+ */
+ /* Set bit that the parent dir was listed completely */
+ currParent->setListed(true);
+
+ kdDebug(250) << "recurseChildren: " << m_recurseChildren << endl;
+ kdDebug(250) << "isLocalFile: " << m_startURL.isLocalFile() << endl;
+ kdDebug(250) << "dirOnlyMode: " << dirOnlyMode() << endl;
+
+
+ if( m_recurseChildren && (!m_startURL.isLocalFile() || ! dirOnlyMode()) )
+ {
+ bool wantRecurseUrl = false;
+ /* look if the url is in the list for url to recurse */
+ for ( KURL::List::Iterator it = m_openChildrenURLs.begin();
+ it != m_openChildrenURLs.end(); ++it )
+ {
+ /* it is only interesting that the url _is_in_ the list. */
+ if( (*it).equals( url, true ) )
+ wantRecurseUrl = true;
+ }
+
+ KFileTreeViewItem *nextChild = 0;
+ kdDebug(250) << "Recursing " << url.prettyURL() << "? " << wantRecurseUrl << endl;
+
+ if( wantRecurseUrl && currParent )
+ {
+
+ /* now walk again through the tree and populate the children to get +-signs */
+ /* This is the starting point. The visible folder has finished,
+ processing the children has not yet started */
+ nextChild = static_cast<KFileTreeViewItem*>
+ (static_cast<TQListViewItem*>(currParent)->firstChild());
+
+ if( ! nextChild )
+ {
+ /* This happens if there is no child at all */
+ kdDebug( 250 ) << "No children to recuse" << endl;
+ }
+
+ /* Since we have listed the children to recurse, we can remove the entry
+ * in the list of the URLs to see the children.
+ */
+ m_openChildrenURLs.remove(url);
+ }
+
+ if( nextChild ) /* This implies that idx > -1 */
+ {
+ /* Next child is defined. We start a dirlister job on every child item
+ * which is a directory to find out how much children are in the child
+ * of the last opened dir
+ */
+
+ /* Skip non directory entries */
+ while( nextChild )
+ {
+ if( nextChild->isDir() && ! nextChild->alreadyListed())
+ {
+ KFileItem *kfi = nextChild->fileItem();
+ if( kfi && kfi->isReadable())
+ {
+ KURL recurseUrl = kfi->url();
+ kdDebug(250) << "Starting to recurse NOW " << recurseUrl.prettyURL() << endl;
+ openURL( recurseUrl, true );
+ }
+ }
+ nextChild = static_cast<KFileTreeViewItem*>(static_cast<TQListViewItem*>(nextChild->nextSibling()));
+ // kdDebug(250) << "Next child " << m_nextChild << endl;
+ }
+ }
+ }
+ else
+ {
+ kdDebug(250) << "skipping to recurse in complete-slot" << endl;
+ }
+}
+
+/* This slot is called when a treeviewitem is expanded in the gui */
+bool KFileTreeBranch::populate( const KURL& url, KFileTreeViewItem *currItem )
+{
+ bool ret = false;
+ if( ! currItem )
+ return ret;
+
+ kdDebug(250) << "Populating <" << url.prettyURL() << ">" << endl;
+
+ /* Add this url to the list of urls to recurse for children */
+ if( m_recurseChildren )
+ {
+ m_openChildrenURLs.append( url );
+ kdDebug(250) << "Appending to list " << url.prettyURL() << endl;
+ }
+
+ if( ! currItem->alreadyListed() )
+ {
+ /* start the lister */
+ ret = openURL( url, true );
+ }
+ else
+ {
+ kdDebug(250) << "Children already existing in treeview!" << endl;
+ slCompleted( url );
+ ret = true;
+ }
+ return ret;
+}
+
+void KFileTreeBranch::virtual_hook( int id, void* data )
+{ KDirLister::virtual_hook( id, data ); }
+
+#include "tdefiletreebranch.moc"
+
diff --git a/tdeio/tdefile/tdefiletreebranch.h b/tdeio/tdefile/tdefiletreebranch.h
new file mode 100644
index 000000000..a8548b10c
--- /dev/null
+++ b/tdeio/tdefile/tdefiletreebranch.h
@@ -0,0 +1,242 @@
+
+/* This file is part of the KDE project
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2001 Klaas Freitag <freitag@suse.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef tdefile_tree_branch_h
+#define tdefile_tree_branch_h
+
+#include <tqdict.h>
+#include <tqlistview.h>
+
+#include <tdefileitem.h>
+#include <tdeio/global.h>
+#include <kdirlister.h>
+#include <tdeio/job.h>
+#include <tdefiletreeviewitem.h>
+
+class KURL;
+class KFileTreeView;
+
+
+/**
+ * This is the branch class of the KFileTreeView, which represents one
+ * branch in the treeview. Every branch has a root which is an url. The branch
+ * lists the files under the root. Every branch uses its own dirlister and can
+ * have its own filter etc.
+ *
+ * @short Branch object for KFileTreeView object.
+ *
+ */
+
+class TDEIO_EXPORT KFileTreeBranch : public KDirLister
+{
+ Q_OBJECT
+public:
+ /**
+ * constructs a branch for KFileTreeView. Does not yet start to list it.
+ * @param url start url of the branch.
+ * @param name the name of the branch, which is displayed in the first column of the treeview.
+ * @param pix is a pixmap to display as an icon of the branch.
+ * @param showHidden flag to make hidden files visible or not.
+ * @param branchRoot is the KFileTreeViewItem to use as the root of the
+ * branch, with the default 0 meaning to let KFileTreeBranch create
+ * it for you.
+ */
+ KFileTreeBranch( KFileTreeView*, const KURL& url, const TQString& name,
+ const TQPixmap& pix, bool showHidden = false,
+ KFileTreeViewItem *branchRoot = 0 );
+
+ /**
+ * @returns the root url of the branch.
+ */
+ KURL rootUrl() const { return( m_startURL ); }
+
+ /**
+ * sets a KFileTreeViewItem as root widget for the branch.
+ * That must be created outside of the branch. All KFileTreeViewItems
+ * the branch is allocating will become children of that object.
+ * @param r the KFileTreeViewItem to become the root item.
+ */
+ virtual void setRoot( KFileTreeViewItem *r ){ m_root = r; };
+
+ /**
+ * @returns the root item.
+ */
+ KFileTreeViewItem *root( ) { return( m_root );}
+
+ /**
+ * @returns the name of the branch.
+ */
+ TQString name() const { return( m_name ); }
+
+ /**
+ * sets the name of the branch.
+ */
+ virtual void setName( const TQString n ) { m_name = n; };
+
+ /*
+ * returns the current root item pixmap set in the constructor. The root
+ * item pixmap defaults to the icon for directories.
+ * @see openPixmap()
+ */
+ const TQPixmap& pixmap(){ return(m_rootIcon); }
+
+ /*
+ * returns the current root item pixmap set by setOpenPixmap()
+ * which is displayed if the branch is expanded.
+ * The root item pixmap defaults to the icon for directories.
+ * @see pixmap()
+ * Note that it depends on KFileTreeView::showFolderOpenPximap weather
+ * open pixmap are displayed or not.
+ */
+ const TQPixmap& openPixmap() { return(m_openRootIcon); }
+
+ /**
+ * @returns whether the items in the branch show their file extensions in the
+ * tree or not. See setShowExtensions for more information.
+ */
+ bool showExtensions( ) const;
+
+ /**
+ * sets the root of the branch open or closed.
+ */
+ void setOpen( bool setopen = true )
+ { if( root() ) root()->setOpen( setopen ); }
+
+ /**
+ * sets if children recursion is wanted or not. If this is switched off, the
+ * child directories of a just opened directory are not listed internally.
+ * That means that it can not be determined if the sub directories are
+ * expandable or not. If this is switched off there will be no call to
+ * setExpandable.
+ * @param t set to true to switch on child recursion
+ */
+ void setChildRecurse( bool t=true );
+
+ /**
+ * @returns if child recursion is on or off.
+ * @see setChildRecurse
+ */
+ bool childRecurse()
+ { return m_recurseChildren; }
+
+public slots:
+ /**
+ * populates a branch. This method must be called after a branch was added
+ * to a KFileTreeView using method addBranch.
+ * @param url is the url of the root item where the branch starts.
+ * @param currItem is the current parent.
+ */
+ virtual bool populate( const KURL &url, KFileTreeViewItem* currItem );
+
+ /**
+ * sets printing of the file extensions on or off. If you pass false to this
+ * slot, all items of this branch will not show their file extensions in the
+ * tree.
+ * @param visible flags if the extensions should be visible or not.
+ */
+ virtual void setShowExtensions( bool visible = true );
+
+ void setOpenPixmap( const TQPixmap& pix );
+
+protected:
+ /**
+ * allocates a KFileTreeViewItem for the branch
+ * for new items.
+ */
+ virtual KFileTreeViewItem *createTreeViewItem( KFileTreeViewItem *parent,
+ KFileItem *fileItem );
+
+public:
+ /**
+ * find the according KFileTreeViewItem by an url
+ */
+ virtual KFileTreeViewItem *findTVIByURL( const KURL& );
+
+signals:
+ /**
+ * emitted with the item of a directory which was finished to populate
+ */
+ void populateFinished( KFileTreeViewItem * );
+
+ /**
+ * emitted with a list of new or updated KFileTreeViewItem which were
+ * found in a branch. Note that this signal is emitted very often and may slow
+ * down the performance of the treeview !
+ */
+ void newTreeViewItems( KFileTreeBranch*, const KFileTreeViewItemList& );
+
+ /**
+ * emitted with the exact count of children for a directory.
+ */
+ void directoryChildCount( KFileTreeViewItem* item, int count );
+
+private slots:
+ void slotRefreshItems( const KFileItemList& );
+ void addItems( const KFileItemList& );
+ void slCompleted( const KURL& );
+ void slotCanceled( const KURL& );
+ void slotListerStarted( const KURL& );
+ void slotDeleteItem( KFileItem* );
+ void slotDirlisterClear();
+ void slotDirlisterClearURL( const KURL& url );
+ void slotRedirect( const KURL& oldUrl, const KURL&newUrl );
+
+private:
+ KFileTreeViewItem *parentKFTVItem( KFileItem *item );
+ static void deleteChildrenOf( TQListViewItem *parent );
+
+ KFileTreeViewItem *m_root;
+ KURL m_startURL;
+ TQString m_name;
+ TQPixmap m_rootIcon;
+ TQPixmap m_openRootIcon;
+
+ /* this list holds the url's which children are opened. */
+ KURL::List m_openChildrenURLs;
+
+
+ /* The next two members are used for caching purposes in findTVIByURL. */
+ KURL m_lastFoundURL;
+ KFileTreeViewItem *m_lastFoundItem;
+
+ bool m_recurseChildren :1;
+ bool m_showExtensions :1;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KFileTreeBranchPrivate;
+ KFileTreeBranchPrivate *d;
+};
+
+
+/**
+ * List of KFileTreeBranches
+ */
+typedef TQPtrList<KFileTreeBranch> KFileTreeBranchList;
+
+/**
+ * Iterator for KFileTreeBranchLists
+ */
+typedef TQPtrListIterator<KFileTreeBranch> KFileTreeBranchIterator;
+
+#endif
+
diff --git a/tdeio/tdefile/tdefiletreeview.cpp b/tdeio/tdefile/tdefiletreeview.cpp
new file mode 100644
index 000000000..480c58ec3
--- /dev/null
+++ b/tdeio/tdefile/tdefiletreeview.cpp
@@ -0,0 +1,677 @@
+/* This file is part of the KDEproject
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqapplication.h>
+#include <tqheader.h>
+#include <tqtimer.h>
+#include <kdebug.h>
+#include <kdirnotify_stub.h>
+#include <kglobalsettings.h>
+#include <tdefileitem.h>
+#include <tdefileview.h>
+#include <kmimetype.h>
+#include <kstandarddirs.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <tdeio/job.h>
+#include <tdeio/global.h>
+#include <kurldrag.h>
+#include <kiconloader.h>
+
+
+#include "tdefiletreeview.h"
+#include "tdefiletreebranch.h"
+#include "tdefiletreeviewitem.h"
+
+KFileTreeView::KFileTreeView( TQWidget *parent, const char *name )
+ : KListView( parent, name ),
+ m_wantOpenFolderPixmaps( true ),
+ m_toolTip( this )
+{
+ setDragEnabled(true);
+ setSelectionModeExt( KListView::Single );
+
+ m_animationTimer = new TQTimer( this );
+ connect( m_animationTimer, TQT_SIGNAL( timeout() ),
+ this, TQT_SLOT( slotAnimation() ) );
+
+ m_currentBeforeDropItem = 0;
+ m_dropItem = 0;
+
+ m_autoOpenTimer = new TQTimer( this );
+ connect( m_autoOpenTimer, TQT_SIGNAL( timeout() ),
+ this, TQT_SLOT( slotAutoOpenFolder() ) );
+
+ /* The executed-Slot only opens a path, while the expanded-Slot populates it */
+ connect( this, TQT_SIGNAL( executed( TQListViewItem * ) ),
+ this, TQT_SLOT( slotExecuted( TQListViewItem * ) ) );
+ connect( this, TQT_SIGNAL( expanded ( TQListViewItem *) ),
+ this, TQT_SLOT( slotExpanded( TQListViewItem *) ));
+ connect( this, TQT_SIGNAL( collapsed( TQListViewItem *) ),
+ this, TQT_SLOT( slotCollapsed( TQListViewItem* )));
+
+
+ /* connections from the konqtree widget */
+ connect( this, TQT_SIGNAL( selectionChanged() ),
+ this, TQT_SLOT( slotSelectionChanged() ) );
+ connect( this, TQT_SIGNAL( onItem( TQListViewItem * )),
+ this, TQT_SLOT( slotOnItem( TQListViewItem * ) ) );
+ connect( this, TQT_SIGNAL(itemRenamed(TQListViewItem*, const TQString &, int)),
+ this, TQT_SLOT(slotItemRenamed(TQListViewItem*, const TQString &, int)));
+
+
+ m_bDrag = false;
+ m_branches.setAutoDelete( true );
+
+ m_openFolderPixmap = DesktopIcon( "folder_open",KIcon::SizeSmall,KIcon::ActiveState );
+}
+
+KFileTreeView::~KFileTreeView()
+{
+ // we must make sure that the KFileTreeViewItems are deleted _before_ the
+ // branches are deleted. Otherwise, the KFileItems would be destroyed
+ // and the KFileTreeViewItems had dangling pointers to them.
+ hide();
+ clear();
+ m_branches.clear(); // finally delete the branches and KFileItems
+}
+
+
+bool KFileTreeView::isValidItem( TQListViewItem *item)
+{
+ if (!item)
+ return false;
+ TQPtrList<TQListViewItem> lst;
+ TQListViewItemIterator it( this );
+ while ( it.current() )
+ {
+ if ( it.current() == item )
+ return true;
+ ++it;
+ }
+ return false;
+}
+
+void KFileTreeView::contentsDragEnterEvent( TQDragEnterEvent *ev )
+{
+ if ( ! acceptDrag( ev ) )
+ {
+ ev->ignore();
+ return;
+ }
+ ev->acceptAction();
+ m_currentBeforeDropItem = selectedItem();
+
+ TQListViewItem *item = itemAt( contentsToViewport( ev->pos() ) );
+ if( item )
+ {
+ m_dropItem = item;
+ m_autoOpenTimer->start( KFileView::autoOpenDelay() );
+ }
+ else
+ {
+ m_dropItem = 0;
+}
+}
+
+void KFileTreeView::contentsDragMoveEvent( TQDragMoveEvent *e )
+{
+ if( ! acceptDrag( e ) )
+ {
+ e->ignore();
+ return;
+ }
+ e->acceptAction();
+
+
+ TQListViewItem *afterme;
+ TQListViewItem *parent;
+
+ findDrop( e->pos(), parent, afterme );
+
+ // "afterme" is 0 when aiming at a directory itself
+ TQListViewItem *item = afterme ? afterme : parent;
+
+ if( item && item->isSelectable() )
+ {
+ setSelected( item, true );
+ if( item != m_dropItem ) {
+ m_autoOpenTimer->stop();
+ m_dropItem = item;
+ m_autoOpenTimer->start( KFileView::autoOpenDelay() );
+ }
+ }
+ else
+ {
+ m_autoOpenTimer->stop();
+ m_dropItem = 0;
+ }
+}
+
+void KFileTreeView::contentsDragLeaveEvent( TQDragLeaveEvent * )
+{
+ // Restore the current item to what it was before the dragging (#17070)
+ if ( isValidItem(m_currentBeforeDropItem) )
+ {
+ setSelected( m_currentBeforeDropItem, true );
+ ensureItemVisible( m_currentBeforeDropItem );
+ }
+ else if ( isValidItem(m_dropItem) )
+ setSelected( m_dropItem, false ); // no item selected
+ m_currentBeforeDropItem = 0;
+ m_dropItem = 0;
+
+}
+
+void KFileTreeView::contentsDropEvent( TQDropEvent *e )
+{
+
+ m_autoOpenTimer->stop();
+ m_dropItem = 0;
+
+ kdDebug(250) << "contentsDropEvent !" << endl;
+ if( ! acceptDrag( e ) ) {
+ e->ignore();
+ return;
+ }
+
+ e->acceptAction();
+ TQListViewItem *afterme;
+ TQListViewItem *parent;
+ findDrop(e->pos(), parent, afterme);
+
+ //kdDebug(250) << " parent=" << (parent?parent->text(0):TQString::null)
+ // << " afterme=" << (afterme?afterme->text(0):TQString::null) << endl;
+
+ if (e->source() == viewport() && itemsMovable())
+ movableDropEvent(parent, afterme);
+ else
+ {
+ emit dropped(e, afterme);
+ emit dropped(this, e, afterme);
+ emit dropped(e, parent, afterme);
+ emit dropped(this, e, parent, afterme);
+
+ KURL::List urls;
+ KURLDrag::decode( e, urls );
+ emit dropped( this, e, urls );
+
+ KURL parentURL;
+ if( parent )
+ parentURL = static_cast<KFileTreeViewItem*>(parent)->url();
+ else
+ // can happen when dropping above the root item
+ // Should we choose the first branch in such a case ??
+ return;
+
+ emit dropped( urls, parentURL );
+ emit dropped( this , e, urls, parentURL );
+ }
+}
+
+bool KFileTreeView::acceptDrag(TQDropEvent* e ) const
+{
+
+ bool ancestOK= acceptDrops();
+ // kdDebug(250) << "Do accept drops: " << ancestOK << endl;
+ ancestOK = ancestOK && itemsMovable();
+ // kdDebug(250) << "acceptDrag: " << ancestOK << endl;
+ // kdDebug(250) << "canDecode: " << KURLDrag::canDecode(e) << endl;
+ // kdDebug(250) << "action: " << e->action() << endl;
+
+ /* KListView::acceptDrag(e); */
+ /* this is what KListView does:
+ * acceptDrops() && itemsMovable() && (e->source()==viewport());
+ * ask acceptDrops and itemsMovable, but not the third
+ */
+ return ancestOK && KURLDrag::canDecode( e ) &&
+ // Why this test? All DnDs are one of those AFAIK (DF)
+ ( e->action() == TQDropEvent::Copy
+ || e->action() == TQDropEvent::Move
+ || e->action() == TQDropEvent::Link );
+}
+
+
+
+TQDragObject * KFileTreeView::dragObject()
+{
+
+ KURL::List urls;
+ const TQPtrList<TQListViewItem> fileList = selectedItems();
+ TQPtrListIterator<TQListViewItem> it( fileList );
+ for ( ; it.current(); ++it )
+ {
+ urls.append( static_cast<KFileTreeViewItem*>(it.current())->url() );
+ }
+ TQPoint hotspot;
+ TQPixmap pixmap;
+ if( urls.count() > 1 ){
+ pixmap = DesktopIcon( "tdemultiple", 16 );
+ }
+ if( pixmap.isNull() )
+ pixmap = currentKFileTreeViewItem()->fileItem()->pixmap( 16 );
+ hotspot.setX( pixmap.width() / 2 );
+ hotspot.setY( pixmap.height() / 2 );
+ TQDragObject* dragObject = new KURLDrag( urls, this );
+ if( dragObject )
+ dragObject->setPixmap( pixmap, hotspot );
+ return dragObject;
+}
+
+
+
+void KFileTreeView::slotCollapsed( TQListViewItem *item )
+{
+ KFileTreeViewItem *kftvi = static_cast<KFileTreeViewItem*>(item);
+ kdDebug(250) << "hit slotCollapsed" << endl;
+ if( kftvi && kftvi->isDir())
+ {
+ item->setPixmap( 0, itemIcon(kftvi));
+ }
+}
+
+void KFileTreeView::slotExpanded( TQListViewItem *item )
+{
+ kdDebug(250) << "slotExpanded here !" << endl;
+
+ if( ! item ) return;
+
+ KFileTreeViewItem *it = static_cast<KFileTreeViewItem*>(item);
+ KFileTreeBranch *branch = it->branch();
+
+ /* Start the animation for the branch object */
+ if( it->isDir() && branch && item->childCount() == 0 )
+ {
+ /* check here if the branch really needs to be populated again */
+ kdDebug(250 ) << "starting to open " << it->url().prettyURL() << endl;
+ startAnimation( it );
+ bool branchAnswer = branch->populate( it->url(), it );
+ kdDebug(250) << "Branches answer: " << branchAnswer << endl;
+ if( ! branchAnswer )
+ {
+ kdDebug(250) << "ERR: Could not populate!" << endl;
+ stopAnimation( it );
+ }
+ }
+
+ /* set a pixmap 'open folder' */
+ if( it->isDir() && isOpen( item ) )
+ {
+ kdDebug(250)<< "Setting open Pixmap" << endl;
+ item->setPixmap( 0, itemIcon( it )); // 0, m_openFolderPixmap );
+ }
+}
+
+
+
+void KFileTreeView::slotExecuted( TQListViewItem *item )
+{
+ if ( !item )
+ return;
+ /* This opens the dir and causes the Expanded-slot to be called,
+ * which strolls through the children.
+ */
+ if( static_cast<KFileTreeViewItem*>(item)->isDir())
+ {
+ item->setOpen( !item->isOpen() );
+ }
+}
+
+
+void KFileTreeView::slotAutoOpenFolder()
+{
+ m_autoOpenTimer->stop();
+
+ if ( !isValidItem(m_dropItem) || m_dropItem->isOpen() )
+ return;
+
+ m_dropItem->setOpen( true );
+ m_dropItem->repaint();
+}
+
+
+void KFileTreeView::slotSelectionChanged()
+{
+ if ( !m_dropItem ) // don't do this while the dragmove thing
+ {
+ }
+}
+
+
+KFileTreeBranch* KFileTreeView::addBranch( const KURL &path, const TQString& name,
+ bool showHidden )
+{
+ const TQPixmap& folderPix = KMimeType::mimeType("inode/directory")->pixmap( KIcon::Desktop,KIcon::SizeSmall );
+
+ return addBranch( path, name, folderPix, showHidden);
+}
+
+KFileTreeBranch* KFileTreeView::addBranch( const KURL &path, const TQString& name,
+ const TQPixmap& pix, bool showHidden )
+{
+ kdDebug(250) << "adding another root " << path.prettyURL() << endl;
+
+ /* Open a new branch */
+ KFileTreeBranch *newBranch = new KFileTreeBranch( this, path, name, pix,
+ showHidden );
+ return addBranch(newBranch);
+}
+
+KFileTreeBranch *KFileTreeView::addBranch(KFileTreeBranch *newBranch)
+{
+ connect( newBranch, TQT_SIGNAL(populateFinished( KFileTreeViewItem* )),
+ this, TQT_SLOT( slotPopulateFinished( KFileTreeViewItem* )));
+
+ connect( newBranch, TQT_SIGNAL( newTreeViewItems( KFileTreeBranch*,
+ const KFileTreeViewItemList& )),
+ this, TQT_SLOT( slotNewTreeViewItems( KFileTreeBranch*,
+ const KFileTreeViewItemList& )));
+
+ m_branches.append( newBranch );
+ return( newBranch );
+}
+
+KFileTreeBranch *KFileTreeView::branch( const TQString& searchName )
+{
+ KFileTreeBranch *branch = 0;
+ TQPtrListIterator<KFileTreeBranch> it( m_branches );
+
+ while ( (branch = it.current()) != 0 ) {
+ ++it;
+ TQString bname = branch->name();
+ kdDebug(250) << "This is the branches name: " << bname << endl;
+ if( bname == searchName )
+ {
+ kdDebug(250) << "Found branch " << bname << " and return ptr" << endl;
+ return( branch );
+ }
+ }
+ return ( 0L );
+}
+
+KFileTreeBranchList& KFileTreeView::branches()
+{
+ return( m_branches );
+}
+
+
+bool KFileTreeView::removeBranch( KFileTreeBranch *branch )
+{
+ if(m_branches.contains(branch))
+ {
+ delete (branch->root());
+ m_branches.remove( branch );
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+}
+
+void KFileTreeView::setDirOnlyMode( KFileTreeBranch* branch, bool bom )
+{
+ if( branch )
+ {
+ branch->setDirOnlyMode( bom );
+ }
+}
+
+
+void KFileTreeView::slotPopulateFinished( KFileTreeViewItem *it )
+{
+ if( it && it->isDir())
+ stopAnimation( it );
+}
+
+void KFileTreeView::slotNewTreeViewItems( KFileTreeBranch* branch, const KFileTreeViewItemList& itemList )
+{
+ if( ! branch ) return;
+ kdDebug(250) << "hitting slotNewTreeViewItems" << endl;
+
+ /* Sometimes it happens that new items should become selected, i.e. if the user
+ * creates a new dir, he probably wants it to be selected. This can not be done
+ * right after creating the directory or file, because it takes some time until
+ * the item appears here in the treeview. Thus, the creation code sets the member
+ * m_neUrlToSelect to the required url. If this url appears here, the item becomes
+ * selected and the member nextUrlToSelect will be cleared.
+ */
+ if( ! m_nextUrlToSelect.isEmpty() )
+ {
+ KFileTreeViewItemListIterator it( itemList );
+
+ bool end = false;
+ for( ; !end && it.current(); ++it )
+ {
+ KURL url = (*it)->url();
+
+ if( m_nextUrlToSelect.equals(url, true )) // ignore trailing / on dirs
+ {
+ setCurrentItem( static_cast<TQListViewItem*>(*it) );
+ m_nextUrlToSelect = KURL();
+ end = true;
+ }
+ }
+ }
+}
+
+TQPixmap KFileTreeView::itemIcon( KFileTreeViewItem *item, int gap ) const
+{
+ TQPixmap pix;
+ kdDebug(250) << "Setting icon for column " << gap << endl;
+
+ if( item )
+ {
+ /* Check if it is a branch root */
+ KFileTreeBranch *brnch = item->branch();
+ if( item == brnch->root() )
+ {
+ pix = brnch->pixmap();
+ if( m_wantOpenFolderPixmaps && brnch->root()->isOpen() )
+ {
+ pix = brnch->openPixmap();
+ }
+ }
+ else
+ {
+ // TODO: different modes, user Pixmaps ?
+ pix = item->fileItem()->pixmap( KIcon::SizeSmall ); // , KIcon::DefaultState);
+
+ /* Only if it is a dir and the user wants open dir pixmap and it is open,
+ * change the fileitem's pixmap to the open folder pixmap. */
+ if( item->isDir() && m_wantOpenFolderPixmaps )
+ {
+ if( isOpen( static_cast<TQListViewItem*>(item)))
+ pix = m_openFolderPixmap;
+ }
+ }
+ }
+
+ return pix;
+}
+
+
+void KFileTreeView::slotAnimation()
+{
+ MapCurrentOpeningFolders::Iterator it = m_mapCurrentOpeningFolders.begin();
+ MapCurrentOpeningFolders::Iterator end = m_mapCurrentOpeningFolders.end();
+ for (; it != end;)
+ {
+ KFileTreeViewItem *item = it.key();
+ if (!isValidItem(item))
+ {
+ ++it;
+ m_mapCurrentOpeningFolders.remove(item);
+ continue;
+ }
+
+ uint & iconNumber = it.data().iconNumber;
+ TQString icon = TQString::fromLatin1( it.data().iconBaseName ).append( TQString::number( iconNumber ) );
+ // kdDebug(250) << "Loading icon " << icon << endl;
+ item->setPixmap( 0, DesktopIcon( icon,KIcon::SizeSmall,KIcon::ActiveState )); // KFileTreeViewFactory::instance() ) );
+
+ iconNumber++;
+ if ( iconNumber > it.data().iconCount )
+ iconNumber = 1;
+
+ ++it;
+ }
+}
+
+
+void KFileTreeView::startAnimation( KFileTreeViewItem * item, const char * iconBaseName, uint iconCount )
+{
+ /* TODO: allow specific icons */
+ if( ! item )
+ {
+ kdDebug(250) << " startAnimation Got called without valid item !" << endl;
+ return;
+ }
+
+ m_mapCurrentOpeningFolders.insert( item,
+ AnimationInfo( iconBaseName,
+ iconCount,
+ itemIcon(item, 0) ) );
+ if ( !m_animationTimer->isActive() )
+ m_animationTimer->start( 50 );
+}
+
+void KFileTreeView::stopAnimation( KFileTreeViewItem * item )
+{
+ if( ! item ) return;
+
+ kdDebug(250) << "Stoping Animation !" << endl;
+
+ MapCurrentOpeningFolders::Iterator it = m_mapCurrentOpeningFolders.find(item);
+ if ( it != m_mapCurrentOpeningFolders.end() )
+ {
+ if( item->isDir() && isOpen( item) )
+ {
+ kdDebug(250) << "Setting folder open pixmap !" << endl;
+ item->setPixmap( 0, itemIcon( item ));
+ }
+ else
+ {
+ item->setPixmap( 0, it.data().originalPixmap );
+ }
+ m_mapCurrentOpeningFolders.remove( item );
+ }
+ else
+ {
+ if( item )
+ kdDebug(250)<< "StopAnimation - could not find item " << item->url().prettyURL()<< endl;
+ else
+ kdDebug(250)<< "StopAnimation - item is zero !" << endl;
+ }
+ if (m_mapCurrentOpeningFolders.isEmpty())
+ m_animationTimer->stop();
+}
+
+KFileTreeViewItem * KFileTreeView::currentKFileTreeViewItem() const
+{
+ return static_cast<KFileTreeViewItem *>( selectedItem() );
+}
+
+KURL KFileTreeView::currentURL() const
+{
+ KFileTreeViewItem *item = currentKFileTreeViewItem();
+ if ( item )
+ return currentKFileTreeViewItem()->url();
+ else
+ return KURL();
+}
+
+void KFileTreeView::slotOnItem( TQListViewItem *item )
+{
+ KFileTreeViewItem *i = static_cast<KFileTreeViewItem *>( item );
+ if( i )
+ {
+ const KURL url = i->url();
+ if ( url.isLocalFile() )
+ emit onItem( url.path() );
+ else
+ emit onItem( url.prettyURL() );
+ }
+}
+
+void KFileTreeView::slotItemRenamed(TQListViewItem* item, const TQString &name, int col)
+{
+ (void) item;
+ kdDebug(250) << "Do not bother: " << name << col << endl;
+}
+
+KFileTreeViewItem *KFileTreeView::findItem( const TQString& branchName, const TQString& relUrl )
+{
+ KFileTreeBranch *br = branch( branchName );
+ return( findItem( br, relUrl ));
+}
+
+KFileTreeViewItem *KFileTreeView::findItem( KFileTreeBranch* brnch, const TQString& relUrl )
+{
+ KFileTreeViewItem *ret = 0;
+ if( brnch )
+ {
+ KURL url = brnch->rootUrl();
+
+ if( ! relUrl.isEmpty() && TQDir::isRelativePath(relUrl) )
+ {
+ TQString partUrl( relUrl );
+
+ if( partUrl.endsWith("/"))
+ partUrl.truncate( relUrl.length()-1 );
+
+ url.addPath( partUrl );
+
+ kdDebug(250) << "assembled complete dir string " << url.prettyURL() << endl;
+
+ KFileItem *fi = brnch->findByURL( url );
+ if( fi )
+ {
+ ret = static_cast<KFileTreeViewItem*>( fi->extraData( brnch ));
+ kdDebug(250) << "Found item !" <<ret << endl;
+ }
+ }
+ else
+ {
+ ret = brnch->root();
+ }
+ }
+ return( ret );
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+void KFileTreeViewToolTip::maybeTip( const TQPoint & )
+{
+#if 0
+ TQListViewItem *item = m_view->itemAt( point );
+ if ( item ) {
+ TQString text = static_cast<KFileViewItem*>( item )->toolTipText();
+ if ( !text.isEmpty() )
+ tip ( m_view->itemRect( item ), text );
+ }
+#endif
+}
+
+void KFileTreeView::virtual_hook( int id, void* data )
+{ KListView::virtual_hook( id, data ); }
+
+#include "tdefiletreeview.moc"
diff --git a/tdeio/tdefile/tdefiletreeview.h b/tdeio/tdefile/tdefiletreeview.h
new file mode 100644
index 000000000..11d695288
--- /dev/null
+++ b/tdeio/tdefile/tdefiletreeview.h
@@ -0,0 +1,273 @@
+/* This file is part of the KDE project
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2002 Klaas Freitag <freitag@suse.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef tdefile_tree_view_h
+#define tdefile_tree_view_h
+
+#include <tqmap.h>
+#include <tqpoint.h>
+#include <tqpixmap.h>
+#include <tqstrlist.h>
+#include <tqtooltip.h>
+
+#include <klistview.h>
+#include <kdirnotify.h>
+#include <tdeio/job.h>
+#include <tdefiletreeviewitem.h>
+#include <tdefiletreebranch.h>
+
+class TQTimer;
+
+
+
+class TDEIO_EXPORT KFileTreeViewToolTip : public TQToolTip
+{
+public:
+ KFileTreeViewToolTip( TQListView *view ) : TQToolTip( view ), m_view( view ) {}
+
+protected:
+ virtual void maybeTip( const TQPoint & );
+
+private:
+ TQListView *m_view;
+};
+
+
+/**
+ * The filetreeview offers a treeview on the file system which behaves like
+ * a QTreeView showing files and/or directories in the file system.
+ *
+ * KFileTreeView is able to handle more than one URL, represented by
+ * KFileTreeBranch.
+ *
+ * Typical usage:
+ * 1. create a KFileTreeView fitting in your layout and add columns to it
+ * 2. call addBranch to create one or more branches
+ * 3. retrieve the root item with KFileTreeBranch::root() and set it open
+ * if desired. That starts the listing.
+ */
+class TDEIO_EXPORT KFileTreeView : public KListView
+{
+ Q_OBJECT
+public:
+ KFileTreeView( TQWidget *parent, const char *name = 0 );
+ virtual ~KFileTreeView();
+
+ /**
+ * @return the current (i.e. selected) item
+ */
+ KFileTreeViewItem * currentKFileTreeViewItem() const;
+
+ /**
+ * @return the URL of the current selected item.
+ */
+ KURL currentURL() const;
+
+ /**
+ * Adds a branch to the treeview item.
+ *
+ * This high-level function creates the branch, adds it to the treeview and
+ * connects some signals. Note that directory listing does not start until
+ * a branch is expanded either by opening the root item by user or by setOpen
+ * on the root item.
+ *
+ * @returns a pointer to the new branch or zero
+ * @param path is the base url of the branch
+ * @param name is the name of the branch, which will be the text for column 0
+ * @param showHidden says if hidden files and directories should be visible
+ */
+ KFileTreeBranch* addBranch( const KURL &path, const TQString& name, bool showHidden = false );
+
+ /**
+ * same as the function above but with a pixmap to set for the branch.
+ */
+ virtual KFileTreeBranch* addBranch( const KURL &path, const TQString& name ,
+ const TQPixmap& pix, bool showHidden = false );
+
+ /**
+ * same as the function above but letting the user create the branch.
+ */
+ virtual KFileTreeBranch* addBranch( KFileTreeBranch * );
+
+ /**
+ * removes the branch from the treeview.
+ * @param branch is a pointer to the branch
+ * @returns true on success.
+ */
+ virtual bool removeBranch( KFileTreeBranch *branch );
+
+ /**
+ * @returns a pointer to the KFileTreeBranch in the KFileTreeView or zero on failure.
+ * @param searchName is the name of a branch
+ */
+ KFileTreeBranch *branch( const TQString& searchName );
+
+
+ /**
+ * @returns a list of pointers to all existing branches in the treeview.
+ **/
+ KFileTreeBranchList& branches();
+
+ /**
+ * set the directory mode for branches. If true is passed, only directories will be loaded.
+ * @param branch is a pointer to a KFileTreeBranch
+ */
+ virtual void setDirOnlyMode( KFileTreeBranch *branch, bool );
+
+ /**
+ * searches a branch for a KFileTreeViewItem identified by the relative url given as
+ * second parameter. The method adds the branches base url to the relative path and finds
+ * the item.
+ * @returns a pointer to the item or zero if the item does not exist.
+ * @param brnch is a pointer to the branch to search in
+ * @param relUrl is the branch relativ url
+ */
+ KFileTreeViewItem *findItem( KFileTreeBranch* brnch, const TQString& relUrl );
+
+ /**
+ * see method above, differs only in the first parameter. Finds the branch by its name.
+ */
+ KFileTreeViewItem *findItem( const TQString& branchName, const TQString& relUrl );
+
+ /**
+ * @returns a flag indicating if extended folder pixmaps are displayed or not.
+ */
+ bool showFolderOpenPixmap() const { return m_wantOpenFolderPixmaps; };
+
+public slots:
+
+ /**
+ * set the flag to show 'extended' folder icons on or off. If switched on, folders will
+ * have an open folder pixmap displayed if their children are visible, and the standard
+ * closed folder pixmap (from mimetype folder) if they are closed.
+ * If switched off, the plain mime pixmap is displayed.
+ * @param showIt = false displays mime type pixmap only
+ */
+ virtual void setShowFolderOpenPixmap( bool showIt = true )
+ { m_wantOpenFolderPixmaps = showIt; }
+
+protected:
+ /**
+ * @returns true if we can decode the drag and support the action
+ */
+
+ virtual bool acceptDrag(TQDropEvent* event) const;
+ virtual TQDragObject * dragObject();
+
+ virtual void startAnimation( KFileTreeViewItem* item, const char * iconBaseName = "kde", uint iconCount = 6 );
+ virtual void stopAnimation( KFileTreeViewItem* item );
+ virtual void contentsDragEnterEvent( TQDragEnterEvent *e );
+ virtual void contentsDragMoveEvent( TQDragMoveEvent *e );
+ virtual void contentsDragLeaveEvent( TQDragLeaveEvent *e );
+ virtual void contentsDropEvent( TQDropEvent *ev );
+
+protected slots:
+ virtual void slotNewTreeViewItems( KFileTreeBranch*,
+ const KFileTreeViewItemList& );
+
+ virtual void slotSetNextUrlToSelect( const KURL &url )
+ { m_nextUrlToSelect = url; }
+
+ virtual TQPixmap itemIcon( KFileTreeViewItem*, int gap = 0 ) const;
+
+private slots:
+ void slotExecuted( TQListViewItem * );
+ void slotExpanded( TQListViewItem * );
+ void slotCollapsed( TQListViewItem *item );
+
+ void slotSelectionChanged();
+
+ void slotAnimation();
+
+ void slotAutoOpenFolder();
+
+ void slotOnItem( TQListViewItem * );
+ void slotItemRenamed(TQListViewItem*, const TQString &, int);
+
+ void slotPopulateFinished( KFileTreeViewItem* );
+
+
+signals:
+
+ void onItem( const TQString& );
+ /* New signals if you like it ? */
+ void dropped( TQWidget*, TQDropEvent* );
+ void dropped( TQWidget*, TQDropEvent*, KURL::List& );
+ void dropped( KURL::List&, KURL& );
+ // The drop event allows to differentiate between move and copy
+ void dropped( TQWidget*, TQDropEvent*, KURL::List&, KURL& );
+
+ void dropped( TQDropEvent *e, TQListViewItem * after);
+ void dropped(KFileTreeView *, TQDropEvent *, TQListViewItem *);
+ void dropped(TQDropEvent *e, TQListViewItem * parent, TQListViewItem * after);
+ void dropped(KFileTreeView *, TQDropEvent *, TQListViewItem *, TQListViewItem *);
+
+protected:
+ KURL m_nextUrlToSelect;
+
+
+private:
+ // Returns whether item is still a valid item in the tree
+ bool isValidItem( TQListViewItem *item);
+ void clearTree();
+
+
+ /* List that holds the branches */
+ KFileTreeBranchList m_branches;
+
+
+ struct AnimationInfo
+ {
+ AnimationInfo( const char * _iconBaseName, uint _iconCount, const TQPixmap & _originalPixmap )
+ : iconBaseName(_iconBaseName), iconCount(_iconCount), iconNumber(1), originalPixmap(_originalPixmap) {}
+ AnimationInfo() : iconCount(0) {}
+ TQCString iconBaseName;
+ uint iconCount;
+ uint iconNumber;
+ TQPixmap originalPixmap;
+ };
+ typedef TQMap<KFileTreeViewItem *, AnimationInfo> MapCurrentOpeningFolders;
+ MapCurrentOpeningFolders m_mapCurrentOpeningFolders;
+
+
+ TQTimer *m_animationTimer;
+
+ TQPoint m_dragPos;
+ bool m_bDrag;
+
+ bool m_wantOpenFolderPixmaps; // Flag weather the folder should have open-folder pixmaps
+
+ TQListViewItem *m_currentBeforeDropItem; // The item that was current before the drag-enter event happened
+ TQListViewItem *m_dropItem; // The item we are moving the mouse over (during a drag)
+ TQStrList m_lstDropFormats;
+ TQPixmap m_openFolderPixmap;
+ TQTimer *m_autoOpenTimer;
+
+ KFileTreeViewToolTip m_toolTip;
+
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KFileTreeViewPrivate;
+ KFileTreeViewPrivate *d;
+};
+
+#endif
diff --git a/tdeio/tdefile/tdefiletreeviewitem.cpp b/tdeio/tdefile/tdefiletreeviewitem.cpp
new file mode 100644
index 000000000..4df2daaa1
--- /dev/null
+++ b/tdeio/tdefile/tdefiletreeviewitem.cpp
@@ -0,0 +1,83 @@
+/* This file is part of the KDEproject
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <kdebug.h>
+#include <tdefileitem.h>
+#include <kicontheme.h>
+
+#include "tdefiletreeviewitem.h"
+
+/* --- KFileTreeViewItem --- */
+/*
+ */
+KFileTreeViewItem::KFileTreeViewItem( KFileTreeViewItem *parent,
+ KFileItem* item,
+ KFileTreeBranch *brnch )
+ : KListViewItem( parent ),
+ m_tdefileitem( item ),
+ m_branch( brnch ),
+ m_wasListed(false)
+{
+ setPixmap(0, item->pixmap( KIcon::SizeSmall ));
+ setText( 0, item->text());
+
+}
+
+KFileTreeViewItem::KFileTreeViewItem( KFileTreeView* parent,
+ KFileItem* item,
+ KFileTreeBranch *brnch )
+ :KListViewItem( (TQListView*)parent ),
+ m_tdefileitem(item ),
+ m_branch( brnch ),
+ m_wasListed(false)
+{
+ setPixmap(0, item->pixmap( KIcon::SizeSmall ));
+ setText( 0, item->text());
+}
+
+KFileTreeViewItem::~KFileTreeViewItem()
+{
+ if ( m_tdefileitem )
+ m_tdefileitem->removeExtraData( m_branch );
+}
+
+bool KFileTreeViewItem::alreadyListed() const
+{
+ return m_wasListed;
+}
+
+void KFileTreeViewItem::setListed( bool wasListed )
+{
+ m_wasListed = wasListed;
+}
+
+KURL KFileTreeViewItem::url() const
+{
+ return m_tdefileitem ? m_tdefileitem->url() : KURL();
+}
+
+TQString KFileTreeViewItem::path() const
+{
+ return m_tdefileitem ? m_tdefileitem->url().path() : TQString::null;
+}
+
+bool KFileTreeViewItem::isDir() const
+{
+ return m_tdefileitem ? m_tdefileitem->isDir() : false;
+}
diff --git a/tdeio/tdefile/tdefiletreeviewitem.h b/tdeio/tdefile/tdefiletreeviewitem.h
new file mode 100644
index 000000000..8fdb2789c
--- /dev/null
+++ b/tdeio/tdefile/tdefiletreeviewitem.h
@@ -0,0 +1,106 @@
+/* This file is part of the KDE project
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef tdefile_tree_view_item_h
+#define tdefile_tree_view_item_h
+
+#include <tqptrlist.h>
+#include <klistview.h>
+
+#include <tdefileitem.h>
+#include <tdeio/global.h>
+#include <kdirlister.h>
+#include <tdeio/job.h>
+
+class KURL;
+class KFileTreeView;
+class KFileTreeBranch;
+class KFileTreeItem;
+
+
+/**
+ * An item for a KFileTreeView that knows about its own KFileItem.
+ */
+class TDEIO_EXPORT KFileTreeViewItem : public KListViewItem
+{
+public:
+ KFileTreeViewItem( KFileTreeViewItem*, KFileItem*, KFileTreeBranch * );
+ KFileTreeViewItem( KFileTreeView*, KFileItem*, KFileTreeBranch * );
+ ~KFileTreeViewItem();
+
+ /**
+ * @return the KFileTreeBranch the item is sorted in.
+ */
+ KFileTreeBranch* branch() const { return m_branch; }
+
+ /**
+ * @return the KFileItem the viewitem is representing.
+ */
+ KFileItem *fileItem() const { return m_tdefileitem; }
+
+ /**
+ * @return the path of the item.
+ */
+ TQString path() const;
+
+ /**
+ * @return the items KURL
+ */
+ KURL url() const;
+
+ /**
+ * @return if the item represents a directory
+ */
+ bool isDir() const;
+
+ /**
+ * @return if this directory was already seen by a KDirLister.
+ */
+ bool alreadyListed() const;
+
+ /**
+ * set the flag if the directory was already listed.
+ */
+ void setListed( bool wasListed );
+
+protected:
+
+private:
+
+ KFileItem *m_tdefileitem;
+ KFileTreeBranch *m_branch;
+ bool m_wasListed;
+ class KFileTreeViewItemPrivate;
+ KFileTreeViewItemPrivate *d;
+};
+
+
+/**
+ * List of KFileTreeViewItems
+ */
+typedef TQPtrList<KFileTreeViewItem> KFileTreeViewItemList;
+
+/**
+ * Iterator for KFileTreeViewItemList
+ */
+typedef TQPtrListIterator<KFileTreeViewItem> KFileTreeViewItemListIterator;
+
+
+#endif
+
diff --git a/tdeio/tdefile/tdefileview.cpp b/tdeio/tdefile/tdefileview.cpp
new file mode 100644
index 000000000..558053cc8
--- /dev/null
+++ b/tdeio/tdefile/tdefileview.cpp
@@ -0,0 +1,429 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1998 Stephan Kulow <coolo@kde.org>
+ 1998 Daniel Grana <grana@ie.iwi.unibe.ch>
+ 2001 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include <kaction.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kstandarddirs.h>
+
+#include "config-tdefile.h"
+#include "tdefileview.h"
+
+#ifdef Unsorted // the "I hate X.h" modus
+#undef Unsorted
+#endif
+
+TQDir::SortSpec KFileView::defaultSortSpec = static_cast<TQDir::SortSpec>(TQDir::Name | TQDir::IgnoreCase | TQDir::DirsFirst);
+
+class KFileView::KFileViewPrivate
+{
+public:
+ KFileViewPrivate()
+ {
+ actions = 0;
+ dropOptions = 0;
+ }
+
+ ~KFileViewPrivate()
+ {
+ if( actions ) {
+ actions->clear(); // so that the removed() signal is emitted!
+ delete actions;
+ }
+ }
+
+ TQGuardedPtr<KActionCollection> actions;
+ int dropOptions;
+};
+
+
+KFileView::KFileView()
+{
+ d = new KFileViewPrivate();
+ m_sorting = KFileView::defaultSortSpec;
+
+ sig = new KFileViewSignaler();
+ sig->setName("view-signaller");
+
+ m_selectedList = 0L;
+ filesNumber = 0;
+ dirsNumber = 0;
+
+ view_mode = All;
+ selection_mode = KFile::Single;
+ m_viewName = i18n("Unknown View");
+
+ myOnlyDoubleClickSelectsFiles = false;
+ m_itemList.setAutoDelete( false ); // just references
+}
+
+KFileView::~KFileView()
+{
+ delete d;
+ delete sig;
+ delete m_selectedList;
+}
+
+void KFileView::setParentView(KFileView *parent)
+{
+ if ( parent ) { // pass all signals right to our parent
+ TQObject::connect(sig, TQT_SIGNAL( activatedMenu(const KFileItem *,
+ const TQPoint& ) ),
+ parent->sig, TQT_SIGNAL( activatedMenu(const KFileItem *,
+ const TQPoint& )));
+ TQObject::connect(sig, TQT_SIGNAL( dirActivated(const KFileItem *)),
+ parent->sig, TQT_SIGNAL( dirActivated(const KFileItem*)));
+ TQObject::connect(sig, TQT_SIGNAL( fileSelected(const KFileItem *)),
+ parent->sig, TQT_SIGNAL( fileSelected(const KFileItem*)));
+ TQObject::connect(sig, TQT_SIGNAL( fileHighlighted(const KFileItem *) ),
+ parent->sig,TQT_SIGNAL(fileHighlighted(const KFileItem*)));
+ TQObject::connect(sig, TQT_SIGNAL( sortingChanged( TQDir::SortSpec ) ),
+ parent->sig, TQT_SIGNAL(sortingChanged( TQDir::SortSpec)));
+ TQObject::connect(sig, TQT_SIGNAL( dropped(const KFileItem *, TQDropEvent*, const KURL::List&) ),
+ parent->sig, TQT_SIGNAL(dropped(const KFileItem *, TQDropEvent*, const KURL::List&)));
+ }
+}
+
+bool KFileView::updateNumbers(const KFileItem *i)
+{
+ if (!( viewMode() & Files ) && i->isFile())
+ return false;
+
+ if (!( viewMode() & Directories ) && i->isDir())
+ return false;
+
+ if (i->isDir())
+ dirsNumber++;
+ else
+ filesNumber++;
+
+ return true;
+}
+
+void qt_qstring_stats();
+
+// filter out files if we're in directory mode and count files/directories
+// and insert into the view
+void KFileView::addItemList(const KFileItemList& list)
+{
+ KFileItem *tmp;
+
+ for (KFileItemListIterator it(list); (tmp = it.current()); ++it)
+ {
+ if (!updateNumbers(tmp))
+ continue;
+
+ insertItem( tmp );
+ }
+
+#ifdef Q2HELPER
+ qt_qstring_stats();
+#endif
+}
+
+void KFileView::insertItem( KFileItem * )
+{
+}
+
+void KFileView::setSorting(TQDir::SortSpec new_sort)
+{
+ m_sorting = new_sort;
+}
+
+void KFileView::clear()
+{
+ m_itemList.clear();
+ filesNumber = 0;
+ dirsNumber = 0;
+ clearView();
+}
+
+void KFileView::sortReversed()
+{
+ int spec = sorting();
+
+ setSorting( static_cast<TQDir::SortSpec>( spec ^ TQDir::Reversed ) );
+}
+
+#if 0
+int KFileView::compareItems(const KFileItem *fi1, const KFileItem *fi2) const
+{
+ static const TQString &dirup = TDEGlobal::staticQString("..");
+ bool bigger = true;
+ bool keepFirst = false;
+ bool dirsFirst = ((m_sorting & TQDir::DirsFirst) == TQDir::DirsFirst);
+
+ if (fi1 == fi2)
+ return 0;
+
+ // .. is always bigger, independent of the sort criteria
+ if ( fi1->name() == dirup ) {
+ bigger = false;
+ keepFirst = dirsFirst;
+ }
+ else if ( fi2->name() == dirup ) {
+ bigger = true;
+ keepFirst = dirsFirst;
+ }
+
+ else {
+ if ( fi1->isDir() != fi2->isDir() && dirsFirst ) {
+ bigger = fi2->isDir();
+ keepFirst = true;
+ }
+ else {
+
+ TQDir::SortSpec sort = static_cast<TQDir::SortSpec>(m_sorting & TQDir::SortByMask);
+
+ //if (fi1->isDir() || fi2->isDir())
+ // sort = static_cast<TQDir::SortSpec>(KFileView::defaultSortSpec & TQDir::SortByMask);
+
+ switch (sort) {
+ case TQDir::Name:
+ default:
+sort_by_name:
+ if ( (m_sorting & TQDir::IgnoreCase) == TQDir::IgnoreCase )
+ bigger = (fi1->name( true ) > fi2->name( true ));
+ else
+ bigger = (fi1->name() > fi2->name());
+ break;
+ case TQDir::Time:
+ {
+ time_t t1 = fi1->time( TDEIO::UDS_MODIFICATION_TIME );
+ time_t t2 = fi2->time( TDEIO::UDS_MODIFICATION_TIME );
+ if ( t1 != t2 ) {
+ bigger = (t1 > t2);
+ break;
+ }
+
+ // Sort by name if both items have the same timestamp.
+ // Don't honor the reverse flag tho.
+ else {
+ keepFirst = true;
+ goto sort_by_name;
+ }
+ }
+ case TQDir::Size:
+ {
+ TDEIO::filesize_t s1 = fi1->size();
+ TDEIO::filesize_t s2 = fi2->size();
+ if ( s1 != s2 ) {
+ bigger = (s1 > s2);
+ break;
+ }
+
+ // Sort by name if both items have the same size.
+ // Don't honor the reverse flag tho.
+ else {
+ keepFirst = true;
+ goto sort_by_name;
+ }
+ }
+ case TQDir::Unsorted:
+ bigger = true; // nothing
+ break;
+ }
+ }
+ }
+
+ if (reversed && !keepFirst ) // don't reverse dirs to the end!
+ bigger = !bigger;
+
+ return (bigger ? 1 : -1);
+}
+#endif
+
+void KFileView::updateView(bool f)
+{
+ widget()->repaint(f);
+}
+
+void KFileView::updateView(const KFileItem *)
+{
+}
+
+void KFileView::setCurrentItem(const TQString &filename )
+{
+ if (!filename.isNull()) {
+ KFileItem *item;
+ for ( (item = firstFileItem()); item; item = nextItem( item ) ) {
+ if (item->name() == filename) {
+ setCurrentItem( item );
+ return;
+ }
+ }
+ }
+
+ kdDebug(tdefile_area) << "setCurrentItem: no match found: " << filename << endl;
+}
+
+const KFileItemList * KFileView::items() const
+{
+ KFileItem *item = 0L;
+
+ // only ever use m_itemList in this method!
+ m_itemList.clear();
+ for ( (item = firstFileItem()); item; item = nextItem( item ) )
+ m_itemList.append( item );
+
+ return &m_itemList;
+}
+
+
+const KFileItemList * KFileView::selectedItems() const
+{
+ if ( !m_selectedList )
+ m_selectedList = new KFileItemList;
+
+ m_selectedList->clear();
+
+ KFileItem *item;
+ for ( (item = firstFileItem()); item; item = nextItem( item ) ) {
+ if ( isSelected( item ) )
+ m_selectedList->append( item );
+ }
+
+ return m_selectedList;
+}
+
+void KFileView::selectAll()
+{
+ if (selection_mode == KFile::NoSelection || selection_mode== KFile::Single)
+ return;
+
+ KFileItem *item = 0L;
+ for ( (item = firstFileItem()); item; item = nextItem( item ) )
+ setSelected( item, true );
+}
+
+
+void KFileView::invertSelection()
+{
+ KFileItem *item = 0L;
+ for ( (item = firstFileItem()); item; item = nextItem( item ) )
+ setSelected( item, !isSelected( item ) );
+}
+
+
+void KFileView::setSelectionMode( KFile::SelectionMode sm )
+{
+ selection_mode = sm;
+}
+
+KFile::SelectionMode KFileView::selectionMode() const
+{
+ return selection_mode;
+}
+
+void KFileView::setViewMode( ViewMode vm )
+{
+ view_mode = vm;
+}
+
+void KFileView::removeItem( const KFileItem *item )
+{
+ if ( !item )
+ return;
+
+ if ( item->isDir() )
+ dirsNumber--;
+ else
+ filesNumber--;
+
+ if ( m_selectedList )
+ m_selectedList->removeRef( item );
+}
+
+void KFileView::listingCompleted()
+{
+ // empty default impl.
+}
+
+KActionCollection * KFileView::actionCollection() const
+{
+ if ( !d->actions )
+ d->actions = new KActionCollection( widget(), "KFileView::d->actions" );
+ return d->actions;
+}
+
+void KFileView::readConfig( TDEConfig *, const TQString& )
+{
+}
+
+void KFileView::writeConfig( TDEConfig *, const TQString& )
+{
+}
+
+TQString KFileView::sortingKey( const TQString& value, bool isDir, int sortSpec )
+{
+ bool reverse = sortSpec & TQDir::Reversed;
+ bool dirsFirst = sortSpec & TQDir::DirsFirst;
+ char start = (isDir && dirsFirst) ? (reverse ? '2' : '0') : '1';
+ TQString result = (sortSpec & TQDir::IgnoreCase) ? value.lower() : value;
+ return result.prepend( start );
+}
+
+TQString KFileView::sortingKey( TDEIO::filesize_t value, bool isDir, int sortSpec)
+{
+ bool reverse = sortSpec & TQDir::Reversed;
+ bool dirsFirst = sortSpec & TQDir::DirsFirst;
+ char start = (isDir && dirsFirst) ? (reverse ? '2' : '0') : '1';
+ return TDEIO::number( value ).rightJustify( 24, '0' ).prepend( start );
+}
+
+void KFileView::setDropOptions(int options)
+{
+ virtual_hook(VIRTUAL_SET_DROP_OPTIONS, &options); // Virtual call
+}
+
+void KFileView::setDropOptions_impl(int options)
+{
+ d->dropOptions = options;
+}
+
+int KFileView::dropOptions()
+{
+ return d->dropOptions;
+}
+
+int KFileView::autoOpenDelay()
+{
+ return (TQApplication::startDragTime() * 3) / 2;
+}
+
+void KFileView::virtual_hook( int id, void* data)
+{
+ switch(id) {
+ case VIRTUAL_SET_DROP_OPTIONS:
+ setDropOptions_impl(*(int *)data);
+ break;
+ default:
+ /*BASE::virtual_hook( id, data );*/
+ break;
+ }
+}
+
+#include "tdefileview.moc"
diff --git a/tdeio/tdefile/tdefileview.h b/tdeio/tdefile/tdefileview.h
new file mode 100644
index 000000000..8f4918030
--- /dev/null
+++ b/tdeio/tdefile/tdefileview.h
@@ -0,0 +1,444 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1997 Stephan Kulow <coolo@kde.org>
+ Copyright (C) 2001 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef KFILEVIEW_H
+#define KFILEVIEW_H
+
+class TQPoint;
+class KActionCollection;
+
+#include <tqwidget.h>
+
+#include "tdefileitem.h"
+#include "tdefile.h"
+
+/**
+ * internal class to make easier to use signals possible
+ * @internal
+ **/
+class TDEIO_EXPORT KFileViewSignaler : public TQObject
+{
+ Q_OBJECT
+
+public:
+ /**
+ * Call this method when an item is selected (depends on single click /
+ * double click configuration). Emits the appropriate signal.
+ **/
+ void activate( const KFileItem *item ) {
+ if ( item->isDir() )
+ emit dirActivated( item );
+ else
+ emit fileSelected( item );
+ }
+ /**
+ * emits the highlighted signal for item. Call this in your view class
+ * whenever the selection changes.
+ */
+ void highlightFile(const KFileItem *i) { emit fileHighlighted(i); }
+
+ void activateMenu( const KFileItem *i, const TQPoint& pos ) {
+ emit activatedMenu( i, pos );
+ }
+
+ void changeSorting( TQDir::SortSpec sorting ) {
+ emit sortingChanged( sorting );
+ }
+
+ void dropURLs(const KFileItem *i, TQDropEvent*e, const KURL::List&urls) {
+ emit dropped(i, e, urls);
+ }
+
+signals:
+ void dirActivated(const KFileItem*);
+
+ void sortingChanged( TQDir::SortSpec );
+
+ /**
+ * the item maybe be 0L, indicating that we're in multiselection mode and
+ * the selection has changed.
+ */
+ void fileHighlighted(const KFileItem*);
+ void fileSelected(const KFileItem*);
+ void activatedMenu( const KFileItem *i, const TQPoint& );
+ void dropped(const KFileItem *, TQDropEvent*, const KURL::List&);
+};
+
+/**
+ * This class defines an interface to all file views. Its intent is
+ * to allow to switch the view of the files in the selector very easily.
+ * It defines some pure virtual functions, that must be implemented to
+ * make a file view working.
+ *
+ * Since this class is not a widget, but it's meant to be added to other
+ * widgets, its most important function is widget. This should return
+ * a pointer to the implemented widget.
+ *
+ * @short A base class for views of the KDE file selector
+ * @author Stephan Kulow <coolo@kde.org>
+ **/
+class TDEIO_EXPORT KFileView {
+
+public:
+ KFileView();
+
+ /**
+ * Destructor
+ */
+ virtual ~KFileView();
+
+ /**
+ * inserts a list of items.
+ **/
+ void addItemList(const KFileItemList &list);
+
+ /**
+ * a pure virtual function to get a TQWidget, that can be added to
+ * other widgets. This function is needed to make it possible for
+ * derived classes to derive from other widgets.
+ **/
+ virtual TQWidget *widget() = 0;
+
+ /**
+ * ### As const-method, to be fixed in 3.0
+ */
+ TQWidget *widget() const { return const_cast<KFileView*>(this)->widget(); }
+
+ /**
+ * Sets @p filename the current item in the view, if available.
+ */
+ void setCurrentItem( const TQString &filename );
+
+ /**
+ * Reimplement this to set @p item the current item in the view, e.g.
+ * the item having focus.
+ */
+ virtual void setCurrentItem( const KFileItem *item ) = 0;
+
+ /**
+ * @returns the "current" KFileItem, e.g. where the cursor is.
+ * Returns 0L when there is no current item (e.g. in an empty view).
+ * Subclasses have to implement this.
+ */
+ virtual KFileItem *currentFileItem() const = 0;
+
+ /**
+ * Clears the view and all item lists.
+ */
+ virtual void clear();
+
+ /**
+ * does a repaint of the view.
+ *
+ * The default implementation calls
+ * \code
+ * widget()->repaint(f)
+ * \endcode
+ **/
+ virtual void updateView(bool f = true);
+
+ virtual void updateView(const KFileItem*);
+
+ /**
+ * Removes an item from the list; has to be implemented by the view.
+ * Call KFileView::removeItem( item ) after removing it.
+ */
+ virtual void removeItem(const KFileItem *item);
+
+ /**
+ * This hook is called when all items of the currently listed directory
+ * are listed and inserted into the view, i.e. there won't come any new
+ * items anymore.
+ */
+ virtual void listingCompleted();
+
+ /**
+ * Returns the sorting order of the internal list. Newly added files
+ * are added through this sorting.
+ */
+ TQDir::SortSpec sorting() const { return m_sorting; }
+
+ /**
+ * Sets the sorting order of the view.
+ *
+ * Default is TQDir::Name | TQDir::IgnoreCase | TQDir::DirsFirst
+ * Override this in your subclass and sort accordingly (usually by
+ * setting the sorting-key for every item and telling QIconView
+ * or TQListView to sort.
+ *
+ * A view may choose to use a different sorting than TQDir::Name, Time
+ * or Size. E.g. to sort by mimetype or any possible string. Set the
+ * sorting to TQDir::Unsorted for that and do the rest internally.
+ *
+ * @see sortingKey
+ */
+ virtual void setSorting(TQDir::SortSpec sort);
+
+ /**
+ * Tells whether the current items are in reversed order (shortcut to
+ * sorting() & TQDir::Reversed).
+ */
+ bool isReversed() const { return (m_sorting & TQDir::Reversed); }
+
+ void sortReversed();
+
+ /**
+ * @returns the number of dirs and files
+ **/
+ uint count() const { return filesNumber + dirsNumber; }
+
+ /**
+ * @returns the number of files.
+ **/
+ uint numFiles() const { return filesNumber; }
+
+ /**
+ * @returns the number of directories
+ **/
+ uint numDirs() const { return dirsNumber; }
+
+ virtual void setSelectionMode( KFile::SelectionMode sm );
+ virtual KFile::SelectionMode selectionMode() const;
+
+ enum ViewMode {
+ Files = 1,
+ Directories = 2,
+ All = Files | Directories
+ };
+ virtual void setViewMode( ViewMode vm );
+ virtual ViewMode viewMode() const { return view_mode; }
+
+ /**
+ * @returns the localized name of the view, which could be displayed
+ * somewhere, e.g. in a menu, where the user can choose between views.
+ * @see setViewName
+ */
+ TQString viewName() const { return m_viewName; }
+
+ /**
+ * Sets the name of the view, which could be displayed somewhere.
+ * E.g. "Image Preview".
+ */
+ void setViewName( const TQString& name ) { m_viewName = name; }
+
+ virtual void setParentView(KFileView *parent);
+
+ /**
+ * The derived view must implement this function to add
+ * the file in the widget.
+ *
+ * Make sure to call this implementation, i.e.
+ * KFileView::insertItem( i );
+ *
+ */
+ virtual void insertItem( KFileItem *i);
+
+ /**
+ * pure virtual function, that should be implemented to clear
+ * the view. At this moment the list is already empty
+ **/
+ virtual void clearView() = 0;
+
+ /**
+ * pure virtual function, that should be implemented to make item i
+ * visible, i.e. by scrolling the view appropriately.
+ */
+ virtual void ensureItemVisible( const KFileItem *i ) = 0;
+
+ /**
+ * Clears any selection, unhighlights everything. Must be implemented by
+ * the view.
+ */
+ virtual void clearSelection() = 0;
+
+ /**
+ * Selects all items. You may want to override this, if you can implement
+ * it more efficiently than calling setSelected() with every item.
+ * This works only in Multiselection mode of course.
+ */
+ virtual void selectAll();
+
+ /**
+ * Inverts the current selection, i.e. selects all items, that were up to
+ * now not selected and deselects the other.
+ */
+ virtual void invertSelection();
+
+ /**
+ * Tells the view that it should highlight the item.
+ * This function must be implemented by the view.
+ **/
+ virtual void setSelected(const KFileItem *, bool enable) = 0;
+
+ /**
+ * @returns whether the given item is currently selected.
+ * Must be implemented by the view.
+ */
+ virtual bool isSelected( const KFileItem * ) const = 0;
+
+ /**
+ * @returns all currently highlighted items.
+ */
+ const KFileItemList * selectedItems() const;
+
+ /**
+ * @returns all items currently available in the current sort-order
+ */
+ const KFileItemList * items() const;
+
+ virtual KFileItem * firstFileItem() const = 0;
+ virtual KFileItem * nextItem( const KFileItem * ) const = 0;
+ virtual KFileItem * prevItem( const KFileItem * ) const = 0;
+
+ /**
+ * This is a KFileDialog specific hack: we want to select directories with
+ * single click, but not files. But as a generic class, we have to be able
+ * to select files on single click as well.
+ *
+ * This gives us the opportunity to do both.
+ *
+ * Every view has to decide when to call select( item ) when a file was
+ * single-clicked, based on onlyDoubleClickSelectsFiles().
+ */
+ void setOnlyDoubleClickSelectsFiles( bool enable ) {
+ myOnlyDoubleClickSelectsFiles = enable;
+ }
+
+ /**
+ * @returns whether files (not directories) should only be select()ed by
+ * double-clicks.
+ * @see setOnlyDoubleClickSelectsFiles
+ */
+ bool onlyDoubleClickSelectsFiles() const {
+ return myOnlyDoubleClickSelectsFiles;
+ }
+
+ /**
+ * increases the number of dirs and files.
+ * @returns true if the item fits the view mode
+ */
+ bool updateNumbers(const KFileItem *i);
+
+ /**
+ * @returns the view-specific action-collection. Every view should
+ * add its actions here (if it has any) to make them available to
+ * e.g. the KDirOperator's popup-menu.
+ */
+ virtual KActionCollection * actionCollection() const;
+
+ KFileViewSignaler * signaler() const { return sig; }
+
+ virtual void readConfig( TDEConfig *, const TQString& group = TQString::null );
+ virtual void writeConfig( TDEConfig *, const TQString& group = TQString::null);
+
+ /**
+ * Various options for drag and drop support.
+ * These values can be or'd together.
+ * @li @p AutoOpenDirs Automatically open directory after hovering above it
+ * for a short while while dragging.
+ * @since 3.2
+ */
+ enum DropOptions {
+ AutoOpenDirs = 1
+ };
+ /**
+ * Specify DND options. See DropOptions for details.
+ * All options are disabled by default.
+ * @since 3.2
+ */
+ // KDE 4: Make virtual
+ void setDropOptions(int options);
+
+ /**
+ * Returns the DND options in effect.
+ * See DropOptions for details.
+ * @since 3.2
+ */
+ int dropOptions();
+
+ /**
+ * This method calculates a TQString from the given parameters, that is
+ * suitable for sorting with e.g. TQIconView or TQListView. Their
+ * Item-classes usually have a setKey( const TQString& ) method or a virtual
+ * method TQString key() that is used for sorting.
+ *
+ * @param value Any string that should be used as sort criterion
+ * @param isDir Tells whether the key is computed for an item representing
+ * a directory (directories are usually sorted before files)
+ * @param sortSpec An ORed combination of TQDir::SortSpec flags.
+ * Currently, the values IgnoreCase, Reversed and
+ * DirsFirst are taken into account.
+ */
+ static TQString sortingKey( const TQString& value, bool isDir, int sortSpec);
+
+ /**
+ * An overloaded method that takes not a TQString, but a number as sort
+ * criterion. You can use this for file-sizes or dates/times for example.
+ * If you use a time_t, you need to cast that to TDEIO::filesize_t because
+ * of ambiguity problems.
+ */
+ static TQString sortingKey( TDEIO::filesize_t value, bool isDir,int sortSpec);
+
+ /**
+ * @internal
+ * delay before auto opening a directory
+ */
+ static int autoOpenDelay();
+
+protected:
+ /**
+ * @internal
+ * class to distribute the signals
+ **/
+ KFileViewSignaler *sig;
+
+private:
+ static TQDir::SortSpec defaultSortSpec;
+ TQDir::SortSpec m_sorting;
+ TQString m_viewName;
+
+ /**
+ * counters
+ **/
+ uint filesNumber;
+ uint dirsNumber;
+
+ ViewMode view_mode;
+ KFile::SelectionMode selection_mode;
+
+ // never use! It's only guaranteed to contain valid items in the items()
+ // method!
+ mutable KFileItemList m_itemList;
+
+ mutable KFileItemList *m_selectedList;
+ bool myOnlyDoubleClickSelectsFiles;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+ /* @internal for virtual_hook */
+ enum { VIRTUAL_SET_DROP_OPTIONS = 1 };
+ void setDropOptions_impl(int options);
+private:
+ class KFileViewPrivate;
+ KFileViewPrivate *d;
+};
+
+#endif // KFILEINFOLISTWIDGET_H
diff --git a/tdeio/tdefile/tests/Makefile.am b/tdeio/tdefile/tests/Makefile.am
new file mode 100644
index 000000000..d869f11f5
--- /dev/null
+++ b/tdeio/tdefile/tests/Makefile.am
@@ -0,0 +1,41 @@
+# This file is part of the KDE libraries
+# Copyright (C) 1996-1997 Matthias Kalle Dalheimer (kalle@kde.org)
+# (C) 1997-1998 Stephan Kulow (coolo@kde.org)
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+INCLUDES = $(all_includes)
+
+AM_LDFLAGS = $(QT_LDFLAGS) $(X_LDFLAGS) $(KDE_RPATH)
+
+check_PROGRAMS = kfstest kurlrequestertest tdefiletreeviewtest \
+ kopenwithtest kdirselectdialogtest kicondialogtest \
+ knotifytest kcustommenueditortest
+
+# noinst_HEADERS =
+
+METASOURCES = AUTO
+
+LDADD = $(LIB_KIO)
+kcustommenueditortest_SOURCES = kcustommenueditortest.cpp
+kurlrequestertest_SOURCES = kurlrequestertest.cpp
+kfstest_SOURCES = kfstest.cpp kfdtest.cpp
+tdefiletreeviewtest_SOURCES = tdefiletreeviewtest.cpp
+kopenwithtest_SOURCES = kopenwithtest.cpp
+kdirselectdialogtest_SOURCES = kdirselectdialogtest.cpp
+kicondialogtest_SOURCES = kicondialogtest.cpp
+knotifytest_SOURCES = knotifytest.cpp
+
diff --git a/tdeio/tdefile/tests/kcustommenueditortest.cpp b/tdeio/tdefile/tests/kcustommenueditortest.cpp
new file mode 100644
index 000000000..df2c692f6
--- /dev/null
+++ b/tdeio/tdefile/tests/kcustommenueditortest.cpp
@@ -0,0 +1,19 @@
+#include "kcustommenueditor.h"
+#include <kapplication.h>
+#include <klocale.h>
+#include <tdeconfig.h>
+
+int main(int argc, char** argv)
+{
+ KLocale::setMainCatalogue("tdelibs");
+ TDEApplication app(argc, argv, "KCustomMenuEditorTest");
+ KCustomMenuEditor editor(0);
+ TDEConfig *cfg = new TDEConfig("kdesktop_custom_menu2");
+ editor.load(cfg);
+ if (editor.exec())
+ {
+ editor.save(cfg);
+ cfg->sync();
+ }
+}
+
diff --git a/kio/kfile/tests/kdirselectdialogtest.cpp b/tdeio/tdefile/tests/kdirselectdialogtest.cpp
index 3d15c47d0..3d15c47d0 100644
--- a/kio/kfile/tests/kdirselectdialogtest.cpp
+++ b/tdeio/tdefile/tests/kdirselectdialogtest.cpp
diff --git a/tdeio/tdefile/tests/kfdtest.cpp b/tdeio/tdefile/tests/kfdtest.cpp
new file mode 100644
index 000000000..60c8b6d70
--- /dev/null
+++ b/tdeio/tdefile/tests/kfdtest.cpp
@@ -0,0 +1,34 @@
+#include "kfdtest.h"
+
+#include <tqstringlist.h>
+#include <tdefiledialog.h>
+#include <kapplication.h>
+#include <kmessagebox.h>
+#include <tqtimer.h>
+
+KFDTest::KFDTest( const TQString& startDir, TQObject *parent, const char *name )
+ : TQObject( parent, name ),
+ m_startDir( startDir )
+{
+ TQTimer::singleShot( 1000, this, TQT_SLOT( doit() ));
+}
+
+void KFDTest::doit()
+{
+ KFileDialog *dlg = new KFileDialog( m_startDir, TQString::null, 0L,
+ "file dialog", true );
+ dlg->setMode( KFile::File);
+ dlg->setOperationMode( KFileDialog::Saving );
+ TQStringList filter;
+ filter << "all/allfiles" << "text/plain";
+ dlg->setMimeFilter( filter, "all/allfiles" );
+
+ if ( dlg->exec() == KDialog::Accepted )
+ {
+ KMessageBox::information(0, TQString::fromLatin1("You selected the file: %1").arg( dlg->selectedURL().prettyURL() ));
+ }
+
+// tqApp->quit();
+}
+
+#include "kfdtest.moc"
diff --git a/kio/kfile/tests/kfdtest.h b/tdeio/tdefile/tests/kfdtest.h
index 6c59550b8..6c59550b8 100644
--- a/kio/kfile/tests/kfdtest.h
+++ b/tdeio/tdefile/tests/kfdtest.h
diff --git a/tdeio/tdefile/tests/kfstest.cpp b/tdeio/tdefile/tests/kfstest.cpp
new file mode 100644
index 000000000..f6ee69687
--- /dev/null
+++ b/tdeio/tdefile/tests/kfstest.cpp
@@ -0,0 +1,183 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1997, 1998 Richard Moore <rich@kde.org>
+ 1998 Stephan Kulow <coolo@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <tqdir.h>
+#include <tqlayout.h>
+#include <tqstringlist.h>
+#include <tqwidget.h>
+
+#include <tdefiledialog.h>
+#include <tdefileiconview.h>
+#include <kmessagebox.h>
+#include <tdeconfig.h>
+#include <kapplication.h>
+#include <kurl.h>
+#include <kurlbar.h>
+#include <kdiroperator.h>
+#include <tdefile.h>
+#include <kdebug.h>
+#include <kicondialog.h>
+
+#include "kfdtest.h"
+
+int main(int argc, char **argv)
+{
+ TDEApplication a(argc, argv, "kfstest");
+ TQString name1;
+ TQStringList names;
+
+ TQString argv1;
+ TQString startDir;
+ if (argc > 1)
+ argv1 = TQString::fromLatin1(argv[1]);
+ if ( argc > 2 )
+ startDir = TQString::fromLatin1( argv[2]);
+
+ if (argv1 == TQString::fromLatin1("diroperator")) {
+ KDirOperator *op = new KDirOperator(startDir, 0, "operator");
+ op->setViewConfig( TDEGlobal::config(), "TestGroup" );
+ op->setView(KFile::Simple);
+ op->show();
+ a.setMainWidget(op);
+ a.exec();
+ }
+
+ else if (argv1 == TQString::fromLatin1("justone")) {
+ TQString name = KFileDialog::getOpenFileName(startDir);
+ tqDebug("filename=%s",name.latin1());
+ }
+
+ else if (argv1 == TQString::fromLatin1("existingURL")) {
+ KURL url = KFileDialog::getExistingURL();
+ tqDebug("URL=%s",url.url().latin1());
+ name1 = url.url();
+ }
+
+ else if (argv1 == TQString::fromLatin1("preview")) {
+ KURL u = KFileDialog::getImageOpenURL();
+ tqDebug("filename=%s", u.url().latin1());
+ }
+
+ else if (argv1 == TQString::fromLatin1("preselect")) {
+ names = KFileDialog::getOpenFileNames(TQString::fromLatin1("/etc/passwd"));
+ TQStringList::Iterator it = names.begin();
+ while ( it != names.end() ) {
+ tqDebug("selected file: %s", (*it).latin1());
+ ++it;
+ }
+ }
+
+ else if (argv1 == TQString::fromLatin1("dirs"))
+ name1 = KFileDialog::getExistingDirectory();
+
+ else if (argv1 == TQString::fromLatin1("heap")) {
+ KFileDialog *dlg = new KFileDialog( startDir, TQString::null, 0L,
+ "file dialog", true );
+ dlg->setMode( KFile::File);
+ dlg->setOperationMode( KFileDialog::Saving );
+ TQStringList filter;
+ filter << "all/allfiles" << "text/plain";
+ dlg->setMimeFilter( filter, "all/allfiles" );
+ KURLBar *urlBar = dlg->speedBar();
+ if ( urlBar )
+ {
+ urlBar->insertDynamicItem( KURL("ftp://ftp.kde.org"),
+ TQString::fromLatin1("KDE FTP Server") );
+ }
+
+ if ( dlg->exec() == KDialog::Accepted )
+ name1 = dlg->selectedURL().url();
+ }
+
+ else if ( argv1 == TQString::fromLatin1("eventloop") )
+ {
+ KFDTest *test = new KFDTest( startDir );
+ return a.exec();
+ }
+
+ else if (argv1 == TQString::fromLatin1("save")) {
+ KURL u = KFileDialog::getSaveURL();
+// TQString(TQDir::homeDirPath() + TQString::fromLatin1("/testfile")),
+// TQString::null, 0L);
+ name1 = u.url();
+ }
+
+ else if (argv1 == TQString::fromLatin1("icon")) {
+ KIconDialog dlg;
+ TQString icon = dlg.selectIcon();
+ kdDebug() << icon << endl;
+ }
+
+// else if ( argv1 == TQString::fromLatin1("dirselect") ) {
+// KURL url;
+// url.setPath( "/" );
+// KURL selected = KDirSelectDialog::selectDirectory( url );
+// name1 = selected.url();
+// tqDebug("*** selected: %s", selected.url().latin1());
+// }
+
+ else {
+ KFileDialog dlg(startDir,
+ TQString::fromLatin1("*|All Files\n"
+ "*.lo *.o *.la|All libtool Files"),
+ 0, 0, true);
+// dlg.setFilter( "*.tdevelop" );
+ dlg.setMode( (KFile::Mode) (KFile::Files |
+ KFile::Directory |
+ KFile::ExistingOnly |
+ KFile::LocalOnly) );
+// TQStringList filter;
+// filter << "text/plain" << "text/html" << "image/png";
+// dlg.setMimeFilter( filter );
+// KMimeType::List types;
+// types.append( KMimeType::mimeType( "text/plain" ) );
+// types.append( KMimeType::mimeType( "text/html" ) );
+// dlg.setFilterMimeType( "Filetypes:", types, types.first() );
+ if ( dlg.exec() == TQDialog::Accepted ) {
+ KURL::List list = dlg.selectedURLs();
+ KURL::List::ConstIterator it = list.begin();
+ tqDebug("*** selectedURLs(): ");
+ while ( it != list.end() ) {
+ name1 = (*it).url();
+ tqDebug(" -> %s", name1.latin1());
+ ++it;
+ }
+ tqDebug("*** selectedFile: %s", dlg.selectedFile().latin1());
+ tqDebug("*** selectedURL: %s", dlg.selectedURL().url().latin1());
+ tqDebug("*** selectedFiles: ");
+ TQStringList l = dlg.selectedFiles();
+ TQStringList::Iterator it2 = l.begin();
+ while ( it2 != l.end() ) {
+ tqDebug(" -> %s", (*it2).latin1());
+ ++it2;
+ }
+ }
+ }
+
+ if (!(name1.isNull()))
+ KMessageBox::information(0, TQString::fromLatin1("You selected the file " ) + name1,
+ TQString::fromLatin1("Your Choice"));
+ return 0;
+}
diff --git a/kio/kfile/tests/kicondialogtest.cpp b/tdeio/tdefile/tests/kicondialogtest.cpp
index b2c56e159..b2c56e159 100644
--- a/kio/kfile/tests/kicondialogtest.cpp
+++ b/tdeio/tdefile/tests/kicondialogtest.cpp
diff --git a/kio/kfile/tests/knotifytest.cpp b/tdeio/tdefile/tests/knotifytest.cpp
index 0493b59b4..0493b59b4 100644
--- a/kio/kfile/tests/knotifytest.cpp
+++ b/tdeio/tdefile/tests/knotifytest.cpp
diff --git a/kio/kfile/tests/kopenwithtest.cpp b/tdeio/tdefile/tests/kopenwithtest.cpp
index f78b1830b..f78b1830b 100644
--- a/kio/kfile/tests/kopenwithtest.cpp
+++ b/tdeio/tdefile/tests/kopenwithtest.cpp
diff --git a/kio/kfile/tests/kurlrequestertest.cpp b/tdeio/tdefile/tests/kurlrequestertest.cpp
index 0e4851cfb..0e4851cfb 100644
--- a/kio/kfile/tests/kurlrequestertest.cpp
+++ b/tdeio/tdefile/tests/kurlrequestertest.cpp
diff --git a/tdeio/tdefile/tests/tdefiletreeviewtest.cpp b/tdeio/tdefile/tests/tdefiletreeviewtest.cpp
new file mode 100644
index 000000000..b74468fda
--- /dev/null
+++ b/tdeio/tdefile/tests/tdefiletreeviewtest.cpp
@@ -0,0 +1,165 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001 Klaas Freitag <freitag@suse.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqdir.h>
+
+#include <kglobal.h>
+#include <kiconloader.h>
+#include <kmainwindow.h>
+#include <kapplication.h>
+#include <kurl.h>
+#include <kdebug.h>
+#include <kstatusbar.h>
+
+#include <tdefiletreeview.h>
+#include "tdefiletreeviewtest.h"
+
+
+#include "tdefiletreeviewtest.moc"
+
+testFrame::testFrame():KMainWindow(0,"Test FileTreeView"),
+ dirOnlyMode(false)
+
+{
+ treeView = new KFileTreeView( this );
+ treeView->setDragEnabled( true );
+ treeView->setAcceptDrops( true );
+ treeView->setDropVisualizer( true );
+
+
+ /* Connect to see the status bar */
+ KStatusBar* sta = statusBar();
+ connect( treeView, TQT_SIGNAL( onItem( const TQString& )),
+ sta, TQT_SLOT( message( const TQString& )));
+
+ connect( treeView, TQT_SIGNAL( dropped( TQWidget*, TQDropEvent*, KURL::List& )),
+ this, TQT_SLOT( urlsDropped( TQWidget*, TQDropEvent*, KURL::List& )));
+
+ connect( treeView, TQT_SIGNAL( dropped( KURL::List&, KURL& )), this,
+ TQT_SLOT( copyURLs( KURL::List&, KURL& )));
+
+ treeView->addColumn( "File" );
+ treeView->addColumn( "ChildCount" );
+ setCentralWidget( treeView );
+ resize( 600, 400 );
+
+ showPath( KURL::fromPathOrURL( TQDir::homeDirPath() ));
+}
+
+void testFrame::showPath( const KURL &url )
+{
+ TQString fname = "TestBranch"; // url.fileName ();
+ /* try a user icon */
+ KIconLoader *loader = TDEGlobal::iconLoader();
+ TQPixmap pix = loader->loadIcon( "contents2", KIcon::Small );
+ TQPixmap pixOpen = loader->loadIcon( "contents", KIcon::Small );
+
+ KFileTreeBranch *nb = treeView->addBranch( url, fname, pix );
+
+ if( nb )
+ {
+ if( dirOnlyMode ) treeView->setDirOnlyMode( nb, true );
+ nb->setOpenPixmap( pixOpen );
+
+ connect( nb, TQT_SIGNAL(populateFinished(KFileTreeViewItem*)),
+ this, TQT_SLOT(slotPopulateFinished(KFileTreeViewItem*)));
+ connect( nb, TQT_SIGNAL( directoryChildCount( KFileTreeViewItem *, int )),
+ this, TQT_SLOT( slotSetChildCount( KFileTreeViewItem*, int )));
+ // nb->setChildRecurse(false );
+
+ nb->setOpen(true);
+ }
+
+
+}
+
+void testFrame::urlsDropped( TQWidget* , TQDropEvent* , KURL::List& list )
+{
+ KURL::List::ConstIterator it = list.begin();
+ for ( ; it != list.end(); ++it ) {
+ kdDebug() << "Url dropped: " << (*it).prettyURL() << endl;
+ }
+}
+
+void testFrame::copyURLs( KURL::List& list, KURL& to )
+{
+ KURL::List::ConstIterator it = list.begin();
+ kdDebug() << "Copy to " << to.prettyURL() << endl;
+ for ( ; it != list.end(); ++it ) {
+ kdDebug() << "Url: " << (*it).prettyURL() << endl;
+ }
+
+}
+
+
+void testFrame::slotPopulateFinished(KFileTreeViewItem *item )
+{
+ if( item )
+ {
+#if 0
+ int cc = item->childCount();
+
+ kdDebug() << "setting column 2 of treeview with count " << cc << endl;
+
+ item->setText( 1, TQString::number( cc ));
+#endif
+ }
+ else
+ {
+ kdDebug() << "slotPopFinished for uninitalised item" << endl;
+ }
+}
+
+void testFrame::slotSetChildCount( KFileTreeViewItem *item, int c )
+{
+ if( item )
+ item->setText(1, TQString::number( c ));
+}
+
+int main(int argc, char **argv)
+{
+ TDEApplication a(argc, argv, "tdefiletreeviewtest");
+ TQString name1;
+ TQStringList names;
+
+ TQString argv1;
+ testFrame *tf;
+
+ tf = new testFrame();
+ a.setMainWidget( tf );
+
+ if (argc > 1)
+ {
+ for( int i = 1; i < argc; i++ )
+ {
+ argv1 = TQString::fromLatin1(argv[i]);
+ kdDebug() << "Opening " << argv1 << endl;
+ if( argv1 == "-d" )
+ tf->setDirOnly();
+ else
+ {
+ KURL u( argv1 );
+ tf->showPath( u );
+ }
+ }
+ }
+ tf->show();
+ int ret = a.exec();
+ return( ret );
+}
diff --git a/kio/kfile/tests/kfiletreeviewtest.h b/tdeio/tdefile/tests/tdefiletreeviewtest.h
index 4ae791ce5..4ae791ce5 100644
--- a/kio/kfile/tests/kfiletreeviewtest.h
+++ b/tdeio/tdefile/tests/tdefiletreeviewtest.h
diff --git a/kio/kfileplugin.desktop b/tdeio/tdefileplugin.desktop
index 6609551a6..6609551a6 100644
--- a/kio/kfileplugin.desktop
+++ b/tdeio/tdefileplugin.desktop
diff --git a/tdeio/tdeio/CMakeLists.txt b/tdeio/tdeio/CMakeLists.txt
new file mode 100644
index 000000000..8aaf395b6
--- /dev/null
+++ b/tdeio/tdeio/CMakeLists.txt
@@ -0,0 +1,138 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdeio/kssl
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore/network
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/kssl
+ ${CMAKE_SOURCE_DIR}/interfaces
+ ${LIBR_INCLUDEDIR}
+ ${GAMIN_INCLUDEDIR}
+)
+
+link_directories(
+ ${GAMIN_LIBDIR}
+)
+
+##### headers ###################################
+
+install( FILES
+ kservicetype.h kmimetype.h kmimemagic.h kservice.h
+ krun.h kdirwatch.h kautomount.h kuserprofile.h
+ kshred.h kar.h ktar.h kzip.h ktrader.h kurifilter.h
+ kurlcompletion.h kshellcompletion.h tdefileitem.h
+ tdefileshare.h ksambashare.h knfsshare.h kdirlister.h
+ kservicegroup.h kimageio.h kdirnotify.h kdirnotify_stub.h
+ kurlpixmapprovider.h kprotocolinfo.h kprotocolmanager.h
+ kfilterbase.h kfilterdev.h kemailsettings.h kscan.h
+ kdatatool.h karchive.h tdefilefilter.h tdefilemetainfo.h
+ renamedlgplugin.h kmimetyperesolver.h kdcopservicestarter.h
+ kremoteencoding.h kmimetypechooser.h
+ DESTINATION ${INCLUDE_INSTALL_DIR} )
+
+# FIXME seems that ACL is no longer optional
+#if( USE_POSIX_ACL )
+ install( FILES kacl.h DESTINATION ${INCLUDE_INSTALL_DIR} )
+#endif( USE_POSIX_ACL )
+
+install( FILES
+ connection.h slaveinterface.h slave.h slaveconfig.h
+ sessiondata.h global.h passdlg.h netaccess.h job.h
+ scheduler.h jobclasses.h paste.h slavebase.h
+ progressbase.h defaultprogress.h statusbarprogress.h
+ tcpslavebase.h forwardingslavebase.h observer.h
+ chmodjob.h kmdbase.h authinfo.h ioslave_defaults.h
+ http_slave_defaults.h previewjob.h thumbcreator.h
+ metainfojob.h davjob.h renamedlg.h skipdlg.h
+ ${CMAKE_CURRENT_BINARY_DIR}/uiserver_stub.h
+ DESTINATION ${INCLUDE_INSTALL_DIR}/tdeio )
+
+
+##### tdeiocore ###################################
+
+set( target tdeiocore )
+
+set( ${target}_SRCS
+ authinfo.cpp kshred.cpp kprotocolmanager.cpp slave.cpp
+ slaveinterface.cpp observer.stub sessiondata.cpp
+ scheduler.cpp connection.cpp job.cpp global.cpp
+ slaveconfig.cpp kurlpixmapprovider.cpp netaccess.cpp
+ paste.cpp pastedialog.cpp kmimemagic.cpp tcpslavebase.cpp
+ slavebase.cpp passdlg.cpp forwardingslavebase.cpp
+ progressbase.cpp defaultprogress.cpp statusbarprogress.cpp
+ kdirnotify.cpp kdirnotify.skel kdirnotify_stub.cpp
+ observer.cpp ../misc/uiserver.stub observer.skel kemailsettings.cpp
+ kprotocolinfo.cpp renamedlg.cpp skipdlg.cpp kremoteencoding.cpp
+ kmimetypechooser.cpp
+)
+
+tde_add_library( ${target} STATIC_PIC AUTOMOC
+ SOURCES ${${target}_SRCS}
+ DEPENDENCIES dcopidl
+)
+
+
+##### tdesycoca ###################################
+
+set( target tdesycoca )
+
+set( ${target}_SRCS
+ kdirwatch.cpp tdefileshare.cpp ksambashare.cpp
+ knfsshare.cpp ktrader.cpp ktraderparse.cpp
+ ktraderparsetree.cpp kservicetypefactory.cpp
+ kservicetype.cpp kmimetype.cpp kservicegroup.cpp
+ kservice.cpp kservicefactory.cpp kuserprofile.cpp
+ kservicegroupfactory.cpp kurifilter.cpp kfilterbase.cpp
+ kfilterdev.cpp kshellcompletion.cpp kurlcompletion.cpp
+ kautomount.cpp krun.cpp tdefileitem.cpp kdirlister.cpp
+ kimageio.cpp yacc.c lex.c chmodjob.cpp kscan.cpp
+ kar.cpp ktar.cpp kzip.cpp previewjob.cpp metainfojob.cpp
+ davjob.cpp kdatatool.cpp karchive.cpp tdefilefilter.cpp
+ tdefilemetainfo.cpp kdcopservicestarter.cpp dataslave.cpp
+ dataprotocol.cpp
+)
+
+# FIXME seems that ACL is no longer optional
+#if( USE_POSIX_ACL )
+ set( ${target}_SRCS ${${target}_SRCS} kacl.cpp posixacladdons.cpp )
+#endif( USE_POSIX_ACL )
+
+tde_add_library( ${target} STATIC_PIC AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK ${GAMIN_LIBRARIES}
+)
+
+
+##### tdelficon ###################################
+
+if( HAVE_ELFICON )
+
+ set( target tdelficon )
+
+ set( ${target}_SRCS
+ tdelficon.cpp
+ )
+
+ tde_add_library( ${target} STATIC_PIC AUTOMOC
+ SOURCES ${${target}_SRCS}
+ )
+
+endif( HAVE_ELFICON )
diff --git a/kio/kio/KFILEMETAINFO_ISSUES b/tdeio/tdeio/KFILEMETAINFO_ISSUES
index a4486f85f..a4486f85f 100644
--- a/kio/kio/KFILEMETAINFO_ISSUES
+++ b/tdeio/tdeio/KFILEMETAINFO_ISSUES
diff --git a/tdeio/tdeio/Makefile.am b/tdeio/tdeio/Makefile.am
new file mode 100644
index 000000000..f0766f5c8
--- /dev/null
+++ b/tdeio/tdeio/Makefile.am
@@ -0,0 +1,129 @@
+# This file is part of the KDE libraries
+# Copyright (C) 1997 Torben Weis (weis@kde.org)
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
+
+INCLUDES= -I$(top_srcdir) -I$(srcdir)/.. -I$(top_srcdir)/tdecore/network -I$(srcdir)/../kssl -I../kssl -I$(srcdir)/../../interfaces $(all_includes) $(SSL_INCLUDES)
+
+noinst_LTLIBRARIES = libtdeiocore.la libtdesycoca.la
+
+# convenience lib - no LDFLAGS or LIBADD !
+
+libtdesycoca_la_SOURCES = \
+ kdirwatch.cpp \
+ tdefileshare.cpp ksambashare.cpp knfsshare.cpp \
+ ktrader.cpp ktraderparse.cpp ktraderparsetree.cpp \
+ kservicetypefactory.cpp kservicetype.cpp \
+ kmimetype.cpp kservicegroup.cpp \
+ kservice.cpp kservicefactory.cpp \
+ kuserprofile.cpp kservicegroupfactory.cpp \
+ kurifilter.cpp \
+ kfilterbase.cpp kfilterdev.cpp \
+ kshellcompletion.cpp kurlcompletion.cpp \
+ kautomount.cpp krun.cpp \
+ tdefileitem.cpp kdirlister.cpp kimageio.cpp \
+ yacc.c lex.c \
+ chmodjob.cpp kscan.cpp kar.cpp ktar.cpp kzip.cpp previewjob.cpp metainfojob.cpp davjob.cpp \
+ kdatatool.cpp karchive.cpp tdefilefilter.cpp \
+ tdefilemetainfo.cpp kdcopservicestarter.cpp \
+ dataslave.cpp dataprotocol.cpp
+#if USE_POSIX_ACL
+ libtdesycoca_la_SOURCES += kacl.cpp posixacladdons.cpp
+#endif
+
+include_HEADERS = \
+ kservicetype.h kmimetype.h kmimemagic.h kservice.h \
+ krun.h kdirwatch.h kautomount.h kuserprofile.h \
+ kshred.h kar.h ktar.h kzip.h ktrader.h kurifilter.h kurlcompletion.h \
+ kshellcompletion.h tdefileitem.h tdefileshare.h ksambashare.h knfsshare.h \
+ kdirlister.h kservicegroup.h \
+ kimageio.h kdirnotify.h kdirnotify_stub.h \
+ kurlpixmapprovider.h kprotocolinfo.h kprotocolmanager.h \
+ kfilterbase.h kfilterdev.h kemailsettings.h kscan.h kdatatool.h \
+ karchive.h tdefilefilter.h tdefilemetainfo.h renamedlgplugin.h \
+ kmimetyperesolver.h kdcopservicestarter.h kremoteencoding.h \
+ kmimetypechooser.h
+#if USE_POSIX_ACL
+include_HEADERS += kacl.h
+#endif
+
+#libtdeiocore_la_LDFLAGS = $(all_libraries)
+#libtdeiocore_la_LIBADD = ../../tdeui/libtdeui.la ../../tdesu/libtdesu.la $(LIBZ) $(LIBFAM) $(LIBVOLMGT)
+
+libtdeiocore_la_SOURCES = authinfo.cpp \
+ kshred.cpp \
+ kprotocolmanager.cpp \
+ slave.cpp slaveinterface.cpp observer.stub \
+ sessiondata.cpp scheduler.cpp \
+ connection.cpp \
+ job.cpp global.cpp \
+ slaveconfig.cpp kurlpixmapprovider.cpp \
+ netaccess.cpp paste.cpp pastedialog.cpp \
+ kmimemagic.cpp \
+ tcpslavebase.cpp slavebase.cpp passdlg.cpp \
+ forwardingslavebase.cpp \
+ progressbase.cpp defaultprogress.cpp \
+ statusbarprogress.cpp \
+ kdirnotify.cpp kdirnotify.skel kdirnotify_stub.cpp \
+ observer.cpp uiserver.stub observer.skel \
+ kemailsettings.cpp \
+ kprotocolinfo.cpp \
+ renamedlg.cpp skipdlg.cpp kremoteencoding.cpp \
+ kmimetypechooser.cpp
+
+uiserver_DIR = $(top_srcdir)/tdeio/misc
+
+METASOURCES = AUTO
+
+tdeioincludedir = $(includedir)/tdeio
+tdeioinclude_HEADERS = connection.h \
+ slaveinterface.h slave.h slaveconfig.h \
+ sessiondata.h global.h passdlg.h \
+ netaccess.h job.h scheduler.h \
+ jobclasses.h paste.h slavebase.h \
+ progressbase.h defaultprogress.h \
+ statusbarprogress.h tcpslavebase.h \
+ forwardingslavebase.h \
+ observer.h chmodjob.h uiserver_stub.h \
+ kmdbase.h authinfo.h \
+ ioslave_defaults.h http_slave_defaults.h previewjob.h thumbcreator.h \
+ metainfojob.h davjob.h renamedlg.h skipdlg.h
+
+# Internal
+noinst_HEADERS = kservicetypefactory.h kservicefactory.h \
+ kmessageboxwrapper.h \
+ ktraderparse.h ktraderparsetree.h yacc.h \
+ kimageiofactory.h kdirwatch_p.h kdirlister_p.h \
+ renamedlg.h skipdlg.h dataslave.h dataprotocol.h \
+ kservice_p.h
+#if USE_POSIX_ACL
+noinst_HEADERS += posixacladdons.h
+#endif
+
+parserfiles = yacc.y lex.l
+
+EXTRA_DIST = $(parserfiles)
+
+parser: $(parserfiles)
+ cd $(srcdir) ;\
+ flex -olex.c -Pkiotrader lex.l ;\
+ bison -d -p kiotrader yacc.y && mv yacc.tab.c yacc.c; mv yacc.tab.h yacc.h
+
+.PHONY: parser
+
+include ../../admin/Doxyfile.am
diff --git a/tdeio/tdeio/authinfo.cpp b/tdeio/tdeio/authinfo.cpp
new file mode 100644
index 000000000..b95a40585
--- /dev/null
+++ b/tdeio/tdeio/authinfo.cpp
@@ -0,0 +1,332 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (C) 2000-2001 Dawit Alemayehu <adawit@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include <config.h>
+
+#include <stdio.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <tqdir.h>
+#include <tqfile.h>
+
+#include <kdebug.h>
+#include <kstandarddirs.h>
+#include <ksavefile.h>
+#include <kstaticdeleter.h>
+#include <kde_file.h>
+
+#include "tdeio/authinfo.h"
+
+#define NETRC_READ_BUF_SIZE 4096
+
+using namespace TDEIO;
+
+AuthInfo::AuthInfo()
+{
+ modified = false;
+ readOnly = false;
+ verifyPath = false;
+ keepPassword = false;
+}
+
+AuthInfo::AuthInfo( const AuthInfo& info )
+{
+ (*this) = info;
+}
+
+AuthInfo& AuthInfo::operator= ( const AuthInfo& info )
+{
+ url = info.url;
+ username = info.username;
+ password = info.password;
+ prompt = info.prompt;
+ caption = info.caption;
+ comment = info.comment;
+ commentLabel = info.commentLabel;
+ realmValue = info.realmValue;
+ digestInfo = info.digestInfo;
+ verifyPath = info.verifyPath;
+ readOnly = info.readOnly;
+ keepPassword = info.keepPassword;
+ modified = info.modified;
+ return *this;
+}
+
+TQDataStream& TDEIO::operator<< (TQDataStream& s, const AuthInfo& a)
+{
+ s << a.url << a.username << a.password << a.prompt << a.caption
+ << a.comment << a.commentLabel << a.realmValue << a.digestInfo
+ << TQ_UINT8(a.verifyPath ? 1:0) << TQ_UINT8(a.readOnly ? 1:0)
+ << TQ_UINT8(a.keepPassword ? 1:0) << TQ_UINT8(a.modified ? 1:0);
+ return s;
+}
+
+TQDataStream& TDEIO::operator>> (TQDataStream& s, AuthInfo& a)
+{
+ TQ_UINT8 verify = 0;
+ TQ_UINT8 ro = 0;
+ TQ_UINT8 keep = 0;
+ TQ_UINT8 mod = 0;
+
+ s >> a.url >> a.username >> a.password >> a.prompt >> a.caption
+ >> a.comment >> a.commentLabel >> a.realmValue >> a.digestInfo
+ >> verify >> ro >> keep >> mod;
+ a.verifyPath = (verify != 0);
+ a.readOnly = (ro != 0);
+ a.keepPassword = (keep != 0);
+ a.modified = (mod != 0);
+ return s;
+}
+
+
+NetRC* NetRC::instance = 0L;
+
+NetRC::NetRC()
+{
+ isDirty = false;
+}
+
+NetRC::~NetRC()
+{
+ delete instance;
+ instance = 0L;
+}
+
+NetRC* NetRC::self()
+{
+ if ( !instance )
+ instance = new NetRC();
+ return instance;
+}
+
+bool NetRC::lookup( const KURL& url, AutoLogin& login, bool userealnetrc,
+ TQString type, int mode )
+{
+ // kdDebug() << "AutoLogin lookup for: " << url.host() << endl;
+ if ( !url.isValid() )
+ return false;
+
+ if ( type.isEmpty() )
+ type = url.protocol();
+
+ if ( loginMap.isEmpty() || isDirty )
+ {
+ loginMap.clear();
+
+ TQString filename = locateLocal("config", "kionetrc");
+ bool status = parse (openf (filename));
+
+ if ( userealnetrc )
+ {
+ filename = TQDir::homeDirPath()+ TQDir::separator() + ".netrc";
+ status |= parse (openf(filename));
+ }
+
+ if ( !status )
+ return false;
+ }
+
+ if ( !loginMap.contains( type ) )
+ return false;
+
+ LoginList l = loginMap[type];
+ if ( l.isEmpty() )
+ return false;
+
+ for (LoginList::Iterator it = l.begin(); it != l.end(); ++it)
+ {
+ AutoLogin &log = *it;
+
+ if ( (mode & defaultOnly) == defaultOnly &&
+ log.machine == TQString::fromLatin1("default") &&
+ (login.login.isEmpty() || login.login == log.login) )
+ {
+ login.type = log.type;
+ login.machine = log.machine;
+ login.login = log.login;
+ login.password = log.password;
+ login.macdef = log.macdef;
+ }
+
+ if ( (mode & presetOnly) == presetOnly &&
+ log.machine == TQString::fromLatin1("preset") &&
+ (login.login.isEmpty() || login.login == log.login) )
+ {
+ login.type = log.type;
+ login.machine = log.machine;
+ login.login = log.login;
+ login.password = log.password;
+ login.macdef = log.macdef;
+ }
+
+ if ( (mode & exactOnly) == exactOnly &&
+ log.machine == url.host() &&
+ (login.login.isEmpty() || login.login == log.login) )
+ {
+ login.type = log.type;
+ login.machine = log.machine;
+ login.login = log.login;
+ login.password = log.password;
+ login.macdef = log.macdef;
+ break;
+ }
+ }
+
+ return true;
+}
+
+int NetRC::openf( const TQString& f )
+{
+ KDE_struct_stat sbuff;
+ TQCString ef = TQFile::encodeName(f);
+ if ( KDE_stat(ef, &sbuff) != 0 )
+ return -1;
+
+ // Security check!!
+ if ( sbuff.st_mode != (S_IFREG|S_IRUSR|S_IWUSR) ||
+ sbuff.st_uid != geteuid() )
+ return -1;
+
+ return KDE_open( ef, O_RDONLY );
+}
+
+TQString NetRC::extract( const char* buf, const char* key, int& pos )
+{
+ int idx = pos;
+ int m_len = strlen(key);
+ int b_len = strlen(buf);
+
+ while( idx < b_len )
+ {
+ while( buf[idx] == ' ' || buf[idx] == '\t' )
+ idx++;
+
+ if ( strncasecmp( buf+idx, key, m_len ) != 0 )
+ idx++;
+ else
+ {
+ idx += m_len;
+ while( buf[idx] == ' ' || buf[idx] == '\t' )
+ idx++;
+
+ int start = idx;
+ while( buf[idx] != ' ' && buf[idx] != '\t' &&
+ buf[idx] != '\n' && buf[idx] != '\r' )
+ idx++;
+
+ if ( idx > start )
+ {
+ pos = idx;
+ return TQString::fromLatin1( buf+start, idx-start);
+ }
+ }
+ }
+
+ return TQString::null;
+}
+
+bool NetRC::parse( int fd )
+{
+ if (fd == -1)
+ return false;
+
+ TQString type;
+ TQString macro;
+
+ uint index = 0;
+ bool isMacro = false;
+ char* buf = new char[NETRC_READ_BUF_SIZE];
+ FILE* fstream = KDE_fdopen( fd,"rb" );
+
+ while ( fgets (buf, NETRC_READ_BUF_SIZE, fstream) != 0L )
+ {
+ int pos = 0;
+
+ while ( buf[pos] == ' ' || buf[pos] == '\t' )
+ pos++;
+
+ if ( buf[pos] == '#' || buf[pos] == '\n' ||
+ buf[pos] == '\r' || buf[pos] == '\0' )
+ {
+ if ( buf[pos] != '#' && isMacro )
+ isMacro = false;
+
+ continue;
+ }
+
+ if ( isMacro )
+ {
+ int tail = strlen(buf);
+ while( buf[tail-1] == '\n' || buf[tail-1] =='\r' )
+ tail--;
+
+ TQString mac = TQString::fromLatin1(buf, tail).stripWhiteSpace();
+ if ( !mac.isEmpty() )
+ loginMap[type][index].macdef[macro].append( mac );
+
+ continue;
+ }
+
+ AutoLogin l;
+ l.machine = extract( buf, "machine", pos );
+ if ( l.machine.isEmpty() )
+ {
+ if (strncasecmp(buf+pos, "default", 7) == 0 )
+ {
+ pos += 7;
+ l.machine = TQString::fromLatin1("default");
+ }
+ else if (strncasecmp(buf+pos, "preset", 6) == 0 )
+ {
+ pos += 6;
+ l.machine = TQString::fromLatin1("preset");
+ }
+ }
+ // kdDebug() << "Machine: " << l.machine << endl;
+
+ l.login = extract( buf, "login", pos );
+ // kdDebug() << "Login: " << l.login << endl;
+
+ l.password = extract( buf, "password", pos );
+ if ( l.password.isEmpty() )
+ l.password = extract( buf, "account", pos );
+ // kdDebug() << "Password: " << l.password << endl;
+
+ type = l.type = extract( buf, "type", pos );
+ if ( l.type.isEmpty() && !l.machine.isEmpty() )
+ type = l.type = TQString::fromLatin1("ftp");
+ // kdDebug() << "Type: " << l.type << endl;
+
+ macro = extract( buf, "macdef", pos );
+ isMacro = !macro.isEmpty();
+ // kdDebug() << "Macro: " << macro << endl;
+
+ loginMap[l.type].append(l);
+ index = loginMap[l.type].count()-1;
+ }
+
+ delete [] buf;
+ fclose (fstream);
+ close (fd);
+ return true;
+}
diff --git a/kio/kio/authinfo.h b/tdeio/tdeio/authinfo.h
index 019311ef8..019311ef8 100644
--- a/kio/kio/authinfo.h
+++ b/tdeio/tdeio/authinfo.h
diff --git a/tdeio/tdeio/chmodjob.cpp b/tdeio/tdeio/chmodjob.cpp
new file mode 100644
index 000000000..434466d77
--- /dev/null
+++ b/tdeio/tdeio/chmodjob.cpp
@@ -0,0 +1,258 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ David Faure <faure@kde.org>
+ Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <config.h>
+
+#include <pwd.h>
+#include <grp.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <assert.h>
+
+#include <tqtimer.h>
+#include <tqfile.h>
+#include <klocale.h>
+#include <kdebug.h>
+#include <kmessagebox.h>
+
+#include "tdeio/job.h"
+#include "tdeio/chmodjob.h"
+
+#include <kdirnotify_stub.h>
+
+using namespace TDEIO;
+
+ChmodJob::ChmodJob( const KFileItemList& lstItems, int permissions, int mask,
+ int newOwner, int newGroup,
+ bool recursive, bool showProgressInfo )
+ : TDEIO::Job( showProgressInfo ), state( STATE_LISTING ),
+ m_permissions( permissions ), m_mask( mask ),
+ m_newOwner( newOwner ), m_newGroup( newGroup ),
+ m_recursive( recursive ), m_lstItems( lstItems )
+{
+ TQTimer::singleShot( 0, this, TQT_SLOT(processList()) );
+}
+
+void ChmodJob::processList()
+{
+ while ( !m_lstItems.isEmpty() )
+ {
+ KFileItem * item = m_lstItems.first();
+ if ( !item->isLink() ) // don't do anything with symlinks
+ {
+ // File or directory -> remember to chmod
+ ChmodInfo info;
+ info.url = item->url();
+ // This is a toplevel file, we apply changes directly (no +X emulation here)
+ info.permissions = ( m_permissions & m_mask ) | ( item->permissions() & ~m_mask );
+ /*kdDebug(7007) << "\n current permissions=" << TQString::number(item->permissions(),8)
+ << "\n wanted permission=" << TQString::number(m_permissions,8)
+ << "\n with mask=" << TQString::number(m_mask,8)
+ << "\n with ~mask (mask bits we keep) =" << TQString::number((uint)~m_mask,8)
+ << "\n bits we keep =" << TQString::number(item->permissions() & ~m_mask,8)
+ << "\n new permissions = " << TQString::number(info.permissions,8)
+ << endl;*/
+ m_infos.prepend( info );
+ //kdDebug(7007) << "processList : Adding info for " << info.url.prettyURL() << endl;
+ // Directory and recursive -> list
+ if ( item->isDir() && m_recursive )
+ {
+ //kdDebug(7007) << "ChmodJob::processList dir -> listing" << endl;
+ TDEIO::ListJob * listJob = TDEIO::listRecursive( item->url(), false /* no GUI */ );
+ connect( listJob, TQT_SIGNAL(entries( TDEIO::Job *,
+ const TDEIO::UDSEntryList& )),
+ TQT_SLOT( slotEntries( TDEIO::Job*,
+ const TDEIO::UDSEntryList& )));
+ addSubjob( listJob );
+ return; // we'll come back later, when this one's finished
+ }
+ }
+ m_lstItems.removeFirst();
+ }
+ kdDebug(7007) << "ChmodJob::processList -> going to STATE_CHMODING" << endl;
+ // We have finished, move on
+ state = STATE_CHMODING;
+ chmodNextFile();
+}
+
+void ChmodJob::slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList & list )
+{
+ TDEIO::UDSEntryListConstIterator it = list.begin();
+ TDEIO::UDSEntryListConstIterator end = list.end();
+ for (; it != end; ++it) {
+ TDEIO::UDSEntry::ConstIterator it2 = (*it).begin();
+ mode_t permissions = 0;
+ bool isDir = false;
+ bool isLink = false;
+ TQString relativePath;
+ for( ; it2 != (*it).end(); it2++ ) {
+ switch( (*it2).m_uds ) {
+ case TDEIO::UDS_NAME:
+ relativePath = (*it2).m_str;
+ break;
+ case TDEIO::UDS_FILE_TYPE:
+ isDir = S_ISDIR((*it2).m_long);
+ break;
+ case TDEIO::UDS_LINK_DEST:
+ isLink = !(*it2).m_str.isEmpty();
+ break;
+ case TDEIO::UDS_ACCESS:
+ permissions = (mode_t)((*it2).m_long);
+ break;
+ default:
+ break;
+ }
+ }
+ if ( !isLink && relativePath != TQString::fromLatin1("..") )
+ {
+ ChmodInfo info;
+ info.url = m_lstItems.first()->url(); // base directory
+ info.url.addPath( relativePath );
+ int mask = m_mask;
+ // Emulate -X: only give +x to files that had a +x bit already
+ // So the check is the opposite : if the file had no x bit, don't touch x bits
+ // For dirs this doesn't apply
+ if ( !isDir )
+ {
+ int newPerms = m_permissions & mask;
+ if ( (newPerms & 0111) && !(permissions & 0111) )
+ {
+ // don't interfere with mandatory file locking
+ if ( newPerms & 02000 )
+ mask = mask & ~0101;
+ else
+ mask = mask & ~0111;
+ }
+ }
+ info.permissions = ( m_permissions & mask ) | ( permissions & ~mask );
+ /*kdDebug(7007) << "\n current permissions=" << TQString::number(permissions,8)
+ << "\n wanted permission=" << TQString::number(m_permissions,8)
+ << "\n with mask=" << TQString::number(mask,8)
+ << "\n with ~mask (mask bits we keep) =" << TQString::number((uint)~mask,8)
+ << "\n bits we keep =" << TQString::number(permissions & ~mask,8)
+ << "\n new permissions = " << TQString::number(info.permissions,8)
+ << endl;*/
+ // Prepend this info in our todo list.
+ // This way, the toplevel dirs are done last.
+ m_infos.prepend( info );
+ }
+ }
+}
+
+void ChmodJob::chmodNextFile()
+{
+ if ( !m_infos.isEmpty() )
+ {
+ ChmodInfo info = m_infos.first();
+ m_infos.remove( m_infos.begin() );
+ // First update group / owner (if local file)
+ // (permissions have to set after, in case of suid and sgid)
+ if ( info.url.isLocalFile() && ( m_newOwner != -1 || m_newGroup != -1 ) )
+ {
+ TQString path = info.url.path();
+ if ( chown( TQFile::encodeName(path), m_newOwner, m_newGroup ) != 0 )
+ {
+ int answer = KMessageBox::warningContinueCancel( 0, i18n( "<qt>Could not modify the ownership of file <b>%1</b>. You have insufficient access to the file to perform the change.</qt>" ).arg(path), TQString::null, i18n("&Skip File") );
+ if (answer == KMessageBox::Cancel)
+ {
+ m_error = ERR_USER_CANCELED;
+ emitResult();
+ return;
+ }
+ }
+ }
+
+ kdDebug(7007) << "ChmodJob::chmodNextFile chmod'ing " << info.url.prettyURL()
+ << " to " << TQString::number(info.permissions,8) << endl;
+ TDEIO::SimpleJob * job = TDEIO::chmod( info.url, info.permissions );
+ // copy the metadata for acl and default acl
+ const TQString aclString = queryMetaData( "ACL_STRING" );
+ const TQString defaultAclString = queryMetaData( "DEFAULT_ACL_STRING" );
+ if ( !aclString.isEmpty() )
+ job->addMetaData( "ACL_STRING", aclString );
+ if ( !defaultAclString.isEmpty() )
+ job->addMetaData( "DEFAULT_ACL_STRING", defaultAclString );
+ addSubjob(job);
+ }
+ else
+ // We have finished
+ emitResult();
+}
+
+void ChmodJob::slotResult( TDEIO::Job * job )
+{
+ if ( job->error() )
+ {
+ m_error = job->error();
+ m_errorText = job->errorText();
+ emitResult();
+ return;
+ }
+ //kdDebug(7007) << " ChmodJob::slotResult( TDEIO::Job * job ) m_lstItems:" << m_lstItems.count() << endl;
+ switch ( state )
+ {
+ case STATE_LISTING:
+ subjobs.remove(job);
+ m_lstItems.removeFirst();
+ kdDebug(7007) << "ChmodJob::slotResult -> processList" << endl;
+ processList();
+ return;
+ case STATE_CHMODING:
+ subjobs.remove(job);
+ kdDebug(7007) << "ChmodJob::slotResult -> chmodNextFile" << endl;
+ chmodNextFile();
+ return;
+ default:
+ assert(0);
+ return;
+ }
+}
+
+// antlarr: KDE 4: Make owner and group be const TQString &
+TDEIO_EXPORT ChmodJob *TDEIO::chmod( const KFileItemList& lstItems, int permissions, int mask,
+ TQString owner, TQString group,
+ bool recursive, bool showProgressInfo )
+{
+ uid_t newOwnerID = (uid_t)-1; // chown(2) : -1 means no change
+ if ( !owner.isEmpty() )
+ {
+ struct passwd* pw = getpwnam(TQFile::encodeName(owner));
+ if ( pw == 0L )
+ kdError(250) << " ERROR: No user " << owner << endl;
+ else
+ newOwnerID = pw->pw_uid;
+ }
+ gid_t newGroupID = (gid_t)-1; // chown(2) : -1 means no change
+ if ( !group.isEmpty() )
+ {
+ struct group* g = getgrnam(TQFile::encodeName(group));
+ if ( g == 0L )
+ kdError(250) << " ERROR: No group " << group << endl;
+ else
+ newGroupID = g->gr_gid;
+ }
+ return new ChmodJob( lstItems, permissions, mask, newOwnerID, newGroupID, recursive, showProgressInfo );
+}
+
+void ChmodJob::virtual_hook( int id, void* data )
+{ TDEIO::Job::virtual_hook( id, data ); }
+
+#include "chmodjob.moc"
diff --git a/tdeio/tdeio/chmodjob.h b/tdeio/tdeio/chmodjob.h
new file mode 100644
index 000000000..105df0e4d
--- /dev/null
+++ b/tdeio/tdeio/chmodjob.h
@@ -0,0 +1,109 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_chmodjob_h__
+#define __kio_chmodjob_h__
+
+#include <kurl.h>
+#include <tqstring.h>
+
+#include <tdeio/global.h>
+#include <tdeio/job.h>
+#include <tdefileitem.h>
+
+namespace TDEIO {
+
+ /**
+ * This job changes permissions on a list of files or directories,
+ * optionally in a recursive manner.
+ * @see TDEIO::chmod()
+ */
+ class TDEIO_EXPORT ChmodJob : public TDEIO::Job
+ {
+ Q_OBJECT
+ public:
+ /**
+ * Create new ChmodJobs using the TDEIO::chmod() function.
+ */
+ ChmodJob( const KFileItemList & lstItems, int permissions, int mask,
+ int newOwner, int newGroup,
+ bool recursive, bool showProgressInfo );
+
+ protected:
+ void chmodNextFile();
+
+ protected slots:
+
+ virtual void slotResult( TDEIO::Job *job );
+ void slotEntries( TDEIO::Job * , const TDEIO::UDSEntryList & );
+ void processList();
+
+ private:
+ struct ChmodInfo
+ {
+ KURL url;
+ int permissions;
+ };
+ enum { STATE_LISTING, STATE_CHMODING } state;
+ int m_permissions;
+ int m_mask;
+ int m_newOwner;
+ int m_newGroup;
+ bool m_recursive;
+ KFileItemList m_lstItems;
+ TQValueList<ChmodInfo> m_infos;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class ChmodJobPrivate* d;
+ };
+
+
+ /**
+ * Creates a job that changes permissions/ownership on several files or directories,
+ * optionally recursively.
+ * This version of chmod uses a KFileItemList so that it directly knows
+ * what to do with the items. TODO: a version that takes a KURL::List,
+ * and a general job that stats each url and returns a KFileItemList.
+ *
+ * Note that change of ownership is only supported for local files.
+ *
+ * Inside directories, the "x" bits will only be changed for files that had
+ * at least one "x" bit before, and for directories.
+ * This emulates the behavior of chmod +X.
+ *
+ * @param lstItems The file items representing several files or directories.
+ * @param permissions the permissions we want to set
+ * @param mask the bits we are allowed to change.
+ * For instance, if mask is 0077, we don't change
+ * the "user" bits, only "group" and "others".
+ * @param newOwner If non-empty, the new owner for the files
+ * @param newGroup If non-empty, the new group for the files
+ * @param recursive whether to open directories recursively
+ * @param showProgressInfo true to show progess information
+ * @return The job handling the operation.
+ */
+ TDEIO_EXPORT ChmodJob * chmod( const KFileItemList& lstItems, int permissions, int mask,
+ TQString newOwner, TQString newGroup,
+ bool recursive, bool showProgressInfo = true );
+
+}
+
+#endif
diff --git a/kio/kio/configure.in.in b/tdeio/tdeio/configure.in.in
index 8683dfec1..8683dfec1 100644
--- a/kio/kio/configure.in.in
+++ b/tdeio/tdeio/configure.in.in
diff --git a/tdeio/tdeio/connection.cpp b/tdeio/tdeio/connection.cpp
new file mode 100644
index 000000000..cbe737693
--- /dev/null
+++ b/tdeio/tdeio/connection.cpp
@@ -0,0 +1,273 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#include <config.h>
+
+#include <kde_file.h>
+#include <ksock.h>
+#include <tqtimer.h>
+
+#include <sys/types.h>
+#include <sys/signal.h>
+#include <sys/time.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "tdeio/connection.h"
+
+#include <kdebug.h>
+#include <tqsocketnotifier.h>
+
+using namespace TDEIO;
+
+Connection::Connection()
+{
+ f_out = 0;
+ fd_in = -1;
+ socket = 0;
+ notifier = 0;
+ receiver = 0;
+ member = 0;
+ m_suspended = false;
+ tasks.setAutoDelete(true);
+}
+
+Connection::~Connection()
+{
+ close();
+}
+
+void Connection::suspend()
+{
+ m_suspended = true;
+ if (notifier)
+ notifier->setEnabled(false);
+}
+
+void Connection::resume()
+{
+ m_suspended = false;
+ if (notifier)
+ notifier->setEnabled(true);
+}
+
+void Connection::close()
+{
+ delete notifier;
+ notifier = 0;
+ delete socket;
+ socket = 0;
+
+ // TDESocket has already closed the file descriptor, but we need to
+ // close the file-stream as well otherwise we leak memory.
+ // As a result we close the file descriptor twice, but that should
+ // be harmless
+ // KDE4: fix this
+ if (f_out)
+ fclose(f_out);
+ f_out = 0;
+ fd_in = -1;
+ tasks.clear();
+}
+
+void Connection::send(int cmd, const TQByteArray& data)
+{
+ if (!inited() || tasks.count() > 0) {
+ Task *task = new Task();
+ task->cmd = cmd;
+ task->data = data;
+ tasks.append(task);
+ } else {
+ sendnow( cmd, data );
+ }
+}
+
+void Connection::dequeue()
+{
+ if (!inited())
+ return;
+
+ while (tasks.count())
+ {
+ tasks.first();
+ Task *task = tasks.take();
+ sendnow( task->cmd, task->data );
+ delete task;
+ }
+}
+
+void Connection::init(TDESocket *sock)
+{
+ delete notifier;
+ notifier = 0;
+#ifdef Q_OS_UNIX //TODO: not yet available on WIN32
+ delete socket;
+ socket = sock;
+ fd_in = socket->socket();
+ f_out = KDE_fdopen( socket->socket(), "wb" );
+#endif
+ if (receiver && ( fd_in != -1 )) {
+ notifier = new TQSocketNotifier(fd_in, TQSocketNotifier::Read);
+ if ( m_suspended ) {
+ suspend();
+ }
+ TQObject::connect(notifier, TQT_SIGNAL(activated(int)), receiver, member);
+ }
+ dequeue();
+}
+
+void Connection::init(int _fd_in, int fd_out)
+{
+ delete notifier;
+ notifier = 0;
+ fd_in = _fd_in;
+ f_out = KDE_fdopen( fd_out, "wb" );
+ if (receiver && ( fd_in != -1 )) {
+ notifier = new TQSocketNotifier(fd_in, TQSocketNotifier::Read);
+ if ( m_suspended ) {
+ suspend();
+ }
+ TQObject::connect(notifier, TQT_SIGNAL(activated(int)), receiver, member);
+ }
+ dequeue();
+}
+
+
+void Connection::connect(TQObject *_receiver, const char *_member)
+{
+ receiver = _receiver;
+ member = _member;
+ delete notifier;
+ notifier = 0;
+ if (receiver && (fd_in != -1 )) {
+ notifier = new TQSocketNotifier(fd_in, TQSocketNotifier::Read);
+ if ( m_suspended )
+ suspend();
+ TQObject::connect(notifier, TQT_SIGNAL(activated(int)), receiver, member);
+ }
+}
+
+bool Connection::sendnow( int _cmd, const TQByteArray &data )
+{
+ if (f_out == 0) {
+ return false;
+ }
+
+ if (data.size() > 0xffffff)
+ return false;
+
+ static char buffer[ 64 ];
+ sprintf( buffer, "%6x_%2x_", data.size(), _cmd );
+
+ size_t n = fwrite( buffer, 1, 10, f_out );
+
+ if ( n != 10 ) {
+ kdError(7017) << "Could not send header" << endl;
+ return false;
+ }
+
+ n = fwrite( data.data(), 1, data.size(), f_out );
+
+ if ( n != data.size() ) {
+ kdError(7017) << "Could not write data" << endl;
+ return false;
+ }
+
+ if (fflush( f_out )) {
+ kdError(7017) << "Could not write data" << endl;
+ return false;
+ }
+
+ return true;
+}
+
+int Connection::read( int* _cmd, TQByteArray &data )
+{
+ if (fd_in == -1 ) {
+ kdError(7017) << "read: not yet inited" << endl;
+ return -1;
+ }
+
+ static char buffer[ 10 ];
+
+ again1:
+ ssize_t n = ::read( fd_in, buffer, 10);
+ if ( n == -1 && errno == EINTR )
+ goto again1;
+
+ if ( n == -1) {
+ kdError(7017) << "Header read failed, errno=" << errno << endl;
+ }
+
+ if ( n != 10 ) {
+ if ( n ) // 0 indicates end of file
+ kdError(7017) << "Header has invalid size (" << n << ")" << endl;
+ return -1;
+ }
+
+ buffer[ 6 ] = 0;
+ buffer[ 9 ] = 0;
+
+ char *p = buffer;
+ while( *p == ' ' ) p++;
+ long int len = strtol( p, 0L, 16 );
+
+ p = buffer + 7;
+ while( *p == ' ' ) p++;
+ long int cmd = strtol( p, 0L, 16 );
+
+ data.resize( len );
+
+ if ( len > 0L ) {
+ size_t bytesToGo = len;
+ size_t bytesRead = 0;
+ do {
+ n = ::read(fd_in, data.data()+bytesRead, bytesToGo);
+ if (n == -1) {
+ if (errno == EINTR)
+ continue;
+
+ kdError(7017) << "Data read failed, errno=" << errno << endl;
+ return -1;
+ }
+ if ( !n ) { // 0 indicates end of file
+ kdError(7017) << "Connection ended unexpectedly (" << n << "/" << bytesToGo << ")" << endl;
+ return -1;
+ }
+
+ bytesRead += n;
+ bytesToGo -= n;
+ }
+ while(bytesToGo);
+ }
+
+ *_cmd = cmd;
+ return len;
+}
+
+#include "connection.moc"
diff --git a/kio/kio/connection.h b/tdeio/tdeio/connection.h
index fb0b50e15..fb0b50e15 100644
--- a/kio/kio/connection.h
+++ b/tdeio/tdeio/connection.h
diff --git a/tdeio/tdeio/dataprotocol.cpp b/tdeio/tdeio/dataprotocol.cpp
new file mode 100644
index 000000000..acc7b28e9
--- /dev/null
+++ b/tdeio/tdeio/dataprotocol.cpp
@@ -0,0 +1,339 @@
+// dataprotocol.cpp
+// ==================
+//
+// Implementation of the data protocol (rfc 2397)
+//
+// Author: Leo Savernik
+// Email: l.savernik@aon.at
+// (C) 2002, 2003 by Leo Savernik
+// Created: Sam Dez 28 14:11:18 CET 2002
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; version 2. *
+ * *
+ ***************************************************************************/
+
+#include "dataprotocol.h"
+
+#include <kdebug.h>
+#include <kmdcodec.h>
+#include <kurl.h>
+#include <tdeio/global.h>
+
+#include <tqcstring.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqtextcodec.h>
+
+#ifdef DATAKIOSLAVE
+# include <kinstance.h>
+# include <stdlib.h>
+#endif
+#ifdef TESTKIO
+# include <iostream.h>
+#endif
+
+#if !defined(DATAKIOSLAVE) && !defined(TESTKIO)
+# define DISPATCH(f) dispatch_##f
+#else
+# define DISPATCH(f) f
+#endif
+
+using namespace TDEIO;
+#ifdef DATAKIOSLAVE
+extern "C" {
+
+ int kdemain( int argc, char **argv ) {
+ TDEInstance instance( "kio_data" );
+
+ kdDebug(7101) << "*** Starting kio_data " << endl;
+
+ if (argc != 4) {
+ kdDebug(7101) << "Usage: kio_data protocol domain-socket1 domain-socket2" << endl;
+ exit(-1);
+ }
+
+ DataProtocol slave(argv[2], argv[3]);
+ slave.dispatchLoop();
+
+ kdDebug(7101) << "*** kio_data Done" << endl;
+ return 0;
+ }
+}
+#endif
+
+/** structure containing header information */
+struct DataHeader {
+ TQString mime_type; // mime type of content (lowercase)
+ MetaData attributes; // attribute/value pairs (attribute lowercase,
+ // value unchanged)
+ bool is_base64; // true if data is base64 encoded
+ TQString url; // reference to decoded url
+ int data_offset; // zero-indexed position within url
+ // where the real data begins. May point beyond
+ // the end to indicate that there is no data
+ TQString *charset; // shortcut to charset (it always exists)
+};
+
+// constant string data
+const TQChar text_plain_str[] = { 't','e','x','t','/','p','l','a','i','n' };
+const TQChar charset_str[] = { 'c','h','a','r','s','e','t' };
+const TQChar us_ascii_str[] = { 'u','s','-','a','s','c','i','i' };
+const TQChar base64_str[] = { 'b','a','s','e','6','4' };
+
+/** returns the position of the first occurrence of any of the given characters
+ * @p c1 to @p c3 or buf.length() if none is contained.
+ * @param buf buffer where to look for c
+ * @param begin zero-indexed starting position
+ * @param c1 character to find
+ * @param c2 alternative character to find or '\0' to ignore
+ * @param c3 alternative character to find or '\0' to ignore
+ */
+static int find(const TQString &buf, int begin, TQChar c1, TQChar c2 = '\0',
+ TQChar c3 = '\0') {
+ int pos = begin;
+ int size = (int)buf.length();
+ while (pos < size) {
+ TQChar ch = buf[pos];
+ if (ch == c1
+ || (c2 != '\0' && ch == c2)
+ || (c3 != '\0' && ch == c3))
+ break;
+ pos++;
+ }/*wend*/
+ return pos;
+}
+
+/** extracts the string between the current position @p pos and the first
+ * occurrence of either @p c1 to @p c3 exclusively and updates @p pos
+ * to point at the found delimiter or at the end of the buffer if
+ * neither character occurred.
+ * @param buf buffer where to look for
+ * @param pos zero-indexed position within buffer
+ * @param c1 character to find
+ * @param c2 alternative character to find or 0 to ignore
+ * @param c3 alternative character to find or 0 to ignore
+ */
+inline TQString extract(const TQString &buf, int &pos, TQChar c1,
+ TQChar c2 = '\0', TQChar c3 = '\0') {
+ int oldpos = pos;
+ pos = find(buf,oldpos,c1,c2,c3);
+ return TQString(buf.unicode() + oldpos, pos - oldpos);
+}
+
+/** ignores all whitespaces
+ * @param buf buffer to operate on
+ * @param pos position to shift to first non-whitespace character
+ * Upon return @p pos will either point to the first non-whitespace
+ * character or to the end of the buffer.
+ */
+inline void ignoreWS(const TQString &buf, int &pos) {
+ int size = (int)buf.length();
+ TQChar ch = buf[pos];
+ while (pos < size && (ch == ' ' || ch == '\t' || ch == '\n'
+ || ch == '\r'))
+ ch = buf[++pos];
+}
+
+/** parses a quoted string as per rfc 822.
+ *
+ * If trailing quote is missing, the whole rest of the buffer is returned.
+ * @param buf buffer to operate on
+ * @param pos position pointing to the leading quote
+ * @return the extracted string. @p pos will be updated to point to the
+ * character following the trailing quote.
+ */
+static TQString parseQuotedString(const TQString &buf, int &pos) {
+ int size = (int)buf.length();
+ TQString res;
+ pos++; // jump over leading quote
+ bool escaped = false; // if true means next character is literal
+ bool parsing = true; // true as long as end quote not found
+ while (parsing && pos < size) {
+ TQChar ch = buf[pos++];
+ if (escaped) {
+ res += ch;
+ escaped = false;
+ } else {
+ switch (ch) {
+ case '"': parsing = false; break;
+ case '\\': escaped = true; break;
+ default: res += ch; break;
+ }/*end switch*/
+ }/*end if*/
+ }/*wend*/
+ return res;
+}
+
+/** parses the header of a data url
+ * @param url the data url
+ * @param header_info fills the given DataHeader structure with the header
+ * information
+ */
+static void parseDataHeader(const KURL &url, DataHeader &header_info) {
+ TQConstString text_plain(text_plain_str,sizeof text_plain_str/sizeof text_plain_str[0]);
+ TQConstString charset(charset_str,sizeof charset_str/sizeof charset_str[0]);
+ TQConstString us_ascii(us_ascii_str,sizeof us_ascii_str/sizeof us_ascii_str[0]);
+ TQConstString base64(base64_str,sizeof base64_str/sizeof base64_str[0]);
+ // initialize header info members
+ header_info.mime_type = text_plain.string();
+ header_info.charset = &header_info.attributes.insert(
+ charset.string(),us_ascii.string())
+ .data();
+ header_info.is_base64 = false;
+
+ // decode url and save it
+ TQString &raw_url = header_info.url = TQString::fromLatin1("data:") + url.path();
+ int raw_url_len = (int)raw_url.length();
+
+ // jump over scheme part (must be "data:", we don't even check that)
+ header_info.data_offset = raw_url.find(':');
+ header_info.data_offset++; // jump over colon or to begin if scheme was missing
+
+ // read mime type
+ if (header_info.data_offset >= raw_url_len) return;
+ TQString mime_type = extract(raw_url,header_info.data_offset,';',',')
+ .stripWhiteSpace();
+ if (!mime_type.isEmpty()) header_info.mime_type = mime_type;
+
+ if (header_info.data_offset >= raw_url_len) return;
+ // jump over delimiter token and return if data reached
+ if (raw_url[header_info.data_offset++] == ',') return;
+
+ // read all attributes and store them
+ bool data_begin_reached = false;
+ while (!data_begin_reached && header_info.data_offset < raw_url_len) {
+ // read attribute
+ TQString attribute = extract(raw_url,header_info.data_offset,'=',';',',')
+ .stripWhiteSpace();
+ if (header_info.data_offset >= raw_url_len
+ || raw_url[header_info.data_offset] != '=') {
+ // no assigment, must be base64 option
+ if (attribute == base64.string())
+ header_info.is_base64 = true;
+ } else {
+ header_info.data_offset++; // jump over '=' token
+
+ // read value
+ ignoreWS(raw_url,header_info.data_offset);
+ if (header_info.data_offset >= raw_url_len) return;
+
+ TQString value;
+ if (raw_url[header_info.data_offset] == '"') {
+ value = parseQuotedString(raw_url,header_info.data_offset);
+ ignoreWS(raw_url,header_info.data_offset);
+ } else
+ value = extract(raw_url,header_info.data_offset,';',',')
+ .stripWhiteSpace();
+
+ // add attribute to map
+ header_info.attributes[attribute.lower()] = value;
+
+ }/*end if*/
+ if (header_info.data_offset < raw_url_len
+ && raw_url[header_info.data_offset] == ',')
+ data_begin_reached = true;
+ header_info.data_offset++; // jump over separator token
+ }/*wend*/
+}
+
+#ifdef DATAKIOSLAVE
+DataProtocol::DataProtocol(const TQCString &pool_socket, const TQCString &app_socket)
+ : SlaveBase("kio_data", pool_socket, app_socket) {
+#else
+DataProtocol::DataProtocol() {
+#endif
+ kdDebug() << "DataProtocol::DataProtocol()" << endl;
+}
+
+/* --------------------------------------------------------------------- */
+
+DataProtocol::~DataProtocol() {
+ kdDebug() << "DataProtocol::~DataProtocol()" << endl;
+}
+
+/* --------------------------------------------------------------------- */
+
+void DataProtocol::get(const KURL& url) {
+ ref();
+ //kdDebug() << "===============================================================================================================================================================================" << endl;
+ kdDebug() << "kio_data@"<<this<<"::get(const KURL& url)" << endl ;
+
+ DataHeader hdr;
+ parseDataHeader(url,hdr);
+
+ int size = (int)hdr.url.length();
+ int data_ofs = QMIN(hdr.data_offset,size);
+ // FIXME: string is copied, would be nice if we could have a reference only
+ TQString url_data = hdr.url.mid(data_ofs);
+ TQCString outData;
+
+#ifdef TESTKIO
+// cout << "current charset: \"" << *hdr.charset << "\"" << endl;
+#endif
+ if (hdr.is_base64) {
+ // base64 stuff is expected to contain the correct charset, so we just
+ // decode it and pass it to the receiver
+ KCodecs::base64Decode(url_data.local8Bit(),outData);
+ } else {
+ // FIXME: This is all flawed, must be reworked thoroughly
+ // non encoded data must be converted to the given charset
+ TQTextCodec *codec = TQTextCodec::codecForName(hdr.charset->latin1());
+ if (codec != 0) {
+ outData = codec->fromUnicode(url_data);
+ } else {
+ // if there is no approprate codec, just use local encoding. This
+ // should work for >90% of all cases.
+ outData = url_data.local8Bit();
+ }/*end if*/
+ }/*end if*/
+
+ //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
+ //kdDebug() << "emit mimeType@"<<this << endl ;
+ mimeType(hdr.mime_type);
+ //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
+ //kdDebug() << "emit totalSize@"<<this << endl ;
+ totalSize(outData.size());
+
+ //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
+ //kdDebug() << "emit setMetaData@"<<this << endl ;
+#if defined(TESTKIO) || defined(DATAKIOSLAVE)
+ MetaData::ConstIterator it;
+ for (it = hdr.attributes.begin(); it != hdr.attributes.end(); ++it) {
+ setMetaData(it.key(),it.data());
+ }/*next it*/
+#else
+ setAllMetaData(hdr.attributes);
+#endif
+
+ //kdDebug() << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
+ //kdDebug() << "emit sendMetaData@"<<this << endl ;
+ sendMetaData();
+ //kdDebug() << "^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C^[[C" << endl;
+// kdDebug() << "(1) queue size " << dispatchQueue.size() << endl;
+ // empiric studies have shown that this shouldn't be queued & dispatched
+ /*DISPATCH*/(data(outData));
+// kdDebug() << "(2) queue size " << dispatchQueue.size() << endl;
+ DISPATCH(data(TQByteArray()));
+// kdDebug() << "(3) queue size " << dispatchQueue.size() << endl;
+ DISPATCH(finished());
+// kdDebug() << "(4) queue size " << dispatchQueue.size() << endl;
+ deref();
+}
+
+/* --------------------------------------------------------------------- */
+
+void DataProtocol::mimetype(const KURL &url) {
+ ref();
+ DataHeader hdr;
+ parseDataHeader(url,hdr);
+ mimeType(hdr.mime_type);
+ finished();
+ deref();
+}
+
+/* --------------------------------------------------------------------- */
+
diff --git a/tdeio/tdeio/dataprotocol.h b/tdeio/tdeio/dataprotocol.h
new file mode 100644
index 000000000..ed9bfc325
--- /dev/null
+++ b/tdeio/tdeio/dataprotocol.h
@@ -0,0 +1,71 @@
+// dataprotocol.h
+// ================
+//
+// Interface of the KDE data protocol core operations
+//
+// Author: Leo Savernik
+// Email: l.savernik@aon.at
+// (C) 2002 by Leo Savernik
+// Created: Sam Dez 28 14:11:18 CET 2002
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; version 2. *
+ * *
+ ***************************************************************************/
+
+#ifndef __dataprotocol_h__
+#define __dataprotocol_h__
+
+// dataprotocol.* interprets the following defines
+// DATAKIOSLAVE: define if you want to compile this into a stand-alone
+// tdeioslave
+// TESTKIO: define for test-driving
+// Both defines are mutually exclusive. Defining none of them compiles
+// DataProtocol for internal usage within libtdeiocore.
+
+class TQString;
+class TQCString;
+
+class KURL;
+
+#if defined(DATAKIOSLAVE)
+# include <tdeio/slavebase.h>
+#elif !defined(TESTKIO)
+# include "tdeio/dataslave.h"
+#endif
+
+namespace TDEIO {
+
+/** This tdeioslave provides support of data urls as specified by rfc 2397
+ * @see http://www.ietf.org/rfc/rfc2397.txt
+ * @author Leo Savernik
+ */
+#if defined(DATAKIOSLAVE)
+class DataProtocol : public TDEIO::SlaveBase {
+#elif defined(TESTKIO)
+class DataProtocol : public TestSlave {
+#else
+class DataProtocol : public DataSlave {
+#endif
+
+public:
+#if defined(DATAKIOSLAVE)
+ DataProtocol(const TQCString &pool_socket, const TQCString &app_socket);
+#else
+ DataProtocol();
+#endif
+ virtual ~DataProtocol();
+ virtual void mimetype(const KURL &url);
+ virtual void get(const KURL &url);
+#if defined(TESTKIO)
+ void ref() {}
+ void deref() {}
+#endif
+};
+
+}/*end namespace*/
+
+#endif
diff --git a/kio/kio/dataslave.cpp b/tdeio/tdeio/dataslave.cpp
index 528368ba5..528368ba5 100644
--- a/kio/kio/dataslave.cpp
+++ b/tdeio/tdeio/dataslave.cpp
diff --git a/tdeio/tdeio/dataslave.h b/tdeio/tdeio/dataslave.h
new file mode 100644
index 000000000..40cfef126
--- /dev/null
+++ b/tdeio/tdeio/dataslave.h
@@ -0,0 +1,126 @@
+// -*- c++ -*-
+/*
+ * This file is part of the KDE libraries
+ * Copyright (c) 2003 Leo Savernik <l.savernik@aon.at>
+ * Derived from slave.h
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#ifndef __KIO_DATASLAVE_H__
+#define __KIO_DATASLAVE_H__
+
+#include <tdeio/global.h>
+#include <tdeio/slave.h>
+
+class TQTimer;
+
+// don't forget to sync DISPATCH_IMPL in dataslave.h
+#define DISPATCH_DECL(type) \
+ void dispatch_##type();
+
+// don't forget to sync DISPATCH_IMPL1 in dataslave.h
+#define DISPATCH_DECL1(type, paramtype, param) \
+ void dispatch_##type(paramtype param);
+
+namespace TDEIO {
+
+ /**
+ * This class provides a high performance implementation for the data
+ * url scheme (rfc2397).
+ *
+ * @internal
+ * Do not use this class in external applications. It is an implementation
+ * detail of KIO and subject to change without notice.
+ * @author Leo Savernik
+ */
+ class DataSlave : public TDEIO::Slave {
+ Q_OBJECT
+ public:
+ DataSlave();
+
+ virtual ~DataSlave();
+
+ virtual void setHost(const TQString &host, int port,
+ const TQString &user, const TQString &passwd);
+ virtual void setConfig(const MetaData &config);
+
+ virtual void suspend();
+ virtual void resume();
+ virtual bool suspended();
+ virtual void send(int cmd, const TQByteArray &data = TQByteArray());
+
+ virtual void hold(const KURL &url);
+
+ // pure virtual methods that are defined by the actual protocol
+ virtual void get(const KURL &url) = 0;
+ virtual void mimetype(const KURL &url) = 0;
+
+ protected:
+ /**
+ * Sets metadata
+ * @internal
+ */
+ void setAllMetaData(const MetaData &);
+ /**
+ * Sends metadata set with setAllMetaData
+ * @internal
+ */
+ void sendMetaData();
+
+ // queueing methods
+ /** identifiers of functions to be queued */
+ enum QueueType { Queue_mimeType = 1, Queue_totalSize,
+ Queue_sendMetaData, Queue_data, Queue_finished };
+ /** structure for queueing. It is very primitive, it doesn't
+ * even try to conserve memory.
+ */
+ struct QueueStruct {
+ QueueType type;
+ TQString s;
+ TDEIO::filesize_t size;
+ TQByteArray ba;
+
+ QueueStruct() {}
+ QueueStruct(QueueType type) : type(type) {}
+ };
+ typedef TQValueList<QueueStruct> DispatchQueue;
+ DispatchQueue dispatchQueue;
+
+ DISPATCH_DECL1(mimeType, const TQString &, s)
+ DISPATCH_DECL1(totalSize, TDEIO::filesize_t, size)
+ DISPATCH_DECL(sendMetaData)
+ DISPATCH_DECL1(data, const TQByteArray &, ba)
+ DISPATCH_DECL(finished)
+
+ protected slots:
+ /** dispatches next queued method. Does nothing if there are no
+ * queued methods.
+ */
+ void dispatchNext();
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ MetaData meta_data;
+ bool _suspended;
+ TQTimer *timer;
+ };
+
+}
+
+#undef DISPATCH_DECL
+#undef DISPATCH_DECL1
+
+#endif /*__KIO_DATASLAVE_H__*/
diff --git a/tdeio/tdeio/davjob.cpp b/tdeio/tdeio/davjob.cpp
new file mode 100644
index 000000000..986e76342
--- /dev/null
+++ b/tdeio/tdeio/davjob.cpp
@@ -0,0 +1,142 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Jan-Pascal van Best <janpascal@vanbest.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <kurl.h>
+
+#include <tqobject.h>
+#include <tqptrlist.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqguardedptr.h>
+#include <tqdom.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <kdebug.h>
+#include <tdeio/jobclasses.h>
+#include <tdeio/global.h>
+#include <tdeio/http.h>
+#include <tdeio/davjob.h>
+#include <tdeio/job.h>
+#include <tdeio/slaveinterface.h>
+
+#define KIO_ARGS TQByteArray packedArgs; TQDataStream stream( packedArgs, IO_WriteOnly ); stream
+
+using namespace TDEIO;
+
+class DavJob::DavJobPrivate
+{
+public:
+ TQByteArray savedStaticData;
+ TQByteArray str_response; // replaces the TQString previously used in DavJob itself
+};
+
+DavJob::DavJob( const KURL& url, int method, const TQString& request, bool showProgressInfo )
+ : TransferJob( url, TDEIO::CMD_SPECIAL, TQByteArray(), TQByteArray(), showProgressInfo )
+{
+ d = new DavJobPrivate;
+ // We couldn't set the args when calling the parent constructor,
+ // so do it now.
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << (int) 7 << url << method;
+ // Same for static data
+ if ( ! request.isEmpty() && ! request.isNull() ) {
+ staticData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + request.utf8();
+ staticData.truncate( staticData.size() - 1 );
+ d->savedStaticData = staticData.copy();
+ }
+}
+
+void DavJob::slotData( const TQByteArray& data )
+{
+ if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error) {
+ unsigned int oldSize = d->str_response.size();
+ d->str_response.resize( oldSize + data.size() );
+ memcpy( d->str_response.data() + oldSize, data.data(), data.size() );
+ }
+}
+
+void DavJob::slotFinished()
+{
+ // kdDebug(7113) << "DavJob::slotFinished()" << endl;
+ // kdDebug(7113) << d->str_response << endl;
+ if (!m_redirectionURL.isEmpty() && m_redirectionURL.isValid() && (m_command == CMD_SPECIAL)) {
+ TQDataStream istream( m_packedArgs, IO_ReadOnly );
+ int s_cmd, s_method;
+ KURL s_url;
+ istream >> s_cmd;
+ istream >> s_url;
+ istream >> s_method;
+ // PROPFIND
+ if ( (s_cmd == 7) && (s_method == (int)TDEIO::DAV_PROPFIND) ) {
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << (int)7 << m_redirectionURL << (int)TDEIO::DAV_PROPFIND;
+ }
+ } else if ( ! m_response.setContent( d->str_response, true ) ) {
+ // An error occurred parsing the XML response
+ TQDomElement root = m_response.createElementNS( "DAV:", "error-report" );
+ m_response.appendChild( root );
+
+ TQDomElement el = m_response.createElementNS( "DAV:", "offending-response" );
+ TQDomText textnode = m_response.createTextNode( d->str_response );
+ el.appendChild( textnode );
+ root.appendChild( el );
+ delete d; // Should be in virtual destructor
+ d = 0;
+ } else {
+ delete d; // Should be in virtual destructor
+ d = 0;
+ }
+ // kdDebug(7113) << m_response.toString() << endl;
+ TransferJob::slotFinished();
+ if( d ) staticData = d->savedStaticData.copy(); // Need to send DAV request to this host too
+}
+
+/* Convenience methods */
+
+// KDE 4: Make it const TQString &
+DavJob* TDEIO::davPropFind( const KURL& url, const TQDomDocument& properties, TQString depth, bool showProgressInfo )
+{
+ DavJob *job = new DavJob( url, (int) TDEIO::DAV_PROPFIND, properties.toString(), showProgressInfo );
+ job->addMetaData( "davDepth", depth );
+ return job;
+}
+
+
+DavJob* TDEIO::davPropPatch( const KURL& url, const TQDomDocument& properties, bool showProgressInfo )
+{
+ return new DavJob( url, (int) TDEIO::DAV_PROPPATCH, properties.toString(), showProgressInfo );
+}
+
+DavJob* TDEIO::davSearch( const KURL& url, const TQString& nsURI, const TQString& qName, const TQString& query, bool showProgressInfo )
+{
+ TQDomDocument doc;
+ TQDomElement searchrequest = doc.createElementNS( "DAV:", "searchrequest" );
+ TQDomElement searchelement = doc.createElementNS( nsURI, qName );
+ TQDomText text = doc.createTextNode( query );
+ searchelement.appendChild( text );
+ searchrequest.appendChild( searchelement );
+ doc.appendChild( searchrequest );
+ return new DavJob( url, TDEIO::DAV_SEARCH, doc.toString(), showProgressInfo );
+}
+
+#include "davjob.moc"
diff --git a/tdeio/tdeio/davjob.h b/tdeio/tdeio/davjob.h
new file mode 100644
index 000000000..1bbb722d0
--- /dev/null
+++ b/tdeio/tdeio/davjob.h
@@ -0,0 +1,127 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Jan-Pascal van Best <janpascal@vanbest.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_davjob_h__
+#define __kio_davjob_h__
+
+#include <kurl.h>
+
+#include <tqobject.h>
+#include <tqptrlist.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqguardedptr.h>
+#include <tqdom.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <tdeio/jobclasses.h>
+#include <tdeio/global.h>
+
+class Observer;
+class TQTimer;
+
+namespace TDEIO {
+
+ class Slave;
+ class SlaveInterface;
+
+ /**
+ * The transfer job pumps data into and/or out of a Slave.
+ * Data is sent to the slave on request of the slave ( dataReq).
+ * If data coming from the slave can not be handled, the
+ * reading of data from the slave should be suspended.
+ * @see TDEIO::davPropFind()
+ * @see TDEIO::davPropPatch()
+ * @see TDEIO::davSearch()
+ * @since 3.1
+ */
+ class TDEIO_EXPORT DavJob : public TransferJob {
+ Q_OBJECT
+
+ public:
+ /**
+ * Use TDEIO::davPropFind(), TDEIO::davPropPatch() and
+ * TDEIO::davSearch() to create a new DavJob.
+ */
+ DavJob(const KURL& url, int method,
+ const TQString& request, bool showProgressInfo);
+ /**
+ * Returns the response as a TQDomDocument.
+ * @return the response document
+ */
+ TQDomDocument& response() { return m_response; }
+
+ protected slots:
+ virtual void slotFinished();
+ virtual void slotData( const TQByteArray &data);
+
+ protected:
+ bool m_suspended;
+ TransferJob *m_subJob;
+ private:
+ class DavJobPrivate;
+ DavJobPrivate *d;
+ TQString dummy; // kept around for BC reasons
+ TQDomDocument m_response;
+ };
+
+ /**
+ * Creates a new DavJob that issues a PROPFIND command. PROPFIND retrieves
+ * the properties of the resource identified by the given @p url.
+ *
+ * @param url the URL of the resource
+ * @param properties a propfind document that describes the properties that
+ * should be retrieved
+ * @param depth the depth of the request. Can be "0", "1" or "infinity"
+ * @param showProgressInfo true to show progress information
+ * @return the new DavJob
+ */
+ TDEIO_EXPORT DavJob* davPropFind( const KURL& url, const TQDomDocument& properties, TQString depth, bool showProgressInfo=true );
+
+ /**
+ * Creates a new DavJob that issues a PROPPATCH command. PROPPATCH sets
+ * the properties of the resource identified by the given @p url.
+ *
+ * @param url the URL of the resource
+ * @param properties a PROPPACTCH document that describes the properties that
+ * should be modified and its new values
+ * @param showProgressInfo true to show progress information
+ * @return the new DavJob
+ */
+ TDEIO_EXPORT DavJob* davPropPatch( const KURL& url, const TQDomDocument& properties, bool showProgressInfo=true );
+
+ /**
+ * Creates a new DavJob that issues a SEARCH command.
+ *
+ * @param url the URL of the resource
+ * @param nsURI the URI of the search method's qualified name
+ * @param qName the local part of the search method's qualified name
+ * @param query the search string
+ * @param showProgressInfo true to show progress information
+ * @return the new DavJob
+ */
+ TDEIO_EXPORT DavJob* davSearch( const KURL &url, const TQString& nsURI, const TQString& qName, const TQString& query, bool showProgressInfo=true );
+
+}
+
+#endif
+
diff --git a/tdeio/tdeio/defaultprogress.cpp b/tdeio/tdeio/defaultprogress.cpp
new file mode 100644
index 000000000..a4de9c31b
--- /dev/null
+++ b/tdeio/tdeio/defaultprogress.cpp
@@ -0,0 +1,507 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Matej Koss <koss@miesto.sk>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqtimer.h>
+#include <tqlayout.h>
+#include <tqtooltip.h>
+#include <tqdatetime.h>
+#include <tqcheckbox.h>
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kdialog.h>
+#include <kstringhandler.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kiconloader.h>
+#include <kprocess.h>
+#include <kpushbutton.h>
+#include <kstandarddirs.h>
+#include <kstdguiitem.h>
+#include <klineedit.h>
+
+#ifdef Q_WS_X11
+#include <twin.h>
+#endif
+
+#include "jobclasses.h"
+#include "defaultprogress.h"
+
+namespace TDEIO {
+
+class DefaultProgress::DefaultProgressPrivate
+{
+public:
+ bool keepOpenChecked;
+ bool noCaptionYet;
+ KPushButton *cancelClose;
+ KPushButton *openFile;
+ KPushButton *openLocation;
+ TQCheckBox *keepOpen;
+ KURL location;
+ TQTime startTime;
+};
+
+DefaultProgress::DefaultProgress( bool showNow )
+ : ProgressBase( 0 ),
+ m_iTotalSize(0), m_iTotalFiles(0), m_iTotalDirs(0),
+ m_iProcessedSize(0), m_iProcessedDirs(0), m_iProcessedFiles(0)
+{
+ init();
+
+ if ( showNow ) {
+ show();
+ }
+}
+
+DefaultProgress::DefaultProgress( TQWidget* parent, const char* /*name*/ )
+ : ProgressBase( parent ),
+ m_iTotalSize(0), m_iTotalFiles(0), m_iTotalDirs(0),
+ m_iProcessedSize(0), m_iProcessedDirs(0), m_iProcessedFiles(0)
+{
+ init();
+}
+
+bool DefaultProgress::keepOpen() const
+{
+ return d->keepOpenChecked;
+}
+
+void DefaultProgress::init()
+{
+ d = new DefaultProgressPrivate;
+
+#ifdef Q_WS_X11 //FIXME(E): Remove once all the KWin::foo calls have been ported to QWS
+ // Set a useful icon for this window!
+ KWin::setIcons( winId(),
+ TDEGlobal::iconLoader()->loadIcon( "filesave", KIcon::NoGroup, 32 ),
+ TDEGlobal::iconLoader()->loadIcon( "filesave", KIcon::NoGroup, 16 ) );
+#endif
+
+ TQVBoxLayout *topLayout = new TQVBoxLayout( this, KDialog::marginHint(),
+ KDialog::spacingHint() );
+ topLayout->addStrut( 360 ); // makes dlg at least that wide
+
+ TQGridLayout *grid = new TQGridLayout( 2, 3 );
+ topLayout->addLayout(TQT_TQLAYOUT(grid));
+ grid->addColSpacing(1, KDialog::spacingHint());
+ // filenames or action name
+ grid->addWidget(new TQLabel(i18n("Source:"), this), 0, 0);
+
+ sourceEdit = new KLineEdit(this);
+ sourceEdit->setReadOnly(true);
+ sourceEdit->setEnableSqueezedText(true);
+ grid->addWidget(sourceEdit, 0, 2);
+
+ destInvite = new TQLabel(i18n("Destination:"), this);
+ grid->addWidget(destInvite, 1, 0);
+
+ destEdit = new KLineEdit(this);
+ destEdit->setReadOnly (true);
+ destEdit->setEnableSqueezedText(true);
+ grid->addWidget(destEdit, 1, 2);
+
+ m_pProgressBar = new KProgress(this);
+ topLayout->addWidget( m_pProgressBar );
+
+ // processed info
+ TQHBoxLayout *hBox = new TQHBoxLayout();
+ topLayout->addLayout(hBox);
+
+ sizeLabel = new TQLabel(this);
+ hBox->addWidget(sizeLabel);
+
+ resumeLabel = new TQLabel(this);
+ hBox->addWidget(resumeLabel);
+
+ progressLabel = new TQLabel( this );
+/* progressLabel->setSizePolicy( TQSizePolicy( TQSizePolicy::MinimumExpanding,
+ TQSizePolicy::Preferred ) );*/
+ progressLabel->setAlignment( TQLabel::AlignRight );
+ hBox->addWidget( progressLabel );
+
+ hBox = new TQHBoxLayout();
+ topLayout->addLayout(hBox);
+
+ speedLabel = new TQLabel(this);
+ hBox->addWidget(speedLabel, 1);
+
+ TQFrame *line = new TQFrame( this );
+ line->setFrameShape( TQFrame::HLine );
+ line->setFrameShadow( TQFrame::Sunken );
+ topLayout->addWidget( line );
+
+ d->keepOpen = new TQCheckBox( i18n("&Keep this window open after transfer is complete"), this);
+ connect( d->keepOpen, TQT_SIGNAL( toggled(bool) ), TQT_SLOT( slotKeepOpenToggled(bool) ) );
+ topLayout->addWidget(d->keepOpen);
+ d->keepOpen->hide();
+
+ hBox = new TQHBoxLayout();
+ topLayout->addLayout(hBox);
+
+ d->openFile = new KPushButton( i18n("Open &File"), this );
+ connect( d->openFile, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOpenFile() ) );
+ hBox->addWidget( d->openFile );
+ d->openFile->setEnabled(false);
+ d->openFile->hide();
+
+ d->openLocation = new KPushButton( i18n("Open &Destination"), this );
+ connect( d->openLocation, TQT_SIGNAL( clicked() ), TQT_SLOT( slotOpenLocation() ) );
+ hBox->addWidget( d->openLocation );
+ d->openLocation->hide();
+
+ hBox->addStretch(1);
+
+ d->cancelClose = new KPushButton( KStdGuiItem::cancel(), this );
+ connect( d->cancelClose, TQT_SIGNAL( clicked() ), TQT_SLOT( slotStop() ) );
+ hBox->addWidget( d->cancelClose );
+
+ resize( sizeHint() );
+ setMaximumHeight(sizeHint().height());
+
+ d->keepOpenChecked = false;
+ d->noCaptionYet = true;
+ setCaption(i18n("Progress Dialog")); // show something better than tdeio_uiserver
+}
+
+DefaultProgress::~DefaultProgress()
+{
+ delete d;
+}
+
+void DefaultProgress::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
+{
+ // size is measured in bytes
+ if ( m_iTotalSize == size )
+ return;
+ m_iTotalSize = size;
+ if (d->startTime.isNull())
+ d->startTime.start();
+}
+
+
+void DefaultProgress::slotTotalFiles( TDEIO::Job*, unsigned long files )
+{
+ if ( m_iTotalFiles == files )
+ return;
+ m_iTotalFiles = files;
+ showTotals();
+}
+
+
+void DefaultProgress::slotTotalDirs( TDEIO::Job*, unsigned long dirs )
+{
+ if ( m_iTotalDirs == dirs )
+ return;
+ m_iTotalDirs = dirs;
+ showTotals();
+}
+
+void DefaultProgress::showTotals()
+{
+ // Show the totals in the progress label, if we still haven't
+ // processed anything. This is useful when the stat'ing phase
+ // of CopyJob takes a long time (e.g. over networks).
+ if ( m_iProcessedFiles == 0 && m_iProcessedDirs == 0 )
+ {
+ TQString tmps;
+ if ( m_iTotalDirs > 1 )
+ // that we have a singular to translate looks weired but is only logical
+ // xgettext: no-c-format
+ tmps = i18n("%n folder", "%n folders", m_iTotalDirs) + " ";
+ // xgettext: no-c-format
+ tmps += i18n("%n file", "%n files", m_iTotalFiles);
+ progressLabel->setText( tmps );
+ }
+}
+
+//static
+TQString DefaultProgress::makePercentString( unsigned long percent,
+ TDEIO::filesize_t totalSize,
+ unsigned long totalFiles )
+{
+ if ( totalSize )
+ return i18n( "%1 % of %2 " ).arg( TQString::number(percent) , TDEIO::convertSize( totalSize ) );
+ else if ( totalFiles )
+ return i18n( "%1 % of 1 file", "%1 % of %n files", totalFiles ).arg( percent );
+ else
+ return i18n( "%1 %" ).arg( percent );
+}
+
+void DefaultProgress::slotPercent( TDEIO::Job*, unsigned long percent )
+{
+ TQString caption = makePercentString( percent, m_iTotalSize, m_iTotalFiles );
+ m_pProgressBar->setValue( percent );
+ switch(mode) {
+ case Copy:
+ caption.append(i18n(" (Copying)"));
+ break;
+ case Move:
+ caption.append(i18n(" (Moving)"));
+ break;
+ case Delete:
+ caption.append(i18n(" (Deleting)"));
+ break;
+ case Create:
+ caption.append(i18n(" (Creating)"));
+ break;
+ case Done:
+ caption.append(i18n(" (Done)"));
+ break;
+ }
+
+ setCaption( caption );
+ d->noCaptionYet = false;
+}
+
+
+void DefaultProgress::slotInfoMessage( TDEIO::Job*, const TQString & msg )
+{
+ speedLabel->setText( msg );
+ speedLabel->setAlignment( speedLabel->alignment() & ~TQt::WordBreak );
+}
+
+
+void DefaultProgress::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t bytes ) {
+ if ( m_iProcessedSize == bytes )
+ return;
+ m_iProcessedSize = bytes;
+
+ TQString tmp = i18n( "%1 of %2 complete")
+ .arg( TDEIO::convertSize(bytes) )
+ .arg( TDEIO::convertSize(m_iTotalSize));
+ sizeLabel->setText( tmp );
+}
+
+
+void DefaultProgress::slotProcessedDirs( TDEIO::Job*, unsigned long dirs )
+{
+ if ( m_iProcessedDirs == dirs )
+ return;
+ m_iProcessedDirs = dirs;
+
+ TQString tmps;
+ tmps = i18n("%1 / %n folder", "%1 / %n folders", m_iTotalDirs).arg( m_iProcessedDirs );
+ tmps += " ";
+ tmps += i18n("%1 / %n file", "%1 / %n files", m_iTotalFiles).arg( m_iProcessedFiles );
+ progressLabel->setText( tmps );
+}
+
+
+void DefaultProgress::slotProcessedFiles( TDEIO::Job*, unsigned long files )
+{
+ if ( m_iProcessedFiles == files )
+ return;
+ m_iProcessedFiles = files;
+
+ TQString tmps;
+ if ( m_iTotalDirs > 1 ) {
+ tmps = i18n("%1 / %n folder", "%1 / %n folders", m_iTotalDirs).arg( m_iProcessedDirs );
+ tmps += " ";
+ }
+ tmps += i18n("%1 / %n file", "%1 / %n files", m_iTotalFiles).arg( m_iProcessedFiles );
+ progressLabel->setText( tmps );
+}
+
+
+void DefaultProgress::slotSpeed( TDEIO::Job*, unsigned long speed )
+{
+ if ( speed == 0 ) {
+ speedLabel->setText( i18n( "Stalled") );
+ } else {
+ speedLabel->setText( i18n( "%1/s ( %2 remaining )").arg( TDEIO::convertSize( speed ))
+ .arg( TDEIO::convertSeconds( TDEIO::calculateRemainingSeconds( m_iTotalSize, m_iProcessedSize, speed ))) );
+ }
+}
+
+
+void DefaultProgress::slotCopying( TDEIO::Job*, const KURL& from, const KURL& to )
+{
+ if ( d->noCaptionYet ) {
+ setCaption(i18n("Copy File(s) Progress"));
+ d->noCaptionYet = false;
+ }
+ mode = Copy;
+ sourceEdit->setText(from.prettyURL());
+ setDestVisible( true );
+ checkDestination( to );
+ destEdit->setText(to.prettyURL());
+}
+
+
+void DefaultProgress::slotMoving( TDEIO::Job*, const KURL& from, const KURL& to )
+{
+ if ( d->noCaptionYet ) {
+ setCaption(i18n("Move File(s) Progress"));
+ d->noCaptionYet = false;
+ }
+ mode = Move;
+ sourceEdit->setText(from.prettyURL());
+ setDestVisible( true );
+ checkDestination( to );
+ destEdit->setText(to.prettyURL());
+}
+
+
+void DefaultProgress::slotCreatingDir( TDEIO::Job*, const KURL& dir )
+{
+ if ( d->noCaptionYet ) {
+ setCaption(i18n("Creating Folder"));
+ d->noCaptionYet = false;
+ }
+ mode = Create;
+ sourceEdit->setText(dir.prettyURL());
+ setDestVisible( false );
+}
+
+
+void DefaultProgress::slotDeleting( TDEIO::Job*, const KURL& url )
+{
+ if ( d->noCaptionYet ) {
+ setCaption(i18n("Delete File(s) Progress"));
+ d->noCaptionYet = false;
+ }
+ mode = Delete;
+ sourceEdit->setText(url.prettyURL());
+ setDestVisible( false );
+}
+
+void DefaultProgress::slotTransferring( TDEIO::Job*, const KURL& url )
+{
+ if ( d->noCaptionYet ) {
+ setCaption(i18n("Loading Progress"));
+ d->noCaptionYet = false;
+ }
+ sourceEdit->setText(url.prettyURL());
+ setDestVisible( false );
+}
+
+void DefaultProgress::slotStating( TDEIO::Job*, const KURL& url )
+{
+ setCaption(i18n("Examining File Progress"));
+ sourceEdit->setText(url.prettyURL());
+ setDestVisible( false );
+}
+
+void DefaultProgress::slotMounting( TDEIO::Job*, const TQString & dev, const TQString & point )
+{
+ setCaption(i18n("Mounting %1").arg(dev));
+ sourceEdit->setText(point);
+ setDestVisible( false );
+}
+
+void DefaultProgress::slotUnmounting( TDEIO::Job*, const TQString & point )
+{
+ setCaption(i18n("Unmounting"));
+ sourceEdit->setText(point);
+ setDestVisible( false );
+}
+
+void DefaultProgress::slotCanResume( TDEIO::Job*, TDEIO::filesize_t resume )
+{
+ if ( resume ) {
+ resumeLabel->setText( i18n("Resuming from %1").arg(TDEIO::number(resume)) );
+ } else {
+ resumeLabel->setText( i18n("Not resumable") );
+ }
+}
+
+void DefaultProgress::setDestVisible( bool visible )
+{
+ // We can't hide the destInvite/destEdit labels,
+ // because it screws up the TQGridLayout.
+ if (visible)
+ {
+ destInvite->show();
+ destEdit->show();
+
+ destInvite->setText( i18n("Destination:") );
+ }
+ else
+ {
+ destInvite->hide();
+ destEdit->hide();
+ destInvite->setText( TQString::null );
+ destEdit->setText( TQString::null );
+ }
+}
+
+void DefaultProgress::slotClean() {
+ if (d->keepOpenChecked) {
+ mode = Done;
+ slotPercent(0, 100);
+ d->cancelClose->setGuiItem( KStdGuiItem::close() );
+ d->openFile->setEnabled(true);
+ slotProcessedSize(0, m_iTotalSize);
+ d->keepOpen->setEnabled(false);
+ if (!d->startTime.isNull()) {
+ int s = d->startTime.elapsed();
+ if (!s)
+ s = 1;
+ speedLabel->setText(i18n("%1/s (done)").arg(TDEIO::convertSize(1000 * m_iTotalSize / s)));
+ }
+ setOnlyClean(false);
+ }
+ else
+ hide();
+}
+
+void DefaultProgress::slotKeepOpenToggled(bool keepopen)
+{
+ d->keepOpenChecked=keepopen;
+}
+
+void DefaultProgress::checkDestination(const KURL& dest) {
+ bool ok = true;
+ if ( dest.isLocalFile() ) {
+ TQString path = dest.path( -1 );
+ TQStringList tmpDirs = TDEGlobal::dirs()->resourceDirs( "tmp" );
+ for ( TQStringList::Iterator it = tmpDirs.begin() ; ok && it != tmpDirs.end() ; ++it )
+ if ( path.contains( *it ) )
+ ok = false; // it's in the tmp resource
+ }
+
+ if ( ok ) {
+ d->openFile->show();
+ d->openLocation->show();
+ d->keepOpen->show();
+ d->location=dest;
+ }
+}
+
+void DefaultProgress::slotOpenFile()
+{
+ TDEProcess proc;
+ proc << "konqueror" << d->location.prettyURL();
+ proc.start(TDEProcess::DontCare);
+}
+
+void DefaultProgress::slotOpenLocation()
+{
+ TDEProcess proc;
+ d->location.setFileName("");
+ proc << "konqueror" << d->location.prettyURL();
+ proc.start(TDEProcess::DontCare);
+}
+
+void DefaultProgress::virtual_hook( int id, void* data )
+{ ProgressBase::virtual_hook( id, data ); }
+
+} /* namespace */
+
+#include "defaultprogress.moc"
diff --git a/tdeio/tdeio/defaultprogress.h b/tdeio/tdeio/defaultprogress.h
new file mode 100644
index 000000000..de0dfd093
--- /dev/null
+++ b/tdeio/tdeio/defaultprogress.h
@@ -0,0 +1,164 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Matej Koss <koss@miesto.sk>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __defaultprogress_h__
+#define __defaultprogress_h__
+
+#include <tqlabel.h>
+
+#include <tdeio/global.h>
+
+#include <kprogress.h>
+
+#include "progressbase.h"
+
+class KLineEdit;
+
+namespace TDEIO {
+
+/*
+ * A default implementation of the progress dialog ProgressBase.
+ * ProgressBase
+ */
+class TDEIO_EXPORT DefaultProgress : public ProgressBase {
+
+ Q_OBJECT
+
+public:
+ /**
+ * Creates a new default progress dialog.
+ * @param showNow true to show immediately, false to show when
+ * needed
+ */
+ DefaultProgress( bool showNow = true );
+ /**
+ * Creates a new default progress dialog.
+ * @param parent the parent of the dialog (or 0 for top-level)
+ * @param name the name of the dialog, can be 0
+ * @since 3.1
+ */
+ DefaultProgress( TQWidget* parent, const char* name = 0 );
+ ~DefaultProgress();
+
+ bool keepOpen() const;
+
+ /// Shared with uiserver.cpp
+ static TQString makePercentString( unsigned long percent,
+ TDEIO::filesize_t totalSize,
+ unsigned long totalFiles );
+
+public slots:
+ virtual void slotTotalSize( TDEIO::Job *job, TDEIO::filesize_t size );
+ virtual void slotTotalFiles( TDEIO::Job *job, unsigned long files );
+ virtual void slotTotalDirs( TDEIO::Job *job, unsigned long dirs );
+
+ virtual void slotProcessedSize( TDEIO::Job *job, TDEIO::filesize_t bytes );
+ virtual void slotProcessedFiles( TDEIO::Job *job, unsigned long files );
+ virtual void slotProcessedDirs( TDEIO::Job *job, unsigned long dirs );
+
+ virtual void slotSpeed( TDEIO::Job *job, unsigned long speed );
+ virtual void slotPercent( TDEIO::Job *job, unsigned long percent );
+ /**
+ * Called to set an information message.
+ * @param job the TDEIO::Job
+ * @param msg the message to set
+ */
+ virtual void slotInfoMessage( TDEIO::Job *job, const TQString & msg );
+
+ virtual void slotCopying( TDEIO::Job* job, const KURL& src, const KURL& dest );
+ virtual void slotMoving( TDEIO::Job* job, const KURL& src, const KURL& dest );
+ virtual void slotDeleting( TDEIO::Job* job, const KURL& url );
+ /**
+ * Called when the job is transferring.
+ * @param job the TDEIO::Job
+ * @param url the url to transfer
+ * @since 3.1
+ */
+ void slotTransferring( TDEIO::Job* job, const KURL& url );
+ virtual void slotCreatingDir( TDEIO::Job* job, const KURL& dir );
+ /**
+ * Called when the job is requesting a stat.
+ * @param job the TDEIO::Job
+ * @param dir the dir to stat
+ * @since 3.1
+ */
+ virtual void slotStating( TDEIO::Job* job, const KURL& dir );
+ /**
+ * Called when the job is mounting.
+ * @param job the TDEIO::Job
+ * @param dev the device to mount
+ * @param point the mount point
+ */
+ virtual void slotMounting( TDEIO::Job* job, const TQString & dev, const TQString & point );
+ /**
+ * Called when the job is unmounting.
+ * @param job the TDEIO::Job
+ * @param point the mount point
+ */
+ virtual void slotUnmounting( TDEIO::Job* job, const TQString & point );
+ virtual void slotCanResume( TDEIO::Job* job, TDEIO::filesize_t from);
+
+ /**
+ * Called when the job is cleaned.
+ * @since 3.1
+ */
+ void slotClean();
+
+protected:
+ /// @since 3.1
+ void init();
+ void showTotals();
+ void setDestVisible( bool visible );
+ /// @since 3.1
+ void checkDestination( const KURL& dest);
+
+ KLineEdit* sourceEdit;
+ KLineEdit* destEdit;
+ TQLabel* progressLabel;
+ TQLabel* destInvite;
+ TQLabel* speedLabel;
+ TQLabel* sizeLabel;
+ TQLabel* resumeLabel;
+
+ KProgress* m_pProgressBar;
+
+ TDEIO::filesize_t m_iTotalSize;
+ unsigned long m_iTotalFiles;
+ unsigned long m_iTotalDirs;
+
+ TDEIO::filesize_t m_iProcessedSize;
+ unsigned long m_iProcessedDirs;
+ unsigned long m_iProcessedFiles;
+
+ enum ModeType { Copy, Move, Delete, Create, Done };
+ ModeType mode;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class DefaultProgressPrivate;
+ DefaultProgressPrivate* d;
+private slots:
+ void slotKeepOpenToggled(bool);
+ void slotOpenFile();
+ void slotOpenLocation();
+};
+
+} /* namespace */
+
+#endif // __defaultprogress_h__
+
diff --git a/tdeio/tdeio/forwardingslavebase.cpp b/tdeio/tdeio/forwardingslavebase.cpp
new file mode 100644
index 000000000..a55f68249
--- /dev/null
+++ b/tdeio/tdeio/forwardingslavebase.cpp
@@ -0,0 +1,475 @@
+/* This file is part of the KDE project
+ Copyright (c) 2004 Kevin Ottens <ervin ipsquad net>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <kdebug.h>
+#include <tdeio/job.h>
+#include <kmimetype.h>
+#include <kprotocolinfo.h>
+
+#include <tqapplication.h>
+#include <tqeventloop.h>
+
+#include "forwardingslavebase.h"
+
+namespace TDEIO
+{
+
+class ForwardingSlaveBasePrivate
+{
+};
+
+ForwardingSlaveBase::ForwardingSlaveBase(const TQCString &protocol,
+ const TQCString &poolSocket,
+ const TQCString &appSocket)
+ : TQObject(), SlaveBase(protocol, poolSocket, appSocket)
+{
+}
+
+ForwardingSlaveBase::~ForwardingSlaveBase()
+{
+}
+
+bool ForwardingSlaveBase::internalRewriteURL(const KURL &url, KURL &newURL)
+{
+ bool result = true;
+
+ if ( url.protocol().ascii()==mProtocol )
+ {
+ result = rewriteURL(url, newURL);
+ }
+ else
+ {
+ newURL = url;
+ }
+
+ m_processedURL = newURL;
+ m_requestedURL = url;
+ return result;
+}
+
+void ForwardingSlaveBase::prepareUDSEntry(TDEIO::UDSEntry &entry,
+ bool listing) const
+{
+ kdDebug() << "ForwardingSlaveBase::prepareUDSEntry: listing=="
+ << listing << endl;
+
+ bool url_found = false;
+ TQString name;
+ KURL url;
+
+ TDEIO::UDSEntry::iterator it = entry.begin();
+ TDEIO::UDSEntry::iterator end = entry.end();
+
+ for(; it!=end; ++it)
+ {
+ KURL new_url = m_requestedURL;
+
+ switch( (*it).m_uds )
+ {
+ case TDEIO::UDS_NAME:
+ name = (*it).m_str;
+ kdDebug() << "Name = " << name << endl;
+ break;
+ case TDEIO::UDS_URL:
+ url_found = true;
+ url = (*it).m_str;
+ if (listing)
+ {
+ new_url.addPath(url.fileName());
+ }
+ (*it).m_str = new_url.url();
+ kdDebug() << "URL = " << url << endl;
+ kdDebug() << "New URL = " << (*it).m_str << endl;
+ break;
+ }
+ }
+
+ if ( m_processedURL.isLocalFile() )
+ {
+ KURL new_url = m_processedURL;
+ if (listing)
+ {
+ new_url.addPath( name );
+ }
+
+ TDEIO::UDSAtom atom;
+ atom.m_uds = TDEIO::UDS_LOCAL_PATH;
+ atom.m_long = 0;
+ atom.m_str = new_url.path();
+ entry.append(atom);
+ }
+}
+
+void ForwardingSlaveBase::get(const KURL &url)
+{
+ kdDebug() << "ForwardingSlaveBase::get: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ TDEIO::TransferJob *job = TDEIO::get(new_url, false, false);
+ connectTransferJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::put(const KURL &url, int permissions,
+ bool overwrite, bool resume )
+{
+ kdDebug() << "ForwardingSlaveBase::put: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ TDEIO::TransferJob *job = TDEIO::put(new_url, permissions, overwrite,
+ resume, false);
+ connectTransferJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::stat(const KURL &url)
+{
+ kdDebug() << "ForwardingSlaveBase::stat: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ TDEIO::SimpleJob *job = TDEIO::stat(new_url, false);
+ connectSimpleJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::mimetype(const KURL &url)
+{
+ kdDebug() << "ForwardingSlaveBase::mimetype: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ TDEIO::TransferJob *job = TDEIO::mimetype(new_url, false);
+ connectTransferJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::listDir(const KURL &url)
+{
+ kdDebug() << "ForwardingSlaveBase::listDir: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ TDEIO::ListJob *job = TDEIO::listDir(new_url, false);
+ connectListJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::mkdir(const KURL &url, int permissions)
+{
+ kdDebug() << "ForwardingSlaveBase::mkdir: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ TDEIO::SimpleJob *job = TDEIO::mkdir(new_url, permissions);
+ connectSimpleJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::rename(const KURL &src, const KURL &dest,
+ bool overwrite)
+{
+ kdDebug() << "ForwardingSlaveBase::rename: " << src << ", " << dest << endl;
+
+ KURL new_src, new_dest;
+ if ( internalRewriteURL(src, new_src) && internalRewriteURL(dest, new_dest) )
+ {
+ TDEIO::Job *job = TDEIO::rename(new_src, new_dest, overwrite);
+ connectJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::symlink(const TQString &target, const KURL &dest,
+ bool overwrite)
+{
+ kdDebug() << "ForwardingSlaveBase::symlink: " << target << ", " << dest << endl;
+
+ KURL new_dest;
+ if ( internalRewriteURL(dest, new_dest) )
+ {
+ TDEIO::SimpleJob *job = TDEIO::symlink(target, new_dest, overwrite, false);
+ connectSimpleJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::chmod(const KURL &url, int permissions)
+{
+ kdDebug() << "ForwardingSlaveBase::chmod: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ TDEIO::SimpleJob *job = TDEIO::chmod(new_url, permissions);
+ connectSimpleJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::copy(const KURL &src, const KURL &dest,
+ int permissions, bool overwrite)
+{
+ kdDebug() << "ForwardingSlaveBase::copy: " << src << ", " << dest << endl;
+
+ KURL new_src, new_dest;
+ if ( internalRewriteURL(src, new_src) && internalRewriteURL(dest, new_dest) )
+ {
+ TDEIO::Job *job = TDEIO::file_copy(new_src, new_dest, permissions,
+ overwrite, false);
+ connectJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::del(const KURL &url, bool isfile)
+{
+ kdDebug() << "ForwardingSlaveBase::del: " << url << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(url, new_url) )
+ {
+ if (isfile)
+ {
+ TDEIO::DeleteJob *job = TDEIO::del(new_url, false, false);
+ connectJob(job);
+ }
+ else
+ {
+ TDEIO::SimpleJob *job = TDEIO::rmdir(new_url);
+ connectSimpleJob(job);
+ }
+
+ tqApp->eventLoop()->enterLoop();
+ }
+}
+
+void ForwardingSlaveBase::localURL(const KURL& remoteURL)
+{
+ kdDebug() << "ForwardingSlaveBase::localURL: " << remoteURL << endl;
+
+ KURL new_url;
+ if ( internalRewriteURL(remoteURL, new_url) )
+ {
+ TDEIO::LocalURLJob *job = TDEIO::localURL(new_url);
+ connectLocalURLJob(job);
+
+ tqApp->eventLoop()->enterLoop();
+ }
+ else
+ {
+ // Let the slave base emit the required signals
+ SlaveBase::localURL(remoteURL);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void ForwardingSlaveBase::connectJob(TDEIO::Job *job)
+{
+ // We will forward the warning message, no need to let the job
+ // display it itself
+ job->setInteractive(false);
+
+ // Forward metadata (e.g. modification time for put())
+ job->setMetaData( allMetaData() );
+#if 0 // debug code
+ kdDebug() << k_funcinfo << "transferring metadata:" << endl;
+ const MetaData md = allMetaData();
+ for ( MetaData::const_iterator it = md.begin(); it != md.end(); ++it )
+ kdDebug() << it.key() << " = " << it.data() << endl;
+#endif
+
+ connect( job, TQT_SIGNAL( result(TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult(TDEIO::Job *) ) );
+ connect( job, TQT_SIGNAL( warning(TDEIO::Job *, const TQString &) ),
+ this, TQT_SLOT( slotWarning(TDEIO::Job *, const TQString &) ) );
+ connect( job, TQT_SIGNAL( infoMessage(TDEIO::Job *, const TQString &) ),
+ this, TQT_SLOT( slotInfoMessage(TDEIO::Job *, const TQString &) ) );
+ connect( job, TQT_SIGNAL( totalSize(TDEIO::Job *, TDEIO::filesize_t) ),
+ this, TQT_SLOT( slotTotalSize(TDEIO::Job *, TDEIO::filesize_t) ) );
+ connect( job, TQT_SIGNAL( processedSize(TDEIO::Job *, TDEIO::filesize_t) ),
+ this, TQT_SLOT( slotProcessedSize(TDEIO::Job *, TDEIO::filesize_t) ) );
+ connect( job, TQT_SIGNAL( speed(TDEIO::Job *, unsigned long) ),
+ this, TQT_SLOT( slotSpeed(TDEIO::Job *, unsigned long) ) );
+}
+
+void ForwardingSlaveBase::connectSimpleJob(TDEIO::SimpleJob *job)
+{
+ connectJob(job);
+ connect( job, TQT_SIGNAL( redirection(TDEIO::Job *, const KURL &) ),
+ this, TQT_SLOT( slotRedirection(TDEIO::Job *, const KURL &) ) );
+}
+
+void ForwardingSlaveBase::connectListJob(TDEIO::ListJob *job)
+{
+ connectSimpleJob(job);
+ connect( job, TQT_SIGNAL( entries(TDEIO::Job *, const TDEIO::UDSEntryList &) ),
+ this, TQT_SLOT( slotEntries(TDEIO::Job *, const TDEIO::UDSEntryList &) ) );
+}
+
+void ForwardingSlaveBase::connectTransferJob(TDEIO::TransferJob *job)
+{
+ connectSimpleJob(job);
+ connect( job, TQT_SIGNAL( data(TDEIO::Job *, const TQByteArray &) ),
+ this, TQT_SLOT( slotData(TDEIO::Job *, const TQByteArray &) ) );
+ connect( job, TQT_SIGNAL( dataReq(TDEIO::Job *, TQByteArray &) ),
+ this, TQT_SLOT( slotDataReq(TDEIO::Job *, TQByteArray &) ) );
+ connect( job, TQT_SIGNAL( mimetype(TDEIO::Job *, const TQString &) ),
+ this, TQT_SLOT( slotMimetype(TDEIO::Job *, const TQString &) ) );
+ connect( job, TQT_SIGNAL( canResume(TDEIO::Job *, TDEIO::filesize_t) ),
+ this, TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t) ) );
+}
+
+void ForwardingSlaveBase::connectLocalURLJob(TDEIO::LocalURLJob *job)
+{
+ connectJob(job);
+ connect( job, TQT_SIGNAL( localURL(TDEIO::Job *, const KURL&, bool) ),
+ this, TQT_SLOT( slotLocalURL(TDEIO::Job *, const KURL&, bool) ) );
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+void ForwardingSlaveBase::slotResult(TDEIO::Job *job)
+{
+ if ( job->error() != 0)
+ {
+ error( job->error(), job->errorText() );
+ }
+ else
+ {
+ TDEIO::StatJob *stat_job = dynamic_cast<TDEIO::StatJob *>(job);
+ if ( stat_job!=0L )
+ {
+ TDEIO::UDSEntry entry = stat_job->statResult();
+ prepareUDSEntry(entry);
+ statEntry( entry );
+ }
+ finished();
+ }
+
+ tqApp->eventLoop()->exitLoop();
+}
+
+void ForwardingSlaveBase::slotWarning(TDEIO::Job* /*job*/, const TQString &msg)
+{
+ warning(msg);
+}
+
+void ForwardingSlaveBase::slotInfoMessage(TDEIO::Job* /*job*/, const TQString &msg)
+{
+ infoMessage(msg);
+}
+
+void ForwardingSlaveBase::slotTotalSize(TDEIO::Job* /*job*/, TDEIO::filesize_t size)
+{
+ totalSize(size);
+}
+
+void ForwardingSlaveBase::slotProcessedSize(TDEIO::Job* /*job*/, TDEIO::filesize_t size)
+{
+ processedSize(size);
+}
+
+void ForwardingSlaveBase::slotSpeed(TDEIO::Job* /*job*/, unsigned long bytesPerSecond)
+{
+ speed(bytesPerSecond);
+}
+
+void ForwardingSlaveBase::slotRedirection(TDEIO::Job *job, const KURL &url)
+{
+ redirection(url);
+
+ // We've been redirected stop everything.
+ job->kill( true );
+ finished();
+
+ tqApp->eventLoop()->exitLoop();
+}
+
+void ForwardingSlaveBase::slotEntries(TDEIO::Job* /*job*/,
+ const TDEIO::UDSEntryList &entries)
+{
+ TDEIO::UDSEntryList final_entries = entries;
+
+ TDEIO::UDSEntryList::iterator it = final_entries.begin();
+ TDEIO::UDSEntryList::iterator end = final_entries.end();
+
+ for(; it!=end; ++it)
+ {
+ prepareUDSEntry(*it, true);
+ }
+
+ listEntries( final_entries );
+}
+
+void ForwardingSlaveBase::slotData(TDEIO::Job* /*job*/, const TQByteArray &d)
+{
+ data(d);
+}
+
+void ForwardingSlaveBase::slotDataReq(TDEIO::Job* /*job*/, TQByteArray &data)
+{
+ dataReq();
+ readData(data);
+}
+
+void ForwardingSlaveBase::slotMimetype (TDEIO::Job* /*job*/, const TQString &type)
+{
+ mimeType(type);
+}
+
+void ForwardingSlaveBase::slotCanResume (TDEIO::Job* /*job*/, TDEIO::filesize_t offset)
+{
+ canResume(offset);
+}
+
+void ForwardingSlaveBase::slotLocalURL(TDEIO::Job *, const KURL& url, bool)
+{
+ SlaveBase::localURL(url);
+}
+
+}
+
+#include "forwardingslavebase.moc"
+
diff --git a/tdeio/tdeio/forwardingslavebase.h b/tdeio/tdeio/forwardingslavebase.h
new file mode 100644
index 000000000..4d84089bf
--- /dev/null
+++ b/tdeio/tdeio/forwardingslavebase.h
@@ -0,0 +1,204 @@
+/* This file is part of the KDE project
+ Copyright (c) 2004 Kevin Ottens <ervin ipsquad net>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _FORWARDING_SLAVE_BASE_H_
+#define _FORWARDING_SLAVE_BASE_H_
+
+#include <tdeio/slavebase.h>
+#include <tdeio/jobclasses.h>
+
+#include <tqobject.h>
+
+namespace TDEIO
+{
+
+class ForwardingSlaveBasePrivate;
+
+/**
+ * This class should be used as a base for ioslaves acting as a
+ * forwarder to other ioslaves. It has been designed to support only
+ * local filesystem like ioslaves.
+ *
+ * If the resulting ioslave should be a simple proxy, you only need
+ * to implement the ForwardingSlaveBase::rewriteURL() method.
+ *
+ * For more advanced behavior, the classic ioslave methods should
+ * be reimplemented, because their default behavior in this class
+ * is to forward using the ForwardingSlaveBase::rewriteURL() method.
+ *
+ * A possible code snippet for an advanced stat() behavior would look
+ * like this in the child class:
+ *
+ * \code
+ * void ChildProtocol::stat(const KURL &url)
+ * {
+ * bool is_special = false;
+ *
+ * // Process the URL to see if it should have
+ * // a special treatment
+ *
+ * if ( is_special )
+ * {
+ * // Handle the URL ourselves
+ * TDEIO::UDSEntry entry;
+ * // Fill entry with UDSAtom instances
+ * statEntry(entry);
+ * finished();
+ * }
+ * else
+ * {
+ * // Setup the ioslave internal state if
+ * // required by ChildProtocol::rewriteURL()
+ * ForwardingSlaveBase::stat(url);
+ * }
+ * }
+ * \endcode
+ *
+ * Of course in this case, you surely need to reimplement listDir()
+ * and get() accordingly.
+ *
+ * If you want view on directories to be correctly refreshed when
+ * something changes on a forwarded URL, you'll need a companion kded
+ * module to emit the KDirNotify Files*() DCOP signals.
+ *
+ * This class was initially used for media:/ ioslave. This ioslave code
+ * and the MediaDirNotify class of its companion kded module can be a
+ * good source of inspiration.
+ *
+ * @see ForwardingSlaveBase::rewriteURL()
+ * @since 3.4
+ * @author Kevin Ottens <ervin@ipsquad.net>
+ */
+class TDEIO_EXPORT ForwardingSlaveBase : public TQObject, public SlaveBase
+{
+Q_OBJECT
+public:
+ ForwardingSlaveBase(const TQCString &protocol,
+ const TQCString &poolSocket,
+ const TQCString &appSocket);
+ virtual ~ForwardingSlaveBase();
+
+ virtual void get(const KURL &url);
+
+ virtual void put(const KURL &url, int permissions,
+ bool overwrite, bool resume);
+
+ virtual void stat(const KURL &url);
+
+ virtual void mimetype(const KURL &url);
+
+ virtual void listDir(const KURL &url);
+
+ virtual void mkdir(const KURL &url, int permissions);
+
+ virtual void rename(const KURL &src, const KURL &dest, bool overwrite);
+
+ virtual void symlink(const TQString &target, const KURL &dest,
+ bool overwrite);
+
+ virtual void chmod(const KURL &url, int permissions);
+
+ virtual void copy(const KURL &src, const KURL &dest,
+ int permissions, bool overwrite);
+
+ virtual void del(const KURL &url, bool isfile);
+
+ virtual void localURL(const KURL& remoteURL);
+
+protected:
+ /**
+ * Rewrite an url to it's forwarded counterpart. It should return
+ * true if everything was ok, and false otherwise.
+ *
+ * If a problem is detected it's up to this method to trigger error()
+ * before returning. Returning false silently cancel the current
+ * slave operation.
+ *
+ * @param url The URL as given during the slave call
+ * @param newURL The new URL to forward the slave call to
+ * @return true if the given url could be correctly rewritten
+ */
+ virtual bool rewriteURL(const KURL &url, KURL &newURL)=0;
+
+ /**
+ * Allow to modify a UDSEntry before it's sent to the ioslave enpoint.
+ * This is the default implementation working in most case, but sometimes
+ * you could make use of more forwarding black magic (for example
+ * dynamically transform any desktop file into a fake directory...)
+ *
+ * @param entry the UDSEntry to post-process
+ * @param listing indicate if this entry it created during a listDir
+ * operation
+ */
+ virtual void prepareUDSEntry(TDEIO::UDSEntry &entry,
+ bool listing=false) const;
+
+ /**
+ * Return the URL being processed by the ioslave
+ * Only access it inside prepareUDSEntry()
+ */
+ KURL processedURL() const { return m_processedURL; }
+
+ /**
+ * Return the URL asked to the ioslave
+ * Only access it inside prepareUDSEntry()
+ */
+ KURL requestedURL() const { return m_requestedURL; }
+
+private:
+ KURL m_processedURL;
+ KURL m_requestedURL;
+ ForwardingSlaveBasePrivate *d;
+
+ bool internalRewriteURL(const KURL &url, KURL &newURL);
+
+ void connectJob(Job *job);
+ void connectSimpleJob(SimpleJob *job);
+ void connectListJob(ListJob *job);
+ void connectTransferJob(TransferJob *job);
+ void connectLocalURLJob(LocalURLJob *job);
+
+private slots:
+ // TDEIO::Job
+ void slotResult(TDEIO::Job *job);
+ void slotWarning(TDEIO::Job *job, const TQString &msg);
+ void slotInfoMessage(TDEIO::Job *job, const TQString &msg);
+ void slotTotalSize(TDEIO::Job *job, TDEIO::filesize_t size);
+ void slotProcessedSize(TDEIO::Job *job, TDEIO::filesize_t size);
+ void slotSpeed(TDEIO::Job *job, unsigned long bytesPerSecond);
+
+ // TDEIO::SimpleJob subclasses
+ void slotRedirection(TDEIO::Job *job, const KURL &url);
+
+ // TDEIO::ListJob
+ void slotEntries(TDEIO::Job *job, const TDEIO::UDSEntryList &entries);
+
+ // TDEIO::TransferJob
+ void slotData(TDEIO::Job *job, const TQByteArray &data);
+ void slotDataReq(TDEIO::Job *job, TQByteArray &data);
+ void slotMimetype (TDEIO::Job *job, const TQString &type);
+ void slotCanResume (TDEIO::Job *job, TDEIO::filesize_t offset);
+
+ // TDEIO::LocalURLJob
+ void slotLocalURL(TDEIO::Job *, const KURL&, bool);
+};
+
+}
+
+#endif
diff --git a/tdeio/tdeio/global.cpp b/tdeio/tdeio/global.cpp
new file mode 100644
index 000000000..e4bfec5f6
--- /dev/null
+++ b/tdeio/tdeio/global.cpp
@@ -0,0 +1,2009 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/uio.h>
+
+#include <assert.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <stdio.h>
+
+#include "tdeio/global.h"
+#include "tdeio/job.h"
+
+#include <kdebug.h>
+#include <klocale.h>
+#include <kglobal.h>
+#include <kprotocolmanager.h>
+#include <kde_file.h>
+
+#ifdef HAVE_VOLMGT
+#include <volmgt.h>
+#endif
+
+TDEIO_EXPORT TQString TDEIO::convertSizeWithBytes( TDEIO::filesize_t size )
+{
+ if ( size >= 1024 )
+ return convertSize( size ) + " (" + i18n( "%1 B" ).arg( TDEGlobal::locale()->formatNumber(size, 0) ) + ")";
+ else
+ return convertSize( size );
+}
+
+TDEIO_EXPORT TQString TDEIO::convertSize( TDEIO::filesize_t size )
+{
+ double fsize = size;
+ TQString s;
+ // Giga-byte
+ if ( size >= 1073741824 )
+ {
+ fsize /= 1073741824.0;
+ if ( fsize > 1024 ) // Tera-byte
+ s = i18n( "%1 TB" ).arg( TDEGlobal::locale()->formatNumber(fsize / 1024.0, 1));
+ else
+ s = i18n( "%1 GB" ).arg( TDEGlobal::locale()->formatNumber(fsize, 1));
+ }
+ // Mega-byte
+ else if ( size >= 1048576 )
+ {
+ fsize /= 1048576.0;
+ s = i18n( "%1 MB" ).arg( TDEGlobal::locale()->formatNumber(fsize, 1));
+ }
+ // Kilo-byte
+ else if ( size >= 1024 )
+ {
+ fsize /= 1024.0;
+ s = i18n( "%1 KB" ).arg( TDEGlobal::locale()->formatNumber(fsize, 1));
+ }
+ // Just byte
+ else if ( size > 0 )
+ {
+ s = i18n( "%1 B" ).arg( TDEGlobal::locale()->formatNumber(fsize, 0));
+ }
+ // Nothing
+ else
+ {
+ s = i18n( "0 B" );
+ }
+ return s;
+}
+
+TDEIO_EXPORT TQString TDEIO::convertSizeFromKB( TDEIO::filesize_t kbSize )
+{
+ return convertSize(kbSize * 1024);
+}
+
+TDEIO_EXPORT TQString TDEIO::number( TDEIO::filesize_t size )
+{
+ char charbuf[256];
+ sprintf(charbuf, "%lld", size);
+ return TQString::fromLatin1(charbuf);
+}
+
+TDEIO_EXPORT unsigned int TDEIO::calculateRemainingSeconds( TDEIO::filesize_t totalSize,
+ TDEIO::filesize_t processedSize, TDEIO::filesize_t speed )
+{
+ if ( (speed != 0) && (totalSize != 0) )
+ return ( totalSize - processedSize ) / speed;
+ else
+ return 0;
+}
+
+TDEIO_EXPORT TQString TDEIO::convertSeconds( unsigned int seconds )
+{
+ unsigned int days = seconds / 86400;
+ unsigned int hours = (seconds - (days * 86400)) / 3600;
+ unsigned int mins = (seconds - (days * 86400) - (hours * 3600)) / 60;
+ seconds = (seconds - (days * 86400) - (hours * 3600) - (mins * 60));
+
+ const TQTime time(hours, mins, seconds);
+ const TQString timeStr( TDEGlobal::locale()->formatTime(time, true /*with seconds*/, true /*duration*/) );
+ if ( days > 0 )
+ return i18n("1 day %1", "%n days %1", days).arg(timeStr);
+ else
+ return timeStr;
+}
+
+TDEIO_EXPORT TQTime TDEIO::calculateRemaining( TDEIO::filesize_t totalSize, TDEIO::filesize_t processedSize, TDEIO::filesize_t speed )
+{
+ TQTime remainingTime;
+
+ if ( speed != 0 ) {
+ TDEIO::filesize_t secs;
+ if ( totalSize == 0 ) {
+ secs = 0;
+ } else {
+ secs = ( totalSize - processedSize ) / speed;
+ }
+ if (secs >= (24*60*60)) // Limit to 23:59:59
+ secs = (24*60*60)-1;
+ int hr = secs / ( 60 * 60 );
+ int mn = ( secs - hr * 60 * 60 ) / 60;
+ int sc = ( secs - hr * 60 * 60 - mn * 60 );
+
+ remainingTime.setHMS( hr, mn, sc );
+ }
+
+ return remainingTime;
+}
+
+TDEIO_EXPORT TQString TDEIO::itemsSummaryString(uint items, uint files, uint dirs, TDEIO::filesize_t size, bool showSize)
+{
+ TQString text = items == 0 ? i18n( "No Items" ) : i18n( "One Item", "%n Items", items );
+ text += " - ";
+ text += files == 0 ? i18n( "No Files" ) : i18n( "One File", "%n Files", files );
+ if ( showSize && files > 0 )
+ {
+ text += " ";
+ text += i18n("(%1 Total)").arg(TDEIO::convertSize( size ) );
+ }
+ text += " - ";
+ text += dirs == 0 ? i18n( "No Folders" ) : i18n("One Folder", "%n Folders", dirs);
+ return text;
+}
+
+TDEIO_EXPORT TQString TDEIO::encodeFileName( const TQString & _str )
+{
+ TQString str( _str );
+
+ int i = 0;
+ while ( ( i = str.find( "%", i ) ) != -1 )
+ {
+ str.replace( i, 1, "%%");
+ i += 2;
+ }
+ while ( ( i = str.find( "/" ) ) != -1 )
+ str.replace( i, 1, "%2f");
+ return str;
+}
+
+TDEIO_EXPORT TQString TDEIO::decodeFileName( const TQString & _str )
+{
+ TQString str;
+
+ unsigned int i = 0;
+ for ( ; i < _str.length() ; ++i )
+ {
+ if ( _str[i]=='%' )
+ {
+ if ( _str[i+1]=='%' ) // %% -> %
+ {
+ str.append('%');
+ ++i;
+ }
+ else if ( _str[i+1]=='2' && (i+2<_str.length()) && _str[i+2].lower()=='f' ) // %2f -> /
+ {
+ str.append('/');
+ i += 2;
+ }
+ else
+ str.append('%');
+ } else
+ str.append(_str[i]);
+ }
+
+ return str;
+}
+
+TDEIO_EXPORT TQString TDEIO::Job::errorString() const
+{
+ return TDEIO::buildErrorString(m_error, m_errorText);
+}
+
+TDEIO_EXPORT TQString TDEIO::buildErrorString(int errorCode, const TQString &errorText)
+{
+ TQString result;
+
+ switch( errorCode )
+ {
+ case TDEIO::ERR_CANNOT_OPEN_FOR_READING:
+ result = i18n( "Could not read %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_OPEN_FOR_WRITING:
+ result = i18n( "Could not write to %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_LAUNCH_PROCESS:
+ result = i18n( "Could not start process %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_INTERNAL:
+ result = i18n( "Internal Error\nPlease send a full bug report at http://bugs.kde.org\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_MALFORMED_URL:
+ result = i18n( "Malformed URL %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_UNSUPPORTED_PROTOCOL:
+ result = i18n( "The protocol %1 is not supported." ).arg( errorText );
+ break;
+ case TDEIO::ERR_NO_SOURCE_PROTOCOL:
+ result = i18n( "The protocol %1 is only a filter protocol.").arg( errorText );
+ break;
+ case TDEIO::ERR_UNSUPPORTED_ACTION:
+ result = errorText;
+// result = i18n( "Unsupported action %1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_IS_DIRECTORY:
+ result = i18n( "%1 is a folder, but a file was expected." ).arg( errorText );
+ break;
+ case TDEIO::ERR_IS_FILE:
+ result = i18n( "%1 is a file, but a folder was expected." ).arg( errorText );
+ break;
+ case TDEIO::ERR_DOES_NOT_EXIST:
+ result = i18n( "The file or folder %1 does not exist." ).arg( errorText );
+ break;
+ case TDEIO::ERR_FILE_ALREADY_EXIST:
+ result = i18n( "A file named %1 already exists." ).arg( errorText );
+ break;
+ case TDEIO::ERR_DIR_ALREADY_EXIST:
+ result = i18n( "A folder named %1 already exists." ).arg( errorText );
+ break;
+ case TDEIO::ERR_UNKNOWN_HOST:
+ result = errorText.isEmpty() ? i18n( "No hostname specified." ) : i18n( "Unknown host %1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_ACCESS_DENIED:
+ result = i18n( "Access denied to %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_WRITE_ACCESS_DENIED:
+ result = i18n( "Access denied.\nCould not write to %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_ENTER_DIRECTORY:
+ result = i18n( "Could not enter folder %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_PROTOCOL_IS_NOT_A_FILESYSTEM:
+ result = i18n( "The protocol %1 does not implement a folder service." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CYCLIC_LINK:
+ result = i18n( "Found a cyclic link in %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_USER_CANCELED:
+ // Do nothing in this case. The user doesn't need to be told what he just did.
+ break;
+ case TDEIO::ERR_CYCLIC_COPY:
+ result = i18n( "Found a cyclic link while copying %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_CREATE_SOCKET:
+ result = i18n( "Could not create socket for accessing %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_CONNECT:
+ result = i18n( "Could not connect to host %1." ).arg( errorText.isEmpty() ? TQString::fromLatin1("localhost") : errorText );
+ break;
+ case TDEIO::ERR_CONNECTION_BROKEN:
+ result = i18n( "Connection to host %1 is broken." ).arg( errorText );
+ break;
+ case TDEIO::ERR_NOT_FILTER_PROTOCOL:
+ result = i18n( "The protocol %1 is not a filter protocol." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_MOUNT:
+ result = i18n( "Could not mount device.\nThe reported error was:\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_UNMOUNT:
+ result = i18n( "Could not unmount device.\nThe reported error was:\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_READ:
+ result = i18n( "Could not read file %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_WRITE:
+ result = i18n( "Could not write to file %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_BIND:
+ result = i18n( "Could not bind %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_LISTEN:
+ result = i18n( "Could not listen %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_ACCEPT:
+ result = i18n( "Could not accept %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_LOGIN:
+ result = errorText;
+ break;
+ case TDEIO::ERR_COULD_NOT_STAT:
+ result = i18n( "Could not access %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_CLOSEDIR:
+ result = i18n( "Could not terminate listing %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_MKDIR:
+ result = i18n( "Could not make folder %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_RMDIR:
+ result = i18n( "Could not remove folder %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_RESUME:
+ result = i18n( "Could not resume file %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_RENAME:
+ result = i18n( "Could not rename file %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_CHMOD:
+ result = i18n( "Could not change permissions for %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_DELETE:
+ result = i18n( "Could not delete file %1." ).arg( errorText );
+ break;
+ case TDEIO::ERR_SLAVE_DIED:
+ result = i18n( "The process for the %1 protocol died unexpectedly." ).arg( errorText );
+ break;
+ case TDEIO::ERR_OUT_OF_MEMORY:
+ result = i18n( "Error. Out of memory.\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_UNKNOWN_PROXY_HOST:
+ result = i18n( "Unknown proxy host\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_COULD_NOT_AUTHENTICATE:
+ result = i18n( "Authorization failed, %1 authentication not supported" ).arg( errorText );
+ break;
+ case TDEIO::ERR_ABORTED:
+ result = i18n( "User canceled action\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_INTERNAL_SERVER:
+ result = i18n( "Internal error in server\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_SERVER_TIMEOUT:
+ result = i18n( "Timeout on server\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_UNKNOWN:
+ result = i18n( "Unknown error\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_UNKNOWN_INTERRUPT:
+ result = i18n( "Unknown interrupt\n%1" ).arg( errorText );
+ break;
+/*
+ case TDEIO::ERR_CHECKSUM_MISMATCH:
+ if (errorText)
+ result = i18n( "Warning: MD5 Checksum for %1 does not match checksum returned from server" ).arg(errorText);
+ else
+ result = i18n( "Warning: MD5 Checksum for %1 does not match checksum returned from server" ).arg("document");
+ break;
+*/
+ case TDEIO::ERR_CANNOT_DELETE_ORIGINAL:
+ result = i18n( "Could not delete original file %1.\nPlease check permissions." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_DELETE_PARTIAL:
+ result = i18n( "Could not delete partial file %1.\nPlease check permissions." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_RENAME_ORIGINAL:
+ result = i18n( "Could not rename original file %1.\nPlease check permissions." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_RENAME_PARTIAL:
+ result = i18n( "Could not rename partial file %1.\nPlease check permissions." ).arg( errorText );
+ break;
+ case TDEIO::ERR_CANNOT_SYMLINK:
+ result = i18n( "Could not create symlink %1.\nPlease check permissions." ).arg( errorText );
+ break;
+ case TDEIO::ERR_NO_CONTENT:
+ result = errorText;
+ break;
+ case TDEIO::ERR_DISK_FULL:
+ result = i18n( "Could not write file %1.\nDisk full." ).arg( errorText );
+ break;
+ case TDEIO::ERR_IDENTICAL_FILES:
+ result = i18n( "The source and destination are the same file.\n%1" ).arg( errorText );
+ break;
+ case TDEIO::ERR_SLAVE_DEFINED:
+ result = errorText;
+ break;
+ case TDEIO::ERR_UPGRADE_REQUIRED:
+ result = i18n( "%1 is required by the server, but is not available." ).arg(errorText);
+ break;
+ case TDEIO::ERR_POST_DENIED:
+ result = i18n( "Access to restricted port in POST denied.");
+ break;
+ case TDEIO::ERR_OFFLINE_MODE:
+ result = i18n( "Could not access %1.\nOffline mode active.").arg( errorText );
+ break;
+ default:
+ result = i18n( "Unknown error code %1\n%2\nPlease send a full bug report at http://bugs.kde.org." ).arg( errorCode ).arg( errorText );
+ break;
+ }
+
+ return result;
+}
+
+TDEIO_EXPORT TQString TDEIO::unsupportedActionErrorString(const TQString &protocol, int cmd) {
+ switch (cmd) {
+ case CMD_CONNECT:
+ return i18n("Opening connections is not supported with the protocol %1." ).arg(protocol);
+ case CMD_DISCONNECT:
+ return i18n("Closing connections is not supported with the protocol %1." ).arg(protocol);
+ case CMD_STAT:
+ return i18n("Accessing files is not supported with the protocol %1.").arg(protocol);
+ case CMD_PUT:
+ return i18n("Writing to %1 is not supported.").arg(protocol);
+ case CMD_SPECIAL:
+ return i18n("There are no special actions available for protocol %1.").arg(protocol);
+ case CMD_LISTDIR:
+ return i18n("Listing folders is not supported for protocol %1.").arg(protocol);
+ case CMD_GET:
+ return i18n("Retrieving data from %1 is not supported.").arg(protocol);
+ case CMD_MIMETYPE:
+ return i18n("Retrieving mime type information from %1 is not supported.").arg(protocol);
+ case CMD_RENAME:
+ return i18n("Renaming or moving files within %1 is not supported.").arg(protocol);
+ case CMD_SYMLINK:
+ return i18n("Creating symlinks is not supported with protocol %1.").arg(protocol);
+ case CMD_COPY:
+ return i18n("Copying files within %1 is not supported.").arg(protocol);
+ case CMD_DEL:
+ return i18n("Deleting files from %1 is not supported.").arg(protocol);
+ case CMD_MKDIR:
+ return i18n("Creating folders is not supported with protocol %1.").arg(protocol);
+ case CMD_CHMOD:
+ return i18n("Changing the attributes of files is not supported with protocol %1.").arg(protocol);
+ case CMD_SUBURL:
+ return i18n("Using sub-URLs with %1 is not supported.").arg(protocol);
+ case CMD_MULTI_GET:
+ return i18n("Multiple get is not supported with protocol %1.").arg(protocol);
+ default:
+ return i18n("Protocol %1 does not support action %2.").arg(protocol).arg(cmd);
+ }/*end switch*/
+}
+
+TDEIO_EXPORT TQStringList TDEIO::Job::detailedErrorStrings( const KURL *reqUrl /*= 0L*/,
+ int method /*= -1*/ ) const
+{
+ TQString errorName, techName, description, ret2;
+ TQStringList causes, solutions, ret;
+
+ TQByteArray raw = rawErrorDetail( m_error, m_errorText, reqUrl, method );
+ TQDataStream stream(raw, IO_ReadOnly);
+
+ stream >> errorName >> techName >> description >> causes >> solutions;
+
+ TQString url, protocol, datetime;
+ if ( reqUrl ) {
+ url = reqUrl->htmlURL();
+ protocol = reqUrl->protocol();
+ } else {
+ url = i18n( "(unknown)" );
+ }
+
+ datetime = TDEGlobal::locale()->formatDateTime( TQDateTime::currentDateTime(),
+ false );
+
+ ret << errorName;
+ ret << TQString::fromLatin1( "<qt><p><b>" ) + errorName +
+ TQString::fromLatin1( "</b></p><p>" ) + description +
+ TQString::fromLatin1( "</p>" );
+ ret2 = TQString::fromLatin1( "<qt><p>" );
+ if ( !techName.isEmpty() )
+ ret2 += i18n( "<b>Technical reason</b>: " ) + techName + TQString::fromLatin1( "</p>" );
+ ret2 += i18n( "</p><p><b>Details of the request</b>:" );
+ ret2 += i18n( "</p><ul><li>URL: %1</li>" ).arg( url );
+ if ( !protocol.isEmpty() ) {
+ ret2 += i18n( "<li>Protocol: %1</li>" ).arg( protocol );
+ }
+ ret2 += i18n( "<li>Date and time: %1</li>" ).arg( datetime );
+ ret2 += i18n( "<li>Additional information: %1</li></ul>" ).arg( m_errorText );
+ if ( !causes.isEmpty() ) {
+ ret2 += i18n( "<p><b>Possible causes</b>:</p><ul><li>" );
+ ret2 += causes.join( "</li><li>" );
+ ret2 += TQString::fromLatin1( "</li></ul>" );
+ }
+ if ( !solutions.isEmpty() ) {
+ ret2 += i18n( "<p><b>Possible solutions</b>:</p><ul><li>" );
+ ret2 += solutions.join( "</li><li>" );
+ ret2 += TQString::fromLatin1( "</li></ul>" );
+ }
+ ret << ret2;
+ return ret;
+}
+
+TDEIO_EXPORT TQByteArray TDEIO::rawErrorDetail(int errorCode, const TQString &errorText,
+ const KURL *reqUrl /*= 0L*/, int /*method = -1*/ )
+{
+ TQString url, host, protocol, datetime, domain, path, dir, filename;
+ bool isSlaveNetwork = false;
+ if ( reqUrl ) {
+ url = reqUrl->prettyURL();
+ host = reqUrl->host();
+ protocol = reqUrl->protocol();
+
+ if ( host.left(4) == "www." )
+ domain = host.mid(4);
+ else
+ domain = host;
+
+ path = reqUrl->path(1);
+ filename = reqUrl->fileName();
+ dir = path + filename;
+
+ // detect if protocol is a network protocol...
+ // add your hacks here...
+ if ( protocol == "http" ||
+ protocol == "https" ||
+ protocol == "ftp" ||
+ protocol == "sftp" ||
+ protocol == "webdav" ||
+ protocol == "webdavs" ||
+ protocol == "finger" ||
+ protocol == "fish" ||
+ protocol == "gopher" ||
+ protocol == "imap" ||
+ protocol == "imaps" ||
+ protocol == "lan" ||
+ protocol == "ldap" ||
+ protocol == "mailto" ||
+ protocol == "news" ||
+ protocol == "nntp" ||
+ protocol == "pop3" ||
+ protocol == "pop3s" ||
+ protocol == "smtp" ||
+ protocol == "smtps" ||
+ protocol == "telnet"
+ ) {
+ isSlaveNetwork = false;
+ }
+ } else {
+ // assume that the errorText has the location we are interested in
+ url = host = domain = path = filename = dir = errorText;
+ protocol = i18n( "(unknown)" );
+ }
+
+ datetime = TDEGlobal::locale()->formatDateTime( TQDateTime::currentDateTime(),
+ false );
+
+ TQString errorName, techName, description;
+ TQStringList causes, solutions;
+
+ // c == cause, s == solution
+ TQString sSysadmin = i18n( "Contact your appropriate computer support system, "
+ "whether the system administrator, or technical support group for further "
+ "assistance." );
+ TQString sServeradmin = i18n( "Contact the administrator of the server "
+ "for further assistance." );
+ // FIXME active link to permissions dialog
+ TQString sAccess = i18n( "Check your access permissions on this resource." );
+ TQString cAccess = i18n( "Your access permissions may be inadequate to "
+ "perform the requested operation on this resource." );
+ TQString cLocked = i18n( "The file may be in use (and thus locked) by "
+ "another user or application." );
+ TQString sQuerylock = i18n( "Check to make sure that no other "
+ "application or user is using the file or has locked the file." );
+ TQString cHardware = i18n( "Although unlikely, a hardware error may have "
+ "occurred." );
+ TQString cBug = i18n( "You may have encountered a bug in the program." );
+ TQString cBuglikely = i18n( "This is most likely to be caused by a bug in the "
+ "program. Please consider submitting a full bug report as detailed below." );
+ TQString sUpdate = i18n( "Update your software to the latest version. "
+ "Your distribution should provide tools to update your software." );
+ TQString sBugreport = i18n( "When all else fails, please consider helping the "
+ "TDE team or the third party maintainer of this software by submitting a "
+ "high quality bug report. If the software is provided by a third party, "
+ "please contact them directly. Otherwise, first look to see if "
+ "the same bug has been submitted by someone else by searching at the "
+ "<a href=\"http://bugs.pearsoncomputing.net//\">TDE bug reporting website</a>. If not, take "
+ "note of the details given above, and include them in your bug report, along "
+ "with as many other details as you think might help." );
+ TQString cNetwork = i18n( "There may have been a problem with your network "
+ "connection." );
+ // FIXME netconf kcontrol link
+ TQString cNetconf = i18n( "There may have been a problem with your network "
+ "configuration. If you have been accessing the Internet with no problems "
+ "recently, this is unlikely." );
+ TQString cNetpath = i18n( "There may have been a problem at some point along "
+ "the network path between the server and this computer." );
+ TQString sTryagain = i18n( "Try again, either now or at a later time." );
+ TQString cProtocol = i18n( "A protocol error or incompatibility may have occurred." );
+ TQString sExists = i18n( "Ensure that the resource exists, and try again." );
+ TQString cExists = i18n( "The specified resource may not exist." );
+ TQString cTypo = i18n( "You may have incorrectly typed the location." );
+ TQString sTypo = i18n( "Double-check that you have entered the correct location "
+ "and try again." );
+ TQString sNetwork = i18n( "Check your network connection status." );
+
+ switch( errorCode ) {
+ case TDEIO::ERR_CANNOT_OPEN_FOR_READING:
+ errorName = i18n( "Cannot Open Resource For Reading" );
+ description = i18n( "This means that the contents of the requested file "
+ "or folder <strong>%1</strong> could not be retrieved, as read "
+ "access could not be obtained." ).arg( dir );
+ causes << i18n( "You may not have permissions to read the file or open "
+ "the folder.") << cLocked << cHardware;
+ solutions << sAccess << sQuerylock << sSysadmin;
+ break;
+
+ case TDEIO::ERR_CANNOT_OPEN_FOR_WRITING:
+ errorName = i18n( "Cannot Open Resource For Writing" );
+ description = i18n( "This means that the file, <strong>%1</strong>, could "
+ "not be written to as requested, because access with permission to "
+ "write could not be obtained." ).arg( filename );
+ causes << cAccess << cLocked << cHardware;
+ solutions << sAccess << sQuerylock << sSysadmin;
+ break;
+
+ case TDEIO::ERR_CANNOT_LAUNCH_PROCESS:
+ errorName = i18n( "Cannot Initiate the %1 Protocol" ).arg( protocol );
+ techName = i18n( "Unable to Launch Process" );
+ description = i18n( "The program on your computer which provides access "
+ "to the <strong>%1</strong> protocol could not be started. This is "
+ "usually due to technical reasons." ).arg( protocol );
+ causes << i18n( "The program which provides compatibility with this "
+ "protocol may not have been updated with your last update of TDE. "
+ "This can cause the program to be incompatible with the current version "
+ "and thus not start." ) << cBug;
+ solutions << sUpdate << sSysadmin;
+ break;
+
+ case TDEIO::ERR_INTERNAL:
+ errorName = i18n( "Internal Error" );
+ description = i18n( "The program on your computer which provides access "
+ "to the <strong>%1</strong> protocol has reported an internal error." )
+ .arg( protocol );
+ causes << cBuglikely;
+ solutions << sUpdate << sBugreport;
+ break;
+
+ case TDEIO::ERR_MALFORMED_URL:
+ errorName = i18n( "Improperly Formatted URL" );
+ description = i18n( "The <strong>U</strong>niform <strong>R</strong>esource "
+ "<strong>L</strong>ocator (URL) that you entered was not properly "
+ "formatted. The format of a URL is generally as follows:"
+ "<blockquote><strong>protocol://user:password@www.example.org:port/folder/"
+ "filename.extension?query=value</strong></blockquote>" );
+ solutions << sTypo;
+ break;
+
+ case TDEIO::ERR_UNSUPPORTED_PROTOCOL:
+ errorName = i18n( "Unsupported Protocol %1" ).arg( protocol );
+ description = i18n( "The protocol <strong>%1</strong> is not supported "
+ "by the TDE programs currently installed on this computer." )
+ .arg( protocol );
+ causes << i18n( "The requested protocol may not be supported." )
+ << i18n( "The versions of the %1 protocol supported by this computer and "
+ "the server may be incompatible." ).arg( protocol );
+ solutions << i18n( "You may perform a search on the Internet for a TDE "
+ "program (called a tdeioslave or ioslave) which supports this protocol. "
+ "Places to search include <a href=\"http://kde-apps.org/\">"
+ "http://kde-apps.org/</a> and <a href=\"http://freshmeat.net/\">"
+ "http://freshmeat.net/</a>." )
+ << sUpdate << sSysadmin;
+ break;
+
+ case TDEIO::ERR_NO_SOURCE_PROTOCOL:
+ errorName = i18n( "URL Does Not Refer to a Resource." );
+ techName = i18n( "Protocol is a Filter Protocol" );
+ description = i18n( "The <strong>U</strong>niform <strong>R</strong>esource "
+ "<strong>L</strong>ocator (URL) that you entered did not refer to a "
+ "specific resource." );
+ causes << i18n( "TDE is able to communicate through a protocol within a "
+ "protocol; the protocol specified is only for use in such situations, "
+ "however this is not one of these situations. This is a rare event, and "
+ "is likely to indicate a programming error." );
+ solutions << sTypo;
+ break;
+
+ case TDEIO::ERR_UNSUPPORTED_ACTION:
+ errorName = i18n( "Unsupported Action: %1" ).arg( errorText );
+ description = i18n( "The requested action is not supported by the TDE "
+ "program which is implementing the <strong>%1</strong> protocol." )
+ .arg( protocol );
+ causes << i18n( "This error is very much dependent on the TDE program. The "
+ "additional information should give you more information than is available "
+ "to the TDE input/output architecture." );
+ solutions << i18n( "Attempt to find another way to accomplish the same "
+ "outcome." );
+ break;
+
+ case TDEIO::ERR_IS_DIRECTORY:
+ errorName = i18n( "File Expected" );
+ description = i18n( "The request expected a file, however the "
+ "folder <strong>%1</strong> was found instead." ).arg( dir );
+ causes << i18n( "This may be an error on the server side." ) << cBug;
+ solutions << sUpdate << sSysadmin;
+ break;
+
+ case TDEIO::ERR_IS_FILE:
+ errorName = i18n( "Folder Expected" );
+ description = i18n( "The request expected a folder, however "
+ "the file <strong>%1</strong> was found instead." ).arg( filename );
+ causes << cBug;
+ solutions << sUpdate << sSysadmin;
+ break;
+
+ case TDEIO::ERR_DOES_NOT_EXIST:
+ errorName = i18n( "File or Folder Does Not Exist" );
+ description = i18n( "The specified file or folder <strong>%1</strong> "
+ "does not exist." ).arg( dir );
+ causes << cBug;
+ solutions << sUpdate << sSysadmin;
+ break;
+
+ case TDEIO::ERR_FILE_ALREADY_EXIST:
+ errorName = i18n( "File Already Exists" );
+ description = i18n( "The requested file could not be created because a "
+ "file with the same name already exists." );
+ solutions << i18n ( "Try moving the current file out of the way first, "
+ "and then try again." )
+ << i18n ( "Delete the current file and try again." )
+ << i18n( "Choose an alternate filename for the new file." );
+ break;
+
+ case TDEIO::ERR_DIR_ALREADY_EXIST:
+ errorName = i18n( "Folder Already Exists" );
+ description = i18n( "The requested folder could not be created because "
+ "a folder with the same name already exists." );
+ solutions << i18n( "Try moving the current folder out of the way first, "
+ "and then try again." )
+ << i18n( "Delete the current folder and try again." )
+ << i18n( "Choose an alternate name for the new folder." );
+ break;
+
+ case TDEIO::ERR_UNKNOWN_HOST:
+ errorName = i18n( "Unknown Host" );
+ description = i18n( "An unknown host error indicates that the server with "
+ "the requested name, <strong>%1</strong>, could not be "
+ "located on the Internet." ).arg( host );
+ causes << i18n( "The name that you typed, %1, may not exist: it may be "
+ "incorrectly typed." ).arg( host )
+ << cNetwork << cNetconf;
+ solutions << sNetwork << sSysadmin;
+ break;
+
+ case TDEIO::ERR_ACCESS_DENIED:
+ errorName = i18n( "Access Denied" );
+ description = i18n( "Access was denied to the specified resource, "
+ "<strong>%1</strong>." ).arg( url );
+ causes << i18n( "You may have supplied incorrect authentication details or "
+ "none at all." )
+ << i18n( "Your account may not have permission to access the "
+ "specified resource." );
+ solutions << i18n( "Retry the request and ensure your authentication details "
+ "are entered correctly." ) << sSysadmin;
+ if ( !isSlaveNetwork ) solutions << sServeradmin;
+ break;
+
+ case TDEIO::ERR_WRITE_ACCESS_DENIED:
+ errorName = i18n( "Write Access Denied" );
+ description = i18n( "This means that an attempt to write to the file "
+ "<strong>%1</strong> was rejected." ).arg( filename );
+ causes << cAccess << cLocked << cHardware;
+ solutions << sAccess << sQuerylock << sSysadmin;
+ break;
+
+ case TDEIO::ERR_CANNOT_ENTER_DIRECTORY:
+ errorName = i18n( "Unable to Enter Folder" );
+ description = i18n( "This means that an attempt to enter (in other words, "
+ "to open) the requested folder <strong>%1</strong> was rejected." )
+ .arg( dir );
+ causes << cAccess << cLocked;
+ solutions << sAccess << sQuerylock << sSysadmin;
+ break;
+
+ case TDEIO::ERR_PROTOCOL_IS_NOT_A_FILESYSTEM:
+ errorName = i18n( "Folder Listing Unavailable" );
+ techName = i18n( "Protocol %1 is not a Filesystem" ).arg( protocol );
+ description = i18n( "This means that a request was made which requires "
+ "determining the contents of the folder, and the TDE program supporting "
+ "this protocol is unable to do so." );
+ causes << cBug;
+ solutions << sUpdate << sBugreport;
+ break;
+
+ case TDEIO::ERR_CYCLIC_LINK:
+ errorName = i18n( "Cyclic Link Detected" );
+ description = i18n( "UNIX environments are commonly able to link a file or "
+ "folder to a separate name and/or location. TDE detected a link or "
+ "series of links that results in an infinite loop - i.e. the file was "
+ "(perhaps in a roundabout way) linked to itself." );
+ solutions << i18n( "Delete one part of the loop in order that it does not "
+ "cause an infinite loop, and try again." ) << sSysadmin;
+ break;
+
+ case TDEIO::ERR_USER_CANCELED:
+ // Do nothing in this case. The user doesn't need to be told what he just did.
+ // rodda: However, if we have been called, an application is about to display
+ // this information anyway. If we don't return sensible information, the
+ // user sees a blank dialog (I have seen this myself)
+ errorName = i18n( "Request Aborted By User" );
+ description = i18n( "The request was not completed because it was "
+ "aborted." );
+ solutions << i18n( "Retry the request." );
+ break;
+
+ case TDEIO::ERR_CYCLIC_COPY:
+ errorName = i18n( "Cyclic Link Detected During Copy" );
+ description = i18n( "UNIX environments are commonly able to link a file or "
+ "folder to a separate name and/or location. During the requested copy "
+ "operation, TDE detected a link or series of links that results in an "
+ "infinite loop - i.e. the file was (perhaps in a roundabout way) linked "
+ "to itself." );
+ solutions << i18n( "Delete one part of the loop in order that it does not "
+ "cause an infinite loop, and try again." ) << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_CREATE_SOCKET:
+ errorName = i18n( "Could Not Create Network Connection" );
+ techName = i18n( "Could Not Create Socket" );
+ description = i18n( "This is a fairly technical error in which a required "
+ "device for network communications (a socket) could not be created." );
+ causes << i18n( "The network connection may be incorrectly configured, or "
+ "the network interface may not be enabled." );
+ solutions << sNetwork << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_CONNECT:
+ errorName = i18n( "Connection to Server Refused" );
+ description = i18n( "The server <strong>%1</strong> refused to allow this "
+ "computer to make a connection." ).arg( host );
+ causes << i18n( "The server, while currently connected to the Internet, "
+ "may not be configured to allow requests." )
+ << i18n( "The server, while currently connected to the Internet, "
+ "may not be running the requested service (%1)." ).arg( protocol )
+ << i18n( "A network firewall (a device which restricts Internet "
+ "requests), either protecting your network or the network of the server, "
+ "may have intervened, preventing this request." );
+ solutions << sTryagain << sServeradmin << sSysadmin;
+ break;
+
+ case TDEIO::ERR_CONNECTION_BROKEN:
+ errorName = i18n( "Connection to Server Closed Unexpectedly" );
+ description = i18n( "Although a connection was established to "
+ "<strong>%1</strong>, the connection was closed at an unexpected point "
+ "in the communication." ).arg( host );
+ causes << cNetwork << cNetpath << i18n( "A protocol error may have occurred, "
+ "causing the server to close the connection as a response to the error." );
+ solutions << sTryagain << sServeradmin << sSysadmin;
+ break;
+
+ case TDEIO::ERR_NOT_FILTER_PROTOCOL:
+ errorName = i18n( "URL Resource Invalid" );
+ techName = i18n( "Protocol %1 is not a Filter Protocol" ).arg( protocol );
+ description = i18n( "The <strong>U</strong>niform <strong>R</strong>esource "
+ "<strong>L</strong>ocator (URL) that you entered did not refer to "
+ "a valid mechanism of accessing the specific resource, "
+ "<strong>%1%2</strong>." )
+ .arg( !host.isNull() ? host + '/' : TQString::null ).arg( dir );
+ causes << i18n( "TDE is able to communicate through a protocol within a "
+ "protocol. This request specified a protocol be used as such, however "
+ "this protocol is not capable of such an action. This is a rare event, "
+ "and is likely to indicate a programming error." );
+ solutions << sTypo << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_MOUNT:
+ errorName = i18n( "Unable to Initialize Input/Output Device" );
+ techName = i18n( "Could Not Mount Device" );
+ description = i18n( "The requested device could not be initialized "
+ "(\"mounted\"). The reported error was: <strong>%1</strong>" )
+ .arg( errorText );
+ causes << i18n( "The device may not be ready, for example there may be "
+ "no media in a removable media device (i.e. no CD-ROM in a CD drive), "
+ "or in the case of a peripheral/portable device, the device may not "
+ "be correctly connected." )
+ << i18n( "You may not have permissions to initialize (\"mount\") the "
+ "device. On UNIX systems, often system administrator privileges are "
+ "required to initialize a device." )
+ << cHardware;
+ solutions << i18n( "Check that the device is ready; removable drives "
+ "must contain media, and portable devices must be connected and powered "
+ "on.; and try again." ) << sAccess << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_UNMOUNT:
+ errorName = i18n( "Unable to Uninitialize Input/Output Device" );
+ techName = i18n( "Could Not Unmount Device" );
+ description = i18n( "The requested device could not be uninitialized "
+ "(\"unmounted\"). The reported error was: <strong>%1</strong>" )
+ .arg( errorText );
+ causes << i18n( "The device may be busy, that is, still in use by "
+ "another application or user. Even such things as having an open "
+ "browser window on a location on this device may cause the device to "
+ "remain in use." )
+ << i18n( "You may not have permissions to uninitialize (\"unmount\") "
+ "the device. On UNIX systems, system administrator privileges are "
+ "often required to uninitialize a device." )
+ << cHardware;
+ solutions << i18n( "Check that no applications are accessing the device, "
+ "and try again." ) << sAccess << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_READ:
+ errorName = i18n( "Cannot Read From Resource" );
+ description = i18n( "This means that although the resource, "
+ "<strong>%1</strong>, was able to be opened, an error occurred while "
+ "reading the contents of the resource." ).arg( url );
+ causes << i18n( "You may not have permissions to read from the resource." );
+ if ( !isSlaveNetwork ) causes << cNetwork;
+ causes << cHardware;
+ solutions << sAccess;
+ if ( !isSlaveNetwork ) solutions << sNetwork;
+ solutions << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_WRITE:
+ errorName = i18n( "Cannot Write to Resource" );
+ description = i18n( "This means that although the resource, <strong>%1</strong>"
+ ", was able to be opened, an error occurred while writing to the resource." )
+ .arg( url );
+ causes << i18n( "You may not have permissions to write to the resource." );
+ if ( !isSlaveNetwork ) causes << cNetwork;
+ causes << cHardware;
+ solutions << sAccess;
+ if ( !isSlaveNetwork ) solutions << sNetwork;
+ solutions << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_BIND:
+ errorName = i18n( "Could Not Listen for Network Connections" );
+ techName = i18n( "Could Not Bind" );
+ description = i18n( "This is a fairly technical error in which a required "
+ "device for network communications (a socket) could not be established "
+ "to listen for incoming network connections." );
+ causes << i18n( "The network connection may be incorrectly configured, or "
+ "the network interface may not be enabled." );
+ solutions << sNetwork << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_LISTEN:
+ errorName = i18n( "Could Not Listen for Network Connections" );
+ techName = i18n( "Could Not Listen" );
+ description = i18n( "This is a fairly technical error in which a required "
+ "device for network communications (a socket) could not be established "
+ "to listen for incoming network connections." );
+ causes << i18n( "The network connection may be incorrectly configured, or "
+ "the network interface may not be enabled." );
+ solutions << sNetwork << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_ACCEPT:
+ errorName = i18n( "Could Not Accept Network Connection" );
+ description = i18n( "This is a fairly technical error in which an error "
+ "occurred while attempting to accept an incoming network connection." );
+ causes << i18n( "The network connection may be incorrectly configured, or "
+ "the network interface may not be enabled." )
+ << i18n( "You may not have permissions to accept the connection." );
+ solutions << sNetwork << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_LOGIN:
+ errorName = i18n( "Could Not Login: %1" ).arg( errorText );
+ description = i18n( "An attempt to login to perform the requested "
+ "operation was unsuccessful." );
+ causes << i18n( "You may have supplied incorrect authentication details or "
+ "none at all." )
+ << i18n( "Your account may not have permission to access the "
+ "specified resource." ) << cProtocol;
+ solutions << i18n( "Retry the request and ensure your authentication details "
+ "are entered correctly." ) << sServeradmin << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_STAT:
+ errorName = i18n( "Could Not Determine Resource Status" );
+ techName = i18n( "Could Not Stat Resource" );
+ description = i18n( "An attempt to determine information about the status "
+ "of the resource <strong>%1</strong>, such as the resource name, type, "
+ "size, etc., was unsuccessful." ).arg( url );
+ causes << i18n( "The specified resource may not have existed or may "
+ "not be accessible." ) << cProtocol << cHardware;
+ solutions << i18n( "Retry the request and ensure your authentication details "
+ "are entered correctly." ) << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_CLOSEDIR:
+ //result = i18n( "Could not terminate listing %1" ).arg( errorText );
+ errorName = i18n( "Could Not Cancel Listing" );
+ techName = i18n( "FIXME: Document this" );
+ break;
+
+ case TDEIO::ERR_COULD_NOT_MKDIR:
+ errorName = i18n( "Could Not Create Folder" );
+ description = i18n( "An attempt to create the requested folder failed." );
+ causes << cAccess << i18n( "The location where the folder was to be created "
+ "may not exist." );
+ if ( !isSlaveNetwork ) causes << cProtocol;
+ solutions << i18n( "Retry the request." ) << sAccess;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_RMDIR:
+ errorName = i18n( "Could Not Remove Folder" );
+ description = i18n( "An attempt to remove the specified folder, "
+ "<strong>%1</strong>, failed." ).arg( dir );
+ causes << i18n( "The specified folder may not exist." )
+ << i18n( "The specified folder may not be empty." )
+ << cAccess;
+ if ( !isSlaveNetwork ) causes << cProtocol;
+ solutions << i18n( "Ensure that the folder exists and is empty, and try "
+ "again." ) << sAccess;
+ break;
+
+ case TDEIO::ERR_CANNOT_RESUME:
+ errorName = i18n( "Could Not Resume File Transfer" );
+ description = i18n( "The specified request asked that the transfer of "
+ "file <strong>%1</strong> be resumed at a certain point of the "
+ "transfer. This was not possible." ).arg( filename );
+ causes << i18n( "The protocol, or the server, may not support file "
+ "resuming." );
+ solutions << i18n( "Retry the request without attempting to resume "
+ "transfer." );
+ break;
+
+ case TDEIO::ERR_CANNOT_RENAME:
+ errorName = i18n( "Could Not Rename Resource" );
+ description = i18n( "An attempt to rename the specified resource "
+ "<strong>%1</strong> failed." ).arg( url );
+ causes << cAccess << cExists;
+ if ( !isSlaveNetwork ) causes << cProtocol;
+ solutions << sAccess << sExists;
+ break;
+
+ case TDEIO::ERR_CANNOT_CHMOD:
+ errorName = i18n( "Could Not Alter Permissions of Resource" );
+ description = i18n( "An attempt to alter the permissions on the specified "
+ "resource <strong>%1</strong> failed." ).arg( url );
+ causes << cAccess << cExists;
+ solutions << sAccess << sExists;
+ break;
+
+ case TDEIO::ERR_CANNOT_DELETE:
+ errorName = i18n( "Could Not Delete Resource" );
+ description = i18n( "An attempt to delete the specified resource "
+ "<strong>%1</strong> failed." ).arg( url );
+ causes << cAccess << cExists;
+ solutions << sAccess << sExists;
+ break;
+
+ case TDEIO::ERR_SLAVE_DIED:
+ errorName = i18n( "Unexpected Program Termination" );
+ description = i18n( "The program on your computer which provides access "
+ "to the <strong>%1</strong> protocol has unexpectedly terminated." )
+ .arg( url );
+ causes << cBuglikely;
+ solutions << sUpdate << sBugreport;
+ break;
+
+ case TDEIO::ERR_OUT_OF_MEMORY:
+ errorName = i18n( "Out of Memory" );
+ description = i18n( "The program on your computer which provides access "
+ "to the <strong>%1</strong> protocol could not obtain the memory "
+ "required to continue." ).arg( protocol );
+ causes << cBuglikely;
+ solutions << sUpdate << sBugreport;
+ break;
+
+ case TDEIO::ERR_UNKNOWN_PROXY_HOST:
+ errorName = i18n( "Unknown Proxy Host" );
+ description = i18n( "While retrieving information about the specified "
+ "proxy host, <strong>%1</strong>, an Unknown Host error was encountered. "
+ "An unknown host error indicates that the requested name could not be "
+ "located on the Internet." ).arg( errorText );
+ causes << i18n( "There may have been a problem with your network "
+ "configuration, specifically your proxy's hostname. If you have been "
+ "accessing the Internet with no problems recently, this is unlikely." )
+ << cNetwork;
+ solutions << i18n( "Double-check your proxy settings and try again." )
+ << sSysadmin;
+ break;
+
+ case TDEIO::ERR_COULD_NOT_AUTHENTICATE:
+ errorName = i18n( "Authentication Failed: Method %1 Not Supported" )
+ .arg( errorText );
+ description = i18n( "Although you may have supplied the correct "
+ "authentication details, the authentication failed because the "
+ "method that the server is using is not supported by the TDE "
+ "program implementing the protocol %1." ).arg( protocol );
+ solutions << i18n( "Please file a bug at <a href=\"http://bugs.kde.org/\">"
+ "http://bugs.pearsoncomputing.net/</a> to inform the TDE team of the unsupported "
+ "authentication method." ) << sSysadmin;
+ break;
+
+ case TDEIO::ERR_ABORTED:
+ errorName = i18n( "Request Aborted" );
+ description = i18n( "The request was not completed because it was "
+ "aborted." );
+ solutions << i18n( "Retry the request." );
+ break;
+
+ case TDEIO::ERR_INTERNAL_SERVER:
+ errorName = i18n( "Internal Error in Server" );
+ description = i18n( "The program on the server which provides access "
+ "to the <strong>%1</strong> protocol has reported an internal error: "
+ "%0." ).arg( protocol );
+ causes << i18n( "This is most likely to be caused by a bug in the "
+ "server program. Please consider submitting a full bug report as "
+ "detailed below." );
+ solutions << i18n( "Contact the administrator of the server "
+ "to advise them of the problem." )
+ << i18n( "If you know who the authors of the server software are, "
+ "submit the bug report directly to them." );
+ break;
+
+ case TDEIO::ERR_SERVER_TIMEOUT:
+ errorName = i18n( "Timeout Error" );
+ description = i18n( "Although contact was made with the server, a "
+ "response was not received within the amount of time allocated for "
+ "the request as follows:<ul>"
+ "<li>Timeout for establishing a connection: %1 seconds</li>"
+ "<li>Timeout for receiving a response: %2 seconds</li>"
+ "<li>Timeout for accessing proxy servers: %3 seconds</li></ul>"
+ "Please note that you can alter these timeout settings in the TDE "
+ "Control Center, by selecting Network -> Preferences." )
+ .arg( KProtocolManager::connectTimeout() )
+ .arg( KProtocolManager::responseTimeout() )
+ .arg( KProtocolManager::proxyConnectTimeout() );
+ causes << cNetpath << i18n( "The server was too busy responding to other "
+ "requests to respond." );
+ solutions << sTryagain << sServeradmin;
+ break;
+
+ case TDEIO::ERR_UNKNOWN:
+ errorName = i18n( "Unknown Error" );
+ description = i18n( "The program on your computer which provides access "
+ "to the <strong>%1</strong> protocol has reported an unknown error: "
+ "%2." ).arg( protocol ).arg( errorText );
+ causes << cBug;
+ solutions << sUpdate << sBugreport;
+ break;
+
+ case TDEIO::ERR_UNKNOWN_INTERRUPT:
+ errorName = i18n( "Unknown Interruption" );
+ description = i18n( "The program on your computer which provides access "
+ "to the <strong>%1</strong> protocol has reported an interruption of "
+ "an unknown type: %2." ).arg( protocol ).arg( errorText );
+ causes << cBug;
+ solutions << sUpdate << sBugreport;
+ break;
+
+ case TDEIO::ERR_CANNOT_DELETE_ORIGINAL:
+ errorName = i18n( "Could Not Delete Original File" );
+ description = i18n( "The requested operation required the deleting of "
+ "the original file, most likely at the end of a file move operation. "
+ "The original file <strong>%1</strong> could not be deleted." )
+ .arg( errorText );
+ causes << cAccess;
+ solutions << sAccess;
+ break;
+
+ case TDEIO::ERR_CANNOT_DELETE_PARTIAL:
+ errorName = i18n( "Could Not Delete Temporary File" );
+ description = i18n( "The requested operation required the creation of "
+ "a temporary file in which to save the new file while being "
+ "downloaded. This temporary file <strong>%1</strong> could not be "
+ "deleted." ).arg( errorText );
+ causes << cAccess;
+ solutions << sAccess;
+ break;
+
+ case TDEIO::ERR_CANNOT_RENAME_ORIGINAL:
+ errorName = i18n( "Could Not Rename Original File" );
+ description = i18n( "The requested operation required the renaming of "
+ "the original file <strong>%1</strong>, however it could not be "
+ "renamed." ).arg( errorText );
+ causes << cAccess;
+ solutions << sAccess;
+ break;
+
+ case TDEIO::ERR_CANNOT_RENAME_PARTIAL:
+ errorName = i18n( "Could Not Rename Temporary File" );
+ description = i18n( "The requested operation required the creation of "
+ "a temporary file <strong>%1</strong>, however it could not be "
+ "created." ).arg( errorText );
+ causes << cAccess;
+ solutions << sAccess;
+ break;
+
+ case TDEIO::ERR_CANNOT_SYMLINK:
+ errorName = i18n( "Could Not Create Link" );
+ techName = i18n( "Could Not Create Symbolic Link" );
+ description = i18n( "The requested symbolic link %1 could not be created." )
+ .arg( errorText );
+ causes << cAccess;
+ solutions << sAccess;
+ break;
+
+ case TDEIO::ERR_NO_CONTENT:
+ errorName = i18n( "No Content" );
+ description = errorText;
+ break;
+
+ case TDEIO::ERR_DISK_FULL:
+ errorName = i18n( "Disk Full" );
+ description = i18n( "The requested file <strong>%1</strong> could not be "
+ "written to as there is inadequate disk space." ).arg( errorText );
+ solutions << i18n( "Free up enough disk space by 1) deleting unwanted and "
+ "temporary files; 2) archiving files to removable media storage such as "
+ "CD-Recordable discs; or 3) obtain more storage capacity." )
+ << sSysadmin;
+ break;
+
+ case TDEIO::ERR_IDENTICAL_FILES:
+ errorName = i18n( "Source and Destination Files Identical" );
+ description = i18n( "The operation could not be completed because the "
+ "source and destination files are the same file." );
+ solutions << i18n( "Choose a different filename for the destination file." );
+ break;
+
+ // We assume that the slave has all the details
+ case TDEIO::ERR_SLAVE_DEFINED:
+ errorName = TQString::null;
+ description = errorText;
+ break;
+
+ default:
+ // fall back to the plain error...
+ errorName = i18n( "Undocumented Error" );
+ description = buildErrorString( errorCode, errorText );
+ }
+
+ TQByteArray ret;
+ TQDataStream stream(ret, IO_WriteOnly);
+ stream << errorName << techName << description << causes << solutions;
+ return ret;
+}
+
+#ifdef Q_OS_UNIX
+
+#include <limits.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <tqfile.h>
+
+#include <config.h>
+
+#ifdef HAVE_PATHS_H
+#include <paths.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+#include <sys/param.h>
+#ifdef HAVE_LIMITS_H
+#include <limits.h>
+#endif
+#ifdef HAVE_SYS_MNTTAB_H
+#include <sys/mnttab.h>
+#endif
+#ifdef HAVE_MNTENT_H
+#include <mntent.h>
+#elif defined(HAVE_SYS_MNTENT_H)
+#include <sys/mntent.h>
+#endif
+#ifdef HAVE_SYS_UCRED_H
+#include <sys/ucred.h>
+#endif
+#ifdef HAVE_SYS_MOUNT_H
+#include <sys/mount.h>
+#endif
+#ifdef HAVE_FSTAB_H
+#include <fstab.h>
+#endif
+#if defined(_AIX)
+#include <sys/mntctl.h>
+#include <sys/vmount.h>
+#include <sys/vfs.h>
+
+/* AIX does not prototype mntctl anywhere that I can find */
+#ifndef mntctl
+extern "C" {
+int mntctl(int command, int size, void* buffer);
+}
+#endif
+extern "C" struct vfs_ent *getvfsbytype(int vfsType);
+extern "C" void endvfsent( );
+#endif
+
+/***************************************************************
+ *
+ * Utility functions
+ *
+ ***************************************************************/
+
+#ifndef HAVE_GETMNTINFO
+
+#ifdef _PATH_MOUNTED
+// On some Linux, MNTTAB points to /etc/fstab !
+# undef MNTTAB
+# define MNTTAB _PATH_MOUNTED
+#else
+# ifndef MNTTAB
+# ifdef MTAB_FILE
+# define MNTTAB MTAB_FILE
+# else
+# define MNTTAB "/etc/mnttab"
+# endif
+# endif
+#endif
+
+#ifndef FSTAB
+# ifdef _PATH_FSTAB
+# define FSTAB _PATH_FSTAB
+# else
+# define FSTAB "/etc/fstab"
+# endif
+#endif
+
+#ifdef __CYGWIN__
+#define hasmntopt(var,opt) (0)
+#endif
+
+// There are (at least) four kind of APIs:
+// setmntent + getmntent + struct mntent (linux...)
+// getmntent + struct mnttab
+// mntctl + struct vmount (AIX)
+// getmntinfo + struct statfs&flags (BSD 4.4 and friends)
+// getfsent + char* (BSD 4.3 and friends)
+
+#ifdef HAVE_SETMNTENT
+#define SETMNTENT setmntent
+#define ENDMNTENT endmntent
+#define STRUCT_MNTENT struct mntent *
+#define STRUCT_SETMNTENT FILE *
+#define GETMNTENT(file, var) ((var = getmntent(file)) != 0)
+#define MOUNTPOINT(var) var->mnt_dir
+#define MOUNTTYPE(var) var->mnt_type
+#define HASMNTOPT(var, opt) hasmntopt(var, opt)
+#define FSNAME(var) var->mnt_fsname
+#elif defined(_AIX)
+/* we don't need this stuff */
+#else
+#define SETMNTENT fopen
+#define ENDMNTENT fclose
+#define STRUCT_MNTENT struct mnttab
+#define STRUCT_SETMNTENT FILE *
+#define GETMNTENT(file, var) (getmntent(file, &var) == 0)
+#define MOUNTPOINT(var) var.mnt_mountp
+#define MOUNTTYPE(var) var.mnt_fstype
+#define HASMNTOPT(var, opt) hasmntopt(&var, opt)
+#define FSNAME(var) var.mnt_special
+#endif
+
+#endif /* HAVE_GETMNTINFO */
+
+TQString TDEIO::findDeviceMountPoint( const TQString& filename )
+{
+ TQString result;
+
+#ifdef HAVE_VOLMGT
+ /*
+ * support for Solaris volume management
+ */
+ const char *volpath;
+ FILE *mnttab;
+ struct mnttab mnt;
+ int len;
+ TQCString devname;
+
+ if( (volpath = volmgt_root()) == NULL ) {
+ kdDebug( 7007 ) << "findDeviceMountPoint: "
+ << "VOLMGT: can't find volmgt root dir" << endl;
+ return TQString::null;
+ }
+
+ if( (mnttab = fopen( MNTTAB, "r" )) == NULL ) {
+ kdDebug( 7007 ) << "findDeviceMountPoint: "
+ << "VOLMGT: can't open mnttab" << endl;
+ return TQString::null;
+ }
+
+ devname = volpath;
+ devname += TQFile::encodeName( filename );
+ devname += '/';
+ len = devname.length();
+// kdDebug( 7007 ) << "findDeviceMountPoint: "
+// << "VOLMGT: searching mountpoint for \"" << devname << "\""
+// << endl;
+
+ /*
+ * find the mountpoint
+ * floppies:
+ * /dev/disketteN => <volpath>/dev/disketteN
+ * CDROM, ZIP, and other media:
+ * /dev/dsk/cXtYdZs2 => <volpath>/dev/dsk/cXtYdZ (without slice#)
+ */
+ rewind( mnttab );
+ result = TQString::null;
+ while( getmntent( mnttab, &mnt ) == 0 ) {
+ /*
+ * either match the exact device name (floppies),
+ * or the device name without the slice#
+ */
+ if( strncmp( devname.data(), mnt.mnt_special, len ) == 0
+ || (strncmp( devname.data(), mnt.mnt_special, len - 3 ) == 0
+ && mnt.mnt_special[len - 3] == '/' )
+ || (strcmp(TQFile::encodeName(filename).data()
+ , mnt.mnt_special)==0)) {
+ result = mnt.mnt_mountp;
+ break;
+ }
+ }
+ fclose( mnttab );
+#else
+
+ char realpath_buffer[MAXPATHLEN];
+ TQCString realname;
+
+ realname = TQFile::encodeName(filename);
+ /* If the path contains symlinks, get the real name */
+ if (realpath(realname, realpath_buffer) != 0)
+ // succes, use result from realpath
+ realname = realpath_buffer;
+
+ //kdDebug(7007) << "findDeviceMountPoint realname=" << realname << endl;
+
+#ifdef HAVE_GETMNTINFO
+
+#ifdef GETMNTINFO_USES_STATVFS
+ struct statvfs *mounted;
+#else
+ struct statfs *mounted;
+#endif
+
+ int num_fs = getmntinfo(&mounted, MNT_NOWAIT);
+
+ for (int i=0;i<num_fs;i++) {
+
+ TQCString device_name = mounted[i].f_mntfromname;
+
+ // If the path contains symlinks, get
+ // the real name
+ if (realpath(device_name, realpath_buffer) != 0)
+ // succes, use result from realpath
+ device_name = realpath_buffer;
+
+ if (realname == device_name) {
+ result = mounted[i].f_mntonname;
+ break;
+ }
+ }
+
+#elif defined(_AIX)
+
+ struct vmount *mntctl_buffer;
+ struct vmount *vm;
+ char *mountedfrom;
+ char *mountedto;
+ int fsname_len, num;
+ int buf_sz = 4096;
+
+ /* mntctl can be used to query mounted file systems.
+ * mntctl takes only the command MCTL_QUERY so far.
+ * The buffer is filled with an array of vmount structures, but these
+ * vmount structures have variable size.
+ * mntctl return values:
+ * -1 error
+ * 0 look in first word of buffer for required bytes, 4096 may be
+ * a good starting size, but if tables grow too large, look here.
+ * >0 number of vmount structures
+ */
+ mntctl_buffer = (struct vmount*)malloc(buf_sz);
+ num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
+ if (num == 0)
+ {
+ buf_sz = *(int*)mntctl_buffer;
+ free(mntctl_buffer);
+ mntctl_buffer = (struct vmount*)malloc(buf_sz);
+ num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
+ }
+
+ if (num > 0)
+ {
+ /* iterate through items in the vmount structure: */
+ vm = mntctl_buffer;
+ for ( ; num > 0; num-- )
+ {
+ /* get the name of the mounted file systems: */
+ fsname_len = vmt2datasize(vm, VMT_STUB);
+ mountedto = (char*)malloc(fsname_len + 1);
+ mountedto[fsname_len] = '\0';
+ strncpy(mountedto, (char *)vmt2dataptr(vm, VMT_STUB), fsname_len);
+
+ /* get the mount-from information: */
+ fsname_len = vmt2datasize(vm, VMT_OBJECT);
+ mountedfrom = (char*)malloc(fsname_len + 1);
+ mountedfrom[fsname_len] = '\0';
+ strncpy(mountedfrom, (char *)vmt2dataptr(vm, VMT_OBJECT), fsname_len);
+
+ TQCString device_name = mountedfrom;
+
+ if (realpath(device_name, realpath_buffer) != 0)
+ // success, use result from realpath
+ device_name = realpath_buffer;
+
+ free(mountedfrom);
+
+ if (realname == device_name) {
+ result = mountedto;
+ free(mountedto);
+ break;
+ }
+
+ free(mountedto);
+
+ /* goto the next vmount structure: */
+ vm = (struct vmount *)((char *)vm + vm->vmt_length);
+ }
+ }
+
+ free( mntctl_buffer );
+
+#else
+
+ STRUCT_SETMNTENT mtab;
+
+ /* Get the list of mounted file systems */
+
+ if ((mtab = SETMNTENT(MNTTAB, "r")) == 0) {
+ perror("setmntent");
+ return TQString::null;
+ }
+
+ /* Loop over all file systems and see if we can find our
+ * mount point.
+ * Note that this is the mount point with the longest match.
+ * XXX: Fails if me->mnt_dir is not a realpath but goes
+ * through a symlink, e.g. /foo/bar where /foo is a symlink
+ * pointing to /local/foo.
+ *
+ * How kinky can you get with a filesystem?
+ */
+
+ STRUCT_MNTENT me;
+
+ while (GETMNTENT(mtab, me))
+ {
+ // There may be symbolic links into the /etc/mnttab
+ // So we have to find the real device name here as well!
+ TQCString device_name = FSNAME(me);
+ if (device_name.isEmpty() || (device_name == "none"))
+ continue;
+
+ //kdDebug( 7007 ) << "device_name=" << device_name << endl;
+
+ // If the path contains symlinks, get
+ // the real name
+ if (realpath(device_name, realpath_buffer) != 0)
+ // succes, use result from realpath
+ device_name = realpath_buffer;
+
+ //kdDebug( 7007 ) << "device_name after realpath =" << device_name << endl;
+
+ if (realname == device_name)
+ {
+ result = MOUNTPOINT(me);
+ break;
+ }
+ }
+
+ ENDMNTENT(mtab);
+
+#endif /* GET_MNTINFO */
+#endif /* HAVE_VOLMGT */
+
+ //kdDebug( 7007 ) << "Returning result " << result << endl;
+ return result;
+}
+
+// Don't just trust the return value, keep iterating to check for a better match (bigger max)
+static bool is_my_mountpoint( const char *mountpoint, const char *realname, int &max )
+{
+ int length = strlen(mountpoint);
+
+ if (!strncmp(mountpoint, realname, length)
+ && length > max) {
+ max = length;
+ if (length == 1 || realname[length] == '/' || realname[length] == '\0')
+ return true;
+ }
+ return false;
+}
+
+typedef enum { Unseen, Right, Wrong } MountState;
+
+/**
+ * Idea and code base by Olaf Kirch <okir@caldera.de>
+ **/
+static void check_mount_point(const char *mounttype,
+ const char *fsname,
+ MountState &isslow, MountState &isautofs)
+{
+ bool nfs = !strcmp(mounttype, "nfs");
+ bool autofs = !strcmp(mounttype, "autofs") || !strcmp(mounttype,"subfs");
+ bool pid = (strstr(fsname, ":(pid") != 0);
+
+ if (nfs && !pid)
+ isslow = Right;
+ else if (isslow == Right)
+ isslow = Wrong;
+
+ /* Does this look like automounted? */
+ if (autofs || (nfs && pid)) {
+ isautofs = Right;
+ isslow = Right;
+ }
+}
+
+// returns the mount point, checks the mount state.
+// if ismanual == Wrong this function does not check the manual mount state
+static TQString get_mount_info(const TQString& filename,
+ MountState& isautofs, MountState& isslow, MountState& ismanual,
+ TQString& fstype)
+{
+ static bool gotRoot = false;
+ static dev_t rootDevice;
+
+ struct cachedDevice_t
+ {
+ dev_t device;
+ TQString mountPoint;
+ MountState isautofs;
+ MountState isslow;
+ MountState ismanual;
+ TQString fstype;
+ };
+ static struct cachedDevice_t *cachedDevice = 0;
+
+ if (!gotRoot)
+ {
+ KDE_struct_stat stat_buf;
+ KDE_stat("/", &stat_buf);
+ gotRoot = true;
+ rootDevice = stat_buf.st_dev;
+ }
+
+ bool gotDevice = false;
+ KDE_struct_stat stat_buf;
+ if (KDE_stat(TQFile::encodeName(filename), &stat_buf) == 0)
+ {
+ gotDevice = true;
+ if (stat_buf.st_dev == rootDevice)
+ {
+ static const TQString &root = TDEGlobal::staticQString("/");
+ isautofs = Wrong;
+ isslow = Wrong;
+ ismanual = Wrong;
+ fstype = TQString::null; // ### do we need it?
+ return root;
+ }
+ if (cachedDevice && (stat_buf.st_dev == cachedDevice->device))
+ {
+ bool interestedInIsManual = ismanual != Wrong;
+ isautofs = cachedDevice->isautofs;
+ isslow = cachedDevice->isslow;
+ ismanual = cachedDevice->ismanual;
+ fstype = cachedDevice->fstype;
+ // Don't use the cache if it doesn't have the information we're looking for
+ if ( !interestedInIsManual || ismanual != Unseen )
+ return cachedDevice->mountPoint;
+ }
+ }
+
+ char realname[MAXPATHLEN];
+
+ memset(realname, 0, MAXPATHLEN);
+
+ /* If the path contains symlinks, get the real name */
+ if (realpath(TQFile::encodeName(filename), realname) == 0) {
+ if( strlcpy(realname, TQFile::encodeName(filename), MAXPATHLEN)>=MAXPATHLEN)
+ return TQString::null;
+ }
+
+ int max = 0;
+ TQString mountPoint;
+
+ /* Loop over all file systems and see if we can find our
+ * mount point.
+ * Note that this is the mount point with the longest match.
+ * XXX: Fails if me->mnt_dir is not a realpath but goes
+ * through a symlink, e.g. /foo/bar where /foo is a symlink
+ * pointing to /local/foo.
+ *
+ * How kinky can you get with a filesystem?
+ */
+
+#ifdef HAVE_GETMNTINFO
+
+#ifdef GETMNTINFO_USES_STATVFS
+ struct statvfs *mounted;
+#else
+ struct statfs *mounted;
+#endif
+
+ char realpath_buffer[MAXPATHLEN];
+
+ int num_fs = getmntinfo(&mounted, MNT_NOWAIT);
+
+ for (int i=0;i<num_fs;i++) {
+
+ TQCString device_name = mounted[i].f_mntfromname;
+
+ // If the path contains symlinks, get
+ // the real name
+ if (realpath(device_name, realpath_buffer) != 0)
+ // succes, use result from realpath
+ device_name = realpath_buffer;
+#ifdef __osf__
+ char * mounttype = mnt_names[mounted[i].f_type];
+#else
+ char * mounttype = mounted[i].f_fstypename;
+#endif
+ if ( is_my_mountpoint( mounted[i].f_mntonname, realname, max ) )
+ {
+ mountPoint = TQFile::decodeName(mounted[i].f_mntonname);
+ fstype = TQString::fromLatin1(mounttype);
+ check_mount_point( mounttype, mounted[i].f_mntfromname,
+ isautofs, isslow );
+ // keep going, looking for a potentially better one
+
+ if (ismanual == Unseen)
+ {
+ struct fstab *ft = getfsfile(mounted[i].f_mntonname);
+ if (!ft || strstr(ft->fs_mntops, "noauto"))
+ ismanual = Right;
+ }
+ }
+ }
+
+#elif defined(_AIX)
+
+ struct vmount *mntctl_buffer;
+ struct vmount *vm;
+ char *mountedfrom;
+ char *mountedto;
+ int fsname_len, num;
+ char realpath_buffer[MAXPATHLEN];
+ int buf_sz = 4096;
+
+ mntctl_buffer = (struct vmount*)malloc(buf_sz);
+ num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
+ if (num == 0)
+ {
+ buf_sz = *(int*)mntctl_buffer;
+ free(mntctl_buffer);
+ mntctl_buffer = (struct vmount*)malloc(buf_sz);
+ num = mntctl(MCTL_QUERY, buf_sz, mntctl_buffer);
+ }
+
+ if (num > 0)
+ {
+ /* iterate through items in the vmount structure: */
+ vm = (struct vmount *)mntctl_buffer;
+ for ( ; num > 0; num-- )
+ {
+ /* get the name of the mounted file systems: */
+ fsname_len = vmt2datasize(vm, VMT_STUB);
+ mountedto = (char*)malloc(fsname_len + 1);
+ mountedto[fsname_len] = '\0';
+ strncpy(mountedto, (char *)vmt2dataptr(vm, VMT_STUB), fsname_len);
+
+ fsname_len = vmt2datasize(vm, VMT_OBJECT);
+ mountedfrom = (char*)malloc(fsname_len + 1);
+ mountedfrom[fsname_len] = '\0';
+ strncpy(mountedfrom, (char *)vmt2dataptr(vm, VMT_OBJECT), fsname_len);
+
+ /* get the mount-from information: */
+ TQCString device_name = mountedfrom;
+
+ if (realpath(device_name, realpath_buffer) != 0)
+ // success, use result from realpath
+ device_name = realpath_buffer;
+
+ /* Look up the string for the file system type,
+ * as listed in /etc/vfs.
+ * ex.: nfs,jfs,afs,cdrfs,sfs,cachefs,nfs3,autofs
+ */
+ struct vfs_ent* ent = getvfsbytype(vm->vmt_gfstype);
+
+ if ( is_my_mountpoint( mountedto, realname, max ) )
+ {
+ mountPoint = TQFile::decodeName(mountedto);
+ fstype = TQString::fromLatin1(ent->vfsent_name);
+ check_mount_point(ent->vfsent_name, device_name, isautofs, isslow);
+
+ if (ismanual == Unseen)
+ {
+ // TODO: add check for ismanual, I couldn't find any way
+ // how to get the mount attribute from /etc/filesystems
+ ismanual == Wrong;
+ }
+ }
+
+ free(mountedfrom);
+ free(mountedto);
+
+ /* goto the next vmount structure: */
+ vm = (struct vmount *)((char *)vm + vm->vmt_length);
+ }
+
+ endvfsent( );
+ }
+
+ free( mntctl_buffer );
+
+#else
+
+ STRUCT_SETMNTENT mtab;
+ /* Get the list of mounted file systems */
+
+ if ((mtab = SETMNTENT(MNTTAB, "r")) == 0) {
+ perror("setmntent");
+ return TQString::null;
+ }
+
+ STRUCT_MNTENT me;
+
+ while (true) {
+ if (!GETMNTENT(mtab, me))
+ break;
+
+ if ( is_my_mountpoint( MOUNTPOINT(me), realname, max ) )
+ {
+ mountPoint = TQFile::decodeName( MOUNTPOINT(me) );
+ fstype = MOUNTTYPE(me);
+ check_mount_point(MOUNTTYPE(me), FSNAME(me), isautofs, isslow);
+ // we don't check if ismanual is Right, if /a/b is manually
+ // mounted /a/b/c can't be automounted. At least IMO.
+ if (ismanual == Unseen)
+ {
+ // The next GETMNTENT call may destroy 'me'
+ // Copy out the info that we need
+ TQCString fsname_me = FSNAME(me);
+ TQCString mounttype_me = MOUNTTYPE(me);
+
+ STRUCT_SETMNTENT fstab;
+ if ((fstab = SETMNTENT(FSTAB, "r")) == 0) {
+ continue;
+ }
+
+ bool found = false;
+ STRUCT_MNTENT fe;
+ while (GETMNTENT(fstab, fe))
+ {
+ if (fsname_me == FSNAME(fe))
+ {
+ found = true;
+ if (HASMNTOPT(fe, "noauto") ||
+ !strcmp(MOUNTTYPE(fe), "supermount"))
+ ismanual = Right;
+ break;
+ }
+ }
+ if (!found || (mounttype_me == "supermount"))
+ ismanual = Right;
+
+ ENDMNTENT(fstab);
+ }
+ }
+ }
+
+ ENDMNTENT(mtab);
+
+#endif
+
+ if (isautofs == Right && isslow == Unseen)
+ isslow = Right;
+
+ if (gotDevice)
+ {
+ if (!cachedDevice)
+ cachedDevice = new cachedDevice_t;
+
+ cachedDevice->device = stat_buf.st_dev;
+ cachedDevice->mountPoint = mountPoint;
+ cachedDevice->isautofs = isautofs;
+ cachedDevice->isslow = isslow;
+ cachedDevice->ismanual = ismanual;
+ cachedDevice->fstype = fstype;
+ }
+
+ return mountPoint;
+}
+
+#else //!Q_OS_UNIX
+//dummy
+TQString TDEIO::findDeviceMountPoint( const TQString& filename )
+{
+ return TQString::null;
+}
+#endif
+
+TQString TDEIO::findPathMountPoint(const TQString& filename)
+{
+#ifdef Q_OS_UNIX
+ MountState isautofs = Unseen, isslow = Unseen, ismanual = Wrong;
+ TQString fstype;
+ return get_mount_info(filename, isautofs, isslow, ismanual, fstype);
+#else //!Q_OS_UNIX
+ return TQString::null;
+#endif
+}
+
+bool TDEIO::manually_mounted(const TQString& filename)
+{
+#ifdef Q_OS_UNIX
+ MountState isautofs = Unseen, isslow = Unseen, ismanual = Unseen;
+ TQString fstype;
+ TQString mountPoint = get_mount_info(filename, isautofs, isslow, ismanual, fstype);
+ return !mountPoint.isNull() && (ismanual == Right);
+#else //!Q_OS_UNIX
+ return false;
+#endif
+}
+
+bool TDEIO::probably_slow_mounted(const TQString& filename)
+{
+#ifdef Q_OS_UNIX
+ MountState isautofs = Unseen, isslow = Unseen, ismanual = Wrong;
+ TQString fstype;
+ TQString mountPoint = get_mount_info(filename, isautofs, isslow, ismanual, fstype);
+ return !mountPoint.isNull() && (isslow == Right);
+#else //!Q_OS_UNIX
+ return false;
+#endif
+}
+
+bool TDEIO::testFileSystemFlag(const TQString& filename, FileSystemFlag flag)
+{
+#ifdef Q_OS_UNIX
+ MountState isautofs = Unseen, isslow = Unseen, ismanual = Wrong;
+ TQString fstype;
+ TQString mountPoint = get_mount_info(filename, isautofs, isslow, ismanual, fstype);
+ kdDebug() << "testFileSystemFlag: fstype=" << fstype << endl;
+ if (mountPoint.isNull())
+ return false;
+ bool isMsDos = ( fstype == "msdos" || fstype == "fat" || fstype == "vfat" );
+ switch (flag) {
+ case SupportsChmod:
+ case SupportsChown:
+ case SupportsUTime:
+ case SupportsSymlinks:
+ return !isMsDos; // it's amazing the number of things FAT doesn't support :)
+ case CaseInsensitive:
+ return isMsDos;
+ }
+#endif
+ return false;
+}
+
+TDEIO::CacheControl TDEIO::parseCacheControl(const TQString &cacheControl)
+{
+ TQString tmp = cacheControl.lower();
+
+ if (tmp == "cacheonly")
+ return TDEIO::CC_CacheOnly;
+ if (tmp == "cache")
+ return TDEIO::CC_Cache;
+ if (tmp == "verify")
+ return TDEIO::CC_Verify;
+ if (tmp == "refresh")
+ return TDEIO::CC_Refresh;
+ if (tmp == "reload")
+ return TDEIO::CC_Reload;
+
+ kdDebug() << "unrecognized Cache control option:"<<cacheControl<<endl;
+ return TDEIO::CC_Verify;
+}
+
+TQString TDEIO::getCacheControlString(TDEIO::CacheControl cacheControl)
+{
+ if (cacheControl == TDEIO::CC_CacheOnly)
+ return "CacheOnly";
+ if (cacheControl == TDEIO::CC_Cache)
+ return "Cache";
+ if (cacheControl == TDEIO::CC_Verify)
+ return "Verify";
+ if (cacheControl == TDEIO::CC_Refresh)
+ return "Refresh";
+ if (cacheControl == TDEIO::CC_Reload)
+ return "Reload";
+ kdDebug() << "unrecognized Cache control enum value:"<<cacheControl<<endl;
+ return TQString::null;
+}
diff --git a/kio/kio/global.h b/tdeio/tdeio/global.h
index 44b9df616..44b9df616 100644
--- a/kio/kio/global.h
+++ b/tdeio/tdeio/global.h
diff --git a/kio/kio/http_slave_defaults.h b/tdeio/tdeio/http_slave_defaults.h
index e3247e39b..e3247e39b 100644
--- a/kio/kio/http_slave_defaults.h
+++ b/tdeio/tdeio/http_slave_defaults.h
diff --git a/kio/kio/ioslave_defaults.h b/tdeio/tdeio/ioslave_defaults.h
index ddf5b6af5..ddf5b6af5 100644
--- a/kio/kio/ioslave_defaults.h
+++ b/tdeio/tdeio/ioslave_defaults.h
diff --git a/tdeio/tdeio/job.cpp b/tdeio/tdeio/job.cpp
new file mode 100644
index 000000000..7bea676c5
--- /dev/null
+++ b/tdeio/tdeio/job.cpp
@@ -0,0 +1,4814 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ David Faure <faure@kde.org>
+ Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdeio/job.h"
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <time.h>
+#include <unistd.h>
+extern "C" {
+#include <pwd.h>
+#include <grp.h>
+}
+#include <tqtimer.h>
+#include <tqfile.h>
+
+#include <kapplication.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <ksimpleconfig.h>
+#include <kdebug.h>
+#include <kdialog.h>
+#include <kmessagebox.h>
+#include <kdatastream.h>
+#include <kmainwindow.h>
+#include <kde_file.h>
+
+#include <errno.h>
+
+#include "kmimetype.h"
+#include "slave.h"
+#include "scheduler.h"
+#include "kdirwatch.h"
+#include "kmimemagic.h"
+#include "kprotocolinfo.h"
+#include "kprotocolmanager.h"
+
+#include "tdeio/observer.h"
+
+#include "kssl/ksslcsessioncache.h"
+
+#include <kdirnotify_stub.h>
+#include <ktempfile.h>
+#include <dcopclient.h>
+
+#ifdef Q_OS_UNIX
+#include <utime.h>
+#endif
+#if defined Q_WS_X11
+#include <netwm.h>
+#include <fixx11h.h>
+#endif
+
+using namespace TDEIO;
+template class TQPtrList<TDEIO::Job>;
+
+//this will update the report dialog with 5 Hz, I think this is fast enough, aleXXX
+#define REPORT_TIMEOUT 200
+
+#define KIO_ARGS TQByteArray packedArgs; TQDataStream stream( packedArgs, IO_WriteOnly ); stream
+
+class Job::JobPrivate
+{
+public:
+ JobPrivate() : m_autoErrorHandling( false ), m_autoWarningHandling( true ),
+ m_interactive( true ), m_parentJob( 0L ), m_extraFlags(0),
+ m_processedSize(0), m_userTimestamp(0)
+ {}
+
+ bool m_autoErrorHandling;
+ bool m_autoWarningHandling;
+ bool m_interactive;
+ TQGuardedPtr<TQWidget> m_errorParentWidget;
+ // Maybe we could use the TQObject parent/child mechanism instead
+ // (requires a new ctor, and moving the ctor code to some init()).
+ Job* m_parentJob;
+ int m_extraFlags;
+ TDEIO::filesize_t m_processedSize;
+ unsigned long m_userTimestamp;
+};
+
+Job::Job(bool showProgressInfo) : TQObject(0, "job"), m_error(0), m_percent(0)
+ , m_progressId(0), m_speedTimer(0), d( new JobPrivate )
+{
+ // All jobs delete themselves after emiting 'result'.
+
+ // Notify the UI Server and get a progress id
+ if ( showProgressInfo )
+ {
+ m_progressId = Observer::self()->newJob( this, true );
+ addMetaData("progress-id", TQString::number(m_progressId));
+ //kdDebug(7007) << "Created job " << this << " with progress info -- m_progressId=" << m_progressId << endl;
+ // Connect global progress info signals
+ connect( this, TQT_SIGNAL( percent( TDEIO::Job*, unsigned long ) ),
+ Observer::self(), TQT_SLOT( slotPercent( TDEIO::Job*, unsigned long ) ) );
+ connect( this, TQT_SIGNAL( infoMessage( TDEIO::Job*, const TQString & ) ),
+ Observer::self(), TQT_SLOT( slotInfoMessage( TDEIO::Job*, const TQString & ) ) );
+ connect( this, TQT_SIGNAL( totalSize( TDEIO::Job*, TDEIO::filesize_t ) ),
+ Observer::self(), TQT_SLOT( slotTotalSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
+ connect( this, TQT_SIGNAL( processedSize( TDEIO::Job*, TDEIO::filesize_t ) ),
+ Observer::self(), TQT_SLOT( slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
+ connect( this, TQT_SIGNAL( speed( TDEIO::Job*, unsigned long ) ),
+ Observer::self(), TQT_SLOT( slotSpeed( TDEIO::Job*, unsigned long ) ) );
+ }
+ // Don't exit while this job is running
+ if (kapp)
+ kapp->ref();
+ if (kapp)
+ updateUserTimestamp( kapp->userTimestamp());
+}
+
+Job::~Job()
+{
+ delete m_speedTimer;
+ delete d;
+ if (kapp)
+ kapp->deref();
+}
+
+int& Job::extraFlags()
+{
+ return d->m_extraFlags;
+}
+
+void Job::setProcessedSize(TDEIO::filesize_t size)
+{
+ d->m_processedSize = size;
+}
+
+TDEIO::filesize_t Job::getProcessedSize()
+{
+ return d->m_processedSize;
+}
+
+void Job::addSubjob(Job *job, bool inheritMetaData)
+{
+ //kdDebug(7007) << "addSubjob(" << job << ") this = " << this << endl;
+ subjobs.append(job);
+
+ connect( job, TQT_SIGNAL(result(TDEIO::Job*)),
+ TQT_SLOT(slotResult(TDEIO::Job*)) );
+
+ // Forward information from that subjob.
+ connect( job, TQT_SIGNAL(speed( TDEIO::Job*, unsigned long )),
+ TQT_SLOT(slotSpeed(TDEIO::Job*, unsigned long)) );
+
+ connect( job, TQT_SIGNAL(infoMessage( TDEIO::Job*, const TQString & )),
+ TQT_SLOT(slotInfoMessage(TDEIO::Job*, const TQString &)) );
+
+ if (inheritMetaData)
+ job->mergeMetaData(m_outgoingMetaData);
+
+ job->setWindow( m_window );
+ job->updateUserTimestamp( d->m_userTimestamp );
+}
+
+void Job::removeSubjob( Job *job )
+{
+ removeSubjob( job, false, true );
+}
+
+void Job::removeSubjob( Job *job, bool mergeMetaData, bool emitResultIfLast )
+{
+ //kdDebug(7007) << "removeSubjob(" << job << ") this = " << this << " subjobs = " << subjobs.count() << endl;
+ // Merge metadata from subjob
+ if ( mergeMetaData )
+ m_incomingMetaData += job->metaData();
+ subjobs.remove(job);
+ if ( subjobs.isEmpty() && emitResultIfLast )
+ emitResult();
+}
+
+void Job::emitPercent( TDEIO::filesize_t processedSize, TDEIO::filesize_t totalSize )
+{
+ // calculate percents
+ unsigned long ipercent = m_percent;
+
+ if ( totalSize == 0 )
+ m_percent = 100;
+ else
+ m_percent = (unsigned long)(( (float)(processedSize) / (float)(totalSize) ) * 100.0);
+
+ if ( m_percent != ipercent || m_percent == 100 /* for those buggy total sizes that grow */ ) {
+ emit percent( this, m_percent );
+ //kdDebug(7007) << "Job::emitPercent - percent = " << (unsigned int) m_percent << endl;
+ }
+}
+
+void Job::emitSpeed( unsigned long bytes_per_second )
+{
+ //kdDebug(7007) << "Job " << this << " emitSpeed " << bytes_per_second << endl;
+ if ( !m_speedTimer )
+ {
+ m_speedTimer = new TQTimer();
+ connect( m_speedTimer, TQT_SIGNAL( timeout() ), TQT_SLOT( slotSpeedTimeout() ) );
+ }
+ emit speed( this, bytes_per_second );
+ m_speedTimer->start( 5000 ); // 5 seconds interval should be enough
+}
+
+void Job::emitResult()
+{
+ // If we are displaying a progress dialog, remove it first.
+ if ( m_progressId ) // Did we get an ID from the observer ?
+ Observer::self()->jobFinished( m_progressId );
+ if ( m_error && d->m_interactive && d->m_autoErrorHandling )
+ showErrorDialog( d->m_errorParentWidget );
+ emit result(this);
+ deleteLater();
+}
+
+void Job::kill( bool quietly )
+{
+ kdDebug(7007) << "Job::kill this=" << this << " " << className() << " m_progressId=" << m_progressId << " quietly=" << quietly << endl;
+ // kill all subjobs, without triggering their result slot
+ TQPtrListIterator<Job> it( subjobs );
+ for ( ; it.current() ; ++it )
+ (*it)->kill( true );
+ subjobs.clear();
+
+ if ( ! quietly ) {
+ m_error = ERR_USER_CANCELED;
+ emit canceled( this ); // Not very useful (deprecated)
+ emitResult();
+ } else
+ {
+ if ( m_progressId ) // in both cases we want to hide the progress window
+ Observer::self()->jobFinished( m_progressId );
+ deleteLater();
+ }
+}
+
+void Job::slotResult( Job *job )
+{
+ // Did job have an error ?
+ if ( job->error() && !m_error )
+ {
+ // Store it in the parent only if first error
+ m_error = job->error();
+ m_errorText = job->errorText();
+ }
+ removeSubjob(job);
+}
+
+void Job::slotSpeed( TDEIO::Job*, unsigned long speed )
+{
+ //kdDebug(7007) << "Job::slotSpeed " << speed << endl;
+ emitSpeed( speed );
+}
+
+void Job::slotInfoMessage( TDEIO::Job*, const TQString & msg )
+{
+ emit infoMessage( this, msg );
+}
+
+void Job::slotSpeedTimeout()
+{
+ //kdDebug(7007) << "slotSpeedTimeout()" << endl;
+ // send 0 and stop the timer
+ // timer will be restarted only when we receive another speed event
+ emit speed( this, 0 );
+ m_speedTimer->stop();
+}
+
+//Job::errorString is implemented in global.cpp
+
+void Job::showErrorDialog( TQWidget * parent )
+{
+ //kdDebug(7007) << "Job::showErrorDialog parent=" << parent << endl;
+ kapp->enableStyles();
+ // Show a message box, except for "user canceled" or "no content"
+ if ( (m_error != ERR_USER_CANCELED) && (m_error != ERR_NO_CONTENT) ) {
+ //old plain error message
+ //kdDebug(7007) << "Default language: " << TDEGlobal::locale()->defaultLanguage() << endl;
+ if ( 1 )
+ KMessageBox::queuedMessageBox( parent, KMessageBox::Error, errorString() );
+#if 0
+ } else {
+ TQStringList errors = detailedErrorStrings();
+ TQString caption, err, detail;
+ TQStringList::const_iterator it = errors.begin();
+ if ( it != errors.end() )
+ caption = *(it++);
+ if ( it != errors.end() )
+ err = *(it++);
+ if ( it != errors.end() )
+ detail = *it;
+ KMessageBox::queuedDetailedError( parent, err, detail, caption );
+ }
+#endif
+ }
+}
+
+void Job::setAutoErrorHandlingEnabled( bool enable, TQWidget *parentWidget )
+{
+ d->m_autoErrorHandling = enable;
+ d->m_errorParentWidget = parentWidget;
+}
+
+bool Job::isAutoErrorHandlingEnabled() const
+{
+ return d->m_autoErrorHandling;
+}
+
+void Job::setAutoWarningHandlingEnabled( bool enable )
+{
+ d->m_autoWarningHandling = enable;
+}
+
+bool Job::isAutoWarningHandlingEnabled() const
+{
+ return d->m_autoWarningHandling;
+}
+
+void Job::setInteractive(bool enable)
+{
+ d->m_interactive = enable;
+}
+
+bool Job::isInteractive() const
+{
+ return d->m_interactive;
+}
+
+void Job::setWindow(TQWidget *window)
+{
+ m_window = window;
+ TDEIO::Scheduler::registerWindow(window);
+}
+
+TQWidget *Job::window() const
+{
+ return m_window;
+}
+
+void Job::updateUserTimestamp( unsigned long time )
+{
+#if defined Q_WS_X11
+ if( d->m_userTimestamp == 0 || NET::timestampCompare( time, d->m_userTimestamp ) > 0 )
+ d->m_userTimestamp = time;
+#endif
+}
+
+unsigned long Job::userTimestamp() const
+{
+ return d->m_userTimestamp;
+}
+
+void Job::setParentJob(Job* job)
+{
+ Q_ASSERT(d->m_parentJob == 0L);
+ Q_ASSERT(job);
+ d->m_parentJob = job;
+}
+
+Job* Job::parentJob() const
+{
+ return d->m_parentJob;
+}
+
+MetaData Job::metaData() const
+{
+ return m_incomingMetaData;
+}
+
+TQString Job::queryMetaData(const TQString &key)
+{
+ if (!m_incomingMetaData.contains(key))
+ return TQString::null;
+ return m_incomingMetaData[key];
+}
+
+void Job::setMetaData( const TDEIO::MetaData &_metaData)
+{
+ m_outgoingMetaData = _metaData;
+}
+
+void Job::addMetaData( const TQString &key, const TQString &value)
+{
+ m_outgoingMetaData.insert(key, value);
+}
+
+void Job::addMetaData( const TQMap<TQString,TQString> &values)
+{
+ TQMapConstIterator<TQString,TQString> it = values.begin();
+ for(;it != values.end(); ++it)
+ m_outgoingMetaData.insert(it.key(), it.data());
+}
+
+void Job::mergeMetaData( const TQMap<TQString,TQString> &values)
+{
+ TQMapConstIterator<TQString,TQString> it = values.begin();
+ for(;it != values.end(); ++it)
+ m_outgoingMetaData.insert(it.key(), it.data(), false);
+}
+
+MetaData Job::outgoingMetaData() const
+{
+ return m_outgoingMetaData;
+}
+
+
+SimpleJob::SimpleJob(const KURL& url, int command, const TQByteArray &packedArgs,
+ bool showProgressInfo )
+ : Job(showProgressInfo), m_slave(0), m_packedArgs(packedArgs),
+ m_url(url), m_command(command), m_totalSize(0)
+{
+ if (m_url.hasSubURL())
+ {
+ KURL::List list = KURL::split(m_url);
+ KURL::List::Iterator it = list.fromLast();
+ list.remove(it);
+ m_subUrl = KURL::join(list);
+ //kdDebug(7007) << "New URL = " << m_url.url() << endl;
+ //kdDebug(7007) << "Sub URL = " << m_subUrl.url() << endl;
+ }
+
+ Scheduler::doJob(this);
+
+ if (!m_url.isValid())
+ {
+ kdDebug() << "ERR_MALFORMED_URL" << endl;
+ m_error = ERR_MALFORMED_URL;
+ m_errorText = m_url.url();
+ TQTimer::singleShot(0, this, TQT_SLOT(slotFinished()) );
+ return;
+ }
+}
+
+void SimpleJob::kill( bool quietly )
+{
+ Scheduler::cancelJob( this ); // deletes the slave if not 0
+ m_slave = 0; // -> set to 0
+ Job::kill( quietly );
+}
+
+void SimpleJob::putOnHold()
+{
+ Q_ASSERT( m_slave );
+ if ( m_slave )
+ {
+ Scheduler::putSlaveOnHold(this, m_url);
+ m_slave = 0;
+ }
+ kill(true);
+}
+
+void SimpleJob::removeOnHold()
+{
+ Scheduler::removeSlaveOnHold();
+}
+
+SimpleJob::~SimpleJob()
+{
+ if (m_slave) // was running
+ {
+ kdDebug(7007) << "SimpleJob::~SimpleJob: Killing running job in destructor!" << endl;
+#if 0
+ m_slave->kill();
+ Scheduler::jobFinished( this, m_slave ); // deletes the slave
+#endif
+ Scheduler::cancelJob( this );
+ m_slave = 0; // -> set to 0
+ }
+}
+
+void SimpleJob::start(Slave *slave)
+{
+ m_slave = slave;
+
+ connect( m_slave, TQT_SIGNAL( error( int , const TQString & ) ),
+ TQT_SLOT( slotError( int , const TQString & ) ) );
+
+ connect( m_slave, TQT_SIGNAL( warning( const TQString & ) ),
+ TQT_SLOT( slotWarning( const TQString & ) ) );
+
+ connect( m_slave, TQT_SIGNAL( infoMessage( const TQString & ) ),
+ TQT_SLOT( slotInfoMessage( const TQString & ) ) );
+
+ connect( m_slave, TQT_SIGNAL( connected() ),
+ TQT_SLOT( slotConnected() ) );
+
+ connect( m_slave, TQT_SIGNAL( finished() ),
+ TQT_SLOT( slotFinished() ) );
+
+ if ((extraFlags() & EF_TransferJobDataSent) == 0)
+ {
+ connect( m_slave, TQT_SIGNAL( totalSize( TDEIO::filesize_t ) ),
+ TQT_SLOT( slotTotalSize( TDEIO::filesize_t ) ) );
+
+ connect( m_slave, TQT_SIGNAL( processedSize( TDEIO::filesize_t ) ),
+ TQT_SLOT( slotProcessedSize( TDEIO::filesize_t ) ) );
+
+ connect( m_slave, TQT_SIGNAL( speed( unsigned long ) ),
+ TQT_SLOT( slotSpeed( unsigned long ) ) );
+ }
+
+ connect( slave, TQT_SIGNAL( needProgressId() ),
+ TQT_SLOT( slotNeedProgressId() ) );
+
+ connect( slave, TQT_SIGNAL(metaData( const TDEIO::MetaData& ) ),
+ TQT_SLOT( slotMetaData( const TDEIO::MetaData& ) ) );
+
+ if (m_window)
+ {
+ TQString id;
+ addMetaData("window-id", id.setNum((ulong)m_window->winId()));
+ }
+ if (userTimestamp())
+ {
+ TQString id;
+ addMetaData("user-timestamp", id.setNum(userTimestamp()));
+ }
+
+ TQString sslSession = KSSLCSessionCache::getSessionForURL(m_url);
+ if ( !sslSession.isNull() )
+ {
+ addMetaData("ssl_session_id", sslSession);
+ }
+
+ if (!isInteractive())
+ {
+ addMetaData("no-auth-prompt", "true");
+ }
+
+ if (!m_outgoingMetaData.isEmpty())
+ {
+ KIO_ARGS << m_outgoingMetaData;
+ slave->send( CMD_META_DATA, packedArgs );
+ }
+
+ if (!m_subUrl.isEmpty())
+ {
+ KIO_ARGS << m_subUrl;
+ m_slave->send( CMD_SUBURL, packedArgs );
+ }
+
+ m_slave->send( m_command, m_packedArgs );
+}
+
+void SimpleJob::slaveDone()
+{
+ if (!m_slave) return;
+ disconnect(m_slave); // Remove all signals between slave and job
+ Scheduler::jobFinished( this, m_slave );
+ m_slave = 0;
+}
+
+void SimpleJob::slotFinished( )
+{
+ // Return slave to the scheduler
+ slaveDone();
+
+ if (subjobs.isEmpty())
+ {
+ if ( !m_error && (m_command == CMD_MKDIR || m_command == CMD_RENAME ) )
+ {
+ KDirNotify_stub allDirNotify( "*", "KDirNotify*" );
+ if ( m_command == CMD_MKDIR )
+ {
+ KURL urlDir( url() );
+ urlDir.setPath( urlDir.directory() );
+ allDirNotify.FilesAdded( urlDir );
+ }
+ else /*if ( m_command == CMD_RENAME )*/
+ {
+ KURL src, dst;
+ TQDataStream str( m_packedArgs, IO_ReadOnly );
+ str >> src >> dst;
+ if ( src.directory() == dst.directory() ) // For the user, moving isn't renaming. Only renaming is.
+ allDirNotify.FileRenamed( src, dst );
+ }
+ }
+ emitResult();
+ }
+}
+
+void SimpleJob::slotError( int error, const TQString & errorText )
+{
+ m_error = error;
+ m_errorText = errorText;
+ if ((m_error == ERR_UNKNOWN_HOST) && m_url.host().isEmpty())
+ m_errorText = TQString::null;
+ // error terminates the job
+ slotFinished();
+}
+
+void SimpleJob::slotWarning( const TQString & errorText )
+{
+ TQGuardedPtr<SimpleJob> guard( this );
+ if (isInteractive() && isAutoWarningHandlingEnabled())
+ {
+ static uint msgBoxDisplayed = 0;
+ if ( msgBoxDisplayed == 0 ) // don't bomb the user with message boxes, only one at a time
+ {
+ msgBoxDisplayed++;
+ KMessageBox::information( 0L, errorText );
+ msgBoxDisplayed--;
+ }
+ // otherwise just discard it.
+ }
+
+ if ( !guard.isNull() )
+ emit warning( this, errorText );
+}
+
+void SimpleJob::slotInfoMessage( const TQString & msg )
+{
+ emit infoMessage( this, msg );
+}
+
+void SimpleJob::slotConnected()
+{
+ emit connected( this );
+}
+
+void SimpleJob::slotNeedProgressId()
+{
+ if ( !m_progressId )
+ m_progressId = Observer::self()->newJob( this, false );
+ m_slave->setProgressId( m_progressId );
+}
+
+void SimpleJob::slotTotalSize( TDEIO::filesize_t size )
+{
+ if (size > m_totalSize)
+ {
+ m_totalSize = size;
+ emit totalSize( this, size );
+ }
+}
+
+void SimpleJob::slotProcessedSize( TDEIO::filesize_t size )
+{
+ //kdDebug(7007) << "SimpleJob::slotProcessedSize " << TDEIO::number(size) << endl;
+ setProcessedSize(size);
+ emit processedSize( this, size );
+ if ( size > m_totalSize ) {
+ slotTotalSize(size); // safety
+ }
+ emitPercent( size, m_totalSize );
+}
+
+void SimpleJob::slotSpeed( unsigned long speed )
+{
+ //kdDebug(7007) << "SimpleJob::slotSpeed( " << speed << " )" << endl;
+ emitSpeed( speed );
+}
+
+void SimpleJob::slotMetaData( const TDEIO::MetaData &_metaData)
+{
+ m_incomingMetaData += _metaData;
+}
+
+void SimpleJob::storeSSLSessionFromJob(const KURL &m_redirectionURL) {
+ TQString sslSession = queryMetaData("ssl_session_id");
+
+ if ( !sslSession.isNull() ) {
+ const KURL &queryURL = m_redirectionURL.isEmpty()?m_url:m_redirectionURL;
+ KSSLCSessionCache::putSessionForURL(queryURL, sslSession);
+ }
+}
+
+//////////
+MkdirJob::MkdirJob( const KURL& url, int command,
+ const TQByteArray &packedArgs, bool showProgressInfo )
+ : SimpleJob(url, command, packedArgs, showProgressInfo)
+{
+}
+
+void MkdirJob::start(Slave *slave)
+{
+ connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
+ TQT_SLOT( slotRedirection(const KURL &) ) );
+
+ SimpleJob::start(slave);
+}
+
+// Slave got a redirection request
+void MkdirJob::slotRedirection( const KURL &url)
+{
+ kdDebug(7007) << "MkdirJob::slotRedirection(" << url << ")" << endl;
+ if (!kapp->authorizeURLAction("redirect", m_url, url))
+ {
+ kdWarning(7007) << "MkdirJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
+ m_error = ERR_ACCESS_DENIED;
+ m_errorText = url.prettyURL();
+ return;
+ }
+ m_redirectionURL = url; // We'll remember that when the job finishes
+ if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
+ m_redirectionURL.setUser(m_url.user()); // Preserve user
+ // Tell the user that we haven't finished yet
+ emit redirection(this, m_redirectionURL);
+}
+
+void MkdirJob::slotFinished()
+{
+ if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
+ {
+ // Return slave to the scheduler
+ SimpleJob::slotFinished();
+ } else {
+ //kdDebug(7007) << "MkdirJob: Redirection to " << m_redirectionURL << endl;
+ if (queryMetaData("permanent-redirect")=="true")
+ emit permanentRedirection(this, m_url, m_redirectionURL);
+ KURL dummyUrl;
+ int permissions;
+ TQDataStream istream( m_packedArgs, IO_ReadOnly );
+ istream >> dummyUrl >> permissions;
+
+ m_url = m_redirectionURL;
+ m_redirectionURL = KURL();
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << m_url << permissions;
+
+ // Return slave to the scheduler
+ slaveDone();
+ Scheduler::doJob(this);
+ }
+}
+
+SimpleJob *TDEIO::mkdir( const KURL& url, int permissions )
+{
+ //kdDebug(7007) << "mkdir " << url << endl;
+ KIO_ARGS << url << permissions;
+ return new MkdirJob(url, CMD_MKDIR, packedArgs, false);
+}
+
+SimpleJob *TDEIO::rmdir( const KURL& url )
+{
+ //kdDebug(7007) << "rmdir " << url << endl;
+ KIO_ARGS << url << TQ_INT8(false); // isFile is false
+ return new SimpleJob(url, CMD_DEL, packedArgs, false);
+}
+
+SimpleJob *TDEIO::chmod( const KURL& url, int permissions )
+{
+ //kdDebug(7007) << "chmod " << url << endl;
+ KIO_ARGS << url << permissions;
+ return new SimpleJob(url, CMD_CHMOD, packedArgs, false);
+}
+
+SimpleJob *TDEIO::rename( const KURL& src, const KURL & dest, bool overwrite )
+{
+ //kdDebug(7007) << "rename " << src << " " << dest << endl;
+ KIO_ARGS << src << dest << (TQ_INT8) overwrite;
+ return new SimpleJob(src, CMD_RENAME, packedArgs, false);
+}
+
+SimpleJob *TDEIO::symlink( const TQString& target, const KURL & dest, bool overwrite, bool showProgressInfo )
+{
+ //kdDebug(7007) << "symlink target=" << target << " " << dest << endl;
+ KIO_ARGS << target << dest << (TQ_INT8) overwrite;
+ return new SimpleJob(dest, CMD_SYMLINK, packedArgs, showProgressInfo);
+}
+
+SimpleJob *TDEIO::special(const KURL& url, const TQByteArray & data, bool showProgressInfo)
+{
+ //kdDebug(7007) << "special " << url << endl;
+ return new SimpleJob(url, CMD_SPECIAL, data, showProgressInfo);
+}
+
+SimpleJob *TDEIO::mount( bool ro, const char *fstype, const TQString& dev, const TQString& point, bool showProgressInfo )
+{
+ KIO_ARGS << int(1) << TQ_INT8( ro ? 1 : 0 )
+ << TQString::fromLatin1(fstype) << dev << point;
+ SimpleJob *job = special( KURL("file:/"), packedArgs, showProgressInfo );
+ if ( showProgressInfo )
+ Observer::self()->mounting( job, dev, point );
+ return job;
+}
+
+SimpleJob *TDEIO::unmount( const TQString& point, bool showProgressInfo )
+{
+ KIO_ARGS << int(2) << point;
+ SimpleJob *job = special( KURL("file:/"), packedArgs, showProgressInfo );
+ if ( showProgressInfo )
+ Observer::self()->unmounting( job, point );
+ return job;
+}
+
+//////////
+LocalURLJob::LocalURLJob( const KURL& url, int command,
+ const TQByteArray &packedArgs, bool showProgressInfo )
+ : SimpleJob(url, command, packedArgs, showProgressInfo)
+{
+
+}
+
+void LocalURLJob::start(Slave *slave)
+{
+ connect( slave, TQT_SIGNAL( localURL(const KURL &, bool) ),
+ TQT_SLOT( slotLocalURL(const KURL &, bool) ) );
+
+ SimpleJob::start(slave);
+}
+
+// Slave sent a response!
+void LocalURLJob::slotLocalURL(const KURL &url, bool isLocal)
+{
+ kdDebug(7007) << "LocalURLJob::slotLocalURL(" << url << ")" << endl;
+ emit localURL(this, url, isLocal);
+}
+
+void LocalURLJob::slotFinished()
+{
+ // Return slave to the scheduler
+ SimpleJob::slotFinished();
+}
+
+LocalURLJob *TDEIO::localURL( const KURL& remoteUrl )
+{
+ KIO_ARGS << remoteUrl;
+ return new LocalURLJob(remoteUrl, CMD_LOCALURL, packedArgs, false);
+}
+
+
+//////////
+
+StatJob::StatJob( const KURL& url, int command,
+ const TQByteArray &packedArgs, bool showProgressInfo )
+ : SimpleJob(url, command, packedArgs, showProgressInfo),
+ m_bSource(true), m_details(2)
+{
+}
+
+void StatJob::start(Slave *slave)
+{
+ m_outgoingMetaData.replace( "statSide", m_bSource ? "source" : "dest" );
+ m_outgoingMetaData.replace( "details", TQString::number(m_details) );
+
+ connect( slave, TQT_SIGNAL( statEntry( const TDEIO::UDSEntry& ) ),
+ TQT_SLOT( slotStatEntry( const TDEIO::UDSEntry & ) ) );
+ connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
+ TQT_SLOT( slotRedirection(const KURL &) ) );
+
+ SimpleJob::start(slave);
+}
+
+void StatJob::slotStatEntry( const TDEIO::UDSEntry & entry )
+{
+ //kdDebug(7007) << "StatJob::slotStatEntry" << endl;
+ m_statResult = entry;
+}
+
+// Slave got a redirection request
+void StatJob::slotRedirection( const KURL &url)
+{
+ kdDebug(7007) << "StatJob::slotRedirection(" << url << ")" << endl;
+ if (!kapp->authorizeURLAction("redirect", m_url, url))
+ {
+ kdWarning(7007) << "StatJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
+ m_error = ERR_ACCESS_DENIED;
+ m_errorText = url.prettyURL();
+ return;
+ }
+ m_redirectionURL = url; // We'll remember that when the job finishes
+ if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
+ m_redirectionURL.setUser(m_url.user()); // Preserve user
+ // Tell the user that we haven't finished yet
+ emit redirection(this, m_redirectionURL);
+}
+
+void StatJob::slotFinished()
+{
+ if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
+ {
+ // Return slave to the scheduler
+ SimpleJob::slotFinished();
+ } else {
+ //kdDebug(7007) << "StatJob: Redirection to " << m_redirectionURL << endl;
+ if (queryMetaData("permanent-redirect")=="true")
+ emit permanentRedirection(this, m_url, m_redirectionURL);
+ m_url = m_redirectionURL;
+ m_redirectionURL = KURL();
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << m_url;
+
+ // Return slave to the scheduler
+ slaveDone();
+ Scheduler::doJob(this);
+ }
+}
+
+void StatJob::slotMetaData( const TDEIO::MetaData &_metaData) {
+ SimpleJob::slotMetaData(_metaData);
+ storeSSLSessionFromJob(m_redirectionURL);
+}
+
+StatJob *TDEIO::stat(const KURL& url, bool showProgressInfo)
+{
+ // Assume sideIsSource. Gets are more common than puts.
+ return stat( url, true, 2, showProgressInfo );
+}
+
+StatJob *TDEIO::stat(const KURL& url, bool sideIsSource, short int details, bool showProgressInfo)
+{
+ kdDebug(7007) << "stat " << url << endl;
+ KIO_ARGS << url;
+ StatJob * job = new StatJob(url, CMD_STAT, packedArgs, showProgressInfo );
+ job->setSide( sideIsSource );
+ job->setDetails( details );
+ if ( showProgressInfo )
+ Observer::self()->stating( job, url );
+ return job;
+}
+
+SimpleJob *TDEIO::http_update_cache( const KURL& url, bool no_cache, time_t expireDate)
+{
+ assert( (url.protocol() == "http") || (url.protocol() == "https") );
+ // Send http update_cache command (2)
+ KIO_ARGS << (int)2 << url << no_cache << expireDate;
+ SimpleJob * job = new SimpleJob( url, CMD_SPECIAL, packedArgs, false );
+ Scheduler::scheduleJob(job);
+ return job;
+}
+
+//////////
+
+TransferJob::TransferJob( const KURL& url, int command,
+ const TQByteArray &packedArgs,
+ const TQByteArray &_staticData,
+ bool showProgressInfo)
+ : SimpleJob(url, command, packedArgs, showProgressInfo), staticData( _staticData)
+{
+ m_suspended = false;
+ m_errorPage = false;
+ m_subJob = 0L;
+ if ( showProgressInfo )
+ Observer::self()->slotTransferring( this, url );
+}
+
+// Slave sends data
+void TransferJob::slotData( const TQByteArray &_data)
+{
+ if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error)
+ emit data( this, _data);
+}
+
+// Slave got a redirection request
+void TransferJob::slotRedirection( const KURL &url)
+{
+ kdDebug(7007) << "TransferJob::slotRedirection(" << url << ")" << endl;
+ if (!kapp->authorizeURLAction("redirect", m_url, url))
+ {
+ kdWarning(7007) << "TransferJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
+ return;
+ }
+
+ // Some websites keep redirecting to themselves where each redirection
+ // acts as the stage in a state-machine. We define "endless redirections"
+ // as 5 redirections to the same URL.
+ if (m_redirectionList.contains(url) > 5)
+ {
+ kdDebug(7007) << "TransferJob::slotRedirection: CYCLIC REDIRECTION!" << endl;
+ m_error = ERR_CYCLIC_LINK;
+ m_errorText = m_url.prettyURL();
+ }
+ else
+ {
+ m_redirectionURL = url; // We'll remember that when the job finishes
+ if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
+ m_redirectionURL.setUser(m_url.user()); // Preserve user
+ m_redirectionList.append(url);
+ m_outgoingMetaData["ssl_was_in_use"] = m_incomingMetaData["ssl_in_use"];
+ // Tell the user that we haven't finished yet
+ emit redirection(this, m_redirectionURL);
+ }
+}
+
+void TransferJob::slotFinished()
+{
+ //kdDebug(7007) << "TransferJob::slotFinished(" << this << ", " << m_url << ")" << endl;
+ if (m_redirectionURL.isEmpty() || !m_redirectionURL.isValid())
+ SimpleJob::slotFinished();
+ else {
+ //kdDebug(7007) << "TransferJob: Redirection to " << m_redirectionURL << endl;
+ if (queryMetaData("permanent-redirect")=="true")
+ emit permanentRedirection(this, m_url, m_redirectionURL);
+ // Honour the redirection
+ // We take the approach of "redirecting this same job"
+ // Another solution would be to create a subjob, but the same problem
+ // happens (unpacking+repacking)
+ staticData.truncate(0);
+ m_incomingMetaData.clear();
+ if (queryMetaData("cache") != "reload")
+ addMetaData("cache","refresh");
+ m_suspended = false;
+ m_url = m_redirectionURL;
+ m_redirectionURL = KURL();
+ // The very tricky part is the packed arguments business
+ TQString dummyStr;
+ KURL dummyUrl;
+ TQDataStream istream( m_packedArgs, IO_ReadOnly );
+ switch( m_command ) {
+ case CMD_GET: {
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << m_url;
+ break;
+ }
+ case CMD_PUT: {
+ int permissions;
+ TQ_INT8 iOverwrite, iResume;
+ istream >> dummyUrl >> iOverwrite >> iResume >> permissions;
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << m_url << iOverwrite << iResume << permissions;
+ break;
+ }
+ case CMD_SPECIAL: {
+ int specialcmd;
+ istream >> specialcmd;
+ if (specialcmd == 1) // HTTP POST
+ {
+ addMetaData("cache","reload");
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << m_url;
+ m_command = CMD_GET;
+ }
+ break;
+ }
+ }
+
+ // Return slave to the scheduler
+ slaveDone();
+ Scheduler::doJob(this);
+ }
+}
+
+void TransferJob::setAsyncDataEnabled(bool enabled)
+{
+ if (enabled)
+ extraFlags() |= EF_TransferJobAsync;
+ else
+ extraFlags() &= ~EF_TransferJobAsync;
+}
+
+void TransferJob::sendAsyncData(const TQByteArray &dataForSlave)
+{
+ if (extraFlags() & EF_TransferJobNeedData)
+ {
+ m_slave->send( MSG_DATA, dataForSlave );
+ if (extraFlags() & EF_TransferJobDataSent)
+ {
+ TDEIO::filesize_t size = getProcessedSize()+dataForSlave.size();
+ setProcessedSize(size);
+ emit processedSize( this, size );
+ if ( size > m_totalSize ) {
+ slotTotalSize(size); // safety
+ }
+ emitPercent( size, m_totalSize );
+ }
+ }
+
+ extraFlags() &= ~EF_TransferJobNeedData;
+}
+
+void TransferJob::setReportDataSent(bool enabled)
+{
+ if (enabled)
+ extraFlags() |= EF_TransferJobDataSent;
+ else
+ extraFlags() &= ~EF_TransferJobDataSent;
+}
+
+bool TransferJob::reportDataSent()
+{
+ return (extraFlags() & EF_TransferJobDataSent);
+}
+
+
+// Slave requests data
+void TransferJob::slotDataReq()
+{
+ TQByteArray dataForSlave;
+
+ extraFlags() |= EF_TransferJobNeedData;
+
+ if (!staticData.isEmpty())
+ {
+ dataForSlave = staticData;
+ staticData = TQByteArray();
+ }
+ else
+ {
+ emit dataReq( this, dataForSlave);
+
+ if (extraFlags() & EF_TransferJobAsync)
+ return;
+ }
+
+ static const size_t max_size = 14 * 1024 * 1024;
+ if (dataForSlave.size() > max_size)
+ {
+ kdDebug(7007) << "send " << dataForSlave.size() / 1024 / 1024 << "MB of data in TransferJob::dataReq. This needs to be splitted, which requires a copy. Fix the application.\n";
+ staticData.duplicate(dataForSlave.data() + max_size , dataForSlave.size() - max_size);
+ dataForSlave.truncate(max_size);
+ }
+
+ sendAsyncData(dataForSlave);
+
+ if (m_subJob)
+ {
+ // Bitburger protocol in action
+ suspend(); // Wait for more data from subJob.
+ m_subJob->resume(); // Ask for more!
+ }
+}
+
+void TransferJob::slotMimetype( const TQString& type )
+{
+ m_mimetype = type;
+ emit mimetype( this, m_mimetype);
+}
+
+
+void TransferJob::suspend()
+{
+ m_suspended = true;
+ if (m_slave)
+ m_slave->suspend();
+}
+
+void TransferJob::resume()
+{
+ m_suspended = false;
+ if (m_slave)
+ m_slave->resume();
+}
+
+void TransferJob::start(Slave *slave)
+{
+ assert(slave);
+ connect( slave, TQT_SIGNAL( data( const TQByteArray & ) ),
+ TQT_SLOT( slotData( const TQByteArray & ) ) );
+
+ connect( slave, TQT_SIGNAL( dataReq() ),
+ TQT_SLOT( slotDataReq() ) );
+
+ connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
+ TQT_SLOT( slotRedirection(const KURL &) ) );
+
+ connect( slave, TQT_SIGNAL(mimeType( const TQString& ) ),
+ TQT_SLOT( slotMimetype( const TQString& ) ) );
+
+ connect( slave, TQT_SIGNAL(errorPage() ),
+ TQT_SLOT( slotErrorPage() ) );
+
+ connect( slave, TQT_SIGNAL( needSubURLData() ),
+ TQT_SLOT( slotNeedSubURLData() ) );
+
+ connect( slave, TQT_SIGNAL(canResume( TDEIO::filesize_t ) ),
+ TQT_SLOT( slotCanResume( TDEIO::filesize_t ) ) );
+
+ if (slave->suspended())
+ {
+ m_mimetype = "unknown";
+ // WABA: The slave was put on hold. Resume operation.
+ slave->resume();
+ }
+
+ SimpleJob::start(slave);
+ if (m_suspended)
+ slave->suspend();
+}
+
+void TransferJob::slotNeedSubURLData()
+{
+ // Job needs data from subURL.
+ m_subJob = TDEIO::get( m_subUrl, false, false);
+ suspend(); // Put job on hold until we have some data.
+ connect(m_subJob, TQT_SIGNAL( data(TDEIO::Job*,const TQByteArray &)),
+ TQT_SLOT( slotSubURLData(TDEIO::Job*,const TQByteArray &)));
+ addSubjob(m_subJob);
+}
+
+void TransferJob::slotSubURLData(TDEIO::Job*, const TQByteArray &data)
+{
+ // The Alternating Bitburg protocol in action again.
+ staticData = data;
+ m_subJob->suspend(); // Put job on hold until we have delivered the data.
+ resume(); // Activate ourselves again.
+}
+
+void TransferJob::slotMetaData( const TDEIO::MetaData &_metaData) {
+ SimpleJob::slotMetaData(_metaData);
+ storeSSLSessionFromJob(m_redirectionURL);
+}
+
+void TransferJob::slotErrorPage()
+{
+ m_errorPage = true;
+}
+
+void TransferJob::slotCanResume( TDEIO::filesize_t offset )
+{
+ emit canResume(this, offset);
+}
+
+void TransferJob::slotResult( TDEIO::Job *job)
+{
+ // This can only be our suburl.
+ assert(job == m_subJob);
+ // Did job have an error ?
+ if ( job->error() )
+ {
+ m_error = job->error();
+ m_errorText = job->errorText();
+
+ emitResult();
+ return;
+ }
+
+ if (job == m_subJob)
+ {
+ m_subJob = 0; // No action required
+ resume(); // Make sure we get the remaining data.
+ }
+ removeSubjob( job, false, false ); // Remove job, but don't kill this job.
+}
+
+TransferJob *TDEIO::get( const KURL& url, bool reload, bool showProgressInfo )
+{
+ // Send decoded path and encoded query
+ KIO_ARGS << url;
+ TransferJob * job = new TransferJob( url, CMD_GET, packedArgs, TQByteArray(), showProgressInfo );
+ if (reload)
+ job->addMetaData("cache", "reload");
+ return job;
+}
+
+class PostErrorJob : public TransferJob
+{
+public:
+
+ PostErrorJob(int _error, const TQString& url, const TQByteArray &packedArgs, const TQByteArray &postData, bool showProgressInfo)
+ : TransferJob(KURL(), CMD_SPECIAL, packedArgs, postData, showProgressInfo)
+ {
+ m_error = _error;
+ m_errorText = url;
+ }
+
+};
+
+TransferJob *TDEIO::http_post( const KURL& url, const TQByteArray &postData, bool showProgressInfo )
+{
+ int _error = 0;
+
+ // filter out some malicious ports
+ static const int bad_ports[] = {
+ 1, // tcpmux
+ 7, // echo
+ 9, // discard
+ 11, // systat
+ 13, // daytime
+ 15, // netstat
+ 17, // qotd
+ 19, // chargen
+ 20, // ftp-data
+ 21, // ftp-cntl
+ 22, // ssh
+ 23, // telnet
+ 25, // smtp
+ 37, // time
+ 42, // name
+ 43, // nicname
+ 53, // domain
+ 77, // priv-rjs
+ 79, // finger
+ 87, // ttylink
+ 95, // supdup
+ 101, // hostriame
+ 102, // iso-tsap
+ 103, // gppitnp
+ 104, // acr-nema
+ 109, // pop2
+ 110, // pop3
+ 111, // sunrpc
+ 113, // auth
+ 115, // sftp
+ 117, // uucp-path
+ 119, // nntp
+ 123, // NTP
+ 135, // loc-srv / epmap
+ 139, // netbios
+ 143, // imap2
+ 179, // BGP
+ 389, // ldap
+ 512, // print / exec
+ 513, // login
+ 514, // shell
+ 515, // printer
+ 526, // tempo
+ 530, // courier
+ 531, // Chat
+ 532, // netnews
+ 540, // uucp
+ 556, // remotefs
+ 587, // sendmail
+ 601, //
+ 989, // ftps data
+ 990, // ftps
+ 992, // telnets
+ 993, // imap/SSL
+ 995, // pop3/SSL
+ 1080, // SOCKS
+ 2049, // nfs
+ 4045, // lockd
+ 6000, // x11
+ 6667, // irc
+ 0};
+ for (int cnt=0; bad_ports[cnt]; ++cnt)
+ if (url.port() == bad_ports[cnt])
+ {
+ _error = TDEIO::ERR_POST_DENIED;
+ break;
+ }
+
+ if( _error )
+ {
+ static bool override_loaded = false;
+ static TQValueList< int >* overriden_ports = NULL;
+ if( !override_loaded )
+ {
+ TDEConfig cfg( "kio_httprc", true );
+ overriden_ports = new TQValueList< int >;
+ *overriden_ports = cfg.readIntListEntry( "OverriddenPorts" );
+ override_loaded = true;
+ }
+ for( TQValueList< int >::ConstIterator it = overriden_ports->begin();
+ it != overriden_ports->end();
+ ++it )
+ if( overriden_ports->contains( url.port()))
+ _error = 0;
+ }
+
+ // filter out non https? protocols
+ if ((url.protocol() != "http") && (url.protocol() != "https" ))
+ _error = TDEIO::ERR_POST_DENIED;
+
+ bool redirection = false;
+ KURL _url(url);
+ if (_url.path().isEmpty())
+ {
+ redirection = true;
+ _url.setPath("/");
+ }
+
+ if (!_error && !kapp->authorizeURLAction("open", KURL(), _url))
+ _error = TDEIO::ERR_ACCESS_DENIED;
+
+ // if request is not valid, return an invalid transfer job
+ if (_error)
+ {
+ KIO_ARGS << (int)1 << url;
+ TransferJob * job = new PostErrorJob(_error, url.prettyURL(), packedArgs, postData, showProgressInfo);
+ return job;
+ }
+
+ // Send http post command (1), decoded path and encoded query
+ KIO_ARGS << (int)1 << _url;
+ TransferJob * job = new TransferJob( _url, CMD_SPECIAL,
+ packedArgs, postData, showProgressInfo );
+
+ if (redirection)
+ TQTimer::singleShot(0, job, TQT_SLOT(slotPostRedirection()) );
+
+ return job;
+}
+
+// http post got redirected from http://host to http://host/ by TransferJob
+// We must do this redirection ourselves because redirections by the
+// slave change post jobs into get jobs.
+void TransferJob::slotPostRedirection()
+{
+ kdDebug(7007) << "TransferJob::slotPostRedirection(" << m_url << ")" << endl;
+ // Tell the user about the new url.
+ emit redirection(this, m_url);
+}
+
+
+TransferJob *TDEIO::put( const KURL& url, int permissions,
+ bool overwrite, bool resume, bool showProgressInfo )
+{
+ KIO_ARGS << url << TQ_INT8( overwrite ? 1 : 0 ) << TQ_INT8( resume ? 1 : 0 ) << permissions;
+ TransferJob * job = new TransferJob( url, CMD_PUT, packedArgs, TQByteArray(), showProgressInfo );
+ return job;
+}
+
+//////////
+
+StoredTransferJob::StoredTransferJob(const KURL& url, int command,
+ const TQByteArray &packedArgs,
+ const TQByteArray &_staticData,
+ bool showProgressInfo)
+ : TransferJob( url, command, packedArgs, _staticData, showProgressInfo ),
+ m_uploadOffset( 0 )
+{
+ connect( this, TQT_SIGNAL( data( TDEIO::Job *, const TQByteArray & ) ),
+ TQT_SLOT( slotStoredData( TDEIO::Job *, const TQByteArray & ) ) );
+ connect( this, TQT_SIGNAL( dataReq( TDEIO::Job *, TQByteArray & ) ),
+ TQT_SLOT( slotStoredDataReq( TDEIO::Job *, TQByteArray & ) ) );
+}
+
+void StoredTransferJob::setData( const TQByteArray& arr )
+{
+ Q_ASSERT( m_data.isNull() ); // check that we're only called once
+ Q_ASSERT( m_uploadOffset == 0 ); // no upload started yet
+ m_data = arr;
+}
+
+void StoredTransferJob::slotStoredData( TDEIO::Job *, const TQByteArray &data )
+{
+ // check for end-of-data marker:
+ if ( data.size() == 0 )
+ return;
+ unsigned int oldSize = m_data.size();
+ m_data.resize( oldSize + data.size(), TQGArray::SpeedOptim );
+ memcpy( m_data.data() + oldSize, data.data(), data.size() );
+}
+
+void StoredTransferJob::slotStoredDataReq( TDEIO::Job *, TQByteArray &data )
+{
+ // Inspired from kmail's KMKernel::byteArrayToRemoteFile
+ // send the data in 64 KB chunks
+ const int MAX_CHUNK_SIZE = 64*1024;
+ int remainingBytes = m_data.size() - m_uploadOffset;
+ if( remainingBytes > MAX_CHUNK_SIZE ) {
+ // send MAX_CHUNK_SIZE bytes to the receiver (deep copy)
+ data.duplicate( m_data.data() + m_uploadOffset, MAX_CHUNK_SIZE );
+ m_uploadOffset += MAX_CHUNK_SIZE;
+ //kdDebug() << "Sending " << MAX_CHUNK_SIZE << " bytes ("
+ // << remainingBytes - MAX_CHUNK_SIZE << " bytes remain)\n";
+ } else {
+ // send the remaining bytes to the receiver (deep copy)
+ data.duplicate( m_data.data() + m_uploadOffset, remainingBytes );
+ m_data = TQByteArray();
+ m_uploadOffset = 0;
+ //kdDebug() << "Sending " << remainingBytes << " bytes\n";
+ }
+}
+
+StoredTransferJob *TDEIO::storedGet( const KURL& url, bool reload, bool showProgressInfo )
+{
+ // Send decoded path and encoded query
+ KIO_ARGS << url;
+ StoredTransferJob * job = new StoredTransferJob( url, CMD_GET, packedArgs, TQByteArray(), showProgressInfo );
+ if (reload)
+ job->addMetaData("cache", "reload");
+ return job;
+}
+
+StoredTransferJob *TDEIO::storedPut( const TQByteArray& arr, const KURL& url, int permissions,
+ bool overwrite, bool resume, bool showProgressInfo )
+{
+ KIO_ARGS << url << TQ_INT8( overwrite ? 1 : 0 ) << TQ_INT8( resume ? 1 : 0 ) << permissions;
+ StoredTransferJob * job = new StoredTransferJob( url, CMD_PUT, packedArgs, TQByteArray(), showProgressInfo );
+ job->setData( arr );
+ return job;
+}
+
+//////////
+
+MimetypeJob::MimetypeJob( const KURL& url, int command,
+ const TQByteArray &packedArgs, bool showProgressInfo )
+ : TransferJob(url, command, packedArgs, TQByteArray(), showProgressInfo)
+{
+}
+
+void MimetypeJob::start(Slave *slave)
+{
+ TransferJob::start(slave);
+}
+
+
+void MimetypeJob::slotFinished( )
+{
+ //kdDebug(7007) << "MimetypeJob::slotFinished()" << endl;
+ if ( m_error == TDEIO::ERR_IS_DIRECTORY )
+ {
+ // It is in fact a directory. This happens when HTTP redirects to FTP.
+ // Due to the "protocol doesn't support listing" code in KRun, we
+ // assumed it was a file.
+ kdDebug(7007) << "It is in fact a directory!" << endl;
+ m_mimetype = TQString::fromLatin1("inode/directory");
+ emit TransferJob::mimetype( this, m_mimetype );
+ m_error = 0;
+ }
+ if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error )
+ {
+ // Return slave to the scheduler
+ TransferJob::slotFinished();
+ } else {
+ //kdDebug(7007) << "MimetypeJob: Redirection to " << m_redirectionURL << endl;
+ if (queryMetaData("permanent-redirect")=="true")
+ emit permanentRedirection(this, m_url, m_redirectionURL);
+ staticData.truncate(0);
+ m_suspended = false;
+ m_url = m_redirectionURL;
+ m_redirectionURL = KURL();
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << m_url;
+
+ // Return slave to the scheduler
+ slaveDone();
+ Scheduler::doJob(this);
+ }
+}
+
+MimetypeJob *TDEIO::mimetype(const KURL& url, bool showProgressInfo )
+{
+ KIO_ARGS << url;
+ MimetypeJob * job = new MimetypeJob(url, CMD_MIMETYPE, packedArgs, showProgressInfo);
+ if ( showProgressInfo )
+ Observer::self()->stating( job, url );
+ return job;
+}
+
+//////////////////////////
+
+DirectCopyJob::DirectCopyJob( const KURL& url, int command,
+ const TQByteArray &packedArgs, bool showProgressInfo )
+ : SimpleJob(url, command, packedArgs, showProgressInfo)
+{
+}
+
+void DirectCopyJob::start( Slave* slave )
+{
+ connect( slave, TQT_SIGNAL(canResume( TDEIO::filesize_t ) ),
+ TQT_SLOT( slotCanResume( TDEIO::filesize_t ) ) );
+ SimpleJob::start(slave);
+}
+
+void DirectCopyJob::slotCanResume( TDEIO::filesize_t offset )
+{
+ emit canResume(this, offset);
+}
+
+//////////////////////////
+
+
+class FileCopyJob::FileCopyJobPrivate
+{
+public:
+ TDEIO::filesize_t m_sourceSize;
+ time_t m_modificationTime;
+ SimpleJob *m_delJob;
+};
+
+/*
+ * The FileCopyJob works according to the famous Bayern
+ * 'Alternating Bitburger Protocol': we either drink a beer or we
+ * we order a beer, but never both at the same time.
+ * Tranlated to io-slaves: We alternate between receiving a block of data
+ * and sending it away.
+ */
+FileCopyJob::FileCopyJob( const KURL& src, const KURL& dest, int permissions,
+ bool move, bool overwrite, bool resume, bool showProgressInfo)
+ : Job(showProgressInfo), m_src(src), m_dest(dest),
+ m_permissions(permissions), m_move(move), m_overwrite(overwrite), m_resume(resume),
+ m_totalSize(0)
+{
+ if (showProgressInfo && !move)
+ Observer::self()->slotCopying( this, src, dest );
+ else if (showProgressInfo && move)
+ Observer::self()->slotMoving( this, src, dest );
+
+ //kdDebug(7007) << "FileCopyJob::FileCopyJob()" << endl;
+ m_moveJob = 0;
+ m_copyJob = 0;
+ m_getJob = 0;
+ m_putJob = 0;
+ d = new FileCopyJobPrivate;
+ d->m_delJob = 0;
+ d->m_sourceSize = (TDEIO::filesize_t) -1;
+ d->m_modificationTime = static_cast<time_t>( -1 );
+ TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
+}
+
+void FileCopyJob::slotStart()
+{
+ if ( m_move )
+ {
+ // The if() below must be the same as the one in startBestCopyMethod
+ if ((m_src.protocol() == m_dest.protocol()) &&
+ (m_src.host() == m_dest.host()) &&
+ (m_src.port() == m_dest.port()) &&
+ (m_src.user() == m_dest.user()) &&
+ (m_src.pass() == m_dest.pass()) &&
+ !m_src.hasSubURL() && !m_dest.hasSubURL())
+ {
+ startRenameJob(m_src);
+ return;
+ }
+ else if (m_src.isLocalFile() && KProtocolInfo::canRenameFromFile(m_dest))
+ {
+ startRenameJob(m_dest);
+ return;
+ }
+ else if (m_dest.isLocalFile() && KProtocolInfo::canRenameToFile(m_src))
+ {
+ startRenameJob(m_src);
+ return;
+ }
+ // No fast-move available, use copy + del.
+ }
+ startBestCopyMethod();
+}
+
+void FileCopyJob::startBestCopyMethod()
+{
+ if ((m_src.protocol() == m_dest.protocol()) &&
+ (m_src.host() == m_dest.host()) &&
+ (m_src.port() == m_dest.port()) &&
+ (m_src.user() == m_dest.user()) &&
+ (m_src.pass() == m_dest.pass()) &&
+ !m_src.hasSubURL() && !m_dest.hasSubURL())
+ {
+ startCopyJob();
+ }
+ else if (m_src.isLocalFile() && KProtocolInfo::canCopyFromFile(m_dest))
+ {
+ startCopyJob(m_dest);
+ }
+ else if (m_dest.isLocalFile() && KProtocolInfo::canCopyToFile(m_src))
+ {
+ startCopyJob(m_src);
+ }
+ else
+ {
+ startDataPump();
+ }
+}
+
+FileCopyJob::~FileCopyJob()
+{
+ delete d;
+}
+
+void FileCopyJob::setSourceSize( off_t size )
+{
+ d->m_sourceSize = size;
+ if (size != (off_t) -1)
+ m_totalSize = size;
+}
+
+void FileCopyJob::setSourceSize64( TDEIO::filesize_t size )
+{
+ d->m_sourceSize = size;
+ if (size != (TDEIO::filesize_t) -1)
+ m_totalSize = size;
+}
+
+void FileCopyJob::setModificationTime( time_t mtime )
+{
+ d->m_modificationTime = mtime;
+}
+
+void FileCopyJob::startCopyJob()
+{
+ startCopyJob(m_src);
+}
+
+void FileCopyJob::startCopyJob(const KURL &slave_url)
+{
+ //kdDebug(7007) << "FileCopyJob::startCopyJob()" << endl;
+ KIO_ARGS << m_src << m_dest << m_permissions << (TQ_INT8) m_overwrite;
+ m_copyJob = new DirectCopyJob(slave_url, CMD_COPY, packedArgs, false);
+ addSubjob( m_copyJob );
+ connectSubjob( m_copyJob );
+ connect( m_copyJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
+ TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
+}
+
+void FileCopyJob::startRenameJob(const KURL &slave_url)
+{
+ KIO_ARGS << m_src << m_dest << (TQ_INT8) m_overwrite;
+ m_moveJob = new SimpleJob(slave_url, CMD_RENAME, packedArgs, false);
+ addSubjob( m_moveJob );
+ connectSubjob( m_moveJob );
+}
+
+void FileCopyJob::connectSubjob( SimpleJob * job )
+{
+ connect( job, TQT_SIGNAL(totalSize( TDEIO::Job*, TDEIO::filesize_t )),
+ this, TQT_SLOT( slotTotalSize(TDEIO::Job*, TDEIO::filesize_t)) );
+
+ connect( job, TQT_SIGNAL(processedSize( TDEIO::Job*, TDEIO::filesize_t )),
+ this, TQT_SLOT( slotProcessedSize(TDEIO::Job*, TDEIO::filesize_t)) );
+
+ connect( job, TQT_SIGNAL(percent( TDEIO::Job*, unsigned long )),
+ this, TQT_SLOT( slotPercent(TDEIO::Job*, unsigned long)) );
+
+}
+
+void FileCopyJob::slotProcessedSize( TDEIO::Job *, TDEIO::filesize_t size )
+{
+ setProcessedSize(size);
+ emit processedSize( this, size );
+ if ( size > m_totalSize ) {
+ slotTotalSize( this, size ); // safety
+ }
+ emitPercent( size, m_totalSize );
+}
+
+void FileCopyJob::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
+{
+ if (size > m_totalSize)
+ {
+ m_totalSize = size;
+ emit totalSize( this, m_totalSize );
+ }
+}
+
+void FileCopyJob::slotPercent( TDEIO::Job*, unsigned long pct )
+{
+ if ( pct > m_percent )
+ {
+ m_percent = pct;
+ emit percent( this, m_percent );
+ }
+}
+
+void FileCopyJob::startDataPump()
+{
+ //kdDebug(7007) << "FileCopyJob::startDataPump()" << endl;
+
+ m_canResume = false;
+ m_resumeAnswerSent = false;
+ m_getJob = 0L; // for now
+ m_putJob = put( m_dest, m_permissions, m_overwrite, m_resume, false /* no GUI */);
+ if ( d->m_modificationTime != static_cast<time_t>( -1 ) ) {
+ TQDateTime dt; dt.setTime_t( d->m_modificationTime );
+ m_putJob->addMetaData( "modified", dt.toString( Qt::ISODate ) );
+ }
+ //kdDebug(7007) << "FileCopyJob: m_putJob = " << m_putJob << " m_dest=" << m_dest << endl;
+
+ // The first thing the put job will tell us is whether we can
+ // resume or not (this is always emitted)
+ connect( m_putJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
+ TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
+ connect( m_putJob, TQT_SIGNAL(dataReq(TDEIO::Job *, TQByteArray&)),
+ TQT_SLOT( slotDataReq(TDEIO::Job *, TQByteArray&)));
+ addSubjob( m_putJob );
+}
+
+void FileCopyJob::slotCanResume( TDEIO::Job* job, TDEIO::filesize_t offset )
+{
+ if ( job == m_putJob || job == m_copyJob )
+ {
+ //kdDebug(7007) << "FileCopyJob::slotCanResume from PUT job. offset=" << TDEIO::number(offset) << endl;
+ if (offset)
+ {
+ RenameDlg_Result res = R_RESUME;
+
+ if (!KProtocolManager::autoResume() && !m_overwrite)
+ {
+ TQString newPath;
+ TDEIO::Job* job = ( !m_progressId && parentJob() ) ? parentJob() : this;
+ // Ask confirmation about resuming previous transfer
+ res = Observer::self()->open_RenameDlg(
+ job, i18n("File Already Exists"),
+ m_src.url(),
+ m_dest.url(),
+ (RenameDlg_Mode) (M_OVERWRITE | M_RESUME | M_NORENAME), newPath,
+ d->m_sourceSize, offset );
+ }
+
+ if ( res == R_OVERWRITE || m_overwrite )
+ offset = 0;
+ else if ( res == R_CANCEL )
+ {
+ if ( job == m_putJob )
+ m_putJob->kill(true);
+ else
+ m_copyJob->kill(true);
+ m_error = ERR_USER_CANCELED;
+ emitResult();
+ return;
+ }
+ }
+ else
+ m_resumeAnswerSent = true; // No need for an answer
+
+ if ( job == m_putJob )
+ {
+ m_getJob = get( m_src, false, false /* no GUI */ );
+ //kdDebug(7007) << "FileCopyJob: m_getJob = " << m_getJob << endl;
+ m_getJob->addMetaData( "errorPage", "false" );
+ m_getJob->addMetaData( "AllowCompressedPage", "false" );
+ // Set size in subjob. This helps if the slave doesn't emit totalSize.
+ if ( d->m_sourceSize != (TDEIO::filesize_t)-1 )
+ m_getJob->slotTotalSize( d->m_sourceSize );
+ if (offset)
+ {
+ //kdDebug(7007) << "Setting metadata for resume to " << (unsigned long) offset << endl;
+ // TODO KDE4: rename to seek or offset and document it
+ // This isn't used only for resuming, but potentially also for extracting (#72302).
+ m_getJob->addMetaData( "resume", TDEIO::number(offset) );
+
+ // Might or might not get emitted
+ connect( m_getJob, TQT_SIGNAL(canResume(TDEIO::Job *, TDEIO::filesize_t)),
+ TQT_SLOT( slotCanResume(TDEIO::Job *, TDEIO::filesize_t)));
+ }
+ m_putJob->slave()->setOffset( offset );
+
+ m_putJob->suspend();
+ addSubjob( m_getJob );
+ connectSubjob( m_getJob ); // Progress info depends on get
+ m_getJob->resume(); // Order a beer
+
+ connect( m_getJob, TQT_SIGNAL(data(TDEIO::Job*,const TQByteArray&)),
+ TQT_SLOT( slotData(TDEIO::Job*,const TQByteArray&)) );
+ connect( m_getJob, TQT_SIGNAL(mimetype(TDEIO::Job*,const TQString&) ),
+ TQT_SLOT(slotMimetype(TDEIO::Job*,const TQString&)) );
+ }
+ else // copyjob
+ {
+ m_copyJob->slave()->sendResumeAnswer( offset != 0 );
+ }
+ }
+ else if ( job == m_getJob )
+ {
+ // Cool, the get job said ok, we can resume
+ m_canResume = true;
+ //kdDebug(7007) << "FileCopyJob::slotCanResume from the GET job -> we can resume" << endl;
+
+ m_getJob->slave()->setOffset( m_putJob->slave()->offset() );
+ }
+ else
+ kdWarning(7007) << "FileCopyJob::slotCanResume from unknown job=" << job
+ << " m_getJob=" << m_getJob << " m_putJob=" << m_putJob << endl;
+}
+
+void FileCopyJob::slotData( TDEIO::Job * , const TQByteArray &data)
+{
+ //kdDebug(7007) << "FileCopyJob::slotData" << endl;
+ //kdDebug(7007) << " data size : " << data.size() << endl;
+ assert(m_putJob);
+ if (!m_putJob) return; // Don't crash
+ m_getJob->suspend();
+ m_putJob->resume(); // Drink the beer
+ m_buffer = data;
+
+ // On the first set of data incoming, we tell the "put" slave about our
+ // decision about resuming
+ if (!m_resumeAnswerSent)
+ {
+ m_resumeAnswerSent = true;
+ //kdDebug(7007) << "FileCopyJob::slotData (first time) -> send resume answer " << m_canResume << endl;
+ m_putJob->slave()->sendResumeAnswer( m_canResume );
+ }
+}
+
+void FileCopyJob::slotDataReq( TDEIO::Job * , TQByteArray &data)
+{
+ //kdDebug(7007) << "FileCopyJob::slotDataReq" << endl;
+ if (!m_resumeAnswerSent && !m_getJob)
+ {
+ // This can't happen (except as a migration bug on 12/10/2000)
+ m_error = ERR_INTERNAL;
+ m_errorText = "'Put' job didn't send canResume or 'Get' job didn't send data!";
+ m_putJob->kill(true);
+ emitResult();
+ return;
+ }
+ if (m_getJob)
+ {
+ m_getJob->resume(); // Order more beer
+ m_putJob->suspend();
+ }
+ data = m_buffer;
+ m_buffer = TQByteArray();
+}
+
+void FileCopyJob::slotMimetype( TDEIO::Job*, const TQString& type )
+{
+ emit mimetype( this, type );
+}
+
+void FileCopyJob::slotResult( TDEIO::Job *job)
+{
+ //kdDebug(7007) << "FileCopyJob this=" << this << " ::slotResult(" << job << ")" << endl;
+ // Did job have an error ?
+ if ( job->error() )
+ {
+ if ((job == m_moveJob) && (job->error() == ERR_UNSUPPORTED_ACTION))
+ {
+ m_moveJob = 0;
+ startBestCopyMethod();
+ removeSubjob(job);
+ return;
+ }
+ else if ((job == m_copyJob) && (job->error() == ERR_UNSUPPORTED_ACTION))
+ {
+ m_copyJob = 0;
+ startDataPump();
+ removeSubjob(job);
+ return;
+ }
+ else if (job == m_getJob)
+ {
+ m_getJob = 0L;
+ if (m_putJob)
+ m_putJob->kill(true);
+ }
+ else if (job == m_putJob)
+ {
+ m_putJob = 0L;
+ if (m_getJob)
+ m_getJob->kill(true);
+ }
+ m_error = job->error();
+ m_errorText = job->errorText();
+ emitResult();
+ return;
+ }
+
+ if (job == m_moveJob)
+ {
+ m_moveJob = 0; // Finished
+ }
+
+ if (job == m_copyJob)
+ {
+ m_copyJob = 0;
+ if (m_move)
+ {
+ d->m_delJob = file_delete( m_src, false/*no GUI*/ ); // Delete source
+ addSubjob(d->m_delJob);
+ }
+ }
+
+ if (job == m_getJob)
+ {
+ m_getJob = 0; // No action required
+ if (m_putJob)
+ m_putJob->resume();
+ }
+
+ if (job == m_putJob)
+ {
+ //kdDebug(7007) << "FileCopyJob: m_putJob finished " << endl;
+ m_putJob = 0;
+ if (m_getJob)
+ {
+ kdWarning(7007) << "WARNING ! Get still going on..." << endl;
+ m_getJob->resume();
+ }
+ if (m_move)
+ {
+ d->m_delJob = file_delete( m_src, false/*no GUI*/ ); // Delete source
+ addSubjob(d->m_delJob);
+ }
+ }
+
+ if (job == d->m_delJob)
+ {
+ d->m_delJob = 0; // Finished
+ }
+ removeSubjob(job);
+}
+
+FileCopyJob *TDEIO::file_copy( const KURL& src, const KURL& dest, int permissions,
+ bool overwrite, bool resume, bool showProgressInfo)
+{
+ return new FileCopyJob( src, dest, permissions, false, overwrite, resume, showProgressInfo );
+}
+
+FileCopyJob *TDEIO::file_move( const KURL& src, const KURL& dest, int permissions,
+ bool overwrite, bool resume, bool showProgressInfo)
+{
+ return new FileCopyJob( src, dest, permissions, true, overwrite, resume, showProgressInfo );
+}
+
+SimpleJob *TDEIO::file_delete( const KURL& src, bool showProgressInfo)
+{
+ KIO_ARGS << src << TQ_INT8(true); // isFile
+ return new SimpleJob(src, CMD_DEL, packedArgs, showProgressInfo );
+}
+
+//////////
+
+// KDE 4: Make it const TQString & _prefix
+ListJob::ListJob(const KURL& u, bool showProgressInfo, bool _recursive, TQString _prefix, bool _includeHidden) :
+ SimpleJob(u, CMD_LISTDIR, TQByteArray(), showProgressInfo),
+ recursive(_recursive), includeHidden(_includeHidden), prefix(_prefix), m_processedEntries(0)
+{
+ // We couldn't set the args when calling the parent constructor,
+ // so do it now.
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << u;
+}
+
+void ListJob::slotListEntries( const TDEIO::UDSEntryList& list )
+{
+ // Emit progress info (takes care of emit processedSize and percent)
+ m_processedEntries += list.count();
+ slotProcessedSize( m_processedEntries );
+
+ if (recursive) {
+ UDSEntryListConstIterator it = list.begin();
+ UDSEntryListConstIterator end = list.end();
+
+ for (; it != end; ++it) {
+ bool isDir = false;
+ bool isLink = false;
+ KURL itemURL;
+
+ UDSEntry::ConstIterator it2 = (*it).begin();
+ UDSEntry::ConstIterator end2 = (*it).end();
+ for( ; it2 != end2; it2++ ) {
+ switch( (*it2).m_uds ) {
+ case UDS_FILE_TYPE:
+ isDir = S_ISDIR((*it2).m_long);
+ break;
+ case UDS_NAME:
+ if( itemURL.isEmpty() ) {
+ itemURL = url();
+ itemURL.addPath( (*it2).m_str );
+ }
+ break;
+ case UDS_URL:
+ itemURL = (*it2).m_str;
+ break;
+ case UDS_LINK_DEST:
+ // This is a link !!! Don't follow !
+ isLink = !(*it2).m_str.isEmpty();
+ break;
+ default:
+ break;
+ }
+ }
+ if (isDir && !isLink) {
+ const TQString filename = itemURL.fileName();
+ // skip hidden dirs when listing if requested
+ if (filename != ".." && filename != "." && (includeHidden || filename[0] != '.')) {
+ ListJob *job = new ListJob(itemURL,
+ false /*no progress info!*/,
+ true /*recursive*/,
+ prefix + filename + "/",
+ includeHidden);
+ Scheduler::scheduleJob(job);
+ connect(job, TQT_SIGNAL(entries( TDEIO::Job *,
+ const TDEIO::UDSEntryList& )),
+ TQT_SLOT( gotEntries( TDEIO::Job*,
+ const TDEIO::UDSEntryList& )));
+ addSubjob(job);
+ }
+ }
+ }
+ }
+
+ // Not recursive, or top-level of recursive listing : return now (send . and .. as well)
+ // exclusion of hidden files also requires the full sweep, but the case for full-listing
+ // a single dir is probably common enough to justify the shortcut
+ if (prefix.isNull() && includeHidden) {
+ emit entries(this, list);
+ } else {
+ // cull the unwanted hidden dirs and/or parent dir references from the listing, then emit that
+ UDSEntryList newlist;
+
+ UDSEntryListConstIterator it = list.begin();
+ UDSEntryListConstIterator end = list.end();
+ for (; it != end; ++it) {
+
+ UDSEntry newone = *it;
+ UDSEntry::Iterator it2 = newone.begin();
+ TQString filename;
+ for( ; it2 != newone.end(); it2++ ) {
+ if ((*it2).m_uds == UDS_NAME) {
+ filename = (*it2).m_str;
+ (*it2).m_str = prefix + filename;
+ }
+ }
+ // Avoid returning entries like subdir/. and subdir/.., but include . and .. for
+ // the toplevel dir, and skip hidden files/dirs if that was requested
+ if ( (prefix.isNull() || (filename != ".." && filename != ".") )
+ && (includeHidden || (filename[0] != '.') ) )
+ newlist.append(newone);
+ }
+
+ emit entries(this, newlist);
+ }
+}
+
+void ListJob::gotEntries(TDEIO::Job *, const TDEIO::UDSEntryList& list )
+{
+ // Forward entries received by subjob - faking we received them ourselves
+ emit entries(this, list);
+}
+
+void ListJob::slotResult( TDEIO::Job * job )
+{
+ // If we can't list a subdir, the result is still ok
+ // This is why we override Job::slotResult() - to skip error checking
+ removeSubjob( job );
+}
+
+void ListJob::slotRedirection( const KURL & url )
+{
+ if (!kapp->authorizeURLAction("redirect", m_url, url))
+ {
+ kdWarning(7007) << "ListJob: Redirection from " << m_url << " to " << url << " REJECTED!" << endl;
+ return;
+ }
+ m_redirectionURL = url; // We'll remember that when the job finishes
+ if (m_url.hasUser() && !url.hasUser() && (m_url.host().lower() == url.host().lower()))
+ m_redirectionURL.setUser(m_url.user()); // Preserve user
+ emit redirection( this, m_redirectionURL );
+}
+
+void ListJob::slotFinished()
+{
+ // Support for listing archives as directories
+ if ( m_error == TDEIO::ERR_IS_FILE && m_url.isLocalFile() ) {
+ KMimeType::Ptr ptr = KMimeType::findByURL( m_url, 0, true, true );
+ if ( ptr ) {
+ TQString proto = ptr->property("X-TDE-LocalProtocol").toString();
+ if ( !proto.isEmpty() && KProtocolInfo::isKnownProtocol(proto) ) {
+ m_redirectionURL = m_url;
+ m_redirectionURL.setProtocol( proto );
+ m_error = 0;
+ emit redirection(this,m_redirectionURL);
+ }
+ }
+ }
+ if ( m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error ) {
+ // Return slave to the scheduler
+ SimpleJob::slotFinished();
+ } else {
+
+ //kdDebug(7007) << "ListJob: Redirection to " << m_redirectionURL << endl;
+ if (queryMetaData("permanent-redirect")=="true")
+ emit permanentRedirection(this, m_url, m_redirectionURL);
+ m_url = m_redirectionURL;
+ m_redirectionURL = KURL();
+ m_packedArgs.truncate(0);
+ TQDataStream stream( m_packedArgs, IO_WriteOnly );
+ stream << m_url;
+
+ // Return slave to the scheduler
+ slaveDone();
+ Scheduler::doJob(this);
+ }
+}
+
+void ListJob::slotMetaData( const TDEIO::MetaData &_metaData) {
+ SimpleJob::slotMetaData(_metaData);
+ storeSSLSessionFromJob(m_redirectionURL);
+}
+
+ListJob *TDEIO::listDir( const KURL& url, bool showProgressInfo, bool includeHidden )
+{
+ ListJob * job = new ListJob(url, showProgressInfo,false,TQString::null,includeHidden);
+ return job;
+}
+
+ListJob *TDEIO::listRecursive( const KURL& url, bool showProgressInfo, bool includeHidden )
+{
+ ListJob * job = new ListJob(url, showProgressInfo, true,TQString::null,includeHidden);
+ return job;
+}
+
+void ListJob::setUnrestricted(bool unrestricted)
+{
+ if (unrestricted)
+ extraFlags() |= EF_ListJobUnrestricted;
+ else
+ extraFlags() &= ~EF_ListJobUnrestricted;
+}
+
+void ListJob::start(Slave *slave)
+{
+ if (kapp && !kapp->authorizeURLAction("list", m_url, m_url) && !(extraFlags() & EF_ListJobUnrestricted))
+ {
+ m_error = ERR_ACCESS_DENIED;
+ m_errorText = m_url.url();
+ TQTimer::singleShot(0, this, TQT_SLOT(slotFinished()) );
+ return;
+ }
+ connect( slave, TQT_SIGNAL( listEntries( const TDEIO::UDSEntryList& )),
+ TQT_SLOT( slotListEntries( const TDEIO::UDSEntryList& )));
+ connect( slave, TQT_SIGNAL( totalSize( TDEIO::filesize_t ) ),
+ TQT_SLOT( slotTotalSize( TDEIO::filesize_t ) ) );
+ connect( slave, TQT_SIGNAL( redirection(const KURL &) ),
+ TQT_SLOT( slotRedirection(const KURL &) ) );
+
+ SimpleJob::start(slave);
+}
+
+class CopyJob::CopyJobPrivate
+{
+public:
+ CopyJobPrivate() {
+ m_defaultPermissions = false;
+ m_bURLDirty = false;
+ }
+ // This is the dest URL that was initially given to CopyJob
+ // It is copied into m_dest, which can be changed for a given src URL
+ // (when using the RENAME dialog in slotResult),
+ // and which will be reset for the next src URL.
+ KURL m_globalDest;
+ // The state info about that global dest
+ CopyJob::DestinationState m_globalDestinationState;
+ // See setDefaultPermissions
+ bool m_defaultPermissions;
+ // Whether URLs changed (and need to be emitted by the next slotReport call)
+ bool m_bURLDirty;
+ // Used after copying all the files into the dirs, to set mtime (TODO: and permissions?)
+ // after the copy is done
+ TQValueList<CopyInfo> m_directoriesCopied;
+};
+
+CopyJob::CopyJob( const KURL::List& src, const KURL& dest, CopyMode mode, bool asMethod, bool showProgressInfo )
+ : Job(showProgressInfo), m_mode(mode), m_asMethod(asMethod),
+ destinationState(DEST_NOT_STATED), state(STATE_STATING),
+ m_totalSize(0), m_processedSize(0), m_fileProcessedSize(0),
+ m_processedFiles(0), m_processedDirs(0),
+ m_srcList(src), m_currentStatSrc(m_srcList.begin()),
+ m_bCurrentOperationIsLink(false), m_bSingleFileCopy(false), m_bOnlyRenames(mode==Move),
+ m_dest(dest), m_bAutoSkip( false ), m_bOverwriteAll( false ),
+ m_conflictError(0), m_reportTimer(0)
+{
+ d = new CopyJobPrivate;
+ d->m_globalDest = dest;
+ d->m_globalDestinationState = destinationState;
+
+ if ( showProgressInfo ) {
+ connect( this, TQT_SIGNAL( totalFiles( TDEIO::Job*, unsigned long ) ),
+ Observer::self(), TQT_SLOT( slotTotalFiles( TDEIO::Job*, unsigned long ) ) );
+
+ connect( this, TQT_SIGNAL( totalDirs( TDEIO::Job*, unsigned long ) ),
+ Observer::self(), TQT_SLOT( slotTotalDirs( TDEIO::Job*, unsigned long ) ) );
+ }
+ TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
+ /**
+ States:
+ STATE_STATING for the dest
+ STATE_STATING for each src url (statNextSrc)
+ for each: if dir -> STATE_LISTING (filling 'dirs' and 'files')
+ but if direct rename possible: STATE_RENAMING instead.
+ STATE_CREATING_DIRS (createNextDir, iterating over 'dirs')
+ if conflict: STATE_CONFLICT_CREATING_DIRS
+ STATE_COPYING_FILES (copyNextFile, iterating over 'files')
+ if conflict: STATE_CONFLICT_COPYING_FILES
+ STATE_DELETING_DIRS (deleteNextDir) (if moving)
+ STATE_SETTING_DIR_ATTRIBUTES (setNextDirAttribute, iterating over d->m_directoriesCopied)
+ done.
+ */
+}
+
+CopyJob::~CopyJob()
+{
+ delete d;
+}
+
+void CopyJob::slotStart()
+{
+ /**
+ We call the functions directly instead of using signals.
+ Calling a function via a signal takes approx. 65 times the time
+ compared to calling it directly (at least on my machine). aleXXX
+ */
+ m_reportTimer = new TQTimer(this);
+
+ connect(m_reportTimer,TQT_SIGNAL(timeout()),this,TQT_SLOT(slotReport()));
+ m_reportTimer->start(REPORT_TIMEOUT,false);
+
+ // Stat the dest
+ TDEIO::Job * job = TDEIO::stat( m_dest, false, 2, false );
+ //kdDebug(7007) << "CopyJob:stating the dest " << m_dest << endl;
+ addSubjob(job);
+}
+
+// For unit test purposes
+TDEIO_EXPORT bool kio_resolve_local_urls = true;
+
+void CopyJob::slotResultStating( Job *job )
+{
+ //kdDebug(7007) << "CopyJob::slotResultStating" << endl;
+ // Was there an error while stating the src ?
+ if (job->error() && destinationState != DEST_NOT_STATED )
+ {
+ KURL srcurl = ((SimpleJob*)job)->url();
+ if ( !srcurl.isLocalFile() )
+ {
+ // Probably : src doesn't exist. Well, over some protocols (e.g. FTP)
+ // this info isn't really reliable (thanks to MS FTP servers).
+ // We'll assume a file, and try to download anyway.
+ kdDebug(7007) << "Error while stating source. Activating hack" << endl;
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
+ struct CopyInfo info;
+ info.permissions = (mode_t) -1;
+ info.mtime = (time_t) -1;
+ info.ctime = (time_t) -1;
+ info.size = (TDEIO::filesize_t)-1;
+ info.uSource = srcurl;
+ info.uDest = m_dest;
+ // Append filename or dirname to destination URL, if allowed
+ if ( destinationState == DEST_IS_DIR && !m_asMethod )
+ info.uDest.addPath( srcurl.fileName() );
+
+ files.append( info );
+ statNextSrc();
+ return;
+ }
+ // Local file. If stat fails, the file definitely doesn't exist.
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+
+ // Is it a file or a dir ? Does it have a local path?
+ UDSEntry entry = ((StatJob*)job)->statResult();
+ bool bDir = false;
+ bool bLink = false;
+ TQString sName;
+ TQString sLocalPath;
+ UDSEntry::ConstIterator it2 = entry.begin();
+ for( ; it2 != entry.end(); it2++ ) {
+ if ( ((*it2).m_uds) == UDS_FILE_TYPE )
+ bDir = S_ISDIR( (mode_t)(*it2).m_long );
+ else if ( ((*it2).m_uds) == UDS_LINK_DEST )
+ bLink = !((*it2).m_str.isEmpty());
+ else if ( ((*it2).m_uds) == UDS_NAME )
+ sName = (*it2).m_str;
+ else if ( ((*it2).m_uds) == UDS_LOCAL_PATH )
+ sLocalPath = (*it2).m_str;
+ }
+
+ if ( destinationState == DEST_NOT_STATED )
+ // we were stating the dest
+ {
+ if (job->error())
+ destinationState = DEST_DOESNT_EXIST;
+ else {
+ // Treat symlinks to dirs as dirs here, so no test on bLink
+ destinationState = bDir ? DEST_IS_DIR : DEST_IS_FILE;
+ //kdDebug(7007) << "CopyJob::slotResultStating dest is dir:" << bDir << endl;
+ }
+ const bool isGlobalDest = m_dest == d->m_globalDest;
+ if ( isGlobalDest )
+ d->m_globalDestinationState = destinationState;
+
+ if ( !sLocalPath.isEmpty() && kio_resolve_local_urls ) {
+ m_dest = KURL();
+ m_dest.setPath(sLocalPath);
+ if ( isGlobalDest )
+ d->m_globalDest = m_dest;
+ }
+
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() );
+
+ // After knowing what the dest is, we can start stat'ing the first src.
+ statCurrentSrc();
+ return;
+ }
+ // We were stating the current source URL
+ m_currentDest = m_dest; // used by slotEntries
+ // Create a dummy list with it, for slotEntries
+ UDSEntryList lst;
+ lst.append(entry);
+
+ // There 6 cases, and all end up calling slotEntries(job, lst) first :
+ // 1 - src is a dir, destination is a directory,
+ // slotEntries will append the source-dir-name to the destination
+ // 2 - src is a dir, destination is a file, ERROR (done later on)
+ // 3 - src is a dir, destination doesn't exist, then it's the destination dirname,
+ // so slotEntries will use it as destination.
+
+ // 4 - src is a file, destination is a directory,
+ // slotEntries will append the filename to the destination.
+ // 5 - src is a file, destination is a file, m_dest is the exact destination name
+ // 6 - src is a file, destination doesn't exist, m_dest is the exact destination name
+ // Tell slotEntries not to alter the src url
+ m_bCurrentSrcIsDir = false;
+ slotEntries(job, lst);
+
+ KURL srcurl;
+ if (!sLocalPath.isEmpty())
+ srcurl.setPath(sLocalPath);
+ else
+ srcurl = ((SimpleJob*)job)->url();
+
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
+
+ if ( bDir
+ && !bLink // treat symlinks as files (no recursion)
+ && m_mode != Link ) // No recursion in Link mode either.
+ {
+ //kdDebug(7007) << " Source is a directory " << endl;
+
+ m_bCurrentSrcIsDir = true; // used by slotEntries
+ if ( destinationState == DEST_IS_DIR ) // (case 1)
+ {
+ if ( !m_asMethod )
+ {
+ // Use <desturl>/<directory_copied> as destination, from now on
+ TQString directory = srcurl.fileName();
+ if ( !sName.isEmpty() && KProtocolInfo::fileNameUsedForCopying( srcurl ) == KProtocolInfo::Name )
+ {
+ directory = sName;
+ }
+ m_currentDest.addPath( directory );
+ }
+ }
+ else if ( destinationState == DEST_IS_FILE ) // (case 2)
+ {
+ m_error = ERR_IS_FILE;
+ m_errorText = m_dest.prettyURL();
+ emitResult();
+ return;
+ }
+ else // (case 3)
+ {
+ // otherwise dest is new name for toplevel dir
+ // so the destination exists, in fact, from now on.
+ // (This even works with other src urls in the list, since the
+ // dir has effectively been created)
+ destinationState = DEST_IS_DIR;
+ if ( m_dest == d->m_globalDest )
+ d->m_globalDestinationState = destinationState;
+ }
+
+ startListing( srcurl );
+ }
+ else
+ {
+ //kdDebug(7007) << " Source is a file (or a symlink), or we are linking -> no recursive listing " << endl;
+ statNextSrc();
+ }
+}
+
+void CopyJob::slotReport()
+{
+ // If showProgressInfo was set, m_progressId is > 0.
+ Observer * observer = m_progressId ? Observer::self() : 0L;
+ switch (state) {
+ case STATE_COPYING_FILES:
+ emit processedFiles( this, m_processedFiles );
+ if (observer) observer->slotProcessedFiles(this, m_processedFiles);
+ if (d->m_bURLDirty)
+ {
+ // Only emit urls when they changed. This saves time, and fixes #66281
+ d->m_bURLDirty = false;
+ if (m_mode==Move)
+ {
+ if (observer) observer->slotMoving( this, m_currentSrcURL, m_currentDestURL);
+ emit moving( this, m_currentSrcURL, m_currentDestURL);
+ }
+ else if (m_mode==Link)
+ {
+ if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL ); // we don't have a slotLinking
+ emit linking( this, m_currentSrcURL.path(), m_currentDestURL );
+ }
+ else
+ {
+ if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL );
+ emit copying( this, m_currentSrcURL, m_currentDestURL );
+ }
+ }
+ break;
+
+ case STATE_CREATING_DIRS:
+ if (observer) observer->slotProcessedDirs( this, m_processedDirs );
+ emit processedDirs( this, m_processedDirs );
+ if (d->m_bURLDirty)
+ {
+ d->m_bURLDirty = false;
+ emit creatingDir( this, m_currentDestURL );
+ if (observer) observer->slotCreatingDir( this, m_currentDestURL);
+ }
+ break;
+
+ case STATE_STATING:
+ case STATE_LISTING:
+ if (d->m_bURLDirty)
+ {
+ d->m_bURLDirty = false;
+ if (observer) observer->slotCopying( this, m_currentSrcURL, m_currentDestURL );
+ }
+ emit totalSize( this, m_totalSize );
+ emit totalFiles( this, files.count() );
+ emit totalDirs( this, dirs.count() );
+ break;
+
+ default:
+ break;
+ }
+}
+
+void CopyJob::slotEntries(TDEIO::Job* job, const UDSEntryList& list)
+{
+ UDSEntryListConstIterator it = list.begin();
+ UDSEntryListConstIterator end = list.end();
+ for (; it != end; ++it) {
+ UDSEntry::ConstIterator it2 = (*it).begin();
+ struct CopyInfo info;
+ info.permissions = -1;
+ info.mtime = (time_t) -1;
+ info.ctime = (time_t) -1;
+ info.size = (TDEIO::filesize_t)-1;
+ TQString displayName;
+ KURL url;
+ TQString localPath;
+ bool isDir = false;
+ for( ; it2 != (*it).end(); it2++ ) {
+ switch ((*it2).m_uds) {
+ case UDS_FILE_TYPE:
+ //info.type = (mode_t)((*it2).m_long);
+ isDir = S_ISDIR( (mode_t)((*it2).m_long) );
+ break;
+ case UDS_NAME: // recursive listing, displayName can be a/b/c/d
+ displayName = (*it2).m_str;
+ break;
+ case UDS_URL: // optional
+ url = KURL((*it2).m_str);
+ break;
+ case UDS_LOCAL_PATH:
+ localPath = (*it2).m_str;
+ break;
+ case UDS_LINK_DEST:
+ info.linkDest = (*it2).m_str;
+ break;
+ case UDS_ACCESS:
+ info.permissions = ((*it2).m_long);
+ break;
+ case UDS_SIZE:
+ info.size = (TDEIO::filesize_t)((*it2).m_long);
+ m_totalSize += info.size;
+ break;
+ case UDS_MODIFICATION_TIME:
+ info.mtime = (time_t)((*it2).m_long);
+ break;
+ case UDS_CREATION_TIME:
+ info.ctime = (time_t)((*it2).m_long);
+ default:
+ break;
+ }
+ }
+ if (displayName != ".." && displayName != ".")
+ {
+ bool hasCustomURL = !url.isEmpty() || !localPath.isEmpty();
+ if( !hasCustomURL ) {
+ // Make URL from displayName
+ url = ((SimpleJob *)job)->url();
+ if ( m_bCurrentSrcIsDir ) { // Only if src is a directory. Otherwise uSource is fine as is
+ //kdDebug(7007) << "adding path " << displayName << endl;
+ url.addPath( displayName );
+ }
+ }
+ //kdDebug(7007) << "displayName=" << displayName << " url=" << url << endl;
+ if (!localPath.isEmpty() && kio_resolve_local_urls) {
+ url = KURL();
+ url.setPath(localPath);
+ }
+
+ info.uSource = url;
+ info.uDest = m_currentDest;
+ //kdDebug(7007) << " uSource=" << info.uSource << " uDest(1)=" << info.uDest << endl;
+ // Append filename or dirname to destination URL, if allowed
+ if ( destinationState == DEST_IS_DIR &&
+ // "copy/move as <foo>" means 'foo' is the dest for the base srcurl
+ // (passed here during stating) but not its children (during listing)
+ ( ! ( m_asMethod && state == STATE_STATING ) ) )
+ {
+ TQString destFileName;
+ if ( hasCustomURL &&
+ KProtocolInfo::fileNameUsedForCopying( url ) == KProtocolInfo::FromURL ) {
+ //destFileName = url.fileName(); // Doesn't work for recursive listing
+ // Count the number of prefixes used by the recursive listjob
+ int numberOfSlashes = displayName.contains( '/' ); // don't make this a find()!
+ TQString path = url.path();
+ int pos = 0;
+ for ( int n = 0; n < numberOfSlashes + 1; ++n ) {
+ pos = path.findRev( '/', pos - 1 );
+ if ( pos == -1 ) { // error
+ kdWarning(7007) << "tdeioslave bug: not enough slashes in UDS_URL " << path << " - looking for " << numberOfSlashes << " slashes" << endl;
+ break;
+ }
+ }
+ if ( pos >= 0 ) {
+ destFileName = path.mid( pos + 1 );
+ }
+
+ } else { // destination filename taken from UDS_NAME
+ destFileName = displayName;
+ }
+
+ // Here we _really_ have to add some filename to the dest.
+ // Otherwise, we end up with e.g. dest=..../Desktop/ itself.
+ // (This can happen when dropping a link to a webpage with no path)
+ if ( destFileName.isEmpty() )
+ destFileName = TDEIO::encodeFileName( info.uSource.prettyURL() );
+
+ //kdDebug(7007) << " adding destFileName=" << destFileName << endl;
+ info.uDest.addPath( destFileName );
+ }
+ //kdDebug(7007) << " uDest(2)=" << info.uDest << endl;
+ //kdDebug(7007) << " " << info.uSource << " -> " << info.uDest << endl;
+ if ( info.linkDest.isEmpty() && isDir && m_mode != Link ) // Dir
+ {
+ dirs.append( info ); // Directories
+ if (m_mode == Move)
+ dirsToRemove.append( info.uSource );
+ }
+ else {
+ files.append( info ); // Files and any symlinks
+ }
+ }
+ }
+}
+
+void CopyJob::skipSrc()
+{
+ m_dest = d->m_globalDest;
+ destinationState = d->m_globalDestinationState;
+ ++m_currentStatSrc;
+ skip( m_currentSrcURL );
+ statCurrentSrc();
+}
+
+void CopyJob::statNextSrc()
+{
+ /* Revert to the global destination, the one that applies to all source urls.
+ * Imagine you copy the items a b and c into /d, but /d/b exists so the user uses "Rename" to put it in /foo/b instead.
+ * m_dest is /foo/b for b, but we have to revert to /d for item c and following.
+ */
+ m_dest = d->m_globalDest;
+ destinationState = d->m_globalDestinationState;
+ ++m_currentStatSrc;
+ statCurrentSrc();
+}
+
+void CopyJob::statCurrentSrc()
+{
+ if ( m_currentStatSrc != m_srcList.end() )
+ {
+ m_currentSrcURL = (*m_currentStatSrc);
+ d->m_bURLDirty = true;
+ if ( m_mode == Link )
+ {
+ // Skip the "stating the source" stage, we don't need it for linking
+ m_currentDest = m_dest;
+ struct CopyInfo info;
+ info.permissions = -1;
+ info.mtime = (time_t) -1;
+ info.ctime = (time_t) -1;
+ info.size = (TDEIO::filesize_t)-1;
+ info.uSource = m_currentSrcURL;
+ info.uDest = m_currentDest;
+ // Append filename or dirname to destination URL, if allowed
+ if ( destinationState == DEST_IS_DIR && !m_asMethod )
+ {
+ if (
+ (m_currentSrcURL.protocol() == info.uDest.protocol()) &&
+ (m_currentSrcURL.host() == info.uDest.host()) &&
+ (m_currentSrcURL.port() == info.uDest.port()) &&
+ (m_currentSrcURL.user() == info.uDest.user()) &&
+ (m_currentSrcURL.pass() == info.uDest.pass()) )
+ {
+ // This is the case of creating a real symlink
+ info.uDest.addPath( m_currentSrcURL.fileName() );
+ }
+ else
+ {
+ // Different protocols, we'll create a .desktop file
+ // We have to change the extension anyway, so while we're at it,
+ // name the file like the URL
+ info.uDest.addPath( TDEIO::encodeFileName( m_currentSrcURL.prettyURL() )+".desktop" );
+ }
+ }
+ files.append( info ); // Files and any symlinks
+ statNextSrc(); // we could use a loop instead of a recursive call :)
+ return;
+ }
+ else if ( m_mode == Move && (
+ // Don't go renaming right away if we need a stat() to find out the destination filename
+ KProtocolInfo::fileNameUsedForCopying( m_currentSrcURL ) == KProtocolInfo::FromURL ||
+ destinationState != DEST_IS_DIR || m_asMethod )
+ )
+ {
+ // If moving, before going for the full stat+[list+]copy+del thing, try to rename
+ // The logic is pretty similar to FileCopyJob::slotStart()
+ if ( (m_currentSrcURL.protocol() == m_dest.protocol()) &&
+ (m_currentSrcURL.host() == m_dest.host()) &&
+ (m_currentSrcURL.port() == m_dest.port()) &&
+ (m_currentSrcURL.user() == m_dest.user()) &&
+ (m_currentSrcURL.pass() == m_dest.pass()) )
+ {
+ startRenameJob( m_currentSrcURL );
+ return;
+ }
+ else if ( m_currentSrcURL.isLocalFile() && KProtocolInfo::canRenameFromFile( m_dest ) )
+ {
+ startRenameJob( m_dest );
+ return;
+ }
+ else if ( m_dest.isLocalFile() && KProtocolInfo::canRenameToFile( m_currentSrcURL ) )
+ {
+ startRenameJob( m_currentSrcURL );
+ return;
+ }
+ }
+
+ // if the file system doesn't support deleting, we do not even stat
+ if (m_mode == Move && !KProtocolInfo::supportsDeleting(m_currentSrcURL)) {
+ TQGuardedPtr<CopyJob> that = this;
+ if (isInteractive())
+ KMessageBox::information( 0, buildErrorString(ERR_CANNOT_DELETE, m_currentSrcURL.prettyURL()));
+ if (that)
+ statNextSrc(); // we could use a loop instead of a recursive call :)
+ return;
+ }
+
+ // Stat the next src url
+ Job * job = TDEIO::stat( m_currentSrcURL, true, 2, false );
+ //kdDebug(7007) << "TDEIO::stat on " << m_currentSrcURL << endl;
+ state = STATE_STATING;
+ addSubjob(job);
+ m_currentDestURL=m_dest;
+ m_bOnlyRenames = false;
+ d->m_bURLDirty = true;
+ }
+ else
+ {
+ // Finished the stat'ing phase
+ // First make sure that the totals were correctly emitted
+ state = STATE_STATING;
+ d->m_bURLDirty = true;
+ slotReport();
+ if (!dirs.isEmpty())
+ emit aboutToCreate( this, dirs );
+ if (!files.isEmpty())
+ emit aboutToCreate( this, files );
+ // Check if we are copying a single file
+ m_bSingleFileCopy = ( files.count() == 1 && dirs.isEmpty() );
+ // Then start copying things
+ state = STATE_CREATING_DIRS;
+ createNextDir();
+ }
+}
+
+void CopyJob::startRenameJob( const KURL& slave_url )
+{
+ KURL dest = m_dest;
+ // Append filename or dirname to destination URL, if allowed
+ if ( destinationState == DEST_IS_DIR && !m_asMethod )
+ dest.addPath( m_currentSrcURL.fileName() );
+ kdDebug(7007) << "This seems to be a suitable case for trying to rename before stat+[list+]copy+del" << endl;
+ state = STATE_RENAMING;
+
+ struct CopyInfo info;
+ info.permissions = -1;
+ info.mtime = (time_t) -1;
+ info.ctime = (time_t) -1;
+ info.size = (TDEIO::filesize_t)-1;
+ info.uSource = m_currentSrcURL;
+ info.uDest = dest;
+ TQValueList<CopyInfo> files;
+ files.append(info);
+ emit aboutToCreate( this, files );
+
+ KIO_ARGS << m_currentSrcURL << dest << (TQ_INT8) false /*no overwrite*/;
+ SimpleJob * newJob = new SimpleJob(slave_url, CMD_RENAME, packedArgs, false);
+ Scheduler::scheduleJob(newJob);
+ addSubjob( newJob );
+ if ( m_currentSrcURL.directory() != dest.directory() ) // For the user, moving isn't renaming. Only renaming is.
+ m_bOnlyRenames = false;
+}
+
+void CopyJob::startListing( const KURL & src )
+{
+ state = STATE_LISTING;
+ d->m_bURLDirty = true;
+ ListJob * newjob = listRecursive( src, false );
+ newjob->setUnrestricted(true);
+ connect(newjob, TQT_SIGNAL(entries( TDEIO::Job *,
+ const TDEIO::UDSEntryList& )),
+ TQT_SLOT( slotEntries( TDEIO::Job*,
+ const TDEIO::UDSEntryList& )));
+ addSubjob( newjob );
+}
+
+void CopyJob::skip( const KURL & sourceUrl )
+{
+ // Check if this is one if toplevel sources
+ // If yes, remove it from m_srcList, for a correct FilesRemoved() signal
+ //kdDebug(7007) << "CopyJob::skip: looking for " << sourceUrl << endl;
+ KURL::List::Iterator sit = m_srcList.find( sourceUrl );
+ if ( sit != m_srcList.end() )
+ {
+ //kdDebug(7007) << "CopyJob::skip: removing " << sourceUrl << " from list" << endl;
+ m_srcList.remove( sit );
+ }
+ dirsToRemove.remove( sourceUrl );
+}
+
+bool CopyJob::shouldOverwrite( const TQString& path ) const
+{
+ if ( m_bOverwriteAll )
+ return true;
+ TQStringList::ConstIterator sit = m_overwriteList.begin();
+ for( ; sit != m_overwriteList.end(); ++sit )
+ if ( path.startsWith( *sit ) )
+ return true;
+ return false;
+}
+
+bool CopyJob::shouldSkip( const TQString& path ) const
+{
+ TQStringList::ConstIterator sit = m_skipList.begin();
+ for( ; sit != m_skipList.end(); ++sit )
+ if ( path.startsWith( *sit ) )
+ return true;
+ return false;
+}
+
+void CopyJob::slotResultCreatingDirs( Job * job )
+{
+ // The dir we are trying to create:
+ TQValueList<CopyInfo>::Iterator it = dirs.begin();
+ // Was there an error creating a dir ?
+ if ( job->error() )
+ {
+ m_conflictError = job->error();
+ if ( (m_conflictError == ERR_DIR_ALREADY_EXIST)
+ || (m_conflictError == ERR_FILE_ALREADY_EXIST) ) // can't happen?
+ {
+ KURL oldURL = ((SimpleJob*)job)->url();
+ // Should we skip automatically ?
+ if ( m_bAutoSkip ) {
+ // We don't want to copy files in this directory, so we put it on the skip list
+ m_skipList.append( oldURL.path( 1 ) );
+ skip( oldURL );
+ dirs.remove( it ); // Move on to next dir
+ } else {
+ // Did the user choose to overwrite already?
+ const TQString destFile = (*it).uDest.path();
+ if ( shouldOverwrite( destFile ) ) { // overwrite => just skip
+ emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
+ dirs.remove( it ); // Move on to next dir
+ } else {
+ if ( !isInteractive() ) {
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+
+ assert( ((SimpleJob*)job)->url().url() == (*it).uDest.url() );
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
+
+ // We need to stat the existing dir, to get its last-modification time
+ KURL existingDest( (*it).uDest );
+ SimpleJob * newJob = TDEIO::stat( existingDest, false, 2, false );
+ Scheduler::scheduleJob(newJob);
+ kdDebug(7007) << "TDEIO::stat for resolving conflict on " << existingDest << endl;
+ state = STATE_CONFLICT_CREATING_DIRS;
+ addSubjob(newJob);
+ return; // Don't move to next dir yet !
+ }
+ }
+ }
+ else
+ {
+ // Severe error, abort
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+ }
+ else // no error : remove from list, to move on to next dir
+ {
+ //this is required for the undo feature
+ emit copyingDone( this, (*it).uSource, (*it).uDest, true, false );
+ d->m_directoriesCopied.append( *it );
+ dirs.remove( it );
+ }
+
+ m_processedDirs++;
+ //emit processedDirs( this, m_processedDirs );
+ subjobs.remove( job );
+ assert( subjobs.isEmpty() ); // We should have only one job at a time ...
+ createNextDir();
+}
+
+void CopyJob::slotResultConflictCreatingDirs( TDEIO::Job * job )
+{
+ // We come here after a conflict has been detected and we've stated the existing dir
+
+ // The dir we were trying to create:
+ TQValueList<CopyInfo>::Iterator it = dirs.begin();
+ // Its modification time:
+ time_t destmtime = (time_t)-1;
+ time_t destctime = (time_t)-1;
+ TDEIO::filesize_t destsize = 0;
+ TQString linkDest;
+
+ UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
+ TDEIO::UDSEntry::ConstIterator it2 = entry.begin();
+ for( ; it2 != entry.end(); it2++ ) {
+ switch ((*it2).m_uds) {
+ case UDS_MODIFICATION_TIME:
+ destmtime = (time_t)((*it2).m_long);
+ break;
+ case UDS_CREATION_TIME:
+ destctime = (time_t)((*it2).m_long);
+ break;
+ case UDS_SIZE:
+ destsize = (*it2).m_long;
+ break;
+ case UDS_LINK_DEST:
+ linkDest = (*it2).m_str;
+ break;
+ }
+ }
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
+
+ // Always multi and skip (since there are files after that)
+ RenameDlg_Mode mode = (RenameDlg_Mode)( M_MULTI | M_SKIP );
+ // Overwrite only if the existing thing is a dir (no chance with a file)
+ if ( m_conflictError == ERR_DIR_ALREADY_EXIST )
+ {
+ if( (*it).uSource == (*it).uDest ||
+ ((*it).uSource.protocol() == (*it).uDest.protocol() &&
+ (*it).uSource.path(-1) == linkDest) )
+ mode = (RenameDlg_Mode)( mode | M_OVERWRITE_ITSELF);
+ else
+ mode = (RenameDlg_Mode)( mode | M_OVERWRITE );
+ }
+
+ TQString existingDest = (*it).uDest.path();
+ TQString newPath;
+ if (m_reportTimer)
+ m_reportTimer->stop();
+ RenameDlg_Result r = Observer::self()->open_RenameDlg( this, i18n("Folder Already Exists"),
+ (*it).uSource.url(),
+ (*it).uDest.url(),
+ mode, newPath,
+ (*it).size, destsize,
+ (*it).ctime, destctime,
+ (*it).mtime, destmtime );
+ if (m_reportTimer)
+ m_reportTimer->start(REPORT_TIMEOUT,false);
+ switch ( r ) {
+ case R_CANCEL:
+ m_error = ERR_USER_CANCELED;
+ emitResult();
+ return;
+ case R_RENAME:
+ {
+ TQString oldPath = (*it).uDest.path( 1 );
+ KURL newUrl( (*it).uDest );
+ newUrl.setPath( newPath );
+ emit renamed( this, (*it).uDest, newUrl ); // for e.g. kpropsdlg
+
+ // Change the current one and strip the trailing '/'
+ (*it).uDest.setPath( newUrl.path( -1 ) );
+ newPath = newUrl.path( 1 ); // With trailing slash
+ TQValueList<CopyInfo>::Iterator renamedirit = it;
+ ++renamedirit;
+ // Change the name of subdirectories inside the directory
+ for( ; renamedirit != dirs.end() ; ++renamedirit )
+ {
+ TQString path = (*renamedirit).uDest.path();
+ if ( path.left(oldPath.length()) == oldPath ) {
+ TQString n = path;
+ n.replace( 0, oldPath.length(), newPath );
+ kdDebug(7007) << "dirs list: " << (*renamedirit).uSource.path()
+ << " was going to be " << path
+ << ", changed into " << n << endl;
+ (*renamedirit).uDest.setPath( n );
+ }
+ }
+ // Change filenames inside the directory
+ TQValueList<CopyInfo>::Iterator renamefileit = files.begin();
+ for( ; renamefileit != files.end() ; ++renamefileit )
+ {
+ TQString path = (*renamefileit).uDest.path();
+ if ( path.left(oldPath.length()) == oldPath ) {
+ TQString n = path;
+ n.replace( 0, oldPath.length(), newPath );
+ kdDebug(7007) << "files list: " << (*renamefileit).uSource.path()
+ << " was going to be " << path
+ << ", changed into " << n << endl;
+ (*renamefileit).uDest.setPath( n );
+ }
+ }
+ if (!dirs.isEmpty())
+ emit aboutToCreate( this, dirs );
+ if (!files.isEmpty())
+ emit aboutToCreate( this, files );
+ }
+ break;
+ case R_AUTO_SKIP:
+ m_bAutoSkip = true;
+ // fall through
+ case R_SKIP:
+ m_skipList.append( existingDest );
+ skip( (*it).uSource );
+ // Move on to next dir
+ dirs.remove( it );
+ m_processedDirs++;
+ break;
+ case R_OVERWRITE:
+ m_overwriteList.append( existingDest );
+ emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
+ // Move on to next dir
+ dirs.remove( it );
+ m_processedDirs++;
+ break;
+ case R_OVERWRITE_ALL:
+ m_bOverwriteAll = true;
+ emit copyingDone( this, ( *it ).uSource, ( *it ).uDest, true /* directory */, false /* renamed */ );
+ // Move on to next dir
+ dirs.remove( it );
+ m_processedDirs++;
+ break;
+ default:
+ assert( 0 );
+ }
+ state = STATE_CREATING_DIRS;
+ //emit processedDirs( this, m_processedDirs );
+ createNextDir();
+}
+
+void CopyJob::createNextDir()
+{
+ KURL udir;
+ if ( !dirs.isEmpty() )
+ {
+ // Take first dir to create out of list
+ TQValueList<CopyInfo>::Iterator it = dirs.begin();
+ // Is this URL on the skip list or the overwrite list ?
+ while( it != dirs.end() && udir.isEmpty() )
+ {
+ const TQString dir = (*it).uDest.path();
+ if ( shouldSkip( dir ) ) {
+ dirs.remove( it );
+ it = dirs.begin();
+ } else
+ udir = (*it).uDest;
+ }
+ }
+ if ( !udir.isEmpty() ) // any dir to create, finally ?
+ {
+ // Create the directory - with default permissions so that we can put files into it
+ // TODO : change permissions once all is finished; but for stuff coming from CDROM it sucks...
+ TDEIO::SimpleJob *newjob = TDEIO::mkdir( udir, -1 );
+ Scheduler::scheduleJob(newjob);
+
+ m_currentDestURL = udir;
+ d->m_bURLDirty = true;
+
+ addSubjob(newjob);
+ return;
+ }
+ else // we have finished creating dirs
+ {
+ emit processedDirs( this, m_processedDirs ); // make sure final number appears
+ if (m_progressId) Observer::self()->slotProcessedDirs( this, m_processedDirs );
+
+ state = STATE_COPYING_FILES;
+ m_processedFiles++; // Ralf wants it to start at 1, not 0
+ copyNextFile();
+ }
+}
+
+void CopyJob::slotResultCopyingFiles( Job * job )
+{
+ // The file we were trying to copy:
+ TQValueList<CopyInfo>::Iterator it = files.begin();
+ if ( job->error() )
+ {
+ // Should we skip automatically ?
+ if ( m_bAutoSkip )
+ {
+ skip( (*it).uSource );
+ m_fileProcessedSize = (*it).size;
+ files.remove( it ); // Move on to next file
+ }
+ else
+ {
+ if ( !isInteractive() ) {
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+
+ m_conflictError = job->error(); // save for later
+ // Existing dest ?
+ if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
+ || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
+ || ( m_conflictError == ERR_IDENTICAL_FILES ) )
+ {
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() );
+ // We need to stat the existing file, to get its last-modification time
+ KURL existingFile( (*it).uDest );
+ SimpleJob * newJob = TDEIO::stat( existingFile, false, 2, false );
+ Scheduler::scheduleJob(newJob);
+ kdDebug(7007) << "TDEIO::stat for resolving conflict on " << existingFile << endl;
+ state = STATE_CONFLICT_COPYING_FILES;
+ addSubjob(newJob);
+ return; // Don't move to next file yet !
+ }
+ else
+ {
+ if ( m_bCurrentOperationIsLink && ::tqqt_cast<TDEIO::DeleteJob*>( job ) )
+ {
+ // Very special case, see a few lines below
+ // We are deleting the source of a symlink we successfully moved... ignore error
+ m_fileProcessedSize = (*it).size;
+ files.remove( it );
+ } else {
+ // Go directly to the conflict resolution, there is nothing to stat
+ slotResultConflictCopyingFiles( job );
+ return;
+ }
+ }
+ }
+ } else // no error
+ {
+ // Special case for moving links. That operation needs two jobs, unlike others.
+ if ( m_bCurrentOperationIsLink && m_mode == Move
+ && !::tqqt_cast<TDEIO::DeleteJob *>( job ) // Deleting source not already done
+ )
+ {
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() );
+ // The only problem with this trick is that the error handling for this del operation
+ // is not going to be right... see 'Very special case' above.
+ TDEIO::Job * newjob = TDEIO::del( (*it).uSource, false /*don't shred*/, false /*no GUI*/ );
+ addSubjob( newjob );
+ return; // Don't move to next file yet !
+ }
+
+ if ( m_bCurrentOperationIsLink )
+ {
+ TQString target = ( m_mode == Link ? (*it).uSource.path() : (*it).linkDest );
+ //required for the undo feature
+ emit copyingLinkDone( this, (*it).uSource, target, (*it).uDest );
+ }
+ else
+ //required for the undo feature
+ emit copyingDone( this, (*it).uSource, (*it).uDest, false, false );
+ // remove from list, to move on to next file
+ files.remove( it );
+ }
+ m_processedFiles++;
+
+ // clear processed size for last file and add it to overall processed size
+ m_processedSize += m_fileProcessedSize;
+ m_fileProcessedSize = 0;
+
+ //kdDebug(7007) << files.count() << " files remaining" << endl;
+
+ removeSubjob( job, true, false ); // merge metadata
+ assert ( subjobs.isEmpty() ); // We should have only one job at a time ...
+ copyNextFile();
+}
+
+void CopyJob::slotResultConflictCopyingFiles( TDEIO::Job * job )
+{
+ // We come here after a conflict has been detected and we've stated the existing file
+ // The file we were trying to create:
+ TQValueList<CopyInfo>::Iterator it = files.begin();
+
+ RenameDlg_Result res;
+ TQString newPath;
+
+ if (m_reportTimer)
+ m_reportTimer->stop();
+
+ if ( ( m_conflictError == ERR_FILE_ALREADY_EXIST )
+ || ( m_conflictError == ERR_DIR_ALREADY_EXIST )
+ || ( m_conflictError == ERR_IDENTICAL_FILES ) )
+ {
+ // Its modification time:
+ time_t destmtime = (time_t)-1;
+ time_t destctime = (time_t)-1;
+ TDEIO::filesize_t destsize = 0;
+ TQString linkDest;
+ UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
+ TDEIO::UDSEntry::ConstIterator it2 = entry.begin();
+ for( ; it2 != entry.end(); it2++ ) {
+ switch ((*it2).m_uds) {
+ case UDS_MODIFICATION_TIME:
+ destmtime = (time_t)((*it2).m_long);
+ break;
+ case UDS_CREATION_TIME:
+ destctime = (time_t)((*it2).m_long);
+ break;
+ case UDS_SIZE:
+ destsize = (*it2).m_long;
+ break;
+ case UDS_LINK_DEST:
+ linkDest = (*it2).m_str;
+ break;
+ }
+ }
+
+ // Offer overwrite only if the existing thing is a file
+ // If src==dest, use "overwrite-itself"
+ RenameDlg_Mode mode;
+ bool isDir = true;
+
+ if( m_conflictError == ERR_DIR_ALREADY_EXIST )
+ mode = (RenameDlg_Mode) 0;
+ else
+ {
+ if ( (*it).uSource == (*it).uDest ||
+ ((*it).uSource.protocol() == (*it).uDest.protocol() &&
+ (*it).uSource.path(-1) == linkDest) )
+ mode = M_OVERWRITE_ITSELF;
+ else
+ mode = M_OVERWRITE;
+ isDir = false;
+ }
+
+ if ( m_bSingleFileCopy )
+ mode = (RenameDlg_Mode) ( mode | M_SINGLE );
+ else
+ mode = (RenameDlg_Mode) ( mode | M_MULTI | M_SKIP );
+
+ res = Observer::self()->open_RenameDlg( this, !isDir ?
+ i18n("File Already Exists") : i18n("Already Exists as Folder"),
+ (*it).uSource.url(),
+ (*it).uDest.url(),
+ mode, newPath,
+ (*it).size, destsize,
+ (*it).ctime, destctime,
+ (*it).mtime, destmtime );
+
+ }
+ else
+ {
+ if ( job->error() == ERR_USER_CANCELED )
+ res = R_CANCEL;
+ else if ( !isInteractive() ) {
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+ else
+ {
+ SkipDlg_Result skipResult = Observer::self()->open_SkipDlg( this, files.count() > 1,
+ job->errorString() );
+
+ // Convert the return code from SkipDlg into a RenameDlg code
+ res = ( skipResult == S_SKIP ) ? R_SKIP :
+ ( skipResult == S_AUTO_SKIP ) ? R_AUTO_SKIP :
+ R_CANCEL;
+ }
+ }
+
+ if (m_reportTimer)
+ m_reportTimer->start(REPORT_TIMEOUT,false);
+
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() );
+ switch ( res ) {
+ case R_CANCEL:
+ m_error = ERR_USER_CANCELED;
+ emitResult();
+ return;
+ case R_RENAME:
+ {
+ KURL newUrl( (*it).uDest );
+ newUrl.setPath( newPath );
+ emit renamed( this, (*it).uDest, newUrl ); // for e.g. kpropsdlg
+ (*it).uDest = newUrl;
+
+ TQValueList<CopyInfo> files;
+ files.append(*it);
+ emit aboutToCreate( this, files );
+ }
+ break;
+ case R_AUTO_SKIP:
+ m_bAutoSkip = true;
+ // fall through
+ case R_SKIP:
+ // Move on to next file
+ skip( (*it).uSource );
+ m_processedSize += (*it).size;
+ files.remove( it );
+ m_processedFiles++;
+ break;
+ case R_OVERWRITE_ALL:
+ m_bOverwriteAll = true;
+ break;
+ case R_OVERWRITE:
+ // Add to overwrite list, so that copyNextFile knows to overwrite
+ m_overwriteList.append( (*it).uDest.path() );
+ break;
+ default:
+ assert( 0 );
+ }
+ state = STATE_COPYING_FILES;
+ //emit processedFiles( this, m_processedFiles );
+ copyNextFile();
+}
+
+void CopyJob::copyNextFile()
+{
+ bool bCopyFile = false;
+ //kdDebug(7007) << "CopyJob::copyNextFile()" << endl;
+ // Take the first file in the list
+ TQValueList<CopyInfo>::Iterator it = files.begin();
+ // Is this URL on the skip list ?
+ while (it != files.end() && !bCopyFile)
+ {
+ const TQString destFile = (*it).uDest.path();
+ bCopyFile = !shouldSkip( destFile );
+ if ( !bCopyFile ) {
+ files.remove( it );
+ it = files.begin();
+ }
+ }
+
+ if (bCopyFile) // any file to create, finally ?
+ {
+ // Do we set overwrite ?
+ bool bOverwrite;
+ const TQString destFile = (*it).uDest.path();
+ kdDebug(7007) << "copying " << destFile << endl;
+ if ( (*it).uDest == (*it).uSource )
+ bOverwrite = false;
+ else
+ bOverwrite = shouldOverwrite( destFile );
+
+ m_bCurrentOperationIsLink = false;
+ TDEIO::Job * newjob = 0L;
+ if ( m_mode == Link )
+ {
+ //kdDebug(7007) << "Linking" << endl;
+ if (
+ ((*it).uSource.protocol() == (*it).uDest.protocol()) &&
+ ((*it).uSource.host() == (*it).uDest.host()) &&
+ ((*it).uSource.port() == (*it).uDest.port()) &&
+ ((*it).uSource.user() == (*it).uDest.user()) &&
+ ((*it).uSource.pass() == (*it).uDest.pass()) )
+ {
+ // This is the case of creating a real symlink
+ TDEIO::SimpleJob *newJob = TDEIO::symlink( (*it).uSource.path(), (*it).uDest, bOverwrite, false /*no GUI*/ );
+ newjob = newJob;
+ Scheduler::scheduleJob(newJob);
+ //kdDebug(7007) << "CopyJob::copyNextFile : Linking target=" << (*it).uSource.path() << " link=" << (*it).uDest << endl;
+ //emit linking( this, (*it).uSource.path(), (*it).uDest );
+ m_bCurrentOperationIsLink = true;
+ m_currentSrcURL=(*it).uSource;
+ m_currentDestURL=(*it).uDest;
+ d->m_bURLDirty = true;
+ //Observer::self()->slotCopying( this, (*it).uSource, (*it).uDest ); // should be slotLinking perhaps
+ } else {
+ //kdDebug(7007) << "CopyJob::copyNextFile : Linking URL=" << (*it).uSource << " link=" << (*it).uDest << endl;
+ if ( (*it).uDest.isLocalFile() )
+ {
+ bool devicesOk=false;
+
+ // if the source is a devices url, handle it a littlebit special
+ if ((*it).uSource.protocol()==TQString::fromLatin1("devices"))
+ {
+ TQByteArray data;
+ TQByteArray param;
+ TQCString retType;
+ TQDataStream streamout(param,IO_WriteOnly);
+ streamout<<(*it).uSource;
+ streamout<<(*it).uDest;
+ if ( kapp && kapp->dcopClient()->call( "kded",
+ "mountwatcher", "createLink(KURL, KURL)", param,retType,data,false ) )
+ {
+ TQDataStream streamin(data,IO_ReadOnly);
+ streamin>>devicesOk;
+ }
+ if (devicesOk)
+ {
+ files.remove( it );
+ m_processedFiles++;
+ //emit processedFiles( this, m_processedFiles );
+ copyNextFile();
+ return;
+ }
+ }
+
+ if (!devicesOk)
+ {
+ TQString path = (*it).uDest.path();
+ //kdDebug(7007) << "CopyJob::copyNextFile path=" << path << endl;
+ TQFile f( path );
+ if ( f.open( IO_ReadWrite ) )
+ {
+ f.close();
+ KSimpleConfig config( path );
+ config.setDesktopGroup();
+ KURL url = (*it).uSource;
+ url.setPass( "" );
+ config.writePathEntry( TQString::fromLatin1("URL"), url.url() );
+ config.writeEntry( TQString::fromLatin1("Name"), url.url() );
+ config.writeEntry( TQString::fromLatin1("Type"), TQString::fromLatin1("Link") );
+ TQString protocol = (*it).uSource.protocol();
+ if ( protocol == TQString::fromLatin1("ftp") )
+ config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("ftp") );
+ else if ( protocol == TQString::fromLatin1("http") )
+ config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("www") );
+ else if ( protocol == TQString::fromLatin1("info") )
+ config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("info") );
+ else if ( protocol == TQString::fromLatin1("mailto") ) // sven:
+ config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("kmail") ); // added mailto: support
+ else
+ config.writeEntry( TQString::fromLatin1("Icon"), TQString::fromLatin1("unknown") );
+ config.sync();
+ files.remove( it );
+ m_processedFiles++;
+ //emit processedFiles( this, m_processedFiles );
+ copyNextFile();
+ return;
+ }
+ else
+ {
+ kdDebug(7007) << "CopyJob::copyNextFile ERR_CANNOT_OPEN_FOR_WRITING" << endl;
+ m_error = ERR_CANNOT_OPEN_FOR_WRITING;
+ m_errorText = (*it).uDest.path();
+ emitResult();
+ return;
+ }
+ }
+ } else {
+ // Todo: not show "link" on remote dirs if the src urls are not from the same protocol+host+...
+ m_error = ERR_CANNOT_SYMLINK;
+ m_errorText = (*it).uDest.prettyURL();
+ emitResult();
+ return;
+ }
+ }
+ }
+ else if ( !(*it).linkDest.isEmpty() &&
+ ((*it).uSource.protocol() == (*it).uDest.protocol()) &&
+ ((*it).uSource.host() == (*it).uDest.host()) &&
+ ((*it).uSource.port() == (*it).uDest.port()) &&
+ ((*it).uSource.user() == (*it).uDest.user()) &&
+ ((*it).uSource.pass() == (*it).uDest.pass()))
+ // Copying a symlink - only on the same protocol/host/etc. (#5601, downloading an FTP file through its link),
+ {
+ TDEIO::SimpleJob *newJob = TDEIO::symlink( (*it).linkDest, (*it).uDest, bOverwrite, false /*no GUI*/ );
+ Scheduler::scheduleJob(newJob);
+ newjob = newJob;
+ //kdDebug(7007) << "CopyJob::copyNextFile : Linking target=" << (*it).linkDest << " link=" << (*it).uDest << endl;
+ //emit linking( this, (*it).linkDest, (*it).uDest );
+ m_currentSrcURL=(*it).linkDest;
+ m_currentDestURL=(*it).uDest;
+ d->m_bURLDirty = true;
+ //Observer::self()->slotCopying( this, (*it).linkDest, (*it).uDest ); // should be slotLinking perhaps
+ m_bCurrentOperationIsLink = true;
+ // NOTE: if we are moving stuff, the deletion of the source will be done in slotResultCopyingFiles
+ } else if (m_mode == Move) // Moving a file
+ {
+ TDEIO::FileCopyJob * moveJob = TDEIO::file_move( (*it).uSource, (*it).uDest, (*it).permissions, bOverwrite, false, false/*no GUI*/ );
+ moveJob->setSourceSize64( (*it).size );
+ newjob = moveJob;
+ //kdDebug(7007) << "CopyJob::copyNextFile : Moving " << (*it).uSource << " to " << (*it).uDest << endl;
+ //emit moving( this, (*it).uSource, (*it).uDest );
+ m_currentSrcURL=(*it).uSource;
+ m_currentDestURL=(*it).uDest;
+ d->m_bURLDirty = true;
+ //Observer::self()->slotMoving( this, (*it).uSource, (*it).uDest );
+ }
+ else // Copying a file
+ {
+ // If source isn't local and target is local, we ignore the original permissions
+ // Otherwise, files downloaded from HTTP end up with -r--r--r--
+ bool remoteSource = !KProtocolInfo::supportsListing((*it).uSource);
+ int permissions = (*it).permissions;
+ if ( d->m_defaultPermissions || ( remoteSource && (*it).uDest.isLocalFile() ) )
+ permissions = -1;
+ TDEIO::FileCopyJob * copyJob = TDEIO::file_copy( (*it).uSource, (*it).uDest, permissions, bOverwrite, false, false/*no GUI*/ );
+ copyJob->setParentJob( this ); // in case of rename dialog
+ copyJob->setSourceSize64( (*it).size );
+ copyJob->setModificationTime( (*it).mtime );
+ newjob = copyJob;
+ //kdDebug(7007) << "CopyJob::copyNextFile : Copying " << (*it).uSource << " to " << (*it).uDest << endl;
+ m_currentSrcURL=(*it).uSource;
+ m_currentDestURL=(*it).uDest;
+ d->m_bURLDirty = true;
+ }
+ addSubjob(newjob);
+ connect( newjob, TQT_SIGNAL( processedSize( TDEIO::Job*, TDEIO::filesize_t ) ),
+ this, TQT_SLOT( slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
+ connect( newjob, TQT_SIGNAL( totalSize( TDEIO::Job*, TDEIO::filesize_t ) ),
+ this, TQT_SLOT( slotTotalSize( TDEIO::Job*, TDEIO::filesize_t ) ) );
+ }
+ else
+ {
+ // We're done
+ //kdDebug(7007) << "copyNextFile finished" << endl;
+ deleteNextDir();
+ }
+}
+
+void CopyJob::deleteNextDir()
+{
+ if ( m_mode == Move && !dirsToRemove.isEmpty() ) // some dirs to delete ?
+ {
+ state = STATE_DELETING_DIRS;
+ d->m_bURLDirty = true;
+ // Take first dir to delete out of list - last ones first !
+ KURL::List::Iterator it = dirsToRemove.fromLast();
+ SimpleJob *job = TDEIO::rmdir( *it );
+ Scheduler::scheduleJob(job);
+ dirsToRemove.remove(it);
+ addSubjob( job );
+ }
+ else
+ {
+ // This step is done, move on
+ setNextDirAttribute();
+ }
+}
+
+void CopyJob::setNextDirAttribute()
+{
+ if ( !d->m_directoriesCopied.isEmpty() )
+ {
+ state = STATE_SETTING_DIR_ATTRIBUTES;
+#ifdef Q_OS_UNIX
+ // TODO KDE4: this should use a SlaveBase method, but we have none yet in KDE3.
+ TQValueList<CopyInfo>::Iterator it = d->m_directoriesCopied.begin();
+ for ( ; it != d->m_directoriesCopied.end() ; ++it ) {
+ const KURL& url = (*it).uDest;
+ if ( url.isLocalFile() && (*it).mtime != (time_t)-1 ) {
+ const TQCString path = TQFile::encodeName( url.path() );
+ KDE_struct_stat statbuf;
+ if (KDE_lstat(path, &statbuf) == 0) {
+ struct utimbuf utbuf;
+ utbuf.actime = statbuf.st_atime; // access time, unchanged
+ utbuf.modtime = (*it).mtime; // modification time
+ utime( path, &utbuf );
+ }
+
+ }
+ }
+#endif
+ d->m_directoriesCopied.clear();
+ }
+
+ // No "else" here, since the above is a simple sync loop
+
+ {
+ // Finished - tell the world
+ if ( !m_bOnlyRenames )
+ {
+ KDirNotify_stub allDirNotify("*", "KDirNotify*");
+ KURL url( d->m_globalDest );
+ if ( d->m_globalDestinationState != DEST_IS_DIR || m_asMethod )
+ url.setPath( url.directory() );
+ //kdDebug(7007) << "KDirNotify'ing FilesAdded " << url << endl;
+ allDirNotify.FilesAdded( url );
+
+ if ( m_mode == Move && !m_srcList.isEmpty() ) {
+ //kdDebug(7007) << "KDirNotify'ing FilesRemoved " << m_srcList.toStringList() << endl;
+ allDirNotify.FilesRemoved( m_srcList );
+ }
+ }
+ if (m_reportTimer)
+ m_reportTimer->stop();
+ --m_processedFiles; // undo the "start at 1" hack
+ slotReport(); // display final numbers, important if progress dialog stays up
+
+ emitResult();
+ }
+}
+
+void CopyJob::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size )
+{
+ //kdDebug(7007) << "CopyJob::slotProcessedSize " << data_size << endl;
+ m_fileProcessedSize = data_size;
+ setProcessedSize(m_processedSize + m_fileProcessedSize);
+
+ if ( m_processedSize + m_fileProcessedSize > m_totalSize )
+ {
+ m_totalSize = m_processedSize + m_fileProcessedSize;
+ //kdDebug(7007) << "Adjusting m_totalSize to " << m_totalSize << endl;
+ emit totalSize( this, m_totalSize ); // safety
+ }
+ //kdDebug(7007) << "emit processedSize " << (unsigned long) (m_processedSize + m_fileProcessedSize) << endl;
+ emit processedSize( this, m_processedSize + m_fileProcessedSize );
+ emitPercent( m_processedSize + m_fileProcessedSize, m_totalSize );
+}
+
+void CopyJob::slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size )
+{
+ //kdDebug(7007) << "slotTotalSize: " << size << endl;
+ // Special case for copying a single file
+ // This is because some protocols don't implement stat properly
+ // (e.g. HTTP), and don't give us a size in some cases (redirection)
+ // so we'd rather rely on the size given for the transfer
+ if ( m_bSingleFileCopy && size > m_totalSize)
+ {
+ //kdDebug(7007) << "slotTotalSize: updating totalsize to " << size << endl;
+ m_totalSize = size;
+ emit totalSize( this, size );
+ }
+}
+
+void CopyJob::slotResultDeletingDirs( Job * job )
+{
+ if (job->error())
+ {
+ // Couldn't remove directory. Well, perhaps it's not empty
+ // because the user pressed Skip for a given file in it.
+ // Let's not display "Could not remove dir ..." for each of those dir !
+ }
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() );
+ deleteNextDir();
+}
+
+#if 0 // TODO KDE4
+void CopyJob::slotResultSettingDirAttributes( Job * job )
+{
+ if (job->error())
+ {
+ // Couldn't set directory attributes. Ignore the error, it can happen
+ // with inferior file systems like VFAT.
+ // Let's not display warnings for each dir like "cp -a" does.
+ }
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() );
+ setNextDirAttribute();
+}
+#endif
+
+void CopyJob::slotResultRenaming( Job* job )
+{
+ int err = job->error();
+ const TQString errText = job->errorText();
+ removeSubjob( job, true, false ); // merge metadata
+ assert ( subjobs.isEmpty() );
+ // Determine dest again
+ KURL dest = m_dest;
+ if ( destinationState == DEST_IS_DIR && !m_asMethod )
+ dest.addPath( m_currentSrcURL.fileName() );
+ if ( err )
+ {
+ // Direct renaming didn't work. Try renaming to a temp name,
+ // this can help e.g. when renaming 'a' to 'A' on a VFAT partition.
+ // In that case it's the _same_ dir, we don't want to copy+del (data loss!)
+ if ( m_currentSrcURL.isLocalFile() && m_currentSrcURL.url(-1) != dest.url(-1) &&
+ m_currentSrcURL.url(-1).lower() == dest.url(-1).lower() &&
+ ( err == ERR_FILE_ALREADY_EXIST ||
+ err == ERR_DIR_ALREADY_EXIST ||
+ err == ERR_IDENTICAL_FILES ) )
+ {
+ kdDebug(7007) << "Couldn't rename directly, dest already exists. Detected special case of lower/uppercase renaming in same dir, try with 2 rename calls" << endl;
+ TQCString _src( TQFile::encodeName(m_currentSrcURL.path()) );
+ TQCString _dest( TQFile::encodeName(dest.path()) );
+ KTempFile tmpFile( m_currentSrcURL.directory(false) );
+ TQCString _tmp( TQFile::encodeName(tmpFile.name()) );
+ kdDebug(7007) << "CopyJob::slotResult KTempFile status:" << tmpFile.status() << " using " << _tmp << " as intermediary" << endl;
+ tmpFile.unlink();
+ if ( ::rename( _src, _tmp ) == 0 )
+ {
+ if ( !TQFile::exists( _dest ) && ::rename( _tmp, _dest ) == 0 )
+ {
+ kdDebug(7007) << "Success." << endl;
+ err = 0;
+ }
+ else
+ {
+ // Revert back to original name!
+ if ( ::rename( _tmp, _src ) != 0 ) {
+ kdError(7007) << "Couldn't rename " << tmpFile.name() << " back to " << _src << " !" << endl;
+ // Severe error, abort
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+ }
+ }
+ }
+ }
+ if ( err )
+ {
+ // This code is similar to CopyJob::slotResultConflictCopyingFiles
+ // but here it's about the base src url being moved/renamed
+ // (*m_currentStatSrc) and its dest (m_dest), not about a single file.
+ // It also means we already stated the dest, here.
+ // On the other hand we haven't stated the src yet (we skipped doing it
+ // to save time, since it's not necessary to rename directly!)...
+
+ Q_ASSERT( m_currentSrcURL == *m_currentStatSrc );
+
+ // Existing dest?
+ if ( ( err == ERR_DIR_ALREADY_EXIST ||
+ err == ERR_FILE_ALREADY_EXIST ||
+ err == ERR_IDENTICAL_FILES )
+ && isInteractive() )
+ {
+ if (m_reportTimer)
+ m_reportTimer->stop();
+
+ // Should we skip automatically ?
+ if ( m_bAutoSkip ) {
+ // Move on to next file
+ skipSrc();
+ return;
+ } else if ( m_bOverwriteAll ) {
+ ; // nothing to do, stat+copy+del will overwrite
+ } else {
+ TQString newPath;
+ // If src==dest, use "overwrite-itself"
+ RenameDlg_Mode mode = (RenameDlg_Mode)
+ ( ( m_currentSrcURL == dest ) ? M_OVERWRITE_ITSELF : M_OVERWRITE );
+
+ if ( m_srcList.count() > 1 )
+ mode = (RenameDlg_Mode) ( mode | M_MULTI | M_SKIP );
+ else
+ mode = (RenameDlg_Mode) ( mode | M_SINGLE );
+
+ // we lack mtime info for both the src (not stated)
+ // and the dest (stated but this info wasn't stored)
+ // Let's do it for local files, at least
+ TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1;
+ TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1;
+ time_t ctimeSrc = (time_t) -1;
+ time_t ctimeDest = (time_t) -1;
+ time_t mtimeSrc = (time_t) -1;
+ time_t mtimeDest = (time_t) -1;
+
+ KDE_struct_stat stat_buf;
+ if ( m_currentSrcURL.isLocalFile() &&
+ KDE_stat(TQFile::encodeName(m_currentSrcURL.path()), &stat_buf) == 0 ) {
+ sizeSrc = stat_buf.st_size;
+ ctimeSrc = stat_buf.st_ctime;
+ mtimeSrc = stat_buf.st_mtime;
+ }
+ if ( dest.isLocalFile() &&
+ KDE_stat(TQFile::encodeName(dest.path()), &stat_buf) == 0 ) {
+ sizeDest = stat_buf.st_size;
+ ctimeDest = stat_buf.st_ctime;
+ mtimeDest = stat_buf.st_mtime;
+ }
+
+ RenameDlg_Result r = Observer::self()->open_RenameDlg(
+ this,
+ err != ERR_DIR_ALREADY_EXIST ? i18n("File Already Exists") : i18n("Already Exists as Folder"),
+ m_currentSrcURL.url(),
+ dest.url(),
+ mode, newPath,
+ sizeSrc, sizeDest,
+ ctimeSrc, ctimeDest,
+ mtimeSrc, mtimeDest );
+ if (m_reportTimer)
+ m_reportTimer->start(REPORT_TIMEOUT,false);
+
+ switch ( r )
+ {
+ case R_CANCEL:
+ {
+ m_error = ERR_USER_CANCELED;
+ emitResult();
+ return;
+ }
+ case R_RENAME:
+ {
+ // Set m_dest to the chosen destination
+ // This is only for this src url; the next one will revert to d->m_globalDest
+ m_dest.setPath( newPath );
+ TDEIO::Job* job = TDEIO::stat( m_dest, false, 2, false );
+ state = STATE_STATING;
+ destinationState = DEST_NOT_STATED;
+ addSubjob(job);
+ return;
+ }
+ case R_AUTO_SKIP:
+ m_bAutoSkip = true;
+ // fall through
+ case R_SKIP:
+ // Move on to next file
+ skipSrc();
+ return;
+ case R_OVERWRITE_ALL:
+ m_bOverwriteAll = true;
+ break;
+ case R_OVERWRITE:
+ // Add to overwrite list
+ // Note that we add dest, not m_dest.
+ // This ensures that when moving several urls into a dir (m_dest),
+ // we only overwrite for the current one, not for all.
+ // When renaming a single file (m_asMethod), it makes no difference.
+ kdDebug(7007) << "adding to overwrite list: " << dest.path() << endl;
+ m_overwriteList.append( dest.path() );
+ break;
+ default:
+ //assert( 0 );
+ break;
+ }
+ }
+ } else if ( err != TDEIO::ERR_UNSUPPORTED_ACTION ) {
+ kdDebug(7007) << "Couldn't rename " << m_currentSrcURL << " to " << dest << ", aborting" << endl;
+ m_error = err;
+ m_errorText = errText;
+ emitResult();
+ return;
+ }
+ kdDebug(7007) << "Couldn't rename " << m_currentSrcURL << " to " << dest << ", reverting to normal way, starting with stat" << endl;
+ //kdDebug(7007) << "TDEIO::stat on " << m_currentSrcURL << endl;
+ TDEIO::Job* job = TDEIO::stat( m_currentSrcURL, true, 2, false );
+ state = STATE_STATING;
+ addSubjob(job);
+ m_bOnlyRenames = false;
+ }
+ else
+ {
+ //kdDebug(7007) << "Renaming succeeded, move on" << endl;
+ emit copyingDone( this, *m_currentStatSrc, dest, true, true );
+ statNextSrc();
+ }
+}
+
+void CopyJob::slotResult( Job *job )
+{
+ //kdDebug(7007) << "CopyJob::slotResult() state=" << (int) state << endl;
+ // In each case, what we have to do is :
+ // 1 - check for errors and treat them
+ // 2 - subjobs.remove(job);
+ // 3 - decide what to do next
+
+ switch ( state ) {
+ case STATE_STATING: // We were trying to stat a src url or the dest
+ slotResultStating( job );
+ break;
+ case STATE_RENAMING: // We were trying to do a direct renaming, before even stat'ing
+ {
+ slotResultRenaming( job );
+ break;
+ }
+ case STATE_LISTING: // recursive listing finished
+ //kdDebug(7007) << "totalSize: " << (unsigned int) m_totalSize << " files: " << files.count() << " dirs: " << dirs.count() << endl;
+ // Was there an error ?
+ if (job->error())
+ {
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+
+ subjobs.remove( job );
+ assert ( subjobs.isEmpty() );
+
+ statNextSrc();
+ break;
+ case STATE_CREATING_DIRS:
+ slotResultCreatingDirs( job );
+ break;
+ case STATE_CONFLICT_CREATING_DIRS:
+ slotResultConflictCreatingDirs( job );
+ break;
+ case STATE_COPYING_FILES:
+ slotResultCopyingFiles( job );
+ break;
+ case STATE_CONFLICT_COPYING_FILES:
+ slotResultConflictCopyingFiles( job );
+ break;
+ case STATE_DELETING_DIRS:
+ slotResultDeletingDirs( job );
+ break;
+ case STATE_SETTING_DIR_ATTRIBUTES: // TODO KDE4
+ assert( 0 );
+ //slotResultSettingDirAttributes( job );
+ break;
+ default:
+ assert( 0 );
+ }
+}
+
+void TDEIO::CopyJob::setDefaultPermissions( bool b )
+{
+ d->m_defaultPermissions = b;
+}
+
+// KDE4: remove
+void TDEIO::CopyJob::setInteractive( bool b )
+{
+ Job::setInteractive( b );
+}
+
+CopyJob *TDEIO::copy(const KURL& src, const KURL& dest, bool showProgressInfo )
+{
+ //kdDebug(7007) << "TDEIO::copy src=" << src << " dest=" << dest << endl;
+ KURL::List srcList;
+ srcList.append( src );
+ return new CopyJob( srcList, dest, CopyJob::Copy, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::copyAs(const KURL& src, const KURL& dest, bool showProgressInfo )
+{
+ //kdDebug(7007) << "TDEIO::copyAs src=" << src << " dest=" << dest << endl;
+ KURL::List srcList;
+ srcList.append( src );
+ return new CopyJob( srcList, dest, CopyJob::Copy, true, showProgressInfo );
+}
+
+CopyJob *TDEIO::copy( const KURL::List& src, const KURL& dest, bool showProgressInfo )
+{
+ //kdDebug(7007) << src << " " << dest << endl;
+ return new CopyJob( src, dest, CopyJob::Copy, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::move(const KURL& src, const KURL& dest, bool showProgressInfo )
+{
+ //kdDebug(7007) << src << " " << dest << endl;
+ KURL::List srcList;
+ srcList.append( src );
+ return new CopyJob( srcList, dest, CopyJob::Move, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::moveAs(const KURL& src, const KURL& dest, bool showProgressInfo )
+{
+ //kdDebug(7007) << src << " " << dest << endl;
+ KURL::List srcList;
+ srcList.append( src );
+ return new CopyJob( srcList, dest, CopyJob::Move, true, showProgressInfo );
+}
+
+CopyJob *TDEIO::move( const KURL::List& src, const KURL& dest, bool showProgressInfo )
+{
+ //kdDebug(7007) << src << " " << dest << endl;
+ return new CopyJob( src, dest, CopyJob::Move, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::link(const KURL& src, const KURL& destDir, bool showProgressInfo )
+{
+ KURL::List srcList;
+ srcList.append( src );
+ return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::link(const KURL::List& srcList, const KURL& destDir, bool showProgressInfo )
+{
+ return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::linkAs(const KURL& src, const KURL& destDir, bool showProgressInfo )
+{
+ KURL::List srcList;
+ srcList.append( src );
+ return new CopyJob( srcList, destDir, CopyJob::Link, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::trash(const KURL& src, bool showProgressInfo )
+{
+ KURL::List srcList;
+ srcList.append( src );
+ return new CopyJob( srcList, KURL( "trash:/" ), CopyJob::Move, false, showProgressInfo );
+}
+
+CopyJob *TDEIO::trash(const KURL::List& srcList, bool showProgressInfo )
+{
+ return new CopyJob( srcList, KURL( "trash:/" ), CopyJob::Move, false, showProgressInfo );
+}
+
+//////////
+
+DeleteJob::DeleteJob( const KURL::List& src, bool /*shred*/, bool showProgressInfo )
+: Job(showProgressInfo), m_totalSize( 0 ), m_processedSize( 0 ), m_fileProcessedSize( 0 ),
+ m_processedFiles( 0 ), m_processedDirs( 0 ), m_totalFilesDirs( 0 ),
+ m_srcList(src), m_currentStat(m_srcList.begin()), m_reportTimer(0)
+{
+ if ( showProgressInfo ) {
+
+ connect( this, TQT_SIGNAL( totalFiles( TDEIO::Job*, unsigned long ) ),
+ Observer::self(), TQT_SLOT( slotTotalFiles( TDEIO::Job*, unsigned long ) ) );
+
+ connect( this, TQT_SIGNAL( totalDirs( TDEIO::Job*, unsigned long ) ),
+ Observer::self(), TQT_SLOT( slotTotalDirs( TDEIO::Job*, unsigned long ) ) );
+
+ // See slotReport
+ /*connect( this, TQT_SIGNAL( processedFiles( TDEIO::Job*, unsigned long ) ),
+ m_observer, TQT_SLOT( slotProcessedFiles( TDEIO::Job*, unsigned long ) ) );
+
+ connect( this, TQT_SIGNAL( processedDirs( TDEIO::Job*, unsigned long ) ),
+ m_observer, TQT_SLOT( slotProcessedDirs( TDEIO::Job*, unsigned long ) ) );
+
+ connect( this, TQT_SIGNAL( deleting( TDEIO::Job*, const KURL& ) ),
+ m_observer, TQT_SLOT( slotDeleting( TDEIO::Job*, const KURL& ) ) );*/
+
+ m_reportTimer=new TQTimer(this);
+ connect(m_reportTimer,TQT_SIGNAL(timeout()),this,TQT_SLOT(slotReport()));
+ //this will update the report dialog with 5 Hz, I think this is fast enough, aleXXX
+ m_reportTimer->start(REPORT_TIMEOUT,false);
+ }
+
+ TQTimer::singleShot(0, this, TQT_SLOT(slotStart()));
+}
+
+void DeleteJob::slotStart()
+{
+ statNextSrc();
+}
+
+//this is called often, so calling the functions
+//from Observer here directly might improve the performance a little bit
+//aleXXX
+void DeleteJob::slotReport()
+{
+ if (m_progressId==0)
+ return;
+
+ Observer * observer = Observer::self();
+
+ emit deleting( this, m_currentURL );
+ observer->slotDeleting(this,m_currentURL);
+
+ switch( state ) {
+ case STATE_STATING:
+ case STATE_LISTING:
+ emit totalSize( this, m_totalSize );
+ emit totalFiles( this, files.count() );
+ emit totalDirs( this, dirs.count() );
+ break;
+ case STATE_DELETING_DIRS:
+ emit processedDirs( this, m_processedDirs );
+ observer->slotProcessedDirs(this,m_processedDirs);
+ emitPercent( m_processedFiles + m_processedDirs, m_totalFilesDirs );
+ break;
+ case STATE_DELETING_FILES:
+ observer->slotProcessedFiles(this,m_processedFiles);
+ emit processedFiles( this, m_processedFiles );
+ emitPercent( m_processedFiles, m_totalFilesDirs );
+ break;
+ }
+}
+
+
+void DeleteJob::slotEntries(TDEIO::Job* job, const UDSEntryList& list)
+{
+ UDSEntryListConstIterator it = list.begin();
+ UDSEntryListConstIterator end = list.end();
+ for (; it != end; ++it)
+ {
+ UDSEntry::ConstIterator it2 = (*it).begin();
+ bool bDir = false;
+ bool bLink = false;
+ TQString displayName;
+ KURL url;
+ int atomsFound(0);
+ for( ; it2 != (*it).end(); it2++ )
+ {
+ switch ((*it2).m_uds)
+ {
+ case UDS_FILE_TYPE:
+ bDir = S_ISDIR((*it2).m_long);
+ atomsFound++;
+ break;
+ case UDS_NAME:
+ displayName = (*it2).m_str;
+ atomsFound++;
+ break;
+ case UDS_URL:
+ url = KURL((*it2).m_str);
+ atomsFound++;
+ break;
+ case UDS_LINK_DEST:
+ bLink = !(*it2).m_str.isEmpty();
+ atomsFound++;
+ break;
+ case UDS_SIZE:
+ m_totalSize += (TDEIO::filesize_t)((*it2).m_long);
+ atomsFound++;
+ break;
+ default:
+ break;
+ }
+ if (atomsFound==5) break;
+ }
+ assert(!displayName.isEmpty());
+ if (displayName != ".." && displayName != ".")
+ {
+ if( url.isEmpty() ) {
+ url = ((SimpleJob *)job)->url(); // assumed to be a dir
+ url.addPath( displayName );
+ }
+ //kdDebug(7007) << "DeleteJob::slotEntries " << displayName << " (" << url << ")" << endl;
+ if ( bLink )
+ symlinks.append( url );
+ else if ( bDir )
+ dirs.append( url );
+ else
+ files.append( url );
+ }
+ }
+}
+
+
+void DeleteJob::statNextSrc()
+{
+ //kdDebug(7007) << "statNextSrc" << endl;
+ if ( m_currentStat != m_srcList.end() )
+ {
+ m_currentURL = (*m_currentStat);
+
+ // if the file system doesn't support deleting, we do not even stat
+ if (!KProtocolInfo::supportsDeleting(m_currentURL)) {
+ TQGuardedPtr<DeleteJob> that = this;
+ ++m_currentStat;
+ if (isInteractive())
+ KMessageBox::information( 0, buildErrorString(ERR_CANNOT_DELETE, m_currentURL.prettyURL()));
+ if (that)
+ statNextSrc();
+ return;
+ }
+ // Stat it
+ state = STATE_STATING;
+ TDEIO::SimpleJob * job = TDEIO::stat( m_currentURL, true, 1, false );
+ Scheduler::scheduleJob(job);
+ //kdDebug(7007) << "TDEIO::stat (DeleteJob) " << m_currentURL << endl;
+ addSubjob(job);
+ //if ( m_progressId ) // Did we get an ID from the observer ?
+ // Observer::self()->slotDeleting( this, *it ); // show asap
+ } else
+ {
+ m_totalFilesDirs = files.count()+symlinks.count() + dirs.count();
+ slotReport();
+ // Now we know which dirs hold the files we're going to delete.
+ // To speed things up and prevent double-notification, we disable KDirWatch
+ // on those dirs temporarily (using KDirWatch::self, that's the instanced
+ // used by e.g. kdirlister).
+ for ( TQStringList::Iterator it = m_parentDirs.begin() ; it != m_parentDirs.end() ; ++it )
+ KDirWatch::self()->stopDirScan( *it );
+ state = STATE_DELETING_FILES;
+ deleteNextFile();
+ }
+}
+
+void DeleteJob::deleteNextFile()
+{
+ //kdDebug(7007) << "deleteNextFile" << endl;
+ if ( !files.isEmpty() || !symlinks.isEmpty() )
+ {
+ SimpleJob *job;
+ do {
+ // Take first file to delete out of list
+ KURL::List::Iterator it = files.begin();
+ bool isLink = false;
+ if ( it == files.end() ) // No more files
+ {
+ it = symlinks.begin(); // Pick up a symlink to delete
+ isLink = true;
+ }
+ // Normal deletion
+ // If local file, try do it directly
+ if ( (*it).isLocalFile() && unlink( TQFile::encodeName((*it).path()) ) == 0 ) {
+ //kdDebug(7007) << "DeleteJob deleted " << (*it).path() << endl;
+ job = 0;
+ m_processedFiles++;
+ if ( m_processedFiles % 300 == 0 || m_totalFilesDirs < 300) { // update progress info every 300 files
+ m_currentURL = *it;
+ slotReport();
+ }
+ } else
+ { // if remote - or if unlink() failed (we'll use the job's error handling in that case)
+ job = TDEIO::file_delete( *it, false /*no GUI*/);
+ Scheduler::scheduleJob(job);
+ m_currentURL=(*it);
+ }
+ if ( isLink )
+ symlinks.remove(it);
+ else
+ files.remove(it);
+ if ( job ) {
+ addSubjob(job);
+ return;
+ }
+ // loop only if direct deletion worked (job=0) and there is something else to delete
+ } while (!job && (!files.isEmpty() || !symlinks.isEmpty()));
+ }
+ state = STATE_DELETING_DIRS;
+ deleteNextDir();
+}
+
+void DeleteJob::deleteNextDir()
+{
+ if ( !dirs.isEmpty() ) // some dirs to delete ?
+ {
+ do {
+ // Take first dir to delete out of list - last ones first !
+ KURL::List::Iterator it = dirs.fromLast();
+ // If local dir, try to rmdir it directly
+ if ( (*it).isLocalFile() && ::rmdir( TQFile::encodeName((*it).path()) ) == 0 ) {
+
+ m_processedDirs++;
+ if ( m_processedDirs % 100 == 0 ) { // update progress info every 100 dirs
+ m_currentURL = *it;
+ slotReport();
+ }
+ } else {
+ SimpleJob* job;
+ if ( KProtocolInfo::canDeleteRecursive( *it ) ) {
+ // If the ioslave supports recursive deletion of a directory, then
+ // we only need to send a single CMD_DEL command, so we use file_delete :)
+ job = TDEIO::file_delete( *it, false /*no gui*/ );
+ } else {
+ job = TDEIO::rmdir( *it );
+ }
+ Scheduler::scheduleJob(job);
+ dirs.remove(it);
+ addSubjob( job );
+ return;
+ }
+ dirs.remove(it);
+ } while ( !dirs.isEmpty() );
+ }
+
+ // Re-enable watching on the dirs that held the deleted files
+ for ( TQStringList::Iterator it = m_parentDirs.begin() ; it != m_parentDirs.end() ; ++it )
+ KDirWatch::self()->restartDirScan( *it );
+
+ // Finished - tell the world
+ if ( !m_srcList.isEmpty() )
+ {
+ KDirNotify_stub allDirNotify("*", "KDirNotify*");
+ //kdDebug(7007) << "KDirNotify'ing FilesRemoved " << m_srcList.toStringList() << endl;
+ allDirNotify.FilesRemoved( m_srcList );
+ }
+ if (m_reportTimer!=0)
+ m_reportTimer->stop();
+ emitResult();
+}
+
+void DeleteJob::slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size )
+{
+ // Note: this is the same implementation as CopyJob::slotProcessedSize but
+ // it's different from FileCopyJob::slotProcessedSize - which is why this
+ // is not in Job.
+
+ m_fileProcessedSize = data_size;
+ setProcessedSize(m_processedSize + m_fileProcessedSize);
+
+ //kdDebug(7007) << "DeleteJob::slotProcessedSize " << (unsigned int) (m_processedSize + m_fileProcessedSize) << endl;
+
+ emit processedSize( this, m_processedSize + m_fileProcessedSize );
+
+ // calculate percents
+ unsigned long ipercent = m_percent;
+
+ if ( m_totalSize == 0 )
+ m_percent = 100;
+ else
+ m_percent = (unsigned long)(( (float)(m_processedSize + m_fileProcessedSize) / (float)m_totalSize ) * 100.0);
+
+ if ( m_percent > ipercent )
+ {
+ emit percent( this, m_percent );
+ //kdDebug(7007) << "DeleteJob::slotProcessedSize - percent = " << (unsigned int) m_percent << endl;
+ }
+
+}
+
+void DeleteJob::slotResult( Job *job )
+{
+ switch ( state )
+ {
+ case STATE_STATING:
+ {
+ // Was there an error while stating ?
+ if (job->error() )
+ {
+ // Probably : doesn't exist
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+
+ // Is it a file or a dir ?
+ UDSEntry entry = ((StatJob*)job)->statResult();
+ bool bDir = false;
+ bool bLink = false;
+ TDEIO::filesize_t size = (TDEIO::filesize_t)-1;
+ UDSEntry::ConstIterator it2 = entry.begin();
+ int atomsFound(0);
+ for( ; it2 != entry.end(); it2++ )
+ {
+ if ( ((*it2).m_uds) == UDS_FILE_TYPE )
+ {
+ bDir = S_ISDIR( (mode_t)(*it2).m_long );
+ atomsFound++;
+ }
+ else if ( ((*it2).m_uds) == UDS_LINK_DEST )
+ {
+ bLink = !((*it2).m_str.isEmpty());
+ atomsFound++;
+ }
+ else if ( ((*it2).m_uds) == UDS_SIZE )
+ {
+ size = (*it2).m_long;
+ atomsFound++;
+ }
+ if (atomsFound==3) break;
+ }
+
+ KURL url = ((SimpleJob*)job)->url();
+
+ subjobs.remove( job );
+ assert( subjobs.isEmpty() );
+
+ if (bDir && !bLink)
+ {
+ // Add toplevel dir in list of dirs
+ dirs.append( url );
+ if ( url.isLocalFile() && !m_parentDirs.contains( url.path(-1) ) )
+ m_parentDirs.append( url.path(-1) );
+
+ if ( !KProtocolInfo::canDeleteRecursive( url ) ) {
+ //kdDebug(7007) << " Target is a directory " << endl;
+ // List it
+ state = STATE_LISTING;
+ ListJob *newjob = listRecursive( url, false );
+ newjob->setUnrestricted(true); // No KIOSK restrictions
+ Scheduler::scheduleJob(newjob);
+ connect(newjob, TQT_SIGNAL(entries( TDEIO::Job *,
+ const TDEIO::UDSEntryList& )),
+ TQT_SLOT( slotEntries( TDEIO::Job*,
+ const TDEIO::UDSEntryList& )));
+ addSubjob(newjob);
+ } else {
+ ++m_currentStat;
+ statNextSrc();
+ }
+ }
+ else
+ {
+ if ( bLink ) {
+ //kdDebug(7007) << " Target is a symlink" << endl;
+ symlinks.append( url );
+ } else {
+ //kdDebug(7007) << " Target is a file" << endl;
+ files.append( url );
+ }
+ if ( url.isLocalFile() && !m_parentDirs.contains( url.directory(false) ) )
+ m_parentDirs.append( url.directory(false) );
+ ++m_currentStat;
+ statNextSrc();
+ }
+ }
+ break;
+ case STATE_LISTING:
+ if ( job->error() )
+ {
+ // Try deleting nonetheless, it may be empty (and non-listable)
+ }
+ subjobs.remove( job );
+ assert( subjobs.isEmpty() );
+ ++m_currentStat;
+ statNextSrc();
+ break;
+ case STATE_DELETING_FILES:
+ if ( job->error() )
+ {
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+ subjobs.remove( job );
+ assert( subjobs.isEmpty() );
+ m_processedFiles++;
+
+ deleteNextFile();
+ break;
+ case STATE_DELETING_DIRS:
+ if ( job->error() )
+ {
+ Job::slotResult( job ); // will set the error and emit result(this)
+ return;
+ }
+ subjobs.remove( job );
+ assert( subjobs.isEmpty() );
+ m_processedDirs++;
+ //emit processedDirs( this, m_processedDirs );
+ //if (!m_shred)
+ //emitPercent( m_processedFiles + m_processedDirs, m_totalFilesDirs );
+
+ deleteNextDir();
+ break;
+ default:
+ assert(0);
+ }
+}
+
+DeleteJob *TDEIO::del( const KURL& src, bool shred, bool showProgressInfo )
+{
+ KURL::List srcList;
+ srcList.append( src );
+ DeleteJob *job = new DeleteJob( srcList, shred, showProgressInfo );
+ return job;
+}
+
+DeleteJob *TDEIO::del( const KURL::List& src, bool shred, bool showProgressInfo )
+{
+ DeleteJob *job = new DeleteJob( src, shred, showProgressInfo );
+ return job;
+}
+
+MultiGetJob::MultiGetJob(const KURL& url,
+ bool showProgressInfo)
+ : TransferJob(url, 0, TQByteArray(), TQByteArray(), showProgressInfo)
+{
+ m_waitQueue.setAutoDelete(true);
+ m_activeQueue.setAutoDelete(true);
+ m_currentEntry = 0;
+}
+
+void MultiGetJob::get(long id, const KURL &url, const MetaData &metaData)
+{
+ GetRequest *entry = new GetRequest(id, url, metaData);
+ entry->metaData["request-id"] = TQString("%1").arg(id);
+ m_waitQueue.append(entry);
+}
+
+void MultiGetJob::flushQueue(TQPtrList<GetRequest> &queue)
+{
+ GetRequest *entry;
+ // Use multi-get
+ // Scan all jobs in m_waitQueue
+ for(entry = m_waitQueue.first(); entry; )
+ {
+ if ((m_url.protocol() == entry->url.protocol()) &&
+ (m_url.host() == entry->url.host()) &&
+ (m_url.port() == entry->url.port()) &&
+ (m_url.user() == entry->url.user()))
+ {
+ m_waitQueue.take();
+ queue.append(entry);
+ entry = m_waitQueue.current();
+ }
+ else
+ {
+ entry = m_waitQueue.next();
+ }
+ }
+ // Send number of URLs, (URL, metadata)*
+ KIO_ARGS << (TQ_INT32) queue.count();
+ for(entry = queue.first(); entry; entry = queue.next())
+ {
+ stream << entry->url << entry->metaData;
+ }
+ m_packedArgs = packedArgs;
+ m_command = CMD_MULTI_GET;
+ m_outgoingMetaData.clear();
+}
+
+void MultiGetJob::start(Slave *slave)
+{
+ // Add first job from m_waitQueue and add it to m_activeQueue
+ GetRequest *entry = m_waitQueue.take(0);
+ m_activeQueue.append(entry);
+
+ m_url = entry->url;
+
+ if (!entry->url.protocol().startsWith("http"))
+ {
+ // Use normal get
+ KIO_ARGS << entry->url;
+ m_packedArgs = packedArgs;
+ m_outgoingMetaData = entry->metaData;
+ m_command = CMD_GET;
+ b_multiGetActive = false;
+ }
+ else
+ {
+ flushQueue(m_activeQueue);
+ b_multiGetActive = true;
+ }
+
+ TransferJob::start(slave); // Anything else to do??
+}
+
+bool MultiGetJob::findCurrentEntry()
+{
+ if (b_multiGetActive)
+ {
+ long id = m_incomingMetaData["request-id"].toLong();
+ for(GetRequest *entry = m_activeQueue.first(); entry; entry = m_activeQueue.next())
+ {
+ if (entry->id == id)
+ {
+ m_currentEntry = entry;
+ return true;
+ }
+ }
+ m_currentEntry = 0;
+ return false;
+ }
+ else
+ {
+ m_currentEntry = m_activeQueue.first();
+ return (m_currentEntry != 0);
+ }
+}
+
+void MultiGetJob::slotRedirection( const KURL &url)
+{
+ if (!findCurrentEntry()) return; // Error
+ if (kapp && !kapp->authorizeURLAction("redirect", m_url, url))
+ {
+ kdWarning(7007) << "MultiGetJob: Redirection from " << m_currentEntry->url << " to " << url << " REJECTED!" << endl;
+ return;
+ }
+ m_redirectionURL = url;
+ if (m_currentEntry->url.hasUser() && !url.hasUser() && (m_currentEntry->url.host().lower() == url.host().lower()))
+ m_redirectionURL.setUser(m_currentEntry->url.user()); // Preserve user
+ get(m_currentEntry->id, m_redirectionURL, m_currentEntry->metaData); // Try again
+}
+
+
+void MultiGetJob::slotFinished()
+{
+ if (!findCurrentEntry()) return;
+ if (m_redirectionURL.isEmpty())
+ {
+ // No redirection, tell the world that we are finished.
+ emit result(m_currentEntry->id);
+ }
+ m_redirectionURL = KURL();
+ m_error = 0;
+ m_incomingMetaData.clear();
+ m_activeQueue.removeRef(m_currentEntry);
+ if (m_activeQueue.count() == 0)
+ {
+ if (m_waitQueue.count() == 0)
+ {
+ // All done
+ TransferJob::slotFinished();
+ }
+ else
+ {
+ // return slave to pool
+ // fetch new slave for first entry in m_waitQueue and call start
+ // again.
+ GetRequest *entry = m_waitQueue.at(0);
+ m_url = entry->url;
+ slaveDone();
+ Scheduler::doJob(this);
+ }
+ }
+}
+
+void MultiGetJob::slotData( const TQByteArray &_data)
+{
+ if(!m_currentEntry) return;// Error, unknown request!
+ if(m_redirectionURL.isEmpty() || !m_redirectionURL.isValid() || m_error)
+ emit data(m_currentEntry->id, _data);
+}
+
+void MultiGetJob::slotMimetype( const TQString &_mimetype )
+{
+ if (b_multiGetActive)
+ {
+ TQPtrList<GetRequest> newQueue;
+ flushQueue(newQueue);
+ if (!newQueue.isEmpty())
+ {
+ while(!newQueue.isEmpty())
+ m_activeQueue.append(newQueue.take(0));
+ m_slave->send( m_command, m_packedArgs );
+ }
+ }
+ if (!findCurrentEntry()) return; // Error, unknown request!
+ emit mimetype(m_currentEntry->id, _mimetype);
+}
+
+MultiGetJob *TDEIO::multi_get(long id, const KURL &url, const MetaData &metaData)
+{
+ MultiGetJob * job = new MultiGetJob( url, false );
+ job->get(id, url, metaData);
+ return job;
+}
+
+
+#ifdef CACHE_INFO
+CacheInfo::CacheInfo(const KURL &url)
+{
+ m_url = url;
+}
+
+TQString CacheInfo::cachedFileName()
+{
+ const TQChar separator = '_';
+
+ TQString CEF = m_url.path();
+
+ int p = CEF.find('/');
+
+ while(p != -1)
+ {
+ CEF[p] = separator;
+ p = CEF.find('/', p);
+ }
+
+ TQString host = m_url.host().lower();
+ CEF = host + CEF + '_';
+
+ TQString dir = KProtocolManager::cacheDir();
+ if (dir[dir.length()-1] != '/')
+ dir += "/";
+
+ int l = m_url.host().length();
+ for(int i = 0; i < l; i++)
+ {
+ if (host[i].isLetter() && (host[i] != 'w'))
+ {
+ dir += host[i];
+ break;
+ }
+ }
+ if (dir[dir.length()-1] == '/')
+ dir += "0";
+
+ unsigned long hash = 0x00000000;
+ TQCString u = m_url.url().latin1();
+ for(int i = u.length(); i--;)
+ {
+ hash = (hash * 12211 + u[i]) % 2147483563;
+ }
+
+ TQString hashString;
+ hashString.sprintf("%08lx", hash);
+
+ CEF = CEF + hashString;
+
+ CEF = dir + "/" + CEF;
+
+ return CEF;
+}
+
+TQFile *CacheInfo::cachedFile()
+{
+#ifdef Q_WS_WIN
+ const char *mode = (readWrite ? "rb+" : "rb");
+#else
+ const char *mode = (readWrite ? "r+" : "r");
+#endif
+
+ FILE *fs = fopen(TQFile::encodeName(CEF), mode); // Open for reading and writing
+ if (!fs)
+ return 0;
+
+ char buffer[401];
+ bool ok = true;
+
+ // CacheRevision
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
+ ok = false;
+
+ time_t date;
+ time_t currentDate = time(0);
+
+ // URL
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ int l = strlen(buffer);
+ if (l>0)
+ buffer[l-1] = 0; // Strip newline
+ if (m_.url.url() != buffer)
+ {
+ ok = false; // Hash collision
+ }
+ }
+
+ // Creation Date
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ date = (time_t) strtoul(buffer, 0, 10);
+ if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
+ {
+ m_bMustRevalidate = true;
+ m_expireDate = currentDate;
+ }
+ }
+
+ // Expiration Date
+ m_cacheExpireDateOffset = ftell(fs);
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ if (m_request.cache == CC_Verify)
+ {
+ date = (time_t) strtoul(buffer, 0, 10);
+ // After the expire date we need to revalidate.
+ if (!date || difftime(currentDate, date) >= 0)
+ m_bMustRevalidate = true;
+ m_expireDate = date;
+ }
+ }
+
+ // ETag
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ m_etag = TQString(buffer).stripWhiteSpace();
+ }
+
+ // Last-Modified
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ m_lastModified = TQString(buffer).stripWhiteSpace();
+ }
+
+ fclose(fs);
+
+ if (ok)
+ return fs;
+
+ unlink( TQFile::encodeName(CEF) );
+ return 0;
+
+}
+
+void CacheInfo::flush()
+{
+ cachedFile().remove();
+}
+
+void CacheInfo::touch()
+{
+
+}
+void CacheInfo::setExpireDate(int);
+void CacheInfo::setExpireTimeout(int);
+
+
+int CacheInfo::creationDate();
+int CacheInfo::expireDate();
+int CacheInfo::expireTimeout();
+#endif
+
+void Job::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+void SimpleJob::virtual_hook( int id, void* data )
+{ TDEIO::Job::virtual_hook( id, data ); }
+
+void MkdirJob::virtual_hook( int id, void* data )
+{ SimpleJob::virtual_hook( id, data ); }
+
+void StatJob::virtual_hook( int id, void* data )
+{ SimpleJob::virtual_hook( id, data ); }
+
+void TransferJob::virtual_hook( int id, void* data )
+{ SimpleJob::virtual_hook( id, data ); }
+
+void MultiGetJob::virtual_hook( int id, void* data )
+{ TransferJob::virtual_hook( id, data ); }
+
+void MimetypeJob::virtual_hook( int id, void* data )
+{ TransferJob::virtual_hook( id, data ); }
+
+void FileCopyJob::virtual_hook( int id, void* data )
+{ Job::virtual_hook( id, data ); }
+
+void ListJob::virtual_hook( int id, void* data )
+{ SimpleJob::virtual_hook( id, data ); }
+
+void CopyJob::virtual_hook( int id, void* data )
+{ Job::virtual_hook( id, data ); }
+
+void DeleteJob::virtual_hook( int id, void* data )
+{ Job::virtual_hook( id, data ); }
+
+void LocalURLJob::virtual_hook( int id, void* data )
+{ Job::virtual_hook( id, data ); }
+
+
+#include "jobclasses.moc"
diff --git a/tdeio/tdeio/job.h b/tdeio/tdeio/job.h
new file mode 100644
index 000000000..d4d7dd41d
--- /dev/null
+++ b/tdeio/tdeio/job.h
@@ -0,0 +1,532 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_job_h__
+#define __kio_job_h__
+
+#include <tdeio/jobclasses.h>
+
+namespace TDEIO {
+
+
+ /**
+ * Creates a single directory.
+ *
+ *
+ *
+ *
+ * @param url The URL of the directory to create.
+ * @param permissions The permissions to set after creating the
+ * directory (unix-style), -1 for default permissions.
+ * @return A pointer to the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob * mkdir( const KURL& url, int permissions = -1 );
+
+ /**
+ * Removes a single directory.
+ *
+ * The directory is assumed to be empty.
+ *
+ *
+ *
+ * @param url The URL of the directory to remove.
+ * @return A pointer to the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob * rmdir( const KURL& url );
+
+ /**
+ * Changes permissions on a file or directory.
+ * See the other chmod below for changing many files
+ * or directories.
+ *
+ * @param url The URL of file or directory.
+ * @param permissions The permissions to set.
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob * chmod( const KURL& url, int permissions );
+
+ /**
+ * Rename a file or directory.
+ * Warning: this operation fails if a direct renaming is not
+ * possible (like with files or dirs on separate partitions)
+ * Use move or file_move in this case.
+ *
+ * @param src The original URL
+ * @param dest The final URL
+ * @param overwrite whether to automatically overwrite if the dest exists
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob * rename( const KURL& src, const KURL & dest, bool overwrite );
+
+ /**
+ * Create or move a symlink.
+ * This is the lowlevel operation, similar to file_copy and file_move.
+ * It doesn't do any check (other than those the slave does)
+ * and it doesn't show rename and skip dialogs - use TDEIO::link for that.
+ * @param target The string that will become the "target" of the link (can be relative)
+ * @param dest The symlink to create.
+ * @param overwrite whether to automatically overwrite if the dest exists
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob * symlink( const TQString & target, const KURL& dest, bool overwrite, bool showProgressInfo = true );
+
+ /**
+ * Execute any command that is specific to one slave (protocol).
+ *
+ * Examples are : HTTP POST, mount and unmount (kio_file)
+ *
+ * @param url The URL isn't passed to the slave, but is used to know
+ * which slave to send it to :-)
+ * @param data Packed data. The meaning is completely dependent on the
+ * slave, but usually starts with an int for the command number.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob * special( const KURL& url, const TQByteArray & data, bool showProgressInfo = true );
+
+ /**
+ * Mount filesystem.
+ *
+ * Special job for @p kio_file.
+ *
+ * @param ro Mount read-only if @p true.
+ * @param fstype File system type (e.g. "ext2", can be 0L).
+ * @param dev Device (e.g. /dev/sda0).
+ * @param point Mount point, can be @p null.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob *mount( bool ro, const char *fstype, const TQString& dev, const TQString& point, bool showProgressInfo = true );
+
+ /**
+ * Unmount filesystem.
+ *
+ * Special job for @p kio_file.
+ *
+ * @param point Point to unmount.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob *unmount( const TQString & point, bool showProgressInfo = true );
+
+ /**
+ * Retrieve local URL if available
+ *
+ * @param remoteURL the remote URL to get the local URL for
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT LocalURLJob *localURL( const KURL& remoteUrl );
+
+ /**
+ * HTTP cache update
+ *
+ * @param url Url to update, protocol must be "http".
+ * @param no_cache If true, cache entry for @p url is deleted.
+ * @param expireDate Local machine time indicating when the entry is
+ * supposed to expire.
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob *http_update_cache( const KURL& url, bool no_cache, time_t expireDate);
+
+ /**
+ * Find all details for one file or directory.
+ *
+ * @param url the URL of the file
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT StatJob * stat( const KURL& url, bool showProgressInfo = true );
+ /**
+ * Find all details for one file or directory.
+ * This version of the call includes two additional booleans, @p sideIsSource and @p details.
+ *
+ * @param url the URL of the file
+ * @param sideIsSource is true when stating a source file (we will do a get on it if
+ * the stat works) and false when stating a destination file (target of a copy).
+ * The reason for this parameter is that in some cases the tdeioslave might not
+ * be able to determine a file's existence (e.g. HTTP doesn't allow it, FTP
+ * has issues with case-sensitivity on some systems).
+ * When the slave can't reliably determine the existence of a file, it will:
+ * @li be optimistic if sideIsSource=true, i.e. it will assume the file exists,
+ * and if it doesn't this will appear when actually trying to download it
+ * @li be pessimistic if sideIsSource=false, i.e. it will assume the file
+ * doesn't exist, to prevent showing "about to overwrite" errors to the user.
+ * If you simply want to check for existence without downloading/uploading afterwards,
+ * then you should use sideIsSource=false.
+ *
+ * @param details selects the level of details we want.
+ * By default this is 2 (all details wanted, including modification time, size, etc.),
+ * setDetails(1) is used when deleting: we don't need all the information if it takes
+ * too much time, no need to follow symlinks etc.
+ * setDetails(0) is used for very simple probing: we'll only get the answer
+ * "it's a file or a directory, or it doesn't exist". This is used by KRun.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT StatJob * stat( const KURL& url, bool sideIsSource, short int details, bool showProgressInfo = true );
+
+ /**
+ * Get (a.k.a. read).
+ *
+ * The slave emits the data through data().
+ * @param url the URL of the file
+ * @param reload true to reload the file, false if it can be taken from the cache
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT TransferJob *get( const KURL& url, bool reload=false, bool showProgressInfo = true );
+
+ /**
+ * Put (a.k.a. write)
+ *
+ * @param url Where to write data.
+ * @param permissions May be -1. In this case no special permission mode is set.
+ * @param overwrite If true, any existing file will be overwritten.
+ * @param resume true to resume an operation. Warning, setting this to true means
+ * that the data will be appended to @p dest if @p dest exists.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ * @see multi_get()
+ */
+ TDEIO_EXPORT TransferJob *put( const KURL& url, int permissions,
+ bool overwrite, bool resume, bool showProgressInfo = true );
+
+ /**
+ * HTTP POST (for form data).
+ *
+ * Example:
+ * \code
+ * job = TDEIO::http_post( url, postData, false );
+ * job->addMetaData("content-type", contentType );
+ * job->addMetaData("referrer", referrerURL);
+ * \endcode
+ *
+ * @p postData is the data that you want to send and
+ * @p contentType is the complete HTTP header line that
+ * specifies the content's MIME type, for example
+ * "Content-Type: text/xml".
+ *
+ * You MUST specify content-type!
+ *
+ * Often @p contentType is
+ * "Content-Type: application/x-www-form-urlencoded" and
+ * the @p postData is then an ASCII string (without null-termination!)
+ * with characters like space, linefeed and percent escaped like %20,
+ * %0A and %25.
+ *
+ * @param url Where to write the data.
+ * @param postData Encoded data to post.
+ * @param showProgressInfo true to display
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT TransferJob *http_post( const KURL& url, const TQByteArray &postData,
+ bool showProgressInfo = true );
+
+ /**
+ * Get (a.k.a. read), into a single TQByteArray.
+ * @see StoredTransferJob
+ *
+ * @param url the URL of the file
+ * @param reload true to reload the file, false if it can be taken from the cache
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ * @since 3.3
+ */
+ TDEIO_EXPORT StoredTransferJob *storedGet( const KURL& url, bool reload=false, bool showProgressInfo = true );
+
+ /**
+ * Put (a.k.a. write) data from a single TQByteArray.
+ * @see StoredTransferJob
+ *
+ * @param arr The data to write
+ * @param url Where to write data.
+ * @param permissions May be -1. In this case no special permission mode is set.
+ * @param overwrite If true, any existing file will be overwritten.
+ * @param resume true to resume an operation. Warning, setting this to true means
+ * that the data will be appended to @p dest if @p dest exists.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ * @since 3.3
+ */
+ TDEIO_EXPORT StoredTransferJob *storedPut( const TQByteArray& arr, const KURL& url, int permissions,
+ bool overwrite, bool resume, bool showProgressInfo = true );
+
+ /**
+ * Creates a new multiple get job.
+ *
+ * @param id the id of the get operation
+ * @param url the URL of the file
+ * @param metaData the MetaData associated with the file
+ *
+ * @return the job handling the operation.
+ * @see get()
+ */
+ TDEIO_EXPORT MultiGetJob *multi_get( long id, const KURL &url, const MetaData &metaData);
+
+ /**
+ * Find mimetype for one file or directory.
+ *
+ * @param url the URL of the file
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT MimetypeJob * mimetype( const KURL& url,
+ bool showProgressInfo = true );
+
+ /**
+ * Copy a single file.
+ *
+ * Uses either SlaveBase::copy() if the slave supports that
+ * or get() and put() otherwise.
+ * @param src Where to get the file.
+ * @param dest Where to put the file.
+ * @param permissions May be -1. In this case no special permission mode is set.
+ * @param overwrite If true, any existing file will be overwritten.
+ * @param resume true to resume an operation. Warning, setting this to true means
+ * that @p src will be appended to @p dest if @p dest exists.
+ * You probably don't want that, so leave it to false :)
+ *
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT FileCopyJob *file_copy( const KURL& src, const KURL& dest, int permissions=-1,
+ bool overwrite=false, bool resume=false,
+ bool showProgressInfo = true);
+
+ /**
+ * Move a single file.
+ *
+ * Use either SlaveBase::rename() if the slave supports that,
+ * or copy() and del() otherwise, or eventually get() & put() & del()
+ * @param src Where to get the file.
+ * @param dest Where to put the file.
+ * @param permissions May be -1. In this case no special permission mode is set.
+ * @param overwrite If @p true, any existing file will be overwritten.
+ * @param resume true to resume an operation. Warning, setting this to true means
+ * that @p src will be appended to @p dest if @p dest exists.
+ * You probably don't want that, so leave it to false :)
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT FileCopyJob *file_move( const KURL& src, const KURL& dest, int permissions=-1,
+ bool overwrite=false, bool resume=false,
+ bool showProgressInfo = true);
+
+ /**
+ * Delete a single file.
+ *
+ * @param src File to delete.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT SimpleJob *file_delete( const KURL& src, bool showProgressInfo = true);
+
+ /**
+ * List the contents of @p url, which is assumed to be a directory.
+ *
+ * "." and ".." are returned, filter them out if you don't want them.
+ *
+ *
+ * @param url the url of the directory
+ * @param showProgressInfo true to show progress information
+ * @param includeHidden true for all files, false to cull out UNIX hidden
+ * files/dirs (whose names start with dot)
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT ListJob *listDir( const KURL& url, bool showProgressInfo = true,
+ bool includeHidden = true );
+
+ /**
+ * The same as the previous method, but recurses subdirectories.
+ * Directory links are not followed.
+ *
+ * "." and ".." are returned but only for the toplevel directory.
+ * Filter them out if you don't want them.
+ *
+ * @param url the url of the directory
+ * @param showProgressInfo true to show progress information
+ * @param includeHidden true for all files, false to cull out UNIX hidden
+ * files/dirs (whose names start with dot)
+ * @return the job handling the operation.
+ */
+ TDEIO_EXPORT ListJob *listRecursive( const KURL& url, bool showProgressInfo = true,
+ bool includeHidden = true );
+
+ /**
+ * Copy a file or directory @p src into the destination @p dest,
+ * which can be a file (including the final filename) or a directory
+ * (into which @p src will be copied).
+ *
+ * This emulates the cp command completely.
+ *
+ * @param src the file or directory to copy
+ * @param dest the destination
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @see copyAs()
+ */
+ TDEIO_EXPORT CopyJob *copy( const KURL& src, const KURL& dest, bool showProgressInfo = true );
+
+ /**
+ * Copy a file or directory @p src into the destination @p dest,
+ * which is the destination name in any case, even for a directory.
+ *
+ * As opposed to copy(), this doesn't emulate cp, but is the only
+ * way to copy a directory, giving it a new name and getting an error
+ * box if a directory already exists with the same name.
+ *
+ * @param src the file or directory to copy
+ * @param dest the destination
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ */
+ TDEIO_EXPORT CopyJob *copyAs( const KURL& src, const KURL& dest, bool showProgressInfo = true );
+
+ /**
+ * Copy a list of file/dirs @p src into a destination directory @p dest.
+ *
+ * @param src the list of files and/or directories
+ * @param dest the destination
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ */
+ TDEIO_EXPORT CopyJob *copy( const KURL::List& src, const KURL& dest, bool showProgressInfo = true );
+
+ /**
+ * Moves a file or directory @p src to the given destination @p dest.
+ *
+ * @param src the file or directory to copy
+ * @param dest the destination
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @see copy()
+ * @see moveAs()
+ */
+ TDEIO_EXPORT CopyJob *move( const KURL& src, const KURL& dest, bool showProgressInfo = true );
+ /**
+ * Moves a file or directory @p src to the given destination @p dest. Unlike move()
+ * this operation will fail when the directory already exists.
+ *
+ * @param src the file or directory to copy
+ * @param dest the destination
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @see copyAs()
+ */
+ TDEIO_EXPORT CopyJob *moveAs( const KURL& src, const KURL& dest, bool showProgressInfo = true );
+ /**
+ * Moves a list of files or directories @p src to the given destination @p dest.
+ *
+ * @param src the list of files or directories to copy
+ * @param dest the destination
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @see copy()
+ */
+ TDEIO_EXPORT CopyJob *move( const KURL::List& src, const KURL& dest, bool showProgressInfo = true );
+
+ /**
+ * Create a link.
+ * If the protocols and hosts are the same, a Unix symlink will be created.
+ * Otherwise, a .desktop file of Type Link and pointing to the src URL will be created.
+ *
+ * @param src The existing file or directory, 'target' of the link.
+ * @param destDir Destination directory where the link will be created.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ */
+ TDEIO_EXPORT CopyJob *link( const KURL& src, const KURL& destDir, bool showProgressInfo = true );
+
+ /**
+ * Create several links
+ * If the protocols and hosts are the same, a Unix symlink will be created.
+ * Otherwise, a .desktop file of Type Link and pointing to the src URL will be created.
+ *
+ * @param src The existing files or directories, 'targets' of the link.
+ * @param destDir Destination directory where the links will be created.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @see link()
+ */
+ TDEIO_EXPORT CopyJob *link( const KURL::List& src, const KURL& destDir, bool showProgressInfo = true );
+
+ /**
+ * Create a link. Unlike link() this operation will fail when the directory already
+ * exists.
+ * If the protocols and hosts are the same, a Unix symlink will be created.
+ * Otherwise, a .desktop file of Type Link and pointing to the src URL will be created.
+ *
+ * @param src The existing file or directory, 'target' of the link.
+ * @param dest Destination directory where the link will be created.
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @see link ()
+ * @see copyAs()
+ */
+ TDEIO_EXPORT CopyJob *linkAs( const KURL& src, const KURL& dest, bool showProgressInfo = true );
+
+ /**
+ * Trash a file or directory.
+ * This is currently only supported for local files and directories.
+ * Use "KURL src; src.setPath( path );" to create a URL from a path.
+ *
+ * @param src file to delete
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @since 3.4
+ */
+ TDEIO_EXPORT CopyJob *trash( const KURL& src, bool showProgressInfo = true );
+
+ /**
+ * Trash a list of files or directories.
+ * This is currently only supported for local files and directories.
+ *
+ * @param src the files to delete
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ * @since 3.4
+ */
+ TDEIO_EXPORT CopyJob *trash( const KURL::List& src, bool showProgressInfo = true );
+
+ /**
+ * Delete a file or directory.
+ *
+ * @param src file to delete
+ * @param shred obsolete (TODO remove in KDE4)
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ */
+ TDEIO_EXPORT DeleteJob *del( const KURL& src, bool shred = false, bool showProgressInfo = true );
+
+ /**
+ * Deletes a list of files or directories.
+ *
+ * @param src the files to delete
+ * @param shred obsolete (TODO remove in KDE4)
+ * @param showProgressInfo true to show progress information
+ * @return the job handling the operation
+ */
+ TDEIO_EXPORT DeleteJob *del( const KURL::List& src, bool shred = false, bool showProgressInfo = true );
+}
+
+#endif
+
diff --git a/tdeio/tdeio/jobclasses.h b/tdeio/tdeio/jobclasses.h
new file mode 100644
index 000000000..7f5ec1f85
--- /dev/null
+++ b/tdeio/tdeio/jobclasses.h
@@ -0,0 +1,1909 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_jobclasses_h__
+#define __kio_jobclasses_h__
+
+#include <tqobject.h>
+#include <tqptrlist.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqguardedptr.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <kurl.h>
+#include <tdeio/global.h>
+
+class Observer;
+class TQTimer;
+
+#define KIO_COPYJOB_HAS_SETINTERACTIVE // new in 3.4. Used by kio_trash.
+
+namespace TDEIO {
+
+ class Slave;
+ class SlaveInterface;
+
+
+ /**
+ * The base class for all jobs.
+ * For all jobs created in an application, the code looks like
+ *
+ * \code
+ * TDEIO::Job * job = TDEIO::someoperation( some parameters );
+ * connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ * this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
+ * \endcode
+ * (other connects, specific to the job)
+ *
+ * And slotResult is usually at least:
+ *
+ * \code
+ * if ( job->error() )
+ * job->showErrorDialog( this or 0L );
+ * \endcode
+ * @see TDEIO::Scheduler
+ * @see TDEIO::Slave
+ */
+ class TDEIO_EXPORT Job : public TQObject {
+ Q_OBJECT
+
+ protected:
+ Job( bool showProgressInfo );
+
+ public:
+ virtual ~Job();
+
+ /**
+ * Abort this job.
+ * This kills all subjobs and deletes the job.
+ *
+ * @param quietly if false, Job will emit signal result
+ * and ask tdeio_uiserver to close the progress window.
+ * @p quietly is set to true for subjobs. Whether applications
+ * should call with true or false depends on whether they rely
+ * on result being emitted or not.
+ */
+ virtual void kill( bool quietly = true );
+
+ /**
+ * Returns the error code, if there has been an error.
+ * Only call this method from the slot connected to result().
+ * @return the error code for this job, 0 if no error.
+ * Error codes are defined in TDEIO::Error.
+ */
+ int error() const { return m_error; }
+
+ /**
+ * Returns the progress id for this job.
+ * @return the progress id for this job, as returned by uiserver
+ */
+ int progressId() const { return m_progressId; }
+
+ /**
+ * Returns the error text if there has been an error.
+ * Only call if error is not 0.
+ * This is really internal, better use errorString() or errorDialog().
+ *
+ * @return a string to help understand the error, usually the url
+ * related to the error. Only valid if error() is not 0.
+ */
+ const TQString & errorText() const { return m_errorText; }
+
+ /**
+ * Converts an error code and a non-i18n error message into an
+ * error message in the current language. The low level (non-i18n)
+ * error message (usually a url) is put into the translated error
+ * message using %1.
+ *
+ * Example for errid == ERR_CANNOT_OPEN_FOR_READING:
+ * \code
+ * i18n( "Could not read\n%1" ).arg( errortext );
+ * \endcode
+ * Use this to display the error yourself, but for a dialog box
+ * use Job::showErrorDialog. Do not call it if error()
+ * is not 0.
+ * @return the error message and if there is no error, a message
+ * telling the user that the app is broken, so check with
+ * error() whether there is an error
+ */
+ TQString errorString() const;
+
+ /**
+ * Converts an error code and a non-i18n error message into i18n
+ * strings suitable for presentation in a detailed error message box.
+ *
+ * @param reqUrl the request URL that generated this error message
+ * @param method the method that generated this error message
+ * (unimplemented)
+ * @return the following strings: caption, error + description,
+ * causes+solutions
+ */
+ TQStringList detailedErrorStrings(const KURL *reqUrl = 0L,
+ int method = -1) const;
+
+ /**
+ * Display a dialog box to inform the user of the error given by
+ * this job.
+ * Only call if error is not 0, and only in the slot connected
+ * to result.
+ * @param parent the parent widget for the dialog box, can be 0 for
+ * top-level
+ */
+ void showErrorDialog( TQWidget * parent = 0L );
+
+ /**
+ * Enable or disable the automatic error handling. When automatic
+ * error handling is enabled and an error occurs, then showErrorDialog()
+ * is called with the specified @p parentWidget (if supplied) , right before
+ * the emission of the result signal.
+ *
+ * The default is false.
+ *
+ * @param enable enable or disable automatic error handling
+ * @param parentWidget the parent widget, passed to showErrorDialog.
+ * Can be 0 for top-level
+ * @see isAutoErrorHandlingEnabled(), showErrorDialog()
+ */
+ void setAutoErrorHandlingEnabled( bool enable, TQWidget *parentWidget = 0 );
+
+ /**
+ * Returns whether automatic error handling is enabled or disabled.
+ * @return true if automatic error handling is enabled
+ * @see setAutoErrorHandlingEnabled()
+ */
+ bool isAutoErrorHandlingEnabled() const;
+
+ /**
+ * Enable or disable the automatic warning handling. When automatic
+ * warning handling is enabled and an error occurs, then a message box
+ * is displayed with the warning message
+ *
+ * The default is true.
+ *
+ * See also isAutoWarningHandlingEnabled , showErrorDialog
+ *
+ * @param enable enable or disable automatic warning handling
+ * @see isAutoWarningHandlingEnabled()
+ * @since 3.5
+ */
+ void setAutoWarningHandlingEnabled( bool enable );
+
+ /**
+ * Returns whether automatic warning handling is enabled or disabled.
+ * See also setAutoWarningHandlingEnabled .
+ * @return true if automatic warning handling is enabled
+ * @see setAutoWarningHandlingEnabled()
+ * @since 3.5
+ */
+ bool isAutoWarningHandlingEnabled() const;
+
+ /**
+ * Enable or disable the message display from the job.
+ *
+ * The default is true.
+ * @param enable enable or disable message display
+ * @since 3.4.1
+ */
+ void setInteractive(bool enable);
+
+ /**
+ * Returns whether message display is enabled or disabled.
+ * @return true if message display is enabled
+ * @see setInteractive()
+ * @since 3.4.1
+ */
+ bool isInteractive() const;
+ /**
+ * Associate this job with a window given by @p window.
+ * @param window the window to associate to
+ * @see window()
+ */
+ void setWindow(TQWidget *window);
+
+ /**
+ * Returns the window this job is associated with.
+ * @return the associated window
+ * @see setWindow()
+ */
+ TQWidget *window() const;
+
+ /**
+ * Updates the last user action timestamp to the given time.
+ * See TDEApplication::updateUserTimestamp() .
+ * @since 3.5.6
+ */
+ void updateUserTimestamp( unsigned long time );
+
+ /**
+ * Set the parent Job.
+ * One example use of this is when FileCopyJob calls open_RenameDlg,
+ * it must pass the correct progress ID of the parent CopyJob
+ * (to hide the progress dialog).
+ * You can set the parent job only once. By default a job does not
+ * have a parent job.
+ * @param parentJob the new parent job
+ * @since 3.1
+ */
+ void setParentJob( Job* parentJob );
+
+ /**
+ * Returns the parent job, if there is one.
+ * @return the parent job, or 0 if there is none
+ * @see setParentJob
+ * @since 3.1
+ */
+ Job* parentJob() const;
+
+ /**
+ * Set meta data to be sent to the slave, replacing existing
+ * meta data.
+ * @param metaData the meta data to set
+ * @see addMetaData()
+ * @see mergeMetaData()
+ */
+ void setMetaData( const TDEIO::MetaData &metaData);
+
+ /**
+ * Add key/value pair to the meta data that is sent to the slave.
+ * @param key the key of the meta data
+ * @param value the value of the meta data
+ * @see setMetaData()
+ * @see mergeMetaData()
+ */
+ void addMetaData(const TQString &key, const TQString &value);
+
+ /**
+ * Add key/value pairs to the meta data that is sent to the slave.
+ * If a certain key already existed, it will be overridden.
+ * @param values the meta data to add
+ * @see setMetaData()
+ * @see mergeMetaData()
+ */
+ void addMetaData(const TQMap<TQString,TQString> &values);
+
+ /**
+ * Add key/value pairs to the meta data that is sent to the slave.
+ * If a certain key already existed, it will remain unchanged.
+ * @param values the meta data to merge
+ * @see setMetaData()
+ * @see addMetaData()
+ */
+ void mergeMetaData(const TQMap<TQString,TQString> &values);
+
+ /**
+ * @internal. For the scheduler. Do not use.
+ */
+ MetaData outgoingMetaData() const;
+
+ /**
+ * Get meta data received from the slave.
+ * (Valid when first data is received and/or slave is finished)
+ * @return the job's meta data
+ */
+ MetaData metaData() const;
+
+ /**
+ * Query meta data received from the slave.
+ * (Valid when first data is received and/or slave is finished)
+ * @param key the key of the meta data to retrieve
+ * @return the value of the meta data, or TQString::null if the
+ * @p key does not exist
+ */
+ TQString queryMetaData(const TQString &key);
+
+ /**
+ * Returns the processed size for this job.
+ * @see processedSize
+ * @since 3.2
+ */
+ TDEIO::filesize_t getProcessedSize();
+
+ signals:
+ /**
+ * Emitted when the job is finished, in any case (completed, canceled,
+ * failed...). Use error to know the result.
+ * @param job the job that emitted this signal
+ */
+ void result( TDEIO::Job *job );
+
+ /**
+ * @deprecated. Don't use !
+ * Emitted when the job is canceled.
+ * Signal result() is emitted as well, and error() is,
+ * in this case, ERR_USER_CANCELED.
+ * @param job the job that emitted this signal
+ */
+ void canceled( TDEIO::Job *job );
+
+ /**
+ * Emitted to display information about this job, as sent by the slave.
+ * Examples of message are "Resolving host", "Connecting to host...", etc.
+ * @param job the job that emitted this signal
+ * @param msg the info message
+ */
+ void infoMessage( TDEIO::Job *job, const TQString & msg );
+ // KDE4: Separate rich-text string from plain-text string, for different widgets.
+
+ /**
+ * Emitted to display a warning about this job, as sent by the slave.
+ * @param job the job that emitted this signal
+ * @param msg the info message
+ * @since 3.5
+ */
+ void warning( TDEIO::Job *job, const TQString & msg );
+ // KDE4: Separate rich-text string from plain-text string, for different widgets.
+
+ /**
+ * Emitted when the slave successfully connected to the host.
+ * There is no guarantee the slave will send this, and this is
+ * currently unused (in the applications).
+ * @param job the job that emitted this signal
+ */
+ void connected( TDEIO::Job *job );
+
+ /**
+ * Progress signal showing the overall progress of the job
+ * This is valid for any kind of job, and allows using a
+ * a progress bar very easily. (see KProgress).
+ * Note that this signal is not emitted for finished jobs.
+ * @param job the job that emitted this signal
+ * @param percent the percentage
+ */
+ void percent( TDEIO::Job *job, unsigned long percent );
+
+ /**
+ * Emitted when we know the size of this job (data size for transfers,
+ * number of entries for listings).
+ * @param job the job that emitted this signal
+ * @param size the total size in bytes
+ */
+ void totalSize( TDEIO::Job *job, TDEIO::filesize_t size );
+
+ /**
+ * Regularly emitted to show the progress of this job
+ * (current data size for transfers, entries listed).
+ * @param job the job that emitted this signal
+ * @param size the processed size in bytes
+ */
+ void processedSize( TDEIO::Job *job, TDEIO::filesize_t size );
+
+ /**
+ * Emitted to display information about the speed of this job.
+ * @param job the job that emitted this signal
+ * @param speed the speed in bytes/s
+ */
+ void speed( TDEIO::Job *job, unsigned long speed );
+
+ protected slots:
+ /**
+ * Called whenever a subjob finishes.
+ * Default implementation checks for errors and propagates
+ * to parent job, then calls removeSubjob.
+ * Override if you don't want subjobs errors to be propagated.
+ * @param job the subjob
+ * @see result()
+ */
+ virtual void slotResult( TDEIO::Job *job );
+
+ /**
+ * Forward signal from subjob.
+ * @param job the subjob
+ * @param speed the speed in bytes/s
+ * @see speed()
+ */
+ void slotSpeed( TDEIO::Job *job, unsigned long speed );
+ /**
+ * Forward signal from subjob.
+ * @param job the subjob
+ * @param msg the info message
+ * @see infoMessage()
+ */
+ void slotInfoMessage( TDEIO::Job *job, const TQString &msg );
+
+ /**
+ * Remove speed information.
+ */
+ void slotSpeedTimeout();
+
+ protected:
+ /**
+ * Add a job that has to be finished before a result
+ * is emitted. This has obviously to be called before
+ * the finish signal is emitted by the slave.
+ *
+ * @param job the subjob to add
+ * @param inheritMetaData if true, the subjob will
+ * inherit the meta data from this job.
+ */
+ virtual void addSubjob( Job *job, bool inheritMetaData=true );
+
+ /**
+ * Mark a sub job as being done. If it's the last to
+ * wait on the job will emit a result - jobs with
+ * two steps might want to override slotResult
+ * in order to avoid calling this method.
+ *
+ * @param job the subjob to add
+ */
+ virtual void removeSubjob( Job *job );
+ /**
+ * Overloaded version of removeSubjob
+ * @param job the subjob to remove
+ * @param mergeMetaData if set, the metadata received by the subjob is
+ * merged into this job.
+ * @param emitResultIfLast if this was the last subjob, emit result,
+ * i.e. terminate this job.
+ */
+ void removeSubjob( Job *job, bool mergeMetaData, bool emitResultIfLast ); // KDE4: merge with above, with =true to both
+
+ /**
+ * Utility function for inherited jobs.
+ * Emits the percent signal if bigger than m_percent,
+ * after calculating it from the parameters.
+ *
+ * @param processedSize the processed size in bytes
+ * @param totalSize the total size in bytes
+ */
+ void emitPercent( TDEIO::filesize_t processedSize, TDEIO::filesize_t totalSize );
+
+ /**
+ * Utility function for inherited jobs.
+ * Emits the speed signal and starts the timer for removing that info
+ *
+ * @param speed the speed in bytes/s
+ */
+ void emitSpeed( unsigned long speed );
+
+ /**
+ * Utility function to emit the result signal, and suicide this job.
+ * It first tells the observer to hide the progress dialog for this job.
+ */
+ void emitResult();
+
+ /**
+ * Set the processed size, does not emit processedSize
+ * @since 3.2
+ */
+ void setProcessedSize(TDEIO::filesize_t size);
+
+ /**
+ * @internal
+ */
+ unsigned long userTimestamp() const;
+
+ /**
+ * @internal
+ * Some extra storage space for jobs that don't have their own
+ * private d pointer.
+ */
+ enum { EF_TransferJobAsync = (1 << 0),
+ EF_TransferJobNeedData = (1 << 1),
+ EF_TransferJobDataSent = (1 << 2),
+ EF_ListJobUnrestricted = (1 << 3) };
+ int &extraFlags();
+
+ TQPtrList<Job> subjobs;
+ int m_error;
+ TQString m_errorText;
+ unsigned long m_percent;
+ int m_progressId; // for uiserver
+ TQTimer *m_speedTimer;
+ TQGuardedPtr<TQWidget> m_window;
+ MetaData m_outgoingMetaData;
+ MetaData m_incomingMetaData;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class JobPrivate;
+ JobPrivate *d;
+ };
+
+ /**
+ * A simple job (one url and one command).
+ * This is the base class for all jobs that are scheduled.
+ * Other jobs are high-level jobs (CopyJob, DeleteJob, FileCopyJob...)
+ * that manage subjobs but aren't scheduled directly.
+ */
+ class TDEIO_EXPORT SimpleJob : public TDEIO::Job {
+ Q_OBJECT
+
+ public:
+ /**
+ * Creates a new simple job. You don't need to use this constructor,
+ * unless you create a new job that inherits from SimpleJob.
+ * @param url the url of the job
+ * @param command the command of the job
+ * @param packedArgs the arguments
+ * @param showProgressInfo true to show progress information to the user
+ */
+ SimpleJob(const KURL& url, int command, const TQByteArray &packedArgs,
+ bool showProgressInfo);
+
+ ~SimpleJob();
+
+ /**
+ * Returns the SimpleJob's URL
+ * @return the url
+ */
+ const KURL& url() const { return m_url; }
+
+ /**
+ * Abort job.
+ * This kills all subjobs and deletes the job.
+ * @param quietly if true, Job will emit signal result
+ * Should only be set to false when the user kills the job
+ * (from tdeio_uiserver), not when you want to abort a job.
+ */
+ virtual void kill( bool quietly = true );
+
+ /**
+ * Abort job.
+ * Suspends slave to be reused by another job for the same request.
+ */
+ virtual void putOnHold();
+
+ /**
+ * Discard suspended slave.
+ */
+ static void removeOnHold();
+
+ /**
+ * @internal
+ * Called by the scheduler when a slave gets to
+ * work on this job.
+ **/
+ virtual void start( Slave *slave );
+
+ /**
+ * @internal
+ * Called to detach a slave from a job.
+ **/
+ void slaveDone();
+
+ /**
+ * @internal
+ * Slave in use by this job.
+ */
+ Slave *slave() const { return m_slave; }
+
+ /**
+ * @internal
+ */
+ int command() const { return m_command; }
+
+ public slots:
+ /**
+ * Forward signal from the slave
+ * Can also be called by the parent job, when it knows the size.
+ * @param data_size the total size
+ */
+ void slotTotalSize( TDEIO::filesize_t data_size );
+
+ protected slots:
+ /**
+ * Called when the slave marks the job
+ * as finished.
+ */
+ virtual void slotFinished( );
+
+ /**
+ * @internal
+ * Called on a slave's warning.
+ */
+ void slotWarning( const TQString & ); // KDE4: make virtual
+
+ /**
+ * Called on a slave's info message.
+ * @param s the info message
+ * @see infoMessage()
+ */
+ void slotInfoMessage( const TQString &s ); // KDE4: make virtual
+
+ /**
+ * Called on a slave's connected signal.
+ * @see connected()
+ */
+ void slotConnected();
+
+ /**
+ * Forward signal from the slave.
+ * @param data_size the processed size in bytes
+ * @see processedSize()
+ */
+ void slotProcessedSize( TDEIO::filesize_t data_size );
+ /**
+ * Forward signal from the slave.
+ * @param speed the speed in bytes/s
+ * @see speed()
+ */
+ void slotSpeed( unsigned long speed );
+
+ /**
+ * MetaData from the slave is received.
+ * @param _metaData the meta data
+ * @see metaData()
+ */
+ virtual void slotMetaData( const TDEIO::MetaData &_metaData);
+
+ public slots:
+ /**
+ * @internal
+ * Called on a slave's error.
+ * Made public for the scheduler.
+ */
+ virtual void slotError( int , const TQString & );
+
+ protected slots:
+ /**
+ * @internal
+ */
+ void slotNeedProgressId();
+
+ protected:
+ Slave * m_slave;
+ TQByteArray m_packedArgs;
+ KURL m_url;
+ KURL m_subUrl;
+ int m_command;
+ TDEIO::filesize_t m_totalSize;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ /*
+ * Allow jobs that inherit SimpleJob and are aware
+ * of redirections to store the SSL session used.
+ * Retrieval is handled by SimpleJob::start
+ * @param m_redirectionURL Reference to redirection URL,
+ * used instead of m_url if not empty
+ */
+ void storeSSLSessionFromJob(const KURL &m_redirectionURL);
+ private:
+ class SimpleJobPrivate* d;
+ };
+
+ /**
+ * A KIO job that retrieves information about a file or directory.
+ * @see TDEIO::stat()
+ */
+ class TDEIO_EXPORT StatJob : public SimpleJob {
+
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not use this constructor to create a StatJob, use TDEIO::stat() instead.
+ * @param url the url of the file or directory to check
+ * @param command the command to issue
+ * @param packedArgs the arguments
+ * @param showProgressInfo true to show progress information to the user
+ */
+ StatJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
+
+ /**
+ * A stat() can have two meanings. Either we want to read from this URL,
+ * or to check if we can write to it. First case is "source", second is "dest".
+ * It is necessary to know what the StatJob is for, to tune the tdeioslave's behavior
+ * (e.g. with FTP).
+ * @param source true for "source" mode, false for "dest" mode
+ */
+ void setSide( bool source ) { m_bSource = source; }
+
+ /**
+ * Selects the level of @p details we want.
+ * By default this is 2 (all details wanted, including modification time, size, etc.),
+ * setDetails(1) is used when deleting: we don't need all the information if it takes
+ * too much time, no need to follow symlinks etc.
+ * setDetails(0) is used for very simple probing: we'll only get the answer
+ * "it's a file or a directory, or it doesn't exist". This is used by KRun.
+ * @param details 2 for all details, 1 for simple, 0 for very simple
+ */
+ void setDetails( short int details ) { m_details = details; }
+
+ /**
+ * Call this in the slot connected to result,
+ * and only after making sure no error happened.
+ * @return the result of the stat
+ */
+ const UDSEntry & statResult() const { return m_statResult; }
+
+ /**
+ * @internal
+ * Called by the scheduler when a @p slave gets to
+ * work on this job.
+ * @param slave the slave that starts working on this job
+ */
+ virtual void start( Slave *slave );
+
+ signals:
+ /**
+ * Signals a redirection.
+ * Use to update the URL shown to the user.
+ * The redirection itself is handled internally.
+ * @param job the job that is redirected
+ * @param url the new url
+ */
+ void redirection( TDEIO::Job *job, const KURL &url );
+
+ /**
+ * Signals a permanent redirection.
+ * The redirection itself is handled internally.
+ * @param job the job that is redirected
+ * @param fromUrl the original URL
+ * @param toUrl the new URL
+ * @since 3.1
+ */
+ void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
+
+ protected slots:
+ void slotStatEntry( const TDEIO::UDSEntry & entry );
+ void slotRedirection( const KURL &url);
+ virtual void slotFinished();
+ virtual void slotMetaData( const TDEIO::MetaData &_metaData);
+
+ protected:
+ UDSEntry m_statResult;
+ KURL m_redirectionURL;
+ bool m_bSource;
+ short int m_details;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class StatJobPrivate;
+ StatJobPrivate *d;
+ };
+
+ /**
+ * A KIO job that creates a directory
+ * @see TDEIO::mkdir()
+ * @since 3.3
+ */
+ class TDEIO_EXPORT MkdirJob : public SimpleJob {
+
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not use this constructor to create a MkdirJob, use TDEIO::mkdir() instead.
+ * @param url the url of the file or directory to check
+ * @param command the command to issue
+ * @param packedArgs the arguments
+ * @param showProgressInfo true to show progress information to the user
+ */
+ MkdirJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
+
+ /**
+ * @internal
+ * Called by the scheduler when a @p slave gets to
+ * work on this job.
+ * @param slave the slave that starts working on this job
+ */
+ virtual void start( Slave *slave );
+
+ signals:
+ /**
+ * Signals a redirection.
+ * Use to update the URL shown to the user.
+ * The redirection itself is handled internally.
+ * @param job the job that is redirected
+ * @param url the new url
+ */
+ void redirection( TDEIO::Job *job, const KURL &url );
+
+ /**
+ * Signals a permanent redirection.
+ * The redirection itself is handled internally.
+ * @param job the job that is redirected
+ * @param fromUrl the original URL
+ * @param toUrl the new URL
+ */
+ void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
+
+ protected slots:
+ void slotRedirection( const KURL &url);
+ virtual void slotFinished();
+
+ protected:
+ KURL m_redirectionURL;
+
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class MkdirJobPrivate;
+ MkdirJobPrivate *d;
+ };
+
+ /**
+ * @internal
+ * Used for direct copy from or to the local filesystem (i.e. SlaveBase::copy())
+ */
+ class TDEIO_EXPORT DirectCopyJob : public SimpleJob {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a DirectCopyJob. Use TDEIO::copy() or TDEIO::file_copy() instead.
+ */
+ DirectCopyJob(const KURL& url, int command, const TQByteArray &packedArgs,
+ bool showProgressInfo);
+ /**
+ * @internal
+ * Called by the scheduler when a @p slave gets to
+ * work on this job.
+ * @param slave the slave that starts working on this job
+ */
+ virtual void start(Slave *slave);
+
+ signals:
+ /**
+ * @internal
+ * Emitted if the job found an existing partial file
+ * and supports resuming. Used by FileCopyJob.
+ */
+ void canResume( TDEIO::Job *job, TDEIO::filesize_t offset );
+
+ private slots:
+ void slotCanResume( TDEIO::filesize_t offset );
+ };
+
+
+ /**
+ * The transfer job pumps data into and/or out of a Slave.
+ * Data is sent to the slave on request of the slave ( dataReq).
+ * If data coming from the slave can not be handled, the
+ * reading of data from the slave should be suspended.
+ */
+ class TDEIO_EXPORT TransferJob : public SimpleJob {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a TransferJob. Use TDEIO::get() or TDEIO::put()
+ * instead.
+ * @param url the url to get or put
+ * @param command the command to issue
+ * @param packedArgs the arguments
+ * @param _staticData additional data to transmit (e.g. in a HTTP Post)
+ * @param showProgressInfo true to show progress information to the user
+ */
+ TransferJob(const KURL& url, int command,
+ const TQByteArray &packedArgs,
+ const TQByteArray &_staticData,
+ bool showProgressInfo);
+
+ /**
+ * @internal
+ * Called by the scheduler when a @p slave gets to
+ * work on this job.
+ * @param slave the slave that starts working on this job
+ */
+ virtual void start(Slave *slave);
+
+ /**
+ * Called when m_subJob finishes.
+ * @param job the job that finished
+ */
+ virtual void slotResult( TDEIO::Job *job );
+
+ /**
+ * Flow control. Suspend data processing from the slave.
+ */
+ void suspend();
+
+ /**
+ * Flow control. Resume data processing from the slave.
+ */
+ void resume();
+
+ /**
+ * Flow control.
+ * @return true if the job is suspended
+ */
+ bool isSuspended() const { return m_suspended; }
+
+
+ /**
+ * Checks whether we got an error page. This currently only happens
+ * with HTTP urls. Call this from your slot connected to result().
+ *
+ * @return true if we got an (HTML) error page from the server
+ * instead of what we asked for.
+ */
+ bool isErrorPage() const { return m_errorPage; }
+
+ /**
+ * Enable the async data mode.
+ * When async data is enabled, data should be provided to the job by
+ * calling sendAsyncData() instead of returning data in the
+ * dataReq() signal.
+ * @since 3.2
+ */
+ void setAsyncDataEnabled(bool enabled);
+
+ /**
+ * Provide data to the job when async data is enabled.
+ * Should be called exactly once after receiving a dataReq signal
+ * Sending an empty block indicates end of data.
+ * @since 3.2
+ */
+ void sendAsyncData(const TQByteArray &data);
+
+ /**
+ * When enabled, the job reports the amount of data that has been sent,
+ * instead of the amount of data that that has been received.
+ * @see slotProcessedSize
+ * @see slotSpeed
+ * @since 3.2
+ */
+ void setReportDataSent(bool enabled);
+
+ /**
+ * Returns whether the job reports the amount of data that has been
+ * sent (true), or whether the job reports the amount of data that
+ * has been received (false)
+ * @since 3.2
+ */
+ bool reportDataSent();
+
+ signals:
+ /**
+ * Data from the slave has arrived.
+ * @param job the job that emitted this signal
+ * @param data data received from the slave.
+ *
+ * End of data (EOD) has been reached if data.size() == 0, however, you
+ * should not be certain of data.size() == 0 ever happening (e.g. in case
+ * of an error), so you should rely on result() instead.
+ */
+ void data( TDEIO::Job *job, const TQByteArray &data );
+
+ /**
+ * Request for data.
+ * Please note, that you shouldn't put too large chunks
+ * of data in it as this requires copies within the frame
+ * work, so you should rather split the data you want
+ * to pass here in reasonable chunks (about 1MB maximum)
+ *
+ * @param job the job that emitted this signal
+ * @param data buffer to fill with data to send to the
+ * slave. An empty buffer indicates end of data. (EOD)
+ */
+ void dataReq( TDEIO::Job *job, TQByteArray &data );
+
+ /**
+ * Signals a redirection.
+ * Use to update the URL shown to the user.
+ * The redirection itself is handled internally.
+ * @param job the job that emitted this signal
+ * @param url the new URL
+ */
+ void redirection( TDEIO::Job *job, const KURL &url );
+
+ /**
+ * Signals a permanent redirection.
+ * The redirection itself is handled internally.
+ * @param job the job that emitted this signal
+ * @param fromUrl the original URL
+ * @param toUrl the new URL
+ * @since 3.1
+ */
+ void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
+
+ /**
+ * Mimetype determined.
+ * @param job the job that emitted this signal
+ * @param type the mime type
+ */
+ void mimetype( TDEIO::Job *job, const TQString &type );
+
+ /**
+ * @internal
+ * Emitted if the "put" job found an existing partial file
+ * (in which case offset is the size of that file)
+ * and emitted by the "get" job if it supports resuming to
+ * the given offset - in this case @p offset is unused)
+ */
+ void canResume( TDEIO::Job *job, TDEIO::filesize_t offset );
+
+
+ protected slots:
+ virtual void slotRedirection( const KURL &url);
+ virtual void slotFinished();
+ virtual void slotData( const TQByteArray &data);
+ virtual void slotDataReq();
+ virtual void slotMimetype( const TQString &mimetype );
+ virtual void slotNeedSubURLData();
+ virtual void slotSubURLData(TDEIO::Job*, const TQByteArray &);
+ virtual void slotMetaData( const TDEIO::MetaData &_metaData);
+ void slotErrorPage();
+ void slotCanResume( TDEIO::filesize_t offset );
+ void slotPostRedirection();
+
+ protected:
+ bool m_suspended;
+ bool m_errorPage;
+ TQByteArray staticData;
+ KURL m_redirectionURL;
+ KURL::List m_redirectionList;
+ TQString m_mimetype;
+ TransferJob *m_subJob;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class TransferJobPrivate *d;
+ };
+
+ /**
+ * StoredTransferJob is a TransferJob (for downloading or uploading data) that
+ * also stores a TQByteArray with the data, making it simpler to use than the
+ * standard TransferJob.
+ *
+ * For TDEIO::storedGet it puts the data into the member TQByteArray, so the user
+ * of this class can get hold of the whole data at once by calling data()
+ * when the result signal is emitted.
+ * You should only use StoredTransferJob to download data if you cannot
+ * process the data by chunks while it's being downloaded, since storing
+ * everything in a TQByteArray can potentially require a lot of memory.
+ *
+ * For TDEIO::storedPut the user of this class simply provides the bytearray from
+ * the start, and the job takes care of uploading it.
+ * You should only use StoredTransferJob to upload data if you cannot
+ * provide the in chunks while it's being uploaded, since storing
+ * everything in a TQByteArray can potentially require a lot of memory.
+ *
+ * @since 3.3
+ */
+ class TDEIO_EXPORT StoredTransferJob : public TDEIO::TransferJob {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a StoredTransferJob. Use storedGet() or storedPut()
+ * instead.
+ * @param url the url to get or put
+ * @param command the command to issue
+ * @param packedArgs the arguments
+ * @param _staticData additional data to transmit (e.g. in a HTTP Post)
+ * @param showProgressInfo true to show progress information to the user
+ */
+ StoredTransferJob(const KURL& url, int command,
+ const TQByteArray &packedArgs,
+ const TQByteArray &_staticData,
+ bool showProgressInfo);
+
+ /**
+ * Set data to be uploaded. This is for put jobs.
+ * Automatically called by TDEIO::storedPut(const TQByteArray &, ...),
+ * do not call this yourself.
+ */
+ void setData( const TQByteArray& arr );
+
+ /**
+ * Get hold of the downloaded data. This is for get jobs.
+ * You're supposed to call this only from the slot connected to the result() signal.
+ */
+ TQByteArray data() const { return m_data; }
+
+ private slots:
+ void slotStoredData( TDEIO::Job *job, const TQByteArray &data );
+ void slotStoredDataReq( TDEIO::Job *job, TQByteArray &data );
+ private:
+ TQByteArray m_data;
+ int m_uploadOffset;
+ };
+
+ /**
+ * The MultiGetJob is a TransferJob that allows you to get
+ * several files from a single server. Don't create directly,
+ * but use TDEIO::multi_get() instead.
+ * @see TDEIO::multi_get()
+ */
+ class TDEIO_EXPORT MultiGetJob : public TransferJob {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a MultiGetJob directly, use TDEIO::multi_get()
+ * instead.
+ *
+ * @param url the first url to get
+ * @param showProgressInfo true to show progress information to the user
+ */
+ MultiGetJob(const KURL& url, bool showProgressInfo);
+
+ /**
+ * @internal
+ * Called by the scheduler when a @p slave gets to
+ * work on this job.
+ * @param slave the slave that starts working on this job
+ */
+ virtual void start(Slave *slave);
+
+ /**
+ * Get an additional file.
+ *
+ * @param id the id of the file
+ * @param url the url of the file to get
+ * @param metaData the meta data for this request
+ */
+ void get(long id, const KURL &url, const MetaData &metaData);
+
+ signals:
+ /**
+ * Data from the slave has arrived.
+ * @param id the id of the request
+ * @param data data received from the slave.
+ * End of data (EOD) has been reached if data.size() == 0
+ */
+ void data( long id, const TQByteArray &data);
+
+ /**
+ * Mimetype determined
+ * @param id the id of the request
+ * @param type the mime type
+ */
+ void mimetype( long id, const TQString &type );
+
+ /**
+ * File transfer completed.
+ *
+ * When all files have been processed, result(TDEIO::Job *) gets
+ * emitted.
+ * @param id the id of the request
+ */
+ void result( long id);
+
+ protected slots:
+ virtual void slotRedirection( const KURL &url);
+ virtual void slotFinished();
+ virtual void slotData( const TQByteArray &data);
+ virtual void slotMimetype( const TQString &mimetype );
+ private:
+ struct GetRequest {
+ public:
+ GetRequest(long _id, const KURL &_url, const MetaData &_metaData)
+ : id(_id), url(_url), metaData(_metaData) { }
+ long id;
+ KURL url;
+ MetaData metaData;
+ };
+ bool findCurrentEntry();
+ void flushQueue(TQPtrList<GetRequest> &queue);
+
+ TQPtrList<GetRequest> m_waitQueue;
+ TQPtrList<GetRequest> m_activeQueue;
+ bool b_multiGetActive;
+ GetRequest *m_currentEntry;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class MultiGetJobPrivate* d;
+ };
+
+ /**
+ * A MimetypeJob is a TransferJob that allows you to get
+ * the mime type of an URL. Don't create directly,
+ * but use TDEIO::mimetype() instead.
+ * @see TDEIO::mimetype()
+ */
+ class TDEIO_EXPORT MimetypeJob : public TransferJob {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a MimetypeJob directly. Use TDEIO::mimetype()
+ * instead.
+ * @param url the url to get
+ * @param command the command to issue
+ * @param packedArgs the arguments
+ * @param showProgressInfo true to show progress information to the user
+ */
+ MimetypeJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
+
+ /**
+ * Call this in the slot connected to result,
+ * and only after making sure no error happened.
+ * @return the mimetype of the URL
+ */
+ TQString mimetype() const { return m_mimetype; }
+
+ /**
+ * @internal
+ * Called by the scheduler when a slave gets to
+ * work on this job.
+ * @param slave the slave that works on the job
+ */
+ virtual void start( Slave *slave );
+
+ protected slots:
+ virtual void slotFinished( );
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class MimetypeJobPrivate* d;
+ };
+
+ /**
+ * The FileCopyJob copies data from one place to another.
+ * @see TDEIO::file_copy()
+ * @see TDEIO::file_move()
+ */
+ class TDEIO_EXPORT FileCopyJob : public Job {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a FileCopyJob directly. Use TDEIO::file_move()
+ * or TDEIO::file_copy() instead.
+ * @param src the source URL
+ * @param dest the destination URL
+ * @param permissions the permissions of the resulting resource
+ * @param move true to move, false to copy
+ * @param overwrite true to allow overwriting, false otherwise
+ * @param resume true to resume an operation, false otherwise
+ * @param showProgressInfo true to show progress information to the user
+ */
+ FileCopyJob( const KURL& src, const KURL& dest, int permissions,
+ bool move, bool overwrite, bool resume, bool showProgressInfo);
+
+ ~FileCopyJob();
+ /**
+ * If you know the size of the source file, call this method
+ * to inform this job. It will be displayed in the "resume" dialog.
+ * @param size the size of the source file
+ * @since 3.2
+ */
+ void setSourceSize64(TDEIO::filesize_t size);
+
+ /**
+ * Sets the modification time of the file
+ *
+ * Note that this is ignored if a direct copy (SlaveBase::copy) can be done,
+ * in which case the mtime of the source is applied to the destination (if the protocol
+ * supports the concept).
+ */
+ void setModificationTime( time_t mtime );
+
+ /**
+ * @deprecated
+ */
+ void setSourceSize( off_t size ) KDE_DEPRECATED;
+
+ /**
+ * Returns the source URL.
+ * @return the source URL
+ */
+ KURL srcURL() const { return m_src; }
+
+ /**
+ * Returns the destination URL.
+ * @return the destination URL
+ */
+ KURL destURL() const { return m_dest; }
+
+ signals:
+ /**
+ * Mimetype determined during a file copy.
+ * This is never emitted during a move, and might not be emitted during
+ * a copy, depending on the slave.
+ * @param job the job that emitted this signal
+ * @param type the mime type
+ *
+ * @since 3.5.7
+ */
+ void mimetype( TDEIO::Job *job, const TQString &type );
+
+ public slots:
+ void slotStart();
+ void slotData( TDEIO::Job *, const TQByteArray &data);
+ void slotDataReq( TDEIO::Job *, TQByteArray &data);
+ void slotMimetype( TDEIO::Job *, const TQString& type );
+
+ protected slots:
+ /**
+ * Called whenever a subjob finishes.
+ * @param job the job that emitted this signal
+ */
+ virtual void slotResult( TDEIO::Job *job );
+
+ /**
+ * Forward signal from subjob
+ * @param job the job that emitted this signal
+ * @param size the processed size in bytes
+ */
+ void slotProcessedSize( TDEIO::Job *job, TDEIO::filesize_t size );
+ /**
+ * Forward signal from subjob
+ * @param job the job that emitted this signal
+ * @param size the total size
+ */
+ void slotTotalSize( TDEIO::Job *job, TDEIO::filesize_t size );
+ /**
+ * Forward signal from subjob
+ * @param job the job that emitted this signal
+ * @param pct the percentage
+ */
+ void slotPercent( TDEIO::Job *job, unsigned long pct );
+ /**
+ * Forward signal from subjob
+ * @param job the job that emitted this signal
+ * @param offset the offset to resume from
+ */
+ void slotCanResume( TDEIO::Job *job, TDEIO::filesize_t offset );
+
+ protected:
+ void startCopyJob();
+ void startCopyJob(const KURL &slave_url);
+ void startRenameJob(const KURL &slave_url);
+ void startDataPump();
+ void connectSubjob( SimpleJob * job );
+
+ private:
+ void startBestCopyMethod();
+
+ protected:
+ KURL m_src;
+ KURL m_dest;
+ int m_permissions;
+ bool m_move:1;
+ bool m_overwrite:1;
+ bool m_resume:1;
+ bool m_canResume:1;
+ bool m_resumeAnswerSent:1;
+ TQByteArray m_buffer;
+ SimpleJob *m_moveJob;
+ SimpleJob *m_copyJob;
+ TransferJob *m_getJob;
+ TransferJob *m_putJob;
+ TDEIO::filesize_t m_totalSize;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class FileCopyJobPrivate;
+ FileCopyJobPrivate* d;
+ };
+
+ /**
+ * A ListJob is allows you to get the get the content of a directory.
+ * Don't create the job directly, but use TDEIO::listRecursive() or
+ * TDEIO::listDir() instead.
+ * @see TDEIO::listRecursive()
+ * @see TDEIO::listDir()
+ */
+ class TDEIO_EXPORT ListJob : public SimpleJob {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a ListJob directly. Use TDEIO::listDir() or
+ * TDEIO::listRecursive() instead.
+ * @param url the url of the directory
+ * @param showProgressInfo true to show progress information to the user
+ * @param recursive true to get the data recursively from child directories,
+ * false to get only the content of the specified dir
+ * @param prefix the prefix of the files, or TQString::null for no prefix
+ * @param includeHidden true to include hidden files (those starting with '.')
+ */
+ ListJob(const KURL& url, bool showProgressInfo,
+ bool recursive = false, TQString prefix = TQString::null,
+ bool includeHidden = true);
+
+ /**
+ * @internal
+ * Called by the scheduler when a @p slave gets to
+ * work on this job.
+ * @param slave the slave that starts working on this job
+ */
+ virtual void start( Slave *slave );
+
+ /**
+ * Returns the ListJob's redirection URL. This will be invalid if there
+ * was no redirection.
+ * @return the redirection url
+ * @since 3.4.1
+ */
+ const KURL& redirectionURL() const { return m_redirectionURL; }
+
+ /**
+ * Do not apply any KIOSK restrictions to this job.
+ * @since 3.2
+ */
+ void setUnrestricted(bool unrestricted);
+
+ signals:
+ /**
+ * This signal emits the entry found by the job while listing.
+ * The progress signals aren't specific to ListJob. It simply
+ * uses SimpleJob's processedSize (number of entries listed) and
+ * totalSize (total number of entries, if known),
+ * as well as percent.
+ * @param job the job that emitted this signal
+ * @param list the list of UDSEntries
+ */
+ void entries( TDEIO::Job *job, const TDEIO::UDSEntryList& list);
+
+ /**
+ * Signals a redirection.
+ * Use to update the URL shown to the user.
+ * The redirection itself is handled internally.
+ * @param job the job that is redirected
+ * @param url the new url
+ */
+ void redirection( TDEIO::Job *job, const KURL &url );
+
+ /**
+ * Signals a permanent redirection.
+ * The redirection itself is handled internally.
+ * @param job the job that emitted this signal
+ * @param fromUrl the original URL
+ * @param toUrl the new URL
+ * @since 3.1
+ */
+ void permanentRedirection( TDEIO::Job *job, const KURL &fromUrl, const KURL &toUrl );
+
+ protected slots:
+ virtual void slotFinished( );
+ virtual void slotMetaData( const TDEIO::MetaData &_metaData);
+ virtual void slotResult( TDEIO::Job *job );
+ void slotListEntries( const TDEIO::UDSEntryList& list );
+ void slotRedirection( const KURL &url );
+ void gotEntries( TDEIO::Job * subjob, const TDEIO::UDSEntryList& list );
+
+ private:
+ bool recursive;
+ bool includeHidden;
+ TQString prefix;
+ unsigned long m_processedEntries;
+ KURL m_redirectionURL;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class ListJobPrivate* d;
+ };
+
+ /// @internal
+ struct TDEIO_EXPORT CopyInfo
+ {
+ KURL uSource;
+ KURL uDest;
+ TQString linkDest; // for symlinks only
+ int permissions;
+ //mode_t type;
+ time_t ctime;
+ time_t mtime;
+ TDEIO::filesize_t size; // 0 for dirs
+ };
+
+ /**
+ * CopyJob is used to move, copy or symlink files and directories.
+ * Don't create the job directly, but use TDEIO::copy(),
+ * TDEIO::move(), TDEIO::link() and friends.
+ *
+ * @see TDEIO::copy()
+ * @see TDEIO::copyAs()
+ * @see TDEIO::move()
+ * @see TDEIO::moveAs()
+ * @see TDEIO::link()
+ * @see TDEIO::linkAs()
+ */
+ class TDEIO_EXPORT CopyJob : public Job {
+ Q_OBJECT
+
+ public:
+ /**
+ * Defines the mode of the operation
+ */
+ enum CopyMode{ Copy, Move, Link };
+
+ /**
+ * Do not create a CopyJob directly. Use TDEIO::copy(),
+ * TDEIO::move(), TDEIO::link() and friends instead.
+ *
+ * @param src the list of source URLs
+ * @param dest the destination URL
+ * @param mode specifies whether the job should copy, move or link
+ * @param asMethod if true, behaves like TDEIO::copyAs(),
+ * TDEIO::moveAs() or TDEIO::linkAs()
+ * @param showProgressInfo true to show progress information to the user
+ * @see TDEIO::copy()
+ * @see TDEIO::copyAs()
+ * @see TDEIO::move()
+ * @see TDEIO::moveAs()
+ * @see TDEIO::link()
+ * @see TDEIO::linkAs()
+ */
+ CopyJob( const KURL::List& src, const KURL& dest, CopyMode mode, bool asMethod, bool showProgressInfo );
+
+ virtual ~CopyJob();
+
+ /**
+ * Returns the list of source URLs.
+ * @return the list of source URLs.
+ */
+ KURL::List srcURLs() const { return m_srcList; }
+
+ /**
+ * Returns the destination URL.
+ * @return the destination URL
+ */
+ KURL destURL() const { return m_dest; }
+
+ /**
+ * By default the permissions of the copied files will be those of the source files.
+ *
+ * But when copying "template" files to "new" files, people prefer the umask
+ * to apply, rather than the template's permissions.
+ * For that case, call setDefaultPermissions(true)
+ *
+ * TODO KDE4: consider adding this as bool to copy/copyAs?
+ * @since 3.2.3
+ */
+ void setDefaultPermissions( bool b );
+
+ /**
+ * When an error happens while copying/moving a file, the user will be presented with
+ * a dialog for skipping the file that can't be copied/moved.
+ * Or if the error is that the destination file already exists, the standard
+ * rename dialog is shown.
+ * If the program doesn't want CopyJob to show dialogs, but to simply fail on error,
+ * call setInteractive( false ).
+ *
+ * KDE4: remove, already in Job
+ * @since 3.4
+ */
+ void setInteractive( bool b );
+
+ signals:
+
+ /**
+ * Emitted when the total number of files is known.
+ * @param job the job that emitted this signal
+ * @param files the total number of files
+ */
+ void totalFiles( TDEIO::Job *job, unsigned long files );
+ /**
+ * Emitted when the toal number of direcotries is known.
+ * @param job the job that emitted this signal
+ * @param dirs the total number of directories
+ */
+ void totalDirs( TDEIO::Job *job, unsigned long dirs );
+
+ /**
+ * Emitted when it is known which files / directories are going
+ * to be created. Note that this may still change e.g. when
+ * existing files with the same name are discovered.
+ * @param job the job that emitted this signal
+ * @param files a list of items that are about to be created.
+ */
+ void aboutToCreate( TDEIO::Job *job, const TQValueList<TDEIO::CopyInfo> &files);
+
+ /**
+ * Sends the number of processed files.
+ * @param job the job that emitted this signal
+ * @param files the number of processed files
+ */
+ void processedFiles( TDEIO::Job *job, unsigned long files );
+ /**
+ * Sends the number of processed directories.
+ * @param job the job that emitted this signal
+ * @param dirs the number of processed dirs
+ */
+ void processedDirs( TDEIO::Job *job, unsigned long dirs );
+
+ /**
+ * The job is copying a file or directory.
+ * @param job the job that emitted this signal
+ * @param from the URl of the file or directory that is currently
+ * being copied
+ * @param to the destination of the current operation
+ */
+ void copying( TDEIO::Job *job, const KURL& from, const KURL& to );
+ /**
+ * The job is creating a symbolic link.
+ * @param job the job that emitted this signal
+ * @param target the URl of the file or directory that is currently
+ * being linked
+ * @param to the destination of the current operation
+ */
+ void linking( TDEIO::Job *job, const TQString& target, const KURL& to );
+ /**
+ * The job is moving a file or directory.
+ * @param job the job that emitted this signal
+ * @param from the URl of the file or directory that is currently
+ * being moved
+ * @param to the destination of the current operation
+ */
+ void moving( TDEIO::Job *job, const KURL& from, const KURL& to );
+ /**
+ * The job is creating the directory @p dir.
+ * @param job the job that emitted this signal
+ * @param dir the directory that is currently being created
+ */
+ void creatingDir( TDEIO::Job *job, const KURL& dir );
+ /**
+ * The user chose to rename @p from to @p to.
+ * @param job the job that emitted this signal
+ * @param from the original name
+ * @param to the new name
+ */
+ void renamed( TDEIO::Job *job, const KURL& from, const KURL& to );
+
+ /**
+ * The job emits this signal when copying or moving a file or directory successfully finished.
+ * This signal is mainly for the Undo feature.
+ *
+ * @param job the job that emitted this signal
+ * @param from the source URL
+ * @param to the destination URL
+ * @param directory indicates whether a file or directory was successfully copied/moved.
+ * true for a directoy, false for file
+ * @param renamed indicates that the destination URL was created using a
+ * rename operation (i.e. fast directory moving). true if is has been renamed
+ */
+ void copyingDone( TDEIO::Job *job, const KURL &from, const KURL &to, bool directory, bool renamed );
+ /**
+ * The job is copying or moving a symbolic link, that points to target.
+ * The new link is created in @p to. The existing one is/was in @p from.
+ * This signal is mainly for the Undo feature.
+ * @param job the job that emitted this signal
+ * @param from the source URL
+ * @param target the target
+ * @param to the destination URL
+ */
+ void copyingLinkDone( TDEIO::Job *job, const KURL &from, const TQString& target, const KURL& to );
+
+ protected:
+ void statCurrentSrc();
+ void statNextSrc();
+
+ // Those aren't slots but submethods for slotResult.
+ void slotResultStating( TDEIO::Job * job );
+ void startListing( const KURL & src );
+ void slotResultCreatingDirs( TDEIO::Job * job );
+ void slotResultConflictCreatingDirs( TDEIO::Job * job );
+ void createNextDir();
+ void slotResultCopyingFiles( TDEIO::Job * job );
+ void slotResultConflictCopyingFiles( TDEIO::Job * job );
+ void copyNextFile();
+ void slotResultDeletingDirs( TDEIO::Job * job );
+ void deleteNextDir();
+ void skip( const KURL & sourceURL );
+ void slotResultRenaming( TDEIO::Job * job );
+ //void slotResultSettingDirAttributes( TDEIO::Job * job );
+ void setNextDirAttribute();
+ private:
+ void startRenameJob(const KURL &slave_url);
+ bool shouldOverwrite( const TQString& path ) const;
+ bool shouldSkip( const TQString& path ) const;
+ void skipSrc();
+
+ protected slots:
+ void slotStart();
+ void slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& list );
+ virtual void slotResult( TDEIO::Job *job );
+ /**
+ * Forward signal from subjob
+ */
+ void slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size );
+ /**
+ * Forward signal from subjob
+ * @param size the total size
+ */
+ void slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size );
+
+ void slotReport();
+ private:
+ CopyMode m_mode;
+ bool m_asMethod;
+ enum DestinationState { DEST_NOT_STATED, DEST_IS_DIR, DEST_IS_FILE, DEST_DOESNT_EXIST };
+ DestinationState destinationState;
+ enum { STATE_STATING, STATE_RENAMING, STATE_LISTING, STATE_CREATING_DIRS,
+ STATE_CONFLICT_CREATING_DIRS, STATE_COPYING_FILES, STATE_CONFLICT_COPYING_FILES,
+ STATE_DELETING_DIRS, STATE_SETTING_DIR_ATTRIBUTES } state;
+ TDEIO::filesize_t m_totalSize;
+ TDEIO::filesize_t m_processedSize;
+ TDEIO::filesize_t m_fileProcessedSize;
+ int m_processedFiles;
+ int m_processedDirs;
+ TQValueList<CopyInfo> files;
+ TQValueList<CopyInfo> dirs;
+ KURL::List dirsToRemove;
+ KURL::List m_srcList;
+ KURL::List::Iterator m_currentStatSrc;
+ bool m_bCurrentSrcIsDir;
+ bool m_bCurrentOperationIsLink;
+ bool m_bSingleFileCopy;
+ bool m_bOnlyRenames;
+ KURL m_dest;
+ KURL m_currentDest;
+ //
+ TQStringList m_skipList;
+ TQStringList m_overwriteList;
+ bool m_bAutoSkip;
+ bool m_bOverwriteAll;
+ int m_conflictError;
+
+ TQTimer *m_reportTimer;
+ //these both are used for progress dialog reporting
+ KURL m_currentSrcURL;
+ KURL m_currentDestURL;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class CopyJobPrivate;
+ CopyJobPrivate* d;
+ friend class CopyJobPrivate; // for DestinationState
+ };
+
+ /**
+ * A more complex Job to delete files and directories.
+ * Don't create the job directly, but use TDEIO::del() instead.
+ *
+ * @see TDEIO::del()
+ */
+ class TDEIO_EXPORT DeleteJob : public Job {
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not create a DeleteJob directly. Use TDEIO::del()
+ * instead.
+ *
+ * @param src the list of URLs to delete
+ * @param shred true to shred (make sure that data is not recoverable)a
+ * @param showProgressInfo true to show progress information to the user
+ * @see TDEIO::del()
+ */
+ DeleteJob( const KURL::List& src, bool shred, bool showProgressInfo );
+
+ /**
+ * Returns the list of URLs.
+ * @return the list of URLs.
+ */
+ KURL::List urls() const { return m_srcList; }
+
+ signals:
+
+ /**
+ * Emitted when the total number of files is known.
+ * @param job the job that emitted this signal
+ * @param files the total number of files
+ */
+ void totalFiles( TDEIO::Job *job, unsigned long files );
+ /**
+ * Emitted when the toal number of direcotries is known.
+ * @param job the job that emitted this signal
+ * @param dirs the total number of directories
+ */
+ void totalDirs( TDEIO::Job *job, unsigned long dirs );
+
+ /**
+ * Sends the number of processed files.
+ * @param job the job that emitted this signal
+ * @param files the number of processed files
+ */
+ void processedFiles( TDEIO::Job *job, unsigned long files );
+ /**
+ * Sends the number of processed directories.
+ * @param job the job that emitted this signal
+ * @param dirs the number of processed dirs
+ */
+ void processedDirs( TDEIO::Job *job, unsigned long dirs );
+
+ /**
+ * Sends the URL of the file that is currently being deleted.
+ * @param job the job that emitted this signal
+ * @param file the URL of the file or directory that is being
+ * deleted
+ */
+ void deleting( TDEIO::Job *job, const KURL& file );
+
+ protected slots:
+ void slotStart();
+ void slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& list );
+ virtual void slotResult( TDEIO::Job *job );
+
+ /**
+ * Forward signal from subjob
+ */
+ void slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t data_size );
+ void slotReport();
+
+ private:
+ void statNextSrc();
+ void deleteNextFile();
+ void deleteNextDir();
+
+ private:
+ enum { STATE_STATING, STATE_LISTING,
+ STATE_DELETING_FILES, STATE_DELETING_DIRS } state;
+ TDEIO::filesize_t m_totalSize;
+ TDEIO::filesize_t m_processedSize;
+ TDEIO::filesize_t m_fileProcessedSize;
+ int m_processedFiles;
+ int m_processedDirs;
+ int m_totalFilesDirs;
+ KURL m_currentURL;
+ KURL::List files;
+ KURL::List symlinks;
+ KURL::List dirs;
+ KURL::List m_srcList;
+ KURL::List::Iterator m_currentStat;
+ TQStringList m_parentDirs;
+ bool m_shred; // BIC: remove in KDE4
+ TQTimer *m_reportTimer;
+ protected:
+ /** \internal */
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class DeleteJobPrivate* d;
+ };
+
+ /**
+ * A KIO job that finds a local URL
+ * @see TDEIO::localURL()
+ * @since R14.0.0
+ */
+ class TDEIO_EXPORT LocalURLJob : public SimpleJob {
+
+ Q_OBJECT
+
+ public:
+ /**
+ * Do not use this constructor to create a LocalURLJob, use TDEIO::localURL() instead.
+ * @param url the url of the file or directory to check
+ * @param command the command to issue
+ * @param packedArgs the arguments
+ * @param showProgressInfo true to show progress information to the user
+ */
+ LocalURLJob(const KURL& url, int command, const TQByteArray &packedArgs, bool showProgressInfo);
+
+ /**
+ * @internal
+ * Called by the scheduler when a @p slave gets to
+ * work on this job.
+ * @param slave the slave that starts working on this job
+ */
+ virtual void start( Slave *slave );
+
+ signals:
+ /**
+ * @param job the job that emitted this signal
+ * @param url the local url
+ * @param isLocal true if the returned URL is local, false if not
+ */
+ void localURL( TDEIO::Job *job, const KURL &url, bool isLocal );
+
+ protected slots:
+ void slotLocalURL( const KURL &url, bool isLocal );
+ virtual void slotFinished();
+
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class LocalURLJobPrivate;
+ LocalURLJobPrivate *d;
+ };
+
+}
+
+#endif
diff --git a/kio/kio/kacl.cpp b/tdeio/tdeio/kacl.cpp
index 432a50d31..432a50d31 100644
--- a/kio/kio/kacl.cpp
+++ b/tdeio/tdeio/kacl.cpp
diff --git a/tdeio/tdeio/kacl.h b/tdeio/tdeio/kacl.h
new file mode 100644
index 000000000..f581f7a8e
--- /dev/null
+++ b/tdeio/tdeio/kacl.h
@@ -0,0 +1,207 @@
+/* This file is part of the KDE project
+ Copyright (C) 2005 Till Adam <adam@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kacl_h__
+#define __kacl_h__
+
+#include <sys/types.h>
+#include <tdeio/global.h>
+
+typedef QPair<TQString, unsigned short> ACLUserPermissions;
+typedef TQValueList<ACLUserPermissions> ACLUserPermissionsList;
+typedef TQValueListIterator<ACLUserPermissions> ACLUserPermissionsIterator;
+typedef TQValueListConstIterator<ACLUserPermissions> ACLUserPermissionsConstIterator;
+
+typedef QPair<TQString, unsigned short> ACLGroupPermissions;
+typedef TQValueList<ACLGroupPermissions> ACLGroupPermissionsList;
+typedef TQValueListIterator<ACLGroupPermissions> ACLGroupPermissionsIterator;
+typedef TQValueListConstIterator<ACLGroupPermissions> ACLGroupPermissionsConstIterator;
+
+/**
+ * The KCAL class encapsulates a POSIX Access Control List. It follows the
+ * little standard that couldn't, 1003.1e/1003.2c, which died in draft status.
+ * @short a POSIX ACL encapsulation
+ * @author Till Adam <adam@kde.org>
+ */
+class TDEIO_EXPORT KACL
+{
+public:
+ /**
+ * Creates a new KACL from @p aclString. If the string is a valid acl
+ * string, isValid() will afterwards return true.
+ */
+ KACL( const TQString & aclString );
+
+ /** Copy ctor */
+ KACL( const KACL& rhs );
+
+ /**
+ * Creates a new KACL from the basic permissions passed in @p basicPermissions.
+ * isValid() will return true, afterwards.
+ */
+ KACL( mode_t basicPermissions );
+
+ /**
+ * Creates an empty KACL. Until a valid acl string is set via setACL,
+ * isValid() will return false.
+ */
+ KACL();
+
+ virtual ~KACL();
+
+ KACL& operator=( const KACL& rhs ) {
+ if ( this != &rhs )
+ setACL( rhs.asString() );
+ return *this;
+ }
+
+ bool operator==( const KACL& rhs ) const;
+
+ bool operator!=( const KACL& rhs ) const {
+ return !operator==( rhs );
+ }
+
+ /**
+ * Returns whether the KACL object represents a valid acl.
+ * @return whether the KACL object represents a valid acl.
+ */
+ bool isValid() const;
+
+ /** The standard (non-extended) part of an ACL. These map directly to
+ * standard unix file permissions. Setting them will never make a valid
+ * ACL invalid. */
+
+ /** @return the owner's premissions entry */
+ unsigned short ownerPermissions() const;
+
+ /** Set the owner's permissions entry.
+ * @return success or failure */
+ bool setOwnerPermissions( unsigned short );
+
+ /** @return the owning group's premissions entry */
+ unsigned short owningGroupPermissions() const;
+
+ /** Set the owning group's permissions entry.
+ * @return success or failure */
+ bool setOwningGroupPermissions( unsigned short );
+
+ /** @return the premissions entry for others */
+ unsigned short othersPermissions() const;
+
+ /** Set the permissions entry for others.
+ * @return success or failure */
+ bool setOthersPermissions( unsigned short );
+
+ /** @return the basic (owner/group/others) part of the ACL as a mode_t */
+ mode_t basePermissions() const;
+
+ /** The interface to the extended ACL. This is a mask, permissions for
+ * n named users and permissions for m named groups. */
+
+ /**
+ * Return whether the ACL contains extended entries or can be expressed
+ * using only basic file permissions.
+ * @return whether the ACL contains extended entries */
+ bool isExtended() const;
+
+ /**
+ * Return the entry for the permissions mask if there is one and sets
+ * @p exists to true. If there is no such entry, @p exists is set to false.
+ * @return the permissions mask entry */
+ unsigned short maskPermissions( bool &exists ) const;
+
+ /** Set the permissions mask for the ACL. Permissions set for individual
+ * entries will be masked with this, such that their effective permissions
+ * are the result of the logical and of their entry and the mask.
+ * @return success or failure */
+ bool setMaskPermissions( unsigned short );
+
+ /**
+ * Access to the permissions entry for a named user, if such an entry
+ * exists. @p exists is set to true if a matching entry exists and
+ * to false otherwise.
+ * @return the permissions for a user entry with the name in @p name */
+ unsigned short namedUserPermissions( const TQString& name, bool *exists ) const;
+
+
+ /** Set the permissions for a user with the name @p name. Will fail
+ * if the user doesn't exist, in which case the ACL will be unchanged.
+ * @return success or failure. */
+ bool setNamedUserPermissions( const TQString& name, unsigned short );
+
+ /** Returns the list of all group permission entries. Each entry consists
+ * of a name/permissions pair. This is a QPair, therefore access is provided
+ * via the .first and .next members.
+ * @return the list of all group permission entries. */
+ ACLUserPermissionsList allUserPermissions() const;
+
+ /** Replace the list of all user permissions with @p list. If one
+ * of the entries in the list does not exists, or setting of the ACL
+ * entry fails for any reason, the ACL will be left unchanged.
+ * @return success or failure */
+ bool setAllUserPermissions( const ACLUserPermissionsList &list );
+
+ /**
+ * Access to the permissions entry for a named group, if such an entry
+ * exists. @p exists is set to true if a matching entry exists and
+ * to false otherwise.
+ * @return the permissions for a group with the name in @p name */
+ unsigned short namedGroupPermissions( const TQString& name, bool *exists ) const;
+
+ /** Set the permissions for a group with the name @p name. Will fail
+ * if the group doesn't exist, in which case the ACL be unchanged.
+ * @return success or failure. */
+ bool setNamedGroupPermissions( const TQString& name, unsigned short );
+
+ /** Returns the list of all group permission entries. Each entry consists
+ * of a name/permissions pair. This is a QPair, therefor access is provided
+ * via the .first and .next members.
+ * @return the list of all group permission entries. */
+
+ ACLGroupPermissionsList allGroupPermissions() const;
+ /** Replace the list of all user permissions with @p list. If one
+ * of the entries in the list does not exists, or setting of the ACL
+ * entry fails for any reason, the ACL will be left unchanged.
+ * @return success or failure */
+ bool setAllGroupPermissions( const ACLGroupPermissionsList & );
+
+ /** Sets the whole list from a string. If the string in @p aclStr represents
+ * a valid ACL, it will be set, otherwise the ACL remains unchanged.
+ * @return whether setting the ACL was successful. */
+ bool setACL( const TQString &aclStr );
+
+ /** Return a string representation of the ACL.
+ * @return a string version of the ACL in the format compatible with libacl and
+ * POSIX 1003.1e. Implementations conforming to that standard should be able
+ * to take such strings as input. */
+ TQString asString() const;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KACLPrivate;
+ KACLPrivate * d;
+ TDEIO_EXPORT friend TQDataStream & operator<< ( TQDataStream & s, const KACL & a );
+ TDEIO_EXPORT friend TQDataStream & operator>> ( TQDataStream & s, KACL & a );
+};
+
+TDEIO_EXPORT TQDataStream & operator<< ( TQDataStream & s, const KACL & a );
+TDEIO_EXPORT TQDataStream & operator>> ( TQDataStream & s, KACL & a );
+
+#endif
diff --git a/kio/kio/kar.cpp b/tdeio/tdeio/kar.cpp
index 07072d0c6..07072d0c6 100644
--- a/kio/kio/kar.cpp
+++ b/tdeio/tdeio/kar.cpp
diff --git a/kio/kio/kar.h b/tdeio/tdeio/kar.h
index 83d94e75c..83d94e75c 100644
--- a/kio/kio/kar.h
+++ b/tdeio/tdeio/kar.h
diff --git a/kio/kio/karchive.cpp b/tdeio/tdeio/karchive.cpp
index 0e8d6789d..0e8d6789d 100644
--- a/kio/kio/karchive.cpp
+++ b/tdeio/tdeio/karchive.cpp
diff --git a/kio/kio/karchive.h b/tdeio/tdeio/karchive.h
index 840c560b7..840c560b7 100644
--- a/kio/kio/karchive.h
+++ b/tdeio/tdeio/karchive.h
diff --git a/tdeio/tdeio/kautomount.cpp b/tdeio/tdeio/kautomount.cpp
new file mode 100644
index 000000000..f167a6ccb
--- /dev/null
+++ b/tdeio/tdeio/kautomount.cpp
@@ -0,0 +1,117 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kautomount.h"
+#include "krun.h"
+#include "kdirwatch.h"
+#include "tdeio/job.h"
+#include <kdirnotify_stub.h>
+#include <kdebug.h>
+
+/***********************************************************************
+ *
+ * Utility classes
+ *
+ ***********************************************************************/
+
+KAutoMount::KAutoMount( bool _readonly, const TQString& _format, const TQString& _device,
+ const TQString& _mountpoint, const TQString & _desktopFile,
+ bool _show_filemanager_window )
+ : m_strDevice( _device ),
+ m_desktopFile( _desktopFile )
+{
+ //kdDebug(7015) << "KAutoMount device=" << _device << " mountpoint=" << _mountpoint << endl;
+ m_bShowFilemanagerWindow = _show_filemanager_window;
+
+ TDEIO::Job* job = TDEIO::mount( _readonly, _format.ascii(), _device, _mountpoint );
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
+}
+
+void KAutoMount::slotResult( TDEIO::Job * job )
+{
+ if ( job->error() ) {
+ emit error();
+ job->showErrorDialog();
+ }
+ else
+ {
+ KURL mountpoint;
+ mountpoint.setPath( TDEIO::findDeviceMountPoint( m_strDevice ) );
+ //kdDebug(7015) << "KAutoMount: m_strDevice=" << m_strDevice << " -> mountpoint=" << mountpoint << endl;
+ Q_ASSERT( mountpoint.isValid() );
+
+ if ( mountpoint.path().isEmpty() )
+ kdWarning(7015) << m_strDevice << " was correctly mounted, but TDEIO::findDeviceMountPoint didn't find it. "
+ << "This looks like a bug, please report it on http://bugs.kde.org, together with your /etc/fstab line" << endl;
+ else if ( m_bShowFilemanagerWindow )
+ KRun::runURL( mountpoint, "inode/directory" );
+
+ // Notify about the new stuff in that dir, in case of opened windows showing it
+ KDirNotify_stub allDirNotify("*", "KDirNotify*");
+ allDirNotify.FilesAdded( mountpoint );
+
+ // Update the desktop file which is used for mount/unmount (icon change)
+ kdDebug(7015) << " mount finished : updating " << m_desktopFile << endl;
+ KURL dfURL;
+ dfURL.setPath( m_desktopFile );
+ allDirNotify.FilesChanged( dfURL );
+ //KDirWatch::self()->setFileDirty( m_desktopFile );
+
+ emit finished();
+ }
+ delete this;
+}
+
+KAutoUnmount::KAutoUnmount( const TQString & _mountpoint, const TQString & _desktopFile )
+ : m_desktopFile( _desktopFile ), m_mountpoint( _mountpoint )
+{
+ TDEIO::Job * job = TDEIO::unmount( m_mountpoint );
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
+}
+
+void KAutoUnmount::slotResult( TDEIO::Job * job )
+{
+ if ( job->error() ) {
+ emit error();
+ job->showErrorDialog();
+ }
+ else
+ {
+ KDirNotify_stub allDirNotify("*", "KDirNotify*");
+ // Update the desktop file which is used for mount/unmount (icon change)
+ kdDebug(7015) << "unmount finished : updating " << m_desktopFile << endl;
+ KURL dfURL;
+ dfURL.setPath( m_desktopFile );
+ allDirNotify.FilesChanged( dfURL );
+ //KDirWatch::self()->setFileDirty( m_desktopFile );
+
+ // Notify about the new stuff in that dir, in case of opened windows showing it
+ // You may think we removed files, but this may have also readded some
+ // (if the mountpoint wasn't empty). The only possible behavior on FilesAdded
+ // is to relist the directory anyway.
+ KURL mp;
+ mp.setPath( m_mountpoint );
+ allDirNotify.FilesAdded( mp );
+
+ emit finished();
+ }
+
+ delete this;
+}
+
+#include "kautomount.moc"
diff --git a/kio/kio/kautomount.h b/tdeio/tdeio/kautomount.h
index 203c037d9..203c037d9 100644
--- a/kio/kio/kautomount.h
+++ b/tdeio/tdeio/kautomount.h
diff --git a/kio/kio/kdatatool.cpp b/tdeio/tdeio/kdatatool.cpp
index 08630d110..08630d110 100644
--- a/kio/kio/kdatatool.cpp
+++ b/tdeio/tdeio/kdatatool.cpp
diff --git a/kio/kio/kdatatool.h b/tdeio/tdeio/kdatatool.h
index 1258767fc..1258767fc 100644
--- a/kio/kio/kdatatool.h
+++ b/tdeio/tdeio/kdatatool.h
diff --git a/kio/kio/kdcopservicestarter.cpp b/tdeio/tdeio/kdcopservicestarter.cpp
index 3c9b55501..3c9b55501 100644
--- a/kio/kio/kdcopservicestarter.cpp
+++ b/tdeio/tdeio/kdcopservicestarter.cpp
diff --git a/kio/kio/kdcopservicestarter.h b/tdeio/tdeio/kdcopservicestarter.h
index f70f0173e..f70f0173e 100644
--- a/kio/kio/kdcopservicestarter.h
+++ b/tdeio/tdeio/kdcopservicestarter.h
diff --git a/tdeio/tdeio/kdirlister.cpp b/tdeio/tdeio/kdirlister.cpp
new file mode 100644
index 000000000..0d3498aa7
--- /dev/null
+++ b/tdeio/tdeio/kdirlister.cpp
@@ -0,0 +1,2538 @@
+/* This file is part of the KDE project
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2001-2005 Michael Brade <brade@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kdirlister.h"
+
+#include <tqregexp.h>
+#include <tqptrlist.h>
+#include <tqtimer.h>
+#include <tqeventloop.h>
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <tdeio/job.h>
+#include <kmessagebox.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <kstaticdeleter.h>
+#include <kprotocolinfo.h>
+
+#include "kdirlister_p.h"
+
+#include <assert.h>
+#include <unistd.h>
+
+KDirListerCache* KDirListerCache::s_pSelf = 0;
+static KStaticDeleter<KDirListerCache> sd_KDirListerCache;
+
+// Enable this to get printDebug() called often, to see the contents of the cache
+//#define DEBUG_CACHE
+
+// Make really sure it doesn't get activated in the final build
+#ifdef NDEBUG
+#undef DEBUG_CACHE
+#endif
+
+KDirListerCache::KDirListerCache( int maxCount )
+ : itemsCached( maxCount )
+{
+ kdDebug(7004) << "+KDirListerCache" << endl;
+
+ itemsInUse.setAutoDelete( false );
+ itemsCached.setAutoDelete( true );
+ urlsCurrentlyListed.setAutoDelete( true );
+ urlsCurrentlyHeld.setAutoDelete( true );
+ pendingUpdates.setAutoDelete( true );
+
+ connect( kdirwatch, TQT_SIGNAL( dirty( const TQString& ) ),
+ this, TQT_SLOT( slotFileDirty( const TQString& ) ) );
+ connect( kdirwatch, TQT_SIGNAL( created( const TQString& ) ),
+ this, TQT_SLOT( slotFileCreated( const TQString& ) ) );
+ connect( kdirwatch, TQT_SIGNAL( deleted( const TQString& ) ),
+ this, TQT_SLOT( slotFileDeleted( const TQString& ) ) );
+}
+
+KDirListerCache::~KDirListerCache()
+{
+ kdDebug(7004) << "-KDirListerCache" << endl;
+
+ itemsInUse.setAutoDelete( true );
+ itemsInUse.clear();
+ itemsCached.clear();
+ urlsCurrentlyListed.clear();
+ urlsCurrentlyHeld.clear();
+
+ if ( KDirWatch::exists() )
+ kdirwatch->disconnect( this );
+}
+
+// setting _reload to true will emit the old files and
+// call updateDirectory
+bool KDirListerCache::listDir( KDirLister *lister, const KURL& _u,
+ bool _keep, bool _reload )
+{
+ // like this we don't have to worry about trailing slashes any further
+ KURL _url = _u;
+ _url.cleanPath(); // kill consecutive slashes
+ _url.adjustPath(-1);
+ TQString urlStr = _url.url();
+
+ if ( !lister->validURL( _url ) )
+ return false;
+
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+ kdDebug(7004) << k_funcinfo << lister << " url=" << _url
+ << " keep=" << _keep << " reload=" << _reload << endl;
+
+ if ( !_keep )
+ {
+ // stop any running jobs for lister
+ stop( lister );
+
+ // clear our internal list for lister
+ forgetDirs( lister );
+
+ lister->d->rootFileItem = 0;
+ }
+ else if ( lister->d->lstDirs.find( _url ) != lister->d->lstDirs.end() )
+ {
+ // stop the job listing _url for this lister
+ stop( lister, _url );
+
+ // clear _url for lister
+ forgetDirs( lister, _url, true );
+
+ if ( lister->d->url == _url )
+ lister->d->rootFileItem = 0;
+ }
+
+ lister->d->lstDirs.append( _url );
+
+ if ( lister->d->url.isEmpty() || !_keep ) // set toplevel URL only if not set yet
+ lister->d->url = _url;
+
+ DirItem *itemU = itemsInUse[urlStr];
+ DirItem *itemC;
+
+ if ( !urlsCurrentlyListed[urlStr] )
+ {
+ // if there is an update running for _url already we get into
+ // the following case - it will just be restarted by updateDirectory().
+
+ if ( itemU )
+ {
+ kdDebug(7004) << "listDir: Entry already in use: " << _url << endl;
+
+ bool oldState = lister->d->complete;
+ lister->d->complete = false;
+
+ emit lister->started( _url );
+
+ if ( !lister->d->rootFileItem && lister->d->url == _url )
+ lister->d->rootFileItem = itemU->rootItem;
+
+ lister->addNewItems( *(itemU->lstItems) );
+ lister->emitItems();
+
+ // _url is already in use, so there is already an entry in urlsCurrentlyHeld
+ assert( urlsCurrentlyHeld[urlStr] );
+ urlsCurrentlyHeld[urlStr]->append( lister );
+
+ lister->d->complete = oldState;
+
+ emit lister->completed( _url );
+ if ( lister->d->complete )
+ emit lister->completed();
+
+ if ( _reload || !itemU->complete )
+ updateDirectory( _url );
+ }
+ else if ( !_reload && (itemC = itemsCached.take( urlStr )) )
+ {
+ kdDebug(7004) << "listDir: Entry in cache: " << _url << endl;
+
+ itemC->decAutoUpdate();
+ itemsInUse.insert( urlStr, itemC );
+ itemU = itemC;
+
+ bool oldState = lister->d->complete;
+ lister->d->complete = false;
+
+ emit lister->started( _url );
+
+ if ( !lister->d->rootFileItem && lister->d->url == _url )
+ lister->d->rootFileItem = itemC->rootItem;
+
+ lister->addNewItems( *(itemC->lstItems) );
+ lister->emitItems();
+
+ Q_ASSERT( !urlsCurrentlyHeld[urlStr] );
+ TQPtrList<KDirLister> *list = new TQPtrList<KDirLister>;
+ list->append( lister );
+ urlsCurrentlyHeld.insert( urlStr, list );
+
+ lister->d->complete = oldState;
+
+ emit lister->completed( _url );
+ if ( lister->d->complete )
+ emit lister->completed();
+
+ if ( !itemC->complete )
+ updateDirectory( _url );
+ }
+ else // dir not in cache or _reload is true
+ {
+ kdDebug(7004) << "listDir: Entry not in cache or reloaded: " << _url << endl;
+
+ TQPtrList<KDirLister> *list = new TQPtrList<KDirLister>;
+ list->append( lister );
+ urlsCurrentlyListed.insert( urlStr, list );
+
+ itemsCached.remove( urlStr );
+ itemU = new DirItem( _url );
+ itemsInUse.insert( urlStr, itemU );
+
+// // we have a limit of MAX_JOBS_PER_LISTER concurrently running jobs
+// if ( lister->numJobs() >= MAX_JOBS_PER_LISTER )
+// {
+// lstPendingUpdates.append( _url );
+// }
+// else
+// {
+
+ if ( lister->d->url == _url )
+ lister->d->rootFileItem = 0;
+
+ TDEIO::ListJob* job = TDEIO::listDir( _url, false /* no default GUI */ );
+ jobs.insert( job, TQValueList<TDEIO::UDSEntry>() );
+
+ lister->jobStarted( job );
+ lister->connectJob( job );
+
+ if ( lister->d->window )
+ job->setWindow( lister->d->window );
+
+ connect( job, TQT_SIGNAL( entries( TDEIO::Job *, const TDEIO::UDSEntryList & ) ),
+ this, TQT_SLOT( slotEntries( TDEIO::Job *, const TDEIO::UDSEntryList & ) ) );
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ this, TQT_SLOT( slotResult( TDEIO::Job * ) ) );
+ connect( job, TQT_SIGNAL( redirection( TDEIO::Job *, const KURL & ) ),
+ this, TQT_SLOT( slotRedirection( TDEIO::Job *, const KURL & ) ) );
+
+ emit lister->started( _url );
+
+// }
+ }
+ }
+ else
+ {
+ kdDebug(7004) << "listDir: Entry currently being listed: " << _url << endl;
+
+ emit lister->started( _url );
+
+ urlsCurrentlyListed[urlStr]->append( lister );
+
+ TDEIO::ListJob *job = jobForUrl( urlStr );
+ Q_ASSERT( job );
+
+ lister->jobStarted( job );
+ lister->connectJob( job );
+
+ Q_ASSERT( itemU );
+
+ if ( !lister->d->rootFileItem && lister->d->url == _url )
+ lister->d->rootFileItem = itemU->rootItem;
+
+ lister->addNewItems( *(itemU->lstItems) );
+ lister->emitItems();
+ }
+
+ // automatic updating of directories
+ if ( lister->d->autoUpdate )
+ itemU->incAutoUpdate();
+
+ return true;
+}
+
+bool KDirListerCache::validURL( const KDirLister *lister, const KURL& url ) const
+{
+ if ( !url.isValid() )
+ {
+ if ( lister->d->autoErrorHandling )
+ {
+ TQString tmp = i18n("Malformed URL\n%1").arg( url.prettyURL() );
+ KMessageBox::error( lister->d->errorParent, tmp );
+ }
+ return false;
+ }
+
+ if ( !KProtocolInfo::supportsListing( url ) )
+ {
+ if ( lister->d->autoErrorHandling )
+ {
+ // TODO: this message should be changed during next string unfreeze!
+ TQString tmp = i18n("Malformed URL\n%1").arg( url.prettyURL() );
+ KMessageBox::error( lister->d->errorParent, tmp );
+ }
+ return false;
+ }
+
+ return true;
+}
+
+void KDirListerCache::stop( KDirLister *lister )
+{
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+ kdDebug(7004) << k_funcinfo << "lister: " << lister << endl;
+ bool stopped = false;
+
+ TQDictIterator< TQPtrList<KDirLister> > it( urlsCurrentlyListed );
+ TQPtrList<KDirLister> *listers;
+ while ( (listers = it.current()) )
+ {
+ if ( listers->findRef( lister ) > -1 )
+ {
+ // lister is listing url
+ TQString url = it.currentKey();
+
+ //kdDebug(7004) << k_funcinfo << " found lister in list - for " << url << endl;
+ bool ret = listers->removeRef( lister );
+ Q_ASSERT( ret );
+
+ TDEIO::ListJob *job = jobForUrl( url );
+ if ( job )
+ lister->jobDone( job );
+
+ // move lister to urlsCurrentlyHeld
+ TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[url];
+ if ( !holders )
+ {
+ holders = new TQPtrList<KDirLister>;
+ urlsCurrentlyHeld.insert( url, holders );
+ }
+
+ holders->append( lister );
+
+ emit lister->canceled( KURL( url ) );
+
+ //kdDebug(7004) << k_funcinfo << "remaining list: " << listers->count() << " listers" << endl;
+
+ if ( listers->isEmpty() )
+ {
+ // kill the job since it isn't used any more
+ if ( job )
+ killJob( job );
+
+ urlsCurrentlyListed.remove( url );
+ }
+
+ stopped = true;
+ }
+ else
+ ++it;
+ }
+
+ if ( stopped )
+ {
+ emit lister->canceled();
+ lister->d->complete = true;
+ }
+
+ // this is wrong if there is still an update running!
+ //Q_ASSERT( lister->d->complete );
+}
+
+void KDirListerCache::stop( KDirLister *lister, const KURL& _u )
+{
+ TQString urlStr( _u.url(-1) );
+ KURL _url( urlStr );
+
+ // TODO: consider to stop all the "child jobs" of _url as well
+ kdDebug(7004) << k_funcinfo << lister << " url=" << _url << endl;
+
+ TQPtrList<KDirLister> *listers = urlsCurrentlyListed[urlStr];
+ if ( !listers || !listers->removeRef( lister ) )
+ return;
+
+ // move lister to urlsCurrentlyHeld
+ TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[urlStr];
+ if ( !holders )
+ {
+ holders = new TQPtrList<KDirLister>;
+ urlsCurrentlyHeld.insert( urlStr, holders );
+ }
+
+ holders->append( lister );
+
+
+ TDEIO::ListJob *job = jobForUrl( urlStr );
+ if ( job )
+ lister->jobDone( job );
+
+ emit lister->canceled( _url );
+
+ if ( listers->isEmpty() )
+ {
+ // kill the job since it isn't used any more
+ if ( job )
+ killJob( job );
+
+ urlsCurrentlyListed.remove( urlStr );
+ }
+
+ if ( lister->numJobs() == 0 )
+ {
+ lister->d->complete = true;
+
+ // we killed the last job for lister
+ emit lister->canceled();
+ }
+}
+
+void KDirListerCache::setAutoUpdate( KDirLister *lister, bool enable )
+{
+ // IMPORTANT: this method does not check for the current autoUpdate state!
+
+ for ( KURL::List::Iterator it = lister->d->lstDirs.begin();
+ it != lister->d->lstDirs.end(); ++it )
+ {
+ if ( enable )
+ itemsInUse[(*it).url()]->incAutoUpdate();
+ else
+ itemsInUse[(*it).url()]->decAutoUpdate();
+ }
+}
+
+void KDirListerCache::forgetDirs( KDirLister *lister )
+{
+ kdDebug(7004) << k_funcinfo << lister << endl;
+
+ emit lister->clear();
+
+ // forgetDirs() will modify lstDirs, make a copy first
+ KURL::List lstDirsCopy = lister->d->lstDirs;
+ for ( KURL::List::Iterator it = lstDirsCopy.begin();
+ it != lstDirsCopy.end(); ++it )
+ {
+ forgetDirs( lister, *it, false );
+ }
+}
+
+void KDirListerCache::forgetDirs( KDirLister *lister, const KURL& _url, bool notify )
+{
+ kdDebug(7004) << k_funcinfo << lister << " _url: " << _url << endl;
+
+ KURL url( _url );
+ url.adjustPath( -1 );
+ TQString urlStr = url.url();
+ TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[urlStr];
+ //Q_ASSERT( holders );
+ if ( holders )
+ {
+ holders->removeRef( lister );
+ }
+
+ // remove the dir from lister->d->lstDirs so that it doesn't contain things
+ // that itemsInUse doesn't. When emitting the canceled signals lstDirs must
+ // not contain anything that itemsInUse does not contain. (otherwise it
+ // might crash in findByName()).
+ lister->d->lstDirs.remove( lister->d->lstDirs.find( url ) );
+
+ DirItem *item = itemsInUse[urlStr];
+
+ if ( holders && holders->isEmpty() )
+ {
+ urlsCurrentlyHeld.remove( urlStr ); // this deletes the (empty) holders list
+ if ( !urlsCurrentlyListed[urlStr] )
+ {
+ // item not in use anymore -> move into cache if complete
+ itemsInUse.remove( urlStr );
+
+ // this job is a running update
+ TDEIO::ListJob *job = jobForUrl( urlStr );
+ if ( job )
+ {
+ lister->jobDone( job );
+ killJob( job );
+ kdDebug(7004) << k_funcinfo << "Killing update job for " << urlStr << endl;
+
+ emit lister->canceled( url );
+ if ( lister->numJobs() == 0 )
+ {
+ lister->d->complete = true;
+ emit lister->canceled();
+ }
+ }
+
+ if ( notify )
+ emit lister->clear( url );
+
+ if ( item && item->complete )
+ {
+ kdDebug(7004) << k_funcinfo << lister << " item moved into cache: " << url << endl;
+ itemsCached.insert( urlStr, item ); // TODO: may return false!!
+
+ // Should we forget the dir for good, or keep a watch on it?
+ // Generally keep a watch, except when it would prevent
+ // unmounting a removable device (#37780)
+ const bool isLocal = item->url.isLocalFile();
+ const bool isManuallyMounted = isLocal && TDEIO::manually_mounted( item->url.path() );
+ bool containsManuallyMounted = false;
+ if ( !isManuallyMounted && item->lstItems && isLocal )
+ {
+ // Look for a manually-mounted directory inside
+ // If there's one, we can't keep a watch either, FAM would prevent unmounting the CDROM
+ // I hope this isn't too slow (manually_mounted caches the last device so most
+ // of the time this is just a stat per subdir)
+ KFileItemListIterator kit( *item->lstItems );
+ for ( ; kit.current() && !containsManuallyMounted; ++kit )
+ if ( (*kit)->isDir() && TDEIO::manually_mounted( (*kit)->url().path() ) )
+ containsManuallyMounted = true;
+ }
+
+ if ( isManuallyMounted || containsManuallyMounted )
+ {
+ kdDebug(7004) << "Not adding a watch on " << item->url << " because it " <<
+ ( isManuallyMounted ? "is manually mounted" : "contains a manually mounted subdir" ) << endl;
+ item->complete = false; // set to "dirty"
+ }
+ else
+ item->incAutoUpdate(); // keep watch
+ }
+ else
+ {
+ delete item;
+ item = 0;
+ }
+ }
+ }
+
+ if ( item && lister->d->autoUpdate )
+ item->decAutoUpdate();
+}
+
+void KDirListerCache::updateDirectory( const KURL& _dir )
+{
+ kdDebug(7004) << k_funcinfo << _dir << endl;
+
+ TQString urlStr = _dir.url(-1);
+ if ( !checkUpdate( urlStr ) )
+ return;
+
+ // A job can be running to
+ // - only list a new directory: the listers are in urlsCurrentlyListed
+ // - only update a directory: the listers are in urlsCurrentlyHeld
+ // - update a currently running listing: the listers are in urlsCurrentlyListed
+ // and urlsCurrentlyHeld
+
+ TQPtrList<KDirLister> *listers = urlsCurrentlyListed[urlStr];
+ TQPtrList<KDirLister> *holders = urlsCurrentlyHeld[urlStr];
+
+ // restart the job for _dir if it is running already
+ bool killed = false;
+ TQWidget *window = 0;
+ TDEIO::ListJob *job = jobForUrl( urlStr );
+ if ( job )
+ {
+ window = job->window();
+
+ killJob( job );
+ killed = true;
+
+ if ( listers )
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->jobDone( job );
+
+ if ( holders )
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ kdl->jobDone( job );
+ }
+ kdDebug(7004) << k_funcinfo << "Killed = " << killed << endl;
+
+ // we don't need to emit canceled signals since we only replaced the job,
+ // the listing is continuing.
+
+ Q_ASSERT( !listers || (listers && killed) );
+
+ job = TDEIO::listDir( _dir, false /* no default GUI */ );
+ jobs.insert( job, TQValueList<TDEIO::UDSEntry>() );
+
+ connect( job, TQT_SIGNAL(entries( TDEIO::Job *, const TDEIO::UDSEntryList & )),
+ this, TQT_SLOT(slotUpdateEntries( TDEIO::Job *, const TDEIO::UDSEntryList & )) );
+ connect( job, TQT_SIGNAL(result( TDEIO::Job * )),
+ this, TQT_SLOT(slotUpdateResult( TDEIO::Job * )) );
+
+ kdDebug(7004) << k_funcinfo << "update started in " << _dir << endl;
+
+ if ( listers )
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->jobStarted( job );
+
+ if ( holders )
+ {
+ if ( !killed )
+ {
+ bool first = true;
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ {
+ kdl->jobStarted( job );
+ if ( first && kdl->d->window )
+ {
+ first = false;
+ job->setWindow( kdl->d->window );
+ }
+ emit kdl->started( _dir );
+ }
+ }
+ else
+ {
+ job->setWindow( window );
+
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ kdl->jobStarted( job );
+ }
+ }
+}
+
+bool KDirListerCache::checkUpdate( const TQString& _dir )
+{
+ if ( !itemsInUse[_dir] )
+ {
+ DirItem *item = itemsCached[_dir];
+ if ( item && item->complete )
+ {
+ item->complete = false;
+ item->decAutoUpdate();
+ // Hmm, this debug output might include login/password from the _dir URL.
+ //kdDebug(7004) << k_funcinfo << "directory " << _dir << " not in use, marked dirty." << endl;
+ }
+ //else
+ //kdDebug(7004) << k_funcinfo << "aborted, directory " << _dir << " not in cache." << endl;
+
+ return false;
+ }
+ else
+ return true;
+}
+
+KFileItemList *KDirListerCache::itemsForDir( const KURL &_dir ) const
+{
+ TQString urlStr = _dir.url(-1);
+ DirItem *item = itemsInUse[ urlStr ];
+ if ( !item )
+ item = itemsCached[ urlStr ];
+ return item ? item->lstItems : 0;
+}
+
+KFileItem *KDirListerCache::findByName( const KDirLister *lister, const TQString& _name ) const
+{
+ Q_ASSERT( lister );
+
+ for ( KURL::List::Iterator it = lister->d->lstDirs.begin();
+ it != lister->d->lstDirs.end(); ++it )
+ {
+ KFileItemListIterator kit( *itemsInUse[(*it).url()]->lstItems );
+ for ( ; kit.current(); ++kit )
+ if ( (*kit)->name() == _name )
+ return (*kit);
+ }
+
+ return 0L;
+}
+
+KFileItem *KDirListerCache::findByURL( const KDirLister *lister, const KURL& _u ) const
+{
+ KURL _url = _u;
+ _url.adjustPath(-1);
+
+ KURL parentDir( _url );
+ parentDir.setPath( parentDir.directory() );
+
+ // If lister is set, check that it contains this dir
+ if ( lister && !lister->d->lstDirs.contains( parentDir ) )
+ return 0L;
+
+ KFileItemList *itemList = itemsForDir( parentDir );
+ if ( itemList )
+ {
+ KFileItemListIterator kit( *itemList );
+ for ( ; kit.current(); ++kit )
+ if ( (*kit)->url() == _url )
+ return (*kit);
+ }
+ return 0L;
+}
+
+void KDirListerCache::FilesAdded( const KURL &dir )
+{
+ kdDebug(7004) << k_funcinfo << dir << endl;
+ updateDirectory( dir );
+}
+
+void KDirListerCache::FilesRemoved( const KURL::List &fileList )
+{
+ kdDebug(7004) << k_funcinfo << endl;
+ KURL::List::ConstIterator it = fileList.begin();
+ for ( ; it != fileList.end() ; ++it )
+ {
+ // emit the deleteItem signal if this file was shown in any view
+ KFileItem *fileitem = 0L;
+ KURL parentDir( *it );
+ parentDir.setPath( parentDir.directory() );
+ KFileItemList *lstItems = itemsForDir( parentDir );
+ if ( lstItems )
+ {
+ KFileItem *fit = lstItems->first();
+ for ( ; fit; fit = lstItems->next() )
+ if ( fit->url() == *it ) {
+ fileitem = fit;
+ lstItems->take(); // remove fileitem from list
+ break;
+ }
+ }
+
+ // Tell the views about it before deleting the KFileItems. They might need the subdirs'
+ // file items (see the dirtree).
+ if ( fileitem )
+ {
+ TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[parentDir.url()];
+ if ( listers )
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->emitDeleteItem( fileitem );
+ }
+
+ // If we found a fileitem, we can test if it's a dir. If not, we'll go to deleteDir just in case.
+ if ( !fileitem || fileitem->isDir() )
+ {
+ // in case of a dir, check if we have any known children, there's much to do in that case
+ // (stopping jobs, removing dirs from cache etc.)
+ deleteDir( *it );
+ }
+
+ // now remove the item itself
+ delete fileitem;
+ }
+}
+
+void KDirListerCache::FilesChanged( const KURL::List &fileList )
+{
+ KURL::List dirsToUpdate;
+ kdDebug(7004) << k_funcinfo << "only half implemented" << endl;
+ KURL::List::ConstIterator it = fileList.begin();
+ for ( ; it != fileList.end() ; ++it )
+ {
+ if ( ( *it ).isLocalFile() )
+ {
+ kdDebug(7004) << "KDirListerCache::FilesChanged " << *it << endl;
+ KFileItem *fileitem = findByURL( 0, *it );
+ if ( fileitem )
+ {
+ // we need to refresh the item, because e.g. the permissions can have changed.
+ aboutToRefreshItem( fileitem );
+ fileitem->refresh();
+ emitRefreshItem( fileitem );
+ }
+ else
+ kdDebug(7004) << "item not found" << endl;
+ } else {
+ // For remote files, refresh() won't be able to figure out the new information.
+ // Let's update the dir.
+ KURL dir( *it );
+ dir.setPath( dir.directory( true ) );
+ if ( dirsToUpdate.find( dir ) == dirsToUpdate.end() )
+ dirsToUpdate.prepend( dir );
+ }
+ }
+
+ KURL::List::ConstIterator itdir = dirsToUpdate.begin();
+ for ( ; itdir != dirsToUpdate.end() ; ++itdir )
+ updateDirectory( *itdir );
+ // ## TODO problems with current jobs listing/updating that dir
+ // ( see kde-2.2.2's kdirlister )
+}
+
+void KDirListerCache::FileRenamed( const KURL &src, const KURL &dst )
+{
+ kdDebug(7004) << k_funcinfo << src.prettyURL() << " -> " << dst.prettyURL() << endl;
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+
+ // Somehow this should only be called if src is a dir. But how could we know if it is?
+ // (Note that looking into itemsInUse isn't good enough. One could rename a subdir in a view.)
+ renameDir( src, dst );
+
+ // Now update the KFileItem representing that file or dir (not exclusive with the above!)
+ KURL oldurl( src );
+ oldurl.adjustPath( -1 );
+ KFileItem *fileitem = findByURL( 0, oldurl );
+ if ( fileitem )
+ {
+ if ( !fileitem->isLocalFile() && !fileitem->localPath().isEmpty() ) // it uses UDS_LOCAL_PATH? ouch, needs an update then
+ FilesChanged( src );
+ else
+ {
+ aboutToRefreshItem( fileitem );
+ fileitem->setURL( dst );
+ fileitem->refreshMimeType();
+ emitRefreshItem( fileitem );
+ }
+ }
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+}
+
+void KDirListerCache::aboutToRefreshItem( KFileItem *fileitem )
+{
+ // Look whether this item was shown in any view, i.e. held by any dirlister
+ KURL parentDir( fileitem->url() );
+ parentDir.setPath( parentDir.directory() );
+ TQString parentDirURL = parentDir.url();
+ TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[parentDirURL];
+ if ( listers )
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->aboutToRefreshItem( fileitem );
+
+ // Also look in urlsCurrentlyListed, in case the user manages to rename during a listing
+ listers = urlsCurrentlyListed[parentDirURL];
+ if ( listers )
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->aboutToRefreshItem( fileitem );
+}
+
+void KDirListerCache::emitRefreshItem( KFileItem *fileitem )
+{
+ // Look whether this item was shown in any view, i.e. held by any dirlister
+ KURL parentDir( fileitem->url() );
+ parentDir.setPath( parentDir.directory() );
+ TQString parentDirURL = parentDir.url();
+ TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[parentDirURL];
+ if ( listers )
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ kdl->addRefreshItem( fileitem );
+ kdl->emitItems();
+ }
+
+ // Also look in urlsCurrentlyListed, in case the user manages to rename during a listing
+ listers = urlsCurrentlyListed[parentDirURL];
+ if ( listers )
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ kdl->addRefreshItem( fileitem );
+ kdl->emitItems();
+ }
+}
+
+KDirListerCache* KDirListerCache::self()
+{
+ if ( !s_pSelf )
+ s_pSelf = sd_KDirListerCache.setObject( s_pSelf, new KDirListerCache );
+
+ return s_pSelf;
+}
+
+bool KDirListerCache::exists()
+{
+ return s_pSelf != 0;
+}
+
+
+// private slots
+
+// _file can also be a directory being currently held!
+void KDirListerCache::slotFileDirty( const TQString& _file )
+{
+ kdDebug(7004) << k_funcinfo << _file << endl;
+
+ if ( !pendingUpdates[_file] )
+ {
+ KURL dir;
+ dir.setPath( _file );
+ if ( checkUpdate( dir.url(-1) ) )
+ updateDirectory( dir );
+
+ // the parent directory of _file
+ dir.setPath( dir.directory() );
+ if ( checkUpdate( dir.url() ) )
+ {
+ // Nice hack to save memory: use the qt object name to store the filename
+ TQTimer *timer = new TQTimer( this, _file.utf8() );
+ connect( timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotFileDirtyDelayed()) );
+ pendingUpdates.insert( _file, timer );
+ timer->start( 500, true );
+ }
+ }
+}
+
+// delayed updating of files, FAM is flooding us with events
+void KDirListerCache::slotFileDirtyDelayed()
+{
+ TQString file = TQString::fromUtf8( TQT_TQOBJECT_CONST(sender())->name() );
+
+ kdDebug(7004) << k_funcinfo << file << endl;
+
+ // TODO: do it better: don't always create/delete the TQTimer but reuse it.
+ // Delete the timer after the parent directory is removed from the cache.
+ pendingUpdates.remove( file );
+
+ KURL u;
+ u.setPath( file );
+ KFileItem *item = findByURL( 0, u ); // search all items
+ if ( item )
+ {
+ // we need to refresh the item, because e.g. the permissions can have changed.
+ aboutToRefreshItem( item );
+ item->refresh();
+ emitRefreshItem( item );
+ }
+}
+
+void KDirListerCache::slotFileCreated( const TQString& _file )
+{
+ kdDebug(7004) << k_funcinfo << _file << endl;
+ // XXX: how to avoid a complete rescan here?
+ KURL u;
+ u.setPath( _file );
+ u.setPath( u.directory() );
+ FilesAdded( u );
+}
+
+void KDirListerCache::slotFileDeleted( const TQString& _file )
+{
+ kdDebug(7004) << k_funcinfo << _file << endl;
+ KURL u;
+ u.setPath( _file );
+ FilesRemoved( u );
+}
+
+void KDirListerCache::slotEntries( TDEIO::Job *job, const TDEIO::UDSEntryList &entries )
+{
+ KURL url = joburl( static_cast<TDEIO::ListJob *>(job) );
+ url.adjustPath(-1);
+ TQString urlStr = url.url();
+
+ kdDebug(7004) << k_funcinfo << "new entries for " << url << endl;
+
+ DirItem *dir = itemsInUse[urlStr];
+ Q_ASSERT( dir );
+
+ TQPtrList<KDirLister> *listers = urlsCurrentlyListed[urlStr];
+ Q_ASSERT( listers );
+ Q_ASSERT( !listers->isEmpty() );
+
+ // check if anyone wants the mimetypes immediately
+ bool delayedMimeTypes = true;
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ delayedMimeTypes = delayedMimeTypes && kdl->d->delayedMimeTypes;
+
+ // avoid creating these QStrings again and again
+ static const TQString& dot = TDEGlobal::staticQString(".");
+ static const TQString& dotdot = TDEGlobal::staticQString("..");
+
+ TDEIO::UDSEntryListConstIterator it = entries.begin();
+ TDEIO::UDSEntryListConstIterator end = entries.end();
+
+ for ( ; it != end; ++it )
+ {
+ TQString name;
+
+ // find out about the name
+ TDEIO::UDSEntry::ConstIterator entit = (*it).begin();
+ for( ; entit != (*it).end(); ++entit )
+ if ( (*entit).m_uds == TDEIO::UDS_NAME )
+ {
+ name = (*entit).m_str;
+ break;
+ }
+
+ Q_ASSERT( !name.isEmpty() );
+ if ( name.isEmpty() )
+ continue;
+
+ if ( name == dot )
+ {
+ Q_ASSERT( !dir->rootItem );
+ dir->rootItem = new KFileItem( *it, url, delayedMimeTypes, true );
+
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ if ( !kdl->d->rootFileItem && kdl->d->url == url )
+ kdl->d->rootFileItem = dir->rootItem;
+ }
+ else if ( name != dotdot )
+ {
+ KFileItem* item = new KFileItem( *it, url, delayedMimeTypes, true );
+ Q_ASSERT( item );
+
+ //kdDebug(7004)<< "Adding item: " << item->url() << endl;
+ dir->lstItems->append( item );
+
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->addNewItem( item );
+ }
+ }
+
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->emitItems();
+}
+
+void KDirListerCache::slotResult( TDEIO::Job *j )
+{
+ Q_ASSERT( j );
+ TDEIO::ListJob *job = static_cast<TDEIO::ListJob *>( j );
+ jobs.remove( job );
+
+ KURL jobUrl = joburl( job );
+ jobUrl.adjustPath(-1); // need remove trailing slashes again, in case of redirections
+ TQString jobUrlStr = jobUrl.url();
+
+ kdDebug(7004) << k_funcinfo << "finished listing " << jobUrl << endl;
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+
+ TQPtrList<KDirLister> *listers = urlsCurrentlyListed.take( jobUrlStr );
+ Q_ASSERT( listers );
+
+ // move the directory to the held directories, do it before emitting
+ // the signals to make sure it exists in KDirListerCache in case someone
+ // calls listDir during the signal emission
+ Q_ASSERT( !urlsCurrentlyHeld[jobUrlStr] );
+ urlsCurrentlyHeld.insert( jobUrlStr, listers );
+
+ KDirLister *kdl;
+
+ if ( job->error() )
+ {
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ kdl->jobDone( job );
+ kdl->handleError( job );
+ emit kdl->canceled( jobUrl );
+ if ( kdl->numJobs() == 0 )
+ {
+ kdl->d->complete = true;
+ emit kdl->canceled();
+ }
+ }
+ }
+ else
+ {
+ DirItem *dir = itemsInUse[jobUrlStr];
+ Q_ASSERT( dir );
+ dir->complete = true;
+
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ kdl->jobDone( job );
+ emit kdl->completed( jobUrl );
+ if ( kdl->numJobs() == 0 )
+ {
+ kdl->d->complete = true;
+ emit kdl->completed();
+ }
+ }
+ }
+
+ // TODO: hmm, if there was an error and job is a parent of one or more
+ // of the pending urls we should cancel it/them as well
+ processPendingUpdates();
+
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+}
+
+void KDirListerCache::slotRedirection( TDEIO::Job *j, const KURL& url )
+{
+ Q_ASSERT( j );
+ TDEIO::ListJob *job = static_cast<TDEIO::ListJob *>( j );
+
+ KURL oldUrl = job->url(); // here we really need the old url!
+ KURL newUrl = url;
+
+ // strip trailing slashes
+ oldUrl.adjustPath(-1);
+ newUrl.adjustPath(-1);
+
+ if ( oldUrl == newUrl )
+ {
+ kdDebug(7004) << k_funcinfo << "New redirection url same as old, giving up." << endl;
+ return;
+ }
+
+ kdDebug(7004) << k_funcinfo << oldUrl.prettyURL() << " -> " << newUrl.prettyURL() << endl;
+
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+
+ // I don't think there can be dirItems that are childs of oldUrl.
+ // Am I wrong here? And even if so, we don't need to delete them, right?
+ // DF: redirection happens before listDir emits any item. Makes little sense otherwise.
+
+ // oldUrl cannot be in itemsCached because only completed items are moved there
+ DirItem *dir = itemsInUse.take( oldUrl.url() );
+ Q_ASSERT( dir );
+
+ TQPtrList<KDirLister> *listers = urlsCurrentlyListed.take( oldUrl.url() );
+ Q_ASSERT( listers );
+ Q_ASSERT( !listers->isEmpty() );
+
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ // TODO: put in own method?
+ if ( kdl->d->url.equals( oldUrl, true ) )
+ {
+ kdl->d->rootFileItem = 0;
+ kdl->d->url = newUrl;
+ }
+
+ *kdl->d->lstDirs.find( oldUrl ) = newUrl;
+
+ if ( kdl->d->lstDirs.count() == 1 )
+ {
+ emit kdl->clear();
+ emit kdl->redirection( newUrl );
+ emit kdl->redirection( oldUrl, newUrl );
+ }
+ else
+ {
+ emit kdl->clear( oldUrl );
+ emit kdl->redirection( oldUrl, newUrl );
+ }
+ }
+
+ // when a lister was stopped before the job emits the redirection signal, the old url will
+ // also be in urlsCurrentlyHeld
+ TQPtrList<KDirLister> *holders = urlsCurrentlyHeld.take( oldUrl.url() );
+ if ( holders )
+ {
+ Q_ASSERT( !holders->isEmpty() );
+
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ {
+ kdl->jobStarted( job );
+
+ // do it like when starting a new list-job that will redirect later
+ emit kdl->started( oldUrl );
+
+ // TODO: maybe don't emit started if there's an update running for newUrl already?
+
+ if ( kdl->d->url.equals( oldUrl, true ) )
+ {
+ kdl->d->rootFileItem = 0;
+ kdl->d->url = newUrl;
+ }
+
+ *kdl->d->lstDirs.find( oldUrl ) = newUrl;
+
+ if ( kdl->d->lstDirs.count() == 1 )
+ {
+ emit kdl->clear();
+ emit kdl->redirection( newUrl );
+ emit kdl->redirection( oldUrl, newUrl );
+ }
+ else
+ {
+ emit kdl->clear( oldUrl );
+ emit kdl->redirection( oldUrl, newUrl );
+ }
+ }
+ }
+
+ DirItem *newDir = itemsInUse[newUrl.url()];
+ if ( newDir )
+ {
+ kdDebug(7004) << "slotRedirection: " << newUrl.url() << " already in use" << endl;
+
+ // only in this case there can newUrl already be in urlsCurrentlyListed or urlsCurrentlyHeld
+ delete dir;
+
+ // get the job if one's running for newUrl already (can be a list-job or an update-job), but
+ // do not return this 'job', which would happen because of the use of redirectionURL()
+ TDEIO::ListJob *oldJob = jobForUrl( newUrl.url(), job );
+
+ // listers of newUrl with oldJob: forget about the oldJob and use the already running one
+ // which will be converted to an updateJob
+ TQPtrList<KDirLister> *curListers = urlsCurrentlyListed[newUrl.url()];
+ if ( curListers )
+ {
+ kdDebug(7004) << "slotRedirection: and it is currently listed" << endl;
+
+ Q_ASSERT( oldJob ); // ?!
+
+ for ( KDirLister *kdl = curListers->first(); kdl; kdl = curListers->next() ) // listers of newUrl
+ {
+ kdl->jobDone( oldJob );
+
+ kdl->jobStarted( job );
+ kdl->connectJob( job );
+ }
+
+ // append listers of oldUrl with newJob to listers of newUrl with oldJob
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ curListers->append( kdl );
+ }
+ else
+ urlsCurrentlyListed.insert( newUrl.url(), listers );
+
+ if ( oldJob ) // kill the old job, be it a list-job or an update-job
+ killJob( oldJob );
+
+ // holders of newUrl: use the already running job which will be converted to an updateJob
+ TQPtrList<KDirLister> *curHolders = urlsCurrentlyHeld[newUrl.url()];
+ if ( curHolders )
+ {
+ kdDebug(7004) << "slotRedirection: and it is currently held." << endl;
+
+ for ( KDirLister *kdl = curHolders->first(); kdl; kdl = curHolders->next() ) // holders of newUrl
+ {
+ kdl->jobStarted( job );
+ emit kdl->started( newUrl );
+ }
+
+ // append holders of oldUrl to holders of newUrl
+ if ( holders )
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ curHolders->append( kdl );
+ }
+ else if ( holders )
+ urlsCurrentlyHeld.insert( newUrl.url(), holders );
+
+
+ // emit old items: listers, holders. NOT: newUrlListers/newUrlHolders, they already have them listed
+ // TODO: make this a separate method?
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
+ kdl->d->rootFileItem = newDir->rootItem;
+
+ kdl->addNewItems( *(newDir->lstItems) );
+ kdl->emitItems();
+ }
+
+ if ( holders )
+ {
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ {
+ if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
+ kdl->d->rootFileItem = newDir->rootItem;
+
+ kdl->addNewItems( *(newDir->lstItems) );
+ kdl->emitItems();
+ }
+ }
+ }
+ else if ( (newDir = itemsCached.take( newUrl.url() )) )
+ {
+ kdDebug(7004) << "slotRedirection: " << newUrl.url() << " is unused, but already in the cache." << endl;
+
+ delete dir;
+ itemsInUse.insert( newUrl.url(), newDir );
+ urlsCurrentlyListed.insert( newUrl.url(), listers );
+ if ( holders )
+ urlsCurrentlyHeld.insert( newUrl.url(), holders );
+
+ // emit old items: listers, holders
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
+ kdl->d->rootFileItem = newDir->rootItem;
+
+ kdl->addNewItems( *(newDir->lstItems) );
+ kdl->emitItems();
+ }
+
+ if ( holders )
+ {
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ {
+ if ( !kdl->d->rootFileItem && kdl->d->url == newUrl )
+ kdl->d->rootFileItem = newDir->rootItem;
+
+ kdl->addNewItems( *(newDir->lstItems) );
+ kdl->emitItems();
+ }
+ }
+ }
+ else
+ {
+ kdDebug(7004) << "slotRedirection: " << newUrl.url() << " has not been listed yet." << endl;
+
+ delete dir->rootItem;
+ dir->rootItem = 0;
+ dir->lstItems->clear();
+ dir->redirect( newUrl );
+ itemsInUse.insert( newUrl.url(), dir );
+ urlsCurrentlyListed.insert( newUrl.url(), listers );
+
+ if ( holders )
+ urlsCurrentlyHeld.insert( newUrl.url(), holders );
+ else
+ {
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+ return; // only in this case the job doesn't need to be converted,
+ }
+ }
+
+ // make the job an update job
+ job->disconnect( this );
+
+ connect( job, TQT_SIGNAL(entries( TDEIO::Job *, const TDEIO::UDSEntryList & )),
+ this, TQT_SLOT(slotUpdateEntries( TDEIO::Job *, const TDEIO::UDSEntryList & )) );
+ connect( job, TQT_SIGNAL(result( TDEIO::Job * )),
+ this, TQT_SLOT(slotUpdateResult( TDEIO::Job * )) );
+
+ // FIXME: autoUpdate-Counts!!
+
+#ifdef DEBUG_CACHE
+ printDebug();
+#endif
+}
+
+void KDirListerCache::renameDir( const KURL &oldUrl, const KURL &newUrl )
+{
+ kdDebug(7004) << k_funcinfo << oldUrl.prettyURL() << " -> " << newUrl.prettyURL() << endl;
+ TQString oldUrlStr = oldUrl.url(-1);
+ TQString newUrlStr = newUrl.url(-1);
+
+ // Not enough. Also need to look at any child dir, even sub-sub-sub-dir.
+ //DirItem *dir = itemsInUse.take( oldUrlStr );
+ //emitRedirections( oldUrl, url );
+
+ // Look at all dirs being listed/shown
+ TQDictIterator<DirItem> itu( itemsInUse );
+ bool goNext;
+ while ( itu.current() )
+ {
+ goNext = true;
+ DirItem *dir = itu.current();
+ KURL oldDirUrl ( itu.currentKey() );
+ //kdDebug(7004) << "itemInUse: " << oldDirUrl.prettyURL() << endl;
+ // Check if this dir is oldUrl, or a subfolder of it
+ if ( oldUrl.isParentOf( oldDirUrl ) )
+ {
+ // TODO should use KURL::cleanpath like isParentOf does
+ TQString relPath = oldDirUrl.path().mid( oldUrl.path().length() );
+
+ KURL newDirUrl( newUrl ); // take new base
+ if ( !relPath.isEmpty() )
+ newDirUrl.addPath( relPath ); // add unchanged relative path
+ //kdDebug(7004) << "KDirListerCache::renameDir new url=" << newDirUrl.prettyURL() << endl;
+
+ // Update URL in dir item and in itemsInUse
+ dir->redirect( newDirUrl );
+ itemsInUse.remove( itu.currentKey() ); // implies ++itu
+ itemsInUse.insert( newDirUrl.url(-1), dir );
+ goNext = false; // because of the implied ++itu above
+ if ( dir->lstItems )
+ {
+ // Rename all items under that dir
+ KFileItemListIterator kit( *dir->lstItems );
+ for ( ; kit.current(); ++kit )
+ {
+ KURL oldItemUrl = (*kit)->url();
+ TQString oldItemUrlStr( oldItemUrl.url(-1) );
+ KURL newItemUrl( oldItemUrl );
+ newItemUrl.setPath( newDirUrl.path() );
+ newItemUrl.addPath( oldItemUrl.fileName() );
+ kdDebug(7004) << "KDirListerCache::renameDir renaming " << oldItemUrlStr << " to " << newItemUrl.url() << endl;
+ (*kit)->setURL( newItemUrl );
+ }
+ }
+ emitRedirections( oldDirUrl, newDirUrl );
+ }
+ if ( goNext )
+ ++itu;
+ }
+
+ // Is oldUrl a directory in the cache?
+ // Remove any child of oldUrl from the cache - even if the renamed dir itself isn't in it!
+ removeDirFromCache( oldUrl );
+ // TODO rename, instead.
+}
+
+void KDirListerCache::emitRedirections( const KURL &oldUrl, const KURL &url )
+{
+ kdDebug(7004) << k_funcinfo << oldUrl.prettyURL() << " -> " << url.prettyURL() << endl;
+ TQString oldUrlStr = oldUrl.url(-1);
+ TQString urlStr = url.url(-1);
+
+ TDEIO::ListJob *job = jobForUrl( oldUrlStr );
+ if ( job )
+ killJob( job );
+
+ // Check if we were listing this dir. Need to abort and restart with new name in that case.
+ TQPtrList<KDirLister> *listers = urlsCurrentlyListed.take( oldUrlStr );
+ if ( listers )
+ {
+ // Tell the world that the job listing the old url is dead.
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ if ( job )
+ kdl->jobDone( job );
+
+ emit kdl->canceled( oldUrl );
+ }
+
+ urlsCurrentlyListed.insert( urlStr, listers );
+ }
+
+ // Check if we are currently displaying this directory (odds opposite wrt above)
+ // Update urlsCurrentlyHeld dict with new URL
+ TQPtrList<KDirLister> *holders = urlsCurrentlyHeld.take( oldUrlStr );
+ if ( holders )
+ {
+ if ( job )
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ kdl->jobDone( job );
+
+ urlsCurrentlyHeld.insert( urlStr, holders );
+ }
+
+ if ( listers )
+ {
+ updateDirectory( url );
+
+ // Tell the world about the new url
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ emit kdl->started( url );
+ }
+
+ if ( holders )
+ {
+ // And notify the dirlisters of the redirection
+ for ( KDirLister *kdl = holders->first(); kdl; kdl = holders->next() )
+ {
+ *kdl->d->lstDirs.find( oldUrl ) = url;
+
+ if ( kdl->d->lstDirs.count() == 1 )
+ emit kdl->redirection( url );
+
+ emit kdl->redirection( oldUrl, url );
+ }
+ }
+}
+
+void KDirListerCache::removeDirFromCache( const KURL& dir )
+{
+ kdDebug(7004) << "KDirListerCache::removeDirFromCache " << dir.prettyURL() << endl;
+ TQCacheIterator<DirItem> itc( itemsCached );
+ while ( itc.current() )
+ {
+ if ( dir.isParentOf( KURL( itc.currentKey() ) ) )
+ itemsCached.remove( itc.currentKey() );
+ else
+ ++itc;
+ }
+}
+
+void KDirListerCache::slotUpdateEntries( TDEIO::Job* job, const TDEIO::UDSEntryList& list )
+{
+ jobs[static_cast<TDEIO::ListJob*>(job)] += list;
+}
+
+void KDirListerCache::slotUpdateResult( TDEIO::Job * j )
+{
+ Q_ASSERT( j );
+ TDEIO::ListJob *job = static_cast<TDEIO::ListJob *>( j );
+
+ KURL jobUrl = joburl( job );
+ jobUrl.adjustPath(-1); // need remove trailing slashes again, in case of redirections
+ TQString jobUrlStr = jobUrl.url();
+
+ kdDebug(7004) << k_funcinfo << "finished update " << jobUrl << endl;
+
+ KDirLister *kdl;
+
+ TQPtrList<KDirLister> *listers = urlsCurrentlyHeld[jobUrlStr];
+ TQPtrList<KDirLister> *tmpLst = urlsCurrentlyListed.take( jobUrlStr );
+
+ if ( tmpLst )
+ {
+ if ( listers )
+ for ( kdl = tmpLst->first(); kdl; kdl = tmpLst->next() )
+ {
+ Q_ASSERT( listers->containsRef( kdl ) == 0 );
+ listers->append( kdl );
+ }
+ else
+ {
+ listers = tmpLst;
+ urlsCurrentlyHeld.insert( jobUrlStr, listers );
+ }
+ }
+
+ // once we are updating dirs that are only in the cache this will fail!
+ Q_ASSERT( listers );
+
+ if ( job->error() )
+ {
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ kdl->jobDone( job );
+
+ //don't bother the user
+ //kdl->handleError( job );
+
+ emit kdl->canceled( jobUrl );
+ if ( kdl->numJobs() == 0 )
+ {
+ kdl->d->complete = true;
+ emit kdl->canceled();
+ }
+ }
+
+ jobs.remove( job );
+
+ // TODO: if job is a parent of one or more
+ // of the pending urls we should cancel them
+ processPendingUpdates();
+ return;
+ }
+
+ DirItem *dir = itemsInUse[jobUrlStr];
+ dir->complete = true;
+
+
+ // check if anyone wants the mimetypes immediately
+ bool delayedMimeTypes = true;
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ delayedMimeTypes = delayedMimeTypes && kdl->d->delayedMimeTypes;
+
+ // should be enough to get reasonable speed in most cases
+ TQDict<KFileItem> fileItems( 9973 );
+
+ KFileItemListIterator kit ( *(dir->lstItems) );
+
+ // Unmark all items in url
+ for ( ; kit.current(); ++kit )
+ {
+ (*kit)->unmark();
+ fileItems.insert( (*kit)->url().url(), *kit );
+ }
+
+ static const TQString& dot = TDEGlobal::staticQString(".");
+ static const TQString& dotdot = TDEGlobal::staticQString("..");
+
+ KFileItem *item = 0, *tmp;
+
+ TQValueList<TDEIO::UDSEntry> buf = jobs[job];
+ TQValueListIterator<TDEIO::UDSEntry> it = buf.begin();
+ for ( ; it != buf.end(); ++it )
+ {
+ // Form the complete url
+ if ( !item )
+ item = new KFileItem( *it, jobUrl, delayedMimeTypes, true );
+ else
+ item->setUDSEntry( *it, jobUrl, delayedMimeTypes, true );
+
+ // Find out about the name
+ TQString name = item->name();
+ Q_ASSERT( !name.isEmpty() );
+
+ // we duplicate the check for dotdot here, to avoid iterating over
+ // all items again and checking in matchesFilter() that way.
+ if ( name.isEmpty() || name == dotdot )
+ continue;
+
+ if ( name == dot )
+ {
+ // if the update was started before finishing the original listing
+ // there is no root item yet
+ if ( !dir->rootItem )
+ {
+ dir->rootItem = item;
+ item = 0;
+
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ if ( !kdl->d->rootFileItem && kdl->d->url == jobUrl )
+ kdl->d->rootFileItem = dir->rootItem;
+ }
+
+ continue;
+ }
+
+ // Find this item
+ if ( (tmp = fileItems[item->url().url()]) )
+ {
+ tmp->mark();
+
+ // check if something changed for this file
+ if ( !tmp->cmp( *item ) )
+ {
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->aboutToRefreshItem( tmp );
+
+ //kdDebug(7004) << "slotUpdateResult: file changed: " << tmp->name() << endl;
+ tmp->assign( *item );
+
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->addRefreshItem( tmp );
+ }
+ }
+ else // this is a new file
+ {
+ //kdDebug(7004) << "slotUpdateResult: new file: " << name << endl;
+
+ item->mark();
+ dir->lstItems->append( item );
+
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->addNewItem( item );
+
+ // item used, we need a new one for the next iteration
+ item = 0;
+ }
+ }
+
+ if ( item )
+ delete item;
+
+ jobs.remove( job );
+
+ deleteUnmarkedItems( listers, dir->lstItems );
+
+ for ( kdl = listers->first(); kdl; kdl = listers->next() )
+ {
+ kdl->emitItems();
+
+ kdl->jobDone( job );
+
+ emit kdl->completed( jobUrl );
+ if ( kdl->numJobs() == 0 )
+ {
+ kdl->d->complete = true;
+ emit kdl->completed();
+ }
+ }
+
+ // TODO: hmm, if there was an error and job is a parent of one or more
+ // of the pending urls we should cancel it/them as well
+ processPendingUpdates();
+}
+
+// private
+
+TDEIO::ListJob *KDirListerCache::jobForUrl( const TQString& url, TDEIO::ListJob *not_job )
+{
+ TDEIO::ListJob *job;
+ TQMap< TDEIO::ListJob *, TQValueList<TDEIO::UDSEntry> >::Iterator it = jobs.begin();
+ while ( it != jobs.end() )
+ {
+ job = it.key();
+ if ( joburl( job ).url(-1) == url && job != not_job )
+ return job;
+ ++it;
+ }
+ return 0;
+}
+
+const KURL& KDirListerCache::joburl( TDEIO::ListJob *job )
+{
+ if ( job->redirectionURL().isValid() )
+ return job->redirectionURL();
+ else
+ return job->url();
+}
+
+void KDirListerCache::killJob( TDEIO::ListJob *job )
+{
+ jobs.remove( job );
+ job->disconnect( this );
+ job->kill();
+}
+
+void KDirListerCache::deleteUnmarkedItems( TQPtrList<KDirLister> *listers, KFileItemList *lstItems )
+{
+ // Find all unmarked items and delete them
+ KFileItem* item;
+ lstItems->first();
+ while ( (item = lstItems->current()) )
+ if ( !item->isMarked() )
+ {
+ //kdDebug() << k_funcinfo << item->name() << endl;
+ for ( KDirLister *kdl = listers->first(); kdl; kdl = listers->next() )
+ kdl->emitDeleteItem( item );
+
+ if ( item->isDir() )
+ deleteDir( item->url() );
+
+ // finally actually delete the item
+ lstItems->take();
+ delete item;
+ }
+ else
+ lstItems->next();
+}
+
+void KDirListerCache::deleteDir( const KURL& dirUrl )
+{
+ //kdDebug() << k_funcinfo << dirUrl.prettyURL() << endl;
+ // unregister and remove the childs of the deleted item.
+ // Idea: tell all the KDirListers that they should forget the dir
+ // and then remove it from the cache.
+
+ TQDictIterator<DirItem> itu( itemsInUse );
+ while ( itu.current() )
+ {
+ KURL deletedUrl( itu.currentKey() );
+ if ( dirUrl.isParentOf( deletedUrl ) )
+ {
+ // stop all jobs for deletedUrl
+
+ TQPtrList<KDirLister> *kdls = urlsCurrentlyListed[deletedUrl.url()];
+ if ( kdls ) // yeah, I lack good names
+ {
+ // we need a copy because stop modifies the list
+ kdls = new TQPtrList<KDirLister>( *kdls );
+ for ( KDirLister *kdl = kdls->first(); kdl; kdl = kdls->next() )
+ stop( kdl, deletedUrl );
+
+ delete kdls;
+ }
+
+ // tell listers holding deletedUrl to forget about it
+ // this will stop running updates for deletedUrl as well
+
+ kdls = urlsCurrentlyHeld[deletedUrl.url()];
+ if ( kdls )
+ {
+ // we need a copy because forgetDirs modifies the list
+ kdls = new TQPtrList<KDirLister>( *kdls );
+
+ for ( KDirLister *kdl = kdls->first(); kdl; kdl = kdls->next() )
+ {
+ // lister's root is the deleted item
+ if ( kdl->d->url == deletedUrl )
+ {
+ // tell the view first. It might need the subdirs' items (which forgetDirs will delete)
+ if ( kdl->d->rootFileItem )
+ emit kdl->deleteItem( kdl->d->rootFileItem );
+ forgetDirs( kdl );
+ kdl->d->rootFileItem = 0;
+ }
+ else
+ {
+ bool treeview = kdl->d->lstDirs.count() > 1;
+ if ( !treeview )
+ emit kdl->clear();
+
+ forgetDirs( kdl, deletedUrl, treeview );
+ }
+ }
+
+ delete kdls;
+ }
+
+ // delete the entry for deletedUrl - should not be needed, it's in
+ // items cached now
+
+ DirItem *dir = itemsInUse.take( deletedUrl.url() );
+ Q_ASSERT( !dir );
+ if ( !dir ) // take didn't find it - move on
+ ++itu;
+ }
+ else
+ ++itu;
+ }
+
+ // remove the children from the cache
+ removeDirFromCache( dirUrl );
+}
+
+void KDirListerCache::processPendingUpdates()
+{
+ // TODO
+}
+
+#ifndef NDEBUG
+void KDirListerCache::printDebug()
+{
+ kdDebug(7004) << "Items in use: " << endl;
+ TQDictIterator<DirItem> itu( itemsInUse );
+ for ( ; itu.current() ; ++itu ) {
+ kdDebug(7004) << " " << itu.currentKey() << " URL: " << itu.current()->url
+ << " rootItem: " << ( itu.current()->rootItem ? itu.current()->rootItem->url() : KURL() )
+ << " autoUpdates refcount: " << itu.current()->autoUpdates
+ << " complete: " << itu.current()->complete
+ << ( itu.current()->lstItems ? TQString(" with %1 items.").arg(itu.current()->lstItems->count()) : TQString(" lstItems=NULL") ) << endl;
+ }
+
+ kdDebug(7004) << "urlsCurrentlyHeld: " << endl;
+ TQDictIterator< TQPtrList<KDirLister> > it( urlsCurrentlyHeld );
+ for ( ; it.current() ; ++it )
+ {
+ TQString list;
+ for ( TQPtrListIterator<KDirLister> listit( *it.current() ); listit.current(); ++listit )
+ list += " 0x" + TQString::number( (long)listit.current(), 16 );
+ kdDebug(7004) << " " << it.currentKey() << " " << it.current()->count() << " listers: " << list << endl;
+ }
+
+ kdDebug(7004) << "urlsCurrentlyListed: " << endl;
+ TQDictIterator< TQPtrList<KDirLister> > it2( urlsCurrentlyListed );
+ for ( ; it2.current() ; ++it2 )
+ {
+ TQString list;
+ for ( TQPtrListIterator<KDirLister> listit( *it2.current() ); listit.current(); ++listit )
+ list += " 0x" + TQString::number( (long)listit.current(), 16 );
+ kdDebug(7004) << " " << it2.currentKey() << " " << it2.current()->count() << " listers: " << list << endl;
+ }
+
+ TQMap< TDEIO::ListJob *, TQValueList<TDEIO::UDSEntry> >::Iterator jit = jobs.begin();
+ kdDebug(7004) << "Jobs: " << endl;
+ for ( ; jit != jobs.end() ; ++jit )
+ kdDebug(7004) << " " << jit.key() << " listing " << joburl( jit.key() ).prettyURL() << ": " << (*jit).count() << " entries." << endl;
+
+ kdDebug(7004) << "Items in cache: " << endl;
+ TQCacheIterator<DirItem> itc( itemsCached );
+ for ( ; itc.current() ; ++itc )
+ kdDebug(7004) << " " << itc.currentKey() << " rootItem: "
+ << ( itc.current()->rootItem ? itc.current()->rootItem->url().prettyURL() : TQString("NULL") )
+ << ( itc.current()->lstItems ? TQString(" with %1 items.").arg(itc.current()->lstItems->count()) : TQString(" lstItems=NULL") ) << endl;
+}
+#endif
+
+/*********************** -- The new KDirLister -- ************************/
+
+
+KDirLister::KDirLister( bool _delayedMimeTypes )
+{
+ kdDebug(7003) << "+KDirLister" << endl;
+
+ d = new KDirListerPrivate;
+
+ d->complete = true;
+ d->delayedMimeTypes = _delayedMimeTypes;
+
+ setAutoUpdate( true );
+ setDirOnlyMode( false );
+ setShowingDotFiles( false );
+
+ setAutoErrorHandlingEnabled( true, 0 );
+}
+
+KDirLister::~KDirLister()
+{
+ kdDebug(7003) << "-KDirLister" << endl;
+
+ if ( KDirListerCache::exists() )
+ {
+ // Stop all running jobs
+ stop();
+ s_pCache->forgetDirs( this );
+ }
+
+ delete d;
+}
+
+bool KDirLister::openURL( const KURL& _url, bool _keep, bool _reload )
+{
+ kdDebug(7003) << k_funcinfo << _url.prettyURL()
+ << " keep=" << _keep << " reload=" << _reload << endl;
+
+ // emit the current changes made to avoid an inconsistent treeview
+ if ( d->changes != NONE && _keep )
+ emitChanges();
+
+ d->changes = NONE;
+
+ // If a local path is available, monitor that instead of the given remote URL...
+ KURL realURL = _url;
+ if (!realURL.isLocalFile()) {
+ TDEIO::LocalURLJob* localURLJob = TDEIO::localURL(_url);
+ if (localURLJob) {
+ connect(localURLJob, TQT_SIGNAL(localURL(TDEIO::Job*, const KURL&, bool)), this, TQT_SLOT(slotLocalURL(TDEIO::Job*, const KURL&, bool)));
+ connect(localURLJob, TQT_SIGNAL(destroyed()), this, TQT_SLOT(slotLocalURLKIODestroyed()));
+ d->localURLSlotFired = false;
+ while (!d->localURLSlotFired) {
+ tqApp->eventLoop()->processEvents(TQEventLoop::ExcludeUserInput);
+ usleep(1000);
+ }
+ if (d->localURLResultIsLocal) {
+ realURL = d->localURLResultURL;
+ }
+ }
+ }
+
+ return s_pCache->listDir( this, realURL, _keep, _reload );
+}
+
+void KDirLister::slotLocalURL(TDEIO::Job *job, const KURL& url, bool isLocal) {
+ d->localURLSlotFired = true;
+ d->localURLResultURL = url;
+ d->localURLResultIsLocal = isLocal;
+}
+
+void KDirLister::slotLocalURLKIODestroyed() {
+ if (!d->localURLSlotFired) {
+ d->localURLSlotFired = true;
+ d->localURLResultURL = KURL();
+ d->localURLResultIsLocal = false;
+ }
+}
+
+void KDirLister::stop()
+{
+ kdDebug(7003) << k_funcinfo << endl;
+ s_pCache->stop( this );
+}
+
+void KDirLister::stop( const KURL& _url )
+{
+ kdDebug(7003) << k_funcinfo << _url.prettyURL() << endl;
+ s_pCache->stop( this, _url );
+}
+
+bool KDirLister::autoUpdate() const
+{
+ return d->autoUpdate;
+}
+
+void KDirLister::setAutoUpdate( bool _enable )
+{
+ if ( d->autoUpdate == _enable )
+ return;
+
+ d->autoUpdate = _enable;
+ s_pCache->setAutoUpdate( this, _enable );
+}
+
+bool KDirLister::showingDotFiles() const
+{
+ return d->isShowingDotFiles;
+}
+
+void KDirLister::setShowingDotFiles( bool _showDotFiles )
+{
+ if ( d->isShowingDotFiles == _showDotFiles )
+ return;
+
+ d->isShowingDotFiles = _showDotFiles;
+ d->changes ^= DOT_FILES;
+}
+
+bool KDirLister::dirOnlyMode() const
+{
+ return d->dirOnlyMode;
+}
+
+void KDirLister::setDirOnlyMode( bool _dirsOnly )
+{
+ if ( d->dirOnlyMode == _dirsOnly )
+ return;
+
+ d->dirOnlyMode = _dirsOnly;
+ d->changes ^= DIR_ONLY_MODE;
+}
+
+bool KDirLister::autoErrorHandlingEnabled() const
+{
+ return d->autoErrorHandling;
+}
+
+void KDirLister::setAutoErrorHandlingEnabled( bool enable, TQWidget* parent )
+{
+ d->autoErrorHandling = enable;
+ d->errorParent = parent;
+}
+
+const KURL& KDirLister::url() const
+{
+ return d->url;
+}
+
+const KURL::List& KDirLister::directories() const
+{
+ return d->lstDirs;
+}
+
+void KDirLister::emitChanges()
+{
+ if ( d->changes == NONE )
+ return;
+
+ static const TQString& dot = TDEGlobal::staticQString(".");
+ static const TQString& dotdot = TDEGlobal::staticQString("..");
+
+ for ( KURL::List::Iterator it = d->lstDirs.begin();
+ it != d->lstDirs.end(); ++it )
+ {
+ KFileItemListIterator kit( *s_pCache->itemsForDir( *it ) );
+ for ( ; kit.current(); ++kit )
+ {
+ if ( (*kit)->text() == dot || (*kit)->text() == dotdot )
+ continue;
+
+ bool oldMime = true, newMime = true;
+
+ if ( d->changes & MIME_FILTER )
+ {
+ oldMime = doMimeFilter( (*kit)->mimetype(), d->oldMimeFilter )
+ && doMimeExcludeFilter( (*kit)->mimetype(), d->oldMimeExcludeFilter );
+ newMime = doMimeFilter( (*kit)->mimetype(), d->mimeFilter )
+ && doMimeExcludeFilter( (*kit)->mimetype(), d->mimeExcludeFilter );
+
+ if ( oldMime && !newMime )
+ {
+ emit deleteItem( *kit );
+ continue;
+ }
+ }
+
+ if ( d->changes & DIR_ONLY_MODE )
+ {
+ // the lister switched to dirOnlyMode
+ if ( d->dirOnlyMode )
+ {
+ if ( !(*kit)->isDir() )
+ emit deleteItem( *kit );
+ }
+ else if ( !(*kit)->isDir() )
+ addNewItem( *kit );
+
+ continue;
+ }
+
+ if ( (*kit)->isHidden() )
+ {
+ if ( d->changes & DOT_FILES )
+ {
+ // the lister switched to dot files mode
+ if ( d->isShowingDotFiles )
+ addNewItem( *kit );
+ else
+ emit deleteItem( *kit );
+
+ continue;
+ }
+ }
+ else if ( d->changes & NAME_FILTER )
+ {
+ bool oldName = (*kit)->isDir() ||
+ d->oldFilters.isEmpty() ||
+ doNameFilter( (*kit)->text(), d->oldFilters );
+
+ bool newName = (*kit)->isDir() ||
+ d->lstFilters.isEmpty() ||
+ doNameFilter( (*kit)->text(), d->lstFilters );
+
+ if ( oldName && !newName )
+ {
+ emit deleteItem( *kit );
+ continue;
+ }
+ else if ( !oldName && newName )
+ addNewItem( *kit );
+ }
+
+ if ( (d->changes & MIME_FILTER) && !oldMime && newMime )
+ addNewItem( *kit );
+ }
+
+ emitItems();
+ }
+
+ d->changes = NONE;
+}
+
+void KDirLister::updateDirectory( const KURL& _u )
+{
+ s_pCache->updateDirectory( _u );
+}
+
+bool KDirLister::isFinished() const
+{
+ return d->complete;
+}
+
+KFileItem *KDirLister::rootItem() const
+{
+ return d->rootFileItem;
+}
+
+KFileItem *KDirLister::findByURL( const KURL& _url ) const
+{
+ return s_pCache->findByURL( this, _url );
+}
+
+KFileItem *KDirLister::findByName( const TQString& _name ) const
+{
+ return s_pCache->findByName( this, _name );
+}
+
+#ifndef KDE_NO_COMPAT
+KFileItem *KDirLister::find( const KURL& _url ) const
+{
+ return findByURL( _url );
+}
+#endif
+
+
+// ================ public filter methods ================ //
+
+void KDirLister::setNameFilter( const TQString& nameFilter )
+{
+ if ( !(d->changes & NAME_FILTER) )
+ {
+ d->oldFilters = d->lstFilters;
+ d->lstFilters.setAutoDelete( false );
+ }
+
+ d->lstFilters.clear();
+ d->lstFilters.setAutoDelete( true );
+
+ d->nameFilter = nameFilter;
+
+ // Split on white space
+ TQStringList list = TQStringList::split( ' ', nameFilter );
+ for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it )
+ d->lstFilters.append( new TQRegExp(*it, false, true ) );
+
+ d->changes |= NAME_FILTER;
+}
+
+const TQString& KDirLister::nameFilter() const
+{
+ return d->nameFilter;
+}
+
+void KDirLister::setMimeFilter( const TQStringList& mimeFilter )
+{
+ if ( !(d->changes & MIME_FILTER) )
+ d->oldMimeFilter = d->mimeFilter;
+
+ if ( mimeFilter.find("all/allfiles") != mimeFilter.end() ||
+ mimeFilter.find("all/all") != mimeFilter.end() )
+ d->mimeFilter.clear();
+ else
+ d->mimeFilter = mimeFilter;
+
+ d->changes |= MIME_FILTER;
+}
+
+void KDirLister::setMimeExcludeFilter( const TQStringList& mimeExcludeFilter )
+{
+ if ( !(d->changes & MIME_FILTER) )
+ d->oldMimeExcludeFilter = d->mimeExcludeFilter;
+
+ d->mimeExcludeFilter = mimeExcludeFilter;
+ d->changes |= MIME_FILTER;
+}
+
+
+void KDirLister::clearMimeFilter()
+{
+ if ( !(d->changes & MIME_FILTER) )
+ {
+ d->oldMimeFilter = d->mimeFilter;
+ d->oldMimeExcludeFilter = d->mimeExcludeFilter;
+ }
+ d->mimeFilter.clear();
+ d->mimeExcludeFilter.clear();
+ d->changes |= MIME_FILTER;
+}
+
+const TQStringList& KDirLister::mimeFilters() const
+{
+ return d->mimeFilter;
+}
+
+bool KDirLister::matchesFilter( const TQString& name ) const
+{
+ return doNameFilter( name, d->lstFilters );
+}
+
+bool KDirLister::matchesMimeFilter( const TQString& mime ) const
+{
+ return doMimeFilter( mime, d->mimeFilter ) && doMimeExcludeFilter(mime,d->mimeExcludeFilter);
+}
+
+// ================ protected methods ================ //
+
+bool KDirLister::matchesFilter( const KFileItem *item ) const
+{
+ Q_ASSERT( item );
+ static const TQString& dotdot = TDEGlobal::staticQString("..");
+
+ if ( item->text() == dotdot )
+ return false;
+
+ if ( !d->isShowingDotFiles && item->isHidden() )
+ return false;
+
+ if ( item->isDir() || d->lstFilters.isEmpty() )
+ return true;
+
+ return matchesFilter( item->text() );
+}
+
+bool KDirLister::matchesMimeFilter( const KFileItem *item ) const
+{
+ Q_ASSERT( item );
+ // Don't lose time determining the mimetype if there is no filter
+ if ( d->mimeFilter.isEmpty() && d->mimeExcludeFilter.isEmpty() )
+ return true;
+ return matchesMimeFilter( item->mimetype() );
+}
+
+bool KDirLister::doNameFilter( const TQString& name, const TQPtrList<TQRegExp>& filters ) const
+{
+ for ( TQPtrListIterator<TQRegExp> it( filters ); it.current(); ++it )
+ if ( it.current()->exactMatch( name ) )
+ return true;
+
+ return false;
+}
+
+bool KDirLister::doMimeFilter( const TQString& mime, const TQStringList& filters ) const
+{
+ if ( filters.isEmpty() )
+ return true;
+
+ KMimeType::Ptr mimeptr = KMimeType::mimeType(mime);
+ //kdDebug(7004) << "doMimeFilter: investigating: "<<mimeptr->name()<<endl;
+ TQStringList::ConstIterator it = filters.begin();
+ for ( ; it != filters.end(); ++it )
+ if ( mimeptr->is(*it) )
+ return true;
+ //else kdDebug(7004) << "doMimeFilter: compared without result to "<<*it<<endl;
+
+
+ return false;
+}
+
+bool KDirLister::doMimeExcludeFilter( const TQString& mime, const TQStringList& filters ) const
+{
+ if ( filters.isEmpty() )
+ return true;
+
+ TQStringList::ConstIterator it = filters.begin();
+ for ( ; it != filters.end(); ++it )
+ if ( (*it) == mime )
+ return false;
+
+ return true;
+}
+
+
+bool KDirLister::validURL( const KURL& _url ) const
+{
+ return s_pCache->validURL( this, _url );
+}
+
+void KDirLister::handleError( TDEIO::Job *job )
+{
+ if ( d->autoErrorHandling )
+ job->showErrorDialog( d->errorParent );
+}
+
+
+// ================= private methods ================= //
+
+void KDirLister::addNewItem( const KFileItem *item )
+{
+ if ( ( d->dirOnlyMode && !item->isDir() ) || !matchesFilter( item ) )
+ return; // No reason to continue... bailing out here prevents a mimetype scan.
+
+ if ( matchesMimeFilter( item ) )
+ {
+ if ( !d->lstNewItems )
+ d->lstNewItems = new KFileItemList;
+
+ d->lstNewItems->append( item ); // items not filtered
+ }
+ else
+ {
+ if ( !d->lstMimeFilteredItems )
+ d->lstMimeFilteredItems = new KFileItemList;
+
+ d->lstMimeFilteredItems->append( item ); // only filtered by mime
+ }
+}
+
+void KDirLister::addNewItems( const KFileItemList& items )
+{
+ // TODO: make this faster - test if we have a filter at all first
+ // DF: was this profiled? The matchesFoo() functions should be fast, w/o filters...
+ // Of course if there is no filter and we can do a range-insertion instead of a loop, that might be good.
+ // But that's for Qt4, not possible with TQPtrList.
+ for ( KFileItemListIterator kit( items ); kit.current(); ++kit )
+ addNewItem( *kit );
+}
+
+void KDirLister::aboutToRefreshItem( const KFileItem *item )
+{
+ // The code here follows the logic in addNewItem
+ if ( ( d->dirOnlyMode && !item->isDir() ) || !matchesFilter( item ) )
+ d->refreshItemWasFiltered = true;
+ else if ( !matchesMimeFilter( item ) )
+ d->refreshItemWasFiltered = true;
+ else
+ d->refreshItemWasFiltered = false;
+}
+
+void KDirLister::addRefreshItem( const KFileItem *item )
+{
+ bool isExcluded = (d->dirOnlyMode && !item->isDir()) || !matchesFilter( item );
+
+ if ( !isExcluded && matchesMimeFilter( item ) )
+ {
+ if ( d->refreshItemWasFiltered )
+ {
+ if ( !d->lstNewItems )
+ d->lstNewItems = new KFileItemList;
+
+ d->lstNewItems->append( item );
+ }
+ else
+ {
+ if ( !d->lstRefreshItems )
+ d->lstRefreshItems = new KFileItemList;
+
+ d->lstRefreshItems->append( item );
+ }
+ }
+ else if ( !d->refreshItemWasFiltered )
+ {
+ if ( !d->lstRemoveItems )
+ d->lstRemoveItems = new KFileItemList;
+
+ // notify the user that the mimetype of a file changed that doesn't match
+ // a filter or does match an exclude filter
+ d->lstRemoveItems->append( item );
+ }
+}
+
+void KDirLister::emitItems()
+{
+ KFileItemList *tmpNew = d->lstNewItems;
+ d->lstNewItems = 0;
+
+ KFileItemList *tmpMime = d->lstMimeFilteredItems;
+ d->lstMimeFilteredItems = 0;
+
+ KFileItemList *tmpRefresh = d->lstRefreshItems;
+ d->lstRefreshItems = 0;
+
+ KFileItemList *tmpRemove = d->lstRemoveItems;
+ d->lstRemoveItems = 0;
+
+ if ( tmpNew )
+ {
+ emit newItems( *tmpNew );
+ delete tmpNew;
+ }
+
+ if ( tmpMime )
+ {
+ emit itemsFilteredByMime( *tmpMime );
+ delete tmpMime;
+ }
+
+ if ( tmpRefresh )
+ {
+ emit refreshItems( *tmpRefresh );
+ delete tmpRefresh;
+ }
+
+ if ( tmpRemove )
+ {
+ for ( KFileItem *tmp = tmpRemove->first(); tmp; tmp = tmpRemove->next() )
+ emit deleteItem( tmp );
+ delete tmpRemove;
+ }
+}
+
+void KDirLister::emitDeleteItem( KFileItem *item )
+{
+ if ( ( d->dirOnlyMode && !item->isDir() ) || !matchesFilter( item ) )
+ return; // No reason to continue... bailing out here prevents a mimetype scan.
+ if ( matchesMimeFilter( item ) )
+ emit deleteItem( item );
+}
+
+
+// ================ private slots ================ //
+
+void KDirLister::slotInfoMessage( TDEIO::Job *, const TQString& message )
+{
+ emit infoMessage( message );
+}
+
+void KDirLister::slotPercent( TDEIO::Job *job, unsigned long pcnt )
+{
+ d->jobData[static_cast<TDEIO::ListJob *>(job)].percent = pcnt;
+
+ int result = 0;
+
+ TDEIO::filesize_t size = 0;
+
+ TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
+ while ( dataIt != d->jobData.end() )
+ {
+ result += (*dataIt).percent * (*dataIt).totalSize;
+ size += (*dataIt).totalSize;
+ ++dataIt;
+ }
+
+ if ( size != 0 )
+ result /= size;
+ else
+ result = 100;
+ emit percent( result );
+}
+
+void KDirLister::slotTotalSize( TDEIO::Job *job, TDEIO::filesize_t size )
+{
+ d->jobData[static_cast<TDEIO::ListJob *>(job)].totalSize = size;
+
+ TDEIO::filesize_t result = 0;
+ TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
+ while ( dataIt != d->jobData.end() )
+ {
+ result += (*dataIt).totalSize;
+ ++dataIt;
+ }
+
+ emit totalSize( result );
+}
+
+void KDirLister::slotProcessedSize( TDEIO::Job *job, TDEIO::filesize_t size )
+{
+ d->jobData[static_cast<TDEIO::ListJob *>(job)].processedSize = size;
+
+ TDEIO::filesize_t result = 0;
+ TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
+ while ( dataIt != d->jobData.end() )
+ {
+ result += (*dataIt).processedSize;
+ ++dataIt;
+ }
+
+ emit processedSize( result );
+}
+
+void KDirLister::slotSpeed( TDEIO::Job *job, unsigned long spd )
+{
+ d->jobData[static_cast<TDEIO::ListJob *>(job)].speed = spd;
+
+ int result = 0;
+ TQMap< TDEIO::ListJob *, KDirListerPrivate::JobData >::Iterator dataIt = d->jobData.begin();
+ while ( dataIt != d->jobData.end() )
+ {
+ result += (*dataIt).speed;
+ ++dataIt;
+ }
+
+ emit speed( result );
+}
+
+uint KDirLister::numJobs()
+{
+ return d->jobData.count();
+}
+
+void KDirLister::jobDone( TDEIO::ListJob *job )
+{
+ d->jobData.remove( job );
+}
+
+void KDirLister::jobStarted( TDEIO::ListJob *job )
+{
+ KDirListerPrivate::JobData jobData;
+ jobData.speed = 0;
+ jobData.percent = 0;
+ jobData.processedSize = 0;
+ jobData.totalSize = 0;
+
+ d->jobData.insert( job, jobData );
+ d->complete = false;
+}
+
+void KDirLister::connectJob( TDEIO::ListJob *job )
+{
+ connect( job, TQT_SIGNAL(infoMessage( TDEIO::Job *, const TQString& )),
+ this, TQT_SLOT(slotInfoMessage( TDEIO::Job *, const TQString& )) );
+ connect( job, TQT_SIGNAL(percent( TDEIO::Job *, unsigned long )),
+ this, TQT_SLOT(slotPercent( TDEIO::Job *, unsigned long )) );
+ connect( job, TQT_SIGNAL(totalSize( TDEIO::Job *, TDEIO::filesize_t )),
+ this, TQT_SLOT(slotTotalSize( TDEIO::Job *, TDEIO::filesize_t )) );
+ connect( job, TQT_SIGNAL(processedSize( TDEIO::Job *, TDEIO::filesize_t )),
+ this, TQT_SLOT(slotProcessedSize( TDEIO::Job *, TDEIO::filesize_t )) );
+ connect( job, TQT_SIGNAL(speed( TDEIO::Job *, unsigned long )),
+ this, TQT_SLOT(slotSpeed( TDEIO::Job *, unsigned long )) );
+}
+
+void KDirLister::setMainWindow( TQWidget *window )
+{
+ d->window = window;
+}
+
+TQWidget *KDirLister::mainWindow()
+{
+ return d->window;
+}
+
+KFileItemList KDirLister::items( WhichItems which ) const
+{
+ return itemsForDir( url(), which );
+}
+
+KFileItemList KDirLister::itemsForDir( const KURL& dir, WhichItems which ) const
+{
+ KFileItemList result;
+ KFileItemList *allItems = s_pCache->itemsForDir( dir );
+ if ( !allItems )
+ return result;
+
+ if ( which == AllItems )
+ result = *allItems; // shallow copy
+ else // only items passing the filters
+ {
+ for ( KFileItemListIterator kit( *allItems ); kit.current(); ++kit )
+ {
+ KFileItem *item = *kit;
+ bool isExcluded = (d->dirOnlyMode && !item->isDir()) || !matchesFilter( item );
+ if ( !isExcluded && matchesMimeFilter( item ) )
+ result.append( item );
+ }
+ }
+
+ return result;
+}
+
+// to keep BC changes
+
+void KDirLister::virtual_hook( int, void * )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+#include "kdirlister.moc"
+#include "kdirlister_p.moc"
diff --git a/tdeio/tdeio/kdirlister.h b/tdeio/tdeio/kdirlister.h
new file mode 100644
index 000000000..188f9ea7a
--- /dev/null
+++ b/tdeio/tdeio/kdirlister.h
@@ -0,0 +1,634 @@
+/* This file is part of the KDE project
+ Copyright (C) 1999 David Faure <faure@kde.org>
+ 2001, 2002, 2004, 2005 Michael Brade <brade@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef kdirlister_h
+#define kdirlister_h
+
+#include "tdefileitem.h"
+#include "kdirnotify.h"
+
+#include <tqstring.h>
+#include <tqstringlist.h>
+
+#include <kurl.h>
+
+namespace TDEIO { class Job; class ListJob; }
+
+/**
+ * The dir lister deals with the kiojob used to list and update a directory
+ * and has signals for the user of this class (e.g. konqueror view or
+ * kdesktop) to create/destroy its items when asked.
+ *
+ * This class is independent from the graphical representation of the dir
+ * (icon container, tree view, ...) and it stores the items (as KFileItems).
+ *
+ * Typical usage :
+ * @li Create an instance.
+ * @li Connect to at least update, clear, newItem, and deleteItem.
+ * @li Call openURL - the signals will be called.
+ * @li Reuse the instance when opening a new url (openURL).
+ * @li Destroy the instance when not needed anymore (usually destructor).
+ *
+ * Advanced usage : call openURL with _keep = true to list directories
+ * without forgetting the ones previously read (e.g. for a tree view)
+ *
+ * @short Helper class for the kiojob used to list and update a directory.
+ * @author Michael Brade <brade@kde.org>
+ */
+class TDEIO_EXPORT KDirLister : public TQObject
+{
+ class KDirListerPrivate;
+ friend class KDirListerPrivate;
+ friend class KDirListerCache;
+
+ Q_OBJECT
+ TQ_PROPERTY( bool autoUpdate READ autoUpdate WRITE setAutoUpdate )
+ TQ_PROPERTY( bool showingDotFiles READ showingDotFiles WRITE setShowingDotFiles )
+ TQ_PROPERTY( bool dirOnlyMode READ dirOnlyMode WRITE setDirOnlyMode )
+ TQ_PROPERTY( bool autoErrorHandlingEnabled READ autoErrorHandlingEnabled )
+ TQ_PROPERTY( TQString nameFilter READ nameFilter WRITE setNameFilter )
+ TQ_PROPERTY( TQStringList mimeFilter READ mimeFilters WRITE setMimeFilter RESET clearMimeFilter )
+
+public:
+ /**
+ * Create a directory lister.
+ * @param _delayedMimeTypes if true, mime types will be fetched on demand. If false,
+ * they will always be fetched immediately
+ */
+ KDirLister( bool _delayedMimeTypes = false );
+
+ /**
+ * Destroy the directory lister.
+ */
+ virtual ~KDirLister();
+
+ /**
+ * Run the directory lister on the given url.
+ *
+ * This method causes KDirLister to emit _all_ the items of @p _url, in any case.
+ * Depending on @p _keep either clear() or clear(const KURL &) will be
+ * emitted first.
+ *
+ * The newItems() signal may be emitted more than once to supply you
+ * with KFileItems, up until the signal completed() is emitted
+ * (and isFinished() returns true).
+ *
+ * @param _url the directory URL.
+ * @param _keep if true the previous directories aren't forgotten
+ * (they are still watched by kdirwatch and their items
+ * are kept for this KDirLister). This is useful for e.g.
+ * a treeview.
+ * @param _reload indicates wether to use the cache (false) or to reread the
+ * directory from the disk.
+ * Use only when opening a dir not yet listed by this lister
+ * without using the cache. Otherwise use updateDirectory.
+ * @return true if successful,
+ * false otherwise (e.g. invalid @p _url)
+ */
+ virtual bool openURL( const KURL& _url, bool _keep = false, bool _reload = false );
+
+ /**
+ * Stop listing all directories currently being listed.
+ *
+ * Emits canceled() if there was at least one job running.
+ * Emits canceled( const KURL& ) for each stopped job if
+ * there are at least two dirctories being watched by KDirLister.
+ */
+ virtual void stop();
+
+ /**
+ * Stop listing the given directory.
+ *
+ * Emits canceled() if the killed job was the last running one.
+ * Emits canceled( const KURL& ) for the killed job if
+ * there are at least two directories being watched by KDirLister.
+ * No signal is emitted if there was no job running for @p _url.
+ * @param _url the directory URL
+ */
+ virtual void stop( const KURL& _url );
+
+ /**
+ * Checks whether KDirWatch will automatically update directories. This is
+ * enabled by default.
+ * @return true if KDirWatch is used to automatically update directories.
+ */
+ bool autoUpdate() const;
+
+ /**
+ * Enable/disable automatic directory updating, when a directory changes
+ * (using KDirWatch).
+ * @param enable true to enable, false to disable
+ */
+ virtual void setAutoUpdate( bool enable );
+
+ /**
+ * Check whether auto error handling is enabled.
+ * If enabled, it will show an error dialog to the user when an
+ * error occurs. It is turned on by default.
+ * @return true if auto error handling is enabled, false otherwise
+ * @see setAutoErrorHandlingEnabled()
+ */
+ bool autoErrorHandlingEnabled() const;
+
+ /**
+ * Enable or disable auto error handling is enabled.
+ * If enabled, it will show an error dialog to the user when an
+ * error occurs. It is turned on by default.
+ * @param enable true to enable auto error handling, false to disable
+ * @param parent the parent widget for the error dialogs, can be 0 for
+ * top-level
+ * @see autoErrorHandlingEnabled()
+ */
+ void setAutoErrorHandlingEnabled( bool enable, TQWidget *parent );
+
+ /**
+ * Checks whether hidden files (files beginning with a dot) will be
+ * shown.
+ * By default this option is disabled (hidden files will be not shown).
+ * @return true if dot files are shown, false otherwise
+ * @see setShowingDotFiles()
+ */
+ bool showingDotFiles() const;
+
+ /**
+ * Changes the "is viewing dot files" setting.
+ * Calls updateDirectory() if setting changed.
+ * By default this option is disabled (hidden files will not be shown).
+ * @param _showDotFiles true to enable showing hidden files, false to
+ * disable
+ * @see showingDotFiles()
+ */
+ virtual void setShowingDotFiles( bool _showDotFiles );
+
+ /**
+ * Checks whether the KDirLister only lists directories or all
+ * files.
+ * By default this option is disabled (all files will be shown).
+ * @return true if setDirOnlyMode(true) was called
+ */
+ bool dirOnlyMode() const;
+
+ /**
+ * Call this to list only directories.
+ * By default this option is disabled (all files will be shown).
+ * @param dirsOnly true to list only directories
+ */
+ virtual void setDirOnlyMode( bool dirsOnly );
+
+ /**
+ * Returns the top level URL that is listed by this KDirLister.
+ * It might be different from the one given with openURL() if there was a
+ * redirection. If you called openURL() with @p _keep == true this is the
+ * first url opened (e.g. in a treeview this is the root).
+ *
+ * @return the url used by this instance to list the files.
+ */
+ const KURL& url() const;
+
+ /**
+ * Returns all URLs that are listed by this KDirLister. This is only
+ * useful if you called openURL() with @p _keep == true, as it happens in a
+ * treeview, for example. (Note that the base url is included in the list
+ * as well, of course.)
+ *
+ * @return the list of all listed URLs
+ * @since 3.4
+ */
+ const KURL::List& directories() const;
+
+ /**
+ * Actually emit the changes made with setShowingDotFiles, setDirOnlyMode,
+ * setNameFilter and setMimeFilter.
+ */
+ virtual void emitChanges();
+
+ /**
+ * Update the directory @p _dir. This method causes KDirLister to _only_ emit
+ * the items of @p _dir that actually changed compared to the current state in the
+ * cache and updates the cache.
+ *
+ * The current implementation calls updateDirectory automatically for
+ * local files, using KDirWatch (if autoUpdate() is true), but it might be
+ * useful to force an update manually.
+ *
+ * @param _dir the directory URL
+ */
+ virtual void updateDirectory( const KURL& _dir );
+
+ /**
+ * Returns true if no io operation is currently in progress.
+ * @return true if finished, false otherwise
+ */
+ bool isFinished() const;
+
+ /**
+ * Returns the file item of the URL.
+ * @return the file item for url() itself (".")
+ */
+ KFileItem *rootItem() const;
+
+ /**
+ * Find an item by its URL.
+ * @param _url the item URL
+ * @return the pointer to the KFileItem
+ */
+ virtual KFileItem *findByURL( const KURL& _url ) const;
+#ifndef KDE_NO_COMPAT
+ KFileItem *find( const KURL& _url ) const;
+#endif
+
+ /**
+ * Find an item by its name.
+ * @param name the item name
+ * @return the pointer to the KFileItem
+ */
+ virtual KFileItem *findByName( const TQString& name ) const;
+
+ /**
+ * Set a name filter to only list items matching this name, e.g. "*.cpp".
+ *
+ * You can set more than one filter by separating them with whitespace, e.g
+ * "*.cpp *.h".
+ * Note: the direcory is not automatically reloaded.
+ *
+ * @param filter the new filter, TQString::null to disable filtering
+ * @see matchesFilter
+ */
+ virtual void setNameFilter( const TQString &filter );
+
+ /**
+ * Returns the current name filter, as set via setNameFilter()
+ * @return the current name filter, can be TQString::null if filtering
+ * is turned off
+ */
+ const TQString& nameFilter() const;
+
+ /**
+ * Set mime-based filter to only list items matching the given mimetypes.
+ *
+ * NOTE: setting the filter does not automatically reload direcory.
+ * Also calling this function will not affect any named filter already set.
+ *
+ * @param mimeList a list of mime-types.
+ *
+ * @see clearMimeFilter
+ * @see matchesMimeFilter
+ */
+ virtual void setMimeFilter( const TQStringList &mimeList );
+
+ /**
+ * Filtering should be done with KFileFilter. This will be implemented in a later
+ * revision of KDirLister. This method may be removed then.
+ *
+ * Set mime-based exclude filter to only list items not matching the given mimetypes
+ *
+ * NOTE: setting the filter does not automatically reload direcory.
+ * Also calling this function will not affect any named filter already set.
+ *
+ * @param mimeList a list of mime-types.
+ * @see clearMimeFilter
+ * @see matchesMimeFilter
+ * @since 3.1
+ * @internal
+ */
+ void setMimeExcludeFilter(const TQStringList &mimeList );
+
+
+ /**
+ * Clears the mime based filter.
+ *
+ * @see setMimeFilter
+ */
+ virtual void clearMimeFilter();
+
+ /**
+ * Returns the list of mime based filters, as set via setMimeFilter().
+ * @return the list of mime based filters. Empty, when no mime filter is set.
+ */
+ const TQStringList& mimeFilters() const;
+
+ /**
+ * Checks whether @p name matches a filter in the list of name filters.
+ * @return true if @p name matches a filter in the list,
+ * otherwise false.
+ * @see setNameFilter
+ */
+ bool matchesFilter( const TQString& name ) const;
+
+ /**
+ * Checks whether @p mime matches a filter in the list of mime types
+ * @param mime the mimetype to find in the filter list.
+ * @return true if @p name matches a filter in the list,
+ * otherwise false.
+ * @see setMimeFilter.
+ */
+ bool matchesMimeFilter( const TQString& mime ) const;
+
+ /**
+ * Pass the main window this object is associated with
+ * this is used for caching authentication data
+ * @param window the window to associate with, 0 to disassociate
+ * @since 3.1
+ */
+ void setMainWindow( TQWidget *window );
+
+ /**
+ * Returns the main window associated with this object.
+ * @return the associated main window, or 0 if there is none
+ * @since 3.1
+ */
+ TQWidget *mainWindow();
+
+ /**
+ * Used by items() and itemsForDir() to specify whether you want
+ * all items for a directory or just the filtered ones.
+ */
+ enum WhichItems
+ {
+ AllItems = 0,
+ FilteredItems = 1
+ };
+
+ /**
+ * Returns the items listed for the current url().
+ * This method will NOT start listing a directory, you should only call
+ * this when receiving the finished() signal.
+ *
+ * The items in the KFileItemList are references to the items used
+ * by KDirLister, so e.g. an item gets destroyed when the deleteItem()
+ * signal is emitted.
+ *
+ * @param which specifies whether the returned list will contain all entries
+ * or only the ones that passed the nameFilter(), mimeFilter(),
+ * etc. Note that the latter causes iteration over all the
+ * items, filtering them. If this is too slow for you, use the
+ * newItems() signal, sending out filtered items in chunks.
+ * @return the items listed for the current url().
+ * @since 3.1
+ */
+ KFileItemList items( WhichItems which = FilteredItems ) const;
+
+ /**
+ * Returns the items listed for the given @p dir.
+ * This method will NOT start listing @p dir, you should only call
+ * this when receiving the finished() signal.
+ *
+ * The items in the KFileItemList are references to the items used
+ * by KDirLister, so e.g. an item gets destroyed when the deleteItem()
+ * signal is emitted.
+ *
+ * @param dir specifies the url for which the items should be returned. This
+ * is only useful if you use KDirLister with multiple URLs
+ * i.e. using bool keep = true in openURL().
+ * @param which specifies whether the returned list will contain all entries
+ * or only the ones that passed the nameFilter, mimeFilter, etc.
+ * Note that the latter causes iteration over all the items,
+ * filtering them. If this is too slow for you, use the
+ * newItems() signal, sending out filtered items in chunks.
+ * @return the items listed for @p dir.
+ * @since 3.1
+ */
+ KFileItemList itemsForDir( const KURL& dir,
+ WhichItems which = FilteredItems ) const;
+
+signals:
+ /**
+ * Tell the view that we started to list @p _url. NOTE: this does _not_ imply that there
+ * is really a job running! I.e. KDirLister::jobs() may return an empty list. In this case
+ * the items are taken from the cache.
+ *
+ * The view knows that openURL should start it, so it might seem useless,
+ * but the view also needs to know when an automatic update happens.
+ * @param _url the URL to list
+ */
+ void started( const KURL& _url );
+
+ /**
+ * Tell the view that listing is finished. There are no jobs running anymore.
+ */
+ void completed();
+
+ /**
+ * Tell the view that the listing of the directory @p _url is finished.
+ * There might be other running jobs left.
+ * @param _url the directory URL
+ */
+ void completed( const KURL& _url );
+
+ /**
+ * Tell the view that the user canceled the listing. No running jobs are left.
+ */
+ void canceled();
+
+ /**
+ * Tell the view that the listing of the directory @p _url was canceled.
+ * There might be other running jobs left.
+ * @param _url the directory URL
+ */
+ void canceled( const KURL& _url );
+
+ /**
+ * Signal a redirection.
+ * Only emitted if there's just one directory to list, i.e. most
+ * probably openURL() has been called with @p _keep == @p false.
+ * @param _url the new URL
+ */
+ void redirection( const KURL& _url );
+
+ /**
+ * Signal a redirection.
+ * @param oldUrl the original URL
+ * @param newUrl the new URL
+ */
+ void redirection( const KURL& oldUrl, const KURL& newUrl );
+
+ /**
+ * Signal to clear all items.
+ * It must always be connected to this signal to avoid doubled items!
+ */
+ void clear();
+
+ /**
+ * Signal to empty the directory @p _url.
+ * It is only emitted if the lister is holding more than one directory.
+ * @param _url the directory that will be emptied
+ */
+ void clear( const KURL& _url );
+
+ /**
+ * Signal new items.
+ * @param items a list of new items
+ */
+ void newItems( const KFileItemList& items );
+
+ /**
+ * Send a list of items filtered-out by mime-type.
+ * @param items the list of filtered items
+ */
+ void itemsFilteredByMime( const KFileItemList& items );
+
+ /**
+ * Signal an item to remove.
+ *
+ * ATTENTION: if @p _fileItem == rootItem() the directory this lister
+ * is holding was deleted and you HAVE to release especially the
+ * rootItem() of this lister, otherwise your app will CRASH!!
+ * The clear() signals have been emitted already.
+ * @param _fileItem the fileItem to delete
+ */
+ void deleteItem( KFileItem *_fileItem );
+
+ /**
+ * Signal an item to refresh (its mimetype/icon/name has changed).
+ * Note: KFileItem::refresh has already been called on those items.
+ * @param items the items to refresh
+ */
+ void refreshItems( const KFileItemList& items );
+
+ /**
+ * Emitted to display information about running jobs.
+ * Examples of message are "Resolving host", "Connecting to host...", etc.
+ * @param msg the info message
+ */
+ void infoMessage( const TQString& msg );
+
+ /**
+ * Progress signal showing the overall progress of the KDirLister.
+ * This allows using a progress bar very easily. (see KProgress)
+ * @param percent the progress in percent
+ */
+ void percent( int percent );
+
+ /**
+ * Emitted when we know the size of the jobs.
+ * @param size the total size in bytes
+ */
+ void totalSize( TDEIO::filesize_t size );
+
+ /**
+ * Regularly emitted to show the progress of this KDirLister.
+ * @param size the processed size in bytes
+ */
+ void processedSize( TDEIO::filesize_t size );
+
+ /**
+ * Emitted to display information about the speed of the jobs.
+ * @param bytes_per_second the speed in bytes/s
+ */
+ void speed( int bytes_per_second );
+
+protected:
+ enum Changes {
+ NONE=0, NAME_FILTER=1, MIME_FILTER=2, DOT_FILES=4, DIR_ONLY_MODE=8
+ };
+
+ /**
+ * Called for every new item before emitting newItems().
+ * You may reimplement this method in a subclass to implement your own
+ * filtering.
+ * The default implementation filters out ".." and everything not matching
+ * the name filter(s)
+ * @return true if the item is "ok".
+ * false if the item shall not be shown in a view, e.g.
+ * files not matching a pattern *.cpp ( KFileItem::isHidden())
+ * @see matchesFilter
+ * @see setNameFilter
+ */
+ virtual bool matchesFilter( const KFileItem * ) const;
+
+ /**
+ * Called for every new item before emitting newItems().
+ * You may reimplement this method in a subclass to implement your own
+ * filtering.
+ * The default implementation filters out ".." and everything not matching
+ * the name filter(s)
+ * @return true if the item is "ok".
+ * false if the item shall not be shown in a view, e.g.
+ * files not matching a pattern *.cpp ( KFileItem::isHidden())
+ * @see matchesMimeFilter
+ * @see setMimeFilter
+ */
+ virtual bool matchesMimeFilter( const KFileItem * ) const;
+
+ /**
+ * Called by the public matchesFilter() to do the
+ * actual filtering. Those methods may be reimplemented to customize
+ * filtering.
+ * @param name the name to filter
+ * @param filters a list of regular expressions for filtering
+ */
+ virtual bool doNameFilter( const TQString& name, const TQPtrList<TQRegExp>& filters ) const;
+
+ /**
+ * Called by the public matchesMimeFilter() to do the
+ * actual filtering. Those methods may be reimplemented to customize
+ * filtering.
+ * @param mime the mime type to filter
+ * @param filters the list of mime types to filter
+ */
+ virtual bool doMimeFilter( const TQString& mime, const TQStringList& filters ) const;
+
+ /**
+ * @internal
+ */
+ bool doMimeExcludeFilter( const TQString& mimeExclude, const TQStringList& filters ) const;
+
+ /**
+ * Checks if an url is malformed or not and displays an error message
+ * if it is and autoErrorHandling is set to true.
+ * @return true if url is valid, otherwise false.
+ */
+ virtual bool validURL( const KURL& ) const;
+
+ /** Reimplement to customize error handling */
+ virtual void handleError( TDEIO::Job * );
+
+protected:
+ virtual void virtual_hook( int id, void *data );
+
+private slots:
+ void slotInfoMessage( TDEIO::Job *, const TQString& );
+ void slotPercent( TDEIO::Job *, unsigned long );
+ void slotTotalSize( TDEIO::Job *, TDEIO::filesize_t );
+ void slotProcessedSize( TDEIO::Job *, TDEIO::filesize_t );
+ void slotSpeed( TDEIO::Job *, unsigned long );
+ void slotLocalURL( TDEIO::Job *, const KURL&, bool );
+ void slotLocalURLKIODestroyed( );
+
+private:
+ void jobStarted( TDEIO::ListJob * );
+ void connectJob( TDEIO::ListJob * );
+ void jobDone( TDEIO::ListJob * );
+
+ uint numJobs();
+
+private:
+ virtual void addNewItem( const KFileItem *item );
+ virtual void addNewItems( const KFileItemList& items );
+ /*virtual*/ void aboutToRefreshItem( const KFileItem *item ); // TODO: KDE 4.0 make virtual
+ virtual void addRefreshItem( const KFileItem *item );
+ virtual void emitItems();
+ virtual void emitDeleteItem( KFileItem *item );
+
+ KDirListerPrivate *d;
+};
+
+#endif
+
diff --git a/tdeio/tdeio/kdirlister_p.h b/tdeio/tdeio/kdirlister_p.h
new file mode 100644
index 000000000..d6dff7bcf
--- /dev/null
+++ b/tdeio/tdeio/kdirlister_p.h
@@ -0,0 +1,358 @@
+/* This file is part of the KDE project
+ Copyright (C) 2002 Michael Brade <brade@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef kdirlister_p_h
+#define kdirlister_p_h
+
+#include "tdefileitem.h"
+
+#include <tqmap.h>
+#include <tqdict.h>
+#include <tqcache.h>
+#include <tqwidget.h>
+
+#include <kurl.h>
+#include <tdeio/global.h>
+#include <kdirwatch.h>
+#include <dcopclient.h>
+
+class TQTimer;
+class KDirLister;
+namespace TDEIO { class Job; class ListJob; }
+
+
+class KDirLister::KDirListerPrivate
+{
+public:
+ KDirListerPrivate()
+ {
+ complete = false;
+
+ autoUpdate = false;
+ isShowingDotFiles = false;
+ dirOnlyMode = false;
+
+ autoErrorHandling = false;
+ errorParent = 0;
+
+ delayedMimeTypes = false;
+
+ rootFileItem = 0;
+ lstNewItems = 0;
+ lstRefreshItems = 0;
+ lstMimeFilteredItems = 0;
+ lstRemoveItems = 0;
+ refreshItemWasFiltered = false;
+
+ changes = NONE;
+
+ window = 0;
+
+ lstFilters.setAutoDelete( true );
+ oldFilters.setAutoDelete( true );
+ }
+
+ /**
+ * List of dirs handled by this dirlister. The first entry is the base URL.
+ * For a tree view, it contains all the dirs shown.
+ */
+ KURL::List lstDirs;
+
+ // toplevel URL
+ KURL url;
+
+ bool complete;
+
+ bool autoUpdate;
+ bool isShowingDotFiles;
+ bool dirOnlyMode;
+
+ bool autoErrorHandling;
+ TQWidget *errorParent;
+
+ bool delayedMimeTypes;
+
+ struct JobData {
+ long unsigned int percent, speed;
+ TDEIO::filesize_t processedSize, totalSize;
+ };
+
+ TQMap<TDEIO::ListJob *, JobData> jobData;
+
+ // file item for the root itself (".")
+ KFileItem *rootFileItem;
+
+ KFileItemList *lstNewItems, *lstRefreshItems;
+ KFileItemList *lstMimeFilteredItems, *lstRemoveItems;
+
+ bool refreshItemWasFiltered;
+
+ int changes;
+
+ TQWidget *window; // Main window ths lister is associated with
+
+ TQString nameFilter;
+ TQPtrList<TQRegExp> lstFilters, oldFilters;
+ TQStringList mimeFilter, oldMimeFilter;
+ TQStringList mimeExcludeFilter, oldMimeExcludeFilter;
+
+ bool localURLSlotFired;
+ KURL localURLResultURL;
+ bool localURLResultIsLocal;
+};
+
+/**
+ * Design of the cache:
+ * There is a single KDirListerCache for the whole process.
+ * It holds all the items used by the dir listers (itemsInUse)
+ * as well as a cache of the recently used items (itemsCached).
+ * Those items are grouped by directory (a DirItem represents a whole directory).
+ *
+ * KDirListerCache also runs all the jobs for listing directories, whether they are for
+ * normal listing or for updates.
+ * For faster lookups, it also stores two dicts:
+ * a URL -> dirlister holding that URL (urlsCurrentlyHeld)
+ * a URL -> dirlister currently listing that URL (urlsCurrentlyListed)
+ */
+class KDirListerCache : public TQObject, KDirNotify
+{
+ Q_OBJECT
+public:
+ KDirListerCache( int maxCount = 10 );
+ ~KDirListerCache();
+
+ bool listDir( KDirLister *lister, const KURL& _url, bool _keep, bool _reload );
+ bool validURL( const KDirLister *lister, const KURL& _url ) const;
+
+ // stop all running jobs for lister
+ void stop( KDirLister *lister );
+ // stop just the job listing url for lister
+ void stop( KDirLister *lister, const KURL &_url );
+
+ void setAutoUpdate( KDirLister *lister, bool enable );
+
+ void forgetDirs( KDirLister *lister );
+ void forgetDirs( KDirLister *lister, const KURL &_url, bool notify );
+
+ void updateDirectory( const KURL &_dir );
+
+ KFileItemList *itemsForDir( const KURL &_dir ) const;
+
+ KFileItem *findByName( const KDirLister *lister, const TQString &_name ) const;
+ // if lister is set, it is checked that the url is held by the lister
+ KFileItem *findByURL( const KDirLister *lister, const KURL &_url ) const;
+
+ /**
+ * Notify that files have been added in @p directory
+ * The receiver will list that directory again to find
+ * the new items (since it needs more than just the names anyway).
+ * Reimplemented from KDirNotify.
+ */
+ virtual void FilesAdded( const KURL &directory );
+
+ /**
+ * Notify that files have been deleted.
+ * This call passes the exact urls of the deleted files
+ * so that any view showing them can simply remove them
+ * or be closed (if its current dir was deleted)
+ * Reimplemented from KDirNotify.
+ */
+ virtual void FilesRemoved( const KURL::List &fileList );
+
+ /**
+ * Notify that files have been changed.
+ * At the moment, this is only used for new icon, but it could be
+ * used for size etc. as well.
+ * Note: this is ASYNC so that it can be used with a broadcast
+ */
+ virtual void FilesChanged( const KURL::List &fileList );
+ virtual void FileRenamed( const KURL &src, const KURL &dst );
+
+ static KDirListerCache *self();
+
+ static bool exists();
+
+private slots:
+ void slotFileDirty( const TQString &_file );
+ void slotFileCreated( const TQString &_file );
+ void slotFileDeleted( const TQString &_file );
+
+ void slotFileDirtyDelayed();
+
+ void slotEntries( TDEIO::Job *job, const TDEIO::UDSEntryList &entries );
+ void slotResult( TDEIO::Job *j );
+ void slotRedirection( TDEIO::Job *job, const KURL &url );
+
+ void slotUpdateEntries( TDEIO::Job *job, const TDEIO::UDSEntryList &entries );
+ void slotUpdateResult( TDEIO::Job *job );
+
+private:
+ TDEIO::ListJob *jobForUrl( const TQString& url, TDEIO::ListJob *not_job = 0 );
+ const KURL& joburl( TDEIO::ListJob *job );
+
+ void killJob( TDEIO::ListJob *job );
+
+ // check if _url is held by some lister and return true,
+ // otherwise schedule a delayed update and return false
+ bool checkUpdate( const TQString& _url );
+ // when there were items deleted from the filesystem all the listers holding
+ // the parent directory need to be notified, the unmarked items have to be deleted
+ // and removed from the cache including all the childs.
+ void deleteUnmarkedItems( TQPtrList<KDirLister> *, KFileItemList * );
+ void processPendingUpdates();
+ // common for slotRedirection and FileRenamed
+ void renameDir( const KURL &oldUrl, const KURL &url );
+ // common for deleteUnmarkedItems and FilesRemoved
+ void deleteDir( const KURL& dirUrl );
+ // remove directory from cache (itemsCached), including all child dirs
+ void removeDirFromCache( const KURL& dir );
+ // helper for renameDir
+ void emitRedirections( const KURL &oldUrl, const KURL &url );
+
+ void aboutToRefreshItem( KFileItem *fileitem );
+ void emitRefreshItem( KFileItem *fileitem );
+
+#ifndef NDEBUG
+ void printDebug();
+#endif
+
+ struct DirItem
+ {
+ DirItem( const KURL &dir )
+ : url(dir), rootItem(0), lstItems(new KFileItemList)
+ {
+ autoUpdates = 0;
+ complete = false;
+ lstItems->setAutoDelete( true );
+ }
+
+ ~DirItem()
+ {
+ if ( autoUpdates )
+ {
+ if ( KDirWatch::exists() && url.isLocalFile() )
+ kdirwatch->removeDir( url.path() );
+ sendSignal( false, url );
+ }
+ delete rootItem;
+ delete lstItems;
+ }
+
+ void sendSignal( bool entering, const KURL& url )
+ {
+ DCOPClient *client = DCOPClient::mainClient();
+ if ( !client )
+ return;
+ TQByteArray data;
+ TQDataStream arg( data, IO_WriteOnly );
+ arg << url;
+ client->emitDCOPSignal( "KDirNotify", entering ? "enteredDirectory(KURL)" : "leftDirectory(KURL)", data );
+ }
+
+ void redirect( const KURL& newUrl )
+ {
+ if ( autoUpdates )
+ {
+ if ( url.isLocalFile() )
+ kdirwatch->removeDir( url.path() );
+ sendSignal( false, url );
+
+ if ( newUrl.isLocalFile() )
+ kdirwatch->addDir( newUrl.path() );
+ sendSignal( true, newUrl );
+ }
+
+ url = newUrl;
+
+ if ( rootItem )
+ rootItem->setURL( newUrl );
+ }
+
+ void incAutoUpdate()
+ {
+ if ( autoUpdates++ == 0 )
+ {
+ if ( url.isLocalFile() )
+ kdirwatch->addDir( url.path() );
+ sendSignal( true, url );
+ }
+ }
+
+ void decAutoUpdate()
+ {
+ if ( --autoUpdates == 0 )
+ {
+ if ( url.isLocalFile() )
+ kdirwatch->removeDir( url.path() );
+ sendSignal( false, url );
+ }
+
+ else if ( autoUpdates < 0 )
+ autoUpdates = 0;
+ }
+
+ // number of KDirListers using autoUpdate for this dir
+ short autoUpdates;
+
+ // this directory is up-to-date
+ bool complete;
+
+ // the complete url of this directory
+ KURL url;
+
+ // KFileItem representing the root of this directory.
+ // Remember that this is optional. FTP sites don't return '.' in
+ // the list, so they give no root item
+ KFileItem *rootItem;
+ KFileItemList *lstItems;
+ };
+
+ static const unsigned short MAX_JOBS_PER_LISTER;
+ TQMap<TDEIO::ListJob *, TDEIO::UDSEntryList> jobs;
+
+ // an item is a complete directory
+ TQDict<DirItem> itemsInUse;
+ TQCache<DirItem> itemsCached;
+
+ // A lister can be EITHER in urlsCurrentlyListed OR urlsCurrentlyHeld but NOT
+ // in both at the same time.
+ // On the other hand there can be some listers in urlsCurrentlyHeld
+ // and some in urlsCurrentlyListed for the same url!
+ // Or differently said, there can be an entry for url in urlsCurrentlyListed
+ // and urlsCurrentlyHeld. This happens if more listers are requesting url at
+ // the same time and one lister was stopped during the listing of files.
+
+ // saves all urls that are currently being listed and maps them
+ // to their KDirListers
+ TQDict< TQPtrList<KDirLister> > urlsCurrentlyListed;
+
+ // saves all KDirListers that are just holding url
+ TQDict< TQPtrList<KDirLister> > urlsCurrentlyHeld;
+
+ // running timers for the delayed update
+ TQDict<TQTimer> pendingUpdates;
+
+ static KDirListerCache *s_pSelf;
+};
+
+const unsigned short KDirListerCache::MAX_JOBS_PER_LISTER = 5;
+
+#define s_pCache KDirListerCache::self()
+
+#endif
diff --git a/kio/kio/kdirnotify.cpp b/tdeio/tdeio/kdirnotify.cpp
index fb98196f5..fb98196f5 100644
--- a/kio/kio/kdirnotify.cpp
+++ b/tdeio/tdeio/kdirnotify.cpp
diff --git a/kio/kio/kdirnotify.h b/tdeio/tdeio/kdirnotify.h
index 14d864609..14d864609 100644
--- a/kio/kio/kdirnotify.h
+++ b/tdeio/tdeio/kdirnotify.h
diff --git a/kio/kio/kdirnotify_stub.cpp b/tdeio/tdeio/kdirnotify_stub.cpp
index 66988d6c9..66988d6c9 100644
--- a/kio/kio/kdirnotify_stub.cpp
+++ b/tdeio/tdeio/kdirnotify_stub.cpp
diff --git a/kio/kio/kdirnotify_stub.h b/tdeio/tdeio/kdirnotify_stub.h
index 56ab168c4..56ab168c4 100644
--- a/kio/kio/kdirnotify_stub.h
+++ b/tdeio/tdeio/kdirnotify_stub.h
diff --git a/tdeio/tdeio/kdirwatch.cpp b/tdeio/tdeio/kdirwatch.cpp
new file mode 100644
index 000000000..c4057264b
--- /dev/null
+++ b/tdeio/tdeio/kdirwatch.cpp
@@ -0,0 +1,1774 @@
+// -*- c-basic-offset: 2 -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 1998 Sven Radej <sven@lisa.exp.univie.ac.at>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+
+// CHANGES:
+// Oct 4, 2005 - Inotify support (Dirk Mueller)
+// Februar 2002 - Add file watching and remote mount check for STAT
+// Mar 30, 2001 - Native support for Linux dir change notification.
+// Jan 28, 2000 - Usage of FAM service on IRIX (Josef.Weidendorfer@in.tum.de)
+// May 24. 1998 - List of times introduced, and some bugs are fixed. (sven)1
+// May 23. 1998 - Removed static pointer - you can have more instances.
+// It was Needed for KRegistry. KDirWatch now emits signals and doesn't
+// call (or need) KFM. No more URL's - just plain paths. (sven)
+// Mar 29. 1998 - added docs, stop/restart for particular Dirs and
+// deep copies for list of dirs. (sven)
+// Mar 28. 1998 - Created. (sven)
+
+
+#include <config.h>
+#include <errno.h>
+
+#ifdef HAVE_DNOTIFY
+#include <unistd.h>
+#include <time.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <errno.h>
+#endif
+
+
+#include <sys/stat.h>
+#include <assert.h>
+#include <tqdir.h>
+#include <tqfile.h>
+#include <tqintdict.h>
+#include <tqptrlist.h>
+#include <tqsocketnotifier.h>
+#include <tqstringlist.h>
+#include <tqtimer.h>
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <tdeconfig.h>
+#include <kglobal.h>
+#include <kstaticdeleter.h>
+#include <kde_file.h>
+
+// debug
+#include <sys/ioctl.h>
+
+#ifdef HAVE_INOTIFY
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/syscall.h>
+#include <linux/types.h>
+// Linux kernel headers are documented to not compile
+#define _S390_BITOPS_H
+#include <sys/inotify.h>
+
+#ifndef __NR_inotify_init
+#if defined(__i386__)
+#define __NR_inotify_init 291
+#define __NR_inotify_add_watch 292
+#define __NR_inotify_rm_watch 293
+#endif
+#if defined(__PPC__)
+#define __NR_inotify_init 275
+#define __NR_inotify_add_watch 276
+#define __NR_inotify_rm_watch 277
+#endif
+#if defined(__x86_64__)
+#define __NR_inotify_init 253
+#define __NR_inotify_add_watch 254
+#define __NR_inotify_rm_watch 255
+#endif
+#endif
+
+#ifndef IN_ONLYDIR
+#define IN_ONLYDIR 0x01000000
+#endif
+
+#ifndef IN_DONT_FOLLOW
+#define IN_DONT_FOLLOW 0x02000000
+#endif
+
+#ifndef IN_MOVE_SELF
+#define IN_MOVE_SELF 0x00000800
+#endif
+
+#endif
+
+#include <sys/utsname.h>
+
+#include "kdirwatch.h"
+#include "kdirwatch_p.h"
+#include "global.h" // TDEIO::probably_slow_mounted
+
+#define NO_NOTIFY (time_t) 0
+
+static KDirWatchPrivate* dwp_self = 0;
+
+#ifdef HAVE_DNOTIFY
+
+static int dnotify_signal = 0;
+
+/* DNOTIFY signal handler
+ *
+ * As this is called asynchronously, only a flag is set and
+ * a rescan is requested.
+ * This is done by writing into a pipe to trigger a TQSocketNotifier
+ * watching on this pipe: a timer is started and after a timeout,
+ * the rescan is done.
+ */
+void KDirWatchPrivate::dnotify_handler(int, siginfo_t *si, void *)
+{
+ if (!dwp_self) return;
+
+ // write might change errno, we have to save it and restore it
+ // (Richard Stevens, Advanced programming in the Unix Environment)
+ int saved_errno = errno;
+
+ Entry* e = dwp_self->fd_Entry.find(si->si_fd);
+
+// kdDebug(7001) << "DNOTIFY Handler: fd " << si->si_fd << " path "
+// << TQString(e ? e->path:"unknown") << endl;
+
+ if(e && e->dn_fd == si->si_fd)
+ e->dirty = true;
+
+ char c = 0;
+ write(dwp_self->mPipe[1], &c, 1);
+ errno = saved_errno;
+}
+
+static struct sigaction old_sigio_act;
+/* DNOTIFY SIGIO signal handler
+ *
+ * When the kernel queue for the dnotify_signal overflows, a SIGIO is send.
+ */
+void KDirWatchPrivate::dnotify_sigio_handler(int sig, siginfo_t *si, void *p)
+{
+ if (dwp_self)
+ {
+ // write might change errno, we have to save it and restore it
+ // (Richard Stevens, Advanced programming in the Unix Environment)
+ int saved_errno = errno;
+
+ dwp_self->rescan_all = true;
+ char c = 0;
+ write(dwp_self->mPipe[1], &c, 1);
+
+ errno = saved_errno;
+ }
+
+ // Call previous signal handler
+ if (old_sigio_act.sa_flags & SA_SIGINFO)
+ {
+ if (old_sigio_act.sa_sigaction)
+ (*old_sigio_act.sa_sigaction)(sig, si, p);
+ }
+ else
+ {
+ if ((old_sigio_act.sa_handler != SIG_DFL) &&
+ (old_sigio_act.sa_handler != SIG_IGN))
+ (*old_sigio_act.sa_handler)(sig);
+ }
+}
+#endif
+
+
+//
+// Class KDirWatchPrivate (singleton)
+//
+
+/* All entries (files/directories) to be watched in the
+ * application (coming from multiple KDirWatch instances)
+ * are registered in a single KDirWatchPrivate instance.
+ *
+ * At the moment, the following methods for file watching
+ * are supported:
+ * - Polling: All files to be watched are polled regularly
+ * using stat (more precise: TQFileInfo.lastModified()).
+ * The polling frequency is determined from global tdeconfig
+ * settings, defaulting to 500 ms for local directories
+ * and 5000 ms for remote mounts
+ * - FAM (File Alternation Monitor): first used on IRIX, SGI
+ * has ported this method to LINUX. It uses a kernel part
+ * (IMON, sending change events to /dev/imon) and a user
+ * level damon (fam), to which applications connect for
+ * notification of file changes. For NFS, the fam damon
+ * on the NFS server machine is used; if IMON is not built
+ * into the kernel, fam uses polling for local files.
+ * - DNOTIFY: In late LINUX 2.3.x, directory notification was
+ * introduced. By opening a directory, you can request for
+ * UNIX signals to be sent to the process when a directory
+ * is changed.
+ * - INOTIFY: In LINUX 2.6.13, inode change notification was
+ * introduced. You're now able to watch arbitrary inode's
+ * for changes, and even get notification when they're
+ * unmounted.
+ */
+
+KDirWatchPrivate::KDirWatchPrivate()
+ : rescan_timer(0, "KDirWatchPrivate::rescan_timer")
+{
+ timer = new TQTimer(this, "KDirWatchPrivate::timer");
+ connect (timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotRescan()));
+ freq = 3600000; // 1 hour as upper bound
+ statEntries = 0;
+ delayRemove = false;
+ m_ref = 0;
+
+ TDEConfigGroup config(TDEGlobal::config(), TQCString("DirWatch"));
+ m_nfsPollInterval = config.readNumEntry("NFSPollInterval", 5000);
+ m_PollInterval = config.readNumEntry("PollInterval", 500);
+
+ TQString available("Stat");
+
+ // used for FAM and DNOTIFY
+ rescan_all = false;
+ connect(&rescan_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotRescan()));
+
+#ifdef HAVE_FAM
+ // It's possible that FAM server can't be started
+ if (FAMOpen(&fc) ==0) {
+ available += ", FAM";
+ use_fam=true;
+ sn = new TQSocketNotifier( FAMCONNECTION_GETFD(&fc),
+ TQSocketNotifier::Read, this);
+ connect( sn, TQT_SIGNAL(activated(int)),
+ this, TQT_SLOT(famEventReceived()) );
+ }
+ else {
+ kdDebug(7001) << "Can't use FAM (fam daemon not running?)" << endl;
+ use_fam=false;
+ }
+#endif
+
+#ifdef HAVE_INOTIFY
+ supports_inotify = true;
+
+ m_inotify_fd = inotify_init();
+
+ if ( m_inotify_fd <= 0 ) {
+ kdDebug(7001) << "Can't use Inotify, kernel doesn't support it" << endl;
+ supports_inotify = false;
+ }
+
+ {
+ struct utsname uts;
+ int major, minor, patch;
+ if (uname(&uts) < 0)
+ supports_inotify = false; // *shrug*
+ else if (sscanf(uts.release, "%d.%d.%d", &major, &minor, &patch) != 3)
+ supports_inotify = false; // *shrug*
+ else if( major * 1000000 + minor * 1000 + patch < 2006014 ) { // <2.6.14
+ kdDebug(7001) << "Can't use INotify, Linux kernel too old" << endl;
+ supports_inotify = false;
+ }
+ }
+
+ if ( supports_inotify ) {
+ available += ", Inotify";
+ fcntl(m_inotify_fd, F_SETFD, FD_CLOEXEC);
+
+ mSn = new TQSocketNotifier( m_inotify_fd, TQSocketNotifier::Read, this );
+ connect( mSn, TQT_SIGNAL(activated( int )), this, TQT_SLOT( slotActivated() ) );
+ }
+#endif
+
+#ifdef HAVE_DNOTIFY
+
+ // if we have inotify, disable dnotify.
+#ifdef HAVE_INOTIFY
+ supports_dnotify = !supports_inotify;
+#else
+ // otherwise, not guilty until proven guilty.
+ supports_dnotify = true;
+#endif
+
+ struct utsname uts;
+ int major, minor, patch;
+ if (uname(&uts) < 0)
+ supports_dnotify = false; // *shrug*
+ else if (sscanf(uts.release, "%d.%d.%d", &major, &minor, &patch) != 3)
+ supports_dnotify = false; // *shrug*
+ else if( major * 1000000 + minor * 1000 + patch < 2004019 ) { // <2.4.19
+ kdDebug(7001) << "Can't use DNotify, Linux kernel too old" << endl;
+ supports_dnotify = false;
+ }
+
+ if( supports_dnotify ) {
+ available += ", DNotify";
+
+ pipe(mPipe);
+ fcntl(mPipe[0], F_SETFD, FD_CLOEXEC);
+ fcntl(mPipe[1], F_SETFD, FD_CLOEXEC);
+ fcntl(mPipe[0], F_SETFL, O_NONBLOCK | fcntl(mPipe[0], F_GETFL));
+ fcntl(mPipe[1], F_SETFL, O_NONBLOCK | fcntl(mPipe[1], F_GETFL));
+ mSn = new TQSocketNotifier( mPipe[0], TQSocketNotifier::Read, this);
+ connect(mSn, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotActivated()));
+ // Install the signal handler only once
+ if ( dnotify_signal == 0 )
+ {
+ dnotify_signal = SIGRTMIN + 8;
+
+ struct sigaction act;
+ act.sa_sigaction = KDirWatchPrivate::dnotify_handler;
+ sigemptyset(&act.sa_mask);
+ act.sa_flags = SA_SIGINFO;
+#ifdef SA_RESTART
+ act.sa_flags |= SA_RESTART;
+#endif
+ sigaction(dnotify_signal, &act, NULL);
+
+ act.sa_sigaction = KDirWatchPrivate::dnotify_sigio_handler;
+ sigaction(SIGIO, &act, &old_sigio_act);
+ }
+ }
+ else
+ {
+ mPipe[0] = -1;
+ mPipe[1] = -1;
+ }
+#endif
+
+ kdDebug(7001) << "Available methods: " << available << endl;
+}
+
+/* This is called on app exit (KStaticDeleter) */
+KDirWatchPrivate::~KDirWatchPrivate()
+{
+ timer->stop();
+
+ /* remove all entries being watched */
+ removeEntries(0);
+
+#ifdef HAVE_FAM
+ if (use_fam) {
+ FAMClose(&fc);
+ kdDebug(7001) << "KDirWatch deleted (FAM closed)" << endl;
+ }
+#endif
+#ifdef HAVE_INOTIFY
+ if ( supports_inotify )
+ ::close( m_inotify_fd );
+#endif
+#ifdef HAVE_DNOTIFY
+ close(mPipe[0]);
+ close(mPipe[1]);
+#endif
+}
+
+#include <stdlib.h>
+
+void KDirWatchPrivate::slotActivated()
+{
+#ifdef HAVE_DNOTIFY
+ if ( supports_dnotify )
+ {
+ char dummy_buf[4096];
+ read(mPipe[0], &dummy_buf, 4096);
+
+ if (!rescan_timer.isActive())
+ rescan_timer.start(m_PollInterval, true /* singleshot */);
+
+ return;
+ }
+#endif
+
+#ifdef HAVE_INOTIFY
+ if ( !supports_inotify )
+ return;
+
+ int pending = -1;
+ int offset = 0;
+ char buf[4096];
+ assert( m_inotify_fd > -1 );
+ ioctl( m_inotify_fd, FIONREAD, &pending );
+
+ while ( pending > 0 ) {
+
+ if ( pending > (int)sizeof( buf ) )
+ pending = sizeof( buf );
+
+ pending = read( m_inotify_fd, buf, pending);
+
+ while ( pending > 0 ) {
+ struct inotify_event *event = (struct inotify_event *) &buf[offset];
+ pending -= sizeof( struct inotify_event ) + event->len;
+ offset += sizeof( struct inotify_event ) + event->len;
+
+ TQString path;
+ if ( event->len )
+ path = TQFile::decodeName( TQCString( event->name, event->len ) );
+
+ if ( path.length() && isNoisyFile( path.latin1() ) )
+ continue;
+
+ kdDebug(7001) << "ev wd: " << event->wd << " mask " << event->mask << " path: " << path << endl;
+
+ // now we're in deep trouble of finding the
+ // associated entries
+ // for now, we suck and iterate
+ for ( EntryMap::Iterator it = m_mapEntries.begin();
+ it != m_mapEntries.end(); ++it ) {
+ Entry* e = &( *it );
+ if ( e->wd == event->wd ) {
+ e->dirty = true;
+
+ if ( 1 || e->isDir) {
+ if( event->mask & IN_DELETE_SELF) {
+ kdDebug(7001) << "-->got deleteself signal for " << e->path << endl;
+ e->m_status = NonExistent;
+ if (e->isDir)
+ addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
+ else
+ addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
+ }
+ if ( event->mask & IN_IGNORED ) {
+ e->wd = 0;
+ }
+ if ( event->mask & (IN_CREATE|IN_MOVED_TO) ) {
+ Entry *sub_entry = e->m_entries.first();
+ for(;sub_entry; sub_entry = e->m_entries.next())
+ if (sub_entry->path == e->path + "/" + path) break;
+
+ if (sub_entry /*&& sub_entry->isDir*/) {
+ removeEntry(0,e->path, sub_entry);
+ KDE_struct_stat stat_buf;
+ TQCString tpath = TQFile::encodeName(path);
+ KDE_stat(tpath, &stat_buf);
+
+ //sub_entry->isDir = S_ISDIR(stat_buf.st_mode);
+ //sub_entry->m_ctime = stat_buf.st_ctime;
+ //sub_entry->m_status = Normal;
+ //sub_entry->m_nlink = stat_buf.st_nlink;
+
+ if(!useINotify(sub_entry))
+ useStat(sub_entry);
+ sub_entry->dirty = true;
+ }
+ }
+ }
+
+ if (!rescan_timer.isActive())
+ rescan_timer.start(m_PollInterval, true /* singleshot */);
+
+ break; // there really should be only one matching wd
+ }
+ }
+
+ }
+ }
+#endif
+}
+
+/* In DNOTIFY/FAM mode, only entries which are marked dirty are scanned.
+ * We first need to mark all yet nonexistent, but possible created
+ * entries as dirty...
+ */
+void KDirWatchPrivate::Entry::propagate_dirty()
+{
+ for (TQPtrListIterator<Entry> sub_entry (m_entries);
+ sub_entry.current(); ++sub_entry)
+ {
+ if (!sub_entry.current()->dirty)
+ {
+ sub_entry.current()->dirty = true;
+ sub_entry.current()->propagate_dirty();
+ }
+ }
+}
+
+
+/* A KDirWatch instance is interested in getting events for
+ * this file/Dir entry.
+ */
+void KDirWatchPrivate::Entry::addClient(KDirWatch* instance)
+{
+ Client* client = m_clients.first();
+ for(;client; client = m_clients.next())
+ if (client->instance == instance) break;
+
+ if (client) {
+ client->count++;
+ return;
+ }
+
+ client = new Client;
+ client->instance = instance;
+ client->count = 1;
+ client->watchingStopped = instance->isStopped();
+ client->pending = NoChange;
+
+ m_clients.append(client);
+}
+
+void KDirWatchPrivate::Entry::removeClient(KDirWatch* instance)
+{
+ Client* client = m_clients.first();
+ for(;client; client = m_clients.next())
+ if (client->instance == instance) break;
+
+ if (client) {
+ client->count--;
+ if (client->count == 0) {
+ m_clients.removeRef(client);
+ delete client;
+ }
+ }
+}
+
+/* get number of clients */
+int KDirWatchPrivate::Entry::clients()
+{
+ int clients = 0;
+ Client* client = m_clients.first();
+ for(;client; client = m_clients.next())
+ clients += client->count;
+
+ return clients;
+}
+
+
+KDirWatchPrivate::Entry* KDirWatchPrivate::entry(const TQString& _path)
+{
+// we only support absolute paths
+ if (TQDir::isRelativePath(_path)) {
+ return 0;
+ }
+
+ TQString path = _path;
+
+ if ( path.length() > 1 && path.right(1) == "/" )
+ path.truncate( path.length() - 1 );
+
+ EntryMap::Iterator it = m_mapEntries.find( path );
+ if ( it == m_mapEntries.end() )
+ return 0;
+ else
+ return &(*it);
+}
+
+// set polling frequency for a entry and adjust global freq if needed
+void KDirWatchPrivate::useFreq(Entry* e, int newFreq)
+{
+ e->freq = newFreq;
+
+ // a reasonable frequency for the global polling timer
+ if (e->freq < freq) {
+ freq = e->freq;
+ if (timer->isActive()) timer->changeInterval(freq);
+ kdDebug(7001) << "Global Poll Freq is now " << freq << " msec" << endl;
+ }
+}
+
+
+#ifdef HAVE_FAM
+// setup FAM notification, returns false if not possible
+bool KDirWatchPrivate::useFAM(Entry* e)
+{
+ if (!use_fam) return false;
+
+ // handle FAM events to avoid deadlock
+ // (FAM sends back all files in a directory when monitoring)
+ famEventReceived();
+
+ e->m_mode = FAMMode;
+ e->dirty = false;
+
+ if (e->isDir) {
+ if (e->m_status == NonExistent) {
+ // If the directory does not exist we watch the parent directory
+ addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
+ }
+ else {
+ int res =FAMMonitorDirectory(&fc, TQFile::encodeName(e->path),
+ &(e->fr), e);
+ if (res<0) {
+ e->m_mode = UnknownMode;
+ use_fam=false;
+ return false;
+ }
+ kdDebug(7001) << " Setup FAM (Req "
+ << FAMREQUEST_GETREQNUM(&(e->fr))
+ << ") for " << e->path << endl;
+ }
+ }
+ else {
+ if (e->m_status == NonExistent) {
+ // If the file does not exist we watch the directory
+ addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
+ }
+ else {
+ int res = FAMMonitorFile(&fc, TQFile::encodeName(e->path),
+ &(e->fr), e);
+ if (res<0) {
+ e->m_mode = UnknownMode;
+ use_fam=false;
+ return false;
+ }
+
+ kdDebug(7001) << " Setup FAM (Req "
+ << FAMREQUEST_GETREQNUM(&(e->fr))
+ << ") for " << e->path << endl;
+ }
+ }
+
+ // handle FAM events to avoid deadlock
+ // (FAM sends back all files in a directory when monitoring)
+ famEventReceived();
+
+ return true;
+}
+#endif
+
+
+#ifdef HAVE_DNOTIFY
+// setup DNotify notification, returns false if not possible
+bool KDirWatchPrivate::useDNotify(Entry* e)
+{
+ e->dn_fd = 0;
+ e->dirty = false;
+ if (!supports_dnotify) return false;
+
+ e->m_mode = DNotifyMode;
+
+ if (e->isDir) {
+ if (e->m_status == Normal) {
+ int fd = KDE_open(TQFile::encodeName(e->path).data(), O_RDONLY);
+ // Migrate fd to somewhere above 128. Some libraries have
+ // constructs like:
+ // fd = socket(...)
+ // if (fd > ARBITRARY_LIMIT)
+ // return error;
+ //
+ // Since programs might end up using a lot of KDirWatch objects
+ // for a rather long time the above braindamage could get
+ // triggered.
+ //
+ // By moving the kdirwatch fd's to > 128, calls like socket() will keep
+ // returning fd's < ARBITRARY_LIMIT for a bit longer.
+ int fd2 = fcntl(fd, F_DUPFD, 128);
+ if (fd2 >= 0)
+ {
+ close(fd);
+ fd = fd2;
+ }
+ if (fd<0) {
+ e->m_mode = UnknownMode;
+ return false;
+ }
+
+ int mask = DN_DELETE|DN_CREATE|DN_RENAME|DN_MULTISHOT;
+ // if dependant is a file watch, we check for MODIFY & ATTRIB too
+ for(Entry* dep=e->m_entries.first();dep;dep=e->m_entries.next())
+ if (!dep->isDir) { mask |= DN_MODIFY|DN_ATTRIB; break; }
+
+ if(fcntl(fd, F_SETSIG, dnotify_signal) < 0 ||
+ fcntl(fd, F_NOTIFY, mask) < 0) {
+
+ kdDebug(7001) << "Not using Linux Directory Notifications."
+ << endl;
+ supports_dnotify = false;
+ ::close(fd);
+ e->m_mode = UnknownMode;
+ return false;
+ }
+
+ fd_Entry.replace(fd, e);
+ e->dn_fd = fd;
+
+ kdDebug(7001) << " Setup DNotify (fd " << fd
+ << ") for " << e->path << endl;
+ }
+ else { // NotExisting
+ addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
+ }
+ }
+ else { // File
+ // we always watch the directory (DNOTIFY can't watch files alone)
+ // this notifies us about changes of files therein
+ addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
+ }
+
+ return true;
+}
+#endif
+
+#ifdef HAVE_INOTIFY
+// setup INotify notification, returns false if not possible
+bool KDirWatchPrivate::useINotify( Entry* e )
+{
+ e->wd = 0;
+ e->dirty = false;
+ if (!supports_inotify) return false;
+
+ e->m_mode = INotifyMode;
+
+ int mask = IN_DELETE|IN_DELETE_SELF|IN_CREATE|IN_MOVE|IN_MOVE_SELF|IN_DONT_FOLLOW;
+ if(!e->isDir)
+ mask |= IN_MODIFY|IN_ATTRIB;
+ else
+ mask |= IN_ONLYDIR;
+
+ // if dependant is a file watch, we check for MODIFY & ATTRIB too
+ for(Entry* dep=e->m_entries.first();dep;dep=e->m_entries.next()) {
+ if (!dep->isDir) { mask |= IN_MODIFY|IN_ATTRIB; break; }
+ }
+
+ if ( ( e->wd = inotify_add_watch( m_inotify_fd,
+ TQFile::encodeName( e->path ), mask) ) > 0 )
+ return true;
+
+ if ( e->m_status == NonExistent ) {
+ if (e->isDir)
+ addEntry(0, TQDir::cleanDirPath(e->path+"/.."), e, true);
+ else
+ addEntry(0, TQFileInfo(e->path).dirPath(true), e, true);
+ return true;
+ }
+
+ return false;
+}
+#endif
+
+bool KDirWatchPrivate::useStat(Entry* e)
+{
+ if ( e->path.startsWith("/media/") || (e->path == "/media")
+ || (TDEIO::probably_slow_mounted(e->path)) )
+ useFreq(e, m_nfsPollInterval);
+ else
+ useFreq(e, m_PollInterval);
+
+ if (e->m_mode != StatMode) {
+ e->m_mode = StatMode;
+ statEntries++;
+
+ if ( statEntries == 1 ) {
+ // if this was first STAT entry (=timer was stopped)
+ timer->start(freq); // then start the timer
+ kdDebug(7001) << " Started Polling Timer, freq " << freq << endl;
+ }
+ }
+
+ kdDebug(7001) << " Setup Stat (freq " << e->freq
+ << ") for " << e->path << endl;
+
+ return true;
+}
+
+
+/* If <instance> !=0, this KDirWatch instance wants to watch at <_path>,
+ * providing in <isDir> the type of the entry to be watched.
+ * Sometimes, entries are dependant on each other: if <sub_entry> !=0,
+ * this entry needs another entry to watch himself (when notExistent).
+ */
+void KDirWatchPrivate::addEntry(KDirWatch* instance, const TQString& _path,
+ Entry* sub_entry, bool isDir)
+{
+ TQString path = _path;
+ if (path.startsWith("/dev/") || (path == "/dev"))
+ return; // Don't even go there.
+
+ if ( path.length() > 1 && path.right(1) == "/" )
+ path.truncate( path.length() - 1 );
+
+ EntryMap::Iterator it = m_mapEntries.find( path );
+ if ( it != m_mapEntries.end() )
+ {
+ if (sub_entry) {
+ (*it).m_entries.append(sub_entry);
+ kdDebug(7001) << "Added already watched Entry " << path
+ << " (for " << sub_entry->path << ")" << endl;
+
+#ifdef HAVE_DNOTIFY
+ {
+ Entry* e = &(*it);
+ if( (e->m_mode == DNotifyMode) && (e->dn_fd > 0) ) {
+ int mask = DN_DELETE|DN_CREATE|DN_RENAME|DN_MULTISHOT;
+ // if dependant is a file watch, we check for MODIFY & ATTRIB too
+ for(Entry* dep=e->m_entries.first();dep;dep=e->m_entries.next())
+ if (!dep->isDir) { mask |= DN_MODIFY|DN_ATTRIB; break; }
+ if( fcntl(e->dn_fd, F_NOTIFY, mask) < 0) { // shouldn't happen
+ ::close(e->dn_fd);
+ e->m_mode = UnknownMode;
+ fd_Entry.remove(e->dn_fd);
+ e->dn_fd = 0;
+ useStat( e );
+ }
+ }
+ }
+#endif
+
+#ifdef HAVE_INOTIFY
+ {
+ Entry* e = &(*it);
+ if( (e->m_mode == INotifyMode) && (e->wd > 0) ) {
+ int mask = IN_DELETE|IN_DELETE_SELF|IN_CREATE|IN_MOVE|IN_MOVE_SELF|IN_DONT_FOLLOW;
+ if(!e->isDir)
+ mask |= IN_MODIFY|IN_ATTRIB;
+ else
+ mask |= IN_ONLYDIR;
+
+ inotify_rm_watch (m_inotify_fd, e->wd);
+ e->wd = inotify_add_watch( m_inotify_fd, TQFile::encodeName( e->path ), mask);
+ }
+ }
+#endif
+
+ }
+ else {
+ (*it).addClient(instance);
+ kdDebug(7001) << "Added already watched Entry " << path
+ << " (now " << (*it).clients() << " clients)"
+ << TQString(TQString(" [%1]").arg(instance->name())) << endl;
+ }
+ return;
+ }
+
+ // we have a new path to watch
+
+ KDE_struct_stat stat_buf;
+ TQCString tpath = TQFile::encodeName(path);
+ bool exists = (KDE_stat(tpath, &stat_buf) == 0);
+
+ Entry newEntry;
+ m_mapEntries.insert( path, newEntry );
+ // the insert does a copy, so we have to use <e> now
+ Entry* e = &(m_mapEntries[path]);
+
+ if (exists) {
+ e->isDir = S_ISDIR(stat_buf.st_mode);
+
+ if (e->isDir && !isDir)
+ kdWarning() << "KDirWatch: " << path << " is a directory. Use addDir!" << endl;
+ else if (!e->isDir && isDir)
+ kdWarning() << "KDirWatch: " << path << " is a file. Use addFile!" << endl;
+
+ e->m_ctime = stat_buf.st_ctime;
+ e->m_status = Normal;
+ e->m_nlink = stat_buf.st_nlink;
+ }
+ else {
+ e->isDir = isDir;
+ e->m_ctime = invalid_ctime;
+ e->m_status = NonExistent;
+ e->m_nlink = 0;
+ }
+
+ e->path = path;
+ if (sub_entry)
+ e->m_entries.append(sub_entry);
+ else
+ e->addClient(instance);
+
+ kdDebug(7001) << "Added " << (e->isDir ? "Dir ":"File ") << path
+ << (e->m_status == NonExistent ? " NotExisting" : "")
+ << (sub_entry ? TQString(TQString(" for %1").arg(sub_entry->path)) : TQString(""))
+ << (instance ? TQString(TQString(" [%1]").arg(instance->name())) : TQString(""))
+ << endl;
+
+
+ // now setup the notification method
+ e->m_mode = UnknownMode;
+ e->msecLeft = 0;
+
+ if ( isNoisyFile( tpath ) )
+ return;
+
+#ifdef HAVE_FAM
+ if (useFAM(e)) return;
+#endif
+
+#ifdef HAVE_INOTIFY
+ if (useINotify(e)) return;
+#endif
+
+#ifdef HAVE_DNOTIFY
+ if (useDNotify(e)) return;
+#endif
+
+ useStat(e);
+}
+
+
+void KDirWatchPrivate::removeEntry( KDirWatch* instance,
+ const TQString& _path, Entry* sub_entry )
+{
+ kdDebug(7001) << "KDirWatchPrivate::removeEntry for '" << _path << "' sub_entry: " << sub_entry << endl;
+ Entry* e = entry(_path);
+ if (!e) {
+ kdDebug(7001) << "KDirWatchPrivate::removeEntry can't handle '" << _path << "'" << endl;
+ return;
+ }
+
+ if (sub_entry)
+ e->m_entries.removeRef(sub_entry);
+ else
+ e->removeClient(instance);
+
+ if (e->m_clients.count() || e->m_entries.count()) {
+ kdDebug(7001) << "removeEntry: unwatched " << e->path << " " << _path << endl;
+ return;
+ }
+
+ if (delayRemove) {
+ // removeList is allowed to contain any entry at most once
+ if (removeList.findRef(e)==-1)
+ removeList.append(e);
+ // now e->isValid() is false
+ return;
+ }
+
+#ifdef HAVE_FAM
+ if (e->m_mode == FAMMode) {
+ if ( e->m_status == Normal) {
+ FAMCancelMonitor(&fc, &(e->fr) );
+ kdDebug(7001) << "Cancelled FAM (Req "
+ << FAMREQUEST_GETREQNUM(&(e->fr))
+ << ") for " << e->path << endl;
+ }
+ else {
+ if (e->isDir)
+ removeEntry(0, TQDir::cleanDirPath(e->path+"/.."), e);
+ else
+ removeEntry(0, TQFileInfo(e->path).dirPath(true), e);
+ }
+ }
+#endif
+
+#ifdef HAVE_INOTIFY
+ kdDebug(7001) << "inotify remove " << ( e->m_mode == INotifyMode ) << " " << ( e->m_status == Normal ) << endl;
+ if (e->m_mode == INotifyMode) {
+ if ( e->m_status == Normal ) {
+ (void) inotify_rm_watch( m_inotify_fd, e->wd );
+ kdDebug(7001) << "Cancelled INotify (fd " <<
+ m_inotify_fd << ", " << e->wd <<
+ ") for " << e->path << endl;
+ }
+ else {
+ if (e->isDir)
+ removeEntry(0, TQDir::cleanDirPath(e->path+"/.."), e);
+ else
+ removeEntry(0, TQFileInfo(e->path).dirPath(true), e);
+ }
+ }
+#endif
+
+#ifdef HAVE_DNOTIFY
+ if (e->m_mode == DNotifyMode) {
+ if (!e->isDir) {
+ removeEntry(0, TQFileInfo(e->path).dirPath(true), e);
+ }
+ else { // isDir
+ // must close the FD.
+ if ( e->m_status == Normal) {
+ if (e->dn_fd) {
+ ::close(e->dn_fd);
+ fd_Entry.remove(e->dn_fd);
+
+ kdDebug(7001) << "Cancelled DNotify (fd " << e->dn_fd
+ << ") for " << e->path << endl;
+ e->dn_fd = 0;
+
+ }
+ }
+ else {
+ removeEntry(0, TQDir::cleanDirPath(e->path+"/.."), e);
+ }
+ }
+ }
+#endif
+
+ if (e->m_mode == StatMode) {
+ statEntries--;
+ if ( statEntries == 0 ) {
+ timer->stop(); // stop timer if lists are empty
+ kdDebug(7001) << " Stopped Polling Timer" << endl;
+ }
+ }
+
+ kdDebug(7001) << "Removed " << (e->isDir ? "Dir ":"File ") << e->path
+ << (sub_entry ? TQString(TQString(" for %1").arg(sub_entry->path)) : TQString(""))
+ << (instance ? TQString(TQString(" [%1]").arg(instance->name())) : TQString(""))
+ << endl;
+ m_mapEntries.remove( e->path ); // <e> not valid any more
+}
+
+
+/* Called from KDirWatch destructor:
+ * remove <instance> as client from all entries
+ */
+void KDirWatchPrivate::removeEntries( KDirWatch* instance )
+{
+ TQPtrList<Entry> list;
+ int minfreq = 3600000;
+
+ // put all entries where instance is a client in list
+ EntryMap::Iterator it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it ) {
+ Client* c = (*it).m_clients.first();
+ for(;c;c=(*it).m_clients.next())
+ if (c->instance == instance) break;
+ if (c) {
+ c->count = 1; // forces deletion of instance as client
+ list.append(&(*it));
+ }
+ else if ( (*it).m_mode == StatMode && (*it).freq < minfreq )
+ minfreq = (*it).freq;
+ }
+
+ for(Entry* e=list.first();e;e=list.next())
+ removeEntry(instance, e->path, 0);
+
+ if (minfreq > freq) {
+ // we can decrease the global polling frequency
+ freq = minfreq;
+ if (timer->isActive()) timer->changeInterval(freq);
+ kdDebug(7001) << "Poll Freq now " << freq << " msec" << endl;
+ }
+}
+
+// instance ==0: stop scanning for all instances
+bool KDirWatchPrivate::stopEntryScan( KDirWatch* instance, Entry* e)
+{
+ int stillWatching = 0;
+ Client* c = e->m_clients.first();
+ for(;c;c=e->m_clients.next()) {
+ if (!instance || instance == c->instance)
+ c->watchingStopped = true;
+ else if (!c->watchingStopped)
+ stillWatching += c->count;
+ }
+
+ kdDebug(7001) << instance->name() << " stopped scanning " << e->path
+ << " (now " << stillWatching << " watchers)" << endl;
+
+ if (stillWatching == 0) {
+ // if nobody is interested, we don't watch
+ e->m_ctime = invalid_ctime; // invalid
+ e->m_status = NonExistent;
+ // e->m_status = Normal;
+ }
+ return true;
+}
+
+// instance ==0: start scanning for all instances
+bool KDirWatchPrivate::restartEntryScan( KDirWatch* instance, Entry* e,
+ bool notify)
+{
+ int wasWatching = 0, newWatching = 0;
+ Client* c = e->m_clients.first();
+ for(;c;c=e->m_clients.next()) {
+ if (!c->watchingStopped)
+ wasWatching += c->count;
+ else if (!instance || instance == c->instance) {
+ c->watchingStopped = false;
+ newWatching += c->count;
+ }
+ }
+ if (newWatching == 0)
+ return false;
+
+ kdDebug(7001) << (instance ? instance->name() : "all") << " restarted scanning " << e->path
+ << " (now " << wasWatching+newWatching << " watchers)" << endl;
+
+ // restart watching and emit pending events
+
+ int ev = NoChange;
+ if (wasWatching == 0) {
+ if (!notify) {
+ KDE_struct_stat stat_buf;
+ bool exists = (KDE_stat(TQFile::encodeName(e->path), &stat_buf) == 0);
+ if (exists) {
+ e->m_ctime = stat_buf.st_ctime;
+ e->m_status = Normal;
+ e->m_nlink = stat_buf.st_nlink;
+ }
+ else {
+ e->m_ctime = invalid_ctime;
+ e->m_status = NonExistent;
+ e->m_nlink = 0;
+ }
+ }
+ e->msecLeft = 0;
+ ev = scanEntry(e);
+ }
+ emitEvent(e,ev);
+
+ return true;
+}
+
+// instance ==0: stop scanning for all instances
+void KDirWatchPrivate::stopScan(KDirWatch* instance)
+{
+ EntryMap::Iterator it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it )
+ stopEntryScan(instance, &(*it));
+}
+
+
+void KDirWatchPrivate::startScan(KDirWatch* instance,
+ bool notify, bool skippedToo )
+{
+ if (!notify)
+ resetList(instance,skippedToo);
+
+ EntryMap::Iterator it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it )
+ restartEntryScan(instance, &(*it), notify);
+
+ // timer should still be running when in polling mode
+}
+
+
+// clear all pending events, also from stopped
+void KDirWatchPrivate::resetList( KDirWatch* /*instance*/,
+ bool skippedToo )
+{
+ EntryMap::Iterator it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it ) {
+
+ Client* c = (*it).m_clients.first();
+ for(;c;c=(*it).m_clients.next())
+ if (!c->watchingStopped || skippedToo)
+ c->pending = NoChange;
+ }
+}
+
+// Return event happened on <e>
+//
+int KDirWatchPrivate::scanEntry(Entry* e)
+{
+#ifdef HAVE_FAM
+ if (e->m_mode == FAMMode) {
+ // we know nothing has changed, no need to stat
+ if(!e->dirty) return NoChange;
+ e->dirty = false;
+ }
+ if (e->isDir) return Changed;
+#endif
+
+ // Shouldn't happen: Ignore "unknown" notification method
+ if (e->m_mode == UnknownMode) return NoChange;
+
+#if defined ( HAVE_DNOTIFY ) || defined( HAVE_INOTIFY )
+ if (e->m_mode == DNotifyMode || e->m_mode == INotifyMode ) {
+ // we know nothing has changed, no need to stat
+ if(!e->dirty) return NoChange;
+ kdDebug(7001) << "scanning " << e->path << " " << e->m_status << " " << e->m_ctime << endl;
+ e->dirty = false;
+ }
+#endif
+
+ if (e->m_mode == StatMode) {
+ // only scan if timeout on entry timer happens;
+ // e.g. when using 500msec global timer, a entry
+ // with freq=5000 is only watched every 10th time
+
+ e->msecLeft -= freq;
+ if (e->msecLeft>0) return NoChange;
+ e->msecLeft += e->freq;
+ }
+
+ KDE_struct_stat stat_buf;
+ bool exists = (KDE_stat(TQFile::encodeName(e->path), &stat_buf) == 0);
+ if (exists) {
+
+ if (e->m_status == NonExistent) {
+ // ctime is the 'creation time' on windows, but with qMax
+ // we get the latest change of any kind, on any platform.
+ e->m_ctime = stat_buf.st_ctime;
+ e->m_status = Normal;
+ e->m_nlink = stat_buf.st_nlink;
+ return Created;
+ }
+
+ if ( (e->m_ctime != invalid_ctime) &&
+ ((stat_buf.st_ctime != e->m_ctime) ||
+ (stat_buf.st_nlink != (nlink_t) e->m_nlink)) ) {
+ e->m_ctime = stat_buf.st_ctime;
+ e->m_nlink = stat_buf.st_nlink;
+ return Changed;
+ }
+
+ return NoChange;
+ }
+
+ // dir/file doesn't exist
+
+ if (e->m_ctime == invalid_ctime && e->m_status == NonExistent) {
+ e->m_nlink = 0;
+ e->m_status = NonExistent;
+ return NoChange;
+ }
+
+ e->m_ctime = invalid_ctime;
+ e->m_nlink = 0;
+ e->m_status = NonExistent;
+
+ return Deleted;
+}
+
+/* Notify all interested KDirWatch instances about a given event on an entry
+ * and stored pending events. When watching is stopped, the event is
+ * added to the pending events.
+ */
+void KDirWatchPrivate::emitEvent(Entry* e, int event, const TQString &fileName)
+{
+ TQString path = e->path;
+ if (!fileName.isEmpty()) {
+ if (!TQDir::isRelativePath(fileName))
+ path = fileName;
+ else
+#ifdef Q_OS_UNIX
+ path += "/" + fileName;
+#elif defined(Q_WS_WIN)
+ //current drive is passed instead of /
+ path += TQDir::currentDirPath().left(2) + "/" + fileName;
+#endif
+ }
+
+ TQPtrListIterator<Client> cit( e->m_clients );
+ for ( ; cit.current(); ++cit )
+ {
+ Client* c = cit.current();
+
+ if (c->instance==0 || c->count==0) continue;
+
+ if (c->watchingStopped) {
+ // add event to pending...
+ if (event == Changed)
+ c->pending |= event;
+ else if (event == Created || event == Deleted)
+ c->pending = event;
+ continue;
+ }
+ // not stopped
+ if (event == NoChange || event == Changed)
+ event |= c->pending;
+ c->pending = NoChange;
+ if (event == NoChange) continue;
+
+ if (event & Deleted) {
+ c->instance->setDeleted(path);
+ // emit only Deleted event...
+ continue;
+ }
+
+ if (event & Created) {
+ c->instance->setCreated(path);
+ // possible emit Change event after creation
+ }
+
+ if (event & Changed)
+ c->instance->setDirty(path);
+ }
+}
+
+// Remove entries which were marked to be removed
+void KDirWatchPrivate::slotRemoveDelayed()
+{
+ Entry* e;
+ delayRemove = false;
+ for(e=removeList.first();e;e=removeList.next())
+ removeEntry(0, e->path, 0);
+ removeList.clear();
+}
+
+/* Scan all entries to be watched for changes. This is done regularly
+ * when polling and once after a DNOTIFY signal. This is NOT used by FAM.
+ */
+void KDirWatchPrivate::slotRescan()
+{
+ EntryMap::Iterator it;
+
+ // People can do very long things in the slot connected to dirty(),
+ // like showing a message box. We don't want to keep polling during
+ // that time, otherwise the value of 'delayRemove' will be reset.
+ bool timerRunning = timer->isActive();
+ if ( timerRunning )
+ timer->stop();
+
+ // We delay deletions of entries this way.
+ // removeDir(), when called in slotDirty(), can cause a crash otherwise
+ delayRemove = true;
+
+#if defined(HAVE_DNOTIFY) || defined(HAVE_INOTIFY)
+ TQPtrList<Entry> dList, cList;
+#endif
+
+ if (rescan_all)
+ {
+ // mark all as dirty
+ it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it )
+ (*it).dirty = true;
+ rescan_all = false;
+ }
+ else
+ {
+ // progate dirty flag to dependant entries (e.g. file watches)
+ it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it )
+ if (((*it).m_mode == INotifyMode || (*it).m_mode == DNotifyMode) && (*it).dirty )
+ (*it).propagate_dirty();
+ }
+
+ it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it ) {
+ // we don't check invalid entries (i.e. remove delayed)
+ if (!(*it).isValid()) continue;
+
+ int ev = scanEntry( &(*it) );
+
+
+#ifdef HAVE_INOTIFY
+ if ((*it).m_mode == INotifyMode && ev == Created && (*it).wd == 0) {
+ cList.append( &(*it) );
+ if (! useINotify( &(*it) )) {
+ useStat( &(*it) );
+ }
+ }
+#endif
+
+#ifdef HAVE_DNOTIFY
+ if ((*it).m_mode == DNotifyMode) {
+ if ((*it).isDir && (ev == Deleted)) {
+ dList.append( &(*it) );
+
+ // must close the FD.
+ if ((*it).dn_fd) {
+ ::close((*it).dn_fd);
+ fd_Entry.remove((*it).dn_fd);
+ (*it).dn_fd = 0;
+ }
+ }
+
+ else if ((*it).isDir && (ev == Created)) {
+ // For created, but yet without DNOTIFYing ...
+ if ( (*it).dn_fd == 0) {
+ cList.append( &(*it) );
+ if (! useDNotify( &(*it) )) {
+ // if DNotify setup fails...
+ useStat( &(*it) );
+ }
+ }
+ }
+ }
+#endif
+
+ if ( ev != NoChange )
+ emitEvent( &(*it), ev);
+ }
+
+
+#if defined(HAVE_DNOTIFY) || defined(HAVE_INOTIFY)
+ // Scan parent of deleted directories for new creation
+ Entry* e;
+ for(e=dList.first();e;e=dList.next())
+ addEntry(0, TQDir::cleanDirPath( e->path+"/.."), e, true);
+
+ // Remove watch of parent of new created directories
+ for(e=cList.first();e;e=cList.next())
+ removeEntry(0, TQDir::cleanDirPath( e->path+"/.."), e);
+#endif
+
+ if ( timerRunning )
+ timer->start(freq);
+
+ TQTimer::singleShot(0, this, TQT_SLOT(slotRemoveDelayed()));
+}
+
+bool KDirWatchPrivate::isNoisyFile( const char * filename )
+{
+ // $HOME/.X.err grows with debug output, so don't notify change
+ if ( *filename == '.') {
+ if (strncmp(filename, ".X.err", 6) == 0) return true;
+ if (strncmp(filename, ".xsession-errors", 16) == 0) return true;
+ // fontconfig updates the cache on every KDE app start
+ // (inclusive kio_thumbnail slaves)
+ if (strncmp(filename, ".fonts.cache", 12) == 0) return true;
+ }
+
+ return false;
+}
+
+#ifdef HAVE_FAM
+void KDirWatchPrivate::famEventReceived()
+{
+ static FAMEvent fe;
+
+ delayRemove = true;
+
+ while(use_fam && FAMPending(&fc)) {
+ if (FAMNextEvent(&fc, &fe) == -1) {
+ kdWarning(7001) << "FAM connection problem, switching to polling."
+ << endl;
+ use_fam = false;
+ delete sn; sn = 0;
+
+ // Replace all FAMMode entries with DNotify/Stat
+ EntryMap::Iterator it;
+ it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it )
+ if ((*it).m_mode == FAMMode && (*it).m_clients.count()>0) {
+#ifdef HAVE_INOTIFY
+ if (useINotify( &(*it) )) continue;
+#endif
+#ifdef HAVE_DNOTIFY
+ if (useDNotify( &(*it) )) continue;
+#endif
+ useStat( &(*it) );
+ }
+ }
+ else
+ checkFAMEvent(&fe);
+ }
+
+ TQTimer::singleShot(0, this, TQT_SLOT(slotRemoveDelayed()));
+}
+
+void KDirWatchPrivate::checkFAMEvent(FAMEvent* fe)
+{
+ // Don't be too verbose ;-)
+ if ((fe->code == FAMExists) ||
+ (fe->code == FAMEndExist) ||
+ (fe->code == FAMAcknowledge)) return;
+
+ if ( isNoisyFile( fe->filename ) )
+ return;
+
+ Entry* e = 0;
+ EntryMap::Iterator it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it )
+ if (FAMREQUEST_GETREQNUM(&( (*it).fr )) ==
+ FAMREQUEST_GETREQNUM(&(fe->fr)) ) {
+ e = &(*it);
+ break;
+ }
+
+ // Entry* e = static_cast<Entry*>(fe->userdata);
+
+#if 0 // #88538
+ kdDebug(7001) << "Processing FAM event ("
+ << ((fe->code == FAMChanged) ? "FAMChanged" :
+ (fe->code == FAMDeleted) ? "FAMDeleted" :
+ (fe->code == FAMStartExecuting) ? "FAMStartExecuting" :
+ (fe->code == FAMStopExecuting) ? "FAMStopExecuting" :
+ (fe->code == FAMCreated) ? "FAMCreated" :
+ (fe->code == FAMMoved) ? "FAMMoved" :
+ (fe->code == FAMAcknowledge) ? "FAMAcknowledge" :
+ (fe->code == FAMExists) ? "FAMExists" :
+ (fe->code == FAMEndExist) ? "FAMEndExist" : "Unknown Code")
+ << ", " << fe->filename
+ << ", Req " << FAMREQUEST_GETREQNUM(&(fe->fr))
+ << ")" << endl;
+#endif
+
+ if (!e) {
+ // this happens e.g. for FAMAcknowledge after deleting a dir...
+ // kdDebug(7001) << "No entry for FAM event ?!" << endl;
+ return;
+ }
+
+ if (e->m_status == NonExistent) {
+ kdDebug(7001) << "FAM event for nonExistent entry " << e->path << endl;
+ return;
+ }
+
+ // Delayed handling. This rechecks changes with own stat calls.
+ e->dirty = true;
+ if (!rescan_timer.isActive())
+ rescan_timer.start(m_PollInterval, true);
+
+ // needed FAM control actions on FAM events
+ if (e->isDir)
+ switch (fe->code)
+ {
+ case FAMDeleted:
+ // file absolute: watched dir
+ if (!TQDir::isRelativePath(fe->filename))
+ {
+ // a watched directory was deleted
+
+ e->m_status = NonExistent;
+ FAMCancelMonitor(&fc, &(e->fr) ); // needed ?
+ kdDebug(7001) << "Cancelled FAMReq "
+ << FAMREQUEST_GETREQNUM(&(e->fr))
+ << " for " << e->path << endl;
+ // Scan parent for a new creation
+ addEntry(0, TQDir::cleanDirPath( e->path+"/.."), e, true);
+ }
+ break;
+
+ case FAMCreated: {
+ // check for creation of a directory we have to watch
+ Entry *sub_entry = e->m_entries.first();
+ for(;sub_entry; sub_entry = e->m_entries.next())
+ if (sub_entry->path == e->path + "/" + fe->filename) break;
+ if (sub_entry && sub_entry->isDir) {
+ TQString path = e->path;
+ removeEntry(0,e->path,sub_entry); // <e> can be invalid here!!
+ sub_entry->m_status = Normal;
+ if (!useFAM(sub_entry))
+#ifdef HAVE_INOTIFY
+ if (!useINotify(sub_entry ))
+#endif
+ useStat(sub_entry);
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+}
+#else
+void KDirWatchPrivate::famEventReceived() {}
+#endif
+
+
+void KDirWatchPrivate::statistics()
+{
+ EntryMap::Iterator it;
+
+ kdDebug(7001) << "Entries watched:" << endl;
+ if (m_mapEntries.count()==0) {
+ kdDebug(7001) << " None." << endl;
+ }
+ else {
+ it = m_mapEntries.begin();
+ for( ; it != m_mapEntries.end(); ++it ) {
+ Entry* e = &(*it);
+ kdDebug(7001) << " " << e->path << " ("
+ << ((e->m_status==Normal)?"":"Nonexistent ")
+ << (e->isDir ? "Dir":"File") << ", using "
+ << ((e->m_mode == FAMMode) ? "FAM" :
+ (e->m_mode == INotifyMode) ? "INotify" :
+ (e->m_mode == DNotifyMode) ? "DNotify" :
+ (e->m_mode == StatMode) ? "Stat" : "Unknown Method")
+ << ")" << endl;
+
+ Client* c = e->m_clients.first();
+ for(;c; c = e->m_clients.next()) {
+ TQString pending;
+ if (c->watchingStopped) {
+ if (c->pending & Deleted) pending += "deleted ";
+ if (c->pending & Created) pending += "created ";
+ if (c->pending & Changed) pending += "changed ";
+ if (!pending.isEmpty()) pending = " (pending: " + pending + ")";
+ pending = ", stopped" + pending;
+ }
+ kdDebug(7001) << " by " << c->instance->name()
+ << " (" << c->count << " times)"
+ << pending << endl;
+ }
+ if (e->m_entries.count()>0) {
+ kdDebug(7001) << " dependent entries:" << endl;
+ Entry* d = e->m_entries.first();
+ for(;d; d = e->m_entries.next()) {
+ kdDebug(7001) << " " << d << endl;
+ kdDebug(7001) << " " << d->path << " (" << d << ") " << endl;
+ }
+ }
+ }
+ }
+}
+
+
+//
+// Class KDirWatch
+//
+
+static KStaticDeleter<KDirWatch> sd_dw;
+KDirWatch* KDirWatch::s_pSelf = 0L;
+
+KDirWatch* KDirWatch::self()
+{
+ if ( !s_pSelf ) {
+ sd_dw.setObject( s_pSelf, new KDirWatch );
+ }
+
+ return s_pSelf;
+}
+
+bool KDirWatch::exists()
+{
+ return s_pSelf != 0;
+}
+
+KDirWatch::KDirWatch (TQObject* parent, const char* name)
+ : TQObject(parent,name)
+{
+ if (!name) {
+ static int nameCounter = 0;
+
+ nameCounter++;
+ setName(TQString(TQString("KDirWatch-%1").arg(nameCounter)).ascii());
+ }
+
+ if (!dwp_self)
+ dwp_self = new KDirWatchPrivate;
+ d = dwp_self;
+ d->ref();
+
+ _isStopped = false;
+}
+
+KDirWatch::~KDirWatch()
+{
+ d->removeEntries(this);
+ if ( d->deref() )
+ {
+ // delete it if it's the last one
+ delete d;
+ dwp_self = 0L;
+ }
+}
+
+
+// TODO: add watchFiles/recursive support
+void KDirWatch::addDir( const TQString& _path,
+ bool watchFiles, bool recursive)
+{
+ if (watchFiles || recursive) {
+ kdDebug(7001) << "addDir - recursive/watchFiles not supported yet in KDE 3.x" << endl;
+ }
+ if (d) d->addEntry(this, _path, 0, true);
+}
+
+void KDirWatch::addFile( const TQString& _path )
+{
+ if (d) d->addEntry(this, _path, 0, false);
+}
+
+TQDateTime KDirWatch::ctime( const TQString &_path )
+{
+ KDirWatchPrivate::Entry* e = d->entry(_path);
+
+ if (!e)
+ return TQDateTime();
+
+ TQDateTime result;
+ result.setTime_t(e->m_ctime);
+ return result;
+}
+
+void KDirWatch::removeDir( const TQString& _path )
+{
+ if (d) d->removeEntry(this, _path, 0);
+}
+
+void KDirWatch::removeFile( const TQString& _path )
+{
+ if (d) d->removeEntry(this, _path, 0);
+}
+
+bool KDirWatch::stopDirScan( const TQString& _path )
+{
+ if (d) {
+ KDirWatchPrivate::Entry *e = d->entry(_path);
+ if (e && e->isDir) return d->stopEntryScan(this, e);
+ }
+ return false;
+}
+
+bool KDirWatch::restartDirScan( const TQString& _path )
+{
+ if (d) {
+ KDirWatchPrivate::Entry *e = d->entry(_path);
+ if (e && e->isDir)
+ // restart without notifying pending events
+ return d->restartEntryScan(this, e, false);
+ }
+ return false;
+}
+
+void KDirWatch::stopScan()
+{
+ if (d) d->stopScan(this);
+ _isStopped = true;
+}
+
+void KDirWatch::startScan( bool notify, bool skippedToo )
+{
+ _isStopped = false;
+ if (d) d->startScan(this, notify, skippedToo);
+}
+
+
+bool KDirWatch::contains( const TQString& _path ) const
+{
+ KDirWatchPrivate::Entry* e = d->entry(_path);
+ if (!e)
+ return false;
+
+ KDirWatchPrivate::Client* c = e->m_clients.first();
+ for(;c;c=e->m_clients.next())
+ if (c->instance == this) return true;
+
+ return false;
+}
+
+void KDirWatch::statistics()
+{
+ if (!dwp_self) {
+ kdDebug(7001) << "KDirWatch not used" << endl;
+ return;
+ }
+ dwp_self->statistics();
+}
+
+
+void KDirWatch::setCreated( const TQString & _file )
+{
+ kdDebug(7001) << name() << " emitting created " << _file << endl;
+ emit created( _file );
+}
+
+void KDirWatch::setDirty( const TQString & _file )
+{
+ kdDebug(7001) << name() << " emitting dirty " << _file << endl;
+ emit dirty( _file );
+}
+
+void KDirWatch::setDeleted( const TQString & _file )
+{
+ kdDebug(7001) << name() << " emitting deleted " << _file << endl;
+ emit deleted( _file );
+}
+
+KDirWatch::Method KDirWatch::internalMethod()
+{
+#ifdef HAVE_FAM
+ if (d->use_fam)
+ return KDirWatch::FAM;
+#endif
+#ifdef HAVE_INOTIFY
+ if (d->supports_inotify)
+ return KDirWatch::INotify;
+#endif
+#ifdef HAVE_DNOTIFY
+ if (d->supports_dnotify)
+ return KDirWatch::DNotify;
+#endif
+ return KDirWatch::Stat;
+}
+
+
+#include "kdirwatch.moc"
+#include "kdirwatch_p.moc"
+
+//sven
+
+// vim: sw=2 ts=8 et
diff --git a/kio/kio/kdirwatch.h b/tdeio/tdeio/kdirwatch.h
index 4abaa302e..4abaa302e 100644
--- a/kio/kio/kdirwatch.h
+++ b/tdeio/tdeio/kdirwatch.h
diff --git a/kio/kio/kdirwatch_p.h b/tdeio/tdeio/kdirwatch_p.h
index 8777f56b2..8777f56b2 100644
--- a/kio/kio/kdirwatch_p.h
+++ b/tdeio/tdeio/kdirwatch_p.h
diff --git a/tdeio/tdeio/kemailsettings.cpp b/tdeio/tdeio/kemailsettings.cpp
new file mode 100644
index 000000000..296455253
--- /dev/null
+++ b/tdeio/tdeio/kemailsettings.cpp
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) 2000 Alex Zepeda <zipzippy@sonic.net>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $Id$
+ */
+
+#include "kemailsettings.h"
+
+#include <tdeconfig.h>
+#include <klocale.h>
+#include <kdebug.h>
+
+class KEMailSettingsPrivate {
+public:
+ KEMailSettingsPrivate() : m_pConfig( 0 ) {}
+ ~KEMailSettingsPrivate() { delete m_pConfig; }
+ TDEConfig *m_pConfig;
+ TQStringList profiles;
+ TQString m_sDefaultProfile, m_sCurrentProfile;
+};
+
+TQString KEMailSettings::defaultProfileName() const
+{
+ return p->m_sDefaultProfile;
+}
+
+TQString KEMailSettings::getSetting(KEMailSettings::Setting s)
+{
+ p->m_pConfig->setGroup(TQString("PROFILE_")+p->m_sCurrentProfile);
+ switch (s) {
+ case ClientProgram: {
+ return p->m_pConfig->readEntry("EmailClient");
+ break;
+ }
+ case ClientTerminal: {
+ return ((p->m_pConfig->readBoolEntry("TerminalClient")) ? TQString("true") : TQString("false") );
+ break;
+ }
+ case RealName: {
+ return p->m_pConfig->readEntry("FullName");
+ break;
+ }
+ case EmailAddress: {
+ return p->m_pConfig->readEntry("EmailAddress");
+ break;
+ }
+ case ReplyToAddress: {
+ return p->m_pConfig->readEntry("ReplyAddr");
+ break;
+ }
+ case Organization: {
+ return p->m_pConfig->readEntry("Organization");
+ break;
+ }
+ case OutServer: {
+ return p->m_pConfig->readEntry("OutgoingServer");
+ break;
+ }
+ case OutServerLogin: {
+ return p->m_pConfig->readEntry("OutgoingUserName");
+ break;
+ }
+ case OutServerPass: {
+ return p->m_pConfig->readEntry("OutgoingPassword");
+ break;
+ }
+ case OutServerType: {
+ return p->m_pConfig->readEntry("OutgoingServerType");
+ break;
+ }
+ case OutServerCommand: {
+ return p->m_pConfig->readEntry("OutgoingCommand");
+ break;
+ }
+ case OutServerTLS: {
+ return ((p->m_pConfig->readBoolEntry("OutgoingServerTLS")) ? TQString("true") : TQString("false") );
+ break;
+ }
+ case InServer: {
+ return p->m_pConfig->readEntry("IncomingServer");
+ break;
+ }
+ case InServerLogin: {
+ return p->m_pConfig->readEntry("IncomingUserName");
+ break;
+ }
+ case InServerPass: {
+ return p->m_pConfig->readEntry("IncomingPassword");
+ break;
+ }
+ case InServerType: {
+ return p->m_pConfig->readEntry("IncomingServerType");
+ break;
+ }
+ case InServerMBXType: {
+ return p->m_pConfig->readEntry("IncomingServerMBXType");
+ break;
+ }
+ case InServerTLS: {
+ return ((p->m_pConfig->readBoolEntry("IncomingServerTLS")) ? TQString("true") : TQString("false") );
+ break;
+ }
+ };
+ return TQString::null;
+}
+void KEMailSettings::setSetting(KEMailSettings::Setting s, const TQString &v)
+{
+ p->m_pConfig->setGroup(TQString("PROFILE_")+p->m_sCurrentProfile);
+ switch (s) {
+ case ClientProgram: {
+ p->m_pConfig->writePathEntry("EmailClient", v);
+ break;
+ }
+ case ClientTerminal: {
+ p->m_pConfig->writeEntry("TerminalClient", (v == "true") ? true : false );
+ break;
+ }
+ case RealName: {
+ p->m_pConfig->writeEntry("FullName", v);
+ break;
+ }
+ case EmailAddress: {
+ p->m_pConfig->writeEntry("EmailAddress", v);
+ break;
+ }
+ case ReplyToAddress: {
+ p->m_pConfig->writeEntry("ReplyAddr", v);
+ break;
+ }
+ case Organization: {
+ p->m_pConfig->writeEntry("Organization", v);
+ break;
+ }
+ case OutServer: {
+ p->m_pConfig->writeEntry("OutgoingServer", v);
+ break;
+ }
+ case OutServerLogin: {
+ p->m_pConfig->writeEntry("OutgoingUserName", v);
+ break;
+ }
+ case OutServerPass: {
+ p->m_pConfig->writeEntry("OutgoingPassword", v);
+ break;
+ }
+ case OutServerType: {
+ p->m_pConfig->writeEntry("OutgoingServerType", v);
+ break;
+ }
+ case OutServerCommand: {
+ p->m_pConfig->writeEntry("OutgoingCommand", v);
+ break;
+ }
+ case OutServerTLS: {
+ p->m_pConfig->writeEntry("OutgoingServerTLS", (v == "true") ? true : false );
+ break;
+ }
+ case InServer: {
+ p->m_pConfig->writeEntry("IncomingServer", v);
+ break;
+ }
+ case InServerLogin: {
+ p->m_pConfig->writeEntry("IncomingUserName", v);
+ break;
+ }
+ case InServerPass: {
+ p->m_pConfig->writeEntry("IncomingPassword", v);
+ break;
+ }
+ case InServerType: {
+ p->m_pConfig->writeEntry("IncomingServerType", v);
+ break;
+ }
+ case InServerMBXType: {
+ p->m_pConfig->writeEntry("IncomingServerMBXType", v);
+ break;
+ }
+ case InServerTLS: {
+ p->m_pConfig->writeEntry("IncomingServerTLS", (v == "true") ? true : false );
+ break;
+ }
+ };
+ p->m_pConfig->sync();
+}
+
+void KEMailSettings::setDefault(const TQString &s)
+{
+ p->m_pConfig->setGroup("Defaults");
+ p->m_pConfig->writeEntry("Profile", s);
+ p->m_pConfig->sync();
+ p->m_sDefaultProfile=s;
+
+}
+
+void KEMailSettings::setProfile (const TQString &s)
+{
+ TQString groupname="PROFILE_";
+ groupname.append(s);
+ p->m_sCurrentProfile=s;
+ if (!p->m_pConfig->hasGroup(groupname)) { // Create a group if it doesn't exist
+ p->m_pConfig->setGroup(groupname);
+ p->m_pConfig->writeEntry("ServerType", TQString::null);
+ p->m_pConfig->sync();
+ p->profiles+=s;
+ }
+}
+
+TQString KEMailSettings::currentProfileName() const
+{
+ return p->m_sCurrentProfile;
+}
+
+TQStringList KEMailSettings::profiles() const
+{
+ return p->profiles;
+}
+
+KEMailSettings::KEMailSettings()
+{
+ p = new KEMailSettingsPrivate();
+ p->m_sCurrentProfile=TQString::null;
+
+ p->m_pConfig = new TDEConfig("emaildefaults");
+
+ TQStringList groups = p->m_pConfig->groupList();
+ for (TQStringList::Iterator it = groups.begin(); it != groups.end(); ++it) {
+ if ( (*it).left(8) == "PROFILE_" )
+ p->profiles+= (*it).mid(8, (*it).length());
+ }
+
+ p->m_pConfig->setGroup("Defaults");
+ p->m_sDefaultProfile=p->m_pConfig->readEntry("Profile", i18n("Default"));
+ if (!p->m_sDefaultProfile.isNull()) {
+ if (!p->m_pConfig->hasGroup(TQString("PROFILE_")+p->m_sDefaultProfile))
+ setDefault(i18n("Default"));
+ else
+ setDefault(p->m_sDefaultProfile);
+ } else {
+ if (p->profiles.count()) {
+ setDefault(p->profiles[0]);
+ } else
+ setDefault(i18n("Default"));
+ }
+ setProfile(defaultProfileName());
+}
+
+KEMailSettings::~KEMailSettings()
+{
+ delete p;
+}
diff --git a/kio/kio/kemailsettings.h b/tdeio/tdeio/kemailsettings.h
index 0ade4520e..0ade4520e 100644
--- a/kio/kio/kemailsettings.h
+++ b/tdeio/tdeio/kemailsettings.h
diff --git a/kio/kio/kfilterbase.cpp b/tdeio/tdeio/kfilterbase.cpp
index f9250cfe9..f9250cfe9 100644
--- a/kio/kio/kfilterbase.cpp
+++ b/tdeio/tdeio/kfilterbase.cpp
diff --git a/kio/kio/kfilterbase.h b/tdeio/tdeio/kfilterbase.h
index 25613c101..25613c101 100644
--- a/kio/kio/kfilterbase.h
+++ b/tdeio/tdeio/kfilterbase.h
diff --git a/kio/kio/kfilterdev.cpp b/tdeio/tdeio/kfilterdev.cpp
index 87d54f5e3..87d54f5e3 100644
--- a/kio/kio/kfilterdev.cpp
+++ b/tdeio/tdeio/kfilterdev.cpp
diff --git a/kio/kio/kfilterdev.h b/tdeio/tdeio/kfilterdev.h
index 8dd0999a9..8dd0999a9 100644
--- a/kio/kio/kfilterdev.h
+++ b/tdeio/tdeio/kfilterdev.h
diff --git a/kio/kio/kimageio.cpp b/tdeio/tdeio/kimageio.cpp
index e983cb945..e983cb945 100644
--- a/kio/kio/kimageio.cpp
+++ b/tdeio/tdeio/kimageio.cpp
diff --git a/kio/kio/kimageio.h b/tdeio/tdeio/kimageio.h
index 671fb5f61..671fb5f61 100644
--- a/kio/kio/kimageio.h
+++ b/tdeio/tdeio/kimageio.h
diff --git a/kio/kio/kimageiofactory.h b/tdeio/tdeio/kimageiofactory.h
index 6d2d15940..6d2d15940 100644
--- a/kio/kio/kimageiofactory.h
+++ b/tdeio/tdeio/kimageiofactory.h
diff --git a/kio/kio/klimitediodevice.h b/tdeio/tdeio/klimitediodevice.h
index 602ba45a0..602ba45a0 100644
--- a/kio/kio/klimitediodevice.h
+++ b/tdeio/tdeio/klimitediodevice.h
diff --git a/kio/kio/kmdbase.h b/tdeio/tdeio/kmdbase.h
index b0c8f8b7d..b0c8f8b7d 100644
--- a/kio/kio/kmdbase.h
+++ b/tdeio/tdeio/kmdbase.h
diff --git a/kio/kio/kmessageboxwrapper.h b/tdeio/tdeio/kmessageboxwrapper.h
index 3590b5e89..3590b5e89 100644
--- a/kio/kio/kmessageboxwrapper.h
+++ b/tdeio/tdeio/kmessageboxwrapper.h
diff --git a/kio/kio/kmimemagic.cpp b/tdeio/tdeio/kmimemagic.cpp
index f639a7049..f639a7049 100644
--- a/kio/kio/kmimemagic.cpp
+++ b/tdeio/tdeio/kmimemagic.cpp
diff --git a/kio/kio/kmimemagic.h b/tdeio/tdeio/kmimemagic.h
index f5430a219..f5430a219 100644
--- a/kio/kio/kmimemagic.h
+++ b/tdeio/tdeio/kmimemagic.h
diff --git a/tdeio/tdeio/kmimetype.cpp b/tdeio/tdeio/kmimetype.cpp
new file mode 100644
index 000000000..344be793a
--- /dev/null
+++ b/tdeio/tdeio/kmimetype.cpp
@@ -0,0 +1,1172 @@
+/* This file is part of the KDE libraries
+ * Copyright (C) 1999 Waldo Bastian <bastian@kde.org>
+ * David Faure <faure@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+// $Id$
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+#include <kprotocolinfo.h>
+#include <tdeio/global.h>
+#include "kmimetype.h"
+#include "kservicetypefactory.h"
+#include "kmimemagic.h"
+#include "kservice.h"
+#include "krun.h"
+#include "kautomount.h"
+#include <kdirnotify_stub.h>
+
+#include <tqstring.h>
+#include <tqfile.h>
+#include <kmessageboxwrapper.h>
+
+#include <dcopclient.h>
+#include <dcopref.h>
+#include <kapplication.h>
+#include <kprocess.h>
+#include <kdebug.h>
+#include <kdesktopfile.h>
+#include <kdirwatch.h>
+#include <kiconloader.h>
+#include <klocale.h>
+#include <ksimpleconfig.h>
+#include <kstandarddirs.h>
+#include <kurl.h>
+#include <tdesycoca.h>
+#include <kde_file.h>
+
+template class KSharedPtr<KMimeType>;
+template class TQValueList<KMimeType::Ptr>;
+
+KMimeType::Ptr KMimeType::s_pDefaultType = 0L;
+bool KMimeType::s_bChecked = false;
+
+void KMimeType::buildDefaultType()
+{
+ assert ( !s_pDefaultType );
+ // Try to find the default type
+ KServiceType * mime = KServiceTypeFactory::self()->
+ findServiceTypeByName( defaultMimeType() );
+
+ if (mime && mime->isType( KST_KMimeType ))
+ {
+ s_pDefaultType = KMimeType::Ptr((KMimeType *) mime);
+ }
+ else
+ {
+ errorMissingMimeType( defaultMimeType() );
+ KStandardDirs stdDirs;
+ TQString sDefaultMimeType = stdDirs.resourceDirs("mime").first()+defaultMimeType()+".desktop";
+ s_pDefaultType = new KMimeType( sDefaultMimeType, defaultMimeType(),
+ "unknown", "mime", TQStringList() );
+ }
+}
+
+KMimeType::Ptr KMimeType::defaultMimeTypePtr()
+{
+ if ( !s_pDefaultType ) // we need a default type first
+ buildDefaultType();
+ return s_pDefaultType;
+}
+
+// Check for essential mimetypes
+void KMimeType::checkEssentialMimeTypes()
+{
+ if ( s_bChecked ) // already done
+ return;
+ if ( !s_pDefaultType ) // we need a default type first
+ buildDefaultType();
+
+ s_bChecked = true; // must be done before building mimetypes
+
+ // No Mime-Types installed ?
+ // Lets do some rescue here.
+ if ( !KServiceTypeFactory::self()->checkMimeTypes() )
+ {
+ KMessageBoxWrapper::error( 0L, i18n( "No mime types installed." ) );
+ return; // no point in going any further
+ }
+
+ if ( KMimeType::mimeType( "inode/directory" ) == s_pDefaultType )
+ errorMissingMimeType( "inode/directory" );
+ if ( KMimeType::mimeType( "inode/directory-locked" ) == s_pDefaultType )
+ errorMissingMimeType( "inode/directory-locked" );
+ if ( KMimeType::mimeType( "inode/blockdevice" ) == s_pDefaultType )
+ errorMissingMimeType( "inode/blockdevice" );
+ if ( KMimeType::mimeType( "inode/chardevice" ) == s_pDefaultType )
+ errorMissingMimeType( "inode/chardevice" );
+ if ( KMimeType::mimeType( "inode/socket" ) == s_pDefaultType )
+ errorMissingMimeType( "inode/socket" );
+ if ( KMimeType::mimeType( "inode/fifo" ) == s_pDefaultType )
+ errorMissingMimeType( "inode/fifo" );
+ if ( KMimeType::mimeType( "application/x-shellscript" ) == s_pDefaultType )
+ errorMissingMimeType( "application/x-shellscript" );
+ if ( KMimeType::mimeType( "application/x-executable" ) == s_pDefaultType )
+ errorMissingMimeType( "application/x-executable" );
+ if ( KMimeType::mimeType( "application/x-desktop" ) == s_pDefaultType )
+ errorMissingMimeType( "application/x-desktop" );
+}
+
+void KMimeType::errorMissingMimeType( const TQString& _type )
+{
+ TQString tmp = i18n( "Could not find mime type\n%1" ).arg( _type );
+
+ KMessageBoxWrapper::sorry( 0, tmp );
+}
+
+KMimeType::Ptr KMimeType::mimeType( const TQString& _name )
+{
+ KServiceType * mime = KServiceTypeFactory::self()->findServiceTypeByName( _name );
+
+ if ( !mime || !mime->isType( KST_KMimeType ) )
+ {
+ // When building tdesycoca, findServiceTypeByName doesn't create an object
+ // but returns one from a dict.
+ if ( !KSycoca::self()->isBuilding() )
+ delete mime;
+ if ( !s_pDefaultType )
+ buildDefaultType();
+ return s_pDefaultType;
+ }
+
+ // We got a mimetype
+ return KMimeType::Ptr((KMimeType *) mime);
+}
+
+KMimeType::List KMimeType::allMimeTypes()
+{
+ return KServiceTypeFactory::self()->allMimeTypes();
+}
+
+KMimeType::Ptr KMimeType::findByURL( const KURL& _url, mode_t _mode,
+ bool _is_local_file, bool _fast_mode )
+{
+ checkEssentialMimeTypes();
+ TQString path = _url.path();
+
+ if ( !_fast_mode && !_is_local_file && _url.isLocalFile() )
+ _is_local_file = true;
+
+ if ( !_fast_mode && _is_local_file && (_mode == 0 || _mode == (mode_t)-1) )
+ {
+ KDE_struct_stat buff;
+ if ( KDE_stat( TQFile::encodeName(path), &buff ) != -1 )
+ _mode = buff.st_mode;
+ }
+
+ // Look at mode_t first
+ if ( S_ISDIR( _mode ) )
+ {
+ // Special hack for local files. We want to see whether we
+ // are allowed to enter the directory
+ if ( _is_local_file )
+ {
+ if ( access( TQFile::encodeName(path), R_OK ) == -1 )
+ return mimeType( "inode/directory-locked" );
+ }
+ return mimeType( "inode/directory" );
+ }
+ if ( S_ISCHR( _mode ) )
+ return mimeType( "inode/chardevice" );
+ if ( S_ISBLK( _mode ) )
+ return mimeType( "inode/blockdevice" );
+ if ( S_ISFIFO( _mode ) )
+ return mimeType( "inode/fifo" );
+ if ( S_ISSOCK( _mode ) )
+ return mimeType( "inode/socket" );
+ // KMimeMagic can do that better for local files
+ if ( !_is_local_file && S_ISREG( _mode ) && ( _mode & ( S_IXUSR | S_IXGRP | S_IXOTH ) ) )
+ return mimeType( "application/x-executable" );
+
+ TQString fileName ( _url.fileName() );
+
+ static const TQString& slash = TDEGlobal::staticQString("/");
+ if ( ! fileName.isNull() && !path.endsWith( slash ) )
+ {
+ // Try to find it out by looking at the filename
+ KMimeType::Ptr mime = KServiceTypeFactory::self()->findFromPattern( fileName );
+ if ( mime )
+ {
+ // Found something - can we trust it ? (e.g. don't trust *.pl over HTTP, could be anything)
+ if ( _is_local_file || _url.hasSubURL() || // Explicitly trust suburls
+ KProtocolInfo::determineMimetypeFromExtension( _url.protocol() ) )
+ {
+ if ( _is_local_file && !_fast_mode ) {
+ if ( mime->patternsAccuracy()<100 )
+ {
+ KMimeMagicResult* result =
+ KMimeMagic::self()->findFileType( path );
+
+ if ( result && result->isValid() && result->accuracy() > 0 )
+ return mimeType( result->mimeType() );
+ }
+ }
+
+ return mime;
+ }
+ }
+
+ static const TQString& dotdesktop = TDEGlobal::staticQString(".desktop");
+ static const TQString& dotkdelnk = TDEGlobal::staticQString(".kdelnk");
+ static const TQString& dotdirectory = TDEGlobal::staticQString(".directory");
+
+ // Another filename binding, hardcoded, is .desktop:
+ if ( fileName.endsWith( dotdesktop ) )
+ return mimeType( "application/x-desktop" );
+ // Another filename binding, hardcoded, is .kdelnk;
+ // this is preserved for backwards compatibility
+ if ( fileName.endsWith( dotkdelnk ) )
+ return mimeType( "application/x-desktop" );
+ // .directory files are detected as x-desktop by mimemagic
+ // but don't have a Type= entry. Better cheat and say they are text files
+ if ( fileName == dotdirectory )
+ return mimeType( "text/plain" );
+ }
+
+ if ( !_is_local_file || _fast_mode )
+ {
+ TQString def = KProtocolInfo::defaultMimetype( _url );
+ if ( !def.isEmpty() && def != defaultMimeType() )
+ {
+ // The protocol says it always returns a given mimetype (e.g. text/html for "man:")
+ return mimeType( def );
+ }
+ if ( path.endsWith( slash ) || path.isEmpty() )
+ {
+ // We have no filename at all. Maybe the protocol has a setting for
+ // which mimetype this means (e.g. directory).
+ // For HTTP (def==defaultMimeType()) we don't assume anything,
+ // because of redirections (e.g. freshmeat downloads).
+ if ( def.isEmpty() )
+ {
+ // Assume inode/directory, if the protocol supports listing.
+ if ( KProtocolInfo::supportsListing( _url ) )
+ return mimeType( TQString::fromLatin1("inode/directory") );
+ else
+ return defaultMimeTypePtr(); // == 'no idea', e.g. for "data:,foo/"
+ }
+ }
+
+ // No more chances for non local URLs
+ return defaultMimeTypePtr();
+ }
+
+ // Do some magic for local files
+ //kdDebug(7009) << TQString("Mime Type finding for '%1'").arg(path) << endl;
+ KMimeMagicResult* result = KMimeMagic::self()->findFileType( path );
+
+ // If we still did not find it, we must assume the default mime type
+ if ( !result || !result->isValid() )
+ return defaultMimeTypePtr();
+
+ // The mimemagic stuff was successful
+ return mimeType( result->mimeType() );
+}
+
+KMimeType::Ptr KMimeType::findByURL( const KURL& _url, mode_t _mode,
+ bool _is_local_file, bool _fast_mode,
+ bool *accurate)
+{
+ KMimeType::Ptr mime = findByURL(_url, _mode, _is_local_file, _fast_mode);
+ if (accurate) *accurate = !(_fast_mode) || ((mime->patternsAccuracy() == 100) && mime != defaultMimeTypePtr());
+ return mime;
+}
+
+KMimeType::Ptr KMimeType::diagnoseFileName(const TQString &fileName, TQString &pattern)
+{
+ return KServiceTypeFactory::self()->findFromPattern( fileName, &pattern );
+}
+
+KMimeType::Ptr KMimeType::findByPath( const TQString& path, mode_t mode, bool fast_mode )
+{
+ KURL u;
+ u.setPath(path);
+ return findByURL( u, mode, true, fast_mode );
+}
+
+KMimeType::Ptr KMimeType::findByContent( const TQByteArray &data, int *accuracy )
+{
+ KMimeMagicResult *result = KMimeMagic::self()->findBufferType(data);
+ if (accuracy)
+ *accuracy = result->accuracy();
+ return mimeType( result->mimeType() );
+}
+
+KMimeType::Ptr KMimeType::findByFileContent( const TQString &fileName, int *accuracy )
+{
+ KMimeMagicResult *result = KMimeMagic::self()->findFileType(fileName);
+ if (accuracy)
+ *accuracy = result->accuracy();
+ return mimeType( result->mimeType() );
+}
+
+#define GZIP_MAGIC1 0x1f
+#define GZIP_MAGIC2 0x8b
+
+KMimeType::Format KMimeType::findFormatByFileContent( const TQString &fileName )
+{
+ KMimeType::Format result;
+ result.compression = Format::NoCompression;
+ KMimeType::Ptr mime = findByPath(fileName);
+
+ result.text = mime->name().startsWith("text/");
+ TQVariant v = mime->property("X-TDE-text");
+ if (v.isValid())
+ result.text = v.toBool();
+
+ if (mime->name().startsWith("inode/"))
+ return result;
+
+ TQFile f(fileName);
+ if (f.open(IO_ReadOnly))
+ {
+ unsigned char buf[10+1];
+ int l = f.readBlock((char *)buf, 10);
+ if ((l > 2) && (buf[0] == GZIP_MAGIC1) && (buf[1] == GZIP_MAGIC2))
+ result.compression = Format::GZipCompression;
+ }
+ return result;
+}
+
+KMimeType::KMimeType( const TQString & _fullpath, const TQString& _type, const TQString& _icon,
+ const TQString& _comment, const TQStringList& _patterns )
+ : KServiceType( _fullpath, _type, _icon, _comment )
+{
+ m_lstPatterns = _patterns;
+}
+
+KMimeType::KMimeType( const TQString & _fullpath ) : KServiceType( _fullpath )
+{
+ KDesktopFile _cfg( _fullpath, true );
+ init ( &_cfg );
+
+ if ( !isValid() )
+ kdWarning(7009) << "mimetype not valid '" << m_strName << "' (missing entry in the file ?)" << endl;
+}
+
+KMimeType::KMimeType( KDesktopFile *config ) : KServiceType( config )
+{
+ init( config );
+
+ if ( !isValid() )
+ kdWarning(7009) << "mimetype not valid '" << m_strName << "' (missing entry in the file ?)" << endl;
+}
+
+void KMimeType::init( KDesktopFile * config )
+{
+ config->setDesktopGroup();
+ m_lstPatterns = config->readListEntry( "Patterns", ';' );
+
+ // Read the X-TDE-AutoEmbed setting and store it in the properties map
+ TQString XKDEAutoEmbed = TQString::fromLatin1("X-TDE-AutoEmbed");
+ if ( config->hasKey( XKDEAutoEmbed ) )
+ m_mapProps.insert( XKDEAutoEmbed, TQVariant( config->readBoolEntry( XKDEAutoEmbed ), 0 ) );
+
+ TQString XKDEText = TQString::fromLatin1("X-TDE-text");
+ if ( config->hasKey( XKDEText ) )
+ m_mapProps.insert( XKDEText, config->readBoolEntry( XKDEText ) );
+
+ TQString XKDEIsAlso = TQString::fromLatin1("X-TDE-IsAlso");
+ if ( config->hasKey( XKDEIsAlso ) ) {
+ TQString inherits = config->readEntry( XKDEIsAlso );
+ if ( inherits != name() )
+ m_mapProps.insert( XKDEIsAlso, inherits );
+ else
+ kdWarning(7009) << "Error: " << inherits << " inherits from itself!!!!" << endl;
+ }
+
+ TQString XKDEPatternsAccuracy = TQString::fromLatin1("X-TDE-PatternsAccuracy");
+ if ( config->hasKey( XKDEPatternsAccuracy ) )
+ m_mapProps.insert( XKDEPatternsAccuracy, config->readEntry( XKDEPatternsAccuracy ) );
+
+}
+
+KMimeType::KMimeType( TQDataStream& _str, int offset ) : KServiceType( _str, offset )
+{
+ loadInternal( _str ); // load our specific stuff
+}
+
+void KMimeType::load( TQDataStream& _str )
+{
+ KServiceType::load( _str );
+ loadInternal( _str );
+}
+
+void KMimeType::loadInternal( TQDataStream& _str )
+{
+ // kdDebug(7009) << "KMimeType::load( TQDataStream& ) : loading list of patterns" << endl;
+ _str >> m_lstPatterns;
+}
+
+void KMimeType::save( TQDataStream& _str )
+{
+ KServiceType::save( _str );
+ // Warning adding/removing fields here involves a binary incompatible change - update version
+ // number in tdesycoca.h
+ _str << m_lstPatterns;
+}
+
+TQVariant KMimeType::property( const TQString& _name ) const
+{
+ if ( _name == "Patterns" )
+ return TQVariant( m_lstPatterns );
+
+ return KServiceType::property( _name );
+}
+
+TQStringList KMimeType::propertyNames() const
+{
+ TQStringList res = KServiceType::propertyNames();
+ res.append( "Patterns" );
+
+ return res;
+}
+
+KMimeType::~KMimeType()
+{
+}
+
+TQPixmap KMimeType::pixmap( KIcon::Group _group, int _force_size, int _state,
+ TQString * _path ) const
+{
+ KIconLoader *iconLoader=TDEGlobal::iconLoader();
+ TQString iconName=icon( TQString::null, false );
+ if (!iconLoader->extraDesktopThemesAdded())
+ {
+ TQPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
+ if (!pixmap.isNull() ) return pixmap;
+
+ iconLoader->addExtraDesktopThemes();
+ }
+
+ return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
+}
+
+TQPixmap KMimeType::pixmap( const KURL& _url, KIcon::Group _group, int _force_size,
+ int _state, TQString * _path ) const
+{
+ KIconLoader *iconLoader=TDEGlobal::iconLoader();
+ TQString iconName=icon( _url, _url.isLocalFile() );
+ if (!iconLoader->extraDesktopThemesAdded())
+ {
+ TQPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
+ if (!pixmap.isNull() ) return pixmap;
+
+ iconLoader->addExtraDesktopThemes();
+ }
+
+ return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
+}
+
+TQPixmap KMimeType::pixmapForURL( const KURL & _url, mode_t _mode, KIcon::Group _group,
+ int _force_size, int _state, TQString * _path )
+{
+ KIconLoader *iconLoader=TDEGlobal::iconLoader();
+ TQString iconName = iconForURL( _url, _mode );
+
+ if (!iconLoader->extraDesktopThemesAdded())
+ {
+ TQPixmap pixmap=iconLoader->loadIcon( iconName, _group, _force_size, _state, _path, true );
+ if (!pixmap.isNull() ) return pixmap;
+
+ iconLoader->addExtraDesktopThemes();
+ }
+
+ return iconLoader->loadIcon( iconName , _group, _force_size, _state, _path, false );
+
+}
+
+TQString KMimeType::iconForURL( const KURL & _url, mode_t _mode )
+{
+ const KMimeType::Ptr mt = findByURL( _url, _mode, _url.isLocalFile(),
+ false /*HACK*/);
+ static const TQString& unknown = TDEGlobal::staticQString("unknown");
+ const TQString mimeTypeIcon = mt->icon( _url, _url.isLocalFile() );
+ TQString i = mimeTypeIcon;
+
+ // if we don't find an icon, maybe we can use the one for the protocol
+ if ( i == unknown || i.isEmpty() || mt == defaultMimeTypePtr()
+ // and for the root of the protocol (e.g. trash:/) the protocol icon has priority over the mimetype icon
+ || _url.path().length() <= 1 )
+ {
+ i = favIconForURL( _url ); // maybe there is a favicon?
+
+ if ( i.isEmpty() )
+ i = KProtocolInfo::icon( _url.protocol() );
+
+ // root of protocol: if we found nothing, revert to mimeTypeIcon (which is usually "folder")
+ if ( _url.path().length() <= 1 && ( i == unknown || i.isEmpty() ) )
+ i = mimeTypeIcon;
+ }
+ return i;
+}
+
+TQString KMimeType::favIconForURL( const KURL& url )
+{
+ // this method will be called quite often, so better not read the config
+ // again and again.
+ static bool useFavIcons = true;
+ static bool check = true;
+ if ( check ) {
+ check = false;
+ TDEConfig *config = TDEGlobal::config();
+ TDEConfigGroupSaver cs( config, "HTML Settings" );
+ useFavIcons = config->readBoolEntry( "EnableFavicon", true );
+ }
+
+ if ( url.isLocalFile() || !url.protocol().startsWith("http")
+ || !useFavIcons )
+ return TQString::null;
+
+ DCOPRef kded( "kded", "favicons" );
+ DCOPReply result = kded.call( "iconForURL(KURL)", url );
+ if ( result.isValid() )
+ return result;
+
+ return TQString::null;
+}
+
+TQString KMimeType::parentMimeType() const
+{
+ TQVariant v = property("X-TDE-IsAlso");
+ return v.toString();
+}
+
+bool KMimeType::is( const TQString& mimeTypeName ) const
+{
+ if ( name() == mimeTypeName )
+ return true;
+ TQString st = parentMimeType();
+ //if (st.isEmpty()) kdDebug(7009)<<"Parent mimetype is empty"<<endl;
+ while ( !st.isEmpty() )
+ {
+ //kdDebug(7009)<<"Checking parent mime type: "<<st<<endl;
+ KMimeType::Ptr ptr = KMimeType::mimeType( st );
+ if (!ptr) return false; //error
+ if ( ptr->name() == mimeTypeName )
+ return true;
+ st = ptr->parentMimeType();
+ }
+ return false;
+}
+
+int KMimeType::patternsAccuracy() const {
+ TQVariant v = property("X-TDE-PatternsAccuracy");
+ if (!v.isValid()) return 100;
+ else
+ return v.toInt();
+}
+
+
+/*******************************************************
+ *
+ * KFolderType
+ *
+ ******************************************************/
+
+TQString KFolderType::icon( const TQString& _url, bool _is_local ) const
+{
+ if ( !_is_local || _url.isEmpty() )
+ return KMimeType::icon( _url, _is_local );
+
+ return KFolderType::icon( KURL(_url), _is_local );
+}
+
+TQString KFolderType::icon( const KURL& _url, bool _is_local ) const
+{
+ if ( !_is_local )
+ return KMimeType::icon( _url, _is_local );
+
+ KURL u( _url );
+ u.addPath( ".directory" );
+
+ TQString icon;
+ // using KStandardDirs as this one checks for path being
+ // a file instead of a directory
+ if ( KStandardDirs::exists( u.path() ) )
+ {
+ KSimpleConfig cfg( u.path(), true );
+ cfg.setDesktopGroup();
+ icon = cfg.readEntry( "Icon" );
+ TQString empty_icon = cfg.readEntry( "EmptyIcon" );
+
+ if ( !empty_icon.isEmpty() )
+ {
+ bool isempty = false;
+ DIR *dp = 0L;
+ struct dirent *ep;
+ dp = opendir( TQFile::encodeName(_url.path()) );
+ if ( dp )
+ {
+ TQValueList<TQCString> entries;
+ // Note that readdir isn't guaranteed to return "." and ".." first (#79826)
+ ep=readdir( dp ); if ( ep ) entries.append( ep->d_name );
+ ep=readdir( dp ); if ( ep ) entries.append( ep->d_name );
+ if ( (ep=readdir( dp )) == 0L ) // third file is NULL entry -> empty directory
+ isempty = true;
+ else {
+ entries.append( ep->d_name );
+ if ( readdir( dp ) == 0 ) { // only three
+ // check if we got "." ".." and ".directory"
+ isempty = entries.find( "." ) != entries.end() &&
+ entries.find( ".." ) != entries.end() &&
+ entries.find( ".directory" ) != entries.end();
+ }
+ }
+ if (!isempty && !strcmp(ep->d_name, ".directory"))
+ isempty = (readdir(dp) == 0L);
+ closedir( dp );
+ }
+
+ if ( isempty )
+ return empty_icon;
+ }
+ }
+
+ if ( icon.isEmpty() )
+ return KMimeType::icon( _url, _is_local );
+
+ if ( icon.startsWith( "./" ) ) {
+ // path is relative with respect to the location
+ // of the .directory file (#73463)
+ KURL v( _url );
+ v.addPath( icon.mid( 2 ) );
+ icon = v.path();
+ }
+
+ return icon;
+}
+
+TQString KFolderType::comment( const TQString& _url, bool _is_local ) const
+{
+ if ( !_is_local || _url.isEmpty() )
+ return KMimeType::comment( _url, _is_local );
+
+ return KFolderType::comment( KURL(_url), _is_local );
+}
+
+TQString KFolderType::comment( const KURL& _url, bool _is_local ) const
+{
+ if ( !_is_local )
+ return KMimeType::comment( _url, _is_local );
+
+ KURL u( _url );
+ u.addPath( ".directory" );
+
+ KDesktopFile cfg( u.path(), true );
+ TQString comment = cfg.readComment();
+ if ( comment.isEmpty() )
+ return KMimeType::comment( _url, _is_local );
+
+ return comment;
+}
+
+/*******************************************************
+ *
+ * KDEDesktopMimeType
+ *
+ ******************************************************/
+
+TQString KDEDesktopMimeType::icon( const TQString& _url, bool _is_local ) const
+{
+ if ( !_is_local || _url.isEmpty() )
+ return KMimeType::icon( _url, _is_local );
+
+ KURL u( _url );
+ return icon( u, _is_local );
+}
+
+TQString KDEDesktopMimeType::icon( const KURL& _url, bool _is_local ) const
+{
+ if ( !_is_local )
+ return KMimeType::icon( _url, _is_local );
+
+ KSimpleConfig cfg( _url.path(), true );
+ cfg.setDesktopGroup();
+ TQString icon = cfg.readEntry( "Icon" );
+ TQString type = cfg.readEntry( "Type" );
+
+ if ( type == "FSDevice" || type == "FSDev") // need to provide FSDev for
+ // backwards compatibility
+ {
+ TQString unmount_icon = cfg.readEntry( "UnmountIcon" );
+ TQString dev = cfg.readEntry( "Dev" );
+ if ( !icon.isEmpty() && !unmount_icon.isEmpty() && !dev.isEmpty() )
+ {
+ TQString mp = TDEIO::findDeviceMountPoint( dev );
+ // Is the device not mounted ?
+ if ( mp.isNull() )
+ return unmount_icon;
+ }
+ } else if ( type == "Link" ) {
+ const TQString emptyIcon = cfg.readEntry( "EmptyIcon" );
+ if ( !emptyIcon.isEmpty() ) {
+ const TQString u = cfg.readPathEntry( "URL" );
+ const KURL url( u );
+ if ( url.protocol() == "trash" ) {
+ // We need to find if the trash is empty, preferrably without using a KIO job.
+ // So instead kio_trash leaves an entry in its config file for us.
+ KSimpleConfig trashConfig( "trashrc", true );
+ trashConfig.setGroup( "Status" );
+ if ( trashConfig.readBoolEntry( "Empty", true ) ) {
+ return emptyIcon;
+ }
+ }
+ }
+ }
+
+ if ( icon.isEmpty() )
+ return KMimeType::icon( _url, _is_local );
+
+ return icon;
+}
+
+TQPixmap KDEDesktopMimeType::pixmap( const KURL& _url, KIcon::Group _group, int _force_size,
+ int _state, TQString * _path ) const
+{
+ TQString _icon = icon( _url, _url.isLocalFile() );
+ TQPixmap pix = TDEGlobal::iconLoader()->loadIcon( _icon, _group,
+ _force_size, _state, _path, false );
+ if ( pix.isNull() )
+ pix = TDEGlobal::iconLoader()->loadIcon( "unknown", _group,
+ _force_size, _state, _path, false );
+ return pix;
+}
+
+TQString KDEDesktopMimeType::comment( const TQString& _url, bool _is_local ) const
+{
+ if ( !_is_local || _url.isEmpty() )
+ return KMimeType::comment( _url, _is_local );
+
+ KURL u( _url );
+ return comment( u, _is_local );
+}
+
+TQString KDEDesktopMimeType::comment( const KURL& _url, bool _is_local ) const
+{
+ if ( !_is_local )
+ return KMimeType::comment( _url, _is_local );
+
+ KDesktopFile cfg( _url.path(), true );
+ TQString comment = cfg.readComment();
+ if ( comment.isEmpty() )
+ return KMimeType::comment( _url, _is_local );
+
+ return comment;
+}
+
+pid_t KDEDesktopMimeType::run( const KURL& u, bool _is_local )
+{
+ // It might be a security problem to run external untrusted desktop
+ // entry files
+ if ( !_is_local )
+ return 0;
+
+ KSimpleConfig cfg( u.path(), true );
+ cfg.setDesktopGroup();
+ TQString type = cfg.readEntry( "Type" );
+ if ( type.isEmpty() )
+ {
+ TQString tmp = i18n("The desktop entry file %1 "
+ "has no Type=... entry.").arg(u.path() );
+ KMessageBoxWrapper::error( 0, tmp);
+ return 0;
+ }
+
+ //kdDebug(7009) << "TYPE = " << type.data() << endl;
+
+ if ( type == "FSDevice" )
+ return runFSDevice( u, cfg );
+ else if ( type == "Application" )
+ return runApplication( u, u.path() );
+ else if ( type == "Link" )
+ {
+ cfg.setDollarExpansion( true ); // for URL=file:$HOME (Simon)
+ return runLink( u, cfg );
+ }
+ else if ( type == "MimeType" )
+ return runMimeType( u, cfg );
+
+
+ TQString tmp = i18n("The desktop entry of type\n%1\nis unknown.").arg( type );
+ KMessageBoxWrapper::error( 0, tmp);
+
+ return 0;
+}
+
+pid_t KDEDesktopMimeType::runFSDevice( const KURL& _url, const KSimpleConfig &cfg )
+{
+ pid_t retval = 0;
+
+ TQString dev = cfg.readEntry( "Dev" );
+
+ if ( dev.isEmpty() )
+ {
+ TQString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( _url.path() );
+ KMessageBoxWrapper::error( 0, tmp);
+ return retval;
+ }
+
+ TQString mp = TDEIO::findDeviceMountPoint( dev );
+ // Is the device already mounted ?
+ if ( !mp.isNull() )
+ {
+ KURL mpURL;
+ mpURL.setPath( mp );
+ // Open a new window
+ retval = KRun::runURL( mpURL, TQString::fromLatin1("inode/directory") );
+ }
+ else
+ {
+ bool ro = cfg.readBoolEntry( "ReadOnly", false );
+ TQString fstype = cfg.readEntry( "FSType" );
+ if ( fstype == "Default" ) // KDE-1 thing
+ fstype = TQString::null;
+ TQString point = cfg.readEntry( "MountPoint" );
+#ifndef Q_WS_WIN
+ (void) new KAutoMount( ro, fstype, dev, point, _url.path() );
+#endif
+ retval = -1; // we don't want to return 0, but we don't want to return a pid
+ }
+
+ return retval;
+}
+
+pid_t KDEDesktopMimeType::runApplication( const KURL& , const TQString & _serviceFile )
+{
+ KService s( _serviceFile );
+ if ( !s.isValid() )
+ // The error message was already displayed, so we can just quit here
+ return 0;
+
+ KURL::List lst;
+ return KRun::run( s, lst );
+}
+
+pid_t KDEDesktopMimeType::runLink( const KURL& _url, const KSimpleConfig &cfg )
+{
+ TQString u = cfg.readPathEntry( "URL" );
+ if ( u.isEmpty() )
+ {
+ TQString tmp = i18n("The desktop entry file\n%1\nis of type Link but has no URL=... entry.").arg( _url.prettyURL() );
+ KMessageBoxWrapper::error( 0, tmp );
+ return 0;
+ }
+
+ KURL url ( u );
+ KRun* run = new KRun(url);
+
+ // X-TDE-LastOpenedWith holds the service desktop entry name that
+ // was should be preferred for opening this URL if possible.
+ // This is used by the Recent Documents menu for instance.
+ TQString lastOpenedWidth = cfg.readEntry( "X-TDE-LastOpenedWith" );
+ if ( !lastOpenedWidth.isEmpty() )
+ run->setPreferredService( lastOpenedWidth );
+
+ return -1; // we don't want to return 0, but we don't want to return a pid
+}
+
+pid_t KDEDesktopMimeType::runMimeType( const KURL& url , const KSimpleConfig & )
+{
+ // Hmm, can't really use keditfiletype since we might be looking
+ // at the global file, or at a file not in share/mimelnk...
+
+ TQStringList args;
+ args << "openProperties";
+ args << url.path();
+
+ int pid;
+ if ( !TDEApplication::tdeinitExec("kfmclient", args, 0, &pid) )
+ return pid;
+
+ TDEProcess p;
+ p << "kfmclient" << args;
+ p.start(TDEProcess::DontCare);
+ return p.pid();
+}
+
+TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::builtinServices( const KURL& _url )
+{
+ TQValueList<Service> result;
+
+ if ( !_url.isLocalFile() )
+ return result;
+
+ KSimpleConfig cfg( _url.path(), true );
+ cfg.setDesktopGroup();
+ TQString type = cfg.readEntry( "Type" );
+
+ if ( type.isEmpty() )
+ return result;
+
+ if ( type == "FSDevice" )
+ {
+ TQString dev = cfg.readEntry( "Dev" );
+ if ( dev.isEmpty() )
+ {
+ TQString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( _url.path() );
+ KMessageBoxWrapper::error( 0, tmp);
+ }
+ else
+ {
+ TQString mp = TDEIO::findDeviceMountPoint( dev );
+ // not mounted ?
+ if ( mp.isEmpty() )
+ {
+ Service mount;
+ mount.m_strName = i18n("Mount");
+ mount.m_type = ST_MOUNT;
+ result.append( mount );
+ }
+ else
+ {
+ Service unmount;
+#ifdef HAVE_VOLMGT
+ /*
+ * Solaris' volume management can only umount+eject
+ */
+ unmount.m_strName = i18n("Eject");
+#else
+ unmount.m_strName = i18n("Unmount");
+#endif
+ unmount.m_type = ST_UNMOUNT;
+ result.append( unmount );
+ }
+ }
+ }
+
+ return result;
+}
+
+TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const TQString& path, bool bLocalFiles )
+{
+ KSimpleConfig cfg( path, true );
+ return userDefinedServices( path, cfg, bLocalFiles );
+}
+
+TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const TQString& path, TDEConfig& cfg, bool bLocalFiles )
+{
+ return userDefinedServices( path, cfg, bLocalFiles, KURL::List() );
+}
+
+TQValueList<KDEDesktopMimeType::Service> KDEDesktopMimeType::userDefinedServices( const TQString& path, TDEConfig& cfg, bool bLocalFiles, const KURL::List & file_list )
+{
+ TQValueList<Service> result;
+
+ cfg.setDesktopGroup();
+
+ if ( !cfg.hasKey( "Actions" ) && !cfg.hasKey( "X-TDE-GetActionMenu") )
+ return result;
+
+ if ( cfg.hasKey( "TryExec" ) )
+ {
+ TQString tryexec = cfg.readPathEntry( "TryExec" );
+ TQString exe = KStandardDirs::findExe( tryexec );
+ if (exe.isEmpty()) {
+ return result;
+ }
+ }
+
+ TQStringList keys;
+
+ if( cfg.hasKey( "X-TDE-GetActionMenu" )) {
+ TQString dcopcall = cfg.readEntry( "X-TDE-GetActionMenu" );
+ const TQCString app = TQString(dcopcall.section(' ', 0,0)).utf8();
+
+ TQByteArray dataToSend;
+ TQDataStream dataStream(dataToSend, IO_WriteOnly);
+ dataStream << file_list;
+ TQCString replyType;
+ TQByteArray replyData;
+ TQCString object = TQString(dcopcall.section(' ', 1,-2)).utf8();
+ TQString function = dcopcall.section(' ', -1);
+ if(!function.endsWith("(KURL::List)")) {
+ kdWarning() << "Desktop file " << path << " contains an invalid X-TDE-ShowIfDcopCall - the function must take the exact parameter (KURL::List) and must be specified." << endl;
+ } else {
+ if(kapp->dcopClient()->call( app, object,
+ function.utf8(),
+ dataToSend, replyType, replyData, true, -1)
+ && replyType == "TQStringList" ) {
+
+ TQDataStream dataStreamIn(replyData, IO_ReadOnly);
+ dataStreamIn >> keys;
+ }
+ }
+ }
+
+ keys += cfg.readListEntry( "Actions", ';' ); //the desktop standard defines ";" as separator!
+
+ if ( keys.count() == 0 )
+ return result;
+
+ TQStringList::ConstIterator it = keys.begin();
+ TQStringList::ConstIterator end = keys.end();
+ for ( ; it != end; ++it )
+ {
+ //kdDebug(7009) << "CURRENT KEY = " << (*it) << endl;
+
+ TQString group = *it;
+
+ if (group == "_SEPARATOR_")
+ {
+ Service s;
+ result.append(s);
+ continue;
+ }
+
+ group.prepend( "Desktop Action " );
+
+ bool bInvalidMenu = false;
+
+ if ( cfg.hasGroup( group ) )
+ {
+ cfg.setGroup( group );
+
+ if ( !cfg.hasKey( "Name" ) || !cfg.hasKey( "Exec" ) )
+ bInvalidMenu = true;
+ else
+ {
+ TQString exec = cfg.readPathEntry( "Exec" );
+ if ( bLocalFiles || exec.contains("%U") || exec.contains("%u") )
+ {
+ Service s;
+ s.m_strName = cfg.readEntry( "Name" );
+ s.m_strIcon = cfg.readEntry( "Icon" );
+ s.m_strExec = exec;
+ s.m_type = ST_USER_DEFINED;
+ s.m_display = !cfg.readBoolEntry( "NoDisplay" );
+ result.append( s );
+ }
+ }
+ }
+ else
+ bInvalidMenu = true;
+
+ if ( bInvalidMenu )
+ {
+ TQString tmp = i18n("The desktop entry file\n%1\n has an invalid menu entry\n%2.").arg( path ).arg( *it );
+ KMessageBoxWrapper::error( 0, tmp );
+ }
+ }
+
+ return result;
+}
+
+void KDEDesktopMimeType::executeService( const TQString& _url, KDEDesktopMimeType::Service& _service )
+{
+ KURL u;
+ u.setPath(_url);
+ KURL::List lst;
+ lst.append( u );
+ executeService( lst, _service );
+}
+
+void KDEDesktopMimeType::executeService( const KURL::List& urls, KDEDesktopMimeType::Service& _service )
+{
+ //kdDebug(7009) << "EXECUTING Service " << _service.m_strName << endl;
+
+ if ( _service.m_type == ST_USER_DEFINED )
+ {
+ kdDebug() << "KDEDesktopMimeType::executeService " << _service.m_strName
+ << " first url's path=" << urls.first().path() << " exec=" << _service.m_strExec << endl;
+ KRun::run( _service.m_strExec, urls, _service.m_strName, _service.m_strIcon, _service.m_strIcon );
+ // The action may update the desktop file. Example: eject unmounts (#5129).
+ KDirNotify_stub allDirNotify("*", "KDirNotify*");
+ allDirNotify.FilesChanged( urls );
+ return;
+ }
+ else if ( _service.m_type == ST_MOUNT || _service.m_type == ST_UNMOUNT )
+ {
+ Q_ASSERT( urls.count() == 1 );
+ TQString path = urls.first().path();
+ //kdDebug(7009) << "MOUNT&UNMOUNT" << endl;
+
+ KSimpleConfig cfg( path, true );
+ cfg.setDesktopGroup();
+ TQString dev = cfg.readEntry( "Dev" );
+ if ( dev.isEmpty() )
+ {
+ TQString tmp = i18n("The desktop entry file\n%1\nis of type FSDevice but has no Dev=... entry.").arg( path );
+ KMessageBoxWrapper::error( 0, tmp );
+ return;
+ }
+ TQString mp = TDEIO::findDeviceMountPoint( dev );
+
+ if ( _service.m_type == ST_MOUNT )
+ {
+ // Already mounted? Strange, but who knows ...
+ if ( !mp.isEmpty() )
+ {
+ kdDebug(7009) << "ALREADY Mounted" << endl;
+ return;
+ }
+
+ bool ro = cfg.readBoolEntry( "ReadOnly", false );
+ TQString fstype = cfg.readEntry( "FSType" );
+ if ( fstype == "Default" ) // KDE-1 thing
+ fstype = TQString::null;
+ TQString point = cfg.readEntry( "MountPoint" );
+#ifndef Q_WS_WIN
+ (void)new KAutoMount( ro, fstype, dev, point, path, false );
+#endif
+ }
+ else if ( _service.m_type == ST_UNMOUNT )
+ {
+ // Not mounted? Strange, but who knows ...
+ if ( mp.isEmpty() )
+ return;
+
+#ifndef Q_WS_WIN
+ (void)new KAutoUnmount( mp, path );
+#endif
+ }
+ }
+ else
+ assert( 0 );
+}
+
+const TQString & KMimeType::defaultMimeType()
+{
+ static const TQString & s_strDefaultMimeType =
+ TDEGlobal::staticQString( "application/octet-stream" );
+ return s_strDefaultMimeType;
+}
+
+void KMimeType::virtual_hook( int id, void* data )
+{ KServiceType::virtual_hook( id, data ); }
+
+void KFolderType::virtual_hook( int id, void* data )
+{ KMimeType::virtual_hook( id, data ); }
+
+void KDEDesktopMimeType::virtual_hook( int id, void* data )
+{ KMimeType::virtual_hook( id, data ); }
+
+void KExecMimeType::virtual_hook( int id, void* data )
+{ KMimeType::virtual_hook( id, data ); }
+
+#include "kmimetyperesolver.moc"
+
diff --git a/kio/kio/kmimetype.h b/tdeio/tdeio/kmimetype.h
index 19a846b46..19a846b46 100644
--- a/kio/kio/kmimetype.h
+++ b/tdeio/tdeio/kmimetype.h
diff --git a/tdeio/tdeio/kmimetypechooser.cpp b/tdeio/tdeio/kmimetypechooser.cpp
new file mode 100644
index 000000000..51db75fe1
--- /dev/null
+++ b/tdeio/tdeio/kmimetypechooser.cpp
@@ -0,0 +1,298 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001 - 2004 Anders Lund <anders@alweb.dk>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kmimetypechooser.h"
+
+#include <tdeconfig.h>
+#include <kiconloader.h>
+#include <klistview.h>
+#include <klocale.h>
+#include <kmimetype.h>
+#include <kprocess.h>
+#include <krun.h>
+#include <tdesycoca.h>
+
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqlineedit.h>
+#include <tqpushbutton.h>
+#include <tqwhatsthis.h>
+
+//BEGIN KMimeTypeChooserPrivate
+class KMimeTypeChooserPrivate
+{
+ public:
+ KListView *lvMimeTypes;
+ TQPushButton *btnEditMimeType;
+
+ TQString defaultgroup;
+ TQStringList groups;
+ int visuals;
+};
+//END
+
+//BEGIN KMimeTypeChooser
+KMimeTypeChooser::KMimeTypeChooser( const TQString &text,
+ const TQStringList &selMimeTypes,
+ const TQString &defaultGroup,
+ const TQStringList &groupsToShow,
+ int visuals,
+ TQWidget *parent,
+ const char *name )
+ : TQVBox( parent, name )
+{
+ d = new KMimeTypeChooserPrivate();
+ d->lvMimeTypes = 0;
+ d->btnEditMimeType = 0;
+ d->defaultgroup = defaultGroup;
+ d->groups = groupsToShow;
+ d->visuals = visuals;
+
+ setSpacing( KDialogBase::spacingHint() );
+
+ if ( !text.isEmpty() )
+ {
+ new TQLabel( text, this );
+ }
+
+ d->lvMimeTypes = new KListView( this );
+
+ d->lvMimeTypes->addColumn( i18n("Mime Type") );
+// d->lvMimeTypes->setColumnWidthMode( 0, TQListView::Manual );
+
+ if ( visuals & Comments )
+ {
+ d->lvMimeTypes->addColumn( i18n("Comment") );
+ d->lvMimeTypes->setColumnWidthMode( 1, TQListView::Manual );
+ }
+ if ( visuals & Patterns )
+ d->lvMimeTypes->addColumn( i18n("Patterns") );
+
+ d->lvMimeTypes->setRootIsDecorated( true );
+
+ loadMimeTypes( selMimeTypes );
+
+ if (visuals & KMimeTypeChooser::EditButton)
+ {
+ TQHBox *btns = new TQHBox( this );
+ ((TQBoxLayout*)btns->layout())->addStretch(1);
+ d->btnEditMimeType = new TQPushButton( i18n("&Edit..."), btns );
+
+ connect( d->btnEditMimeType, TQT_SIGNAL(clicked()), this, TQT_SLOT(editMimeType()) );
+ d->btnEditMimeType->setEnabled( false );
+ connect( d->lvMimeTypes, TQT_SIGNAL( doubleClicked ( TQListViewItem * )),
+ this, TQT_SLOT( editMimeType()));
+ connect( d->lvMimeTypes, TQT_SIGNAL(currentChanged(TQListViewItem*)),
+ this, TQT_SLOT(slotCurrentChanged(TQListViewItem*)) );
+
+ TQWhatsThis::add( d->btnEditMimeType, i18n(
+ "Click this button to display the familiar TDE mime type editor.") );
+ }
+}
+
+KMimeTypeChooser::~KMimeTypeChooser()
+{
+ delete d;
+}
+
+void KMimeTypeChooser::loadMimeTypes( const TQStringList &_selectedMimeTypes )
+{
+ TQStringList selMimeTypes;
+
+ if ( !_selectedMimeTypes.isEmpty() )
+ selMimeTypes = _selectedMimeTypes;
+ else
+ selMimeTypes = mimeTypes();
+
+ d->lvMimeTypes->clear();
+
+ TQMap<TQString,TQListViewItem*> groups;
+ // thanks to tdebase/kcontrol/filetypes/filetypesview
+ KMimeType::List mimetypes = KMimeType::allMimeTypes();
+ TQValueListIterator<KMimeType::Ptr> it(mimetypes.begin());
+
+ TQListViewItem *groupItem;
+ bool agroupisopen = false;
+ TQListViewItem *idefault = 0; //open this, if all other fails
+ TQListViewItem *firstChecked = 0; // make this one visible after the loop
+
+ for (; it != mimetypes.end(); ++it)
+ {
+ TQString mimetype = (*it)->name();
+ int index = mimetype.find("/");
+ TQString maj = mimetype.left(index);
+
+ if ( d->groups.count() && !d->groups.contains( maj ) )
+ continue;
+
+ TQString min = mimetype.right(mimetype.length() - (index+1));
+
+ TQMapIterator<TQString,TQListViewItem*> mit = groups.find( maj );
+ if ( mit == groups.end() )
+ {
+ groupItem = new TQListViewItem( d->lvMimeTypes, maj );
+ groups.insert( maj, groupItem );
+ if ( maj == d->defaultgroup )
+ idefault = groupItem;
+ }
+ else
+ groupItem = mit.data();
+
+ TQCheckListItem *item = new TQCheckListItem( groupItem, min, TQCheckListItem::CheckBox );
+ item->setPixmap( 0, SmallIcon( (*it)->icon(TQString::null,false) ) );
+
+ int cl = 1;
+
+ if ( d->visuals & Comments )
+ {
+ item->setText( cl, (*it)->comment(TQString::null, false) );
+ cl++;
+ }
+
+ if ( d->visuals & Patterns )
+ item->setText( cl, (*it)->patterns().join("; ") );
+
+ if ( selMimeTypes.contains(mimetype) )
+ {
+ item->setOn( true );
+ groupItem->setOpen( true );
+ agroupisopen = true;
+ if ( !firstChecked )
+ firstChecked = item;
+ }
+ }
+
+ if ( firstChecked )
+ d->lvMimeTypes->ensureItemVisible( firstChecked );
+
+ if ( !agroupisopen && idefault )
+ {
+ idefault->setOpen( true );
+ d->lvMimeTypes->ensureItemVisible( idefault );
+ }
+}
+
+void KMimeTypeChooser::editMimeType()
+{
+ if ( !(d->lvMimeTypes->currentItem() && (d->lvMimeTypes->currentItem())->parent()) )
+ return;
+ TQString mt = (d->lvMimeTypes->currentItem()->parent())->text( 0 ) + "/" + (d->lvMimeTypes->currentItem())->text( 0 );
+ // thanks to libkonq/konq_operations.cc
+ connect( KSycoca::self(), TQT_SIGNAL(databaseChanged()),
+ this, TQT_SLOT(slotSycocaDatabaseChanged()) );
+ TQString keditfiletype = TQString::fromLatin1("keditfiletype");
+ KRun::runCommand( keditfiletype
+ + " --parent " + TQString::number( (ulong)topLevelWidget()->winId())
+ + " " + TDEProcess::quote(mt),
+ keditfiletype, keditfiletype /*unused*/);
+}
+
+void KMimeTypeChooser::slotCurrentChanged(TQListViewItem* i)
+{
+ if ( d->btnEditMimeType )
+ d->btnEditMimeType->setEnabled( i->parent() );
+}
+
+void KMimeTypeChooser::slotSycocaDatabaseChanged()
+{
+ if ( KSycoca::self()->isChanged("mime") )
+ loadMimeTypes();
+}
+
+TQStringList KMimeTypeChooser::mimeTypes() const
+{
+ TQStringList l;
+ TQListViewItemIterator it( d->lvMimeTypes );
+ for (; it.current(); ++it)
+ {
+ if ( it.current()->parent() && ((TQCheckListItem*)it.current())->isOn() )
+ l << it.current()->parent()->text(0) + "/" + it.current()->text(0); // FIXME uncecked, should be Ok unless someone changes mimetypes during this!
+ }
+ return l;
+}
+
+TQStringList KMimeTypeChooser::patterns() const
+{
+ TQStringList l;
+ KMimeType::Ptr p;
+ TQString defMT = KMimeType::defaultMimeType();
+ TQListViewItemIterator it( d->lvMimeTypes );
+ for (; it.current(); ++it)
+ {
+ if ( it.current()->parent() && ((TQCheckListItem*)it.current())->isOn() )
+ {
+ p = KMimeType::mimeType( it.current()->parent()->text(0) + "/" + it.current()->text(0) );
+ if ( p->name() != defMT )
+ l += p->patterns();
+ }
+ }
+ return l;
+}
+//END
+
+//BEGIN KMimeTypeChooserDialog
+KMimeTypeChooserDialog::KMimeTypeChooserDialog(
+ const TQString &caption,
+ const TQString& text,
+ const TQStringList &selMimeTypes,
+ const TQString &defaultGroup,
+ const TQStringList &groupsToShow,
+ int visuals,
+ TQWidget *parent, const char *name )
+ : KDialogBase(parent, name, true, caption, Cancel|Ok, Ok)
+{
+ m_chooser = new KMimeTypeChooser( text, selMimeTypes,
+ defaultGroup, groupsToShow, visuals,
+ this, "chooser" );
+ setMainWidget(m_chooser);
+
+ TDEConfigGroup group( TDEGlobal::config(), "KMimeTypeChooserDialog");
+ TQSize defaultSize( 400, 300 );
+ resize( group.readSizeEntry("size", &defaultSize) );
+}
+
+KMimeTypeChooserDialog::KMimeTypeChooserDialog(
+ const TQString &caption,
+ const TQString& text,
+ const TQStringList &selMimeTypes,
+ const TQString &defaultGroup,
+ TQWidget *parent, const char *name )
+ : KDialogBase(parent, name, true, caption, Cancel|Ok, Ok)
+{
+ m_chooser = new KMimeTypeChooser( text, selMimeTypes,
+ defaultGroup, TQStringList(),
+ KMimeTypeChooser::Comments|KMimeTypeChooser::Patterns|KMimeTypeChooser::EditButton,
+ this, "chooser" );
+ setMainWidget(m_chooser);
+
+ TDEConfigGroup group( TDEGlobal::config(), "KMimeTypeChooserDialog");
+ TQSize defaultSize( 400, 300 );
+ resize( group.readSizeEntry("size", &defaultSize) );
+}
+
+
+KMimeTypeChooserDialog::~KMimeTypeChooserDialog()
+{
+ TDEConfigGroup group( TDEGlobal::config(), "KMimeTypeChooserDialog");
+ group.writeEntry("size", size());
+}
+
+//END KMimeTypeChooserDialog
+
+// kate: space-indent on; indent-width 2; replace-tabs on;
+#include "kmimetypechooser.moc"
diff --git a/kio/kio/kmimetypechooser.h b/tdeio/tdeio/kmimetypechooser.h
index 16ec052f5..16ec052f5 100644
--- a/kio/kio/kmimetypechooser.h
+++ b/tdeio/tdeio/kmimetypechooser.h
diff --git a/kio/kio/kmimetyperesolver.h b/tdeio/tdeio/kmimetyperesolver.h
index c8828a0da..c8828a0da 100644
--- a/kio/kio/kmimetyperesolver.h
+++ b/tdeio/tdeio/kmimetyperesolver.h
diff --git a/tdeio/tdeio/knfsshare.cpp b/tdeio/tdeio/knfsshare.cpp
new file mode 100644
index 000000000..b4a3d903a
--- /dev/null
+++ b/tdeio/tdeio/knfsshare.cpp
@@ -0,0 +1,219 @@
+/* This file is part of the KDE project
+ Copyright (c) 2004 Jan Schaefer <j_schaef@informatik.uni-kl.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqdict.h>
+#include <tqfile.h>
+#include <tqtextstream.h>
+
+#include <kdirwatch.h>
+#include <kstaticdeleter.h>
+#include <kdebug.h>
+#include <tdeconfig.h>
+
+#include "knfsshare.h"
+
+class KNFSSharePrivate
+{
+public:
+ KNFSSharePrivate();
+
+ bool readExportsFile();
+ bool findExportsFile();
+
+ TQDict<bool> sharedPaths;
+ TQString exportsFile;
+};
+
+KNFSSharePrivate::KNFSSharePrivate()
+{
+ if (findExportsFile())
+ readExportsFile();
+}
+
+/**
+ * Try to find the nfs config file path
+ * First tries the tdeconfig, then checks
+ * several well-known paths
+ * @return wether an 'exports' file was found.
+ **/
+bool KNFSSharePrivate::findExportsFile() {
+ TDEConfig config("knfsshare");
+ config.setGroup("General");
+ exportsFile = config.readPathEntry("exportsFile");
+
+ if ( TQFile::exists(exportsFile) )
+ return true;
+
+ if ( TQFile::exists("/etc/exports") )
+ exportsFile = "/etc/exports";
+ else {
+ kdDebug(7000) << "KNFSShare: Could not found exports file!" << endl;
+ return false;
+ }
+
+ config.writeEntry("exportsFile",exportsFile);
+ return true;
+}
+
+/**
+ * Reads all paths from the exports file
+ * and fills the sharedPaths dict with the values
+ */
+bool KNFSSharePrivate::readExportsFile() {
+ TQFile f(exportsFile);
+
+ kdDebug(7000) << "KNFSShare::readExportsFile " << exportsFile << endl;
+
+ if (!f.open(IO_ReadOnly)) {
+ kdError() << "KNFSShare: Could not open " << exportsFile << endl;
+ return false;
+ }
+
+
+ sharedPaths.clear();
+
+ TQTextStream s( &f );
+
+ bool continuedLine = false; // is true if the line before ended with a backslash
+ TQString completeLine;
+
+ while ( !s.eof() )
+ {
+ TQString currentLine = s.readLine().stripWhiteSpace();
+
+ if (continuedLine) {
+ completeLine += currentLine;
+ continuedLine = false;
+ }
+ else
+ completeLine = currentLine;
+
+ // is the line continued in the next line ?
+ if ( completeLine[completeLine.length()-1] == '\\' )
+ {
+ continuedLine = true;
+ // remove the ending backslash
+ completeLine.truncate( completeLine.length()-1 );
+ continue;
+ }
+
+ // comments or empty lines
+ if (completeLine.isEmpty() ||
+ '#' == completeLine[0])
+ {
+ continue;
+ }
+
+ TQString path;
+
+ // Handle quotation marks
+ if ( completeLine[0] == '"' ) {
+ int i = completeLine.find('"',1);
+ if (i == -1) {
+ kdError() << "KNFSShare: Parse error: Missing quotation mark: " << completeLine << endl;
+ continue;
+ }
+ path = completeLine.mid(1,i-1);
+
+ } else { // no quotation marks
+ int i = completeLine.find(' ');
+ if (i == -1)
+ i = completeLine.find('\t');
+
+ if (i == -1)
+ path = completeLine;
+ else
+ path = completeLine.left(i);
+
+ }
+
+ kdDebug(7000) << "KNFSShare: Found path: " << path << endl;
+
+ // normalize path
+ if ( path[path.length()-1] != '/' )
+ path += '/';
+
+ bool b = true;
+ sharedPaths.insert(path,&b);
+ }
+
+ f.close();
+
+ return true;
+
+}
+
+KNFSShare::KNFSShare() {
+ d = new KNFSSharePrivate();
+ if (TQFile::exists(d->exportsFile)) {
+ KDirWatch::self()->addFile(d->exportsFile);
+ connect(KDirWatch::self(), TQT_SIGNAL(dirty (const TQString&)),this,
+ TQT_SLOT(slotFileChange(const TQString&)));
+ }
+}
+
+KNFSShare::~KNFSShare() {
+ if (TQFile::exists(d->exportsFile)) {
+ KDirWatch::self()->removeFile(d->exportsFile);
+ }
+ delete d;
+}
+
+
+bool KNFSShare::isDirectoryShared( const TQString & path ) const {
+ TQString fixedPath = path;
+ if ( path[path.length()-1] != '/' )
+ fixedPath += '/';
+
+ return d->sharedPaths.find(fixedPath) != 0;
+}
+
+TQStringList KNFSShare::sharedDirectories() const {
+ TQStringList result;
+ TQDictIterator<bool> it(d->sharedPaths);
+ for( ; it.current(); ++it )
+ result << it.currentKey();
+
+ return result;
+}
+
+TQString KNFSShare::exportsPath() const {
+ return d->exportsFile;
+}
+
+
+
+void KNFSShare::slotFileChange( const TQString & path ) {
+ if (path == d->exportsFile)
+ d->readExportsFile();
+
+ emit changed();
+}
+
+KNFSShare* KNFSShare::_instance = 0L;
+static KStaticDeleter<KNFSShare> ksdNFSShare;
+
+KNFSShare* KNFSShare::instance() {
+ if (! _instance )
+ _instance = ksdNFSShare.setObject(_instance, new KNFSShare());
+
+ return _instance;
+}
+
+#include "knfsshare.moc"
+
diff --git a/kio/kio/knfsshare.h b/tdeio/tdeio/knfsshare.h
index 64cd28dcf..64cd28dcf 100644
--- a/kio/kio/knfsshare.h
+++ b/tdeio/tdeio/knfsshare.h
diff --git a/kio/kio/kprotocolinfo.cpp b/tdeio/tdeio/kprotocolinfo.cpp
index 9523b70cb..9523b70cb 100644
--- a/kio/kio/kprotocolinfo.cpp
+++ b/tdeio/tdeio/kprotocolinfo.cpp
diff --git a/tdeio/tdeio/kprotocolinfo.h b/tdeio/tdeio/kprotocolinfo.h
new file mode 100644
index 000000000..65ed8c7cb
--- /dev/null
+++ b/tdeio/tdeio/kprotocolinfo.h
@@ -0,0 +1,688 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1999 Torben Weis <weis@kde.org>
+ Copyright (C) 2000-2001 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __kprotocolinfo_h__
+#define __kprotocolinfo_h__
+
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqdatastream.h>
+
+#include <kurl.h>
+#include <tdesycocaentry.h>
+#include <tdesycocatype.h>
+
+/**
+ * Information about I/O (Internet, etc.) protocols supported by KDE.
+
+ * This class is useful if you want to know which protocols
+ * KDE supports. In addition you can find out lots of information
+ * about a certain protocol. A KProtocolInfo instance represents a
+ * single protocol. Most of the functionality is provided by the static
+ * methods that scan the *.protocol files of all installed tdeioslaves to get
+ * this information.
+ *
+ * *.protocol files are installed in the "services" resource.
+ *
+ * @author Torben Weis <weis@kde.org>
+ */
+class TDEIO_EXPORT KProtocolInfo : public KSycocaEntry
+{
+ friend class KProtocolInfoFactory;
+ K_SYCOCATYPE( KST_KProtocolInfo, KSycocaEntry )
+
+public:
+ typedef KSharedPtr<KProtocolInfo> Ptr;
+
+public:
+ /**
+ * Read a protocol description file
+ * @param path the path of the description file
+ */
+ KProtocolInfo( const TQString & path); // KDE4: make private and add friend class KProtocolInfoBuildFactory
+ // Then we can get rid of the d pointer
+
+ /**
+ * Returns whether the protocol description file is valid.
+ * @return true if valid, false otherwise
+ */
+ virtual bool isValid() const { return !m_name.isEmpty(); }
+
+ /**
+ * Returns the name of the protocol.
+ *
+ * This corresponds to the "protocol=" field in the protocol description file.
+ *
+ * @return the name of the protocol
+ * @see KURL::protocol()
+ */
+ virtual TQString name() const { return m_name; }
+
+ //
+ // Static functions:
+ //
+
+ /**
+ * Returns list of all known protocols.
+ * @return a list of all known protocols
+ */
+ static TQStringList protocols();
+
+ /**
+ * Returns whether a protocol is installed that is able to handle @p url.
+ *
+ * @param url the url to check
+ * @return true if the protocol is known
+ * @see name()
+ */
+ static bool isKnownProtocol( const KURL &url );
+
+ /**
+ * Same as above except you can supply just the protocol instead of
+ * the whole URL.
+ */
+ static bool isKnownProtocol( const TQString& protocol )
+#ifdef KPROTOCOLINFO_TDECORE
+ KDE_WEAK_SYMBOL
+#endif
+ ;
+
+ /**
+ * Returns the library / executable to open for the protocol @p protocol
+ * Example : "kio_ftp", meaning either the executable "kio_ftp" or
+ * the library "kio_ftp.la" (recommended), whichever is available.
+ *
+ * This corresponds to the "exec=" field in the protocol description file.
+ * @param protocol the protocol to check
+ * @return the executable of library to open, or TQString::null for
+ * unsupported protocols
+ * @see KURL::protocol()
+ */
+ static TQString exec( const TQString& protocol );
+
+ /**
+ * Describes the type of a protocol.
+ */
+ enum Type { T_STREAM, ///< protocol returns a stream
+ T_FILESYSTEM, ///<protocol describes location in a file system
+ T_NONE, ///< no information about the tyope available
+ T_ERROR ///< used to signal an error
+ };
+
+ /**
+ * Returns whether the protocol should be treated as a filesystem
+ * or as a stream when reading from it.
+ *
+ * This corresponds to the "input=" field in the protocol description file.
+ * Valid values for this field are "filesystem", "stream" or "none" (default).
+ *
+ * @param url the url to check
+ * @return the input type of the given @p url
+ */
+ static Type inputType( const KURL &url );
+
+ /**
+ * Returns whether the protocol should be treated as a filesystem
+ * or as a stream when writing to it.
+ *
+ * This corresponds to the "output=" field in the protocol description file.
+ * Valid values for this field are "filesystem", "stream" or "none" (default).
+ *
+ * @param url the url to check
+ * @return the output type of the given @p url
+ */
+ static Type outputType( const KURL &url );
+
+ /**
+ * Returns the list of fields this protocol returns when listing
+ * The current possibilities are
+ * Name, Type, Size, Date, AccessDate, Access, Owner, Group, Link, URL, MimeType
+ * as well as Extra1, Extra2 etc. for extra fields (see extraFields).
+ *
+ * This corresponds to the "listing=" field in the protocol description file.
+ * The supported fields should be separated with ',' in the protocol description file.
+ *
+ * @param url the url to check
+ * @return a list of field names
+ */
+ static TQStringList listing( const KURL &url );
+
+ /**
+ * Definition of an extra field in the UDS entries, returned by a listDir operation.
+ *
+ * The name is the name of the column, translated.
+ *
+ * The type name comes from TQVariant::typeName()
+ * Currently supported types: "TQString", "TQDateTime" (ISO-8601 format)
+ *
+ * @since 3.2
+ */
+ struct ExtraField {
+ ExtraField() {} // for QValueList
+ ExtraField(const TQString& _name, const TQString& _type )
+ : name(_name), type(_type) {
+ }
+ TQString name;
+ TQString type; // KDE4: make it TQVariant::Type
+ };
+ typedef TQValueList<ExtraField > ExtraFieldList;
+ /**
+ * Definition of extra fields in the UDS entries, returned by a listDir operation.
+ *
+ * This corresponds to the "ExtraNames=" and "ExtraTypes=" fields in the protocol description file.
+ * Those two lists should be separated with ',' in the protocol description file.
+ * See ExtraField for details about names and types
+ *
+ * @since 3.2
+ */
+ static ExtraFieldList extraFields( const KURL& url );
+
+ /**
+ * Returns whether the protocol can act as a source protocol.
+ *
+ * A source protocol retrieves data from or stores data to the
+ * location specified by a URL.
+ * A source protocol is the opposite of a filter protocol.
+ *
+ * The "source=" field in the protocol description file determines
+ * whether a protocol is a source protocol or a filter protocol.
+ * @param url the url to check
+ * @return true if the protocol is a source of data (e.g. http), false if the
+ * protocol is a filter (e.g. gzip)
+ */
+ static bool isSourceProtocol( const KURL &url );
+
+ /**
+ * Returns whether the protocol can act as a helper protocol.
+ * A helper protocol invokes an external application and does not return
+ * a file or stream.
+ *
+ * This corresponds to the "helper=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol is a helper protocol (e.g. vnc), false
+ * if not (e.g. http)
+ */
+ static bool isHelperProtocol( const KURL &url );
+
+ /**
+ * Same as above except you can supply just the protocol instead of
+ * the whole URL.
+ */
+ static bool isHelperProtocol( const TQString& protocol )
+#ifdef KPROTOCOLINFO_TDECORE
+ KDE_WEAK_SYMBOL
+#endif
+ ;
+
+ /**
+ * Returns whether the protocol can act as a filter protocol.
+ *
+ * A filter protocol can operate on data that is passed to it
+ * but does not retrieve/store data itself, like gzip.
+ * A filter protocol is the opposite of a source protocol.
+ *
+ * The "source=" field in the protocol description file determines
+ * whether a protocol is a source protocol or a filter protocol.
+ * Valid values for this field are "true" (default) for source protocol or
+ * "false" for filter protocol.
+ *
+ * @param url the url to check
+ * @return true if the protocol is a filter (e.g. gzip), false if the
+ * protocol is a helper or source
+ */
+ static bool isFilterProtocol( const KURL &url );
+
+ /**
+ * Same as above except you can supply just the protocol instead of
+ * the whole URL.
+ */
+ static bool isFilterProtocol( const TQString& protocol )
+#ifdef KPROTOCOLINFO_TDECORE
+ KDE_WEAK_SYMBOL
+#endif
+ ;
+
+ /**
+ * Returns whether the protocol can list files/objects.
+ * If a protocol supports listing it can be browsed in e.g. file-dialogs
+ * and konqueror.
+ *
+ * Whether a protocol supports listing is determined by the "listing="
+ * field in the protocol description file.
+ * If the protocol support listing it should list the fields it provides in
+ * this field. If the protocol does not support listing this field should
+ * remain empty (default.)
+ *
+ * @param url the url to check
+ * @return true if the protocol support listing
+ * @see listing()
+ */
+ static bool supportsListing( const KURL &url );
+
+ /**
+ * Returns whether the protocol can retrieve data from URLs.
+ *
+ * This corresponds to the "reading=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if it is possible to read from the URL
+ */
+ static bool supportsReading( const KURL &url );
+
+ /**
+ * Returns whether the protocol can store data to URLs.
+ *
+ * This corresponds to the "writing=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol supports writing
+ */
+ static bool supportsWriting( const KURL &url );
+
+ /**
+ * Returns whether the protocol can create directories/folders.
+ *
+ * This corresponds to the "makedir=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol can create directories
+ */
+ static bool supportsMakeDir( const KURL &url );
+
+ /**
+ * Returns whether the protocol can delete files/objects.
+ *
+ * This corresponds to the "deleting=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol supports deleting
+ */
+ static bool supportsDeleting( const KURL &url );
+
+ /**
+ * Returns whether the protocol can create links between files/objects.
+ *
+ * This corresponds to the "linking=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol supports linking
+ */
+ static bool supportsLinking( const KURL &url );
+
+ /**
+ * Returns whether the protocol can move files/objects between different
+ * locations.
+ *
+ * This corresponds to the "moving=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol supports moving
+ */
+ static bool supportsMoving( const KURL &url );
+
+ /**
+ * Returns whether the protocol can copy files/objects directly from the
+ * filesystem itself. If not, the application will read files from the
+ * filesystem using the file-protocol and pass the data on to the destination
+ * protocol.
+ *
+ * This corresponds to the "copyFromFile=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol can copy files from the local file system
+ */
+ static bool canCopyFromFile( const KURL &url );
+
+ /**
+ * Returns whether the protocol can copy files/objects directly to the
+ * filesystem itself. If not, the application will receive the data from
+ * the source protocol and store it in the filesystem using the
+ * file-protocol.
+ *
+ * This corresponds to the "copyToFile=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol can copy files to the local file system
+ */
+ static bool canCopyToFile( const KURL &url );
+
+ /**
+ * Returns whether the protocol can rename (i.e. move fast) files/objects
+ * directly from the filesystem itself. If not, the application will read
+ * files from the filesystem using the file-protocol and pass the data on
+ * to the destination protocol.
+ *
+ * This corresponds to the "renameFromFile=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol can rename/move files from the local file system
+ * @since 3.4
+ */
+ static bool canRenameFromFile( const KURL &url );
+
+ /**
+ * Returns whether the protocol can rename (i.e. move fast) files/objects
+ * directly to the filesystem itself. If not, the application will receive
+ * the data from the source protocol and store it in the filesystem using the
+ * file-protocol.
+ *
+ * This corresponds to the "renameToFile=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol can rename files to the local file system
+ * @since 3.4
+ */
+ static bool canRenameToFile( const KURL &url );
+
+ /**
+ * Returns whether the protocol can recursively delete directories by itself.
+ * If not (the usual case) then KIO will list the directory and delete files
+ * and empty directories one by one.
+ *
+ * This corresponds to the "deleteRecursive=" field in the protocol description file.
+ * Valid values for this field are "true" or "false" (default).
+ *
+ * @param url the url to check
+ * @return true if the protocol can delete non-empty directories by itself.
+ * @since 3.4
+ */
+ static bool canDeleteRecursive( const KURL &url );
+
+ typedef enum { Name, FromURL } FileNameUsedForCopying;
+
+ /**
+ * This setting defines the strategy to use for generating a filename, when
+ * copying a file or directory to another directory. By default the destination
+ * filename is made out of the filename in the source URL. However if the
+ * ioslave displays names that are different from the filename of the URL
+ * (e.g. kio_fonts shows Arial for arial.ttf, or kio_trash shows foo.txt and
+ * uses some internal URL), using Name means that the display name (UDS_NAME)
+ * will be used to as the filename in the destination directory.
+ *
+ * This corresponds to the "fileNameUsedForCopying=" field in the protocol description file.
+ * Valid values for this field are "Name" or "FromURL" (default).
+ *
+ * @param url the url to check
+ * @return how to generate the filename in the destination directory when copying/moving
+ * @since 3.4
+ */
+ static FileNameUsedForCopying fileNameUsedForCopying( const KURL &url );
+
+ /**
+ * Returns default mimetype for this URL based on the protocol.
+ *
+ * This corresponds to the "defaultMimetype=" field in the protocol description file.
+ *
+ * @param url the url to check
+ * @return the default mime type of the protocol, or null if unknown
+ */
+ static TQString defaultMimetype( const KURL& url );
+
+ /**
+ * Returns the name of the icon, associated with the specified protocol.
+ *
+ * This corresponds to the "Icon=" field in the protocol description file.
+ *
+ * @param protocol the protocol to check
+ * @return the icon of the protocol, or null if unknown
+ */
+ static TQString icon( const TQString& protocol );
+
+ /**
+ * Returns the name of the config file associated with the
+ * specified protocol. This is useful if two similar protocols
+ * need to share a single config file, e.g. http and https.
+ *
+ * This corresponds to the "config=" field in the protocol description file.
+ * The default is the protocol name, see name()
+ *
+ * @param protocol the protocol to check
+ * @return the config file, or null if unknown
+ */
+ static TQString config( const TQString& protocol );
+
+ /**
+ * Returns the soft limit on the number of slaves for this protocol.
+ * This limits the number of slaves used for a single operation, note
+ * that multiple operations may result in a number of instances that
+ * exceeds this soft limit.
+ *
+ * This corresponds to the "maxInstances=" field in the protocol description file.
+ * The default is 1.
+ *
+ * @param protocol the protocol to check
+ * @return the maximum number of slaves, or 1 if unknown
+ */
+ static int maxSlaves( const TQString& protocol );
+
+ /**
+ * Returns whether mimetypes can be determined based on extension for this
+ * protocol. For some protocols, e.g. http, the filename extension in the URL
+ * can not be trusted to truly reflect the file type.
+ *
+ * This corresponds to the "determineMimetypeFromExtension=" field in the protocol description file.
+ * Valid values for this field are "true" (default) or "false".
+ *
+ * @param protocol the protocol to check
+ * @return true if the mime types can be determined by extension
+ */
+ static bool determineMimetypeFromExtension( const TQString &protocol );
+
+ /**
+ * Returns the documentation path for the specified protocol.
+ *
+ * This corresponds to the "DocPath=" field in the protocol description file.
+ *
+ * @param protocol the protocol to check
+ * @return the docpath of the protocol, or null if unknown
+ * @since 3.2
+ */
+ static TQString docPath( const TQString& protocol );
+
+ /**
+ * Returns the protocol class for the specified protocol.
+ *
+ * This corresponds to the "Class=" field in the protocol description file.
+ *
+ * The following classes are defined:
+ * @li ":internet" for common internet protocols
+ * @li ":local" for protocols that access local resources
+ *
+ * Protocol classes always start with a ':' so that they can not be confused with
+ * the protocols themselves.
+ *
+ * @param protocol the protocol to check
+ * @return the class of the protocol, or null if unknown
+ * @since 3.2
+ */
+ static TQString protocolClass( const TQString& protocol );
+
+ /**
+ * Returns whether file previews should be shown for the specified protocol.
+ *
+ * This corresponds to the "ShowPreviews=" field in the protocol description file.
+ *
+ * By default previews are shown if protocolClass is :local.
+ *
+ * @param protocol the protocol to check
+ * @return true if previews should be shown by default, false otherwise
+ * @since 3.2
+ */
+ static bool showFilePreview( const TQString& protocol );
+
+ /**
+ * Returns the suggested URI parsing mode for the KURL parser.
+ *
+ * This corresponds to the "URIMode=" field in the protocol description file.
+ *
+ * The following parsing modes are defined:
+ * @li "url" for a standards compliant URL
+ * @li "rawuri" for a non-conformant URI for which URL parsing would be meaningless
+ * @li "mailto" for a mailto style URI (the path part contains only an email address)
+ *
+ * @param protocol the protocol to check
+ * @return the suggested parsing mode, or KURL::Auto if unspecified
+ *
+ * @since 3.2
+ */
+ static KURL::URIMode uriParseMode( const TQString& protocol );
+
+ /**
+ * Returns the list of capabilities provided by the tdeioslave implementing
+ * this protocol.
+ *
+ * This corresponds to the "Capabilities=" field in the protocol description file.
+ *
+ * The capability names are not defined globally, they are up to each
+ * slave implementation. For example when adding support for a new
+ * special command for mounting, one would add the string "Mount" to the
+ * capabilities list, and applications could check for that string
+ * before sending a special() command that would otherwise do nothing
+ * on older tdeioslave implementations.
+ *
+ * @param protocol the protocol to check
+ * @return the list of capabilities.
+ *
+ * @since 3.3
+ */
+ static TQStringList capabilities( const TQString& protocol );
+
+ /**
+ * Returns the name of the protocol through which the request
+ * will be routed if proxy support is enabled.
+ *
+ * A good example of this is the ftp protocol for which proxy
+ * support is commonly handled by the http protocol.
+ *
+ * This corresponds to the "ProxiedBy=" in the protocol description file.
+ *
+ * @since 3.3
+ */
+ static TQString proxiedBy( const TQString& protocol );
+
+public:
+ // Internal functions:
+ /**
+ * @internal construct a KProtocolInfo from a stream
+ */
+ KProtocolInfo( TQDataStream& _str, int offset);
+
+ virtual ~KProtocolInfo();
+
+ /**
+ * @internal
+ * Load the protocol info from a stream.
+ */
+ virtual void load(TQDataStream& );
+
+ /**
+ * @internal
+ * Save the protocol info to a stream.
+ */
+ virtual void save(TQDataStream& );
+
+ ////////////////////////// DEPRECATED /////////////////////////
+ // The following methods are deprecated:
+
+ /// @deprecated
+ static Type inputType( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static Type outputType( const TQString& protocol ) KDE_DEPRECATED;
+ /**
+ * @deprecated
+ * Returns the list of fields this protocol returns when listing
+ * The current possibilities are
+ * Name, Type, Size, Date, AccessDate, Access, Owner, Group, Link, URL, MimeType
+ */
+ static TQStringList listing( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool isSourceProtocol( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool supportsListing( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool supportsReading( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool supportsWriting( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool supportsMakeDir( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool supportsDeleting( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool supportsLinking( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool supportsMoving( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool canCopyFromFile( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static bool canCopyToFile( const TQString& protocol ) KDE_DEPRECATED;
+ /// @deprecated
+ static TQString defaultMimetype( const TQString& protocol) KDE_DEPRECATED;
+ //////////////////////// END DEPRECATED ///////////////////////
+
+protected:
+ TQString m_name;
+ TQString m_exec;
+ Type m_inputType;
+ Type m_outputType;
+ TQStringList m_listing;
+ bool m_isSourceProtocol;
+ bool m_isHelperProtocol;
+ bool m_supportsListing;
+ bool m_supportsReading;
+ bool m_supportsWriting;
+ bool m_supportsMakeDir;
+ bool m_supportsDeleting;
+ bool m_supportsLinking;
+ bool m_supportsMoving;
+ TQString m_defaultMimetype;
+ bool m_determineMimetypeFromExtension;
+ TQString m_icon;
+ bool m_canCopyFromFile;
+ bool m_canCopyToFile;
+ TQString m_config;
+ int m_maxSlaves;
+
+ bool canRenameFromFile() const; // for kprotocolinfo_tdecore
+ bool canRenameToFile() const; // for kprotocolinfo_tdecore
+ bool canDeleteRecursive() const; // for kprotocolinfo_tdecore
+ FileNameUsedForCopying fileNameUsedForCopying() const; // for kprotocolinfo_tdecore
+ static KProtocolInfo* findProtocol(const KURL &url); // for kprotocolinfo_tdecore
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KProtocolInfoPrivate;
+ KProtocolInfoPrivate* d;
+};
+
+TDEIO_EXPORT TQDataStream& operator>>( TQDataStream& s, KProtocolInfo::ExtraField& field );
+TDEIO_EXPORT TQDataStream& operator<<( TQDataStream& s, const KProtocolInfo::ExtraField& field );
+
+#endif
diff --git a/tdeio/tdeio/kprotocolmanager.cpp b/tdeio/tdeio/kprotocolmanager.cpp
new file mode 100644
index 000000000..450b9d107
--- /dev/null
+++ b/tdeio/tdeio/kprotocolmanager.cpp
@@ -0,0 +1,534 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1999 Torben Weis <weis@kde.org>
+ Copyright (C) 2000- Waldo Bastain <bastain@kde.org>
+ Copyright (C) 2000- Dawit Alemayehu <adawit@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <string.h>
+#include <sys/utsname.h>
+
+#include <dcopref.h>
+#include <kdebug.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <tdeconfig.h>
+#include <kstandarddirs.h>
+#include <klibloader.h>
+#include <kstringhandler.h>
+#include <kstaticdeleter.h>
+#include <tdeio/slaveconfig.h>
+#include <tdeio/ioslave_defaults.h>
+#include <tdeio/http_slave_defaults.h>
+
+#include "kprotocolmanager.h"
+
+class
+KProtocolManagerPrivate
+{
+public:
+ KProtocolManagerPrivate();
+
+ ~KProtocolManagerPrivate();
+
+ TDEConfig *config;
+ TDEConfig *http_config;
+ bool init_busy;
+ KURL url;
+ TQString protocol;
+ TQString proxy;
+ TQString modifiers;
+ TQString useragent;
+};
+
+static KProtocolManagerPrivate* d = 0;
+static KStaticDeleter<KProtocolManagerPrivate> kpmpksd;
+
+KProtocolManagerPrivate::KProtocolManagerPrivate()
+ :config(0), http_config(0), init_busy(false)
+{
+ kpmpksd.setObject(d, this);
+}
+
+KProtocolManagerPrivate::~KProtocolManagerPrivate()
+{
+ delete config;
+ delete http_config;
+}
+
+
+// DEFAULT USERAGENT STRING
+#define CFG_DEFAULT_UAGENT(X) \
+TQString("Mozilla/5.0 (compatible; Konqueror/%1.%2%3) KHTML/%4.%5.%6 (like Gecko)") \
+ .arg(TDE_VERSION_MAJOR).arg(TDE_VERSION_MINOR).arg(X).arg(TDE_VERSION_MAJOR).arg(TDE_VERSION_MINOR).arg(TDE_VERSION_RELEASE)
+
+void KProtocolManager::reparseConfiguration()
+{
+ kpmpksd.destructObject();
+
+ // Force the slave config to re-read its config...
+ TDEIO::SlaveConfig::self()->reset ();
+}
+
+TDEConfig *KProtocolManager::config()
+{
+ if (!d)
+ d = new KProtocolManagerPrivate;
+
+ if (!d->config)
+ {
+ d->config = new TDEConfig("tdeioslaverc", true, false);
+ }
+ return d->config;
+}
+
+TDEConfig *KProtocolManager::http_config()
+{
+ if (!d)
+ d = new KProtocolManagerPrivate;
+
+ if (!d->http_config)
+ {
+ d->http_config = new TDEConfig("kio_httprc", false, false);
+ }
+ return d->http_config;
+}
+
+/*=============================== TIMEOUT SETTINGS ==========================*/
+
+int KProtocolManager::readTimeout()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ int val = cfg->readNumEntry( "ReadTimeout", DEFAULT_READ_TIMEOUT );
+ return QMAX(MIN_TIMEOUT_VALUE, val);
+}
+
+int KProtocolManager::connectTimeout()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ int val = cfg->readNumEntry( "ConnectTimeout", DEFAULT_CONNECT_TIMEOUT );
+ return QMAX(MIN_TIMEOUT_VALUE, val);
+}
+
+int KProtocolManager::proxyConnectTimeout()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ int val = cfg->readNumEntry( "ProxyConnectTimeout", DEFAULT_PROXY_CONNECT_TIMEOUT );
+ return QMAX(MIN_TIMEOUT_VALUE, val);
+}
+
+int KProtocolManager::responseTimeout()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ int val = cfg->readNumEntry( "ResponseTimeout", DEFAULT_RESPONSE_TIMEOUT );
+ return QMAX(MIN_TIMEOUT_VALUE, val);
+}
+
+/*========================== PROXY SETTINGS =================================*/
+
+bool KProtocolManager::useProxy()
+{
+ return proxyType() != NoProxy;
+}
+
+bool KProtocolManager::useReverseProxy()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( "Proxy Settings" );
+ return cfg->readBoolEntry("ReversedException", false);
+}
+
+KProtocolManager::ProxyType KProtocolManager::proxyType()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( "Proxy Settings" );
+ return static_cast<ProxyType>(cfg->readNumEntry( "ProxyType" ));
+}
+
+KProtocolManager::ProxyAuthMode KProtocolManager::proxyAuthMode()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( "Proxy Settings" );
+ return static_cast<ProxyAuthMode>(cfg->readNumEntry( "AuthMode" ));
+}
+
+/*========================== CACHING =====================================*/
+
+bool KProtocolManager::useCache()
+{
+ TDEConfig *cfg = http_config();
+ return cfg->readBoolEntry( "UseCache", true );
+}
+
+TDEIO::CacheControl KProtocolManager::cacheControl()
+{
+ TDEConfig *cfg = http_config();
+ TQString tmp = cfg->readEntry("cache");
+ if (tmp.isEmpty())
+ return DEFAULT_CACHE_CONTROL;
+ return TDEIO::parseCacheControl(tmp);
+}
+
+TQString KProtocolManager::cacheDir()
+{
+ TDEConfig *cfg = http_config();
+ return cfg->readPathEntry("CacheDir", TDEGlobal::dirs()->saveLocation("cache","http"));
+}
+
+int KProtocolManager::maxCacheAge()
+{
+ TDEConfig *cfg = http_config();
+ return cfg->readNumEntry( "MaxCacheAge", DEFAULT_MAX_CACHE_AGE ); // 14 days
+}
+
+int KProtocolManager::maxCacheSize()
+{
+ TDEConfig *cfg = http_config();
+ return cfg->readNumEntry( "MaxCacheSize", DEFAULT_MAX_CACHE_SIZE ); // 5 MB
+}
+
+TQString KProtocolManager::noProxyForRaw()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( "Proxy Settings" );
+
+ return cfg->readEntry( "NoProxyFor" );
+}
+
+TQString KProtocolManager::noProxyFor()
+{
+ TQString noProxy = noProxyForRaw();
+ if (proxyType() == EnvVarProxy)
+ noProxy = TQString::fromLocal8Bit(getenv(noProxy.local8Bit()));
+
+ return noProxy;
+}
+
+TQString KProtocolManager::proxyFor( const TQString& protocol )
+{
+ TQString scheme = protocol.lower();
+
+ if (scheme == "webdav")
+ scheme = "http";
+ else if (scheme == "webdavs")
+ scheme = "https";
+
+ TDEConfig *cfg = config();
+ cfg->setGroup( "Proxy Settings" );
+ return cfg->readEntry( scheme + "Proxy" );
+}
+
+TQString KProtocolManager::proxyForURL( const KURL &url )
+{
+ TQString proxy;
+ ProxyType pt = proxyType();
+
+ switch (pt)
+ {
+ case PACProxy:
+ case WPADProxy:
+ if (!url.host().isEmpty())
+ {
+ KURL u (url);
+ TQString p = u.protocol().lower();
+
+ // webdav is a KDE specific protocol. Look up proxy
+ // information using HTTP instead...
+ if ( p == "webdav" )
+ {
+ p = "http";
+ u.setProtocol( p );
+ }
+ else if ( p == "webdavs" )
+ {
+ p = "https";
+ u.setProtocol( p );
+ }
+
+ if ( p.startsWith("http") || p == "ftp" || p == "gopher" )
+ DCOPRef( "kded", "proxyscout" ).call( "proxyForURL", u ).get( proxy );
+ }
+ break;
+ case EnvVarProxy:
+ proxy = TQString(TQString::fromLocal8Bit(getenv(proxyFor(url.protocol()).local8Bit()))).stripWhiteSpace();
+ break;
+ case ManualProxy:
+ proxy = proxyFor( url.protocol() );
+ break;
+ case NoProxy:
+ default:
+ break;
+ }
+
+ return (proxy.isEmpty() ? TQString::fromLatin1("DIRECT") : proxy);
+}
+
+void KProtocolManager::badProxy( const TQString &proxy )
+{
+ DCOPRef( "kded", "proxyscout" ).send( "blackListProxy", proxy );
+}
+
+/*
+ Domain suffix match. E.g. return true if host is "cuzco.inka.de" and
+ nplist is "inka.de,hadiko.de" or if host is "localhost" and nplist is
+ "localhost".
+*/
+static bool revmatch(const char *host, const char *nplist)
+{
+ if (host == 0)
+ return false;
+
+ const char *hptr = host + strlen( host ) - 1;
+ const char *nptr = nplist + strlen( nplist ) - 1;
+ const char *shptr = hptr;
+
+ while ( nptr >= nplist )
+ {
+ if ( *hptr != *nptr )
+ {
+ hptr = shptr;
+
+ // Try to find another domain or host in the list
+ while(--nptr>=nplist && *nptr!=',' && *nptr!=' ') ;
+
+ // Strip out multiple spaces and commas
+ while(--nptr>=nplist && (*nptr==',' || *nptr==' ')) ;
+ }
+ else
+ {
+ if ( nptr==nplist || nptr[-1]==',' || nptr[-1]==' ')
+ return true;
+ if ( hptr == host ) // e.g. revmatch("bugs.kde.org","mybugs.kde.org")
+ return false;
+
+ hptr--;
+ nptr--;
+ }
+ }
+
+ return false;
+}
+
+TQString KProtocolManager::slaveProtocol(const KURL &url, TQString &proxy)
+{
+ if (url.hasSubURL()) // We don't want the suburl's protocol
+ {
+ KURL::List list = KURL::split(url);
+ KURL::List::Iterator it = list.fromLast();
+ return slaveProtocol(*it, proxy);
+ }
+
+ if (!d)
+ d = new KProtocolManagerPrivate;
+
+ if (d->url == url)
+ {
+ proxy = d->proxy;
+ return d->protocol;
+ }
+
+ if (useProxy())
+ {
+ proxy = proxyForURL(url);
+ if ((proxy != "DIRECT") && (!proxy.isEmpty()))
+ {
+ bool isRevMatch = false;
+ KProtocolManager::ProxyType type = proxyType();
+ bool useRevProxy = ((type == ManualProxy) && useReverseProxy());
+
+ TQString noProxy;
+ // Check no proxy information iff the proxy type is either
+ // ManualProxy or EnvVarProxy
+ if ( (type == ManualProxy) || (type == EnvVarProxy) )
+ noProxy = noProxyFor();
+
+ if (!noProxy.isEmpty())
+ {
+ TQString qhost = url.host().lower();
+ const char *host = qhost.latin1();
+ TQString qno_proxy = noProxy.stripWhiteSpace().lower();
+ const char *no_proxy = qno_proxy.latin1();
+ isRevMatch = revmatch(host, no_proxy);
+
+ // If no match is found and the request url has a port
+ // number, try the combination of "host:port". This allows
+ // users to enter host:port in the No-proxy-For list.
+ if (!isRevMatch && url.port() > 0)
+ {
+ qhost += ':' + TQString::number (url.port());
+ host = qhost.latin1();
+ isRevMatch = revmatch (host, no_proxy);
+ }
+
+ // If the hostname does not contain a dot, check if
+ // <local> is part of noProxy.
+ if (!isRevMatch && host && (strchr(host, '.') == NULL))
+ isRevMatch = revmatch("<local>", no_proxy);
+ }
+
+ if ( (!useRevProxy && !isRevMatch) || (useRevProxy && isRevMatch) )
+ {
+ d->url = proxy;
+ if ( d->url.isValid() )
+ {
+ // The idea behind slave protocols is not applicable to http
+ // and webdav protocols.
+ TQString protocol = url.protocol().lower();
+ if (protocol.startsWith("http") || protocol.startsWith("webdav"))
+ d->protocol = protocol;
+ else
+ {
+ d->protocol = d->url.protocol();
+ kdDebug () << "slaveProtocol: " << d->protocol << endl;
+ }
+
+ d->url = url;
+ d->proxy = proxy;
+ return d->protocol;
+ }
+ }
+ }
+ }
+
+ d->url = url;
+ d->proxy = proxy = TQString::null;
+ d->protocol = url.protocol();
+ return d->protocol;
+}
+
+/*================================= USER-AGENT SETTINGS =====================*/
+
+TQString KProtocolManager::userAgentForHost( const TQString& hostname )
+{
+ TQString sendUserAgent = TDEIO::SlaveConfig::self()->configData("http", hostname.lower(), "SendUserAgent").lower();
+ if (sendUserAgent == "false")
+ return TQString::null;
+
+ TQString useragent = TDEIO::SlaveConfig::self()->configData("http", hostname.lower(), "UserAgent");
+
+ // Return the default user-agent if none is specified
+ // for the requested host.
+ if (useragent.isEmpty())
+ return defaultUserAgent();
+
+ return useragent;
+}
+
+TQString KProtocolManager::defaultUserAgent( )
+{
+ TQString modifiers = TDEIO::SlaveConfig::self()->configData("http", TQString::null, "UserAgentKeys");
+ return defaultUserAgent(modifiers);
+}
+
+TQString KProtocolManager::defaultUserAgent( const TQString &_modifiers )
+{
+ if (!d)
+ d = new KProtocolManagerPrivate;
+
+ TQString modifiers = _modifiers.lower();
+ if (modifiers.isEmpty())
+ modifiers = DEFAULT_USER_AGENT_KEYS;
+
+ if (d->modifiers == modifiers)
+ return d->useragent;
+
+ TQString supp;
+ struct utsname nam;
+ if( uname(&nam) >= 0 )
+ {
+ if( modifiers.contains('o') )
+ {
+ supp += TQString("; %1").arg(nam.sysname);
+ if ( modifiers.contains('v') )
+ supp += TQString(" %1").arg(nam.release);
+ }
+ if( modifiers.contains('p') )
+ {
+ // TODO: determine this value instead of hardcoding it...
+ supp += TQString::fromLatin1("; X11");
+ }
+ if( modifiers.contains('m') )
+ {
+ supp += TQString("; %1").arg(nam.machine);
+ }
+ if( modifiers.contains('l') )
+ {
+ TQStringList languageList = TDEGlobal::locale()->languageList();
+ TQStringList::Iterator it = languageList.find( TQString::fromLatin1("C") );
+ if( it != languageList.end() )
+ {
+ if( languageList.contains( TQString::fromLatin1("en") ) > 0 )
+ languageList.remove( it );
+ else
+ (*it) = TQString::fromLatin1("en");
+ }
+ if( languageList.count() )
+ supp += TQString("; %1").arg(languageList.join(", "));
+ }
+ }
+ d->modifiers = modifiers;
+ d->useragent = CFG_DEFAULT_UAGENT(supp);
+ return d->useragent;
+}
+
+/*==================================== OTHERS ===============================*/
+
+bool KProtocolManager::markPartial()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ return cfg->readBoolEntry( "MarkPartial", true );
+}
+
+int KProtocolManager::minimumKeepSize()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ return cfg->readNumEntry( "MinimumKeepSize",
+ DEFAULT_MINIMUM_KEEP_SIZE ); // 5000 byte
+}
+
+bool KProtocolManager::autoResume()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ return cfg->readBoolEntry( "AutoResume", false );
+}
+
+bool KProtocolManager::persistentConnections()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ return cfg->readBoolEntry( "PersistentConnections", true );
+}
+
+bool KProtocolManager::persistentProxyConnection()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( TQString::null );
+ return cfg->readBoolEntry( "PersistentProxyConnection", false );
+}
+
+TQString KProtocolManager::proxyConfigScript()
+{
+ TDEConfig *cfg = config();
+ cfg->setGroup( "Proxy Settings" );
+ return cfg->readEntry( "Proxy Config Script" );
+}
diff --git a/tdeio/tdeio/kprotocolmanager.h b/tdeio/tdeio/kprotocolmanager.h
new file mode 100644
index 000000000..ce504a83f
--- /dev/null
+++ b/tdeio/tdeio/kprotocolmanager.h
@@ -0,0 +1,389 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 1999 Torben Weis <weis@kde.org>
+ Copyright (C) 2000- Waldo Bastain <bastain@kde.org>
+ Copyright (C) 2000- Dawit Alemayehu <adawit@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __kprotocolmanager_h__
+#define __kprotocolmanager_h__
+
+#include <tqstringlist.h>
+
+#include <kapplication.h>
+#include <tdeio/global.h>
+
+/** @deprecated Use KProtocolManager::defaultUserAgent() instead. */
+#define DEFAULT_USERAGENT_STRING ""
+
+class TDEConfig;
+
+/**
+ * Provides information about I/O (Internet, etc.) settings chosen/set
+ * by the end user.
+ *
+ * KProtocolManager has a heap of static functions that allows only read
+ * access to KDE's IO related settings. These include proxy, cache, file
+ * transfer resumption, timeout and user-agent related settings.
+ *
+ * The information provided by this class is generic enough to be applicable
+ * to any application that makes use of KDE's IO sub-system. Note that this
+ * mean the proxy, timeout etc. settings are saved in a separate user-specific
+ * config file and not in the config file of the application.
+ *
+ * Original author:
+ * @author Torben Weis <weis@kde.org>
+ *
+ * Revised by:
+ * @author Waldo Bastain <bastain@kde.org>
+ * @author Dawit Alemayehu <adawit@kde.org>
+ * @see KPAC
+ */
+class TDEIO_EXPORT KProtocolManager
+{
+public:
+
+
+/*=========================== USER-AGENT SETTINGS ===========================*/
+
+
+ /**
+ * Returns the default user-agent string.
+ *
+ * @return the default user-agent string
+ */
+ static TQString defaultUserAgent();
+
+ /**
+ * Returns the default user-agent value.
+ *
+ * @param keys can be any of the following:
+ * @li 'o' Show OS
+ * @li 'v' Show OS Version
+ * @li 'p' Show platform
+ * @li 'm' Show machine architecture
+ * @li 'l' Show language
+ * @return the default user-agent value with the given @p keys
+ */
+ static TQString defaultUserAgent(const TQString &keys);
+
+ /**
+ * Returns the userAgent string configured for the
+ * specified host.
+ *
+ * If hostname is not found or is empty (i.e. "" or
+ * TQString::null) this function will return the default
+ * user agent.
+ *
+ * @param hostname name of the host
+ * @return specified userAgent string
+ */
+ static TQString userAgentForHost( const TQString &hostname );
+
+
+/*=========================== TIMEOUT CONFIG ================================*/
+
+
+ /**
+ * Returns the preferred timeout value for reading from
+ * remote connections in seconds.
+ *
+ * @return timeout value for remote connection in secs.
+ */
+ static int readTimeout();
+
+ /**
+ * Returns the preferred timeout value for remote connections
+ * in seconds.
+ *
+ * @return timeout value for remote connection in secs.
+ */
+ static int connectTimeout();
+
+ /**
+ * Returns the preferred timeout value for proxy connections
+ * in seconds.
+ *
+ * @return timeout value for proxy connection in secs.
+ */
+ static int proxyConnectTimeout();
+
+ /**
+ * Returns the preferred response timeout value for
+ * remote connecting in seconds.
+ *
+ * @return timeout value for remote connection in seconds.
+ */
+ static int responseTimeout();
+
+
+/*=============================== PROXY CONFIG ==============================*/
+
+
+ /**
+ * Returns true if the user specified a proxy server to make connections.
+ *
+ * @see slaveProtocol, proxyForURL, proxyFor
+ */
+ static bool useProxy();
+
+ /**
+ * Returns true if the proxy settings should apply to the list
+ * returned by @ref noProxyFor.
+ *
+ * Normally addresses listed in the noProxyFor list are not routed
+ * through a proxy server. However, if this function returns true,
+ * then all addresses listed in the noProxyFor list are to be routed
+ * through a proxy server where as those that are not should bypass it.
+ *
+ * This function as well as @ref noProxyFor only apply when @ref proxyType
+ * is @p ManualProxy.
+ *
+ * @see proxyForURL, proxyFor, slaveProtocol
+ */
+ static bool useReverseProxy();
+
+ /**
+ * Types of proxy configuration
+ * @li NoProxy - No proxy is used
+ * @li ManualProxy - Proxies are manually configured
+ * @li PACProxy - A Proxy configuration URL has been given
+ * @li WPADProxy - A proxy should be automatically discovered
+ * @li EnvVarProxy - Use the proxy values set through environment variables.
+ */
+ enum ProxyType
+ {
+ NoProxy,
+ ManualProxy,
+ PACProxy,
+ WPADProxy,
+ EnvVarProxy
+ };
+
+ /**
+ * Returns the type of proxy configuration that is used.
+ *
+ * @see ProxyType
+ */
+ static ProxyType proxyType();
+
+ /**
+ * Proxy authorization modes.
+ *
+ * @li Prompt - Ask for authorization as needed
+ * @li Automatic - Use auto login as defined in .kionetrc files.
+ *
+ * NOTE: .kionetrc files have the same format as ftp .netrc files.
+ * Please note the use of .kionetrc files is highly discouraged since
+ * password is stored in clear text. For future releases the ability
+ * to store preset password for proxy servers will probably be supported
+ * through KWallet integration.
+ */
+ enum ProxyAuthMode
+ {
+ Prompt,
+ Automatic
+ };
+
+ /**
+ * Returns the way proxy authorization should be handled.
+ *
+ * @see ProxyAuthMode
+ */
+ static ProxyAuthMode proxyAuthMode();
+
+ /**
+ * Returns a comma-separated list of hostnames or partial
+ * host-names that should bypass any proxy settings.
+ *
+ * This function as well as @ref useReverseProxy only apply
+ * when @ref proxyType is @p ManualProxy.
+ *
+ * @see useReverseProxy, proxyFor, proxyForURL, slaveProtocol
+ */
+ static TQString noProxyFor();
+
+ /**
+ * Same as above except the environment variable name
+ * is returned instead of the variable value when
+ * @ref proxyType is @p EnvVarProxy.
+ *
+ * @see noProxyFor
+ * @since 3.5.x
+ */
+ static TQString noProxyForRaw();
+
+ /**
+ * Returns the proxy server address for a given protocol.
+ *
+ * NOTE: This function does not take the @ref useReverseProxy()
+ * settings into account.
+ *
+ * @see useReverseProxy, slaveProtocol
+ * @param protocol the protocol whose proxy info is needed
+ * @returns the proxy server address if one is available,
+ * or TQString::null if not available
+ */
+ static TQString proxyFor( const TQString& protocol );
+
+ /**
+ * Returns the proxy server address for a given URL.
+ *
+ * If @ref proxyType returns Automatic, an external service
+ * called KPAC (a kded module) is used to determine the proxy
+ * server. Otherwise, @ref proxyFor is invoked to determine
+ * whether the URL needs to be routed through a proxy server.
+ *
+ * NOTE: This function does not take the @ref useReverseProxy()
+ * or the @ref noProxyFor() settings into account.
+ *
+ * @see useReverseProxy, slaveProtocol, noProxyFor
+ * @param url the URL whose proxy info is needed
+ * @returns the proxy server address or the text "DIRECT"
+ * if no proxying is needed for the given address.
+ */
+ static TQString proxyForURL( const KURL& url );
+
+ /**
+ * Marks this proxy as bad (down). It will not be used for the
+ * next 30 minutes. (The script may supply an alternate proxy)
+ * @param proxy the proxy to mark as bad (as URL)
+ */
+ static void badProxy( const TQString & proxy );
+
+ /**
+ * Returns the URL of the script for automatic proxy configuration.
+ * @return the proxy configuration script
+ */
+ static TQString proxyConfigScript();
+
+
+/*========================== CACHE CONFIG ===================================*/
+
+
+ /**
+ * Returns true/false to indicate whether a cache
+ * should be used
+ *
+ * @return true to use the cache, false otherwisea
+ */
+ static bool useCache();
+
+ /**
+ * Returns the maximum age in seconds cached files should be
+ * kept before they are deleted as necessary.
+ *
+ * @return the maximum cache age in seconds
+ */
+ static int maxCacheAge();
+
+ /**
+ * Returns the maximum size that can be used for caching.
+ *
+ * By default this function returns the DEFAULT_MAX_CACHE_SIZE
+ * value as defined in http_slave_defaults.h. Not that the
+ * value returned is in bytes, hence a value of 5120 would mean
+ * 5 Kb.
+ *
+ * @return the maximum cache size in bytes
+ */
+ static int maxCacheSize(); // Maximum cache size in Kb.
+
+ /**
+ * The directory which contains the cache files.
+ * @return the directory that contains the cache files
+ */
+ static TQString cacheDir();
+
+ /**
+ * Returns the Cache control directive to be used.
+ * @return the cache control value
+ */
+ static TDEIO::CacheControl cacheControl();
+
+
+/*============================ DOWNLOAD CONFIG ==============================*/
+
+ /**
+ * Returns true if partial downloads should be
+ * automatically resumed.
+ * @return true to resume partial downloads
+ */
+ static bool autoResume();
+
+ /**
+ * Returns true if partial downloads should be marked
+ * with a ".part" extension.
+ * @return true if partial downloads should get an ".part" extension
+ */
+ static bool markPartial();
+
+ /**
+ * Returns the minimum file size for keeping aborted
+ * downloads.
+ *
+ * Any data downloaded that does not meet this minimum
+ * requirement will simply be discarded. The default size
+ * is 5 KB.
+ *
+ * @return the minimum keep size for aborted downloads in bytes
+ */
+ static int minimumKeepSize();
+
+
+ /*============================ NETWORK CONNECTIONS ==========================*/
+ /**
+ * Returns true if proxy connections should be persistent.
+ * @return true if proxy connections should be persistent
+ * @since 3.1
+ */
+ static bool persistentProxyConnection();
+
+ /**
+ * Returns true if connections should be persistent
+ * @return true if the connections should be persistent
+ */
+ static bool persistentConnections();
+
+/*=============================== OTHERS ====================================*/
+
+
+ /**
+ * Force a reload of the general config file of
+ * io-slaves ( tdeioslaverc).
+ */
+ static void reparseConfiguration();
+
+ /**
+ * Return the protocol to use in order to handle the given @p url
+ * It's usually the same, except that FTP, when handled by a proxy,
+ * needs an HTTP ioslave.
+ *
+ * When a proxy is to be used, proxy contains the URL for the proxy.
+ * @param url the url to check
+ * @param proxy the URL of the proxy to use
+ * @return the slave protocol (e.g. 'http'), can be null if unknown
+ */
+ static TQString slaveProtocol(const KURL &url, TQString &proxy);
+
+ /**
+ * @internal
+ * (Shared with SlaveConfig)
+ */
+ static TDEConfig *config();
+private:
+ static TDEConfig *http_config();
+};
+#endif
diff --git a/kio/kio/kremoteencoding.cpp b/tdeio/tdeio/kremoteencoding.cpp
index 632eeb8b2..632eeb8b2 100644
--- a/kio/kio/kremoteencoding.cpp
+++ b/tdeio/tdeio/kremoteencoding.cpp
diff --git a/kio/kio/kremoteencoding.h b/tdeio/tdeio/kremoteencoding.h
index 18dfe1fdb..18dfe1fdb 100644
--- a/kio/kio/kremoteencoding.h
+++ b/tdeio/tdeio/kremoteencoding.h
diff --git a/tdeio/tdeio/krun.cpp b/tdeio/tdeio/krun.cpp
new file mode 100644
index 000000000..5810bdda4
--- /dev/null
+++ b/tdeio/tdeio/krun.cpp
@@ -0,0 +1,1574 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Torben Weis <weis@kde.org>
+ Copyright (C) 2006 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "krun.h"
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <typeinfo>
+
+#include <tqwidget.h>
+#include <tqguardedptr.h>
+
+#include "kuserprofile.h"
+#include "kmimetype.h"
+#include "kmimemagic.h"
+#include "tdeio/job.h"
+#include "tdeio/global.h"
+#include "tdeio/scheduler.h"
+#include "tdeio/netaccess.h"
+#include "tdefile/kopenwith.h"
+#include "tdefile/krecentdocument.h"
+
+#include <kdatastream.h>
+#include <kmessageboxwrapper.h>
+#include <kurl.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kprotocolinfo.h>
+#include <kstandarddirs.h>
+#include <kprocess.h>
+#include <dcopclient.h>
+#include <tqfile.h>
+#include <tqfileinfo.h>
+#include <tqtextstream.h>
+#include <tqdatetime.h>
+#include <tqregexp.h>
+#include <kdesktopfile.h>
+#include <kstartupinfo.h>
+#include <kmacroexpander.h>
+#include <kshell.h>
+#include <kde_file.h>
+#include <kstringhandler.h>
+
+#ifdef Q_WS_X11
+#include <twin.h>
+#endif
+
+class KRun::KRunPrivate
+{
+public:
+ KRunPrivate() { m_showingError = false; }
+
+ bool m_showingError;
+ bool m_runExecutables;
+
+ TQString m_preferredService;
+ TQString m_externalBrowser;
+ TQString m_localPath;
+ TQString m_suggestedFileName;
+ TQGuardedPtr <TQWidget> m_window;
+ TQCString m_asn;
+};
+
+pid_t KRun::runURL( const KURL& u, const TQString& _mimetype )
+{
+ return runURL( u, _mimetype, false, true, TQString::null );
+}
+
+pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile )
+{
+ return runURL( u, _mimetype, tempFile, true, TQString::null );
+}
+
+pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile, bool runExecutables )
+{
+ return runURL( u, _mimetype, tempFile, runExecutables, TQString::null );
+}
+
+bool KRun::isExecutableFile( const KURL& url, const TQString &mimetype )
+{
+ if ( !url.isLocalFile() )
+ return false;
+ TQFileInfo file( url.path() );
+ if ( file.isExecutable() ) // Got a prospective file to run
+ {
+ KMimeType::Ptr mimeType = KMimeType::mimeType( mimetype );
+
+ if ( mimeType->is("application/x-executable") || mimeType->is("application/x-executable-script") )
+ return true;
+ }
+ return false;
+}
+
+pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, bool tempFile, bool runExecutables, const TQString& suggestedFileName )
+{
+ return runURL( u, _mimetype, NULL, "", tempFile, runExecutables, suggestedFileName );
+}
+
+// This is called by foundMimeType, since it knows the mimetype of the URL
+pid_t KRun::runURL( const KURL& u, const TQString& _mimetype, TQWidget* window, const TQCString& asn,
+ bool tempFile, bool runExecutables, const TQString& suggestedFileName )
+{
+ bool noRun = false;
+ bool noAuth = false;
+ if ( _mimetype == "inode/directory-locked" )
+ {
+ KMessageBoxWrapper::error( window,
+ i18n("<qt>Unable to enter <b>%1</b>.\nYou do not have access rights to this location.</qt>").arg(u.htmlURL()) );
+ return 0;
+ }
+ else if ( (_mimetype == "application/x-desktop") ||
+ (_mimetype == "media/builtin-mydocuments") ||
+ (_mimetype == "media/builtin-mycomputer") ||
+ (_mimetype == "media/builtin-mynetworkplaces") ||
+ (_mimetype == "media/builtin-printers") ||
+ (_mimetype == "media/builtin-trash") ||
+ (_mimetype == "media/builtin-webbrowser") )
+ {
+ if ( u.isLocalFile() && runExecutables )
+ return KDEDesktopMimeType::run( u, true );
+ }
+ else if ( isExecutableFile(u, _mimetype) )
+ {
+ if ( u.isLocalFile() && runExecutables)
+ {
+ if (kapp->authorize("shell_access"))
+ {
+ TQString path = u.path();
+ shellQuote( path );
+ return (KRun::runCommand(path, TQString::null, TQString::null, window, asn)); // just execute the url as a command
+ // ## TODO implement deleting the file if tempFile==true
+ }
+ else
+ {
+ noAuth = true;
+ }
+ }
+ else if (_mimetype == "application/x-executable")
+ noRun = true;
+ }
+ else if ( isExecutable(_mimetype) )
+ {
+ if (!runExecutables)
+ noRun = true;
+
+ if (!kapp->authorize("shell_access"))
+ noAuth = true;
+ }
+
+ if ( noRun )
+ {
+ KMessageBox::sorry( window,
+ i18n("<qt>The file <b>%1</b> is an executable program. "
+ "For safety it will not be started.</qt>").arg(u.htmlURL()));
+ return 0;
+ }
+ if ( noAuth )
+ {
+ KMessageBoxWrapper::error( window,
+ i18n("<qt>You do not have permission to run <b>%1</b>.</qt>").arg(u.htmlURL()) );
+ return 0;
+ }
+
+ KURL::List lst;
+ lst.append( u );
+
+ static const TQString& app_str = TDEGlobal::staticQString("Application");
+
+ KService::Ptr offer = KServiceTypeProfile::preferredService( _mimetype, app_str );
+
+ if ( !offer )
+ {
+ // Open-with dialog
+ // TODO : pass the mimetype as a parameter, to show it (comment field) in the dialog !
+ // Hmm, in fact KOpenWithDlg::setServiceType already guesses the mimetype from the first URL of the list...
+ return displayOpenWithDialog( lst, tempFile, suggestedFileName );
+ }
+
+ return KRun::run( *offer, lst, window, asn, tempFile, suggestedFileName );
+}
+
+bool KRun::displayOpenWithDialog( const KURL::List& lst )
+{
+ return displayOpenWithDialog( lst, false, TQString::null );
+}
+
+bool KRun::displayOpenWithDialog( const KURL::List& lst, bool tempFiles )
+{
+ return displayOpenWithDialog( lst, tempFiles, TQString::null );
+}
+
+bool KRun::displayOpenWithDialog( const KURL::List& lst, bool tempFiles, const TQString& suggestedFileName )
+{
+ if (kapp && !kapp->authorizeKAction("openwith"))
+ {
+ // TODO: Better message, i18n freeze :-(
+ KMessageBox::sorry(0L, i18n("You are not authorized to open this file."));
+ return false;
+ }
+
+ KOpenWithDlg l( lst, i18n("Open with:"), TQString::null, 0L );
+ if ( l.exec() )
+ {
+ KService::Ptr service = l.service();
+ if ( !!service )
+ return KRun::run( *service, lst, 0 /*window*/, tempFiles, suggestedFileName );
+
+ kdDebug(7010) << "No service set, running " << l.text() << endl;
+ return KRun::run( l.text(), lst, suggestedFileName ); // TODO handle tempFiles
+ }
+ return false;
+}
+
+void KRun::shellQuote( TQString &_str )
+{
+ // Credits to Walter, says Bernd G. :)
+ if (_str.isEmpty()) // Don't create an explicit empty parameter
+ return;
+ TQChar q('\'');
+ _str.replace(q, "'\\''").prepend(q).append(q);
+}
+
+
+class KRunMX1 : public KMacroExpanderBase {
+public:
+ KRunMX1( const KService &_service ) :
+ KMacroExpanderBase( '%' ), hasUrls( false ), hasSpec( false ), service( _service ) {}
+ bool hasUrls:1, hasSpec:1;
+
+protected:
+ virtual int expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret );
+
+private:
+ const KService &service;
+};
+
+int
+KRunMX1::expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret )
+{
+ uint option = str[pos + 1];
+ switch( option ) {
+ case 'c':
+ ret << service.name().replace( '%', "%%" );
+ break;
+ case 'k':
+ ret << service.desktopEntryPath().replace( '%', "%%" );
+ break;
+ case 'i':
+ ret << "-icon" << service.icon().replace( '%', "%%" );
+ break;
+ case 'm':
+ ret << "-miniicon" << service.icon().replace( '%', "%%" );
+ break;
+ case 'u':
+ case 'U':
+ hasUrls = true;
+ /* fallthrough */
+ case 'f':
+ case 'F':
+ case 'n':
+ case 'N':
+ case 'd':
+ case 'D':
+ case 'v':
+ hasSpec = true;
+ /* fallthrough */
+ default:
+ return -2; // subst with same and skip
+ }
+ return 2;
+}
+
+class KRunMX2 : public KMacroExpanderBase {
+public:
+ KRunMX2( const KURL::List &_urls ) :
+ KMacroExpanderBase( '%' ), ignFile( false ), urls( _urls ) {}
+ bool ignFile:1;
+
+protected:
+ virtual int expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret );
+
+private:
+ void subst( int option, const KURL &url, TQStringList &ret );
+
+ const KURL::List &urls;
+};
+
+void
+KRunMX2::subst( int option, const KURL &url, TQStringList &ret )
+{
+ switch( option ) {
+ case 'u':
+ ret << url.pathOrURL();
+ break;
+ case 'd':
+ ret << url.directory();
+ break;
+ case 'f':
+ ret << url.path();
+ break;
+ case 'n':
+ ret << url.fileName();
+ break;
+ case 'v':
+ if (url.isLocalFile() && TQFile::exists( url.path() ) )
+ ret << KDesktopFile( url.path(), true ).readEntry( "Dev" );
+ break;
+ }
+ return;
+}
+
+int
+KRunMX2::expandEscapedMacro( const TQString &str, uint pos, TQStringList &ret )
+{
+ uint option = str[pos + 1];
+ switch( option ) {
+ case 'f':
+ case 'u':
+ case 'n':
+ case 'd':
+ case 'v':
+ if( urls.isEmpty() ) {
+ if (!ignFile)
+ kdDebug() << "KRun::processDesktopExec: No URLs supplied to single-URL service " << str << endl;
+ } else if( urls.count() > 1 )
+ kdWarning() << "KRun::processDesktopExec: " << urls.count() << " URLs supplied to single-URL service " << str << endl;
+ else
+ subst( option, urls.first(), ret );
+ break;
+ case 'F':
+ case 'U':
+ case 'N':
+ case 'D':
+ option += 'a' - 'A';
+ for( KURL::List::ConstIterator it = urls.begin(); it != urls.end(); ++it )
+ subst( option, *it, ret );
+ break;
+ case '%':
+ ret = "%";
+ break;
+ default:
+ return -2; // subst with same and skip
+ }
+ return 2;
+}
+
+// BIC: merge methods below
+TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell) {
+ return processDesktopExec( _service, _urls, has_shell, false, TQString::null );
+}
+
+TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell /* KDE4: remove */, bool tempFiles)
+{
+ return processDesktopExec( _service, _urls, has_shell, tempFiles, TQString::null );
+}
+
+TQStringList KRun::processDesktopExec(const KService &_service, const KURL::List& _urls, bool has_shell /* KDE4: remove */, bool tempFiles, const TQString& suggestedFileName)
+{
+ TQString exec = _service.exec();
+ TQStringList result;
+ bool appHasTempFileOption;
+
+ KRunMX1 mx1( _service );
+ KRunMX2 mx2( _urls );
+
+ /// compatibility hack -- KDE 4: remove
+ TQRegExp re("^\\s*(?:/bin/)?sh\\s+-c\\s+(.*)$");
+ if (!re.search( exec )) {
+ exec = TQString(re.cap( 1 )).stripWhiteSpace();
+ for (uint pos = 0; pos < exec.length(); ) {
+ TQChar c = exec.unicode()[pos];
+ if (c != '\'' && c != '"')
+ goto synerr; // what else can we do? after normal parsing the substs would be insecure
+ int pos2 = exec.find( c, pos + 1 ) - 1;
+ if (pos2 < 0)
+ goto synerr; // quoting error
+ memcpy( (void *)(exec.unicode() + pos), exec.unicode() + pos + 1, (pos2 - pos) * sizeof(TQChar));
+ pos = pos2;
+ exec.remove( pos, 2 );
+ }
+ }
+
+ if( !mx1.expandMacrosShellQuote( exec ) )
+ goto synerr; // error in shell syntax
+
+ // FIXME: the current way of invoking tdeioexec disables term and su use
+
+ // Check if we need "tempexec" (tdeioexec in fact)
+ appHasTempFileOption = tempFiles && _service.property("X-TDE-HasTempFileOption").toBool();
+ if( tempFiles && !appHasTempFileOption && _urls.size() ) {
+ result << "tdeioexec" << "--tempfiles" << exec;
+ result += _urls.toStringList();
+ if (has_shell)
+ result = KShell::joinArgs( result );
+ return result;
+ }
+
+ // Check if we need tdeioexec
+ if( !mx1.hasUrls ) {
+ for( KURL::List::ConstIterator it = _urls.begin(); it != _urls.end(); ++it )
+ if ( !(*it).isLocalFile() && !KProtocolInfo::isHelperProtocol(*it) ) {
+ // We need to run the app through tdeioexec
+ result << "tdeioexec";
+ if ( tempFiles )
+ result << "--tempfiles";
+ if ( !suggestedFileName.isEmpty() ) {
+ result << "--suggestedfilename";
+ result << suggestedFileName;
+ }
+ result << exec;
+ result += _urls.toStringList();
+ if (has_shell)
+ result = KShell::joinArgs( result );
+ return result;
+ }
+ }
+
+ if ( appHasTempFileOption )
+ exec += " --tempfile";
+
+ // Did the user forget to append something like '%f'?
+ // If so, then assume that '%f' is the right choice => the application
+ // accepts only local files.
+ if( !mx1.hasSpec ) {
+ exec += " %f";
+ mx2.ignFile = true;
+ }
+
+ mx2.expandMacrosShellQuote( exec ); // syntax was already checked, so don't check return value
+
+/*
+ 1 = need_shell, 2 = terminal, 4 = su, 8 = has_shell
+
+ 0 << split(cmd)
+ 1 << "sh" << "-c" << cmd
+ 2 << split(term) << "-e" << split(cmd)
+ 3 << split(term) << "-e" << "sh" << "-c" << cmd
+
+ 4 << "tdesu" << "-u" << user << "-c" << cmd
+ 5 << "tdesu" << "-u" << user << "-c" << ("sh -c " + quote(cmd))
+ 6 << split(term) << "-e" << "su" << user << "-c" << cmd
+ 7 << split(term) << "-e" << "su" << user << "-c" << ("sh -c " + quote(cmd))
+
+ 8 << cmd
+ 9 << cmd
+ a << term << "-e" << cmd
+ b << term << "-e" << ("sh -c " + quote(cmd))
+
+ c << "tdesu" << "-u" << user << "-c" << quote(cmd)
+ d << "tdesu" << "-u" << user << "-c" << quote("sh -c " + quote(cmd))
+ e << term << "-e" << "su" << user << "-c" << quote(cmd)
+ f << term << "-e" << "su" << user << "-c" << quote("sh -c " + quote(cmd))
+
+ "sh -c" is needed in the "su" case, too, as su uses the user's login shell, not sh.
+ this could be optimized with the -s switch of some su versions (e.g., debian linux).
+*/
+
+ if (_service.terminal()) {
+ TDEConfigGroupSaver gs(TDEGlobal::config(), "General");
+ TQString terminal = TDEGlobal::config()->readPathEntry("TerminalApplication", "konsole");
+ if (terminal == "konsole")
+ terminal += " -caption=%c %i %m";
+ terminal += " ";
+ terminal += _service.terminalOptions();
+ if( !mx1.expandMacrosShellQuote( terminal ) ) {
+ kdWarning() << "KRun: syntax error in command `" << terminal << "', service `" << _service.name() << "'" << endl;
+ return TQStringList();
+ }
+ mx2.expandMacrosShellQuote( terminal );
+ if (has_shell)
+ result << terminal;
+ else
+ result = KShell::splitArgs( terminal ); // assuming that the term spec never needs a shell!
+ result << "-e";
+ }
+
+ int err;
+ if (_service.substituteUid()) {
+ if (_service.terminal())
+ result << "su";
+ else
+ result << "tdesu" << "-u";
+ result << _service.username() << "-c";
+ KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
+ if (err == KShell::FoundMeta) {
+ shellQuote( exec );
+ exec.prepend( "/bin/sh -c " );
+ } else if (err != KShell::NoError)
+ goto synerr;
+ if (has_shell)
+ shellQuote( exec );
+ result << exec;
+ } else {
+ if (has_shell) {
+ if (_service.terminal()) {
+ KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
+ if (err == KShell::FoundMeta) {
+ shellQuote( exec );
+ exec.prepend( "/bin/sh -c " );
+ } else if (err != KShell::NoError)
+ goto synerr;
+ }
+ result << exec;
+ } else {
+ result += KShell::splitArgs(exec, KShell::AbortOnMeta | KShell::TildeExpand, &err);
+ if (err == KShell::FoundMeta)
+ result << "/bin/sh" << "-c" << exec;
+ else if (err != KShell::NoError)
+ goto synerr;
+ }
+ }
+
+ return result;
+
+ synerr:
+ kdWarning() << "KRun: syntax error in command `" << _service.exec() << "', service `" << _service.name() << "'" << endl;
+ return TQStringList();
+}
+
+//static
+TQString KRun::binaryName( const TQString & execLine, bool removePath )
+{
+ // Remove parameters and/or trailing spaces.
+ TQStringList args = KShell::splitArgs( execLine );
+ for (TQStringList::ConstIterator it = args.begin(); it != args.end(); ++it)
+ if (!(*it).contains('='))
+ // Remove path if wanted
+ return removePath ? (*it).mid(TQString(*it).findRev('/') + 1) : *it;
+ return TQString();
+}
+
+static pid_t runCommandInternal( TDEProcess* proc, const KService* service, const TQString& binName,
+ const TQString &execName, const TQString & iconName, TQWidget* window, TQCString asn )
+{
+ if (service && !service->desktopEntryPath().isEmpty()
+ && !KDesktopFile::isAuthorizedDesktopFile( service->desktopEntryPath() ))
+ {
+ kdWarning() << "No authorization to execute " << service->desktopEntryPath() << endl;
+ KMessageBox::sorry(window, i18n("You are not authorized to execute this file."));
+ return 0;
+ }
+ TQString bin = KRun::binaryName( binName, true );
+#ifdef Q_WS_X11 // Startup notification doesn't work with QT/E, service isn't needed without Startup notification
+ bool silent;
+ TQCString wmclass;
+ KStartupInfoId id;
+ bool startup_notify = ( asn != "0" && KRun::checkStartupNotify( binName, service, &silent, &wmclass ));
+ if( startup_notify )
+ {
+ id.initId( asn );
+ id.setupStartupEnv();
+ KStartupInfoData data;
+ data.setHostname();
+ data.setBin( bin );
+ if( !execName.isEmpty())
+ data.setName( execName );
+ else if( service && !service->name().isEmpty())
+ data.setName( service->name());
+ data.setDescription( i18n( "Launching %1" ).arg( data.name()));
+ if( !iconName.isEmpty())
+ data.setIcon( iconName );
+ else if( service && !service->icon().isEmpty())
+ data.setIcon( service->icon());
+ if( !wmclass.isEmpty())
+ data.setWMClass( wmclass );
+ if( silent )
+ data.setSilent( KStartupInfoData::Yes );
+ data.setDesktop( KWin::currentDesktop());
+ if( window )
+ data.setLaunchedBy( window->winId());
+ KStartupInfo::sendStartup( id, data );
+ }
+ pid_t pid = TDEProcessRunner::run( proc, binName, id );
+ if( startup_notify && pid )
+ {
+ KStartupInfoData data;
+ data.addPid( pid );
+ KStartupInfo::sendChange( id, data );
+ KStartupInfo::resetStartupEnv();
+ }
+ return pid;
+#else
+ Q_UNUSED( execName );
+ Q_UNUSED( iconName );
+ return TDEProcessRunner::run( proc, bin );
+#endif
+}
+
+// This code is also used in tdelauncher.
+bool KRun::checkStartupNotify( const TQString& /*binName*/, const KService* service, bool* silent_arg, TQCString* wmclass_arg )
+{
+ bool silent = false;
+ TQCString wmclass;
+ if( service && service->property( "StartupNotify" ).isValid())
+ {
+ silent = !service->property( "StartupNotify" ).toBool();
+ wmclass = service->property( "StartupWMClass" ).toString().latin1();
+ }
+ else if( service && service->property( "X-TDE-StartupNotify" ).isValid())
+ {
+ silent = !service->property( "X-TDE-StartupNotify" ).toBool();
+ wmclass = service->property( "X-TDE-WMClass" ).toString().latin1();
+ }
+ else // non-compliant app
+ {
+ if( service )
+ {
+ if( service->type() == "Application" )
+ wmclass = "0"; // doesn't have .desktop entries needed, start as non-compliant
+ else
+ return false; // no startup notification at all
+ }
+ else
+ {
+#if 0
+ // Create startup notification even for apps for which there shouldn't be any,
+ // just without any visual feedback. This will ensure they'll be positioned on the proper
+ // virtual desktop, and will get user timestamp from the ASN ID.
+ wmclass = "0";
+ silent = true;
+#else // That unfortunately doesn't work, when the launched non-compliant application
+ // launches another one that is compliant and there is any delay inbetween (bnc:#343359)
+ return false;
+#endif
+ }
+ }
+ if( silent_arg != NULL )
+ *silent_arg = silent;
+ if( wmclass_arg != NULL )
+ *wmclass_arg = wmclass;
+ return true;
+}
+
+static pid_t runTempService( const KService& _service, const KURL::List& _urls, TQWidget* window,
+ const TQCString& asn, bool tempFiles, const TQString& suggestedFileName )
+{
+ if (!_urls.isEmpty()) {
+ kdDebug(7010) << "runTempService: first url " << _urls.first().url() << endl;
+ }
+
+ TQStringList args;
+ if ((_urls.count() > 1) && !_service.allowMultipleFiles())
+ {
+ // We need to launch the application N times. That sucks.
+ // We ignore the result for application 2 to N.
+ // For the first file we launch the application in the
+ // usual way. The reported result is based on this
+ // application.
+ KURL::List::ConstIterator it = _urls.begin();
+ while(++it != _urls.end())
+ {
+ KURL::List singleUrl;
+ singleUrl.append(*it);
+ runTempService( _service, singleUrl, window, "", tempFiles, suggestedFileName );
+ }
+ KURL::List singleUrl;
+ singleUrl.append(_urls.first());
+ args = KRun::processDesktopExec(_service, singleUrl, false, tempFiles, suggestedFileName);
+ }
+ else
+ {
+ args = KRun::processDesktopExec(_service, _urls, false, tempFiles, suggestedFileName);
+ }
+ kdDebug(7010) << "runTempService: TDEProcess args=" << args << endl;
+
+ TDEProcess * proc = new TDEProcess;
+ *proc << args;
+
+ if (!_service.path().isEmpty())
+ proc->setWorkingDirectory(_service.path());
+
+ return runCommandInternal( proc, &_service, KRun::binaryName( _service.exec(), false ),
+ _service.name(), _service.icon(), window, asn );
+}
+
+// WARNING: don't call this from processDesktopExec, since tdelauncher uses that too...
+static KURL::List resolveURLs( const KURL::List& _urls, const KService& _service )
+{
+ // Check which protocols the application supports.
+ // This can be a list of actual protocol names, or just KIO for KDE apps.
+ TQStringList supportedProtocols = _service.property("X-TDE-Protocols").toStringList();
+ KRunMX1 mx1( _service );
+ TQString exec = _service.exec();
+ if ( mx1.expandMacrosShellQuote( exec ) && !mx1.hasUrls ) {
+ Q_ASSERT( supportedProtocols.isEmpty() ); // huh? If you support protocols you need %u or %U...
+ } else {
+ if ( supportedProtocols.isEmpty() )
+ {
+ // compat mode: assume KIO if not set and it's a KDE app
+ TQStringList categories = _service.property("Categories").toStringList();
+ if (( categories.find("TDE") != categories.end() ) && ( categories.find("KDE") != categories.end() ))
+ supportedProtocols.append( "KIO" );
+ else { // if no KDE app, be a bit over-generic
+ supportedProtocols.append( "http");
+ supportedProtocols.append( "ftp");
+ }
+ }
+ }
+ kdDebug(7010) << "supportedProtocols:" << supportedProtocols << endl;
+
+ KURL::List urls( _urls );
+ if ( supportedProtocols.find( "KIO" ) == supportedProtocols.end() ) {
+ for( KURL::List::Iterator it = urls.begin(); it != urls.end(); ++it ) {
+ const KURL url = *it;
+ bool supported = url.isLocalFile() || supportedProtocols.find( url.protocol().lower() ) != supportedProtocols.end();
+ kdDebug(7010) << "Looking at url=" << url << " supported=" << supported << endl;
+ if ( !supported && KProtocolInfo::protocolClass(url.protocol()) == ":local" )
+ {
+ // Maybe we can resolve to a local URL?
+ KURL localURL = TDEIO::NetAccess::mostLocalURL( url, 0 );
+ if ( localURL != url ) {
+ *it = localURL;
+ kdDebug(7010) << "Changed to " << localURL << endl;
+ }
+ }
+ }
+ }
+ return urls;
+}
+
+// BIC merge methods below
+pid_t KRun::run( const KService& _service, const KURL::List& _urls )
+{
+ return run( _service, _urls, 0, false, TQString::null );
+}
+
+pid_t KRun::run( const KService& _service, const KURL::List& _urls, bool tempFiles )
+{
+ return run( _service, _urls, 0, tempFiles, TQString::null );
+}
+
+pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, bool tempFiles )
+{
+ return run( _service, _urls, window, "", tempFiles, TQString::null );
+}
+
+pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, const TQCString& asn, bool tempFiles )
+{
+ return run( _service, _urls, window, asn, tempFiles, TQString::null );
+}
+
+pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, bool tempFiles, const TQString& suggestedFileName )
+{
+ return run( _service, _urls, window, "", tempFiles, suggestedFileName );
+}
+
+pid_t KRun::run( const KService& _service, const KURL::List& _urls, TQWidget* window, const TQCString& asn,
+ bool tempFiles, const TQString& suggestedFileName )
+{
+ if (!_service.desktopEntryPath().isEmpty() &&
+ !KDesktopFile::isAuthorizedDesktopFile( _service.desktopEntryPath()))
+ {
+ kdWarning() << "No authorization to execute " << _service.desktopEntryPath() << endl;
+ KMessageBox::sorry(window, i18n("You are not authorized to execute this service."));
+ return 0;
+ }
+
+ if ( !tempFiles )
+ {
+ // Remember we opened those urls, for the "recent documents" menu in kicker
+ KURL::List::ConstIterator it = _urls.begin();
+ for(; it != _urls.end(); ++it) {
+ //kdDebug(7010) << "KRecentDocument::adding " << (*it).url() << endl;
+ KRecentDocument::add( *it, _service.desktopEntryName() );
+ }
+ }
+
+ if ( tempFiles || _service.desktopEntryPath().isEmpty() || !suggestedFileName.isEmpty() )
+ {
+ return runTempService(_service, _urls, window, asn, tempFiles, suggestedFileName);
+ }
+
+ kdDebug(7010) << "KRun::run " << _service.desktopEntryPath() << endl;
+
+ if (!_urls.isEmpty()) {
+ kdDebug(7010) << "First url " << _urls.first().url() << endl;
+ }
+
+ // Resolve urls if needed, depending on what the app supports
+ const KURL::List urls = resolveURLs( _urls, _service );
+
+ TQString error;
+ int pid = 0;
+
+ TQCString myasn = asn;
+ // startServiceByDesktopPath() doesn't take TQWidget*, add it to the startup info now
+ if( window != NULL )
+ {
+ if( myasn.isEmpty())
+ myasn = KStartupInfo::createNewStartupId();
+ if( myasn != "0" )
+ {
+ KStartupInfoId id;
+ id.initId( myasn );
+ KStartupInfoData data;
+ data.setLaunchedBy( window->winId());
+ KStartupInfo::sendChange( id, data );
+ }
+ }
+
+ int i = TDEApplication::startServiceByDesktopPath(
+ _service.desktopEntryPath(), urls.toStringList(), &error, 0L, &pid, myasn
+ );
+
+ if (i != 0)
+ {
+ kdDebug(7010) << error << endl;
+ KMessageBox::sorry( window, error );
+ return 0;
+ }
+
+ kdDebug(7010) << "startServiceByDesktopPath worked fine" << endl;
+ return (pid_t) pid;
+}
+
+
+pid_t KRun::run( const TQString& _exec, const KURL::List& _urls, const TQString& _name,
+ const TQString& _icon, const TQString&, const TQString&)
+{
+ KService::Ptr service = new KService(_name, _exec, _icon);
+
+ return run(*service, _urls);
+}
+
+pid_t KRun::runCommand( TQString cmd )
+{
+ return KRun::runCommand( cmd, TQString::null, TQString::null, NULL, "" );
+}
+
+pid_t KRun::runCommand( const TQString& cmd, const TQString &execName, const TQString & iconName )
+{
+ return KRun::runCommand( cmd, execName, iconName, NULL, "" );
+}
+
+pid_t KRun::runCommand( const TQString& cmd, const TQString &execName, const TQString & iconName,
+ TQWidget* window, const TQCString& asn )
+{
+ kdDebug(7010) << "runCommand " << cmd << "," << execName << endl;
+ TDEProcess * proc = new TDEProcess;
+ proc->setUseShell(true);
+ *proc << cmd;
+ KService::Ptr service = KService::serviceByDesktopName( binaryName( execName, true ) );
+ TQString bin = binaryName( cmd, false );
+ int pos = bin.findRev( '/' );
+ if (pos != -1) {
+ proc->setWorkingDirectory( bin.mid(0, pos) );
+ }
+ return runCommandInternal( proc, service.data(), binaryName( execName, false ), execName, iconName, window, asn );
+}
+
+KRun::KRun( const KURL& url, mode_t mode, bool isLocalFile, bool showProgressInfo )
+ :m_timer(0,"KRun::timer")
+{
+ init (url, 0, "", mode, isLocalFile, showProgressInfo);
+}
+
+KRun::KRun( const KURL& url, TQWidget* window, mode_t mode, bool isLocalFile,
+ bool showProgressInfo )
+ :m_timer(0,"KRun::timer")
+{
+ init (url, window, "", mode, isLocalFile, showProgressInfo);
+}
+
+KRun::KRun( const KURL& url, TQWidget* window, const TQCString& asn, mode_t mode, bool isLocalFile,
+ bool showProgressInfo )
+ :m_timer(0,"KRun::timer")
+{
+ init (url, window, asn, mode, isLocalFile, showProgressInfo);
+}
+
+void KRun::init ( const KURL& url, TQWidget* window, const TQCString& asn, mode_t mode, bool isLocalFile,
+ bool showProgressInfo )
+{
+ m_bFault = false;
+ m_bAutoDelete = true;
+ m_bProgressInfo = showProgressInfo;
+ m_bFinished = false;
+ m_job = 0L;
+ m_strURL = url;
+ m_bScanFile = false;
+ m_bIsDirectory = false;
+ m_bIsLocalFile = isLocalFile;
+ m_mode = mode;
+ d = new KRunPrivate;
+ d->m_runExecutables = true;
+ d->m_window = window;
+ d->m_asn = asn;
+ setEnableExternalBrowser(true);
+
+ // Start the timer. This means we will return to the event
+ // loop and do initialization afterwards.
+ // Reason: We must complete the constructor before we do anything else.
+ m_bInit = true;
+ connect( &m_timer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( slotTimeout() ) );
+ m_timer.start( 0, true );
+ kdDebug(7010) << " new KRun " << this << " " << url.prettyURL() << " timer=" << &m_timer << endl;
+
+ kapp->ref();
+}
+
+void KRun::init()
+{
+ kdDebug(7010) << "INIT called" << endl;
+
+ bool bypassErrorMessage = false;
+
+ if (m_strURL.url().startsWith("$(")) {
+ // check for environment variables and make necessary translations
+ TQString aValue = m_strURL.url();
+ int nDollarPos = aValue.find( '$' );
+
+ while( nDollarPos != -1 && nDollarPos+1 < static_cast<int>(aValue.length())) {
+ // there is at least one $
+ if( (aValue)[nDollarPos+1] == '(' ) {
+ uint nEndPos = nDollarPos+1;
+ // the next character is no $
+ while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!=')') )
+ nEndPos++;
+ nEndPos++;
+ TQString cmd = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
+
+ TQString result;
+ FILE *fs = popen(TQFile::encodeName(cmd).data(), "r");
+ if (fs)
+ {
+ {
+ TQTextStream ts(fs, IO_ReadOnly);
+ result = ts.read().stripWhiteSpace();
+ }
+ pclose(fs);
+ }
+ aValue.replace( nDollarPos, nEndPos-nDollarPos, result );
+ } else if( (aValue)[nDollarPos+1] != '$' ) {
+ uint nEndPos = nDollarPos+1;
+ // the next character is no $
+ TQString aVarName;
+ if (aValue[nEndPos]=='{')
+ {
+ while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') )
+ nEndPos++;
+ nEndPos++;
+ aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
+ }
+ else
+ {
+ while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber()
+ || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' ) )
+ nEndPos++;
+ aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 );
+ }
+ const char* pEnv = 0;
+ if (!aVarName.isEmpty())
+ pEnv = getenv( aVarName.ascii() );
+ if( pEnv ) {
+ // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
+ // A environment variables may contain values in 8bit
+ // locale cpecified encoding or in UTF8 encoding.
+ aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) );
+ } else
+ aValue.remove( nDollarPos, nEndPos-nDollarPos );
+ } else {
+ // remove one of the dollar signs
+ aValue.remove( nDollarPos, 1 );
+ nDollarPos++;
+ }
+ nDollarPos = aValue.find( '$', nDollarPos );
+ }
+ m_strURL = KURL(aValue);
+ bypassErrorMessage = true;
+ }
+
+ if ( !m_strURL.isValid() )
+ {
+ if (bypassErrorMessage == false) {
+ d->m_showingError = true;
+ KMessageBoxWrapper::error( d->m_window, i18n( "Malformed URL\n%1" ).arg( m_strURL.url() ) );
+ d->m_showingError = false;
+ }
+ m_bFault = true;
+ m_bFinished = true;
+ m_timer.start( 0, true );
+ return;
+ }
+ if ( !kapp->authorizeURLAction( "open", KURL(), m_strURL))
+ {
+ TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, m_strURL.prettyURL());
+ d->m_showingError = true;
+ KMessageBoxWrapper::error( d->m_window, msg );
+ d->m_showingError = false;
+ m_bFault = true;
+ m_bFinished = true;
+ m_timer.start( 0, true );
+ return;
+ }
+
+ if ( !m_bIsLocalFile && m_strURL.isLocalFile() )
+ m_bIsLocalFile = true;
+
+ TQString exec;
+ if (m_strURL.protocol().startsWith("http"))
+ {
+ exec = d->m_externalBrowser;
+ }
+
+ if ( m_bIsLocalFile )
+ {
+ if ( m_mode == 0 )
+ {
+ KDE_struct_stat buff;
+ if ( KDE_stat( TQFile::encodeName(m_strURL.path()), &buff ) == -1 )
+ {
+ d->m_showingError = true;
+ KMessageBoxWrapper::error( d->m_window, i18n( "<qt>Unable to run the command specified. The file or folder <b>%1</b> does not exist.</qt>" ).arg( m_strURL.htmlURL() ) );
+ d->m_showingError = false;
+ m_bFault = true;
+ m_bFinished = true;
+ m_timer.start( 0, true );
+ return;
+ }
+ m_mode = buff.st_mode;
+ }
+
+ KMimeType::Ptr mime = KMimeType::findByURL( m_strURL, m_mode, m_bIsLocalFile );
+ assert( mime != 0L );
+ kdDebug(7010) << "MIME TYPE is " << mime->name() << endl;
+ foundMimeType( mime->name() );
+ return;
+ }
+ else if ( !exec.isEmpty() || KProtocolInfo::isHelperProtocol( m_strURL ) ) {
+ kdDebug(7010) << "Helper protocol" << endl;
+
+ bool ok = false;
+ KURL::List urls;
+ if (!((m_strURL.protocol().startsWith("http")) && (m_strURL.url() == "http://default.browser")))
+ urls.append( m_strURL );
+ if (exec.isEmpty())
+ {
+ exec = KProtocolInfo::exec( m_strURL.protocol() );
+ if (exec.isEmpty())
+ {
+ foundMimeType(KProtocolInfo::defaultMimetype(m_strURL));
+ return;
+ }
+ run( exec, urls );
+ ok = true;
+ }
+ else if (exec.startsWith("!"))
+ {
+ exec = exec.mid(1); // Literal command
+ exec += " %u";
+ run( exec, urls );
+ ok = true;
+ }
+ else
+ {
+ KService::Ptr service = KService::serviceByStorageId( exec );
+ if (service)
+ {
+ run( *service, urls, d->m_window, d->m_asn );
+ ok = true;
+ }
+ }
+
+ if (ok)
+ {
+ m_bFinished = true;
+ // will emit the error and autodelete this
+ m_timer.start( 0, true );
+ return;
+ }
+ }
+
+ if ((m_strURL.protocol().startsWith("http")) && (m_strURL.url() == "http://default.browser")) {
+ KURL::List urls;
+ run( "kfmclient openProfile webbrowsing", urls );
+ m_bFinished = true;
+ // will emit the error and autodelete this
+ m_timer.start( 0, true );
+ return;
+ }
+
+ // Did we already get the information that it is a directory ?
+ if ( S_ISDIR( m_mode ) )
+ {
+ foundMimeType( "inode/directory" );
+ return;
+ }
+
+ // Let's see whether it is a directory
+
+ if ( !KProtocolInfo::supportsListing( m_strURL ) )
+ {
+ //kdDebug(7010) << "Protocol has no support for listing" << endl;
+ // No support for listing => it can't be a directory (example: http)
+ scanFile();
+ return;
+ }
+
+ kdDebug(7010) << "Testing directory (stating)" << endl;
+
+ // It may be a directory or a file, let's stat
+ TDEIO::StatJob *job = TDEIO::stat( m_strURL, true, 0 /* no details */, m_bProgressInfo );
+ job->setWindow (d->m_window);
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ this, TQT_SLOT( slotStatResult( TDEIO::Job * ) ) );
+ m_job = job;
+ kdDebug(7010) << " Job " << job << " is about stating " << m_strURL.url() << endl;
+}
+
+KRun::~KRun()
+{
+ kdDebug(7010) << "KRun::~KRun() " << this << endl;
+ m_timer.stop();
+ killJob();
+ kapp->deref();
+ kdDebug(7010) << "KRun::~KRun() done " << this << endl;
+ delete d;
+}
+
+void KRun::scanFile()
+{
+ kdDebug(7010) << "###### KRun::scanFile " << m_strURL.url() << endl;
+ // First, let's check for well-known extensions
+ // Not when there is a query in the URL, in any case.
+ if ( m_strURL.query().isEmpty() )
+ {
+ KMimeType::Ptr mime = KMimeType::findByURL( m_strURL );
+ assert( mime != 0L );
+ if ( mime->name() != "application/octet-stream" || m_bIsLocalFile )
+ {
+ kdDebug(7010) << "Scanfile: MIME TYPE is " << mime->name() << endl;
+ foundMimeType( mime->name() );
+ return;
+ }
+ }
+
+ // No mimetype found, and the URL is not local (or fast mode not allowed).
+ // We need to apply the 'KIO' method, i.e. either asking the server or
+ // getting some data out of the file, to know what mimetype it is.
+
+ if ( !KProtocolInfo::supportsReading( m_strURL ) )
+ {
+ kdError(7010) << "#### NO SUPPORT FOR READING!" << endl;
+ m_bFault = true;
+ m_bFinished = true;
+ m_timer.start( 0, true );
+ return;
+ }
+ kdDebug(7010) << this << " Scanning file " << m_strURL.url() << endl;
+
+ TDEIO::TransferJob *job = TDEIO::get( m_strURL, false /*reload*/, m_bProgressInfo );
+ job->setWindow (d->m_window);
+ connect(job, TQT_SIGNAL( result(TDEIO::Job *)),
+ this, TQT_SLOT( slotScanFinished(TDEIO::Job *)));
+ connect(job, TQT_SIGNAL( mimetype(TDEIO::Job *, const TQString &)),
+ this, TQT_SLOT( slotScanMimeType(TDEIO::Job *, const TQString &)));
+ m_job = job;
+ kdDebug(7010) << " Job " << job << " is about getting from " << m_strURL.url() << endl;
+}
+
+void KRun::slotTimeout()
+{
+ kdDebug(7010) << this << " slotTimeout called" << endl;
+ if ( m_bInit )
+ {
+ m_bInit = false;
+ init();
+ return;
+ }
+
+ if ( m_bFault ) {
+ emit error();
+ }
+ if ( m_bFinished ) {
+ emit finished();
+ }
+ else
+ {
+ if ( m_bScanFile )
+ {
+ m_bScanFile = false;
+ scanFile();
+ return;
+ }
+ else if ( m_bIsDirectory )
+ {
+ m_bIsDirectory = false;
+ foundMimeType( "inode/directory" );
+ return;
+ }
+ }
+
+ if ( m_bAutoDelete )
+ {
+ delete this;
+ return;
+ }
+}
+
+void KRun::slotStatResult( TDEIO::Job * job )
+{
+ m_job = 0L;
+ if (job->error())
+ {
+ d->m_showingError = true;
+ kdError(7010) << this << " ERROR " << job->error() << " " << job->errorString() << endl;
+ job->showErrorDialog();
+ //kdDebug(7010) << this << " KRun returning from showErrorDialog, starting timer to delete us" << endl;
+ d->m_showingError = false;
+
+ m_bFault = true;
+ m_bFinished = true;
+
+ // will emit the error and autodelete this
+ m_timer.start( 0, true );
+
+ } else {
+
+ kdDebug(7010) << "Finished" << endl;
+ if(!dynamic_cast<TDEIO::StatJob*>(job))
+ kdFatal() << "job is a " << typeid(*job).name() << " should be a StatJob" << endl;
+
+ TQString knownMimeType;
+ TDEIO::UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
+ TDEIO::UDSEntry::ConstIterator it = entry.begin();
+ for( ; it != entry.end(); it++ ) {
+ switch( (*it).m_uds ) {
+ case TDEIO::UDS_FILE_TYPE:
+ if ( S_ISDIR( (mode_t)((*it).m_long) ) )
+ m_bIsDirectory = true; // it's a dir
+ else
+ m_bScanFile = true; // it's a file
+ break;
+ case TDEIO::UDS_MIME_TYPE: // mimetype already known? (e.g. print:/manager)
+ knownMimeType = (*it).m_str;
+ break;
+ case TDEIO::UDS_LOCAL_PATH:
+ d->m_localPath = (*it).m_str;
+ break;
+ default:
+ break;
+ }
+ }
+ if ( !knownMimeType.isEmpty() )
+ {
+ foundMimeType( knownMimeType );
+ m_bFinished = true;
+ }
+
+ // We should have found something
+ assert ( m_bScanFile || m_bIsDirectory );
+
+ // Start the timer. Once we get the timer event this
+ // protocol server is back in the pool and we can reuse it.
+ // This gives better performance than starting a new slave
+ m_timer.start( 0, true );
+ }
+}
+
+void KRun::slotScanMimeType( TDEIO::Job *, const TQString &mimetype )
+{
+ if ( mimetype.isEmpty() )
+ kdWarning(7010) << "KRun::slotScanFinished : MimetypeJob didn't find a mimetype! Probably a tdeioslave bug." << endl;
+ foundMimeType( mimetype );
+ m_job = 0;
+}
+
+void KRun::slotScanFinished( TDEIO::Job *job )
+{
+ m_job = 0;
+ if (job->error())
+ {
+ d->m_showingError = true;
+ kdError(7010) << this << " ERROR (stat) : " << job->error() << " " << job->errorString() << endl;
+ job->showErrorDialog();
+ //kdDebug(7010) << this << " KRun returning from showErrorDialog, starting timer to delete us" << endl;
+ d->m_showingError = false;
+
+ m_bFault = true;
+ m_bFinished = true;
+
+ // will emit the error and autodelete this
+ m_timer.start( 0, true );
+ }
+}
+
+void KRun::foundMimeType( const TQString& type )
+{
+ kdDebug(7010) << "Resulting mime type is " << type << endl;
+
+/*
+ // Automatically unzip stuff
+
+ // Disabled since the new KIO doesn't have filters yet.
+
+ if ( type == "application/x-gzip" ||
+ type == "application/x-bzip" ||
+ type == "application/x-bzip2" )
+ {
+ KURL::List lst = KURL::split( m_strURL );
+ if ( lst.isEmpty() )
+ {
+ TQString tmp = i18n( "Malformed URL" );
+ tmp += "\n";
+ tmp += m_strURL.url();
+ KMessageBoxWrapper::error( 0L, tmp );
+ return;
+ }
+
+ if ( type == "application/x-gzip" )
+ lst.prepend( KURL( "gzip:/decompress" ) );
+ else if ( type == "application/x-bzip" )
+ lst.prepend( KURL( "bzip:/decompress" ) );
+ else if ( type == "application/x-bzip2" )
+ lst.prepend( KURL( "bzip2:/decompress" ) );
+ else if ( type == "application/x-tar" )
+ lst.prepend( KURL( "tar:/" ) );
+
+ // Move the HTML style reference to the leftmost URL
+ KURL::List::Iterator it = lst.begin();
+ ++it;
+ (*lst.begin()).setRef( (*it).ref() );
+ (*it).setRef( TQString::null );
+
+ // Create the new URL
+ m_strURL = KURL::join( lst );
+
+ kdDebug(7010) << "Now trying with " << debugString(m_strURL.url()) << endl;
+
+ killJob();
+
+ // We don't know if this is a file or a directory. Let's test this first.
+ // (For instance a tar.gz is a directory contained inside a file)
+ // It may be a directory or a file, let's stat
+ TDEIO::StatJob *job = TDEIO::stat( m_strURL, m_bProgressInfo );
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ this, TQT_SLOT( slotStatResult( TDEIO::Job * ) ) );
+ m_job = job;
+
+ return;
+ }
+*/
+ TDEIO::TransferJob *job = ::tqqt_cast<TDEIO::TransferJob *>( m_job );
+ if ( job )
+ {
+ job->putOnHold();
+ TDEIO::Scheduler::publishSlaveOnHold();
+ m_job = 0;
+ }
+
+ Q_ASSERT( !m_bFinished );
+
+ // Suport for preferred service setting, see setPreferredService
+ if ( !d->m_preferredService.isEmpty() ) {
+ kdDebug(7010) << "Attempting to open with preferred service: " << d->m_preferredService << endl;
+ KService::Ptr serv = KService::serviceByDesktopName( d->m_preferredService );
+ if ( serv && serv->hasServiceType( type ) )
+ {
+ KURL::List lst;
+ lst.append( m_strURL );
+ m_bFinished = KRun::run( *serv, lst, d->m_window, d->m_asn );
+ /// Note: the line above means that if that service failed, we'll
+ /// go to runURL to maybe find another service, even though a dialog
+ /// box was displayed. That's good if runURL tries another service,
+ /// but it's not good if it tries the same one :}
+ }
+ }
+
+ // Resolve .desktop files from media:/, remote:/, applications:/ etc.
+ if ( ((type == "application/x-desktop") ||
+ (type == "media/builtin-mydocuments") ||
+ (type == "media/builtin-mycomputer") ||
+ (type == "media/builtin-mynetworkplaces") ||
+ (type == "media/builtin-printers") ||
+ (type == "media/builtin-trash") ||
+ (type == "media/builtin-webbrowser")) /* or inheriting? */ && (!d->m_localPath.isEmpty()) )
+ {
+ m_strURL = KURL();
+ m_strURL.setPath( d->m_localPath );
+ }
+
+ if (!m_bFinished && KRun::runURL( m_strURL, type, d->m_window, d->m_asn, false, d->m_runExecutables, d->m_suggestedFileName )){
+ m_bFinished = true;
+ }
+ else{
+ m_bFinished = true;
+ m_bFault = true;
+ }
+
+ m_timer.start( 0, true );
+}
+
+void KRun::killJob()
+{
+ if ( m_job )
+ {
+ kdDebug(7010) << "KRun::killJob run=" << this << " m_job=" << m_job << endl;
+ m_job->kill();
+ m_job = 0L;
+ }
+}
+
+void KRun::abort()
+{
+ kdDebug(7010) << "KRun::abort " << this << " m_showingError=" << d->m_showingError << endl;
+ killJob();
+ // If we're showing an error message box, the rest will be done
+ // after closing the msgbox -> don't autodelete nor emit signals now.
+ if ( d->m_showingError )
+ return;
+ m_bFault = true;
+ m_bFinished = true;
+ m_bInit = false;
+ m_bScanFile = false;
+
+ // will emit the error and autodelete this
+ m_timer.start( 0, true );
+}
+
+void KRun::setEnableExternalBrowser(bool b)
+{
+ if (b)
+ d->m_externalBrowser = TDEConfigGroup(TDEGlobal::config(), "General").readEntry("BrowserApplication");
+ else
+ d->m_externalBrowser = TQString::null;
+}
+
+void KRun::setPreferredService( const TQString& desktopEntryName )
+{
+ d->m_preferredService = desktopEntryName;
+}
+
+void KRun::setRunExecutables(bool b)
+{
+ d->m_runExecutables = b;
+}
+
+void KRun::setSuggestedFileName( const TQString& fileName )
+{
+ d->m_suggestedFileName = fileName;
+}
+
+bool KRun::isExecutable( const TQString& serviceType )
+{
+ return ( serviceType == "application/x-desktop" ||
+ serviceType == "media/builtin-mydocuments" ||
+ serviceType == "media/builtin-mycomputer" ||
+ serviceType == "media/builtin-mynetworkplaces" ||
+ serviceType == "media/builtin-printers" ||
+ serviceType == "media/builtin-trash" ||
+ serviceType == "media/builtin-webbrowser" ||
+ serviceType == "application/x-executable" ||
+ serviceType == "application/x-msdos-program" ||
+ serviceType == "application/x-shellscript" );
+}
+
+/****************/
+
+pid_t
+TDEProcessRunner::run(TDEProcess * p, const TQString & binName)
+{
+ return (new TDEProcessRunner(p, binName))->pid();
+}
+
+#ifdef Q_WS_X11
+pid_t
+TDEProcessRunner::run(TDEProcess * p, const TQString & binName, const KStartupInfoId& id )
+{
+ return (new TDEProcessRunner(p, binName, id))->pid();
+}
+#endif
+
+TDEProcessRunner::TDEProcessRunner(TDEProcess * p, const TQString & _binName )
+ : TQObject(),
+ process_(p),
+ binName( _binName )
+{
+ TQObject::connect(
+ process_, TQT_SIGNAL(processExited(TDEProcess *)),
+ this, TQT_SLOT(slotProcessExited(TDEProcess *)));
+
+ process_->start();
+ if ( !process_->pid() )
+ slotProcessExited( process_ );
+}
+
+#ifdef Q_WS_X11
+TDEProcessRunner::TDEProcessRunner(TDEProcess * p, const TQString & _binName, const KStartupInfoId& id )
+ : TQObject(),
+ process_(p),
+ binName( _binName ),
+ id_( id )
+{
+ TQObject::connect(
+ process_, TQT_SIGNAL(processExited(TDEProcess *)),
+ this, TQT_SLOT(slotProcessExited(TDEProcess *)));
+
+ process_->start();
+ if ( !process_->pid() )
+ slotProcessExited( process_ );
+}
+#endif
+
+TDEProcessRunner::~TDEProcessRunner()
+{
+ delete process_;
+}
+
+ pid_t
+TDEProcessRunner::pid() const
+{
+ return process_->pid();
+}
+
+ void
+TDEProcessRunner::slotProcessExited(TDEProcess * p)
+{
+ if (p != process_)
+ return; // Eh ?
+
+ kdDebug(7010) << "slotProcessExited " << binName << endl;
+ kdDebug(7010) << "normalExit " << process_->normalExit() << endl;
+ kdDebug(7010) << "exitStatus " << process_->exitStatus() << endl;
+ bool showErr = process_->normalExit()
+ && ( process_->exitStatus() == 127 || process_->exitStatus() == 1 );
+ if ( !binName.isEmpty() && ( showErr || process_->pid() == 0 ) )
+ {
+ // Often we get 1 (zsh, csh) or 127 (ksh, bash) because the binary doesn't exist.
+ // We can't just rely on that, but it's a good hint.
+ // Before assuming its really so, we'll try to find the binName
+ // relatively to current directory, and then in the PATH.
+ if ( !TQFile( binName ).exists() && KStandardDirs::findExe( binName ).isEmpty() )
+ {
+ kapp->ref();
+ KMessageBox::sorry( 0L, i18n("Could not find the program '%1'").arg( binName ) );
+ kapp->deref();
+ }
+ }
+#ifdef Q_WS_X11
+ if( !id_.none())
+ {
+ KStartupInfoData data;
+ data.addPid( pid()); // announce this pid for the startup notification has finished
+ data.setHostname();
+ KStartupInfo::sendFinish( id_, data );
+ }
+#endif
+ deleteLater();
+}
+
+void KRun::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+#include "krun.moc"
diff --git a/kio/kio/krun.h b/tdeio/tdeio/krun.h
index 03186af85..03186af85 100644
--- a/kio/kio/krun.h
+++ b/tdeio/tdeio/krun.h
diff --git a/tdeio/tdeio/ksambashare.cpp b/tdeio/tdeio/ksambashare.cpp
new file mode 100644
index 000000000..608594ee5
--- /dev/null
+++ b/tdeio/tdeio/ksambashare.cpp
@@ -0,0 +1,239 @@
+/* This file is part of the KDE project
+ Copyright (c) 2004 Jan Schaefer <j_schaef@informatik.uni-kl.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqdict.h>
+#include <tqfile.h>
+#include <tqtextstream.h>
+
+#include <kdirwatch.h>
+#include <kstaticdeleter.h>
+#include <kdebug.h>
+#include <ksimpleconfig.h>
+
+#include "ksambashare.h"
+
+class KSambaSharePrivate
+{
+public:
+ KSambaSharePrivate();
+
+ bool readSmbConf();
+ bool findSmbConf();
+ bool load();
+
+ TQDict<bool> sharedPaths;
+ TQString smbConf;
+};
+
+KSambaSharePrivate::KSambaSharePrivate()
+{
+ load();
+}
+
+
+#define FILESHARECONF "/etc/security/fileshare.conf"
+
+bool KSambaSharePrivate::load() {
+ if (!findSmbConf())
+ return false;
+
+ return readSmbConf();
+}
+
+/**
+ * Try to find the samba config file path
+ * First tries the tdeconfig, then checks
+ * several well-known paths
+ * @return wether a smb.conf was found.
+ **/
+bool KSambaSharePrivate::findSmbConf() {
+ KSimpleConfig config(TQString::fromLatin1(FILESHARECONF),true);
+ smbConf = config.readEntry("SMBCONF");
+
+ if ( TQFile::exists(smbConf) )
+ return true;
+
+ if ( TQFile::exists("/etc/samba/smb.conf") )
+ smbConf = "/etc/samba/smb.conf";
+ else
+ if ( TQFile::exists("/etc/smb.conf") )
+ smbConf = "/etc/smb.conf";
+ else
+ if ( TQFile::exists("/usr/local/samba/lib/smb.conf") )
+ smbConf = "/usr/local/samba/lib/smb.conf";
+ else
+ if ( TQFile::exists("/usr/samba/lib/smb.conf") )
+ smbConf = "/usr/samba/lib/smb.conf";
+ else
+ if ( TQFile::exists("/usr/lib/smb.conf") )
+ smbConf = "/usr/lib/smb.conf";
+ else
+ if ( TQFile::exists("/usr/local/lib/smb.conf") )
+ smbConf = "/usr/local/lib/smb.conf";
+ else {
+ kdDebug(7000) << "KSambaShare: Could not found smb.conf!" << endl;
+ return false;
+ }
+
+ return true;
+}
+
+
+/**
+ * Reads all path= entries from the smb.conf file
+ * and fills the sharedPaths dict with the values
+ */
+bool KSambaSharePrivate::readSmbConf() {
+ TQFile f(smbConf);
+
+ kdDebug(7000) << "KSambaShare::readSmbConf " << smbConf << endl;
+
+ if (!f.open(IO_ReadOnly)) {
+ kdError() << "KSambaShare: Could not open " << smbConf << endl;
+ return false;
+ }
+
+ sharedPaths.clear();
+
+ TQTextStream s(&f);
+
+ bool continuedLine = false; // is true if the line before ended with a backslash
+ TQString completeLine;
+
+ while (!s.eof())
+ {
+ TQString currentLine = s.readLine().stripWhiteSpace();
+
+ if (continuedLine) {
+ completeLine += currentLine;
+ continuedLine = false;
+ }
+ else
+ completeLine = currentLine;
+
+ // is the line continued in the next line ?
+ if ( completeLine[completeLine.length()-1] == '\\' )
+ {
+ continuedLine = true;
+ // remove the ending backslash
+ completeLine.truncate( completeLine.length()-1 );
+ continue;
+ }
+
+ // comments or empty lines
+ if (completeLine.isEmpty() ||
+ '#' == completeLine[0] ||
+ ';' == completeLine[0])
+ {
+ continue;
+ }
+
+ // parameter
+ int i = completeLine.find('=');
+
+ if (i>-1)
+ {
+ TQString name = completeLine.left(i).stripWhiteSpace().lower();
+ TQString value = completeLine.mid(i+1).stripWhiteSpace();
+
+ if (name == TDEGlobal::staticQString("path")) {
+ // Handle quotation marks
+ if ( value[0] == '"' )
+ value.remove(0,1);
+
+ if ( value[value.length()-1] == '"' )
+ value.truncate(value.length()-1);
+
+ // Normalize path
+ if ( value[value.length()-1] != '/' )
+ value += '/';
+
+ bool b = true;
+ sharedPaths.insert(value,&b);
+ kdDebug(7000) << "KSambaShare: Found path: " << value << endl;
+ }
+ }
+ }
+
+ f.close();
+
+ return true;
+
+}
+
+KSambaShare::KSambaShare() {
+ d = new KSambaSharePrivate();
+ if (TQFile::exists(d->smbConf)) {
+ KDirWatch::self()->addFile(d->smbConf);
+ KDirWatch::self()->addFile(FILESHARECONF);
+ connect(KDirWatch::self(), TQT_SIGNAL(dirty (const TQString&)),this,
+ TQT_SLOT(slotFileChange(const TQString&)));
+ }
+}
+
+KSambaShare::~KSambaShare() {
+ if (TQFile::exists(d->smbConf)) {
+ KDirWatch::self()->removeFile(d->smbConf);
+ KDirWatch::self()->removeFile(FILESHARECONF);
+ }
+ delete d;
+}
+
+TQString KSambaShare::smbConfPath() const {
+ return d->smbConf;
+}
+
+bool KSambaShare::isDirectoryShared( const TQString & path ) const {
+ TQString fixedPath = path;
+ if ( path[path.length()-1] != '/' )
+ fixedPath += '/';
+
+ return d->sharedPaths.find(fixedPath) != 0;
+}
+
+TQStringList KSambaShare::sharedDirectories() const {
+ TQStringList result;
+ TQDictIterator<bool> it(d->sharedPaths);
+ for( ; it.current(); ++it )
+ result << it.currentKey();
+
+ return result;
+}
+
+void KSambaShare::slotFileChange( const TQString & path ) {
+ if (path == d->smbConf)
+ d->readSmbConf();
+ else
+ if (path == FILESHARECONF)
+ d->load();
+
+ emit changed();
+}
+
+KSambaShare* KSambaShare::_instance = 0L;
+static KStaticDeleter<KSambaShare> ksdSambaShare;
+
+KSambaShare* KSambaShare::instance() {
+ if (! _instance )
+ _instance = ksdSambaShare.setObject(_instance, new KSambaShare());
+
+ return _instance;
+}
+
+#include "ksambashare.moc"
+
diff --git a/kio/kio/ksambashare.h b/tdeio/tdeio/ksambashare.h
index ffd298588..ffd298588 100644
--- a/kio/kio/ksambashare.h
+++ b/tdeio/tdeio/ksambashare.h
diff --git a/kio/kio/kscan.cpp b/tdeio/tdeio/kscan.cpp
index 49ae7c5ab..49ae7c5ab 100644
--- a/kio/kio/kscan.cpp
+++ b/tdeio/tdeio/kscan.cpp
diff --git a/kio/kio/kscan.h b/tdeio/tdeio/kscan.h
index 940b8ceaa..940b8ceaa 100644
--- a/kio/kio/kscan.h
+++ b/tdeio/tdeio/kscan.h
diff --git a/tdeio/tdeio/kservice.cpp b/tdeio/tdeio/kservice.cpp
new file mode 100644
index 000000000..2a24743ab
--- /dev/null
+++ b/tdeio/tdeio/kservice.cpp
@@ -0,0 +1,934 @@
+/* This file is part of the KDE libraries
+ * Copyright (C) 1999 - 2001 Waldo Bastian <bastian@kde.org>
+ * Copyright (C) 1999 David Faure <faure@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+// $Id$
+
+#include <config.h>
+
+#include "kservice.h"
+#include "kservice_p.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <stddef.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+#include <tqstring.h>
+#include <tqfile.h>
+#include <tqdir.h>
+#include <tqtl.h>
+
+#include <ksimpleconfig.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kdesktopfile.h>
+#include <kglobal.h>
+#include <kiconloader.h>
+#include <klocale.h>
+#include <tdeconfigbase.h>
+#include <kstandarddirs.h>
+#include <dcopclient.h>
+
+#include "kservicefactory.h"
+#include "kservicetypefactory.h"
+#include "kservicetype.h"
+#include "kuserprofile.h"
+#include "tdesycoca.h"
+
+class KService::KServicePrivate
+{
+public:
+ TQStringList categories;
+ TQString menuId;
+};
+
+KService::KService( const TQString & _name, const TQString &_exec, const TQString &_icon)
+ : KSycocaEntry( TQString::null)
+{
+ d = new KServicePrivate;
+ m_bValid = true;
+ m_bDeleted = false;
+ m_strType = "Application";
+ m_strName = _name;
+ m_strExec = _exec;
+ m_strIcon = _icon;
+ m_bTerminal = false;
+ m_bAllowAsDefault = true;
+ m_initialPreference = 10;
+}
+
+
+KService::KService( const TQString & _fullpath )
+ : KSycocaEntry( _fullpath)
+{
+ KDesktopFile config( _fullpath );
+
+ init(&config);
+}
+
+KService::KService( KDesktopFile *config )
+ : KSycocaEntry( config->fileName())
+{
+ init(config);
+}
+
+void
+KService::init( KDesktopFile *config )
+{
+ d = new KServicePrivate;
+ m_bValid = true;
+
+ bool absPath = !TQDir::isRelativePath(entryPath());
+ bool kde4application = config->fileName().startsWith("/usr/share/applications/kde4/");
+
+ config->setDesktopGroup();
+
+ TQMap<TQString, TQString> entryMap = config->entryMap(config->group());
+
+ entryMap.remove("Encoding"); // reserved as part of Desktop Entry Standard
+ entryMap.remove("Version"); // reserved as part of Desktop Entry Standard
+
+ m_bDeleted = config->readBoolEntry( "Hidden", false );
+ entryMap.remove("Hidden");
+ if (m_bDeleted)
+ {
+ //kdDebug() << "Hidden=true for " << entryPath() << endl;
+ m_bValid = false;
+ return;
+ }
+
+ m_strName = config->readName();
+ entryMap.remove("Name");
+ if ( m_strName.isEmpty() )
+ {
+ if (config->readEntry( "Exec" ).isEmpty())
+ {
+ //kdWarning(7012) << "The desktop entry file " << entryPath()
+ // << " has no Name and no Exec" << endl;
+ m_bValid = false;
+ return;
+ }
+ // Try to make up a name.
+ m_strName = entryPath();
+ int i = m_strName.findRev('/');
+ m_strName = m_strName.mid(i+1);
+ i = m_strName.findRev('.');
+ if (i != -1)
+ m_strName = m_strName.left(i);
+ }
+
+ m_strType = config->readType();
+ entryMap.remove("Type");
+ if ( m_strType.isEmpty() )
+ {
+ /*kdWarning(7012) << "The desktop entry file " << entryPath()
+ << " has no Type=... entry."
+ << " It should be \"Application\" or \"Service\"" << endl;
+ m_bValid = false;
+ return;*/
+ m_strType = "Application";
+ } else if ( m_strType != "Application" && m_strType != "Service" )
+ {
+ kdWarning(7012) << "The desktop entry file " << entryPath()
+ << " has Type=" << m_strType
+ << " instead of \"Application\" or \"Service\"" << endl;
+ m_bValid = false;
+ return;
+ }
+
+ // In case Try Exec is set, check if the application is available
+ if (!config->tryExec()) {
+ //kdDebug(7012) << "tryExec said false for " << entryPath() << endl;
+ m_bDeleted = true;
+ m_bValid = false;
+ return;
+ }
+
+ TQString resource = config->resource();
+
+ if ( (m_strType == "Application") &&
+ (!resource.isEmpty()) &&
+ (resource != "apps") &&
+ !absPath)
+ {
+ kdWarning(7012) << "The desktop entry file " << entryPath()
+ << " has Type=" << m_strType << " but is located under \"" << resource
+ << "\" instead of \"apps\"" << endl;
+ m_bValid = false;
+ return;
+ }
+
+ if ( (m_strType == "Service") &&
+ (!resource.isEmpty()) &&
+ (resource != "services") &&
+ !absPath)
+ {
+ kdWarning(7012) << "The desktop entry file " << entryPath()
+ << " has Type=" << m_strType << " but is located under \"" << resource
+ << "\" instead of \"services\"" << endl;
+ m_bValid = false;
+ return;
+ }
+
+ TQString name = entryPath();
+ int pos = name.findRev('/');
+ if (pos != -1)
+ name = name.mid(pos+1);
+ pos = name.find('.');
+ if (pos != -1)
+ name = name.left(pos);
+
+ m_strExec = config->readPathEntry( "Exec" );
+ if (kde4application && !m_strExec.startsWith("/")) {
+ m_strExec = "XDG_DATA_DIRS=/usr/share XDG_CONFIG_DIRS=/etc/xdg/ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:$PATH "+m_strExec;
+ } else if (config->readBoolEntry("X-TDE-SubstituteUID")) {
+ int space = m_strExec.find(" ");
+ if (space==-1)
+ m_strExec = KStandardDirs::findExe(m_strExec);
+ else {
+ const TQString command = m_strExec.left(space);
+ m_strExec.replace(command,KStandardDirs::findExe(command));
+ }
+ }
+
+ entryMap.remove("Exec");
+
+ m_strIcon = config->readEntry( "Icon", "unknown" );
+ if (kde4application) {
+ if (TQFile::exists("/usr/share/icons/oxygen/22x22/apps/" + m_strIcon + ".png")) {
+ m_strIcon = "/usr/share/icons/oxygen/22x22/apps/" + m_strIcon + ".png";
+ } else if (TQFile::exists("/usr/share/icons/hicolor/22x22/apps/" + m_strIcon + ".png")) {
+ m_strIcon = "/usr/share/icons/hicolor/22x22/apps/" + m_strIcon + ".png";
+ }
+ }
+ entryMap.remove("Icon");
+ m_bTerminal = (config->readBoolEntry( "Terminal" )); // should be a property IMHO
+ entryMap.remove("Terminal");
+ m_strTerminalOptions = config->readEntry( "TerminalOptions" ); // should be a property IMHO
+ entryMap.remove("TerminalOptions");
+ m_strPath = config->readPath();
+ entryMap.remove("Path");
+ m_strComment = config->readComment();
+ entryMap.remove("Comment");
+ m_strGenName = config->readGenericName();
+ if (kde4application) {
+ m_strGenName += " [KDE4]";
+ }
+ entryMap.remove("GenericName");
+ TQString untranslatedGenericName = config->readEntryUntranslated( "GenericName" );
+ if (!untranslatedGenericName.isEmpty())
+ entryMap.insert("UntranslatedGenericName", untranslatedGenericName);
+
+ m_lstKeywords = config->readListEntry("Keywords");
+ entryMap.remove("Keywords");
+ d->categories = config->readListEntry("Categories", ';');
+ entryMap.remove("Categories");
+ m_strLibrary = config->readEntry( "X-TDE-Library" );
+ entryMap.remove("X-TDE-Library");
+ m_strInit = config->readEntry("X-TDE-Init" );
+ entryMap.remove("X-TDE-Init");
+
+ m_lstServiceTypes = config->readListEntry( "ServiceTypes" );
+ entryMap.remove("ServiceTypes");
+ // For compatibility with KDE 1.x
+ if (!kde4application)
+ m_lstServiceTypes += config->readListEntry( "MimeType", ';' );
+ entryMap.remove("MimeType");
+
+ if ( m_strType == "Application" && !m_lstServiceTypes.contains("Application") )
+ // Applications implement the service type "Application" ;-)
+ m_lstServiceTypes += "Application";
+
+ TQString dcopServiceType = config->readEntry("X-DCOP-ServiceType").lower();
+ entryMap.remove("X-DCOP-ServiceType");
+ if (dcopServiceType == "unique")
+ m_DCOPServiceType = DCOP_Unique;
+ else if (dcopServiceType == "multi")
+ m_DCOPServiceType = DCOP_Multi;
+ else if (dcopServiceType == "wait")
+ m_DCOPServiceType = DCOP_Wait;
+ else
+ m_DCOPServiceType = DCOP_None;
+
+ m_strDesktopEntryName = name.lower();
+ if (kde4application)
+ m_strDesktopEntryName = "kde4-" + m_strDesktopEntryName;
+
+ m_bAllowAsDefault = config->readBoolEntry( "AllowDefault", true );
+ entryMap.remove("AllowDefault");
+
+ m_initialPreference = config->readNumEntry( "X-TDE-InitialPreference", 1 );
+ entryMap.remove("X-TDE-InitialPreference");
+ if ( m_initialPreference == 1 )
+ m_initialPreference = config->readNumEntry( "InitialPreference", 1 );
+ entryMap.remove("InitialPreference");
+
+ // Store all additional entries in the property map.
+ // A TQMap<TQString,TQString> would be easier for this but we can't
+ // brake BC, so we have to store it in m_mapProps.
+// tqWarning("Path = %s", entryPath().latin1());
+ TQMap<TQString,TQString>::ConstIterator it = entryMap.begin();
+ for( ; it != entryMap.end();++it)
+ {
+ //tqDebug(" Key = %s Data = %s", it.key().latin1(), it.data().latin1());
+ TQString key = it.key();
+ if (kde4application && key=="OnlyShowIn" && it.data()=="KDE;")
+ key = "NotShowIn";
+ m_mapProps.insert( key, TQVariant( it.data()));
+ }
+}
+
+KService::KService( TQDataStream& _str, int offset ) : KSycocaEntry( _str, offset )
+{
+ d = new KServicePrivate;
+ load( _str );
+}
+
+KService::~KService()
+{
+ //debug("KService::~KService()");
+ delete d;
+}
+
+TQPixmap KService::pixmap( KIcon::Group _group, int _force_size, int _state, TQString * _path ) const
+{
+ KIconLoader *iconLoader=TDEGlobal::iconLoader();
+ if (!iconLoader->extraDesktopThemesAdded())
+ {
+ TQPixmap pixmap=iconLoader->loadIcon( m_strIcon, _group, _force_size, _state, _path, true );
+ if (!pixmap.isNull() ) return pixmap;
+
+ iconLoader->addExtraDesktopThemes();
+ }
+
+ return iconLoader->loadIcon( m_strIcon, _group, _force_size, _state, _path );
+}
+
+void KService::load( TQDataStream& s )
+{
+ // dummies are here because of fields that were removed, to keep bin compat.
+ // Feel free to re-use, but fields for Applications only (not generic services)
+ // should rather be added to application.desktop
+ TQ_INT8 def, term, dummy1, dummy2;
+ TQ_INT8 dst, initpref;
+ TQString dummyStr1, dummyStr2;
+ int dummyI1, dummyI2;
+ TQ_UINT32 dummyUI32;
+
+ // WARNING: IN KDE 3.x THIS NEEDS TO REMAIN COMPATIBLE WITH KDE 2.x!
+ // !! This data structure should remain binary compatible at all times !!
+ // You may add new fields at the end. Make sure to update the version
+ // number in tdesycoca.h
+ s >> m_strType >> m_strName >> m_strExec >> m_strIcon
+ >> term >> m_strTerminalOptions
+ >> m_strPath >> m_strComment >> m_lstServiceTypes >> def >> m_mapProps
+ >> m_strLibrary >> dummyI1 >> dummyI2
+ >> dst
+ >> m_strDesktopEntryName
+ >> dummy1 >> dummyStr1 >> initpref >> dummyStr2 >> dummy2
+ >> m_lstKeywords >> m_strInit >> dummyUI32 >> m_strGenName
+ >> d->categories >> d->menuId;
+
+ m_bAllowAsDefault = def;
+ m_bTerminal = term;
+ m_DCOPServiceType = (DCOPServiceType_t) dst;
+ m_initialPreference = initpref;
+
+ m_bValid = true;
+}
+
+void KService::save( TQDataStream& s )
+{
+ KSycocaEntry::save( s );
+ TQ_INT8 def = m_bAllowAsDefault, initpref = m_initialPreference;
+ TQ_INT8 term = m_bTerminal;
+ TQ_INT8 dst = (TQ_INT8) m_DCOPServiceType;
+ TQ_INT8 dummy1 = 0, dummy2 = 0; // see ::load
+ TQString dummyStr1, dummyStr2;
+ int dummyI1 = 0, dummyI2 = 0;
+ TQ_UINT32 dummyUI32 = 0;
+
+ // WARNING: IN KDE 3.x THIS NEEDS TO REMAIN COMPATIBLE WITH KDE 2.x!
+ // !! This data structure should remain binary compatible at all times !!
+ // You may add new fields at the end. Make sure to update the version
+ // number in tdesycoca.h
+ s << m_strType << m_strName << m_strExec << m_strIcon
+ << term << m_strTerminalOptions
+ << m_strPath << m_strComment << m_lstServiceTypes << def << m_mapProps
+ << m_strLibrary << dummyI1 << dummyI2
+ << dst
+ << m_strDesktopEntryName
+ << dummy1 << dummyStr1 << initpref << dummyStr2 << dummy2
+ << m_lstKeywords << m_strInit << dummyUI32 << m_strGenName
+ << d->categories << d->menuId;
+}
+
+bool KService::hasServiceType( const TQString& _servicetype ) const
+{
+ if (!m_bValid) return false; // safety test
+
+ //kdDebug(7012) << "Testing " << m_strDesktopEntryName << " for " << _servicetype << endl;
+
+ KMimeType::Ptr mimePtr = KMimeType::mimeType( _servicetype );
+ if ( mimePtr && mimePtr == KMimeType::defaultMimeTypePtr() )
+ mimePtr = 0;
+
+ bool isNumber;
+ // For each service type we are associated with, if it doesn't
+ // match then we try its parent service types.
+ TQStringList::ConstIterator it = m_lstServiceTypes.begin();
+ for( ; it != m_lstServiceTypes.end(); ++it )
+ {
+ (*it).toInt(&isNumber);
+ if (isNumber)
+ continue;
+ //kdDebug(7012) << " has " << (*it) << endl;
+ KServiceType::Ptr ptr = KServiceType::serviceType( *it );
+ if ( ptr && ptr->inherits( _servicetype ) )
+ return true;
+
+ // The mimetype inheritance ("is also") works the other way.
+ // e.g. if we're looking for a handler for mimePtr==smb-workgroup
+ // then a handler for inode/directory is ok.
+ if ( mimePtr && mimePtr->is( *it ) )
+ return true;
+ }
+ return false;
+}
+
+int KService::initialPreferenceForMimeType( const TQString& mimeType ) const
+{
+ if (!m_bValid) return 0; // safety test
+
+ bool isNumber;
+
+ // For each service type we are associated with
+ TQStringList::ConstIterator it = m_lstServiceTypes.begin();
+ for( ; it != m_lstServiceTypes.end(); ++it )
+ {
+ (*it).toInt(&isNumber);
+ if (isNumber)
+ continue;
+ //kdDebug(7012) << " has " << (*it) << endl;
+ KServiceType::Ptr ptr = KServiceType::serviceType( *it );
+ if ( !ptr || !ptr->inherits( mimeType ) )
+ continue;
+
+ int initalPreference = m_initialPreference;
+ ++it;
+ if (it != m_lstServiceTypes.end())
+ {
+ int i = (*it).toInt(&isNumber);
+ if (isNumber)
+ initalPreference = i;
+ }
+ return initalPreference;
+ }
+
+ KMimeType::Ptr mimePtr = KMimeType::mimeType( mimeType );
+ if ( mimePtr && mimePtr == KMimeType::defaultMimeTypePtr() )
+ mimePtr = 0;
+
+ // Try its parent service types.
+ it = m_lstServiceTypes.begin();
+ for( ; it != m_lstServiceTypes.end(); ++it )
+ {
+ (*it).toInt(&isNumber);
+ if (isNumber)
+ continue;
+
+ // The mimetype inheritance ("is also") works the other way.
+ // e.g. if we're looking for a handler for mimePtr==smb-workgroup
+ // then a handler for inode/directory is ok.
+ if ( !mimePtr || !mimePtr->is( *it ) )
+ continue;
+
+ int initalPreference = m_initialPreference;
+ ++it;
+ if (it != m_lstServiceTypes.end())
+ {
+ int i = (*it).toInt(&isNumber);
+ if (isNumber)
+ initalPreference = i;
+ }
+ return initalPreference;
+ }
+ return 0;
+}
+
+class KServiceReadProperty : public TDEConfigBase
+{
+public:
+ KServiceReadProperty(const TQString &_key, const TQCString &_value)
+ : key(_key), value(_value) { }
+
+ bool internalHasGroup(const TQCString &) const { /*tqDebug("hasGroup(const TQCString &)");*/ return false; }
+
+ TQStringList groupList() const { return TQStringList(); }
+
+ TQMap<TQString,TQString> entryMap(const TQString &group) const
+ { Q_UNUSED(group); return TQMap<TQString,TQString>(); }
+
+ void reparseConfiguration() { }
+
+ KEntryMap internalEntryMap( const TQString &pGroup) const
+ { Q_UNUSED(pGroup); return KEntryMap(); }
+
+ KEntryMap internalEntryMap() const { return KEntryMap(); }
+
+ void putData(const KEntryKey &_key, const KEntry& _data, bool _checkGroup)
+ { Q_UNUSED(_key); Q_UNUSED(_data); Q_UNUSED(_checkGroup); }
+
+ KEntry lookupData(const KEntryKey &_key) const
+ { Q_UNUSED(_key); KEntry entry; entry.mValue = value; return entry; }
+protected:
+ TQString key;
+ TQCString value;
+};
+
+TQVariant KService::property( const TQString& _name) const
+{
+ return property( _name, TQVariant::Invalid);
+}
+
+// Return a string TQVariant if string isn't null, and invalid variant otherwise
+// (the variant must be invalid if the field isn't in the .desktop file)
+// This allows trader queries like "exist Library" to work.
+static TQVariant makeStringVariant( const TQString& string )
+{
+ // Using isEmpty here would be wrong.
+ // Empty is "specified but empty", null is "not specified" (in the .desktop file)
+ return string.isNull() ? TQVariant() : TQVariant( string );
+}
+
+TQVariant KService::property( const TQString& _name, TQVariant::Type t ) const
+{
+ if ( _name == "Type" )
+ return TQVariant( m_strType ); // can't be null
+ else if ( _name == "Name" )
+ return TQVariant( m_strName ); // can't be null
+ else if ( _name == "Exec" )
+ return makeStringVariant( m_strExec );
+ else if ( _name == "Icon" )
+ return makeStringVariant( m_strIcon );
+ else if ( _name == "Terminal" )
+ return TQVariant( static_cast<int>(m_bTerminal) );
+ else if ( _name == "TerminalOptions" )
+ return makeStringVariant( m_strTerminalOptions );
+ else if ( _name == "Path" )
+ return makeStringVariant( m_strPath );
+ else if ( _name == "Comment" )
+ return makeStringVariant( m_strComment );
+ else if ( _name == "GenericName" )
+ return makeStringVariant( m_strGenName );
+ else if ( _name == "ServiceTypes" )
+ return TQVariant( m_lstServiceTypes );
+ else if ( _name == "AllowAsDefault" )
+ return TQVariant( static_cast<int>(m_bAllowAsDefault) );
+ else if ( _name == "InitialPreference" )
+ return TQVariant( m_initialPreference );
+ else if ( _name == "Library" )
+ return makeStringVariant( m_strLibrary );
+ else if ( _name == "DesktopEntryPath" ) // can't be null
+ return TQVariant( entryPath() );
+ else if ( _name == "DesktopEntryName")
+ return TQVariant( m_strDesktopEntryName ); // can't be null
+ else if ( _name == "Categories")
+ return TQVariant( d->categories );
+ else if ( _name == "Keywords")
+ return TQVariant( m_lstKeywords );
+
+ // Ok we need to convert the property from a TQString to its real type.
+ // Maybe the caller helped us.
+ if (t == TQVariant::Invalid)
+ {
+ // No luck, let's ask KServiceTypeFactory what the type of this property
+ // is supposed to be.
+ t = KServiceTypeFactory::self()->findPropertyTypeByName(_name);
+ if (t == TQVariant::Invalid)
+ {
+ kdDebug(7012) << "Request for unknown property '" << _name << "'\n";
+ return TQVariant(); // Unknown property: Invalid variant.
+ }
+ }
+
+ // Then we use a homebuild class based on TDEConfigBase to convert the TQString.
+ // For some often used property types we do the conversion ourselves.
+ TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( _name );
+ if ( (it == m_mapProps.end()) || (!it.data().isValid()))
+ {
+ //kdDebug(7012) << "Property not found " << _name << endl;
+ return TQVariant(); // No property set.
+ }
+
+ switch(t)
+ {
+ case TQVariant::String:
+ return it.data();
+ case TQVariant::Bool:
+ case TQVariant::Int:
+ {
+ TQString aValue = it.data().toString();
+ int val = 0;
+ if (aValue == "true" || aValue == "on" || aValue == "yes")
+ val = 1;
+ else
+ {
+ bool bOK;
+ val = aValue.toInt( &bOK );
+ if( !bOK )
+ val = 0;
+ }
+ if (t == TQVariant::Bool)
+ {
+ return TQVariant((bool)val, 1);
+ }
+ return TQVariant(val);
+ }
+ default:
+ // All others
+ KServiceReadProperty ksrp(_name, it.data().toString().utf8());
+ return ksrp.readPropertyEntry(_name, t);
+ }
+}
+
+TQStringList KService::propertyNames() const
+{
+ TQStringList res;
+
+ TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.begin();
+ for( ; it != m_mapProps.end(); ++it )
+ res.append( it.key() );
+
+ res.append( "Type" );
+ res.append( "Name" );
+ res.append( "Comment" );
+ res.append( "GenericName" );
+ res.append( "Icon" );
+ res.append( "Exec" );
+ res.append( "Terminal" );
+ res.append( "TerminalOptions" );
+ res.append( "Path" );
+ res.append( "ServiceTypes" );
+ res.append( "AllowAsDefault" );
+ res.append( "InitialPreference" );
+ res.append( "Library" );
+ res.append( "DesktopEntryPath" );
+ res.append( "DesktopEntryName" );
+ res.append( "Keywords" );
+ res.append( "Categories" );
+
+ return res;
+}
+
+KService::List KService::allServices()
+{
+ return KServiceFactory::self()->allServices();
+}
+
+KService::Ptr KService::serviceByName( const TQString& _name )
+{
+ KService * s = KServiceFactory::self()->findServiceByName( _name );
+ return KService::Ptr( s );
+}
+
+KService::Ptr KService::serviceByDesktopPath( const TQString& _name )
+{
+ KService * s = KServiceFactory::self()->findServiceByDesktopPath( _name );
+ return KService::Ptr( s );
+}
+
+KService::Ptr KService::serviceByDesktopName( const TQString& _name )
+{
+ KService * s = KServiceFactory::self()->findServiceByDesktopName( _name.lower() );
+ if (!s && !_name.startsWith("kde-"))
+ s = KServiceFactory::self()->findServiceByDesktopName( "kde-"+_name.lower() );
+ return KService::Ptr( s );
+}
+
+KService::Ptr KService::serviceByMenuId( const TQString& _name )
+{
+ KService * s = KServiceFactory::self()->findServiceByMenuId( _name );
+ return KService::Ptr( s );
+}
+
+KService::Ptr KService::serviceByStorageId( const TQString& _storageId )
+{
+ KService::Ptr service = KService::serviceByMenuId( _storageId );
+ if (service)
+ return service;
+
+ service = KService::serviceByDesktopPath(_storageId);
+ if (service)
+ return service;
+
+ if (!TQDir::isRelativePath(_storageId) && TQFile::exists(_storageId))
+ return new KService(_storageId);
+
+ TQString tmp = _storageId;
+ tmp = tmp.mid(tmp.findRev('/')+1); // Strip dir
+
+ if (tmp.endsWith(".desktop"))
+ tmp.truncate(tmp.length()-8);
+
+ if (tmp.endsWith(".kdelnk"))
+ tmp.truncate(tmp.length()-7);
+
+ service = KService::serviceByDesktopName(tmp);
+
+ return service;
+}
+
+KService::List KService::allInitServices()
+{
+ return KServiceFactory::self()->allInitServices();
+}
+
+bool KService::substituteUid() const {
+ TQVariant v = property("X-TDE-SubstituteUID", TQVariant::Bool);
+ return v.isValid() && v.toBool();
+}
+
+TQString KService::username() const {
+ // See also KDesktopFile::tryExec()
+ TQString user;
+ TQVariant v = property("X-TDE-Username", TQVariant::String);
+ user = v.isValid() ? v.toString() : TQString::null;
+ if (user.isEmpty())
+ user = ::getenv("ADMIN_ACCOUNT");
+ if (user.isEmpty())
+ user = "root";
+ return user;
+}
+
+bool KService::noDisplay() const {
+ TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( "NoDisplay" );
+ if ( (it != m_mapProps.end()) && (it.data().isValid()))
+ {
+ TQString aValue = it.data().toString().lower();
+ if (aValue == "true" || aValue == "on" || aValue == "yes")
+ return true;
+ }
+
+ it = m_mapProps.find( "OnlyShowIn" );
+ if ( (it != m_mapProps.end()) && (it.data().isValid()))
+ {
+ TQString aValue = it.data().toString();
+ TQStringList aList = TQStringList::split(';', aValue);
+ if ((!aList.contains("TDE")) && (!aList.contains("KDE")))
+ return true;
+ }
+
+ it = m_mapProps.find( "NotShowIn" );
+ if ( (it != m_mapProps.end()) && (it.data().isValid()))
+ {
+ TQString aValue = it.data().toString();
+ TQStringList aList = TQStringList::split(';', aValue);
+ if ((aList.contains("TDE")) || (aList.contains("KDE")))
+ return true;
+ }
+
+ if (!kapp->authorizeControlModule(d->menuId))
+ return true;
+
+ return false;
+}
+
+TQString KService::untranslatedGenericName() const {
+ TQVariant v = property("UntranslatedGenericName", TQVariant::String);
+ return v.isValid() ? v.toString() : TQString::null;
+}
+
+bool KService::SuSEunimportant() const {
+ TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( "X-SuSE-Unimportant" );
+ if ( (it == m_mapProps.end()) || (!it.data().isValid()))
+ {
+ return false;
+ }
+
+ TQString aValue = it.data().toString();
+ if (aValue == "true" || aValue == "on" || aValue == "yes")
+ return true;
+ else
+ return false;
+}
+
+TQString KService::parentApp() const {
+ TQMap<TQString,TQVariant>::ConstIterator it = m_mapProps.find( "X-TDE-ParentApp" );
+ if ( (it == m_mapProps.end()) || (!it.data().isValid()))
+ {
+ return TQString::null;
+ }
+
+ return it.data().toString();
+}
+
+bool KService::allowMultipleFiles() const {
+ // Can we pass multiple files on the command line or do we have to start the application for every single file ?
+ if ( m_strExec.find( "%F" ) != -1 || m_strExec.find( "%U" ) != -1 ||
+ m_strExec.find( "%N" ) != -1 || m_strExec.find( "%D" ) != -1 )
+ return true;
+ else
+ return false;
+}
+
+TQStringList KService::categories() const
+{
+ return d->categories;
+}
+
+TQString KService::menuId() const
+{
+ return d->menuId;
+}
+
+void KService::setMenuId(const TQString &menuId)
+{
+ d->menuId = menuId;
+}
+
+TQString KService::storageId() const
+{
+ if (!d->menuId.isEmpty())
+ return d->menuId;
+ return entryPath();
+}
+
+TQString KService::locateLocal()
+{
+ if (d->menuId.isEmpty() || desktopEntryPath().startsWith(".hidden") ||
+ (TQDir::isRelativePath(desktopEntryPath()) && d->categories.isEmpty()))
+ return KDesktopFile::locateLocal(desktopEntryPath());
+
+ return ::locateLocal("xdgdata-apps", d->menuId);
+}
+
+TQString KService::newServicePath(bool showInMenu, const TQString &suggestedName,
+ TQString *menuId, const TQStringList *reservedMenuIds)
+{
+ TQString base = suggestedName;
+ if (!showInMenu)
+ base.prepend("kde-");
+
+ TQString result;
+ for(int i = 1; true; i++)
+ {
+ if (i == 1)
+ result = base + ".desktop";
+ else
+ result = base + TQString("-%1.desktop").arg(i);
+
+ if (reservedMenuIds && reservedMenuIds->contains(result))
+ continue;
+
+ // Lookup service by menu-id
+ KService::Ptr s = serviceByMenuId(result);
+ if (s)
+ continue;
+
+ if (showInMenu)
+ {
+ if (!locate("xdgdata-apps", result).isEmpty())
+ continue;
+ }
+ else
+ {
+ TQString file = result.mid(4); // Strip "kde-"
+ if (!locate("apps", ".hidden/"+file).isEmpty())
+ continue;
+ }
+
+ break;
+ }
+ if (menuId)
+ *menuId = result;
+
+ if (showInMenu)
+ {
+ return ::locateLocal("xdgdata-apps", result);
+ }
+ else
+ {
+ TQString file = result.mid(4); // Strip "kde-"
+ return ::locateLocal("apps", ".hidden/"+file);
+ }
+}
+
+
+void KService::virtual_hook( int id, void* data )
+{ KSycocaEntry::virtual_hook( id, data ); }
+
+
+void KService::rebuildKSycoca(TQWidget *parent)
+{
+ KServiceProgressDialog dlg(parent, "tdesycoca_progress",
+ i18n("Updating System Configuration"),
+ i18n("Updating system configuration."));
+
+ TQByteArray data;
+ DCOPClient *client = kapp->dcopClient();
+
+ int result = client->callAsync("kded", "tdebuildsycoca", "recreate()",
+ data, TQT_TQOBJECT(&dlg), TQT_SLOT(slotFinished()));
+
+ if (result)
+ {
+ dlg.exec();
+ }
+}
+
+KServiceProgressDialog::KServiceProgressDialog(TQWidget *parent, const char *name,
+ const TQString &caption, const TQString &text)
+ : KProgressDialog(parent, name, caption, text, true)
+{
+ connect(&m_timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotProgress()));
+ progressBar()->setTotalSteps(20);
+ m_timeStep = 700;
+ m_timer.start(m_timeStep);
+ setAutoClose(false);
+}
+
+void
+KServiceProgressDialog::slotProgress()
+{
+ int p = progressBar()->progress();
+ if (p == 18)
+ {
+ progressBar()->reset();
+ progressBar()->setProgress(1);
+ m_timeStep = m_timeStep * 2;
+ m_timer.start(m_timeStep);
+ }
+ else
+ {
+ progressBar()->setProgress(p+1);
+ }
+}
+
+void
+KServiceProgressDialog::slotFinished()
+{
+ progressBar()->setProgress(20);
+ m_timer.stop();
+ TQTimer::singleShot(1000, this, TQT_SLOT(close()));
+}
+
+#include "kservice_p.moc"
diff --git a/kio/kio/kservice.h b/tdeio/tdeio/kservice.h
index 4db478ba6..4db478ba6 100644
--- a/kio/kio/kservice.h
+++ b/tdeio/tdeio/kservice.h
diff --git a/kio/kio/kservice_p.h b/tdeio/tdeio/kservice_p.h
index 180ab8fc3..180ab8fc3 100644
--- a/kio/kio/kservice_p.h
+++ b/tdeio/tdeio/kservice_p.h
diff --git a/kio/kio/kservicefactory.cpp b/tdeio/tdeio/kservicefactory.cpp
index f4646fa75..f4646fa75 100644
--- a/kio/kio/kservicefactory.cpp
+++ b/tdeio/tdeio/kservicefactory.cpp
diff --git a/kio/kio/kservicefactory.h b/tdeio/tdeio/kservicefactory.h
index 4e6df6534..4e6df6534 100644
--- a/kio/kio/kservicefactory.h
+++ b/tdeio/tdeio/kservicefactory.h
diff --git a/kio/kio/kservicegroup.cpp b/tdeio/tdeio/kservicegroup.cpp
index 2e27c99b0..2e27c99b0 100644
--- a/kio/kio/kservicegroup.cpp
+++ b/tdeio/tdeio/kservicegroup.cpp
diff --git a/kio/kio/kservicegroup.h b/tdeio/tdeio/kservicegroup.h
index f2cd5a09f..f2cd5a09f 100644
--- a/kio/kio/kservicegroup.h
+++ b/tdeio/tdeio/kservicegroup.h
diff --git a/kio/kio/kservicegroupfactory.cpp b/tdeio/tdeio/kservicegroupfactory.cpp
index 56ec0c07f..56ec0c07f 100644
--- a/kio/kio/kservicegroupfactory.cpp
+++ b/tdeio/tdeio/kservicegroupfactory.cpp
diff --git a/kio/kio/kservicegroupfactory.h b/tdeio/tdeio/kservicegroupfactory.h
index 77bc7c042..77bc7c042 100644
--- a/kio/kio/kservicegroupfactory.h
+++ b/tdeio/tdeio/kservicegroupfactory.h
diff --git a/kio/kio/kservicetype.cpp b/tdeio/tdeio/kservicetype.cpp
index 8565029ee..8565029ee 100644
--- a/kio/kio/kservicetype.cpp
+++ b/tdeio/tdeio/kservicetype.cpp
diff --git a/kio/kio/kservicetype.h b/tdeio/tdeio/kservicetype.h
index b1cad7284..b1cad7284 100644
--- a/kio/kio/kservicetype.h
+++ b/tdeio/tdeio/kservicetype.h
diff --git a/kio/kio/kservicetypefactory.cpp b/tdeio/tdeio/kservicetypefactory.cpp
index ecf527384..ecf527384 100644
--- a/kio/kio/kservicetypefactory.cpp
+++ b/tdeio/tdeio/kservicetypefactory.cpp
diff --git a/kio/kio/kservicetypefactory.h b/tdeio/tdeio/kservicetypefactory.h
index e18630b2c..e18630b2c 100644
--- a/kio/kio/kservicetypefactory.h
+++ b/tdeio/tdeio/kservicetypefactory.h
diff --git a/kio/kio/kshellcompletion.cpp b/tdeio/tdeio/kshellcompletion.cpp
index 2fb67a31f..2fb67a31f 100644
--- a/kio/kio/kshellcompletion.cpp
+++ b/tdeio/tdeio/kshellcompletion.cpp
diff --git a/kio/kio/kshellcompletion.h b/tdeio/tdeio/kshellcompletion.h
index fa90c509e..fa90c509e 100644
--- a/kio/kio/kshellcompletion.h
+++ b/tdeio/tdeio/kshellcompletion.h
diff --git a/kio/kio/kshred.cpp b/tdeio/tdeio/kshred.cpp
index f3997bf58..f3997bf58 100644
--- a/kio/kio/kshred.cpp
+++ b/tdeio/tdeio/kshred.cpp
diff --git a/tdeio/tdeio/kshred.h b/tdeio/tdeio/kshred.h
new file mode 100644
index 000000000..5fabcaa5b
--- /dev/null
+++ b/tdeio/tdeio/kshred.h
@@ -0,0 +1,156 @@
+/*--------------------------------------------------------------------------*
+ KShred.h Copyright (c) 2000 MieTerra LLC.
+ Credits: Andreas F. Pour <bugs@mieterra.com>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+#ifndef kshred_h
+#define kshred_h
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <tqstring.h>
+#include <tqfile.h>
+#include <tqobject.h>
+
+#include <tdeio/global.h>
+
+/**
+ * @deprecated
+ * Erase a file in a way that makes recovery impossible -- well, no guarentee
+ * of that, but at least as difficult as reasonably possible.
+ * For this, KShred write several times over the
+ * existing file, using different patterns, before deleting it.
+ * @author Andreas F. Pour <bugs@mieterra.com>
+ * @author David Faure <faure@kde.org> (integration into KDE and progress signal)
+ */
+class TDEIO_EXPORT_DEPRECATED KShred : public TQObject { // KDE4: remove
+
+ Q_OBJECT
+
+ public:
+
+ /**
+ * Initialize the class using the name of the file to 'shred'.
+ * @param fileName fully qualified name of the file to shred.
+ */
+ KShred(TQString fileName);
+
+ /*
+ * Destructor for the class.
+ */
+ ~KShred();
+
+ /**
+ * Writes all 1's over the entire file and flushes the file buffers.
+ * @return true on success, false on error (invalid filename or write error)
+ */
+
+ bool fill1s();
+ /**
+ * Writes all 0's over the entire file and flushes the file buffers.
+ * @return true on success, false on error (invalid filename or write error)
+ */
+ bool fill0s();
+
+ /**
+ * Writes the specified byte over the entire file and flushes the file buffers.
+ * @param byte the value to write over every byte of the file
+ * @return true on success, false on error (invalid filename or write error)
+ */
+ bool fillbyte(unsigned int byte);
+
+ /**
+ * Writes random bites over the entire file and flushes the file buffers.
+ * @return true on success, false on error (invalid filename or write error)
+ */
+ bool fillrandom();
+
+ /**
+ * Writes the specified byte array over the entire file and flushes the file buffers.
+ * @param pattern the value to write over the entire file
+ * @param size the length of the 'pattern' byte array
+ * @return true on success, false on error (invalid filename or write error)
+ */
+ bool fillpattern(unsigned char *pattern, unsigned int size);
+
+ /**
+ * Shreds a file by writing a series of values over it (uses
+ * #fill0s, then fill1s, then fillrandom, then
+ * fillbyte with 0101..., then fillbyte with 1010....
+ * @return true on success, false on error (invalid filename or write error)
+ */
+ bool shred();
+
+ /**
+ * The simplest method to shred a file.
+ * No need to create an instance of the class.
+ * @param fileName fully qualified name of the file to shred.
+ */
+ static bool shred(TQString fileName);
+
+ signals:
+ /**
+ * Shows progress of the shredding.
+ * @param bytes the number of bytes written to the file
+ */
+ void processedSize(TDEIO::filesize_t bytes);
+
+ /**
+ * Shows a message in the progress dialog
+ * @param message the message to display
+ */
+ void infoMessage(const TQString & message);
+
+ private:
+ /**
+ * @internal write the data to the file
+ */
+ bool writeData(unsigned char *data, unsigned int size);
+
+ /**
+ * @internal flush the data to the file
+ */
+ bool flush();
+
+ /**
+ * @internal structure for the file information
+ */
+ TQFile *file;
+
+ /**
+ * @internal for the size of the file
+ */
+ TDEIO::filesize_t fileSize;
+
+ /**
+ * @internal for keeping track of progress
+ */
+ unsigned int totalBytes;
+ unsigned int bytesWritten;
+ unsigned int lastSignalled;
+ unsigned int tbpc;
+ unsigned int fspc;
+ private:
+ class KShredPrivate* d;
+};
+
+#endif
diff --git a/kio/kio/ktar.cpp b/tdeio/tdeio/ktar.cpp
index 9bde2873a..9bde2873a 100644
--- a/kio/kio/ktar.cpp
+++ b/tdeio/tdeio/ktar.cpp
diff --git a/kio/kio/ktar.h b/tdeio/tdeio/ktar.h
index fc238073c..fc238073c 100644
--- a/kio/kio/ktar.h
+++ b/tdeio/tdeio/ktar.h
diff --git a/kio/kio/ktrader.cpp b/tdeio/tdeio/ktrader.cpp
index 585c6a499..585c6a499 100644
--- a/kio/kio/ktrader.cpp
+++ b/tdeio/tdeio/ktrader.cpp
diff --git a/tdeio/tdeio/ktrader.h b/tdeio/tdeio/ktrader.h
new file mode 100644
index 000000000..c96a64a21
--- /dev/null
+++ b/tdeio/tdeio/ktrader.h
@@ -0,0 +1,295 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Torben Weis <weis@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __ktrader_h__
+#define __ktrader_h__
+
+#include <tqstring.h>
+#include <tqobject.h>
+#include <kservice.h>
+
+/**
+ * A Trader interface, similar to the CORBA Trader.
+ *
+ * Basically, it provides a way for an application to query
+ * all KDE services (that is, applications and components) that match
+ * a specific set of requirements. This allows you to find an
+ * application in real-time without you having to hard-code the name
+ * and/or path of the application.
+ *
+ * \par Examples
+ *
+ * A few examples will make this a lot more clear.
+ *
+ * Say you have an application that will display HTML. In this
+ * example, you don't want to link to tdehtml... and furthermore, you
+ * really don't care if the HTML browser is ours or not, as long as
+ * it works. The way that you formulate your query as well as the way
+ * that you execute the browser depends on whether or not you want the
+ * browser to run stand-alone or embedded.
+ *
+ * If you want the browser to run standalone, then you will limit the
+ * query to search for all services that handle 'text/html' @em and,
+ * furthermore, they must be applications (Type=Application). You
+ * then will use KRun::run() to invoke the application. In "trader-speak",
+ * this looks like this:
+ * \code
+ * KTrader::OfferList offers = KTrader::self()->query("text/html", "Type == 'Application'");
+ * KService::Ptr ptr = offers.first();
+ * KURL::List lst;
+ * lst.append("http://www.kde.org/index.html");
+ * KRun::run(*ptr, lst);
+ * \endcode
+ *
+ * Now, say that you want to list all KParts component that can handle HTML.
+ * \code
+ * KTrader::OfferList offers = KTrader::self()->query("text/html", "KParts/ReadOnlyPart");
+ * \endcode
+ *
+ * If you want to get the preferred KParts component for text/html you could use
+ * KServiceTypeProfile::preferredService("text/html", "KParts/ReadOnlyPart"), although if this is about
+ * loading that component you would rather use KParts::ComponentFactory directly.
+ *
+ *
+ * Please note that when including property names containing arithmetic operators like - or +, then you have
+ * to put brackets around the property name, in order to correctly separate arithmetic operations from
+ * the name. So for example a constraint expression like
+ * X-TDE-Blah < 4
+ * needs to be written as
+ * [X-TDE-Blah] < 4
+ * otherwise it could also be interpreted as
+ * Substract the numeric value of the property "KDE" and "Blah" from the property "X" and make sure it
+ * is less than 4.
+ * Instead of the other meaning, make sure that the numeric value of "X-TDE-Blah" is less than 4.
+ *
+ * See also the formal syntax defined in @ref tradersyntax .
+ *
+ * @short Provides a way to query the KDE infrastructure for specific
+ * applications or components.
+ * @author Torben Weis <weis@kde.org>
+ */
+class TDEIO_EXPORT KTrader : public TQObject
+{
+ Q_OBJECT
+public:
+ /**
+ * A list of services.
+ */
+ typedef TQValueList<KService::Ptr> OfferList;
+ typedef TQValueListIterator<KService::Ptr> OfferListIterator;
+
+ /**
+ * Standard destructor
+ */
+ virtual ~KTrader();
+
+ /**
+ * The main function in the KTrader class.
+ *
+ * It will return a list of services that match your
+ * specifications. The only required parameter is the service
+ * type. This is something like 'text/plain' or 'text/html'. The
+ * constraint parameter is used to limit the possible choices
+ * returned based on the constraints you give it.
+ *
+ * The @p constraint language is rather full. The most common
+ * keywords are AND, OR, NOT, IN, and EXIST, all used in an
+ * almost spoken-word form. An example is:
+ * \code
+ * (Type == 'Service') and (('KParts/ReadOnlyPart' in ServiceTypes) or (exist Exec))
+ * \endcode
+ *
+ * The keys used in the query (Type, ServiceType, Exec) are all
+ * fields found in the .desktop files.
+ *
+ * @param servicetype A service type like 'text/plain', 'text/html', or 'KOfficePlugin'.
+ * @param constraint A constraint to limit the choices returned, TQString::null to
+ * get all services of the given @p servicetype
+ * @param preferences Indicates a particular preference to return, TQString::null to ignore.
+ * Uses an expression in the constraint language that must return
+ * a number
+ *
+ * @return A list of services that satisfy the query
+ * @see http://developer.kde.org/documentation/library/3.5-api/tdelibs-apidocs/tdeio/tdeio/html/tradersyntax.html
+ */
+ virtual OfferList query( const TQString& servicetype,
+ const TQString& constraint = TQString::null,
+ const TQString& preferences = TQString::null) const;
+
+ /**
+ * A variant of query(), that takes two service types as an input.
+ * It is not exactly the same as adding the second service type
+ * in the constraints of the other query call, because this one
+ * takes into account user preferences for this combination of service types.
+ *
+ * Example usage:
+ * To get list of applications that can handle a given mimetype,
+ * set @p servicetype to the mimetype and @p genericServiceType is "Application".
+ * To get list of embeddable components that can handle a given mimetype,
+ * set @p servicetype to the mimetype and @p genericServiceType is "KParts/ReadOnlyPart".
+ *
+ * @param servicetype A service type like 'text/plain', 'text/html', or 'KOfficePlugin'.
+ * @param genericServiceType a basic service type, like 'KParts/ReadOnlyPart' or 'Application'
+ * @param constraint A constraint to limit the choices returned, TQString::null to
+ * get all services of the given @p servicetype
+ * @param preferences Indicates a particular preference to return, TQString::null to ignore.
+ * Uses an expression in the constraint language that must return
+ * a number
+ *
+ * @return A list of services that satisfy the query
+ * @see http://developer.kde.org/documentation/library/kdeqt/tradersyntax.html
+ */
+ OfferList query( const TQString& servicetype, const TQString& genericServiceType,
+ const TQString& constraint /*= TQString::null*/,
+ const TQString& preferences /*= TQString::null*/) const;
+
+ /**
+ * This is a static pointer to a KTrader instance.
+ *
+ * You will need
+ * to use this to access the KTrader functionality since the
+ * constuctors are protected.
+ *
+ * @return Static KTrader instance
+ */
+ static KTrader* self();
+
+protected:
+ /**
+ * @internal
+ */
+ KTrader();
+
+private:
+ static KTrader* s_self;
+protected:
+ virtual void virtual_hook( int id, void* data );
+};
+
+/** @page tradersyntax Trader Syntax
+ *
+ *
+ * @section Literals
+ *
+ * As elementary atoms of the constraint language, KTrader supports
+ * booleans, integers, floats and strings. Boolean literals are
+ * @a TRUE and @a FALSE . Integers can be positive or negative,
+ * i.e. @a 42 and @a -10 are legal values. Floating point
+ * numbers are @a 3.141592535 or @a -999.999 . Scientific notation
+ * like @a 1.5e-2 is not supported. Character literals are delimited
+ * by single quotation marks, e.g. @a 'Bernd' .
+ *
+ *
+ * @section Symbols
+ *
+ * Identifiers in query string are interpreted as property names, which
+ * are listed in the service's <tt>.desktop</tt> file. For example,
+ * <tt>Name</tt> is the name of the service, <tt>ServiceTypes</tt> is a
+ * list of the service types it supports. Note that only properties can
+ * be written as-is which start with an alphabetical character and contain
+ * only alphanumerical characters. Other properties have to be enclosed in
+ * brackets, e.g. <tt>[X-TDE-Init]</tt>. Properties must not contain any
+ * special characters other than <tt>-</tt>.
+ *
+ * Special property names:
+ * - <b>DesktopEntryName</b> stands for the filename of the service
+ * desktop entry without any extension. This can be useful to
+ * exclude some specific services.
+ * - <b>DesktopEntryPath</b> stands for the relative or full path
+ * to the .desktop file, see KService::desktopEntryPath. Mentionned
+ * here for completeness, better not use it (things can be moved
+ * around).
+ * - <b>Library</b> is the property whose value is set by
+ * <tt>X-TDE-Library</tt> in the .desktop file. This renaming
+ * happened to conform to the desktop file standard, but the
+ * property name didn't change.
+ *
+ *
+ * @section Comparison
+ *
+ * Supported comparison operators are:
+ *
+ * - <tt>==</tt>
+ * - <tt>!=</tt>
+ * - <tt>&lt;</tt>
+ * - <tt>&lt;=</tt>
+ * - <tt>&gt;</tt>
+ * - <tt>&gt;=</tt>
+ *
+ *
+ * @section Arithmetic Arithmetic and boolean expressions
+ *
+ * - <tt>+</tt>
+ * - <tt>-</tt>
+ * - <tt>*</tt>
+ * - <tt>/</tt>
+ * - <tt>and</tt>
+ * - <tt>or</tt>
+ * - <tt>not</tt>
+ *
+ * Note that the arithmetic operators are possible for integers and
+ * floating point numbers. <tt>-</tt> is both a unary and binary operator,
+ * <tt>not</tt> is a unary operator.
+ *
+ *
+ * @section Other Other operators
+ *
+ * - <tt>~</tt>
+ * - <tt>in</tt>
+ * - <tt>exist</tt>
+ * - <tt>()</tt>
+ *
+ * The tilde operator stands for a substring match. For example,
+ * <tt>KParts ~ 'KParts/ReadOnlyPart'</tt> is TRUE. The membership
+ * operator <tt>in</tt> tests whether a value is in a list. A list is a
+ * string with semi-colon- or comma-separated entries, depending on the
+ * type. An example for the membership operator is
+ * <tt>'text/plain' in ServiceTypes</tt>.
+ * The <tt>exist</tt> tests whether a certain property is defined in the
+ * <tt>.desktop</tt> file. Subexpressions are written in parentheses.
+ *
+ * Warning, testing the contents of a property only works if the property
+ * is specified. There is not support for default values. If the property
+ * might be missing, and you still want such services to be included, you
+ * have to check for existence before testing it. For instance, to say
+ * that MyProp is a boolean that defaults to true, and that you want the
+ * services that have it set to true, use:
+ * <tt>not exist MyProp or MyProp</tt>
+ * Simply testing for <tt>MyProp</tt> would
+ * exclude the services without the property at all.
+ *
+ *
+ * @section Examples
+ *
+ * The following examples show filters for .desktop files.
+ * <tt>Type</tt>, <tt>ServiceTypes</tt> and <tt>MimeType</tt> are
+ * properties in .desktop files. Be aware that within KTrader MimeType
+ * properties are understood as ServiceTypes ones.
+ *
+ *
+ * - <tt>Type == 'Application'</tt>@n
+ * All services that are applications.
+ * - <tt>'KParts/ReadOnlyPart' in ServiceTypes</tt>@n
+ * All read-only KParts.
+ * - <tt>('KParts/ReadOnlyPart' in ServiceTypes) and ('text/plain' in ServiceTypes)</tt>@n
+ * All read-only KParts that handle the mime type 'text/plain'.
+ *
+ * @author Bernd Gehrmann <a href="mailto:bernd@tdevelop.org">bernd@tdevelop.org</a>
+*/
+
+
+#endif
diff --git a/kio/kio/ktraderparse.cpp b/tdeio/tdeio/ktraderparse.cpp
index 627791c00..627791c00 100644
--- a/kio/kio/ktraderparse.cpp
+++ b/tdeio/tdeio/ktraderparse.cpp
diff --git a/kio/kio/ktraderparse.h b/tdeio/tdeio/ktraderparse.h
index bfeb15fe0..bfeb15fe0 100644
--- a/kio/kio/ktraderparse.h
+++ b/tdeio/tdeio/ktraderparse.h
diff --git a/kio/kio/ktraderparsetree.cpp b/tdeio/tdeio/ktraderparsetree.cpp
index 0a04b7918..0a04b7918 100644
--- a/kio/kio/ktraderparsetree.cpp
+++ b/tdeio/tdeio/ktraderparsetree.cpp
diff --git a/kio/kio/ktraderparsetree.h b/tdeio/tdeio/ktraderparsetree.h
index a08b61a5a..a08b61a5a 100644
--- a/kio/kio/ktraderparsetree.h
+++ b/tdeio/tdeio/ktraderparsetree.h
diff --git a/kio/kio/kurifilter.cpp b/tdeio/tdeio/kurifilter.cpp
index 5c50f4fa9..5c50f4fa9 100644
--- a/kio/kio/kurifilter.cpp
+++ b/tdeio/tdeio/kurifilter.cpp
diff --git a/kio/kio/kurifilter.h b/tdeio/tdeio/kurifilter.h
index fd7cb9b3c..fd7cb9b3c 100644
--- a/kio/kio/kurifilter.h
+++ b/tdeio/tdeio/kurifilter.h
diff --git a/tdeio/tdeio/kurlcompletion.cpp b/tdeio/tdeio/kurlcompletion.cpp
new file mode 100644
index 000000000..22bbe147a
--- /dev/null
+++ b/tdeio/tdeio/kurlcompletion.cpp
@@ -0,0 +1,1604 @@
+/* -*- indent-tabs-mode: t; tab-width: 4; c-basic-offset:4 -*-
+
+ This file is part of the KDE libraries
+ Copyright (C) 2000 David Smith <dsmith@algonet.se>
+ Copyright (C) 2004 Scott Wheeler <wheeler@kde.org>
+
+ This class was inspired by a previous KURLCompletion by
+ Henner Zeller <zeller@think.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <config.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <limits.h>
+
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqvaluelist.h>
+#include <tqregexp.h>
+#include <tqtimer.h>
+#include <tqdir.h>
+#include <tqfile.h>
+#include <tqtextstream.h>
+#include <tqdeepcopy.h>
+#include <tqthread.h>
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kcompletion.h>
+#include <kurl.h>
+#include <tdeio/jobclasses.h>
+#include <tdeio/job.h>
+#include <kprotocolinfo.h>
+#include <tdeconfig.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kde_file.h>
+
+#include <sys/types.h>
+#include <dirent.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <pwd.h>
+#include <time.h>
+#include <sys/param.h>
+
+#include "kurlcompletion.h"
+
+static bool expandTilde(TQString &);
+static bool expandEnv(TQString &);
+
+static TQString unescape(const TQString &text);
+
+// Permission mask for files that are executable by
+// user, group or other
+#define MODE_EXE (S_IXUSR | S_IXGRP | S_IXOTH)
+
+// Constants for types of completion
+enum ComplType {CTNone=0, CTEnv, CTUser, CTMan, CTExe, CTFile, CTUrl, CTInfo};
+
+class CompletionThread;
+
+/**
+ * A custom event type that is used to return a list of completion
+ * matches from an asyncrynous lookup.
+ */
+
+class CompletionMatchEvent : public TQCustomEvent
+{
+public:
+ CompletionMatchEvent( CompletionThread *thread ) :
+ TQCustomEvent( uniqueType() ),
+ m_completionThread( thread )
+ {}
+
+ CompletionThread *completionThread() const { return m_completionThread; }
+ static int uniqueType() { return User + 61080; }
+
+private:
+ CompletionThread *m_completionThread;
+};
+
+class CompletionThread : public TQThread
+{
+protected:
+ CompletionThread( KURLCompletion *receiver ) :
+ TQThread(),
+ m_receiver( receiver ),
+ m_terminationRequested( false )
+ {}
+
+public:
+ void requestTermination() { m_terminationRequested = true; }
+ TQDeepCopy<TQStringList> matches() const { return m_matches; }
+
+protected:
+ void addMatch( const TQString &match ) { m_matches.append( match ); }
+ bool terminationRequested() const { return m_terminationRequested; }
+ void done()
+ {
+ if ( !m_terminationRequested )
+ kapp->postEvent( m_receiver, new CompletionMatchEvent( this ) );
+ else
+ delete this;
+ }
+
+private:
+ KURLCompletion *m_receiver;
+ TQStringList m_matches;
+ bool m_terminationRequested;
+};
+
+/**
+ * A simple thread that fetches a list of tilde-completions and returns this
+ * to the caller via a CompletionMatchEvent.
+ */
+
+class UserListThread : public CompletionThread
+{
+public:
+ UserListThread( KURLCompletion *receiver ) :
+ CompletionThread( receiver )
+ {}
+
+protected:
+ virtual void run()
+ {
+ static const TQChar tilde = '~';
+
+ struct passwd *pw;
+ while ( ( pw = ::getpwent() ) && !terminationRequested() )
+ addMatch( tilde + TQString::fromLocal8Bit( pw->pw_name ) );
+
+ ::endpwent();
+
+ addMatch( tilde );
+
+ done();
+ }
+};
+
+class DirectoryListThread : public CompletionThread
+{
+public:
+ DirectoryListThread( KURLCompletion *receiver,
+ const TQStringList &dirList,
+ const TQString &filter,
+ bool onlyExe,
+ bool onlyDir,
+ bool noHidden,
+ bool appendSlashToDir ) :
+ CompletionThread( receiver ),
+ m_dirList( TQDeepCopy<TQStringList>( dirList ) ),
+ m_filter( TQDeepCopy<TQString>( filter ) ),
+ m_onlyExe( onlyExe ),
+ m_onlyDir( onlyDir ),
+ m_noHidden( noHidden ),
+ m_appendSlashToDir( appendSlashToDir )
+ {}
+
+ virtual void run();
+
+private:
+ TQStringList m_dirList;
+ TQString m_filter;
+ bool m_onlyExe;
+ bool m_onlyDir;
+ bool m_noHidden;
+ bool m_appendSlashToDir;
+};
+
+void DirectoryListThread::run()
+{
+ // Thread safety notes:
+ //
+ // There very possibly may be thread safety issues here, but I've done a check
+ // of all of the things that would seem to be problematic. Here are a few
+ // things that I have checked to be safe here (some used indirectly):
+ //
+ // TQDir::currentDirPath(), TQDir::setCurrent(), TQFile::decodeName(), TQFile::encodeName()
+ // TQString::fromLocal8Bit(), TQString::local8Bit(), TQTextCodec::codecForLocale()
+ //
+ // Also see (for POSIX functions):
+ // http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_09.html
+
+ DIR *dir = 0;
+
+ for ( TQStringList::ConstIterator it = m_dirList.begin();
+ it != m_dirList.end() && !terminationRequested();
+ ++it )
+ {
+ // Open the next directory
+
+ if ( !dir ) {
+ dir = ::opendir( TQFile::encodeName( *it ) );
+ if ( ! dir ) {
+ kdDebug() << "Failed to open dir: " << *it << endl;
+ done();
+ return;
+ }
+ }
+
+ // A trick from KIO that helps performance by a little bit:
+ // chdir to the directroy so we won't have to deal with full paths
+ // with stat()
+
+ TQString path = TQDir::currentDirPath();
+ TQDir::setCurrent( *it );
+
+ // Loop through all directory entries
+ // Solaris and IRIX dirent structures do not allocate space for d_name. On
+ // systems that do (HP-UX, Linux, Tru64 UNIX), we overallocate space but
+ // that's ok.
+#ifndef HAVE_READDIR_R
+ struct dirent *dirEntry = 0;
+ while ( !terminationRequested() &&
+ (dirEntry = ::readdir( dir)))
+#else
+#if !defined(MAXPATHLEN) && defined(__GNU__)
+#define MAXPATHLEN UCHAR_MAX
+#endif
+ struct dirent *dirPosition = (struct dirent *) malloc( sizeof( struct dirent ) + MAXPATHLEN + 1 );
+ struct dirent *dirEntry = 0;
+ while ( !terminationRequested() &&
+ ::readdir_r( dir, dirPosition, &dirEntry ) == 0 && dirEntry )
+#endif
+
+ {
+ // Skip hidden files if m_noHidden is true
+
+ if ( dirEntry->d_name[0] == '.' && m_noHidden )
+ continue;
+
+ // Skip "."
+
+ if ( dirEntry->d_name[0] == '.' && dirEntry->d_name[1] == '\0' )
+ continue;
+
+ // Skip ".."
+
+ if ( dirEntry->d_name[0] == '.' && dirEntry->d_name[1] == '.' && dirEntry->d_name[2] == '\0' )
+ continue;
+
+ TQString file = TQFile::decodeName( dirEntry->d_name );
+
+ if ( m_filter.isEmpty() || file.startsWith( m_filter ) ) {
+
+ if ( m_onlyExe || m_onlyDir || m_appendSlashToDir ) {
+ KDE_struct_stat sbuff;
+
+ if ( KDE_stat( dirEntry->d_name, &sbuff ) == 0 ) {
+
+ // Verify executable
+
+ if ( m_onlyExe && ( sbuff.st_mode & MODE_EXE ) == 0 )
+ continue;
+
+ // Verify directory
+
+ if ( m_onlyDir && !S_ISDIR( sbuff.st_mode ) )
+ continue;
+
+ // Add '/' to directories
+
+ if ( m_appendSlashToDir && S_ISDIR( sbuff.st_mode ) )
+ file.append( '/' );
+
+ }
+ else {
+ kdDebug() << "Could not stat file " << file << endl;
+ continue;
+ }
+ }
+
+ addMatch( file );
+ }
+ }
+
+ // chdir to the original directory
+
+ TQDir::setCurrent( path );
+
+ ::closedir( dir );
+ dir = 0;
+#ifdef HAVE_READDIR_R
+ free( dirPosition );
+#endif
+ }
+
+ done();
+}
+
+///////////////////////////////////////////////////////
+///////////////////////////////////////////////////////
+// MyURL - wrapper for KURL with some different functionality
+//
+
+class KURLCompletion::MyURL
+{
+public:
+ MyURL(const TQString &url, const TQString &cwd);
+ MyURL(const MyURL &url);
+ ~MyURL();
+
+ KURL *kurl() const { return m_kurl; }
+
+ TQString protocol() const { return m_kurl->protocol(); }
+ // The directory with a trailing '/'
+ TQString dir() const { return m_kurl->directory(false, false); }
+ TQString file() const { return m_kurl->fileName(false); }
+
+ // The initial, unparsed, url, as a string.
+ TQString url() const { return m_url; }
+
+ // Is the initial string a URL, or just a path (whether absolute or relative)
+ bool isURL() const { return m_isURL; }
+
+ void filter( bool replace_user_dir, bool replace_env );
+
+private:
+ void init(const TQString &url, const TQString &cwd);
+
+ KURL *m_kurl;
+ TQString m_url;
+ bool m_isURL;
+};
+
+KURLCompletion::MyURL::MyURL(const TQString &url, const TQString &cwd)
+{
+ init(url, cwd);
+}
+
+KURLCompletion::MyURL::MyURL(const MyURL &url)
+{
+ m_kurl = new KURL( *(url.m_kurl) );
+ m_url = url.m_url;
+ m_isURL = url.m_isURL;
+}
+
+void KURLCompletion::MyURL::init(const TQString &url, const TQString &cwd)
+{
+ // Save the original text
+ m_url = url;
+
+ // Non-const copy
+ TQString url_copy = url;
+
+ // Special shortcuts for "man:" and "info:"
+ if ( url_copy[0] == '#' ) {
+ if ( url_copy[1] == '#' )
+ url_copy.replace( 0, 2, TQString("info:") );
+ else
+ url_copy.replace( 0, 1, TQString("man:") );
+ }
+
+ // Look for a protocol in 'url'
+ TQRegExp protocol_regex = TQRegExp( "^[^/\\s\\\\]*:" );
+
+ // Assume "file:" or whatever is given by 'cwd' if there is
+ // no protocol. (KURL does this only for absoute paths)
+ if ( protocol_regex.search( url_copy ) == 0 )
+ {
+ m_kurl = new KURL( url_copy );
+ m_isURL = true;
+ }
+ else // relative path or ~ or $something
+ {
+ m_isURL = false;
+ if ( cwd.isEmpty() )
+ {
+ m_kurl = new KURL();
+ if ( !TQDir::isRelativePath(url_copy) || url_copy[0] == '$' || url_copy[0] == '~' )
+ m_kurl->setPath( url_copy );
+ else
+ *m_kurl = url_copy;
+ }
+ else
+ {
+ KURL base = KURL::fromPathOrURL( cwd );
+ base.adjustPath(+1);
+
+ if ( !TQDir::isRelativePath(url_copy) || url_copy[0] == '~' || url_copy[0] == '$' )
+ {
+ m_kurl = new KURL();
+ m_kurl->setPath( url_copy );
+ }
+ else // relative path
+ {
+ //m_kurl = new KURL( base, url_copy );
+ m_kurl = new KURL( base );
+ m_kurl->addPath( url_copy );
+ }
+ }
+ }
+}
+
+KURLCompletion::MyURL::~MyURL()
+{
+ delete m_kurl;
+}
+
+void KURLCompletion::MyURL::filter( bool replace_user_dir, bool replace_env )
+{
+ TQString d = dir() + file();
+ if ( replace_user_dir ) expandTilde( d );
+ if ( replace_env ) expandEnv( d );
+ m_kurl->setPath( d );
+}
+
+///////////////////////////////////////////////////////
+///////////////////////////////////////////////////////
+// KURLCompletionPrivate
+//
+class KURLCompletionPrivate
+{
+public:
+ KURLCompletionPrivate() : url_auto_completion(true),
+ userListThread(0),
+ dirListThread(0) {}
+ ~KURLCompletionPrivate();
+
+ TQValueList<KURL*> list_urls;
+
+ bool onlyLocalProto;
+
+ // urlCompletion() in Auto/Popup mode?
+ bool url_auto_completion;
+
+ // Append '/' to directories in Popup mode?
+ // Doing that stat's all files and is slower
+ bool popup_append_slash;
+
+ // Keep track of currently listed files to avoid reading them again
+ TQString last_path_listed;
+ TQString last_file_listed;
+ TQString last_prepend;
+ int last_compl_type;
+ int last_no_hidden;
+
+ TQString cwd; // "current directory" = base dir for completion
+
+ KURLCompletion::Mode mode; // ExeCompletion, FileCompletion, DirCompletion
+ bool replace_env;
+ bool replace_home;
+ bool complete_url; // if true completing a URL (i.e. 'prepend' is a URL), otherwise a path
+
+ TDEIO::ListJob *list_job; // kio job to list directories
+
+ TQString prepend; // text to prepend to listed items
+ TQString compl_text; // text to pass on to KCompletion
+
+ // Filters for files read with kio
+ bool list_urls_only_exe; // true = only list executables
+ bool list_urls_no_hidden;
+ TQString list_urls_filter; // filter for listed files
+
+ CompletionThread *userListThread;
+ CompletionThread *dirListThread;
+};
+
+KURLCompletionPrivate::~KURLCompletionPrivate()
+{
+ if ( userListThread )
+ userListThread->requestTermination();
+ if ( dirListThread )
+ dirListThread->requestTermination();
+}
+
+///////////////////////////////////////////////////////
+///////////////////////////////////////////////////////
+// KURLCompletion
+//
+
+KURLCompletion::KURLCompletion() : KCompletion()
+{
+ init();
+}
+
+
+KURLCompletion::KURLCompletion( Mode mode ) : KCompletion()
+{
+ init();
+ setMode ( mode );
+}
+
+KURLCompletion::~KURLCompletion()
+{
+ stop();
+ delete d;
+}
+
+
+void KURLCompletion::init()
+{
+ d = new KURLCompletionPrivate;
+
+ d->cwd = TQDir::homeDirPath();
+
+ d->replace_home = true;
+ d->replace_env = true;
+ d->last_no_hidden = false;
+ d->last_compl_type = 0;
+ d->list_job = 0L;
+ d->mode = KURLCompletion::FileCompletion;
+
+ // Read settings
+ TDEConfig *c = TDEGlobal::config();
+ TDEConfigGroupSaver cgs( c, "URLCompletion" );
+
+ d->url_auto_completion = c->readBoolEntry("alwaysAutoComplete", true);
+ d->popup_append_slash = c->readBoolEntry("popupAppendSlash", true);
+ d->onlyLocalProto = c->readBoolEntry("LocalProtocolsOnly", false);
+}
+
+void KURLCompletion::setDir(const TQString &dir)
+{
+ d->cwd = dir;
+}
+
+TQString KURLCompletion::dir() const
+{
+ return d->cwd;
+}
+
+KURLCompletion::Mode KURLCompletion::mode() const
+{
+ return d->mode;
+}
+
+void KURLCompletion::setMode( Mode mode )
+{
+ d->mode = mode;
+}
+
+bool KURLCompletion::replaceEnv() const
+{
+ return d->replace_env;
+}
+
+void KURLCompletion::setReplaceEnv( bool replace )
+{
+ d->replace_env = replace;
+}
+
+bool KURLCompletion::replaceHome() const
+{
+ return d->replace_home;
+}
+
+void KURLCompletion::setReplaceHome( bool replace )
+{
+ d->replace_home = replace;
+}
+
+/*
+ * makeCompletion()
+ *
+ * Entry point for file name completion
+ */
+TQString KURLCompletion::makeCompletion(const TQString &text)
+{
+ //kdDebug() << "KURLCompletion::makeCompletion: " << text << " d->cwd=" << d->cwd << endl;
+
+ MyURL url(text, d->cwd);
+
+ d->compl_text = text;
+
+ // Set d->prepend to the original URL, with the filename [and ref/query] stripped.
+ // This is what gets prepended to the directory-listing matches.
+ int toRemove = url.file().length() - url.kurl()->query().length();
+ if ( url.kurl()->hasRef() )
+ toRemove += url.kurl()->ref().length() + 1;
+ d->prepend = text.left( text.length() - toRemove );
+ d->complete_url = url.isURL();
+
+ TQString match;
+
+ // Environment variables
+ //
+ if ( d->replace_env && envCompletion( url, &match ) )
+ return match;
+
+ // User directories
+ //
+ if ( d->replace_home && userCompletion( url, &match ) )
+ return match;
+
+ // Replace user directories and variables
+ url.filter( d->replace_home, d->replace_env );
+
+ //kdDebug() << "Filtered: proto=" << url.protocol()
+ // << ", dir=" << url.dir()
+ // << ", file=" << url.file()
+ // << ", kurl url=" << *url.kurl() << endl;
+
+ if ( d->mode == ExeCompletion ) {
+ // Executables
+ //
+ if ( exeCompletion( url, &match ) )
+ return match;
+
+ // KRun can run "man:" and "info:" etc. so why not treat them
+ // as executables...
+
+ if ( urlCompletion( url, &match ) )
+ return match;
+ }
+ else if ( d->mode == SystemExeCompletion ) {
+ // Executables
+ //
+ if ( systemexeCompletion( url, &match ) )
+ return match;
+
+ // KRun can run "man:" and "info:" etc. so why not treat them
+ // as executables...
+
+ if ( urlCompletion( url, &match ) )
+ return match;
+ }
+ else {
+ // Local files, directories
+ //
+ if ( fileCompletion( url, &match ) )
+ return match;
+
+ // All other...
+ //
+ if ( urlCompletion( url, &match ) )
+ return match;
+ }
+
+ setListedURL( CTNone );
+ stop();
+
+ return TQString::null;
+}
+
+/*
+ * finished
+ *
+ * Go on and call KCompletion.
+ * Called when all matches have been added
+ */
+TQString KURLCompletion::finished()
+{
+ if ( d->last_compl_type == CTInfo )
+ return KCompletion::makeCompletion( d->compl_text.lower() );
+ else
+ return KCompletion::makeCompletion( d->compl_text );
+}
+
+/*
+ * isRunning
+ *
+ * Return true if either a KIO job or the DirLister
+ * is running
+ */
+bool KURLCompletion::isRunning() const
+{
+ return d->list_job || (d->dirListThread && !d->dirListThread->finished());
+}
+
+/*
+ * stop
+ *
+ * Stop and delete a running KIO job or the DirLister
+ */
+void KURLCompletion::stop()
+{
+ if ( d->list_job ) {
+ d->list_job->kill();
+ d->list_job = 0L;
+ }
+
+ if ( !d->list_urls.isEmpty() ) {
+ TQValueList<KURL*>::Iterator it = d->list_urls.begin();
+ for ( ; it != d->list_urls.end(); it++ )
+ delete (*it);
+ d->list_urls.clear();
+ }
+
+ if ( d->dirListThread ) {
+ d->dirListThread->requestTermination();
+ d->dirListThread = 0;
+ }
+}
+
+/*
+ * Keep track of the last listed directory
+ */
+void KURLCompletion::setListedURL( int complType,
+ const TQString& dir,
+ const TQString& filter,
+ bool no_hidden )
+{
+ d->last_compl_type = complType;
+ d->last_path_listed = dir;
+ d->last_file_listed = filter;
+ d->last_no_hidden = (int)no_hidden;
+ d->last_prepend = d->prepend;
+}
+
+bool KURLCompletion::isListedURL( int complType,
+ const TQString& dir,
+ const TQString& filter,
+ bool no_hidden )
+{
+ return d->last_compl_type == complType
+ && ( d->last_path_listed == dir
+ || (dir.isEmpty() && d->last_path_listed.isEmpty()) )
+ && ( filter.startsWith(d->last_file_listed)
+ || (filter.isEmpty() && d->last_file_listed.isEmpty()) )
+ && d->last_no_hidden == (int)no_hidden
+ && d->last_prepend == d->prepend; // e.g. relative path vs absolute
+}
+
+/*
+ * isAutoCompletion
+ *
+ * Returns true if completion mode is Auto or Popup
+ */
+bool KURLCompletion::isAutoCompletion()
+{
+ return completionMode() == TDEGlobalSettings::CompletionAuto
+ || completionMode() == TDEGlobalSettings::CompletionPopup
+ || completionMode() == TDEGlobalSettings::CompletionMan
+ || completionMode() == TDEGlobalSettings::CompletionPopupAuto;
+}
+//////////////////////////////////////////////////
+//////////////////////////////////////////////////
+// User directories
+//
+
+bool KURLCompletion::userCompletion(const MyURL &url, TQString *match)
+{
+ if ( url.protocol() != "file"
+ || !url.dir().isEmpty()
+ || url.file().at(0) != '~' )
+ return false;
+
+ if ( !isListedURL( CTUser ) ) {
+ stop();
+ clear();
+
+ if ( !d->userListThread ) {
+ d->userListThread = new UserListThread( this );
+ d->userListThread->start();
+
+ // If the thread finishes quickly make sure that the results
+ // are added to the first matching case.
+
+ d->userListThread->wait( 200 );
+ TQStringList l = d->userListThread->matches();
+ addMatches( l );
+ }
+ }
+ *match = finished();
+ return true;
+}
+
+/////////////////////////////////////////////////////
+/////////////////////////////////////////////////////
+// Environment variables
+//
+
+extern char **environ; // Array of environment variables
+
+bool KURLCompletion::envCompletion(const MyURL &url, TQString *match)
+{
+ if ( url.file().at(0) != '$' )
+ return false;
+
+ if ( !isListedURL( CTEnv ) ) {
+ stop();
+ clear();
+
+ char **env = environ;
+
+ TQString dollar = TQString("$");
+
+ TQStringList l;
+
+ while ( *env ) {
+ TQString s = TQString::fromLocal8Bit( *env );
+
+ int pos = s.find('=');
+
+ if ( pos == -1 )
+ pos = s.length();
+
+ if ( pos > 0 )
+ l.append( dollar + s.left(pos) );
+
+ env++;
+ }
+
+ addMatches( l );
+ }
+
+ setListedURL( CTEnv );
+
+ *match = finished();
+ return true;
+}
+
+//////////////////////////////////////////////////
+//////////////////////////////////////////////////
+// Executables
+//
+
+bool KURLCompletion::exeCompletion(const MyURL &url, TQString *match)
+{
+ if ( url.protocol() != "file" )
+ return false;
+
+ TQString dir = url.dir();
+
+ dir = unescape( dir ); // remove escapes
+
+ // Find directories to search for completions, either
+ //
+ // 1. complete path given in url
+ // 2. current directory (d->cwd)
+ // 3. $PATH
+ // 4. no directory at all
+
+ TQStringList dirList;
+
+ if ( !TQDir::isRelativePath(dir) ) {
+ // complete path in url
+ dirList.append( dir );
+ }
+ else if ( !dir.isEmpty() && !d->cwd.isEmpty() ) {
+ // current directory
+ dirList.append( d->cwd + '/' + dir );
+ }
+ else if ( !url.file().isEmpty() ) {
+ // $PATH
+ dirList = TQStringList::split(KPATH_SEPARATOR,
+ TQString::fromLocal8Bit(::getenv("PATH")));
+
+ TQStringList::Iterator it = dirList.begin();
+
+ for ( ; it != dirList.end(); it++ )
+ (*it).append('/');
+ }
+
+ // No hidden files unless the user types "."
+ bool no_hidden_files = url.file().at(0) != '.';
+
+ // List files if needed
+ //
+ if ( !isListedURL( CTExe, dir, url.file(), no_hidden_files ) )
+ {
+ stop();
+ clear();
+
+ setListedURL( CTExe, dir, url.file(), no_hidden_files );
+
+ *match = listDirectories( dirList, url.file(), true, false, no_hidden_files );
+ }
+ else if ( !isRunning() ) {
+ *match = finished();
+ }
+ else {
+ if ( d->dirListThread )
+ setListedURL( CTExe, dir, url.file(), no_hidden_files );
+ *match = TQString::null;
+ }
+
+ return true;
+}
+
+//////////////////////////////////////////////////
+//////////////////////////////////////////////////
+// System Executables
+//
+
+bool KURLCompletion::systemexeCompletion(const MyURL &url, TQString *match)
+{
+ if ( url.protocol() != "file" )
+ return false;
+
+ TQString dir = url.dir();
+
+ dir = unescape( dir ); // remove escapes
+
+ // Find directories to search for completions, either
+ //
+ // 1. complete path given in url
+ // 2. current directory (d->cwd)
+ // 3. $PATH
+ // 4. no directory at all
+
+ TQStringList dirList;
+
+ if ( !url.file().isEmpty() ) {
+ // $PATH
+ dirList = TQStringList::split(KPATH_SEPARATOR,
+ TQString::fromLocal8Bit(::getenv("PATH")));
+
+ TQStringList::Iterator it = dirList.begin();
+
+ for ( ; it != dirList.end(); it++ )
+ (*it).append('/');
+ }
+
+ // No hidden files unless the user types "."
+ bool no_hidden_files = url.file().at(0) != '.';
+
+ // List files if needed
+ //
+ if ( !isListedURL( CTExe, dir, url.file(), no_hidden_files ) )
+ {
+ stop();
+ clear();
+
+ setListedURL( CTExe, dir, url.file(), no_hidden_files );
+
+ *match = listDirectories( dirList, url.file(), true, false, no_hidden_files );
+ }
+ else if ( !isRunning() ) {
+ *match = finished();
+ }
+ else {
+ if ( d->dirListThread )
+ setListedURL( CTExe, dir, url.file(), no_hidden_files );
+ *match = TQString::null;
+ }
+
+ return true;
+}
+
+//////////////////////////////////////////////////
+//////////////////////////////////////////////////
+// Local files
+//
+
+bool KURLCompletion::fileCompletion(const MyURL &url, TQString *match)
+{
+ if ( url.protocol() != "file" )
+ return false;
+
+ TQString dir = url.dir();
+
+ if (url.url()[0] == '.')
+ {
+ if (url.url().length() == 1)
+ {
+ *match =
+ ( completionMode() == TDEGlobalSettings::CompletionMan )? "." : "..";
+ return true;
+ }
+ if (url.url().length() == 2 && url.url()[1]=='.')
+ {
+ *match="..";
+ return true;
+ }
+ }
+
+ //kdDebug() << "fileCompletion " << url.url() << " dir=" << dir << endl;
+
+ dir = unescape( dir ); // remove escapes
+
+ // Find directories to search for completions, either
+ //
+ // 1. complete path given in url
+ // 2. current directory (d->cwd)
+ // 3. no directory at all
+
+ TQStringList dirList;
+
+ if ( !TQDir::isRelativePath(dir) ) {
+ // complete path in url
+ dirList.append( dir );
+ }
+ else if ( !d->cwd.isEmpty() ) {
+ // current directory
+ dirList.append( d->cwd + '/' + dir );
+ }
+
+ // No hidden files unless the user types "."
+ bool no_hidden_files = ( url.file().at(0) != '.' );
+
+ // List files if needed
+ //
+ if ( !isListedURL( CTFile, dir, "", no_hidden_files ) )
+ {
+ stop();
+ clear();
+
+ setListedURL( CTFile, dir, "", no_hidden_files );
+
+ // Append '/' to directories in Popup mode?
+ bool append_slash = ( d->popup_append_slash
+ && (completionMode() == TDEGlobalSettings::CompletionPopup ||
+ completionMode() == TDEGlobalSettings::CompletionPopupAuto ) );
+
+ bool only_dir = ( d->mode == DirCompletion );
+
+ *match = listDirectories( dirList, "", false, only_dir, no_hidden_files,
+ append_slash );
+ }
+ else if ( !isRunning() ) {
+ *match = finished();
+ }
+ else {
+ *match = TQString::null;
+ }
+
+ return true;
+}
+
+//////////////////////////////////////////////////
+//////////////////////////////////////////////////
+// URLs not handled elsewhere...
+//
+
+bool KURLCompletion::urlCompletion(const MyURL &url, TQString *match)
+{
+ //kdDebug() << "urlCompletion: url = " << *url.kurl() << endl;
+ if (d->onlyLocalProto && KProtocolInfo::protocolClass(url.protocol()) != ":local")
+ return false;
+
+ // Use d->cwd as base url in case url is not absolute
+ KURL url_cwd = KURL::fromPathOrURL( d->cwd );
+
+ // Create an URL with the directory to be listed
+ KURL url_dir( url_cwd, url.kurl()->url() );
+
+ // Don't try url completion if
+ // 1. malformed url
+ // 2. protocol that doesn't have listDir()
+ // 3. there is no directory (e.g. "ftp://ftp.kd" shouldn't do anything)
+ // 4. auto or popup completion mode depending on settings
+
+ bool man_or_info = ( url_dir.protocol() == TQString("man")
+ || url_dir.protocol() == TQString("info") );
+
+ if ( !url_dir.isValid()
+ || !KProtocolInfo::supportsListing( url_dir )
+ || ( !man_or_info
+ && ( url_dir.directory(false,false).isEmpty()
+ || ( isAutoCompletion()
+ && !d->url_auto_completion ) ) ) ) {
+ return false;
+ }
+
+ url_dir.setFileName(""); // not really nesseccary, but clear the filename anyway...
+
+ // Remove escapes
+ TQString dir = url_dir.directory( false, false );
+
+ dir = unescape( dir );
+
+ url_dir.setPath( dir );
+
+ // List files if needed
+ //
+ if ( !isListedURL( CTUrl, url_dir.prettyURL(), url.file() ) )
+ {
+ stop();
+ clear();
+
+ setListedURL( CTUrl, url_dir.prettyURL(), "" );
+
+ TQValueList<KURL*> url_list;
+ url_list.append( new KURL( url_dir ) );
+
+ listURLs( url_list, "", false );
+
+ *match = TQString::null;
+ }
+ else if ( !isRunning() ) {
+ *match = finished();
+ }
+ else {
+ *match = TQString::null;
+ }
+
+ return true;
+}
+
+//////////////////////////////////////////////////
+//////////////////////////////////////////////////
+// Directory and URL listing
+//
+
+/*
+ * addMatches
+ *
+ * Called to add matches to KCompletion
+ */
+void KURLCompletion::addMatches( const TQStringList &matches )
+{
+ TQStringList::ConstIterator it = matches.begin();
+ TQStringList::ConstIterator end = matches.end();
+
+ if ( d->complete_url )
+ for ( ; it != end; it++ )
+ addItem( d->prepend + KURL::encode_string(*it));
+ else
+ for ( ; it != end; it++ )
+ addItem( d->prepend + (*it));
+}
+
+/*
+ * listDirectories
+ *
+ * List files starting with 'filter' in the given directories,
+ * either using DirLister or listURLs()
+ *
+ * In either case, addMatches() is called with the listed
+ * files, and eventually finished() when the listing is done
+ *
+ * Returns the match if available, or TQString::null if
+ * DirLister timed out or using kio
+ */
+TQString KURLCompletion::listDirectories(
+ const TQStringList &dirList,
+ const TQString &filter,
+ bool only_exe,
+ bool only_dir,
+ bool no_hidden,
+ bool append_slash_to_dir)
+{
+ assert( !isRunning() );
+
+ if ( !::getenv("KURLCOMPLETION_LOCAL_KIO") ) {
+
+ //kdDebug() << "Listing (listDirectories): " << dirList << " filter=" << filter << " without KIO" << endl;
+
+ // Don't use KIO
+
+ if ( d->dirListThread )
+ d->dirListThread->requestTermination();
+
+ TQStringList dirs;
+
+ for ( TQStringList::ConstIterator it = dirList.begin();
+ it != dirList.end();
+ ++it )
+ {
+ KURL url;
+ url.setPath(*it);
+ if ( kapp->authorizeURLAction( "list", KURL(), url ) )
+ dirs.append( *it );
+ }
+
+ d->dirListThread = new DirectoryListThread( this, dirs, filter, only_exe, only_dir,
+ no_hidden, append_slash_to_dir );
+ d->dirListThread->start();
+ d->dirListThread->wait( 200 );
+ addMatches( d->dirListThread->matches() );
+
+ return finished();
+ }
+ else {
+
+ // Use KIO
+ //kdDebug() << "Listing (listDirectories): " << dirList << " with KIO" << endl;
+
+ TQValueList<KURL*> url_list;
+
+ TQStringList::ConstIterator it = dirList.begin();
+
+ for ( ; it != dirList.end(); it++ )
+ url_list.append( new KURL(*it) );
+
+ listURLs( url_list, filter, only_exe, no_hidden );
+ // Will call addMatches() and finished()
+
+ return TQString::null;
+ }
+}
+
+/*
+ * listURLs
+ *
+ * Use KIO to list the given urls
+ *
+ * addMatches() is called with the listed files
+ * finished() is called when the listing is done
+ */
+void KURLCompletion::listURLs(
+ const TQValueList<KURL *> &urls,
+ const TQString &filter,
+ bool only_exe,
+ bool no_hidden )
+{
+ assert( d->list_urls.isEmpty() );
+ assert( d->list_job == 0L );
+
+ d->list_urls = urls;
+ d->list_urls_filter = filter;
+ d->list_urls_only_exe = only_exe;
+ d->list_urls_no_hidden = no_hidden;
+
+// kdDebug() << "Listing URLs: " << urls[0]->prettyURL() << ",..." << endl;
+
+ // Start it off by calling slotIOFinished
+ //
+ // This will start a new list job as long as there
+ // are urls in d->list_urls
+ //
+ slotIOFinished(0L);
+}
+
+/*
+ * slotEntries
+ *
+ * Receive files listed by KIO and call addMatches()
+ */
+void KURLCompletion::slotEntries(TDEIO::Job*, const TDEIO::UDSEntryList& entries)
+{
+ TQStringList matches;
+
+ TDEIO::UDSEntryListConstIterator it = entries.begin();
+ TDEIO::UDSEntryListConstIterator end = entries.end();
+
+ TQString filter = d->list_urls_filter;
+
+ int filter_len = filter.length();
+
+ // Iterate over all files
+ //
+ for (; it != end; ++it) {
+ TQString name;
+ TQString url;
+ bool is_exe = false;
+ bool is_dir = false;
+
+ TDEIO::UDSEntry e = *it;
+ TDEIO::UDSEntry::ConstIterator it_2 = e.begin();
+
+ for( ; it_2 != e.end(); it_2++ ) {
+ switch ( (*it_2).m_uds ) {
+ case TDEIO::UDS_NAME:
+ name = (*it_2).m_str;
+ break;
+ case TDEIO::UDS_ACCESS:
+ is_exe = ((*it_2).m_long & MODE_EXE) != 0;
+ break;
+ case TDEIO::UDS_FILE_TYPE:
+ is_dir = ((*it_2).m_long & S_IFDIR) != 0;
+ break;
+ case TDEIO::UDS_URL:
+ url = (*it_2).m_str;
+ break;
+ }
+ }
+
+ if (!url.isEmpty()) {
+ // kdDebug() << "KURLCompletion::slotEntries url: " << url << endl;
+ name = KURL(url).fileName();
+ }
+
+ // kdDebug() << "KURLCompletion::slotEntries name: " << name << endl;
+
+ if ( name[0] == '.' &&
+ ( d->list_urls_no_hidden ||
+ name.length() == 1 ||
+ ( name.length() == 2 && name[1] == '.' ) ) )
+ continue;
+
+ if ( d->mode == DirCompletion && !is_dir )
+ continue;
+
+ if ( filter_len == 0 || name.left(filter_len) == filter ) {
+ if ( is_dir )
+ name.append( '/' );
+
+ if ( is_exe || !d->list_urls_only_exe )
+ matches.append( name );
+ }
+ }
+
+ addMatches( matches );
+}
+
+/*
+ * slotIOFinished
+ *
+ * Called when a KIO job is finished.
+ *
+ * Start a new list job if there are still urls in
+ * d->list_urls, otherwise call finished()
+ */
+void KURLCompletion::slotIOFinished( TDEIO::Job * job )
+{
+// kdDebug() << "slotIOFinished() " << endl;
+
+ assert( job == d->list_job );
+
+ if ( d->list_urls.isEmpty() ) {
+
+ d->list_job = 0L;
+
+ finished(); // will call KCompletion::makeCompletion()
+
+ }
+ else {
+
+ KURL *kurl = d->list_urls.first();
+
+ d->list_urls.remove( kurl );
+
+// kdDebug() << "Start KIO: " << kurl->prettyURL() << endl;
+
+ d->list_job = TDEIO::listDir( *kurl, false );
+ d->list_job->addMetaData("no-auth-prompt", "true");
+
+ assert( d->list_job );
+
+ connect( d->list_job,
+ TQT_SIGNAL(result(TDEIO::Job*)),
+ TQT_SLOT(slotIOFinished(TDEIO::Job*)) );
+
+ connect( d->list_job,
+ TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
+ TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList&)) );
+
+ delete kurl;
+ }
+}
+
+///////////////////////////////////////////////////
+///////////////////////////////////////////////////
+
+/*
+ * postProcessMatch, postProcessMatches
+ *
+ * Called by KCompletion before emitting match() and matches()
+ *
+ * Append '/' to directories for file completion. This is
+ * done here to avoid stat()'ing a lot of files
+ */
+void KURLCompletion::postProcessMatch( TQString *match ) const
+{
+// kdDebug() << "KURLCompletion::postProcess: " << *match << endl;
+
+ if ( !match->isEmpty() ) {
+
+ // Add '/' to directories in file completion mode
+ // unless it has already been done
+ if ( d->last_compl_type == CTFile )
+ adjustMatch( *match );
+ }
+}
+
+void KURLCompletion::adjustMatch( TQString& match ) const
+{
+ if ( match.at( match.length()-1 ) != '/' )
+ {
+ TQString copy;
+
+ if ( match.startsWith( TQString("file:") ) )
+ copy = KURL(match).path();
+ else
+ copy = match;
+
+ expandTilde( copy );
+ expandEnv( copy );
+ if ( TQDir::isRelativePath(copy) )
+ copy.prepend( d->cwd + '/' );
+
+// kdDebug() << "postProcess: stating " << copy << endl;
+
+ KDE_struct_stat sbuff;
+
+ TQCString file = TQFile::encodeName( copy );
+
+ if ( KDE_stat( (const char*)file, &sbuff ) == 0 ) {
+ if ( S_ISDIR ( sbuff.st_mode ) )
+ match.append( '/' );
+ }
+ else {
+ kdDebug() << "Could not stat file " << copy << endl;
+ }
+ }
+}
+
+void KURLCompletion::postProcessMatches( TQStringList * matches ) const
+{
+ if ( !matches->isEmpty() && d->last_compl_type == CTFile ) {
+ TQStringList::Iterator it = matches->begin();
+ for (; it != matches->end(); ++it ) {
+ adjustMatch( (*it) );
+ }
+ }
+}
+
+void KURLCompletion::postProcessMatches( KCompletionMatches * matches ) const
+{
+ if ( !matches->isEmpty() && d->last_compl_type == CTFile ) {
+ KCompletionMatches::Iterator it = matches->begin();
+ for (; it != matches->end(); ++it ) {
+ adjustMatch( (*it).value() );
+ }
+ }
+}
+
+void KURLCompletion::customEvent(TQCustomEvent *e)
+{
+ if ( e->type() == CompletionMatchEvent::uniqueType() ) {
+
+ CompletionMatchEvent *event = static_cast<CompletionMatchEvent *>( e );
+
+ event->completionThread()->wait();
+
+ if ( !isListedURL( CTUser ) ) {
+ stop();
+ clear();
+ addMatches( event->completionThread()->matches() );
+ }
+
+ setListedURL( CTUser );
+
+ if ( d->userListThread == event->completionThread() )
+ d->userListThread = 0;
+
+ if ( d->dirListThread == event->completionThread() )
+ d->dirListThread = 0;
+
+ delete event->completionThread();
+ }
+}
+
+// static
+TQString KURLCompletion::replacedPath( const TQString& text, bool replaceHome, bool replaceEnv )
+{
+ if ( text.isEmpty() )
+ return text;
+
+ MyURL url( text, TQString::null ); // no need to replace something of our current cwd
+ if ( !url.kurl()->isLocalFile() )
+ return text;
+
+ url.filter( replaceHome, replaceEnv );
+ return url.dir() + url.file();
+}
+
+
+TQString KURLCompletion::replacedPath( const TQString& text )
+{
+ return replacedPath( text, d->replace_home, d->replace_env );
+}
+
+/////////////////////////////////////////////////////////
+/////////////////////////////////////////////////////////
+// Static functions
+
+/*
+ * expandEnv
+ *
+ * Expand environment variables in text. Escaped '$' are ignored.
+ * Return true if expansion was made.
+ */
+static bool expandEnv( TQString &text )
+{
+ // Find all environment variables beginning with '$'
+ //
+ int pos = 0;
+
+ bool expanded = false;
+
+ while ( (pos = text.find('$', pos)) != -1 ) {
+
+ // Skip escaped '$'
+ //
+ if ( text[pos-1] == '\\' ) {
+ pos++;
+ }
+ // Variable found => expand
+ //
+ else {
+ // Find the end of the variable = next '/' or ' '
+ //
+ int pos2 = text.find( ' ', pos+1 );
+ int pos_tmp = text.find( '/', pos+1 );
+
+ if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) )
+ pos2 = pos_tmp;
+
+ if ( pos2 == -1 )
+ pos2 = text.length();
+
+ // Replace if the variable is terminated by '/' or ' '
+ // and defined
+ //
+ if ( pos2 >= 0 ) {
+ int len = pos2 - pos;
+ TQString key = text.mid( pos+1, len-1);
+ TQString value =
+ TQString::fromLocal8Bit( ::getenv(key.local8Bit()) );
+
+ if ( !value.isEmpty() ) {
+ expanded = true;
+ text.replace( pos, len, value );
+ pos = pos + value.length();
+ }
+ else {
+ pos = pos2;
+ }
+ }
+ }
+ }
+
+ return expanded;
+}
+
+/*
+ * expandTilde
+ *
+ * Replace "~user" with the users home directory
+ * Return true if expansion was made.
+ */
+static bool expandTilde(TQString &text)
+{
+ if ( text[0] != '~' )
+ return false;
+
+ bool expanded = false;
+
+ // Find the end of the user name = next '/' or ' '
+ //
+ int pos2 = text.find( ' ', 1 );
+ int pos_tmp = text.find( '/', 1 );
+
+ if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) )
+ pos2 = pos_tmp;
+
+ if ( pos2 == -1 )
+ pos2 = text.length();
+
+ // Replace ~user if the user name is terminated by '/' or ' '
+ //
+ if ( pos2 >= 0 ) {
+
+ TQString user = text.mid( 1, pos2-1 );
+ TQString dir;
+
+ // A single ~ is replaced with $HOME
+ //
+ if ( user.isEmpty() ) {
+ dir = TQDir::homeDirPath();
+ }
+ // ~user is replaced with the dir from passwd
+ //
+ else {
+ struct passwd *pw = ::getpwnam( user.local8Bit() );
+
+ if ( pw )
+ dir = TQFile::decodeName( pw->pw_dir );
+
+ ::endpwent();
+ }
+
+ if ( !dir.isEmpty() ) {
+ expanded = true;
+ text.replace(0, pos2, dir);
+ }
+ }
+
+ return expanded;
+}
+
+/*
+ * unescape
+ *
+ * Remove escapes and return the result in a new string
+ *
+ */
+static TQString unescape(const TQString &text)
+{
+ TQString result;
+
+ for (uint pos = 0; pos < text.length(); pos++)
+ if ( text[pos] != '\\' )
+ result.insert( result.length(), text[pos] );
+
+ return result;
+}
+
+void KURLCompletion::virtual_hook( int id, void* data )
+{ KCompletion::virtual_hook( id, data ); }
+
+#include "kurlcompletion.moc"
+
diff --git a/tdeio/tdeio/kurlcompletion.h b/tdeio/tdeio/kurlcompletion.h
new file mode 100644
index 000000000..30a825d3d
--- /dev/null
+++ b/tdeio/tdeio/kurlcompletion.h
@@ -0,0 +1,236 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Smith <dsmith@algonet.se>
+
+ This class was inspired by a previous KURLCompletion by
+ Henner Zeller <zeller@think.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef KURLCOMPLETION_H
+#define KURLCOMPLETION_H
+
+#include <kcompletion.h>
+#include <tdeio/jobclasses.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+
+class KURL;
+class KURLCompletionPrivate;
+
+/**
+ * This class does completion of URLs including user directories (~user)
+ * and environment variables. Remote URLs are passed to KIO.
+ *
+ * @short Completion of a single URL
+ * @author David Smith <dsmith@algonet.se>
+ */
+class TDEIO_EXPORT KURLCompletion : public KCompletion
+{
+ Q_OBJECT
+
+public:
+ /**
+ * Determines how completion is done.
+ * @li ExeCompletion - executables in $PATH or with full path.
+ * @li FileCompletion - all files with full path or in dir(), URLs
+ * are listed using KIO.
+ * @li DirCompletion - Same as FileCompletion but only returns directories.
+ */
+ enum Mode { ExeCompletion=1, FileCompletion, DirCompletion, SystemExeCompletion };
+
+ /**
+ * Constructs a KURLCompletion object in FileCompletion mode.
+ */
+ KURLCompletion();
+ /**
+ * This overloaded constructor allows you to set the Mode to ExeCompletion
+ * or FileCompletion without using setMode. Default is FileCompletion.
+ */
+ KURLCompletion(Mode);
+ /**
+ * Destructs the KURLCompletion object.
+ */
+ virtual ~KURLCompletion();
+
+ /**
+ * Finds completions to the given text.
+ *
+ * Remote URLs are listed with KIO. For performance reasons, local files
+ * are listed with KIO only if KURLCOMPLETION_LOCAL_KIO is set.
+ * The completion is done asyncronously if KIO is used.
+ *
+ * Returns the first match for user, environment, and local dir completion
+ * and TQString::null for asynchronous completion (KIO or threaded).
+ *
+ * @param text the text to complete
+ * @return the first match, or TQString::null if not found
+ */
+ virtual TQString makeCompletion(const TQString &text); // KDE4: remove return value, it's often null due to threading
+
+ /**
+ * Sets the current directory (used as base for completion).
+ * Default = $HOME.
+ * @param dir the current directory, either as a path or URL
+ */
+ virtual void setDir(const TQString &dir);
+
+ /**
+ * Returns the current directory, as it was given in setDir
+ * @return the current directory (path or URL)
+ */
+ virtual TQString dir() const;
+
+ /**
+ * Check whether asynchronous completion is in progress.
+ * @return true if asynchronous completion is in progress
+ */
+ virtual bool isRunning() const;
+
+ /**
+ * Stops asynchronous completion.
+ */
+ virtual void stop();
+
+ /**
+ * Returns the completion mode: exe or file completion (default FileCompletion).
+ * @return the completion mode
+ */
+ virtual Mode mode() const;
+
+ /**
+ * Changes the completion mode: exe or file completion
+ * @param mode the new completion mode
+ */
+ virtual void setMode( Mode mode );
+
+ /**
+ * Checks whether environment variables are completed and
+ * whether they are replaced internally while finding completions.
+ * Default is enabled.
+ * @return true if environment vvariables will be replaced
+ */
+ virtual bool replaceEnv() const;
+
+ /**
+ * Enables/disables completion and replacement (internally) of
+ * environment variables in URLs. Default is enabled.
+ * @param replace true to replace environment variables
+ */
+ virtual void setReplaceEnv( bool replace );
+
+ /**
+ * Returns whether ~username is completed and whether ~username
+ * is replaced internally with the user's home directory while
+ * finding completions. Default is enabled.
+ * @return true to replace tilde with the home directory
+ */
+ virtual bool replaceHome() const;
+
+ /**
+ * Enables/disables completion of ~username and replacement
+ * (internally) of ~username with the user's home directory.
+ * Default is enabled.
+ * @param replace true to replace tilde with the home directory
+ */
+ virtual void setReplaceHome( bool replace );
+
+ /**
+ * Replaces username and/or environment variables, depending on the
+ * current settings and returns the filtered url. Only works with
+ * local files, i.e. returns back the original string for non-local
+ * urls.
+ * @param text the text to process
+ * @return the path or URL resulting from this operation. If you
+ * want to convert it to a KURL, use KURL::fromPathOrURL.
+ */
+ TQString replacedPath( const TQString& text );
+
+ /**
+ * @internal I'll let ossi add a real one to KShell :)
+ * @since 3.2
+ */
+ static TQString replacedPath( const TQString& text,
+ bool replaceHome, bool replaceEnv = true );
+
+ class MyURL;
+protected:
+ // Called by KCompletion, adds '/' to directories
+ void postProcessMatch( TQString *match ) const;
+ void postProcessMatches( TQStringList *matches ) const;
+ void postProcessMatches( KCompletionMatches* matches ) const;
+
+ virtual void customEvent( TQCustomEvent *e );
+
+protected slots:
+ void slotEntries( TDEIO::Job *, const TDEIO::UDSEntryList& );
+ void slotIOFinished( TDEIO::Job * );
+
+private:
+
+ bool isAutoCompletion();
+
+ bool userCompletion(const MyURL &url, TQString *match);
+ bool envCompletion(const MyURL &url, TQString *match);
+ bool exeCompletion(const MyURL &url, TQString *match);
+ bool systemexeCompletion(const MyURL &url, TQString *match);
+ bool fileCompletion(const MyURL &url, TQString *match);
+ bool urlCompletion(const MyURL &url, TQString *match);
+
+ // List a directory using readdir()
+ void listDir( const TQString& dir,
+ TQStringList *matches,
+ const TQString& filter,
+ bool only_exe,
+ bool no_hidden );
+
+ // List the next dir in m_dirs
+ TQString listDirectories(const TQStringList &,
+ const TQString &,
+ bool only_exe = false,
+ bool only_dir = false,
+ bool no_hidden = false,
+ bool stat_files = true);
+
+ void listURLs( const TQValueList<KURL *> &urls,
+ const TQString &filter = TQString::null,
+ bool only_exe = false,
+ bool no_hidden = false );
+
+ void addMatches( const TQStringList & );
+ TQString finished();
+
+ void init();
+
+ void setListedURL(int compl_type /* enum ComplType */,
+ const TQString& dir = TQString::null,
+ const TQString& filter = TQString::null,
+ bool no_hidden = false );
+
+ bool isListedURL( int compl_type /* enum ComplType */,
+ const TQString& dir = TQString::null,
+ const TQString& filter = TQString::null,
+ bool no_hidden = false );
+
+ void adjustMatch( TQString& match ) const;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ KURLCompletionPrivate *d;
+};
+
+#endif // KURLCOMPLETION_H
diff --git a/kio/kio/kurlpixmapprovider.cpp b/tdeio/tdeio/kurlpixmapprovider.cpp
index caeedf066..caeedf066 100644
--- a/kio/kio/kurlpixmapprovider.cpp
+++ b/tdeio/tdeio/kurlpixmapprovider.cpp
diff --git a/kio/kio/kurlpixmapprovider.h b/tdeio/tdeio/kurlpixmapprovider.h
index 82be4bd1b..82be4bd1b 100644
--- a/kio/kio/kurlpixmapprovider.h
+++ b/tdeio/tdeio/kurlpixmapprovider.h
diff --git a/tdeio/tdeio/kuserprofile.cpp b/tdeio/tdeio/kuserprofile.cpp
new file mode 100644
index 000000000..ebd8b8deb
--- /dev/null
+++ b/tdeio/tdeio/kuserprofile.cpp
@@ -0,0 +1,355 @@
+/* This file is part of the KDE libraries
+ * Copyright (C) 1999 Torben Weis <weis@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#include "kuserprofile.h"
+#include "kservice.h"
+#include "kservicetype.h"
+#include "kservicetypefactory.h"
+
+#include <tdeconfig.h>
+#include <kapplication.h>
+#include <kglobal.h>
+#include <kdebug.h>
+#include <kstaticdeleter.h>
+
+#include <tqtl.h>
+
+template class TQPtrList<KServiceTypeProfile>;
+typedef TQPtrList<KServiceTypeProfile> KServiceTypeProfileList;
+
+/*********************************************
+ *
+ * KServiceTypeProfile
+ *
+ *********************************************/
+
+KServiceTypeProfileList* KServiceTypeProfile::s_lstProfiles = 0L;
+static KStaticDeleter< KServiceTypeProfileList > profileDeleter;
+bool KServiceTypeProfile::s_configurationMode = false;
+
+void KServiceTypeProfile::initStatic()
+{
+ if ( s_lstProfiles )
+ return;
+
+ // Make sure that a KServiceTypeFactory gets created.
+ (void) KServiceTypeFactory::self();
+
+ profileDeleter.setObject(s_lstProfiles, new KServiceTypeProfileList);
+ s_lstProfiles->setAutoDelete( true );
+
+ TDEConfig config( "profilerc", true, false);
+
+ static const TQString & defaultGroup = TDEGlobal::staticQString("<default>");
+
+ TQStringList tmpList = config.groupList();
+ for (TQStringList::Iterator aIt = tmpList.begin();
+ aIt != tmpList.end(); ++aIt) {
+ if ( *aIt == defaultGroup )
+ continue;
+
+ config.setGroup( *aIt );
+
+ TQString appId = config.readEntry( "Application" );
+
+ KService::Ptr pService = KService::serviceByStorageId(appId);
+
+ if ( pService ) {
+ TQString application = pService->storageId();
+ TQString type = config.readEntry( "ServiceType" );
+ TQString type2 = config.readEntry( "GenericServiceType" );
+ if (type2.isEmpty()) // compat code
+ type2 = (pService->type() == "Application") ? "Application" : "KParts/ReadOnlyPart";
+ int pref = config.readNumEntry( "Preference" );
+
+ if ( !type.isEmpty() /* && pref >= 0*/ ) // Don't test for pref here. We want those in the list, to mark them as forbidden
+ {
+ KServiceTypeProfile* p =
+ KServiceTypeProfile::serviceTypeProfile( type, type2 );
+
+ if ( !p ) {
+ p = new KServiceTypeProfile( type, type2 );
+ s_lstProfiles->append( p );
+ }
+
+ bool allow = config.readBoolEntry( "AllowAsDefault" );
+ //kdDebug(7014) << "KServiceTypeProfile::initStatic adding service " << application << " to profile for " << type << "," << type2 << " with preference " << pref << endl;
+ p->addService( application, pref, allow );
+ }
+ }
+ }
+}
+
+//static
+void KServiceTypeProfile::clear()
+{
+ // HACK tdesycoca may open the dummy db, in such case the first call to tdesycoca
+ // in initStatic() leads to closing the dummy db and clear() being called
+ // in the middle of it, making s_lstProfiles be NULL
+ if( s_lstProfiles == NULL || s_lstProfiles->count() == 0 )
+ return;
+ profileDeleter.destructObject();
+}
+
+//static
+KServiceTypeProfile::OfferList KServiceTypeProfile::offers( const TQString& _servicetype, const TQString& _genericServiceType )
+{
+ OfferList offers;
+ TQStringList serviceList;
+ //kdDebug(7014) << "KServiceTypeProfile::offers( " << _servicetype << "," << _genericServiceType << " )" << endl;
+
+ // Note that KServiceTypeProfile::offers() calls KServiceType::offers(),
+ // so we _do_ get the new services, that are available but not in the profile.
+ if ( _genericServiceType.isEmpty() )
+ {
+ initStatic();
+ // We want all profiles for servicetype, if we have profiles.
+ // ## Slow loop, if profilerc is big. We should use a map instead?
+ TQPtrListIterator<KServiceTypeProfile> it( *s_lstProfiles );
+ for( ; it.current(); ++it )
+ if ( it.current()->m_strServiceType == _servicetype )
+ {
+ offers += it.current()->offers();
+ }
+ //kdDebug(7014) << "Found profile: " << offers.count() << " offers" << endl;
+ }
+ else
+ {
+ KServiceTypeProfile* profile = serviceTypeProfile( _servicetype, _genericServiceType );
+ if ( profile )
+ {
+ //kdDebug(7014) << "Found profile: " << profile->offers().count() << " offers" << endl;
+ offers += profile->offers();
+ }
+ else
+ {
+ // Try the other way round, order is not like size, it doesn't matter.
+ profile = serviceTypeProfile( _genericServiceType, _servicetype );
+ if ( profile )
+ {
+ //kdDebug(7014) << "Found profile after switching: " << profile->offers().count() << " offers" << endl;
+ offers += profile->offers();
+ }
+ }
+ }
+
+ // Collect services, to make the next loop faster
+ OfferList::Iterator itOffers = offers.begin();
+ for( ; itOffers != offers.end(); ++itOffers )
+ serviceList += (*itOffers).service()->desktopEntryPath(); // this should identify each service uniquely
+ //kdDebug(7014) << "serviceList: " << serviceList.join(",") << endl;
+
+ // Now complete with any other offers that aren't in the profile
+ // This can be because the services have been installed after the profile was written,
+ // but it's also the case for any service that's neither App nor ReadOnlyPart, e.g. RenameDlg/Plugin
+ KService::List list = KServiceType::offers( _servicetype );
+ //kdDebug(7014) << "Using KServiceType::offers, result: " << list.count() << " offers" << endl;
+ TQValueListIterator<KService::Ptr> it = list.begin();
+ for( ; it != list.end(); ++it )
+ {
+ if (_genericServiceType.isEmpty() /*no constraint*/ || (*it)->hasServiceType( _genericServiceType ))
+ {
+ // Check that we don't already have it ;)
+ if ( serviceList.find( (*it)->desktopEntryPath() ) == serviceList.end() )
+ {
+ bool allow = (*it)->allowAsDefault();
+ KServiceOffer o( (*it), (*it)->initialPreferenceForMimeType(_servicetype), allow );
+ offers.append( o );
+ //kdDebug(7014) << "Appending offer " << (*it)->name() << " initial preference=" << (*it)->initialPreference() << " allow-as-default=" << allow << endl;
+ }
+ //else
+ // kdDebug(7014) << "Already having offer " << (*it)->name() << endl;
+ }
+ }
+
+ qBubbleSort( offers );
+
+#if 0
+ // debug code, comment if you wish but don't remove.
+ kdDebug(7014) << "Sorted list:" << endl;
+ OfferList::Iterator itOff = offers.begin();
+ for( ; itOff != offers.end(); ++itOff )
+ kdDebug(7014) << (*itOff).service()->name() << " allow-as-default=" << (*itOff).allowAsDefault() << endl;
+#endif
+
+ //kdDebug(7014) << "Returning " << offers.count() << " offers" << endl;
+ return offers;
+}
+
+KServiceTypeProfile::KServiceTypeProfile( const TQString& _servicetype, const TQString& _genericServiceType )
+{
+ initStatic();
+
+ m_strServiceType = _servicetype;
+ m_strGenericServiceType = _genericServiceType;
+}
+
+KServiceTypeProfile::~KServiceTypeProfile()
+{
+}
+
+void KServiceTypeProfile::addService( const TQString& _service,
+ int _preference, bool _allow_as_default )
+{
+ m_mapServices[ _service ].m_iPreference = _preference;
+ m_mapServices[ _service ].m_bAllowAsDefault = _allow_as_default;
+}
+
+int KServiceTypeProfile::preference( const TQString& _service ) const
+{
+ KService::Ptr service = KService::serviceByName( _service );
+ if (!service)
+ return 0;
+ TQMap<TQString,Service>::ConstIterator it = m_mapServices.find( service->storageId() );
+ if ( it == m_mapServices.end() )
+ return 0;
+
+ return it.data().m_iPreference;
+}
+
+bool KServiceTypeProfile::allowAsDefault( const TQString& _service ) const
+{
+ KService::Ptr service = KService::serviceByName( _service );
+ if (!service)
+ return false;
+
+ // Does the service itself not allow that ?
+ if ( !service->allowAsDefault() )
+ return false;
+
+ // Look what the user says ...
+ TQMap<TQString,Service>::ConstIterator it = m_mapServices.find( service->storageId() );
+ if ( it == m_mapServices.end() )
+ return 0;
+
+ return it.data().m_bAllowAsDefault;
+}
+
+KServiceTypeProfile* KServiceTypeProfile::serviceTypeProfile( const TQString& _servicetype, const TQString& _genericServiceType )
+{
+ initStatic();
+ static const TQString& app_str = TDEGlobal::staticQString("Application");
+
+ const TQString &_genservicetype = ((!_genericServiceType.isEmpty()) ? _genericServiceType : app_str);
+
+ TQPtrListIterator<KServiceTypeProfile> it( *s_lstProfiles );
+ for( ; it.current(); ++it )
+ if (( it.current()->m_strServiceType == _servicetype ) &&
+ ( it.current()->m_strGenericServiceType == _genservicetype))
+ return it.current();
+
+ return 0;
+}
+
+
+KServiceTypeProfile::OfferList KServiceTypeProfile::offers() const
+{
+ OfferList offers;
+
+ kdDebug(7014) << "KServiceTypeProfile::offers serviceType=" << m_strServiceType << " genericServiceType=" << m_strGenericServiceType << endl;
+ KService::List list = KServiceType::offers( m_strServiceType );
+ TQValueListIterator<KService::Ptr> it = list.begin();
+ for( ; it != list.end(); ++it )
+ {
+ //kdDebug(7014) << "KServiceTypeProfile::offers considering " << (*it)->name() << endl;
+ if ( m_strGenericServiceType.isEmpty() || (*it)->hasServiceType( m_strGenericServiceType ) )
+ {
+ // Now look into the profile, to find this service's preference.
+ TQMap<TQString,Service>::ConstIterator it2 = m_mapServices.find( (*it)->storageId() );
+
+ if( it2 != m_mapServices.end() )
+ {
+ //kdDebug(7014) << "found in mapServices pref=" << it2.data().m_iPreference << endl;
+ if ( it2.data().m_iPreference > 0 ) {
+ bool allow = (*it)->allowAsDefault();
+ if ( allow )
+ allow = it2.data().m_bAllowAsDefault;
+ KServiceOffer o( (*it), it2.data().m_iPreference, allow );
+ offers.append( o );
+ }
+ }
+ else
+ {
+ //kdDebug(7014) << "not found in mapServices. Appending." << endl;
+ // We use 0 as the preference to ensure new apps don't take over existing apps (which default to 1)
+ KServiceOffer o( (*it), 0, (*it)->allowAsDefault() );
+ offers.append( o );
+ }
+ }/* else
+ kdDebug(7014) << "Doesn't have " << m_strGenericServiceType << endl;*/
+ }
+
+ qBubbleSort( offers );
+
+ //kdDebug(7014) << "KServiceTypeProfile::offers returning " << offers.count() << " offers" << endl;
+ return offers;
+}
+
+KService::Ptr KServiceTypeProfile::preferredService( const TQString & _serviceType, const TQString & _genericServiceType )
+{
+ OfferList lst = offers( _serviceType, _genericServiceType );
+
+ OfferList::Iterator itOff = lst.begin();
+ // Look for the first one that is allowed as default.
+ // Since the allowed-as-default are first anyway, we only have
+ // to look at the first one to know.
+ if( itOff != lst.end() && (*itOff).allowAsDefault() )
+ return (*itOff).service();
+
+ //kdDebug(7014) << "No offers, or none allowed as default" << endl;
+ return 0L;
+}
+
+/*********************************************
+ *
+ * KServiceOffer
+ *
+ *********************************************/
+
+KServiceOffer::KServiceOffer()
+{
+ m_iPreference = -1;
+}
+
+KServiceOffer::KServiceOffer( const KServiceOffer& _o )
+{
+ m_pService = _o.m_pService;
+ m_iPreference = _o.m_iPreference;
+ m_bAllowAsDefault = _o.m_bAllowAsDefault;
+}
+
+KServiceOffer::KServiceOffer( KService::Ptr _service, int _pref, bool _default )
+{
+ m_pService = _service;
+ m_iPreference = _pref;
+ m_bAllowAsDefault = _default;
+}
+
+
+bool KServiceOffer::operator< ( const KServiceOffer& _o ) const
+{
+ // Put offers allowed as default FIRST.
+ if ( _o.m_bAllowAsDefault && !m_bAllowAsDefault )
+ return false; // _o is default and not 'this'.
+ if ( !_o.m_bAllowAsDefault && m_bAllowAsDefault )
+ return true; // 'this' is default but not _o.
+ // Both offers are allowed or not allowed as default
+ // -> use preferences to sort them
+ // The bigger the better, but we want the better FIRST
+ return _o.m_iPreference < m_iPreference;
+}
diff --git a/kio/kio/kuserprofile.h b/tdeio/tdeio/kuserprofile.h
index 45b58fe6a..45b58fe6a 100644
--- a/kio/kio/kuserprofile.h
+++ b/tdeio/tdeio/kuserprofile.h
diff --git a/tdeio/tdeio/kzip.cpp b/tdeio/tdeio/kzip.cpp
new file mode 100644
index 000000000..85dcb76d1
--- /dev/null
+++ b/tdeio/tdeio/kzip.cpp
@@ -0,0 +1,1460 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ Copyright (C) 2002 Holger Schroeder <holger-kde@holgis.net>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+/*
+ This class implements a tdeioslave to access ZIP files from KDE.
+ you can use it in IO_ReadOnly or in IO_WriteOnly mode, and it
+ behaves just as expected (i hope ;-) ).
+ It can also be used in IO_ReadWrite mode, in this case one can
+ append files to an existing zip archive. when you append new files, which
+ are not yet in the zip, it works as expected, they are appended at the end.
+ when you append a file, which is already in the file, the reference to the
+ old file is dropped and the new one is added to the zip. but the
+ old data from the file itself is not deleted, it is still in the
+ zipfile. so when you want to have a small and garbagefree zipfile,
+ just read the contents of the appended zipfile and write it to a new one
+ in IO_WriteOnly mode. especially take care of this, when you don't want
+ to leak information of how intermediate versions of files in the zip
+ were looking.
+ For more information on the zip fileformat go to
+ http://www.pkware.com/support/appnote.html .
+
+*/
+
+#include "kzip.h"
+#include "kfilterdev.h"
+#include "klimitediodevice.h"
+#include <kmimetype.h>
+#include <ksavefile.h>
+#include <kdebug.h>
+
+#include <tqasciidict.h>
+#include <tqfile.h>
+#include <tqdir.h>
+#include <tqdatetime.h>
+#include <tqptrlist.h>
+
+#include <zlib.h>
+#include <time.h>
+#include <string.h>
+
+const int max_path_len = 4095; // maximum number of character a path may contain
+
+static void transformToMsDos(const TQDateTime& dt, char* buffer)
+{
+ if ( dt.isValid() )
+ {
+ const TQ_UINT16 time =
+ ( dt.time().hour() << 11 ) // 5 bit hour
+ | ( dt.time().minute() << 5 ) // 6 bit minute
+ | ( dt.time().second() >> 1 ); // 5 bit double seconds
+
+ buffer[0] = char(time);
+ buffer[1] = char(time >> 8);
+
+ const TQ_UINT16 date =
+ ( ( dt.date().year() - 1980 ) << 9 ) // 7 bit year 1980-based
+ | ( dt.date().month() << 5 ) // 4 bit month
+ | ( dt.date().day() ); // 5 bit day
+
+ buffer[2] = char(date);
+ buffer[3] = char(date >> 8);
+ }
+ else // !dt.isValid(), assume 1980-01-01 midnight
+ {
+ buffer[0] = 0;
+ buffer[1] = 0;
+ buffer[2] = 33;
+ buffer[3] = 0;
+ }
+}
+
+static time_t transformFromMsDos(const char* buffer)
+{
+ TQ_UINT16 time = (uchar)buffer[0] | ( (uchar)buffer[1] << 8 );
+ int h = time >> 11;
+ int m = ( time & 0x7ff ) >> 5;
+ int s = ( time & 0x1f ) * 2 ;
+ TQTime qt(h, m, s);
+
+ TQ_UINT16 date = (uchar)buffer[2] | ( (uchar)buffer[3] << 8 );
+ int y = ( date >> 9 ) + 1980;
+ int o = ( date & 0x1ff ) >> 5;
+ int d = ( date & 0x1f );
+ TQDate qd(y, o, d);
+
+ TQDateTime dt( qd, qt );
+ return dt.toTime_t();
+}
+
+// == parsing routines for zip headers
+
+/** all relevant information about parsing file information */
+struct ParseFileInfo {
+ // file related info
+// TQCString name; // filename
+ mode_t perm; // permissions of this file
+ time_t atime; // last access time (UNIX format)
+ time_t mtime; // modification time (UNIX format)
+ time_t ctime; // creation time (UNIX format)
+ int uid; // user id (-1 if not specified)
+ int gid; // group id (-1 if not specified)
+ TQCString guessed_symlink; // guessed symlink target
+ int extralen; // length of extra field
+
+ // parsing related info
+ bool exttimestamp_seen; // true if extended timestamp extra field
+ // has been parsed
+ bool newinfounix_seen; // true if Info-ZIP Unix New extra field has
+ // been parsed
+
+ ParseFileInfo() : perm(0100644), uid(-1), gid(-1), extralen(0),
+ exttimestamp_seen(false), newinfounix_seen(false) {
+ ctime = mtime = atime = time(0);
+ }
+};
+
+/** updates the parse information with the given extended timestamp extra field.
+ * @param buffer start content of buffer known to contain an extended
+ * timestamp extra field (without magic & size)
+ * @param size size of field content (must not count magic and size entries)
+ * @param islocal true if this is a local field, false if central
+ * @param pfi ParseFileInfo object to be updated
+ * @return true if processing was successful
+ */
+static bool parseExtTimestamp(const char *buffer, int size, bool islocal,
+ ParseFileInfo &pfi) {
+ if (size < 1) {
+ kdDebug(7040) << "premature end of extended timestamp (#1)" << endl;
+ return false;
+ }/*end if*/
+ int flags = *buffer; // read flags
+ buffer += 1;
+ size -= 1;
+
+ if (flags & 1) { // contains modification time
+ if (size < 4) {
+ kdDebug(7040) << "premature end of extended timestamp (#2)" << endl;
+ return false;
+ }/*end if*/
+ pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
+ | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
+ buffer += 4;
+ size -= 4;
+ }/*end if*/
+ // central extended field cannot contain more than the modification time
+ // even if other flags are set
+ if (!islocal) {
+ pfi.exttimestamp_seen = true;
+ return true;
+ }/*end if*/
+
+ if (flags & 2) { // contains last access time
+ if (size < 4) {
+ kdDebug(7040) << "premature end of extended timestamp (#3)" << endl;
+ return true;
+ }/*end if*/
+ pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
+ | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
+ buffer += 4;
+ size -= 4;
+ }/*end if*/
+
+ if (flags & 4) { // contains creation time
+ if (size < 4) {
+ kdDebug(7040) << "premature end of extended timestamp (#4)" << endl;
+ return true;
+ }/*end if*/
+ pfi.ctime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
+ | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
+ buffer += 4;
+ }/*end if*/
+
+ pfi.exttimestamp_seen = true;
+ return true;
+}
+
+/** updates the parse information with the given Info-ZIP Unix old extra field.
+ * @param buffer start of content of buffer known to contain an Info-ZIP
+ * Unix old extra field (without magic & size)
+ * @param size size of field content (must not count magic and size entries)
+ * @param islocal true if this is a local field, false if central
+ * @param pfi ParseFileInfo object to be updated
+ * @return true if processing was successful
+ */
+static bool parseInfoZipUnixOld(const char *buffer, int size, bool islocal,
+ ParseFileInfo &pfi) {
+ // spec mandates to omit this field if one of the newer fields are available
+ if (pfi.exttimestamp_seen || pfi.newinfounix_seen) return true;
+
+ if (size < 8) {
+ kdDebug(7040) << "premature end of Info-ZIP unix extra field old" << endl;
+ return false;
+ }/*end if*/
+
+ pfi.atime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
+ | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
+ buffer += 4;
+ pfi.mtime = time_t((uchar)buffer[0] | (uchar)buffer[1] << 8
+ | (uchar)buffer[2] << 16 | (uchar)buffer[3] << 24);
+ buffer += 4;
+ if (islocal && size >= 12) {
+ pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
+ buffer += 2;
+ pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
+ buffer += 2;
+ }/*end if*/
+ return true;
+}
+
+#if 0 // not needed yet
+/** updates the parse information with the given Info-ZIP Unix new extra field.
+ * @param buffer start of content of buffer known to contain an Info-ZIP
+ * Unix new extra field (without magic & size)
+ * @param size size of field content (must not count magic and size entries)
+ * @param islocal true if this is a local field, false if central
+ * @param pfi ParseFileInfo object to be updated
+ * @return true if processing was successful
+ */
+static bool parseInfoZipUnixNew(const char *buffer, int size, bool islocal,
+ ParseFileInfo &pfi) {
+ if (!islocal) { // contains nothing in central field
+ pfi.newinfounix = true;
+ return true;
+ }/*end if*/
+
+ if (size < 4) {
+ kdDebug(7040) << "premature end of Info-ZIP unix extra field new" << endl;
+ return false;
+ }/*end if*/
+
+ pfi.uid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
+ buffer += 2;
+ pfi.gid = (uchar)buffer[0] | (uchar)buffer[1] << 8;
+ buffer += 2;
+
+ pfi.newinfounix = true;
+ return true;
+}
+#endif
+
+/**
+ * parses the extra field
+ * @param buffer start of buffer where the extra field is to be found
+ * @param size size of the extra field
+ * @param islocal true if this is part of a local header, false if of central
+ * @param pfi ParseFileInfo object which to write the results into
+ * @return true if parsing was successful
+ */
+static bool parseExtraField(const char *buffer, int size, bool islocal,
+ ParseFileInfo &pfi) {
+ // extra field in central directory doesn't contain useful data, so we
+ // don't bother parsing it
+ if (!islocal) return true;
+
+ while (size >= 4) { // as long as a potential extra field can be read
+ int magic = (uchar)buffer[0] | (uchar)buffer[1] << 8;
+ buffer += 2;
+ int fieldsize = (uchar)buffer[0] | (uchar)buffer[1] << 8;
+ buffer += 2;
+ size -= 4;
+
+ if (fieldsize > size) {
+ //kdDebug(7040) << "fieldsize: " << fieldsize << " size: " << size << endl;
+ kdDebug(7040) << "premature end of extra fields reached" << endl;
+ break;
+ }/*end if*/
+
+ switch (magic) {
+ case 0x5455: // extended timestamp
+ if (!parseExtTimestamp(buffer, fieldsize, islocal, pfi)) return false;
+ break;
+ case 0x5855: // old Info-ZIP unix extra field
+ if (!parseInfoZipUnixOld(buffer, fieldsize, islocal, pfi)) return false;
+ break;
+#if 0 // not needed yet
+ case 0x7855: // new Info-ZIP unix extra field
+ if (!parseInfoZipUnixNew(buffer, fieldsize, islocal, pfi)) return false;
+ break;
+#endif
+ default:
+ /* ignore everything else */;
+ }/*end switch*/
+
+ buffer += fieldsize;
+ size -= fieldsize;
+ }/*wend*/
+ return true;
+}
+
+////////////////////////////////////////////////////////////////////////
+/////////////////////////// KZip ///////////////////////////////////////
+////////////////////////////////////////////////////////////////////////
+
+class KZip::KZipPrivate
+{
+public:
+ KZipPrivate()
+ : m_crc( 0 ),
+ m_currentFile( 0L ),
+ m_currentDev( 0L ),
+ m_compression( 8 ),
+ m_extraField( KZip::NoExtraField ),
+ m_offset( 0L ),
+ m_saveFile( 0 ) {}
+
+ unsigned long m_crc; // checksum
+ KZipFileEntry* m_currentFile; // file currently being written
+ TQIODevice* m_currentDev; // filterdev used to write to the above file
+ TQPtrList<KZipFileEntry> m_fileList; // flat list of all files, for the index (saves a recursive method ;)
+ int m_compression;
+ KZip::ExtraField m_extraField;
+ unsigned int m_offset; // holds the offset of the place in the zip,
+ // where new data can be appended. after openarchive it points to 0, when in
+ // writeonly mode, or it points to the beginning of the central directory.
+ // each call to writefile updates this value.
+ KSaveFile* m_saveFile;
+};
+
+KZip::KZip( const TQString& filename )
+ : KArchive( 0L )
+{
+ //kdDebug(7040) << "KZip(filename) reached." << endl;
+ Q_ASSERT( !filename.isEmpty() );
+ m_filename = filename;
+ d = new KZipPrivate;
+ // unusual: this ctor leaves the device set to 0.
+ // This is for the use of KSaveFile, see openArchive.
+ // KDE4: move KSaveFile support to base class, KArchive.
+}
+
+KZip::KZip( TQIODevice * dev )
+ : KArchive( dev )
+{
+ //kdDebug(7040) << "KZip::KZip( TQIODevice * dev) reached." << endl;
+ d = new KZipPrivate;
+}
+
+KZip::~KZip()
+{
+ // mjarrett: Closes to prevent ~KArchive from aborting w/o device
+ //kdDebug(7040) << "~KZip reached." << endl;
+ if( isOpened() )
+ close();
+ if ( !m_filename.isEmpty() ) { // we created the device ourselves
+ if ( d->m_saveFile ) // writing mode
+ delete d->m_saveFile;
+ else // reading mode
+ delete device(); // (the TQFile)
+ }
+ delete d;
+}
+
+bool KZip::openArchive( int mode )
+{
+ //kdDebug(7040) << "openarchive reached." << endl;
+ d->m_fileList.clear();
+
+ switch ( mode ) {
+ case IO_WriteOnly:
+ // The use of KSaveFile can't be done in the ctor (no mode known yet)
+ // Ideally we would reimplement open() and do it there (BIC)
+ if ( !m_filename.isEmpty() ) {
+ kdDebug(7040) << "Writing to a file using KSaveFile" << endl;
+ d->m_saveFile = new KSaveFile( m_filename );
+ if ( d->m_saveFile->status() != 0 ) {
+ kdWarning(7040) << "KSaveFile creation for " << m_filename << " failed, " << strerror( d->m_saveFile->status() ) << endl;
+ delete d->m_saveFile;
+ d->m_saveFile = 0;
+ return false;
+ }
+ Q_ASSERT( d->m_saveFile->file() );
+ setDevice( TQT_TQIODEVICE(d->m_saveFile->file()) );
+ }
+ return true;
+ case IO_ReadOnly:
+ case IO_ReadWrite:
+ {
+ // ReadWrite mode still uses TQFile for now; we'd need to copy to the tempfile, in fact.
+ if ( !m_filename.isEmpty() ) {
+ setDevice( TQT_TQIODEVICE(new TQFile( m_filename )) );
+ if ( !device()->open( mode ) )
+ return false;
+ }
+ break; // continued below
+ }
+ default:
+ kdWarning(7040) << "Unsupported mode " << mode << endl;
+ return false;
+ }
+
+ char buffer[47];
+
+ // Check that it's a valid ZIP file
+ // the above code opened the underlying device already.
+ TQIODevice* dev = device();
+
+ if (!dev) {
+ return false;
+ }
+
+ uint offset = 0; // holds offset, where we read
+ int n;
+
+ // contains information gathered from the local file headers
+ TQAsciiDict<ParseFileInfo> pfi_map(1009, true /*case sensitive */, true /*copy keys*/);
+ pfi_map.setAutoDelete(true);
+
+ // We set a bool for knowing if we are allowed to skip the start of the file
+ bool startOfFile = true;
+
+ for (;;) // repeat until 'end of entries' signature is reached
+ {
+kdDebug(7040) << "loop starts" << endl;
+kdDebug(7040) << "dev->at() now : " << dev->at() << endl;
+ n = dev->readBlock( buffer, 4 );
+
+ if (n < 4)
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#1)" << endl;
+
+ return false;
+ }
+
+ if ( !memcmp( buffer, "PK\5\6", 4 ) ) // 'end of entries'
+ {
+ kdDebug(7040) << "PK56 found end of archive" << endl;
+ startOfFile = false;
+ break;
+ }
+
+ if ( !memcmp( buffer, "PK\3\4", 4 ) ) // local file header
+ {
+ kdDebug(7040) << "PK34 found local file header" << endl;
+ startOfFile = false;
+ // can this fail ???
+ dev->at( dev->at() + 2 ); // skip 'version needed to extract'
+
+ // read static header stuff
+ n = dev->readBlock( buffer, 24 );
+ if (n < 24) {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#4)" << endl;
+ return false;
+ }
+
+ int gpf = (uchar)buffer[0]; // "general purpose flag" not "general protection fault" ;-)
+ int compression_mode = (uchar)buffer[2] | (uchar)buffer[3] << 8;
+ time_t mtime = transformFromMsDos( buffer+4 );
+
+ TQ_LONG compr_size = (uchar)buffer[12] | (uchar)buffer[13] << 8
+ | (uchar)buffer[14] << 16 | (uchar)buffer[15] << 24;
+ TQ_LONG uncomp_size = (uchar)buffer[16] | (uchar)buffer[17] << 8
+ | (uchar)buffer[18] << 16 | (uchar)buffer[19] << 24;
+ int namelen = (uchar)buffer[20] | (uchar)buffer[21] << 8;
+ int extralen = (uchar)buffer[22] | (uchar)buffer[23] << 8;
+
+ kdDebug(7040) << "general purpose bit flag: " << gpf << endl;
+ kdDebug(7040) << "compressed size: " << compr_size << endl;
+ kdDebug(7040) << "uncompressed size: " << uncomp_size << endl;
+ kdDebug(7040) << "namelen: " << namelen << endl;
+ kdDebug(7040) << "extralen: " << extralen << endl;
+ kdDebug(7040) << "archive size: " << dev->size() << endl;
+
+ // read filename
+ TQCString filename(namelen + 1);
+ n = dev->readBlock(filename.data(), namelen);
+ if ( n < namelen ) {
+ kdWarning(7040) << "Invalid ZIP file. Name not completely read (#2)" << endl;
+ return false;
+ }
+
+ ParseFileInfo *pfi = new ParseFileInfo();
+ pfi->mtime = mtime;
+ pfi_map.insert(filename.data(), pfi);
+
+ // read and parse the beginning of the extra field,
+ // skip rest of extra field in case it is too long
+ unsigned int extraFieldEnd = dev->at() + extralen;
+ pfi->extralen = extralen;
+ int handledextralen = QMIN(extralen, (int)sizeof buffer);
+
+ kdDebug(7040) << "handledextralen: " << handledextralen << endl;
+
+ n = dev->readBlock(buffer, handledextralen);
+ // no error msg necessary as we deliberately truncate the extra field
+ if (!parseExtraField(buffer, handledextralen, true, *pfi))
+ {
+ kdWarning(7040) << "Invalid ZIP File. Broken ExtraField." << endl;
+ return false;
+ }
+
+ // jump to end of extra field
+ dev->at( extraFieldEnd );
+
+ // we have to take care of the 'general purpose bit flag'.
+ // if bit 3 is set, the header doesn't contain the length of
+ // the file and we look for the signature 'PK\7\8'.
+ if ( gpf & 8 )
+ {
+ // here we have to read through the compressed data to find
+ // the next PKxx
+ kdDebug(7040) << "trying to seek for next PK78" << endl;
+ bool foundSignature = false;
+
+ while (!foundSignature)
+ {
+ n = dev->readBlock( buffer, 1 );
+ if (n < 1)
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#2)" << endl;
+ return false;
+ }
+
+ if ( buffer[0] != 'P' )
+ continue;
+
+ n = dev->readBlock( buffer, 3 );
+ if (n < 3)
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#3)" << endl;
+ return false;
+ }
+
+ // we have to detect three magic tokens here:
+ // PK34 for the next local header in case there is no data descriptor
+ // PK12 for the central header in case there is no data descriptor
+ // PK78 for the data descriptor in case it is following the compressed data
+
+ if ( buffer[0] == 'K' && buffer[1] == 7 && buffer[2] == 8 )
+ {
+ foundSignature = true;
+ dev->at( dev->at() + 12 ); // skip the 'data_descriptor'
+ }
+ else if ( ( buffer[0] == 'K' && buffer[1] == 1 && buffer[2] == 2 )
+ || ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2] == 4 ) )
+ {
+ foundSignature = true;
+ dev->at( dev->at() - 4 ); // go back 4 bytes, so that the magic bytes can be found...
+ }
+ else if ( buffer[0] == 'P' || buffer[1] == 'P' || buffer[2] == 'P' )
+ {
+ // We have another P character so we must go back a little to check if it is a magic
+ dev->at( dev->at() - 3 );
+ }
+
+ }
+ }
+ else
+ {
+ // here we skip the compressed data and jump to the next header
+ kdDebug(7040) << "general purpose bit flag indicates, that local file header contains valid size" << endl;
+ // check if this could be a symbolic link
+ if (compression_mode == NoCompression
+ && uncomp_size <= max_path_len
+ && uncomp_size > 0) {
+ // read content and store it
+ pfi->guessed_symlink.resize(uncomp_size + 1);
+ kdDebug(7040) << "guessed symlink size: " << uncomp_size << endl;
+ n = dev->readBlock(pfi->guessed_symlink.data(), uncomp_size);
+ if (n < uncomp_size) {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#5)" << endl;
+ return false;
+ }
+ } else {
+
+ if ( compr_size > (TQ_LONG)dev->size() )
+ {
+ // here we cannot trust the compressed size, so scan through the compressed
+ // data to find the next header
+ bool foundSignature = false;
+
+ while (!foundSignature)
+ {
+ n = dev->readBlock( buffer, 1 );
+ if (n < 1)
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#2)" << endl;
+ return false;
+ }
+
+ if ( buffer[0] != 'P' )
+ continue;
+
+ n = dev->readBlock( buffer, 3 );
+ if (n < 3)
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. (#3)" << endl;
+ return false;
+ }
+
+ // we have to detect three magic tokens here:
+ // PK34 for the next local header in case there is no data descriptor
+ // PK12 for the central header in case there is no data descriptor
+ // PK78 for the data descriptor in case it is following the compressed data
+
+ if ( buffer[0] == 'K' && buffer[1] == 7 && buffer[2] == 8 )
+ {
+ foundSignature = true;
+ dev->at( dev->at() + 12 ); // skip the 'data_descriptor'
+ }
+
+ if ( ( buffer[0] == 'K' && buffer[1] == 1 && buffer[2] == 2 )
+ || ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2] == 4 ) )
+ {
+ foundSignature = true;
+ dev->at( dev->at() - 4 );
+ // go back 4 bytes, so that the magic bytes can be found
+ // in the next cycle...
+ }
+ }
+ }
+ else
+ {
+// kdDebug(7040) << "before interesting dev->at(): " << dev->at() << endl;
+ bool success;
+ success = dev->at( dev->at() + compr_size ); // can this fail ???
+/* kdDebug(7040) << "after interesting dev->at(): " << dev->at() << endl;
+ if ( success )
+ kdDebug(7040) << "dev->at was successful... " << endl;
+ else
+ kdDebug(7040) << "dev->at failed... " << endl;*/
+ }
+
+ }
+
+// not needed any more
+/* // here we calculate the length of the file in the zip
+ // with headers and jump to the next header.
+ uint skip = compr_size + namelen + extralen;
+ offset += 30 + skip;*/
+ }
+ }
+ else if ( !memcmp( buffer, "PK\1\2", 4 ) ) // central block
+ {
+ kdDebug(7040) << "PK12 found central block" << endl;
+ startOfFile = false;
+
+ // so we reached the central header at the end of the zip file
+ // here we get all interesting data out of the central header
+ // of a file
+ offset = dev->at() - 4;
+
+ //set offset for appending new files
+ if ( d->m_offset == 0L ) d->m_offset = offset;
+
+ n = dev->readBlock( buffer + 4, 42 );
+ if (n < 42) {
+ kdWarning(7040) << "Invalid ZIP file, central entry too short" << endl; // not long enough for valid entry
+ return false;
+ }
+
+ //int gpf = (uchar)buffer[9] << 8 | (uchar)buffer[10];
+ //kdDebug() << "general purpose flag=" << gpf << endl;
+ // length of the filename (well, pathname indeed)
+ int namelen = (uchar)buffer[29] << 8 | (uchar)buffer[28];
+ TQCString bufferName( namelen + 1 );
+ n = dev->readBlock( bufferName.data(), namelen );
+ if ( n < namelen )
+ kdWarning(7040) << "Invalid ZIP file. Name not completely read" << endl;
+
+ ParseFileInfo *pfi = pfi_map[bufferName];
+ if (!pfi) { // can that happen?
+ pfi_map.insert(bufferName.data(), pfi = new ParseFileInfo());
+ }
+ TQString name( TQFile::decodeName(bufferName) );
+
+ //kdDebug(7040) << "name: " << name << endl;
+ // only in central header ! see below.
+ // length of extra attributes
+ int extralen = (uchar)buffer[31] << 8 | (uchar)buffer[30];
+ // length of comment for this file
+ int commlen = (uchar)buffer[33] << 8 | (uchar)buffer[32];
+ // compression method of this file
+ int cmethod = (uchar)buffer[11] << 8 | (uchar)buffer[10];
+
+ //kdDebug(7040) << "cmethod: " << cmethod << endl;
+ //kdDebug(7040) << "extralen: " << extralen << endl;
+
+ // uncompressed file size
+ uint ucsize = (uchar)buffer[27] << 24 | (uchar)buffer[26] << 16 |
+ (uchar)buffer[25] << 8 | (uchar)buffer[24];
+ // compressed file size
+ uint csize = (uchar)buffer[23] << 24 | (uchar)buffer[22] << 16 |
+ (uchar)buffer[21] << 8 | (uchar)buffer[20];
+
+ // offset of local header
+ uint localheaderoffset = (uchar)buffer[45] << 24 | (uchar)buffer[44] << 16 |
+ (uchar)buffer[43] << 8 | (uchar)buffer[42];
+
+ // some clever people use different extra field lengths
+ // in the central header and in the local header... funny.
+ // so we need to get the localextralen to calculate the offset
+ // from localheaderstart to dataoffset
+ int localextralen = pfi->extralen; // FIXME: this will not work if
+ // no local header exists
+
+ //kdDebug(7040) << "localextralen: " << localextralen << endl;
+
+ // offset, where the real data for uncompression starts
+ uint dataoffset = localheaderoffset + 30 + localextralen + namelen; //comment only in central header
+
+ //kdDebug(7040) << "esize: " << esize << endl;
+ //kdDebug(7040) << "eoffset: " << eoffset << endl;
+ //kdDebug(7040) << "csize: " << csize << endl;
+
+ int os_madeby = (uchar)buffer[5];
+ bool isdir = false;
+ int access = 0100644;
+
+ if (os_madeby == 3) { // good ole unix
+ access = (uchar)buffer[40] | (uchar)buffer[41] << 8;
+ }
+
+ TQString entryName;
+
+ if ( name.endsWith( "/" ) ) // Entries with a trailing slash are directories
+ {
+ isdir = true;
+ name = name.left( name.length() - 1 );
+ if (os_madeby != 3) access = S_IFDIR | 0755;
+ else Q_ASSERT(access & S_IFDIR);
+ }
+
+ int pos = name.findRev( '/' );
+ if ( pos == -1 )
+ entryName = name;
+ else
+ entryName = name.mid( pos + 1 );
+ Q_ASSERT( !entryName.isEmpty() );
+
+ KArchiveEntry* entry;
+ if ( isdir )
+ {
+ TQString path = TQDir::cleanDirPath( name );
+ KArchiveEntry* ent = rootDir()->entry( path );
+ if ( ent && ent->isDirectory() )
+ {
+ //kdDebug(7040) << "Directory already exists, NOT going to add it again" << endl;
+ entry = 0L;
+ }
+ else
+ {
+ entry = new KArchiveDirectory( this, entryName, access, (int)pfi->mtime, rootDir()->user(), rootDir()->group(), TQString::null );
+ //kdDebug(7040) << "KArchiveDirectory created, entryName= " << entryName << ", name=" << name << endl;
+ }
+ }
+ else
+ {
+ TQString symlink;
+ if (S_ISLNK(access)) {
+ symlink = TQFile::decodeName(pfi->guessed_symlink);
+ }
+ entry = new KZipFileEntry( this, entryName, access, pfi->mtime,
+ rootDir()->user(), rootDir()->group(),
+ symlink, name, dataoffset,
+ ucsize, cmethod, csize );
+ static_cast<KZipFileEntry *>(entry)->setHeaderStart( localheaderoffset );
+ //kdDebug(7040) << "KZipFileEntry created, entryName= " << entryName << ", name=" << name << endl;
+ d->m_fileList.append( static_cast<KZipFileEntry *>( entry ) );
+ }
+
+ if ( entry )
+ {
+ if ( pos == -1 )
+ {
+ rootDir()->addEntry(entry);
+ }
+ else
+ {
+ // In some tar files we can find dir/./file => call cleanDirPath
+ TQString path = TQDir::cleanDirPath( name.left( pos ) );
+ // Ensure container directory exists, create otherwise
+ KArchiveDirectory * tdir = findOrCreate( path );
+ tdir->addEntry(entry);
+ }
+ }
+
+ //calculate offset to next entry
+ offset += 46 + commlen + extralen + namelen;
+ bool b = dev->at(offset);
+ Q_ASSERT( b );
+ if ( !b )
+ return false;
+ }
+ else if ( startOfFile )
+ {
+ // The file does not start with any ZIP header (e.g. self-extractable ZIP files)
+ // Therefore we need to find the first PK\003\004 (local header)
+ kdDebug(7040) << "Try to skip start of file" << endl;
+ startOfFile = false;
+ bool foundSignature = false;
+
+ while (!foundSignature)
+ {
+ n = dev->readBlock( buffer, 1 );
+ if (n < 1)
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. " << k_funcinfo << endl;
+ return false;
+ }
+
+ if ( buffer[0] != 'P' )
+ continue;
+
+ n = dev->readBlock( buffer, 3 );
+ if (n < 3)
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unexpected end of file. " << k_funcinfo << endl;
+ return false;
+ }
+
+ // We have to detect the magic token for a local header: PK\003\004
+ /*
+ * Note: we do not need to check the other magics, if the ZIP file has no
+ * local header, then it has not any files!
+ */
+ if ( buffer[0] == 'K' && buffer[1] == 3 && buffer[2] == 4 )
+ {
+ foundSignature = true;
+ dev->at( dev->at() - 4 ); // go back 4 bytes, so that the magic bytes can be found...
+ }
+ else if ( buffer[0] == 'P' || buffer[1] == 'P' || buffer[2] == 'P' )
+ {
+ // We have another P character so we must go back a little to check if it is a magic
+ dev->at( dev->at() - 3 );
+ }
+ }
+ }
+ else
+ {
+ kdWarning(7040) << "Invalid ZIP file. Unrecognized header at offset " << offset << endl;
+
+ return false;
+ }
+ }
+ //kdDebug(7040) << "*** done *** " << endl;
+ return true;
+}
+
+bool KZip::closeArchive()
+{
+ if ( ! ( mode() & IO_WriteOnly ) )
+ {
+ //kdDebug(7040) << "closearchive readonly reached." << endl;
+ return true;
+ }
+
+ kdDebug() << k_funcinfo << "device=" << device() << endl;
+ //ReadWrite or WriteOnly
+ //write all central dir file entries
+
+ if ( !device() ) // saving aborted
+ return false;
+
+ // to be written at the end of the file...
+ char buffer[ 22 ]; // first used for 12, then for 22 at the end
+ uLong crc = crc32(0L, Z_NULL, 0);
+
+ TQ_LONG centraldiroffset = device()->at();
+ //kdDebug(7040) << "closearchive: centraldiroffset: " << centraldiroffset << endl;
+ TQ_LONG atbackup = centraldiroffset;
+ TQPtrListIterator<KZipFileEntry> it( d->m_fileList );
+
+ for ( ; it.current() ; ++it )
+ { //set crc and compressed size in each local file header
+ if ( !device()->at( it.current()->headerStart() + 14 ) )
+ return false;
+ //kdDebug(7040) << "closearchive setcrcandcsize: filename: "
+ // << it.current()->path()
+ // << " encoding: "<< it.current()->encoding() << endl;
+
+ uLong mycrc = it.current()->crc32();
+ buffer[0] = char(mycrc); // crc checksum, at headerStart+14
+ buffer[1] = char(mycrc >> 8);
+ buffer[2] = char(mycrc >> 16);
+ buffer[3] = char(mycrc >> 24);
+
+ int mysize1 = it.current()->compressedSize();
+ buffer[4] = char(mysize1); // compressed file size, at headerStart+18
+ buffer[5] = char(mysize1 >> 8);
+ buffer[6] = char(mysize1 >> 16);
+ buffer[7] = char(mysize1 >> 24);
+
+ int myusize = it.current()->size();
+ buffer[8] = char(myusize); // uncompressed file size, at headerStart+22
+ buffer[9] = char(myusize >> 8);
+ buffer[10] = char(myusize >> 16);
+ buffer[11] = char(myusize >> 24);
+
+ if ( device()->writeBlock( buffer, 12 ) != 12 )
+ return false;
+ }
+ device()->at( atbackup );
+
+ for ( it.toFirst(); it.current() ; ++it )
+ {
+ //kdDebug(7040) << "closearchive: filename: " << it.current()->path()
+ // << " encoding: "<< it.current()->encoding() << endl;
+
+ TQCString path = TQFile::encodeName(it.current()->path());
+
+ const int extra_field_len = 9;
+ int bufferSize = extra_field_len + path.length() + 46;
+ char* buffer = new char[ bufferSize ];
+
+ memset(buffer, 0, 46); // zero is a nice default for most header fields
+
+ const char head[] =
+ {
+ 'P', 'K', 1, 2, // central file header signature
+ 0x14, 3, // version made by (3 == UNIX)
+ 0x14, 0 // version needed to extract
+ };
+
+ // I do not know why memcpy is not working here
+ //memcpy(buffer, head, sizeof(head));
+ tqmemmove(buffer, head, sizeof(head));
+
+ buffer[ 10 ] = char(it.current()->encoding()); // compression method
+ buffer[ 11 ] = char(it.current()->encoding() >> 8);
+
+ transformToMsDos( it.current()->datetime(), &buffer[ 12 ] );
+
+ uLong mycrc = it.current()->crc32();
+ buffer[ 16 ] = char(mycrc); // crc checksum
+ buffer[ 17 ] = char(mycrc >> 8);
+ buffer[ 18 ] = char(mycrc >> 16);
+ buffer[ 19 ] = char(mycrc >> 24);
+
+ int mysize1 = it.current()->compressedSize();
+ buffer[ 20 ] = char(mysize1); // compressed file size
+ buffer[ 21 ] = char(mysize1 >> 8);
+ buffer[ 22 ] = char(mysize1 >> 16);
+ buffer[ 23 ] = char(mysize1 >> 24);
+
+ int mysize = it.current()->size();
+ buffer[ 24 ] = char(mysize); // uncompressed file size
+ buffer[ 25 ] = char(mysize >> 8);
+ buffer[ 26 ] = char(mysize >> 16);
+ buffer[ 27 ] = char(mysize >> 24);
+
+ buffer[ 28 ] = char(it.current()->path().length()); // filename length
+ buffer[ 29 ] = char(it.current()->path().length() >> 8);
+
+ buffer[ 30 ] = char(extra_field_len);
+ buffer[ 31 ] = char(extra_field_len >> 8);
+
+ buffer[ 40 ] = char(it.current()->permissions());
+ buffer[ 41 ] = char(it.current()->permissions() >> 8);
+
+ int myhst = it.current()->headerStart();
+ buffer[ 42 ] = char(myhst); //relative offset of local header
+ buffer[ 43 ] = char(myhst >> 8);
+ buffer[ 44 ] = char(myhst >> 16);
+ buffer[ 45 ] = char(myhst >> 24);
+
+ // file name
+ strncpy( buffer + 46, path, path.length() );
+ //kdDebug(7040) << "closearchive length to write: " << bufferSize << endl;
+
+ // extra field
+ char *extfield = buffer + 46 + path.length();
+ extfield[0] = 'U';
+ extfield[1] = 'T';
+ extfield[2] = 5;
+ extfield[3] = 0;
+ extfield[4] = 1 | 2 | 4; // specify flags from local field
+ // (unless I misread the spec)
+ // provide only modification time
+ unsigned long time = (unsigned long)it.current()->date();
+ extfield[5] = char(time);
+ extfield[6] = char(time >> 8);
+ extfield[7] = char(time >> 16);
+ extfield[8] = char(time >> 24);
+
+ crc = crc32(crc, (Bytef *)buffer, bufferSize );
+ bool ok = ( device()->writeBlock( buffer, bufferSize ) == bufferSize );
+ delete[] buffer;
+ if ( !ok )
+ return false;
+ }
+ TQ_LONG centraldirendoffset = device()->at();
+ //kdDebug(7040) << "closearchive: centraldirendoffset: " << centraldirendoffset << endl;
+ //kdDebug(7040) << "closearchive: device()->at(): " << device()->at() << endl;
+
+ //write end of central dir record.
+ buffer[ 0 ] = 'P'; //end of central dir signature
+ buffer[ 1 ] = 'K';
+ buffer[ 2 ] = 5;
+ buffer[ 3 ] = 6;
+
+ buffer[ 4 ] = 0; // number of this disk
+ buffer[ 5 ] = 0;
+
+ buffer[ 6 ] = 0; // number of disk with start of central dir
+ buffer[ 7 ] = 0;
+
+ int count = d->m_fileList.count();
+ //kdDebug(7040) << "number of files (count): " << count << endl;
+
+
+ buffer[ 8 ] = char(count); // total number of entries in central dir of
+ buffer[ 9 ] = char(count >> 8); // this disk
+
+ buffer[ 10 ] = buffer[ 8 ]; // total number of entries in the central dir
+ buffer[ 11 ] = buffer[ 9 ];
+
+ int cdsize = centraldirendoffset - centraldiroffset;
+ buffer[ 12 ] = char(cdsize); // size of the central dir
+ buffer[ 13 ] = char(cdsize >> 8);
+ buffer[ 14 ] = char(cdsize >> 16);
+ buffer[ 15 ] = char(cdsize >> 24);
+
+ //kdDebug(7040) << "end : centraldiroffset: " << centraldiroffset << endl;
+ //kdDebug(7040) << "end : centraldirsize: " << cdsize << endl;
+
+ buffer[ 16 ] = char(centraldiroffset); // central dir offset
+ buffer[ 17 ] = char(centraldiroffset >> 8);
+ buffer[ 18 ] = char(centraldiroffset >> 16);
+ buffer[ 19 ] = char(centraldiroffset >> 24);
+
+ buffer[ 20 ] = 0; //zipfile comment length
+ buffer[ 21 ] = 0;
+
+ if ( device()->writeBlock( buffer, 22 ) != 22 )
+ return false;
+
+ if ( d->m_saveFile ) {
+ d->m_saveFile->close();
+ setDevice( 0 );
+ delete d->m_saveFile;
+ d->m_saveFile = 0;
+ }
+
+ //kdDebug(7040) << __FILE__" reached." << endl;
+ return true;
+}
+
+// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
+bool KZip::writeFile( const TQString& name, const TQString& user, const TQString& group, uint size, const char* data )
+{
+ mode_t mode = 0100644;
+ time_t the_time = time(0);
+ return KArchive::writeFile( name, user, group, size, mode, the_time,
+ the_time, the_time, data );
+}
+
+// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
+bool KZip::writeFile( const TQString& name, const TQString& user,
+ const TQString& group, uint size, mode_t perm,
+ time_t atime, time_t mtime, time_t ctime,
+ const char* data ) {
+ return KArchive::writeFile(name, user, group, size, perm, atime, mtime,
+ ctime, data);
+}
+
+// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
+bool KZip::prepareWriting( const TQString& name, const TQString& user, const TQString& group, uint size )
+{
+ mode_t dflt_perm = 0100644;
+ time_t the_time = time(0);
+ return prepareWriting(name,user,group,size,dflt_perm,
+ the_time,the_time,the_time);
+}
+
+// Doesn't need to be reimplemented anymore. Remove for KDE-4.0
+bool KZip::prepareWriting(const TQString& name, const TQString& user,
+ const TQString& group, uint size, mode_t perm,
+ time_t atime, time_t mtime, time_t ctime) {
+ return KArchive::prepareWriting(name,user,group,size,perm,atime,mtime,ctime);
+}
+
+bool KZip::prepareWriting_impl(const TQString &name, const TQString &user,
+ const TQString &group, uint /*size*/, mode_t perm,
+ time_t atime, time_t mtime, time_t ctime) {
+ //kdDebug(7040) << "prepareWriting reached." << endl;
+ if ( !isOpened() )
+ {
+ tqWarning( "KZip::writeFile: You must open the zip file before writing to it\n");
+ return false;
+ }
+
+ if ( ! ( mode() & IO_WriteOnly ) ) // accept WriteOnly and ReadWrite
+ {
+ tqWarning( "KZip::writeFile: You must open the zip file for writing\n");
+ return false;
+ }
+
+ if ( !device() ) { // aborted
+ //kdWarning(7040) << "prepareWriting_impl: no device" << endl;
+ return false;
+ }
+
+ // set right offset in zip.
+ if ( !device()->at( d->m_offset ) ) {
+ kdWarning(7040) << "prepareWriting_impl: cannot seek in ZIP file. Disk full?" << endl;
+ abort();
+ return false;
+ }
+
+ // delete entries in the filelist with the same filename as the one we want
+ // to save, so that we don�t have duplicate file entries when viewing the zip
+ // with konqi...
+ // CAUTION: the old file itself is still in the zip and won't be removed !!!
+ TQPtrListIterator<KZipFileEntry> it( d->m_fileList );
+
+ //kdDebug(7040) << "filename to write: " << name <<endl;
+ for ( ; it.current() ; ++it )
+ {
+ //kdDebug(7040) << "prepfilename: " << it.current()->path() <<endl;
+ if (name == it.current()->path() )
+ {
+ //kdDebug(7040) << "removing following entry: " << it.current()->path() <<endl;
+ d->m_fileList.remove();
+ }
+
+ }
+ // Find or create parent dir
+ KArchiveDirectory* parentDir = rootDir();
+ TQString fileName( name );
+ int i = name.findRev( '/' );
+ if ( i != -1 )
+ {
+ TQString dir = name.left( i );
+ fileName = name.mid( i + 1 );
+ //kdDebug(7040) << "KZip::prepareWriting ensuring " << dir << " exists. fileName=" << fileName << endl;
+ parentDir = findOrCreate( dir );
+ }
+
+ // construct a KZipFileEntry and add it to list
+ KZipFileEntry * e = new KZipFileEntry( this, fileName, perm, mtime, user, group, TQString::null,
+ name, device()->at() + 30 + name.length(), // start
+ 0 /*size unknown yet*/, d->m_compression, 0 /*csize unknown yet*/ );
+ e->setHeaderStart( device()->at() );
+ //kdDebug(7040) << "wrote file start: " << e->position() << " name: " << name << endl;
+ parentDir->addEntry( e );
+
+ d->m_currentFile = e;
+ d->m_fileList.append( e );
+
+ int extra_field_len = 0;
+ if ( d->m_extraField == ModificationTime )
+ extra_field_len = 17; // value also used in doneWriting()
+
+ // write out zip header
+ TQCString encodedName = TQFile::encodeName(name);
+ int bufferSize = extra_field_len + encodedName.length() + 30;
+ //kdDebug(7040) << "KZip::prepareWriting bufferSize=" << bufferSize << endl;
+ char* buffer = new char[ bufferSize ];
+
+ buffer[ 0 ] = 'P'; //local file header signature
+ buffer[ 1 ] = 'K';
+ buffer[ 2 ] = 3;
+ buffer[ 3 ] = 4;
+
+ buffer[ 4 ] = 0x14; // version needed to extract
+ buffer[ 5 ] = 0;
+
+ buffer[ 6 ] = 0; // general purpose bit flag
+ buffer[ 7 ] = 0;
+
+ buffer[ 8 ] = char(e->encoding()); // compression method
+ buffer[ 9 ] = char(e->encoding() >> 8);
+
+ transformToMsDos( e->datetime(), &buffer[ 10 ] );
+
+ buffer[ 14 ] = 'C'; //dummy crc
+ buffer[ 15 ] = 'R';
+ buffer[ 16 ] = 'C';
+ buffer[ 17 ] = 'q';
+
+ buffer[ 18 ] = 'C'; //compressed file size
+ buffer[ 19 ] = 'S';
+ buffer[ 20 ] = 'I';
+ buffer[ 21 ] = 'Z';
+
+ buffer[ 22 ] = 'U'; //uncompressed file size
+ buffer[ 23 ] = 'S';
+ buffer[ 24 ] = 'I';
+ buffer[ 25 ] = 'Z';
+
+ buffer[ 26 ] = (uchar)(encodedName.length()); //filename length
+ buffer[ 27 ] = (uchar)(encodedName.length() >> 8);
+
+ buffer[ 28 ] = (uchar)(extra_field_len); // extra field length
+ buffer[ 29 ] = (uchar)(extra_field_len >> 8);
+
+ // file name
+ strncpy( buffer + 30, encodedName, encodedName.length() );
+
+ // extra field
+ if ( d->m_extraField == ModificationTime )
+ {
+ char *extfield = buffer + 30 + encodedName.length();
+ // "Extended timestamp" header (0x5455)
+ extfield[0] = 'U';
+ extfield[1] = 'T';
+ extfield[2] = 13; // data size
+ extfield[3] = 0;
+ extfield[4] = 1 | 2 | 4; // contains mtime, atime, ctime
+
+ extfield[5] = char(mtime);
+ extfield[6] = char(mtime >> 8);
+ extfield[7] = char(mtime >> 16);
+ extfield[8] = char(mtime >> 24);
+
+ extfield[9] = char(atime);
+ extfield[10] = char(atime >> 8);
+ extfield[11] = char(atime >> 16);
+ extfield[12] = char(atime >> 24);
+
+ extfield[13] = char(ctime);
+ extfield[14] = char(ctime >> 8);
+ extfield[15] = char(ctime >> 16);
+ extfield[16] = char(ctime >> 24);
+ }
+
+ // Write header
+ bool b = (device()->writeBlock( buffer, bufferSize ) == bufferSize );
+ d->m_crc = 0L;
+ delete[] buffer;
+
+ Q_ASSERT( b );
+ if (!b) {
+ abort();
+ return false;
+ }
+
+ // Prepare device for writing the data
+ // Either device() if no compression, or a KFilterDev to compress
+ if ( d->m_compression == 0 ) {
+ d->m_currentDev = device();
+ return true;
+ }
+
+ d->m_currentDev = KFilterDev::device( device(), "application/x-gzip", false );
+ Q_ASSERT( d->m_currentDev );
+ if ( !d->m_currentDev ) {
+ abort();
+ return false; // ouch
+ }
+ static_cast<KFilterDev *>(d->m_currentDev)->setSkipHeaders(); // Just zlib, not gzip
+
+ b = d->m_currentDev->open( IO_WriteOnly );
+ Q_ASSERT( b );
+ return b;
+}
+
+bool KZip::doneWriting( uint size )
+{
+ if ( d->m_currentFile->encoding() == 8 ) {
+ // Finish
+ (void)d->m_currentDev->writeBlock( 0, 0 );
+ delete d->m_currentDev;
+ }
+ // If 0, d->m_currentDev was device() - don't delete ;)
+ d->m_currentDev = 0L;
+
+ Q_ASSERT( d->m_currentFile );
+ //kdDebug(7040) << "donewriting reached." << endl;
+ //kdDebug(7040) << "filename: " << d->m_currentFile->path() << endl;
+ //kdDebug(7040) << "getpos (at): " << device()->at() << endl;
+ d->m_currentFile->setSize(size);
+ int extra_field_len = 0;
+ if ( d->m_extraField == ModificationTime )
+ extra_field_len = 17; // value also used in doneWriting()
+
+ int csize = device()->at() -
+ d->m_currentFile->headerStart() - 30 -
+ d->m_currentFile->path().length() - extra_field_len;
+ d->m_currentFile->setCompressedSize(csize);
+ //kdDebug(7040) << "usize: " << d->m_currentFile->size() << endl;
+ //kdDebug(7040) << "csize: " << d->m_currentFile->compressedSize() << endl;
+ //kdDebug(7040) << "headerstart: " << d->m_currentFile->headerStart() << endl;
+
+ //kdDebug(7040) << "crc: " << d->m_crc << endl;
+ d->m_currentFile->setCRC32( d->m_crc );
+
+ d->m_currentFile = 0L;
+
+ // update saved offset for appending new files
+ d->m_offset = device()->at();
+ return true;
+}
+
+bool KZip::writeSymLink(const TQString &name, const TQString &target,
+ const TQString &user, const TQString &group,
+ mode_t perm, time_t atime, time_t mtime, time_t ctime) {
+ return KArchive::writeSymLink(name,target,user,group,perm,atime,mtime,ctime);
+}
+
+bool KZip::writeSymLink_impl(const TQString &name, const TQString &target,
+ const TQString &user, const TQString &group,
+ mode_t perm, time_t atime, time_t mtime, time_t ctime) {
+
+ // reassure that symlink flag is set, otherwise strange things happen on
+ // extraction
+ perm |= S_IFLNK;
+ Compression c = compression();
+ setCompression(NoCompression); // link targets are never compressed
+
+ if (!prepareWriting(name, user, group, 0, perm, atime, mtime, ctime)) {
+ kdWarning() << "KZip::writeFile prepareWriting failed" << endl;
+ setCompression(c);
+ return false;
+ }
+
+ TQCString symlink_target = TQFile::encodeName(target);
+ if (!writeData(symlink_target, symlink_target.length())) {
+ kdWarning() << "KZip::writeFile writeData failed" << endl;
+ setCompression(c);
+ return false;
+ }
+
+ if (!doneWriting(symlink_target.length())) {
+ kdWarning() << "KZip::writeFile doneWriting failed" << endl;
+ setCompression(c);
+ return false;
+ }
+
+ setCompression(c);
+ return true;
+}
+
+void KZip::virtual_hook( int id, void* data )
+{
+ switch (id) {
+ case VIRTUAL_WRITE_DATA: {
+ WriteDataParams* params = reinterpret_cast<WriteDataParams *>(data);
+ params->retval = writeData_impl( params->data, params->size );
+ break;
+ }
+ case VIRTUAL_WRITE_SYMLINK: {
+ WriteSymlinkParams *params = reinterpret_cast<WriteSymlinkParams *>(data);
+ params->retval = writeSymLink_impl(*params->name,*params->target,
+ *params->user,*params->group,params->perm,
+ params->atime,params->mtime,params->ctime);
+ break;
+ }
+ case VIRTUAL_PREPARE_WRITING: {
+ PrepareWritingParams *params = reinterpret_cast<PrepareWritingParams *>(data);
+ params->retval = prepareWriting_impl(*params->name,*params->user,
+ *params->group,params->size,params->perm,
+ params->atime,params->mtime,params->ctime);
+ break;
+ }
+ default:
+ KArchive::virtual_hook( id, data );
+ }/*end switch*/
+}
+
+// made virtual using virtual_hook
+bool KZip::writeData(const char * c, uint i)
+{
+ return KArchive::writeData( c, i );
+}
+
+bool KZip::writeData_impl(const char * c, uint i)
+{
+ Q_ASSERT( d->m_currentFile );
+ Q_ASSERT( d->m_currentDev );
+ if (!d->m_currentFile || !d->m_currentDev) {
+ abort();
+ return false;
+ }
+
+ // crc to be calculated over uncompressed stuff...
+ // and they didn't mention it in their docs...
+ d->m_crc = crc32(d->m_crc, (const Bytef *) c , i);
+
+ TQ_LONG written = d->m_currentDev->writeBlock( c, i );
+ //kdDebug(7040) << "KZip::writeData wrote " << i << " bytes." << endl;
+ bool ok = written == (TQ_LONG)i;
+ if ( !ok )
+ abort();
+ return ok;
+}
+
+void KZip::setCompression( Compression c )
+{
+ d->m_compression = ( c == NoCompression ) ? 0 : 8;
+}
+
+KZip::Compression KZip::compression() const
+{
+ return ( d->m_compression == 8 ) ? DeflateCompression : NoCompression;
+}
+
+void KZip::setExtraField( ExtraField ef )
+{
+ d->m_extraField = ef;
+}
+
+KZip::ExtraField KZip::extraField() const
+{
+ return d->m_extraField;
+}
+
+void KZip::abort()
+{
+ if ( d->m_saveFile ) {
+ d->m_saveFile->abort();
+ setDevice( 0 );
+ }
+}
+
+
+///////////////
+
+TQByteArray KZipFileEntry::data() const
+{
+ TQIODevice* dev = device();
+ TQByteArray arr;
+ if ( dev ) {
+ arr = dev->readAll();
+ delete dev;
+ }
+ return arr;
+}
+
+TQIODevice* KZipFileEntry::device() const
+{
+ //kdDebug(7040) << "KZipFileEntry::device creating iodevice limited to pos=" << position() << ", csize=" << compressedSize() << endl;
+ // Limit the reading to the appropriate part of the underlying device (e.g. file)
+ KLimitedIODevice* limitedDev = new KLimitedIODevice( archive()->device(), position(), compressedSize() );
+ if ( encoding() == 0 || compressedSize() == 0 ) // no compression (or even no data)
+ return limitedDev;
+
+ if ( encoding() == 8 )
+ {
+ // On top of that, create a device that uncompresses the zlib data
+ TQIODevice* filterDev = KFilterDev::device( limitedDev, "application/x-gzip" );
+ if ( !filterDev )
+ return 0L; // ouch
+ static_cast<KFilterDev *>(filterDev)->setSkipHeaders(); // Just zlib, not gzip
+ bool b = filterDev->open( IO_ReadOnly );
+ Q_ASSERT( b );
+ return filterDev;
+ }
+
+ kdError() << "This zip file contains files compressed with method "
+ << encoding() <<", this method is currently not supported by KZip,"
+ <<" please use a command-line tool to handle this file." << endl;
+ return 0L;
+}
diff --git a/tdeio/tdeio/kzip.h b/tdeio/tdeio/kzip.h
new file mode 100644
index 000000000..333736e21
--- /dev/null
+++ b/tdeio/tdeio/kzip.h
@@ -0,0 +1,284 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Holger Schroeder <holger-kde@holgis.net>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __kzip_h
+#define __kzip_h
+
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <tqdatetime.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+#include <tqdict.h>
+#include <tqvaluelist.h>
+#include <karchive.h>
+
+class KZipFileEntry;
+/**
+ * This class implements a tdeioslave to access zip files from KDE.
+ * You can use it in IO_ReadOnly or in IO_WriteOnly mode, and it
+ * behaves just as expected.
+ * It can also be used in IO_ReadWrite mode, in this case one can
+ * append files to an existing zip archive. When you append new files, which
+ * are not yet in the zip, it works as expected, i.e. the files are appended at the end.
+ * When you append a file, which is already in the file, the reference to the
+ * old file is dropped and the new one is added to the zip - but the
+ * old data from the file itself is not deleted, it is still in the
+ * zipfile. so when you want to have a small and garbage-free zipfile,
+ * just read the contents of the appended zip file and write it to a new one
+ * in IO_WriteOnly mode. This is especially important when you don't want
+ * to leak information of how intermediate versions of files in the zip
+ * were looking.
+ * For more information on the zip fileformat go to
+ * http://www.pkware.com/products/enterprise/white_papers/appnote.html
+ * @short A class for reading/writing zip archives.
+ * @author Holger Schroeder <holger-kde@holgis.net>
+ * @since 3.1
+ */
+class TDEIO_EXPORT KZip : public KArchive
+{
+public:
+ /**
+ * Creates an instance that operates on the given filename.
+ * using the compression filter associated to given mimetype.
+ *
+ * @param filename is a local path (e.g. "/home/holger/myfile.zip")
+ */
+ KZip( const TQString& filename );
+
+ /**
+ * Creates an instance that operates on the given device.
+ * The device can be compressed (KFilterDev) or not (TQFile, etc.).
+ * @warning Do not assume that giving a TQFile here will decompress the file,
+ * in case it's compressed!
+ * @param dev the device to access
+ */
+ KZip( TQIODevice * dev );
+
+ /**
+ * If the zip file is still opened, then it will be
+ * closed automatically by the destructor.
+ */
+ virtual ~KZip();
+
+ /**
+ * The name of the zip file, as passed to the constructor.
+ * Null if you used the TQIODevice constructor.
+ * @return the zip's file name, or null if a TQIODevice is used
+ */
+ TQString fileName() { return m_filename; }
+
+ /**
+ * Describes the contents of the "extra field" for a given file in the Zip archive.
+ */
+ enum ExtraField { NoExtraField = 0, ///< No extra field
+ ModificationTime = 1, ///< Modification time ("extended timestamp" header)
+ DefaultExtraField = 1
+ };
+
+ /**
+ * Call this before writeFile or prepareWriting, to define what the next
+ * file to be written should have in its extra field.
+ * @param ef the type of "extra field"
+ * @see extraField()
+ */
+ void setExtraField( ExtraField ef );
+
+ /**
+ * The current type of "extra field" that will be used for new files.
+ * @return the current type of "extra field"
+ * @see setExtraField()
+ */
+ ExtraField extraField() const;
+
+ /**
+ * Describes the compression type for a given file in the Zip archive.
+ */
+ enum Compression { NoCompression = 0, ///< Uncompressed.
+ DeflateCompression = 1 ///< Deflate compression method.
+ };
+
+
+ /**
+ * Call this before writeFile or prepareWriting, to define whether the next
+ * files to be written should be compressed or not.
+ * @param c the new compression mode
+ * @see compression()
+ */
+ void setCompression( Compression c );
+
+ /**
+ * The current compression mode that will be used for new files.
+ * @return the current compression mode
+ * @see setCompression()
+ */
+ Compression compression() const;
+
+ /**
+ * If an archive is opened for writing then you can add a new file
+ * using this function.
+ * This method takes the whole data at once.
+ * @param name can include subdirs e.g. path/to/the/file
+ * @param user the user owning the file
+ * @param group the group owning the file
+ * @param size the size of the file
+ * @param data a pointer to the data
+ * @return true if successful, false otherwise
+ */
+ virtual bool writeFile( const TQString& name, const TQString& user, const TQString& group, uint size, const char* data ); // BC: remove reimplementation for KDE-4.0
+
+ /**
+ * Alternative method for writing: call prepareWriting(), then feed the data
+ * in small chunks using writeData(), and call doneWriting() when done.
+ * @param name can include subdirs e.g. path/to/the/file
+ * @param user the user owning the file
+ * @param group the group owning the file
+ * @param size unused argument
+ * @return true if successful, false otherwise
+ */
+ virtual bool prepareWriting( const TQString& name, const TQString& user, const TQString& group, uint size );
+
+ // TODO(BIC) make virtual. For now it must be implemented by virtual_hook.
+ bool writeSymLink(const TQString &name, const TQString &target,
+ const TQString &user, const TQString &group,
+ mode_t perm, time_t atime, time_t mtime, time_t ctime);
+ // TODO(BIC) make virtual. For now it must be implemented by virtual_hook.
+ bool prepareWriting( const TQString& name, const TQString& user,
+ const TQString& group, uint size, mode_t perm,
+ time_t atime, time_t mtime, time_t ctime );
+ // TODO(BIC) make virtual. For now it must be implemented by virtual_hook.
+ bool writeFile( const TQString& name, const TQString& user, const TQString& group,
+ uint size, mode_t perm, time_t atime, time_t mtime,
+ time_t ctime, const char* data );
+ /**
+ * Write data to a file that has been created using prepareWriting().
+ * @param data a pointer to the data
+ * @param size the size of the chunk
+ * @return true if successful, false otherwise
+ */
+ bool writeData( const char* data, uint size ); // TODO make virtual
+
+ /**
+ * Write data to a file that has been created using prepareWriting().
+ * @param size the size of the file
+ * @return true if successful, false otherwise
+ */
+ virtual bool doneWriting( uint size );
+
+protected:
+ /**
+ * Opens the archive for reading.
+ * Parses the directory listing of the archive
+ * and creates the KArchiveDirectory/KArchiveFile entries.
+ * @param mode the mode of the file
+ */
+ virtual bool openArchive( int mode );
+ /// Closes the archive
+ virtual bool closeArchive();
+
+ /**
+ * @internal Not needed for zip
+ */
+ virtual bool writeDir( const TQString& name, const TQString& user, const TQString& group) { Q_UNUSED(name); Q_UNUSED(user); Q_UNUSED(group); return true; }
+ // TODO(BIC) uncomment and make virtual for KDE 4.
+// bool writeDir( const TQString& name, const TQString& user, const TQString& group,
+// mode_t perm, time_t atime, time_t mtime, time_t ctime );
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+ /** @internal for virtual_hook */
+ // from KArchive
+ bool writeData_impl( const char* data, uint size );
+ bool prepareWriting_impl(const TQString& name, const TQString& user,
+ const TQString& group, uint size, mode_t perm,
+ time_t atime, time_t mtime, time_t ctime);
+ bool writeSymLink_impl(const TQString &name, const TQString &target,
+ const TQString &user, const TQString &group,
+ mode_t perm, time_t atime, time_t mtime, time_t ctime);
+private:
+ void abort();
+
+private:
+ TQString m_filename;
+ class KZipPrivate;
+ KZipPrivate * d;
+};
+
+
+/**
+ * @internal
+ */
+class TDEIO_EXPORT KZipFileEntry : public KArchiveFile
+{
+public:
+ /*KZipFileEntry() : st(-1)
+ {}*/
+ KZipFileEntry( KZip* zip, const TQString& name, int access, int date,
+ const TQString& user, const TQString& group, const TQString& symlink,
+ const TQString& path, TQ_LONG start, TQ_LONG uncompressedSize,
+ int encoding, TQ_LONG compressedSize) :
+ KArchiveFile( zip, name, access, date, user, group, symlink,
+ start, uncompressedSize ),
+ m_crc(0),
+ m_compressedSize(compressedSize),
+ m_headerStart(0),
+ m_encoding(encoding),
+ m_path( path )
+ {}
+ int encoding() const { return m_encoding; }
+ TQ_LONG compressedSize() const { return m_compressedSize; }
+
+ /// Only used when writing
+ void setCompressedSize(TQ_LONG compressedSize) { m_compressedSize = compressedSize; }
+
+ /// Header start: only used when writing
+ void setHeaderStart(TQ_LONG headerstart) { m_headerStart = headerstart; }
+ TQ_LONG headerStart() const {return m_headerStart; }
+
+ /// CRC: only used when writing
+ unsigned long crc32() const { return m_crc; }
+ void setCRC32(unsigned long crc32) { m_crc=crc32; }
+
+ /// Name with complete path - KArchiveFile::name() is the filename only (no path)
+ TQString path() const { return m_path; }
+
+ /**
+ * @return the content of this file.
+ * Call data() with care (only once per file), this data isn't cached.
+ */
+ virtual TQByteArray data() const;
+
+ /**
+ * This method returns a TQIODevice to read the file contents.
+ * This is obviously for reading only.
+ * Note that the ownership of the device is being transferred to the caller,
+ * who will have to delete it.
+ * The returned device auto-opens (in readonly mode), no need to open it.
+ */
+ TQIODevice* device() const; // WARNING, not virtual!
+
+private:
+ unsigned long m_crc;
+ TQ_LONG m_compressedSize;
+ TQ_LONG m_headerStart;
+ int m_encoding;
+ TQString m_path;
+ // KDE4: d pointer or at least some int for future extensions
+};
+
+#endif
diff --git a/kio/kio/lex.c b/tdeio/tdeio/lex.c
index 99848a2f3..99848a2f3 100644
--- a/kio/kio/lex.c
+++ b/tdeio/tdeio/lex.c
diff --git a/kio/kio/lex.l b/tdeio/tdeio/lex.l
index 073a34965..073a34965 100644
--- a/kio/kio/lex.l
+++ b/tdeio/tdeio/lex.l
diff --git a/tdeio/tdeio/metainfojob.cpp b/tdeio/tdeio/metainfojob.cpp
new file mode 100644
index 000000000..d9a31ab0e
--- /dev/null
+++ b/tdeio/tdeio/metainfojob.cpp
@@ -0,0 +1,184 @@
+// -*- c++ -*-
+// vim: ts=4 sw=4 et
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Rolf Magnus <ramagnus@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation version 2.0.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+ $Id$
+*/
+
+#include <kdatastream.h> // Do not remove, needed for correct bool serialization
+#include <tdefileitem.h>
+#include <kdebug.h>
+#include <tdefilemetainfo.h>
+#include <tdeio/kservice.h>
+#include <tdeparts/componentfactory.h>
+
+#include <tqtimer.h>
+
+#include "metainfojob.moc"
+
+using namespace TDEIO;
+
+struct TDEIO::MetaInfoJobPrivate
+{
+ KFileItemList items; // all the items we got
+ KFileItemListIterator* currentItem; // argh! No default constructor
+ bool deleteItems; // Delete the KFileItems when done?
+ bool succeeded; // if the current item is ok
+};
+
+MetaInfoJob::MetaInfoJob(const KFileItemList &items, bool deleteItems)
+ : TDEIO::Job(false /* no GUI */)
+{
+ d = new MetaInfoJobPrivate;
+ d->deleteItems = deleteItems;
+ d->succeeded = false;
+ d->items = items;
+ d->currentItem = new KFileItemListIterator(d->items);
+
+ d->items.setAutoDelete(deleteItems);
+
+ if (d->currentItem->isEmpty())
+ {
+ kdDebug(7007) << "nothing to do for the MetaInfoJob\n";
+ emitResult();
+ return;
+ }
+
+ kdDebug(7007) << "starting MetaInfoJob\n";
+
+ // Return to event loop first, determineNextFile() might delete this;
+ // (no idea what that means, it comes from previewjob)
+ TQTimer::singleShot(0, this, TQT_SLOT(start()));
+}
+
+MetaInfoJob::~MetaInfoJob()
+{
+ delete d->currentItem;
+ delete d;
+}
+
+void MetaInfoJob::start()
+{
+ getMetaInfo();
+}
+
+void MetaInfoJob::removeItem(const KFileItem* item)
+{
+ if (d->currentItem->current() == item)
+ {
+ subjobs.first()->kill();
+ subjobs.removeFirst();
+ determineNextFile();
+ }
+
+ d->items.remove(d->items.find(item));
+}
+
+void MetaInfoJob::determineNextFile()
+{
+ if (d->currentItem->atLast())
+ {
+ kdDebug(7007) << "finished MetaInfoJob\n";
+ emitResult();
+ return;
+ }
+
+ ++(*d->currentItem);
+ d->succeeded = false;
+
+ // does the file item already have the needed info? Then shortcut
+ if (d->currentItem->current()->metaInfo(false).isValid())
+ {
+// kdDebug(7007) << "Is already valid *************************\n";
+ emit gotMetaInfo(d->currentItem->current());
+ determineNextFile();
+ return;
+ }
+
+ getMetaInfo();
+}
+
+void MetaInfoJob::slotResult( TDEIO::Job *job )
+{
+ subjobs.remove(job);
+ Q_ASSERT(subjobs.isEmpty()); // We should have only one job at a time ...
+
+ determineNextFile();
+}
+
+void MetaInfoJob::getMetaInfo()
+{
+ Q_ASSERT(!d->currentItem->isEmpty());
+
+ KURL URL;
+ URL.setProtocol("metainfo");
+ URL.setPath(d->currentItem->current()->url().path());
+
+ TDEIO::TransferJob* job = TDEIO::get(URL, false, false);
+ addSubjob(job);
+
+ connect(job, TQT_SIGNAL(data(TDEIO::Job *, const TQByteArray &)),
+ this, TQT_SLOT(slotMetaInfo(TDEIO::Job *, const TQByteArray &)));
+
+ job->addMetaData("mimeType", d->currentItem->current()->mimetype());
+}
+
+
+void MetaInfoJob::slotMetaInfo(TDEIO::Job*, const TQByteArray &data)
+{
+ KFileMetaInfo info;
+ TQDataStream s(data, IO_ReadOnly);
+
+ s >> info;
+
+ d->currentItem->current()->setMetaInfo(info);
+ emit gotMetaInfo(d->currentItem->current());
+ d->succeeded = true;
+}
+
+TQStringList MetaInfoJob::availablePlugins()
+{
+ TQStringList result;
+ KTrader::OfferList plugins = KTrader::self()->query("KFilePlugin");
+ for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
+ result.append((*it)->desktopEntryName());
+ return result;
+}
+
+TQStringList MetaInfoJob::supportedMimeTypes()
+{
+ TQStringList result;
+ KTrader::OfferList plugins = KTrader::self()->query("KFilePlugin");
+ for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
+ result += (*it)->property("MimeTypes").toStringList();
+ return result;
+}
+
+TDEIO_EXPORT MetaInfoJob *TDEIO::fileMetaInfo( const KFileItemList &items)
+{
+ return new MetaInfoJob(items, false);
+}
+
+TDEIO_EXPORT MetaInfoJob *TDEIO::fileMetaInfo( const KURL::List &items)
+{
+ KFileItemList fileItems;
+ for (KURL::List::ConstIterator it = items.begin(); it != items.end(); ++it)
+ fileItems.append(new KFileItem(KFileItem::Unknown, KFileItem::Unknown, *it, true));
+ return new MetaInfoJob(fileItems, true);
+}
+
diff --git a/tdeio/tdeio/metainfojob.h b/tdeio/tdeio/metainfojob.h
new file mode 100644
index 000000000..3a9fab67e
--- /dev/null
+++ b/tdeio/tdeio/metainfojob.h
@@ -0,0 +1,119 @@
+// -*- c++ -*-
+// vim: ts=4 sw=4 et
+/* This file is part of the KDE libraries
+ Copyright (C) 2001 Rolf Magnus <ramagnus@kde.org>
+ parts of this taken from previewjob.h
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation version 2.0.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_metainfojob_h__
+#define __kio_metainfojob_h__
+
+#include <tdeio/job.h>
+#include <tdefileitem.h>
+
+namespace TDEIO {
+ /**
+ * MetaInfoJob is a KIO Job to retrieve meta information from files.
+ *
+ * @short KIO Job to retrieve meta information from files.
+ * @since 3.1
+ */
+ class TDEIO_EXPORT MetaInfoJob : public TDEIO::Job
+ {
+ Q_OBJECT
+ public:
+ /**
+ * Creates a new MetaInfoJob.
+ * @param items A list of KFileItems to get the metainfo for
+ * @param deleteItems If true, the finished KFileItems are deleted
+ */
+ MetaInfoJob(const KFileItemList &items, bool deleteItems = false);
+ virtual ~MetaInfoJob();
+
+ /**
+ * Removes an item from metainfo extraction.
+ *
+ * @param item the item that should be removed from the queue
+ */
+ void removeItem( const KFileItem *item );
+
+ /**
+ * Returns a list of all available metainfo plugins. The list
+ * contains the basenames of the plugins' .desktop files (no path,
+ * no .desktop).
+ * @return the list of available meta info plugins
+ */
+ static TQStringList availablePlugins();
+
+ /**
+ * Returns a list of all supported MIME types. The list can
+ * contain entries like text/ * (without the space).
+ * @return the list of MIME types that are supported
+ */
+ static TQStringList supportedMimeTypes();
+
+ signals:
+ /**
+ * Emitted when the meta info for @p item has been successfully
+ * retrieved.
+ * @param item the KFileItem describing the fetched item
+ */
+ void gotMetaInfo( const KFileItem *item );
+ /**
+ * Emitted when metainfo for @p item could not be extracted,
+ * either because a plugin for its MIME type does not
+ * exist, or because something went wrong.
+ * @param item the KFileItem of the file that failed
+ */
+ void failed( const KFileItem *item );
+
+ protected:
+ void getMetaInfo();
+
+ protected slots:
+ virtual void slotResult( TDEIO::Job *job );
+
+ private slots:
+ void start();
+ void slotMetaInfo(TDEIO::Job *, const TQByteArray &);
+
+ private:
+ void determineNextFile();
+// void saveMetaInfo(const TQByteArray info);
+
+ private:
+ struct MetaInfoJobPrivate *d;
+ };
+
+ /**
+ * Retrieves meta information for the given items.
+ *
+ * @param items files to get metainfo for
+ * @return the MetaInfoJob to retrieve the items
+ */
+ TDEIO_EXPORT MetaInfoJob* fileMetaInfo(const KFileItemList& items);
+
+ /**
+ * Retrieves meta information for the given items.
+ *
+ * @param items files to get metainfo for
+ * @return the MetaInfoJob to retrieve the items
+ */
+ TDEIO_EXPORT MetaInfoJob* fileMetaInfo(const KURL::List& items);
+}
+
+#endif
diff --git a/tdeio/tdeio/netaccess.cpp b/tdeio/tdeio/netaccess.cpp
new file mode 100644
index 000000000..89830d88b
--- /dev/null
+++ b/tdeio/tdeio/netaccess.cpp
@@ -0,0 +1,536 @@
+/* $Id$
+
+ This file is part of the KDE libraries
+ Copyright (C) 1997 Torben Weis (weis@kde.org)
+ Copyright (C) 1998 Matthias Ettrich (ettrich@kde.org)
+ Copyright (C) 1999 David Faure (faure@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <signal.h>
+#include <unistd.h>
+
+#include <cstring>
+
+#include <tqstring.h>
+#include <tqapplication.h>
+#include <tqfile.h>
+#include <tqmetaobject.h>
+
+#include <kapplication.h>
+#include <klocale.h>
+#include <ktempfile.h>
+#include <kdebug.h>
+#include <kurl.h>
+#include <tdeio/job.h>
+#include <tdeio/scheduler.h>
+
+#include "tdeio/netaccess.h"
+
+using namespace TDEIO;
+
+TQString * NetAccess::lastErrorMsg;
+int NetAccess::lastErrorCode = 0;
+TQStringList* NetAccess::tmpfiles;
+
+bool NetAccess::download(const KURL& u, TQString & target)
+{
+ return NetAccess::download (u, target, 0);
+}
+
+bool NetAccess::download(const KURL& u, TQString & target, TQWidget* window)
+{
+ if (u.isLocalFile()) {
+ // file protocol. We do not need the network
+ target = u.path();
+ bool accessible = checkAccess(target, R_OK);
+ if(!accessible)
+ {
+ if(!lastErrorMsg)
+ lastErrorMsg = new TQString;
+ *lastErrorMsg = i18n("File '%1' is not readable").arg(target);
+ lastErrorCode = ERR_COULD_NOT_READ;
+ }
+ return accessible;
+ }
+
+ if (target.isEmpty())
+ {
+ KTempFile tmpFile;
+ target = tmpFile.name();
+ if (!tmpfiles)
+ tmpfiles = new TQStringList;
+ tmpfiles->append(target);
+ }
+
+ NetAccess kioNet;
+ KURL dest;
+ dest.setPath( target );
+ return kioNet.filecopyInternal( u, dest, -1, true /*overwrite*/,
+ false, window, false /*copy*/);
+}
+
+bool NetAccess::upload(const TQString& src, const KURL& target)
+{
+ return NetAccess::upload(src, target, 0);
+}
+
+bool NetAccess::upload(const TQString& src, const KURL& target, TQWidget* window)
+{
+ if (target.isEmpty())
+ return false;
+
+ // If target is local... well, just copy. This can be useful
+ // when the client code uses a temp file no matter what.
+ // Let's make sure it's not the exact same file though
+ if (target.isLocalFile() && target.path() == src)
+ return true;
+
+ NetAccess kioNet;
+ KURL s;
+ s.setPath(src);
+ return kioNet.filecopyInternal( s, target, -1, true /*overwrite*/,
+ false, window, false /*copy*/ );
+}
+
+bool NetAccess::copy( const KURL & src, const KURL & target )
+{
+ return NetAccess::file_copy( src, target, -1, false /*not overwrite*/, false, 0L );
+}
+
+bool NetAccess::copy( const KURL & src, const KURL & target, TQWidget* window )
+{
+ return NetAccess::file_copy( src, target, -1, false /*not overwrite*/, false, window );
+}
+
+bool NetAccess::file_copy( const KURL& src, const KURL& target, int permissions,
+ bool overwrite, bool resume, TQWidget* window )
+{
+ NetAccess kioNet;
+ return kioNet.filecopyInternal( src, target, permissions, overwrite, resume,
+ window, false /*copy*/ );
+}
+
+
+bool NetAccess::file_move( const KURL& src, const KURL& target, int permissions,
+ bool overwrite, bool resume, TQWidget* window )
+{
+ NetAccess kioNet;
+ return kioNet.filecopyInternal( src, target, permissions, overwrite, resume,
+ window, true /*move*/ );
+}
+
+bool NetAccess::dircopy( const KURL & src, const KURL & target )
+{
+ return NetAccess::dircopy( src, target, 0 );
+}
+
+bool NetAccess::dircopy( const KURL & src, const KURL & target, TQWidget* window )
+{
+ KURL::List srcList;
+ srcList.append( src );
+ return NetAccess::dircopy( srcList, target, window );
+}
+
+bool NetAccess::dircopy( const KURL::List & srcList, const KURL & target, TQWidget* window )
+{
+ NetAccess kioNet;
+ return kioNet.dircopyInternal( srcList, target, window, false /*copy*/ );
+}
+
+bool NetAccess::move( const KURL& src, const KURL& target, TQWidget* window )
+{
+ KURL::List srcList;
+ srcList.append( src );
+ return NetAccess::move( srcList, target, window );
+}
+
+bool NetAccess::move( const KURL::List& srcList, const KURL& target, TQWidget* window )
+{
+ NetAccess kioNet;
+ return kioNet.dircopyInternal( srcList, target, window, true /*move*/ );
+}
+
+bool NetAccess::exists( const KURL & url )
+{
+ return NetAccess::exists( url, false, 0 );
+}
+
+bool NetAccess::exists( const KURL & url, TQWidget* window )
+{
+ return NetAccess::exists( url, false, window );
+}
+
+bool NetAccess::exists( const KURL & url, bool source )
+{
+ return NetAccess::exists( url, source, 0 );
+}
+
+bool NetAccess::exists( const KURL & url, bool source, TQWidget* window )
+{
+ if ( url.isLocalFile() )
+ return TQFile::exists( url.path() );
+ NetAccess kioNet;
+ return kioNet.statInternal( url, 0 /*no details*/, source, window );
+}
+
+bool NetAccess::stat( const KURL & url, TDEIO::UDSEntry & entry )
+{
+ return NetAccess::stat( url, entry, 0 );
+}
+
+bool NetAccess::stat( const KURL & url, TDEIO::UDSEntry & entry, TQWidget* window )
+{
+ NetAccess kioNet;
+ bool ret = kioNet.statInternal( url, 2 /*all details*/, true /*source*/, window );
+ if (ret)
+ entry = kioNet.m_entry;
+ return ret;
+}
+
+KURL NetAccess::mostLocalURL(const KURL & url, TQWidget* window)
+{
+ if ( url.isLocalFile() )
+ {
+ return url;
+ }
+
+ TDEIO::UDSEntry entry;
+ if (!stat(url, entry, window))
+ {
+ return url;
+ }
+
+ TQString path;
+
+ // Extract the local path from the TDEIO::UDSEntry
+ TDEIO::UDSEntry::ConstIterator it = entry.begin();
+ const TDEIO::UDSEntry::ConstIterator end = entry.end();
+ for ( ; it != end; ++it )
+ {
+ if ( (*it).m_uds == TDEIO::UDS_LOCAL_PATH )
+ {
+ path = (*it).m_str;
+ break;
+ }
+ }
+
+ if ( !path.isEmpty() )
+ {
+ KURL new_url;
+ new_url.setPath(path);
+ return new_url;
+ }
+
+ return url;
+}
+
+
+bool NetAccess::del( const KURL & url )
+{
+ return NetAccess::del( url, 0 );
+}
+
+bool NetAccess::del( const KURL & url, TQWidget* window )
+{
+ NetAccess kioNet;
+ return kioNet.delInternal( url, window );
+}
+
+bool NetAccess::mkdir( const KURL & url, int permissions )
+{
+ return NetAccess::mkdir( url, 0, permissions );
+}
+
+bool NetAccess::mkdir( const KURL & url, TQWidget* window, int permissions )
+{
+ NetAccess kioNet;
+ return kioNet.mkdirInternal( url, permissions, window );
+}
+
+TQString NetAccess::fish_execute( const KURL & url, const TQString command, TQWidget* window )
+{
+ NetAccess kioNet;
+ return kioNet.fish_executeInternal( url, command, window );
+}
+
+bool NetAccess::synchronousRun( Job* job, TQWidget* window, TQByteArray* data,
+ KURL* finalURL, TQMap<TQString, TQString>* metaData )
+{
+ NetAccess kioNet;
+ return kioNet.synchronousRunInternal( job, window, data, finalURL, metaData );
+}
+
+TQString NetAccess::mimetype( const KURL& url )
+{
+ NetAccess kioNet;
+ return kioNet.mimetypeInternal( url, 0 );
+}
+
+TQString NetAccess::mimetype( const KURL& url, TQWidget* window )
+{
+ NetAccess kioNet;
+ return kioNet.mimetypeInternal( url, window );
+}
+
+void NetAccess::removeTempFile(const TQString& name)
+{
+ if (!tmpfiles)
+ return;
+ if (tmpfiles->contains(name))
+ {
+ unlink(TQFile::encodeName(name));
+ tmpfiles->remove(name);
+ }
+}
+
+bool NetAccess::filecopyInternal(const KURL& src, const KURL& target, int permissions,
+ bool overwrite, bool resume, TQWidget* window, bool move)
+{
+ bJobOK = true; // success unless further error occurs
+
+ TDEIO::Scheduler::checkSlaveOnHold(true);
+ TDEIO::Job * job = move
+ ? TDEIO::file_move( src, target, permissions, overwrite, resume )
+ : TDEIO::file_copy( src, target, permissions, overwrite, resume );
+ job->setWindow (window);
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+
+ enter_loop();
+ return bJobOK;
+}
+
+bool NetAccess::dircopyInternal(const KURL::List& src, const KURL& target,
+ TQWidget* window, bool move)
+{
+ bJobOK = true; // success unless further error occurs
+
+ TDEIO::Job * job = move
+ ? TDEIO::move( src, target )
+ : TDEIO::copy( src, target );
+ job->setWindow (window);
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+
+ enter_loop();
+ return bJobOK;
+}
+
+bool NetAccess::statInternal( const KURL & url, int details, bool source,
+ TQWidget* window )
+{
+ bJobOK = true; // success unless further error occurs
+ TDEIO::StatJob * job = TDEIO::stat( url, !url.isLocalFile() && !url.url().startsWith("beagle:?") );
+ job->setWindow (window);
+ job->setDetails( details );
+ job->setSide( source );
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+ enter_loop();
+ return bJobOK;
+}
+
+bool NetAccess::delInternal( const KURL & url, TQWidget* window )
+{
+ bJobOK = true; // success unless further error occurs
+ TDEIO::Job * job = TDEIO::del( url );
+ job->setWindow (window);
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+ enter_loop();
+ return bJobOK;
+}
+
+bool NetAccess::mkdirInternal( const KURL & url, int permissions,
+ TQWidget* window )
+{
+ bJobOK = true; // success unless further error occurs
+ TDEIO::Job * job = TDEIO::mkdir( url, permissions );
+ job->setWindow (window);
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+ enter_loop();
+ return bJobOK;
+}
+
+TQString NetAccess::mimetypeInternal( const KURL & url, TQWidget* window )
+{
+ bJobOK = true; // success unless further error occurs
+ m_mimetype = TQString::fromLatin1("unknown");
+ TDEIO::Job * job = TDEIO::mimetype( url );
+ job->setWindow (window);
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+ connect( job, TQT_SIGNAL( mimetype (TDEIO::Job *, const TQString &) ),
+ this, TQT_SLOT( slotMimetype (TDEIO::Job *, const TQString &) ) );
+ enter_loop();
+ return m_mimetype;
+}
+
+void NetAccess::slotMimetype( TDEIO::Job *, const TQString & type )
+{
+ m_mimetype = type;
+}
+
+TQString NetAccess::fish_executeInternal(const KURL & url, const TQString command, TQWidget* window)
+{
+ TQString target, remoteTempFileName, resultData;
+ KURL tempPathUrl;
+ KTempFile tmpFile;
+ tmpFile.setAutoDelete( true );
+
+ if( url.protocol() == "fish" )
+ {
+ // construct remote temp filename
+ tempPathUrl = url;
+ remoteTempFileName = tmpFile.name();
+ // only need the filename KTempFile adds some KDE specific dirs
+ // that probably does not exist on the remote side
+ int pos = remoteTempFileName.findRev('/');
+ remoteTempFileName = "/tmp/fishexec_" + remoteTempFileName.mid(pos + 1);
+ tempPathUrl.setPath( remoteTempFileName );
+ bJobOK = true; // success unless further error occurs
+ TQByteArray packedArgs;
+ TQDataStream stream( packedArgs, IO_WriteOnly );
+
+ stream << int('X') << tempPathUrl << command;
+
+ TDEIO::Job * job = TDEIO::special( tempPathUrl, packedArgs, true );
+ job->setWindow( window );
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+ enter_loop();
+
+ // since the TDEIO::special does not provide feedback we need to download the result
+ if( NetAccess::download( tempPathUrl, target, window ) )
+ {
+ TQFile resultFile( target );
+
+ if (resultFile.open( IO_ReadOnly ))
+ {
+ TQTextStream ts( &resultFile );
+ ts.setEncoding( TQTextStream::Locale ); // Locale??
+ resultData = ts.read();
+ resultFile.close();
+ NetAccess::del( tempPathUrl, window );
+ }
+ }
+ }
+ else
+ {
+ resultData = i18n( "ERROR: Unknown protocol '%1'" ).arg( url.protocol() );
+ }
+ return resultData;
+}
+
+bool NetAccess::synchronousRunInternal( Job* job, TQWidget* window, TQByteArray* data,
+ KURL* finalURL, TQMap<TQString,TQString>* metaData )
+{
+ job->setWindow( window );
+
+ m_metaData = metaData;
+ if ( m_metaData ) {
+ for ( TQMap<TQString, TQString>::iterator it = m_metaData->begin(); it != m_metaData->end(); ++it ) {
+ job->addMetaData( it.key(), it.data() );
+ }
+ }
+
+ if ( finalURL ) {
+ SimpleJob *sj = dynamic_cast<SimpleJob*>( job );
+ if ( sj ) {
+ m_url = sj->url();
+ }
+ }
+
+ connect( job, TQT_SIGNAL( result (TDEIO::Job *) ),
+ this, TQT_SLOT( slotResult (TDEIO::Job *) ) );
+
+ TQMetaObject *meta = job->metaObject();
+
+ static const char dataSignal[] = "data(TDEIO::Job*,const " TQBYTEARRAY_OBJECT_NAME_STRING "&)";
+ if ( meta->findSignal( dataSignal ) != -1 ) {
+ connect( job, TQT_SIGNAL(data(TDEIO::Job*,const TQByteArray&)),
+ this, TQT_SLOT(slotData(TDEIO::Job*,const TQByteArray&)) );
+ }
+
+ static const char redirSignal[] = "redirection(TDEIO::Job*,const KURL&)";
+ if ( meta->findSignal( redirSignal ) != -1 ) {
+ connect( job, TQT_SIGNAL(redirection(TDEIO::Job*,const KURL&)),
+ this, TQT_SLOT(slotRedirection(TDEIO::Job*, const KURL&)) );
+ }
+
+ enter_loop();
+
+ if ( finalURL )
+ *finalURL = m_url;
+ if ( data )
+ *data = m_data;
+
+ return bJobOK;
+}
+
+// If a troll sees this, he kills me
+void tqt_enter_modal( TQWidget *widget );
+void tqt_leave_modal( TQWidget *widget );
+
+void NetAccess::enter_loop()
+{
+ TQWidget dummy(0,0,(WFlags)(WType_Dialog | WShowModal));
+ dummy.setFocusPolicy( TQ_NoFocus );
+ tqt_enter_modal(&dummy);
+ tqApp->enter_loop();
+ tqt_leave_modal(&dummy);
+}
+
+void NetAccess::slotResult( TDEIO::Job * job )
+{
+ lastErrorCode = job->error();
+ bJobOK = !job->error();
+ if ( !bJobOK )
+ {
+ if ( !lastErrorMsg )
+ lastErrorMsg = new TQString;
+ *lastErrorMsg = job->errorString();
+ }
+ if ( job->isA("TDEIO::StatJob") )
+ m_entry = static_cast<TDEIO::StatJob *>(job)->statResult();
+
+ if ( m_metaData )
+ *m_metaData = job->metaData();
+
+ tqApp->exit_loop();
+}
+
+void NetAccess::slotData( TDEIO::Job*, const TQByteArray& data )
+{
+ if ( data.isEmpty() )
+ return;
+
+ unsigned offset = m_data.size();
+ m_data.resize( offset + data.size() );
+ std::memcpy( m_data.data() + offset, data.data(), data.size() );
+}
+
+void NetAccess::slotRedirection( TDEIO::Job*, const KURL& url )
+{
+ m_url = url;
+}
+
+#include "netaccess.moc"
diff --git a/tdeio/tdeio/netaccess.h b/tdeio/tdeio/netaccess.h
new file mode 100644
index 000000000..356a91738
--- /dev/null
+++ b/tdeio/tdeio/netaccess.h
@@ -0,0 +1,540 @@
+/*
+ This file is part of the KDE libraries
+ Copyright (C) 1997 Torben Weis (weis@kde.org)
+ Copyright (C) 1998 Matthias Ettrich (ettrich@kde.org)
+ Copyright (C) 1999-2004 David Faure (faure@kde.org)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_netaccess_h
+#define __kio_netaccess_h
+
+#include <tqobject.h>
+#include <tqstring.h>
+#include <tdeio/global.h>
+
+class TQStringList;
+class TQWidget;
+class KURL;
+template<typename T, typename K> class TQMap;
+
+namespace TDEIO {
+
+ class Job;
+
+ /**
+ * Net Transparency.
+ *
+ * NetAccess allows you to do simple file operation (load, save,
+ * copy, delete...) without working with TDEIO::Job directly.
+ * Whereas a TDEIO::Job is asynchronous, meaning that the
+ * developer has to connect slots for it, TDEIO::NetAccess provides
+ * synchronous downloads and uploads, as well as temporary file
+ * creation and removal. The functions appear to be blocking,
+ * but the Qt event loop continues running while the operations
+ * are handled. This means that the GUI will not freeze.
+ *
+ * This class isn't meant to be used as a class but only as a simple
+ * namespace for static functions, though an instance of the class
+ * is built for internal purposes.
+ *
+ * Port to kio done by David Faure, faure@kde.org
+ *
+ * @short Provides an easy, synchronous interface to KIO file operations.
+ */
+class TDEIO_EXPORT NetAccess : public TQObject
+{
+ Q_OBJECT
+
+public:
+ /**
+ * Downloads a file from an arbitrary URL (@p src) to a
+ * temporary file on the local filesystem (@p target).
+ *
+ * If the argument
+ * for @p target is an empty string, download will generate a
+ * unique temporary filename in /tmp. Since @p target is a reference
+ * to TQString you can access this filename easily. Download will
+ * return true if the download was successful, otherwise false.
+ *
+ * Special case:
+ * If the URL is of kind file:, then no downloading is
+ * processed but the full filename is returned in @p target.
+ * That means you @em have to take care about the @p target argument.
+ * (This is very easy to do, please see the example below.)
+ *
+ * Download is synchronous. That means you can use it like
+ * this, (assuming @p u is a string which represents a URL and your
+ * application has a loadFile() function):
+ *
+ * \code
+ * TQString tmpFile;
+ * if( TDEIO::NetAccess::download( u, tmpFile, window ) )
+ * {
+ * loadFile( tmpFile );
+ * TDEIO::NetAccess::removeTempFile( tmpFile );
+ * } else {
+ * KMessageBox::error(this, TDEIO::NetAccess::lastErrorString() );
+ * }
+ * \endcode
+ *
+ * Of course, your user interface will still process exposure/repaint
+ * events during the download.
+ *
+ * If the download fails, lastError() and lastErrorString() will be set.
+ *
+ * @param src URL Reference to the file to download.
+ * @param target String containing the final local location of the
+ * file. If you insert an empty string, it will
+ * return a location in a temporary spot. <B>Note:</B>
+ * you are responsible for the removal of this file when
+ * you are finished reading it using removeTempFile.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @return true if successful, false for failure. Use lastErrorString() to
+ * get the reason it failed.
+ *
+ * @see lastErrorString()
+ * @since 3.2
+ */
+ static bool download(const KURL& src, TQString & target, TQWidget* window);
+
+ /**
+ * @deprecated. Use the function above instead.
+ */
+ static bool download(const KURL& src, TQString & target) KDE_DEPRECATED;
+
+ /**
+ * Removes the specified file if and only if it was created
+ * by TDEIO::NetAccess as a temporary file for a former download.
+ *
+ * Note: This means that if you created your temporary with KTempFile,
+ * use KTempFile::unlink() or KTempFile::setAutoDelete() to have
+ * it removed.
+ *
+ * @param name Path to temporary file to remove. May not be
+ * empty.
+ */
+ static void removeTempFile(const TQString& name);
+
+ /**
+ * Uploads file @p src to URL @p target.
+ *
+ * Both must be specified, unlike download.
+ * Note that this is assumed to be used for saving a file over
+ * the network, so overwriting is set to true. This is not the
+ * case with copy.
+ *
+ * @param src URL Referencing the file to upload.
+ * @param target URL containing the final location of the file.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be cached
+ * only for a short duration after which the user will again be
+ * prompted for passwords as needed.
+ *
+ * @return true if successful, false for failure
+ * @since 3.2
+ */
+ static bool upload(const TQString& src, const KURL& target, TQWidget* window);
+
+ /**
+ * @deprecated. Use the function above instead.
+ */
+ static bool upload(const TQString& src, const KURL& target) KDE_DEPRECATED;
+
+ /**
+ * Alternative to upload for copying over the network.
+ * Overwrite is false, so this will fail if @p target exists.
+ *
+ * This one takes two URLs and is a direct equivalent
+ * of TDEIO::file_copy (not TDEIO::copy!).
+ * It will be renamed file_copy in KDE4, so better use file_copy.
+ *
+ * @param src URL Referencing the file to upload.
+ * @param target URL containing the final location of the file.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be cached
+ * only for a short duration after which the user will again be
+ * prompted for passwords as needed.
+ *
+ * @return true if successful, false for failure
+ */
+ static bool copy( const KURL& src, const KURL& target, TQWidget* window );
+ // KDE4: rename to file_copy
+
+ /**
+ * @deprecated. Use the function above instead.
+ */
+ static bool copy( const KURL& src, const KURL& target ) KDE_DEPRECATED;
+ // KDE4: merge with above
+
+ /**
+ * Full-fledged equivalent of TDEIO::file_copy
+ */
+ static bool file_copy( const KURL& src, const KURL& dest, int permissions=-1,
+ bool overwrite=false, bool resume=false, TQWidget* window = 0L );
+
+ /**
+ * Full-fledged equivalent of TDEIO::file_move.
+ * Moves or renames *one file*.
+ * @since 3.2
+ */
+ static bool file_move( const KURL& src, const KURL& target, int permissions=-1,
+ bool overwrite=false, bool resume=false, TQWidget* window = 0L );
+
+
+ /**
+ * Alternative method for copying over the network.
+ * Overwrite is false, so this will fail if @p target exists.
+ *
+ * This one takes two URLs and is a direct equivalent
+ * of TDEIO::copy!.
+ * This means that it can copy files and directories alike
+ * (it should have been named copy()).
+ *
+ * @param src URL Referencing the file to upload.
+ * @param target URL containing the final location of the
+ * file.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be cached
+ * only for a short duration after which the user will again be
+ * prompted for passwords as needed.
+ * @return true if successful, false for failure
+ */
+ static bool dircopy( const KURL& src, const KURL& target, TQWidget* window );
+
+ /**
+ * @deprecated. Use the function above instead.
+ */
+ static bool dircopy( const KURL& src, const KURL& target ) KDE_DEPRECATED; // KDE4: merge
+
+ /**
+ * Overloaded method, which takes a list of source URLs
+ */
+ static bool dircopy( const KURL::List& src, const KURL& target, TQWidget* window = 0L );
+
+ /**
+ * Full-fledged equivalent of TDEIO::move.
+ * Moves or renames one file or directory.
+ * @since 3.2
+ */
+ static bool move( const KURL& src, const KURL& target, TQWidget* window = 0L );
+
+ /**
+ * Full-fledged equivalent of TDEIO::move.
+ * Moves or renames a list of files or directories.
+ * @since 3.2
+ */
+ static bool move( const KURL::List& src, const KURL& target, TQWidget* window = 0L );
+
+ /**
+ * Tests whether a URL exists.
+ *
+ * @param url the URL we are testing
+ * @param source if true, we want to read from that URL.
+ * If false, we want to write to it.
+ * IMPORTANT: see documentation for TDEIO::stat for more details about this.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @return true if the URL exists and we can do the operation specified by
+ * @p source, false otherwise
+ * @since 3.2
+ */
+ static bool exists(const KURL& url, bool source, TQWidget* window);
+
+ /**
+ * @deprecated. Use the function above instead.
+ * @since 3.2
+ */
+ static bool exists(const KURL& url, TQWidget* window) KDE_DEPRECATED;
+
+ /**
+ * @deprecated. Use the function above instead.
+ */
+ static bool exists(const KURL& url) KDE_DEPRECATED;
+
+ /**
+ * @deprecated. Use the function above instead.
+ */
+ static bool exists(const KURL& url, bool source) KDE_DEPRECATED; // KDE4: merge
+
+ /**
+ * Tests whether a URL exists and return information on it.
+ *
+ * This is a convenience function for TDEIO::stat
+ * (it saves creating a slot and testing for the job result).
+ *
+ * @param url The URL we are testing.
+ * @param entry The result of the stat. Iterate over the list
+ * of atoms to get hold of name, type, size, etc., or use KFileItem.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @return true if successful, false for failure
+ */
+ static bool stat(const KURL& url, TDEIO::UDSEntry & entry, TQWidget* window);
+
+ /**
+ * @deprecated. Use the function above instead.
+ */
+ static bool stat(const KURL& url, TDEIO::UDSEntry & entry) KDE_DEPRECATED;
+
+ /**
+ * Tries to map a local URL for the given URL.
+ *
+ * This is a convenience function for TDEIO::stat + parsing the
+ * resulting UDSEntry.
+ *
+ * @param url The URL we are testing.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @return a local URL corresponding to the same ressource than the
+ * original URL, or the original URL if no local URL can be mapped
+ * @since 3.5
+ */
+ static KURL mostLocalURL(const KURL& url, TQWidget* window);
+
+ /**
+ * Deletes a file or a directory in a synchronous way.
+ *
+ * This is a convenience function for TDEIO::del
+ * (it saves creating a slot and testing for the job result).
+ *
+ * @param url The file or directory to delete.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @return true on success, false on failure.
+ */
+ static bool del( const KURL & url, TQWidget* window );
+
+ /**
+ * @deprecated. Use the function above instead. Passing NULL as the
+ * additional argument will give the same behaviour, but
+ * you should try to identify a suitable parent widget
+ * if at all possible.
+ */
+ static bool del( const KURL & url ) KDE_DEPRECATED;
+
+ /**
+ * Creates a directory in a synchronous way.
+ *
+ * This is a convenience function for @p TDEIO::mkdir
+ * (it saves creating a slot and testing for the job result).
+ *
+ * @param url The directory to create.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @param permissions directory permissions.
+ * @return true on success, false on failure.
+ */
+ static bool mkdir( const KURL & url, TQWidget* window, int permissions = -1 );
+
+ /**
+ * @deprecated. Use the function above instead. Passing NULL as the
+ * additional argument will give the same behaviour, but
+ * you should try to identify a suitable parent widget
+ * if at all possible.
+ */
+ static bool mkdir( const KURL & url, int permissions = -1 ) KDE_DEPRECATED;
+
+ /**
+ * Executes a remote process via the fish ioslave in a synchronous way.
+ *
+ * @param url The remote machine where the command should be executed.
+ * e.g. fish://someuser\@somehost:sshport/
+ * some special cases exist.
+ * fish://someuser\@localhost/
+ * will use su instead of ssh to connect and execute the command.
+ * fish://someuser\@localhost:port/
+ * will use ssh to connect and execute the command.
+ * @param command The command to be executed.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @return The resulting output of the @p command that is executed.
+ */
+ static TQString fish_execute( const KURL & url, const TQString command, TQWidget* window );
+
+ /**
+ * This function executes a job in a synchronous way.
+ * If a job fetches some data, pass a TQByteArray pointer as data parameter to this function
+ * and after the function returns it will contain all the data fetched by this job.
+ *
+ * <code>
+ * TDEIO::Job *job = TDEIO::get( url, false, false );
+ * TQMap<TQString, TQString> metaData;
+ * metaData.insert( "PropagateHttpHeader", "true" );
+ * if ( NetAccess::synchronousRun( job, 0, &data, &url, &metaData ) ) {
+ * TQString responseHeaders = metaData[ "HTTP-Headers" ];
+ * kdDebug()<<"Response header = "<< responseHeaders << endl;
+ * }
+ * </code>
+ *
+ * @param job job which the function will run. Note that after this function
+ * finishes running, job is deleted and you can't access it anymore!
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @param data if passed and relevant to this job then it will contain the data
+ * that was fetched by the job
+ * @param finalURL if passed will contain the final url of this job (it might differ
+ * from the one it was created with if there was a redirection)
+ * @param metaData you can pass a pointer to the map with meta data you wish to
+ * set on the job. After the job finishes this map will hold all the
+ * meta data from the job.
+ *
+ * @return true on success, false on failure.
+ *
+ * @since 3.4
+ */
+ static bool synchronousRun( Job* job, TQWidget* window, TQByteArray* data=0,
+ KURL* finalURL=0, TQMap<TQString,TQString>* metaData=0 );
+
+ /**
+ * @internal
+ * This function is not implemented!?
+ * (only mimetypeInternal)
+ *
+ * Determines the mimetype of a given URL.
+ *
+ * This is a convenience function for TDEIO::mimetype. You
+ * should call this only when really necessary.
+ * KMimeType::findByURL can determine extension a lot faster, but
+ * less reliably for remote files. Only when findByURL() returns
+ * unknown (application/octet-stream) then this one should be
+ * used.
+ *
+ * @param url The URL whose mimetype we are interested in.
+ * @param window main window associated with this job. This is used to
+ * automatically cache and discard authentication information
+ * as needed. If NULL, authentication information will be
+ * cached only for a short duration after which the user will
+ * again be prompted for passwords as needed.
+ * @return The mimetype name.
+ */
+ static TQString mimetype( const KURL & url, TQWidget* window );
+
+ /**
+ * @deprecated. Use the function above instead. Passing NULL as the
+ * additional argument will give the same behaviour, but
+ * you should try to identify a suitable parent widget
+ * if at all possible.
+ */
+ static TQString mimetype( const KURL & url ) KDE_DEPRECATED;
+
+ /**
+ * Returns the error string for the last job, in case it failed.
+ * Note that this is already translated.
+ * @return the last error string, or TQString::null
+ */
+ static TQString lastErrorString() { return lastErrorMsg ? *lastErrorMsg : TQString::null; }
+
+ /**
+ * Returns the error code for the last job, in case it failed.
+ * @return the last error code
+ * @since 3.3
+ */
+ static int lastError() { return lastErrorCode; }
+
+private:
+ /**
+ * Private constructor
+ */
+ NetAccess() : m_metaData(0), d(0) {}
+
+ /**
+ * Private destructor
+ */
+ ~NetAccess() {}
+
+ /**
+ * Internal methods
+ */
+ bool filecopyInternal(const KURL& src, const KURL& target, int permissions,
+ bool overwrite, bool resume, TQWidget* window, bool move);
+ bool dircopyInternal(const KURL::List& src, const KURL& target,
+ TQWidget* window, bool move);
+ bool statInternal(const KURL & url, int details, bool source, TQWidget* window = 0);
+
+ bool delInternal(const KURL & url, TQWidget* window = 0);
+ bool mkdirInternal(const KURL & url, int permissions, TQWidget* window = 0);
+ TQString fish_executeInternal(const KURL & url, const TQString command, TQWidget* window = 0);
+ bool synchronousRunInternal( Job* job, TQWidget* window, TQByteArray* data,
+ KURL* finalURL, TQMap<TQString,TQString>* metaData );
+
+ TQString mimetypeInternal(const KURL & url, TQWidget* window = 0);
+ void enter_loop();
+
+ /**
+ * List of temporary files
+ */
+ static TQStringList* tmpfiles;
+
+ static TQString* lastErrorMsg;
+ static int lastErrorCode;
+
+ friend class I_like_this_class;
+
+private slots:
+ void slotResult( TDEIO::Job * job );
+ void slotMimetype( TDEIO::Job * job, const TQString & type );
+ void slotData( TDEIO::Job*, const TQByteArray& );
+ void slotRedirection( TDEIO::Job*, const KURL& );
+
+private:
+ UDSEntry m_entry;
+ TQString m_mimetype;
+ TQByteArray m_data;
+ KURL m_url;
+ TQMap<TQString, TQString> *m_metaData;
+
+ /**
+ * Whether the download succeeded or not
+ */
+ bool bJobOK;
+
+private:
+ class NetAccessPrivate* d; // not really needed, the ctor is private already.
+};
+
+}
+
+#endif
diff --git a/tdeio/tdeio/observer.cpp b/tdeio/tdeio/observer.cpp
new file mode 100644
index 000000000..5e4e7aa87
--- /dev/null
+++ b/tdeio/tdeio/observer.cpp
@@ -0,0 +1,417 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Matej Koss <koss@miesto.sk>
+ David Faure <faure@kde.org>
+
+ $Id$
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <assert.h>
+
+#include <kdebug.h>
+#include <kapplication.h>
+#include <dcopclient.h>
+#include <kurl.h>
+
+#include "jobclasses.h"
+#include "observer.h"
+
+#include "uiserver_stub.h"
+
+#include "passdlg.h"
+#include "slavebase.h"
+#include "observer_stub.h"
+#include <kmessagebox.h>
+#include <ksslinfodlg.h>
+#include <ksslcertdlg.h>
+#include <ksslcertificate.h>
+#include <ksslcertchain.h>
+#include <klocale.h>
+
+using namespace TDEIO;
+
+template class TQIntDict<TDEIO::Job>;
+
+Observer * Observer::s_pObserver = 0L;
+
+const int KDEBUG_OBSERVER = 7007; // Should be 7028
+
+Observer::Observer() : DCOPObject("TDEIO::Observer")
+{
+ // Register app as able to receive DCOP messages
+ if (kapp && !kapp->dcopClient()->isAttached())
+ {
+ kapp->dcopClient()->attach();
+ }
+
+ if ( !kapp->dcopClient()->isApplicationRegistered( "tdeio_uiserver" ) )
+ {
+ kdDebug(KDEBUG_OBSERVER) << "Starting tdeio_uiserver" << endl;
+ TQString error;
+ int ret = TDEApplication::startServiceByDesktopPath( "tdeio_uiserver.desktop",
+ TQStringList(), &error );
+ if ( ret > 0 )
+ {
+ kdError() << "Couldn't start tdeio_uiserver from tdeio_uiserver.desktop: " << error << endl;
+ } else
+ kdDebug(KDEBUG_OBSERVER) << "startServiceByDesktopPath returned " << ret << endl;
+
+ }
+ if ( !kapp->dcopClient()->isApplicationRegistered( "tdeio_uiserver" ) )
+ kdDebug(KDEBUG_OBSERVER) << "The application tdeio_uiserver is STILL NOT REGISTERED" << endl;
+ else
+ kdDebug(KDEBUG_OBSERVER) << "tdeio_uiserver registered" << endl;
+
+ m_uiserver = new UIServer_stub( "tdeio_uiserver", "UIServer" );
+}
+
+int Observer::newJob( TDEIO::Job * job, bool showProgress )
+{
+ // Tell the UI Server about this new job, and give it the application id
+ // at the same time
+ int progressId = m_uiserver->newJob( kapp->dcopClient()->appId(), showProgress );
+
+ // Keep the result in a dict
+ m_dctJobs.insert( progressId, job );
+
+ return progressId;
+}
+
+void Observer::jobFinished( int progressId )
+{
+ m_uiserver->jobFinished( progressId );
+ m_dctJobs.remove( progressId );
+}
+
+void Observer::killJob( int progressId )
+{
+ TDEIO::Job * job = m_dctJobs[ progressId ];
+ if (!job)
+ {
+ kdWarning() << "Can't find job to kill ! There is no job with progressId=" << progressId << " in this process" << endl;
+ return;
+ }
+ job->kill( false /* not quietly */ );
+}
+
+MetaData Observer::metadata( int progressId )
+{
+ TDEIO::Job * job = m_dctJobs[ progressId ];
+ assert(job);
+ return job->metaData();
+}
+
+void Observer::slotTotalSize( TDEIO::Job* job, TDEIO::filesize_t size )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTotalSize " << job << " " << TDEIO::number(size) << endl;
+ m_uiserver->totalSize64( job->progressId(), size );
+}
+
+void Observer::slotTotalFiles( TDEIO::Job* job, unsigned long files )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTotalFiles " << job << " " << files << endl;
+ m_uiserver->totalFiles( job->progressId(), files );
+}
+
+void Observer::slotTotalDirs( TDEIO::Job* job, unsigned long dirs )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTotalDirs " << job << " " << dirs << endl;
+ m_uiserver->totalDirs( job->progressId(), dirs );
+}
+
+void Observer::slotProcessedSize( TDEIO::Job* job, TDEIO::filesize_t size )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotProcessedSize " << job << " " << job->progressId() << " " << TDEIO::number(size) << endl;
+ m_uiserver->processedSize64( job->progressId(), size );
+}
+
+void Observer::slotProcessedFiles( TDEIO::Job* job, unsigned long files )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotProcessedFiles " << job << " " << files << endl;
+ m_uiserver->processedFiles( job->progressId(), files );
+}
+
+void Observer::slotProcessedDirs( TDEIO::Job* job, unsigned long dirs )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotProcessedDirs " << job << " " << dirs << endl;
+ m_uiserver->processedDirs( job->progressId(), dirs );
+}
+
+void Observer::slotSpeed( TDEIO::Job* job, unsigned long speed )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotSpeed " << job << " " << speed << endl;
+ m_uiserver->speed( job->progressId(), speed );
+}
+
+void Observer::slotPercent( TDEIO::Job* job, unsigned long percent )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotPercent " << job << " " << percent << endl;
+ m_uiserver->percent( job->progressId(), percent );
+}
+
+void Observer::slotInfoMessage( TDEIO::Job* job, const TQString & msg )
+{
+ m_uiserver->infoMessage( job->progressId(), msg );
+}
+
+void Observer::slotCopying( TDEIO::Job* job, const KURL& from, const KURL& to )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotCopying " << job << " " << from.url() << " " << to.url() << endl;
+ m_uiserver->copying( job->progressId(), from, to );
+}
+
+void Observer::slotMoving( TDEIO::Job* job, const KURL& from, const KURL& to )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotMoving " << job << " " << from.url() << " " << to.url() << endl;
+ m_uiserver->moving( job->progressId(), from, to );
+}
+
+void Observer::slotDeleting( TDEIO::Job* job, const KURL& url )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotDeleting " << job << " " << url.url() << endl;
+ m_uiserver->deleting( job->progressId(), url );
+}
+
+void Observer::slotTransferring( TDEIO::Job* job, const KURL& url )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotTransferring " << job << " " << url.url() << endl;
+ m_uiserver->transferring( job->progressId(), url );
+}
+
+void Observer::slotCreatingDir( TDEIO::Job* job, const KURL& dir )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotCreatingDir " << job << " " << dir.url() << endl;
+ m_uiserver->creatingDir( job->progressId(), dir );
+}
+
+void Observer::slotCanResume( TDEIO::Job* job, TDEIO::filesize_t offset )
+{
+ //kdDebug(KDEBUG_OBSERVER) << "** Observer::slotCanResume " << job << " " << TDEIO::number(offset) << endl;
+ m_uiserver->canResume64( job->progressId(), offset );
+}
+
+void Observer::stating( TDEIO::Job* job, const KURL& url )
+{
+ m_uiserver->stating( job->progressId(), url );
+}
+
+void Observer::mounting( TDEIO::Job* job, const TQString & dev, const TQString & point )
+{
+ m_uiserver->mounting( job->progressId(), dev, point );
+}
+
+void Observer::unmounting( TDEIO::Job* job, const TQString & point )
+{
+ m_uiserver->unmounting( job->progressId(), point );
+}
+
+bool Observer::openPassDlg( const TQString& prompt, TQString& user,
+ TQString& pass, bool readOnly )
+{
+ AuthInfo info;
+ info.prompt = prompt;
+ info.username = user;
+ info.password = pass;
+ info.readOnly = readOnly;
+ bool result = openPassDlg ( info );
+ if ( result )
+ {
+ user = info.username;
+ pass = info.password;
+ }
+ return result;
+}
+
+bool Observer::openPassDlg( TDEIO::AuthInfo& info )
+{
+ kdDebug(KDEBUG_OBSERVER) << "Observer::openPassDlg: User= " << info.username
+ << ", Message= " << info.prompt << endl;
+ int result = TDEIO::PasswordDialog::getNameAndPassword( info.username, info.password,
+ &info.keepPassword, info.prompt,
+ info.readOnly, info.caption,
+ info.comment, info.commentLabel );
+ if ( result == TQDialog::Accepted )
+ {
+ info.setModified( true );
+ return true;
+ }
+ return false;
+}
+
+int Observer::messageBox( int progressId, int type, const TQString &text,
+ const TQString &caption, const TQString &buttonYes,
+ const TQString &buttonNo )
+{
+ return messageBox( progressId, type, text, caption, buttonYes, buttonNo, TQString::null );
+}
+
+int Observer::messageBox( int progressId, int type, const TQString &text,
+ const TQString &caption, const TQString &buttonYes,
+ const TQString &buttonNo, const TQString &dontAskAgainName )
+{
+ kdDebug() << "Observer::messageBox " << type << " " << text << " - " << caption << endl;
+ int result = -1;
+ TDEConfig *config = new TDEConfig("tdeioslaverc");
+ KMessageBox::setDontShowAskAgainConfig(config);
+
+ switch (type) {
+ case TDEIO::SlaveBase::QuestionYesNo:
+ result = KMessageBox::questionYesNo( 0L, // parent ?
+ text, caption, buttonYes, buttonNo, dontAskAgainName );
+ break;
+ case TDEIO::SlaveBase::WarningYesNo:
+ result = KMessageBox::warningYesNo( 0L, // parent ?
+ text, caption, buttonYes, buttonNo, dontAskAgainName );
+ break;
+ case TDEIO::SlaveBase::WarningContinueCancel:
+ result = KMessageBox::warningContinueCancel( 0L, // parent ?
+ text, caption, buttonYes, dontAskAgainName );
+ break;
+ case TDEIO::SlaveBase::WarningYesNoCancel:
+ result = KMessageBox::warningYesNoCancel( 0L, // parent ?
+ text, caption, buttonYes, buttonNo, dontAskAgainName );
+ break;
+ case TDEIO::SlaveBase::Information:
+ KMessageBox::information( 0L, // parent ?
+ text, caption, dontAskAgainName );
+ result = 1; // whatever
+ break;
+ case TDEIO::SlaveBase::SSLMessageBox:
+ {
+ TQCString observerAppId = caption.utf8(); // hack, see slaveinterface.cpp
+ // Contact the object "TDEIO::Observer" in the application <appId>
+ // Yes, this could be the same application we are, but not necessarily.
+ Observer_stub observer( observerAppId, "TDEIO::Observer" );
+
+ TDEIO::MetaData meta = observer.metadata( progressId );
+ KSSLInfoDlg *kid = new KSSLInfoDlg(meta["ssl_in_use"].upper()=="TRUE", 0L /*parent?*/, 0L, true);
+ KSSLCertificate *x = KSSLCertificate::fromString(meta["ssl_peer_certificate"].local8Bit());
+ if (x) {
+ // Set the chain back onto the certificate
+ TQStringList cl =
+ TQStringList::split(TQString("\n"), meta["ssl_peer_chain"]);
+ TQPtrList<KSSLCertificate> ncl;
+
+ ncl.setAutoDelete(true);
+ for (TQStringList::Iterator it = cl.begin(); it != cl.end(); ++it) {
+ KSSLCertificate *y = KSSLCertificate::fromString((*it).local8Bit());
+ if (y) ncl.append(y);
+ }
+
+ if (ncl.count() > 0)
+ x->chain().setChain(ncl);
+
+ kid->setup( x,
+ meta["ssl_peer_ip"],
+ text, // the URL
+ meta["ssl_cipher"],
+ meta["ssl_cipher_desc"],
+ meta["ssl_cipher_version"],
+ meta["ssl_cipher_used_bits"].toInt(),
+ meta["ssl_cipher_bits"].toInt(),
+ KSSLCertificate::KSSLValidation(meta["ssl_cert_state"].toInt()));
+ kdDebug(7024) << "Showing SSL Info dialog" << endl;
+ kid->exec();
+ delete x;
+ kdDebug(7024) << "SSL Info dialog closed" << endl;
+ } else {
+ KMessageBox::information( 0L, // parent ?
+ i18n("The peer SSL certificate appears to be corrupt."), i18n("SSL") );
+ }
+ // This doesn't have to get deleted. It deletes on it's own.
+ result = 1; // whatever
+ break;
+ }
+ default:
+ kdWarning() << "Observer::messageBox: unknown type " << type << endl;
+ result = 0;
+ break;
+ }
+ KMessageBox::setDontShowAskAgainConfig(0);
+ delete config;
+ return result;
+#if 0
+ TQByteArray data, replyData;
+ TQCString replyType;
+ TQDataStream arg( data, IO_WriteOnly );
+ arg << progressId;
+ arg << type;
+ arg << text;
+ arg << caption;
+ arg << buttonYes;
+ arg << buttonNo;
+ if ( kapp->dcopClient()->call( "tdeio_uiserver", "UIServer", "messageBox(int,int,TQString,TQString,TQString,TQString)", data, replyType, replyData, true )
+ && replyType == "int" )
+ {
+ int result;
+ TQDataStream _reply_stream( replyData, IO_ReadOnly );
+ _reply_stream >> result;
+ kdDebug(KDEBUG_OBSERVER) << "Observer::messageBox got result " << result << endl;
+ return result;
+ }
+ kdDebug(KDEBUG_OBSERVER) << "Observer::messageBox call failed" << endl;
+ return 0;
+#endif
+}
+
+RenameDlg_Result Observer::open_RenameDlg( TDEIO::Job* job,
+ const TQString & caption,
+ const TQString& src, const TQString & dest,
+ RenameDlg_Mode mode, TQString& newDest,
+ TDEIO::filesize_t sizeSrc,
+ TDEIO::filesize_t sizeDest,
+ time_t ctimeSrc,
+ time_t ctimeDest,
+ time_t mtimeSrc,
+ time_t mtimeDest
+ )
+{
+ kdDebug(KDEBUG_OBSERVER) << "Observer::open_RenameDlg job=" << job << endl;
+ if (job)
+ kdDebug(KDEBUG_OBSERVER) << " progressId=" << job->progressId() << endl;
+ // Hide existing dialog box if any
+ if (job && job->progressId())
+ m_uiserver->setJobVisible( job->progressId(), false );
+ // We now do it in process => KDE4: move this code out of Observer (back to job.cpp), so that
+ // opening the rename dialog doesn't start uiserver for nothing if progressId=0 (e.g. F2 in konq)
+ RenameDlg_Result res = TDEIO::open_RenameDlg( caption, src, dest, mode,
+ newDest, sizeSrc, sizeDest,
+ ctimeSrc, ctimeDest, mtimeSrc,
+ mtimeDest );
+ if (job && job->progressId())
+ m_uiserver->setJobVisible( job->progressId(), true );
+ return res;
+}
+
+SkipDlg_Result Observer::open_SkipDlg( TDEIO::Job* job,
+ bool _multi,
+ const TQString& _error_text )
+{
+ kdDebug(KDEBUG_OBSERVER) << "Observer::open_SkipDlg job=" << job << " progressId=" << job->progressId() << endl;
+ // Hide existing dialog box if any
+ if (job && job->progressId())
+ m_uiserver->setJobVisible( job->progressId(), false );
+ // We now do it in process. So this method is a useless wrapper around TDEIO::open_RenameDlg.
+ SkipDlg_Result res = TDEIO::open_SkipDlg( _multi, _error_text );
+ if (job && job->progressId())
+ m_uiserver->setJobVisible( job->progressId(), true );
+ return res;
+}
+
+void Observer::virtual_hook( int id, void* data )
+{ DCOPObject::virtual_hook( id, data ); }
+
+#include "observer.moc"
diff --git a/tdeio/tdeio/observer.h b/tdeio/tdeio/observer.h
new file mode 100644
index 000000000..f018bb399
--- /dev/null
+++ b/tdeio/tdeio/observer.h
@@ -0,0 +1,213 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Matej Koss <koss@miesto.sk>
+ David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __kio_observer_h__
+#define __kio_observer_h__
+
+#include <tqobject.h>
+#include <dcopobject.h>
+#include <tqintdict.h>
+
+#include <tdeio/global.h>
+#include <tdeio/authinfo.h>
+#include "tdeio/job.h"
+#include "tdeio/skipdlg.h"
+#include "tdeio/renamedlg.h"
+
+class UIServer_stub;
+class KURL;
+
+namespace TDEIO {
+ class Job;
+}
+
+/**
+ * Observer for TDEIO::Job progress information.
+ *
+ * This class, of which there is always only one instance,
+ * "observes" what jobs do and forwards this information
+ * to the progress-info server.
+ *
+ * It is a DCOP object so that the UI server can call the
+ * kill method when the user presses Cancel.
+ *
+ * Usually jobs are automatically registered by the
+ * TDEIO::Scheduler, so you do not have to care about that.
+ *
+ * @short Observer for TDEIO::Job progress information
+ * @author David Faure <faure@kde.org>
+ */
+class TDEIO_EXPORT Observer : public TQObject, public DCOPObject {
+
+ K_DCOP
+ Q_OBJECT
+
+public:
+
+ /**
+ * Returns the unique observer object.
+ * @return the observer object
+ */
+ static Observer * self() {
+ if (!s_pObserver) s_pObserver = new Observer;
+ return s_pObserver;
+ }
+
+ /**
+ * Called by the job constructor, to signal its presence to the
+ * UI Server.
+ * @param job the new job
+ * @param showProgress true to show progress, false otherwise
+ * @return the progress ID assigned by the UI Server to the Job.
+ */
+ int newJob( TDEIO::Job * job, bool showProgress );
+
+ /**
+ * Called by the job destructor, to tell the UI Server that
+ * the job ended.
+ * @param progressId the progress ID of the job, as returned by newJob()
+ */
+ void jobFinished( int progressId );
+
+ /**
+ * @deprecated use TDEIO::AutoInfo
+ */
+ bool openPassDlg( const TQString& prompt, TQString& user, TQString& pass,
+ bool readOnly );
+
+ /**
+ * Opens a password dialog.
+ * @param info the authentication information
+ * @return true if successful ("ok" clicked), false otherwise
+ */
+ bool openPassDlg( TDEIO::AuthInfo& info );
+
+ /**
+ * Popup a message box. See TDEIO::SlaveBase.
+ * This doesn't use DCOP anymore, it shows the dialog in the application's process.
+ * Otherwise, other apps would block when trying to communicate with UIServer.
+ * @param progressId the progress ID of the job, as returned by newJob()
+ * @param type the type of the message box
+ * @param text the text to show
+ * @param caption the window caption
+ * @param buttonYes the text of the "Yes" button
+ * @param buttonNo the text of the "No button
+ */
+ static int messageBox( int progressId, int type, const TQString &text, const TQString &caption,
+ const TQString &buttonYes, const TQString &buttonNo );
+
+ /**
+ * Popup a message box. See TDEIO::SlaveBase.
+ * This doesn't use DCOP anymore, it shows the dialog in the application's process.
+ * Otherwise, other apps would block when trying to communicate with UIServer.
+ * @param progressId the progress ID of the job, as returned by newJob()
+ * @param type the type of the message box
+ * @param text the text to show
+ * @param caption the window caption
+ * @param buttonYes the text of the "Yes" button
+ * @param buttonNo the text of the "No button
+ * @param dontAskAgainName A checkbox is added with which further confirmation can be turned off.
+ * The string is used to lookup and store the setting in tdeioslaverc.
+ * @since 3.3
+ */
+ static int messageBox( int progressId, int type, const TQString &text, const TQString &caption,
+ const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName );
+
+ /**
+ * @internal
+ * See renamedlg.h
+ */
+ TDEIO::RenameDlg_Result open_RenameDlg( TDEIO::Job * job,
+ const TQString & caption,
+ const TQString& src, const TQString & dest,
+ TDEIO::RenameDlg_Mode mode,
+ TQString& newDest,
+ TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1,
+ TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1,
+ time_t ctimeSrc = (time_t) -1,
+ time_t ctimeDest = (time_t) -1,
+ time_t mtimeSrc = (time_t) -1,
+ time_t mtimeDest = (time_t) -1
+ );
+
+ /**
+ * @internal
+ * See skipdlg.h
+ */
+ TDEIO::SkipDlg_Result open_SkipDlg( TDEIO::Job * job,
+ bool multi,
+ const TQString & error_text );
+
+k_dcop:
+ /**
+ * Called by the UI Server (using DCOP) if the user presses cancel.
+ * @param progressId the progress ID of the job, as returned by newJob()
+ */
+ void killJob( int progressId );
+
+ /**
+ * Called by the UI Server (using DCOP) to get all the metadata of the job
+ * @param progressId the progress IDof the job, as returned by newJob()
+ */
+ TDEIO::MetaData metadata( int progressId );
+
+protected:
+
+ static Observer * s_pObserver;
+ Observer();
+ ~Observer() {}
+
+ UIServer_stub * m_uiserver;
+
+ TQIntDict< TDEIO::Job > m_dctJobs;
+
+public slots:
+
+ void slotTotalSize( TDEIO::Job*, TDEIO::filesize_t size );
+ void slotTotalFiles( TDEIO::Job*, unsigned long files );
+ void slotTotalDirs( TDEIO::Job*, unsigned long dirs );
+
+ void slotProcessedSize( TDEIO::Job*, TDEIO::filesize_t size );
+ void slotProcessedFiles( TDEIO::Job*, unsigned long files );
+ void slotProcessedDirs( TDEIO::Job*, unsigned long dirs );
+
+ void slotSpeed( TDEIO::Job*, unsigned long speed );
+ void slotPercent( TDEIO::Job*, unsigned long percent );
+ void slotInfoMessage( TDEIO::Job*, const TQString & msg );
+
+ void slotCopying( TDEIO::Job*, const KURL& from, const KURL& to );
+ void slotMoving( TDEIO::Job*, const KURL& from, const KURL& to );
+ void slotDeleting( TDEIO::Job*, const KURL& url );
+ /// @since 3.1
+ void slotTransferring( TDEIO::Job*, const KURL& url );
+ void slotCreatingDir( TDEIO::Job*, const KURL& dir );
+ // currently unused
+ void slotCanResume( TDEIO::Job*, TDEIO::filesize_t offset );
+
+public:
+ void stating( TDEIO::Job*, const KURL& url );
+ void mounting( TDEIO::Job*, const TQString & dev, const TQString & point );
+ void unmounting( TDEIO::Job*, const TQString & point );
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class ObserverPrivate* d;
+};
+
+// -*- mode: c++; c-basic-offset: 2 -*-
+#endif
diff --git a/tdeio/tdeio/passdlg.cpp b/tdeio/tdeio/passdlg.cpp
new file mode 100644
index 000000000..54bcec3b2
--- /dev/null
+++ b/tdeio/tdeio/passdlg.cpp
@@ -0,0 +1,367 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "passdlg.h"
+
+#include <tqapplication.h>
+#include <tqcheckbox.h>
+#include <tqhbox.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqsimplerichtext.h>
+#include <tqstylesheet.h>
+
+#include <kcombobox.h>
+#include <tdeconfig.h>
+#include <kiconloader.h>
+#include <klineedit.h>
+#include <klocale.h>
+#include <kstandarddirs.h>
+
+using namespace TDEIO;
+
+struct PasswordDialog::PasswordDialogPrivate
+{
+ TQGridLayout *layout;
+ TQLineEdit* userEdit;
+ KLineEdit* passEdit;
+ TQLabel* userNameLabel;
+ TQLabel* prompt;
+ TQCheckBox* keepCheckBox;
+ TQMap<TQString,TQString> knownLogins;
+ KComboBox* userEditCombo;
+ TQHBox* userNameHBox;
+
+ bool keep;
+ short unsigned int nRow;
+};
+
+PasswordDialog::PasswordDialog( const TQString& prompt, const TQString& user,
+ bool enableKeep, bool modal, TQWidget* parent,
+ const char* name )
+ :KDialogBase( parent, name, modal, i18n("Password"), Ok|Cancel, Ok, true)
+{
+ init ( prompt, user, enableKeep );
+}
+
+PasswordDialog::~PasswordDialog()
+{
+ delete d;
+}
+
+void PasswordDialog::init( const TQString& prompt, const TQString& user,
+ bool enableKeep )
+{
+ TQWidget *main = makeMainWidget();
+
+ d = new PasswordDialogPrivate;
+ d->keep = false;
+ d->nRow = 0;
+ d->keepCheckBox = 0;
+
+ TDEConfig* cfg = TDEGlobal::config();
+ TDEConfigGroupSaver saver( cfg, "Passwords" );
+
+ d->layout = new TQGridLayout( main, 9, 3, spacingHint(), marginHint());
+ d->layout->addColSpacing(1, 5);
+
+ // Row 0: pixmap prompt
+ TQLabel* lbl;
+ TQPixmap pix( TDEGlobal::iconLoader()->loadIcon( "password", KIcon::NoGroup, KIcon::SizeHuge, 0, 0, true));
+ if ( !pix.isNull() )
+ {
+ lbl = new TQLabel( main );
+ lbl->setPixmap( pix );
+ lbl->setAlignment( Qt::AlignLeft|Qt::AlignVCenter );
+ lbl->setFixedSize( lbl->sizeHint() );
+ d->layout->addWidget( lbl, 0, 0, Qt::AlignLeft );
+ }
+ d->prompt = new TQLabel( main );
+ d->prompt->setAlignment( Qt::AlignLeft|Qt::AlignVCenter|TQt::WordBreak );
+ d->layout->addWidget( d->prompt, 0, 2, Qt::AlignLeft );
+ if ( prompt.isEmpty() )
+ setPrompt( i18n( "You need to supply a username and a password" ) );
+ else
+ setPrompt( prompt );
+
+ // Row 1: Row Spacer
+ d->layout->addRowSpacing( 1, 7 );
+
+ // Row 2-3: Reserved for an additional comment
+
+ // Row 4: Username field
+ d->userNameLabel = new TQLabel( i18n("&Username:"), main );
+ d->userNameLabel->setAlignment( Qt::AlignVCenter | Qt::AlignLeft );
+ d->userNameLabel->setFixedSize( d->userNameLabel->sizeHint() );
+ d->userNameHBox = new TQHBox( main );
+
+ d->userEdit = new KLineEdit( d->userNameHBox );
+ TQSize s = d->userEdit->sizeHint();
+ d->userEdit->setFixedHeight( s.height() );
+ d->userEdit->setMinimumWidth( s.width() );
+ d->userNameLabel->setBuddy( d->userEdit );
+ d->layout->addWidget( d->userNameLabel, 4, 0 );
+ d->layout->addWidget( d->userNameHBox, 4, 2 );
+
+ // Row 5: Row spacer
+ d->layout->addRowSpacing( 5, 4 );
+
+ // Row 6: Password field
+ lbl = new TQLabel( i18n("&Password:"), main );
+ lbl->setAlignment( Qt::AlignVCenter | Qt::AlignLeft );
+ lbl->setFixedSize( lbl->sizeHint() );
+ TQHBox* hbox = new TQHBox( main );
+ d->passEdit = new KLineEdit( hbox );
+ if ( cfg->readEntry("EchoMode", "OneStar") == "NoEcho" )
+ d->passEdit->setEchoMode( TQLineEdit::NoEcho );
+ else
+ d->passEdit->setEchoMode( TQLineEdit::Password );
+ s = d->passEdit->sizeHint();
+ d->passEdit->setFixedHeight( s.height() );
+ d->passEdit->setMinimumWidth( s.width() );
+ lbl->setBuddy( d->passEdit );
+ d->layout->addWidget( lbl, 6, 0 );
+ d->layout->addWidget( hbox, 6, 2 );
+
+ if ( enableKeep )
+ {
+ // Row 7: Add spacer
+ d->layout->addRowSpacing( 7, 4 );
+ // Row 8: Keep Password
+ hbox = new TQHBox( main );
+ d->keepCheckBox = new TQCheckBox( i18n("&Keep password"), hbox );
+ d->keepCheckBox->setFixedSize( d->keepCheckBox->sizeHint() );
+ d->keep = cfg->readBoolEntry("Keep", false );
+ d->keepCheckBox->setChecked( d->keep );
+ connect(d->keepCheckBox, TQT_SIGNAL(toggled( bool )), TQT_SLOT(slotKeep( bool )));
+ d->layout->addWidget( hbox, 8, 2 );
+ }
+
+ // Configure necessary key-bindings and connect necessar slots and signals
+ connect( d->userEdit, TQT_SIGNAL(returnPressed()), d->passEdit, TQT_SLOT(setFocus()) );
+ connect( d->passEdit, TQT_SIGNAL(returnPressed()), TQT_SLOT(slotOk()) );
+
+ if ( !user.isEmpty() )
+ {
+ d->userEdit->setText( user );
+ d->passEdit->setFocus();
+ }
+ else
+ d->userEdit->setFocus();
+
+ d->userEditCombo = 0;
+// setFixedSize( sizeHint() );
+}
+
+TQString PasswordDialog::username() const
+{
+ return d->userEdit->text();
+}
+
+TQString PasswordDialog::password() const
+{
+ return d->passEdit->text();
+}
+
+void PasswordDialog::setKeepPassword( bool b )
+{
+ if ( d->keepCheckBox )
+ d->keepCheckBox->setChecked( b );
+}
+
+bool PasswordDialog::keepPassword() const
+{
+ return d->keep;
+}
+
+static void calculateLabelSize(TQLabel *label)
+{
+ TQString qt_text = label->text();
+
+ int pref_width = 0;
+ int pref_height = 0;
+ // Calculate a proper size for the text.
+ {
+ TQSimpleRichText rt(qt_text, label->font());
+ TQRect d = TDEGlobalSettings::desktopGeometry(label->topLevelWidget());
+
+ pref_width = d.width() / 4;
+ rt.setWidth(pref_width-10);
+ int used_width = rt.widthUsed();
+ pref_height = rt.height();
+ if (used_width <= pref_width)
+ {
+ while(true)
+ {
+ int new_width = (used_width * 9) / 10;
+ rt.setWidth(new_width-10);
+ int new_height = rt.height();
+ if (new_height > pref_height)
+ break;
+ used_width = rt.widthUsed();
+ if (used_width > new_width)
+ break;
+ }
+ pref_width = used_width;
+ }
+ else
+ {
+ if (used_width > (pref_width *2))
+ pref_width = pref_width *2;
+ else
+ pref_width = used_width;
+ }
+ }
+ label->setFixedSize(TQSize(pref_width+10, pref_height));
+}
+
+void PasswordDialog::addCommentLine( const TQString& label,
+ const TQString comment )
+{
+ if (d->nRow > 0)
+ return;
+
+ TQWidget *main = mainWidget();
+
+ TQLabel* lbl = new TQLabel( label, main);
+ lbl->setAlignment( Qt::AlignVCenter|Qt::AlignRight );
+ lbl->setFixedSize( lbl->sizeHint() );
+ d->layout->addWidget( lbl, d->nRow+2, 0, Qt::AlignLeft );
+ lbl = new TQLabel( comment, main);
+ lbl->setAlignment( Qt::AlignVCenter|Qt::AlignLeft|TQt::WordBreak );
+ calculateLabelSize(lbl);
+ d->layout->addWidget( lbl, d->nRow+2, 2, Qt::AlignLeft );
+ d->layout->addRowSpacing( 3, 10 ); // Add a spacer
+ d->nRow++;
+}
+
+void PasswordDialog::slotKeep( bool keep )
+{
+ d->keep = keep;
+}
+
+static TQString qrichtextify( const TQString& text )
+{
+ if ( text.isEmpty() || text[0] == '<' )
+ return text;
+
+ TQStringList lines = TQStringList::split('\n', text);
+ for(TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it)
+ {
+ *it = TQStyleSheet::convertFromPlainText( *it, TQStyleSheetItem::WhiteSpaceNormal );
+ }
+
+ return lines.join(TQString::null);
+}
+
+void PasswordDialog::setPrompt(const TQString& prompt)
+{
+ TQString text = qrichtextify(prompt);
+ d->prompt->setText(text);
+ calculateLabelSize(d->prompt);
+}
+
+void PasswordDialog::setPassword(const TQString &p)
+{
+ d->passEdit->setText(p);
+}
+
+void PasswordDialog::setUserReadOnly( bool readOnly )
+{
+ d->userEdit->setReadOnly( readOnly );
+ if ( readOnly && d->userEdit->hasFocus() )
+ d->passEdit->setFocus();
+}
+
+void PasswordDialog::setKnownLogins( const TQMap<TQString, TQString>& knownLogins )
+{
+ const int nr = knownLogins.count();
+ if ( nr == 0 )
+ return;
+ if ( nr == 1 ) {
+ d->userEdit->setText( knownLogins.begin().key() );
+ setPassword( knownLogins.begin().data() );
+ return;
+ }
+
+ Q_ASSERT( !d->userEdit->isReadOnly() );
+ if ( !d->userEditCombo ) {
+ delete d->userEdit;
+ d->userEditCombo = new KComboBox( true, d->userNameHBox );
+ d->userEdit = d->userEditCombo->lineEdit();
+ TQSize s = d->userEditCombo->sizeHint();
+ d->userEditCombo->setFixedHeight( s.height() );
+ d->userEditCombo->setMinimumWidth( s.width() );
+ d->userNameLabel->setBuddy( d->userEditCombo );
+ d->layout->addWidget( d->userNameHBox, 4, 2 );
+ }
+
+ d->knownLogins = knownLogins;
+ d->userEditCombo->insertStringList( knownLogins.keys() );
+ d->userEditCombo->setFocus();
+
+ connect( d->userEditCombo, TQT_SIGNAL( activated( const TQString& ) ),
+ this, TQT_SLOT( slotActivated( const TQString& ) ) );
+}
+
+void PasswordDialog::slotActivated( const TQString& userName )
+{
+ TQMap<TQString, TQString>::ConstIterator it = d->knownLogins.find( userName );
+ if ( it != d->knownLogins.end() )
+ setPassword( it.data() );
+}
+
+
+int PasswordDialog::getNameAndPassword( TQString& user, TQString& pass, bool* keep,
+ const TQString& prompt, bool readOnly,
+ const TQString& caption,
+ const TQString& comment,
+ const TQString& label )
+{
+ PasswordDialog* dlg;
+ if( keep )
+ dlg = new PasswordDialog( prompt, user, (*keep) );
+ else
+ dlg = new PasswordDialog( prompt, user );
+
+ if ( !caption.isEmpty() )
+ dlg->setPlainCaption( caption );
+ else
+ dlg->setPlainCaption( i18n("Authorization Dialog") );
+
+ if ( !comment.isEmpty() )
+ dlg->addCommentLine( label, comment );
+
+ if ( readOnly )
+ dlg->setUserReadOnly( readOnly );
+
+ int ret = dlg->exec();
+ if ( ret == Accepted )
+ {
+ user = dlg->username();
+ pass = dlg->password();
+ if ( keep ) { (*keep) = dlg->keepPassword(); }
+ }
+ delete dlg;
+ return ret;
+ }
+
+void PasswordDialog::virtual_hook( int id, void* data )
+{ KDialogBase::virtual_hook( id, data ); }
+
+#include "passdlg.moc"
diff --git a/kio/kio/passdlg.h b/tdeio/tdeio/passdlg.h
index 864023398..864023398 100644
--- a/kio/kio/passdlg.h
+++ b/tdeio/tdeio/passdlg.h
diff --git a/tdeio/tdeio/paste.cpp b/tdeio/tdeio/paste.cpp
new file mode 100644
index 000000000..fd24f9a0d
--- /dev/null
+++ b/tdeio/tdeio/paste.cpp
@@ -0,0 +1,308 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "paste.h"
+#include "pastedialog.h"
+
+#include "tdeio/job.h"
+#include "tdeio/global.h"
+#include "tdeio/netaccess.h"
+#include "tdeio/observer.h"
+#include "tdeio/renamedlg.h"
+#include "tdeio/kprotocolmanager.h"
+
+#include <kurl.h>
+#include <kurldrag.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kinputdialog.h>
+#include <kmessagebox.h>
+#include <kmimetype.h>
+#include <ktempfile.h>
+
+#include <tqapplication.h>
+#include <tqclipboard.h>
+#include <tqdragobject.h>
+#include <tqtextstream.h>
+#include <tqvaluevector.h>
+
+static KURL getNewFileName( const KURL &u, const TQString& text )
+{
+ bool ok;
+ TQString dialogText( text );
+ if ( dialogText.isEmpty() )
+ dialogText = i18n( "Filename for clipboard content:" );
+ TQString file = KInputDialog::getText( TQString::null, dialogText, TQString::null, &ok );
+ if ( !ok )
+ return KURL();
+
+ KURL myurl(u);
+ myurl.addPath( file );
+
+ if (TDEIO::NetAccess::exists(myurl, false, 0))
+ {
+ kdDebug(7007) << "Paste will overwrite file. Prompting..." << endl;
+ TDEIO::RenameDlg_Result res = TDEIO::R_OVERWRITE;
+
+ TQString newPath;
+ // Ask confirmation about resuming previous transfer
+ res = Observer::self()->open_RenameDlg(
+ 0L, i18n("File Already Exists"),
+ u.pathOrURL(),
+ myurl.pathOrURL(),
+ (TDEIO::RenameDlg_Mode) (TDEIO::M_OVERWRITE | TDEIO::M_SINGLE), newPath);
+
+ if ( res == TDEIO::R_RENAME )
+ {
+ myurl = newPath;
+ }
+ else if ( res == TDEIO::R_CANCEL )
+ {
+ return KURL();
+ }
+ }
+
+ return myurl;
+}
+
+// The finaly step: write _data to tempfile and move it to neW_url
+static TDEIO::CopyJob* pasteDataAsyncTo( const KURL& new_url, const TQByteArray& _data )
+{
+ KTempFile tempFile;
+ tempFile.dataStream()->writeRawBytes( _data.data(), _data.size() );
+ tempFile.close();
+
+ KURL orig_url;
+ orig_url.setPath(tempFile.name());
+
+ return TDEIO::move( orig_url, new_url );
+}
+
+#ifndef QT_NO_MIMECLIPBOARD
+static TDEIO::CopyJob* chooseAndPaste( const KURL& u, TQMimeSource* data,
+ const TQValueVector<TQCString>& formats,
+ const TQString& text,
+ TQWidget* widget,
+ bool clipboard )
+{
+ TQStringList formatLabels;
+ for ( uint i = 0; i < formats.size(); ++i ) {
+ const TQCString& fmt = formats[i];
+ KMimeType::Ptr mime = KMimeType::mimeType( fmt );
+ if ( mime != KMimeType::defaultMimeTypePtr() )
+ formatLabels.append( i18n( "%1 (%2)" ).arg( mime->comment() ).arg( fmt.data() ) );
+ else
+ formatLabels.append( fmt );
+ }
+
+ TQString dialogText( text );
+ if ( dialogText.isEmpty() )
+ dialogText = i18n( "Filename for clipboard content:" );
+ TDEIO::PasteDialog dlg( TQString::null, dialogText, TQString::null, formatLabels, widget, clipboard );
+
+ if ( dlg.exec() != KDialogBase::Accepted )
+ return 0;
+
+ if ( clipboard && dlg.clipboardChanged() ) {
+ KMessageBox::sorry( widget,
+ i18n( "The clipboard has changed since you used 'paste': "
+ "the chosen data format is no longer applicable. "
+ "Please copy again what you wanted to paste." ) );
+ return 0;
+ }
+
+ const TQString result = dlg.lineEditText();
+ const TQCString chosenFormat = formats[ dlg.comboItem() ];
+
+ kdDebug() << " result=" << result << " chosenFormat=" << chosenFormat << endl;
+ KURL new_url( u );
+ new_url.addPath( result );
+ // if "data" came from TQClipboard, then it was deleted already - by a nice 0-seconds timer
+ // In that case, get it again. Let's hope the user didn't copy something else meanwhile :/
+ if ( clipboard ) {
+ data = TQApplication::clipboard()->data();
+ }
+ const TQByteArray ba = data->encodedData( chosenFormat );
+ return pasteDataAsyncTo( new_url, ba );
+}
+#endif
+
+// KDE4: remove
+TDEIO_EXPORT bool TDEIO::isClipboardEmpty()
+{
+#ifndef QT_NO_MIMECLIPBOARD
+ TQMimeSource *data = TQApplication::clipboard()->data();
+ if ( data->provides( "text/uri-list" ) && data->encodedData( "text/uri-list" ).size() > 0 )
+ return false;
+#else
+ // Happens with some versions of Qt Embedded... :/
+ // Guess.
+ TQString data = TQApplication::clipboard()->text();
+ if(data.contains("://"))
+ return false;
+#endif
+ return true;
+}
+
+#ifndef QT_NO_MIMECLIPBOARD
+// The main method for dropping
+TDEIO::CopyJob* TDEIO::pasteMimeSource( TQMimeSource* data, const KURL& dest_url,
+ const TQString& dialogText, TQWidget* widget, bool clipboard )
+{
+ TQByteArray ba;
+
+ // Now check for plain text
+ // We don't want to display a mimetype choice for a TQTextDrag, those mimetypes look ugly.
+ TQString text;
+ if ( TQTextDrag::canDecode( data ) && TQTextDrag::decode( data, text ) )
+ {
+ TQTextStream txtStream( ba, IO_WriteOnly );
+ txtStream << text;
+ }
+ else
+ {
+ TQValueVector<TQCString> formats;
+ const char* fmt;
+ for ( int i = 0; ( fmt = data->format( i ) ); ++i ) {
+ if ( qstrcmp( fmt, "application/x-qiconlist" ) == 0 ) // see QIconDrag
+ continue;
+ if ( qstrcmp( fmt, "application/x-kde-cutselection" ) == 0 ) // see KonqDrag
+ continue;
+ if ( strchr( fmt, '/' ) == 0 ) // e.g. TARGETS, MULTIPLE, TIMESTAMP
+ continue;
+ formats.append( fmt );
+ }
+
+ if ( formats.size() == 0 )
+ return 0;
+
+ if ( formats.size() > 1 ) {
+ return chooseAndPaste( dest_url, data, formats, dialogText, widget, clipboard );
+ }
+ ba = data->encodedData( formats.first() );
+ }
+ if ( ba.size() == 0 )
+ {
+ KMessageBox::sorry(0, i18n("The clipboard is empty"));
+ return 0;
+ }
+
+ return pasteDataAsync( dest_url, ba, dialogText );
+}
+#endif
+
+// The main method for pasting
+TDEIO_EXPORT TDEIO::Job *TDEIO::pasteClipboard( const KURL& dest_url, bool move )
+{
+ if ( !dest_url.isValid() ) {
+ KMessageBox::error( 0L, i18n( "Malformed URL\n%1" ).arg( dest_url.url() ) );
+ return 0;
+ }
+
+#ifndef QT_NO_MIMECLIPBOARD
+ TQMimeSource *data = TQApplication::clipboard()->data();
+
+ // First check for URLs.
+ KURL::List urls;
+ if ( KURLDrag::canDecode( data ) && KURLDrag::decode( data, urls ) ) {
+ if ( urls.count() == 0 ) {
+ KMessageBox::error( 0L, i18n("The clipboard is empty"));
+ return 0;
+ }
+
+ TDEIO::Job *res = 0;
+ if ( move )
+ res = TDEIO::move( urls, dest_url );
+ else
+ res = TDEIO::copy( urls, dest_url );
+
+ // If moving, erase the clipboard contents, the original files don't exist anymore
+ if ( move )
+ TQApplication::clipboard()->clear();
+ return res;
+ }
+ return pasteMimeSource( data, dest_url, TQString::null, 0 /*TODO parent widget*/, true /*clipboard*/ );
+#else
+ TQByteArray ba;
+ TQTextStream txtStream( ba, IO_WriteOnly );
+ TQStringList data = TQStringList::split("\n", TQApplication::clipboard()->text());
+ KURL::List urls;
+ KURLDrag::decode(data, urls);
+ TQStringList::Iterator end(data.end());
+ for(TQStringList::Iterator it=data.begin(); it!=end; ++it)
+ txtStream << *it;
+ if ( ba.size() == 0 )
+ {
+ KMessageBox::sorry(0, i18n("The clipboard is empty"));
+ return 0;
+ }
+ return pasteDataAsync( dest_url, ba );
+#endif
+}
+
+
+TDEIO_EXPORT void TDEIO::pasteData( const KURL& u, const TQByteArray& _data )
+{
+ KURL new_url = getNewFileName( u, TQString::null );
+ // We could use TDEIO::put here, but that would require a class
+ // for the slotData call. With NetAccess, we can do a synchronous call.
+
+ if (new_url.isEmpty())
+ return;
+
+ KTempFile tempFile;
+ tempFile.setAutoDelete( true );
+ tempFile.dataStream()->writeRawBytes( _data.data(), _data.size() );
+ tempFile.close();
+
+ (void) TDEIO::NetAccess::upload( tempFile.name(), new_url, 0 );
+}
+
+TDEIO_EXPORT TDEIO::CopyJob* TDEIO::pasteDataAsync( const KURL& u, const TQByteArray& _data )
+{
+ return pasteDataAsync( u, _data, TQString::null );
+}
+
+TDEIO_EXPORT TDEIO::CopyJob* TDEIO::pasteDataAsync( const KURL& u, const TQByteArray& _data, const TQString& text )
+{
+ KURL new_url = getNewFileName( u, text );
+
+ if (new_url.isEmpty())
+ return 0;
+
+ return pasteDataAsyncTo( new_url, _data );
+}
+
+TDEIO_EXPORT TQString TDEIO::pasteActionText()
+{
+ TQMimeSource *data = TQApplication::clipboard()->data();
+ KURL::List urls;
+ if ( KURLDrag::canDecode( data ) && KURLDrag::decode( data, urls ) ) {
+ if ( urls.isEmpty() )
+ return TQString::null; // nothing to paste
+ else if ( urls.first().isLocalFile() )
+ return i18n( "&Paste File", "&Paste %n Files", urls.count() );
+ else
+ return i18n( "&Paste URL", "&Paste %n URLs", urls.count() );
+ } else if ( data->format(0) != 0 ) {
+ return i18n( "&Paste Clipboard Contents" );
+ } else {
+ return TQString::null;
+ }
+}
+
diff --git a/kio/kio/paste.h b/tdeio/tdeio/paste.h
index 66579831a..66579831a 100644
--- a/kio/kio/paste.h
+++ b/tdeio/tdeio/paste.h
diff --git a/kio/kio/pastedialog.cpp b/tdeio/tdeio/pastedialog.cpp
index 0252baff1..0252baff1 100644
--- a/kio/kio/pastedialog.cpp
+++ b/tdeio/tdeio/pastedialog.cpp
diff --git a/kio/kio/pastedialog.h b/tdeio/tdeio/pastedialog.h
index 2e7bdfda1..2e7bdfda1 100644
--- a/kio/kio/pastedialog.h
+++ b/tdeio/tdeio/pastedialog.h
diff --git a/kio/kio/posixacladdons.cpp b/tdeio/tdeio/posixacladdons.cpp
index bae51592b..bae51592b 100644
--- a/kio/kio/posixacladdons.cpp
+++ b/tdeio/tdeio/posixacladdons.cpp
diff --git a/kio/kio/posixacladdons.h b/tdeio/tdeio/posixacladdons.h
index 45c4af245..45c4af245 100644
--- a/kio/kio/posixacladdons.h
+++ b/tdeio/tdeio/posixacladdons.h
diff --git a/tdeio/tdeio/previewjob.cpp b/tdeio/tdeio/previewjob.cpp
new file mode 100644
index 000000000..539d88bea
--- /dev/null
+++ b/tdeio/tdeio/previewjob.cpp
@@ -0,0 +1,597 @@
+// -*- c++ -*-
+// vim: ts=4 sw=4 et
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2001 Malte Starostik <malte.starostik@t-online.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "previewjob.h"
+
+#include <sys/stat.h>
+#ifdef __FreeBSD__
+ #include <machine/param.h>
+#endif
+#include <sys/types.h>
+
+#ifdef Q_OS_UNIX
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#endif
+
+#include <tqdir.h>
+#include <tqfile.h>
+#include <tqimage.h>
+#include <tqtimer.h>
+#include <tqregexp.h>
+
+#include <kdatastream.h> // Do not remove, needed for correct bool serialization
+#include <tdefileitem.h>
+#include <kapplication.h>
+#include <ktempfile.h>
+#include <ktrader.h>
+#include <kmdcodec.h>
+#include <kglobal.h>
+#include <kstandarddirs.h>
+
+#include <tdeio/kservice.h>
+
+#include "previewjob.moc"
+
+namespace TDEIO { struct PreviewItem; }
+using namespace TDEIO;
+
+struct TDEIO::PreviewItem
+{
+ KFileItem *item;
+ KService::Ptr plugin;
+};
+
+struct TDEIO::PreviewJobPrivate
+{
+ enum { STATE_STATORIG, // if the thumbnail exists
+ STATE_GETORIG, // if we create it
+ STATE_CREATETHUMB // thumbnail:/ slave
+ } state;
+ KFileItemList initialItems;
+ const TQStringList *enabledPlugins;
+ // Our todo list :)
+ TQValueList<PreviewItem> items;
+ // The current item
+ PreviewItem currentItem;
+ // The modification time of that URL
+ time_t tOrig;
+ // Path to thumbnail cache for the current size
+ TQString thumbPath;
+ // Original URL of current item in TMS format
+ // (file:///path/to/file instead of file:/path/to/file)
+ TQString origName;
+ // Thumbnail file name for current item
+ TQString thumbName;
+ // Size of thumbnail
+ int width;
+ int height;
+ // Unscaled size of thumbnail (128 or 256 if cache is enabled)
+ int cacheWidth;
+ int cacheHeight;
+ // Whether the thumbnail should be scaled
+ bool bScale;
+ // Whether we should save the thumbnail
+ bool bSave;
+ // If the file to create a thumb for was a temp file, this is its name
+ TQString tempName;
+ // Over that, it's too much
+ unsigned long maximumSize;
+ // the size for the icon overlay
+ int iconSize;
+ // the transparency of the blended mimetype icon
+ int iconAlpha;
+ // Shared memory segment Id. The segment is allocated to a size
+ // of extent x extent x 4 (32 bit image) on first need.
+ int shmid;
+ // And the data area
+ uchar *shmaddr;
+ // Delete the KFileItems when done?
+ bool deleteItems;
+ bool succeeded;
+ // Root of thumbnail cache
+ TQString thumbRoot;
+ bool ignoreMaximumSize;
+ TQTimer startPreviewTimer;
+};
+
+PreviewJob::PreviewJob( const KFileItemList &items, int width, int height,
+ int iconSize, int iconAlpha, bool scale, bool save,
+ const TQStringList *enabledPlugins, bool deleteItems )
+ : TDEIO::Job( false /* no GUI */ )
+{
+ d = new PreviewJobPrivate;
+ d->tOrig = 0;
+ d->shmid = -1;
+ d->shmaddr = 0;
+ d->initialItems = items;
+ d->enabledPlugins = enabledPlugins;
+ d->width = width;
+ d->height = height ? height : width;
+ d->cacheWidth = d->width;
+ d->cacheHeight = d->height;
+ d->iconSize = iconSize;
+ d->iconAlpha = iconAlpha;
+ d->deleteItems = deleteItems;
+ d->bScale = scale;
+ d->bSave = save && scale;
+ d->succeeded = false;
+ d->currentItem.item = 0;
+ d->thumbRoot = TQDir::homeDirPath() + "/.thumbnails/";
+ d->ignoreMaximumSize = false;
+
+ // Return to event loop first, determineNextFile() might delete this;
+ connect(&d->startPreviewTimer, TQT_SIGNAL(timeout()), TQT_SLOT(startPreview()) );
+ d->startPreviewTimer.start(0, true);
+}
+
+PreviewJob::~PreviewJob()
+{
+#ifdef Q_OS_UNIX
+ if (d->shmaddr) {
+ shmdt((char*)d->shmaddr);
+ shmctl(d->shmid, IPC_RMID, 0);
+ }
+#endif
+ delete d;
+}
+
+void PreviewJob::startPreview()
+{
+ // Load the list of plugins to determine which mimetypes are supported
+ KTrader::OfferList plugins = KTrader::self()->query("ThumbCreator");
+ TQMap<TQString, KService::Ptr> mimeMap;
+
+ for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
+ if (!d->enabledPlugins || d->enabledPlugins->contains((*it)->desktopEntryName()))
+ {
+ TQStringList mimeTypes = (*it)->property("MimeTypes").toStringList();
+ for (TQStringList::ConstIterator mt = mimeTypes.begin(); mt != mimeTypes.end(); ++mt)
+ mimeMap.insert(*mt, *it);
+ }
+
+ // Look for images and store the items in our todo list :)
+ bool bNeedCache = false;
+ for (KFileItemListIterator it(d->initialItems); it.current(); ++it )
+ {
+ PreviewItem item;
+ item.item = it.current();
+ TQMap<TQString, KService::Ptr>::ConstIterator plugin = mimeMap.find(it.current()->mimetype());
+ if (plugin == mimeMap.end()
+ && (it.current()->mimetype() != "application/x-desktop")
+ && (it.current()->mimetype() != "media/builtin-mydocuments")
+ && (it.current()->mimetype() != "media/builtin-mycomputer")
+ && (it.current()->mimetype() != "media/builtin-mynetworkplaces")
+ && (it.current()->mimetype() != "media/builtin-printers")
+ && (it.current()->mimetype() != "media/builtin-trash")
+ && (it.current()->mimetype() != "media/builtin-webbrowser"))
+ {
+ TQString mimeType = it.current()->mimetype();
+ plugin = mimeMap.find(mimeType.replace(TQRegExp("/.*"), "/*"));
+
+ if (plugin == mimeMap.end())
+ {
+ // check mime type inheritance
+ KMimeType::Ptr mimeInfo = KMimeType::mimeType(it.current()->mimetype());
+ TQString parentMimeType = mimeInfo->parentMimeType();
+ while (!parentMimeType.isEmpty())
+ {
+ plugin = mimeMap.find(parentMimeType);
+ if (plugin != mimeMap.end()) break;
+
+ KMimeType::Ptr parentMimeInfo = KMimeType::mimeType(parentMimeType);
+ if (!parentMimeInfo) break;
+
+ parentMimeType = parentMimeInfo->parentMimeType();
+ }
+ }
+
+ if (plugin == mimeMap.end())
+ {
+ // check X-TDE-Text property
+ KMimeType::Ptr mimeInfo = KMimeType::mimeType(it.current()->mimetype());
+ TQVariant textProperty = mimeInfo->property("X-TDE-text");
+ if (textProperty.isValid() && textProperty.type() == TQVariant::Bool)
+ {
+ if (textProperty.toBool())
+ {
+ plugin = mimeMap.find("text/plain");
+ if (plugin == mimeMap.end())
+ {
+ plugin = mimeMap.find( "text/*" );
+ }
+ }
+ }
+ }
+ }
+
+ if (plugin != mimeMap.end())
+ {
+ item.plugin = *plugin;
+ d->items.append(item);
+ if (!bNeedCache && d->bSave &&
+ (it.current()->url().protocol() != "file" ||
+ !it.current()->url().directory( false ).startsWith(d->thumbRoot)) &&
+ (*plugin)->property("CacheThumbnail").toBool())
+ bNeedCache = true;
+ }
+ else
+ {
+ emitFailed(it.current());
+ if (d->deleteItems)
+ delete it.current();
+ }
+ }
+
+ // Read configuration value for the maximum allowed size
+ TDEConfig * config = TDEGlobal::config();
+ TDEConfigGroupSaver cgs( config, "PreviewSettings" );
+ d->maximumSize = config->readNumEntry( "MaximumSize", 1024*1024 /* 1MB */ );
+
+ if (bNeedCache)
+ {
+ if (d->width <= 128 && d->height <= 128) d->cacheWidth = d->cacheHeight = 128;
+ else d->cacheWidth = d->cacheHeight = 256;
+ d->thumbPath = d->thumbRoot + (d->cacheWidth == 128 ? "normal/" : "large/");
+ KStandardDirs::makeDir(d->thumbPath, 0700);
+ }
+ else
+ d->bSave = false;
+ determineNextFile();
+}
+
+void PreviewJob::removeItem( const KFileItem *item )
+{
+ for (TQValueList<PreviewItem>::Iterator it = d->items.begin(); it != d->items.end(); ++it)
+ if ((*it).item == item)
+ {
+ d->items.remove(it);
+ break;
+ }
+
+ if (d->currentItem.item == item)
+ {
+ subjobs.first()->kill();
+ subjobs.removeFirst();
+ determineNextFile();
+ }
+}
+
+void PreviewJob::setIgnoreMaximumSize(bool ignoreSize)
+{
+ d->ignoreMaximumSize = ignoreSize;
+}
+
+void PreviewJob::determineNextFile()
+{
+ if (d->currentItem.item)
+ {
+ if (!d->succeeded)
+ emitFailed();
+ if (d->deleteItems) {
+ delete d->currentItem.item;
+ d->currentItem.item = 0L;
+ }
+ }
+ // No more items ?
+ if ( d->items.isEmpty() )
+ {
+ emitResult();
+ return;
+ }
+ else
+ {
+ // First, stat the orig file
+ d->state = PreviewJobPrivate::STATE_STATORIG;
+ d->currentItem = d->items.first();
+ d->succeeded = false;
+ d->items.remove(d->items.begin());
+ TDEIO::Job *job = TDEIO::stat( d->currentItem.item->url(), false );
+ job->addMetaData( "no-auth-prompt", "true" );
+ addSubjob(job);
+ }
+}
+
+void PreviewJob::slotResult( TDEIO::Job *job )
+{
+ subjobs.remove( job );
+ Q_ASSERT ( subjobs.isEmpty() ); // We should have only one job at a time ...
+ switch ( d->state )
+ {
+ case PreviewJobPrivate::STATE_STATORIG:
+ {
+ if (job->error()) // that's no good news...
+ {
+ // Drop this one and move on to the next one
+ determineNextFile();
+ return;
+ }
+ TDEIO::UDSEntry entry = ((TDEIO::StatJob*)job)->statResult();
+ TDEIO::UDSEntry::ConstIterator it = entry.begin();
+ d->tOrig = 0;
+ int found = 0;
+ for( ; it != entry.end() && found < 2; it++ )
+ {
+ if ( (*it).m_uds == TDEIO::UDS_MODIFICATION_TIME )
+ {
+ d->tOrig = (time_t)((*it).m_long);
+ found++;
+ }
+ else if ( (*it).m_uds == TDEIO::UDS_SIZE )
+ {
+ if ( filesize_t((*it).m_long) > d->maximumSize &&
+ !d->ignoreMaximumSize &&
+ !d->currentItem.plugin->property("IgnoreMaximumSize").toBool() )
+ {
+ determineNextFile();
+ return;
+ }
+ found++;
+ }
+ }
+
+ if ( !d->currentItem.plugin->property( "CacheThumbnail" ).toBool() )
+ {
+ // This preview will not be cached, no need to look for a saved thumbnail
+ // Just create it, and be done
+ getOrCreateThumbnail();
+ return;
+ }
+
+ if ( statResultThumbnail() )
+ return;
+
+ getOrCreateThumbnail();
+ return;
+ }
+ case PreviewJobPrivate::STATE_GETORIG:
+ {
+ if (job->error())
+ {
+ determineNextFile();
+ return;
+ }
+
+ createThumbnail( static_cast<TDEIO::FileCopyJob*>(job)->destURL().path() );
+ return;
+ }
+ case PreviewJobPrivate::STATE_CREATETHUMB:
+ {
+ if (!d->tempName.isEmpty())
+ {
+ TQFile::remove(d->tempName);
+ d->tempName = TQString::null;
+ }
+ determineNextFile();
+ return;
+ }
+ }
+}
+
+bool PreviewJob::statResultThumbnail()
+{
+ if ( d->thumbPath.isEmpty() )
+ return false;
+
+ KURL url = d->currentItem.item->url();
+ // Don't include the password if any
+ url.setPass(TQString::null);
+ // The TMS defines local files as file:///path/to/file instead of KDE's
+ // way (file:/path/to/file)
+#ifdef KURL_TRIPLE_SLASH_FILE_PROT
+ d->origName = url.url();
+#else
+ if (url.protocol() == "file") d->origName = "file://" + url.path();
+ else d->origName = url.url();
+#endif
+
+ KMD5 md5( TQFile::encodeName( d->origName ).data() );
+ d->thumbName = TQFile::encodeName( md5.hexDigest() ) + ".png";
+
+ TQImage thumb;
+ if ( !thumb.load( d->thumbPath + d->thumbName ) ) return false;
+
+ if ( thumb.text( "Thumb::URI", 0 ) != d->origName ||
+ thumb.text( "Thumb::MTime", 0 ).toInt() != d->tOrig ) return false;
+
+ // Found it, use it
+ emitPreview( thumb );
+ d->succeeded = true;
+ determineNextFile();
+ return true;
+}
+
+
+void PreviewJob::getOrCreateThumbnail()
+{
+ // We still need to load the orig file ! (This is getting tedious) :)
+ const KFileItem* item = d->currentItem.item;
+ const TQString localPath = item->localPath();
+ if ( !localPath.isEmpty() )
+ createThumbnail( localPath );
+ else
+ {
+ d->state = PreviewJobPrivate::STATE_GETORIG;
+ KTempFile localFile;
+ KURL localURL;
+ localURL.setPath( d->tempName = localFile.name() );
+ const KURL currentURL = item->url();
+ TDEIO::Job * job = TDEIO::file_copy( currentURL, localURL, -1, true,
+ false, false /* No GUI */ );
+ job->addMetaData("thumbnail","1");
+ addSubjob(job);
+ }
+}
+
+// KDE 4: Make it const TQString &
+void PreviewJob::createThumbnail( TQString pixPath )
+{
+ d->state = PreviewJobPrivate::STATE_CREATETHUMB;
+ KURL thumbURL;
+ thumbURL.setProtocol("thumbnail");
+ thumbURL.setPath(pixPath);
+ TDEIO::TransferJob *job = TDEIO::get(thumbURL, false, false);
+ addSubjob(job);
+ connect(job, TQT_SIGNAL(data(TDEIO::Job *, const TQByteArray &)), TQT_SLOT(slotThumbData(TDEIO::Job *, const TQByteArray &)));
+ bool save = d->bSave && d->currentItem.plugin->property("CacheThumbnail").toBool();
+ job->addMetaData("mimeType", d->currentItem.item->mimetype());
+ job->addMetaData("width", TQString().setNum(save ? d->cacheWidth : d->width));
+ job->addMetaData("height", TQString().setNum(save ? d->cacheHeight : d->height));
+ job->addMetaData("iconSize", TQString().setNum(save ? 64 : d->iconSize));
+ job->addMetaData("iconAlpha", TQString().setNum(d->iconAlpha));
+ job->addMetaData("plugin", d->currentItem.plugin->library());
+#ifdef Q_OS_UNIX
+ if (d->shmid == -1)
+ {
+ if (d->shmaddr) {
+ shmdt((char*)d->shmaddr);
+ shmctl(d->shmid, IPC_RMID, 0);
+ }
+ d->shmid = shmget(IPC_PRIVATE, d->cacheWidth * d->cacheHeight * 4, IPC_CREAT|0600);
+ if (d->shmid != -1)
+ {
+ d->shmaddr = (uchar *)(shmat(d->shmid, 0, SHM_RDONLY));
+ if (d->shmaddr == (uchar *)-1)
+ {
+ shmctl(d->shmid, IPC_RMID, 0);
+ d->shmaddr = 0;
+ d->shmid = -1;
+ }
+ }
+ else
+ d->shmaddr = 0;
+ }
+ if (d->shmid != -1)
+ job->addMetaData("shmid", TQString().setNum(d->shmid));
+#endif
+}
+
+void PreviewJob::slotThumbData(TDEIO::Job *, const TQByteArray &data)
+{
+ bool save = d->bSave &&
+ d->currentItem.plugin->property("CacheThumbnail").toBool() &&
+ (d->currentItem.item->url().protocol() != "file" ||
+ !d->currentItem.item->url().directory( false ).startsWith(d->thumbRoot));
+ TQImage thumb;
+#ifdef Q_OS_UNIX
+ if (d->shmaddr)
+ {
+ TQDataStream str(data, IO_ReadOnly);
+ int width, height, depth;
+ bool alpha;
+ str >> width >> height >> depth >> alpha;
+ thumb = TQImage(d->shmaddr, width, height, depth, 0, 0, TQImage::IgnoreEndian);
+ thumb.setAlphaBuffer(alpha);
+ }
+ else
+#endif
+ thumb.loadFromData(data);
+
+ if (save)
+ {
+ thumb.setText("Thumb::URI", 0, d->origName);
+ thumb.setText("Thumb::MTime", 0, TQString::number(d->tOrig));
+ thumb.setText("Thumb::Size", 0, number(d->currentItem.item->size()));
+ thumb.setText("Thumb::Mimetype", 0, d->currentItem.item->mimetype());
+ thumb.setText("Software", 0, "KDE Thumbnail Generator");
+ KTempFile temp(d->thumbPath + "kde-tmp-", ".png");
+ if (temp.status() == 0) //Only try to write out the thumbnail if we
+ { //actually created the temp file.
+ thumb.save(temp.name(), "PNG");
+ rename(TQFile::encodeName(temp.name()), TQFile::encodeName(d->thumbPath + d->thumbName));
+ }
+ }
+ emitPreview( thumb );
+ d->succeeded = true;
+}
+
+void PreviewJob::emitPreview(const TQImage &thumb)
+{
+ TQPixmap pix;
+ if (thumb.width() > d->width || thumb.height() > d->height)
+ {
+ double imgRatio = (double)thumb.height() / (double)thumb.width();
+ if (imgRatio > (double)d->height / (double)d->width)
+ pix.convertFromImage(
+ thumb.smoothScale((int)TQMAX((double)d->height / imgRatio, 1), d->height));
+ else pix.convertFromImage(
+ thumb.smoothScale(d->width, (int)TQMAX((double)d->width * imgRatio, 1)));
+ }
+ else pix.convertFromImage(thumb);
+ emit gotPreview(d->currentItem.item, pix);
+}
+
+void PreviewJob::emitFailed(const KFileItem *item)
+{
+ if (!item)
+ item = d->currentItem.item;
+ emit failed(item);
+}
+
+TQStringList PreviewJob::availablePlugins()
+{
+ TQStringList result;
+ KTrader::OfferList plugins = KTrader::self()->query("ThumbCreator");
+ for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
+ if (!result.contains((*it)->desktopEntryName()))
+ result.append((*it)->desktopEntryName());
+ return result;
+}
+
+TQStringList PreviewJob::supportedMimeTypes()
+{
+ TQStringList result;
+ KTrader::OfferList plugins = KTrader::self()->query("ThumbCreator");
+ for (KTrader::OfferList::ConstIterator it = plugins.begin(); it != plugins.end(); ++it)
+ result += (*it)->property("MimeTypes").toStringList();
+ return result;
+}
+
+void PreviewJob::kill( bool quietly )
+{
+ d->startPreviewTimer.stop();
+ Job::kill( quietly );
+}
+
+PreviewJob *TDEIO::filePreview( const KFileItemList &items, int width, int height,
+ int iconSize, int iconAlpha, bool scale, bool save,
+ const TQStringList *enabledPlugins )
+{
+ return new PreviewJob(items, width, height, iconSize, iconAlpha,
+ scale, save, enabledPlugins);
+}
+
+PreviewJob *TDEIO::filePreview( const KURL::List &items, int width, int height,
+ int iconSize, int iconAlpha, bool scale, bool save,
+ const TQStringList *enabledPlugins )
+{
+ KFileItemList fileItems;
+ for (KURL::List::ConstIterator it = items.begin(); it != items.end(); ++it)
+ fileItems.append(new KFileItem(KFileItem::Unknown, KFileItem::Unknown, *it, true));
+ return new PreviewJob(fileItems, width, height, iconSize, iconAlpha,
+ scale, save, enabledPlugins, true);
+}
+
+void PreviewJob::virtual_hook( int id, void* data )
+{ TDEIO::Job::virtual_hook( id, data ); }
+
diff --git a/tdeio/tdeio/previewjob.h b/tdeio/tdeio/previewjob.h
new file mode 100644
index 000000000..9c62859c9
--- /dev/null
+++ b/tdeio/tdeio/previewjob.h
@@ -0,0 +1,182 @@
+// -*- c++ -*-
+// vim: ts=4 sw=4 et
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ 2000 Carsten Pfeiffer <pfeiffer@kde.org>
+ 2001 Malte Starostik <malte.starostik@t-online.de>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_previewjob_h__
+#define __kio_previewjob_h__
+
+#include <tdefileitem.h>
+#include <tdeio/job.h>
+
+class TQPixmap;
+
+namespace TDEIO {
+ /*!
+ * This class catches a preview (thumbnail) for files.
+ * @short KIO Job to get a thumbnail picture
+ */
+ class TDEIO_EXPORT PreviewJob : public TDEIO::Job
+ {
+ Q_OBJECT
+ public:
+ /**
+ * Creates a new PreviewJob.
+ * @param items a list of files to create previews for
+ * @param width the desired width
+ * @param height the desired height, 0 to use the @p width
+ * @param iconSize the size of the mimetype icon to overlay over the
+ * preview or zero to not overlay an icon. This has no effect if the
+ * preview plugin that will be used doesn't use icon overlays.
+ * @param iconAlpha transparency to use for the icon overlay
+ * @param scale if the image is to be scaled to the requested size or
+ * returned in its original size
+ * @param save if the image should be cached for later use
+ * @param enabledPlugins if non-zero, this points to a list containing
+ * the names of the plugins that may be used.
+ * @param deleteItems true to delete the items when done
+ */
+ PreviewJob( const KFileItemList &items, int width, int height,
+ int iconSize, int iconAlpha, bool scale, bool save,
+ const TQStringList *enabledPlugins, bool deleteItems = false );
+ virtual ~PreviewJob();
+
+ /**
+ * Removes an item from preview processing. Use this if you passed
+ * an item to filePreview and want to delete it now.
+ *
+ * @param item the item that should be removed from the preview queue
+ */
+ void removeItem( const KFileItem *item );
+
+ /**
+ * If @p ignoreSize is true, then the preview is always
+ * generated regardless of the settings
+ *
+ * @since KDE 3.4
+ **/
+ void setIgnoreMaximumSize(bool ignoreSize = true);
+
+ /**
+ * Returns a list of all available preview plugins. The list
+ * contains the basenames of the plugins' .desktop files (no path,
+ * no .desktop).
+ * @return the list of plugins
+ */
+ static TQStringList availablePlugins();
+
+ /**
+ * Returns a list of all supported MIME types. The list can
+ * contain entries like text/ * (without the space).
+ * @return the list of mime types
+ */
+ static TQStringList supportedMimeTypes();
+
+ /**
+ * Reimplemented for internal reasons
+ */
+ virtual void kill( bool quietly = true );
+
+ signals:
+ /**
+ * Emitted when a thumbnail picture for @p item has been successfully
+ * retrieved.
+ * @param item the file of the preview
+ * @param preview the preview image
+ */
+ void gotPreview( const KFileItem *item, const TQPixmap &preview );
+ /**
+ * Emitted when a thumbnail for @p item could not be created,
+ * either because a ThumbCreator for its MIME type does not
+ * exist, or because something went wrong.
+ * @param item the file that failed
+ */
+ void failed( const KFileItem *item );
+
+ protected:
+ void getOrCreateThumbnail();
+ bool statResultThumbnail();
+ void createThumbnail( TQString );
+
+ protected slots:
+ virtual void slotResult( TDEIO::Job *job );
+
+ private slots:
+ void startPreview();
+ void slotThumbData(TDEIO::Job *, const TQByteArray &);
+
+ private:
+ void determineNextFile();
+ void emitPreview(const TQImage &thumb);
+ void emitFailed(const KFileItem *item = 0);
+
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ struct PreviewJobPrivate *d;
+ };
+
+ /**
+ * Creates a PreviewJob to generate or retrieve a preview image
+ * for the given URL.
+ *
+ * @param items files to get previews for
+ * @param width the maximum width to use
+ * @param height the maximum height to use, if this is 0, the same
+ * value as width is used.
+ * @param iconSize the size of the mimetype icon to overlay over the
+ * preview or zero to not overlay an icon. This has no effect if the
+ * preview plugin that will be used doesn't use icon overlays.
+ * @param iconAlpha transparency to use for the icon overlay
+ * @param scale if the image is to be scaled to the requested size or
+ * returned in its original size
+ * @param save if the image should be cached for later use
+ * @param enabledPlugins if non-zero, this points to a list containing
+ * the names of the plugins that may be used.
+ * @return the new PreviewJob
+ * @see PreviewJob::availablePlugins()
+ */
+ TDEIO_EXPORT PreviewJob *filePreview( const KFileItemList &items, int width, int height = 0, int iconSize = 0, int iconAlpha = 70, bool scale = true, bool save = true, const TQStringList *enabledPlugins = 0 );
+
+ /**
+ * Creates a PreviewJob to generate or retrieve a preview image
+ * for the given URL.
+ *
+ * @param items files to get previews for
+ * @param width the maximum width to use
+ * @param height the maximum height to use, if this is 0, the same
+ * value as width is used.
+ * @param iconSize the size of the mimetype icon to overlay over the
+ * preview or zero to not overlay an icon. This has no effect if the
+ * preview plugin that will be used doesn't use icon overlays.
+ * @param iconAlpha transparency to use for the icon overlay
+ * @param scale if the image is to be scaled to the requested size or
+ * returned in its original size
+ * @param save if the image should be cached for later use
+ * @param enabledPlugins if non-zero, this points to a list containing
+ * the names of the plugins that may be used.
+ * @return the new PreviewJob
+ * @see PreviewJob::availablePlugins()
+ */
+ TDEIO_EXPORT PreviewJob *filePreview( const KURL::List &items, int width, int height = 0, int iconSize = 0, int iconAlpha = 70, bool scale = true, bool save = true, const TQStringList *enabledPlugins = 0 );
+}
+
+#endif
diff --git a/kio/kio/progressbase.cpp b/tdeio/tdeio/progressbase.cpp
index 146f4182e..146f4182e 100644
--- a/kio/kio/progressbase.cpp
+++ b/tdeio/tdeio/progressbase.cpp
diff --git a/tdeio/tdeio/progressbase.h b/tdeio/tdeio/progressbase.h
new file mode 100644
index 000000000..655edeee5
--- /dev/null
+++ b/tdeio/tdeio/progressbase.h
@@ -0,0 +1,271 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Matej Koss <koss@miesto.sk>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+#ifndef __progressbase_h__
+#define __progressbase_h__
+
+
+#include <tqwidget.h>
+
+#include <tdeio/global.h>
+
+class KURL;
+namespace TDEIO {
+ class Job;
+ class CopyJob;
+ class DeleteJob;
+}
+
+namespace TDEIO
+{
+ enum Progress {
+ DEFAULT = 1,
+ STATUSBAR = 2,
+ LIST = 3
+ };
+
+/**
+* This class does all initialization stuff for progress,
+* like connecting signals to slots.
+* All slots are implemented as pure virtual methods.
+*
+* All custom IO progress dialog should inherit this class.
+* Add your GUI code to the constructor and implemement those virtual
+* methods which you need in order to display progress.
+*
+* E.g. StatusbarProgress only implements slotTotalSize(),
+* slotPercent() and slotSpeed().
+*
+* Custom progress dialog will be used like this :
+* \code
+* // create job
+* CopyJob* job = TDEIO::copy(...);
+* // create a dialog
+* MyCustomProgress *customProgress;
+* customProgress = new MyCustomProgress();
+* // connect progress with job
+* customProgress->setJob( job );
+* ...
+* \endcode
+*
+* There is a special method setStopOnClose() that controls the behavior of
+* the dialog.
+* @short Base class for IO progress dialogs.
+* @author Matej Koss <koss@miesto.sk>
+*/
+class TDEIO_EXPORT ProgressBase : public TQWidget {
+
+ Q_OBJECT
+
+public:
+
+ /**
+ * Creates a new progress dialog.
+ * @param parent the parent of this dialog window, or 0
+ */
+ ProgressBase( TQWidget *parent );
+ ~ProgressBase() {}
+
+ /**
+ * Assign a TDEIO::Job to this progress dialog.
+ * @param job the job to assign
+ */
+ void setJob( TDEIO::Job *job );
+ /**
+ * Assign a TDEIO::Job to this progress dialog.
+ * @param job the job to assign
+ */
+ void setJob( TDEIO::CopyJob *job );
+ /**
+ * Assign a TDEIO::Job to this progress dialog.
+ * @param job the job to assign
+ */
+ void setJob( TDEIO::DeleteJob *job );
+
+ // should we stop the job when the dialog is closed ?
+ void setStopOnClose( bool stopOnClose ) { m_bStopOnClose = stopOnClose; }
+ bool stopOnClose() const { return m_bStopOnClose; }
+
+ // should we delete the dialog or just clean it when the job is finished ?
+ /**
+ * This controls whether the dialog should be deleted or only cleaned when
+ * the TDEIO::Job is finished (or canceled).
+ *
+ * If your dialog is an embedded widget and not a separate window, you should
+ * setOnlyClean(true) in the constructor of your custom dialog.
+ *
+ * @param onlyClean If true the dialog will only call method slotClean.
+ * If false the dialog will be deleted.
+ * @see onlyClean()
+ */
+ void setOnlyClean( bool onlyClean ) { m_bOnlyClean = onlyClean; }
+
+ /**
+ * Checks whether the dialog should be deleted or cleaned.
+ * @return true if the dialog only calls slotClean, false if it will be
+ * deleted
+ * @see setOnlyClean()
+ */
+ bool onlyClean() const { return m_bOnlyClean; }
+
+ /**
+ * Call when the operation finished.
+ * @since 3.1
+ */
+ void finished();
+
+public slots:
+ /**
+ * This method should be called for correct cancellation of IO operation
+ * Connect this to the progress widgets buttons etc.
+ */
+ void slotStop();
+ /**
+ * This method is called when the widget should be cleaned (after job is finished).
+ * redefine this for custom behavior.
+ */
+ virtual void slotClean();
+
+ // progress slots
+ /**
+ * Called to set the total size.
+ * @param job the TDEIO::Job
+ * @param size the total size in bytes
+ */
+ virtual void slotTotalSize( TDEIO::Job* job, TDEIO::filesize_t size ) {
+ Q_UNUSED(job);Q_UNUSED(size);}
+ /**
+ * Called to set the total number of files.
+ * @param job the TDEIO::Job
+ * @param files the number of files
+ */
+ virtual void slotTotalFiles( TDEIO::Job* job, unsigned long files ) {
+ Q_UNUSED(job);Q_UNUSED(files);}
+ /**
+ * Called to set the total number of directories.
+ * @param job the TDEIO::Job
+ * @param dirs the number of directories
+ */
+ virtual void slotTotalDirs( TDEIO::Job* job, unsigned long dirs ) {
+ Q_UNUSED(job);Q_UNUSED(dirs);}
+
+ /**
+ * Called to set the processed size.
+ * @param job the TDEIO::Job
+ * @param bytes the processed size in bytes
+ */
+ virtual void slotProcessedSize( TDEIO::Job* job, TDEIO::filesize_t bytes ) {
+ Q_UNUSED(job);Q_UNUSED(bytes);}
+ /**
+ * Called to set the number of processed files.
+ * @param job the TDEIO::Job
+ * @param files the number of files
+ */
+ virtual void slotProcessedFiles( TDEIO::Job* job, unsigned long files ) {
+ Q_UNUSED(job);Q_UNUSED(files);}
+ /**
+ * Called to set the number of processed directories.
+ * @param job the TDEIO::Job
+ * @param dirs the number of directories
+ */
+ virtual void slotProcessedDirs( TDEIO::Job* job, unsigned long dirs ) {
+ Q_UNUSED(job);Q_UNUSED(dirs);}
+
+ /**
+ * Called to set the speed.
+ * @param job the TDEIO::Job
+ * @param speed the speed in bytes/second
+ */
+ virtual void slotSpeed( TDEIO::Job* job, unsigned long speed ) {
+ Q_UNUSED(job);Q_UNUSED(speed);}
+
+ /**
+ * Called to set the percentage.
+ * @param job the TDEIO::Job
+ * @param percent the percentage
+ */
+ virtual void slotPercent( TDEIO::Job* job, unsigned long percent ) {
+ Q_UNUSED(job);Q_UNUSED(percent);}
+
+ /**
+ * Called when the job is copying.
+ * @param job the TDEIO::Job
+ * @param src the source of the operation
+ * @param dest the destination of the operation
+ */
+ virtual void slotCopying( TDEIO::Job* job, const KURL& src, const KURL& dest ) {
+ Q_UNUSED(job);Q_UNUSED(src);Q_UNUSED(dest);}
+ /**
+ * Called when the job is moving.
+ * @param job the TDEIO::Job
+ * @param src the source of the operation
+ * @param dest the destination of the operation
+ */
+ virtual void slotMoving( TDEIO::Job* job, const KURL& src, const KURL& dest ) {
+ Q_UNUSED(job);Q_UNUSED(src);Q_UNUSED(dest);}
+ /**
+ * Called when the job is deleting.
+ * @param job the TDEIO::Job
+ * @param url the URL to delete
+ */
+ virtual void slotDeleting( TDEIO::Job* job, const KURL& url) {
+ Q_UNUSED(job);Q_UNUSED(url);}
+ /**
+ * Called when the job is creating a directory.
+ * @param job the TDEIO::Job
+ * @param dir the URL of the directory to create
+ */
+ virtual void slotCreatingDir( TDEIO::Job* job, const KURL& dir ) {
+ Q_UNUSED(job);Q_UNUSED(dir);}
+
+ /**
+ * Called when the job is resuming..
+ * @param job the TDEIO::Job
+ * @param from the position to resume from in bytes
+ */
+ virtual void slotCanResume( TDEIO::Job* job, TDEIO::filesize_t from) {
+ Q_UNUSED(job);Q_UNUSED(from);}
+
+signals:
+ /**
+ * Called when the operation stopped.
+ */
+ void stopped();
+
+protected slots:
+ void slotFinished( TDEIO::Job* );
+
+protected:
+
+ virtual void closeEvent( TQCloseEvent * );
+
+ TDEIO::Job* m_pJob;
+
+private:
+ bool m_bOnlyClean;
+ bool m_bStopOnClose;
+
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class ProgressBasePrivate* d;
+};
+
+} /* namespace */
+
+#endif // __progressbase_h__
diff --git a/tdeio/tdeio/renamedlg.cpp b/tdeio/tdeio/renamedlg.cpp
new file mode 100644
index 000000000..d66130993
--- /dev/null
+++ b/tdeio/tdeio/renamedlg.cpp
@@ -0,0 +1,574 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ David Faure <faure@kde.org>
+ 2001 Holger Freyther <freyther@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdeio/renamedlg.h"
+#include "tdeio/renamedlgplugin.h"
+#include <stdio.h>
+#include <assert.h>
+
+#include <tqfileinfo.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqlineedit.h>
+#include <tqdir.h>
+
+#include <kmessagebox.h>
+#include <kpushbutton.h>
+#include <kapplication.h>
+#include <tdeio/global.h>
+#include <ktrader.h>
+#include <klibloader.h>
+#include <kdialog.h>
+#include <klocale.h>
+#include <kglobal.h>
+#include <kdebug.h>
+#include <kurl.h>
+#include <kmimetype.h>
+#include <kseparator.h>
+#include <kstringhandler.h>
+#include <kstdguiitem.h>
+#include <kguiitem.h>
+#include <ksqueezedtextlabel.h>
+
+#ifdef Q_WS_X11
+#include <twin.h>
+#endif
+
+using namespace TDEIO;
+
+class RenameDlg::RenameDlgPrivate
+{
+ public:
+ RenameDlgPrivate(){
+ bCancel = 0;
+ bRename = bSkip = bAutoSkip = bOverwrite = bOverwriteAll = 0;
+ bResume = bResumeAll = bSuggestNewName = 0;
+ m_pLineEdit = 0;
+ }
+ KPushButton *bCancel;
+ TQPushButton *bRename;
+ TQPushButton *bSkip;
+ TQPushButton *bAutoSkip;
+ TQPushButton *bOverwrite;
+ TQPushButton *bOverwriteAll;
+ TQPushButton *bResume;
+ TQPushButton *bResumeAll;
+ TQPushButton *bSuggestNewName;
+ TQLineEdit* m_pLineEdit;
+ KURL src;
+ KURL dest;
+ TQString mimeSrc;
+ TQString mimeDest;
+ bool modal;
+ bool plugin;
+};
+
+RenameDlg::RenameDlg(TQWidget *parent, const TQString & _caption,
+ const TQString &_src, const TQString &_dest,
+ RenameDlg_Mode _mode,
+ TDEIO::filesize_t sizeSrc,
+ TDEIO::filesize_t sizeDest,
+ time_t ctimeSrc,
+ time_t ctimeDest,
+ time_t mtimeSrc,
+ time_t mtimeDest,
+ bool _modal)
+ : TQDialog ( parent, "TDEIO::RenameDialog" , _modal )
+{
+ d = new RenameDlgPrivate( );
+ d->modal = _modal;
+#if 0
+ // Set "StaysOnTop", because this dialog is typically used in tdeio_uiserver,
+ // i.e. in a separate process.
+ // ####### This isn't the case anymore - remove?
+#if !defined(Q_WS_QWS) && !defined(Q_WS_WIN) //FIXME(E): Implement for QT Embedded & win32
+ if (d->modal)
+ KWin::setState( winId(), NET::StaysOnTop );
+#endif
+#endif
+
+ d->src = _src;
+ d->dest = _dest;
+ d->plugin = false;
+
+
+ setCaption( _caption );
+
+ d->bCancel = new KPushButton( KStdGuiItem::cancel(), this );
+ connect(d->bCancel, TQT_SIGNAL(clicked()), this, TQT_SLOT(b0Pressed()));
+
+ if ( ! (_mode & M_NORENAME ) ) {
+ d->bRename = new TQPushButton( i18n( "&Rename" ), this );
+ d->bRename->setEnabled(false);
+ d->bSuggestNewName = new TQPushButton( i18n( "Suggest New &Name" ), this );
+ connect(d->bSuggestNewName, TQT_SIGNAL(clicked()), this, TQT_SLOT(b8Pressed()));
+ connect(d->bRename, TQT_SIGNAL(clicked()), this, TQT_SLOT(b1Pressed()));
+ }
+
+ if ( ( _mode & M_MULTI ) && ( _mode & M_SKIP ) ) {
+ d->bSkip = new TQPushButton( i18n( "&Skip" ), this );
+ connect(d->bSkip, TQT_SIGNAL(clicked()), this, TQT_SLOT(b2Pressed()));
+
+ d->bAutoSkip = new TQPushButton( i18n( "&Auto Skip" ), this );
+ connect(d->bAutoSkip, TQT_SIGNAL(clicked()), this, TQT_SLOT(b3Pressed()));
+ }
+
+ if ( _mode & M_OVERWRITE ) {
+ d->bOverwrite = new TQPushButton( i18n( "&Overwrite" ), this );
+ connect(d->bOverwrite, TQT_SIGNAL(clicked()), this, TQT_SLOT(b4Pressed()));
+
+ if ( _mode & M_MULTI ) {
+ d->bOverwriteAll = new TQPushButton( i18n( "O&verwrite All" ), this );
+ connect(d->bOverwriteAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(b5Pressed()));
+ }
+ }
+
+ if ( _mode & M_RESUME ) {
+ d->bResume = new TQPushButton( i18n( "&Resume" ), this );
+ connect(d->bResume, TQT_SIGNAL(clicked()), this, TQT_SLOT(b6Pressed()));
+
+ if ( _mode & M_MULTI )
+ {
+ d->bResumeAll = new TQPushButton( i18n( "R&esume All" ), this );
+ connect(d->bResumeAll, TQT_SIGNAL(clicked()), this, TQT_SLOT(b7Pressed()));
+ }
+ }
+
+ TQVBoxLayout* pLayout = new TQVBoxLayout( this, KDialog::marginHint(),
+ KDialog::spacingHint() );
+ pLayout->addStrut( 360 ); // makes dlg at least that wide
+
+ // User tries to overwrite a file with itself ?
+ if ( _mode & M_OVERWRITE_ITSELF ) {
+ TQLabel *lb = new TQLabel( i18n( "This action would overwrite '%1' with itself.\n"
+ "Please enter a new file name:" ).arg( KStringHandler::csqueeze( d->src.pathOrURL(),100 ) ), this );
+ d->bRename->setText(i18n("C&ontinue"));
+ pLayout->addWidget( lb );
+ }
+ else if ( _mode & M_OVERWRITE ) {
+
+ // Figure out the mimetype and load one plugin
+ // (This is the only mode that is handled by plugins)
+ pluginHandling();
+ KTrader::OfferList plugin_offers;
+ if( d->mimeSrc != KMimeType::defaultMimeType() ){
+ plugin_offers = KTrader::self()->query(d->mimeSrc, "'RenameDlg/Plugin' in ServiceTypes");
+
+ }else if(d->mimeDest != KMimeType::defaultMimeType() ) {
+ plugin_offers = KTrader::self()->query(d->mimeDest, "'RenameDlg/Plugin' in ServiceTypes");
+ }
+ if(!plugin_offers.isEmpty() ){
+ kdDebug(7024) << "Offers" << endl;
+ KTrader::OfferList::ConstIterator it = plugin_offers.begin();
+ KTrader::OfferList::ConstIterator end = plugin_offers.end();
+ for( ; it != end; ++it ){
+ TQString libName = (*it)->library();
+ if( libName.isEmpty() ){
+ kdDebug(7024) << "lib is empty" << endl;
+ continue;
+ }
+ KLibrary *lib = KLibLoader::self()->library(libName.local8Bit() );
+ if(!lib) {
+ continue;
+ }
+ KLibFactory *factory = lib->factory();
+ if(!factory){
+ lib->unload();
+ continue;
+ }
+ TQObject *obj = factory->create( TQT_TQOBJECT(this), (*it)->name().latin1() );
+ if(!obj) {
+ lib->unload();
+ continue;
+ }
+ RenameDlgPlugin *plugin = static_cast<RenameDlgPlugin *>(TQT_TQWIDGET(obj));
+ if(!plugin ){
+ delete obj;
+ continue;
+ }
+ if( plugin->initialize( _mode, _src, _dest, d->mimeSrc,
+ d->mimeDest, sizeSrc, sizeDest,
+ ctimeSrc, ctimeDest,
+ mtimeSrc, mtimeDest ) ) {
+ d->plugin = true;
+ pLayout->addWidget(plugin );
+ kdDebug(7024) << "RenameDlgPlugin" << endl;
+ break;
+ } else {
+ delete obj;
+ }
+ }
+
+ }
+
+ if( !d->plugin ){
+ // No plugin found, build default dialog
+ TQGridLayout * gridLayout = new TQGridLayout( 0L, 9, 2, KDialog::marginHint(),
+ KDialog::spacingHint() );
+ pLayout->addLayout(TQT_TQLAYOUT(gridLayout));
+ gridLayout->setColStretch(0,0);
+ gridLayout->setColStretch(1,10);
+
+ TQString sentence1;
+ if (mtimeDest < mtimeSrc)
+ sentence1 = i18n("An older item named '%1' already exists.");
+ else if (mtimeDest == mtimeSrc)
+ sentence1 = i18n("A similar file named '%1' already exists.");
+ else
+ sentence1 = i18n("A newer item named '%1' already exists.");
+
+ TQLabel * lb1 = new KSqueezedTextLabel( sentence1.arg(d->dest.pathOrURL() ), this );
+ gridLayout->addMultiCellWidget( lb1, 0, 0, 0, 1 ); // takes the complete first line
+
+ lb1 = new TQLabel( this );
+ lb1->setPixmap( KMimeType::pixmapForURL( d->dest ) );
+ gridLayout->addMultiCellWidget( lb1, 1, 3, 0, 0 ); // takes the first column on rows 1-3
+
+ int row = 1;
+ if ( sizeDest != (TDEIO::filesize_t)-1 )
+ {
+ TQLabel * lb = new TQLabel( i18n("size %1").arg( TDEIO::convertSize(sizeDest) ), this );
+ gridLayout->addWidget( lb, row, 1 );
+ row++;
+
+ }
+ if ( ctimeDest != (time_t)-1 )
+ {
+ TQDateTime dctime; dctime.setTime_t( ctimeDest );
+ TQLabel * lb = new TQLabel( i18n("created on %1").arg( TDEGlobal::locale()->formatDateTime(dctime) ), this );
+ gridLayout->addWidget( lb, row, 1 );
+ row++;
+ }
+ if ( mtimeDest != (time_t)-1 )
+ {
+ TQDateTime dmtime; dmtime.setTime_t( mtimeDest );
+ TQLabel * lb = new TQLabel( i18n("modified on %1").arg( TDEGlobal::locale()->formatDateTime(dmtime) ), this );
+ gridLayout->addWidget( lb, row, 1 );
+ row++;
+ }
+
+ if ( !d->src.isEmpty() )
+ {
+ // rows 1 to 3 are the details (size/ctime/mtime), row 4 is empty
+ gridLayout->addRowSpacing( 4, 20 );
+
+ TQLabel * lb2 = new KSqueezedTextLabel( i18n("The source file is '%1'").arg(d->src.pathOrURL()), this );
+ gridLayout->addMultiCellWidget( lb2, 5, 5, 0, 1 ); // takes the complete first line
+
+ lb2 = new TQLabel( this );
+ lb2->setPixmap( KMimeType::pixmapForURL( d->src ) );
+ gridLayout->addMultiCellWidget( lb2, 6, 8, 0, 0 ); // takes the first column on rows 6-8
+
+ row = 6;
+
+ if ( sizeSrc != (TDEIO::filesize_t)-1 )
+ {
+ TQLabel * lb = new TQLabel( i18n("size %1").arg( TDEIO::convertSize(sizeSrc) ), this );
+ gridLayout->addWidget( lb, row, 1 );
+ row++;
+ }
+ if ( ctimeSrc != (time_t)-1 )
+ {
+ TQDateTime dctime; dctime.setTime_t( ctimeSrc );
+ TQLabel * lb = new TQLabel( i18n("created on %1").arg( TDEGlobal::locale()->formatDateTime(dctime) ), this );
+ gridLayout->addWidget( lb, row, 1 );
+ row++;
+ }
+ if ( mtimeSrc != (time_t)-1 )
+ {
+ TQDateTime dmtime; dmtime.setTime_t( mtimeSrc );
+ TQLabel * lb = new TQLabel( i18n("modified on %1").arg( TDEGlobal::locale()->formatDateTime(dmtime) ), this );
+ gridLayout->addWidget( lb, row, 1 );
+ row++;
+ }
+ }
+ }
+ }
+ else
+ {
+ // This is the case where we don't want to allow overwriting, the existing
+ // file must be preserved (e.g. when renaming).
+ TQString sentence1;
+ if (mtimeDest < mtimeSrc)
+ sentence1 = i18n("An older item named '%1' already exists.");
+ else if (mtimeDest == mtimeSrc)
+ sentence1 = i18n("A similar file named '%1' already exists.");
+ else
+ sentence1 = i18n("A newer item named '%1' already exists.");
+
+ TQLabel *lb = new KSqueezedTextLabel( sentence1.arg(d->dest.pathOrURL()), this );
+ pLayout->addWidget(lb);
+ }
+ TQHBoxLayout* layout2 = new TQHBoxLayout();
+ pLayout->addLayout( layout2 );
+
+ d->m_pLineEdit = new TQLineEdit( this );
+ layout2->addWidget( d->m_pLineEdit );
+ TQString fileName = d->dest.fileName();
+ d->m_pLineEdit->setText( TDEIO::decodeFileName( fileName ) );
+ if ( d->bRename || d->bOverwrite )
+ connect(d->m_pLineEdit, TQT_SIGNAL(textChanged(const TQString &)),
+ TQT_SLOT(enableRenameButton(const TQString &)));
+ if ( d->bSuggestNewName )
+ {
+ layout2->addWidget( d->bSuggestNewName );
+ setTabOrder( d->m_pLineEdit, d->bSuggestNewName );
+ }
+
+ KSeparator* separator = new KSeparator( this );
+ pLayout->addWidget( separator );
+
+ TQHBoxLayout* layout = new TQHBoxLayout();
+ pLayout->addLayout( layout );
+
+ layout->addStretch(1);
+
+ if ( d->bRename )
+ {
+ layout->addWidget( d->bRename );
+ setTabOrder( d->bRename, d->bCancel );
+ }
+ if ( d->bSkip )
+ {
+ layout->addWidget( d->bSkip );
+ setTabOrder( d->bSkip, d->bCancel );
+ }
+ if ( d->bAutoSkip )
+ {
+ layout->addWidget( d->bAutoSkip );
+ setTabOrder( d->bAutoSkip, d->bCancel );
+ }
+ if ( d->bOverwrite )
+ {
+ layout->addWidget( d->bOverwrite );
+ setTabOrder( d->bOverwrite, d->bCancel );
+ }
+ if ( d->bOverwriteAll )
+ {
+ layout->addWidget( d->bOverwriteAll );
+ setTabOrder( d->bOverwriteAll, d->bCancel );
+ }
+ if ( d->bResume )
+ {
+ layout->addWidget( d->bResume );
+ setTabOrder( d->bResume, d->bCancel );
+ }
+ if ( d->bResumeAll )
+ {
+ layout->addWidget( d->bResumeAll );
+ setTabOrder( d->bResumeAll, d->bCancel );
+ }
+
+ d->bCancel->setDefault( true );
+ layout->addWidget( d->bCancel );
+
+ resize( sizeHint() );
+}
+
+RenameDlg::~RenameDlg()
+{
+ delete d;
+ // no need to delete Pushbuttons,... qt will do this
+}
+
+void RenameDlg::enableRenameButton(const TQString &newDest)
+{
+ if ( newDest != TDEIO::decodeFileName( d->dest.fileName() ) && !newDest.isEmpty() )
+ {
+ d->bRename->setEnabled( true );
+ d->bRename->setDefault( true );
+ if ( d->bOverwrite )
+ d->bOverwrite->setEnabled( false ); // prevent confusion (#83114)
+ }
+ else
+ {
+ d->bRename->setEnabled( false );
+ if ( d->bOverwrite )
+ d->bOverwrite->setEnabled( true );
+ }
+}
+
+KURL RenameDlg::newDestURL()
+{
+ KURL newDest( d->dest );
+ TQString fileName = d->m_pLineEdit->text();
+ newDest.setFileName( TDEIO::encodeFileName( fileName ) );
+ return newDest;
+}
+
+void RenameDlg::b0Pressed()
+{
+ done( 0 );
+}
+
+// Rename
+void RenameDlg::b1Pressed()
+{
+ if ( d->m_pLineEdit->text().isEmpty() )
+ return;
+
+ KURL u = newDestURL();
+ if ( !u.isValid() )
+ {
+ KMessageBox::error( this, i18n( "Malformed URL\n%1" ).arg( u.url() ) );
+ return;
+ }
+
+ done( 1 );
+}
+
+TQString RenameDlg::suggestName(const KURL& baseURL, const TQString& oldName)
+{
+ TQString dotSuffix, suggestedName;
+ TQString basename = oldName;
+
+ int index = basename.find( '.' );
+ if ( index != -1 ) {
+ dotSuffix = basename.mid( index );
+ basename.truncate( index );
+ }
+
+ int pos = basename.findRev( '_' );
+ if(pos != -1 ){
+ TQString tmp = basename.mid( pos+1 );
+ bool ok;
+ int number = tmp.toInt( &ok );
+ if ( !ok ) {// ok there is no number
+ suggestedName = basename + "1" + dotSuffix;
+ }
+ else {
+ // yes there's already a number behind the _ so increment it by one
+ basename.replace( pos+1, tmp.length(), TQString::number(number+1) );
+ suggestedName = basename + dotSuffix;
+ }
+ }
+ else // no underscore yet
+ suggestedName = basename + "_1" + dotSuffix ;
+
+ // Check if suggested name already exists
+ bool exists = false;
+ // TODO: network transparency. However, using NetAccess from a modal dialog
+ // could be a problem, no? (given that it uses a modal widget itself....)
+ if ( baseURL.isLocalFile() )
+ exists = TQFileInfo( baseURL.path(+1) + suggestedName ).exists();
+
+ if ( !exists )
+ return suggestedName;
+ else // already exists -> recurse
+ return suggestName( baseURL, suggestedName );
+}
+
+// Propose button clicked
+void RenameDlg::b8Pressed()
+{
+ /* no name to play with */
+ if ( d->m_pLineEdit->text().isEmpty() )
+ return;
+
+ KURL destDirectory( d->dest );
+ destDirectory.setPath( destDirectory.directory() );
+ d->m_pLineEdit->setText( suggestName( destDirectory, d->m_pLineEdit->text() ) );
+ return;
+}
+
+void RenameDlg::b2Pressed()
+{
+ done( 2 );
+}
+
+void RenameDlg::b3Pressed()
+{
+ done( 3 );
+}
+
+void RenameDlg::b4Pressed()
+{
+ done( 4 );
+}
+
+void RenameDlg::b5Pressed()
+{
+ done( 5 );
+}
+
+void RenameDlg::b6Pressed()
+{
+ done( 6 );
+}
+
+void RenameDlg::b7Pressed()
+{
+ done( 7 );
+}
+
+static TQString mime( const KURL& src )
+{
+ KMimeType::Ptr type = KMimeType::findByURL( src );
+ //if( type->name() == KMimeType::defaultMimeType() ){ // ok no mimetype
+ // TQString ty = TDEIO::NetAccess::mimetype(d->src );
+ // return ty;
+ return type->name();
+}
+
+/** This will figure out the mimetypes and query for a plugin
+ * Loads it then and asks the plugin if it wants to do the job
+ * We'll take the first available mimetype
+ * The scanning for a mimetype will be done in 2 ways
+ *
+ */
+void RenameDlg::pluginHandling()
+{
+ d->mimeSrc = mime( d->src );
+ d->mimeDest = mime(d->dest );
+
+ kdDebug(7024) << "Source Mimetype: "<< d->mimeSrc << endl;
+ kdDebug(7024) << "Dest Mimetype: "<< d->mimeDest << endl;
+}
+
+
+RenameDlg_Result TDEIO::open_RenameDlg( const TQString & _caption,
+ const TQString & _src, const TQString & _dest,
+ RenameDlg_Mode _mode,
+ TQString& _new,
+ TDEIO::filesize_t sizeSrc,
+ TDEIO::filesize_t sizeDest,
+ time_t ctimeSrc,
+ time_t ctimeDest,
+ time_t mtimeSrc,
+ time_t mtimeDest)
+{
+ Q_ASSERT(kapp);
+
+ RenameDlg dlg( 0L, _caption, _src, _dest, _mode,
+ sizeSrc, sizeDest, ctimeSrc, ctimeDest, mtimeSrc, mtimeDest,
+ true /*modal*/ );
+ int i = dlg.exec();
+ _new = dlg.newDestURL().path();
+
+ return (RenameDlg_Result)i;
+}
+
+#include "renamedlg.moc"
+
+
+
+
+
diff --git a/tdeio/tdeio/renamedlg.h b/tdeio/tdeio/renamedlg.h
new file mode 100644
index 000000000..81f16df94
--- /dev/null
+++ b/tdeio/tdeio/renamedlg.h
@@ -0,0 +1,153 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ David Faure <faure@kde.org>
+ 2001 Holger Freyther <freyther@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_rename_dlg__
+#define __kio_rename_dlg__
+
+#include <kurl.h>
+#include <tqdialog.h>
+#include <tqstring.h>
+#include <sys/types.h>
+
+#include <tdeio/global.h>
+
+namespace TDEIO {
+
+// KDE4: get rid of M_OVERWRITE_ITSELF, trigger it internally if src==dest
+enum RenameDlg_Mode { M_OVERWRITE = 1, M_OVERWRITE_ITSELF = 2, M_SKIP = 4, M_SINGLE = 8, M_MULTI = 16, M_RESUME = 32, M_NORENAME = 64 };
+
+/**
+ * The result of open_RenameDlg().
+ */
+enum RenameDlg_Result { R_RESUME = 6, R_RESUME_ALL = 7, R_OVERWRITE = 4, R_OVERWRITE_ALL = 5, R_SKIP = 2, R_AUTO_SKIP = 3, R_RENAME = 1, R_CANCEL = 0 };
+
+
+/**
+ * A dialog for the options to rename two files.
+ * @short A dialog for renaming files.
+ * @since 3.1
+ */
+class TDEIO_EXPORT RenameDlg : public TQDialog
+{
+ Q_OBJECT
+public:
+ /**
+ * Construct a "rename" dialog.
+ * @param parent parent widget (often 0)
+ * @param caption the caption for the dialog box
+ * @param src the url to the file/dir we're trying to copy, as it's part of the text message
+ * @param dest the path to destination file/dir, i.e. the one that already exists
+ * @param mode parameters for the dialog (which buttons to show...),
+ * @param sizeSrc size of source file
+ * @param sizeDest size of destination file
+ * @param ctimeSrc creation time of source file
+ * @param ctimeDest creation time of destination file
+ * @param mtimeSrc modification time of source file
+ * @param mtimeDest modification time of destination file
+ * @param modal set to true for a modal dialog
+ * @see RenameDlg_Mode
+ */
+ RenameDlg( TQWidget *parent, const TQString & caption,
+ // KDE4: make those KURLs, and use pathOrURL() internally.
+ const TQString & src, const TQString & dest,
+ RenameDlg_Mode mode,
+ TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1,
+ TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1,
+ time_t ctimeSrc = (time_t) -1,
+ time_t ctimeDest = (time_t) -1,
+ time_t mtimeSrc = (time_t) -1,
+ time_t mtimeDest = (time_t) -1,
+ bool modal = false );
+ ~RenameDlg();
+
+ /**
+ * @return the new destination
+ * valid only if RENAME was chosen
+ */
+ KURL newDestURL();
+
+ /**
+ * Given a directory path and a filename (which usually exists already),
+ * this function returns a suggested name for a file that doesn't exist
+ * in that directory. The existence is only checked for local urls though.
+ * The suggested file name is of the form foo_1 foo_2 etc.
+ * @since 3.4
+ */
+ static TQString suggestName(const KURL& baseURL, const TQString& oldName);
+
+public slots:
+ /// KDE4: rename to cancelPressed(), renamePressed() etc.
+ void b0Pressed();
+ void b1Pressed();
+ void b2Pressed();
+ void b3Pressed();
+ void b4Pressed();
+ void b5Pressed();
+ void b6Pressed();
+ void b7Pressed();
+ void b8Pressed();
+
+protected slots:
+ void enableRenameButton(const TQString &);
+private:
+ class RenameDlgPrivate;
+ RenameDlgPrivate *d;
+ void pluginHandling( );
+};
+
+ /**
+ * \addtogroup renamedlg "RenameDlg related Functions"
+ * @{
+ * \relates TDEIO::RenameDlg
+ * Construct a modal, parent-less "rename" dialog, and return
+ * a result code, as well as the new dest. Much easier to use than the
+ * class RenameDlg directly.
+
+ * @param caption the caption for the dialog box
+ * @param src the URL of the file/dir we're trying to copy, as it's part of the text message
+ * @param dest the URL of the destination file/dir, i.e. the one that already exists
+ * @param mode parameters for the dialog (which buttons to show...),
+ * see RenameDlg_Mode
+ * @param newDest the new destination path, valid if R_RENAME was returned.
+ * @param sizeSrc size of source file
+ * @param sizeDest size of destination file
+ * @param ctimeSrc creation time of source file
+ * @param ctimeDest creation time of destination file
+ * @param mtimeSrc modification time of source file
+ * @param mtimeDest modification time of destination file
+ * @return the result
+ */
+TDEIO_EXPORT RenameDlg_Result open_RenameDlg( const TQString & caption,
+ // KDE4: make those KURLs
+ const TQString& src, const TQString & dest,
+ RenameDlg_Mode mode, TQString& newDestPath,
+ TDEIO::filesize_t sizeSrc = (TDEIO::filesize_t) -1,
+ TDEIO::filesize_t sizeDest = (TDEIO::filesize_t) -1,
+ time_t ctimeSrc = (time_t) -1,
+ time_t ctimeDest = (time_t) -1,
+ time_t mtimeSrc = (time_t) -1,
+ time_t mtimeDest = (time_t) -1
+ );
+
+/*! @} */
+
+}
+#endif
diff --git a/tdeio/tdeio/renamedlgplugin.h b/tdeio/tdeio/renamedlgplugin.h
new file mode 100644
index 000000000..18daab017
--- /dev/null
+++ b/tdeio/tdeio/renamedlgplugin.h
@@ -0,0 +1,59 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2001 Holger Freyther <freyther@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef renamedlgplugin_h
+#define renamedlgplugin_h
+
+#include <tdeio/renamedlg.h>
+#include <tqdialog.h>
+#include <sys/types.h>
+#include <tqstring.h>
+#include <tqstringlist.h>
+
+/**
+ * This is the base class for all RenameDlg plugins.
+ * @short Base class for RenameDlg plugins.
+ * @since 3.1
+ */
+class TDEIO_EXPORT RenameDlgPlugin : public TQWidget
+{
+public:
+ /**
+ * This is the c'tor.
+ */
+ RenameDlgPlugin(TQDialog *dialog, const char *name, const TQStringList &/*list*/ = TQStringList() ): TQWidget(dialog, name ) {};
+
+ /**
+ * This function will be called by RenameDlg. The params are infos about the files.
+ * @return If the plugin want's to display it return true, if not return false
+ */
+ virtual bool initialize(TDEIO::RenameDlg_Mode /*mod*/ , const TQString &/*_src*/, const TQString &/*_dest*/,
+ const TQString &/*mimeSrc*/,
+ const TQString &/*mimeDest*/,
+ TDEIO::filesize_t /*sizeSrc*/,
+ TDEIO::filesize_t /*sizeDest*/,
+ time_t /*ctimeSrc*/,
+ time_t /*ctimeDest*/,
+ time_t /*mtimeSrc*/,
+ time_t /*mtimeDest*/ ) {return false;};
+
+};
+
+#endif
+
diff --git a/tdeio/tdeio/scheduler.cpp b/tdeio/tdeio/scheduler.cpp
new file mode 100644
index 000000000..c0aad7d38
--- /dev/null
+++ b/tdeio/tdeio/scheduler.cpp
@@ -0,0 +1,922 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdeio/sessiondata.h"
+#include "tdeio/slaveconfig.h"
+#include "tdeio/scheduler.h"
+#include "tdeio/authinfo.h"
+#include "tdeio/slave.h"
+#include <tqptrlist.h>
+#include <tqdict.h>
+
+#include <dcopclient.h>
+
+#include <kdebug.h>
+#include <kglobal.h>
+#include <kprotocolmanager.h>
+#include <kprotocolinfo.h>
+#include <assert.h>
+#include <kstaticdeleter.h>
+#include <tdesu/client.h>
+
+
+// Slaves may be idle for MAX_SLAVE_IDLE time before they are being returned
+// to the system wide slave pool. (3 minutes)
+#define MAX_SLAVE_IDLE (3*60)
+
+using namespace TDEIO;
+
+template class TQDict<TDEIO::Scheduler::ProtocolInfo>;
+
+Scheduler *Scheduler::instance = 0;
+
+class TDEIO::SlaveList: public TQPtrList<Slave>
+{
+ public:
+ SlaveList() { }
+};
+
+//
+// There are two kinds of protocol:
+// (1) The protocol of the url
+// (2) The actual protocol that the io-slave uses.
+//
+// These two often match, but not necasserily. Most notably, they don't
+// match when doing ftp via a proxy.
+// In that case (1) is ftp, but (2) is http.
+//
+// JobData::protocol stores (2) while Job::url().protocol() returns (1).
+// The ProtocolInfoDict is indexed with (2).
+//
+// We schedule slaves based on (2) but tell the slave about (1) via
+// Slave::setProtocol().
+
+class TDEIO::Scheduler::JobData
+{
+public:
+ JobData() : checkOnHold(false) { }
+
+public:
+ TQString protocol;
+ TQString proxy;
+ bool checkOnHold;
+};
+
+class TDEIO::Scheduler::ExtraJobData: public TQPtrDict<TDEIO::Scheduler::JobData>
+{
+public:
+ ExtraJobData() { setAutoDelete(true); }
+};
+
+class TDEIO::Scheduler::ProtocolInfo
+{
+public:
+ ProtocolInfo() : maxSlaves(1), skipCount(0)
+ {
+ joblist.setAutoDelete(false);
+ }
+
+ TQPtrList<SimpleJob> joblist;
+ SlaveList activeSlaves;
+ int maxSlaves;
+ int skipCount;
+ TQString protocol;
+};
+
+class TDEIO::Scheduler::ProtocolInfoDict : public TQDict<TDEIO::Scheduler::ProtocolInfo>
+{
+ public:
+ ProtocolInfoDict() { }
+
+ TDEIO::Scheduler::ProtocolInfo *get( const TQString &protocol);
+};
+
+TDEIO::Scheduler::ProtocolInfo *
+TDEIO::Scheduler::ProtocolInfoDict::get(const TQString &protocol)
+{
+ ProtocolInfo *info = find(protocol);
+ if (!info)
+ {
+ info = new ProtocolInfo;
+ info->protocol = protocol;
+ info->maxSlaves = KProtocolInfo::maxSlaves( protocol );
+
+ insert(protocol, info);
+ }
+ return info;
+}
+
+
+Scheduler::Scheduler()
+ : DCOPObject( "TDEIO::Scheduler" ),
+ TQObject(kapp, "scheduler"),
+ slaveTimer(0, "Scheduler::slaveTimer"),
+ coSlaveTimer(0, "Scheduler::coSlaveTimer"),
+ cleanupTimer(0, "Scheduler::cleanupTimer")
+{
+ checkOnHold = true; // !! Always check with KLauncher for the first request.
+ slaveOnHold = 0;
+ protInfoDict = new ProtocolInfoDict;
+ slaveList = new SlaveList;
+ idleSlaves = new SlaveList;
+ coIdleSlaves = new SlaveList;
+ extraJobData = new ExtraJobData;
+ sessionData = new SessionData;
+ slaveConfig = SlaveConfig::self();
+ connect(&slaveTimer, TQT_SIGNAL(timeout()), TQT_SLOT(startStep()));
+ connect(&coSlaveTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotScheduleCoSlave()));
+ connect(&cleanupTimer, TQT_SIGNAL(timeout()), TQT_SLOT(slotCleanIdleSlaves()));
+ busy = false;
+}
+
+Scheduler::~Scheduler()
+{
+ protInfoDict->setAutoDelete(true);
+ delete protInfoDict; protInfoDict = 0;
+ delete idleSlaves; idleSlaves = 0;
+ delete coIdleSlaves; coIdleSlaves = 0;
+ slaveList->setAutoDelete(true);
+ delete slaveList; slaveList = 0;
+ delete extraJobData; extraJobData = 0;
+ delete sessionData; sessionData = 0;
+ instance = 0;
+}
+
+void
+Scheduler::debug_info()
+{
+}
+
+bool Scheduler::process(const TQCString &fun, const TQByteArray &data, TQCString &replyType, TQByteArray &replyData )
+{
+ if ( fun != "reparseSlaveConfiguration(TQString)" )
+ return DCOPObject::process( fun, data, replyType, replyData );
+
+ slaveConfig = SlaveConfig::self();
+ replyType = "void";
+ TQDataStream stream( data, IO_ReadOnly );
+ TQString proto;
+ stream >> proto;
+
+ kdDebug( 7006 ) << "reparseConfiguration( " << proto << " )" << endl;
+ KProtocolManager::reparseConfiguration();
+ slaveConfig->reset();
+ sessionData->reset();
+ NetRC::self()->reload();
+
+ Slave *slave = slaveList->first();
+ for (; slave; slave = slaveList->next() )
+ if ( slave->slaveProtocol() == proto || proto.isEmpty() )
+ {
+ slave->send( CMD_REPARSECONFIGURATION );
+ slave->resetHost();
+ }
+ return true;
+}
+
+QCStringList Scheduler::functions()
+{
+ QCStringList funcs = DCOPObject::functions();
+ funcs << "void reparseSlaveConfiguration(TQString)";
+ return funcs;
+}
+
+void Scheduler::_doJob(SimpleJob *job) {
+ JobData *jobData = new JobData;
+ jobData->protocol = KProtocolManager::slaveProtocol(job->url(), jobData->proxy);
+// kdDebug(7006) << "Scheduler::_doJob protocol=" << jobData->protocol << endl;
+ if (job->command() == CMD_GET)
+ {
+ jobData->checkOnHold = checkOnHold;
+ checkOnHold = false;
+ }
+ extraJobData->replace(job, jobData);
+ newJobs.append(job);
+ slaveTimer.start(0, true);
+#ifndef NDEBUG
+ if (newJobs.count() > 150)
+ kdDebug() << "WARNING - TDEIO::Scheduler got more than 150 jobs! This shows a misuse in your app (yes, a job is a TQObject)." << endl;
+#endif
+}
+
+void Scheduler::_scheduleJob(SimpleJob *job) {
+ newJobs.removeRef(job);
+ JobData *jobData = extraJobData->find(job);
+ if (!jobData)
+{
+ kdFatal(7006) << "BUG! _ScheduleJob(): No extraJobData for job!" << endl;
+ return;
+}
+ TQString protocol = jobData->protocol;
+// kdDebug(7006) << "Scheduler::_scheduleJob protocol=" << protocol << endl;
+ ProtocolInfo *protInfo = protInfoDict->get(protocol);
+ protInfo->joblist.append(job);
+
+ slaveTimer.start(0, true);
+}
+
+void Scheduler::_cancelJob(SimpleJob *job) {
+// kdDebug(7006) << "Scheduler: canceling job " << job << endl;
+ Slave *slave = job->slave();
+ if ( !slave )
+ {
+ // was not yet running (don't call this on a finished job!)
+ JobData *jobData = extraJobData->find(job);
+ if (!jobData)
+ return; // I said: "Don't call this on a finished job!"
+
+ newJobs.removeRef(job);
+ ProtocolInfo *protInfo = protInfoDict->get(jobData->protocol);
+ protInfo->joblist.removeRef(job);
+
+ // Search all slaves to see if job is in the queue of a coSlave
+ slave = slaveList->first();
+ for(; slave; slave = slaveList->next())
+ {
+ JobList *list = coSlaves.find(slave);
+ if (list && list->removeRef(job))
+ break; // Job was found and removed.
+ // Fall through to kill the slave as well!
+ }
+ if (!slave)
+ {
+ extraJobData->remove(job);
+ return; // Job was not yet running and not in a coSlave queue.
+ }
+ }
+ kdDebug(7006) << "Scheduler: killing slave " << slave->slave_pid() << endl;
+ slave->kill();
+ _jobFinished( job, slave );
+ slotSlaveDied( slave);
+}
+
+void Scheduler::startStep()
+{
+ while(newJobs.count())
+ {
+ (void) startJobDirect();
+ }
+ TQDictIterator<TDEIO::Scheduler::ProtocolInfo> it(*protInfoDict);
+ while(it.current())
+ {
+ if (startJobScheduled(it.current())) return;
+ ++it;
+ }
+}
+
+void Scheduler::setupSlave(TDEIO::Slave *slave, const KURL &url, const TQString &protocol, const TQString &proxy , bool newSlave, const TDEIO::MetaData *config)
+{
+ TQString host = url.host();
+ int port = url.port();
+ TQString user = url.user();
+ TQString passwd = url.pass();
+
+ if ((newSlave) ||
+ (slave->host() != host) ||
+ (slave->port() != port) ||
+ (slave->user() != user) ||
+ (slave->passwd() != passwd))
+ {
+ slaveConfig = SlaveConfig::self();
+
+ MetaData configData = slaveConfig->configData(protocol, host);
+ sessionData->configDataFor( configData, protocol, host );
+
+ configData["UseProxy"] = proxy;
+
+ TQString autoLogin = configData["EnableAutoLogin"].lower();
+ if ( autoLogin == "true" )
+ {
+ NetRC::AutoLogin l;
+ l.login = user;
+ bool usern = (protocol == "ftp");
+ if ( NetRC::self()->lookup( url, l, usern) )
+ {
+ configData["autoLoginUser"] = l.login;
+ configData["autoLoginPass"] = l.password;
+ if ( usern )
+ {
+ TQString macdef;
+ TQMap<TQString, TQStringList>::ConstIterator it = l.macdef.begin();
+ for ( ; it != l.macdef.end(); ++it )
+ macdef += it.key() + '\\' + it.data().join( "\\" ) + '\n';
+ configData["autoLoginMacro"] = macdef;
+ }
+ }
+ }
+ if (config)
+ configData += *config;
+ slave->setConfig(configData);
+ slave->setProtocol(url.protocol());
+ slave->setHost(host, port, user, passwd);
+ }
+}
+
+bool Scheduler::startJobScheduled(ProtocolInfo *protInfo)
+{
+ if (protInfo->joblist.isEmpty())
+ return false;
+
+// kdDebug(7006) << "Scheduling job" << endl;
+ debug_info();
+ bool newSlave = false;
+
+ SimpleJob *job = 0;
+ Slave *slave = 0;
+
+ if (protInfo->skipCount > 2)
+ {
+ bool dummy;
+ // Prevent starvation. We skip the first entry in the queue at most
+ // 2 times in a row. The
+ protInfo->skipCount = 0;
+ job = protInfo->joblist.at(0);
+ slave = findIdleSlave(protInfo, job, dummy );
+ }
+ else
+ {
+ bool exact=false;
+ SimpleJob *firstJob = 0;
+ Slave *firstSlave = 0;
+ for(uint i = 0; (i < protInfo->joblist.count()) && (i < 10); i++)
+ {
+ job = protInfo->joblist.at(i);
+ slave = findIdleSlave(protInfo, job, exact);
+ if (!firstSlave)
+ {
+ firstJob = job;
+ firstSlave = slave;
+ }
+ if (!slave) break;
+ if (exact) break;
+ }
+
+ if (!exact)
+ {
+ slave = firstSlave;
+ job = firstJob;
+ }
+ if (job == firstJob)
+ protInfo->skipCount = 0;
+ else
+ protInfo->skipCount++;
+ }
+
+ if (!slave)
+ {
+ if ( protInfo->maxSlaves > static_cast<int>(protInfo->activeSlaves.count()) )
+ {
+ newSlave = true;
+ slave = createSlave(protInfo, job, job->url());
+ if (!slave)
+ slaveTimer.start(0, true);
+ }
+ }
+
+ if (!slave)
+ {
+// kdDebug(7006) << "No slaves available" << endl;
+// kdDebug(7006) << " -- active: " << protInfo->activeSlaves.count() << endl;
+ return false;
+ }
+
+ protInfo->activeSlaves.append(slave);
+ idleSlaves->removeRef(slave);
+ protInfo->joblist.removeRef(job);
+// kdDebug(7006) << "scheduler: job started " << job << endl;
+
+
+ JobData *jobData = extraJobData->find(job);
+ setupSlave(slave, job->url(), jobData->protocol, jobData->proxy, newSlave);
+ job->start(slave);
+
+ slaveTimer.start(0, true);
+ return true;
+}
+
+bool Scheduler::startJobDirect()
+{
+ debug_info();
+ SimpleJob *job = newJobs.take(0);
+ JobData *jobData = extraJobData->find(job);
+ if (!jobData)
+ {
+ kdFatal(7006) << "BUG! startjobDirect(): No extraJobData for job!"
+ << endl;
+ return false;
+ }
+ TQString protocol = jobData->protocol;
+ ProtocolInfo *protInfo = protInfoDict->get(protocol);
+
+ bool newSlave = false;
+ bool dummy;
+
+ // Look for matching slave
+ Slave *slave = findIdleSlave(protInfo, job, dummy);
+
+ if (!slave)
+ {
+ newSlave = true;
+ slave = createSlave(protInfo, job, job->url());
+ }
+
+ if (!slave)
+ return false;
+
+ idleSlaves->removeRef(slave);
+// kdDebug(7006) << "scheduler: job started " << job << endl;
+
+ setupSlave(slave, job->url(), protocol, jobData->proxy, newSlave);
+ job->start(slave);
+ return true;
+}
+
+static Slave *searchIdleList(SlaveList *idleSlaves, const KURL &url, const TQString &protocol, bool &exact)
+{
+ TQString host = url.host();
+ int port = url.port();
+ TQString user = url.user();
+ exact = true;
+
+ for( Slave *slave = idleSlaves->first();
+ slave;
+ slave = idleSlaves->next())
+ {
+ if ((protocol == slave->slaveProtocol()) &&
+ (host == slave->host()) &&
+ (port == slave->port()) &&
+ (user == slave->user()))
+ return slave;
+ }
+
+ exact = false;
+
+ // Look for slightly matching slave
+ for( Slave *slave = idleSlaves->first();
+ slave;
+ slave = idleSlaves->next())
+ {
+ if (protocol == slave->slaveProtocol())
+ return slave;
+ }
+ return 0;
+}
+
+Slave *Scheduler::findIdleSlave(ProtocolInfo *, SimpleJob *job, bool &exact)
+{
+ Slave *slave = 0;
+ JobData *jobData = extraJobData->find(job);
+ if (!jobData)
+ {
+ kdFatal(7006) << "BUG! findIdleSlave(): No extraJobData for job!" << endl;
+ return 0;
+ }
+ if (jobData->checkOnHold)
+ {
+ slave = Slave::holdSlave(jobData->protocol, job->url());
+ if (slave)
+ return slave;
+ }
+ if (slaveOnHold)
+ {
+ // Make sure that the job wants to do a GET or a POST, and with no offset
+ bool bCanReuse = (job->command() == CMD_GET);
+ TDEIO::TransferJob * tJob = dynamic_cast<TDEIO::TransferJob *>(job);
+ if ( tJob )
+ {
+ bCanReuse = (job->command() == CMD_GET || job->command() == CMD_SPECIAL);
+ if ( bCanReuse )
+ {
+ TDEIO::MetaData outgoing = tJob->outgoingMetaData();
+ TQString resume = (!outgoing.contains("resume")) ? TQString() : outgoing["resume"];
+ kdDebug(7006) << "Resume metadata is '" << resume << "'" << endl;
+ bCanReuse = (resume.isEmpty() || resume == "0");
+ }
+ }
+// kdDebug(7006) << "bCanReuse = " << bCanReuse << endl;
+ if (bCanReuse)
+ {
+ if (job->url() == urlOnHold)
+ {
+ kdDebug(7006) << "HOLD: Reusing held slave for " << urlOnHold.prettyURL() << endl;
+ slave = slaveOnHold;
+ }
+ else
+ {
+ kdDebug(7006) << "HOLD: Discarding held slave (" << urlOnHold.prettyURL() << ")" << endl;
+ slaveOnHold->kill();
+ }
+ slaveOnHold = 0;
+ urlOnHold = KURL();
+ }
+ if (slave)
+ return slave;
+ }
+
+ return searchIdleList(idleSlaves, job->url(), jobData->protocol, exact);
+}
+
+Slave *Scheduler::createSlave(ProtocolInfo *protInfo, SimpleJob *job, const KURL &url)
+{
+ int error;
+ TQString errortext;
+ Slave *slave = Slave::createSlave(protInfo->protocol, url, error, errortext);
+ if (slave)
+ {
+ slaveList->append(slave);
+ idleSlaves->append(slave);
+ connect(slave, TQT_SIGNAL(slaveDied(TDEIO::Slave *)),
+ TQT_SLOT(slotSlaveDied(TDEIO::Slave *)));
+ connect(slave, TQT_SIGNAL(slaveStatus(pid_t,const TQCString &,const TQString &, bool)),
+ TQT_SLOT(slotSlaveStatus(pid_t,const TQCString &, const TQString &, bool)));
+
+ connect(slave,TQT_SIGNAL(authorizationKey(const TQCString&, const TQCString&, bool)),
+ sessionData,TQT_SLOT(slotAuthData(const TQCString&, const TQCString&, bool)));
+ connect(slave,TQT_SIGNAL(delAuthorization(const TQCString&)), sessionData,
+ TQT_SLOT(slotDelAuthData(const TQCString&)));
+ }
+ else
+ {
+ kdError() <<": couldn't create slave : " << errortext << endl;
+ if (job)
+ {
+ protInfo->joblist.removeRef(job);
+ extraJobData->remove(job);
+ job->slotError( error, errortext );
+ }
+ }
+ return slave;
+}
+
+void Scheduler::slotSlaveStatus(pid_t, const TQCString &, const TQString &, bool)
+{
+}
+
+void Scheduler::_jobFinished(SimpleJob *job, Slave *slave)
+{
+ JobData *jobData = extraJobData->take(job);
+ if (!jobData)
+ {
+ kdFatal(7006) << "BUG! _jobFinished(): No extraJobData for job!" << endl;
+ return;
+ }
+ ProtocolInfo *protInfo = protInfoDict->get(jobData->protocol);
+ delete jobData;
+ slave->disconnect(job);
+ protInfo->activeSlaves.removeRef(slave);
+ if (slave->isAlive())
+ {
+ JobList *list = coSlaves.find(slave);
+ if (list)
+ {
+ assert(slave->isConnected());
+ assert(!coIdleSlaves->contains(slave));
+ coIdleSlaves->append(slave);
+ if (!list->isEmpty())
+ coSlaveTimer.start(0, true);
+ return;
+ }
+ else
+ {
+ assert(!slave->isConnected());
+ idleSlaves->append(slave);
+ slave->setIdle();
+ _scheduleCleanup();
+// slave->send( CMD_SLAVE_STATUS );
+ }
+ }
+ if (protInfo->joblist.count())
+ {
+ slaveTimer.start(0, true);
+ }
+}
+
+void Scheduler::slotSlaveDied(TDEIO::Slave *slave)
+{
+ assert(!slave->isAlive());
+ ProtocolInfo *protInfo = protInfoDict->get(slave->slaveProtocol());
+ protInfo->activeSlaves.removeRef(slave);
+ if (slave == slaveOnHold)
+ {
+ slaveOnHold = 0;
+ urlOnHold = KURL();
+ }
+ idleSlaves->removeRef(slave);
+ JobList *list = coSlaves.find(slave);
+ if (list)
+ {
+ // coSlave dies, kill jobs waiting in queue
+ disconnectSlave(slave);
+ }
+
+ if (!slaveList->removeRef(slave))
+ kdDebug(7006) << "Scheduler: BUG!! Slave " << slave << "/" << slave->slave_pid() << " died, but is NOT in slaveList!!!\n" << endl;
+ else
+ slave->deref(); // Delete slave
+}
+
+void Scheduler::slotCleanIdleSlaves()
+{
+ for(Slave *slave = idleSlaves->first();slave;)
+ {
+ if (slave->idleTime() >= MAX_SLAVE_IDLE)
+ {
+ // kdDebug(7006) << "Removing idle slave: " << slave->slaveProtocol() << " " << slave->host() << endl;
+ Slave *removeSlave = slave;
+ slave = idleSlaves->next();
+ idleSlaves->removeRef(removeSlave);
+ slaveList->removeRef(removeSlave);
+ removeSlave->connection()->close();
+ removeSlave->deref();
+ }
+ else
+ {
+ slave = idleSlaves->next();
+ }
+ }
+ _scheduleCleanup();
+}
+
+void Scheduler::_scheduleCleanup()
+{
+ if (idleSlaves->count())
+ {
+ if (!cleanupTimer.isActive())
+ cleanupTimer.start( MAX_SLAVE_IDLE*1000, true );
+ }
+}
+
+void Scheduler::_putSlaveOnHold(TDEIO::SimpleJob *job, const KURL &url)
+{
+ Slave *slave = job->slave();
+ slave->disconnect(job);
+
+ if (slaveOnHold)
+ {
+ slaveOnHold->kill();
+ }
+ slaveOnHold = slave;
+ urlOnHold = url;
+ slaveOnHold->suspend();
+}
+
+void Scheduler::_publishSlaveOnHold()
+{
+ if (!slaveOnHold)
+ return;
+
+ slaveOnHold->hold(urlOnHold);
+}
+
+void Scheduler::_removeSlaveOnHold()
+{
+ if (slaveOnHold)
+ {
+ slaveOnHold->kill();
+ }
+ slaveOnHold = 0;
+ urlOnHold = KURL();
+}
+
+Slave *
+Scheduler::_getConnectedSlave(const KURL &url, const TDEIO::MetaData &config )
+{
+ TQString proxy;
+ TQString protocol = KProtocolManager::slaveProtocol(url, proxy);
+ bool dummy;
+ Slave *slave = searchIdleList(idleSlaves, url, protocol, dummy);
+ if (!slave)
+ {
+ ProtocolInfo *protInfo = protInfoDict->get(protocol);
+ slave = createSlave(protInfo, 0, url);
+ }
+ if (!slave)
+ return 0; // Error
+ idleSlaves->removeRef(slave);
+
+ setupSlave(slave, url, protocol, proxy, true, &config);
+
+ slave->send( CMD_CONNECT );
+ connect(slave, TQT_SIGNAL(connected()),
+ TQT_SLOT(slotSlaveConnected()));
+ connect(slave, TQT_SIGNAL(error(int, const TQString &)),
+ TQT_SLOT(slotSlaveError(int, const TQString &)));
+
+ coSlaves.insert(slave, new TQPtrList<SimpleJob>());
+// kdDebug(7006) << "_getConnectedSlave( " << slave << ")" << endl;
+ return slave;
+}
+
+void
+Scheduler::slotScheduleCoSlave()
+{
+ Slave *nextSlave;
+ slaveConfig = SlaveConfig::self();
+ for(Slave *slave = coIdleSlaves->first();
+ slave;
+ slave = nextSlave)
+ {
+ nextSlave = coIdleSlaves->next();
+ JobList *list = coSlaves.find(slave);
+ assert(list);
+ if (list && !list->isEmpty())
+ {
+ SimpleJob *job = list->take(0);
+ coIdleSlaves->removeRef(slave);
+// kdDebug(7006) << "scheduler: job started " << job << endl;
+
+ assert(!coIdleSlaves->contains(slave));
+
+ KURL url =job->url();
+ TQString host = url.host();
+ int port = url.port();
+
+ if (slave->host() == "<reset>")
+ {
+ TQString user = url.user();
+ TQString passwd = url.pass();
+
+ MetaData configData = slaveConfig->configData(url.protocol(), url.host());
+ slave->setConfig(configData);
+ slave->setProtocol(url.protocol());
+ slave->setHost(host, port, user, passwd);
+ }
+
+ assert(slave->protocol() == url.protocol());
+ assert(slave->host() == host);
+ assert(slave->port() == port);
+ job->start(slave);
+ }
+ }
+}
+
+void
+Scheduler::slotSlaveConnected()
+{
+ Slave *slave = (Slave *)sender();
+// kdDebug(7006) << "slotSlaveConnected( " << slave << ")" << endl;
+ slave->setConnected(true);
+ disconnect(slave, TQT_SIGNAL(connected()),
+ this, TQT_SLOT(slotSlaveConnected()));
+ emit slaveConnected(slave);
+ assert(!coIdleSlaves->contains(slave));
+ coIdleSlaves->append(slave);
+ coSlaveTimer.start(0, true);
+}
+
+void
+Scheduler::slotSlaveError(int errorNr, const TQString &errorMsg)
+{
+ Slave *slave = (Slave *)sender();
+ if (!slave->isConnected() || (coIdleSlaves->find(slave) != -1))
+ {
+ // Only forward to application if slave is idle or still connecting.
+ emit slaveError(slave, errorNr, errorMsg);
+ }
+}
+
+bool
+Scheduler::_assignJobToSlave(TDEIO::Slave *slave, SimpleJob *job)
+{
+// kdDebug(7006) << "_assignJobToSlave( " << job << ", " << slave << ")" << endl;
+ TQString dummy;
+ if ((slave->slaveProtocol() != KProtocolManager::slaveProtocol( job->url(), dummy ))
+ ||
+ (!newJobs.removeRef(job)))
+ {
+ kdDebug(7006) << "_assignJobToSlave(): ERROR, nonmatching or unknown job." << endl;
+ job->kill();
+ return false;
+ }
+
+ JobList *list = coSlaves.find(slave);
+ assert(list);
+ if (!list)
+ {
+ kdDebug(7006) << "_assignJobToSlave(): ERROR, unknown slave." << endl;
+ job->kill();
+ return false;
+ }
+
+ assert(list->contains(job) == 0);
+ list->append(job);
+ coSlaveTimer.start(0, true); // Start job on timer event
+
+ return true;
+}
+
+bool
+Scheduler::_disconnectSlave(TDEIO::Slave *slave)
+{
+// kdDebug(7006) << "_disconnectSlave( " << slave << ")" << endl;
+ JobList *list = coSlaves.take(slave);
+ assert(list);
+ if (!list)
+ return false;
+ // Kill jobs still in queue.
+ while(!list->isEmpty())
+ {
+ Job *job = list->take(0);
+ job->kill();
+ }
+ delete list;
+ coIdleSlaves->removeRef(slave);
+ assert(!coIdleSlaves->contains(slave));
+ disconnect(slave, TQT_SIGNAL(connected()),
+ this, TQT_SLOT(slotSlaveConnected()));
+ disconnect(slave, TQT_SIGNAL(error(int, const TQString &)),
+ this, TQT_SLOT(slotSlaveError(int, const TQString &)));
+ if (slave->isAlive())
+ {
+ idleSlaves->append(slave);
+ slave->send( CMD_DISCONNECT );
+ slave->setIdle();
+ slave->setConnected(false);
+ _scheduleCleanup();
+ }
+ return true;
+}
+
+void
+Scheduler::_checkSlaveOnHold(bool b)
+{
+ checkOnHold = b;
+}
+
+void
+Scheduler::_registerWindow(TQWidget *wid)
+{
+ if (!wid)
+ return;
+
+ TQObject *obj = TQT_TQOBJECT(wid);
+ if (!m_windowList.contains(obj))
+ {
+ // We must store the window Id because by the time
+ // the destroyed signal is emitted we can no longer
+ // access TQWidget::winId() (already destructed)
+ WId windowId = wid->winId();
+ m_windowList.insert(obj, windowId);
+ connect(TQT_TQOBJECT(wid), TQT_SIGNAL(destroyed(TQObject *)),
+ this, TQT_SLOT(slotUnregisterWindow(TQObject*)));
+ TQByteArray params;
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << windowId;
+ if( !kapp->dcopClient()->send( "kded", "kded",
+ "registerWindowId(long int)", params ) )
+ kdDebug(7006) << "Could not register window with kded!" << endl;
+ }
+}
+
+void
+Scheduler::slotUnregisterWindow(TQObject *obj)
+{
+ if (!obj)
+ return;
+
+ TQMap<TQObject *, WId>::Iterator it = m_windowList.find(obj);
+ if (it == m_windowList.end())
+ return;
+ WId windowId = it.data();
+ disconnect( it.key(), TQT_SIGNAL(destroyed(TQObject *)),
+ this, TQT_SLOT(slotUnregisterWindow(TQObject*)));
+ m_windowList.remove( it );
+ if (kapp)
+ {
+ TQByteArray params;
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << windowId;
+ kapp->dcopClient()->send( "kded", "kded",
+ "unregisterWindowId(long int)", params );
+ }
+}
+
+Scheduler* Scheduler::self() {
+ if ( !instance ) {
+ instance = new Scheduler;
+ }
+ return instance;
+}
+
+void Scheduler::virtual_hook( int id, void* data )
+{ DCOPObject::virtual_hook( id, data ); }
+
+
+
+#include "scheduler.moc"
diff --git a/tdeio/tdeio/scheduler.h b/tdeio/tdeio/scheduler.h
new file mode 100644
index 000000000..e55b2293c
--- /dev/null
+++ b/tdeio/tdeio/scheduler.h
@@ -0,0 +1,364 @@
+// -*- c++ -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
+ Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _kio_scheduler_h
+#define _kio_scheduler_h
+
+#include "tdeio/job.h"
+#include "tdeio/jobclasses.h"
+#include <tqtimer.h>
+#include <tqptrdict.h>
+#include <tqmap.h>
+
+#include <dcopobject.h>
+
+namespace TDEIO {
+
+ class Slave;
+ class SlaveList;
+ class SlaveConfig;
+ class SessionData;
+
+ /**
+ * The TDEIO::Scheduler manages io-slaves for the application.
+ * It also queues jobs and assigns the job to a slave when one
+ * becomes available.
+ *
+ * There are 3 possible ways for a job to get a slave:
+ *
+ * <h3>1. Direct</h3>
+ * This is the default. When you create a job the
+ * TDEIO::Scheduler will be notified and will find either an existing
+ * slave that is idle or it will create a new slave for the job.
+ *
+ * Example:
+ * \code
+ * TransferJob *job = TDEIO::get(KURL("http://www.kde.org"));
+ * \endcode
+ *
+ *
+ * <h3>2. Scheduled</h3>
+ * If you create a lot of jobs, you might want not want to have a
+ * slave for each job. If you schedule a job, a maximum number
+ * of slaves will be created. When more jobs arrive, they will be
+ * queued. When a slave is finished with a job, it will be assigned
+ * a job from the queue.
+ *
+ * Example:
+ * \code
+ * TransferJob *job = TDEIO::get(KURL("http://www.kde.org"));
+ * TDEIO::Scheduler::scheduleJob(job);
+ * \endcode
+ *
+ * <h3>3. Connection Oriented</h3>
+ * For some operations it is important that multiple jobs use
+ * the same connection. This can only be ensured if all these jobs
+ * use the same slave.
+ *
+ * You can ask the scheduler to open a slave for connection oriented
+ * operations. You can then use the scheduler to assign jobs to this
+ * slave. The jobs will be queued and the slave will handle these jobs
+ * one after the other.
+ *
+ * Example:
+ * \code
+ * Slave *slave = TDEIO::Scheduler::getConnectedSlave(
+ * KURL("pop3://bastian:password@mail.kde.org"));
+ * TransferJob *job1 = TDEIO::get(
+ * KURL("pop3://bastian:password@mail.kde.org/msg1"));
+ * TDEIO::Scheduler::assignJobToSlave(slave, job1);
+ * TransferJob *job2 = TDEIO::get(
+ * KURL("pop3://bastian:password@mail.kde.org/msg2"));
+ * TDEIO::Scheduler::assignJobToSlave(slave, job2);
+ * TransferJob *job3 = TDEIO::get(
+ * KURL("pop3://bastian:password@mail.kde.org/msg3"));
+ * TDEIO::Scheduler::assignJobToSlave(slave, job3);
+ *
+ * // ... Wait for jobs to finish...
+ *
+ * TDEIO::Scheduler::disconnectSlave(slave);
+ * \endcode
+ *
+ * Note that you need to explicitly disconnect the slave when the
+ * connection goes down, so your error handler should contain:
+ * \code
+ * if (error == TDEIO::ERR_CONNECTION_BROKEN)
+ * TDEIO::Scheduler::disconnectSlave(slave);
+ * \endcode
+ *
+ * @see TDEIO::Slave
+ * @see TDEIO::Job
+ **/
+
+ class TDEIO_EXPORT Scheduler : public TQObject, virtual public DCOPObject {
+ Q_OBJECT
+
+ public:
+ typedef TQPtrList<SimpleJob> JobList;
+
+ // InfoDict needs Info, so we can't declare it private
+ class ProtocolInfo;
+ class JobData;
+
+ ~Scheduler();
+
+ /**
+ * Register @p job with the scheduler.
+ * The default is to create a new slave for the job if no slave
+ * is available. This can be changed by calling scheduleJob.
+ * @param job the job to register
+ */
+ static void doJob(SimpleJob *job)
+ { self()->_doJob(job); }
+
+ /**
+ * Calling ths function makes that @p job gets scheduled for later
+ * execution, if multiple jobs are registered it might wait for
+ * other jobs to finish.
+ * @param job the job to schedule
+ */
+ static void scheduleJob(SimpleJob *job)
+ { self()->_scheduleJob(job); }
+
+ /**
+ * Stop the execution of a job.
+ * @param job the job to cancel
+ */
+ static void cancelJob(SimpleJob *job)
+ { self()->_cancelJob(job); }
+
+ /**
+ * Called when a job is done.
+ * @param job the finished job
+ * @param slave the slave that executed the @p job
+ */
+ static void jobFinished(TDEIO::SimpleJob *job, TDEIO::Slave *slave)
+ { self()->_jobFinished(job, slave); }
+
+ /**
+ * Puts a slave on notice. A next job may reuse this slave if it
+ * requests the same URL.
+ *
+ * A job can be put on hold after it has emit'ed its mimetype.
+ * Based on the mimetype, the program can give control to another
+ * component in the same process which can then resume the job
+ * by simply asking for the same URL again.
+ * @param job the job that should be stopped
+ * @param url the URL that is handled by the @p url
+ */
+ static void putSlaveOnHold(TDEIO::SimpleJob *job, const KURL &url)
+ { self()->_putSlaveOnHold(job, url); }
+
+ /**
+ * Removes any slave that might have been put on hold. If a slave
+ * was put on hold it will be killed.
+ */
+ static void removeSlaveOnHold()
+ { self()->_removeSlaveOnHold(); }
+
+ /**
+ * Send the slave that was put on hold back to KLauncher. This
+ * allows another process to take over the slave and resume the job
+ * that was started.
+ */
+ static void publishSlaveOnHold()
+ { self()->_publishSlaveOnHold(); }
+
+ /**
+ * Requests a slave for use in connection-oriented mode.
+ *
+ * @param url This defines the username,password,host & port to
+ * connect with.
+ * @param config Configuration data for the slave.
+ *
+ * @return A pointer to a connected slave or 0 if an error occurred.
+ * @see assignJobToSlave()
+ * @see disconnectSlave()
+ */
+ static TDEIO::Slave *getConnectedSlave(const KURL &url, const TDEIO::MetaData &config = MetaData() )
+ { return self()->_getConnectedSlave(url, config); }
+
+ /*
+ * Uses @p slave to do @p job.
+ * This function should be called immediately after creating a Job.
+ *
+ * @param slave The slave to use. The slave must have been obtained
+ * with a call to getConnectedSlave and must not
+ * be currently assigned to any other job.
+ * @param job The job to do.
+ *
+ * @return true is successful, false otherwise.
+ *
+ * @see getConnectedSlave()
+ * @see disconnectSlave()
+ * @see slaveConnected()
+ * @see slaveError()
+ */
+ static bool assignJobToSlave(TDEIO::Slave *slave, TDEIO::SimpleJob *job)
+ { return self()->_assignJobToSlave(slave, job); }
+
+ /*
+ * Disconnects @p slave.
+ *
+ * @param slave The slave to disconnect. The slave must have been
+ * obtained with a call to getConnectedSlave
+ * and must not be assigned to any job.
+ *
+ * @return true is successful, false otherwise.
+ *
+ * @see getConnectedSlave
+ * @see assignJobToSlave
+ */
+ static bool disconnectSlave(TDEIO::Slave *slave)
+ { return self()->_disconnectSlave(slave); }
+
+ /**
+ * Send the slave that was put on hold back to KLauncher. This
+ * allows another process to take over the slave and resume the job
+ * the that was started.
+ * Register the mainwindow @p wid with the KIO subsystem
+ * Do not call this, it is called automatically from
+ * void TDEIO::Job::setWindow(TQWidget*).
+ * @param wid the window to register
+ * @since 3.1
+ */
+ static void registerWindow(TQWidget *wid)
+ { self()->_registerWindow(wid); }
+
+ /**
+ * @internal
+ * Unregisters the window registered by registerWindow().
+ */
+ static void unregisterWindow(TQObject *wid)
+ { self()->slotUnregisterWindow(wid); }
+
+ /**
+ * Function to connect signals emitted by the scheduler.
+ *
+ * @see slaveConnected()
+ * @see slaveError()
+ */
+ static bool connect( const char *signal, const TQObject *receiver,
+ const char *member)
+ { return TQObject::connect(self(), signal, receiver, member); }
+
+ static bool connect( const TQObject* sender, const char* signal,
+ const TQObject* receiver, const char* member )
+ { return TQObject::connect(sender, signal, receiver, member); }
+
+ static bool disconnect( const TQObject* sender, const char* signal,
+ const TQObject* receiver, const char* member )
+ { return TQObject::disconnect(sender, signal, receiver, member); }
+
+ bool connect( const TQObject *sender, const char *signal,
+ const char *member )
+ { return TQObject::connect(sender, signal, member); }
+
+ /**
+ * When true, the next job will check whether KLauncher has a slave
+ * on hold that is suitable for the job.
+ * @param b true when KLauncher has a job on hold
+ */
+ static void checkSlaveOnHold(bool b) { self()->_checkSlaveOnHold(b); }
+
+ void debug_info();
+
+ virtual bool process(const TQCString &fun, const TQByteArray &data,
+ TQCString& replyType, TQByteArray &replyData);
+
+ virtual QCStringList functions();
+
+ public slots:
+ void slotSlaveDied(TDEIO::Slave *slave);
+ void slotSlaveStatus(pid_t pid, const TQCString &protocol,
+ const TQString &host, bool connected);
+ signals:
+ void slaveConnected(TDEIO::Slave *slave);
+ void slaveError(TDEIO::Slave *slave, int error, const TQString &errorMsg);
+
+ protected:
+ void setupSlave(TDEIO::Slave *slave, const KURL &url, const TQString &protocol, const TQString &proxy , bool newSlave, const TDEIO::MetaData *config=0);
+ bool startJobScheduled(ProtocolInfo *protInfo);
+ bool startJobDirect();
+ Scheduler();
+
+ protected slots:
+ void startStep();
+ void slotCleanIdleSlaves();
+ void slotSlaveConnected();
+ void slotSlaveError(int error, const TQString &errorMsg);
+ void slotScheduleCoSlave();
+ /// @since 3.1
+ void slotUnregisterWindow(TQObject *);
+
+ private:
+ class ProtocolInfoDict;
+ class ExtraJobData;
+
+ Scheduler(const Scheduler&);
+ static Scheduler *self();
+ static Scheduler *instance;
+ void _doJob(SimpleJob *job);
+ void _scheduleJob(SimpleJob *job);
+ void _cancelJob(SimpleJob *job);
+ void _jobFinished(TDEIO::SimpleJob *job, TDEIO::Slave *slave);
+ void _scheduleCleanup();
+ void _putSlaveOnHold(TDEIO::SimpleJob *job, const KURL &url);
+ void _removeSlaveOnHold();
+ Slave *_getConnectedSlave(const KURL &url, const TDEIO::MetaData &metaData );
+ bool _assignJobToSlave(TDEIO::Slave *slave, TDEIO::SimpleJob *job);
+ bool _disconnectSlave(TDEIO::Slave *slave);
+ void _checkSlaveOnHold(bool b);
+ void _publishSlaveOnHold();
+ void _registerWindow(TQWidget *wid);
+
+ Slave *findIdleSlave(ProtocolInfo *protInfo, SimpleJob *job, bool &exact);
+ Slave *createSlave(ProtocolInfo *protInfo, SimpleJob *job, const KURL &url);
+
+
+ TQTimer slaveTimer;
+ TQTimer coSlaveTimer;
+ TQTimer cleanupTimer;
+ bool busy;
+
+ SlaveList *slaveList;
+ SlaveList *idleSlaves;
+ SlaveList *coIdleSlaves;
+
+ ProtocolInfoDict *protInfoDict;
+ Slave *slaveOnHold;
+ KURL urlOnHold;
+ JobList newJobs;
+
+ TQPtrDict<JobList> coSlaves;
+ ExtraJobData *extraJobData;
+ SlaveConfig *slaveConfig;
+ SessionData *sessionData;
+ bool checkOnHold;
+ TQMap<TQObject *,WId> m_windowList;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ private:
+ class SchedulerPrivate* d;
+};
+
+}
+#endif
diff --git a/tdeio/tdeio/sessiondata.cpp b/tdeio/tdeio/sessiondata.cpp
new file mode 100644
index 000000000..99c6a26f3
--- /dev/null
+++ b/tdeio/tdeio/sessiondata.cpp
@@ -0,0 +1,311 @@
+/* This file is part of the KDE project
+ Copyright (C) 2000 Dawit Alemayehu <adawit@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License (LGPL) as published by the Free Software Foundation;
+ either version 2 of the License, or (at your option) any
+ later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; see the file COPYING.LIB. If not,
+ write to the Free Software Foundation, Inc., 51 Franklin Street,
+ Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#include <tqptrlist.h>
+#include <tqtextcodec.h>
+
+#include <kdebug.h>
+#include <tdeconfig.h>
+#include <kglobal.h>
+#include <klocale.h>
+#include <kcharsets.h>
+#include <dcopclient.h>
+#include <kprotocolmanager.h>
+#include <kstandarddirs.h>
+
+#include <tdesu/client.h>
+#include <tdeio/slaveconfig.h>
+#include <tdeio/http_slave_defaults.h>
+
+#include "sessiondata.h"
+#include "sessiondata.moc"
+
+namespace TDEIO {
+
+/***************************** SessionData::AuthData ************************/
+struct SessionData::AuthData
+{
+
+public:
+ AuthData() {}
+
+ AuthData(const TQCString& k, const TQCString& g, bool p) {
+ key = k;
+ group = g;
+ persist = p;
+ }
+
+ bool isKeyMatch( const TQCString& val ) const {
+ return (val==key);
+ }
+
+ bool isGroupMatch( const TQCString& val ) const {
+ return (val==group);
+ }
+
+ TQCString key;
+ TQCString group;
+ bool persist;
+};
+
+/************************* SessionData::AuthDataList ****************************/
+class SessionData::AuthDataList : public TQPtrList<SessionData::AuthData>
+{
+public:
+ AuthDataList();
+ ~AuthDataList();
+
+ void addData( SessionData::AuthData* );
+ void removeData( const TQCString& );
+
+ bool pingCacheDaemon();
+ void registerAuthData( SessionData::AuthData* );
+ void unregisterAuthData( SessionData::AuthData* );
+ void purgeCachedData();
+
+private:
+#ifdef Q_OS_UNIX
+ KDEsuClient * m_tdesuClient;
+#endif
+};
+
+SessionData::AuthDataList::AuthDataList()
+{
+#ifdef Q_OS_UNIX
+ m_tdesuClient = new KDEsuClient;
+#endif
+ setAutoDelete(true);
+}
+
+SessionData::AuthDataList::~AuthDataList()
+{
+ purgeCachedData();
+#ifdef Q_OS_UNIX
+ delete m_tdesuClient;
+ m_tdesuClient = 0;
+#endif
+}
+
+void SessionData::AuthDataList::addData( SessionData::AuthData* d )
+{
+ TQPtrListIterator<SessionData::AuthData> it ( *this );
+ for ( ; it.current(); ++it )
+ {
+ if ( it.current()->isKeyMatch( d->key ) )
+ return;
+ }
+ registerAuthData( d );
+ append( d );
+}
+
+void SessionData::AuthDataList::removeData( const TQCString& gkey )
+{
+ TQPtrListIterator<SessionData::AuthData> it( *this );
+ for( ; it.current(); ++it )
+ {
+ if ( it.current()->isGroupMatch(gkey) && pingCacheDaemon() )
+ {
+ unregisterAuthData( it.current() );
+ remove( it.current() );
+ }
+ }
+}
+
+bool SessionData::AuthDataList::pingCacheDaemon()
+{
+#ifdef Q_OS_UNIX
+ Q_ASSERT(m_tdesuClient);
+
+ int success = m_tdesuClient->ping();
+ if( success == -1 )
+ {
+ success = m_tdesuClient->startServer();
+ if( success == -1 )
+ return false;
+ }
+ return true;
+#else
+ return false;
+#endif
+}
+
+void SessionData::AuthDataList::registerAuthData( SessionData::AuthData* d )
+{
+ if( !pingCacheDaemon() )
+ return;
+
+#ifdef Q_OS_UNIX
+ bool ok;
+ TQCString ref_key = d->key + "-refcount";
+ int count = m_tdesuClient->getVar(ref_key).toInt( &ok );
+ if( ok )
+ {
+ TQCString val;
+ val.setNum( count+1 );
+ m_tdesuClient->setVar( ref_key, val, 0, d->group );
+ }
+ else
+ m_tdesuClient->setVar( ref_key, "1", 0, d->group );
+#endif
+}
+
+void SessionData::AuthDataList::unregisterAuthData( SessionData::AuthData* d )
+{
+ if ( !d || d->persist )
+ return;
+
+ bool ok;
+ int count;
+ TQCString ref_key = d->key + "-refcount";
+
+#ifdef Q_OS_UNIX
+ count = m_tdesuClient->getVar( ref_key ).toInt( &ok );
+ if ( ok )
+ {
+ if ( count > 1 )
+ {
+ TQCString val;
+ val.setNum(count-1);
+ m_tdesuClient->setVar( ref_key, val, 0, d->group );
+ }
+ else
+ {
+ m_tdesuClient->delVars(d->key);
+ }
+ }
+#endif
+}
+
+void SessionData::AuthDataList::purgeCachedData()
+{
+ if ( !isEmpty() && pingCacheDaemon() )
+ {
+ TQPtrListIterator<SessionData::AuthData> it( *this );
+ for ( ; it.current(); ++it )
+ unregisterAuthData( it.current() );
+ }
+}
+
+/********************************* SessionData ****************************/
+
+class SessionData::SessionDataPrivate
+{
+public:
+ SessionDataPrivate() {
+ useCookie = true;
+ initDone = false;
+ }
+
+ bool initDone;
+ bool useCookie;
+ TQString charsets;
+ TQString language;
+};
+
+SessionData::SessionData()
+{
+ authData = 0;
+ d = new SessionDataPrivate;
+}
+
+SessionData::~SessionData()
+{
+ delete d;
+ delete authData;
+ d = 0L;
+ authData = 0L;
+}
+
+void SessionData::configDataFor( MetaData &configData, const TQString &proto,
+ const TQString & )
+{
+ if ( (proto.find("http", 0, false) == 0 ) ||
+ (proto.find("webdav", 0, false) == 0) )
+ {
+ if (!d->initDone)
+ reset();
+
+ // These might have already been set so check first
+ // to make sure that we do not trumpt settings sent
+ // by apps or end-user.
+ if ( configData["Cookies"].isEmpty() )
+ configData["Cookies"] = d->useCookie ? "true" : "false";
+ if ( configData["Languages"].isEmpty() )
+ configData["Languages"] = d->language;
+ if ( configData["Charsets"].isEmpty() )
+ configData["Charsets"] = d->charsets;
+ if ( configData["CacheDir"].isEmpty() )
+ configData["CacheDir"] = TDEGlobal::dirs()->saveLocation("cache", "http");
+ if ( configData["UserAgent"].isEmpty() )
+ {
+ configData["UserAgent"] = KProtocolManager::defaultUserAgent();
+ }
+ }
+}
+
+void SessionData::reset()
+{
+ d->initDone = true;
+ // Get Cookie settings...
+ TDEConfig* cfg = new TDEConfig("kcookiejarrc", true, false);
+ cfg->setGroup( "Cookie Policy" );
+ d->useCookie = cfg->readBoolEntry( "Cookies", true );
+ delete cfg;
+
+ static const TQString & english = TDEGlobal::staticQString( "en" );
+
+ // Get language settings...
+ TQStringList languageList = TDEGlobal::locale()->languagesTwoAlpha();
+ TQStringList::Iterator it = languageList.find( TQString::fromLatin1("C") );
+ if ( it != languageList.end() )
+ {
+ if ( languageList.contains( english ) > 0 )
+ languageList.remove( it );
+ else
+ (*it) = english;
+ }
+ if ( !languageList.contains( english ) )
+ languageList.append( english );
+
+ d->language = languageList.join( ", " );
+
+ d->charsets = TQString::fromLatin1(TQTextCodec::codecForLocale()->mimeName()).lower();
+ KProtocolManager::reparseConfiguration();
+}
+
+void SessionData::slotAuthData( const TQCString& key, const TQCString& gkey,
+ bool keep )
+{
+ if (!authData)
+ authData = new AuthDataList;
+ authData->addData( new SessionData::AuthData(key, gkey, keep) );
+}
+
+void SessionData::slotDelAuthData( const TQCString& gkey )
+{
+ if (!authData)
+ return;
+ authData->removeData( gkey );
+}
+
+void SessionData::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+}
diff --git a/tdeio/tdeio/sessiondata.h b/tdeio/tdeio/sessiondata.h
new file mode 100644
index 000000000..a87e63dba
--- /dev/null
+++ b/tdeio/tdeio/sessiondata.h
@@ -0,0 +1,67 @@
+/* This file is part of the KDE project
+ Copyright (C) 2000 Dawit Alemayehu <adawit@kde.org
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License (LGPL) as published by the Free Software Foundation;
+ either version 2 of the License, or (at your option) any
+ later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; see the file COPYING.LIB. If not,
+ write to the Free Software Foundation, Inc., 51 Franklin Street,
+ Fifth Floor, Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __KIO_SESSIONDATA_H
+#define __KIO_SESSIONDATA_H
+
+#include <tqobject.h>
+#include <tdeio/global.h>
+
+namespace TDEIO {
+
+class SlaveConfig;
+
+
+/**
+ * @internal
+ */
+class TDEIO_EXPORT SessionData : public TQObject
+{
+ Q_OBJECT
+
+public:
+ SessionData();
+ ~SessionData();
+
+ virtual void configDataFor( TDEIO::MetaData &configData, const TQString &proto,
+ const TQString &host );
+ virtual void reset();
+
+ /// @since 3.1
+ struct AuthData;
+public slots:
+ void slotAuthData( const TQCString&, const TQCString&, bool );
+ void slotDelAuthData( const TQCString& );
+
+private:
+ class AuthDataList;
+ friend class AuthDataList;
+ AuthDataList* authData;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class SessionDataPrivate;
+ SessionDataPrivate* d;
+};
+
+} // namespace
+
+#endif
diff --git a/tdeio/tdeio/skipdlg.cpp b/tdeio/tdeio/skipdlg.cpp
new file mode 100644
index 000000000..eab245dfc
--- /dev/null
+++ b/tdeio/tdeio/skipdlg.cpp
@@ -0,0 +1,143 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdeio/skipdlg.h"
+
+#include <stdio.h>
+#include <assert.h>
+
+#include <tqmessagebox.h>
+#include <tqwidget.h>
+#include <tqlayout.h>
+#include <tqlabel.h>
+
+#include <kapplication.h>
+#include <klocale.h>
+#include <kurl.h>
+#include <kpushbutton.h>
+#include <kstdguiitem.h>
+
+#ifdef Q_WS_X11
+#include <twin.h>
+#endif
+
+using namespace TDEIO;
+
+SkipDlg::SkipDlg(TQWidget *parent, bool _multi, const TQString& _error_text, bool _modal ) :
+ KDialog ( parent, "" , _modal )
+{
+ // TODO : port to KDialogBase
+ modal = _modal;
+
+ // Set "StaysOnTop", because this dialog is typically used in tdeio_uiserver,
+ // i.e. in a separate process.
+#ifdef Q_WS_X11 //FIXME(E): Implement for QT Embedded, mac & win32
+ if (modal)
+ KWin::setState( winId(), NET::StaysOnTop );
+#endif
+
+ b0 = b1 = b2 = 0L;
+
+ setCaption( i18n( "Information" ) );
+
+ b0 = new KPushButton( KStdGuiItem::cancel(), this );
+ connect(b0, TQT_SIGNAL(clicked()), this, TQT_SLOT(b0Pressed()));
+
+ if ( _multi )
+ {
+ b1 = new TQPushButton( i18n( "Skip" ), this );
+ connect(b1, TQT_SIGNAL(clicked()), this, TQT_SLOT(b1Pressed()));
+
+ b2 = new TQPushButton( i18n( "Auto Skip" ), this );
+ connect(b2, TQT_SIGNAL(clicked()), this, TQT_SLOT(b2Pressed()));
+ }
+
+ TQVBoxLayout *vlayout = new TQVBoxLayout( this, 10, 0 );
+ // vlayout->addStrut( 360 ); makes dlg at least that wide
+
+ TQLabel * lb = new TQLabel( _error_text, this );
+ lb->setFixedHeight( lb->sizeHint().height() );
+ lb->setMinimumWidth( lb->sizeHint().width() );
+ vlayout->addWidget( lb );
+
+ vlayout->addSpacing( 10 );
+
+ TQHBoxLayout* layout = new TQHBoxLayout();
+ vlayout->addLayout( layout );
+ if ( b0 )
+ {
+ b0->setDefault( true );
+ b0->setFixedSize( b0->sizeHint() );
+ layout->addWidget( b0 );
+ layout->addSpacing( 5 );
+ }
+ if ( b1 )
+ {
+ b1->setFixedSize( b1->sizeHint() );
+ layout->addWidget( b1 );
+ layout->addSpacing( 5 );
+ }
+ if ( b2 )
+ {
+ b2->setFixedSize( b2->sizeHint() );
+ layout->addWidget( b2 );
+ layout->addSpacing( 5 );
+ }
+
+ vlayout->addStretch( 10 );
+ vlayout->activate();
+ resize( sizeHint() );
+}
+
+SkipDlg::~SkipDlg()
+{
+}
+
+void SkipDlg::b0Pressed()
+{
+ if ( modal )
+ done( 0 );
+ else
+ emit result( this, 0 );
+}
+
+void SkipDlg::b1Pressed()
+{
+ if ( modal )
+ done( 1 );
+ else
+ emit result( this, 1 );
+}
+
+void SkipDlg::b2Pressed()
+{
+ if ( modal )
+ done( 2 );
+ else
+ emit result( this, 2 );
+}
+
+SkipDlg_Result TDEIO::open_SkipDlg( bool _multi, const TQString& _error_text )
+{
+ Q_ASSERT(kapp);
+
+ SkipDlg dlg( 0L, _multi, _error_text, true );
+ return (SkipDlg_Result) dlg.exec();
+}
+
+#include "skipdlg.moc"
diff --git a/kio/kio/skipdlg.h b/tdeio/tdeio/skipdlg.h
index 56252dace..56252dace 100644
--- a/kio/kio/skipdlg.h
+++ b/tdeio/tdeio/skipdlg.h
diff --git a/tdeio/tdeio/slave.cpp b/tdeio/tdeio/slave.cpp
new file mode 100644
index 000000000..dfd6d6bb3
--- /dev/null
+++ b/tdeio/tdeio/slave.cpp
@@ -0,0 +1,519 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (c) 2000 Waldo Bastian <bastian@kde.org>
+ * 2000 Stephan Kulow <coolo@kde.org>
+ *
+ * $Id$
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#include <config.h>
+
+#include <time.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <signal.h>
+#include <sys/types.h>
+
+#include <tqfile.h>
+#include <tqtimer.h>
+
+#include <dcopclient.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kglobal.h>
+#include <kstandarddirs.h>
+#include <kapplication.h>
+#include <ktempfile.h>
+#include <ksock.h>
+#include <kprocess.h>
+#include <klibloader.h>
+
+#include "tdeio/dataprotocol.h"
+#include "tdeio/slave.h"
+#include "tdeio/kservice.h"
+#include <tdeio/global.h>
+#include <kprotocolmanager.h>
+#include <kprotocolinfo.h>
+
+#ifdef HAVE_PATHS_H
+#include <paths.h>
+#endif
+
+#ifndef _PATH_TMP
+#define _PATH_TMP "/tmp"
+#endif
+
+using namespace TDEIO;
+
+#define SLAVE_CONNECTION_TIMEOUT_MIN 2
+
+// Without debug info we consider it an error if the slave doesn't connect
+// within 10 seconds.
+// With debug info we give the slave an hour so that developers have a chance
+// to debug their slave.
+#ifdef NDEBUG
+#define SLAVE_CONNECTION_TIMEOUT_MAX 10
+#else
+#define SLAVE_CONNECTION_TIMEOUT_MAX 3600
+#endif
+
+namespace TDEIO {
+
+ /**
+ * @internal
+ */
+ class SlavePrivate {
+ public:
+ bool derived; // true if this instance of Slave is actually an
+ // instance of a derived class.
+
+ SlavePrivate(bool derived) : derived(derived) {}
+ };
+}
+
+void Slave::accept(TDESocket *socket)
+{
+#ifndef Q_WS_WIN
+ slaveconn.init(socket);
+#endif
+ delete serv;
+ serv = 0;
+ slaveconn.connect(this, TQT_SLOT(gotInput()));
+ unlinkSocket();
+}
+
+void Slave::unlinkSocket()
+{
+ if (m_socket.isEmpty()) return;
+ TQCString filename = TQFile::encodeName(m_socket);
+ unlink(filename.data());
+ m_socket = TQString::null;
+}
+
+void Slave::timeout()
+{
+ if (!serv) return;
+ kdDebug(7002) << "slave failed to connect to application pid=" << m_pid << " protocol=" << m_protocol << endl;
+ if (m_pid && (::kill(m_pid, 0) == 0))
+ {
+ int delta_t = (int) difftime(time(0), contact_started);
+ kdDebug(7002) << "slave is slow... pid=" << m_pid << " t=" << delta_t << endl;
+ if (delta_t < SLAVE_CONNECTION_TIMEOUT_MAX)
+ {
+ TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, this, TQT_SLOT(timeout()));
+ return;
+ }
+ }
+ kdDebug(7002) << "Houston, we lost our slave, pid=" << m_pid << endl;
+ delete serv;
+ serv = 0;
+ unlinkSocket();
+ dead = true;
+ TQString arg = m_protocol;
+ if (!m_host.isEmpty())
+ arg += "://"+m_host;
+ kdDebug(7002) << "slave died pid = " << m_pid << endl;
+ ref();
+ // Tell the job about the problem.
+ emit error(ERR_SLAVE_DIED, arg);
+ // Tell the scheduler about the problem.
+ emit slaveDied(this);
+ // After the above signal we're dead!!
+ deref();
+}
+
+Slave::Slave(TDEServerSocket *socket, const TQString &protocol, const TQString &socketname)
+ : SlaveInterface(&slaveconn), serv(socket), contacted(false),
+ d(new SlavePrivate(false))
+{
+ m_refCount = 1;
+ m_protocol = protocol;
+ m_slaveProtocol = protocol;
+ m_socket = socketname;
+ dead = false;
+ contact_started = time(0);
+ idle_since = contact_started;
+ m_pid = 0;
+ m_port = 0;
+#ifndef Q_WS_WIN
+ connect(serv, TQT_SIGNAL(accepted( TDESocket* )),
+ TQT_SLOT(accept(TDESocket*) ) );
+#endif
+}
+
+Slave::Slave(bool /*derived*/, TDEServerSocket *socket, const TQString &protocol,
+ const TQString &socketname)
+ : SlaveInterface(&slaveconn), serv(socket), contacted(false),
+ d(new SlavePrivate(true))
+{
+ // FIXME: hmm, duplicating code here from public ctor, no good (LS)
+ m_refCount = 1;
+ m_protocol = protocol;
+ m_slaveProtocol = protocol;
+ m_socket = socketname;
+ dead = false;
+ contact_started = time(0);
+ idle_since = contact_started;
+ m_pid = 0;
+ m_port = 0;
+ if (serv != 0) {
+#ifndef Q_WS_WIN
+ connect(serv, TQT_SIGNAL(accepted( TDESocket* )),
+ TQT_SLOT(accept(TDESocket*) ) );
+#endif
+ }
+}
+
+Slave::~Slave()
+{
+ // kdDebug(7002) << "destructing slave object pid = " << m_pid << endl;
+ if (serv != 0) {
+ delete serv;
+ serv = 0;
+ }
+ unlinkSocket();
+ m_pid = 99999;
+ delete d;
+ d = 0;
+}
+
+void Slave::setProtocol(const TQString & protocol)
+{
+ m_protocol = protocol;
+}
+
+void Slave::setIdle()
+{
+ idle_since = time(0);
+}
+
+time_t Slave::idleTime()
+{
+ return (time_t) difftime(time(0), idle_since);
+}
+
+void Slave::setPID(pid_t pid)
+{
+ m_pid = pid;
+}
+
+void Slave::hold(const KURL &url)
+{
+ if (d->derived) { // TODO: clean up before KDE 4
+ HoldParams params;
+ params.url = &url;
+ virtual_hook(VIRTUAL_HOLD, &params);
+ return;
+ }/*end if*/
+
+ ref();
+ {
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly );
+ stream << url;
+ slaveconn.send( CMD_SLAVE_HOLD, data );
+ slaveconn.close();
+ dead = true;
+ emit slaveDied(this);
+ }
+ deref();
+ // Call KLauncher::waitForSlave(pid);
+ {
+ DCOPClient *client = kapp->dcopClient();
+ if (!client->isAttached())
+ client->attach();
+
+ TQByteArray params, reply;
+ TQCString replyType;
+ TQDataStream stream(params, IO_WriteOnly);
+ pid_t pid = m_pid;
+ stream << pid;
+
+ TQCString launcher = TDEApplication::launcher();
+ client->call(launcher, launcher, "waitForSlave(pid_t)",
+ params, replyType, reply);
+ }
+}
+
+void Slave::suspend()
+{
+ if (d->derived) { // TODO: clean up before KDE 4
+ virtual_hook(VIRTUAL_SUSPEND, 0);
+ return;
+ }/*end if*/
+
+ slaveconn.suspend();
+}
+
+void Slave::resume()
+{
+ if (d->derived) { // TODO: clean up before KDE 4
+ virtual_hook(VIRTUAL_RESUME, 0);
+ return;
+ }/*end if*/
+
+ slaveconn.resume();
+}
+
+bool Slave::suspended()
+{
+ if (d->derived) { // TODO: clean up before KDE 4
+ SuspendedParams params;
+ virtual_hook(VIRTUAL_SUSPENDED, &params);
+ return params.retval;
+ }/*end if*/
+
+ return slaveconn.suspended();
+}
+
+void Slave::send(int cmd, const TQByteArray &arr) {
+ if (d->derived) { // TODO: clean up before KDE 4
+ SendParams params;
+ params.cmd = cmd;
+ params.arr = &arr;
+ virtual_hook(VIRTUAL_SEND, &params);
+ return;
+ }/*end if*/
+
+ slaveconn.send(cmd, arr);
+}
+
+void Slave::gotInput()
+{
+ ref();
+ if (!dispatch())
+ {
+ slaveconn.close();
+ dead = true;
+ TQString arg = m_protocol;
+ if (!m_host.isEmpty())
+ arg += "://"+m_host;
+ kdDebug(7002) << "slave died pid = " << m_pid << endl;
+ // Tell the job about the problem.
+ emit error(ERR_SLAVE_DIED, arg);
+ // Tell the scheduler about the problem.
+ emit slaveDied(this);
+ }
+ deref();
+ // Here we might be dead!!
+}
+
+void Slave::kill()
+{
+ dead = true; // OO can be such simple.
+ kdDebug(7002) << "killing slave pid=" << m_pid << " (" << m_protocol << "://"
+ << m_host << ")" << endl;
+ if (m_pid)
+ {
+ ::kill(m_pid, SIGTERM);
+ }
+}
+
+void Slave::setHost( const TQString &host, int port,
+ const TQString &user, const TQString &passwd)
+{
+ m_host = host;
+ m_port = port;
+ m_user = user;
+ m_passwd = passwd;
+
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly );
+ stream << m_host << m_port << m_user << m_passwd;
+ slaveconn.send( CMD_HOST, data );
+}
+
+void Slave::resetHost()
+{
+ m_host = "<reset>";
+}
+
+void Slave::setConfig(const MetaData &config)
+{
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly );
+ stream << config;
+ slaveconn.send( CMD_CONFIG, data );
+}
+
+Slave* Slave::createSlave( const TQString &protocol, const KURL& url, int& error, TQString& error_text )
+{
+ //kdDebug(7002) << "createSlave '" << protocol << "' for " << url.prettyURL() << endl;
+ // Firstly take into account all special slaves
+ if (protocol == "data")
+ return new DataProtocol();
+
+ DCOPClient *client = kapp->dcopClient();
+ if (!client->isAttached())
+ client->attach();
+
+ TQString prefix = locateLocal("socket", TDEGlobal::instance()->instanceName());
+ KTempFile socketfile(prefix, TQString::fromLatin1(".slave-socket"));
+ if ( socketfile.status() != 0 )
+ {
+ error_text = i18n("Unable to create io-slave: %1").arg(strerror(errno));
+ error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
+ return 0;
+ }
+
+#ifdef __CYGWIN__
+ socketfile.close();
+#endif
+
+#ifndef Q_WS_WIN
+ TDEServerSocket *kss = new TDEServerSocket(TQFile::encodeName(socketfile.name()).data());
+
+ Slave *slave = new Slave(kss, protocol, socketfile.name());
+#else
+ Slave *slave = 0;
+#endif
+
+ // WABA: if the dcopserver is running under another uid we don't ask
+ // tdelauncher for a slave, because the slave might have that other uid
+ // as well, which might either be a) undesired or b) make it impossible
+ // for the slave to connect to the application.
+ // In such case we start the slave via TDEProcess.
+ // It's possible to force this by setting the env. variable
+ // TDE_FORK_SLAVES, Clearcase seems to require this.
+ static bool bForkSlaves = !TQCString(getenv("TDE_FORK_SLAVES")).isEmpty();
+
+ if (bForkSlaves || !client->isAttached() || client->isAttachedToForeignServer())
+ {
+ TQString _name = KProtocolInfo::exec(protocol);
+ if (_name.isEmpty())
+ {
+ error_text = i18n("Unknown protocol '%1'.").arg(protocol);
+ error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
+ delete slave;
+ return 0;
+ }
+ TQString lib_path = KLibLoader::findLibrary(_name.latin1());
+ if (lib_path.isEmpty())
+ {
+ error_text = i18n("Can not find io-slave for protocol '%1'.").arg(protocol);
+ error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
+ return 0;
+ }
+
+ TDEProcess proc;
+
+ proc << locate("exe", "tdeioslave") << lib_path << protocol << "" << socketfile.name();
+ kdDebug(7002) << "tdeioslave" << ", " << lib_path << ", " << protocol << ", " << TQString::null << ", " << socketfile.name() << endl;
+
+ proc.start(TDEProcess::DontCare);
+
+#ifndef Q_WS_WIN
+ slave->setPID(proc.pid());
+ TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, slave, TQT_SLOT(timeout()));
+#endif
+ return slave;
+ }
+
+
+ TQByteArray params, reply;
+ TQCString replyType;
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << protocol << url.host() << socketfile.name();
+
+ TQCString launcher = TDEApplication::launcher();
+ if (!client->call(launcher, launcher, "requestSlave(TQString,TQString,TQString)",
+ params, replyType, reply)) {
+ error_text = i18n("Cannot talk to tdelauncher");
+ error = TDEIO::ERR_SLAVE_DEFINED;
+ delete slave;
+ return 0;
+ }
+ TQDataStream stream2(reply, IO_ReadOnly);
+ TQString errorStr;
+ pid_t pid;
+ stream2 >> pid >> errorStr;
+ if (!pid)
+ {
+ error_text = i18n("Unable to create io-slave:\ntdelauncher said: %1").arg(errorStr);
+ error = TDEIO::ERR_CANNOT_LAUNCH_PROCESS;
+ delete slave;
+ return 0;
+ }
+#ifndef Q_WS_WIN
+ slave->setPID(pid);
+ TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, slave, TQT_SLOT(timeout()));
+#endif
+ return slave;
+}
+
+Slave* Slave::holdSlave( const TQString &protocol, const KURL& url )
+{
+ //kdDebug(7002) << "holdSlave '" << protocol << "' for " << url.prettyURL() << endl;
+ // Firstly take into account all special slaves
+ if (protocol == "data")
+ return 0;
+
+ DCOPClient *client = kapp->dcopClient();
+ if (!client->isAttached())
+ client->attach();
+
+ TQString prefix = locateLocal("socket", TDEGlobal::instance()->instanceName());
+ KTempFile socketfile(prefix, TQString::fromLatin1(".slave-socket"));
+ if ( socketfile.status() != 0 )
+ return 0;
+
+#ifdef __CYGWIN__
+ socketfile.close();
+ socketfile.unlink();
+#endif
+
+#ifndef Q_WS_WIN
+ TDEServerSocket *kss = new TDEServerSocket(TQFile::encodeName(socketfile.name()).data());
+
+ Slave *slave = new Slave(kss, protocol, socketfile.name());
+#else
+ Slave *slave = 0;
+#endif
+
+ TQByteArray params, reply;
+ TQCString replyType;
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << url << socketfile.name();
+
+ TQCString launcher = TDEApplication::launcher();
+ if (!client->call(launcher, launcher, "requestHoldSlave(KURL,TQString)",
+ params, replyType, reply)) {
+ delete slave;
+ return 0;
+ }
+ TQDataStream stream2(reply, IO_ReadOnly);
+ pid_t pid;
+ stream2 >> pid;
+ if (!pid)
+ {
+ delete slave;
+ return 0;
+ }
+#ifndef Q_WS_WIN
+ slave->setPID(pid);
+ TQTimer::singleShot(1000*SLAVE_CONNECTION_TIMEOUT_MIN, slave, TQT_SLOT(timeout()));
+#endif
+ return slave;
+}
+
+void Slave::virtual_hook( int id, void* data ) {
+ TDEIO::SlaveInterface::virtual_hook( id, data );
+}
+
+#include "slave.moc"
diff --git a/tdeio/tdeio/slave.h b/tdeio/tdeio/slave.h
new file mode 100644
index 000000000..80ae30d3a
--- /dev/null
+++ b/tdeio/tdeio/slave.h
@@ -0,0 +1,270 @@
+// -*- c++ -*-
+/*
+ * This file is part of the KDE libraries
+ * Copyright (c) 2000 Waldo Bastian <bastian@kde.org>
+ * 2000 Stephan Kulow <coolo@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#ifndef KIO_SLAVE_H
+#define KIO_SLAVE_H
+
+#include <time.h>
+#include <unistd.h>
+
+#include <tqobject.h>
+
+#include <kurl.h>
+
+#include "tdeio/slaveinterface.h"
+#include "tdeio/connection.h"
+
+class TDEServerSocket;
+class TDESocket;
+
+namespace TDEIO {
+
+ /** Attention developers: If you change the implementation of TDEIO::Slave,
+ * do *not* use connection() or slaveconn but the respective TDEIO::Slave
+ * accessor methods. Otherwise classes derived from Slave might break. (LS)
+ */
+ class TDEIO_EXPORT Slave : public TDEIO::SlaveInterface
+ {
+ Q_OBJECT
+
+
+ protected:
+ /**
+ * Use this constructor if you derive your own class from Slave
+ * @p derived must be true in any case
+ * @internal
+ * @since 3.2
+ */
+ Slave(bool derived, TDEServerSocket *unixdomain, const TQString &protocol,
+ const TQString &socketname); // TODO(BIC): Remove in KDE 4
+
+ public:
+ Slave(TDEServerSocket *unixdomain,
+ const TQString &protocol, const TQString &socketname);
+
+ virtual ~Slave();
+
+ void setPID(pid_t);
+
+ int slave_pid() { return m_pid; }
+
+ /**
+ * Force termination
+ */
+ void kill();
+
+ /**
+ * @return true if the slave survived the last mission.
+ */
+ bool isAlive() { return !dead; }
+
+ /**
+ * Set host for url
+ * @param host to connect to.
+ * @param port to connect to.
+ * @param user to login as
+ * @param passwd to login with
+ */
+ void setHost( const TQString &host, int port,
+ const TQString &user, const TQString &passwd); // TODO(BIC): make virtual
+
+ /**
+ * Clear host info.
+ */
+ void resetHost();
+
+ /**
+ * Configure slave
+ */
+ void setConfig(const MetaData &config); // TODO(BIC): make virtual
+
+ /**
+ * The protocol this slave handles.
+ *
+ * @return name of protocol handled by this slave, as seen by the user
+ */
+ TQString protocol() { return m_protocol; }
+
+ void setProtocol(const TQString & protocol);
+ /**
+ * The actual protocol used to handle the request.
+ *
+ * This method will return a different protocol than
+ * the one obtained by using protocol() if a
+ * proxy-server is used for the given protocol. This
+ * usually means that this method will return "http"
+ * when the actuall request was to retrieve a resource
+ * from an "ftp" server by going through a proxy server.
+ *
+ * @return the actual protocol (io-slave) that handled the request
+ */
+ TQString slaveProtocol() { return m_slaveProtocol; }
+
+ /**
+ * @return Host this slave is (was?) connected to
+ */
+ TQString host() { return m_host; }
+
+ /**
+ * @return port this slave is (was?) connected to
+ */
+ int port() { return m_port; }
+
+ /**
+ * @return User this slave is (was?) logged in as
+ */
+ TQString user() { return m_user; }
+
+ /**
+ * @return Passwd used to log in
+ */
+ TQString passwd() { return m_passwd; }
+
+ /**
+ * Creates a new slave.
+ *
+ * @param protocol protocol the slave is for.
+ * @param url URL the slave should operate on.
+ * @param error is the error code on failure and undefined else.
+ * @param error_text is the error text on failure and undefined else.
+ *
+ * @return 0 on failure, or a pointer to a slave otherwise.
+ * @todo What are legal @p protocol values?
+ */
+ static Slave* createSlave( const TQString &protocol, const KURL& url, int& error, TQString& error_text );
+
+ static Slave* holdSlave( const TQString &protocol, const KURL& url );
+
+ // == communication with connected tdeioslave ==
+ // whenever possible prefer these methods over the respective
+ // methods in connection()
+ /**
+ * Suspends the operation of the attached tdeioslave.
+ */
+ void suspend(); // TODO(BIC): make virtual
+ /**
+ * Resumes the operation of the attached tdeioslave.
+ */
+ void resume(); // TODO(BIC): make virtual
+ /**
+ * Tells wether the tdeioslave is suspended.
+ * @return true if the tdeioslave is suspended.
+ * @since 3.2
+ */
+ bool suspended(); // TODO(BIC): make virtual
+ /**
+ * Sends the given command to the tdeioslave.
+ * @param cmd command id
+ * @param data byte array containing data
+ * @since 3.2
+ */
+ void send(int cmd, const TQByteArray &data = TQByteArray());// TODO(BIC): make virtual
+ // == end communication with connected tdeioslave ==
+
+ /**
+ * Puts the tdeioslave associated with @p url at halt.
+ */
+ void hold(const KURL &url); // TODO(BIC): make virtual
+
+ /**
+ * @return The time this slave has been idle.
+ */
+ time_t idleTime();
+
+ /**
+ * Marks this slave as idle.
+ */
+ void setIdle();
+
+ /*
+ * @returns Whether the slave is connected
+ * (Connection oriented slaves only)
+ */
+ bool isConnected() { return contacted; }
+ void setConnected(bool c) { contacted = c; }
+
+ /** @deprecated This method is obsolete, use the accessor methods
+ * within TDEIO::Slave instead. Old code directly accessing connection()
+ * will not be able to access special protocols.
+ */
+ KDE_DEPRECATED Connection *connection() { return &slaveconn; } // TODO(BIC): remove before KDE 4
+
+ void ref() { m_refCount++; }
+ void deref() { m_refCount--; if (!m_refCount) delete this; }
+
+ public slots:
+ void accept(TDESocket *socket);
+ void gotInput();
+ void timeout();
+ signals:
+ void slaveDied(TDEIO::Slave *slave);
+
+ protected:
+ void unlinkSocket();
+
+ private:
+ TQString m_protocol;
+ TQString m_slaveProtocol;
+ TQString m_host;
+ int m_port;
+ TQString m_user;
+ TQString m_passwd;
+ TDEServerSocket *serv;
+ TQString m_socket;
+ pid_t m_pid;
+ bool contacted;
+ bool dead;
+ time_t contact_started;
+ time_t idle_since;
+ TDEIO::Connection slaveconn;
+ int m_refCount;
+ protected:
+ virtual void virtual_hook( int id, void* data );
+ // grant SlaveInterface all IDs < 0x200
+ enum { VIRTUAL_SUSPEND = 0x200, VIRTUAL_RESUME, VIRTUAL_SEND,
+ VIRTUAL_HOLD, VIRTUAL_SUSPENDED,
+ VIRTUAL_SET_HOST, VIRTUAL_SET_CONFIG };
+ struct SendParams {
+ int cmd;
+ const TQByteArray *arr;
+ };
+ struct HoldParams {
+ const KURL *url;
+ };
+ struct SuspendedParams {
+ bool retval;
+ };
+ struct SetHostParams {
+ const TQString *host;
+ int port;
+ const TQString *user;
+ const TQString *passwd;
+ };
+ struct SetConfigParams {
+ const MetaData *config;
+ };
+ private:
+ class SlavePrivate* d;
+ };
+
+}
+
+#endif
diff --git a/tdeio/tdeio/slavebase.cpp b/tdeio/tdeio/slavebase.cpp
new file mode 100644
index 000000000..e979f530b
--- /dev/null
+++ b/tdeio/tdeio/slavebase.cpp
@@ -0,0 +1,1315 @@
+/*
+ *
+ * This file is part of the KDE libraries
+ * Copyright (c) 2000 Waldo Bastian <bastian@kde.org>
+ * Copyright (c) 2000 David Faure <faure@kde.org>
+ * Copyright (c) 2000 Stephan Kulow <coolo@kde.org>
+ *
+ * $Id$
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ **/
+
+#include "slavebase.h"
+
+#include <config.h>
+
+#include <sys/time.h>
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h> // Needed on some systems.
+#endif
+
+#include <assert.h>
+#include <kdebug.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <unistd.h>
+#include <signal.h>
+#include <time.h>
+
+#include <tqfile.h>
+
+#include <dcopclient.h>
+
+#include <kapplication.h>
+#include <ksock.h>
+#include <kcrash.h>
+#include <tdesu/client.h>
+#include <klocale.h>
+#include <ksocks.h>
+
+#include "kremoteencoding.h"
+
+#include "tdeio/slavebase.h"
+#include "tdeio/connection.h"
+#include "tdeio/ioslave_defaults.h"
+#include "tdeio/slaveinterface.h"
+
+#include "uiserver_stub.h"
+
+#ifndef NDEBUG
+#ifdef HAVE_BACKTRACE
+#include <execinfo.h>
+#endif
+#endif
+
+using namespace TDEIO;
+
+template class TQPtrList<TQValueList<UDSAtom> >;
+typedef TQValueList<TQCString> AuthKeysList;
+typedef TQMap<TQString,TQCString> AuthKeysMap;
+#define KIO_DATA TQByteArray data; TQDataStream stream( data, IO_WriteOnly ); stream
+#define KIO_FILESIZE_T(x) (unsigned long)(x & 0xffffffff) << (unsigned long)(x >> 32)
+
+namespace TDEIO {
+
+class SlaveBaseConfig : public TDEConfigBase
+{
+public:
+ SlaveBaseConfig(SlaveBase *_slave)
+ : slave(_slave) { }
+
+ bool internalHasGroup(const TQCString &) const { tqWarning("hasGroup(const TQCString &)");
+return false; }
+
+ TQStringList groupList() const { return TQStringList(); }
+
+ TQMap<TQString,TQString> entryMap(const TQString &group) const
+ { Q_UNUSED(group); return TQMap<TQString,TQString>(); }
+
+ void reparseConfiguration() { }
+
+ KEntryMap internalEntryMap( const TQString &pGroup) const { Q_UNUSED(pGroup); return KEntryMap(); }
+
+ KEntryMap internalEntryMap() const { return KEntryMap(); }
+
+ void putData(const KEntryKey &_key, const KEntry&_data, bool _checkGroup)
+ { Q_UNUSED(_key); Q_UNUSED(_data); Q_UNUSED(_checkGroup); }
+
+ KEntry lookupData(const KEntryKey &_key) const
+ {
+ KEntry entry;
+ TQString value = slave->metaData(_key.c_key);
+ if (!value.isNull())
+ entry.mValue = value.utf8();
+ return entry;
+ }
+protected:
+ SlaveBase *slave;
+};
+
+
+class SlaveBasePrivate {
+public:
+ TQString slaveid;
+ bool resume:1;
+ bool needSendCanResume:1;
+ bool onHold:1;
+ bool wasKilled:1;
+ MetaData configData;
+ SlaveBaseConfig *config;
+ KURL onHoldUrl;
+
+ struct timeval last_tv;
+ TDEIO::filesize_t totalSize;
+ TDEIO::filesize_t sentListEntries;
+ DCOPClient *dcopClient;
+ KRemoteEncoding *remotefile;
+ time_t timeout;
+ TQByteArray timeoutData;
+};
+
+}
+
+static SlaveBase *globalSlave;
+long SlaveBase::s_seqNr;
+
+static volatile bool slaveWriteError = false;
+
+static const char *s_protocol;
+
+#ifdef Q_OS_UNIX
+static void genericsig_handler(int sigNumber)
+{
+ signal(sigNumber,SIG_IGN);
+ //WABA: Don't do anything that requires malloc, we can deadlock on it since
+ //a SIGTERM signal can come in while we are in malloc/free.
+ //kdDebug()<<"tdeioslave : exiting due to signal "<<sigNumber<<endl;
+ //set the flag which will be checked in dispatchLoop() and which *should* be checked
+ //in lengthy operations in the various slaves
+ if (globalSlave!=0)
+ globalSlave->setKillFlag();
+ signal(SIGALRM,SIG_DFL);
+ alarm(5); //generate an alarm signal in 5 seconds, in this time the slave has to exit
+}
+#endif
+
+//////////////
+
+SlaveBase::SlaveBase( const TQCString &protocol,
+ const TQCString &pool_socket,
+ const TQCString &app_socket )
+ : mProtocol(protocol), m_pConnection(0),
+ mPoolSocket( TQFile::decodeName(pool_socket)),
+ mAppSocket( TQFile::decodeName(app_socket))
+{
+ s_protocol = protocol.data();
+#ifdef Q_OS_UNIX
+ if (!getenv("TDE_DEBUG"))
+ {
+ KCrash::setCrashHandler( sigsegv_handler );
+ signal(SIGILL,&sigsegv_handler);
+ signal(SIGTRAP,&sigsegv_handler);
+ signal(SIGABRT,&sigsegv_handler);
+ signal(SIGBUS,&sigsegv_handler);
+ signal(SIGALRM,&sigsegv_handler);
+ signal(SIGFPE,&sigsegv_handler);
+#ifdef SIGPOLL
+ signal(SIGPOLL, &sigsegv_handler);
+#endif
+#ifdef SIGSYS
+ signal(SIGSYS, &sigsegv_handler);
+#endif
+#ifdef SIGVTALRM
+ signal(SIGVTALRM, &sigsegv_handler);
+#endif
+#ifdef SIGXCPU
+ signal(SIGXCPU, &sigsegv_handler);
+#endif
+#ifdef SIGXFSZ
+ signal(SIGXFSZ, &sigsegv_handler);
+#endif
+ }
+
+ struct sigaction act;
+ act.sa_handler = sigpipe_handler;
+ sigemptyset( &act.sa_mask );
+ act.sa_flags = 0;
+ sigaction( SIGPIPE, &act, 0 );
+
+ signal(SIGINT,&genericsig_handler);
+ signal(SIGQUIT,&genericsig_handler);
+ signal(SIGTERM,&genericsig_handler);
+#endif
+
+ globalSlave=this;
+
+ appconn = new Connection();
+ listEntryCurrentSize = 100;
+ struct timeval tp;
+ gettimeofday(&tp, 0);
+ listEntry_sec = tp.tv_sec;
+ listEntry_usec = tp.tv_usec;
+ mConnectedToApp = true;
+
+ d = new SlaveBasePrivate;
+ // by kahl for netmgr (need a way to identify slaves)
+ d->slaveid = protocol;
+ d->slaveid += TQString::number(getpid());
+ d->resume = false;
+ d->needSendCanResume = false;
+ d->config = new SlaveBaseConfig(this);
+ d->onHold = false;
+ d->wasKilled=false;
+ d->last_tv.tv_sec = 0;
+ d->last_tv.tv_usec = 0;
+// d->processed_size = 0;
+ d->totalSize=0;
+ d->sentListEntries=0;
+ d->timeout = 0;
+ connectSlave(mAppSocket);
+
+ d->dcopClient = 0;
+ d->remotefile = 0;
+}
+
+SlaveBase::~SlaveBase()
+{
+ delete d;
+ s_protocol = "";
+}
+
+DCOPClient *SlaveBase::dcopClient()
+{
+ if (!d->dcopClient)
+ {
+ d->dcopClient = TDEApplication::dcopClient();
+ if (!d->dcopClient->isAttached())
+ d->dcopClient->attach();
+ d->dcopClient->setDaemonMode( true );
+ }
+ return d->dcopClient;
+}
+
+void SlaveBase::dispatchLoop()
+{
+#ifdef Q_OS_UNIX //TODO: WIN32
+ fd_set rfds;
+ int retval;
+
+ while (true)
+ {
+ if (d->timeout && (d->timeout < time(0)))
+ {
+ TQByteArray data = d->timeoutData;
+ d->timeout = 0;
+ d->timeoutData = TQByteArray();
+ special(data);
+ }
+ FD_ZERO(&rfds);
+
+ assert(appconn->inited());
+ int maxfd = appconn->fd_from();
+ FD_SET(appconn->fd_from(), &rfds);
+ if( d->dcopClient )
+ {
+ FD_SET( d->dcopClient->socket(), &rfds );
+ if( d->dcopClient->socket() > maxfd )
+ maxfd = d->dcopClient->socket();
+ }
+
+ if (!d->timeout) // we can wait forever
+ {
+ retval = select( maxfd + 1, &rfds, NULL, NULL, NULL);
+ }
+ else
+ {
+ struct timeval tv;
+ tv.tv_sec = kMax(d->timeout-time(0),(time_t) 1);
+ tv.tv_usec = 0;
+ retval = select( maxfd + 1, &rfds, NULL, NULL, &tv);
+ }
+ if ((retval>0) && FD_ISSET(appconn->fd_from(), &rfds))
+ { // dispatch application messages
+ int cmd;
+ TQByteArray data;
+ if ( appconn->read(&cmd, data) != -1 )
+ {
+ dispatch(cmd, data);
+ }
+ else // some error occurred, perhaps no more application
+ {
+ // When the app exits, should the slave be put back in the pool ?
+ if (mConnectedToApp && !mPoolSocket.isEmpty())
+ {
+ disconnectSlave();
+ mConnectedToApp = false;
+ closeConnection();
+ connectSlave(mPoolSocket);
+ }
+ else
+ {
+ return;
+ }
+ }
+ }
+ if( retval > 0 && d->dcopClient && FD_ISSET( d->dcopClient->socket(), &rfds ))
+ {
+ d->dcopClient->processSocketData( d->dcopClient->socket());
+ }
+ if ((retval<0) && (errno != EINTR))
+ {
+ kdDebug(7019) << "dispatchLoop(): select returned " << retval << " "
+ << (errno==EBADF?"EBADF":errno==EINTR?"EINTR":errno==EINVAL?"EINVAL":errno==ENOMEM?"ENOMEM":"unknown")
+ << " (" << errno << ")" << endl;
+ return;
+ }
+ //I think we get here when we were killed in dispatch() and not in select()
+ if (wasKilled())
+ {
+ kdDebug(7019)<<" dispatchLoop() slave was killed, returning"<<endl;
+ return;
+ }
+ }
+#else
+#error The KIO slave system only works under UNIX
+#endif
+}
+
+void SlaveBase::connectSlave(const TQString& path)
+{
+#ifdef Q_OS_UNIX //TODO: TDESocket not yet available on WIN32
+ appconn->init(new TDESocket(TQFile::encodeName(path).data()));
+ if (!appconn->inited())
+ {
+ kdDebug(7019) << "SlaveBase: failed to connect to " << path << endl;
+ exit();
+ }
+
+ setConnection(appconn);
+#endif
+}
+
+void SlaveBase::disconnectSlave()
+{
+ appconn->close();
+}
+
+void SlaveBase::setMetaData(const TQString &key, const TQString &value)
+{
+ mOutgoingMetaData.replace(key, value);
+}
+
+TQString SlaveBase::metaData(const TQString &key) const
+{
+ if (mIncomingMetaData.contains(key))
+ return mIncomingMetaData[key];
+ if (d->configData.contains(key))
+ return d->configData[key];
+ return TQString::null;
+}
+
+bool SlaveBase::hasMetaData(const TQString &key) const
+{
+ if (mIncomingMetaData.contains(key))
+ return true;
+ if (d->configData.contains(key))
+ return true;
+ return false;
+}
+
+// ### remove the next two methods for KDE4 (they miss the const)
+TQString SlaveBase::metaData(const TQString &key) {
+ return const_cast<const SlaveBase*>(this)->metaData( key );
+}
+bool SlaveBase::hasMetaData(const TQString &key) {
+ return const_cast<const SlaveBase*>(this)->hasMetaData( key );
+}
+
+TDEConfigBase *SlaveBase::config()
+{
+ return d->config;
+}
+
+void SlaveBase::sendMetaData()
+{
+ KIO_DATA << mOutgoingMetaData;
+
+ slaveWriteError = false;
+ m_pConnection->send( INF_META_DATA, data );
+ if (slaveWriteError) exit();
+ mOutgoingMetaData.clear(); // Clear
+}
+
+KRemoteEncoding *SlaveBase::remoteEncoding()
+{
+ if (d->remotefile != 0)
+ return d->remotefile;
+
+ return d->remotefile = new KRemoteEncoding(metaData("Charset").latin1());
+}
+
+void SlaveBase::data( const TQByteArray &data )
+{
+ if (!mOutgoingMetaData.isEmpty())
+ sendMetaData();
+ slaveWriteError = false;
+ m_pConnection->send( MSG_DATA, data );
+ if (slaveWriteError) exit();
+}
+
+void SlaveBase::dataReq( )
+{
+/*
+ if (!mOutgoingMetaData.isEmpty())
+ sendMetaData();
+*/
+ if (d->needSendCanResume)
+ canResume(0);
+ m_pConnection->send( MSG_DATA_REQ );
+}
+
+void SlaveBase::error( int _errid, const TQString &_text )
+{
+ mIncomingMetaData.clear(); // Clear meta data
+ mOutgoingMetaData.clear();
+ KIO_DATA << (TQ_INT32) _errid << _text;
+
+ m_pConnection->send( MSG_ERROR, data );
+ //reset
+ listEntryCurrentSize = 100;
+ d->sentListEntries=0;
+ d->totalSize=0;
+}
+
+void SlaveBase::connected()
+{
+ slaveWriteError = false;
+ m_pConnection->send( MSG_CONNECTED );
+ if (slaveWriteError) exit();
+}
+
+void SlaveBase::finished()
+{
+ mIncomingMetaData.clear(); // Clear meta data
+ if (!mOutgoingMetaData.isEmpty())
+ sendMetaData();
+ m_pConnection->send( MSG_FINISHED );
+
+ // reset
+ listEntryCurrentSize = 100;
+ d->sentListEntries=0;
+ d->totalSize=0;
+}
+
+void SlaveBase::needSubURLData()
+{
+ m_pConnection->send( MSG_NEED_SUBURL_DATA );
+}
+
+void SlaveBase::slaveStatus( const TQString &host, bool connected )
+{
+ pid_t pid = getpid();
+ TQ_INT8 b = connected ? 1 : 0;
+ KIO_DATA << pid << mProtocol << host << b;
+ if (d->onHold)
+ stream << d->onHoldUrl;
+ m_pConnection->send( MSG_SLAVE_STATUS, data );
+}
+
+void SlaveBase::canResume()
+{
+ m_pConnection->send( MSG_CANRESUME );
+}
+
+void SlaveBase::totalSize( TDEIO::filesize_t _bytes )
+{
+ KIO_DATA << KIO_FILESIZE_T(_bytes);
+ slaveWriteError = false;
+ m_pConnection->send( INF_TOTAL_SIZE, data );
+ if (slaveWriteError) exit();
+
+ //this one is usually called before the first item is listed in listDir()
+ struct timeval tp;
+ gettimeofday(&tp, 0);
+ listEntry_sec = tp.tv_sec;
+ listEntry_usec = tp.tv_usec;
+ d->totalSize=_bytes;
+ d->sentListEntries=0;
+}
+
+void SlaveBase::processedSize( TDEIO::filesize_t _bytes )
+{
+ bool emitSignal=false;
+ struct timeval tv;
+ int gettimeofday_res=gettimeofday( &tv, 0L );
+
+ if( _bytes == d->totalSize )
+ emitSignal=true;
+ else if ( gettimeofday_res == 0 ) {
+ time_t msecdiff = 2000;
+ if (d->last_tv.tv_sec) {
+ // Compute difference, in ms
+ msecdiff = 1000 * ( tv.tv_sec - d->last_tv.tv_sec );
+ time_t usecdiff = tv.tv_usec - d->last_tv.tv_usec;
+ if ( usecdiff < 0 ) {
+ msecdiff--;
+ msecdiff += 1000;
+ }
+ msecdiff += usecdiff / 1000;
+ }
+ emitSignal=msecdiff >= 100; // emit size 10 times a second
+ }
+
+ if( emitSignal ) {
+ KIO_DATA << KIO_FILESIZE_T(_bytes);
+ slaveWriteError = false;
+ m_pConnection->send( INF_PROCESSED_SIZE, data );
+ if (slaveWriteError) exit();
+ if ( gettimeofday_res == 0 ) {
+ d->last_tv.tv_sec = tv.tv_sec;
+ d->last_tv.tv_usec = tv.tv_usec;
+ }
+ }
+// d->processed_size = _bytes;
+}
+
+void SlaveBase::processedPercent( float /* percent */ )
+{
+ kdDebug(7019) << "SlaveBase::processedPercent: STUB" << endl;
+}
+
+
+void SlaveBase::speed( unsigned long _bytes_per_second )
+{
+ KIO_DATA << (TQ_UINT32) _bytes_per_second;
+ slaveWriteError = false;
+ m_pConnection->send( INF_SPEED, data );
+ if (slaveWriteError) exit();
+}
+
+void SlaveBase::redirection( const KURL& _url )
+{
+ KIO_DATA << _url;
+ m_pConnection->send( INF_REDIRECTION, data );
+}
+
+void SlaveBase::errorPage()
+{
+ m_pConnection->send( INF_ERROR_PAGE );
+}
+
+static bool isSubCommand(int cmd)
+{
+ return ( (cmd == CMD_REPARSECONFIGURATION) ||
+ (cmd == CMD_META_DATA) ||
+ (cmd == CMD_CONFIG) ||
+ (cmd == CMD_SUBURL) ||
+ (cmd == CMD_SLAVE_STATUS) ||
+ (cmd == CMD_SLAVE_CONNECT) ||
+ (cmd == CMD_SLAVE_HOLD) ||
+ (cmd == CMD_MULTI_GET));
+}
+
+void SlaveBase::mimeType( const TQString &_type)
+{
+ // kdDebug(7019) << "(" << getpid() << ") SlaveBase::mimeType '" << _type << "'" << endl;
+ int cmd;
+ do
+ {
+ // Send the meta-data each time we send the mime-type.
+ if (!mOutgoingMetaData.isEmpty())
+ {
+ // kdDebug(7019) << "(" << getpid() << ") mimeType: emitting meta data" << endl;
+ KIO_DATA << mOutgoingMetaData;
+ m_pConnection->send( INF_META_DATA, data );
+ }
+ KIO_DATA << _type;
+ m_pConnection->send( INF_MIME_TYPE, data );
+ while(true)
+ {
+ cmd = 0;
+ if ( m_pConnection->read( &cmd, data ) == -1 ) {
+ kdDebug(7019) << "SlaveBase: mimetype: read error" << endl;
+ exit();
+ }
+ // kdDebug(7019) << "(" << getpid() << ") Slavebase: mimetype got " << cmd << endl;
+ if ( cmd == CMD_HOST) // Ignore.
+ continue;
+ if ( isSubCommand(cmd) )
+ {
+ dispatch( cmd, data );
+ continue; // Disguised goto
+ }
+ break;
+ }
+ }
+ while (cmd != CMD_NONE);
+ mOutgoingMetaData.clear();
+}
+
+void SlaveBase::exit()
+{
+ this->~SlaveBase();
+ ::exit(255);
+}
+
+void SlaveBase::warning( const TQString &_msg)
+{
+ KIO_DATA << _msg;
+ m_pConnection->send( INF_WARNING, data );
+}
+
+void SlaveBase::infoMessage( const TQString &_msg)
+{
+ KIO_DATA << _msg;
+ m_pConnection->send( INF_INFOMESSAGE, data );
+}
+
+bool SlaveBase::requestNetwork(const TQString& host)
+{
+ KIO_DATA << host << d->slaveid;
+ m_pConnection->send( MSG_NET_REQUEST, data );
+
+ if ( waitForAnswer( INF_NETWORK_STATUS, 0, data ) != -1 )
+ {
+ bool status;
+ TQDataStream stream( data, IO_ReadOnly );
+ stream >> status;
+ return status;
+ } else
+ return false;
+}
+
+void SlaveBase::dropNetwork(const TQString& host)
+{
+ KIO_DATA << host << d->slaveid;
+ m_pConnection->send( MSG_NET_DROP, data );
+}
+
+void SlaveBase::statEntry( const UDSEntry& entry )
+{
+ KIO_DATA << entry;
+ slaveWriteError = false;
+ m_pConnection->send( MSG_STAT_ENTRY, data );
+ if (slaveWriteError) exit();
+}
+
+void SlaveBase::listEntry( const UDSEntry& entry, bool _ready )
+{
+ static struct timeval tp;
+ static const int maximum_updatetime = 300;
+ static const int minimum_updatetime = 100;
+
+ if (!_ready) {
+ pendingListEntries.append(entry);
+
+ if (pendingListEntries.count() > listEntryCurrentSize) {
+ gettimeofday(&tp, 0);
+
+ long diff = ((tp.tv_sec - listEntry_sec) * 1000000 +
+ tp.tv_usec - listEntry_usec) / 1000;
+ if (diff==0) diff=1;
+
+ if (diff > maximum_updatetime) {
+ listEntryCurrentSize = listEntryCurrentSize * 3 / 4;
+ _ready = true;
+ }
+//if we can send all list entries of this dir which have not yet been sent
+//within maximum_updatetime, then make listEntryCurrentSize big enough for all of them
+ else if (((pendingListEntries.count()*maximum_updatetime)/diff) > (d->totalSize-d->sentListEntries))
+ listEntryCurrentSize=d->totalSize-d->sentListEntries+1;
+//if we are below minimum_updatetime, estimate how much we will get within
+//maximum_updatetime
+ else if (diff < minimum_updatetime)
+ listEntryCurrentSize = (pendingListEntries.count() * maximum_updatetime) / diff;
+ else
+ _ready=true;
+ }
+ }
+ if (_ready) { // may happen when we started with !ready
+ listEntries( pendingListEntries );
+ pendingListEntries.clear();
+
+ gettimeofday(&tp, 0);
+ listEntry_sec = tp.tv_sec;
+ listEntry_usec = tp.tv_usec;
+ }
+}
+
+void SlaveBase::listEntries( const UDSEntryList& list )
+{
+ KIO_DATA << (TQ_UINT32)list.count();
+ UDSEntryListConstIterator it = list.begin();
+ UDSEntryListConstIterator end = list.end();
+ for (; it != end; ++it)
+ stream << *it;
+ slaveWriteError = false;
+ m_pConnection->send( MSG_LIST_ENTRIES, data);
+ if (slaveWriteError) exit();
+ d->sentListEntries+=(uint)list.count();
+}
+
+void SlaveBase::sendAuthenticationKey( const TQCString& key,
+ const TQCString& group,
+ bool keepPass )
+{
+ KIO_DATA << key << group << keepPass;
+ m_pConnection->send( MSG_AUTH_KEY, data );
+}
+
+void SlaveBase::delCachedAuthentication( const TQString& key )
+{
+ KIO_DATA << key.utf8() ;
+ m_pConnection->send( MSG_DEL_AUTH_KEY, data );
+}
+
+void SlaveBase::sigsegv_handler(int sig)
+{
+#ifdef Q_OS_UNIX
+ signal(sig,SIG_DFL); // Next one kills
+
+ //Kill us if we deadlock
+ signal(SIGALRM,SIG_DFL);
+ alarm(5); //generate an alarm signal in 5 seconds, in this time the slave has to exit
+
+ // Debug and printf should be avoided because they might
+ // call malloc.. and get in a nice recursive malloc loop
+ char buffer[120];
+ snprintf(buffer, sizeof(buffer), "tdeioslave: ####### CRASH ###### protocol = %s pid = %d signal = %d\n", s_protocol, getpid(), sig);
+ write(2, buffer, strlen(buffer));
+#ifndef NDEBUG
+#ifdef HAVE_BACKTRACE
+ void* trace[256];
+ int n = backtrace(trace, 256);
+ if (n)
+ backtrace_symbols_fd(trace, n, 2);
+#endif
+#endif
+ ::exit(1);
+#endif
+}
+
+void SlaveBase::sigpipe_handler (int)
+{
+ // We ignore a SIGPIPE in slaves.
+ // A SIGPIPE can happen in two cases:
+ // 1) Communication error with application.
+ // 2) Communication error with network.
+ slaveWriteError = true;
+
+ // Don't add anything else here, especially no debug output
+}
+
+void SlaveBase::setHost(TQString const &, int, TQString const &, TQString const &)
+{
+}
+
+void SlaveBase::openConnection(void)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_CONNECT)); }
+void SlaveBase::closeConnection(void)
+{ } // No response!
+void SlaveBase::stat(KURL const &)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_STAT)); }
+void SlaveBase::put(KURL const &, int, bool, bool)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_PUT)); }
+void SlaveBase::special(const TQByteArray &)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_SPECIAL)); }
+void SlaveBase::listDir(KURL const &)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_LISTDIR)); }
+void SlaveBase::get(KURL const & )
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_GET)); }
+void SlaveBase::mimetype(KURL const &url)
+{ get(url); }
+void SlaveBase::rename(KURL const &, KURL const &, bool)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_RENAME)); }
+void SlaveBase::symlink(TQString const &, KURL const &, bool)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_SYMLINK)); }
+void SlaveBase::copy(KURL const &, KURL const &, int, bool)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_COPY)); }
+void SlaveBase::del(KURL const &, bool)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_DEL)); }
+void SlaveBase::mkdir(KURL const &, int)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_MKDIR)); }
+void SlaveBase::chmod(KURL const &, int)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_CHMOD)); }
+void SlaveBase::setSubURL(KURL const &)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_SUBURL)); }
+void SlaveBase::multiGet(const TQByteArray &)
+{ error( ERR_UNSUPPORTED_ACTION, unsupportedActionErrorString(mProtocol, CMD_MULTI_GET)); }
+
+
+void SlaveBase::slave_status()
+{ slaveStatus( TQString::null, false ); }
+
+void SlaveBase::reparseConfiguration()
+{
+}
+
+void SlaveBase::localURL(const KURL& remoteURL)
+{
+ bool local = remoteURL.isLocalFile();
+ TQ_INT8 islocal;
+ KURL retURL;
+ if (local) {
+ islocal = true;
+ retURL = remoteURL;
+ }
+ else {
+ islocal = false;
+ retURL = remoteURL;
+ }
+ KIO_DATA << islocal << retURL;
+ m_pConnection->send( INF_LOCALURL, data );
+}
+
+bool SlaveBase::dispatch()
+{
+ assert( m_pConnection );
+
+ int cmd;
+ TQByteArray data;
+ if ( m_pConnection->read( &cmd, data ) == -1 )
+ {
+ kdDebug(7019) << "SlaveBase::dispatch() has read error." << endl;
+ return false;
+ }
+
+ dispatch( cmd, data );
+ return true;
+}
+
+bool SlaveBase::openPassDlg( AuthInfo& info )
+{
+ return openPassDlg(info, TQString::null);
+}
+
+bool SlaveBase::openPassDlg( AuthInfo& info, const TQString &errorMsg )
+{
+ TQCString replyType;
+ TQByteArray params;
+ TQByteArray reply;
+ AuthInfo authResult;
+ long windowId = metaData("window-id").toLong();
+ long progressId = metaData("progress-id").toLong();
+ unsigned long userTimestamp = metaData("user-timestamp").toULong();
+
+ kdDebug(7019) << "SlaveBase::openPassDlg window-id=" << windowId << " progress-id=" << progressId << endl;
+
+ (void) dcopClient(); // Make sure to have a dcop client.
+
+ UIServer_stub uiserver( "tdeio_uiserver", "UIServer" );
+ if (progressId)
+ uiserver.setJobVisible( progressId, false );
+
+ TQDataStream stream(params, IO_WriteOnly);
+
+ if (metaData("no-auth-prompt").lower() == "true")
+ stream << info << TQString("<NoAuthPrompt>") << windowId << s_seqNr << userTimestamp;
+ else
+ stream << info << errorMsg << windowId << s_seqNr << userTimestamp;
+
+ bool callOK = d->dcopClient->call( "kded", "kpasswdserver", "queryAuthInfo(TDEIO::AuthInfo, TQString, long int, long int, unsigned long int)",
+ params, replyType, reply );
+
+ if (progressId)
+ uiserver.setJobVisible( progressId, true );
+
+ if (!callOK)
+ {
+ kdWarning(7019) << "Can't communicate with kded_kpasswdserver!" << endl;
+ return false;
+ }
+
+ if ( replyType == "TDEIO::AuthInfo" )
+ {
+ TQDataStream stream2( reply, IO_ReadOnly );
+ stream2 >> authResult >> s_seqNr;
+ }
+ else
+ {
+ kdError(7019) << "DCOP function queryAuthInfo(...) returns "
+ << replyType << ", expected TDEIO::AuthInfo" << endl;
+ return false;
+ }
+
+ if (!authResult.isModified())
+ return false;
+
+ info = authResult;
+
+ kdDebug(7019) << "SlaveBase::openPassDlg: username=" << info.username << endl;
+ kdDebug(7019) << "SlaveBase::openPassDlg: password=[hidden]" << endl;
+
+ return true;
+}
+
+int SlaveBase::messageBox( MessageBoxType type, const TQString &text, const TQString &caption,
+ const TQString &buttonYes, const TQString &buttonNo )
+{
+ return messageBox( text, type, caption, buttonYes, buttonNo, TQString::null );
+}
+
+int SlaveBase::messageBox( const TQString &text, MessageBoxType type, const TQString &caption,
+ const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName )
+{
+ kdDebug(7019) << "messageBox " << type << " " << text << " - " << caption << buttonYes << buttonNo << endl;
+ KIO_DATA << (TQ_INT32)type << text << caption << buttonYes << buttonNo << dontAskAgainName;
+ m_pConnection->send( INF_MESSAGEBOX, data );
+ if ( waitForAnswer( CMD_MESSAGEBOXANSWER, 0, data ) != -1 )
+ {
+ TQDataStream stream( data, IO_ReadOnly );
+ int answer;
+ stream >> answer;
+ kdDebug(7019) << "got messagebox answer" << answer << endl;
+ return answer;
+ } else
+ return 0; // communication failure
+}
+
+bool SlaveBase::canResume( TDEIO::filesize_t offset )
+{
+ kdDebug(7019) << "SlaveBase::canResume offset=" << TDEIO::number(offset) << endl;
+ d->needSendCanResume = false;
+ KIO_DATA << KIO_FILESIZE_T(offset);
+ m_pConnection->send( MSG_RESUME, data );
+ if ( offset )
+ {
+ int cmd;
+ if ( waitForAnswer( CMD_RESUMEANSWER, CMD_NONE, data, &cmd ) != -1 )
+ {
+ kdDebug(7019) << "SlaveBase::canResume returning " << (cmd == CMD_RESUMEANSWER) << endl;
+ return cmd == CMD_RESUMEANSWER;
+ } else
+ return false;
+ }
+ else // No resuming possible -> no answer to wait for
+ return true;
+}
+
+
+
+int SlaveBase::waitForAnswer( int expected1, int expected2, TQByteArray & data, int *pCmd )
+{
+ int cmd, result;
+ for (;;)
+ {
+ result = m_pConnection->read( &cmd, data );
+ if ( result == -1 )
+ {
+ kdDebug(7019) << "SlaveBase::waitForAnswer has read error." << endl;
+ return -1;
+ }
+ if ( cmd == expected1 || cmd == expected2 )
+ {
+ if ( pCmd ) *pCmd = cmd;
+ return result;
+ }
+ if ( isSubCommand(cmd) )
+ {
+ dispatch( cmd, data );
+ }
+ else
+ {
+ kdWarning() << "Got cmd " << cmd << " while waiting for an answer!" << endl;
+ }
+ }
+}
+
+
+int SlaveBase::readData( TQByteArray &buffer)
+{
+ int result = waitForAnswer( MSG_DATA, 0, buffer );
+ //kdDebug(7019) << "readData: length = " << result << " " << endl;
+ return result;
+}
+
+void SlaveBase::setTimeoutSpecialCommand(int timeout, const TQByteArray &data)
+{
+ if (timeout > 0)
+ d->timeout = time(0)+(time_t)timeout;
+ else if (timeout == 0)
+ d->timeout = 1; // Immediate timeout
+ else
+ d->timeout = 0; // Canceled
+
+ d->timeoutData = data;
+}
+
+void SlaveBase::dispatch( int command, const TQByteArray &data )
+{
+ TQDataStream stream( data, IO_ReadOnly );
+
+ KURL url;
+ int i;
+
+ switch( command ) {
+ case CMD_HOST: {
+ // Reset s_seqNr, see kpasswdserver/DESIGN
+ s_seqNr = 0;
+ TQString passwd;
+ TQString host, user;
+ stream >> host >> i >> user >> passwd;
+ setHost( host, i, user, passwd );
+ }
+ break;
+ case CMD_CONNECT:
+ openConnection( );
+ break;
+ case CMD_DISCONNECT:
+ closeConnection( );
+ break;
+ case CMD_SLAVE_STATUS:
+ slave_status();
+ break;
+ case CMD_SLAVE_CONNECT:
+ {
+ d->onHold = false;
+ TQString app_socket;
+ TQDataStream stream( data, IO_ReadOnly);
+ stream >> app_socket;
+ appconn->send( MSG_SLAVE_ACK );
+ disconnectSlave();
+ mConnectedToApp = true;
+ connectSlave(app_socket);
+ } break;
+ case CMD_SLAVE_HOLD:
+ {
+ KURL url;
+ TQDataStream stream( data, IO_ReadOnly);
+ stream >> url;
+ d->onHoldUrl = url;
+ d->onHold = true;
+ disconnectSlave();
+ mConnectedToApp = false;
+ // Do not close connection!
+ connectSlave(mPoolSocket);
+ } break;
+ case CMD_REPARSECONFIGURATION:
+ reparseConfiguration();
+ break;
+ case CMD_CONFIG:
+ stream >> d->configData;
+#ifdef Q_OS_UNIX //TODO: not yet available on WIN32
+ KSocks::setConfig(d->config);
+#endif
+ delete d->remotefile;
+ d->remotefile = 0;
+ break;
+ case CMD_GET:
+ {
+ stream >> url;
+ get( url );
+ } break;
+ case CMD_PUT:
+ {
+ int permissions;
+ TQ_INT8 iOverwrite, iResume;
+ stream >> url >> iOverwrite >> iResume >> permissions;
+ bool overwrite = ( iOverwrite != 0 );
+ bool resume = ( iResume != 0 );
+
+ // Remember that we need to send canResume(), TransferJob is expecting
+ // it. Well, in theory this shouldn't be done if resume is true.
+ // (the resume bool is currently unused)
+ d->needSendCanResume = true /* !resume */;
+
+ put( url, permissions, overwrite, resume);
+ } break;
+ case CMD_STAT:
+ stream >> url;
+ stat( url );
+ break;
+ case CMD_MIMETYPE:
+ stream >> url;
+ mimetype( url );
+ break;
+ case CMD_LISTDIR:
+ stream >> url;
+ listDir( url );
+ break;
+ case CMD_MKDIR:
+ stream >> url >> i;
+ mkdir( url, i );
+ break;
+ case CMD_RENAME:
+ {
+ TQ_INT8 iOverwrite;
+ KURL url2;
+ stream >> url >> url2 >> iOverwrite;
+ bool overwrite = (iOverwrite != 0);
+ rename( url, url2, overwrite );
+ } break;
+ case CMD_SYMLINK:
+ {
+ TQ_INT8 iOverwrite;
+ TQString target;
+ stream >> target >> url >> iOverwrite;
+ bool overwrite = (iOverwrite != 0);
+ symlink( target, url, overwrite );
+ } break;
+ case CMD_COPY:
+ {
+ int permissions;
+ TQ_INT8 iOverwrite;
+ KURL url2;
+ stream >> url >> url2 >> permissions >> iOverwrite;
+ bool overwrite = (iOverwrite != 0);
+ copy( url, url2, permissions, overwrite );
+ } break;
+ case CMD_DEL:
+ {
+ TQ_INT8 isFile;
+ stream >> url >> isFile;
+ del( url, isFile != 0);
+ } break;
+ case CMD_CHMOD:
+ stream >> url >> i;
+ chmod( url, i);
+ break;
+ case CMD_SPECIAL:
+ special( data );
+ break;
+ case CMD_META_DATA:
+ //kdDebug(7019) << "(" << getpid() << ") Incoming meta-data..." << endl;
+ stream >> mIncomingMetaData;
+ break;
+ case CMD_SUBURL:
+ stream >> url;
+ setSubURL(url);
+ break;
+ case CMD_NONE:
+ fprintf(stderr, "Got unexpected CMD_NONE!\n");
+ break;
+ case CMD_MULTI_GET:
+ multiGet( data );
+ break;
+ case CMD_LOCALURL:
+ {
+ stream >> url;
+ localURL( url );
+ } break;
+ default:
+ // Some command we don't understand.
+ // Just ignore it, it may come from some future version of KDE.
+ break;
+ }
+}
+
+TQString SlaveBase::createAuthCacheKey( const KURL& url )
+{
+ if( !url.isValid() )
+ return TQString::null;
+
+ // Generate the basic key sequence.
+ TQString key = url.protocol();
+ key += '-';
+ key += url.host();
+ int port = url.port();
+ if( port )
+ {
+ key += ':';
+ key += TQString::number(port);
+ }
+
+ return key;
+}
+
+bool SlaveBase::pingCacheDaemon() const
+{
+#ifdef Q_OS_UNIX
+ // TODO: Ping kded / kpasswdserver
+ KDEsuClient client;
+ int success = client.ping();
+ if( success == -1 )
+ {
+ success = client.startServer();
+ if( success == -1 )
+ {
+ kdDebug(7019) << "Cannot start a new deamon!!" << endl;
+ return false;
+ }
+ kdDebug(7019) << "Sucessfully started new cache deamon!!" << endl;
+ }
+ return true;
+#else
+ return false;
+#endif
+}
+
+bool SlaveBase::checkCachedAuthentication( AuthInfo& info )
+{
+ TQCString replyType;
+ TQByteArray params;
+ TQByteArray reply;
+ AuthInfo authResult;
+ long windowId = metaData("window-id").toLong();
+ unsigned long userTimestamp = metaData("user-timestamp").toULong();
+
+ kdDebug(7019) << "SlaveBase::checkCachedAuthInfo window = " << windowId << " url = " << info.url.url() << endl;
+
+ (void) dcopClient(); // Make sure to have a dcop client.
+
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << info << windowId << userTimestamp;
+
+ if ( !d->dcopClient->call( "kded", "kpasswdserver", "checkAuthInfo(TDEIO::AuthInfo, long int, unsigned long int)",
+ params, replyType, reply ) )
+ {
+ kdWarning(7019) << "Can't communicate with kded_kpasswdserver!" << endl;
+ return false;
+ }
+
+ if ( replyType == "TDEIO::AuthInfo" )
+ {
+ TQDataStream stream2( reply, IO_ReadOnly );
+ stream2 >> authResult;
+ }
+ else
+ {
+ kdError(7019) << "DCOP function checkAuthInfo(...) returns "
+ << replyType << ", expected TDEIO::AuthInfo" << endl;
+ return false;
+ }
+ if (!authResult.isModified())
+ {
+ return false;
+ }
+
+ info = authResult;
+ return true;
+}
+
+bool SlaveBase::cacheAuthentication( const AuthInfo& info )
+{
+ TQByteArray params;
+ long windowId = metaData("window-id").toLong();
+
+ (void) dcopClient(); // Make sure to have a dcop client.
+
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << info << windowId;
+
+ d->dcopClient->send( "kded", "kpasswdserver", "addAuthInfo(TDEIO::AuthInfo, long int)", params );
+
+ return true;
+}
+
+int SlaveBase::connectTimeout()
+{
+ bool ok;
+ TQString tmp = metaData("ConnectTimeout");
+ int result = tmp.toInt(&ok);
+ if (ok)
+ return result;
+ return DEFAULT_CONNECT_TIMEOUT;
+}
+
+int SlaveBase::proxyConnectTimeout()
+{
+ bool ok;
+ TQString tmp = metaData("ProxyConnectTimeout");
+ int result = tmp.toInt(&ok);
+ if (ok)
+ return result;
+ return DEFAULT_PROXY_CONNECT_TIMEOUT;
+}
+
+
+int SlaveBase::responseTimeout()
+{
+ bool ok;
+ TQString tmp = metaData("ResponseTimeout");
+ int result = tmp.toInt(&ok);
+ if (ok)
+ return result;
+ return DEFAULT_RESPONSE_TIMEOUT;
+}
+
+
+int SlaveBase::readTimeout()
+{
+ bool ok;
+ TQString tmp = metaData("ReadTimeout");
+ int result = tmp.toInt(&ok);
+ if (ok)
+ return result;
+ return DEFAULT_READ_TIMEOUT;
+}
+
+bool SlaveBase::wasKilled() const
+{
+ return d->wasKilled;
+}
+
+void SlaveBase::setKillFlag()
+{
+ d->wasKilled=true;
+}
+
+void SlaveBase::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
diff --git a/tdeio/tdeio/slavebase.h b/tdeio/tdeio/slavebase.h
new file mode 100644
index 000000000..1030d94c4
--- /dev/null
+++ b/tdeio/tdeio/slavebase.h
@@ -0,0 +1,847 @@
+/*
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __slavebase_h
+#define __slavebase_h
+
+#include <kurl.h>
+#include <tdeconfigbase.h>
+#include <tdeio/global.h>
+#include <tdeio/authinfo.h>
+
+class DCOPClient;
+class KRemoteEncoding;
+
+namespace TDEIO {
+
+class Connection;
+class SlaveBasePrivate;
+
+/**
+ * There are two classes that specifies the protocol between application (job)
+ * and tdeioslave. SlaveInterface is the class to use on the application end,
+ * SlaveBase is the one to use on the slave end.
+ *
+ * Slave implementations should simply inherit SlaveBase
+ *
+ * A call to foo() results in a call to slotFoo() on the other end.
+ */
+class TDEIO_EXPORT SlaveBase
+{
+public:
+ SlaveBase( const TQCString &protocol, const TQCString &pool_socket, const TQCString &app_socket);
+ virtual ~SlaveBase();
+
+ /**
+ * @internal
+ * Terminate the slave by calling the destructor and then ::exit()
+ */
+ void exit();
+
+ /**
+ * @internal
+ */
+ void dispatchLoop();
+
+ /**
+ * @internal
+ */
+ void setConnection( Connection* connection ) { m_pConnection = connection; }
+ /**
+ * @internal
+ */
+ Connection *connection() const { return m_pConnection; }
+
+
+ ///////////
+ // Message Signals to send to the job
+ ///////////
+
+ /**
+ * Sends data in the slave to the job (i.e. in get).
+ *
+ * To signal end of data, simply send an empty
+ * TQByteArray().
+ *
+ * @param data the data read by the slave
+ */
+ void data( const TQByteArray &data );
+
+ /**
+ * Asks for data from the job.
+ * @see readData
+ */
+ void dataReq( );
+
+ /**
+ * Call to signal an error.
+ * This also finishes the job, no need to call finished.
+ *
+ * If the Error code is TDEIO::ERR_SLAVE_DEFINED then the
+ * _text should contain the complete translated text of
+ * of the error message. This message will be displayed
+ * in an KTextBrowser which allows rich text complete
+ * with hyper links. Email links will call the default
+ * mailer, "exec:/command arg1 arg2" will be forked and
+ * all other links will call the default browser.
+ *
+ * @see TDEIO::Error
+ * @see KTextBrowser
+ * @param _errid the error code from TDEIO::Error
+ * @param _text the rich text error message
+ */
+ void error( int _errid, const TQString &_text );
+
+ /**
+ * Call in openConnection, if you reimplement it, when you're done.
+ */
+ void connected();
+
+ /**
+ * Call to signal successful completion of any command
+ * (besides openConnection and closeConnection)
+ */
+ void finished();
+
+ /**
+ * Call to signal that data from the sub-URL is needed
+ */
+ void needSubURLData();
+
+ /**
+ * Used to report the status of the slave.
+ * @param host the slave is currently connected to. (Should be
+ * empty if not connected)
+ * @param connected Whether an actual network connection exists.
+ **/
+ void slaveStatus(const TQString &host, bool connected);
+
+ /**
+ * Call this from stat() to express details about an object, the
+ * UDSEntry customarily contains the atoms describing file name, size,
+ * mimetype, etc.
+ * @param _entry The UDSEntry containing all of the object attributes.
+ */
+ void statEntry( const UDSEntry& _entry );
+
+ /**
+ * Call this in listDir, each time you have a bunch of entries
+ * to report.
+ * @param _entry The UDSEntry containing all of the object attributes.
+ */
+ void listEntries( const UDSEntryList& _entry );
+
+ /**
+ * Call this at the beginning of put(), to give the size of the existing
+ * partial file, if there is one. The @p offset argument notifies the
+ * other job (the one that gets the data) about the offset to use.
+ * In this case, the boolean returns whether we can indeed resume or not
+ * (we can't if the protocol doing the get() doesn't support setting an offset)
+ */
+ bool canResume( TDEIO::filesize_t offset );
+
+ /*
+ * Call this at the beginning of get(), if the "resume" metadata was set
+ * and resuming is implemented by this protocol.
+ */
+ void canResume();
+
+ ///////////
+ // Info Signals to send to the job
+ ///////////
+
+ /**
+ * Call this in get and copy, to give the total size
+ * of the file
+ * Call in listDir too, when you know the total number of items.
+ */
+ void totalSize( TDEIO::filesize_t _bytes );
+ /**
+ * Call this during get and copy, once in a while,
+ * to give some info about the current state.
+ * Don't emit it in listDir, listEntries speaks for itself.
+ */
+ void processedSize( TDEIO::filesize_t _bytes );
+
+ /**
+ * Only use this if you can't know in advance the size of the
+ * copied data. For example, if you're doing variable bitrate
+ * compression of the source.
+ *
+ * STUB ! Currently unimplemented. Here now for binary compatibility.
+ *
+ * Call this during get and copy, once in a while,
+ * to give some info about the current state.
+ * Don't emit it in listDir, listEntries speaks for itself.
+ */
+ void processedPercent( float percent );
+
+ /**
+ * Call this in get and copy, to give the current transfer
+ * speed, but only if it can't be calculated out of the size you
+ * passed to processedSize (in most cases you don't want to call it)
+ */
+ void speed( unsigned long _bytes_per_second );
+
+ /**
+ * Call this to signal a redirection
+ * The job will take care of going to that url.
+ */
+ void redirection( const KURL &_url );
+
+ /**
+ * Tell that we will only get an error page here.
+ * This means: the data you'll get isn't the data you requested,
+ * but an error page (usually HTML) that describes an error.
+ */
+ void errorPage();
+
+ /**
+ * Call this in mimetype() and in get(), when you know the mimetype.
+ * See mimetype about other ways to implement it.
+ */
+ void mimeType( const TQString &_type );
+
+ /**
+ * Call to signal a warning, to be displayed in a dialog box.
+ */
+ void warning( const TQString &msg );
+
+ /**
+ * Call to signal a message, to be displayed if the application wants to,
+ * for instance in a status bar. Usual examples are "connecting to host xyz", etc.
+ */
+ void infoMessage( const TQString &msg );
+
+ enum MessageBoxType { QuestionYesNo = 1, WarningYesNo = 2, WarningContinueCancel = 3, WarningYesNoCancel = 4, Information = 5, SSLMessageBox = 6 };
+
+ /**
+ * Call this to show a message box from the slave
+ * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
+ * @param text Message string. May contain newlines.
+ * @param caption Message box title.
+ * @param buttonYes The text for the first button.
+ * The default is i18n("&Yes").
+ * @param buttonNo The text for the second button.
+ * The default is i18n("&No").
+ * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
+ * and for Information, none is used.
+ * @return a button code, as defined in KMessageBox, or 0 on communication error.
+ */
+ int messageBox( MessageBoxType type, const TQString &text,
+ const TQString &caption = TQString::null,
+ const TQString &buttonYes = TQString::null,
+ const TQString &buttonNo = TQString::null );
+
+ /**
+ * Call this to show a message box from the slave
+ * @param text Message string. May contain newlines.
+ * @param type type of message box: QuestionYesNo, WarningYesNo, WarningContinueCancel...
+ * @param caption Message box title.
+ * @param buttonYes The text for the first button.
+ * The default is i18n("&Yes").
+ * @param buttonNo The text for the second button.
+ * The default is i18n("&No").
+ * Note: for ContinueCancel, buttonYes is the continue button and buttonNo is unused.
+ * and for Information, none is used.
+ * @param dontAskAgainName A checkbox is added with which further confirmation can be turned off.
+ * The string is used to lookup and store the setting in tdeioslaverc.
+ * @return a button code, as defined in KMessageBox, or 0 on communication error.
+ * @since 3.3
+ */
+ int messageBox( const TQString &text, MessageBoxType type,
+ const TQString &caption = TQString::null,
+ const TQString &buttonYes = TQString::null,
+ const TQString &buttonNo = TQString::null,
+ const TQString &dontAskAgainName = TQString::null );
+
+ /**
+ * Sets meta-data to be send to the application before the first
+ * data() or finished() signal.
+ */
+ void setMetaData(const TQString &key, const TQString &value);
+
+ /**
+ * Queries for the existence of a certain config/meta-data entry
+ * send by the application to the slave.
+ * @since 3.2
+ */
+ bool hasMetaData(const TQString &key) const;
+
+ /**
+ * Queries for config/meta-data send by the application to the slave.
+ * @since 3.2
+ */
+ TQString metaData(const TQString &key) const;
+
+ /**
+ * @obsolete kept for binary compatibility
+ * Queries for the existence of a certain config/meta-data entry
+ * send by the application to the slave.
+ */
+ bool hasMetaData(const TQString &key);
+
+ /**
+ * @obsolete kept for binary compatibility
+ * Queries for config/meta-data sent by the application to the slave.
+ */
+ TQString metaData(const TQString &key);
+
+ /**
+ * @internal for ForwardingSlaveBase
+ * Contains all metadata (but no config) sent by the application to the slave.
+ * @since 3.5.2
+ */
+ MetaData allMetaData() const { return mIncomingMetaData; }
+
+ /**
+ * Returns a configuration object to query config/meta-data information
+ * from.
+ *
+ * The application provides the slave with all configuration information
+ * relevant for the current protocol and host.
+ */
+ TDEConfigBase* config();
+
+ /**
+ * Returns an object that can translate remote filenames into proper
+ * Unicode forms. This encoding can be set by the user.
+ *
+ * @since 3.3
+ */
+ KRemoteEncoding* remoteEncoding();
+
+
+ ///////////
+ // Commands sent by the job, the slave has to
+ // override what it wants to implement
+ ///////////
+
+ /**
+ * Set the host
+ * @param host
+ * @param port
+ * @param user
+ * @param pass
+ * Called directly by createSlave, this is why there is no equivalent in
+ * SlaveInterface, unlike the other methods.
+ *
+ * This method is called whenever a change in host, port or user occurs.
+ */
+ virtual void setHost(const TQString& host, int port, const TQString& user, const TQString& pass);
+
+ /**
+ * Prepare slave for streaming operation
+ */
+ virtual void setSubURL(const KURL&url);
+
+ /**
+ * Opens the connection (forced)
+ * When this function gets called the slave is operating in
+ * connection-oriented mode.
+ * When a connection gets lost while the slave operates in
+ * connection oriented mode, the slave should report
+ * ERR_CONNECTION_BROKEN instead of reconnecting. The user is
+ * expected to disconnect the slave in the error handler.
+ */
+ virtual void openConnection();
+
+ /**
+ * Closes the connection (forced)
+ * Called when the application disconnects the slave to close
+ * any open network connections.
+ *
+ * When the slave was operating in connection-oriented mode,
+ * it should reset itself to connectionless (default) mode.
+ */
+ virtual void closeConnection();
+
+ /**
+ * get, aka read.
+ * @param url the full url for this request. Host, port and user of the URL
+ * can be assumed to be the same as in the last setHost() call.
+ * The slave emits the data through data
+ */
+ virtual void get( const KURL& url );
+
+ /**
+ * put, i.e. write data into a file.
+ *
+ * @param url where to write the file
+ * @param permissions may be -1. In this case no special permission mode is set.
+ * @param overwrite if true, any existing file will be overwritten.
+ * If the file indeed already exists, the slave should NOT apply the
+ * permissions change to it.
+ * @param resume currently unused, please ignore.
+ * The support for resuming using .part files is done by calling canResume().
+ *
+ * IMPORTANT: Use the "modified" metadata in order to set the modification time of the file.
+ *
+ * @see canResume()
+ */
+ virtual void put( const KURL& url, int permissions, bool overwrite, bool resume );
+
+ /**
+ * Finds all details for one file or directory.
+ * The information returned is the same as what listDir returns,
+ * but only for one file or directory.
+ */
+ virtual void stat( const KURL& url );
+
+ /**
+ * Finds mimetype for one file or directory.
+ *
+ * This method should either emit 'mimeType' or it
+ * should send a block of data big enough to be able
+ * to determine the mimetype.
+ *
+ * If the slave doesn't reimplement it, a get will
+ * be issued, i.e. the whole file will be downloaded before
+ * determining the mimetype on it - this is obviously not a
+ * good thing in most cases.
+ */
+ virtual void mimetype( const KURL& url );
+
+ /**
+ * Lists the contents of @p url.
+ * The slave should emit ERR_CANNOT_ENTER_DIRECTORY if it doesn't exist,
+ * if we don't have enough permissions, or if it is a file
+ * It should also emit totalFiles as soon as it knows how many
+ * files it will list.
+ */
+ virtual void listDir( const KURL& url );
+
+ /**
+ * Create a directory
+ * @param url path to the directory to create
+ * @param permissions the permissions to set after creating the directory
+ * (-1 if no permissions to be set)
+ * The slave emits ERR_COULD_NOT_MKDIR if failure.
+ */
+ virtual void mkdir( const KURL&url, int permissions );
+
+ /**
+ * Rename @p oldname into @p newname.
+ * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
+ * ask for copy + del instead.
+ * @param src where to move the file from
+ * @param dest where to move the file to
+ * @param overwrite if true, any existing file will be overwritten
+ */
+ virtual void rename( const KURL& src, const KURL& dest, bool overwrite );
+
+ /**
+ * Creates a symbolic link named @p dest, pointing to @p target, which
+ * may be a relative or an absolute path.
+ * @param target The string that will become the "target" of the link (can be relative)
+ * @param dest The symlink to create.
+ * @param overwrite whether to automatically overwrite if the dest exists
+ */
+ virtual void symlink( const TQString& target, const KURL& dest, bool overwrite );
+
+ /**
+ * Change permissions on @p path
+ * The slave emits ERR_DOES_NOT_EXIST or ERR_CANNOT_CHMOD
+ */
+ virtual void chmod( const KURL& url, int permissions );
+
+ /**
+ * Copy @p src into @p dest.
+ * If the slave returns an error ERR_UNSUPPORTED_ACTION, the job will
+ * ask for get + put instead.
+ * @param src where to copy the file from (decoded)
+ * @param dest where to copy the file to (decoded)
+ * @param permissions may be -1. In this case no special permission mode is set.
+ * @param overwrite if true, any existing file will be overwritten
+ *
+ */
+ virtual void copy( const KURL &src, const KURL &dest, int permissions, bool overwrite );
+
+ /**
+ * Delete a file or directory.
+ * @param url file/directory to delete
+ * @param isfile if true, a file should be deleted.
+ * if false, a directory should be deleted.
+ */
+ virtual void del( const KURL &url, bool isfile);
+
+ // TODO KDE4: add setLinkDest() or something, to modify symlink targets.
+ // Will be used for kio_file but also kio_remote (#97129)
+
+ /**
+ * Used for any command that is specific to this slave (protocol)
+ * Examples are : HTTP POST, mount and unmount (kio_file)
+ *
+ * @param data packed data; the meaning is completely dependent on the
+ * slave, but usually starts with an int for the command number.
+ * Document your slave's commands, at least in its header file.
+ */
+ virtual void special( const TQByteArray & data );
+
+ /**
+ * Used for multiple get. Currently only used foir HTTP pielining
+ * support.
+ *
+ * @param data packed data; Contains number of URLs to fetch, and for
+ * each URL the URL itself and its associated MetaData.
+ */
+ virtual void multiGet( const TQByteArray & data );
+
+ /**
+ * Called to get the status of the slave. Slave should respond
+ * by calling slaveStatus(...)
+ */
+ virtual void slave_status();
+
+ /**
+ * Called by the scheduler to tell the slave that the configuration
+ * changed (i.e. proxy settings) .
+ */
+ virtual void reparseConfiguration();
+
+ /**
+ * For use with for ForwardingSlaveBase
+ * Returns the local URL of the given remote URL if possible
+ * @since R14.0.0
+ */
+ virtual void localURL( const KURL& remoteURL );
+
+ /**
+ * @return timeout value for connecting to remote host.
+ */
+ int connectTimeout();
+
+ /**
+ * @return timeout value for connecting to proxy in secs.
+ */
+ int proxyConnectTimeout();
+
+ /**
+ * @return timeout value for read from first data from
+ * remote host in seconds.
+ */
+ int responseTimeout();
+
+ /**
+ * @return timeout value for read from subsequent data from
+ * remote host in secs.
+ */
+ int readTimeout();
+
+ /**
+ * This function sets a timeout of @p timeout seconds and calls
+ * special(data) when the timeout occurs as if it was called by the
+ * application.
+ *
+ * A timeout can only occur when the slave is waiting for a command
+ * from the application.
+ *
+ * Specifying a negative timeout cancels a pending timeout.
+ *
+ * Only one timeout at a time is supported, setting a timeout
+ * cancels any pending timeout.
+ * @since 3.1
+ */
+ void setTimeoutSpecialCommand(int timeout, const TQByteArray &data=TQByteArray());
+
+ /**
+ * @internal
+ */
+ static void sigsegv_handler(int);
+ /**
+ * @internal
+ */
+ static void sigpipe_handler(int);
+
+ /////////////////
+ // Dispatching (internal)
+ ////////////////
+
+ /**
+ * @internal
+ */
+ virtual bool dispatch();
+ /**
+ * @internal
+ */
+ virtual void dispatch( int command, const TQByteArray &data );
+
+ /**
+ * Read data send by the job, after a dataReq
+ *
+ * @param buffer buffer where data is stored
+ * @return 0 on end of data,
+ * > 0 bytes read
+ * < 0 error
+ **/
+ int readData( TQByteArray &buffer );
+
+ /**
+ * internal function to be called by the slave.
+ * It collects entries and emits them via listEntries
+ * when enough of them are there or a certain time
+ * frame exceeded (to make sure the app gets some
+ * items in time but not too many items one by one
+ * as this will cause a drastic performance penalty)
+ * @param _entry The UDSEntry containing all of the object attributes.
+ * @param ready set to true after emitting all items. @p _entry is not
+ * used in this case
+ */
+ void listEntry( const UDSEntry& _entry, bool ready);
+
+ /**
+ * internal function to connect a slave to/ disconnect from
+ * either the slave pool or the application
+ */
+ void connectSlave(const TQString& path);
+ void disconnectSlave();
+
+ /**
+ * Prompt the user for Authorization info (login & password).
+ *
+ * Use this function to request authorization information from
+ * the end user. You can also pass an error message which explains
+ * why a previous authorization attempt failed. Here is a very
+ * simple example:
+ *
+ * \code
+ * TDEIO::AuthInfo authInfo;
+ * if ( openPassDlg( authInfo ) )
+ * {
+ * kdDebug() << TQString::fromLatin1("User: ")
+ * << authInfo.username << endl;
+ * kdDebug() << TQString::fromLatin1("Password: ")
+ * << TQString::fromLatin1("Not displayed here!") << endl;
+ * }
+ * \endcode
+ *
+ * You can also preset some values like the username, caption or
+ * comment as follows:
+ *
+ * \code
+ * TDEIO::AuthInfo authInfo;
+ * authInfo.caption= "Acme Password Dialog";
+ * authInfo.username= "Wile E. Coyote";
+ * TQString errorMsg = "You entered an incorrect password.";
+ * if ( openPassDlg( authInfo, errorMsg ) )
+ * {
+ * kdDebug() << TQString::fromLatin1("User: ")
+ * << authInfo.username << endl;
+ * kdDebug() << TQString::fromLatin1("Password: ")
+ * << TQString::fromLatin1("Not displayed here!") << endl;
+ * }
+ * \endcode
+ *
+ * \note You should consider using checkCachedAuthentication() to
+ * see if the password is available in kpasswdserver before calling
+ * this function.
+ *
+ * \note A call to this function can fail and return @p false,
+ * if the UIServer could not be started for whatever reason.
+ *
+ * @see checkCachedAuthentication
+ * @param info See AuthInfo.
+ * @param errorMsg Error message to show
+ * @return @p true if user clicks on "OK", @p false otherwsie.
+ * @since 3.1
+ */
+ bool openPassDlg( TDEIO::AuthInfo& info, const TQString &errorMsg );
+
+ /**
+ * Same as above function except it does not need error message.
+ * BIC: Combine this function with the above for KDE4.
+ */
+ bool openPassDlg( TDEIO::AuthInfo& info );
+
+ /**
+ * Checks for cached authentication based on parameters
+ * given by @p info.
+ *
+ * Use this function to check if any cached password exists
+ * for the URL given by @p info. If @p AuthInfo::realmValue
+ * and/or @p AuthInfo::verifyPath flag is specified, then
+ * they will also be factored in determining the presence
+ * of a cached password. Note that @p Auth::url is a required
+ * parameter when attempting to check for cached authorization
+ * info. Here is a simple example:
+ *
+ * \code
+ * AuthInfo info;
+ * info.url = KURL("http://www.foobar.org/foo/bar");
+ * info.username = "somename";
+ * info.verifyPath = true;
+ * if ( !checkCachedAuthentication( info ) )
+ * {
+ * if ( !openPassDlg(info) )
+ * ....
+ * }
+ * \endcode
+ *
+ * @param info See AuthInfo.
+ * @return @p true if cached Authorization is found, false otherwise.
+ */
+ bool checkCachedAuthentication( AuthInfo& info );
+
+ /**
+ * Explicitly store authentication information. openPassDlg already
+ * stores password information automatically, you only need to call
+ * this function if you want to store authentication information that
+ * is different from the information returned by openPassDlg.
+ */
+ bool cacheAuthentication( const AuthInfo& info );
+
+ /**
+ * @obsolete as of 3.1.
+ * TODO: Remove before KDE 4.0
+ */
+ bool pingCacheDaemon() const;
+
+ /**
+ * @obsolete as of 3.1. Use openPassDlg instead.
+ * TODO: Remove before KDE 4.0
+ * Creates a basic key to be used to cache the password.
+ * @param url the url from which the key is supposed to be generated
+ */
+ TQString createAuthCacheKey( const KURL& url );
+
+ /**
+ * @obsolete as of 3.1. Use openPassDlg instead.
+ * TODO: Remove before KDE 4.0
+ *
+ * Cache authentication information is now stored automatically
+ * by openPassDlg.
+ */
+ void sendAuthenticationKey( const TQCString& gKey, const TQCString& key, bool keep );
+
+ /**
+ * @obsolete as of 3.1. Use openPassDlg instead.
+ * TODO: Remove before KDE 4.0
+ *
+ * Cached authentication information is now session based and
+ * removed automatically when a given session ends, i.e. the
+ * application is closed.
+ */
+ void delCachedAuthentication( const TQString& key );
+
+ /**
+ * @obsolete as of 3.1. Use openPassDlg instead.
+ * TODO: Remove before KDE 4.0
+ */
+ void setMultipleAuthCaching( bool ) {};
+
+ /**
+ * @obsolete as of 3.1. Use openPassDlg instead.
+ * TODO: Remove before KDE 4.0
+ */
+ bool multipleAuthCaching() const { return false; }
+
+ /**
+ * Used by the slave to check if it can connect
+ * to a given host. This should be called where the slave is ready
+ * to do a ::connect() on a socket. For each call to
+ * requestNetwork must exist a matching call to
+ * dropNetwork, or the system will stay online until
+ * KNetMgr gets closed (or the SlaveBase gets destructed)!
+ *
+ * If KNetMgr is not running, then this is a no-op and returns true
+ *
+ * @param host tells the netmgr the host the slave wants to connect
+ * to. As this could also be a proxy, we can't just take
+ * the host currenctly connected to (but that's the default
+ * value)
+ *
+ * @return true in theorie, the host is reachable
+ * false the system is offline and the host is in a remote network.
+ */
+ bool requestNetwork(const TQString& host = TQString::null);
+
+ /**
+ * Used by the slave to withdraw a connection requested by
+ * requestNetwork. This function cancels the last call to
+ * requestNetwork. If a client uses more than one internet
+ * connection, it must use dropNetwork(host) to
+ * stop each request.
+ *
+ * If KNetMgr is not running, then this is a no-op.
+ *
+ * @param host the host passed to requestNetwork
+ *
+ * A slave should call this function every time it disconnect from a host.
+ * */
+ void dropNetwork(const TQString& host = TQString::null);
+
+ /**
+ * Return the dcop client used by this slave.
+ * @since 3.1
+ */
+ DCOPClient *dcopClient();
+
+ /**
+ * Wait for an answer to our request, until we get @p expected1 or @p expected2
+ * @return the result from readData, as well as the cmd in *pCmd if set, and the data in @p data
+ */
+ int waitForAnswer( int expected1, int expected2, TQByteArray & data, int * pCmd = 0 );
+
+ /**
+ * Internal function to transmit meta data to the application.
+ */
+ void sendMetaData();
+
+ /**
+ * Name of the protocol supported by this slave
+ */
+ TQCString mProtocol;
+
+ Connection * m_pConnection;
+
+ MetaData mOutgoingMetaData;
+ MetaData mIncomingMetaData;
+
+ /** If your ioslave was killed by a signal, wasKilled() returns true.
+ Check it regularly in lengthy functions (e.g. in get();) and return
+ as fast as possible from this function if wasKilled() returns true.
+ This will ensure that your slave destructor will be called correctly.
+ @since 3.1
+ */
+ bool wasKilled() const;
+
+ /** Internally used.
+ * @internal
+ * @since 3.1
+ */
+ void setKillFlag();
+
+protected:
+ UDSEntryList pendingListEntries;
+ uint listEntryCurrentSize;
+ long listEntry_sec, listEntry_usec;
+ Connection *appconn;
+ TQString mPoolSocket;
+ TQString mAppSocket;
+ bool mConnectedToApp;
+ static long s_seqNr;
+ virtual void virtual_hook( int id, void* data );
+
+private:
+ SlaveBasePrivate *d;
+};
+
+}
+
+#endif
diff --git a/tdeio/tdeio/slaveconfig.cpp b/tdeio/tdeio/slaveconfig.cpp
new file mode 100644
index 000000000..e81146e76
--- /dev/null
+++ b/tdeio/tdeio/slaveconfig.cpp
@@ -0,0 +1,225 @@
+// -*- c++ -*-
+/*
+ * This file is part of the KDE libraries
+ * Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
+ *
+ * $Id$
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#include <assert.h>
+
+#include <tqdict.h>
+
+#include <tdeconfig.h>
+#include <kstaticdeleter.h>
+#include <kprotocolinfo.h>
+#include <kprotocolmanager.h>
+
+#include "slaveconfig.h"
+
+using namespace TDEIO;
+
+namespace TDEIO {
+
+class SlaveConfigProtocol
+{
+public:
+ SlaveConfigProtocol() { host.setAutoDelete(true); }
+ ~SlaveConfigProtocol()
+ {
+ delete configFile;
+ }
+
+public:
+ MetaData global;
+ TQDict<MetaData> host;
+ TDEConfig *configFile;
+};
+
+static void readConfig(TDEConfig *config, const TQString & group, MetaData *metaData)
+{
+ *metaData += config->entryMap(group);
+}
+
+class SlaveConfigPrivate
+{
+ public:
+ void readGlobalConfig();
+ SlaveConfigProtocol *readProtocolConfig(const TQString &_protocol);
+ SlaveConfigProtocol *findProtocolConfig(const TQString &_protocol);
+ void readConfigProtocolHost(const TQString &_protocol, SlaveConfigProtocol *scp, const TQString &host);
+ public:
+ MetaData global;
+ TQDict<SlaveConfigProtocol> protocol;
+};
+
+void SlaveConfigPrivate::readGlobalConfig()
+{
+ global.clear();
+ // Read stuff...
+ TDEConfig *config = KProtocolManager::config();
+ readConfig(TDEGlobal::config(), "Socks", &global); // Socks settings.
+ if ( config )
+ readConfig(config, "<default>", &global);
+}
+
+SlaveConfigProtocol* SlaveConfigPrivate::readProtocolConfig(const TQString &_protocol)
+{
+ SlaveConfigProtocol *scp = protocol.find(_protocol);
+ if (!scp)
+ {
+ TQString filename = KProtocolInfo::config(_protocol);
+ scp = new SlaveConfigProtocol;
+ scp->configFile = new TDEConfig(filename, true, false);
+ protocol.insert(_protocol, scp);
+ }
+ // Read global stuff...
+ readConfig(scp->configFile, "<default>", &(scp->global));
+ return scp;
+}
+
+SlaveConfigProtocol* SlaveConfigPrivate::findProtocolConfig(const TQString &_protocol)
+{
+ SlaveConfigProtocol *scp = protocol.find(_protocol);
+ if (!scp)
+ scp = readProtocolConfig(_protocol);
+ return scp;
+}
+
+void SlaveConfigPrivate::readConfigProtocolHost(const TQString &, SlaveConfigProtocol *scp, const TQString &host)
+{
+ MetaData *metaData = new MetaData;
+ scp->host.replace(host, metaData);
+
+ // Read stuff
+ // Break host into domains
+ TQString domain = host;
+
+ if (!domain.contains('.'))
+ {
+ // Host without domain.
+ if (scp->configFile->hasGroup("<local>"))
+ readConfig(scp->configFile, "<local>", metaData);
+ }
+
+ int pos = 0;
+ do
+ {
+ pos = host.findRev('.', pos-1);
+
+ if (pos < 0)
+ domain = host;
+ else
+ domain = host.mid(pos+1);
+
+ if (scp->configFile->hasGroup(domain))
+ readConfig(scp->configFile, domain.lower(), metaData);
+ }
+ while (pos > 0);
+}
+
+
+SlaveConfig *SlaveConfig::_self = 0;
+static KStaticDeleter<SlaveConfig> slaveconfigsd;
+
+SlaveConfig *SlaveConfig::self()
+{
+ if (!_self)
+ _self = slaveconfigsd.setObject(_self, new SlaveConfig);
+ return _self;
+}
+
+SlaveConfig::SlaveConfig()
+{
+ d = new SlaveConfigPrivate;
+ d->protocol.setAutoDelete(true);
+ d->readGlobalConfig();
+}
+
+SlaveConfig::~SlaveConfig()
+{
+ delete d; d = 0;
+ _self = 0;
+}
+
+void SlaveConfig::setConfigData(const TQString &protocol,
+ const TQString &host,
+ const TQString &key,
+ const TQString &value )
+{
+ MetaData config;
+ config.insert(key, value);
+ setConfigData(protocol, host, config);
+}
+
+void SlaveConfig::setConfigData(const TQString &protocol, const TQString &host, const MetaData &config )
+{
+ if (protocol.isEmpty())
+ d->global += config;
+ else {
+ SlaveConfigProtocol *scp = d->findProtocolConfig(protocol);
+ if (host.isEmpty())
+ {
+ scp->global += config;
+ }
+ else
+ {
+ MetaData *hostConfig = scp->host.find(host);
+ if (!hostConfig)
+ {
+ d->readConfigProtocolHost(protocol, scp, host);
+ hostConfig = scp->host.find(host);
+ assert(hostConfig);
+ }
+ *hostConfig += config;
+ }
+ }
+}
+
+MetaData SlaveConfig::configData(const TQString &protocol, const TQString &host)
+{
+ MetaData config = d->global;
+ SlaveConfigProtocol *scp = d->findProtocolConfig(protocol);
+ config += scp->global;
+ if (host.isEmpty())
+ return config;
+ MetaData *hostConfig = scp->host.find(host);
+ if (!hostConfig)
+ {
+ d->readConfigProtocolHost(protocol, scp, host);
+ emit configNeeded(protocol, host);
+ hostConfig = scp->host.find(host);
+ assert(hostConfig);
+ }
+ config += *hostConfig;
+ return config;
+}
+
+TQString SlaveConfig::configData(const TQString &protocol, const TQString &host, const TQString &key)
+{
+ return configData(protocol, host)[key];
+}
+
+void SlaveConfig::reset()
+{
+ d->protocol.clear();
+ d->readGlobalConfig();
+}
+
+}
+
+#include "slaveconfig.moc"
diff --git a/tdeio/tdeio/slaveconfig.h b/tdeio/tdeio/slaveconfig.h
new file mode 100644
index 000000000..500910062
--- /dev/null
+++ b/tdeio/tdeio/slaveconfig.h
@@ -0,0 +1,106 @@
+// -*- c++ -*-
+/*
+ * This file is part of the KDE libraries
+ * Copyright (c) 2001 Waldo Bastian <bastian@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#ifndef KIO_SLAVE_CONFIG_H
+#define KIO_SLAVE_CONFIG_H
+
+#include <tqobject.h>
+#include <tdeio/global.h>
+
+namespace TDEIO {
+
+ class SlaveConfigPrivate;
+ /**
+ * SlaveConfig
+ *
+ * This class manages the configuration for io-slaves based on protocol
+ * and host. The Scheduler makes use of this class to configure the slave
+ * whenever it has to connect to a new host.
+ *
+ * You only need to use this class if you want to override specific
+ * configuration items of an io-slave when the io-slave is used by
+ * your application.
+ *
+ * Normally io-slaves are being configured by "kio_<protocol>rc"
+ * configuration files. Groups defined in such files are treated as host
+ * or domain specification. Configuration items defined in a group are
+ * only applied when the slave is connecting with a host that matches with
+ * the host and/or domain specified by the group.
+ */
+ class TDEIO_EXPORT SlaveConfig : public TQObject
+ {
+ Q_OBJECT
+ public:
+ static SlaveConfig *self();
+ ~SlaveConfig();
+ /**
+ * Configure slaves of type @p protocol by setting @p key to @p value.
+ * If @p host is specified the configuration only applies when dealing
+ * with @p host.
+ *
+ * Changes made to the slave configuration only apply to slaves
+ * used by the current process.
+ */
+ void setConfigData(const TQString &protocol, const TQString &host, const TQString &key, const TQString &value );
+
+ /**
+ * Configure slaves of type @p protocol with @p config.
+ * If @p host is specified the configuration only applies when dealing
+ * with @p host.
+ *
+ * Changes made to the slave configuration only apply to slaves
+ * used by the current process.
+ */
+ void setConfigData(const TQString &protocol, const TQString &host, const MetaData &config );
+
+ /**
+ * Query slave configuration for slaves of type @p protocol when
+ * dealing with @p host.
+ */
+ MetaData configData(const TQString &protocol, const TQString &host);
+
+ /**
+ * Query a specific configuration key for slaves of type @p protocol when
+ * dealing with @p host.
+ */
+ TQString configData(const TQString &protocol, const TQString &host, const TQString &key);
+
+ /**
+ * Undo any changes made by calls to setConfigData.
+ */
+ void reset();
+ signals:
+ /**
+ * This signal is raised when a slave of type @p protocol deals
+ * with @p host for the first time.
+ *
+ * Your application can use this signal to make some last minute
+ * configuration changes with setConfigData based on the
+ * host.
+ */
+ void configNeeded(const TQString &protocol, const TQString &host);
+ protected:
+ SlaveConfig();
+ static SlaveConfig *_self;
+ SlaveConfigPrivate *d;
+ };
+}
+
+#endif
diff --git a/tdeio/tdeio/slaveinterface.cpp b/tdeio/tdeio/slaveinterface.cpp
new file mode 100644
index 000000000..40b66c47a
--- /dev/null
+++ b/tdeio/tdeio/slaveinterface.cpp
@@ -0,0 +1,550 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdeio/slaveinterface.h"
+#include "tdeio/slavebase.h"
+#include "tdeio/connection.h"
+#include <errno.h>
+#include <assert.h>
+#include <kdebug.h>
+#include <stdlib.h>
+#include <sys/time.h>
+#include <unistd.h>
+#include <signal.h>
+#include <tdeio/observer.h>
+#include <kapplication.h>
+#include <dcopclient.h>
+#include <time.h>
+#include <tqtimer.h>
+
+using namespace TDEIO;
+
+
+TQDataStream &operator <<(TQDataStream &s, const TDEIO::UDSEntry &e )
+{
+ // On 32-bit platforms we send UDS_SIZE with UDS_SIZE_LARGE in front
+ // of it to carry the 32 msb. We can't send a 64 bit UDS_SIZE because
+ // that would break the compatibility of the wire-protocol with KDE 2.
+ // We do the same on 64-bit platforms in case we run in a mixed 32/64bit
+ // environment.
+
+ TQ_UINT32 size = 0;
+ TDEIO::UDSEntry::ConstIterator it = e.begin();
+ for( ; it != e.end(); ++it )
+ {
+ size++;
+ if ((*it).m_uds == TDEIO::UDS_SIZE)
+ size++;
+ }
+ s << size;
+ it = e.begin();
+ for( ; it != e.end(); ++it )
+ {
+ if ((*it).m_uds == TDEIO::UDS_SIZE)
+ {
+ TDEIO::UDSAtom a;
+ a.m_uds = TDEIO::UDS_SIZE_LARGE;
+ a.m_long = (*it).m_long >> 32;
+ s << a;
+ }
+ s << *it;
+ }
+ return s;
+}
+
+TQDataStream &operator >>(TQDataStream &s, TDEIO::UDSEntry &e )
+{
+ e.clear();
+ TQ_UINT32 size;
+ s >> size;
+
+ // On 32-bit platforms we send UDS_SIZE with UDS_SIZE_LARGE in front
+ // of it to carry the 32 msb. We can't send a 64 bit UDS_SIZE because
+ // that would break the compatibility of the wire-protocol with KDE 2.
+ // We do the same on 64-bit platforms in case we run in a mixed 32/64bit
+ // environment.
+ TQ_LLONG msb = 0;
+ for(TQ_UINT32 i = 0; i < size; i++)
+ {
+ TDEIO::UDSAtom a;
+ s >> a;
+ if (a.m_uds == TDEIO::UDS_SIZE_LARGE)
+ {
+ msb = a.m_long;
+ }
+ else
+ {
+ if (a.m_uds == TDEIO::UDS_SIZE)
+ {
+ if (a.m_long < 0)
+ a.m_long += (TQ_LLONG) 1 << 32;
+ a.m_long += msb << 32;
+ }
+ e.append(a);
+ msb = 0;
+ }
+ }
+ return s;
+}
+
+static const unsigned int max_nums = 8;
+
+class TDEIO::SlaveInterfacePrivate
+{
+public:
+ SlaveInterfacePrivate() {
+ slave_calcs_speed = false;
+ start_time.tv_sec = 0;
+ start_time.tv_usec = 0;
+ last_time = 0;
+ nums = 0;
+ filesize = 0;
+ offset = 0;
+ }
+ bool slave_calcs_speed;
+ struct timeval start_time;
+ uint nums;
+ long times[max_nums];
+ TDEIO::filesize_t sizes[max_nums];
+ size_t last_time;
+ TDEIO::filesize_t filesize, offset;
+
+ TQTimer speed_timer;
+};
+
+//////////////
+
+SlaveInterface::SlaveInterface( Connection * connection )
+{
+ m_pConnection = connection;
+ m_progressId = 0;
+
+ d = new SlaveInterfacePrivate;
+ connect(&d->speed_timer, TQT_SIGNAL(timeout()), TQT_SLOT(calcSpeed()));
+}
+
+SlaveInterface::~SlaveInterface()
+{
+ // Note: no kdDebug() here (scheduler is deleted very late)
+ m_pConnection = 0; // a bit like the "wasDeleted" of TQObject...
+
+ delete d;
+}
+
+static TDEIO::filesize_t readFilesize_t(TQDataStream &stream)
+{
+ TDEIO::filesize_t result;
+ unsigned long ul;
+ stream >> ul;
+ result = ul;
+ if (stream.atEnd())
+ return result;
+ stream >> ul;
+ result += ((TDEIO::filesize_t)ul) << 32;
+ return result;
+}
+
+
+bool SlaveInterface::dispatch()
+{
+ assert( m_pConnection );
+
+ int cmd;
+ TQByteArray data;
+
+ if (m_pConnection->read( &cmd, data ) == -1)
+ return false;
+
+ return dispatch( cmd, data );
+}
+
+void SlaveInterface::calcSpeed()
+{
+ if (d->slave_calcs_speed) {
+ d->speed_timer.stop();
+ return;
+ }
+
+ struct timeval tv;
+ gettimeofday(&tv, 0);
+
+ long diff = ((tv.tv_sec - d->start_time.tv_sec) * 1000000 +
+ tv.tv_usec - d->start_time.tv_usec) / 1000;
+ if (diff - d->last_time >= 900) {
+ d->last_time = diff;
+ if (d->nums == max_nums) {
+ // let's hope gcc can optimize that well enough
+ // otherwise I'd try memcpy :)
+ for (unsigned int i = 1; i < max_nums; ++i) {
+ d->times[i-1] = d->times[i];
+ d->sizes[i-1] = d->sizes[i];
+ }
+ d->nums--;
+ }
+ d->times[d->nums] = diff;
+ d->sizes[d->nums++] = d->filesize - d->offset;
+
+ TDEIO::filesize_t lspeed = 1000 * (d->sizes[d->nums-1] - d->sizes[0]) / (d->times[d->nums-1] - d->times[0]);
+
+// kdDebug() << "proceeed " << (long)d->filesize << " " << diff << " "
+// << long(d->sizes[d->nums-1] - d->sizes[0]) << " "
+// << d->times[d->nums-1] - d->times[0] << " "
+// << long(lspeed) << " " << double(d->filesize) / diff
+// << " " << convertSize(lspeed) << " "
+// << convertSize(long(double(d->filesize) / diff) * 1000) << " "
+// << endl ;
+
+ if (!lspeed) {
+ d->nums = 1;
+ d->times[0] = diff;
+ d->sizes[0] = d->filesize - d->offset;
+ }
+ emit speed(lspeed);
+ }
+}
+
+bool SlaveInterface::dispatch( int _cmd, const TQByteArray &rawdata )
+{
+ //kdDebug(7007) << "dispatch " << _cmd << endl;
+
+ TQDataStream stream( rawdata, IO_ReadOnly );
+
+ TQString str1;
+ TQ_INT32 i;
+ TQ_INT8 b;
+ TQ_UINT32 ul;
+
+ switch( _cmd ) {
+ case MSG_DATA:
+ emit data( rawdata );
+ break;
+ case MSG_DATA_REQ:
+ emit dataReq();
+ break;
+ case MSG_FINISHED:
+ //kdDebug(7007) << "Finished [this = " << this << "]" << endl;
+ d->offset = 0;
+ d->speed_timer.stop();
+ emit finished();
+ break;
+ case MSG_STAT_ENTRY:
+ {
+ UDSEntry entry;
+ stream >> entry;
+ emit statEntry(entry);
+ }
+ break;
+ case MSG_LIST_ENTRIES:
+ {
+ TQ_UINT32 count;
+ stream >> count;
+
+ UDSEntryList list;
+ UDSEntry entry;
+ for (uint i = 0; i < count; i++) {
+ stream >> entry;
+ list.append(entry);
+ }
+ emit listEntries(list);
+
+ }
+ break;
+ case MSG_RESUME: // From the put job
+ {
+ d->offset = readFilesize_t(stream);
+ emit canResume( d->offset );
+ }
+ break;
+ case MSG_CANRESUME: // From the get job
+ d->filesize = d->offset;
+ emit canResume(0); // the arg doesn't matter
+ break;
+ case MSG_ERROR:
+ stream >> i >> str1;
+ kdDebug(7007) << "error " << i << " " << str1 << endl;
+ emit error( i, str1 );
+ break;
+ case MSG_SLAVE_STATUS:
+ {
+ pid_t pid;
+ TQCString protocol;
+ stream >> pid >> protocol >> str1 >> b;
+ emit slaveStatus(pid, protocol, str1, (b != 0));
+ }
+ break;
+ case MSG_CONNECTED:
+ emit connected();
+ break;
+
+ case INF_TOTAL_SIZE:
+ {
+ TDEIO::filesize_t size = readFilesize_t(stream);
+ gettimeofday(&d->start_time, 0);
+ d->last_time = 0;
+ d->filesize = d->offset;
+ d->sizes[0] = d->filesize - d->offset;
+ d->times[0] = 0;
+ d->nums = 1;
+ d->speed_timer.start(1000);
+ d->slave_calcs_speed = false;
+ emit totalSize( size );
+ }
+ break;
+ case INF_PROCESSED_SIZE:
+ {
+ TDEIO::filesize_t size = readFilesize_t(stream);
+ emit processedSize( size );
+ d->filesize = size;
+ }
+ break;
+ case INF_SPEED:
+ stream >> ul;
+ d->slave_calcs_speed = true;
+ d->speed_timer.stop();
+
+ emit speed( ul );
+ break;
+ case INF_GETTING_FILE:
+ break;
+ case INF_ERROR_PAGE:
+ emit errorPage();
+ break;
+ case INF_REDIRECTION:
+ {
+ KURL url;
+ stream >> url;
+
+ emit redirection( url );
+ }
+ break;
+ case INF_MIME_TYPE:
+ stream >> str1;
+
+ emit mimeType( str1 );
+ if (!m_pConnection->suspended())
+ m_pConnection->sendnow( CMD_NONE, TQByteArray() );
+ break;
+ case INF_WARNING:
+ stream >> str1;
+
+ emit warning( str1 );
+ break;
+ case INF_NEED_PASSWD: {
+ AuthInfo info;
+ stream >> info;
+ openPassDlg( info );
+ break;
+ }
+ case INF_MESSAGEBOX: {
+ kdDebug(7007) << "needs a msg box" << endl;
+ TQString text, caption, buttonYes, buttonNo, dontAskAgainName;
+ int type;
+ stream >> type >> text >> caption >> buttonYes >> buttonNo;
+ if (stream.atEnd())
+ messageBox(type, text, caption, buttonYes, buttonNo);
+ else {
+ stream >> dontAskAgainName;
+ messageBox(type, text, caption, buttonYes, buttonNo, dontAskAgainName);
+ }
+ break;
+ }
+ case INF_INFOMESSAGE: {
+ TQString msg;
+ stream >> msg;
+ infoMessage(msg);
+ break;
+ }
+ case INF_META_DATA: {
+ MetaData meta_data;
+ stream >> meta_data;
+ metaData(meta_data);
+ break;
+ }
+ case INF_LOCALURL: {
+ TQ_INT8 islocal;
+ KURL url;
+ stream >> islocal >> url;
+ emit localURL( url, islocal );
+ break;
+ }
+ case MSG_NET_REQUEST: {
+ TQString host;
+ TQString slaveid;
+ stream >> host >> slaveid;
+ requestNetwork(host, slaveid);
+ break;
+ }
+ case MSG_NET_DROP: {
+ TQString host;
+ TQString slaveid;
+ stream >> host >> slaveid;
+ dropNetwork(host, slaveid);
+ break;
+ }
+ case MSG_NEED_SUBURL_DATA: {
+ emit needSubURLData();
+ break;
+ }
+ case MSG_AUTH_KEY: {
+ bool keep;
+ TQCString key, group;
+ stream >> key >> group >> keep;
+ kdDebug(7007) << "Got auth-key: " << key << endl
+ << " group-key: " << group << endl
+ << " keep password: " << keep << endl;
+ emit authorizationKey( key, group, keep );
+ break;
+ }
+ case MSG_DEL_AUTH_KEY: {
+ TQCString key;
+ stream >> key;
+ kdDebug(7007) << "Delete auth-key: " << key << endl;
+ emit delAuthorization( key );
+ }
+ default:
+ kdWarning(7007) << "Slave sends unknown command (" << _cmd << "), dropping slave" << endl;
+ return false;
+ }
+ return true;
+}
+
+void SlaveInterface::setOffset( TDEIO::filesize_t o)
+{
+ d->offset = o;
+}
+
+TDEIO::filesize_t SlaveInterface::offset() const { return d->offset; }
+
+void SlaveInterface::requestNetwork(const TQString &host, const TQString &slaveid)
+{
+ kdDebug(7007) << "requestNetwork " << host << slaveid << endl;
+ TQByteArray packedArgs;
+ TQDataStream stream( packedArgs, IO_WriteOnly );
+ stream << true;
+ m_pConnection->sendnow( INF_NETWORK_STATUS, packedArgs );
+}
+
+void SlaveInterface::dropNetwork(const TQString &host, const TQString &slaveid)
+{
+ kdDebug(7007) << "dropNetwork " << host << slaveid << endl;
+}
+
+void SlaveInterface::sendResumeAnswer( bool resume )
+{
+ kdDebug(7007) << "SlaveInterface::sendResumeAnswer ok for resuming :" << resume << endl;
+ m_pConnection->sendnow( resume ? CMD_RESUMEANSWER : CMD_NONE, TQByteArray() );
+}
+
+void SlaveInterface::openPassDlg( const TQString& prompt, const TQString& user, bool readOnly )
+{
+ AuthInfo info;
+ info.prompt = prompt;
+ info.username = user;
+ info.readOnly = readOnly;
+ openPassDlg( info );
+}
+
+void SlaveInterface::openPassDlg( const TQString& prompt, const TQString& user,
+ const TQString& caption, const TQString& comment,
+ const TQString& label, bool readOnly )
+{
+ AuthInfo info;
+ info.prompt = prompt;
+ info.username = user;
+ info.caption = caption;
+ info.comment = comment;
+ info.commentLabel = label;
+ info.readOnly = readOnly;
+ openPassDlg( info );
+}
+
+void SlaveInterface::openPassDlg( AuthInfo& info )
+{
+ kdDebug(7007) << "SlaveInterface::openPassDlg: "
+ << "User= " << info.username
+ << ", Message= " << info.prompt << endl;
+ bool result = Observer::self()->openPassDlg( info );
+ if ( m_pConnection )
+ {
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly );
+ if ( result )
+ {
+ stream << info;
+ kdDebug(7007) << "SlaveInterface:::openPassDlg got: "
+ << "User= " << info.username
+ << ", Password= [hidden]" << endl;
+ m_pConnection->sendnow( CMD_USERPASS, data );
+ }
+ else
+ m_pConnection->sendnow( CMD_NONE, data );
+ }
+}
+
+void SlaveInterface::messageBox( int type, const TQString &text, const TQString &_caption,
+ const TQString &buttonYes, const TQString &buttonNo )
+{
+ messageBox( type, text, _caption, buttonYes, buttonNo, TQString::null );
+}
+
+void SlaveInterface::messageBox( int type, const TQString &text, const TQString &_caption,
+ const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName )
+{
+ kdDebug(7007) << "messageBox " << type << " " << text << " - " << _caption << " " << dontAskAgainName << endl;
+ TQByteArray packedArgs;
+ TQDataStream stream( packedArgs, IO_WriteOnly );
+
+ TQString caption( _caption );
+ if ( type == TDEIO::SlaveBase::SSLMessageBox )
+ caption = TQString::fromUtf8(kapp->dcopClient()->appId()); // hack, see observer.cpp
+
+ emit needProgressId();
+ kdDebug(7007) << "SlaveInterface::messageBox m_progressId=" << m_progressId << endl;
+ TQGuardedPtr<SlaveInterface> me = this;
+ m_pConnection->suspend();
+ int result = Observer::/*self()->*/messageBox( m_progressId, type, text, caption, buttonYes, buttonNo, dontAskAgainName );
+ if ( me && m_pConnection ) // Don't do anything if deleted meanwhile
+ {
+ m_pConnection->resume();
+ kdDebug(7007) << this << " SlaveInterface result=" << result << endl;
+ stream << result;
+ m_pConnection->sendnow( CMD_MESSAGEBOXANSWER, packedArgs );
+ }
+}
+
+// No longer used.
+// Remove in KDE 4.0
+void SlaveInterface::sigpipe_handler(int)
+{
+ int saved_errno = errno;
+ // Using kdDebug from a signal handler is not a good idea.
+#ifndef NDEBUG
+ char msg[1000];
+ sprintf(msg, "*** SIGPIPE *** (ignored, pid = %ld)\n", (long) getpid());
+ write(2, msg, strlen(msg));
+#endif
+
+ // Do nothing.
+ // dispatch will return false and that will trigger ERR_SLAVE_DIED in slave.cpp
+ errno = saved_errno;
+}
+
+void SlaveInterface::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+#include "slaveinterface.moc"
diff --git a/tdeio/tdeio/slaveinterface.h b/tdeio/tdeio/slaveinterface.h
new file mode 100644
index 000000000..a8992ee65
--- /dev/null
+++ b/tdeio/tdeio/slaveinterface.h
@@ -0,0 +1,290 @@
+/* This file is part of the KDE project
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __kio_slaveinterface_h
+#define __kio_slaveinterface_h
+
+#include <unistd.h>
+#include <sys/types.h>
+
+#include <tqobject.h>
+
+#include <kurl.h>
+#include <tdeio/global.h>
+#include <tdeio/authinfo.h>
+#include <kdatastream.h>
+
+namespace TDEIO {
+
+class Connection;
+// better there is one ...
+class SlaveInterfacePrivate;
+
+ // Definition of enum Command has been moved to global.h
+
+ /**
+ * Identifiers for KIO informational messages.
+ */
+ enum Info {
+ INF_TOTAL_SIZE = 10,
+ INF_PROCESSED_SIZE = 11,
+ INF_SPEED,
+ INF_REDIRECTION = 20,
+ INF_MIME_TYPE = 21,
+ INF_ERROR_PAGE = 22,
+ INF_WARNING = 23,
+ INF_GETTING_FILE, // Deprecated
+ INF_NEED_PASSWD = 25,
+ INF_INFOMESSAGE,
+ INF_META_DATA,
+ INF_NETWORK_STATUS,
+ INF_MESSAGEBOX,
+ INF_LOCALURL
+ // add new ones here once a release is done, to avoid breaking binary compatibility
+ };
+
+ /**
+ * Identifiers for KIO data messages.
+ */
+ enum Message {
+ MSG_DATA = 100,
+ MSG_DATA_REQ,
+ MSG_ERROR,
+ MSG_CONNECTED,
+ MSG_FINISHED,
+ MSG_STAT_ENTRY,
+ MSG_LIST_ENTRIES,
+ MSG_RENAMED, // unused
+ MSG_RESUME,
+ MSG_SLAVE_STATUS,
+ MSG_SLAVE_ACK,
+ MSG_NET_REQUEST,
+ MSG_NET_DROP,
+ MSG_NEED_SUBURL_DATA,
+ MSG_CANRESUME,
+ MSG_AUTH_KEY, // deprecated.
+ MSG_DEL_AUTH_KEY // deprecated.
+ // add new ones here once a release is done, to avoid breaking binary compatibility
+ };
+
+/**
+ * There are two classes that specifies the protocol between application
+ * (TDEIO::Job) and tdeioslave. SlaveInterface is the class to use on the application
+ * end, SlaveBase is the one to use on the slave end.
+ *
+ * A call to foo() results in a call to slotFoo() on the other end.
+ */
+class TDEIO_EXPORT SlaveInterface : public TQObject
+{
+ Q_OBJECT
+
+public:
+ SlaveInterface( Connection *connection );
+ virtual ~SlaveInterface();
+
+ void setConnection( Connection* connection ) { m_pConnection = connection; }
+ Connection *connection() const { return m_pConnection; }
+
+ void setProgressId( int id ) { m_progressId = id; }
+ int progressId() const { return m_progressId; }
+
+ /** Send our answer to the MSG_RESUME (canResume) request
+ * (to tell the "put" job whether to resume or not)
+ */
+ void sendResumeAnswer( bool resume );
+
+ void setOffset( TDEIO::filesize_t offset );
+ TDEIO::filesize_t offset() const;
+
+signals:
+ ///////////
+ // Messages sent by the slave
+ ///////////
+
+ void data( const TQByteArray & );
+ void dataReq( );
+ void error( int , const TQString & );
+ void connected();
+ void finished();
+ void slaveStatus(pid_t, const TQCString &, const TQString &, bool);
+ void listEntries( const TDEIO::UDSEntryList& );
+ void statEntry( const TDEIO::UDSEntry& );
+ void needSubURLData();
+ void needProgressId();
+
+ void canResume( TDEIO::filesize_t ) ;
+
+ ///////////
+ // Info sent by the slave
+ //////////
+ void metaData( const TDEIO::MetaData & );
+ void totalSize( TDEIO::filesize_t ) ;
+ void processedSize( TDEIO::filesize_t ) ;
+ void redirection( const KURL& ) ;
+ void localURL( const KURL&, bool ) ;
+
+ void speed( unsigned long ) ;
+ void errorPage() ;
+ void mimeType( const TQString & ) ;
+ void warning( const TQString & ) ;
+ void infoMessage( const TQString & ) ;
+ void connectFinished();
+
+ /**
+ * @deprecated. Obsolete as of 3.1. Replaced by kpassword, a kded module.
+ */
+ void authorizationKey( const TQCString&, const TQCString&, bool );
+
+ /**
+ * @deprecated. Obsolete as of 3.1. Replaced by kpassword, a kded module.
+ */
+ void delAuthorization( const TQCString& grpkey );
+
+protected:
+ /////////////////
+ // Dispatching
+ ////////////////
+
+ virtual bool dispatch();
+ virtual bool dispatch( int _cmd, const TQByteArray &data );
+
+ /**
+ * Prompt the user for authrization info (login & password).
+ *
+ * Use this function to request authorization info from the
+ * the end user. For example to open an empty password dialog
+ * using default values:
+ *
+ * \code
+ * TDEIO::AuthInfo authInfo;
+ * bool result = openPassDlg( authInfo );
+ * if ( result )
+ * {
+ * printf( "Username: %s", result.username.latin1() );
+ * printf( "Username: %s", result.username.latin1() );
+ * }
+ * \endcode
+ *
+ * You can also pre-set some values like the username before hand
+ * if it is known as well as the comment and caption to be displayed:
+ *
+ * \code
+ * authInfo.comment= "Enter username and password to access acmeone";
+ * authInfo.caption= "Acme Password Dialog";
+ * authInfo.username= "Wily E. kaiody";
+ * bool result = openPassDlg( authInfo );
+ * if ( result )
+ * {
+ * printf( "Username: %s", result.username.latin1() );
+ * printf( "Username: %s", result.username.latin1() );
+ * }
+ * \endcode
+ *
+ * NOTE: A call to this function can also fail and result
+ * in a return value of @p false, if the UIServer could not
+ * be started for whatever reason.
+ *
+ * @param info See AuthInfo.
+ * @return true if user clicks on "OK", false otherwsie.
+ */
+ void openPassDlg( TDEIO::AuthInfo& info );
+
+ /**
+ * @deprecated. Use openPassDlg( AuthInfo& ) instead.
+ */
+ void openPassDlg( const TQString& prompt, const TQString& user,
+ const TQString& caption, const TQString& comment,
+ const TQString& label, bool readOnly ) KDE_DEPRECATED;
+
+ /**
+ * @deprecated. Use openPassDlg( AuthInfo& ) instead.
+ */
+ void openPassDlg( const TQString& prompt, const TQString& user, bool readOnly ) KDE_DEPRECATED;
+
+ void messageBox( int type, const TQString &text, const TQString &caption,
+ const TQString &buttonYes, const TQString &buttonNo );
+
+ /**
+ * @since 3.3
+ */
+ void messageBox( int type, const TQString &text, const TQString &caption,
+ const TQString &buttonYes, const TQString &buttonNo, const TQString &dontAskAgainName );
+
+ // I need to identify the slaves
+ void requestNetwork( const TQString &, const TQString &);
+ void dropNetwork( const TQString &, const TQString &);
+
+ /**
+ * @internal
+ * KDE 4.0: Remove
+ */
+ static void sigpipe_handler(int);
+
+protected slots:
+ void calcSpeed();
+
+protected:
+ Connection * m_pConnection;
+
+private:
+ int m_progressId;
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ SlaveInterfacePrivate *d;
+};
+
+}
+
+inline TQDataStream &operator >>(TQDataStream &s, TDEIO::UDSAtom &a )
+{
+ TQ_INT32 l;
+ s >> a.m_uds;
+
+ if ( a.m_uds & TDEIO::UDS_LONG ) {
+ s >> l;
+ a.m_long = l;
+ a.m_str = TQString::null;
+ } else if ( a.m_uds & TDEIO::UDS_STRING ) {
+ s >> a.m_str;
+ a.m_long = 0;
+ } else {} // DIE!
+ // assert( 0 );
+
+ return s;
+}
+
+inline TQDataStream &operator <<(TQDataStream &s, const TDEIO::UDSAtom &a )
+{
+ s << a.m_uds;
+
+ if ( a.m_uds & TDEIO::UDS_LONG )
+ s << (TQ_INT32) a.m_long;
+ else if ( a.m_uds & TDEIO::UDS_STRING )
+ s << a.m_str;
+ else {} // DIE!
+ // assert( 0 );
+
+ return s;
+}
+
+TDEIO_EXPORT TQDataStream &operator <<(TQDataStream &s, const TDEIO::UDSEntry &e );
+TDEIO_EXPORT TQDataStream &operator >>(TQDataStream &s, TDEIO::UDSEntry &e );
+
+#endif
diff --git a/kio/kio/statusbarprogress.cpp b/tdeio/tdeio/statusbarprogress.cpp
index 66517ca03..66517ca03 100644
--- a/kio/kio/statusbarprogress.cpp
+++ b/tdeio/tdeio/statusbarprogress.cpp
diff --git a/kio/kio/statusbarprogress.h b/tdeio/tdeio/statusbarprogress.h
index d1d591fbe..d1d591fbe 100644
--- a/kio/kio/statusbarprogress.h
+++ b/tdeio/tdeio/statusbarprogress.h
diff --git a/tdeio/tdeio/tcpslavebase.cpp b/tdeio/tdeio/tcpslavebase.cpp
new file mode 100644
index 000000000..2b7df9d7b
--- /dev/null
+++ b/tdeio/tdeio/tcpslavebase.cpp
@@ -0,0 +1,1343 @@
+/*
+ * $Id$
+ *
+ * Copyright (C) 2000 Alex Zepeda <zipzippy@sonic.net
+ * Copyright (C) 2001-2003 George Staikos <staikos@kde.org>
+ * Copyright (C) 2001 Dawit Alemayehu <adawit@kde.org>
+ *
+ * This file is part of the KDE project
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+
+#include <time.h>
+#include <netdb.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include <ksocks.h>
+#include <kdebug.h>
+#include <ksslall.h>
+#include <ksslcertdlg.h>
+#include <kmessagebox.h>
+#ifndef Q_WS_WIN //temporary
+#include <kresolver.h>
+#endif
+
+#include <klocale.h>
+#include <dcopclient.h>
+#include <tqcstring.h>
+#include <tqdatastream.h>
+
+#include <kapplication.h>
+
+#include <kprotocolmanager.h>
+#include <kde_file.h>
+
+#include "tdeio/tcpslavebase.h"
+
+using namespace TDEIO;
+
+class TCPSlaveBase::TcpSlaveBasePrivate
+{
+public:
+
+ TcpSlaveBasePrivate() : rblockSz(256), militantSSL(false), userAborted(false) {}
+ ~TcpSlaveBasePrivate() {}
+
+ KSSL *kssl;
+ bool usingTLS;
+ KSSLCertificateCache *cc;
+ TQString host;
+ TQString realHost;
+ TQString ip;
+ DCOPClient *dcc;
+ KSSLPKCS12 *pkcs;
+
+ int status;
+ int timeout;
+ int rblockSz; // Size for reading blocks in readLine()
+ bool block;
+ bool useSSLTunneling;
+ bool needSSLHandShake;
+ bool militantSSL; // If true, we just drop a connection silently
+ // if SSL certificate check fails in any way.
+ bool userAborted;
+ MetaData savedMetaData;
+};
+
+
+TCPSlaveBase::TCPSlaveBase(unsigned short int defaultPort,
+ const TQCString &protocol,
+ const TQCString &poolSocket,
+ const TQCString &appSocket)
+ :SlaveBase (protocol, poolSocket, appSocket),
+ m_iSock(-1),
+ m_iDefaultPort(defaultPort),
+ m_sServiceName(protocol),
+ fp(0)
+{
+ // We have to have two constructors, so don't add anything
+ // else in here. Put it in doConstructorStuff() instead.
+ doConstructorStuff();
+ m_bIsSSL = false;
+}
+
+TCPSlaveBase::TCPSlaveBase(unsigned short int defaultPort,
+ const TQCString &protocol,
+ const TQCString &poolSocket,
+ const TQCString &appSocket,
+ bool useSSL)
+ :SlaveBase (protocol, poolSocket, appSocket),
+ m_iSock(-1),
+ m_bIsSSL(useSSL),
+ m_iDefaultPort(defaultPort),
+ m_sServiceName(protocol),
+ fp(0)
+{
+ doConstructorStuff();
+ if (useSSL)
+ m_bIsSSL = initializeSSL();
+}
+
+// The constructor procedures go here now.
+void TCPSlaveBase::doConstructorStuff()
+{
+ d = new TcpSlaveBasePrivate;
+ d->kssl = 0L;
+ d->ip = "";
+ d->cc = 0L;
+ d->usingTLS = false;
+ d->dcc = 0L;
+ d->pkcs = 0L;
+ d->status = -1;
+ d->timeout = KProtocolManager::connectTimeout();
+ d->block = false;
+ d->useSSLTunneling = false;
+}
+
+TCPSlaveBase::~TCPSlaveBase()
+{
+ cleanSSL();
+ if (d->usingTLS) delete d->kssl;
+ if (d->dcc) delete d->dcc;
+ if (d->pkcs) delete d->pkcs;
+ delete d;
+}
+
+ssize_t TCPSlaveBase::write(const void *data, ssize_t len)
+{
+#ifdef Q_OS_UNIX
+ if ( (m_bIsSSL || d->usingTLS) && !d->useSSLTunneling )
+ {
+ if ( d->needSSLHandShake )
+ (void) doSSLHandShake( true );
+ return d->kssl->write(data, len);
+ }
+ return KSocks::self()->write(m_iSock, data, len);
+#else
+ return 0;
+#endif
+}
+
+ssize_t TCPSlaveBase::read(void *data, ssize_t len)
+{
+#ifdef Q_OS_UNIX
+ if ( (m_bIsSSL || d->usingTLS) && !d->useSSLTunneling )
+ {
+ if ( d->needSSLHandShake )
+ (void) doSSLHandShake( true );
+ return d->kssl->read(data, len);
+ }
+ return KSocks::self()->read(m_iSock, data, len);
+#else
+ return 0;
+#endif
+}
+
+
+void TCPSlaveBase::setBlockSize(int sz)
+{
+ if (sz <= 0)
+ sz = 1;
+
+ d->rblockSz = sz;
+}
+
+
+ssize_t TCPSlaveBase::readLine(char *data, ssize_t len)
+{
+// Optimization:
+// It's small, but it probably results in a gain on very high
+// speed connections. I moved 3 if statements out of the while loop
+// so that the while loop is as small as possible. (GS)
+
+ // let's not segfault!
+ if (!data)
+ return -1;
+
+ char tmpbuf[1024]; // 1kb temporary buffer for peeking
+ *data = 0;
+ ssize_t clen = 0;
+ char *buf = data;
+ int rc = 0;
+
+if ((m_bIsSSL || d->usingTLS) && !d->useSSLTunneling) { // SSL CASE
+ if ( d->needSSLHandShake )
+ (void) doSSLHandShake( true );
+
+ while (clen < len-1) {
+ rc = d->kssl->pending();
+ if (rc > 0) { // Read a chunk
+ int bytes = rc;
+ if (bytes > d->rblockSz)
+ bytes = d->rblockSz;
+
+ rc = d->kssl->peek(tmpbuf, bytes);
+ if (rc <= 0) {
+ // FIXME: this doesn't cover rc == 0 case
+ return -1;
+ }
+
+ bytes = rc; // in case it contains no \n
+ for (int i = 0; i < rc; i++) {
+ if (tmpbuf[i] == '\n') {
+ bytes = i+1;
+ break;
+ }
+ }
+
+ if (bytes+clen >= len) // don't read too much!
+ bytes = len - clen - 1;
+
+ rc = d->kssl->read(buf, bytes);
+ if (rc > 0) {
+ clen += rc;
+ buf += (rc-1);
+ if (*buf++ == '\n')
+ break;
+ } else {
+ // FIXME: different case if rc == 0;
+ return -1;
+ }
+ } else { // Read a byte
+ rc = d->kssl->read(buf, 1);
+ if (rc <= 0) {
+ return -1;
+ // hm rc = 0 then
+ // SSL_read says to call SSL_get_error to see if
+ // this was an error. FIXME
+ } else {
+ clen++;
+ if (*buf++ == '\n')
+ break;
+ }
+ }
+ }
+} else { // NON SSL CASE
+ while (clen < len-1) {
+#ifdef Q_OS_UNIX
+ rc = KSocks::self()->read(m_iSock, buf, 1);
+#else
+ rc = 0;
+#endif
+ if (rc <= 0) {
+ // FIXME: this doesn't cover rc == 0 case
+ return -1;
+ } else {
+ clen++;
+ if (*buf++ == '\n')
+ break;
+ }
+ }
+}
+
+ // Both cases fall through to here
+ *buf = 0;
+return clen;
+}
+
+unsigned short int TCPSlaveBase::port(unsigned short int _p)
+{
+ unsigned short int p = _p;
+
+ if (_p <= 0)
+ {
+ p = m_iDefaultPort;
+ }
+
+ return p;
+}
+
+// This function is simply a wrapper to establish the connection
+// to the server. It's a bit more complicated than ::connect
+// because we first have to check to see if the user specified
+// a port, and if so use it, otherwise we check to see if there
+// is a port specified in /etc/services, and if so use that
+// otherwise as a last resort use the supplied default port.
+bool TCPSlaveBase::connectToHost( const TQString &host,
+ unsigned int _port,
+ bool sendError )
+{
+#ifdef Q_OS_UNIX
+ unsigned short int p;
+ KExtendedSocket ks;
+
+ d->userAborted = false;
+
+ // - leaving SSL - warn before we even connect
+ if (metaData("main_frame_request") == "TRUE" &&
+ metaData("ssl_activate_warnings") == "TRUE" &&
+ metaData("ssl_was_in_use") == "TRUE" &&
+ !m_bIsSSL) {
+ KSSLSettings kss;
+ if (kss.warnOnLeave()) {
+ int result = messageBox( i18n("You are about to leave secure "
+ "mode. Transmissions will no "
+ "longer be encrypted.\nThis "
+ "means that a third party could "
+ "observe your data in transit."),
+ WarningContinueCancel,
+ i18n("Security Information"),
+ i18n("C&ontinue Loading"), TQString::null,
+ "WarnOnLeaveSSLMode" );
+
+ // Move this setting into KSSL instead
+ TDEConfig *config = new TDEConfig("tdeioslaverc");
+ config->setGroup("Notification Messages");
+
+ if (!config->readBoolEntry("WarnOnLeaveSSLMode", true)) {
+ config->deleteEntry("WarnOnLeaveSSLMode");
+ config->sync();
+ kss.setWarnOnLeave(false);
+ kss.save();
+ }
+ delete config;
+
+ if ( result == KMessageBox::Cancel ) {
+ d->userAborted = true;
+ return false;
+ }
+ }
+ }
+
+ d->status = -1;
+ d->host = host;
+ d->needSSLHandShake = m_bIsSSL;
+ p = port(_port);
+ ks.setAddress(host, p);
+ if ( d->timeout > -1 )
+ ks.setTimeout( d->timeout );
+
+ if (ks.connect() < 0)
+ {
+ d->status = ks.status();
+ if ( sendError )
+ {
+ if (d->status == IO_LookupError)
+ error( ERR_UNKNOWN_HOST, host);
+ else if ( d->status != -1 )
+ error( ERR_COULD_NOT_CONNECT, host);
+ }
+ return false;
+ }
+
+ m_iSock = ks.fd();
+
+ // store the IP for later
+ const TDESocketAddress *sa = ks.peerAddress();
+ if (sa)
+ d->ip = sa->nodeName();
+ else
+ d->ip = "";
+
+ ks.release(); // KExtendedSocket no longer applicable
+
+ if ( d->block != ks.blockingMode() )
+ ks.setBlockingMode( d->block );
+
+ m_iPort=p;
+
+ if (m_bIsSSL && !d->useSSLTunneling) {
+ if ( !doSSLHandShake( sendError ) )
+ return false;
+ }
+ else
+ setMetaData("ssl_in_use", "FALSE");
+
+ // Since we want to use stdio on the socket,
+ // we must fdopen it to get a file pointer,
+ // if it fails, close everything up
+ if ((fp = KDE_fdopen(m_iSock, "w+")) == 0) {
+ closeDescriptor();
+ return false;
+ }
+
+ return true;
+#else //!Q_OS_UNIX
+ return false;
+#endif //Q_OS_UNIX
+}
+
+void TCPSlaveBase::closeDescriptor()
+{
+ stopTLS();
+ if (fp) {
+ fclose(fp);
+ fp=0;
+ m_iSock=-1;
+ if (m_bIsSSL)
+ d->kssl->close();
+ }
+ if (m_iSock != -1) {
+ close(m_iSock);
+ m_iSock=-1;
+ }
+ d->ip = "";
+ d->host = "";
+}
+
+bool TCPSlaveBase::initializeSSL()
+{
+ if (m_bIsSSL) {
+ if (KSSL::doesSSLWork()) {
+ d->kssl = new KSSL;
+ return true;
+ }
+ }
+return false;
+}
+
+void TCPSlaveBase::cleanSSL()
+{
+ delete d->cc;
+
+ if (m_bIsSSL) {
+ delete d->kssl;
+ d->kssl = 0;
+ }
+ d->militantSSL = false;
+}
+
+bool TCPSlaveBase::atEnd()
+{
+ return feof(fp);
+}
+
+int TCPSlaveBase::startTLS()
+{
+ if (d->usingTLS || d->useSSLTunneling || m_bIsSSL || !KSSL::doesSSLWork())
+ return false;
+
+ d->kssl = new KSSL(false);
+ if (!d->kssl->TLSInit()) {
+ delete d->kssl;
+ return -1;
+ }
+
+ if ( !d->realHost.isEmpty() )
+ {
+ kdDebug(7029) << "Setting real hostname: " << d->realHost << endl;
+ d->kssl->setPeerHost(d->realHost);
+ } else {
+ kdDebug(7029) << "Setting real hostname: " << d->host << endl;
+ d->kssl->setPeerHost(d->host);
+ }
+
+ if (hasMetaData("ssl_session_id")) {
+ KSSLSession *s = KSSLSession::fromString(metaData("ssl_session_id"));
+ if (s) {
+ d->kssl->setSession(s);
+ delete s;
+ }
+ }
+ certificatePrompt();
+
+ int rc = d->kssl->connect(m_iSock);
+ if (rc < 0) {
+ delete d->kssl;
+ return -2;
+ }
+
+ setMetaData("ssl_session_id", d->kssl->session()->toString());
+
+ d->usingTLS = true;
+ setMetaData("ssl_in_use", "TRUE");
+
+ if (!d->kssl->reusingSession()) {
+ rc = verifyCertificate();
+ if (rc != 1) {
+ setMetaData("ssl_in_use", "FALSE");
+ d->usingTLS = false;
+ delete d->kssl;
+ return -3;
+ }
+ }
+
+ d->savedMetaData = mOutgoingMetaData;
+ return (d->usingTLS ? 1 : 0);
+}
+
+
+void TCPSlaveBase::stopTLS()
+{
+ if (d->usingTLS) {
+ delete d->kssl;
+ d->usingTLS = false;
+ setMetaData("ssl_in_use", "FALSE");
+ }
+}
+
+
+void TCPSlaveBase::setSSLMetaData() {
+ if (!(d->usingTLS || d->useSSLTunneling || m_bIsSSL))
+ return;
+
+ mOutgoingMetaData = d->savedMetaData;
+}
+
+
+bool TCPSlaveBase::canUseTLS()
+{
+ if (m_bIsSSL || d->needSSLHandShake || !KSSL::doesSSLWork())
+ return false;
+
+ KSSLSettings kss;
+ return kss.tlsv1();
+}
+
+
+void TCPSlaveBase::certificatePrompt()
+{
+TQString certname; // the cert to use this session
+bool send = false, prompt = false, save = false, forcePrompt = false;
+KSSLCertificateHome::KSSLAuthAction aa;
+
+ setMetaData("ssl_using_client_cert", "FALSE"); // we change this if needed
+
+ if (metaData("ssl_no_client_cert") == "TRUE") return;
+ forcePrompt = (metaData("ssl_force_cert_prompt") == "TRUE");
+
+ // Delete the old cert since we're certainly done with it now
+ if (d->pkcs) {
+ delete d->pkcs;
+ d->pkcs = NULL;
+ }
+
+ if (!d->kssl) return;
+
+ // Look for a general certificate
+ if (!forcePrompt) {
+ certname = KSSLCertificateHome::getDefaultCertificateName(&aa);
+ switch(aa) {
+ case KSSLCertificateHome::AuthSend:
+ send = true; prompt = false;
+ break;
+ case KSSLCertificateHome::AuthDont:
+ send = false; prompt = false;
+ certname = TQString::null;
+ break;
+ case KSSLCertificateHome::AuthPrompt:
+ send = false; prompt = true;
+ break;
+ default:
+ break;
+ }
+ }
+
+ TQString ourHost;
+ if (!d->realHost.isEmpty()) {
+ ourHost = d->realHost;
+ } else {
+ ourHost = d->host;
+ }
+
+ // Look for a certificate on a per-host basis as an override
+ TQString tmpcn = KSSLCertificateHome::getDefaultCertificateName(ourHost, &aa);
+ if (aa != KSSLCertificateHome::AuthNone) { // we must override
+ switch (aa) {
+ case KSSLCertificateHome::AuthSend:
+ send = true;
+ prompt = false;
+ certname = tmpcn;
+ break;
+ case KSSLCertificateHome::AuthDont:
+ send = false;
+ prompt = false;
+ certname = TQString::null;
+ break;
+ case KSSLCertificateHome::AuthPrompt:
+ send = false;
+ prompt = true;
+ certname = tmpcn;
+ break;
+ default:
+ break;
+ }
+ }
+
+ // Finally, we allow the application to override anything.
+ if (hasMetaData("ssl_demand_certificate")) {
+ certname = metaData("ssl_demand_certificate");
+ if (!certname.isEmpty()) {
+ forcePrompt = false;
+ prompt = false;
+ send = true;
+ }
+ }
+
+ if (certname.isEmpty() && !prompt && !forcePrompt) return;
+
+ // Ok, we're supposed to prompt the user....
+ if (prompt || forcePrompt) {
+ TQStringList certs = KSSLCertificateHome::getCertificateList();
+
+ for (TQStringList::Iterator it = certs.begin(); it != certs.end(); ++it) {
+ KSSLPKCS12 *pkcs = KSSLCertificateHome::getCertificateByName(*it);
+ if (pkcs && (!pkcs->getCertificate() ||
+ !pkcs->getCertificate()->x509V3Extensions().certTypeSSLClient())) {
+ certs.remove(*it);
+ }
+ delete pkcs;
+ }
+
+ if (certs.isEmpty()) return; // we had nothing else, and prompt failed
+
+ if (!d->dcc) {
+ d->dcc = new DCOPClient;
+ d->dcc->attach();
+ if (!d->dcc->isApplicationRegistered("tdeio_uiserver")) {
+ TDEApplication::startServiceByDesktopPath("tdeio_uiserver.desktop",
+ TQStringList() );
+ }
+ }
+
+ TQByteArray data, retval;
+ TQCString rettype;
+ TQDataStream arg(data, IO_WriteOnly);
+ arg << ourHost;
+ arg << certs;
+ arg << metaData("window-id").toInt();
+ bool rc = d->dcc->call("tdeio_uiserver", "UIServer",
+ "showSSLCertDialog(TQString, TQStringList,int)",
+ data, rettype, retval);
+
+ if (rc && rettype == "KSSLCertDlgRet") {
+ TQDataStream retStream(retval, IO_ReadOnly);
+ KSSLCertDlgRet drc;
+ retStream >> drc;
+ if (drc.ok) {
+ send = drc.send;
+ save = drc.save;
+ certname = drc.choice;
+ }
+ }
+ }
+
+ // The user may have said to not send the certificate,
+ // but to save the choice
+ if (!send) {
+ if (save) {
+ KSSLCertificateHome::setDefaultCertificate(certname, ourHost,
+ false, false);
+ }
+ return;
+ }
+
+ // We're almost committed. If we can read the cert, we'll send it now.
+ KSSLPKCS12 *pkcs = KSSLCertificateHome::getCertificateByName(certname);
+ if (!pkcs && KSSLCertificateHome::hasCertificateByName(certname)) { // We need the password
+ TDEIO::AuthInfo ai;
+ bool first = true;
+ do {
+ ai.prompt = i18n("Enter the certificate password:");
+ ai.caption = i18n("SSL Certificate Password");
+ ai.url.setProtocol("kssl");
+ ai.url.setHost(certname);
+ ai.username = certname;
+ ai.keepPassword = true;
+
+ bool showprompt;
+ if (first)
+ showprompt = !checkCachedAuthentication(ai);
+ else
+ showprompt = true;
+ if (showprompt) {
+ if (!openPassDlg(ai, first ? TQString::null :
+ i18n("Unable to open the certificate. Try a new password?")))
+ break;
+ }
+
+ first = false;
+ pkcs = KSSLCertificateHome::getCertificateByName(certname, ai.password);
+ } while (!pkcs);
+
+ }
+
+ // If we could open the certificate, let's send it
+ if (pkcs) {
+ if (!d->kssl->setClientCertificate(pkcs)) {
+ messageBox(Information, i18n("The procedure to set the "
+ "client certificate for the session "
+ "failed."), i18n("SSL"));
+ delete pkcs; // we don't need this anymore
+ pkcs = 0L;
+ } else {
+ kdDebug(7029) << "Client SSL certificate is being used." << endl;
+ setMetaData("ssl_using_client_cert", "TRUE");
+ if (save) {
+ KSSLCertificateHome::setDefaultCertificate(certname, ourHost,
+ true, false);
+ }
+ }
+ d->pkcs = pkcs;
+ }
+}
+
+
+
+bool TCPSlaveBase::usingTLS() const
+{
+ return d->usingTLS;
+}
+
+// ### remove this for KDE4 (misses const):
+bool TCPSlaveBase::usingTLS()
+{
+ return d->usingTLS;
+}
+
+
+// Returns 0 for failed verification, -1 for rejected cert and 1 for ok
+int TCPSlaveBase::verifyCertificate()
+{
+ int rc = 0;
+ bool permacache = false;
+ bool isChild = false;
+ bool _IPmatchesCN = false;
+ int result;
+ bool doAddHost = false;
+ TQString ourHost;
+
+ if (!d->realHost.isEmpty())
+ ourHost = d->realHost;
+ else ourHost = d->host;
+
+ TQString theurl = TQString(m_sServiceName)+"://"+ourHost+":"+TQString::number(m_iPort);
+
+ if (!hasMetaData("ssl_militant") || metaData("ssl_militant") == "FALSE")
+ d->militantSSL = false;
+ else if (metaData("ssl_militant") == "TRUE")
+ d->militantSSL = true;
+
+ if (!d->cc) d->cc = new KSSLCertificateCache;
+
+ KSSLCertificate& pc = d->kssl->peerInfo().getPeerCertificate();
+
+ KSSLCertificate::KSSLValidationList ksvl = pc.validateVerbose(KSSLCertificate::SSLServer);
+
+ _IPmatchesCN = d->kssl->peerInfo().certMatchesAddress();
+ if (!_IPmatchesCN) {
+#ifndef Q_WS_WIN //temporary
+ KNetwork::KResolverResults res = KNetwork::KResolver::resolve(d->kssl->peerInfo().peerHost(), "80", KNetwork::KResolver::CanonName);
+ if (!res.isEmpty()) {
+ TQString old = d->kssl->peerInfo().peerHost();
+ d->kssl->peerInfo().setPeerHost(res[0].canonicalName());
+ _IPmatchesCN = d->kssl->peerInfo().certMatchesAddress();
+ if (!_IPmatchesCN) {
+ d->kssl->peerInfo().setPeerHost(old);
+ }
+ }
+#endif
+ if (!_IPmatchesCN && !d->militantSSL) { // force this if the user wants it
+ if (d->cc->getHostList(pc).contains(ourHost)) {
+ _IPmatchesCN = true;
+ }
+ }
+ }
+
+ if (!_IPmatchesCN) {
+ ksvl << KSSLCertificate::InvalidHost;
+ }
+
+ KSSLCertificate::KSSLValidation ksv = KSSLCertificate::Ok;
+ if (!ksvl.isEmpty())
+ ksv = ksvl.first();
+
+ /* Setting the various bits of meta-info that will be needed. */
+ setMetaData("ssl_cipher", d->kssl->connectionInfo().getCipher());
+ setMetaData("ssl_cipher_desc",
+ d->kssl->connectionInfo().getCipherDescription());
+ setMetaData("ssl_cipher_version",
+ d->kssl->connectionInfo().getCipherVersion());
+ setMetaData("ssl_cipher_used_bits",
+ TQString::number(d->kssl->connectionInfo().getCipherUsedBits()));
+ setMetaData("ssl_cipher_bits",
+ TQString::number(d->kssl->connectionInfo().getCipherBits()));
+ setMetaData("ssl_peer_ip", d->ip);
+ if (!d->realHost.isEmpty()) {
+ setMetaData("ssl_proxied", "true");
+ }
+
+ TQString errorStr;
+ for(KSSLCertificate::KSSLValidationList::ConstIterator it = ksvl.begin();
+ it != ksvl.end(); ++it)
+ {
+ errorStr += TQString::number(*it)+":";
+ }
+ setMetaData("ssl_cert_errors", errorStr);
+ setMetaData("ssl_peer_certificate", pc.toString());
+
+ if (pc.chain().isValid() && pc.chain().depth() > 1) {
+ TQString theChain;
+ TQPtrList<KSSLCertificate> chain = pc.chain().getChain();
+ chain.setAutoDelete(true);
+ for (KSSLCertificate *c = chain.first(); c; c = chain.next()) {
+ theChain += c->toString();
+ theChain += "\n";
+ }
+ setMetaData("ssl_peer_chain", theChain);
+ } else setMetaData("ssl_peer_chain", "");
+
+ setMetaData("ssl_cert_state", TQString::number(ksv));
+
+ if (ksv == KSSLCertificate::Ok) {
+ rc = 1;
+ setMetaData("ssl_action", "accept");
+ }
+
+ kdDebug(7029) << "SSL HTTP frame the parent? " << metaData("main_frame_request") << endl;
+ if (!hasMetaData("main_frame_request") || metaData("main_frame_request") == "TRUE") {
+ // Since we're the parent, we need to teach the child.
+ setMetaData("ssl_parent_ip", d->ip);
+ setMetaData("ssl_parent_cert", pc.toString());
+ // - Read from cache and see if there is a policy for this
+ KSSLCertificateCache::KSSLCertificatePolicy cp =
+ d->cc->getPolicyByCertificate(pc);
+
+ // - validation code
+ if (ksv != KSSLCertificate::Ok) {
+ if (d->militantSSL) {
+ return -1;
+ }
+
+ if (cp == KSSLCertificateCache::Unknown ||
+ cp == KSSLCertificateCache::Ambiguous) {
+ cp = KSSLCertificateCache::Prompt;
+ } else {
+ // A policy was already set so let's honor that.
+ permacache = d->cc->isPermanent(pc);
+ }
+
+ if (!_IPmatchesCN && cp == KSSLCertificateCache::Accept) {
+ cp = KSSLCertificateCache::Prompt;
+// ksv = KSSLCertificate::Ok;
+ }
+
+ // Precondition: cp is one of Reject, Accept or Prompt
+ switch (cp) {
+ case KSSLCertificateCache::Accept:
+ rc = 1;
+ setMetaData("ssl_action", "accept");
+ break;
+ case KSSLCertificateCache::Reject:
+ rc = -1;
+ setMetaData("ssl_action", "reject");
+ break;
+ case KSSLCertificateCache::Prompt:
+ {
+ do {
+ if (ksv == KSSLCertificate::InvalidHost) {
+ TQString msg = i18n("The IP address of the host %1 "
+ "does not match the one the "
+ "certificate was issued to.");
+ result = messageBox( WarningYesNoCancel,
+ msg.arg(ourHost),
+ i18n("Server Authentication"),
+ i18n("&Details"),
+ i18n("Co&ntinue") );
+ } else {
+ TQString msg = i18n("The server certificate failed the "
+ "authenticity test (%1).");
+ result = messageBox( WarningYesNoCancel,
+ msg.arg(ourHost),
+ i18n("Server Authentication"),
+ i18n("&Details"),
+ i18n("Co&ntinue") );
+ }
+
+ if (result == KMessageBox::Yes) {
+ if (!d->dcc) {
+ d->dcc = new DCOPClient;
+ d->dcc->attach();
+ if (!d->dcc->isApplicationRegistered("tdeio_uiserver")) {
+ TDEApplication::startServiceByDesktopPath("tdeio_uiserver.desktop",
+ TQStringList() );
+ }
+
+ }
+ TQByteArray data, ignore;
+ TQCString ignoretype;
+ TQDataStream arg(data, IO_WriteOnly);
+ arg << theurl << mOutgoingMetaData;
+ arg << metaData("window-id").toInt();
+ d->dcc->call("tdeio_uiserver", "UIServer",
+ "showSSLInfoDialog(TQString,TDEIO::MetaData,int)",
+ data, ignoretype, ignore);
+ }
+ } while (result == KMessageBox::Yes);
+
+ if (result == KMessageBox::No) {
+ setMetaData("ssl_action", "accept");
+ rc = 1;
+ cp = KSSLCertificateCache::Accept;
+ doAddHost = true;
+ result = messageBox( WarningYesNo,
+ i18n("Would you like to accept this "
+ "certificate forever without "
+ "being prompted?"),
+ i18n("Server Authentication"),
+ i18n("&Forever"),
+ i18n("&Current Sessions Only"));
+ if (result == KMessageBox::Yes)
+ permacache = true;
+ else
+ permacache = false;
+ } else {
+ setMetaData("ssl_action", "reject");
+ rc = -1;
+ cp = KSSLCertificateCache::Prompt;
+ }
+ break;
+ }
+ default:
+ kdDebug(7029) << "TCPSlaveBase/SSL error in cert code."
+ << "Please report this to kfm-devel@kde.org."
+ << endl;
+ break;
+ }
+ }
+
+
+ // - cache the results
+ d->cc->addCertificate(pc, cp, permacache);
+ if (doAddHost) d->cc->addHost(pc, ourHost);
+ } else { // Child frame
+ // - Read from cache and see if there is a policy for this
+ KSSLCertificateCache::KSSLCertificatePolicy cp =
+ d->cc->getPolicyByCertificate(pc);
+ isChild = true;
+
+ // Check the cert and IP to make sure they're the same
+ // as the parent frame
+ bool certAndIPTheSame = (d->ip == metaData("ssl_parent_ip") &&
+ pc.toString() == metaData("ssl_parent_cert"));
+
+ if (ksv == KSSLCertificate::Ok) {
+ if (certAndIPTheSame) { // success
+ rc = 1;
+ setMetaData("ssl_action", "accept");
+ } else {
+ /*
+ if (d->militantSSL) {
+ return -1;
+ }
+ result = messageBox(WarningYesNo,
+ i18n("The certificate is valid but does not appear to have been assigned to this server. Do you wish to continue loading?"),
+ i18n("Server Authentication"));
+ if (result == KMessageBox::Yes) { // success
+ rc = 1;
+ setMetaData("ssl_action", "accept");
+ } else { // fail
+ rc = -1;
+ setMetaData("ssl_action", "reject");
+ }
+ */
+ setMetaData("ssl_action", "accept");
+ rc = 1; // Let's accept this now. It's bad, but at least the user
+ // will see potential attacks in KDE3 with the pseudo-lock
+ // icon on the toolbar, and can investigate with the RMB
+ }
+ } else {
+ if (d->militantSSL) {
+ return -1;
+ }
+
+ if (cp == KSSLCertificateCache::Accept) {
+ if (certAndIPTheSame) { // success
+ rc = 1;
+ setMetaData("ssl_action", "accept");
+ } else { // fail
+ result = messageBox(WarningYesNo,
+ i18n("You have indicated that you wish to accept this certificate, but it is not issued to the server who is presenting it. Do you wish to continue loading?"),
+ i18n("Server Authentication"));
+ if (result == KMessageBox::Yes) {
+ rc = 1;
+ setMetaData("ssl_action", "accept");
+ d->cc->addHost(pc, ourHost);
+ } else {
+ rc = -1;
+ setMetaData("ssl_action", "reject");
+ }
+ }
+ } else if (cp == KSSLCertificateCache::Reject) { // fail
+ messageBox(Information, i18n("SSL certificate is being rejected as requested. You can disable this in the TDE Control Center."),
+ i18n("Server Authentication"));
+ rc = -1;
+ setMetaData("ssl_action", "reject");
+ } else {
+ do {
+ TQString msg = i18n("The server certificate failed the "
+ "authenticity test (%1).");
+ result = messageBox(WarningYesNoCancel,
+ msg.arg(ourHost),
+ i18n("Server Authentication"),
+ i18n("&Details"),
+ i18n("Co&nnect"));
+ if (result == KMessageBox::Yes) {
+ if (!d->dcc) {
+ d->dcc = new DCOPClient;
+ d->dcc->attach();
+ if (!d->dcc->isApplicationRegistered("tdeio_uiserver")) {
+ TDEApplication::startServiceByDesktopPath("tdeio_uiserver.desktop",
+ TQStringList() );
+ }
+ }
+ TQByteArray data, ignore;
+ TQCString ignoretype;
+ TQDataStream arg(data, IO_WriteOnly);
+ arg << theurl << mOutgoingMetaData;
+ arg << metaData("window-id").toInt();
+ d->dcc->call("tdeio_uiserver", "UIServer",
+ "showSSLInfoDialog(TQString,TDEIO::MetaData,int)",
+ data, ignoretype, ignore);
+ }
+ } while (result == KMessageBox::Yes);
+
+ if (result == KMessageBox::No) {
+ setMetaData("ssl_action", "accept");
+ rc = 1;
+ cp = KSSLCertificateCache::Accept;
+ result = messageBox(WarningYesNo,
+ i18n("Would you like to accept this "
+ "certificate forever without "
+ "being prompted?"),
+ i18n("Server Authentication"),
+ i18n("&Forever"),
+ i18n("&Current Sessions Only"));
+ permacache = (result == KMessageBox::Yes);
+ d->cc->addCertificate(pc, cp, permacache);
+ d->cc->addHost(pc, ourHost);
+ } else {
+ setMetaData("ssl_action", "reject");
+ rc = -1;
+ cp = KSSLCertificateCache::Prompt;
+ d->cc->addCertificate(pc, cp, permacache);
+ }
+ }
+ }
+ }
+
+
+ if (rc == -1) {
+ return rc;
+ }
+
+ if (metaData("ssl_activate_warnings") == "TRUE") {
+ // - entering SSL
+ if (!isChild && metaData("ssl_was_in_use") == "FALSE" &&
+ d->kssl->settings()->warnOnEnter()) {
+ int result;
+ do {
+ result = messageBox( i18n("You are about to "
+ "enter secure mode. "
+ "All transmissions "
+ "will be encrypted "
+ "unless otherwise "
+ "noted.\nThis means "
+ "that no third party "
+ "will be able to "
+ "easily observe your "
+ "data in transit."),
+ WarningYesNo,
+ i18n("Security Information"),
+ i18n("Display SSL "
+ "&Information"),
+ i18n("C&onnect"),
+ "WarnOnEnterSSLMode" );
+ // Move this setting into KSSL instead
+ TDEConfig *config = new TDEConfig("tdeioslaverc");
+ config->setGroup("Notification Messages");
+
+ if (!config->readBoolEntry("WarnOnEnterSSLMode", true)) {
+ config->deleteEntry("WarnOnEnterSSLMode");
+ config->sync();
+ d->kssl->settings()->setWarnOnEnter(false);
+ d->kssl->settings()->save();
+ }
+ delete config;
+
+ if ( result == KMessageBox::Yes )
+ {
+ if (!d->dcc) {
+ d->dcc = new DCOPClient;
+ d->dcc->attach();
+ if (!d->dcc->isApplicationRegistered("tdeio_uiserver")) {
+ TDEApplication::startServiceByDesktopPath("tdeio_uiserver.desktop",
+ TQStringList() );
+ }
+ }
+ TQByteArray data, ignore;
+ TQCString ignoretype;
+ TQDataStream arg(data, IO_WriteOnly);
+ arg << theurl << mOutgoingMetaData;
+ arg << metaData("window-id").toInt();
+ d->dcc->call("tdeio_uiserver", "UIServer",
+ "showSSLInfoDialog(TQString,TDEIO::MetaData,int)",
+ data, ignoretype, ignore);
+ }
+ } while (result != KMessageBox::No);
+ }
+
+ } // if ssl_activate_warnings
+
+
+ kdDebug(7029) << "SSL connection information follows:" << endl
+ << "+-----------------------------------------------" << endl
+ << "| Cipher: " << d->kssl->connectionInfo().getCipher() << endl
+ << "| Description: " << d->kssl->connectionInfo().getCipherDescription() << endl
+ << "| Version: " << d->kssl->connectionInfo().getCipherVersion() << endl
+ << "| Strength: " << d->kssl->connectionInfo().getCipherUsedBits()
+ << " of " << d->kssl->connectionInfo().getCipherBits()
+ << " bits used." << endl
+ << "| PEER:" << endl
+ << "| Subject: " << d->kssl->peerInfo().getPeerCertificate().getSubject() << endl
+ << "| Issuer: " << d->kssl->peerInfo().getPeerCertificate().getIssuer() << endl
+ << "| Validation: " << (int)ksv << endl
+ << "| Certificate matches IP: " << _IPmatchesCN << endl
+ << "+-----------------------------------------------"
+ << endl;
+
+ // sendMetaData(); Do not call this function!!
+ return rc;
+}
+
+
+bool TCPSlaveBase::isConnectionValid()
+{
+ if ( m_iSock == -1 )
+ return false;
+
+ fd_set rdfs;
+ FD_ZERO(&rdfs);
+ FD_SET(m_iSock , &rdfs);
+
+ struct timeval tv;
+ tv.tv_usec = 0;
+ tv.tv_sec = 0;
+ int retval;
+#ifdef Q_OS_UNIX
+ do {
+ retval = KSocks::self()->select(m_iSock+1, &rdfs, NULL, NULL, &tv);
+ if (wasKilled())
+ return false; // Beam us out of here
+ } while ((retval == -1) && (errno == EAGAIN));
+#else
+ retval = -1;
+#endif
+ // retval == -1 ==> Error
+ // retval == 0 ==> Connection Idle
+ // retval >= 1 ==> Connection Active
+ //kdDebug(7029) << "TCPSlaveBase::isConnectionValid: select returned: "
+ // << retval << endl;
+
+ if (retval == -1)
+ return false;
+
+ if (retval == 0)
+ return true;
+
+ // Connection is active, check if it has closed.
+ char buffer[100];
+#ifdef Q_OS_UNIX
+ do {
+ retval = KSocks::self()->recv(m_iSock, buffer, 80, MSG_PEEK);
+
+ } while ((retval == -1) && (errno == EAGAIN));
+#else
+ retval = -1;
+#endif
+ //kdDebug(7029) << "TCPSlaveBase::isConnectionValid: recv returned: "
+ // << retval << endl;
+ if (retval <= 0)
+ return false; // Error or connection closed.
+
+ return true; // Connection still valid.
+}
+
+
+bool TCPSlaveBase::waitForResponse( int t )
+{
+ fd_set rd;
+ struct timeval timeout;
+
+ if ( (m_bIsSSL || d->usingTLS) && !d->useSSLTunneling && d->kssl )
+ if (d->kssl->pending() > 0)
+ return true;
+
+ FD_ZERO(&rd);
+ FD_SET(m_iSock, &rd);
+
+ timeout.tv_usec = 0;
+ timeout.tv_sec = t;
+ time_t startTime;
+
+ int rc;
+ int n = t;
+
+reSelect:
+ startTime = time(NULL);
+#ifdef Q_OS_UNIX
+ rc = KSocks::self()->select(m_iSock+1, &rd, NULL, NULL, &timeout);
+#else
+ rc = -1;
+#endif
+ if (wasKilled())
+ return false; // We're dead.
+
+ if (rc == -1)
+ return false;
+
+ if (FD_ISSET(m_iSock, &rd))
+ return true;
+
+ // Well it returned but it wasn't set. Let's see if it
+ // returned too early (perhaps from an errant signal) and
+ // start over with the remaining time
+ int timeDone = time(NULL) - startTime;
+ if (timeDone < n)
+ {
+ n -= timeDone;
+ timeout.tv_sec = n;
+ goto reSelect;
+ }
+
+ return false; // Timed out!
+}
+
+int TCPSlaveBase::connectResult()
+{
+ return d->status;
+}
+
+void TCPSlaveBase::setBlockConnection( bool b )
+{
+ d->block = b;
+}
+
+void TCPSlaveBase::setConnectTimeout( int t )
+{
+ d->timeout = t;
+}
+
+bool TCPSlaveBase::isSSLTunnelEnabled()
+{
+ return d->useSSLTunneling;
+}
+
+void TCPSlaveBase::setEnableSSLTunnel( bool enable )
+{
+ d->useSSLTunneling = enable;
+}
+
+void TCPSlaveBase::setRealHost( const TQString& realHost )
+{
+ d->realHost = realHost;
+}
+
+bool TCPSlaveBase::doSSLHandShake( bool sendError )
+{
+ kdDebug(7029) << "TCPSlaveBase::doSSLHandShake: " << endl;
+ TQString msgHost = d->host;
+
+ d->kssl->reInitialize();
+
+ if (hasMetaData("ssl_session_id")) {
+ KSSLSession *s = KSSLSession::fromString(metaData("ssl_session_id"));
+ if (s) {
+ d->kssl->setSession(s);
+ delete s;
+ }
+ }
+ certificatePrompt();
+
+ if ( !d->realHost.isEmpty() )
+ {
+ msgHost = d->realHost;
+ }
+
+ kdDebug(7029) << "Setting real hostname: " << msgHost << endl;
+ d->kssl->setPeerHost(msgHost);
+
+ d->status = d->kssl->connect(m_iSock);
+ if (d->status < 0)
+ {
+ closeDescriptor();
+ if ( sendError )
+ error( ERR_COULD_NOT_CONNECT, msgHost);
+ return false;
+ }
+
+ setMetaData("ssl_session_id", d->kssl->session()->toString());
+ setMetaData("ssl_in_use", "TRUE");
+
+ if (!d->kssl->reusingSession()) {
+ int rc = verifyCertificate();
+ if ( rc != 1 ) {
+ d->status = -1;
+ closeDescriptor();
+ if ( sendError )
+ error( ERR_COULD_NOT_CONNECT, msgHost);
+ return false;
+ }
+ }
+
+ d->needSSLHandShake = false;
+
+ d->savedMetaData = mOutgoingMetaData;
+ return true;
+}
+
+
+bool TCPSlaveBase::userAborted() const
+{
+ return d->userAborted;
+}
+
+void TCPSlaveBase::virtual_hook( int id, void* data )
+{ SlaveBase::virtual_hook( id, data ); }
+
diff --git a/tdeio/tdeio/tcpslavebase.h b/tdeio/tdeio/tcpslavebase.h
new file mode 100644
index 000000000..4903dd7ac
--- /dev/null
+++ b/tdeio/tdeio/tcpslavebase.h
@@ -0,0 +1,389 @@
+/*
+ * Copyright (C) 2000 Alex Zepeda <zipzippy@sonic.net>
+ * Copyright (C) 2001 George Staikos <staikos@kde.org>
+ * Copyright (C) 2001 Dawit Alemayehu <adawit@kde.org>
+ *
+ * This file is part of the KDE project
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef _TCP_SLAVEBASE_H
+#define _TCP_SLAVEBASE_H
+
+#include <sys/types.h>
+#include <stdio.h>
+
+#include <kextsock.h>
+#include <tdeio/slavebase.h>
+
+
+namespace TDEIO {
+
+/**
+ * There are two classes that specifies the protocol between application (job)
+ * and tdeioslave. SlaveInterface is the class to use on the application end,
+ * SlaveBase is the one to use on the slave end.
+ *
+ * Slave implementations should simply inherit SlaveBase
+ *
+ * A call to foo() results in a call to slotFoo() on the other end.
+ */
+class TDEIO_EXPORT TCPSlaveBase : public SlaveBase
+{
+public:
+ TCPSlaveBase(unsigned short int defaultPort, const TQCString &protocol,
+ const TQCString &poolSocket, const TQCString &appSocket);
+
+ TCPSlaveBase(unsigned short int defaultPort, const TQCString &protocol,
+ const TQCString &poolSocket, const TQCString &appSocket,
+ bool useSSL);
+
+ virtual ~TCPSlaveBase();
+
+protected:
+
+#ifndef KDE_NO_COMPAT
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED ssize_t Write(const void *data, ssize_t len) { return write( data, len ); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED ssize_t Read(void *data, ssize_t len) { return read( data, len ); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED ssize_t ReadLine(char *data, ssize_t len) { return readLine( data, len ); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED unsigned short int GetPort(unsigned short int p) { return port(p); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED bool ConnectToHost( const TQString &host, unsigned int port,
+ bool sendError ) { return connectToHost( host, port, sendError ); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED void CloseDescriptor() { closeDescriptor(); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED bool AtEOF() { return atEnd(); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED bool InitializeSSL() { return initializeSSL(); }
+
+ /**
+ * @deprecated Due to inconsistency with KDE naming convention.
+ */
+ KDE_DEPRECATED void CleanSSL() { cleanSSL(); }
+#endif
+
+ /**
+ * This function acts like standard write function call
+ * except it is also capable of making SSL or SOCKS
+ * connections.
+ *
+ * @param data info to be sent to remote machine
+ * @param len the length of the data to be sent
+ *
+ * @return the actual size of the data that was sent
+ */
+ ssize_t write(const void *data, ssize_t len);
+
+ /**
+ * This function acts like standard read function call
+ * except it is also capable of deciphering SSL data as
+ * well as handling data over SOCKSified connections.
+ *
+ * @param data storage for the info read from server
+ * @param len length of the info to read from the server
+ *
+ * @return the actual size of data that was obtained
+ */
+ ssize_t read(void *data, ssize_t len);
+
+ /**
+ * Same as above except it reads data one line at a time.
+ */
+ ssize_t readLine(char *data, ssize_t len);
+
+ /**
+ * Sets the maximum size of blocks read in during calls to readLine().
+ * This allows a slave to optimize for the protocol which it implements.
+ * Ideally this should be (common_line_length+1) or so.
+ * Making this too large will have adverse effects on performance.
+ * Initial/default value is 256(bytes)
+ */
+ void setBlockSize(int sz);
+
+ /**
+ * Determines the appropriate port to use.
+ *
+ * This functions attempts to discover the appropriate port.
+ *
+ * @param _port the port to try, if it works, it is returned
+ * @return the default port if the given port doesn't work
+ */
+ unsigned short int port(unsigned short int _port);
+
+ /**
+ * Performs the initial TCP connection stuff and/or
+ * SSL handshaking as necessary.
+ *
+ * Please note that unlike its deprecated counterpart, this
+ * function allows you to disable any error message from being
+ * sent back to the calling application! You can then use the
+ * connectResult() function to determine the result of the
+ * request for connection.
+ *
+ * @param host hostname
+ * @param port port number to connect to
+ * @param sendError if true sends error message to calling app.
+ *
+ * @return on succes, true is returned.
+ * on failure, false is returned and an appropriate
+ * error message is send to the application.
+ */
+ bool connectToHost( const TQString &host, unsigned int port,
+ bool sendError = true );
+
+ /**
+ * Are we using SSL?
+ *
+ * @return if so, true is returned.
+ * if not, true isn't returned.
+ * @since 3.2
+ */
+ bool usingSSL() const { return m_bIsSSL; }
+
+ /**
+ * Are we using TLS?
+ *
+ * @return if so, true is returned.
+ * if not, true isn't returned.
+ * @since 3.2
+ */
+ bool usingTLS() const;
+
+ /**
+ * @obsolete kept for binary compatibility
+ * Are we using TLS?
+ *
+ * @return if so, true is returned.
+ * if not, true isn't returned.
+ */
+ bool usingTLS();
+
+ /**
+ * Can we use TLS?
+ *
+ * @return if so, true is returned.
+ * if not, true isn't returned.
+ */
+ bool canUseTLS();
+
+ /**
+ * Start using TLS on the connection.
+ *
+ * @return on success, 1 is returned.
+ * on failure, 0 is returned.
+ * on TLS init failure, -1 is returned.
+ * on connect failure, -2 is returned.
+ * on certificate failure, -3 is returned.
+ */
+ int startTLS();
+
+ /**
+ * Stop using TLS on the connection.
+ */
+ void stopTLS();
+
+ /**
+ * Closes the current file descriptor.
+ *
+ * Call this function to properly close up the socket
+ * since it also takes care to prroperly close the stdio
+ * fstream stuff, as well as sets the socket back to -1
+ */
+ void closeDescriptor();
+
+
+ /**
+ * Returns true when end of data is reached
+ */
+ bool atEnd();
+
+
+ /**
+ * Call this if you use persistent connections and want all the
+ * metadata restored. This is particularly important for SSL
+ * sessions since the app needs to know the state of connection,
+ * certificates, etc.
+ */
+ void setSSLMetaData();
+
+
+ /**
+ * Initializs all SSL variables
+ */
+ bool initializeSSL();
+
+
+ /**
+ * Cleans up all SSL settings.
+ */
+ void cleanSSL();
+
+ /**
+ * Determines whether or not we are still connected
+ * to the remote machine.
+ *
+ * This method may fail to detect a closed SSL connection.
+ *
+ * return @p true if the socket is still active or
+ * false otherwise.
+ */
+ bool isConnectionValid();
+
+ /**
+ * Returns the status of the connection.
+ *
+ * This function allows you to invoke ConnectToHost
+ * with the @p sendError flag set to false so that you
+ * can send the appropriate error message back to the
+ * calling io-slave.
+ *
+ * @return the status code as returned by KExtendedSocket.
+ */
+ int connectResult();
+
+ /**
+ * Wait for some type of activity on the socket
+ * for the period specified by @p t.
+ *
+ * @param t length of time in seconds that we should monitor the
+ * socket before timing out.
+ *
+ * @return true if any activity was seen on the socket before the
+ * timeout value was reached, false otherwise.
+ */
+ bool waitForResponse( int t );
+
+ /**
+ * Sets the mode of the connection to blocking or non-blocking.
+ *
+ * Be sure to call this function before calling connectToHost.
+ * Otherwise, this setting will not have any effect until the next
+ * @p connectToHost.
+ *
+ * @param b true to make the connection a blocking one, false otherwise.
+ */
+ void setBlockConnection( bool b );
+
+ /**
+ * Sets how long to wait for orignally connecting to
+ * the requested before timinig out.
+ *
+ * Be sure to call this function before calling ConnectToHost,
+ * otherwise the setting will not take effect until the next call
+ * to @p ConnectToHost.
+ *
+ * @param t timeout value
+ */
+ void setConnectTimeout( int t );
+
+ /**
+ * Returns true if SSL tunneling is enabled.
+ *
+ * @see setEnableSSlTunnel
+ */
+ bool isSSLTunnelEnabled();
+
+ /**
+ * Set up SSL tunneling mode.
+ *
+ * Calling this function with a @p true argument will allow
+ * you to temprarly ignore the @p m_bIsSSL flag setting and
+ * make a non-SSL connection. It is mostly useful for making
+ * connections to SSL sites through a non-transparent proxy
+ * server (i.e. most proxy servers out there).
+ *
+ * Note that once you have successfully "tunneled" through the
+ * proxy server you must call this function with its argument
+ * set to false to properly connect to the SSL site.
+ *
+ * @param enable if true SSL Tunneling will be enabled
+ */
+ void setEnableSSLTunnel( bool enable );
+
+ /**
+ * Sets up the the real hostname for an SSL connection
+ * that goes through a proxy server.
+ *
+ * This function is essential in making sure that the
+ * real hostname is used for validating certificates from
+ * SSL sites!
+ *
+ * @param realHost the actual host name we are connecting to
+ */
+ void setRealHost( const TQString& realHost );
+
+ // don't use me!
+ void doConstructorStuff();
+
+ // For the certificate verification code
+ int verifyCertificate();
+
+ // For prompting for the certificate to use
+ void certificatePrompt();
+
+ // Did the user abort (as the reason for connectToHost returning false)
+ bool userAborted() const;
+
+protected:
+ int m_iSock;
+ bool m_bIsSSL;
+ unsigned short int m_iPort;
+ unsigned short int m_iDefaultPort;
+ TQCString m_sServiceName;
+ FILE *fp;
+
+private:
+ bool doSSLHandShake( bool sendError );
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class TcpSlaveBasePrivate;
+ TcpSlaveBasePrivate *d;
+};
+
+}
+
+#endif
diff --git a/tdeio/tdeio/tdefilefilter.cpp b/tdeio/tdeio/tdefilefilter.cpp
new file mode 100644
index 000000000..310b86221
--- /dev/null
+++ b/tdeio/tdeio/tdefilefilter.cpp
@@ -0,0 +1,134 @@
+/* This file is part of the KDE libraries
+
+ Copyright (c) 2001,2002 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License (LGPL) as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <tqregexp.h>
+
+#include <tdefileitem.h>
+#include <kglobal.h>
+
+#include "tdefilefilter.h"
+
+KSimpleFileFilter::KSimpleFileFilter()
+ : m_filterDotFiles( true ),
+ m_filterSpecials( true ),
+ m_modeFilter( 0 )
+{
+ m_nameFilters.setAutoDelete( true );
+}
+
+KSimpleFileFilter::~KSimpleFileFilter()
+{
+}
+
+void KSimpleFileFilter::setFilterDotFiles( bool filter )
+{
+ m_filterDotFiles = filter;
+}
+
+void KSimpleFileFilter::setFilterSpecials( bool filter )
+{
+ m_filterSpecials = filter;
+}
+
+void KSimpleFileFilter::setNameFilters( const TQString& nameFilters )
+{
+ // KDE 3.0 defaults
+ setNameFilters( nameFilters, false, ' ' );
+}
+
+void KSimpleFileFilter::setNameFilters( const TQString& nameFilters,
+ bool caseSensitive,
+ const TQChar& separator )
+{
+ m_nameFilters.clear();
+
+ // Split on white space
+ TQStringList list = TQStringList::split(separator, nameFilters);
+
+ TQStringList::ConstIterator it = list.begin();
+ for ( ; it != list.end(); ++it )
+ m_nameFilters.append(new TQRegExp(*it, caseSensitive, true ));
+}
+
+void KSimpleFileFilter::setMimeFilters( const TQStringList& mimeFilters )
+{
+ m_mimeFilters = mimeFilters;
+}
+
+void KSimpleFileFilter::setModeFilter( mode_t mode )
+{
+ m_modeFilter = mode;
+}
+
+bool KSimpleFileFilter::passesFilter( const KFileItem *item ) const
+{
+ static const TQString& dot = TDEGlobal::staticQString(".");
+ static const TQString& dotdot = TDEGlobal::staticQString("..");
+
+ const TQString& name = item->name();
+
+ if ( m_filterDotFiles && item->isHidden() )
+ return false;
+
+ if ( m_filterSpecials && (name == dot || name == dotdot) )
+ return false;
+
+ if ( m_modeFilter && !(m_modeFilter & item->mode()) )
+ return false;
+
+ if ( !m_mimeFilters.isEmpty() ) {
+ // correct or guessed mimetype -- we don't mind
+ KMimeType::Ptr mime = item->mimeTypePtr();
+ bool ok = false;
+
+ TQStringList::ConstIterator it = m_mimeFilters.begin();
+ for ( ; it != m_mimeFilters.end(); ++it ) {
+ if ( mime->is(*it) ) { // match!
+ ok = true;
+ break;
+ }
+ }
+ if ( !ok )
+ return false;
+ }
+
+ if ( !m_nameFilters.isEmpty() ) {
+ bool ok = false;
+
+ TQPtrListIterator<TQRegExp> it( m_nameFilters );
+ for ( ; it.current(); ++it ) {
+ if ( it.current()->exactMatch( name ) ) { // match!
+ ok = true;
+ break;
+ }
+ }
+ if ( !ok )
+ return false;
+ }
+
+ return true; // passes the filter!
+}
+
+void KFileFilter::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+void KSimpleFileFilter::virtual_hook( int id, void* data )
+{ KFileFilter::virtual_hook( id, data ); }
+
diff --git a/kio/kio/kfilefilter.h b/tdeio/tdeio/tdefilefilter.h
index 2891e800e..2891e800e 100644
--- a/kio/kio/kfilefilter.h
+++ b/tdeio/tdeio/tdefilefilter.h
diff --git a/tdeio/tdeio/tdefileitem.cpp b/tdeio/tdeio/tdefileitem.cpp
new file mode 100644
index 000000000..bd043504a
--- /dev/null
+++ b/tdeio/tdeio/tdefileitem.cpp
@@ -0,0 +1,1202 @@
+/* This file is part of the KDE project
+ Copyright (C) 1999 David Faure <faure@kde.org>
+ 2001 Carsten Pfeiffer <pfeiffer@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+// $Id$
+
+#include <config.h>
+
+#include <sys/time.h>
+#include <pwd.h>
+#include <grp.h>
+#include <sys/types.h>
+
+#include <assert.h>
+#include <unistd.h>
+
+#include "tdefileitem.h"
+
+#include <tqdir.h>
+#include <tqfile.h>
+#include <tqmap.h>
+#include <tqstylesheet.h>
+#include <tqimage.h>
+
+#include <kdebug.h>
+#include <tdefilemetainfo.h>
+#include <ksambashare.h>
+#include <knfsshare.h>
+#include <kglobal.h>
+#include <kglobalsettings.h>
+#include <kiconloader.h>
+#include <klargefile.h>
+#include <klocale.h>
+#include <kmimetype.h>
+#include <krun.h>
+
+#ifdef HAVE_ELFICON
+#include "tdelficon.h"
+#endif // HAVE_ELFICON
+
+class KFileItem::KFileItemPrivate {
+ public:
+ TQString iconName;
+};
+
+KFileItem::KFileItem( const TDEIO::UDSEntry& _entry, const KURL& _url,
+ bool _determineMimeTypeOnDemand, bool _urlIsDirectory ) :
+ m_entry( _entry ),
+ m_url( _url ),
+ m_pMimeType( 0 ),
+ m_fileMode( KFileItem::Unknown ),
+ m_permissions( KFileItem::Unknown ),
+ m_bMarked( false ),
+ m_bLink( false ),
+ m_bIsLocalURL( _url.isLocalFile() ),
+ m_bMimeTypeKnown( false ),
+ m_hidden( Auto ),
+ d(0)
+{
+ readUDSEntry( _urlIsDirectory );
+ init( _determineMimeTypeOnDemand );
+}
+
+KFileItem::KFileItem( mode_t _mode, mode_t _permissions, const KURL& _url, bool _determineMimeTypeOnDemand ) :
+ m_entry(), // warning !
+ m_url( _url ),
+ m_strName( _url.fileName() ),
+ m_strText( TDEIO::decodeFileName( m_strName ) ),
+ m_pMimeType( 0 ),
+ m_fileMode ( _mode ),
+ m_permissions( _permissions ),
+ m_bMarked( false ),
+ m_bLink( false ),
+ m_bIsLocalURL( _url.isLocalFile() ),
+ m_bMimeTypeKnown( false ),
+ m_hidden( Auto ),
+ d(0)
+{
+ init( _determineMimeTypeOnDemand );
+}
+
+KFileItem::KFileItem( const KURL &url, const TQString &mimeType, mode_t mode )
+: m_url( url ),
+ m_strName( url.fileName() ),
+ m_strText( TDEIO::decodeFileName( m_strName ) ),
+ m_pMimeType( 0 ),
+ m_fileMode( mode ),
+ m_permissions( KFileItem::Unknown ),
+ m_bMarked( false ),
+ m_bLink( false ),
+ m_bIsLocalURL( url.isLocalFile() ),
+ m_bMimeTypeKnown( !mimeType.isEmpty() ),
+ m_hidden( Auto ),
+ d(0)
+{
+ if (m_bMimeTypeKnown)
+ m_pMimeType = KMimeType::mimeType( mimeType );
+
+ init( false );
+}
+
+KFileItem::KFileItem( const KFileItem & item ) :
+ d(0)
+{
+ assign( item );
+}
+
+KFileItem& KFileItem::operator=( const KFileItem & item )
+{
+ assign( item );
+ return *this;
+}
+
+KFileItem::~KFileItem()
+{
+ delete d;
+}
+
+void KFileItem::init( bool _determineMimeTypeOnDemand )
+{
+ m_access = TQString::null;
+ m_size = (TDEIO::filesize_t) -1;
+ // metaInfo = KFileMetaInfo();
+ for ( int i = 0; i < NumFlags; i++ )
+ m_time[i] = (time_t) -1;
+
+ // determine mode and/or permissions if unknown
+ if ( m_fileMode == KFileItem::Unknown || m_permissions == KFileItem::Unknown )
+ {
+ mode_t mode = 0;
+ if ( m_url.isLocalFile() )
+ {
+ /* directories may not have a slash at the end if
+ * we want to stat() them; it requires that we
+ * change into it .. which may not be allowed
+ * stat("/is/unaccessible") -> rwx------
+ * stat("/is/unaccessible/") -> EPERM H.Z.
+ * This is the reason for the -1
+ */
+ KDE_struct_stat buf;
+ TQCString path = TQFile::encodeName(m_url.path( -1 ));
+ if ( KDE_lstat( path.data(), &buf ) == 0 )
+ {
+ mode = buf.st_mode;
+ if ( S_ISLNK( mode ) )
+ {
+ m_bLink = true;
+ if ( KDE_stat( path.data(), &buf ) == 0 )
+ mode = buf.st_mode;
+ else // link pointing to nowhere (see tdeio/file/file.cc)
+ mode = (S_IFMT-1) | S_IRWXU | S_IRWXG | S_IRWXO;
+ }
+ // While we're at it, store the times
+ m_time[ Modification ] = buf.st_mtime;
+ m_time[ Access ] = buf.st_atime;
+ if ( m_fileMode == KFileItem::Unknown )
+ m_fileMode = mode & S_IFMT; // extract file type
+ if ( m_permissions == KFileItem::Unknown )
+ m_permissions = mode & 07777; // extract permissions
+ }
+ }
+ }
+
+ // determine the mimetype
+ if (!m_pMimeType && !m_url.isEmpty())
+ {
+ bool accurate = false;
+ bool isLocalURL;
+ KURL url = mostLocalURL(isLocalURL);
+
+ m_pMimeType = KMimeType::findByURL( url, m_fileMode, isLocalURL,
+ // use fast mode if not mimetype on demand
+ _determineMimeTypeOnDemand, &accurate );
+ //kdDebug() << "finding mimetype for " << url.url() << " : " << m_pMimeType->name() << endl;
+ // if we didn't use fast mode, or if we got a result, then this is the mimetype
+ // otherwise, determineMimeType will be able to do better.
+ m_bMimeTypeKnown = (!_determineMimeTypeOnDemand) || accurate;
+ }
+}
+
+void KFileItem::readUDSEntry( bool _urlIsDirectory )
+{
+ // extract the mode and the filename from the TDEIO::UDS Entry
+ bool UDS_URL_seen = false;
+
+ if (&m_entry == NULL) return;
+
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ for( ; it != m_entry.end(); ++it ) {
+ switch ((*it).m_uds) {
+
+ case TDEIO::UDS_FILE_TYPE:
+ m_fileMode = (mode_t)((*it).m_long);
+ break;
+
+ case TDEIO::UDS_ACCESS:
+ m_permissions = (mode_t)((*it).m_long);
+ break;
+
+ case TDEIO::UDS_USER:
+ m_user = ((*it).m_str);
+ break;
+
+ case TDEIO::UDS_GROUP:
+ m_group = ((*it).m_str);
+ break;
+
+ case TDEIO::UDS_NAME:
+ m_strName = (*it).m_str;
+ m_strText = TDEIO::decodeFileName( m_strName );
+ break;
+
+ case TDEIO::UDS_URL:
+ UDS_URL_seen = true;
+ m_url = KURL((*it).m_str);
+ if ( m_url.isLocalFile() )
+ m_bIsLocalURL = true;
+ break;
+
+ case TDEIO::UDS_MIME_TYPE:
+ m_pMimeType = KMimeType::mimeType((*it).m_str);
+ m_bMimeTypeKnown = true;
+ break;
+
+ case TDEIO::UDS_GUESSED_MIME_TYPE:
+ m_guessedMimeType = (*it).m_str;
+ break;
+
+ case TDEIO::UDS_LINK_DEST:
+ m_bLink = !(*it).m_str.isEmpty(); // we don't store the link dest
+ break;
+
+ case TDEIO::UDS_ICON_NAME:
+ if ( !d )
+ d = new KFileItemPrivate();
+ d->iconName = (*it).m_str;
+ break;
+
+ case TDEIO::UDS_HIDDEN:
+ if ( (*it).m_long )
+ m_hidden = Hidden;
+ else
+ m_hidden = Shown;
+ break;
+ }
+ }
+
+ // avoid creating these QStrings again and again
+ static const TQString& dot = TDEGlobal::staticQString(".");
+ if ( _urlIsDirectory && !UDS_URL_seen && !m_strName.isEmpty() && m_strName != dot )
+ m_url.addPath( m_strName );
+}
+
+void KFileItem::refresh()
+{
+ m_fileMode = KFileItem::Unknown;
+ m_permissions = KFileItem::Unknown;
+ m_pMimeType = 0L;
+ m_user = TQString::null;
+ m_group = TQString::null;
+ m_metaInfo = KFileMetaInfo();
+ m_hidden = Auto;
+
+ // Basically, we can't trust any information we got while listing.
+ // Everything could have changed...
+ // Clearing m_entry makes it possible to detect changes in the size of the file,
+ // the time information, etc.
+ m_entry = TDEIO::UDSEntry();
+ init( false );
+}
+
+void KFileItem::refreshMimeType()
+{
+ m_pMimeType = 0L;
+ init( false ); // Will determine the mimetype
+}
+
+void KFileItem::setURL( const KURL &url )
+{
+ m_url = url;
+ setName( url.fileName() );
+}
+
+void KFileItem::setName( const TQString& name )
+{
+ m_strName = name;
+ m_strText = TDEIO::decodeFileName( m_strName );
+}
+
+TQString KFileItem::linkDest() const
+{
+ if (&m_entry == NULL) return TQString::null;
+
+ // Extract it from the TDEIO::UDSEntry
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ for( ; it != m_entry.end(); ++it )
+ if ( (*it).m_uds == TDEIO::UDS_LINK_DEST )
+ return (*it).m_str;
+ // If not in the TDEIO::UDSEntry, or if UDSEntry empty, use readlink() [if local URL]
+ if ( m_bIsLocalURL )
+ {
+ char buf[1000];
+ int n = readlink( TQFile::encodeName(m_url.path( -1 )), buf, sizeof(buf)-1 );
+ if ( n != -1 )
+ {
+ buf[ n ] = 0;
+ return TQFile::decodeName( buf );
+ }
+ }
+ return TQString::null;
+}
+
+TQString KFileItem::localPath() const
+{
+ if ( m_bIsLocalURL )
+ {
+ return m_url.path();
+ }
+ else
+ {
+ if (&m_entry == NULL) return TQString::null;
+
+ // Extract the local path from the TDEIO::UDSEntry
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ const TDEIO::UDSEntry::ConstIterator end = m_entry.end();
+ for( ; it != end; ++it )
+ if ( (*it).m_uds == TDEIO::UDS_LOCAL_PATH )
+ return (*it).m_str;
+ }
+
+ return TQString::null;
+}
+
+TDEIO::filesize_t KFileItem::size(bool &exists) const
+{
+ exists = true;
+ if ( m_size != (TDEIO::filesize_t) -1 )
+ return m_size;
+
+ if (&m_entry == NULL) return 0L;
+
+ // Extract it from the TDEIO::UDSEntry
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ for( ; it != m_entry.end(); ++it )
+ if ( (*it).m_uds == TDEIO::UDS_SIZE ) {
+ m_size = (*it).m_long;
+ return m_size;
+ }
+ // If not in the TDEIO::UDSEntry, or if UDSEntry empty, use stat() [if local URL]
+ if ( m_bIsLocalURL )
+ {
+ KDE_struct_stat buf;
+ if ( KDE_stat( TQFile::encodeName(m_url.path( -1 )), &buf ) == 0 )
+ return buf.st_size;
+ }
+ exists = false;
+ return 0L;
+}
+
+bool KFileItem::hasExtendedACL() const
+{
+ if (&m_entry == NULL) return false;
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ for( ; it != m_entry.end(); it++ )
+ if ( (*it).m_uds == TDEIO::UDS_EXTENDED_ACL ) {
+ return true;
+ }
+ return false;
+}
+
+KACL KFileItem::ACL() const
+{
+ if ( hasExtendedACL() ) {
+ if (&m_entry == NULL) return KACL( m_permissions );
+
+ // Extract it from the TDEIO::UDSEntry
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ for( ; it != m_entry.end(); ++it )
+ if ( (*it).m_uds == TDEIO::UDS_ACL_STRING )
+ return KACL((*it).m_str);
+ }
+ // create one from the basic permissions
+ return KACL( m_permissions );
+}
+
+KACL KFileItem::defaultACL() const
+{
+ if (&m_entry == NULL) return KACL();
+
+ // Extract it from the TDEIO::UDSEntry
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ for( ; it != m_entry.end(); ++it )
+ if ( (*it).m_uds == TDEIO::UDS_DEFAULT_ACL_STRING )
+ return KACL((*it).m_str);
+ return KACL();
+}
+
+TDEIO::filesize_t KFileItem::size() const
+{
+ bool exists;
+ return size(exists);
+}
+
+time_t KFileItem::time( unsigned int which ) const
+{
+ bool hasTime;
+ return time(which, hasTime);
+}
+time_t KFileItem::time( unsigned int which, bool &hasTime ) const
+{
+ hasTime = true;
+ unsigned int mappedWhich = 0;
+
+ switch( which ) {
+ case TDEIO::UDS_MODIFICATION_TIME:
+ mappedWhich = Modification;
+ break;
+ case TDEIO::UDS_ACCESS_TIME:
+ mappedWhich = Access;
+ break;
+ case TDEIO::UDS_CREATION_TIME:
+ mappedWhich = Creation;
+ break;
+ }
+
+ if ( m_time[mappedWhich] != (time_t) -1 )
+ return m_time[mappedWhich];
+
+ if (&m_entry == NULL) return static_cast<time_t>(0);
+
+ // Extract it from the TDEIO::UDSEntry
+ TDEIO::UDSEntry::ConstIterator it = m_entry.begin();
+ for( ; it != m_entry.end(); ++it )
+ if ( (*it).m_uds == which ) {
+ m_time[mappedWhich] = static_cast<time_t>((*it).m_long);
+ return m_time[mappedWhich];
+ }
+
+ // If not in the TDEIO::UDSEntry, or if UDSEntry empty, use stat() [if local URL]
+ if ( m_bIsLocalURL )
+ {
+ KDE_struct_stat buf;
+ if ( KDE_stat( TQFile::encodeName(m_url.path(-1)), &buf ) == 0 )
+ {
+ if(which == TDEIO::UDS_CREATION_TIME) {
+ // We can't determine creation time for local files
+ hasTime = false;
+ m_time[mappedWhich] = static_cast<time_t>(0);
+ return m_time[mappedWhich];
+ }
+ m_time[mappedWhich] = (which == TDEIO::UDS_MODIFICATION_TIME) ?
+ buf.st_mtime :
+ /* which == TDEIO::UDS_ACCESS_TIME)*/
+ buf.st_atime;
+ return m_time[mappedWhich];
+ }
+ }
+ hasTime = false;
+ return static_cast<time_t>(0);
+}
+
+
+TQString KFileItem::user() const
+{
+ if ( m_user.isEmpty() && m_bIsLocalURL )
+ {
+ KDE_struct_stat buff;
+ if ( KDE_lstat( TQFile::encodeName(m_url.path( -1 )), &buff ) == 0) // get uid/gid of the link, if it's a link
+ {
+ struct passwd *user = getpwuid( buff.st_uid );
+ if ( user != 0L )
+ m_user = TQString::fromLocal8Bit(user->pw_name);
+ }
+ }
+ return m_user;
+}
+
+TQString KFileItem::group() const
+{
+#ifdef Q_OS_UNIX
+ if (m_group.isEmpty() && m_bIsLocalURL )
+ {
+ KDE_struct_stat buff;
+ if ( KDE_lstat( TQFile::encodeName(m_url.path( -1 )), &buff ) == 0) // get uid/gid of the link, if it's a link
+ {
+ struct group *ge = getgrgid( buff.st_gid );
+ if ( ge != 0L ) {
+ m_group = TQString::fromLocal8Bit(ge->gr_name);
+ if (m_group.isEmpty())
+ m_group.sprintf("%d",ge->gr_gid);
+ } else
+ m_group.sprintf("%d",buff.st_gid);
+ }
+ }
+#endif
+ return m_group;
+}
+
+TQString KFileItem::mimetype() const
+{
+ KFileItem * that = const_cast<KFileItem *>(this);
+ return that->determineMimeType()->name();
+}
+
+KMimeType::Ptr KFileItem::determineMimeType()
+{
+ if ( !m_pMimeType || !m_bMimeTypeKnown )
+ {
+ bool isLocalURL;
+ KURL url = mostLocalURL(isLocalURL);
+
+ m_pMimeType = KMimeType::findByURL( url, m_fileMode, isLocalURL );
+ //kdDebug() << "finding mimetype for " << url.url() << " : " << m_pMimeType->name() << endl;
+ m_bMimeTypeKnown = true;
+ }
+
+ return m_pMimeType;
+}
+
+bool KFileItem::isMimeTypeKnown() const
+{
+ // The mimetype isn't known if determineMimeType was never called (on-demand determination)
+ // or if this fileitem has a guessed mimetype (e.g. ftp symlink) - in which case
+ // it always remains "not fully determined"
+ return m_bMimeTypeKnown && m_guessedMimeType.isEmpty();
+}
+
+TQString KFileItem::mimeComment()
+{
+ KMimeType::Ptr mType = determineMimeType();
+
+ bool isLocalURL;
+ KURL url = mostLocalURL(isLocalURL);
+
+ TQString comment = mType->comment( url, isLocalURL );
+ //kdDebug() << "finding comment for " << url.url() << " : " << m_pMimeType->name() << endl;
+ if (!comment.isEmpty())
+ return comment;
+ else
+ return mType->name();
+}
+
+TQString KFileItem::iconName()
+{
+ if (d && (!d->iconName.isEmpty())) return d->iconName;
+
+ bool isLocalURL;
+ KURL url = mostLocalURL(isLocalURL);
+
+ //kdDebug() << "finding icon for " << url.url() << " : " << m_pMimeType->name() << endl;
+ return determineMimeType()->icon(url, isLocalURL);
+}
+
+int KFileItem::overlays() const
+{
+ int _state = 0;
+ if ( m_bLink )
+ _state |= KIcon::LinkOverlay;
+
+ if ( !S_ISDIR( m_fileMode ) // Locked dirs have a special icon, use the overlay for files only
+ && !isReadable())
+ _state |= KIcon::LockOverlay;
+
+ if ( isHidden() )
+ _state |= KIcon::HiddenOverlay;
+
+ if( S_ISDIR( m_fileMode ) && m_bIsLocalURL)
+ {
+ if (KSambaShare::instance()->isDirectoryShared( m_url.path() ) ||
+ KNFSShare::instance()->isDirectoryShared( m_url.path() ))
+ {
+ //kdDebug()<<"KFileShare::isDirectoryShared : "<<m_url.path()<<endl;
+ _state |= KIcon::ShareOverlay;
+ }
+ }
+
+ if ( m_pMimeType->name() == "application/x-gzip" && m_url.fileName().right(3) == ".gz" )
+ _state |= KIcon::ZipOverlay;
+ return _state;
+}
+
+TQPixmap KFileItem::pixmap( int _size, int _state ) const
+{
+ if (d && (!d->iconName.isEmpty()))
+ return DesktopIcon(d->iconName,_size,_state);
+
+ if ( !m_pMimeType )
+ {
+ static const TQString & defaultFolderIcon =
+ TDEGlobal::staticQString(KMimeType::mimeType( "inode/directory" )->KServiceType::icon());
+
+ if ( S_ISDIR( m_fileMode ) )
+ return DesktopIcon( defaultFolderIcon, _size, _state );
+
+ return DesktopIcon( "unknown", _size, _state );
+ }
+
+ _state |= overlays();
+
+ KMimeType::Ptr mime;
+ // Use guessed mimetype if the main one hasn't been determined for sure
+ if ( !m_bMimeTypeKnown && !m_guessedMimeType.isEmpty() )
+ mime = KMimeType::mimeType( m_guessedMimeType );
+ else
+ mime = m_pMimeType;
+
+ // Support for gzipped files: extract mimetype of contained file
+ // See also the relevant code in overlays, which adds the zip overlay.
+ if ( mime->name() == "application/x-gzip" && m_url.fileName().right(3) == ".gz" )
+ {
+ KURL sf;
+ sf.setPath( m_url.path().left( m_url.path().length() - 3 ) );
+ //kdDebug() << "KFileItem::pixmap subFileName=" << subFileName << endl;
+ mime = KMimeType::findByURL( sf, 0, m_bIsLocalURL );
+ }
+
+ bool isLocalURL;
+ KURL url = mostLocalURL(isLocalURL);
+
+ TQPixmap p = mime->pixmap( url, KIcon::Desktop, _size, _state );
+ //kdDebug() << "finding pixmap for " << url.url() << " : " << mime->name() << endl;
+ if (p.isNull())
+ kdWarning() << "Pixmap not found for mimetype " << m_pMimeType->name() << endl;
+
+ if ( mime->name() == "application/x-executable" ) {
+ // At first glance it might seem to be a good idea to
+ // look for .desktop files for this executable before resorting to the embedded icon
+ // in the same fashion as the minicli, but on close examination this is NOT A GOOD IDEA.
+ // Specifically it allows one executable to mimic another purely based on filename,
+ // which could at certain times fool any user regardless of experience level.
+#ifdef HAVE_ELFICON
+ // Check for an embedded icon
+ unsigned int icon_size;
+ libr_icon *icon = NULL;
+ libr_file *handle = NULL;
+ libr_access_t access = LIBR_READ;
+
+ if((handle = libr_open(const_cast<char*>(url.path().ascii()), access)) == NULL)
+ {
+ kdWarning() << "failed to open file" << url.path() << endl;
+ return p;
+ }
+
+ icon_size = _size;
+ icon = libr_icon_geticon_bysize(handle, icon_size);
+
+ // See if the embedded icon name matches any icon file names already on the system
+ // If it does, use the system icon instead of the embedded one
+ int iconresnamefound = 0;
+ iconentry *entry = NULL;
+ iconlist icons;
+ if(!get_iconlist(handle, &icons))
+ {
+ // Failed to obtain a list of ELF icons
+ kdWarning() << "failed to obtain ELF icon: " << libr_errmsg() << endl;
+
+ // See if there is a system icon we can use
+ TQString sysIconName = elf_get_resource(handle, ".metadata_sysicon");
+ if (!sysIconName.isEmpty()) {
+ if (TDEGlobal::iconLoader()->iconPath(sysIconName.ascii(), 0, true) != "") {
+ p = DesktopIcon( sysIconName.ascii(), _size, _state );
+ }
+ }
+
+ libr_close(handle);
+ return p;
+ }
+ else {
+ while((entry = get_nexticon(&icons, entry)) != NULL)
+ {
+ if(icon == NULL)
+ {
+ // Try loading this icon as fallback
+ icon = libr_icon_geticon_byname(handle, entry->name);
+ }
+ if (TDEGlobal::iconLoader()->iconPath(entry->name, 0, true) != "") {
+ iconresnamefound = 1;
+ p = DesktopIcon( entry->name, _size, _state );
+ break;
+ }
+ }
+ }
+
+ if ((iconresnamefound == 0) && (icon)) {
+ // Extract the embedded icon
+ size_t icon_data_length;
+ char* icondata = libr_icon_malloc(icon, &icon_data_length);
+ p.loadFromData(static_cast<uchar*>(static_cast<void*>(icondata)), icon_data_length); // EVIL CAST
+ if (icon_size != 0) {
+ TQImage ip = p.convertToImage();
+ ip = ip.smoothScale(icon_size, icon_size);
+ p.convertFromImage(ip);
+ }
+ free(icondata);
+ libr_icon_close(icon);
+ }
+
+ libr_close(handle);
+#endif // HAVE_ELFICON
+ }
+
+ return p;
+}
+
+bool KFileItem::isReadable() const
+{
+ /*
+ struct passwd * user = getpwuid( geteuid() );
+ bool isMyFile = (TQString::fromLocal8Bit(user->pw_name) == m_user);
+ // This gets ugly for the group....
+ // Maybe we want a static TQString for the user and a static QStringList
+ // for the groups... then we need to handle the deletion properly...
+ */
+
+ if ( m_permissions != KFileItem::Unknown ) {
+ // No read permission at all
+ if ( !(S_IRUSR & m_permissions) && !(S_IRGRP & m_permissions) && !(S_IROTH & m_permissions) )
+ return false;
+
+ // Read permissions for all: save a stat call
+ if ( (S_IRUSR|S_IRGRP|S_IROTH) & m_permissions )
+ return true;
+ }
+
+ // Or if we can't read it [using ::access()] - not network transparent
+ if ( m_bIsLocalURL && ::access( TQFile::encodeName(m_url.path()), R_OK ) == -1 )
+ return false;
+
+ return true;
+}
+
+bool KFileItem::isWritable() const
+{
+ /*
+ struct passwd * user = getpwuid( geteuid() );
+ bool isMyFile = (TQString::fromLocal8Bit(user->pw_name) == m_user);
+ // This gets ugly for the group....
+ // Maybe we want a static TQString for the user and a static QStringList
+ // for the groups... then we need to handle the deletion properly...
+ */
+
+ if ( m_permissions != KFileItem::Unknown ) {
+ // No write permission at all
+ if ( !(S_IWUSR & m_permissions) && !(S_IWGRP & m_permissions) && !(S_IWOTH & m_permissions) )
+ return false;
+ }
+
+ // Or if we can't read it [using ::access()] - not network transparent
+ if ( m_bIsLocalURL && ::access( TQFile::encodeName(m_url.path()), W_OK ) == -1 )
+ return false;
+
+ return true;
+}
+
+bool KFileItem::isHidden() const
+{
+ if ( m_hidden != Auto )
+ return m_hidden == Hidden;
+
+ if ( !m_url.isEmpty() )
+ return m_url.fileName()[0] == '.';
+ else // should never happen
+ return m_strName[0] == '.';
+}
+
+bool KFileItem::isDir() const
+{
+ if ( m_fileMode == KFileItem::Unknown )
+ {
+ kdDebug() << " KFileItem::isDir can't say -> false " << endl;
+ return false; // can't say for sure, so no
+ }
+ return (S_ISDIR(m_fileMode));
+/*
+ if (!S_ISDIR(m_fileMode)) {
+ if (m_url.isLocalFile()) {
+ KMimeType::Ptr ptr=KMimeType::findByURL(m_url,0,true,true);
+ if ((ptr!=0) && (ptr->is("directory/inode"))) return true;
+ }
+ return false
+ } else return true;*/
+}
+
+bool KFileItem::acceptsDrops()
+{
+ // A directory ?
+ if ( S_ISDIR( mode() ) ) {
+ return isWritable();
+ }
+
+ // But only local .desktop files and executables
+ if ( !m_bIsLocalURL )
+ return false;
+
+ if (( mimetype() == "application/x-desktop") ||
+ ( mimetype() == "media/builtin-mydocuments") ||
+ ( mimetype() == "media/builtin-mycomputer") ||
+ ( mimetype() == "media/builtin-mynetworkplaces") ||
+ ( mimetype() == "media/builtin-printers") ||
+ ( mimetype() == "media/builtin-trash") ||
+ ( mimetype() == "media/builtin-webbrowser"))
+ return true;
+
+ // Executable, shell script ... ?
+ if ( ::access( TQFile::encodeName(m_url.path()), X_OK ) == 0 )
+ return true;
+
+ return false;
+}
+
+TQString KFileItem::getStatusBarInfo()
+{
+ TQString text = m_strText;
+
+ if ( m_bLink )
+ {
+ TQString comment = determineMimeType()->comment( m_url, m_bIsLocalURL );
+ TQString tmp;
+ if ( comment.isEmpty() )
+ tmp = i18n ( "Symbolic Link" );
+ else
+ tmp = i18n("%1 (Link)").arg(comment);
+ text += "->";
+ text += linkDest();
+ text += " ";
+ text += tmp;
+ }
+ else if ( S_ISREG( m_fileMode ) )
+ {
+ bool hasSize;
+ TDEIO::filesize_t sizeValue = size(hasSize);
+ if(hasSize)
+ text += TQString(" (%1) ").arg( TDEIO::convertSize( sizeValue ) );
+ text += mimeComment();
+ }
+ else if ( S_ISDIR ( m_fileMode ) )
+ {
+ text += "/ ";
+ text += mimeComment();
+ }
+ else
+ {
+ text += " ";
+ text += mimeComment();
+ }
+ text.replace('\n', " "); // replace any newlines with a space, so the statusbar doesn't get a two-line string which messes the display up, Alex
+ return text;
+}
+
+TQString KFileItem::getToolTipText(int maxcount)
+{
+ // we can return TQString::null if no tool tip should be shown
+ TQString tip;
+ KFileMetaInfo info = metaInfo();
+
+ // the font tags are a workaround for the fact that the tool tip gets
+ // screwed if the color scheme uses white as default text color
+ const char* start = "<tr><td><nobr><font color=\"black\">";
+ const char* mid = "</font></nobr></td><td><nobr><font color=\"black\">";
+ const char* end = "</font></nobr></td></tr>";
+
+ tip = "<table cellspacing=0 cellpadding=0>";
+
+ tip += start + i18n("Name:") + mid + text() + end;
+ tip += start + i18n("Type:") + mid;
+
+ TQString type = TQStyleSheet::escape(mimeComment());
+ if ( m_bLink ) {
+ tip += i18n("Link to %1 (%2)").arg(linkDest(), type) + end;
+ } else
+ tip += type + end;
+
+ if ( !S_ISDIR ( m_fileMode ) ) {
+ bool hasSize;
+ TDEIO::filesize_t sizeValue = size(hasSize);
+ if(hasSize)
+ tip += start + i18n("Size:") + mid +
+ TDEIO::convertSizeWithBytes(sizeValue) + end;
+ }
+ TQString timeStr = timeString( TDEIO::UDS_MODIFICATION_TIME);
+ if(!timeStr.isEmpty())
+ tip += start + i18n("Modified:") + mid +
+ timeStr + end;
+#ifndef Q_WS_WIN //TODO: show win32-specific permissions
+ TQString userStr = user();
+ TQString groupStr = group();
+ if(!userStr.isEmpty() || !groupStr.isEmpty())
+ tip += start + i18n("Owner:") + mid + userStr + " - " + groupStr + end +
+ start + i18n("Permissions:") + mid +
+ parsePermissions(m_permissions) + end;
+#endif
+
+ if (info.isValid() && !info.isEmpty() )
+ {
+ tip += "<tr><td colspan=2><center><s>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</s></center></td></tr>";
+ TQStringList keys = info.preferredKeys();
+
+ // now the rest
+ TQStringList::Iterator it = keys.begin();
+ for (int count = 0; count<maxcount && it!=keys.end() ; ++it)
+ {
+ KFileMetaInfoItem item = info.item( *it );
+ if ( item.isValid() )
+ {
+ TQString s = item.string();
+ if ( ( item.attributes() & KFileMimeTypeInfo::SqueezeText )
+ && s.length() > 50) {
+ s.truncate(47);
+ s.append("...");
+ }
+ if ( !s.isEmpty() )
+ {
+ count++;
+ tip += start +
+ TQStyleSheet::escape( item.translatedKey() ) + ":" +
+ mid +
+ TQStyleSheet::escape( s ) +
+ end;
+ }
+
+ }
+ }
+ }
+ tip += "</table>";
+
+ //kdDebug() << "making this the tool tip rich text:\n";
+ //kdDebug() << tip << endl;
+
+ return tip;
+}
+
+void KFileItem::run()
+{
+ // It might be faster to pass skip that when we know the mimetype,
+ // and just call KRun::runURL. But then we need to use mostLocalURL()
+ // for application/x-desktop files, to be able to execute them.
+ (void) new KRun( m_url, m_fileMode, m_bIsLocalURL );
+}
+
+bool KFileItem::cmp( const KFileItem & item )
+{
+ bool hasSize1,hasSize2,hasTime1,hasTime2;
+ hasSize1 = hasSize2 = hasTime1 = hasTime2 = false;
+ return ( m_strName == item.m_strName
+ && m_bIsLocalURL == item.m_bIsLocalURL
+ && m_fileMode == item.m_fileMode
+ && m_permissions == item.m_permissions
+ && m_user == item.m_user
+ && m_group == item.m_group
+ && m_bLink == item.m_bLink
+ && m_hidden == item.m_hidden
+ && size(hasSize1) == item.size(hasSize2)
+ && hasSize1 == hasSize2
+ && time(TDEIO::UDS_MODIFICATION_TIME, hasTime1) == item.time(TDEIO::UDS_MODIFICATION_TIME, hasTime2)
+ && hasTime1 == hasTime2
+ && (!d || !item.d || d->iconName == item.d->iconName) );
+
+ // Don't compare the mimetypes here. They might not be known, and we don't want to
+ // do the slow operation of determining them here.
+}
+
+void KFileItem::assign( const KFileItem & item )
+{
+ if ( this == &item )
+ return;
+ m_entry = item.m_entry;
+ m_url = item.m_url;
+ m_bIsLocalURL = item.m_bIsLocalURL;
+ m_strName = item.m_strName;
+ m_strText = item.m_strText;
+ m_fileMode = item.m_fileMode;
+ m_permissions = item.m_permissions;
+ m_user = item.m_user;
+ m_group = item.m_group;
+ m_bLink = item.m_bLink;
+ m_pMimeType = item.m_pMimeType;
+ m_strLowerCaseName = item.m_strLowerCaseName;
+ m_bMimeTypeKnown = item.m_bMimeTypeKnown;
+ m_hidden = item.m_hidden;
+ m_guessedMimeType = item.m_guessedMimeType;
+ m_access = item.m_access;
+ m_metaInfo = item.m_metaInfo;
+ for ( int i = 0; i < NumFlags; i++ )
+ m_time[i] = item.m_time[i];
+ m_size = item.m_size;
+ // note: m_extra is NOT copied, as we'd have no control over who is
+ // deleting the data or not.
+
+ // We had a mimetype previously (probably), so we need to re-determine it
+ determineMimeType();
+
+ if ( item.d ) {
+ if ( !d )
+ d = new KFileItemPrivate;
+ d->iconName = item.d->iconName;
+ } else {
+ delete d;
+ d = 0;
+ }
+}
+
+void KFileItem::setUDSEntry( const TDEIO::UDSEntry& _entry, const KURL& _url,
+ bool _determineMimeTypeOnDemand, bool _urlIsDirectory )
+{
+ m_entry = _entry;
+ m_url = _url;
+ m_strName = TQString::null;
+ m_strText = TQString::null;
+ m_user = TQString::null;
+ m_group = TQString::null;
+ m_strLowerCaseName = TQString::null;
+ m_pMimeType = 0;
+ m_fileMode = KFileItem::Unknown;
+ m_permissions = KFileItem::Unknown;
+ m_bMarked = false;
+ m_bLink = false;
+ m_bIsLocalURL = _url.isLocalFile();
+ m_bMimeTypeKnown = false;
+ m_hidden = Auto;
+ m_guessedMimeType = TQString::null;
+ m_metaInfo = KFileMetaInfo();
+
+ if ( d )
+ d->iconName = TQString::null;
+
+ readUDSEntry( _urlIsDirectory );
+ init( _determineMimeTypeOnDemand );
+}
+
+void KFileItem::setFileMode( mode_t m )
+{
+ m_fileMode = m;
+}
+
+void KFileItem::setMimeType( const TQString& mimetype )
+{
+ m_pMimeType = KMimeType::mimeType( mimetype );
+}
+
+void KFileItem::setExtraData( const void *key, void *value )
+{
+ if ( !key )
+ return;
+
+ m_extra.replace( key, value );
+}
+
+const void * KFileItem::extraData( const void *key ) const
+{
+ TQMapConstIterator<const void*,void*> it = m_extra.find( key );
+ if ( it != m_extra.end() )
+ return it.data();
+ return 0L;
+}
+
+void * KFileItem::extraData( const void *key )
+{
+ TQMapIterator<const void*,void*> it = m_extra.find( key );
+ if ( it != m_extra.end() )
+ return it.data();
+ return 0L;
+}
+
+void KFileItem::removeExtraData( const void *key )
+{
+ m_extra.remove( key );
+}
+
+TQString KFileItem::permissionsString() const
+{
+ if (m_access.isNull())
+ m_access = parsePermissions( m_permissions );
+
+ return m_access;
+}
+
+TQString KFileItem::parsePermissions(mode_t perm) const
+{
+ char p[] = "---------- ";
+
+ if (isDir())
+ p[0]='d';
+ else if (isLink())
+ p[0]='l';
+
+ if (perm & TQFileInfo::ReadUser)
+ p[1]='r';
+ if (perm & TQFileInfo::WriteUser)
+ p[2]='w';
+ if ((perm & TQFileInfo::ExeUser) && !(perm & S_ISUID)) p[3]='x';
+ else if ((perm & TQFileInfo::ExeUser) && (perm & S_ISUID)) p[3]='s';
+ else if (!(perm & TQFileInfo::ExeUser) && (perm & S_ISUID)) p[3]='S';
+
+ if (perm & TQFileInfo::ReadGroup)
+ p[4]='r';
+ if (perm & TQFileInfo::WriteGroup)
+ p[5]='w';
+ if ((perm & TQFileInfo::ExeGroup) && !(perm & S_ISGID)) p[6]='x';
+ else if ((perm & TQFileInfo::ExeGroup) && (perm & S_ISGID)) p[6]='s';
+ else if (!(perm & TQFileInfo::ExeGroup) && (perm & S_ISGID)) p[6]='S';
+
+ if (perm & TQFileInfo::ReadOther)
+ p[7]='r';
+ if (perm & TQFileInfo::WriteOther)
+ p[8]='w';
+ if ((perm & TQFileInfo::ExeOther) && !(perm & S_ISVTX)) p[9]='x';
+ else if ((perm & TQFileInfo::ExeOther) && (perm & S_ISVTX)) p[9]='t';
+ else if (!(perm & TQFileInfo::ExeOther) && (perm & S_ISVTX)) p[9]='T';
+
+ if (hasExtendedACL())
+ p[10]='+';
+
+ return TQString::fromLatin1(p);
+}
+
+// check if we need to cache this
+TQString KFileItem::timeString( unsigned int which ) const
+{
+ bool hasTime;
+ time_t time_ = time(which, hasTime);
+ if(!hasTime) return TQString::null;
+
+ TQDateTime t;
+ t.setTime_t( time_);
+ return TDEGlobal::locale()->formatDateTime( t );
+}
+
+void KFileItem::setMetaInfo( const KFileMetaInfo & info )
+{
+ m_metaInfo = info;
+}
+
+const KFileMetaInfo & KFileItem::metaInfo(bool autoget, int) const
+{
+ bool isLocalURL;
+ KURL url = mostLocalURL(isLocalURL);
+
+ if ( autoget && !m_metaInfo.isValid() &&
+ TDEGlobalSettings::showFilePreview(url) )
+ {
+ m_metaInfo = KFileMetaInfo( url, mimetype() );
+ }
+
+ return m_metaInfo;
+}
+
+KURL KFileItem::mostLocalURL(bool &local) const
+{
+ TQString local_path = localPath();
+
+ if ( !local_path.isEmpty() )
+ {
+ local = true;
+ KURL url;
+ url.setPath(local_path);
+ return url;
+ }
+ else
+ {
+ local = m_bIsLocalURL;
+ return m_url;
+ }
+}
+
+void KFileItem::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+TQDataStream & operator<< ( TQDataStream & s, const KFileItem & a )
+{
+ // We don't need to save/restore anything that refresh() invalidates,
+ // since that means we can re-determine those by ourselves.
+ s << a.m_url;
+ s << a.m_strName;
+ s << a.m_strText;
+ return s;
+}
+
+TQDataStream & operator>> ( TQDataStream & s, KFileItem & a )
+{
+ s >> a.m_url;
+ s >> a.m_strName;
+ s >> a.m_strText;
+ a.m_bIsLocalURL = a.m_url.isLocalFile();
+ a.m_bMimeTypeKnown = false;
+ a.refresh();
+ return s;
+}
diff --git a/tdeio/tdeio/tdefileitem.h b/tdeio/tdeio/tdefileitem.h
new file mode 100644
index 000000000..7097d7bc5
--- /dev/null
+++ b/tdeio/tdeio/tdefileitem.h
@@ -0,0 +1,671 @@
+/* This file is part of the KDE project
+ Copyright (C) 1999 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __tdefileitem_h__
+#define __tdefileitem_h__
+
+#include <tqstringlist.h>
+#include <sys/stat.h>
+
+#include <tqptrlist.h>
+#include <tdeio/global.h>
+#include <kurl.h>
+#include <kacl.h>
+#include <kmimetype.h>
+#include <tdefilemetainfo.h>
+
+#define KFILEITEM_HAS_ISWRITABLE // only used in libkonq/konq_iconviewwidget.cc, will be removed for 3.4
+
+/**
+ * A KFileItem is a generic class to handle a file, local or remote.
+ * In particular, it makes it easier to handle the result of TDEIO::listDir
+ * (UDSEntry isn't very friendly to use).
+ * It includes many file attributes such as mimetype, icon, text, mode, link...
+ */
+class TDEIO_EXPORT KFileItem
+{
+public:
+ enum { Unknown = (mode_t) - 1 };
+
+ /**
+ * Creates an item representing a file, from a UDSEntry.
+ * This is the preferred constructor when using TDEIO::listDir().
+ *
+ * @param _entry the KIO entry used to get the file, contains info about it
+ * @param _url the file url
+ * @param _determineMimeTypeOnDemand specifies if the mimetype of the given
+ * URL should be determined immediately or on demand
+ * @param _urlIsDirectory specifies if the url is just the directory of the
+ * fileitem and the filename from the UDSEntry should be used.
+ */
+ KFileItem( const TDEIO::UDSEntry& _entry, const KURL& _url,
+ bool _determineMimeTypeOnDemand = false,
+ bool _urlIsDirectory = false );
+
+ /**
+ * Creates an item representing a file, from all the necessary info for it.
+ * @param _mode the file mode (according to stat() (e.g. S_IFDIR...)
+ * Set to KFileItem::Unknown if unknown. For local files, KFileItem will use stat().
+ * @param _permissions the access permissions
+ * If you set both the mode and the permissions, you save a ::stat() for
+ * local files.
+ * Set to KFileItem::Unknown if you don't know the mode or the permission.
+ * @param _url the file url
+ *
+ * @param _determineMimeTypeOnDemand specify if the mimetype of the given URL
+ * should be determined immediately or on demand
+ */
+ KFileItem( mode_t _mode, mode_t _permissions, const KURL& _url,
+ bool _determineMimeTypeOnDemand = false );
+
+ /**
+ * Creates an item representing a file, for which the mimetype is already known.
+ * @param url the file url
+ * @param mimeType the name of the file's mimetype
+ * @param mode the mode (S_IFDIR...)
+ */
+ KFileItem( const KURL &url, const TQString &mimeType, mode_t mode );
+
+ /**
+ * Copy constructor. Note that extra-data set via setExtraData() is not
+ * deeply copied -- just the pointers are copied.
+ */
+ KFileItem( const KFileItem &item );
+
+ /**
+ * Destructs the KFileItem. Extra data set via setExtraData()
+ * is not deleted.
+ */
+ virtual ~KFileItem();
+
+ /**
+ * Throw away and re-read (for local files) all information about the file.
+ * This is called when the _file_ changes.
+ */
+ void refresh();
+
+ /**
+ * Re-reads mimetype information.
+ * This is called when the mimetype database changes.
+ */
+ void refreshMimeType();
+
+ /**
+ * Returns the url of the file.
+ * @return the url of the file
+ */
+ const KURL & url() const { return m_url; }
+
+ /**
+ * Sets the item's URL. Do not call unless you know what you are doing!
+ * (used for example when an item got renamed).
+ * @param url the item's URL
+ */
+ void setURL( const KURL &url );
+
+ /**
+ * Sets the item's name (i.e. the filename).
+ * This is automatically done by setURL, to set the name from the URL's fileName().
+ * This method is provided for some special cases like relative paths as names (KFindPart)
+ * @param name the item's name
+ */
+ void setName( const TQString &name );
+
+ /**
+ * Returns the permissions of the file (stat.st_mode containing only permissions).
+ * @return the permissions of the file
+ */
+ mode_t permissions() const { return m_permissions; }
+
+ /**
+ * Returns the access permissions for the file as a string.
+ * @return the access persmission as string
+ */
+ TQString permissionsString() const;
+
+ /**
+ * Tells if the file has extended access level information ( Posix ACL )
+ * @return true if the file has extend ACL information or false if it hasn't
+ * @since 3.5
+ */
+ bool hasExtendedACL() const;
+
+ /**
+ * Returns the access control list for the file.
+ * @return the access control list as a KACL
+ * @since 3.5
+ */
+ KACL ACL() const;
+
+ /**
+ * Returns the default access control list for the directory.
+ * @return the default access control list as a KACL
+ * @since 3.5
+ */
+ KACL defaultACL() const;
+
+ /**
+ * Returns the file type (stat.st_mode containing only S_IFDIR, S_IFLNK, ...).
+ * @return the file type
+ */
+ mode_t mode() const { return m_fileMode; }
+
+ /**
+ * Returns the owner of the file.
+ * @return the file's owner
+ */
+ TQString user() const;
+
+ /**
+ * Returns the group of the file.
+ * @return the file's group
+ */
+ TQString group() const;
+
+ /**
+ * Returns true if this item represents a link in the UNIX sense of
+ * a link.
+ * @return true if the file is a link
+ */
+ bool isLink() const { return m_bLink; }
+
+ /**
+ * Returns true if this item represents a directory.
+ * @return true if the item is a directory
+ */
+ bool isDir() const;
+
+ /**
+ * Returns true if this item represents a file (and not a a directory)
+ * @return true if the item is a file
+ */
+ bool isFile() const { return !isDir(); }
+
+ /**
+ * Checks whether the file or directory is readable. In some cases
+ * (remote files), we may return true even though it can't be read.
+ * @return true if the file can be read - more precisely,
+ * false if we know for sure it can't
+ */
+ bool isReadable() const;
+
+ /**
+ * Checks whether the file or directory is writable. In some cases
+ * (remote files), we may return true even though it can't be written to.
+ * @return true if the file or directory can be written to - more precisely,
+ * false if we know for sure it can't
+ * @since 3.4
+ */
+ bool isWritable() const;
+
+ /**
+ * Checks whether the file is hidden.
+ * @return true if the file is hidden.
+ */
+ bool isHidden() const;
+
+ /**
+ * Returns the link destination if isLink() == true.
+ * @return the link destination. TQString::null if the item is not a link
+ */
+ TQString linkDest() const;
+
+ /**
+ * Returns the local path if isLocalFile() == true or the KIO item has
+ * a UDS_LOCAL_PATH atom.
+ * @return the item local path, or TQString::null if not known
+ * @since 3.4
+ */
+ TQString localPath() const;
+
+ //FIXME KDE4 deprecate this in favor of size(bool &hasSize)
+ /**
+ * Returns the size of the file, if known.
+ * @return the file size, or 0 if not known
+ */
+ TDEIO::filesize_t size() const;
+
+ /**
+ * Returns the size of the file, if known, and sets @p hasSize to false if not known
+ * @param @hasSize This is set to true if the size is known, and false if not known
+ * @return the file size, or 0 if not known
+ */
+ TDEIO::filesize_t size(bool &hasSize) const;
+
+ //FIXME KDE4 deprecate this in favor of time(unsigned int which, bool &hasSize)
+ /**
+ * Requests the modification, access or creation time, depending on @p which.
+ * @param which UDS_MODIFICATION_TIME, UDS_ACCESS_TIME or UDS_CREATION_TIME
+ * @return the time asked for, (time_t)0 if not available
+ * @see timeString()
+ */
+ time_t time( unsigned int which ) const;
+
+ /**
+ * Requests the modification, access or creation time, depending on @p which.
+ * @param which UDS_MODIFICATION_TIME, UDS_ACCESS_TIME or UDS_CREATION_TIME
+ * @param hasTime This is set to true is the time is known, and false if not known
+ * @return the time asked for, (time_t)0 if not known/available
+ * @see timeString()
+ */
+ time_t time( unsigned int which, bool &hasTime ) const;
+
+ /**
+ * Requests the modification, access or creation time as a string, depending
+ * on @p which.
+ * @param which UDS_MODIFICATION_TIME, UDS_ACCESS_TIME or UDS_CREATION_TIME
+ * @returns a formatted string of the requested time, TQString::null if time is not known
+ * @see time
+ */
+ TQString timeString( unsigned int which = TDEIO::UDS_MODIFICATION_TIME ) const;
+
+ /**
+ * Returns true if the file is a local file.
+ * @return true if the file is local, false otherwise
+ */
+ bool isLocalFile() const { return m_bIsLocalURL; }
+
+ /**
+ * Returns the text of the file item.
+ * It's not exactly the filename since some decoding happens ('%2F'->'/').
+ * @return the text of the file item
+ */
+ const TQString& text() const { return m_strText; }
+
+ /**
+ * Return the name of the file item (without a path).
+ * Similar to text(), but unencoded, i.e. the original name.
+ * @param lowerCase if true, the name will be returned in lower case,
+ * which is useful to speed up sorting by name, case insensitively.
+ * @return the file's name
+ */
+ const TQString& name( bool lowerCase = false ) const {
+ if ( !lowerCase )
+ return m_strName;
+ else
+ if ( m_strLowerCaseName.isNull() )
+ m_strLowerCaseName = m_strName.lower();
+ return m_strLowerCaseName;
+ }
+
+ /**
+ * Returns the mimetype of the file item.
+ * If @p _determineMimeTypeOnDemand was used in the constructor, this will determine
+ * the mimetype first. Equivalent to determineMimeType()->name()
+ * @return the mime type of the file
+ */
+ TQString mimetype() const;
+
+ /**
+ * Returns the mimetype of the file item.
+ * If _determineMimeTypeOnDemand was used in the constructor, this will determine
+ * the mimetype first.
+ * @return the mime type
+ */
+ KMimeType::Ptr determineMimeType();
+
+ /**
+ * Returns the currently known mimetype of the file item.
+ * This will not try to determine the mimetype if unknown.
+ * @return the known mime type
+ */
+ KMimeType::Ptr mimeTypePtr() const { return m_pMimeType; }
+
+ bool isMimeTypeKnown() const;
+ /**
+ * Returns the descriptive comment for this mime type, or
+ * the mime type itself if none is present.
+ * @return the mime type description, or the mime type itself
+ */
+ TQString mimeComment();
+
+ /**
+ * Returns the full path name to the icon that represents
+ * this mime type.
+ * @return iconName the name of the file's icon
+ */
+ TQString iconName();
+
+ /**
+ * Returns a pixmap representing the file.
+ * @param _size Size for the pixmap in pixels. Zero will return the
+ * globally configured default size.
+ * @param _state The state of the icon: KIcon::DefaultState,
+ * KIcon::ActiveState or KIcon::DisabledState.
+ * @return the pixmap
+ */
+ TQPixmap pixmap( int _size, int _state=0 ) const;
+
+ /**
+ * Returns the overlays (bitfield of KIcon::*Overlay flags) that are used
+ * for this item's pixmap. Overlays are used to show for example, whether
+ * a file can be modified.
+ * @return the overlays of the pixmap
+ */
+ int overlays() const;
+
+ /**
+ * Returns the string to be displayed in the statusbar,
+ * e.g. when the mouse is over this item
+ * @return the status bar information
+ */
+ TQString getStatusBarInfo();
+
+ /**
+ * Returns the string to be displayed in the tool tip when the mouse
+ * is over this item. This may load a plugin to determine additional
+ * information specific to the mimetype of the file.
+ *
+ * @param maxcount the maximum number of entries shown
+ * @return the tool tip string
+ */
+ TQString getToolTipText(int maxcount = 6);
+
+ /**
+ * Returns true if files can be dropped over this item.
+ * Contrary to popular belief, not only dirs will return true :)
+ * Executables, .desktop files, will do so as well.
+ * @return true if you can drop files over the item
+ */
+ bool acceptsDrops( );
+
+ /**
+ * Let's "KRun" this file !
+ * (e.g. when file is clicked or double-clicked or return is pressed)
+ */
+ void run();
+
+ /**
+ * Returns the UDS entry. Used by the tree view to access all details
+ * by position.
+ * @return the UDS entry
+ */
+ const TDEIO::UDSEntry & entry() const { return m_entry; }
+
+ /**
+ * Used when updating a directory. marked == seen when refreshing.
+ * @return true if the file item is marked
+ */
+ bool isMarked() const { return m_bMarked; }
+ /**
+ * Marks the item.
+ * @see isMarked()
+ */
+ void mark() { m_bMarked = true; }
+ /**
+ * Unmarks the item.
+ * @see isMarked()
+ */
+ void unmark() { m_bMarked = false; }
+
+ /**
+ * Somewhat like a comparison operator, but more explicit.
+ * @param item the item to compare
+ * @return true if all values are equal
+ */
+ bool cmp( const KFileItem & item );
+
+ /**
+ * This allows to associate some "extra" data to a KFileItem. As one
+ * KFileItem can be used by several objects (often views) which all need
+ * to add some data, you have to use a key to reference your extra data
+ * within the KFileItem.
+ *
+ * That way a KFileItem can hold and provide access to all those views
+ * separately.
+ *
+ * I.e. a KFileIconView that associates a KFileIconViewItem (an item suitable
+ * for use with TQIconView) does
+ *
+ * \code
+ * tdefileItem->setExtraData( this, iconViewItem );
+ * \endcode
+ *
+ * and can later access the iconViewItem by doing
+ *
+ * \code
+ * KFileIconViewItem *iconViewItem = static_cast<KFileIconViewItem*>( tdefileItem->extraData( this ));
+ * \endcode
+ *
+ * This is usually more efficient then having every view associate data to
+ * items by using a separate TQDict or TQMap.
+ *
+ * Note: you have to remove and destroy the data you associated yourself
+ * when you don't need it anymore!
+ *
+ * @param key the key of the extra data
+ * @param value the value of the extra data
+ * @see extraData
+ * @see removeExtraData
+ */
+ virtual void setExtraData( const void *key, void *value );
+
+ /**
+ * Retrieves the extra data with the given @p key.
+ * @param key the key of the extra data
+ * @return the extra data associated to an item with @p key via
+ * setExtraData. 0L if nothing was associated with @p key.
+ * @see extraData
+ */
+ virtual const void * extraData( const void *key ) const;
+
+ /**
+ * Retrieves the extra data with the given @p key.
+ * @param key the key of the extra data
+ * @return the extra data associated to an item with @p key via
+ * setExtraData. 0L if nothing was associated with @p key.
+ * @see extraData
+ */
+ virtual void * extraData( const void *key );
+
+ /**
+ * Removes the extra data associated with an item via @p key.
+ * @param key the key of the extra data to remove
+ */
+ virtual void removeExtraData( const void *key );
+
+ /**
+ * Sets the metainfo of this item to @p info.
+ * @param info the new meta info
+ */
+ void setMetaInfo( const KFileMetaInfo & info );
+
+ /**
+ * Sets the file type (stat.st_mode containing only S_IFDIR, S_IFLNK, ...).
+ * @param m the new file type
+ * @since 3.5.0
+ * @todo Actually explain what this does -- does setting S_IFDIR
+ * mean the file type is set to Directory?
+ */
+ void setFileMode( mode_t m );
+
+ /**
+ * Sets new mimetype for item
+ * @param mimetype the new mimetype
+ * @since 3.5.0
+ */
+ void setMimeType( const TQString& mimetype );
+
+ /**
+ * Returns the metainfo of this item.
+ * @param autoget if true, the metainfo will automatically be created
+ * @param what ignored
+ */
+ const KFileMetaInfo & metaInfo(bool autoget = true,
+ int what = KFileMetaInfo::Fastest) const;
+
+ /**
+ * Somewhat like an assignment operator, but more explicit.
+ * Note: extra-data set with setExtraData() is not copied, so be careful
+ * what you do!
+ *
+ * @param item the item to copy
+ */
+ void assign( const KFileItem & item );
+
+ /**
+ * Reinitialize KFileItem with a new UDSEntry.
+ *
+ * Note: extra-data set with setExtraData() is not changed or deleted, so
+ * be careful what you do!
+ *
+ * KDirListerCache uses it to save new/delete calls by updating existing
+ * items that are otherwise not needed anymore.
+ *
+ * @param entry the UDSEntry to assign to this KFileItem
+ * @param url the file url
+ * @param determineMimeTypeOnDemand specifies if the mimetype of the given
+ * URL should be determined immediately or on demand
+ * @param urlIsDirectory specifies if the url is just the directory of the
+ * fileitem and the filename from the UDSEntry should be used.
+ * @since 3.4.1
+ */
+ void setUDSEntry( const TDEIO::UDSEntry& entry, const KURL& url,
+ bool determineMimeTypeOnDemand = false,
+ bool urlIsDirectory = false );
+
+ /**
+ * Assignment operator, calls assign()
+ */
+ KFileItem& operator=( const KFileItem& );
+
+ /**
+ * Tries to give a local URL for this file item if possible.
+ * The given boolean indicates if the returned url is local or not.
+ */
+ KURL mostLocalURL(bool &local) const;
+
+ /////////////
+
+protected:
+ /**
+ * Computes the text, mode, and mimetype from the UDSEntry
+ * Called by constructor, but can be called again later
+ */
+ void init( bool _determineMimeTypeOnDemand );
+
+ /**
+ * Extracts the data from the UDSEntry member and updates the KFileItem
+ * accordingly.
+ * @since 3.4.1
+ */
+ void readUDSEntry( bool _urlIsDirectory );
+
+ /**
+ * Parses the given permission set and provides it for access()
+ */
+ TQString parsePermissions( mode_t perm ) const;
+
+private:
+ /**
+ * We keep a copy of the UDSEntry since we need it for getStatusBarInfo
+ */
+ TDEIO::UDSEntry m_entry;
+ /**
+ * The url of the file
+ */
+ KURL m_url;
+
+ /**
+ * The text for this item, i.e. the file name without path,
+ */
+ TQString m_strName;
+
+ /**
+ * The text for this item, i.e. the file name without path, decoded
+ * ('%%' becomes '%', '%2F' becomes '/')
+ */
+ TQString m_strText;
+
+ /**
+ * the user and group assigned to the file.
+ */
+ mutable TQString m_user, m_group;
+
+ /**
+ * The filename in lower case (to speed up sorting)
+ */
+ mutable TQString m_strLowerCaseName;
+
+ /**
+ * The mimetype of the file
+ */
+ KMimeType::Ptr m_pMimeType;
+
+ /**
+ * The file mode
+ */
+ mode_t m_fileMode;
+ /**
+ * The permissions
+ */
+ mode_t m_permissions;
+
+ /**
+ * Marked : see mark()
+ */
+ bool m_bMarked:1;
+ /**
+ * Whether the file is a link
+ */
+ bool m_bLink:1;
+ /**
+ * True if local file
+ */
+ bool m_bIsLocalURL:1;
+
+ bool m_bMimeTypeKnown:1;
+
+ // Auto: check leading dot.
+ enum { Auto, Hidden, Shown } m_hidden:3;
+
+ // For special case like link to dirs over FTP
+ TQString m_guessedMimeType;
+ mutable TQString m_access;
+ TQMap<const void*, void*> m_extra;
+ mutable KFileMetaInfo m_metaInfo;
+
+ enum { Modification = 0, Access = 1, Creation = 2, NumFlags = 3 };
+ mutable time_t m_time[3];
+ mutable TDEIO::filesize_t m_size;
+
+protected:
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KFileItemPrivate;
+ KFileItemPrivate * d;
+ TDEIO_EXPORT friend TQDataStream & operator<< ( TQDataStream & s, const KFileItem & a );
+ TDEIO_EXPORT friend TQDataStream & operator>> ( TQDataStream & s, KFileItem & a );
+};
+
+/**
+ * List of KFileItems
+ */
+typedef TQPtrList<KFileItem> KFileItemList;
+
+/**
+ * Iterator for KFileItemList
+ */
+typedef TQPtrListIterator<KFileItem> KFileItemListIterator;
+
+TDEIO_EXPORT TQDataStream & operator<< ( TQDataStream & s, const KFileItem & a );
+TDEIO_EXPORT TQDataStream & operator>> ( TQDataStream & s, KFileItem & a );
+
+
+#endif
diff --git a/tdeio/tdeio/tdefilemetainfo.cpp b/tdeio/tdeio/tdefilemetainfo.cpp
new file mode 100644
index 000000000..4943dea93
--- /dev/null
+++ b/tdeio/tdeio/tdefilemetainfo.cpp
@@ -0,0 +1,1859 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (C) 2001-2002 Rolf Magnus <ramagnus@kde.org>
+ * Copyright (C) 2001-2002 Carsten Pfeiffer <pfeiffer@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation version 2.0.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ * $Id$
+ */
+
+#include <assert.h>
+
+#include <tqshared.h>
+#include <tqdict.h>
+
+#include <ktrader.h>
+#include <kstaticdeleter.h>
+#include <tdeparts/componentfactory.h>
+#include <kuserprofile.h>
+#include <kdebug.h>
+#include <kmimetype.h>
+#include <kdatastream.h> // needed for serialization of bool
+#include <klocale.h>
+#include <tdeio/global.h>
+
+#include "tdefilemetainfo.h"
+
+// shared data of a KFileMetaInfoItem
+class KFileMetaInfoItem::Data : public TQShared
+{
+public:
+ Data( const KFileMimeTypeInfo::ItemInfo* mti, const TQString& _key,
+ const TQVariant& _value )
+ : TQShared(),
+ mimeTypeInfo( mti ),
+ key( _key ),
+ value( _value ),
+ dirty( false ),
+ added( false ),
+ removed( false )
+ {}
+
+ // we use this one for the streaming operators
+ Data() : mimeTypeInfo( 0L )
+ {}
+
+ ~Data()
+ {
+ if ( this == null ) // only the null item owns its mimeTypeInfo
+ delete mimeTypeInfo;
+ }
+
+ const KFileMimeTypeInfo::ItemInfo* mimeTypeInfo;
+ // mimeTypeInfo has the key, too, but only for non-variable ones
+ TQString key;
+ TQVariant value;
+ bool dirty :1;
+ bool added :1;
+ bool removed :1;
+
+ static Data* null;
+ static Data* makeNull();
+};
+
+//this is our null data
+KFileMetaInfoItem::Data* KFileMetaInfoItem::Data::null = 0L;
+static KStaticDeleter<KFileMetaInfoItem::Data> sd_KFileMetaInfoItemData;
+
+KFileMetaInfoItem::Data* KFileMetaInfoItem::Data::makeNull()
+{
+ if (!null)
+ {
+ // We deliberately do not reset "null" after it has been destroyed!
+ // Otherwise we will run into problems later in ~KFileMetaInfoItem
+ // where the d-pointer is compared against null.
+
+ KFileMimeTypeInfo::ItemInfo* info = new KFileMimeTypeInfo::ItemInfo();
+ null = new Data(info, TQString::null, TQVariant());
+ sd_KFileMetaInfoItemData.setObject( null );
+ }
+ return null;
+}
+
+KFileMetaInfoItem::KFileMetaInfoItem( const KFileMimeTypeInfo::ItemInfo* mti,
+ const TQString& key, const TQVariant& value )
+ : d( new Data( mti, key, value ) )
+{
+}
+
+KFileMetaInfoItem::KFileMetaInfoItem( const KFileMetaInfoItem& item )
+{
+ // operator= does everything that's necessary
+ d = Data::makeNull();
+ *this = item;
+}
+
+KFileMetaInfoItem::KFileMetaInfoItem()
+{
+ d = Data::makeNull();
+}
+
+KFileMetaInfoItem::~KFileMetaInfoItem()
+{
+ deref();
+}
+
+const KFileMetaInfoItem& KFileMetaInfoItem::operator=
+ (const KFileMetaInfoItem & item )
+{
+ if (d != item.d)
+ {
+ // first deref the old one
+ deref();
+ d = item.d;
+ // and now ref the new one
+ ref();
+ }
+
+ return *this;
+}
+
+bool KFileMetaInfoItem::setValue( const TQVariant& value )
+{
+ // We don't call makeNull here since it isn't necassery, see deref()
+ if ( d == Data::null ) return false;
+
+ if ( ! (d->mimeTypeInfo->attributes() & KFileMimeTypeInfo::Modifiable ) ||
+ ! (value.canCast(d->mimeTypeInfo->type())))
+ {
+ kdDebug(7033) << "setting the value of " << key() << "failed\n";
+ return false;
+ }
+
+// kdDebug(7033) << key() << ".setValue()\n";
+
+ if ( d->value == value )
+ return true;
+
+ d->dirty = true;
+ d->value = value;
+ // If we don't cast (and test for canCast in the above if), TQVariant is
+ // very picky about types (e.g. TQString vs. TQCString or int vs. uint)
+ d->value.cast(d->mimeTypeInfo->type());
+
+ return true;
+}
+
+bool KFileMetaInfoItem::isRemoved() const
+{
+ return d->removed;
+}
+
+TQString KFileMetaInfoItem::key() const
+{
+ return d->key;
+}
+
+TQString KFileMetaInfoItem::translatedKey() const
+{
+ // are we a variable key?
+ if (d->mimeTypeInfo->key().isNull())
+ {
+ // then try if we have luck with i18n()
+ return i18n(d->key.utf8());
+ }
+
+ return d->mimeTypeInfo->translatedKey();
+}
+
+const TQVariant& KFileMetaInfoItem::value() const
+{
+ return d->value;
+}
+
+TQString KFileMetaInfoItem::string( bool mangle ) const
+{
+ return d->mimeTypeInfo->string(d->value, mangle);
+}
+
+TQVariant::Type KFileMetaInfoItem::type() const
+{
+ return d->mimeTypeInfo->type();
+}
+
+uint KFileMetaInfoItem::unit() const
+{
+ return d->mimeTypeInfo->unit();
+}
+
+bool KFileMetaInfoItem::isModified() const
+{
+ return d->dirty;
+}
+
+TQString KFileMetaInfoItem::prefix() const
+{
+ return d->mimeTypeInfo->prefix();
+}
+
+TQString KFileMetaInfoItem::suffix() const
+{
+ return d->mimeTypeInfo->suffix();
+}
+
+uint KFileMetaInfoItem::hint() const
+{
+ return d->mimeTypeInfo->hint();
+}
+
+uint KFileMetaInfoItem::attributes() const
+{
+ return d->mimeTypeInfo->attributes();
+}
+
+bool KFileMetaInfoItem::isEditable() const
+{
+ return d->mimeTypeInfo->attributes() & KFileMimeTypeInfo::Modifiable;
+}
+
+bool KFileMetaInfoItem::isValid() const
+{
+ // We don't call makeNull here since it isn't necassery:
+ // If d is equal to null it means that null is initialized already.
+ // null is 0L when it hasn't been initialized and d is never 0L.
+ return d != Data::null;
+}
+
+void KFileMetaInfoItem::setAdded()
+{
+ d->added = true;
+}
+
+void KFileMetaInfoItem::setRemoved()
+{
+ d->removed = true;
+}
+
+void KFileMetaInfoItem::ref()
+{
+ if (d != Data::null) d->ref();
+}
+
+void KFileMetaInfoItem::deref()
+{
+ // We don't call makeNull here since it isn't necassery:
+ // If d is equal to null it means that null is initialized already.
+ // null is 0L when it hasn't been initialized and d is never 0L.
+ if ((d != Data::null) && d->deref())
+ {
+// kdDebug(7033) << "item " << d->key
+// << " is finally deleted\n";
+ delete d;
+ d = 0;
+ }
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+// shared data of a KFileMetaInfo
+class KFileMetaInfo::Data : public TQShared
+{
+public:
+ Data(const KURL& _url, uint _what)
+ : TQShared(),
+ url(_url),
+ what(_what),
+ mimeTypeInfo( 0L )
+ {}
+
+ // wee use this one for the streaming operators
+ Data() {};
+
+ KURL url;
+ uint what;
+ TQMap<TQString, KFileMetaInfoGroup> groups;
+ const KFileMimeTypeInfo* mimeTypeInfo;
+ TQStringList removedGroups;
+
+ static Data* null;
+ static Data* makeNull();
+
+};
+
+KFileMetaInfo::KFileMetaInfo( const TQString& path, const TQString& mimeType,
+ uint what )
+{
+ KURL u;
+
+ u.setPath(path);
+ init(u, mimeType, what);
+}
+
+KFileMetaInfo::KFileMetaInfo( const KURL& url, const TQString& mimeType,
+ uint what )
+{
+ init(url, mimeType, what);
+}
+
+void KFileMetaInfo::init( const KURL& url, const TQString& mimeType,
+ uint what )
+{
+ d = new Data( url, what );
+
+ TQString mT;
+ if (mimeType.isEmpty())
+ mT = KMimeType::findByURL(url)->name();
+ else
+ mT = mimeType;
+
+ // let's "share our property"
+ KFileMetaInfo item(*this);
+
+ //kdDebug() << k_funcinfo << mT << " " << url << endl;
+
+ d->mimeTypeInfo = KFileMetaInfoProvider::self()->mimeTypeInfo( mT, url.protocol() );
+ if ( d->mimeTypeInfo )
+ {
+ //kdDebug(7033) << "Found mimetype info for " << mT /* or protocol*/ << endl;
+ KFilePlugin *p = plugin();
+ Q_ASSERT( p );
+ if ( p && !p->readInfo( item, what) )
+ {
+ deref();
+ d = Data::makeNull();
+ }
+ }
+ else
+ {
+// kdDebug(7033) << "No mimetype info for " << mimeType << endl;
+ deref();
+ d = Data::makeNull();
+ }
+}
+
+KFileMetaInfo::KFileMetaInfo( const KFileMetaInfo& original )
+{
+ // operator= does everything that's necessary
+ d = Data::makeNull();
+ *this = original;
+}
+
+KFileMetaInfo::KFileMetaInfo()
+{
+ d = Data::makeNull();
+}
+
+KFileMetaInfo::~KFileMetaInfo()
+{
+ deref();
+}
+
+TQStringList KFileMetaInfo::supportedGroups() const
+{
+ assert(isValid());
+ return d->mimeTypeInfo->supportedGroups();
+}
+
+TQStringList KFileMetaInfo::supportedKeys() const
+{
+ assert(isValid());
+ return d->mimeTypeInfo->supportedKeys();
+}
+
+TQStringList KFileMetaInfo::groups() const
+{
+ TQStringList list;
+ TQMapConstIterator<TQString, KFileMetaInfoGroup> it = d->groups.begin();
+ for ( ; it != d->groups.end(); ++it )
+ list += (*it).name();
+
+ return list;
+}
+
+TQStringList KFileMetaInfo::editableGroups() const
+{
+ TQStringList list;
+ TQStringList supported = supportedGroups();
+ TQStringList::ConstIterator it = supported.begin();
+ for ( ; it != supported.end(); ++it ) {
+ const KFileMimeTypeInfo::GroupInfo * groupInfo = d->mimeTypeInfo->groupInfo( *it );
+ if ( groupInfo && groupInfo->attributes() &
+ (KFileMimeTypeInfo::Addable | KFileMimeTypeInfo::Removable) )
+ list.append( *it );
+ }
+
+ return list;
+}
+
+TQStringList KFileMetaInfo::preferredGroups() const
+{
+ assert(isValid());
+ TQStringList list = groups();
+ TQStringList newlist;
+ TQStringList preferred = d->mimeTypeInfo->preferredGroups();
+ TQStringList::Iterator pref;
+
+ // move all keys from the preferred groups that are in our list to a new list
+ for ( pref = preferred.begin(); pref != preferred.end(); ++pref )
+ {
+ TQStringList::Iterator group = list.find(*pref);
+ if ( group != list.end() )
+ {
+ newlist.append( *group );
+ list.remove(group);
+ }
+ }
+
+ // now the old list only contains the non-preferred items, so we
+ // add the remaining ones to newlist
+ newlist += list;
+
+ return newlist;
+}
+
+TQStringList KFileMetaInfo::preferredKeys() const
+{
+ TQStringList newlist;
+
+ TQStringList list = preferredGroups();
+ for (TQStringList::Iterator git = list.begin(); git != list.end(); ++git)
+ {
+ newlist += d->groups[*git].preferredKeys();
+ }
+
+ return newlist;
+}
+
+KFileMetaInfoGroup KFileMetaInfo::group(const TQString& key) const
+{
+ TQMapIterator<TQString,KFileMetaInfoGroup> it = d->groups.find( key );
+ if ( it != d->groups.end() )
+ return it.data();
+ else
+ return KFileMetaInfoGroup();
+}
+
+bool KFileMetaInfo::addGroup( const TQString& name )
+{
+ assert(isValid());
+ if ( d->mimeTypeInfo->supportedGroups().contains(name) &&
+ ! d->groups.contains(name) )
+ {
+ KFileMetaInfoGroup group( name, d->mimeTypeInfo );
+
+ // add all the items that can't be added by the user later
+ const KFileMimeTypeInfo::GroupInfo* ginfo = d->mimeTypeInfo->groupInfo(name);
+ Q_ASSERT(ginfo);
+ if (!ginfo) return false;
+
+ TQStringList keys = ginfo->supportedKeys();
+ for (TQStringList::Iterator it = keys.begin(); it != keys.end(); ++it)
+ {
+ const KFileMimeTypeInfo::ItemInfo* iteminfo = ginfo->itemInfo(*it);
+ Q_ASSERT(ginfo);
+ if (!iteminfo) return false;
+
+ if ( !(iteminfo->attributes() & KFileMimeTypeInfo::Addable) &&
+ (iteminfo->attributes() & KFileMimeTypeInfo::Modifiable))
+ {
+ // append it now or never
+ group.appendItem(iteminfo->key(), TQVariant());
+ }
+
+ }
+
+ d->groups.insert(name, group);
+ group.setAdded();
+ return true;
+ }
+
+ return false;
+}
+
+bool KFileMetaInfo::removeGroup( const TQString& name )
+{
+ TQMapIterator<TQString, KFileMetaInfoGroup> it = d->groups.find(name);
+ if ( (it==d->groups.end()) ||
+ !((*it).attributes() & KFileMimeTypeInfo::Removable))
+ return false;
+
+ d->groups.remove(it);
+ d->removedGroups.append(name);
+ return true;
+}
+
+TQStringList KFileMetaInfo::removedGroups()
+{
+ return d->removedGroups;
+}
+
+const KFileMetaInfo& KFileMetaInfo::operator= (const KFileMetaInfo& info )
+{
+ if (d != info.d)
+ {
+ deref();
+ // first deref the old one
+ d = info.d;
+ // and now ref the new one
+ ref();
+ }
+ return *this;
+}
+
+bool KFileMetaInfo::isValid() const
+{
+ // We don't call makeNull here since it isn't necassery, see deref()
+ return d != Data::null;
+}
+
+bool KFileMetaInfo::isEmpty() const
+{
+ for (TQMapIterator<TQString, KFileMetaInfoGroup> it = d->groups.begin();
+ it!=d->groups.end(); ++it)
+ if (!(*it).isEmpty())
+ return false;
+ return true;
+}
+
+bool KFileMetaInfo::applyChanges()
+{
+ return applyChanges( path() );
+}
+
+bool KFileMetaInfo::applyChanges( const TQString& path )
+{
+ bool doit = false;
+
+// kdDebug(7033) << "KFileMetaInfo::applyChanges()\n";
+
+ // look up if we need to write to the file
+ TQMapConstIterator<TQString, KFileMetaInfoGroup> it;
+ for (it = d->groups.begin(); it!=d->groups.end() && !doit; ++it)
+ {
+ if ( (*it).isModified() )
+ doit = true;
+
+ else
+ {
+ TQStringList keys = it.data().keys();
+ for (TQStringList::Iterator it2 = keys.begin(); it2!=keys.end(); ++it2)
+ {
+ if ( (*it)[*it2].isModified() )
+ {
+ doit = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if (!doit)
+ {
+ kdDebug(7033) << "Don't need to write, nothing changed\n";
+ return true;
+ }
+
+ KFilePlugin* p = plugin();
+ if (!p) return false;
+
+// kdDebug(7033) << "Ok, trying to write the info\n";
+
+ KURL savedURL = url();
+ d->url = KURL();
+ d->url.setPath( path );
+
+ bool ret = p->writeInfo(*this);
+
+ d->url = savedURL;
+ return ret;
+}
+
+KFilePlugin * KFileMetaInfo::plugin() const
+{
+ assert(isValid());
+ KFileMetaInfoProvider* prov = KFileMetaInfoProvider::self();
+ return prov->plugin( d->mimeTypeInfo->mimeType(), d->url.protocol() );
+}
+
+TQString KFileMetaInfo::mimeType() const
+{
+ assert(isValid());
+ return d->mimeTypeInfo->mimeType();
+}
+
+bool KFileMetaInfo::contains(const TQString& key) const
+{
+ TQStringList glist = groups();
+ for (TQStringList::Iterator it = glist.begin(); it != glist.end(); ++it)
+ {
+ KFileMetaInfoGroup g = d->groups[*it];
+ if (g.contains(key)) return true;
+ }
+ return false;
+}
+
+bool KFileMetaInfo::containsGroup(const TQString& key) const
+{
+ return groups().contains(key);
+}
+
+KFileMetaInfoItem KFileMetaInfo::item( const TQString& key) const
+{
+ TQStringList groups = preferredGroups();
+ for (TQStringList::Iterator it = groups.begin(); it != groups.end(); ++it)
+ {
+ KFileMetaInfoItem i = d->groups[*it][key];
+ if (i.isValid()) return i;
+ }
+ return KFileMetaInfoItem();
+}
+
+KFileMetaInfoItem KFileMetaInfo::item(const KFileMetaInfoItem::Hint hint) const
+{
+ TQStringList groups = preferredGroups();
+ TQStringList::ConstIterator it;
+ for (it = groups.begin(); it != groups.end(); ++it)
+ {
+ KFileMetaInfoItem i = d->groups[*it].item(hint);
+ if (i.isValid()) return i;
+ }
+ return KFileMetaInfoItem();
+}
+
+KFileMetaInfoItem KFileMetaInfo::saveItem( const TQString& key,
+ const TQString& preferredGroup,
+ bool createGroup )
+{
+ assert(isValid());
+ // try the preferred groups first
+ if ( !preferredGroup.isEmpty() ) {
+ TQMapIterator<TQString,KFileMetaInfoGroup> it =
+ d->groups.find( preferredGroup );
+
+ // try to create the preferred group, if necessary
+ if ( it == d->groups.end() && createGroup ) {
+ const KFileMimeTypeInfo::GroupInfo *groupInfo =
+ d->mimeTypeInfo->groupInfo( preferredGroup );
+ if ( groupInfo && groupInfo->supportedKeys().contains( key ) ) {
+ if ( addGroup( preferredGroup ) )
+ it = d->groups.find( preferredGroup );
+ }
+ }
+
+ if ( it != d->groups.end() ) {
+ KFileMetaInfoItem item = it.data().addItem( key );
+ if ( item.isValid() )
+ return item;
+ }
+ }
+
+ TQStringList groups = preferredGroups();
+
+ KFileMetaInfoItem item;
+
+ TQStringList::ConstIterator groupIt = groups.begin();
+ for ( ; groupIt != groups.end(); ++groupIt )
+ {
+ TQMapIterator<TQString,KFileMetaInfoGroup> it = d->groups.find( *groupIt );
+ if ( it != d->groups.end() )
+ {
+ KFileMetaInfoGroup group = it.data();
+ item = findEditableItem( group, key );
+ if ( item.isValid() )
+ return item;
+ }
+ else // not existant -- try to create the group
+ {
+ const KFileMimeTypeInfo::GroupInfo *groupInfo =
+ d->mimeTypeInfo->groupInfo( *groupIt );
+ if ( groupInfo && groupInfo->supportedKeys().contains( key ) )
+ {
+ if ( addGroup( *groupIt ) )
+ {
+ KFileMetaInfoGroup group = d->groups[*groupIt];
+ KFileMetaInfoItem item = group.addItem( key );
+ if ( item.isValid() )
+ return item;
+// else ### add when removeGroup() is implemented :)
+// removeGroup( *groupIt ); // couldn't add item -> remove
+ }
+ }
+ }
+ }
+
+ // finally check for variable items
+
+ return item;
+}
+
+KFileMetaInfoItem KFileMetaInfo::findEditableItem( KFileMetaInfoGroup& group,
+ const TQString& key )
+{
+ assert(isValid());
+ KFileMetaInfoItem item = group.addItem( key );
+ if ( item.isValid() && item.isEditable() )
+ return item;
+
+ if ( (d->mimeTypeInfo->groupInfo( group.name() )->attributes() & KFileMimeTypeInfo::Addable) )
+ return item;
+
+ return KFileMetaInfoItem();
+}
+
+KFileMetaInfoGroup KFileMetaInfo::appendGroup(const TQString& name)
+{
+ assert(isValid());
+ if ( d->mimeTypeInfo->supportedGroups().contains(name) &&
+ ! d->groups.contains(name) )
+ {
+ KFileMetaInfoGroup group( name, d->mimeTypeInfo );
+ d->groups.insert(name, group);
+ return group;
+ }
+
+ else {
+ kdWarning(7033) << "Someone's trying to add a KFileMetaInfoGroup which is not supported or already existing: " << name << endl;
+ return KFileMetaInfoGroup();
+ }
+}
+
+TQString KFileMetaInfo::path() const
+{
+ return d->url.isLocalFile() ? d->url.path() : TQString::null;
+}
+
+KURL KFileMetaInfo::url() const
+{
+ return d->url;
+}
+
+void KFileMetaInfo::ref()
+{
+ if (d != Data::null) d->ref();
+
+}
+
+void KFileMetaInfo::deref()
+{
+ // We don't call makeNull here since it isn't necassery:
+ // If d is equal to null it means that null is initialized already.
+ // null is 0L when it hasn't been initialized and d is never 0L.
+ if ((d != Data::null) && d->deref())
+ {
+// kdDebug(7033) << "metainfo object for " << d->url.path << " is finally deleted\n";
+ delete d;
+ d = 0;
+ }
+
+}
+
+
+KFileMetaInfo::Data* KFileMetaInfo::Data::null = 0L;
+static KStaticDeleter<KFileMetaInfo::Data> sd_KFileMetaInfoData;
+
+KFileMetaInfo::Data* KFileMetaInfo::Data::makeNull()
+{
+ if (!null)
+ // We deliberately do not reset "null" after it has been destroyed!
+ // Otherwise we will run into problems later in ~KFileMetaInfoItem
+ // where the d-pointer is compared against null.
+ null = sd_KFileMetaInfoData.setObject( new KFileMetaInfo::Data(KURL(), 0) );
+ return null;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+KFilePlugin::KFilePlugin( TQObject *parent, const char *name,
+ const TQStringList& /*args*/)
+ : TQObject( parent, name )
+{
+// kdDebug(7033) << "loaded a plugin for " << name << endl;
+}
+
+KFilePlugin::~KFilePlugin()
+{
+// kdDebug(7033) << "unloaded a plugin for " << name() << endl;
+}
+
+KFileMimeTypeInfo * KFilePlugin::addMimeTypeInfo( const TQString& mimeType )
+{
+ return KFileMetaInfoProvider::self()->addMimeTypeInfo( mimeType );
+}
+
+void KFilePlugin::virtual_hook( int, void* )
+{ /*BASE::virtual_hook( id, data );*/ }
+
+
+KFileMimeTypeInfo::GroupInfo* KFilePlugin::addGroupInfo(KFileMimeTypeInfo* info,
+ const TQString& key, const TQString& translatedKey) const
+{
+ return info->addGroupInfo(key, translatedKey);
+}
+
+void KFilePlugin::setAttributes(KFileMimeTypeInfo::GroupInfo* gi, uint attr) const
+{
+ gi->m_attr = attr;
+}
+
+void KFilePlugin::addVariableInfo(KFileMimeTypeInfo::GroupInfo* gi,
+ TQVariant::Type type, uint attr) const
+{
+ gi->addVariableInfo(type, attr);
+}
+
+KFileMimeTypeInfo::ItemInfo* KFilePlugin::addItemInfo(KFileMimeTypeInfo::GroupInfo* gi,
+ const TQString& key,
+ const TQString& translatedKey,
+ TQVariant::Type type)
+{
+ return gi->addItemInfo(key, translatedKey, type);
+}
+
+void KFilePlugin::setAttributes(KFileMimeTypeInfo::ItemInfo* item, uint attr)
+{
+ item->m_attr = attr;
+}
+
+void KFilePlugin::setHint(KFileMimeTypeInfo::ItemInfo* item, uint hint)
+{
+ item->m_hint = hint;
+}
+
+void KFilePlugin::setUnit(KFileMimeTypeInfo::ItemInfo* item, uint unit)
+{
+ item->m_unit = unit;
+ // set prefix and suffix
+ switch (unit)
+ {
+ case KFileMimeTypeInfo::Seconds:
+ item->m_suffix = i18n("s"); break;
+
+ case KFileMimeTypeInfo::MilliSeconds:
+ item->m_suffix = i18n("ms"); break;
+
+ case KFileMimeTypeInfo::BitsPerSecond:
+ item->m_suffix = i18n("bps"); break;
+
+ case KFileMimeTypeInfo::Pixels:
+ item->m_suffix = i18n("pixels"); break;
+
+ case KFileMimeTypeInfo::Inches:
+ item->m_suffix = i18n("in"); break;
+
+ case KFileMimeTypeInfo::Centimeters:
+ item->m_suffix = i18n("cm"); break;
+
+ case KFileMimeTypeInfo::Bytes:
+ item->m_suffix = i18n("B"); break;
+
+ case KFileMimeTypeInfo::KiloBytes:
+ item->m_suffix = i18n("KB"); break;
+
+ case KFileMimeTypeInfo::FramesPerSecond:
+ item->m_suffix = i18n("fps"); break;
+
+ case KFileMimeTypeInfo::DotsPerInch:
+ item->m_suffix = i18n("dpi"); break;
+
+ case KFileMimeTypeInfo::BitsPerPixel:
+ item->m_suffix = i18n("bpp"); break;
+
+ case KFileMimeTypeInfo::Hertz:
+ item->m_suffix = i18n("Hz"); break;
+
+ case KFileMimeTypeInfo::Millimeters:
+ item->m_suffix = i18n("mm");
+ }
+}
+
+void KFilePlugin::setPrefix(KFileMimeTypeInfo::ItemInfo* item, const TQString& prefix)
+{
+ item->m_prefix = prefix;
+}
+
+void KFilePlugin::setSuffix(KFileMimeTypeInfo::ItemInfo* item, const TQString& suffix)
+{
+ item->m_suffix = suffix;
+}
+
+KFileMetaInfoGroup KFilePlugin::appendGroup(KFileMetaInfo& info, const TQString& key)
+{
+ return info.appendGroup(key);
+}
+
+void KFilePlugin::appendItem(KFileMetaInfoGroup& group, const TQString& key, TQVariant value)
+{
+ group.appendItem(key, value);
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+KFileMetaInfoProvider * KFileMetaInfoProvider::s_self;
+static KStaticDeleter<KFileMetaInfoProvider> sd;
+
+KFileMetaInfoProvider * KFileMetaInfoProvider::self()
+{
+ if ( !s_self )
+ s_self = sd.setObject( s_self, new KFileMetaInfoProvider() );
+
+ return s_self;
+}
+
+KFileMetaInfoProvider::KFileMetaInfoProvider()
+{
+ m_plugins.setAutoDelete( true );
+}
+
+KFileMetaInfoProvider::~KFileMetaInfoProvider()
+{
+ m_plugins.clear();
+ sd.setObject( 0 );
+}
+
+KFilePlugin* KFileMetaInfoProvider::loadPlugin( const TQString& mimeType, const TQString& protocol )
+{
+ //kdDebug() << "loadPlugin: mimeType=" << mimeType << " protocol=" << protocol << endl;
+ // Currently the idea is: either the mimetype is set or the protocol, but not both.
+ // We need PNG fileinfo, and trash: fileinfo, but not "PNG in the trash".
+ TQString queryMimeType, query;
+ if ( !mimeType.isEmpty() ) {
+ query = "(not exist [X-TDE-Protocol])";
+ queryMimeType = mimeType;
+ } else {
+ query = TQString::fromLatin1( "[X-TDE-Protocol] == '%1'" ).arg(protocol);
+ // querying for a protocol: we have no mimetype, so we need to use KFilePlugin as one
+ queryMimeType = "KFilePlugin";
+ // hopefully using KFilePlugin as genericMimeType too isn't a problem
+ }
+ const KTrader::OfferList offers = KTrader::self()->query( queryMimeType, "KFilePlugin", query, TQString::null );
+ if ( offers.isEmpty() )
+ return 0;
+ KService::Ptr service = *(offers.begin());
+ Q_ASSERT( service && service->isValid() );
+ if ( !service || !service->isValid() )
+ return 0;
+
+ KFilePlugin* plugin = KParts::ComponentFactory::createInstanceFromService<KFilePlugin>
+ ( service, TQT_TQOBJECT(this), mimeType.local8Bit() );
+ if (!plugin)
+ kdWarning(7033) << "error loading the plugin from " << service->desktopEntryPath() << endl;
+
+ return plugin;
+}
+
+KFilePlugin* KFileMetaInfoProvider::loadAndRegisterPlugin( const TQString& mimeType, const TQString& protocol )
+{
+ Q_ASSERT( m_pendingMimetypeInfos.isEmpty() );
+ m_pendingMimetypeInfos.clear();
+
+ KFilePlugin* plugin = loadPlugin( mimeType, protocol );
+ if ( !plugin ) {
+ // No plugin found. Remember that, to save time.
+ m_plugins.insert( protocol.isEmpty() ? mimeType : protocol, new CachedPluginInfo );
+ return 0;
+ }
+
+ if ( !protocol.isEmpty() ) {
+ // Protocol-metainfo: only one entry
+ Q_ASSERT( m_pendingMimetypeInfos.count() == 1 );
+ KFileMimeTypeInfo* info = m_pendingMimetypeInfos[ protocol ];
+ Q_ASSERT( info );
+ m_plugins.insert( protocol, new CachedPluginInfo( plugin, info, true ) );
+ } else {
+ // Mimetype-metainfo: the plugin can register itself for multiple mimetypes, remember them all
+ bool first = true;
+ TQDictIterator<KFileMimeTypeInfo> it( m_pendingMimetypeInfos );
+ for( ; it.current(); ++it ) {
+ KFileMimeTypeInfo* info = it.current();
+ m_plugins.insert( it.currentKey(), new CachedPluginInfo( plugin, info, first ) );
+ first = false;
+ }
+ // Hopefully the above includes the mimetype we asked for!
+ if ( m_pendingMimetypeInfos.find( mimeType ) == 0 )
+ kdWarning(7033) << plugin->className() << " was created for " << mimeType << " but doesn't call addMimeTypeInfo for it!" << endl;
+ }
+ m_pendingMimetypeInfos.clear();
+ return plugin;
+}
+
+KFilePlugin * KFileMetaInfoProvider::plugin(const TQString& mimeType)
+{
+ return plugin( mimeType, TQString::null );
+}
+
+KFilePlugin * KFileMetaInfoProvider::plugin(const TQString& mimeType, const TQString& protocol)
+{
+ //kdDebug(7033) << "plugin() : looking for plugin for protocol=" << protocol << " mimeType=" << mimeType << endl;
+
+ if ( !protocol.isEmpty() ) {
+ CachedPluginInfo *cache = m_plugins.find( protocol );
+ if ( cache && cache->plugin ) {
+ return cache->plugin;
+ }
+ if ( !cache ) {
+ KFilePlugin* plugin = loadAndRegisterPlugin( TQString::null, protocol );
+ if ( plugin )
+ return plugin;
+ }
+ }
+
+ CachedPluginInfo *cache = m_plugins.find( mimeType );
+ if ( cache ) {
+ return cache->plugin;
+ }
+
+ KFilePlugin* plugin = loadAndRegisterPlugin( mimeType, TQString::null );
+
+#if 0
+ kdDebug(7033) << "currently loaded plugins:\n";
+
+ TQDictIterator<CachedPluginInfo> it( m_plugins );
+ for( ; it.current(); ++it ) {
+ CachedPluginInfo* cache = it.current();
+ kdDebug(7033)
+ << it.currentKey() // mimetype or protocol
+ << " : " << (cache->plugin ? cache->plugin->className() : "(no plugin)") << endl; // plugin
+ // TODO print cache->mimeTypeInfo
+ }
+#endif
+
+ return plugin;
+}
+
+TQStringList KFileMetaInfoProvider::preferredKeys( const TQString& mimeType ) const
+{
+ KService::Ptr service =
+ KServiceTypeProfile::preferredService( mimeType, "KFilePlugin");
+
+ if ( !service || !service->isValid() )
+ {
+// kdDebug(7033) << "no valid service found\n";
+ return TQStringList();
+ }
+ return service->property("PreferredItems").toStringList();
+}
+
+TQStringList KFileMetaInfoProvider::preferredGroups( const TQString& mimeType ) const
+{
+ KService::Ptr service =
+ KServiceTypeProfile::preferredService( mimeType, "KFilePlugin");
+
+ if ( !service || !service->isValid() )
+ {
+// kdDebug(7033) << "no valid service found\n";
+ return TQStringList();
+ }
+ return service->property("PreferredGroups").toStringList();
+}
+
+const KFileMimeTypeInfo * KFileMetaInfoProvider::mimeTypeInfo( const TQString& mimeType )
+{
+ return mimeTypeInfo( mimeType, TQString::null );
+}
+
+const KFileMimeTypeInfo * KFileMetaInfoProvider::mimeTypeInfo( const TQString& mimeType, const TQString& protocol )
+{
+ //kdDebug(7033) << "mimeTypeInfo() : looking for plugin for protocol=" << protocol << " mimeType=" << mimeType << endl;
+ if ( !protocol.isEmpty() ) {
+ CachedPluginInfo *cache = m_plugins.find( protocol );
+ if ( cache && cache->mimeTypeInfo ) {
+ return cache->mimeTypeInfo;
+ }
+
+ if ( !cache ) {
+ loadAndRegisterPlugin( TQString::null, protocol );
+ cache = m_plugins.find( protocol );
+ if ( cache && cache->mimeTypeInfo ) {
+ return cache->mimeTypeInfo;
+ }
+ }
+ }
+
+ CachedPluginInfo *cache = m_plugins.find( mimeType );
+ if ( cache ) {
+ return cache->mimeTypeInfo;
+ }
+
+ loadAndRegisterPlugin( mimeType, TQString::null );
+ cache = m_plugins.find( mimeType );
+ if ( cache ) {
+ return cache->mimeTypeInfo;
+ }
+ return 0;
+}
+
+KFileMimeTypeInfo * KFileMetaInfoProvider::addMimeTypeInfo(
+ const TQString& mimeType )
+{
+
+ KFileMimeTypeInfo *info = m_pendingMimetypeInfos.find( mimeType );
+ Q_ASSERT( !info );
+ if ( !info )
+ {
+ info = new KFileMimeTypeInfo( mimeType );
+ m_pendingMimetypeInfos.insert( mimeType, info );
+ }
+
+ info->m_preferredKeys = preferredKeys( mimeType );
+ info->m_preferredGroups = preferredGroups( mimeType );
+
+ return info;
+}
+
+TQStringList KFileMetaInfoProvider::supportedMimeTypes() const
+{
+ TQStringList allMimeTypes;
+ TQString tdefilePlugin = "KFilePlugin";
+
+ KTrader::OfferList offers = KTrader::self()->query( "KFilePlugin" );
+ KTrader::OfferListIterator it = offers.begin();
+ for ( ; it != offers.end(); ++it )
+ {
+ const TQStringList mimeTypes = (*it)->serviceTypes();
+ TQStringList::ConstIterator it2 = mimeTypes.begin();
+ for ( ; it2 != mimeTypes.end(); ++it2 )
+ if ( allMimeTypes.find( *it2 ) == allMimeTypes.end() &&
+ *it2 != tdefilePlugin ) // also in serviceTypes()
+ allMimeTypes.append( *it2 );
+ }
+
+ return allMimeTypes;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+// shared data of a KFileMetaInfoGroup
+class KFileMetaInfoGroup::Data : public TQShared
+{
+public:
+ Data(const TQString& _name)
+ : TQShared(),
+ name(_name),
+ mimeTypeInfo(0L),
+ dirty( false ),
+ added( false )
+ {}
+
+ // we use this one for the streaming operators
+ Data() : mimeTypeInfo(0L) {}
+ ~Data() {
+ if ( this == null )
+ delete mimeTypeInfo;
+ };
+
+ TQString name;
+ TQMap<TQString, KFileMetaInfoItem> items;
+ const KFileMimeTypeInfo* mimeTypeInfo;
+ TQStringList removedItems;
+ bool dirty :1;
+ bool added :1;
+
+ static Data* null;
+ static Data* makeNull();
+
+};
+
+KFileMetaInfoGroup::KFileMetaInfoGroup( const TQString& name,
+ const KFileMimeTypeInfo* info )
+ : d(new Data( name ) )
+{
+ d->mimeTypeInfo = info;
+}
+
+KFileMetaInfoGroup::KFileMetaInfoGroup( const KFileMetaInfoGroup& original )
+{
+ // operator= does everything that's necessary
+ d = Data::makeNull();
+ *this = original;
+}
+
+KFileMetaInfoGroup::KFileMetaInfoGroup()
+{
+ d = Data::makeNull();
+}
+
+KFileMetaInfoGroup::~KFileMetaInfoGroup()
+{
+ deref();
+}
+
+const KFileMetaInfoGroup& KFileMetaInfoGroup::operator= (const KFileMetaInfoGroup& info )
+{
+ if (d != info.d)
+ {
+ deref();
+ // first deref the old one
+ d = info.d;
+ // and now ref the new one
+ ref();
+ }
+ return *this;
+}
+
+bool KFileMetaInfoGroup::isValid() const
+{
+ // We don't call makeNull here since it isn't necassery, see deref()
+ return d != Data::null;
+}
+
+bool KFileMetaInfoGroup::isEmpty() const
+{
+ return d->items.isEmpty();
+}
+
+TQStringList KFileMetaInfoGroup::preferredKeys() const
+{
+ assert(isValid());
+ TQStringList list = keys();
+ TQStringList newlist;
+ TQStringList preferredKeys = d->mimeTypeInfo->preferredKeys();
+ TQStringList::Iterator pref;
+ TQStringList::Iterator begin = preferredKeys.begin();
+ TQStringList::Iterator end = preferredKeys.end();
+
+ // move all keys from the preferred keys that are in our list to a new list
+ for ( pref = begin; pref!=end; ++pref )
+ {
+ TQStringList::Iterator item = list.find(*pref);
+ if ( item != list.end() )
+ {
+ newlist.append( *item );
+ list.remove(item);
+ }
+ }
+
+ // now the old list only contains the non-preferred items, so we
+ // add the remaining ones to newlist
+ newlist += list;
+
+ return newlist;
+}
+
+TQStringList KFileMetaInfoGroup::keys() const
+{
+ if (d == Data::makeNull())
+ kdWarning(7033) << "attempt to get the keys of "
+ "an invalid metainfo group";
+
+ TQStringList list;
+
+ // make a TQStringList with all available keys
+ TQMapConstIterator<TQString, KFileMetaInfoItem> it;
+ for (it = d->items.begin(); it!=d->items.end(); ++it)
+ {
+ list.append(it.data().key());
+// kdDebug(7033) << "Item " << it.data().key() << endl;
+ }
+ return list;
+}
+
+TQString KFileMetaInfoGroup::translatedName() const
+{
+ assert(isValid());
+ return d->mimeTypeInfo->groupInfo(d->name)->translatedName();
+}
+
+TQStringList KFileMetaInfoGroup::supportedKeys() const
+{
+ assert(isValid());
+ return d->mimeTypeInfo->groupInfo(d->name)->supportedKeys();
+}
+
+bool KFileMetaInfoGroup::supportsVariableKeys() const
+{
+ assert(isValid());
+ return d->mimeTypeInfo->groupInfo(d->name)->supportsVariableKeys();
+}
+
+bool KFileMetaInfoGroup::contains( const TQString& key ) const
+{
+ return d->items.contains(key);
+}
+
+KFileMetaInfoItem KFileMetaInfoGroup::item( const TQString& key) const
+{
+ TQMapIterator<TQString,KFileMetaInfoItem> it = d->items.find( key );
+ if ( it != d->items.end() )
+ return it.data();
+
+ return KFileMetaInfoItem();
+}
+
+KFileMetaInfoItem KFileMetaInfoGroup::item(uint hint) const
+{
+ TQMapIterator<TQString, KFileMetaInfoItem> it;
+
+ for (it = d->items.begin(); it!=d->items.end(); ++it)
+ if (it.data().hint() == hint)
+ return it.data();
+
+ return KFileMetaInfoItem();
+}
+
+TQString KFileMetaInfoGroup::name() const
+{
+ return d->name;
+}
+
+uint KFileMetaInfoGroup::attributes() const
+{
+ assert(isValid());
+ return d->mimeTypeInfo->groupInfo(d->name)->attributes();
+}
+
+void KFileMetaInfoGroup::setAdded()
+{
+ d->added = true;
+}
+
+bool KFileMetaInfoGroup::isModified() const
+{
+ return d->dirty;
+}
+
+void KFileMetaInfoGroup::ref()
+{
+ if (d != Data::null) d->ref();
+
+}
+
+void KFileMetaInfoGroup::deref()
+{
+ // We don't call makeNull here since it isn't necassery:
+ // If d is equal to null it means that null is initialized already.
+ // null is 0L when it hasn't been initialized and d is never 0L.
+ if ((d != Data::null) && d->deref())
+ {
+// kdDebug(7033) << "metainfo group " << d->name
+// << " is finally deleted\n";
+ delete d;
+ d = 0;
+ }
+
+}
+
+KFileMetaInfoItem KFileMetaInfoGroup::addItem( const TQString& key )
+{
+ assert(isValid());
+ TQMapIterator<TQString,KFileMetaInfoItem> it = d->items.find( key );
+ if ( it != d->items.end() )
+ return it.data();
+
+ const KFileMimeTypeInfo::GroupInfo* ginfo = d->mimeTypeInfo->groupInfo(d->name);
+
+ if ( !ginfo ) {
+ Q_ASSERT( ginfo );
+ return KFileMetaInfoItem();
+ }
+
+ const KFileMimeTypeInfo::ItemInfo* info = ginfo->itemInfo(key);
+
+ if ( !info ) {
+ Q_ASSERT( info );
+ return KFileMetaInfoItem();
+ }
+
+ KFileMetaInfoItem item;
+
+ if (info->isVariableItem())
+ item = KFileMetaInfoItem(ginfo->variableItemInfo(), key, TQVariant());
+ else
+ item = KFileMetaInfoItem(info, key, TQVariant());
+
+ d->items.insert(key, item);
+ item.setAdded(); // mark as added
+ d->dirty = true; // mark ourself as dirty, too
+ return item;
+}
+
+bool KFileMetaInfoGroup::removeItem( const TQString& key )
+{
+ if (!isValid())
+ {
+ kdDebug(7033) << "trying to remove an item from an invalid group\n";
+ return false;
+ }
+
+ TQMapIterator<TQString, KFileMetaInfoItem> it = d->items.find(key);
+ if ( it==d->items.end() )
+ {
+ kdDebug(7033) << "trying to remove the non existant item " << key << "\n";
+ return false;
+ }
+
+ if (!((*it).attributes() & KFileMimeTypeInfo::Removable))
+ {
+ kdDebug(7033) << "trying to remove a non removable item\n";
+ return false;
+ }
+
+ (*it).setRemoved();
+ d->items.remove(it);
+ d->removedItems.append(key);
+ d->dirty = true;
+ return true;
+}
+
+TQStringList KFileMetaInfoGroup::removedItems()
+{
+ return d->removedItems;
+}
+
+KFileMetaInfoItem KFileMetaInfoGroup::appendItem(const TQString& key,
+ const TQVariant& value)
+{
+ //KDE4 enforce (value.type() == d->mimeTypeInfo->type())
+ assert(isValid());
+ const KFileMimeTypeInfo::GroupInfo* ginfo = d->mimeTypeInfo->groupInfo(d->name);
+ if ( !ginfo ) {
+ kdWarning() << "Trying to append a Metadata item for a non-existant group:" << d->name << endl;
+ return KFileMetaInfoItem();
+ }
+ const KFileMimeTypeInfo::ItemInfo* info = ginfo->itemInfo(key);
+ if ( !info ) {
+ kdWarning() << "Trying to append a Metadata item for an unknown key (no ItemInfo): " << key << endl;
+ return KFileMetaInfoItem();
+ }
+
+ KFileMetaInfoItem item;
+
+ if (info->key().isNull())
+ item = KFileMetaInfoItem(ginfo->variableItemInfo(), key, value);
+ else
+ item = KFileMetaInfoItem(info, key, value);
+
+ kdDebug(7033) << "KFileMetaInfogroup inserting a " << key << endl;
+
+ d->items.insert(key, item);
+ return item;
+}
+
+KFileMetaInfoGroup::Data* KFileMetaInfoGroup::Data::null = 0L;
+static KStaticDeleter<KFileMetaInfoGroup::Data> sd_KFileMetaInfoGroupData;
+
+KFileMetaInfoGroup::Data* KFileMetaInfoGroup::Data::makeNull()
+{
+ if (!null)
+ {
+ // We deliberately do not reset "null" after it has been destroyed!
+ // Otherwise we will run into problems later in ~KFileMetaInfoItem
+ // where the d-pointer is compared against null.
+ null = new Data(TQString::null);
+ null->mimeTypeInfo = new KFileMimeTypeInfo();
+ sd_KFileMetaInfoGroupData.setObject( null );
+ }
+ return null;
+}
+
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+KFileMimeTypeInfo::KFileMimeTypeInfo( const TQString& mimeType )
+ : m_mimeType( mimeType )
+{
+ m_groups.setAutoDelete( true );
+}
+
+KFileMimeTypeInfo::~KFileMimeTypeInfo()
+{
+}
+
+const KFileMimeTypeInfo::GroupInfo * KFileMimeTypeInfo::groupInfo( const TQString& group ) const
+{
+ return m_groups.find( group );
+}
+
+KFileMimeTypeInfo::GroupInfo * KFileMimeTypeInfo::addGroupInfo(
+ const TQString& name, const TQString& translatedName )
+{
+ GroupInfo* group = new GroupInfo( name, translatedName );
+ m_groups.insert(name, group);
+ return group;
+}
+
+TQStringList KFileMimeTypeInfo::supportedGroups() const
+{
+ TQStringList list;
+ TQDictIterator<GroupInfo> it( m_groups );
+ for ( ; it.current(); ++it )
+ list.append( it.current()->name() );
+
+ return list;
+}
+
+TQStringList KFileMimeTypeInfo::translatedGroups() const
+{
+ TQStringList list;
+ TQDictIterator<GroupInfo> it( m_groups );
+ for ( ; it.current(); ++it )
+ list.append( it.current()->translatedName() );
+
+ return list;
+}
+
+TQStringList KFileMimeTypeInfo::supportedKeys() const
+{
+ // not really efficient, but not those are not large lists, probably.
+ // maybe cache the result?
+ TQStringList keys;
+ TQStringList::ConstIterator lit;
+ TQDictIterator<GroupInfo> it( m_groups );
+ for ( ; it.current(); ++it ) { // need to nuke dupes
+ TQStringList list = it.current()->supportedKeys();
+ for ( lit = list.begin(); lit != list.end(); ++lit ) {
+ if ( keys.find( *lit ) == keys.end() )
+ keys.append( *lit );
+ }
+ }
+
+ return keys;
+}
+
+TQValidator * KFileMimeTypeInfo::createValidator(const TQString& group,
+ const TQString& key,
+ TQObject *parent,
+ const char *name) const
+{
+ KFilePlugin* plugin = KFileMetaInfoProvider::self()->plugin(m_mimeType);
+ if (plugin) return plugin->createValidator(mimeType(), group, key,
+ parent, name);
+ return 0;
+}
+
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+KFileMimeTypeInfo::GroupInfo::GroupInfo( const TQString& name,
+ const TQString& translatedName )
+ : m_name( name ),
+ m_translatedName( translatedName ),
+ m_attr( 0 ),
+ m_variableItemInfo( 0 )
+
+{
+ m_itemDict.setAutoDelete( true );
+}
+
+KFileMimeTypeInfo::GroupInfo::~GroupInfo()
+{
+ delete m_variableItemInfo;
+}
+
+const KFileMimeTypeInfo::ItemInfo * KFileMimeTypeInfo::GroupInfo::itemInfo( const TQString& key ) const
+{
+ ItemInfo* item = m_itemDict.find( key );
+
+ // if we the item isn't found and variable keys are supported, we need to
+ // return the default variable key iteminfo.
+ if (!item && m_variableItemInfo)
+ {
+ return m_variableItemInfo;
+ }
+ return item;
+}
+
+KFileMimeTypeInfo::ItemInfo* KFileMimeTypeInfo::GroupInfo::addItemInfo(
+ const TQString& key, const TQString& translatedKey,
+ TQVariant::Type type)
+{
+// kdDebug(7034) << key << "(" << translatedKey << ") -> " << TQVariant::typeToName(type) << endl;
+
+ ItemInfo* item = new ItemInfo(key, translatedKey, type);
+ m_supportedKeys.append(key);
+ m_itemDict.insert(key, item);
+ return item;
+}
+
+
+void KFileMimeTypeInfo::GroupInfo::addVariableInfo( TQVariant::Type type,
+ uint attr )
+{
+ // just make sure that it's not already there
+ delete m_variableItemInfo;
+ m_variableItemInfo = new ItemInfo(TQString::null, TQString::null, type);
+ m_variableItemInfo->m_attr = attr;
+}
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+TQString KFileMimeTypeInfo::ItemInfo::string(const TQVariant& value, bool mangle) const
+{
+ TQString s;
+
+ switch (value.type())
+ {
+ case TQVariant::Invalid :
+ return "---";
+
+ case TQVariant::Bool :
+ s = value.toBool() ? i18n("Yes") : i18n("No");
+ break;
+
+ case TQVariant::Int :
+ if (unit() == KFileMimeTypeInfo::Seconds)
+ {
+ int seconds = value.toInt() % 60;
+ int minutes = value.toInt() / 60 % 60;
+ int hours = value.toInt() / 3600;
+ s = hours ? TQString().sprintf("%d:%02d:%02d",hours, minutes, seconds)
+ : TQString().sprintf("%02d:%02d", minutes, seconds);
+ return s; // no suffix wanted
+ }
+ else if (unit() == KFileMimeTypeInfo::Bytes)
+ {
+ // convertSize already adds the correct suffix
+ return TDEIO::convertSize(value.toInt());
+ }
+ else if (unit() == KFileMimeTypeInfo::KiloBytes)
+ {
+ // convertSizeFromKB already adds the correct suffix
+ return TDEIO::convertSizeFromKB(value.toInt());
+ }
+ else
+ s = TDEGlobal::locale()->formatNumber( value.toInt() , 0);
+ break;
+
+ case TQVariant::LongLong :
+ s = TDEGlobal::locale()->formatNumber( value.toLongLong(), 0 );
+ break;
+
+ case TQVariant::ULongLong :
+ if ( unit() == KFileMimeTypeInfo::Bytes )
+ return TDEIO::convertSize( value.toULongLong() );
+ else if ( unit() == KFileMimeTypeInfo::KiloBytes )
+ return TDEIO::convertSizeFromKB( value.toULongLong() );
+ else
+ s = TDEGlobal::locale()->formatNumber( value.toULongLong(), 0 );
+ break;
+
+ case TQVariant::UInt :
+ s = TDEGlobal::locale()->formatNumber( value.toUInt() , 0);
+ break;
+
+ case TQVariant::Double :
+ s = TDEGlobal::locale()->formatNumber( value.toDouble(), 3);
+ break;
+
+ case TQVariant::Date :
+ s = TDEGlobal::locale()->formatDate( value.toDate(), true );
+ break;
+
+ case TQVariant::Time :
+ s = TDEGlobal::locale()->formatTime( value.toTime(), true );
+ break;
+
+ case TQVariant::DateTime :
+ s = TDEGlobal::locale()->formatDateTime( value.toDateTime(),
+ true, true );
+ break;
+
+ case TQVariant::Size :
+ s = TQString("%1 x %2").arg(value.toSize().width())
+ .arg(value.toSize().height());
+ break;
+
+ case TQVariant::Point :
+ s = TQString("%1/%2").arg(value.toSize().width())
+ .arg(value.toSize().height());
+ break;
+
+ default:
+ s = value.toString();
+ }
+
+ if (mangle && !s.isNull())
+ {
+ s.prepend(prefix());
+ s.append(" " + suffix());
+ }
+ return s;
+}
+
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+
+// stream operators
+
+/* serialization of a KFileMetaInfoItem:
+ first a bool that says if the items is valid, and if yes,
+ all the elements of the Data
+*/
+TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoItem& item )
+{
+
+ KFileMetaInfoItem::Data* d = item.d;
+
+ // if the object is invalid, put only a char in the stream
+ bool isValid = item.isValid();
+ s << isValid;
+ // ### what do about mimetypeInfo ?
+ if (isValid)
+ s << d->key
+ << d->value
+ << d->dirty
+ << d->added
+ << d->removed;
+
+ return s;
+}
+
+
+TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoItem& item )
+{
+ bool isValid;
+ s >> isValid;
+
+ if (!isValid)
+ {
+ item = KFileMetaInfoItem();
+ return s;
+ }
+
+ // we need a new object for our data
+ item.deref();
+ item.d = new KFileMetaInfoItem::Data();
+
+ // ### what do about mimetypeInfo ?
+ bool dirty, added, removed;
+ s >> item.d->key
+ >> item.d->value
+ >> dirty
+ >> added
+ >> removed;
+ item.d->dirty = dirty;
+ item.d->added = added;
+ item.d->removed = removed;
+
+ return s;
+}
+
+
+// serialization of a KFileMetaInfoGroup
+// we serialize the name of the mimetype here instead of the mimetype info
+// on the other side, we can simply use this to ask the provider for the info
+TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoGroup& group )
+{
+ KFileMetaInfoGroup::Data* d = group.d;
+
+ // if the object is invalid, put only a byte in the stream
+ bool isValid = group.isValid();
+
+ s << isValid;
+ if (isValid)
+ {
+ s << d->name
+ << d->items
+ << d->mimeTypeInfo->mimeType();
+ }
+ return s;
+}
+
+TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& group )
+{
+ TQString mimeType;
+ bool isValid;
+ s >> isValid;
+
+ // if it's invalid, there is not much to do
+ if (!isValid)
+ {
+ group = KFileMetaInfoGroup();
+ return s;
+ }
+
+ // we need a new object for our data
+ group.deref();
+ group.d = new KFileMetaInfoGroup::Data();
+
+ s >> group.d->name
+ >> group.d->items
+ >> mimeType;
+
+ group.d->mimeTypeInfo = KFileMetaInfoProvider::self()->mimeTypeInfo(mimeType);
+
+ // we need to set the item info for the items here
+ TQMapIterator<TQString, KFileMetaInfoItem> it = group.d->items.begin();
+ for ( ; it != group.d->items.end(); ++it)
+ {
+ (*it).d->mimeTypeInfo = group.d->mimeTypeInfo->groupInfo(group.d->name)
+ ->itemInfo((*it).key());
+ }
+
+ return s;
+}
+
+// serialization of a KFileMetaInfo object
+// we serialize the name of the mimetype here instead of the mimetype info
+// on the other side, we can simply use this to ask the provider for the info
+TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfo& info )
+{
+ KFileMetaInfo::Data* d = info.d;
+
+ // if the object is invalid, put only a byte that tells this
+ bool isValid = info.isValid();
+
+ s << isValid;
+ if (isValid)
+ {
+ s << d->url
+ << d->what
+ << d->groups
+ << d->mimeTypeInfo->mimeType();
+ }
+ return s;
+}
+
+TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfo& info )
+{
+ TQString mimeType;
+ bool isValid;
+ s >> isValid;
+
+ // if it's invalid, there is not much to do
+ if (!isValid)
+ {
+ info = KFileMetaInfo();
+ return s;
+ }
+
+ // we need a new object for our data
+ info.deref();
+ info.d = new KFileMetaInfo::Data();
+
+ s >> info.d->url
+ >> info.d->what
+ >> info.d->groups
+ >> mimeType;
+ info.d->mimeTypeInfo = KFileMetaInfoProvider::self()->mimeTypeInfo(mimeType);
+
+ return s;
+}
+
+#include "tdefilemetainfo.moc"
diff --git a/tdeio/tdeio/tdefilemetainfo.h b/tdeio/tdeio/tdefilemetainfo.h
new file mode 100644
index 000000000..8cc3fdbdf
--- /dev/null
+++ b/tdeio/tdeio/tdefilemetainfo.h
@@ -0,0 +1,1738 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (C) 2001-2002 Rolf Magnus <ramagnus@kde.org>
+ * Copyright (C) 2001-2002 Carsten Pfeiffer <pfeiffer@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation version 2.0.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+#ifndef KILEMETAINFO_H
+#define KILEMETAINFO_H
+
+/* Hack for HPUX: Namespace pollution
+ m_unit is a define in <sys/sysmacros.h> */
+#define m_unit outouftheway_m_unit
+
+#include <tqdict.h>
+#include <tqvariant.h>
+#include <tqobject.h>
+#include <tqstring.h>
+#include <kurl.h>
+
+#undef m_unit
+
+class TQValidator;
+class KFilePlugin;
+class KFileMetaInfoGroup;
+
+/**
+ * @brief Represents the capabilities of a KFilePlugin for a given mimetype
+ *
+ * This class provides information about the capabilities that a
+ * KFilePlugin for a given mimetype has. It includes a list of metainfo
+ * groups and items together with their type, a prefix, suffix and some other
+ * information about how to use, display or edit the items.
+ *
+ * @author Rolf Magnus
+ * @author Carsten Pfeiffer
+ */
+class TDEIO_EXPORT KFileMimeTypeInfo
+{
+ // the plugin needs to be a friend because it puts the data into the object,
+ // and it should be the only one allowed to do this.
+ friend class KFilePlugin;
+ friend class KFileMetaInfoProvider;
+
+public:
+ KFileMimeTypeInfo() {}
+
+ /**
+ * This enum is used to specify some attributes that an item can have,
+ * which fit neither in the Hint nor in the Unit enum.
+ */
+ enum Attributes
+ {
+ Addable = 1, ///< The item or group can be added by a user
+ Removable = 2, ///< It can be removed
+ Modifiable = 4, ///< The value can be edited (no meaning for a group)
+ Cumulative = 8, /**< If an application wants to display information
+ for more than one file, it may add up the values
+ for this item (e.g. play time of an mp3 file) */
+ Cummulative = Cumulative, ///< @deprecated Use Cumulative instead
+ Averaged = 16, /**< Similar to Cumulative, but the average should
+ be calculated instead of the sum */
+ MultiLine = 32, /**< This attribute says that a string item is likely
+ to be more than one line long, so for editing, a
+ widget capable for multline text should be used
+ @since 3.1 */
+ SqueezeText = 64 /**< If the text for this item is very long, it
+ should be squeezed to the size of the widget
+ where it's displayed
+ @since 3.1 */
+ };
+
+ /**
+ * This enum is mainly for items that have a special meaning for some
+ * applications.
+ */
+ enum Hint {
+ NoHint = 0, ///< No hint
+ Name = 1, ///< The name or title of the document
+ Author = 2, ///< The one who created the contents of it
+ Description = 3, ///< Description Some information about the document
+ Width = 4, ///< The width in pixels
+ Height = 5, ///< The height in pixels
+ Size = 6, ///< The size in pixels (width and height)
+ Bitrate = 7, ///< For media files
+ Length = 8, ///< The length of the file, also for media files
+ Hidden = 9, ///< The item is usually not shown to the user
+ Thumbnail = 10 ///< The item is a thumbnail picture of the file
+
+ };
+
+ /**
+ * This enum exists so that you can specify units for items, which you
+ * can usually use for integer items, so an application knows how to
+ * display it (e.g. a time in seconds in a hh:mm:ss form). You can either
+ * use one of those units, or if you don't find one that fits, you can
+ * add it yourself using a prefix and/or suffix.
+ */
+ enum Unit {
+ NoUnit = 0, ///< None of the listed units
+ Seconds = 1, ///< The item represents a time in seconds
+ MilliSeconds = 2, ///< The item represents a time in milliseconds
+ BitsPerSecond = 3, ///< A bit rate
+ Pixels = 4, ///< For image dimensions and similar
+ Inches = 5, ///< Sizes
+ Centimeters = 6, ///< Sizes
+ Bytes = 7, ///< Some data/file size in bytes
+ FramesPerSecond = 8, ///< A frame rate @since 3.1
+ DotsPerInch = 9, ///< Resolution in DPI @since 3.1
+ BitsPerPixel = 10, ///< A bit depth @since 3.1
+ Hertz = 11, ///< Sample rates and similar @since 3.1
+ KiloBytes = 12, ///< Some data/file size in kilobytes @since 3.1
+ Millimeters = 13 ///< Sizes @since 3.3
+ };
+
+
+ class ItemInfo;
+
+ /**
+ * @brief Information about a meta information group
+ *
+ * This is the class for one group of items of a KFileMimeTypeInfo.
+ * It contains, among other things, the information about the group's name
+ * and a list of supported items.
+ */
+ class TDEIO_EXPORT GroupInfo
+ {
+
+ friend class KFilePlugin;
+ friend class KFileMimeTypeInfo;
+ public:
+ /**
+ * Use this method to get a list of keys in the specified group that
+ * the plugin knows about. No variable keys.
+ * For a group that doesn't support variable keys, all keys that this
+ * group may have are returned. For a group that does support them, the
+ * non-variable ones are returned. See KFileMetaInfo about variable
+ * keys
+ *
+ * @return the list of keys supported for this mimetype
+ **/
+ TQStringList supportedKeys() const
+ {
+ return m_supportedKeys;
+ }
+
+ /**
+ * Use this method to get the name of the group. This string doesn't
+ * depend on the user's locale settings
+ *
+ * @return the group name
+ */
+ const TQString& name() const
+ {
+ return m_name;
+ }
+
+ /**
+ * Use this method to get the string to display to the user as group
+ * name. This may be different to name() and it returns the
+ * name in the user's language
+ *
+ * @return the translated group name
+ */
+ const TQString& translatedName() const
+ {
+ return m_translatedName;
+ }
+
+ /**
+ * A group object can contain several item objects (of which you can
+ * get the names with supportedKeys() . With this method, you can
+ * get one of those item objects. See ItemInfo
+ *
+ * @return a pointer to the item info. Don't delete this object!
+ */
+ const ItemInfo * itemInfo( const TQString& key ) const;
+
+ /**
+ * Get the attributes of this group (see Attributes)
+ *
+ * @return the attributes
+ */
+ uint attributes() const
+ {
+ return m_attr;
+ }
+
+ /**
+ * @return true if this group supports adding or removing arbitrary
+ * keys, false if not.
+ **/
+ bool supportsVariableKeys() const
+ {
+ return m_variableItemInfo;
+ }
+
+ /**
+ * If the group supports variable keys, you can query their item
+ * info with this method. The main reason for this is that you can
+ * get the type and attributes of variable keys.
+ *
+ * @return a pointer to the item info. Don't delete this object!
+ **/
+ const ItemInfo* variableItemInfo( ) const
+ {
+ return m_variableItemInfo;
+ }
+
+ /** @internal */
+ ~GroupInfo();
+ private:
+ /** @internal */
+ GroupInfo( const TQString& name, const TQString& translatedName);
+
+ /** @internal */
+ KFileMimeTypeInfo::ItemInfo* addItemInfo( const TQString& key,
+ const TQString& translatedKey,
+ TQVariant::Type type);
+
+ /** @internal */
+ void addVariableInfo( TQVariant::Type type, uint attr );
+
+ TQString m_name;
+ TQString m_translatedName;
+ TQStringList m_supportedKeys;
+ uint m_attr;
+ ItemInfo* m_variableItemInfo;
+ TQDict<ItemInfo> m_itemDict;
+
+ };
+
+ /**
+ * This is the class for one item of a KFileMimeTypeInfo.
+ * It contains every information about a KFileMetaInfoItem that this
+ * item has in common for each file of a specific mimetype.
+ **/
+ class TDEIO_EXPORT ItemInfo
+ {
+ friend class KFilePlugin;
+ friend class GroupInfo;
+ public:
+ /** @internal */
+ ItemInfo() {} // ### should be private?
+
+ /**
+ *
+ * This method returns a translated prefix to be displayed before the
+ * value. Think e.g. of the $ in $30
+ *
+ * @return the prefix
+ */
+ const TQString& prefix() const
+ {
+ return m_prefix;
+ }
+
+ /**
+ * This method returns a translated suffix to be displayed after the
+ * value. Think of the kbps in 128kbps
+ *
+ * @return the prefix
+ */
+ const TQString& suffix() const
+ {
+ return m_suffix;
+ }
+
+ /**
+ * The items for a file are stored as a TQVariant and this method
+ * can be used to get the data type of this item.
+ *
+ * @return the TQVariant type
+ */
+ TQVariant::Type type() const
+ {
+ return m_type;
+ }
+
+ /**
+ * Returns the name of the item.
+ * @return the name of the item
+ */
+ const TQString& key() const
+ {
+ return m_key;
+ }
+
+ /**
+ * Returns a string for the specified @p value, if possible. If not,
+ * TQString::null is returned. This can be used by programs if they want
+ * to display a sum or an average of some item for a list of files.
+ *
+ * @param value the value to convert
+ * @param mangle if true, the string will already contain prefix and
+ * suffix
+ * @return the converted string, or TQString::null if not possible
+ * @since 3.1
+ */
+ TQString string( const TQVariant& value, bool mangle = true ) const;
+
+ /**
+ * Is this item the variable item?
+ *
+ * @return true if it is, false if not
+ */
+ bool isVariableItem() const
+ {
+ // every valid item is supposed to have a non-null key
+ return key().isNull();
+ }
+
+ /**
+ * Returns a translation of the key for displaying to the user. If the
+ * plugin provides translation to the key, it's also in the user's
+ * language.
+ * @return the translated key
+ */
+ const TQString& translatedKey() const
+ {
+ return m_translatedKey;
+ }
+
+ /**
+ * Return the attributes of the item. See
+ * KFileMimeTypeInfo::Attributes.
+ * @return the attributes
+ */
+ uint attributes() const
+ {
+ return m_attr;
+ }
+
+ /**
+ * Return the hints for the item. See
+ * KFileMimeTypeInfo::Hint
+ * @return the hint
+ */
+ uint hint() const
+ {
+ return m_hint;
+ }
+
+ /**
+ * Return the unit of the item. See
+ * KFileMimeTypeInfo::Unit
+ * @return the unit
+ */
+ uint unit() const
+ {
+ return m_unit;
+ }
+
+ private:
+ /** @internal */
+ ItemInfo(const TQString& key, const TQString& translatedKey,
+ TQVariant::Type type)
+ : m_key(key), m_translatedKey(translatedKey),
+ m_type(type),
+ m_attr(0), m_unit(NoUnit), m_hint(NoHint),
+ m_prefix(TQString::null), m_suffix(TQString::null)
+ {}
+
+ TQString m_key;
+ TQString m_translatedKey;
+ TQVariant::Type m_type;
+ uint m_attr;
+ uint m_unit;
+ uint m_hint;
+ TQString m_prefix;
+ TQString m_suffix;
+ };
+
+ // ### could it be made private? Would this be BC?
+ ~KFileMimeTypeInfo();
+
+ /**
+ * Creates a validator for this item. Make sure to supply a proper
+ * @p parent argument or delete the validator yourself.
+ *
+ * @param group the group of the item
+ * @param key the key of the item
+ * @param parent the parent of the TQObject, or 0 for a parent-less object
+ * @param name the name of the TQObject, can be 0
+ * @return the validator. You are responsible for deleting it. 0 if
+ * creation failed
+ */
+ TQValidator * createValidator(const TQString& group, const TQString& key,
+ TQObject *parent = 0, const char *name = 0) const;
+
+ /**
+ * Returns the list of all groups that the plugin for this mimetype
+ * supports.
+ *
+ * @return the list of groups
+ */
+ TQStringList supportedGroups() const;
+
+ /**
+ * Same as the above function, but returns the strings to display to the
+ * user.
+ *
+ * @return the list of groups
+ */
+ TQStringList translatedGroups() const;
+
+ /**
+ * This returns the list of groups in the preferred order that's specified
+ * in the .desktop file.
+ *
+ * @return the list of groups
+ */
+ TQStringList preferredGroups() const
+ {
+ return m_preferredGroups;
+ }
+
+ /**
+ * Returns the mimetype to which this info belongs.
+ *
+ * @return the mimetype of this info
+ */
+ TQString mimeType() const {return m_mimeType;}
+
+ /**
+ * Get the group info for a specific group.
+ *
+ * @param group the group whose group info should be retrieved
+ * @return a pointer to the info. 0 if it does not
+ * exist. Don't delete this object!
+ */
+ const GroupInfo * groupInfo( const TQString& group ) const;
+
+ // always returning stringlists which the user has to iterate and use them
+ // to look up the real items sounds strange to me. I think we should add
+ // our own iterators some time (somewhere in the future ;)
+
+ /**
+ * Return a list of all supported keys without looking for a specific
+ * group
+ *
+ * @return the list of keys
+ */
+ TQStringList supportedKeys() const;
+
+ /**
+ * Return a list of all supported keys in preference order
+ *
+ * @return the list of keys
+ */
+ TQStringList preferredKeys() const
+ {
+ return m_preferredKeys;
+ }
+
+ // ### shouldn't this be private? BC?
+ GroupInfo * addGroupInfo( const TQString& name,
+ const TQString& translatedName);
+
+ TQString m_translatedName;
+ TQStringList m_supportedKeys;
+ uint m_attr;
+ // bool m_supportsVariableKeys : 1;
+ TQDict<ItemInfo> m_itemDict;
+
+// ### this should be made private instead, but this would be BIC
+protected:
+ /** @internal */
+ KFileMimeTypeInfo( const TQString& mimeType );
+
+ TQDict<GroupInfo> m_groups;
+ TQString m_mimeType;
+ TQStringList m_preferredKeys; // same as KFileMetaInfoProvider::preferredKeys()
+ TQStringList m_preferredGroups; // same as KFileMetaInfoProvider::preferredKeys()
+};
+
+
+/**
+ * @brief A meta information item about a file
+ *
+ * This is one item of the meta information about a file (see
+ * KFileMetaInfo).
+ */
+class TDEIO_EXPORT KFileMetaInfoItem
+{
+public:
+ class Data;
+ typedef KFileMimeTypeInfo::Hint Hint;
+ typedef KFileMimeTypeInfo::Unit Unit;
+ typedef KFileMimeTypeInfo::Attributes Attributes;
+
+ /**
+ * @internal
+ * You usually don't need to use this constructor yourself. Let
+ * KFileMetaInfo do it for you.
+ **/
+ // ### hmm, then it should be private
+ KFileMetaInfoItem( const KFileMimeTypeInfo::ItemInfo* mti,
+ const TQString& key, const TQVariant& value);
+
+ /**
+ * Copy constructor
+ **/
+ KFileMetaInfoItem( const KFileMetaInfoItem & item );
+
+ /**
+ * The assignment operator, so you can do:
+ * @code
+ * KFileMetaInfoItem item = info.item("Title");
+ * @endcode
+ *
+ * This will create a shared copy of the object. The actual data
+ * is automatically deleted if all copies go out of scope
+ **/
+ const KFileMetaInfoItem& operator= (const KFileMetaInfoItem & item );
+
+ /**
+ * Default constructor. This creates an "invalid" item
+ */
+ KFileMetaInfoItem();
+
+ ~KFileMetaInfoItem();
+
+ /**
+ * Returns the key of the item.
+ *
+ * @return the key of this item
+ */
+ TQString key() const;
+
+ /**
+ * Returns a translation of the key for displaying to the user. If the
+ * plugin provides translation to the key, it's also in the user's language
+ *
+ * @return the translated key
+ */
+ TQString translatedKey() const;
+
+ /**
+ * Returns the value of the item.
+ *
+ * @return the value of the item.
+ */
+ const TQVariant& value() const;
+
+ /**
+ * Returns a string containing the value, if possible. If not,
+ * TQString::null is returned.
+ *
+ * @param mangle if true, the string will already contain prefix and
+ * suffix
+ * @return the value string, or TQString::null if not possible
+ */
+ TQString string( bool mangle = true ) const;
+
+ /**
+ * Changes the value of the item.
+ *
+ * @param value the new value
+ * @return true if successful, false otherwise
+ */
+ bool setValue( const TQVariant& value );
+
+ /**
+ * Return the type of the item.
+ *
+ * @return the type of the item
+ */
+ TQVariant::Type type() const;
+
+ /**
+ * You can query if the application can edit the item and write it back to
+ * the file with this method.
+ *
+ * @note This doesn't ensure that you have write access to the file and
+ * that enough space is available.
+ *
+ * @return true if the item's value can be changed, false if not
+ */
+ bool isEditable() const;
+
+ /**
+ * If you remove an item, it is only marked for removal for the file. On
+ * the next KFileMetaInfo::applyChanges() , it will be removed from
+ * the file. With this method, you can ask if the item is marked for
+ * removal.
+ *
+ * @return true if the item was removed, false if not
+ */
+ bool isRemoved() const;
+
+ /**
+ * If you change an item, it is marked as "dirty". On the next
+ * KFileMetaInfo::applyChanges() , the change will be written to the
+ * file. With this method, you can ask if this item is dirty.
+ *
+ * @return true if the item contains changes that have not yet been written
+ * back into the file. Removing or adding an item counts as such a change
+ */
+ bool isModified() const;
+
+ /**
+ * This method returns a translated prefix to be displayed before the
+ * value. Think e.g. of the $ in $30
+ *
+ * @return the prefix
+ */
+ TQString prefix() const;
+
+ /**
+ * This method returns a translated suffix to be displayed after the
+ * value. Think of the kbps in 128kbps
+ *
+ * @return the suffix
+ */
+ TQString suffix() const;
+
+ /**
+ * Returns the hint for this item. See KFileMimeTypeInfo::Hint.
+ *
+ * @return the hint
+ **/
+ uint hint() const;
+
+ /**
+ * Returns the unit for this item. See KFileMimeTypeInfo::Unit.
+ *
+ * @return the unit
+ * @since 3.2
+ **/
+ uint unit() const;
+
+ /**
+ * Returns the attributes for this item. See
+ * KFileMimeTypeInfo::Attributes.
+ *
+ * @return the attributes
+ **/
+ uint attributes() const;
+
+ /**
+ * Return true if the item is valid, i.e. if it contains data, false
+ * if it's invalid (created with the default constructor and not been
+ * assigned anything), or if KFileMetaInfoGroup::item() didn't find
+ * your requested item).
+ *
+ * @return true if valid, false if invalid
+ */
+ bool isValid() const;
+
+ TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoItem& );
+ TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& );
+ TDEIO_EXPORT friend TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoItem& );
+ friend class KFileMetaInfoGroup;
+
+protected:
+ void setAdded();
+ void setRemoved();
+
+ void ref();
+ void deref();
+
+ Data *d;
+};
+
+/**
+ * @brief A group of meta information items about a file
+ *
+ * This is one group of meta information items about a file (see
+ * KFileMetaInfo).
+ */
+class TDEIO_EXPORT KFileMetaInfoGroup
+{
+ friend class KFilePlugin;
+ friend class KFileMetaInfo;
+ TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& );
+ TDEIO_EXPORT friend TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoGroup& );
+
+public:
+ class Data;
+ /**
+ * @internal
+ * You usually don't need to use this constructor yourself. Let
+ * KFileMetaInfo do it for you.
+ **/
+ // ### hmm, then it should be private
+ KFileMetaInfoGroup( const TQString& name, const KFileMimeTypeInfo* info );
+
+ /**
+ * Copy constructor
+ **/
+ KFileMetaInfoGroup( const KFileMetaInfoGroup& original );
+
+ /**
+ * The assignment operator, so you can do:
+ * @code
+ * KFileMetaInfoGroup group = info.group("Technical");
+ * @endcode
+ *
+ * This will create a shared copy of the object. The actual data
+ * is automatically deleted if all copies go out of scope
+ **/
+ const KFileMetaInfoGroup& operator= (const KFileMetaInfoGroup& info );
+
+ /**
+ * Default constructor. This creates an "invalid" item
+ *
+ * @since 3.1
+ */
+ KFileMetaInfoGroup();
+
+ ~KFileMetaInfoGroup();
+
+ /**
+ * Returns true if the item is valid, i.e. if it contains data, false
+ * if it's invalid (created with the default constructor and not been
+ * assigned anything), or if KFileMetaInfoGroup::item() didn't find
+ * your requested item).
+ *
+ * @return true if valid, false if invalid
+ */
+ bool isValid() const;
+
+ /**
+ * Returns false if the object contains data, true if it's empty. An
+ * empty group is a group with no items (amazing, isn't it?).
+ *
+ * @return true if empty, false otherwise
+ */
+ bool isEmpty() const;
+
+ /**
+ * Returns true if an item as added or removed from the group.
+ *
+ * @return true if an item was added or removed from the group, otherwise
+ * false.
+ *
+ * @since 3.1
+ */
+ bool isModified() const;
+
+ /**
+ * Operator for convenience. It does the same as item(),
+ * but you cannot specify a group to search in
+ */
+ KFileMetaInfoItem operator[]( const TQString& key ) const
+ { return item( key ); }
+
+ /**
+ * This method searches for the specified item.
+ *
+ * @param key the key of the item to search
+ * @return the specified item if found, an invalid item, if not
+ **/
+ KFileMetaInfoItem item( const TQString& key ) const;
+
+ /**
+ * Returns the item with the given @p hint.
+ *
+ * @param hint the hint of the item
+ * @return the item with the specified @p hint
+ **/
+ KFileMetaInfoItem item( uint hint ) const;
+
+ /**
+ * Convenience function. Returns the value of the specified key.
+ * It does the same as item(key).value().
+ *
+ * @param key the key of the item to search
+ * @return the value with the given key
+ */
+ const TQVariant value( const TQString& key ) const
+ {
+ const KFileMetaInfoItem &i = item( key );
+ return i.value();
+ }
+
+ /**
+ * Use this method to get a list of keys in the specified group that
+ * the plugin knows about. No variable keys.
+ * For a group that doesn't support variable keys, all keys that this
+ * group may have are returned. For a group that does support them, the
+ * non-variable ones are returned. See KFileMetaInfo about variable
+ * keys
+ *
+ * @return the list of keys supported for this mimetype
+ **/
+ TQStringList supportedKeys() const;
+
+ /**
+ * Returns true if this group supports adding or removing arbitrary
+ * keys, false if not.
+ *
+ * @return true is variable keys are supported, false otherwise
+ **/
+ bool supportsVariableKeys() const;
+
+ /**
+ * Checks whether an item with the given @p key exists.
+ *
+ * @return true if an item for this @p key exists.
+ */
+ bool contains( const TQString& key ) const;
+
+ /**
+ * Returns a list of all keys.
+ *
+ * @return a list of all keys in the order they were inserted.
+ **/
+ TQStringList keys() const;
+
+ /**
+ * Returns a list of all keys in preference order.
+ *
+ * @return a list of all keys in preference order.
+ **/
+ TQStringList preferredKeys() const;
+
+ /**
+ * @return the list of possible types that the value for the specified key
+ * can be. You can use this to determine the possible types for new
+ * keys before you add them.
+ *
+ **/
+ // ### do we really want to support that?
+ // let's not waste time on thinking about it. Let's just kick it for now
+ // and add it in 4.0 if needed ;)
+// const TQMemArray<TQVariant::Type>& types( const TQString& key ) const;
+
+ /**
+ * Add an item to the info. This is only possible if the specified @p key
+ * is in the supportedKeys list and not yet defined or if
+ * the group supports variable keys.
+ *
+ * @param key the key of the item
+ * @return the KFileMetaInfoItem for the given @p key
+ **/
+ KFileMetaInfoItem addItem( const TQString& key );
+
+ /**
+ * Remove this item from the meta info of the file. You cannot query
+ * KFileMetaInfo for a removed object, but you can query for a list of
+ * removed items with removedItems() if you need to.
+ * If you re-add it, its value will be cleared.
+ *
+ * @param key the key of the removed item
+ * @return true if successful, false otherwise
+ */
+ bool removeItem(const TQString& key);
+
+ /**
+ * Returns a list of all removed items.
+ *
+ * @return a list of all removed items
+ */
+ TQStringList removedItems();
+
+ /**
+ * The name of this group.
+ *
+ * @return the name of this group
+ */
+ TQString name() const;
+
+ /**
+ * The translated name of this group.
+ *
+ * @return the translated name of this group
+ *
+ * @since 3.2
+ */
+ TQString translatedName() const;
+
+ /**
+ * Returns the attributes of this item.
+ *
+ * @return the attributes
+ */
+ uint attributes() const;
+
+protected:
+ void setAdded();
+ KFileMetaInfoItem appendItem( const TQString& key, const TQVariant& value);
+
+ Data* d;
+ void ref();
+ void deref();
+
+};
+
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+/**
+ * @brief Meta Information about a file
+ *
+ * This is the class for objects that hold meta information about a file.
+ * The information is kept in form of a system of key/value pairs. See also
+ * KFileMetaInfoItem.
+ * This information is retrieved from the file through a plugin system, and
+ * this class is the main interface to it.
+ * If you want to write your own plugin, have a look at KFilePlugin.
+ * There are basically two different kinds of meta information: Fixed ones
+ * that the plugin knows about (e.g. an mp3 id3v1 tag has a well defined
+ * fixed list of fields), and variable keys that exist in mimetypes that
+ * support their own key/value system (comments in png files are of this type).
+ * Almost every file has fixed keys, but some also have variable keys.
+ *
+ * The groups and the What enum are not yet supported, but already added to
+ * the interface so that adding support doesn't break compatibility.
+ */
+class TDEIO_EXPORT KFileMetaInfo
+{
+public:
+ typedef KFileMimeTypeInfo::Hint Hint;
+ typedef KFileMimeTypeInfo::Unit Unit;
+ typedef KFileMimeTypeInfo::Attributes Attributes;
+ class Data;
+
+ /**
+ * This is used to specify what a KFileMetaInfo object should read, so
+ * you can specify if you want to read "expensive" items or not.
+ */
+ enum What
+ {
+ Fastest = 0x1, /**< do the fastest possible read and omit all items
+ that might need a significantly longer time
+ than the others */
+ DontCare = 0x2, ///< let the plugin decide what to read
+
+ TechnicalInfo = 0x4, /**< extract technical details about the file, like
+ e.g. play time, resolution or a compressioni
+ type */
+ ContentInfo = 0x8, /**< read information about the content of the file,
+ like comments or id3 tags */
+ ExtenedAttr = 0x10, /**< read filesystem based extended attributes if
+ they are supported for the filesystem */
+ Thumbnail = 0x20, /**< only read the file's thumbnail, if it contains
+ one */
+ Preferred = 0x40, ///< get at least the preferred items
+ Everything = 0xffff ///< read everything, even if it might take a while
+
+ };
+
+ /**
+ * The constructor.
+ *
+ * creating a KFileMetaInfo item through this will autoload the plugin
+ * belonging to the mimetype and try to get meta information about
+ * the specified file.
+ *
+ * If no info is available, you'll get an empty (not invalid) object.
+ * You can test for it with the isEmpty() method.
+ *
+ * @param path The file name. This must be the path to a local file.
+ * @param mimeType The name of the file's mimetype. If ommited, the
+ * mimetype is autodetected
+ * @param what one or more of the What enum values. It gives some
+ * hint to the plugin what information is desired. The plugin
+ * may still return more items.
+ *
+ * @note This version will @b only work for @b local (file:/) files.
+ *
+ **/
+ KFileMetaInfo( const TQString& path,
+ const TQString& mimeType = TQString::null,
+ uint what = Fastest);
+
+ /**
+ * Another constructor
+ *
+ * Similar to the above, but takes a URL so that meta-data may be retrieved
+ * over other protocols (ftp, etc.)
+ *
+ **/
+ KFileMetaInfo( const KURL& url,
+ const TQString& mimeType = TQString::null,
+ uint what = Fastest);
+
+ /**
+ * Default constructor. This will create an invalid object (see
+ * isValid().
+ **/
+ KFileMetaInfo();
+
+ /**
+ * Copy constructor. This creates a copy of the original object, but
+ * that copy will point to the same data, so if you change the original,
+ * the copy will be changed, too. After all, they are referring to the same
+ * file.
+ **/
+ KFileMetaInfo( const KFileMetaInfo& original);
+
+ ~KFileMetaInfo();
+
+ /**
+ * The assignment operator, so you can do e.g.:
+ * @code
+ * KFileMetaInfo info;
+ * if (something) info = KFileMetaInfo("/the/file");
+ * @endcode
+ *
+ * This will create a shared copy of the object. The actual data
+ * is automatically deleted if all copies go out of scope.
+ **/
+ const KFileMetaInfo& operator= (const KFileMetaInfo& info );
+
+
+ /**
+ * Returns a list of all groups.
+ *
+ * @return the keys of the groups that the file has.
+ */
+ TQStringList groups() const;
+
+ /**
+ * Returns a list of all supported groups.
+ *
+ * @return the supported keys of the groups that the file has.
+ */
+ TQStringList supportedGroups() const;
+
+ /**
+ * Returns a list of the preferred groups.
+ *
+ * @return the keys of the preferred groups that the file has.
+ */
+ TQStringList preferredGroups() const;
+
+ /**
+ * Returns a list of all preferred keys.
+ *
+ * @return a list of all preferred keys.
+ */
+ TQStringList preferredKeys() const;
+
+ /**
+ * Returns a list of supported keys.
+ *
+ * @return a list of supported keys
+ */
+ TQStringList supportedKeys() const;
+
+ /**
+ * Returns the list of groups that you can add or remove from the file.
+ *
+ * @return the groups can be added or removed
+ */
+ TQStringList editableGroups() const;
+
+ // I'd like to keep those for lookup without group, at least the hint
+ // version
+ /**
+ * Returns the KFileMetaInfoItem with the given @p key.
+ *
+ * @param key the key of the item
+ * @return the item. Invalid if there is no item with the given @p key.
+ */
+ KFileMetaInfoItem item(const TQString& key) const;
+ /**
+ * Returns the KFileMetaInfoItem with the given @p hint.
+ *
+ * @param hint the hint of the item
+ * @return the item. Invalid if there is no item with the given @p hint.
+ */
+ KFileMetaInfoItem item(const KFileMetaInfoItem::Hint hint) const;
+
+ /**
+ * Saves the item with the given @p key.
+ *
+ * @param key the key of the item
+ * @param preferredGroup the preferred group, or TQString::null
+ * @param createGroup true to create the group if necessary
+ * @return the saved item
+ */
+ KFileMetaInfoItem saveItem( const TQString& key,
+ const TQString& preferredGroup = TQString::null,
+ bool createGroup = true );
+
+ /**
+ * Returns the KFileMetaInfoGroup with the given @p key.
+ *
+ * @param key the key of the item
+ * @return the group. Invalid if there is no group with the given @p key.
+ */
+ KFileMetaInfoGroup group(const TQString& key) const;
+
+ /**
+ * Returns the KFileMetaInfoGroup with the given @p key.
+ *
+ * @param key the key of the item
+ * @return the group. Invalid if there is no group with the given @p key.
+ */
+ KFileMetaInfoGroup operator[] (const TQString& key) const
+ {
+ return group(key);
+ }
+
+ /**
+ * Try to add the specified group. This will only succeed if it is
+ * in the list of editableGroups().
+ *
+ * @note that all non-variable items that belong to this group are
+ * automatically added as empty item.
+ *
+ * @param name the name of the group to add
+ * @return true if successful, false if not
+ */
+ bool addGroup( const TQString& name );
+
+ /**
+ * Remove the specified group. This will only succeed if it is
+ * in the list of editableGroups(). Beware that this also
+ * removes all the items in that group, so always ask the user
+ * before removing it!
+ *
+ * @param name the name of the group to remove
+ * @return true if successful, false if not
+ */
+ bool removeGroup( const TQString& name );
+
+ /**
+ * Returns a list of removed groups.
+ *
+ * @return a list of removed groups.
+ */
+ TQStringList removedGroups();
+
+ /**
+ * This method writes all pending changes of the meta info back to the file.
+ * If any items are marked as removed, they are really removed from the
+ * list. The info object as well as all items are updated.
+ *
+ * @return true if successful, false if not
+ */
+ bool applyChanges();
+
+ /**
+ * This method writes all pending changes of the meta info to the file @p path.
+ * If any items are marked as removed, they are really removed from the
+ * list. The info object as well as all items are updated.
+ *
+ * @return true if successful, false if not
+ */
+ bool applyChanges(const TQString& path);
+
+ /**
+ * Checks whether an item with the given @p key exists.
+ *
+ * @param key the key to check
+ * @return whether an item for this @p key exists.
+ */
+ bool contains( const TQString& key ) const;
+
+ /**
+ * Checks whether a group with the given @p key exists.
+ *
+ * @param key the key to check
+ * @return whether a group with this name exists.
+ */
+ bool containsGroup( const TQString& key ) const;
+
+ /**
+ * Returns the value with the given @p key.
+ *
+ * @param key the key to retrieve
+ * @return the value. Invalid if it does not exist
+ */
+ const TQVariant value( const TQString& key ) const
+ {
+ return item(key).value();
+ }
+
+
+ /**
+ * Returns true if the item is valid, i.e. if actually represents the info
+ * about a file, false if the object is uninitialized.
+ *
+ * @return true if valid, false otherwise
+ */
+ bool isValid() const;
+
+ /**
+ * Returns false if the object contains data, true if it's empty. You'll
+ * get an empty object if no plugin for the file could be found.
+ *
+ * @return true if empty, false otherwise
+ */
+ bool isEmpty() const;
+
+ /**
+ * Returns the mime type of file.
+ *
+ * @return the file's mime type
+ */
+ TQString mimeType() const;
+
+ /**
+ * Returns the path of file - or TQString::null if file is non-local
+ *
+ * @return the file's path - or TQString::null if file is non-local
+ */
+ TQString path() const;
+
+ /**
+ * Returns the url of file
+ *
+ * @return the file's url
+ */
+ KURL url() const;
+
+ TDEIO_EXPORT friend TQDataStream& operator >>(TQDataStream& s, KFileMetaInfo& );
+ TDEIO_EXPORT friend TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfo& );
+ friend class KFilePlugin;
+
+protected:
+ KFileMetaInfoGroup appendGroup(const TQString& name);
+
+ /**
+ * @return a pointer to the plugin that belogs to this object's mimetype.
+ * It will be auto-loaded if it's currently not loaded
+ **/
+ KFilePlugin * plugin() const;
+
+ void ref();
+ void deref();
+
+ Data* d;
+
+private:
+ KFileMetaInfoItem findEditableItem( KFileMetaInfoGroup& group,
+ const TQString& key );
+
+ void init( const KURL& url,
+ const TQString& mimeType = TQString::null,
+ uint what = Fastest);
+};
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+/**
+ * @brief Base class for a meta information plugin
+ *
+ * Meta information plugins are used to extract useful information from files
+ * of a given type. These plugins are used in Konqueror's file properties
+ * dialog, for example.
+ *
+ * If you want to write your own plugin, you need to derive from this class.
+ *
+ * In the constructor of your class, you need to call addMimeTypeInfo() to tell
+ * the KFile framework which mimetype(s) your plugin supports. For each
+ * mimetype, use the addGroupInfo() and addItemInfo() methods to declare the
+ * meta information items the plugin calculates and to group them accordingly.
+ * For groups, use setAttributes() to customize your group (see
+ * KFileMimeTypeInfo::Attributes). For items, use setAttributes() to define the
+ * behaviour of the item; use setHint() to define the meaning of the item; use
+ * setUnit() to define the Unit, such as KFileMimeTypeInfo::Seconds or
+ * KFileMimeTypeInfo::KiloBytes. In short, the constructor defines the data
+ * structure of the meta information supported by your plugin.
+ *
+ * Example:
+ * @code
+ * FooPlugin::FooPlugin(TQObject *parent, const char *name,
+ * const TQStringList &args)
+ * : KFilePlugin(parent, name, args)
+ * {
+ * KFileMimeTypeInfo* info = addMimeTypeInfo( "application/x-foo" );
+ *
+ * // our new group
+ * KFileMimeTypeInfo::GroupInfo* group = 0L;
+ * group = addGroupInfo(info, "FooInfo", i18n("Foo Information"));
+ *
+ * KFileMimeTypeInfo::ItemInfo* item;
+ *
+ * // our new items in the group
+ * item = addItemInfo(group, "Items", i18n("Items"), TQVariant::Int);
+ * item = addItemInfo(group, "Size", i18n("Size"), TQVariant::Int);
+ * setUnit(item, KFileMimeTypeInfo::KiloBytes);
+ *
+ * // strings are possible, too:
+ * //addItemInfo(group, "Document Type", i18n("Document type"), TQVariant::String);
+ * }
+ * @endcode
+ *
+ * Some meta information items are likely to be available in several different
+ * file formats, such as @c "Author", @c "Title" (for documents), and
+ * @c "Length" (for multimedia files). Be sure to use the naming scheme from
+ * existing plugins for your meta information items if possible. If, for
+ * example, the meta information of a group of files is shown in a table view,
+ * this will allow two files to share the same column (say "Length") even if
+ * they are of a different file type.
+ *
+ * You must overwrite the readInfo() method. In this method you need to extract
+ * the meta information of the given file. You can use a third-party library to
+ * achieve this task. This might be the best way for binary files, since a
+ * change in the file format is likely to be supported by subsequent releases
+ * of that library. Alternatively, for text-based file formats, you can use
+ * TQTextStream to parse the file. For simple file formats, TQRegExp can be of
+ * great help, too.
+ *
+ * After you extracted the relevant information, use appendGroup() and
+ * appendItem() to fill the meta information data structure (as defined in the
+ * constructor) with values. Note that you can leave out groups or items
+ * which are not appropriate for a particular file.
+ *
+ * Example:
+ * @code
+ * bool FooPlugin::readInfo( KFileMetaInfo& info, uint what)
+ * {
+ * int numItems = 0;
+ * int size = 0;
+ *
+ * // do your calculations here, e.g. using a third-party
+ * // library or by writing an own parser using e.g. QTextStream
+ *
+ * // calculate numItems and size ...
+ *
+ * // note: use the same key strings as in the constructor
+ * KFileMetaInfoGroup group = appendGroup(info, "FooInfo");
+ *
+ * appendItem(group, "Items", numItems);
+ * appendItem(group, "Size", size);
+ *
+ * return true;
+ * }
+ * @endcode
+ *
+ * If you want to define mutable meta information items, you need to overwrite
+ * the writeInfo() method. In this method, you can use third-party library
+ * (appropriate mostly for binary files, see above) or TQTextStream to write the
+ * information back to the file. If you use TQTextStream, be sure to write all
+ * file contents back.
+ *
+ * For some items, it might be that not all possible values are allowed. You
+ * can overwrite the createValidator() method to define constraints for a meta
+ * information item. For example, the @c "Year" field for an MP3 file could
+ * reject values outside the range 1500 - 2050 (at least for now). The
+ * validator is used to check values before the writeInfo() method is called so
+ * that writeInfo() is only provided correct values.
+ *
+ * In your plugin, you need to create a factory for the KFilePlugin
+ *
+ * Example:
+ * @code
+ * typedef KGenericFactory<FooPlugin> FooFactory;
+ * K_EXPORT_COMPONENT_FACTORY(tdefile_foo, FooFactory("tdefile_foo"));
+ * @endcode
+ *
+ * To make your plugin available within KDE, you also need to provide a
+ * @c .desktop file which describes your plugin. The required fields in the
+ * file are:
+ *
+ * - @c Type: must be @c "Service"
+ * - @c Name: the name of the plugin
+ * - @c ServiceTypes: must contain @c "KFilePlugin"
+ * - @c X-TDE-Library: the name of the library containing the KFile plugin
+ * - @c MimeType: the mimetype(s) which are supported by the plugin
+ * - @c PreferredGroups: a comma-separated list of the most important groups.
+ * This list defines the order in which the meta information groups should be
+ * displayed
+ * - @c PreferredItems: a comma-separated list of the most important items.
+ * This list defines the order in which the meta information items should be
+ * displayed
+ *
+ * Example:
+ * @code
+ * [Desktop Entry]
+ * Encoding=UTF-8
+ * Type=Service
+ * Name=Foo Info
+ * ServiceTypes=KFilePlugin
+ * X-TDE-Library=tdefile_foo
+ * MimeType=application/x-foo
+ * PreferredGroups=FooInfo
+ * PreferredItems=Items,Size
+ * @endcode
+ **/
+class TDEIO_EXPORT KFilePlugin : public TQObject
+{
+ Q_OBJECT
+
+public:
+ /**
+ * Creates a new KFilePlugin instance. You need to implement a constructor
+ * with the same argument list as this is required by KGenericFactory
+ *
+ * @param parent the parent of the TQObject, can be @c 0
+ * @param name the name of the TQObject, can be @c 0
+ * @param args currently ignored
+ *
+ * @see addMimeTypeInfo()
+ * @see addGroupInfo()
+ * @see addItemInfo()
+ * @see TQObject()
+ **/
+ KFilePlugin( TQObject *parent, const char *name,
+ const TQStringList& args );
+
+ /**
+ * Destructor
+ */
+ virtual ~KFilePlugin();
+
+ /**
+ * Read the info from the file in this method and insert it into the
+ * provided KFileMetaInfo object. You can get the path to the file with
+ * KFileMetaInfo::path(). Use appendGroup() and appendItem() to fill
+ * @p info with the extracted values
+ *
+ * @param info the information will be written here
+ * @param what defines what to read, see KFileMetaInfo::What
+ * @return @c true if successful, @c false if it failed
+ *
+ * @see writeInfo()
+ **/
+ virtual bool readInfo( KFileMetaInfo& info,
+ uint what = KFileMetaInfo::Fastest ) = 0;
+
+ /**
+ * Similar to the readInfo() but for writing the info back to the file.
+ * If you don't have any writable keys, don't implement this method
+ *
+ * @param info the information that will be written
+ * @return @c true if successful, @c false if it failed
+ **/
+ virtual bool writeInfo( const KFileMetaInfo& info ) const
+ {
+ Q_UNUSED(info);
+ return true;
+ }
+
+ /**
+ * This method should create an appropriate validator for the specified
+ * item if it's editable or return a null pointer if not. If you don't have
+ * any editable items, you don't need to implement this method.
+ *
+ * If you you don't need any validation, e.g. you accept any input, you can
+ * simply return @c 0L, or not reimplement this method at all.
+ *
+ * @param mimeType the mime type
+ * @param group the group name of the validator item
+ * @param key the key name of the validator item
+ * @param parent the TQObject parent, can be @c 0
+ * @param name the name of the TQObject, can be @c 0
+ **/
+ virtual TQValidator* createValidator( const TQString& mimeType,
+ const TQString& group,
+ const TQString& key,
+ TQObject* parent,
+ const char* name) const
+ {
+ Q_UNUSED(mimeType); Q_UNUSED(group);Q_UNUSED(key);
+ Q_UNUSED(parent);Q_UNUSED(name);
+ return 0;
+ }
+
+protected:
+
+ /**
+ * Call this from within your constructor to tell the KFile framework what
+ * mimetypes your plugin supports.
+ *
+ * @param mimeType a string containing the mimetype, e.g. @c "text/html"
+ * @return a KFileMimeTypeInfo object, to be used with addGroupInfo()
+ **/
+ KFileMimeTypeInfo * addMimeTypeInfo( const TQString& mimeType );
+ // ### do we need this, if it only calls the provider?
+ // IMHO the Plugin shouldn't call its provider.
+ // DF: yes we need this. A plugin can create more than one mimetypeinfo.
+ // What sucks though, is to let plugins do that in their ctor.
+ // Would be much simpler to have a virtual init method for that,
+ // so that the provider can set up stuff with the plugin pointer first!
+
+ /**
+ * Creates a meta information group for KFileMimeTypeInfo object returned
+ * by addMimeTypeInfo().
+ *
+ * @param info the object returned by addMimeTypeInfo()
+ * @param key a unique string identifiing this group. For simplicity it is
+ * recommended to use the same string as for the translatedKey
+ * parameter
+ * @param translatedKey the translated version of the key string for
+ * displaying in user interfaces. Use i18n() to translate the string
+ * @return a GroupInfo object. Pass this object to addItemInfo to add meta
+ * information attributed to this group.
+ *
+ * @see setAttributes()
+ * @see addItemInfo()
+ **/
+ KFileMimeTypeInfo::GroupInfo* addGroupInfo(KFileMimeTypeInfo* info,
+ const TQString& key, const TQString& translatedKey) const;
+
+ /**
+ * Sets attributes of the GroupInfo object returned by addGroupInfo().
+ *
+ * @param gi the object returned by addGroupInfo()
+ * @param attr the attributes for this group; these are values of type
+ * KFileMimeTypeInfo::Attributes, or'ed together
+ **/
+ void setAttributes(KFileMimeTypeInfo::GroupInfo* gi, uint attr) const;
+
+ void addVariableInfo(KFileMimeTypeInfo::GroupInfo* gi, TQVariant::Type type,
+ uint attr) const;
+
+ /**
+ * Adds a meta information item to a GroupInfo object as returned by
+ * addGroupInfo().
+ *
+ * @param gi the GroupInfo object to add a new item to
+ * @param key a unique string to identify this item. For simplicity it is
+ * recommended to use the same string as for the translatedKey
+ * parameter
+ * @param translatedKey the translated version of the key string for
+ * displaying in user interfaces. Use i18n() to translate the string
+ * @param type the type of the meta information item, e.g. TQVariant::Int
+ * or TQVariant::String.
+ * @return an ItemInfo object. Pass this object to setAttributes()
+ **/
+ KFileMimeTypeInfo::ItemInfo* addItemInfo(KFileMimeTypeInfo::GroupInfo* gi,
+ const TQString& key,
+ const TQString& translatedKey,
+ TQVariant::Type type);
+
+ /**
+ * Sets some attributes for a meta information item. The attributes
+ * describe if the item is mutable, how it should be computed for a list of
+ * files, and how it should be displayed
+ *
+ * @param item the ItemInfo object as returned by addItemInfo()
+ * @param attr the attributes for this item; these are values of type
+ * KFileMimeTypeInfo::Attributes, or'ed together
+ **/
+ void setAttributes(KFileMimeTypeInfo::ItemInfo* item, uint attr);
+
+ /**
+ * Defines the meaning of the meta information item. Some applications make
+ * use of this information, so be sure to check KFileMimeTypeInfo::Hint to
+ * see if an item's meaning is in the list.
+ *
+ * @param item the ItemInfo object as returned by addItemInfo()
+ * @param hint the item's meaning. See KFileMimeTypeInfo::Hint for a list
+ * of available meanings
+ **/
+ void setHint(KFileMimeTypeInfo::ItemInfo* item, uint hint);
+
+ /**
+ * Sets the unit used in the meta information item. This unit is used to
+ * format the value and to make large values human-readable. For example,
+ * if the item's unit is KFileMimeTypeInfo::Seconds and the value is 276,
+ * it will be displayed as 4:36.
+ *
+ * @param item the ItemInfo object as returned by addItemInfo()
+ * @param unit the item's unit. See KFileMimeTypeInfo::Unit for a list of
+ * available units
+ **/
+ void setUnit(KFileMimeTypeInfo::ItemInfo* item, uint unit);
+
+ /**
+ * Sets a prefix string which is displayed before the item's value. Use
+ * this string if no predefined unit fits the item's unit. Be sure to
+ * translate the string with i18n()
+ *
+ * @param item the ItemInfo object as returned by addItemInfo()
+ * @param prefix the prefix string to display
+ **/
+ void setPrefix(KFileMimeTypeInfo::ItemInfo* item, const TQString& prefix);
+
+ /**
+ * Sets a suffix string which is displayed before the item's value. Use
+ * this string if no predefined unit fits the item's unit. Be sure to
+ * translate the string with i18n()
+ *
+ * @param item the ItemInfo object as returned by addItemInfo()
+ * @param suffix the suffix string to display
+ **/
+ void setSuffix(KFileMimeTypeInfo::ItemInfo* item, const TQString& suffix);
+
+ /**
+ * Call this method from within readInfo() to indicate that you wish to
+ * fill meta information items of the group identified by @p key with
+ * values.
+ *
+ * @param info the KFileMetaInfo object. Use the parameter of the
+ * readInfo() method
+ * @param key the key string to identify the group. Use the string that you
+ * defined in your class' constructor
+ * @return a KFileMetaInfoGroup object, to be used in appendItem()
+ **/
+ KFileMetaInfoGroup appendGroup(KFileMetaInfo& info, const TQString& key);
+
+ /**
+ * Call this method from within readInfo() to fill the meta information item
+ * identified by @p key with a @p value
+ *
+ * @param group the KFileMetaInfoGroup object, as returned by appendGroup()
+ * @param key the key string to identify the item.
+ * @param value the value of the meta information item
+ **/
+ void appendItem(KFileMetaInfoGroup& group, const TQString& key, TQVariant value);
+
+ TQStringList m_preferredKeys;
+ TQStringList m_preferredGroups;
+
+protected:
+ /**
+ * Helper method to allow binary compatible extensions when needing
+ * "new virtual methods"
+ *
+ * @param id the identifier of the new "virtual" method
+ * @param data any parameter data the new "virtual" method needs
+ */
+ virtual void virtual_hook( int id, void* data );
+private:
+ class KFilePluginPrivate;
+ KFilePluginPrivate *d;
+};
+
+///////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////
+
+
+/**
+ * @internal
+ * Synchronous access to metadata of a local file. Usually, you don't want
+ * to use this class for getting metainfo from a file. Use KFileMetaInfo
+ * directly. However, if you want to find out if a specific mimetype is
+ * supported and which groups and items are provided for it, you can ask
+ * the KFileMetainfoProvider for it.
+ **/
+class TDEIO_EXPORT KFileMetaInfoProvider: private QObject
+{
+ friend class KFilePlugin;
+
+ Q_OBJECT
+public:
+ virtual ~KFileMetaInfoProvider();
+
+ static KFileMetaInfoProvider * self();
+
+ /**
+ * @return a pointer to the plugin that belongs to the specified mimetype,
+ * which means also load the plugin if it's not in memory
+ */
+ KFilePlugin * plugin( const TQString& mimeType ); // KDE4: merge with method below
+
+ /**
+ * @return a pointer to the plugin that belongs to the specified mimetype,
+ * for the given protocol.
+ * This loads the plugin if it's not in memory yet.
+ */
+ KFilePlugin * plugin( const TQString& mimeType, const TQString& protocol );
+
+ const KFileMimeTypeInfo * mimeTypeInfo( const TQString& mimeType ); // KDE4: merge with below
+ const KFileMimeTypeInfo * mimeTypeInfo( const TQString& mimeType, const TQString& protocol );
+
+ TQStringList preferredKeys( const TQString& mimeType ) const;
+ TQStringList preferredGroups( const TQString& mimeType ) const;
+
+ /// @since 3.1
+ TQStringList supportedMimeTypes() const;
+
+protected: // ## should be private, right?
+ KFileMetaInfoProvider();
+
+private:
+
+ // Data structure:
+ // Mimetype or Protocol -> { Plugin and MimeTypeInfo }
+ // The {} struct is CachedPluginInfo
+ struct CachedPluginInfo
+ {
+ CachedPluginInfo() : plugin( 0 ), mimeTypeInfo( 0 ), ownsPlugin( false ) {}
+ CachedPluginInfo( KFilePlugin* p, KFileMimeTypeInfo* i, bool owns )
+ : plugin( p ), mimeTypeInfo( i ), ownsPlugin( owns ) {}
+ // auto-delete behavior
+ ~CachedPluginInfo() {
+ if ( ownsPlugin ) delete plugin;
+ delete mimeTypeInfo;
+ }
+
+ // If plugin and mimeTypeInfo are 0, means that no plugin is available.
+ KFilePlugin* plugin;
+ KFileMimeTypeInfo* mimeTypeInfo;
+ // The problem here is that plugin can be shared in multiple instances,
+ // so the memory management isn't easy. KDE4 solution: use KSharedPtr?
+ // For now we flag one copy of the KFilePlugin pointer as being "owned".
+ bool ownsPlugin;
+ };
+
+ // The key is either a mimetype or a protocol. Those things don't look the same
+ // so there's no need for two QDicts.
+ TQDict<CachedPluginInfo> m_plugins;
+
+ // This data is aggregated during the creation of a plugin,
+ // before being moved to the appropriate CachedPluginInfo(s)
+ // At any other time than during the loading of a plugin, this dict is EMPTY.
+ // Same key as in m_plugins: mimetype or protocol
+ TQDict<KFileMimeTypeInfo> m_pendingMimetypeInfos;
+
+private:
+ static KFileMetaInfoProvider * s_self;
+
+ KFilePlugin* loadPlugin( const TQString& mimeType, const TQString& protocol );
+ KFilePlugin* loadAndRegisterPlugin( const TQString& mimeType, const TQString& protocol );
+ KFileMimeTypeInfo * addMimeTypeInfo( const TQString& mimeType );
+
+ class KFileMetaInfoProviderPrivate;
+ KFileMetaInfoProviderPrivate *d;
+
+};
+
+TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoItem& );
+TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoItem& );
+
+TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfoGroup& );
+TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfoGroup& );
+
+TDEIO_EXPORT TQDataStream& operator <<(TQDataStream& s, const KFileMetaInfo& );
+TDEIO_EXPORT TQDataStream& operator >>(TQDataStream& s, KFileMetaInfo& );
+
+
+#endif // KILEMETAINFO_H
diff --git a/tdeio/tdeio/tdefileshare.cpp b/tdeio/tdeio/tdefileshare.cpp
new file mode 100644
index 000000000..fe6e0bd15
--- /dev/null
+++ b/tdeio/tdeio/tdefileshare.cpp
@@ -0,0 +1,346 @@
+/* This file is part of the KDE project
+ Copyright (c) 2001 David Faure <david@mandrakesoft.com>
+ Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "tdefileshare.h"
+#include <tqdir.h>
+#include <tqfile.h>
+#include <tqregexp.h>
+#include <kprocess.h>
+#include <kprocio.h>
+#include <klocale.h>
+#include <kstaticdeleter.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kdirwatch.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <kdirnotify_stub.h>
+#include <ksimpleconfig.h>
+#include <kuser.h>
+
+KFileShare::Authorization KFileShare::s_authorization = NotInitialized;
+//TQStringList* KFileShare::s_shareList = 0L;
+//static KStaticDeleter<TQStringList> sdShareList;
+TQMap<TQString,TQString>* KFileShare::s_shareMap = 0L;
+static KStaticDeleter<TQMap<TQString,TQString> > sdShareMap;
+
+KFileShare::ShareMode KFileShare::s_shareMode;
+bool KFileShare::s_sambaEnabled;
+bool KFileShare::s_nfsEnabled;
+bool KFileShare::s_restricted;
+TQString KFileShare::s_fileShareGroup;
+bool KFileShare::s_sharingEnabled;
+
+
+#define FILESHARECONF "/etc/security/fileshare.conf"
+
+KFileSharePrivate::KFileSharePrivate()
+{
+ KDirWatch::self()->addFile(FILESHARECONF);
+ connect(KDirWatch::self(), TQT_SIGNAL(dirty (const TQString&)),this,
+ TQT_SLOT(slotFileChange(const TQString &)));
+ connect(KDirWatch::self(), TQT_SIGNAL(created(const TQString&)),this,
+ TQT_SLOT(slotFileChange(const TQString &)));
+ connect(KDirWatch::self(), TQT_SIGNAL(deleted(const TQString&)),this,
+ TQT_SLOT(slotFileChange(const TQString &)));
+}
+
+KFileSharePrivate::~KFileSharePrivate()
+{
+ KDirWatch::self()->removeFile(FILESHARECONF);
+}
+
+KFileSharePrivate *KFileSharePrivate::_self=0L;
+
+static KStaticDeleter<KFileSharePrivate> kstFileShare;
+
+KFileSharePrivate* KFileSharePrivate::self()
+{
+ if (!_self)
+ _self = kstFileShare.setObject(_self, new KFileSharePrivate());
+ return _self;
+}
+
+void KFileSharePrivate::slotFileChange(const TQString &file)
+{
+ if(file==FILESHARECONF) {
+ KFileShare::readConfig();
+ KFileShare::readShareList();
+ }
+}
+
+void KFileShare::readConfig() // static
+{
+ // Create KFileSharePrivate instance
+ KFileSharePrivate::self();
+ KSimpleConfig config(TQString::fromLatin1(FILESHARECONF),true);
+
+ s_sharingEnabled = config.readEntry("FILESHARING", "yes") == "yes";
+ s_restricted = config.readEntry("RESTRICT", "yes") == "yes";
+ s_fileShareGroup = config.readEntry("FILESHAREGROUP", "fileshare");
+
+
+ if (!s_sharingEnabled)
+ s_authorization = UserNotAllowed;
+ else
+ if (!s_restricted )
+ s_authorization = Authorized;
+ else {
+ // check if current user is in fileshare group
+ KUserGroup shareGroup(s_fileShareGroup);
+ if (shareGroup.users().findIndex(KUser()) > -1 )
+ s_authorization = Authorized;
+ else
+ s_authorization = UserNotAllowed;
+ }
+
+ if (config.readEntry("SHARINGMODE", "simple") == "simple")
+ s_shareMode = Simple;
+ else
+ s_shareMode = Advanced;
+
+
+ s_sambaEnabled = config.readEntry("SAMBA", "yes") == "yes";
+ s_nfsEnabled = config.readEntry("NFS", "yes") == "yes";
+}
+
+KFileShare::ShareMode KFileShare::shareMode() {
+ if ( s_authorization == NotInitialized )
+ readConfig();
+
+ return s_shareMode;
+}
+
+bool KFileShare::sharingEnabled() {
+ if ( s_authorization == NotInitialized )
+ readConfig();
+
+ return s_sharingEnabled;
+}
+
+bool KFileShare::isRestricted() {
+ if ( s_authorization == NotInitialized )
+ readConfig();
+
+ return s_restricted;
+}
+
+TQString KFileShare::fileShareGroup() {
+ if ( s_authorization == NotInitialized )
+ readConfig();
+
+ return s_fileShareGroup;
+}
+
+
+bool KFileShare::sambaEnabled() {
+ if ( s_authorization == NotInitialized )
+ readConfig();
+
+ return s_sambaEnabled;
+}
+
+bool KFileShare::nfsEnabled() {
+ if ( s_authorization == NotInitialized )
+ readConfig();
+
+ return s_nfsEnabled;
+}
+
+
+void KFileShare::readShareList()
+{
+ KFileSharePrivate::self();
+ if ( !s_shareMap )
+ sdShareMap.setObject( s_shareMap, new TQMap<TQString,TQString> );
+ else
+ s_shareMap->clear();
+
+ // /usr/sbin on Mandrake, $PATH allows flexibility for other distributions
+ TQString exe = findExe( "filesharelist" );
+ if (exe.isEmpty()) {
+ s_authorization = ErrorNotFound;
+ return;
+ }
+ KProcIO proc;
+ proc << exe;
+ if ( !proc.start( TDEProcess::Block ) ) {
+ kdError() << "Can't run " << exe << endl;
+ s_authorization = ErrorNotFound;
+ return;
+ }
+
+ // Reading code shamelessly stolen from khostname.cpp ;)
+ TQString line;
+ TQString options;
+ TQString path;
+ int length;
+ TQRegExp rx_line("([^\\s]+)\\s+(.*)");
+ do {
+ length = proc.readln(line, true);
+ if ( length > 0 )
+ {
+ if ( line[length-1] != '/' )
+ line += '/';
+ if( rx_line.search( line ) != -1 ) {
+ options = rx_line.cap(1);
+ path = rx_line.cap(2);
+ (*s_shareMap)[path] = options;
+ }
+ kdDebug(7000) << "Shared dir:" << line << endl;
+ }
+ } while (length > -1);
+}
+
+
+int KFileShare::isDirectoryShared( const TQString& _path )
+{
+ int ret(0);
+
+ if ( ! s_shareMap )
+ readShareList();
+
+ TQString path( _path );
+ if ( path[path.length()-1] != '/' )
+ path += '/';
+ //return s_shareList && s_shareList->contains( path );
+ if( (*s_shareMap).contains(path) && !((*s_shareMap)[path].isEmpty()) ) {
+ ret+=1;
+ if( (*s_shareMap)[path].find("readwrite") != -1 )
+ ret+=2;
+ }
+
+ return ret;
+}
+
+KFileShare::Authorization KFileShare::authorization()
+{
+ // The app should do this on startup, but if it doesn't, let's do here.
+ if ( s_authorization == NotInitialized )
+ readConfig();
+ return s_authorization;
+}
+
+TQString KFileShare::findExe( const char* exeName )
+{
+ // /usr/sbin on Mandrake, $PATH allows flexibility for other distributions
+ TQString path = TQString::fromLocal8Bit(getenv("PATH")) + TQString::fromLatin1(":/usr/sbin");
+ TQString exe = KStandardDirs::findExe( exeName, path );
+ if (exe.isEmpty())
+ kdError() << exeName << " not found in " << path << endl;
+ return exe;
+}
+
+bool KFileShare::setShared( const TQString& path, bool shared )
+{
+ return SuSEsetShared( path, shared, false );
+}
+
+bool KFileShare::SuSEsetShared( const TQString& path, bool shared, bool rw )
+{
+ if (! KFileShare::sharingEnabled() ||
+ KFileShare::shareMode() == Advanced)
+ return false;
+
+ TQString exe = KFileShare::findExe( "fileshareset" );
+ if (exe.isEmpty())
+ return false;
+
+ // we want to share, so we kick it first - just to be sure
+ TDEProcess proc;
+ proc << exe;
+ proc << "--remove";
+ proc << path;
+ proc.start( TDEProcess::Block );
+ proc.clearArguments();
+
+ proc << exe;
+ if( rw )
+ proc << "--rw";
+ if ( shared )
+ proc << "--add";
+ else
+ proc << "--remove";
+ proc << path;
+ proc.start( TDEProcess::Block ); // should be ok, the perl script terminates fast
+ bool ok = proc.normalExit() && (proc.exitStatus() == 0);
+ kdDebug(7000) << "KFileSharePropsPlugin::setShared normalExit="
+ << proc.normalExit() << endl;
+ kdDebug(7000) << "KFileSharePropsPlugin::setShared exitStatus="
+ << proc.exitStatus() << endl;
+ if ( proc.normalExit() ) {
+ switch( proc.exitStatus() ) {
+ case 1:
+ // User is not authorized
+ break;
+ case 3:
+ // Called script with --add, but path was already shared before.
+ // Result is nevertheless what the client wanted, so
+ // this is alright.
+ ok = true;
+ break;
+ case 4:
+ // Invalid mount point
+ break;
+ case 5:
+ // Called script with --remove, but path was not shared before.
+ // Result is nevertheless what the client wanted, so
+ // this is alright.
+ ok = true;
+ break;
+ case 6:
+ // There is no export method
+ break;
+ case 7:
+ // file sharing is disabled
+ break;
+ case 8:
+ // advanced sharing is enabled
+ break;
+ case 255:
+ // Abitrary error
+ break;
+ }
+ }
+
+ return ok;
+}
+
+bool KFileShare::sambaActive()
+{
+ // rcsmb is not executable by users, try ourselves
+ int status = system( "/sbin/checkproc -p /var/run/samba/smbd.pid /usr/sbin/smbd" );
+ return status != -1 && WIFEXITED( status ) && WEXITSTATUS( status ) == 0;
+}
+
+bool KFileShare::nfsActive()
+{
+ // rcnfsserver is not executable by users, try ourselves
+ int status = system( "/sbin/checkproc /usr/sbin/rpc.mountd" );
+ if( status != -1 && WIFEXITED( status ) && WEXITSTATUS( status ) == 0 )
+ {
+ status = system( "/sbin/checkproc -n nfsd" );
+ if( status != -1 && WIFEXITED( status ) && WEXITSTATUS( status ) == 0 )
+ return true;
+ }
+ return false;
+}
+
+#include "tdefileshare.moc"
diff --git a/tdeio/tdeio/tdefileshare.h b/tdeio/tdeio/tdefileshare.h
new file mode 100644
index 000000000..e18749972
--- /dev/null
+++ b/tdeio/tdeio/tdefileshare.h
@@ -0,0 +1,165 @@
+/* This file is part of the KDE project
+ Copyright (c) 2001 David Faure <david@mandrakesoft.com>
+ Copyright (c) 2001 Laurent Montel <lmontel@mandrakesoft.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License version 2 as published by the Free Software Foundation.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef tdefileshare_h
+#define tdefileshare_h
+#include <tqobject.h>
+
+#include <tdelibs_export.h>
+
+class KDirWatch;
+
+/**
+ * @internal
+ * Do not use, ever.
+ */
+class KFileSharePrivate : public TQObject
+{
+ Q_OBJECT
+
+public:
+ KFileSharePrivate();
+ ~KFileSharePrivate();
+ KDirWatch* m_watchFile;
+ static KFileSharePrivate *self();
+ static KFileSharePrivate *_self;
+protected slots: // this is why this class needs to be in the .h
+ void slotFileChange(const TQString &);
+};
+
+/**
+ * Common functionality for the file sharing
+ * (communication with the backend)
+ * @since 3.1
+ */
+class TDEIO_EXPORT KFileShare
+{
+
+
+public:
+ /**
+ * Reads the file share configuration file
+ */
+ static void readConfig();
+
+ /**
+ * Reads the list of shared folders
+ */
+ static void readShareList();
+
+
+ /**
+ * Call this to know if a directory is currently shared
+ */
+ static int isDirectoryShared( const TQString& path );
+
+ enum Authorization { NotInitialized, ErrorNotFound, Authorized, UserNotAllowed };
+ /**
+ * Call this to know if the current user is authorized to share directories
+ */
+ static Authorization authorization();
+
+ static TQString findExe( const char* exeName );
+
+ /**
+ * Uses a suid perl script to share the given path
+ * with NFS and Samba
+ * @param path the path to share
+ * @param shared whether the path should be shared or not
+ * @returns whether the perl script was successful
+ */
+ static bool setShared( const TQString& path, bool shared );
+
+ /*
+ * SuSE only enhancement for now
+ */
+ static bool SuSEsetShared( const TQString& path, bool shared, bool ro );
+
+ /**
+ * The used share mode.
+ * Simple means that the simple sharing dialog is used and
+ * users can share only folders from there HOME folder.
+ * Advanced means that the advanced sharing dialog is used and
+ * users can share any folder.
+ */
+ enum ShareMode { Simple, Advanced };
+
+ /**
+ * Returns whether sharing is enabled
+ * If this is false, file sharing is disabled and
+ * nobody can share files.
+ */
+ static bool sharingEnabled();
+
+ /**
+ * Returns whether file sharing is restricted.
+ * If it is not restricted every user can shar files.
+ * If it is restricted only users in the configured
+ * file share group can share files.
+ */
+ static bool isRestricted();
+
+ /**
+ * Returns the group that is used for file sharing.
+ * That is, all users in that group are allowed to
+ * share files if file sharing is restricted.
+ */
+ static TQString fileShareGroup();
+
+ /**
+ * Returns the configured share mode
+ */
+ static ShareMode shareMode();
+
+ /**
+ * Returns whether Samba is enabled
+ */
+ static bool sambaEnabled();
+
+ /**
+ * Returns whether NFS is enabled
+ */
+ static bool nfsEnabled();
+
+ /**
+ * Returns whether Samba is active (service is running)
+ * @internal
+ */
+ static bool sambaActive();
+
+ /**
+ * Returns whether NFS is active (service is running)
+ * @internal
+ */
+ static bool nfsActive();
+
+private:
+ static Authorization s_authorization;
+// static TQStringList* s_shareList;
+ static TQMap<TQString,TQString>* s_shareMap;
+ static ShareMode s_shareMode;
+ static bool s_sambaEnabled;
+ static bool s_nfsEnabled;
+ static bool s_restricted;
+ static TQString s_fileShareGroup;
+ static bool s_sharingEnabled;
+
+};
+
+#endif
diff --git a/kio/kio/tdelficon.cpp b/tdeio/tdeio/tdelficon.cpp
index 49ceffd24..49ceffd24 100644
--- a/kio/kio/tdelficon.cpp
+++ b/tdeio/tdeio/tdelficon.cpp
diff --git a/kio/kio/tdelficon.h b/tdeio/tdeio/tdelficon.h
index 7a962bdaa..7a962bdaa 100644
--- a/kio/kio/tdelficon.h
+++ b/tdeio/tdeio/tdelficon.h
diff --git a/tdeio/tdeio/thumbcreator.h b/tdeio/tdeio/thumbcreator.h
new file mode 100644
index 000000000..756dd0cf9
--- /dev/null
+++ b/tdeio/tdeio/thumbcreator.h
@@ -0,0 +1,124 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 Malte Starostik <malte@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _THUMBCREATOR_H_
+#define _THUMBCREATOR_H_
+
+#include <tqstring.h>
+
+class TQString;
+class TQImage;
+/**
+ * This is the baseclass for "thumbnail-plugins" in KDE. Using the class
+ * TDEIO::PreviewJob allows you to generate small images (thumbnails)
+ * for any kind of file, where a "ThumbCreator" is available. Have a look
+ * at tdebase/tdeioslave/thumbnail/ for existing ThumbCreators.
+ *
+ * What you need to do to create and register a ThumbCreator:
+ * @li Inherit from this class and reimplement the create() method to
+ * generate a thumbnail for the given file-path.
+ * @li Provide a factory method in your implementation file to instantiate
+ * your plugin, e.g.:
+ * \code
+ * extern "C"
+ * {
+ * ThumbCreator *new_creator()
+ * {
+ * return new YourThumbCreator();
+ * }
+ * };
+ * \endcode
+ *
+ * Compile your ThumbCreator as a module. The contents of Makefile.am
+ * need to look like this:
+ * \code
+ * INCLUDES = $(all_includes)
+ * kde_module_LTLIBRARIES = yourthumbcreator.la
+ * yourthumbcreator_la_SOURCES = yourthumbcreator.cpp
+ * yourthumbcreator_la_LIBADD = $(LIB_KIO)
+ * yourthumbcreator_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
+ * kde_services_DATA = yourthumbcreator.desktop
+ * \endcode
+ *
+ * @li Create a file yourthumbcreator.desktop with the following contents:
+ * \code
+ * [Desktop Entry]
+ * Encoding=UTF-8
+ * Type=Service
+ * Name=Name of the type of files your ThumbCreator supports
+ * ServiceTypes=ThumbCreator
+ * MimeTypes=application/x-somemimetype
+ * CacheThumbnail=true
+ * X-TDE-Library=yourthumbcreator
+ * \endcode
+ *
+ * You can supply a comma-separated list of mimetypes to the MimeTypes entry,
+ * naming all mimetypes your ThumbCreator supports. You can also use simple
+ * wildcards, like (where you see [slash], put a /)
+ * \code
+ * text[slash]* or image[slash]*.
+ * \endcode
+ *
+ * If your plugin is rather inexpensive (e.g. like the text preview ThumbCreator),
+ * you can set CacheThumbnail=false to prevent your thumbnails from being cached
+ * on disk.
+ *
+ * @short Baseclass for thumbnail-generating plugins.
+ */
+class ThumbCreator
+{
+public:
+ /**
+ * The flags of this plugin.
+ * @see flags()
+ */
+ enum Flags { None = 0, DrawFrame = 1, BlendIcon = 2 };
+ virtual ~ThumbCreator() {}
+
+ /**
+ * Creates a thumbnail
+ * Note that the width and height parameters should not be used
+ * for scaling. Only plugins that create an image "from scratch",
+ * like the TextCreator should directly use the specified size.
+ * If the resulting preview is larger than width x height, it will be
+ * scaled down.
+ *
+ * @param path the (always local) file path to create a preview for
+ * @param width maximum width for the preview
+ * @param height maximum height for the preview
+ * @param img this image will contain the preview on success
+ *
+ * @return true if preview generation succeeded
+ */
+ virtual bool create(const TQString &path, int width, int height, TQImage &img) = 0;
+
+ /**
+ * The flags of this plugin:
+ * @li None nothing special
+ * @li DrawFrame a frame should be painted around the preview
+ * @li BlendIcon the mimetype icon should be blended over the preview
+ *
+ * @return flags for this plugin
+ */
+ virtual Flags flags() const { return None; }
+};
+
+typedef ThumbCreator *(*newCreator)();
+
+#endif
diff --git a/kio/kio/yacc.c b/tdeio/tdeio/yacc.c
index a6fa63428..a6fa63428 100644
--- a/kio/kio/yacc.c
+++ b/tdeio/tdeio/yacc.c
diff --git a/kio/kio/yacc.h b/tdeio/tdeio/yacc.h
index ca84fb025..ca84fb025 100644
--- a/kio/kio/yacc.h
+++ b/tdeio/tdeio/yacc.h
diff --git a/kio/kio/yacc.y b/tdeio/tdeio/yacc.y
index 1b86f4737..1b86f4737 100644
--- a/kio/kio/yacc.y
+++ b/tdeio/tdeio/yacc.y
diff --git a/tdeio/tdeioexec/CMakeLists.txt b/tdeio/tdeioexec/CMakeLists.txt
new file mode 100644
index 000000000..b0cdf0b52
--- /dev/null
+++ b/tdeio/tdeioexec/CMakeLists.txt
@@ -0,0 +1,42 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeui
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### tdeioexec ###################################
+
+set( target tdeioexec )
+
+set( ${target}_SRCS
+ main.cpp
+)
+
+tde_add_executable( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${BIN_INSTALL_DIR}
+)
+
+tde_install_symlink( ${target} ${BIN_INSTALL_DIR}/kfmexec )
diff --git a/tdeio/tdeioexec/Makefile.am b/tdeio/tdeioexec/Makefile.am
new file mode 100644
index 000000000..2879342ff
--- /dev/null
+++ b/tdeio/tdeioexec/Makefile.am
@@ -0,0 +1,19 @@
+AM_CPPFLAGS = $(all_includes)
+
+bin_PROGRAMS = tdeioexec
+
+tdeioexec_SOURCES = main.cpp
+tdeioexec_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+tdeioexec_LDADD = $(LIB_KIO)
+
+noinst_HEADERS = main.h
+METASOURCES = AUTO
+
+messages:
+ $(XGETTEXT) $(tdeioexec_SOURCES) -o $(podir)/tdeioexec.pot
+
+install-exec-local:
+ @rm -f $(DESTDIR)$(bindir)/kfmexec
+ @$(LN_S) tdeioexec $(DESTDIR)$(bindir)/kfmexec
+
+include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kio/kioexec/README b/tdeio/tdeioexec/README
index daaa38bdb..daaa38bdb 100644
--- a/kio/kioexec/README
+++ b/tdeio/tdeioexec/README
diff --git a/tdeio/tdeioexec/main.cpp b/tdeio/tdeioexec/main.cpp
new file mode 100644
index 000000000..9f7bd9faa
--- /dev/null
+++ b/tdeio/tdeioexec/main.cpp
@@ -0,0 +1,294 @@
+/* This file is part of the KDE project
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+ Copyright (C) 2000 David Faure <faure@kde.org>
+ Copyright (C) 2001 Waldo Bastian <bastian@kde.org>
+
+ 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; see the file COPYING. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <config.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+
+#include <tqfile.h>
+
+#include <kapplication.h>
+#include <kstandarddirs.h>
+#include <kdebug.h>
+#include <kmessagebox.h>
+#include <tdeio/job.h>
+#include <krun.h>
+#include <tdeio/netaccess.h>
+#include <kprocess.h>
+#include <kservice.h>
+#include <klocale.h>
+#include <kcmdlineargs.h>
+#include <kaboutdata.h>
+#include <kstartupinfo.h>
+#include <kshell.h>
+#include <kde_file.h>
+
+
+#include "main.h"
+
+
+static const char description[] =
+ I18N_NOOP("KIO Exec - Opens remote files, watches modifications, asks for upload");
+
+static KCmdLineOptions options[] =
+{
+ { "tempfiles", I18N_NOOP("Treat URLs as local files and delete them afterwards"), 0 },
+ { "suggestedfilename <file name>", I18N_NOOP("Suggested file name for the downloaded file"), 0 },
+ { "+command", I18N_NOOP("Command to execute"), 0 },
+ { "+[URLs]", I18N_NOOP("URL(s) or local file(s) used for 'command'"), 0 },
+ KCmdLineLastOption
+};
+
+
+int jobCounter = 0;
+
+TQPtrList<TDEIO::Job>* jobList = 0L;
+
+KIOExec::KIOExec()
+{
+ jobList = new TQPtrList<TDEIO::Job>;
+ jobList->setAutoDelete( false ); // jobs autodelete themselves
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+ if (args->count() < 1)
+ TDECmdLineArgs::usage(i18n("'command' expected.\n"));
+
+ tempfiles = args->isSet("tempfiles");
+ if ( args->isSet( "suggestedfilename" ) )
+ suggestedFileName = TQString::fromLocal8Bit( args->getOption( "suggestedfilename" ) );
+ expectedCounter = 0;
+ command = args->arg(0);
+ kdDebug() << "command=" << command << endl;
+
+ for ( int i = 1; i < args->count(); i++ )
+ {
+ KURL url = args->url(i);
+ // we need to map system:/ etc to make sure we get this right
+ url = TDEIO::NetAccess::mostLocalURL( url, 0 );
+
+ //kdDebug() << "url=" << url.url() << " filename=" << url.fileName() << endl;
+ // A local file, not an URL ?
+ // => It is not encoded and not shell escaped, too.
+ if ( url.isLocalFile() )
+ {
+ fileInfo file;
+ file.path = url.path();
+ file.url = url;
+ fileList.append(file);
+ }
+ // It is an URL
+ else
+ {
+ if ( !url.isValid() )
+ KMessageBox::error( 0L, i18n( "The URL %1\nis malformed" ).arg( url.url() ) );
+ else if ( tempfiles )
+ KMessageBox::error( 0L, i18n( "Remote URL %1\nnot allowed with --tempfiles switch" ).arg( url.url() ) );
+ else
+ // We must fetch the file
+ {
+ TQString fileName = TDEIO::encodeFileName( url.fileName() );
+ if ( !suggestedFileName.isEmpty() )
+ fileName = suggestedFileName;
+ // Build the destination filename, in ~/.trinity/cache-*/krun/
+ // Unlike KDE-1.1, we put the filename at the end so that the extension is kept
+ // (Some programs rely on it)
+ TQString tmp = TDEGlobal::dirs()->saveLocation( "cache", "krun/" ) +
+ TQString("%1.%2.%3").arg(getpid()).arg(jobCounter++).arg(fileName);
+ fileInfo file;
+ file.path = tmp;
+ file.url = url;
+ fileList.append(file);
+
+ expectedCounter++;
+ KURL dest;
+ dest.setPath( tmp );
+ kdDebug() << "Copying " << url.prettyURL() << " to " << dest << endl;
+ TDEIO::Job *job = TDEIO::file_copy( url, dest );
+ jobList->append( job );
+
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ), TQT_SLOT( slotResult( TDEIO::Job * ) ) );
+ }
+ }
+ }
+ args->clear();
+
+ if ( tempfiles ) {
+ // #113991
+ TQTimer::singleShot( 0, this, TQT_SLOT( slotRunApp() ) );
+ //slotRunApp(); // does not return
+ return;
+ }
+
+ counter = 0;
+ if ( counter == expectedCounter )
+ slotResult( 0L );
+}
+
+void KIOExec::slotResult( TDEIO::Job * job )
+{
+ if (job && job->error())
+ {
+ // That error dialog would be queued, i.e. not immediate...
+ //job->showErrorDialog();
+ if ( (job->error() != TDEIO::ERR_USER_CANCELED) )
+ KMessageBox::error( 0L, job->errorString() );
+
+ TQString path = static_cast<TDEIO::FileCopyJob*>(job)->destURL().path();
+
+ TQValueList<fileInfo>::Iterator it = fileList.begin();
+ for(;it != fileList.end(); ++it)
+ {
+ if ((*it).path == path)
+ break;
+ }
+
+ if ( it != fileList.end() )
+ fileList.remove( it );
+ else
+ kdDebug() << static_cast<TDEIO::FileCopyJob*>(job)->destURL().path() << " not found in list" << endl;
+ }
+
+ counter++;
+
+ if ( counter < expectedCounter )
+ return;
+
+ kdDebug() << "All files downloaded, will call slotRunApp shortly" << endl;
+ // We know we can run the app now - but let's finish the job properly first.
+ TQTimer::singleShot( 0, this, TQT_SLOT( slotRunApp() ) );
+
+ jobList->clear();
+}
+
+void KIOExec::slotRunApp()
+{
+ if ( fileList.isEmpty() ) {
+ kdDebug() << k_funcinfo << "No files downloaded -> exiting" << endl;
+ exit(1);
+ }
+
+ KService service("dummy", command, TQString::null);
+
+ KURL::List list;
+ // Store modification times
+ TQValueList<fileInfo>::Iterator it = fileList.begin();
+ for ( ; it != fileList.end() ; ++it )
+ {
+ KDE_struct_stat buff;
+ (*it).time = KDE_stat( TQFile::encodeName((*it).path), &buff ) ? 0 : buff.st_mtime;
+ KURL url;
+ url.setPath((*it).path);
+ list << url;
+ }
+
+ TQStringList params = KRun::processDesktopExec(service, list, false /*no shell*/);
+
+ kdDebug() << "EXEC " << KShell::joinArgs( params ) << endl;
+
+#ifdef Q_WS_X11
+ // propagate the startup indentification to the started process
+ KStartupInfoId id;
+ id.initId( kapp->startupId());
+ id.setupStartupEnv();
+#endif
+
+ TDEProcess proc;
+ proc << params;
+ proc.start( TDEProcess::Block );
+
+#ifdef Q_WS_X11
+ KStartupInfo::resetStartupEnv();
+#endif
+
+ kdDebug() << "EXEC done" << endl;
+
+ // Test whether one of the files changed
+ it = fileList.begin();
+ for( ;it != fileList.end(); ++it )
+ {
+ KDE_struct_stat buff;
+ TQString src = (*it).path;
+ KURL dest = (*it).url;
+ if ( (KDE_stat( TQFile::encodeName(src), &buff ) == 0) &&
+ ((*it).time != buff.st_mtime) )
+ {
+ if ( tempfiles )
+ {
+ if ( KMessageBox::questionYesNo( 0L,
+ i18n( "The supposedly temporary file\n%1\nhas been modified.\nDo you still want to delete it?" ).arg(dest.prettyURL()),
+ i18n( "File Changed" ), KStdGuiItem::del(), i18n("Do Not Delete") ) != KMessageBox::Yes )
+ continue; // don't delete the temp file
+ }
+ else if ( ! dest.isLocalFile() ) // no upload when it's already a local file
+ {
+ if ( KMessageBox::questionYesNo( 0L,
+ i18n( "The file\n%1\nhas been modified.\nDo you want to upload the changes?" ).arg(dest.prettyURL()),
+ i18n( "File Changed" ), i18n("Upload"), i18n("Do Not Upload") ) == KMessageBox::Yes )
+ {
+ kdDebug() << TQString(TQString("src='%1' dest='%2'").arg(src).arg(dest.url())).ascii() << endl;
+ // Do it the synchronous way.
+ if ( !TDEIO::NetAccess::upload( src, dest, 0 ) )
+ {
+ KMessageBox::error( 0L, TDEIO::NetAccess::lastErrorString() );
+ continue; // don't delete the temp file
+ }
+ }
+ }
+ }
+
+ if ( !dest.isLocalFile() || tempfiles ) {
+ // Wait for a reasonable time so that even if the application forks on startup (like OOo or amarok)
+ // it will have time to start up and read the file before it gets deleted. #130709.
+ kdDebug() << "sleeping..." << endl;
+ sleep(180); // 3 mn
+ kdDebug() << "about to delete " << src << endl;
+ unlink( TQFile::encodeName(src) );
+ }
+ }
+
+ //kapp->quit(); not efficient enough
+ exit(0);
+}
+
+int main( int argc, char **argv )
+{
+ TDEAboutData aboutData( "tdeioexec", I18N_NOOP("KIOExec"),
+ VERSION, description, TDEAboutData::License_GPL,
+ "(c) 1998-2000,2003 The KFM/Konqueror Developers");
+ aboutData.addAuthor("David Faure",0, "faure@kde.org");
+ aboutData.addAuthor("Stephan Kulow",0, "coolo@kde.org");
+ aboutData.addAuthor("Bernhard Rosenkraenzer",0, "bero@arklinux.org");
+ aboutData.addAuthor("Waldo Bastian",0, "bastian@kde.org");
+ aboutData.addAuthor("Oswald Buddenhagen",0, "ossi@kde.org");
+
+ TDECmdLineArgs::init( argc, argv, &aboutData );
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDEApplication app;
+
+ KIOExec exec;
+
+ kdDebug() << "Constructor returned..." << endl;
+ return app.exec();
+}
+
+#include "main.moc"
diff --git a/kio/kioexec/main.h b/tdeio/tdeioexec/main.h
index beb6a2297..beb6a2297 100644
--- a/kio/kioexec/main.h
+++ b/tdeio/tdeioexec/main.h
diff --git a/tdeio/tdeioslave.upd b/tdeio/tdeioslave.upd
new file mode 100644
index 000000000..cd4972741
--- /dev/null
+++ b/tdeio/tdeioslave.upd
@@ -0,0 +1,18 @@
+# Hello world
+Id=kde2.2/r1
+File=tdeioslaverc,kio_httprc
+Group=Cache Settings,
+Key=MaxCacheSize
+Key=MaxCacheAge
+Key=UseCache
+File=tdeioslaverc
+Group=Browser Settings/UserAgent,UserAgent
+AllKeys
+Id=kde2.2/r2
+File=tdeioslaverc,kio_httprc
+Group=UserAgent
+Script=useragent.pl,perl
+Id=kde2.2/r3
+File=tdeioslaverc
+Group=Proxy Settings
+Script=proxytype.pl,perl
diff --git a/tdeio/tests/CMakeLists.txt b/tdeio/tests/CMakeLists.txt
new file mode 100644
index 000000000..a9f6bd4ef
--- /dev/null
+++ b/tdeio/tests/CMakeLists.txt
@@ -0,0 +1,36 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### tdetradertest ###############################
+
+set( target tdetradertest )
+
+set( ${target}_SRCS
+ tdetradertest.cpp
+)
+
+tde_add_executable( ${target}
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${BIN_INSTALL_DIR}
+)
diff --git a/tdeio/tests/Makefile.am b/tdeio/tests/Makefile.am
new file mode 100644
index 000000000..138d0f0d2
--- /dev/null
+++ b/tdeio/tests/Makefile.am
@@ -0,0 +1,91 @@
+# This file is part of the KDE libraries
+# Copyright (C) 1997 David Faure <faure@kde.org>
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Library General Public
+# License as published by the Free Software Foundation; either
+# version 2 of the License, or (at your option) any later version.
+
+# This library 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
+# Library General Public License for more details.
+
+# You should have received a copy of the GNU Library General Public License
+# along with this library; see the file COPYING.LIB. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+# Boston, MA 02110-1301, USA.
+
+INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/tdeio $(all_includes)
+LDADD = $(LIB_KIO)
+AM_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+
+check_PROGRAMS = tdesycocatest getalltest kruntest ktartest kziptest\
+ tdeioslavetest kdirwatchtest kshredtest speed kurifiltertest \
+ kdefaultprogresstest kmimemagictest \
+ kfiltertest kiopassdlgtest kscantest kdirlistertest \
+ previewtest kionetrctest kdcopcheck metatest \
+ kmimefromext kpropsdlgtest kmfitest dataprotocoltest \
+ kprotocolinfotest tdesycocaupdatetest netaccesstest jobtest \
+ kurlcompletiontest kmimetypetest kacltest
+
+# Unfortunately some tests depend on the network settings, it seems
+#check: kurifiltertest
+# ./kurifiltertest
+check-local: kziptest
+ ./kziptest list $(srcdir)/wronglocalsizes.zip
+
+TESTS = kmimetypetest
+
+bin_PROGRAMS = tdetradertest
+
+METASOURCES = AUTO
+
+speed_SOURCES = speed.cpp
+tdeioslavetest_SOURCES = tdeioslavetest.cpp
+kshredtest_SOURCES = kshredtest.cpp
+kdefaultprogresstest_SOURCES = kdefaultprogresstest.cpp
+kionetrctest_SOURCES = kionetrctest.cpp
+kiopassdlgtest_SOURCES = kiopassdlgtest.cpp
+kurifiltertest_SOURCES = kurifiltertest.cpp
+tdesycocatest_SOURCES = tdesycocatest.cpp
+kdcopcheck_SOURCES = kdcopcheck.cpp
+getalltest_SOURCES = getalltest.cpp
+kruntest_SOURCES = kruntest.cpp
+kdirwatchtest_SOURCES = kdirwatchtest.cpp
+tdetradertest_SOURCES = tdetradertest.cpp
+kmimemagictest_SOURCES = kmimemagictest.cpp
+kfiltertest_SOURCES = kfiltertest.cpp
+kscantest_SOURCES = kscantest.cpp
+kdirlistertest_SOURCES = kdirlistertest.cpp
+previewtest_SOURCES = previewtest.cpp
+ktartest_SOURCES = ktartest.cpp
+kziptest_SOURCES = kziptest.cpp
+metatest_SOURCES = metatest.cpp
+kmimefromext_SOURCES = kmimefromext.cpp
+kpropsdlgtest_SOURCES = kpropsdlgtest.cpp
+kmfitest_SOURCES = kmfitest.cpp
+dataprotocoltest_SOURCES = dataprotocoltest.cpp
+kprotocolinfotest_SOURCES = kprotocolinfotest.cpp
+tdesycocaupdatetest_SOURCES = tdesycocaupdatetest.cpp
+netaccesstest_SOURCES = netaccesstest.cpp
+jobtest_SOURCES = jobtest.cpp
+kurlcompletiontest_SOURCES = kurlcompletiontest.cpp
+kmimetypetest_SOURCES = kmimetypetest.cpp
+kacltest_SOURCES = kacltest.cpp
+
+
+check_LTLIBRARIES = tdeunittest_kdirwatch.la
+tdeunittest_kdirwatch_la_SOURCES = kdirwatchunittest.cpp
+tdeunittest_kdirwatch_la_LIBADD = $(LIB_KUNITTEST) $(LIB_KIO)
+tdeunittest_kdirwatch_la_LDFLAGS = -module $(KDE_CHECK_PLUGIN)
+
+# tdefile meta stuff. Comment this in, if you want a small
+# metadata plugin test and "make install".
+#kde_module_LTLIBRARIES = dummymeta.la
+#dummymeta_la_SOURCES = dummymeta.cpp
+#dummymeta_la_LIBADD = $(LIB_KIO)
+#dummymeta_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
+
+#services_DATA = dummymeta.desktop
+#servicesdir = $(kde_servicesdir)
diff --git a/tdeio/tests/dataprotocoltest.cpp b/tdeio/tests/dataprotocoltest.cpp
new file mode 100644
index 000000000..e236a2d7c
--- /dev/null
+++ b/tdeio/tests/dataprotocoltest.cpp
@@ -0,0 +1,287 @@
+// testing the data tdeioslave
+// (C) 2002, 2003 Leo Savernik
+//
+// invoke "make dataprotocoltest" to generate the binary inside KDE CVS
+// invoke "make test" to generate the binary outside KDE CVS
+
+// fix the symptoms, not the illness ;-)
+#ifdef QT_NO_ASCII_CAST
+# undef QT_NO_ASCII_CAST
+#endif
+
+#ifdef DATAKIOSLAVE
+# undef DATAKIOSLAVE
+#endif
+#ifndef TESTKIO
+# define TESTKIO
+#endif
+
+#include <tdeio/global.h>
+
+#include <tqcstring.h>
+#include <tqstring.h>
+
+#include <iostream.h>
+
+class KURL;
+
+class TestSlave {
+public:
+ TestSlave() {
+ }
+ virtual ~TestSlave() {
+ }
+
+ virtual void get(const KURL &) = 0;
+ virtual void mimetype(const KURL &) = 0;
+
+ void mimeType(const TQString &type) {
+ testStrings("MIME Type: ",mime_type_expected,type);
+ }
+
+ void totalSize(TDEIO::filesize_t bytes) {
+// cout << "content size: " << bytes << " bytes" << endl;
+ }
+
+ void setMetaData(const TQString &key, const TQString &value) {
+// meta_data[key] = value;
+// cout << "§ " << key << " = " << value << endl;
+ TQString prefix = "Metadata[\""+key+"\"]: ";
+ TDEIO::MetaData::Iterator it = attributes_expected.find(key);
+ if (it != attributes_expected.end()) {
+ testStrings(prefix,it.data(),value);
+ // remove key from map
+ attributes_expected.remove(it);
+ } else {
+ cout << endl << prefix << " no such key expected";
+ total++;
+ }
+ }
+
+ void sendMetaData() {
+ // check here if attributes_expected contains any excess keys
+ TDEIO::MetaData::ConstIterator it = attributes_expected.begin();
+ TDEIO::MetaData::ConstIterator end = attributes_expected.end();
+ for (; it != end; ++it) {
+ cout << endl << "Metadata[\"" << it.key()
+ << "\"] was expected but not defined";
+ total++;
+ }
+ }
+
+ void data(const TQByteArray &a) {
+ if (a.isEmpty())
+/* cout << "<no more data>" << endl*/;
+ else {
+ testStrings("Content: ",content_expected,a);
+ }/*end if*/
+ }
+
+ void finished() {
+ }
+
+ void dispatchLoop() {
+ // dummy to make kde_main happy
+ }
+
+ // == stuff for regression testing
+private:
+ int testcaseno; // number of testcase
+ bool failure; // true if any testcase failed
+ TQMap<int,bool> failed_testcases;
+
+ // -- testcase related members
+ TQString mime_type_expected; // expected mime type
+ /** contains all attributes and values the testcase has to set */
+ TDEIO::MetaData attributes_expected;
+ /** contains the content as it is expected to be returned */
+ TQByteArray content_expected;
+ int passed; // # of passed tests
+ int total; // # of total tests
+
+ /**
+ * compares two strings, printing an error message if they don't match.
+ * @param prefix prefix string for output in case of mismatch
+ * @param templat template string
+ * @param s string to compare to template
+ * @param casesensitive true if case sensitive compare (currently not used)
+ */
+ void testStrings(const TQString &prefix, const TQString &templat,
+ const TQString &s, bool /*casesensitive*/ = true) {
+ if (templat == s)
+ passed++;
+ else {
+ cout << endl << prefix << "expected \"" << templat << "\", found \""
+ << s << "\"";
+ failure = true;
+ }/*end if*/
+ total++;
+ }
+
+public:
+ /** begins a testrun over all testcases */
+ void initTestrun() {
+ testcaseno = 0;
+ failure = false;
+ }
+
+ /** reuturns true if any testcase failed
+ */
+ bool hasFailedTestcases() const { return failure; }
+
+ /**
+ * sets up a new testcase
+ * @param name screen name for testcase
+ */
+ void beginTestcase(const char *name) {
+ passed = 0;
+ total = 0;
+ testcaseno++;
+ cout << "Testcase " << testcaseno << ": [" << name << "] ";
+ }
+
+ /**
+ * sets the mime type that this testcase is expected to return
+ */
+ void setExpectedMimeType(const TQString &mime_type) {
+ mime_type_expected = mime_type;
+ }
+
+ /**
+ * sets all attribute-value pairs the testcase must deliver.
+ */
+ void setExpectedAttributes(const TDEIO::MetaData &attres) {
+ attributes_expected = attres;
+ }
+
+ /**
+ * sets content as expected to be delivered by the testcase.
+ */
+ void setExpectedContent(const TQByteArray &content) {
+ content_expected = content;
+ }
+
+ /**
+ * closes testcase, printing out stats
+ */
+ void endTestcase() {
+ bool failed = passed < total;
+ if (failed) {
+ failure = true;
+ failed_testcases[testcaseno] = true;
+ cout << endl;
+ }
+ cout << "(" << passed << " of " << total << ") " << (failed ? "failed"
+ : "passed") << endl;
+ }
+
+ void endTestrun() {
+ if (failure) {
+ TQMap<int,bool>::ConstIterator it = failed_testcases.begin();
+ for (; it != failed_testcases.end(); ++it) {
+ cout << "Testcase " << it.key() << " failed" << endl;
+ }
+ }
+ }
+};
+
+#include "dataprotocol.cpp" // we need access to static data & functions
+
+// == general functionality
+const struct {
+const char * const name;
+const char * const exp_mime_type; // 0 means "text/plain"
+const struct {
+ const char * const key;
+ const char * const value;
+} exp_attrs[10]; // ended with a key==0, value==0 pair
+const char * const exp_content;
+const char * const url;
+} testcases[] = {
+ // -----------------------------------------------------------------
+ { "escape resolving", 0, {}, "blah blah", "data:,blah%20blah" },
+ // --------------------
+ { "mime type, escape resolving", "text/html", {},
+ "<div style=\"border:thin orange solid;padding:1ex;background-color:"
+ "yellow;color:black\">Rich <b>text</b></div>",
+ "data:text/html,<div%20style=\"border:thin%20orange%20solid;"
+ "padding:1ex;background-color:yellow;color:black\">Rich%20<b>text</b>"
+ "</div>" },
+ // -------------------- whitespace test I
+ { "whitespace test I", "text/css", {
+ { "charset", "iso-8859-15" }, { 0,0 } },
+ " body { color: yellow; background:darkblue; font-weight:bold }",
+ "data:text/css ; charset = iso-8859-15 , body { color: yellow; "
+ "background:darkblue; font-weight:bold }" },
+ // -------------------- out of spec argument order, base64 decoding,
+ // whitespace test II
+ { "out of spec argument order, base64 decoding, whitespace test II",
+ 0, {
+ { "charset", "iso-8859-1" }, { 0,0 } },
+ "paaaaaaaasd!!\n",
+ "data: ; base64 ; charset = \"iso-8859-1\" ,cGFhYWFhYWFhc2QhIQo=" },
+ // -------------------- arbitrary keys, reserved names as keys,
+ // whitespace test III
+ { "arbitrary keys, reserved names as keys, whitespace test III", 0, {
+ { "base64", "nospace" }, { "key", "onespaceinner" },
+ { "key2", "onespaceouter" }, { "charset", "utf8" },
+ { "<<empty>>", "" }, { 0,0 } },
+ "Die, Allied Schweinehund (C) 1990 Wolfenstein 3D",
+ "data: ;base64=nospace;key = onespaceinner; key2=onespaceouter ;"
+ " charset = utf8 ; <<empty>>= ,Die, Allied Schweinehund "
+ "(C) 1990 Wolfenstein 3D" },
+ // -------------------- string literal with escaped chars, testing
+ // delimiters within string
+ { "string literal with escaped chars, testing delimiters within "
+ "string", 0, {
+ { "fortune-cookie", "Master Leep say: \"Rabbit is humble, "
+ "Rabbit is gentle; follow the Rabbit\"" }, { 0,0 } },
+ "(C) 1997 Shadow Warrior ;-)",
+ "data:;fortune-cookie=\"Master Leep say: \\\"Rabbit is humble, "
+ "Rabbit is gentle; follow the Rabbit\\\"\",(C) 1997 Shadow Warrior "
+ ";-)" },
+};
+
+#if 0
+// == charset tests
+ // -------------------- string
+const QChar
+const TQChar * const charset_urls[] = {
+#endif
+
+int main(int /*argc*/,char* /*argv*/[]) {
+ DataProtocol kio_data;
+
+ kio_data.initTestrun();
+ for (uint i = 0; i < sizeof testcases/sizeof testcases[0]; i++) {
+ kio_data.beginTestcase(testcases[i].name);
+ kio_data.setExpectedMimeType(testcases[i].exp_mime_type != 0
+ ? testcases[i].exp_mime_type : "text/plain");
+
+ bool has_charset = false;
+ MetaData exp_attrs;
+ if (testcases[i].exp_attrs != 0) {
+ for (uint j = 0; testcases[i].exp_attrs[j].key != 0; j++) {
+ exp_attrs[testcases[i].exp_attrs[j].key] = testcases[i].exp_attrs[j].value;
+ if (strcmp(testcases[i].exp_attrs[j].key,"charset") == 0)
+ has_charset = true;
+ }/*next j*/
+ }
+ if (!has_charset) exp_attrs["charset"] = "us-ascii";
+ kio_data.setExpectedAttributes(exp_attrs);
+
+ TQByteArray exp_content;
+ uint exp_content_len = strlen(testcases[i].exp_content);
+ exp_content.setRawData(testcases[i].exp_content,exp_content_len);
+ kio_data.setExpectedContent(exp_content);
+
+ kio_data.get(testcases[i].url);
+
+ kio_data.endTestcase();
+ exp_content.resetRawData(testcases[i].exp_content,exp_content_len);
+ }/*next i*/
+ kio_data.endTestrun();
+
+ return kio_data.hasFailedTestcases() ? 1 : 0;
+}
+
diff --git a/kio/tests/dummymeta.cpp b/tdeio/tests/dummymeta.cpp
index 938b4d00b..938b4d00b 100644
--- a/kio/tests/dummymeta.cpp
+++ b/tdeio/tests/dummymeta.cpp
diff --git a/kio/tests/dummymeta.desktop b/tdeio/tests/dummymeta.desktop
index 6d2748c82..6d2748c82 100644
--- a/kio/tests/dummymeta.desktop
+++ b/tdeio/tests/dummymeta.desktop
diff --git a/tdeio/tests/dummymeta.h b/tdeio/tests/dummymeta.h
new file mode 100644
index 000000000..4cefcc01d
--- /dev/null
+++ b/tdeio/tests/dummymeta.h
@@ -0,0 +1,20 @@
+#ifndef DUMMYMETA_H
+#define DUMMYMETA_H
+
+#include <tdefilemetainfo.h>
+
+class KFileMetaInfo;
+
+class DummyMeta : public KFilePlugin
+{
+ Q_OBJECT
+
+public:
+ DummyMeta( TQObject *parent, const char *name, const TQStringList &args );
+ ~DummyMeta() {}
+
+ virtual bool readInfo( KFileMetaInfo::Internal& info );
+
+};
+
+#endif
diff --git a/kio/tests/getalltest.cpp b/tdeio/tests/getalltest.cpp
index 07d8723ed..07d8723ed 100644
--- a/kio/tests/getalltest.cpp
+++ b/tdeio/tests/getalltest.cpp
diff --git a/tdeio/tests/jobtest.cpp b/tdeio/tests/jobtest.cpp
new file mode 100644
index 000000000..12f106cd2
--- /dev/null
+++ b/tdeio/tests/jobtest.cpp
@@ -0,0 +1,613 @@
+/* This file is part of the KDE project
+ Copyright (C) 2004-2006 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "jobtest.h"
+
+#include <config.h>
+
+#include <kurl.h>
+#include <kapplication.h>
+#include <klargefile.h>
+#include <tdeio/netaccess.h>
+#include <kdebug.h>
+#include <kcmdlineargs.h>
+#include <kprotocolinfo.h>
+
+#include <tqfileinfo.h>
+#include <tqeventloop.h>
+#include <tqdir.h>
+#include <tqfileinfo.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <time.h>
+#include <utime.h>
+
+// The code comes partly from tdebase/tdeioslave/trash/testtrash.cpp
+
+static bool check(const TQString& txt, TQString a, TQString b)
+{
+ if (a.isEmpty())
+ a = TQString::null;
+ if (b.isEmpty())
+ b = TQString::null;
+ if (a == b) {
+ kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
+ }
+ else {
+ kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
+ exit(1);
+ }
+ return true;
+}
+
+int main(int argc, char *argv[])
+{
+ TDEApplication::disableAutoDcopRegistration();
+ TDECmdLineArgs::init(argc,argv,"jobtest", 0, 0, 0, 0);
+ TDEApplication app;
+
+ JobTest test;
+ test.setup();
+ test.runAll();
+ test.cleanup();
+ kdDebug() << "All tests OK." << endl;
+ return 0; // success. The exit(1) in check() is what happens in case of failure.
+}
+
+TQString JobTest::homeTmpDir() const
+{
+ return TQDir::homeDirPath() + "/.trinity/jobtest/";
+}
+
+TQString JobTest::otherTmpDir() const
+{
+ // This one needs to be on another partition
+ return "/tmp/jobtest/";
+}
+
+KURL JobTest::systemTmpDir() const
+{
+ return "system:/home/.trinity/jobtest-system/";
+}
+
+TQString JobTest::realSystemPath() const
+{
+ return TQDir::homeDirPath() + "/.trinity/jobtest-system/";
+}
+
+void JobTest::setup()
+{
+ // Start with a clean base dir
+ cleanup();
+ TQDir dir; // TT: why not a static method?
+ bool ok = dir.mkdir( homeTmpDir() );
+ if ( !ok )
+ kdFatal() << "Couldn't create " << homeTmpDir() << endl;
+ ok = dir.mkdir( otherTmpDir() );
+ if ( !ok )
+ kdFatal() << "Couldn't create " << otherTmpDir() << endl;
+ ok = dir.mkdir( realSystemPath() );
+ if ( !ok )
+ kdFatal() << "Couldn't create " << realSystemPath() << endl;
+}
+
+void JobTest::runAll()
+{
+ get();
+ copyFileToSamePartition();
+ copyDirectoryToSamePartition();
+ copyDirectoryToExistingDirectory();
+ copyFileToOtherPartition();
+ copyDirectoryToOtherPartition();
+ listRecursive();
+ moveFileToSamePartition();
+ moveDirectoryToSamePartition();
+ moveFileToOtherPartition();
+ moveSymlinkToOtherPartition();
+ moveDirectoryToOtherPartition();
+ moveFileNoPermissions();
+ moveDirectoryNoPermissions();
+
+ copyFileToSystem();
+}
+
+void JobTest::cleanup()
+{
+ TDEIO::NetAccess::del( homeTmpDir(), 0 );
+ TDEIO::NetAccess::del( otherTmpDir(), 0 );
+ TDEIO::NetAccess::del( systemTmpDir(), 0 );
+}
+
+static void setTimeStamp( const TQString& path )
+{
+#ifdef Q_OS_UNIX
+ // Put timestamp in the past so that we can check that the
+ // copy actually preserves it.
+ struct timeval tp;
+ gettimeofday( &tp, 0 );
+ struct utimbuf utbuf;
+ utbuf.actime = tp.tv_sec - 30; // 30 seconds ago
+ utbuf.modtime = tp.tv_sec - 60; // 60 second ago
+ utime( TQFile::encodeName( path ), &utbuf );
+ tqDebug( "Time changed for %s", path.latin1() );
+#endif
+}
+
+static void createTestFile( const TQString& path )
+{
+ TQFile f( path );
+ if ( !f.open( IO_WriteOnly ) )
+ kdFatal() << "Can't create " << path << endl;
+ f.tqwriteBlock( "Hello world", 11 );
+ f.close();
+ setTimeStamp( path );
+}
+
+static void createTestSymlink( const TQString& path )
+{
+ // Create symlink if it doesn't exist yet
+ KDE_struct_stat buf;
+ if ( KDE_lstat( TQFile::encodeName( path ), &buf ) != 0 ) {
+ bool ok = symlink( "/IDontExist", TQFile::encodeName( path ) ) == 0; // broken symlink
+ if ( !ok )
+ kdFatal() << "couldn't create symlink: " << strerror( errno ) << endl;
+ }
+}
+
+static void createTestDirectory( const TQString& path )
+{
+ TQDir dir;
+ bool ok = dir.mkdir( path );
+ if ( !ok && !dir.exists() )
+ kdFatal() << "couldn't create " << path << endl;
+ createTestFile( path + "/testfile" );
+ createTestSymlink( path + "/testlink" );
+ setTimeStamp( path );
+}
+
+void JobTest::get()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString filePath = homeTmpDir() + "fileFromHome";
+ createTestFile( filePath );
+ KURL u; u.setPath( filePath );
+ m_result = -1;
+ TDEIO::StoredTransferJob* job = TDEIO::storedGet( u );
+ connect( job, TQT_SIGNAL( result( TDEIO::Job* ) ),
+ this, TQT_SLOT( slotGetResult( TDEIO::Job* ) ) );
+ kapp->eventLoop()->enterLoop();
+ assert( m_result == 0 ); // no error
+ assert( m_data.size() == 11 );
+ assert( TQCString( m_data ) == "Hello world" );
+}
+
+void JobTest::slotGetResult( TDEIO::Job* job )
+{
+ m_result = job->error();
+ m_data = static_cast<TDEIO::StoredTransferJob *>(job)->data();
+ kapp->eventLoop()->exitLoop();
+}
+
+////
+
+void JobTest::copyLocalFile( const TQString& src, const TQString& dest )
+{
+ KURL u;
+ u.setPath( src );
+ KURL d;
+ d.setPath( dest );
+
+ // copy the file with file_copy
+ bool ok = TDEIO::NetAccess::file_copy( u, d );
+ assert( ok );
+ assert( TQFile::exists( dest ) );
+ assert( TQFile::exists( src ) ); // still there
+
+ {
+ // check that the timestamp is the same (#24443)
+ // Note: this only works because of copy() in kio_file.
+ // The datapump solution ignores mtime, the app has to call FileCopyJob::setModificationTime()
+ TQFileInfo srcInfo( src );
+ TQFileInfo destInfo( dest );
+ assert( srcInfo.lastModified() == destInfo.lastModified() );
+ }
+
+ // cleanup and retry with TDEIO::copy()
+ TQFile::remove( dest );
+ ok = TDEIO::NetAccess::dircopy( u, d, 0 );
+ assert( ok );
+ assert( TQFile::exists( dest ) );
+ assert( TQFile::exists( src ) ); // still there
+ {
+ // check that the timestamp is the same (#24443)
+ TQFileInfo srcInfo( src );
+ TQFileInfo destInfo( dest );
+ assert( srcInfo.lastModified() == destInfo.lastModified() );
+ }
+}
+
+void JobTest::copyLocalDirectory( const TQString& src, const TQString& _dest, int flags )
+{
+ assert( TQFileInfo( src ).isDir() );
+ assert( TQFileInfo( src + "/testfile" ).isFile() );
+ KURL u;
+ u.setPath( src );
+ TQString dest( _dest );
+ KURL d;
+ d.setPath( dest );
+ if ( flags & AlreadyExists )
+ assert( TQFile::exists( dest ) );
+ else
+ assert( !TQFile::exists( dest ) );
+
+ bool ok = TDEIO::NetAccess::dircopy( u, d, 0 );
+ assert( ok );
+
+ if ( flags & AlreadyExists ) {
+ dest += "/" + u.fileName();
+ //kdDebug() << "Expecting dest=" << dest << endl;
+ }
+
+ assert( TQFile::exists( dest ) );
+ assert( TQFileInfo( dest ).isDir() );
+ assert( TQFileInfo( dest + "/testfile" ).isFile() );
+ assert( TQFile::exists( src ) ); // still there
+ {
+ // check that the timestamp is the same (#24443)
+ TQFileInfo srcInfo( src );
+ TQFileInfo destInfo( dest );
+ assert( srcInfo.lastModified() == destInfo.lastModified() );
+ }
+}
+
+void JobTest::copyFileToSamePartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString filePath = homeTmpDir() + "fileFromHome";
+ const TQString dest = homeTmpDir() + "fileFromHome_copied";
+ createTestFile( filePath );
+ copyLocalFile( filePath, dest );
+}
+
+void JobTest::copyDirectoryToSamePartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString src = homeTmpDir() + "dirFromHome";
+ const TQString dest = homeTmpDir() + "dirFromHome_copied";
+ createTestDirectory( src );
+ copyLocalDirectory( src, dest );
+}
+
+void JobTest::copyDirectoryToExistingDirectory()
+{
+ kdDebug() << k_funcinfo << endl;
+ // just the same as copyDirectoryToSamePartition, but it means that
+ // this time dest exists.
+ const TQString src = homeTmpDir() + "dirFromHome";
+ const TQString dest = homeTmpDir() + "dirFromHome_copied";
+ createTestDirectory( src );
+ copyLocalDirectory( src, dest, AlreadyExists );
+}
+
+void JobTest::copyFileToOtherPartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString filePath = homeTmpDir() + "fileFromHome";
+ const TQString dest = otherTmpDir() + "fileFromHome_copied";
+ createTestFile( filePath );
+ copyLocalFile( filePath, dest );
+}
+
+void JobTest::copyDirectoryToOtherPartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString src = homeTmpDir() + "dirFromHome";
+ const TQString dest = otherTmpDir() + "dirFromHome_copied";
+ // src is already created by copyDirectoryToSamePartition()
+ // so this is just in case someone calls this method only
+ if ( !TQFile::exists( src ) )
+ createTestDirectory( src );
+ copyLocalDirectory( src, dest );
+}
+
+void JobTest::moveLocalFile( const TQString& src, const TQString& dest )
+{
+ assert( TQFile::exists( src ) );
+ KURL u;
+ u.setPath( src );
+ KURL d;
+ d.setPath( dest );
+
+ // move the file with file_move
+ bool ok = TDEIO::NetAccess::file_move( u, d );
+ assert( ok );
+ assert( TQFile::exists( dest ) );
+ assert( !TQFile::exists( src ) ); // not there anymore
+
+ // move it back with TDEIO::move()
+ ok = TDEIO::NetAccess::move( d, u, 0 );
+ assert( ok );
+ assert( !TQFile::exists( dest ) );
+ assert( TQFile::exists( src ) ); // it's back
+}
+
+static void moveLocalSymlink( const TQString& src, const TQString& dest )
+{
+ KDE_struct_stat buf;
+ assert ( KDE_lstat( TQFile::encodeName( src ), &buf ) == 0 );
+ KURL u;
+ u.setPath( src );
+ KURL d;
+ d.setPath( dest );
+
+ // move the symlink with move, NOT with file_move
+ bool ok = TDEIO::NetAccess::move( u, d );
+ if ( !ok )
+ kdWarning() << TDEIO::NetAccess::lastError() << endl;
+ assert( ok );
+ assert ( KDE_lstat( TQFile::encodeName( dest ), &buf ) == 0 );
+ assert( !TQFile::exists( src ) ); // not there anymore
+
+ // move it back with TDEIO::move()
+ ok = TDEIO::NetAccess::move( d, u, 0 );
+ assert( ok );
+ assert ( KDE_lstat( TQFile::encodeName( dest ), &buf ) != 0 ); // doesn't exist anymore
+ assert ( KDE_lstat( TQFile::encodeName( src ), &buf ) == 0 ); // it's back
+}
+
+void JobTest::moveLocalDirectory( const TQString& src, const TQString& dest )
+{
+ assert( TQFile::exists( src ) );
+ assert( TQFileInfo( src ).isDir() );
+ assert( TQFileInfo( src + "/testfile" ).isFile() );
+ assert( TQFileInfo( src + "/testlink" ).isSymLink() );
+ KURL u;
+ u.setPath( src );
+ KURL d;
+ d.setPath( dest );
+
+ bool ok = TDEIO::NetAccess::move( u, d, 0 );
+ assert( ok );
+ assert( TQFile::exists( dest ) );
+ assert( TQFileInfo( dest ).isDir() );
+ assert( TQFileInfo( dest + "/testfile" ).isFile() );
+ assert( !TQFile::exists( src ) ); // not there anymore
+
+ assert( TQFileInfo( dest + "/testlink" ).isSymLink() );
+}
+
+void JobTest::moveFileToSamePartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString filePath = homeTmpDir() + "fileFromHome";
+ const TQString dest = homeTmpDir() + "fileFromHome_moved";
+ createTestFile( filePath );
+ moveLocalFile( filePath, dest );
+}
+
+void JobTest::moveDirectoryToSamePartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString src = homeTmpDir() + "dirFromHome";
+ const TQString dest = homeTmpDir() + "dirFromHome_moved";
+ createTestDirectory( src );
+ moveLocalDirectory( src, dest );
+}
+
+void JobTest::moveFileToOtherPartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString filePath = homeTmpDir() + "fileFromHome";
+ const TQString dest = otherTmpDir() + "fileFromHome_moved";
+ createTestFile( filePath );
+ moveLocalFile( filePath, dest );
+}
+
+void JobTest::moveSymlinkToOtherPartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString filePath = homeTmpDir() + "testlink";
+ const TQString dest = otherTmpDir() + "testlink_moved";
+ createTestSymlink( filePath );
+ moveLocalSymlink( filePath, dest );
+}
+
+void JobTest::moveDirectoryToOtherPartition()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString src = homeTmpDir() + "dirFromHome";
+ const TQString dest = otherTmpDir() + "dirFromHome_moved";
+ createTestDirectory( src );
+ moveLocalDirectory( src, dest );
+}
+
+void JobTest::moveFileNoPermissions()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString src = "/etc/passwd";
+ const TQString dest = homeTmpDir() + "passwd";
+ assert( TQFile::exists( src ) );
+ assert( TQFileInfo( src ).isFile() );
+ KURL u;
+ u.setPath( src );
+ KURL d;
+ d.setPath( dest );
+
+ TDEIO::CopyJob* job = TDEIO::move( u, d, 0 );
+ job->setInteractive( false ); // no skip dialog, thanks
+ TQMap<TQString, TQString> metaData;
+ bool ok = TDEIO::NetAccess::synchronousRun( job, 0, 0, 0, &metaData );
+ assert( !ok );
+ assert( TDEIO::NetAccess::lastError() == TDEIO::ERR_ACCESS_DENIED );
+ // OK this is fishy. Just like mv(1), KIO's behavior depends on whether
+ // a direct rename(2) was used, or a full copy+del. In the first case
+ // there is no destination file created, but in the second case the
+ // destination file remains.
+ // In fact we assume /home is a separate partition, in this test, so:
+ assert( TQFile::exists( dest ) );
+ assert( TQFile::exists( src ) );
+}
+
+void JobTest::moveDirectoryNoPermissions()
+{
+ kdDebug() << k_funcinfo << endl;
+ const TQString src = "/etc/init.d";
+ const TQString dest = homeTmpDir() + "init.d";
+ assert( TQFile::exists( src ) );
+ assert( TQFileInfo( src ).isDir() );
+ KURL u;
+ u.setPath( src );
+ KURL d;
+ d.setPath( dest );
+
+ TDEIO::CopyJob* job = TDEIO::move( u, d, 0 );
+ job->setInteractive( false ); // no skip dialog, thanks
+ TQMap<TQString, TQString> metaData;
+ bool ok = TDEIO::NetAccess::synchronousRun( job, 0, 0, 0, &metaData );
+ assert( !ok );
+ assert( TDEIO::NetAccess::lastError() == TDEIO::ERR_ACCESS_DENIED );
+ assert( TQFile::exists( dest ) ); // see moveFileNoPermissions
+ assert( TQFile::exists( src ) );
+}
+
+void JobTest::listRecursive()
+{
+ const TQString src = homeTmpDir();
+ KURL u;
+ u.setPath( src );
+ TDEIO::ListJob* job = TDEIO::listRecursive( u );
+ connect( job, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList& ) ),
+ TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& ) ) );
+ bool ok = TDEIO::NetAccess::synchronousRun( job, 0 );
+ assert( ok );
+ m_names.sort();
+ check( "listRecursive", m_names.join( "," ), ".,..,"
+ "dirFromHome,dirFromHome/testfile,dirFromHome/testlink,dirFromHome_copied,"
+ "dirFromHome_copied/dirFromHome,dirFromHome_copied/dirFromHome/testfile,dirFromHome_copied/dirFromHome/testlink,"
+ "dirFromHome_copied/testfile,dirFromHome_copied/testlink,"
+ "fileFromHome,fileFromHome_copied" );
+}
+
+void JobTest::slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& lst )
+{
+ for( TDEIO::UDSEntryList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) {
+ TDEIO::UDSEntry::ConstIterator it2 = (*it).begin();
+ TQString displayName;
+ KURL url;
+ for( ; it2 != (*it).end(); it2++ ) {
+ switch ((*it2).m_uds) {
+ case TDEIO::UDS_NAME:
+ displayName = (*it2).m_str;
+ break;
+ case TDEIO::UDS_URL:
+ url = (*it2).m_str;
+ break;
+ }
+ }
+ m_names.append( displayName );
+ }
+}
+
+void JobTest::copyFileToSystem()
+{
+ if ( !KProtocolInfo::isKnownProtocol( TQString::fromLatin1( "system" ) ) ) {
+ kdDebug() << k_funcinfo << "no kio_system, skipping test" << endl;
+ return;
+ }
+
+ // First test with support for UDS_LOCAL_PATH
+ copyFileToSystem( true );
+
+ TQString dest = realSystemPath() + "fileFromHome_copied";
+ TQFile::remove( dest );
+
+ // Then disable support for UDS_LOCAL_PATH, i.e. test what would
+ // happen for ftp, smb, http etc.
+ copyFileToSystem( false );
+}
+
+void JobTest::copyFileToSystem( bool resolve_local_urls )
+{
+ kdDebug() << k_funcinfo << resolve_local_urls << endl;
+ extern TDEIO_EXPORT bool kio_resolve_local_urls;
+ kio_resolve_local_urls = resolve_local_urls;
+
+ const TQString src = homeTmpDir() + "fileFromHome";
+ createTestFile( src );
+ KURL u;
+ u.setPath( src );
+ KURL d = systemTmpDir();
+ d.addPath( "fileFromHome_copied" );
+
+ kdDebug() << "copying " << u << " to " << d << endl;
+
+ // copy the file with file_copy
+ TDEIO::FileCopyJob* job = TDEIO::file_copy( u, d );
+ connect( job, TQT_SIGNAL(mimetype(TDEIO::Job*,const TQString&)),
+ this, TQT_SLOT(slotMimetype(TDEIO::Job*,const TQString&)) );
+ bool ok = TDEIO::NetAccess::synchronousRun( job, 0 );
+ assert( ok );
+
+ TQString dest = realSystemPath() + "fileFromHome_copied";
+
+ assert( TQFile::exists( dest ) );
+ assert( TQFile::exists( src ) ); // still there
+
+ {
+ // do NOT check that the timestamp is the same.
+ // It can't work with file_copy when it uses the datapump,
+ // unless we use setModificationTime in the app code.
+ }
+
+ // Check mimetype
+ kdDebug() << m_mimetype << endl;
+ // There's no mimemagic determination in kio_file in trinity. Fixing this for kde4...
+ assert( m_mimetype == "application/octet-stream" );
+ //assert( m_mimetype == "text/plain" );
+
+ // cleanup and retry with TDEIO::copy()
+ TQFile::remove( dest );
+ ok = TDEIO::NetAccess::dircopy( u, d, 0 );
+ assert( ok );
+ assert( TQFile::exists( dest ) );
+ assert( TQFile::exists( src ) ); // still there
+ {
+ // check that the timestamp is the same (#79937)
+ TQFileInfo srcInfo( src );
+ TQFileInfo destInfo( dest );
+ assert( srcInfo.lastModified() == destInfo.lastModified() );
+ }
+
+ // restore normal behavior
+ kio_resolve_local_urls = true;
+}
+
+void JobTest::slotMimetype(TDEIO::Job* job, const TQString& type)
+{
+ assert( job );
+ m_mimetype = type;
+}
+
+#include "jobtest.moc"
diff --git a/tdeio/tests/jobtest.h b/tdeio/tests/jobtest.h
new file mode 100644
index 000000000..aeaceff0d
--- /dev/null
+++ b/tdeio/tests/jobtest.h
@@ -0,0 +1,79 @@
+/* This file is part of the KDE project
+ Copyright (C) 2004 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef JOBTEST_H
+#define JOBTEST_H
+
+#include <tqstring.h>
+#include <tqobject.h>
+#include <tdeio/job.h>
+
+class JobTest : public TQObject
+{
+ Q_OBJECT
+
+public:
+ JobTest() {}
+ void setup();
+ void runAll();
+ void cleanup();
+
+ // Local tests (kio_file only)
+ void get();
+ void copyFileToSamePartition();
+ void copyDirectoryToSamePartition();
+ void copyDirectoryToExistingDirectory();
+ void copyFileToOtherPartition();
+ void copyDirectoryToOtherPartition();
+ void listRecursive();
+ void moveFileToSamePartition();
+ void moveDirectoryToSamePartition();
+ void moveFileToOtherPartition();
+ void moveSymlinkToOtherPartition();
+ void moveDirectoryToOtherPartition();
+ void moveFileNoPermissions();
+ void moveDirectoryNoPermissions();
+
+ // Remote tests
+ void copyFileToSystem();
+
+private slots:
+ void slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList& lst );
+ void slotGetResult( TDEIO::Job* );
+ void slotMimetype(TDEIO::Job*,const TQString&);
+
+private:
+ TQString homeTmpDir() const;
+ TQString otherTmpDir() const;
+ TQString realSystemPath() const;
+ KURL systemTmpDir() const;
+ enum { AlreadyExists = 1 };
+ void copyLocalFile( const TQString& src, const TQString& dest );
+ void copyLocalDirectory( const TQString& src, const TQString& dest, int flags = 0 );
+ void moveLocalFile( const TQString& src, const TQString& dest );
+ void moveLocalDirectory( const TQString& src, const TQString& dest );
+ void copyFileToSystem( bool resolve_local_urls );
+
+ int m_result;
+ TQByteArray m_data;
+ TQStringList m_names;
+ TQString m_mimetype;
+};
+
+#endif
diff --git a/tdeio/tests/kacltest.cpp b/tdeio/tests/kacltest.cpp
new file mode 100644
index 000000000..b55aedce8
--- /dev/null
+++ b/tdeio/tests/kacltest.cpp
@@ -0,0 +1,309 @@
+/* This file is part of the KDE project
+ Copyright (C) 2005 Till Adam <adam@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "kacltest.h"
+
+#include <config.h>
+
+#include <kacl.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kcmdlineargs.h>
+
+#include <tqfileinfo.h>
+#include <tqeventloop.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <tqdir.h>
+
+// The code comes partly from tdebase/tdeioslave/trash/testtrash.cpp
+
+static bool check(const TQString& txt, TQString a, TQString b)
+{
+ if (a.isEmpty())
+ a = TQString::null;
+ if (b.isEmpty())
+ b = TQString::null;
+ if (a == b) {
+ kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
+ }
+ else {
+ kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
+ exit(1);
+ }
+ return true;
+}
+
+template<typename T>
+static bool check(const TQString& txt, T a, T b)
+{
+ if (a == b) {
+ kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl;
+ }
+ else {
+ kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl;
+ exit(1);
+ }
+ return true;
+}
+
+int main(int argc, char *argv[])
+{
+ TDEApplication::disableAutoDcopRegistration();
+ TDECmdLineArgs::init(argc,argv,"kacltest", 0, 0, 0, 0);
+ TDEApplication app;
+
+ KACLTest test;
+ test.setup();
+ test.runAll();
+ test.cleanup();
+ kdDebug() << "All tests OK." << endl;
+ return 0; // success. The exit(1) in check() is what happens in case of failure.
+}
+
+#ifdef Q_OS_FREEBSD
+static const TQString s_group1 = TQString::fromLatin1("staff");
+static const TQString s_group2 = TQString::fromLatin1("guest");
+#else
+static const TQString s_group1 = TQString::fromLatin1("audio");
+static const TQString s_group2 = TQString::fromLatin1("users");
+#endif
+
+static const TQString s_testACL = TQString::fromLatin1( "user::rw-\nuser:bin:rwx\ngroup::rw-\nmask::rwx\nother::r--\n" );
+static const TQString s_testACL2 = TQString::fromLatin1( "user::rwx\nuser:bin:rwx\ngroup::rw-\n") +
+ TQString::fromLatin1( "group:" ) + s_group1 + TQString::fromLatin1( ":--x\n" ) +
+ TQString::fromLatin1( "group:" ) + s_group2 + TQString::fromLatin1( ":r--\n" ) +
+ TQString::fromLatin1( "mask::r-x\nother::r--\n" );
+static const TQString s_testACLEffective = TQString::fromLatin1( "user::rwx\nuser:bin:rwx #effective:r-x\ngroup::rw- #effective:r--\n" ) +
+ TQString::fromLatin1( "group:" ) + s_group1 + TQString::fromLatin1( ":--x\n" ) +
+ TQString::fromLatin1( "group:" ) + s_group2 + TQString::fromLatin1( ":r--\n" ) +
+ TQString::fromLatin1( "mask::r-x\nother::r--\n" );
+
+KACLTest::KACLTest()
+:m_acl( s_testACL )
+{
+}
+
+void KACLTest::setup()
+{
+}
+
+void KACLTest::runAll()
+{
+ testAsString();
+ testGetOwnerPermissions();
+ testGetOwningGroupPermissions();
+ testGetOthersPermissions();
+
+ testGetMaskPermissions();
+ testGetAllUserPermissions();
+
+ testIsExtended();
+
+ // from here on we operate with the second test string
+ testSetACL();
+ testGetAllGroupsPermissions();
+
+ testOperators();
+ testSettingBasic();
+ testSettingExtended();
+ testSettingErrorHandling();
+
+ testNewMask();
+}
+
+void KACLTest::cleanup()
+{
+}
+
+void KACLTest::testAsString()
+{
+ check( "asString: ", m_acl.asString(), s_testACL );
+}
+
+void KACLTest::testSetACL()
+{
+ m_acl.setACL( s_testACL2 );
+ check( "setACL: ", m_acl.asString().simplifyWhiteSpace().remove(" "), s_testACLEffective.simplifyWhiteSpace().remove(" ") );
+}
+
+void KACLTest::testGetOwnerPermissions()
+{
+ check( "Owner permissions: ", TQString::number( m_acl.ownerPermissions() ), "6" );
+}
+
+void KACLTest::testGetOwningGroupPermissions()
+{
+ check( "Owning group permissions: ", TQString::number( m_acl.owningGroupPermissions() ), "6" );
+}
+
+void KACLTest::testGetOthersPermissions()
+{
+ check( "Others permissions: ", TQString::number( m_acl.othersPermissions() ), "4" );
+}
+
+void KACLTest::testGetMaskPermissions()
+{
+ bool exists = false;
+ unsigned short mask = m_acl.maskPermissions( exists );
+ check( "Mask permissions: ", TQString::number( mask ), "7" );
+ check( "Mask permissions: ", exists, true );
+}
+
+void KACLTest::testGetAllUserPermissions()
+{
+ ACLUserPermissionsList list = m_acl.allUserPermissions();
+ ACLUserPermissionsConstIterator it = list.begin();
+ TQString name;
+ unsigned short permissions;
+ int count = 0;
+ while ( it != list.end() ) {
+ name = ( *it ).first;
+ permissions = ( *it ).second;
+ ++it;
+ ++count;
+ }
+ check( "All users count: ", TQString::number( count ), "1" );
+ check( "All users name: ", name, "bin" );
+ check( "All users permissions: ", TQString::number( permissions ), "7" );
+}
+
+void KACLTest::testGetAllGroupsPermissions()
+{
+ ACLGroupPermissionsList list = m_acl.allGroupPermissions();
+ ACLGroupPermissionsConstIterator it = list.begin();
+ TQString name;
+ unsigned short permissions;
+ int count = 0;
+ while ( it != list.end() ) {
+ name = ( *it ).first;
+ permissions = ( *it ).second;
+ // setACL sorts them alphabetically ...
+ if ( count == 0 ) {
+ check( "All groups name: ", name, s_group1 );
+ check( "All groups permissions: ", TQString::number( permissions ), "1" );
+ } else if ( count == 1 ) {
+ check( "All groups name: ", name, s_group2 );
+ check( "All groups permissions: ", TQString::number( permissions ), "4" );
+ }
+ ++it;
+ ++count;
+ }
+ check( "All users count: ", TQString::number( count ), "2" );
+}
+
+void KACLTest::testIsExtended()
+{
+ KACL dukeOfMonmoth( s_testACL );
+ check( "isExtended on an extended one: ", dukeOfMonmoth.isExtended(), true );
+ KACL earlOfUpnor( "user::r--\ngroup::r--\nother::r--\n" );
+ check( "isExtended on a not extended one: ", earlOfUpnor.isExtended(), false );
+}
+
+void KACLTest::testOperators()
+{
+ KACL dukeOfMonmoth( s_testACL );
+ KACL JamesScott( s_testACL );
+ KACL earlOfUpnor( s_testACL2 );
+ check( "operator== on different ones: ", dukeOfMonmoth == earlOfUpnor, false );
+ check( "operator== on identical ones: ", dukeOfMonmoth == JamesScott, true );
+ check( "operator!= on diffenrent ones: ", dukeOfMonmoth != earlOfUpnor, true );
+ check( "operator!=: on identical ones: ", dukeOfMonmoth != JamesScott, false );
+}
+
+void KACLTest::testSettingBasic()
+{
+ KACL CharlesII( s_testACL );
+ CharlesII.setOwnerPermissions( 7 ); // clearly
+ CharlesII.setOwningGroupPermissions( 0 );
+ CharlesII.setOthersPermissions( 0 );
+ check( "setOwnerPermissions: ", TQString::number( CharlesII.ownerPermissions() ),"7" );
+ check( "setOwningGroupPermissions: ", TQString::number( CharlesII.owningGroupPermissions() ),"0" );
+ check( "setOthersPermissions: ", TQString::number( CharlesII.othersPermissions() ),"0" );
+}
+
+void KACLTest::testSettingExtended()
+{
+ KACL CharlesII( s_testACL );
+ CharlesII.setMaskPermissions( 7 ); // clearly
+ bool dummy = false;
+ check( "setMaskPermissions: ", TQString::number( CharlesII.maskPermissions( dummy ) ),"7" );
+
+ const TQString expected( "user::rw-\nuser:root:rwx\nuser:bin:r--\ngroup::rw-\nmask::rwx\nother::r--\n" );
+
+ ACLUserPermissionsList users;
+ ACLUserPermissions user = qMakePair( TQString( "root" ), ( unsigned short )7 );
+ users.append( user );
+ user = qMakePair( TQString( "bin" ), ( unsigned short )4 );
+ users.append( user );
+ CharlesII.setAllUserPermissions( users );
+ check( "setAllUserPermissions: ", CharlesII.asString(), expected );
+
+ CharlesII.setACL( s_testACL ); // reset
+ // it already has an entry for bin, let's change it
+ CharlesII.setNamedUserPermissions( TQString("bin"), 4 );
+ CharlesII.setNamedUserPermissions( TQString( "root" ), 7 );
+ check( "setNamedUserPermissions: ", CharlesII.asString(), expected );
+
+ // groups, all and named
+
+ const TQString expected2 = TQString::fromLatin1( "user::rw-\nuser:bin:rwx\ngroup::rw-\ngroup:" ) + s_group1 +
+ TQString::fromLatin1( ":-wx\ngroup:" ) + s_group2 + TQString::fromLatin1(":r--\nmask::rwx\nother::r--\n" );
+ CharlesII.setACL( s_testACL ); // reset
+ ACLGroupPermissionsList groups;
+ ACLGroupPermissions group = qMakePair( s_group1, ( unsigned short )3 );
+ groups.append( group );
+ group = qMakePair( s_group2, ( unsigned short )4 );
+ groups.append( group );
+ CharlesII.setAllGroupPermissions( groups );
+ check( "setAllGroupPermissions: ", CharlesII.asString(), expected2 );
+
+ CharlesII.setACL( s_testACL ); // reset
+ CharlesII.setNamedGroupPermissions( s_group1, 3 );
+ CharlesII.setNamedGroupPermissions( s_group2, 4 );
+ check( "setNamedGroupPermissions: ", CharlesII.asString(), expected2 );
+}
+
+void KACLTest::testSettingErrorHandling()
+{
+ KACL foo( s_testACL );
+ bool v = foo.setNamedGroupPermissions( s_group1, 7 ); // existing group
+ check( "Existing group: ", v, true );
+ v = foo.setNamedGroupPermissions( "jongel", 7 ); // non-existing group
+ check( "Non-existing group: ", v, false );
+
+ v = foo.setNamedUserPermissions( "bin", 7 ); // existing user
+ check( "Existing user: ", v, true );
+ v = foo.setNamedUserPermissions( "jongel", 7 ); // non-existing user
+ check( "Non-existing user: ", v, false );
+}
+
+void KACLTest::testNewMask()
+{
+ KACL CharlesII( "user::rw-\ngroup::rw-\nother::rw\n" );
+ bool dummy = false;
+ CharlesII.maskPermissions( dummy );
+ check( "mask exists: ", dummy, false );
+
+ CharlesII.setMaskPermissions( 6 );
+ check( "new mask set: ", TQString::number( CharlesII.maskPermissions( dummy ) ), "6" );
+ check( "mask exists now: ", dummy, true );
+}
diff --git a/kio/tests/kacltest.h b/tdeio/tests/kacltest.h
index 1a85e4109..1a85e4109 100644
--- a/kio/tests/kacltest.h
+++ b/tdeio/tests/kacltest.h
diff --git a/kio/tests/kdcopcheck.cpp b/tdeio/tests/kdcopcheck.cpp
index 79f050f51..79f050f51 100644
--- a/kio/tests/kdcopcheck.cpp
+++ b/tdeio/tests/kdcopcheck.cpp
diff --git a/kio/tests/kdcopcheck.h b/tdeio/tests/kdcopcheck.h
index 593dbba1e..593dbba1e 100644
--- a/kio/tests/kdcopcheck.h
+++ b/tdeio/tests/kdcopcheck.h
diff --git a/tdeio/tests/kdefaultprogresstest.cpp b/tdeio/tests/kdefaultprogresstest.cpp
new file mode 100644
index 000000000..7e77611ed
--- /dev/null
+++ b/tdeio/tests/kdefaultprogresstest.cpp
@@ -0,0 +1,39 @@
+#include <kapplication.h>
+#include <tdeio/defaultprogress.h>
+#include <kurl.h>
+#include <kdebug.h>
+
+using namespace TDEIO;
+
+int main(int argc, char **argv)
+{
+ TDEApplication app(argc, argv, "kdefaultprogresstest");
+
+ DefaultProgress* dlg = new DefaultProgress();
+ KURL src("http://this.host.doesn't.exist/this/dir/neither/andthisfileneither");
+ KURL dest("file:/tmp/dest");
+ dlg->slotCopying( 0L, src, dest );
+ dlg->slotTotalSize( 0L, 12000 );
+ dlg->slotTotalFiles( 0L, 12 );
+ dlg->slotTotalDirs( 0L, 1 );
+
+ dlg->slotSpeed( 0L, 55 );
+ dlg->slotInfoMessage( 0L, TQString::fromLatin1( "Starting..." ) );
+
+ int files = 0;
+ for ( int size = 0 ; size < 12000 ; size += 1 )
+ {
+ dlg->slotProcessedSize( 0L, size );
+ dlg->slotPercent( 0L, 100 * size / 12000 );
+ if ( size % 1000 == 0 )
+ {
+ dlg->slotProcessedFiles( 0L, ++files );
+ }
+ kapp->processEvents();
+ }
+ dlg->slotInfoMessage( 0L, TQString::fromLatin1( "Done." ) );
+
+ delete dlg;
+ return 0;
+}
+
diff --git a/kio/tests/kdirlistertest.cpp b/tdeio/tests/kdirlistertest.cpp
index 000fb200c..000fb200c 100644
--- a/kio/tests/kdirlistertest.cpp
+++ b/tdeio/tests/kdirlistertest.cpp
diff --git a/tdeio/tests/kdirlistertest.h b/tdeio/tests/kdirlistertest.h
new file mode 100644
index 000000000..484121eef
--- /dev/null
+++ b/tdeio/tests/kdirlistertest.h
@@ -0,0 +1,120 @@
+/* This file is part of the KDE desktop environment
+
+ Copyright (C) 2001, 2002 Michael Brade <brade@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef _KDIRLISTERTEST_H_
+#define _KDIRLISTERTEST_H_
+
+#include <tqwidget.h>
+#include <tqstring.h>
+
+#include <kurl.h>
+#include <tdefileitem.h>
+
+#include <iostream>
+
+using namespace std;
+
+class PrintSignals : public TQObject
+{
+ Q_OBJECT
+public:
+ PrintSignals() : TQObject() { }
+
+public slots:
+ void started( const KURL &url )
+ {
+ cout << "*** started( " << url.url().local8Bit() << " )" << endl;
+ }
+ void canceled() { cout << "canceled()" << endl; }
+ void canceled( const KURL& url )
+ {
+ cout << "*** canceled( " << url.prettyURL().local8Bit() << " )" << endl;
+ }
+ void completed() { cout << "*** completed()" << endl; }
+ void completed( const KURL& url )
+ {
+ cout << "*** completed( " << url.prettyURL().local8Bit() << " )" << endl;
+ }
+ void redirection( const KURL& url )
+ {
+ cout << "*** redirection( " << url.prettyURL().local8Bit() << " )" << endl;
+ }
+ void redirection( const KURL& src, const KURL& dest )
+ {
+ cout << "*** redirection( " << src.prettyURL().local8Bit() << ", "
+ << dest.prettyURL().local8Bit() << " )" << endl;
+ }
+ void clear() { cout << "*** clear()" << endl; }
+ void newItems( const KFileItemList& items )
+ {
+ cout << "*** newItems: " << endl;
+ for ( KFileItemListIterator it( items ) ; it.current() ; ++it )
+ cout << it.current() << " " << it.current()->name().local8Bit() << endl;
+ }
+ void deleteItem( KFileItem* item )
+ {
+ cout << "*** deleteItem: " << item->url().prettyURL().local8Bit() << endl;
+ }
+ void itemsFilteredByMime( const KFileItemList& )
+ {
+ cout << "*** itemsFilteredByMime: " << endl;
+ // TODO
+ }
+ void refreshItems( const KFileItemList& )
+ {
+ cout << "*** refreshItems: " << endl;
+ // TODO
+ }
+ void infoMessage( const TQString& msg )
+ { cout << "*** infoMessage: " << msg.local8Bit() << endl; }
+
+ void percent( int percent )
+ { cout << "*** percent: " << percent << endl; }
+
+ void totalSize( TDEIO::filesize_t size )
+ { cout << "*** totalSize: " << (long)size << endl; }
+
+ void processedSize( TDEIO::filesize_t size )
+ { cout << "*** processedSize: " << (long)size << endl; }
+
+ void speed( int bytes_per_second )
+ { cout << "*** speed: " << bytes_per_second << endl; }
+};
+
+class KDirListerTest : public TQWidget
+{
+ Q_OBJECT
+public:
+ KDirListerTest( TQWidget *parent=0, const char *name=0 );
+ ~KDirListerTest();
+
+public slots:
+ void startRoot();
+ void startHome();
+ void startTar();
+ void test();
+ void completed();
+
+private:
+ KDirLister *lister;
+ PrintSignals *debug;
+};
+
+#endif
diff --git a/kio/tests/kdirwatchtest.cpp b/tdeio/tests/kdirwatchtest.cpp
index c741b20f0..c741b20f0 100644
--- a/kio/tests/kdirwatchtest.cpp
+++ b/tdeio/tests/kdirwatchtest.cpp
diff --git a/kio/tests/kdirwatchtest.h b/tdeio/tests/kdirwatchtest.h
index 24dc94a91..24dc94a91 100644
--- a/kio/tests/kdirwatchtest.h
+++ b/tdeio/tests/kdirwatchtest.h
diff --git a/kio/tests/kdirwatchunittest.cpp b/tdeio/tests/kdirwatchunittest.cpp
index 3d7505a3f..3d7505a3f 100644
--- a/kio/tests/kdirwatchunittest.cpp
+++ b/tdeio/tests/kdirwatchunittest.cpp
diff --git a/kio/tests/kdirwatchunittest.h b/tdeio/tests/kdirwatchunittest.h
index 42222a787..42222a787 100644
--- a/kio/tests/kdirwatchunittest.h
+++ b/tdeio/tests/kdirwatchunittest.h
diff --git a/kio/tests/kfiltertest.cpp b/tdeio/tests/kfiltertest.cpp
index 1922e207e..1922e207e 100644
--- a/kio/tests/kfiltertest.cpp
+++ b/tdeio/tests/kfiltertest.cpp
diff --git a/kio/tests/kionetrctest.cpp b/tdeio/tests/kionetrctest.cpp
index 2d96c8495..2d96c8495 100644
--- a/kio/tests/kionetrctest.cpp
+++ b/tdeio/tests/kionetrctest.cpp
diff --git a/kio/tests/kiopassdlgtest.cpp b/tdeio/tests/kiopassdlgtest.cpp
index adb14a306..adb14a306 100644
--- a/kio/tests/kiopassdlgtest.cpp
+++ b/tdeio/tests/kiopassdlgtest.cpp
diff --git a/tdeio/tests/kmfitest.cpp b/tdeio/tests/kmfitest.cpp
new file mode 100644
index 000000000..a2ec91717
--- /dev/null
+++ b/tdeio/tests/kmfitest.cpp
@@ -0,0 +1,28 @@
+#include <stdio.h>
+#include <tqdir.h>
+#include <tqfile.h>
+#include <kinstance.h>
+#include <kurl.h>
+#include <tdefilemetainfo.h>
+#include <kmimetype.h>
+
+int main (int argc, char **argv)
+{
+ TDEInstance ins("kmfitest");
+
+ if (argc < 2) {
+ printf("usage: %s <file>\n", argv[0]);
+ return 1;
+ }
+
+ for (int i = 1; i < argc; i++) {
+ TQString file = TQFile::decodeName(argv[i]);
+ tqWarning("File: %s", file.local8Bit().data());
+ KMimeType::Ptr p;
+ p = KMimeType::findByPath(file);
+ tqWarning("Mime type (findByPath): %s", p->name().latin1());
+ KFileMetaInfo meta(file, TQString::null, KFileMetaInfo::TechnicalInfo | KFileMetaInfo::ContentInfo);
+ }
+
+ return 0;
+}
diff --git a/kio/tests/kmimefromext.cpp b/tdeio/tests/kmimefromext.cpp
index 026d4173b..026d4173b 100644
--- a/kio/tests/kmimefromext.cpp
+++ b/tdeio/tests/kmimefromext.cpp
diff --git a/kio/tests/kmimemagictest.cpp b/tdeio/tests/kmimemagictest.cpp
index 00c545c3c..00c545c3c 100644
--- a/kio/tests/kmimemagictest.cpp
+++ b/tdeio/tests/kmimemagictest.cpp
diff --git a/kio/tests/kmimetypetest.cpp b/tdeio/tests/kmimetypetest.cpp
index 5d963c81c..5d963c81c 100644
--- a/kio/tests/kmimetypetest.cpp
+++ b/tdeio/tests/kmimetypetest.cpp
diff --git a/kio/tests/kpropsdlgtest.cpp b/tdeio/tests/kpropsdlgtest.cpp
index 811f03923..811f03923 100644
--- a/kio/tests/kpropsdlgtest.cpp
+++ b/tdeio/tests/kpropsdlgtest.cpp
diff --git a/kio/tests/kprotocolinfotest.cpp b/tdeio/tests/kprotocolinfotest.cpp
index 845f3367c..845f3367c 100644
--- a/kio/tests/kprotocolinfotest.cpp
+++ b/tdeio/tests/kprotocolinfotest.cpp
diff --git a/kio/tests/kruntest.cpp b/tdeio/tests/kruntest.cpp
index d8f47859b..d8f47859b 100644
--- a/kio/tests/kruntest.cpp
+++ b/tdeio/tests/kruntest.cpp
diff --git a/kio/tests/kruntest.h b/tdeio/tests/kruntest.h
index 68e7a7280..68e7a7280 100644
--- a/kio/tests/kruntest.h
+++ b/tdeio/tests/kruntest.h
diff --git a/kio/tests/kscantest.cpp b/tdeio/tests/kscantest.cpp
index 14abd1b33..14abd1b33 100644
--- a/kio/tests/kscantest.cpp
+++ b/tdeio/tests/kscantest.cpp
diff --git a/kio/tests/kshredtest.cpp b/tdeio/tests/kshredtest.cpp
index 76e87fca4..76e87fca4 100644
--- a/kio/tests/kshredtest.cpp
+++ b/tdeio/tests/kshredtest.cpp
diff --git a/kio/tests/ktartest.cpp b/tdeio/tests/ktartest.cpp
index 2c470f6e4..2c470f6e4 100644
--- a/kio/tests/ktartest.cpp
+++ b/tdeio/tests/ktartest.cpp
diff --git a/tdeio/tests/kurifiltertest.cpp b/tdeio/tests/kurifiltertest.cpp
new file mode 100644
index 000000000..473ba6840
--- /dev/null
+++ b/tdeio/tests/kurifiltertest.cpp
@@ -0,0 +1,361 @@
+/*
+ * Copyright (C) 2002, 2003 David Faure <faure@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "kurifilter.h"
+
+#include <config.h>
+#include <iostream>
+#include <stdlib.h>
+
+#include <kaboutdata.h>
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kcmdlineargs.h>
+#include <kstandarddirs.h>
+#include <ksimpleconfig.h>
+
+#include <tqdir.h>
+#include <tqregexp.h>
+#include <tdeio/netaccess.h>
+
+static const char * const s_uritypes[] = { "NET_PROTOCOL", "LOCAL_FILE", "LOCAL_DIR", "EXECUTABLE", "HELP", "SHELL", "BLOCKED", "ERROR", "UNKNOWN" };
+#define NO_FILTERING -2
+
+void filter( const char* u, const char * expectedResult = 0, int expectedUriType = -1, TQStringList list = TQStringList(), const char * abs_path = 0, bool checkForExecutables = true )
+{
+ TQString a = TQString::fromUtf8( u );
+ KURIFilterData * m_filterData = new KURIFilterData;
+ m_filterData->setData( a );
+ m_filterData->setCheckForExecutables( checkForExecutables );
+
+ if( abs_path )
+ {
+ m_filterData->setAbsolutePath( TQString::fromLatin1( abs_path ) );
+ kdDebug() << "Filtering: " << a << " with abs_path=" << abs_path << endl;
+ }
+ else
+ kdDebug() << "Filtering: " << a << endl;
+
+ if (KURIFilter::self()->filterURI(*m_filterData, list))
+ {
+ // Copied from minicli...
+ TQString cmd;
+ KURL uri = m_filterData->uri();
+
+ if ( uri.isLocalFile() && !uri.hasRef() && uri.query().isEmpty() )
+ cmd = uri.path();
+ else
+ cmd = uri.url();
+
+ switch( m_filterData->uriType() )
+ {
+ case KURIFilterData::LOCAL_FILE:
+ case KURIFilterData::LOCAL_DIR:
+ case KURIFilterData::HELP:
+ kdDebug() << "*** Result: Local Resource => '"
+ << m_filterData->uri().url() << "'" << endl;
+ break;
+ case KURIFilterData::NET_PROTOCOL:
+ kdDebug() << "*** Result: Network Resource => '"
+ << m_filterData->uri().url() << "'" << endl;
+ break;
+ case KURIFilterData::SHELL:
+ case KURIFilterData::EXECUTABLE:
+ if( m_filterData->hasArgsAndOptions() )
+ cmd += m_filterData->argsAndOptions();
+ kdDebug() << "*** Result: Executable/Shell => '" << cmd << "'"<< endl;
+ break;
+ case KURIFilterData::ERROR:
+ kdDebug() << "*** Result: Encountered error. See reason below." << endl;
+ break;
+ default:
+ kdDebug() << "*** Result: Unknown or invalid resource." << endl;
+ }
+
+ if ( expectedUriType != -1 && expectedUriType != m_filterData->uriType() )
+ {
+ kdError() << " Got URI type " << s_uritypes[m_filterData->uriType()]
+ << " expected " << s_uritypes[expectedUriType] << endl;
+ ::exit(1);
+ }
+
+ if ( expectedResult )
+ {
+ // Hack for other locales than english, normalize google hosts to google.com
+ cmd = cmd.replace( TQRegExp( "www\\.google\\.[^/]*/" ), "www.google.com/" );
+ if ( cmd != TQString::fromLatin1( expectedResult ) )
+ {
+ kdError() << " Got " << cmd << " expected " << expectedResult << endl;
+ ::exit(1);
+ }
+ }
+ }
+ else
+ {
+ if ( expectedUriType == NO_FILTERING )
+ kdDebug() << "*** No filtering required." << endl;
+ else
+ {
+ kdDebug() << "*** Could not be filtered." << endl;
+ if( expectedUriType != m_filterData->uriType() )
+ {
+ kdError() << " Got URI type " << s_uritypes[m_filterData->uriType()]
+ << " expected " << s_uritypes[expectedUriType] << endl;
+ ::exit(1);
+ }
+ }
+ }
+
+ delete m_filterData;
+ kdDebug() << "-----" << endl;
+}
+
+void testLocalFile( const TQString& filename )
+{
+ TQFile tmpFile( filename ); // Yeah, I know, security risk blah blah. This is a test prog!
+
+ if ( tmpFile.open( IO_ReadWrite ) )
+ {
+ TQCString fname = TQFile::encodeName( tmpFile.name() );
+ filter(fname, fname, KURIFilterData::LOCAL_FILE);
+ tmpFile.close();
+ tmpFile.remove();
+ }
+ else
+ kdDebug() << "Couldn't create " << tmpFile.name() << ", skipping test" << endl;
+}
+
+static const char appName[] = "kurifiltertest";
+static const char programName[] = I18N_NOOP("kurifiltertest");
+static const char description[] = I18N_NOOP("Unit test for the URI filter plugin framework.");
+static const char version[] = "1.5";
+
+static const KCmdLineOptions options[] =
+{
+ { "s", I18N_NOOP("Use space as keyword delimeter for web shortcuts"), 0},
+ KCmdLineLastOption
+};
+
+int main(int argc, char **argv)
+{
+ // Ensure that user configuration doesn't change the results of those tests
+ // TDEHOME needs to be writable though, for a tdesycoca database
+ setenv( "TDEHOME", TQFile::encodeName( TQDir::homeDirPath() + "/.tde-kurifiltertest" ), true );
+ setenv( "TDE_FORK_SLAVES", "yes", true ); // simpler, for the final cleanup
+
+ TDEAboutData aboutData(appName, programName, version, description);
+ TDECmdLineArgs::init(argc, argv, &aboutData);
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDEApplication app;
+ app.disableAutoDcopRegistration();
+
+ // Allow testing of the search engine using both delimiters...
+ char delimiter = TDECmdLineArgs::parsedArgs()->isSet("s") ? ' ' : ':';
+
+ // Many tests check the "default search engine" feature.
+ // There is no default search engine by default (since it was annoying when making typos),
+ // so the user has to set it up, which we do here.
+ {
+ KSimpleConfig cfg( "kuriikwsfilterrc" );
+ cfg.setGroup( "General" );
+ cfg.writeEntry( "DefaultSearchEngine", "google" );
+ cfg.writeEntry( "Verbose", true );
+ cfg.writeEntry( "KeywordDelimiter", delimiter );
+ cfg.sync();
+ }
+
+ // Enable verbosity for debugging
+ {
+ KSimpleConfig cfg( "kshorturifilterrc" );
+ cfg.writeEntry( "Verbose", true );
+ cfg.sync();
+ }
+
+ TQStringList minicliFilters;
+ minicliFilters << "kshorturifilter" << "kurisearchfilter" << "localdomainurifilter";
+
+ // URI that should require no filtering
+ filter( "http://www.kde.org", "http://www.kde.org", KURIFilterData::NET_PROTOCOL );
+ filter( "http://www.kde.org/developer//index.html", "http://www.kde.org/developer//index.html", KURIFilterData::NET_PROTOCOL );
+ // URL with reference
+ filter( "http://www.kde.org/index.html#q8", "http://www.kde.org/index.html#q8", KURIFilterData::NET_PROTOCOL );
+ // local file with reference
+ filter( "file:/etc/passwd#q8", "file:///etc/passwd#q8", KURIFilterData::LOCAL_FILE );
+ filter( "file:///etc/passwd#q8", "file:///etc/passwd#q8", KURIFilterData::LOCAL_FILE );
+ filter( "/etc/passwd#q8", "file:///etc/passwd#q8", KURIFilterData::LOCAL_FILE );
+ // local file with query (can be used by javascript)
+ filter( "file:/etc/passwd?foo=bar", "file:///etc/passwd?foo=bar", KURIFilterData::LOCAL_FILE );
+ testLocalFile( "/tmp/kurifiltertest?foo" ); // local file with ? in the name (#58990)
+ testLocalFile( "/tmp/kurlfiltertest#foo" ); // local file with '#' in the name
+ testLocalFile( "/tmp/kurlfiltertest#foo?bar" ); // local file with both
+ testLocalFile( "/tmp/kurlfiltertest?foo#bar" ); // local file with both, the other way round
+
+ // hostnames are lowercased by KURL
+ filter( "http://www.myDomain.commyPort/ViewObjectRes//Default:name=hello",
+ "http://www.mydomain.commyport/ViewObjectRes//Default:name=hello", KURIFilterData::NET_PROTOCOL);
+ filter( "ftp://ftp.kde.org", "ftp://ftp.kde.org", KURIFilterData::NET_PROTOCOL );
+ filter( "ftp://username@ftp.kde.org:500", "ftp://username@ftp.kde.org:500", KURIFilterData::NET_PROTOCOL );
+
+ // ShortURI/LocalDomain filter tests. NOTE: any of these tests can fail
+ // if you have specified your own patterns in kshorturifilterrc. For
+ // examples, see $TDEDIR/share/config/kshorturifilterrc .
+ filter( "linuxtoday.com", "http://linuxtoday.com", KURIFilterData::NET_PROTOCOL );
+ filter( "LINUXTODAY.COM", "http://linuxtoday.com", KURIFilterData::NET_PROTOCOL );
+ filter( "kde.org", "http://kde.org", KURIFilterData::NET_PROTOCOL );
+ filter( "ftp.kde.org", "ftp://ftp.kde.org", KURIFilterData::NET_PROTOCOL );
+ filter( "ftp.kde.org:21", "ftp://ftp.kde.org:21", KURIFilterData::NET_PROTOCOL );
+ filter( "cr.yp.to", "http://cr.yp.to", KURIFilterData::NET_PROTOCOL );
+ filter( "user@192.168.1.0:3128", "http://user@192.168.1.0:3128", KURIFilterData::NET_PROTOCOL );
+ filter( "127.0.0.1", "http://127.0.0.1", KURIFilterData::NET_PROTOCOL );
+ filter( "127.0.0.1:3128", "http://127.0.0.1:3128", KURIFilterData::NET_PROTOCOL );
+ filter( "foo@bar.com", "mailto:foo@bar.com", KURIFilterData::NET_PROTOCOL );
+ filter( "firstname.lastname@x.foo.bar", "mailto:firstname.lastname@x.foo.bar", KURIFilterData::NET_PROTOCOL );
+ filter( "www.123.foo", "http://www.123.foo", KURIFilterData::NET_PROTOCOL );
+ filter( "user@www.123.foo:3128", "http://user@www.123.foo:3128", KURIFilterData::NET_PROTOCOL );
+
+ // Exotic IPv4 address formats...
+ filter( "127.1", "http://127.1", KURIFilterData::NET_PROTOCOL );
+ filter( "127.0.1", "http://127.0.1", KURIFilterData::NET_PROTOCOL );
+
+ // Local domain filter - If you uncomment these test, make sure you
+ // you adjust it based on the localhost entry in your /etc/hosts file.
+ // filter( "localhost:3128", "http://localhost.localdomain:3128", KURIFilterData::NET_PROTOCOL );
+ // filter( "localhost", "http://localhost.localdomain", KURIFilterData::NET_PROTOCOL );
+ // filter( "localhost/~blah", "http://localhost.localdomain/~blah", KURIFilterData::NET_PROTOCOL );
+
+ filter( "/", "/", KURIFilterData::LOCAL_DIR );
+ filter( "/", "/", KURIFilterData::LOCAL_DIR, "kshorturifilter" );
+ filter( "~/.bashrc", TQDir::homeDirPath().local8Bit()+"/.bashrc", KURIFilterData::LOCAL_FILE, "kshorturifilter" );
+ filter( "~", TQDir::homeDirPath().local8Bit(), KURIFilterData::LOCAL_DIR, "kshorturifilter", "/tmp" );
+ filter( "~foobar", 0, KURIFilterData::ERROR, "kshorturifilter" );
+ filter( "user@host.domain", "mailto:user@host.domain", KURIFilterData::NET_PROTOCOL ); // new in KDE-3.2
+
+ // Windows style SMB (UNC) URL. Should be converted into the valid smb format...
+ filter( "\\\\mainserver\\share\\file", "smb://mainserver/share/file" , KURIFilterData::NET_PROTOCOL );
+
+ // Should not be filtered at all. All valid protocols of this form will be ignored.
+ filter( "ftp:" , "ftp:", KURIFilterData::UNKNOWN );
+ filter( "http:" , "http:", KURIFilterData::UNKNOWN );
+
+ /*
+ Automatic searching tests. NOTE: If the Default search engine is set to 'None',
+ this stuff will fail as the status returned will then be KURIFilterData::UNKNOWN.
+ */
+ filter( "gg:", 0 , KURIFilterData::NET_PROTOCOL );
+ filter( "KDE", 0 , KURIFilterData::NET_PROTOCOL );
+ filter( "FTP", 0 , KURIFilterData::NET_PROTOCOL );
+
+ // If your default search engine is set to 'Google', you can uncomment the test below.
+ filter( "gg:", "http://www.google.com/search?q=gg%3A&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+ filter( "KDE", "http://www.google.com/search?q=KDE&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+ filter( "FTP", "http://www.google.com/search?q=FTP&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+
+ // Typing 'cp' or any other valid unix command in konq's location bar should result in
+ // a search using the default search engine
+ // 'ls' is a bit of a special case though, due to the toplevel domain called 'ls'
+ filter( "cp", "http://www.google.com/search?q=cp&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL,
+ TQStringList(), 0, false /* don't check for executables, see konq_misc.cc */ );
+
+ // Executable tests - No IKWS in minicli
+ filter( "cp", "cp", KURIFilterData::EXECUTABLE, minicliFilters );
+ filter( "kfmclient", "kfmclient", KURIFilterData::EXECUTABLE, minicliFilters );
+ filter( "xwininfo", "xwininfo", KURIFilterData::EXECUTABLE, minicliFilters );
+ filter( "KDE", "KDE", NO_FILTERING, minicliFilters );
+ filter( "I/dont/exist", "I/dont/exist", NO_FILTERING, minicliFilters );
+ filter( "/I/dont/exist", 0, KURIFilterData::ERROR, minicliFilters );
+ filter( "/I/dont/exist#a", 0, KURIFilterData::ERROR, minicliFilters );
+ filter( "kfmclient --help", "kfmclient --help", KURIFilterData::EXECUTABLE, minicliFilters ); // the args are in argsAndOptions()
+ filter( "/usr/bin/gs", "/usr/bin/gs", KURIFilterData::EXECUTABLE, minicliFilters );
+ filter( "/usr/bin/gs -q -option arg1", "/usr/bin/gs -q -option arg1", KURIFilterData::EXECUTABLE, minicliFilters ); // the args are in argsAndOptions()
+
+ // ENVIRONMENT variable
+ setenv( "SOMEVAR", "/somevar", 0 );
+ setenv( "ETC", "/etc", 0 );
+
+ TQCString qtdir=getenv("QTDIR");
+ TQCString home = getenv("HOME");
+ TQCString tdehome = getenv("TDEHOME");
+
+ filter( "$SOMEVAR/tdelibs/tdeio", 0, KURIFilterData::ERROR ); // note: this dir doesn't exist...
+ filter( "$ETC/passwd", "/etc/passwd", KURIFilterData::LOCAL_FILE );
+ filter( "$QTDIR/doc/html/functions.html#s", TQCString("file://")+qtdir+"/doc/html/functions.html#s", KURIFilterData::LOCAL_FILE );
+ filter( "http://www.kde.org/$USER", "http://www.kde.org/$USER", KURIFilterData::NET_PROTOCOL ); // no expansion
+
+ // Assume the default (~/.trinity) if
+ if (tdehome.isEmpty())
+ {
+ tdehome += "$HOME/.trinity";
+ setenv("TDEHOME", tdehome.data(), 0);
+ }
+
+ filter( "$TDEHOME/share", tdehome+"/share", KURIFilterData::LOCAL_DIR );
+ KStandardDirs::makeDir( tdehome+"/a+plus" );
+ filter( "$TDEHOME/a+plus", tdehome+"/a+plus", KURIFilterData::LOCAL_DIR );
+
+ // BR 27788
+ KStandardDirs::makeDir( tdehome+"/share/Dir With Space" );
+ filter( "$TDEHOME/share/Dir With Space", tdehome+"/share/Dir With Space", KURIFilterData::LOCAL_DIR );
+
+ // support for name filters (BR 93825)
+ filter( "$TDEHOME/*.txt", tdehome+"/*.txt", KURIFilterData::LOCAL_DIR );
+ filter( "$TDEHOME/[a-b]*.txt", tdehome+"/[a-b]*.txt", KURIFilterData::LOCAL_DIR );
+ filter( "$TDEHOME/a?c.txt", tdehome+"/a?c.txt", KURIFilterData::LOCAL_DIR );
+ filter( "$TDEHOME/?c.txt", tdehome+"/?c.txt", KURIFilterData::LOCAL_DIR );
+ // but let's check that a directory with * in the name still works
+ KStandardDirs::makeDir( tdehome+"/share/Dir*With*Stars" );
+ filter( "$TDEHOME/share/Dir*With*Stars", tdehome+"/share/Dir*With*Stars", KURIFilterData::LOCAL_DIR );
+ KStandardDirs::makeDir( tdehome+"/share/Dir?QuestionMark" );
+ filter( "$TDEHOME/share/Dir?QuestionMark", tdehome+"/share/Dir?QuestionMark", KURIFilterData::LOCAL_DIR );
+ KStandardDirs::makeDir( tdehome+"/share/Dir[Bracket" );
+ filter( "$TDEHOME/share/Dir[Bracket", tdehome+"/share/Dir[Bracket", KURIFilterData::LOCAL_DIR );
+
+ filter( "$HOME/$TDEDIR/tdebase/kcontrol/ebrowsing", 0, KURIFilterData::ERROR );
+ filter( "$1/$2/$3", "http://www.google.com/search?q=$1/$2/$3&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL ); // can be used as bogus or valid test. Currently triggers default search, i.e. google
+ filter( "$$$$", "http://www.google.com/search?q=$$$$&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL ); // worst case scenarios.
+
+ // Replaced the match testing with a 0 since
+ // the shortURI filter will return the string
+ // itself if the requested environment variable
+ // is not already set.
+ filter( "$QTDIR", 0, KURIFilterData::LOCAL_DIR, "kshorturifilter" ); //use specific filter.
+ filter( "$HOME", home, KURIFilterData::LOCAL_DIR, "kshorturifilter" ); //use specific filter.
+
+
+ TQCString sc;
+ filter( sc.sprintf("gg%cfoo bar",delimiter), "http://www.google.com/search?q=foo+bar&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+ filter( sc.sprintf("bug%c55798", delimiter), "http://bugs.kde.org/show_bug.cgi?id=55798", KURIFilterData::NET_PROTOCOL );
+
+ filter( sc.sprintf("gg%cC++", delimiter), "http://www.google.com/search?q=C%2B%2B&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+ filter( sc.sprintf("ya%cfoo bar was here", delimiter), 0, -1 ); // this triggers default search, i.e. google
+ filter( sc.sprintf("gg%cwww.kde.org", delimiter), "http://www.google.com/search?q=www.kde.org&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+ filter( sc.sprintf("av%c+rock +sample", delimiter), "http://www.altavista.com/cgi-bin/query?pg=q&kl=XX&stype=stext&q=%2Brock+%2Bsample", KURIFilterData::NET_PROTOCOL );
+ filter( sc.sprintf("gg%cé", delimiter) /*eaccent in utf8*/, "http://www.google.com/search?q=%C3%A9&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+ filter( sc.sprintf("gg%cпрйвет", delimiter) /* greetings in russian utf-8*/, "http://www.google.com/search?q=%D0%BF%D1%80%D0%B9%D0%B2%D0%B5%D1%82&ie=UTF-8&oe=UTF-8", KURIFilterData::NET_PROTOCOL );
+
+ // Absolute Path tests for kshorturifilter
+ filter( "./", tdehome+"/share", KURIFilterData::LOCAL_DIR, "kshorturifilter", tdehome+"/share/" ); // cleanDirPath removes the trailing slash
+ filter( "../", tdehome, KURIFilterData::LOCAL_DIR, "kshorturifilter", tdehome+"/share" );
+ filter( "config", tdehome+"/share/config", KURIFilterData::LOCAL_DIR, "kshorturifilter", tdehome+"/share" );
+
+ // Clean up
+ TDEIO::NetAccess::del( tdehome, 0 );
+
+ kdDebug() << "All tests done. Go home..." << endl;
+ return 0;
+}
diff --git a/kio/tests/kurlcompletiontest.cpp b/tdeio/tests/kurlcompletiontest.cpp
index c8dc99595..c8dc99595 100644
--- a/kio/tests/kurlcompletiontest.cpp
+++ b/tdeio/tests/kurlcompletiontest.cpp
diff --git a/kio/tests/kziptest.cpp b/tdeio/tests/kziptest.cpp
index 84d38d134..84d38d134 100644
--- a/kio/tests/kziptest.cpp
+++ b/tdeio/tests/kziptest.cpp
diff --git a/tdeio/tests/metatest.cpp b/tdeio/tests/metatest.cpp
new file mode 100644
index 000000000..ee1d38201
--- /dev/null
+++ b/tdeio/tests/metatest.cpp
@@ -0,0 +1,321 @@
+#include <kapplication.h>
+#include <tdefilemetainfo.h>
+#include <kcmdlineargs.h>
+#include <tqstringlist.h>
+#include <tqimage.h>
+#include <kdebug.h>
+#include <tqlabel.h>
+#include <tqvalidator.h>
+
+#define I18N_NOOP
+
+ static KCmdLineOptions options[] =
+ {
+ { "+file", "File name", 0 },
+ { "addgroup ", "Add a group to a file", 0},
+ { "removegroup ", "Remove a group from a file", 0},
+ { "removeitem ", "Remove the item from --group from a file", 0},
+ { "group ", "Specify a group to work on", 0},
+ { "validator", "Create a validator for an item and show its class", 0},
+ { "item ", "Specify an item to work on", 0},
+ { "add ", "Add the --item to the --group and set the value", 0},
+ { "autogroupadd", "Automatically add a group if none is found", 0},
+ { "set ", "Set the value of --item in --group", 0},
+ { "groups", "list the groups of this file", 0 },
+ { "mimetypeinfo ", "the mimetype info for a mimetype", 0 },
+ KCmdLineLastOption
+ };
+
+void printKeyValues(KFileMetaInfo& info)
+{
+ TQStringList l = info.preferredKeys();
+ kdDebug() << "found " << l.size() << " keys\n";
+
+ TQString s;
+ TQStringList::Iterator it;
+ for (it = l.begin(); it!=l.end(); ++it)
+ {
+ s +=" - " + *it;
+ }
+ kdDebug() << "keys: " << s << endl;
+
+ for (it = l.begin(); it!=l.end(); ++it)
+ {
+ KFileMetaInfoItem item = info.item(*it);
+ if ( item.isValid() && item.value().canCast(TQVariant::String)) {
+ kdDebug() << item.key() << "(" << item.translatedKey() << ") -> "
+ << item.string() << endl;
+ }
+ }
+}
+
+void printMimeTypeInfo(TQString mimetype)
+{
+ const KFileMimeTypeInfo* info = KFileMetaInfoProvider::self()->mimeTypeInfo(mimetype);
+
+ if (!info) return;
+ kdDebug() << "Preferred groups:\n";
+ kdDebug() << "=================\n";
+ TQStringList groups = info->preferredGroups();
+
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ {
+ kdDebug() << *it << endl;
+ }
+
+ kdDebug() << endl;
+ kdDebug() << "Supported groups:\n";
+ kdDebug() << "=================\n";
+ groups = info->supportedGroups();
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ {
+ kdDebug() << *it << endl;
+ }
+
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ {
+ const KFileMimeTypeInfo::GroupInfo* groupinfo = info->groupInfo(*it);
+
+ kdDebug() << endl;
+ kdDebug() << "Group \"" << *it << "\"\n";
+ kdDebug() << "==================\n";
+
+ if (!groupinfo) kdDebug() << "argh! no group info\n";
+
+ kdDebug() << endl;
+ kdDebug() << " Supported keys:\n";
+ TQStringList keys = groupinfo->supportedKeys();
+ if (!keys.count()) kdDebug() << " none\n";
+ for (TQStringList::Iterator kit=keys.begin(); kit!=keys.end(); ++kit)
+ {
+ kdDebug() << " " << *kit << endl;
+
+ const KFileMimeTypeInfo::ItemInfo* iti = groupinfo->itemInfo(*kit);
+ kdDebug() << " Key: " << iti->key() << endl;
+ kdDebug() << " Translated: " << iti->key() << endl;
+ kdDebug() << " Type: " << TQVariant::typeToName(iti->type()) << endl;
+ kdDebug() << " Unit: " << iti->unit() << endl;
+ kdDebug() << " Hint: " << iti->hint() << endl;
+ kdDebug() << " Attributes: " << iti->attributes() << endl;
+ kdDebug() << " Prefix: " << iti->prefix() << endl;
+ kdDebug() << " Suffix: " << iti->suffix() << endl;
+ }
+
+ kdDebug() << " name: " << groupinfo->name() << endl;
+ kdDebug() << " translated: " << groupinfo->translatedName() << endl;
+ kdDebug() << " attributes: " << groupinfo->attributes() << endl;
+ kdDebug() << " variable keys: " << (groupinfo->supportsVariableKeys() ? "Yes" : "No") << endl;
+ if (groupinfo->supportsVariableKeys())
+ {
+ const KFileMimeTypeInfo::ItemInfo* iti = groupinfo->variableItemInfo();
+ kdDebug() << " variable key type/attr: " << TQVariant::typeToName(iti->type()) << " / " << iti->attributes() << endl;
+ }
+ }
+
+ kdDebug() << endl;
+ kdDebug() << "Preferred keys:\n";
+ kdDebug() << "===============\n";
+ TQStringList prefKeys = info->preferredKeys();
+ if (!prefKeys.count()) kdDebug() << " none\n";
+ for (TQStringList::Iterator kit=prefKeys.begin(); kit!=prefKeys.end(); ++kit)
+ {
+ kdDebug() << *kit << endl;
+ }
+
+ kdDebug() << endl;
+ kdDebug() << "Supported keys:\n";
+ kdDebug() << "===============\n";
+ TQStringList supKeys = info->supportedKeys();
+ if (!supKeys.count()) kdDebug() << " none\n";
+ for (TQStringList::Iterator kit=supKeys.begin(); kit!=supKeys.end(); ++kit)
+ {
+ kdDebug() << *kit << endl;
+ }
+}
+
+void addGroup(KFileMetaInfo& info, TQString group)
+{
+ kdDebug() << "trying to add group " << group << endl;
+
+ kdDebug() << "groups before: \n";
+ TQStringList groups = info.groups();
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ kdDebug() << " " << *it << endl;
+
+ if (info.addGroup(group))
+ kdDebug() << "addGroup succeeded\n";
+ else
+ kdDebug() << "addGroup failed\n";
+
+ kdDebug() << "trying another addGroup to see what happens\n";
+
+ if (info.addGroup(group))
+ kdDebug() << "addGroup succeeded\n";
+ else
+ kdDebug() << "addGroup failed\n";
+
+
+ kdDebug() << "and afterwards: \n";
+ groups = info.groups();
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ kdDebug() << " " << *it << endl;
+}
+
+void removeGroup(KFileMetaInfo& info, TQString group)
+{
+ kdDebug() << "trying to remove group " << group << endl;
+
+ kdDebug() << "groups before: \n";
+ TQStringList groups = info.groups();
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ kdDebug() << " " << *it << endl;
+
+ info.removeGroup(group);
+
+ kdDebug() << "and afterwards: \n";
+ groups = info.groups();
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ kdDebug() << " " << *it << endl;
+}
+
+int main( int argc, char **argv )
+{
+ // Initialize command line args
+ TDECmdLineArgs::init(argc, argv, "tdefilemetatest", "testing kfilmetainfo", "X");
+
+ // Tell which options are supported
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ // Add options from other components
+ TDEApplication::addCmdLineOptions();
+
+ TDEApplication app;
+
+ TDECmdLineArgs* args = TDECmdLineArgs::parsedArgs();
+
+ TQCString ov;
+ ov = args->getOption("mimetypeinfo");
+ if (ov)
+ {
+ printMimeTypeInfo(ov);
+ return 0;
+ }
+
+ if (!args->count()) return 1;
+
+ KFileMetaInfo info( args->url(0), TQString::null, KFileMetaInfo::Everything);
+
+ if (args->isSet("groups"))
+ {
+ TQStringList groups = info.groups();
+ for (TQStringList::Iterator it=groups.begin() ; it!=groups.end(); ++it)
+ {
+ kdDebug() << "group " << *it << endl;
+ }
+ return 0;
+ }
+
+ TQString group, item;
+
+ ov = args->getOption("addgroup");
+ if (ov) addGroup(info, ov);
+
+ ov = args->getOption("removegroup");
+ if (ov) removeGroup(info, ov);
+
+ ov = args->getOption("group");
+ if (ov) group = ov;
+
+ ov = args->getOption("item");
+ if (ov) item = ov;
+
+ ov = args->getOption("add");
+ if (ov && !group.isNull() && !item.isNull())
+ {
+ KFileMetaInfoGroup g = info[group];
+ if (!g.isValid() && args->isSet("autogroupadd"))
+ {
+ kdDebug() << "group is not there, adding it\n";
+ info.addGroup(group);
+ }
+ // add the item
+ KFileMetaInfoItem i = info[group].addItem(item);
+ if (i.isValid())
+ kdDebug() << "additem success\n";
+ else
+ kdDebug() << "additem failed\n";
+
+ if (i.setValue(ov))
+ kdDebug() << "setValue success\n";
+ else
+ kdDebug() << "setValue failed\n";
+ }
+
+ ov = args->getOption("set");
+ if (ov && !group.isNull() && !item.isNull())
+ {
+ if (info[group][item].setValue(TQString(ov)))
+ kdDebug() << "setValue success\n";
+ else
+ kdDebug() << "setValue failed\n";
+ }
+
+ ov = args->getOption("removeitem");
+ if (ov && !group.isNull())
+ {
+ if (info[group].removeItem(ov))
+ kdDebug() << "removeitem success\n";
+ else
+ kdDebug() << "removeitem failed\n";
+ }
+
+ if (args->isSet("validator") && !group.isNull() && !item.isNull())
+ {
+ const KFileMimeTypeInfo* kfmti = KFileMetaInfoProvider::self()->mimeTypeInfo(info.mimeType());
+ TQValidator* v = kfmti->createValidator(group, item);
+ if (!v)
+ kdDebug() << "got no validator\n";
+ else
+ {
+ kdDebug() << "validator is a " << v->className() << endl;
+ delete v;
+ }
+
+ }
+
+ kdDebug() << "is it valid?\n";
+
+ if (!info.isValid()) return 1;
+
+ kdDebug() << "it is!\n";
+
+ printKeyValues(info);
+
+
+ kdDebug() << "========= again after applyChanges() =========\n";
+
+ info.applyChanges();
+
+ printKeyValues(info);
+
+ KFileMetaInfoItem thumbitem = info.item(KFileMimeTypeInfo::Thumbnail);
+// KFileMetaInfoItem thumbitem = info.item("Thumbnail");
+
+ if (!thumbitem.isValid()) kdDebug() << "no thumbnail\n";
+ else
+ kdDebug() << "type of thumbnail is " << thumbitem.value().typeName() << endl;
+
+
+ if (thumbitem.isValid() && thumbitem.value().canCast(TQVariant::Image))
+ {
+ TQLabel* label = new TQLabel(0);
+ app.setMainWidget(label);
+ TQPixmap pix;
+ pix.convertFromImage(thumbitem.value().toImage());
+ label->setPixmap(pix);
+ label->show();
+ app.exec();
+ }
+
+ return 0;
+}
diff --git a/tdeio/tests/netaccesstest.cpp b/tdeio/tests/netaccesstest.cpp
new file mode 100644
index 000000000..1a5de205d
--- /dev/null
+++ b/tdeio/tests/netaccesstest.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2004 David Faure <faure@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <kurl.h>
+#include <tdeio/netaccess.h>
+#include <tqfile.h>
+
+int main(int argc, char **argv)
+{
+ TDEApplication app( argc, argv, "netaccesstest", true /* it _has_ a GUI ! */);
+
+ KURL srcURL( "ftp://ftp.kde.org/pub/kde/README" );
+ KURL tmpURL( "file:/tmp/netaccesstest_README" );
+
+ for ( uint i = 0; i < 4 ; ++i ) {
+ kdDebug() << "file_copy" << endl;
+ if ( !TDEIO::NetAccess::file_copy(srcURL, tmpURL, -1, true, false, 0) )
+ kdError() << "file_copy failed: " << TDEIO::NetAccess::lastErrorString() << endl;
+ else {
+ TQFile f( tmpURL.path() );
+ if (!f.open(IO_ReadOnly))
+ kdFatal() << "Cannot open: " << f.name() << ". The error was: " << f.errorString() << endl;
+ else {
+ f.close();
+ }
+ }
+ }
+
+ return 0;
+}
+
diff --git a/tdeio/tests/previewtest.cpp b/tdeio/tests/previewtest.cpp
new file mode 100644
index 000000000..87bdd326d
--- /dev/null
+++ b/tdeio/tests/previewtest.cpp
@@ -0,0 +1,64 @@
+
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqpushbutton.h>
+
+#include <kapplication.h>
+#include <kdebug.h>
+#include <klineedit.h>
+
+#include <tdeio/previewjob.h>
+
+#include "previewtest.moc"
+
+PreviewTest::PreviewTest()
+ :TQWidget()
+{
+ TQGridLayout *layout = new TQGridLayout(this, 2, 2);
+ m_url = new KLineEdit(this);
+ m_url->setText("/home/malte/gore_bush.jpg");
+ layout->addWidget(m_url, 0, 0);
+ TQPushButton *btn = new TQPushButton("Generate", this);
+ connect(btn, TQT_SIGNAL(clicked()), TQT_SLOT(slotGenerate()));
+ layout->addWidget(btn, 0, 1);
+ m_preview = new TQLabel(this);
+ m_preview->setMinimumSize(400, 300);
+ layout->addMultiCellWidget(m_preview, 1, 1, 0, 1);
+}
+
+void PreviewTest::slotGenerate()
+{
+ KURL::List urls;
+ urls.append(m_url->text());
+ TDEIO::PreviewJob *job = TDEIO::filePreview(urls, m_preview->width(), m_preview->height(), true, 48);
+ connect(job, TQT_SIGNAL(result(TDEIO::Job*)), TQT_SLOT(slotResult(TDEIO::Job*)));
+ connect(job, TQT_SIGNAL(gotPreview(const KFileItem *, const TQPixmap &)), TQT_SLOT(slotPreview(const KFileItem *, const TQPixmap &)));
+ connect(job, TQT_SIGNAL(failed(const KFileItem *)), TQT_SLOT(slotFailed()));
+}
+
+void PreviewTest::slotResult(TDEIO::Job*)
+{
+ kdDebug() << "PreviewTest::slotResult(...)" << endl;
+}
+
+void PreviewTest::slotPreview(const KFileItem *, const TQPixmap &pix)
+{
+ kdDebug() << "PreviewTest::slotPreview()" << endl;
+ m_preview->setPixmap(pix);
+}
+
+void PreviewTest::slotFailed()
+{
+ kdDebug() << "PreviewTest::slotFailed()" << endl;
+ m_preview->setText("failed");
+}
+
+int main(int argc, char **argv)
+{
+ TDEApplication app(argc, argv, "previewtest");
+ PreviewTest *w = new PreviewTest;
+ w->show();
+ app.setMainWidget(w);
+ return app.exec();
+}
+
diff --git a/tdeio/tests/previewtest.h b/tdeio/tests/previewtest.h
new file mode 100644
index 000000000..5ef82916d
--- /dev/null
+++ b/tdeio/tests/previewtest.h
@@ -0,0 +1,25 @@
+
+#include <tqwidget.h>
+#include <tdeio/job.h>
+
+class KLineEdit;
+class TQLabel;
+class KFileItem;
+
+class PreviewTest : public TQWidget
+{
+ Q_OBJECT
+public:
+ PreviewTest();
+
+private slots:
+ void slotGenerate();
+ void slotResult(TDEIO::Job *);
+ void slotPreview( const KFileItem *, const TQPixmap & );
+ void slotFailed();
+
+private:
+ KLineEdit *m_url;
+ TQLabel *m_preview;
+};
+
diff --git a/tdeio/tests/speed.cpp b/tdeio/tests/speed.cpp
new file mode 100644
index 000000000..978845669
--- /dev/null
+++ b/tdeio/tests/speed.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2002, 2003 Stephan Kulow <coolo@kde.org>
+ * Copyright (C) 2003 David Faure <faure@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+#include <kdebug.h>
+#include <kapplication.h>
+#include <time.h>
+#include "speed.h"
+#include <tdeio/job.h>
+#include <kcmdlineargs.h>
+#include <tqdir.h>
+#include <tdeio/global.h>
+
+using namespace TDEIO;
+
+SpeedTest::SpeedTest( const KURL & url )
+ : TQObject(0, "speed")
+{
+ Job *job = listRecursive( url );
+ //Job *job = del( KURL("file:" + TQDir::currentDirPath()) ); DANGEROUS !
+ connect(job, TQT_SIGNAL( result( TDEIO::Job*)),
+ TQT_SLOT( finished( TDEIO::Job* ) ));
+ /*connect(job, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
+ TQT_SLOT( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)));
+ */
+}
+
+void SpeedTest::entries(TDEIO::Job*, const UDSEntryList& list) {
+
+ UDSEntryListConstIterator it=list.begin();
+ for (; it != list.end(); ++it) {
+ UDSEntry::ConstIterator it2 = (*it).begin();
+ for( ; it2 != (*it).end(); it2++ ) {
+ if ((*it2).m_uds == UDS_NAME)
+ kdDebug() << ( *it2 ).m_str << endl;
+ }
+ }
+}
+
+
+void SpeedTest::finished(Job*) {
+ kdDebug() << "job finished" << endl;
+ kapp->quit();
+}
+
+static KCmdLineOptions options[] =
+{
+ { "+[URL]", "the URL to list", 0 },
+ KCmdLineLastOption
+};
+
+int main(int argc, char **argv) {
+
+ TDECmdLineArgs::init( argc, argv, "speedapp", "A TDEIO::listRecursive testing tool", "0.0" );
+
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDEApplication app;
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ KURL url;
+ if ( args->count() == 1 )
+ url = args->url(0);
+ else
+ url = "file:" + TQDir::currentDirPath();
+
+ kdDebug() << url.url() << " is probably " << (TDEIO::probably_slow_mounted(url.path()) ? "slow" : "normal") << " mounted\n";
+ kdDebug() << url.url() << " is " << (TDEIO::manually_mounted(url.path()) ? "manually" : "system") << " mounted\n";
+ TQString mp = TDEIO::findDeviceMountPoint(url.path());
+ if (mp.isEmpty()) {
+ kdDebug() << "no mount point for device " << url.url() << " found\n";
+ } else
+ kdDebug() << mp << " is the mount point for device " << url.url() << endl;
+
+ mp = TDEIO::findPathMountPoint(url.path());
+ if (mp.isEmpty()) {
+ kdDebug() << "no mount point for path " << url.url() << " found\n";
+ } else
+ kdDebug() << mp << " is the mount point for path " << url.url() << endl;
+ // SpeedTest test( url );
+ // app.exec();
+
+ mp = TDEIO::findPathMountPoint(url.path());
+ if (mp.isEmpty()) {
+ kdDebug() << "no mount point for path " << url.url() << " found\n";
+ } else
+ kdDebug() << mp << " is the mount point for path " << url.url() << endl;
+ // SpeedTest test( url );
+ // app.exec();
+
+ url.setPath(TQDir::homeDirPath());
+
+ mp = TDEIO::findPathMountPoint(url.path());
+ if (mp.isEmpty()) {
+ kdDebug() << "no mount point for path " << url.url() << " found\n";
+ } else
+ kdDebug() << mp << " is the mount point for path " << url.url() << endl;
+ // SpeedTest test( url );
+ // app.exec();
+
+ mp = TDEIO::findPathMountPoint(url.path());
+ if (mp.isEmpty()) {
+ kdDebug() << "no mount point for path " << url.url() << " found\n";
+ } else
+ kdDebug() << mp << " is the mount point for path " << url.url() << endl;
+ // SpeedTest test( url );
+ // app.exec();
+
+ if ( args->count() == 1 )
+ url = args->url(0);
+ else
+ url = "file:" + TQDir::currentDirPath();
+
+ mp = TDEIO::findPathMountPoint(url.path());
+ if (mp.isEmpty()) {
+ kdDebug() << "no mount point for path " << url.url() << " found\n";
+ } else
+ kdDebug() << mp << " is the mount point for path " << url.url() << endl;
+ // SpeedTest test( url );
+ // app.exec();
+
+}
+
+#include "speed.moc"
diff --git a/tdeio/tests/speed.h b/tdeio/tests/speed.h
new file mode 100644
index 000000000..d7801ae47
--- /dev/null
+++ b/tdeio/tests/speed.h
@@ -0,0 +1,24 @@
+// -*- c++ -*-
+#ifndef _SPEED_H
+#define _SPEED_H
+
+#include <tdeio/global.h>
+#include <kurl.h>
+
+namespace TDEIO {
+ class Job;
+}
+
+class SpeedTest : public TQObject {
+ Q_OBJECT
+
+public:
+ SpeedTest(const KURL & url);
+
+private slots:
+ void entries( TDEIO::Job *, const TDEIO::UDSEntryList& );
+ void finished( TDEIO::Job *job );
+
+};
+
+#endif
diff --git a/tdeio/tests/tdeioslavetest.cpp b/tdeio/tests/tdeioslavetest.cpp
new file mode 100644
index 000000000..5fa19073c
--- /dev/null
+++ b/tdeio/tests/tdeioslavetest.cpp
@@ -0,0 +1,555 @@
+ /*
+ This file is or will be part of KDE desktop environment
+
+ Copyright 1999 Matt Koss <koss@miesto.sk>
+
+ It is licensed under GPL version 2.
+
+ If it is part of KDE libraries than this file is licensed under
+ LGPL version 2.
+ */
+
+#include <tqlayout.h>
+#include <tqmessagebox.h>
+#include <tqdir.h>
+
+#include <kacl.h>
+#include <kapplication.h>
+#include <kcmdlineargs.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <kurl.h>
+#include <kstatusbar.h>
+#include <tdeio/job.h>
+#include <tdeio/scheduler.h>
+#include <kprotocolinfo.h>
+
+#include "tdeioslavetest.h"
+
+using namespace TDEIO;
+
+KioslaveTest::KioslaveTest( TQString src, TQString dest, uint op, uint pr )
+ : KMainWindow(0, "")
+{
+
+ job = 0L;
+
+ main_widget = new TQWidget( this, "");
+ TQBoxLayout *topLayout = new TQVBoxLayout( main_widget, 10, 5 );
+
+ TQGridLayout *grid = new TQGridLayout( 2, 2, 10 );
+ topLayout->addLayout( grid );
+
+ grid->setRowStretch(0,1);
+ grid->setRowStretch(1,1);
+
+ grid->setColStretch(0,1);
+ grid->setColStretch(1,100);
+
+ lb_from = new TQLabel( "From:", main_widget );
+ grid->addWidget( lb_from, 0, 0 );
+
+ le_source = new TQLineEdit( main_widget );
+ grid->addWidget( le_source, 0, 1 );
+ le_source->setText( src );
+
+ lb_to = new TQLabel( "To:", main_widget );
+ grid->addWidget( lb_to, 1, 0 );
+
+ le_dest = new TQLineEdit( main_widget );
+ grid->addWidget( le_dest, 1, 1 );
+ le_dest->setText( dest );
+
+ // Operation groupbox & buttons
+ opButtons = new TQButtonGroup( "Operation", main_widget );
+ topLayout->addWidget( opButtons, 10 );
+ connect( opButtons, TQT_SIGNAL(clicked(int)), TQT_SLOT(changeOperation(int)) );
+
+ TQBoxLayout *hbLayout = new TQHBoxLayout( opButtons, 15 );
+
+ rbList = new TQRadioButton( "List", opButtons );
+ opButtons->insert( rbList, List );
+ hbLayout->addWidget( rbList, 5 );
+
+ rbListRecursive = new TQRadioButton( "ListRecursive", opButtons );
+ opButtons->insert( rbListRecursive, ListRecursive );
+ hbLayout->addWidget( rbListRecursive, 5 );
+
+ rbStat = new TQRadioButton( "Stat", opButtons );
+ opButtons->insert( rbStat, Stat );
+ hbLayout->addWidget( rbStat, 5 );
+
+ rbGet = new TQRadioButton( "Get", opButtons );
+ opButtons->insert( rbGet, Get );
+ hbLayout->addWidget( rbGet, 5 );
+
+ rbPut = new TQRadioButton( "Put", opButtons );
+ opButtons->insert( rbPut, Put );
+ hbLayout->addWidget( rbPut, 5 );
+
+ rbCopy = new TQRadioButton( "Copy", opButtons );
+ opButtons->insert( rbCopy, Copy );
+ hbLayout->addWidget( rbCopy, 5 );
+
+ rbMove = new TQRadioButton( "Move", opButtons );
+ opButtons->insert( rbMove, Move );
+ hbLayout->addWidget( rbMove, 5 );
+
+ rbDelete = new TQRadioButton( "Delete", opButtons );
+ opButtons->insert( rbDelete, Delete );
+ hbLayout->addWidget( rbDelete, 5 );
+
+ rbShred = new TQRadioButton( "Shred", opButtons );
+ opButtons->insert( rbShred, Shred );
+ hbLayout->addWidget( rbShred, 5 );
+
+ rbMkdir = new TQRadioButton( "Mkdir", opButtons );
+ opButtons->insert( rbMkdir, Mkdir );
+ hbLayout->addWidget( rbMkdir, 5 );
+
+ rbMimetype = new TQRadioButton( "Mimetype", opButtons );
+ opButtons->insert( rbMimetype, Mimetype );
+ hbLayout->addWidget( rbMimetype, 5 );
+
+ opButtons->setButton( op );
+ changeOperation( op );
+
+ // Progress groupbox & buttons
+ progressButtons = new TQButtonGroup( "Progress dialog mode", main_widget );
+ topLayout->addWidget( progressButtons, 10 );
+ connect( progressButtons, TQT_SIGNAL(clicked(int)), TQT_SLOT(changeProgressMode(int)) );
+
+ hbLayout = new TQHBoxLayout( progressButtons, 15 );
+
+ rbProgressNone = new TQRadioButton( "None", progressButtons );
+ progressButtons->insert( rbProgressNone, ProgressNone );
+ hbLayout->addWidget( rbProgressNone, 5 );
+
+ rbProgressDefault = new TQRadioButton( "Default", progressButtons );
+ progressButtons->insert( rbProgressDefault, ProgressDefault );
+ hbLayout->addWidget( rbProgressDefault, 5 );
+
+ rbProgressStatus = new TQRadioButton( "Status", progressButtons );
+ progressButtons->insert( rbProgressStatus, ProgressStatus );
+ hbLayout->addWidget( rbProgressStatus, 5 );
+
+ progressButtons->setButton( pr );
+ changeProgressMode( pr );
+
+ // statusbar progress widget
+ statusProgress = new StatusbarProgress( statusBar() );
+ statusBar()->addWidget( statusProgress, 0, true );
+
+ // run & stop butons
+ hbLayout = new TQHBoxLayout( topLayout, 15 );
+
+ pbStart = new TQPushButton( "&Start", main_widget );
+ pbStart->setFixedSize( pbStart->sizeHint() );
+ connect( pbStart, TQT_SIGNAL(clicked()), TQT_SLOT(startJob()) );
+ hbLayout->addWidget( pbStart, 5 );
+
+ pbStop = new TQPushButton( "Sto&p", main_widget );
+ pbStop->setFixedSize( pbStop->sizeHint() );
+ pbStop->setEnabled( false );
+ connect( pbStop, TQT_SIGNAL(clicked()), TQT_SLOT(stopJob()) );
+ hbLayout->addWidget( pbStop, 5 );
+
+ // close button
+ close = new TQPushButton( "&Close", main_widget );
+ close->setFixedSize( close->sizeHint() );
+ connect(close, TQT_SIGNAL(clicked()), this, TQT_SLOT(slotQuit()));
+
+ topLayout->addWidget( close, 5 );
+
+ main_widget->setMinimumSize( main_widget->sizeHint() );
+ setCentralWidget( main_widget );
+
+ slave = 0;
+// slave = TDEIO::Scheduler::getConnectedSlave(KURL("ftp://ftp.kde.org"));
+ TDEIO::Scheduler::connect(TQT_SIGNAL(slaveConnected(TDEIO::Slave*)),
+ this, TQT_SLOT(slotSlaveConnected()));
+ TDEIO::Scheduler::connect(TQT_SIGNAL(slaveError(TDEIO::Slave*,int,const TQString&)),
+ this, TQT_SLOT(slotSlaveError()));
+}
+
+
+void KioslaveTest::closeEvent( TQCloseEvent * ){
+ slotQuit();
+}
+
+
+void KioslaveTest::slotQuit(){
+ if ( job ) {
+ job->kill( true ); // kill the job quietly
+ }
+ if (slave)
+ TDEIO::Scheduler::disconnectSlave(slave);
+ kapp->quit();
+}
+
+
+void KioslaveTest::changeOperation( int id ) {
+ // only two urls for copy and move
+ bool enab = rbCopy->isChecked() || rbMove->isChecked();
+
+ le_dest->setEnabled( enab );
+
+ selectedOperation = id;
+}
+
+
+void KioslaveTest::changeProgressMode( int id ) {
+ progressMode = id;
+
+ if ( progressMode == ProgressStatus ) {
+ statusBar()->show();
+ } else {
+ statusBar()->hide();
+ }
+}
+
+
+void KioslaveTest::startJob() {
+ TQString sCurrent = TQDir::currentDirPath()+"/";
+ KURL::encode_string(sCurrent);
+ TQString sSrc( le_source->text() );
+ KURL src( sCurrent, sSrc );
+
+ if ( !src.isValid() ) {
+ TQMessageBox::critical(this, "Kioslave Error Message", "Source URL is malformed" );
+ return;
+ }
+
+ TQString sDest( le_dest->text() );
+ KURL dest( sCurrent, sDest );
+
+ if ( !dest.isValid() &&
+ ( selectedOperation == Copy || selectedOperation == Move ) ) {
+ TQMessageBox::critical(this, "Kioslave Error Message",
+ "Destination URL is malformed" );
+ return;
+ }
+
+ pbStart->setEnabled( false );
+
+ bool observe = true;
+ if (progressMode != ProgressDefault) {
+ observe = false;
+ }
+
+ SimpleJob *myJob = 0;
+
+ switch ( selectedOperation ) {
+ case List:
+ myJob = TDEIO::listDir( src );
+ connect(myJob, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
+ TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList&)));
+ break;
+
+ case ListRecursive:
+ myJob = TDEIO::listRecursive( src );
+ connect(myJob, TQT_SIGNAL( entries( TDEIO::Job*, const TDEIO::UDSEntryList&)),
+ TQT_SLOT( slotEntries( TDEIO::Job*, const TDEIO::UDSEntryList&)));
+ break;
+
+ case Stat:
+ myJob = TDEIO::stat( src, false, 2 );
+ break;
+
+ case Get:
+ myJob = TDEIO::get( src, true );
+ connect(myJob, TQT_SIGNAL( data( TDEIO::Job*, const TQByteArray &)),
+ TQT_SLOT( slotData( TDEIO::Job*, const TQByteArray &)));
+ break;
+
+ case Put:
+ putBuffer = 0;
+ myJob = TDEIO::put( src, -1, true, false);
+ connect(myJob, TQT_SIGNAL( dataReq( TDEIO::Job*, TQByteArray &)),
+ TQT_SLOT( slotDataReq( TDEIO::Job*, TQByteArray &)));
+ break;
+
+ case Copy:
+ job = TDEIO::copy( src, dest, observe );
+ break;
+
+ case Move:
+ job = TDEIO::move( src, dest, observe );
+ break;
+
+ case Delete:
+ job = TDEIO::del( src, false, observe );
+ break;
+
+ case Shred:
+ job = TDEIO::del(src, true, observe);
+ break;
+
+ case Mkdir:
+ myJob = TDEIO::mkdir( src );
+ break;
+
+ case Mimetype:
+ myJob = TDEIO::mimetype( src );
+ break;
+ }
+ if (myJob)
+ {
+ if (slave)
+ TDEIO::Scheduler::assignJobToSlave(slave, myJob);
+ job = myJob;
+ }
+
+ connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
+ TQT_SLOT( slotResult( TDEIO::Job * ) ) );
+
+ connect( job, TQT_SIGNAL( canceled( TDEIO::Job * ) ),
+ TQT_SLOT( slotResult( TDEIO::Job * ) ) );
+
+ if (progressMode == ProgressStatus) {
+ statusProgress->setJob( job );
+ }
+
+ pbStop->setEnabled( true );
+}
+
+
+void KioslaveTest::slotResult( TDEIO::Job * _job )
+{
+ if ( _job->error() )
+ {
+ _job->showErrorDialog();
+ }
+ else if ( selectedOperation == Stat )
+ {
+ UDSEntry entry = ((TDEIO::StatJob*)_job)->statResult();
+ printUDSEntry( entry );
+ }
+ else if ( selectedOperation == Mimetype )
+ {
+ kdDebug() << "mimetype is " << ((TDEIO::MimetypeJob*)_job)->mimetype() << endl;
+ }
+
+ if (job == _job)
+ job = 0L;
+ pbStart->setEnabled( true );
+ pbStop->setEnabled( false );
+}
+
+void KioslaveTest::slotSlaveConnected()
+{
+ kdDebug() << "Slave connected." << endl;
+}
+
+void KioslaveTest::slotSlaveError()
+{
+ kdDebug() << "Error connected." << endl;
+ slave = 0;
+}
+
+static void printACL( const TQString& acl )
+{
+ KACL kacl( acl );
+ kdDebug() << "According to KACL: " << endl << kacl.asString() << endl;
+ kdDebug() << "Owner: " << kacl.ownerPermissions() << endl;
+ kdDebug() << "Owning group: " << kacl.owningGroupPermissions() << endl;
+ kdDebug() << "Others: " << kacl.othersPermissions() << endl;
+}
+
+
+void KioslaveTest::printUDSEntry( const TDEIO::UDSEntry & entry )
+{
+ TDEIO::UDSEntry::ConstIterator it = entry.begin();
+ for( ; it != entry.end(); it++ ) {
+ switch ((*it).m_uds) {
+ case TDEIO::UDS_FILE_TYPE:
+ kdDebug() << "File Type : " << (mode_t)((*it).m_long) << endl;
+ if ( S_ISDIR( (mode_t)((*it).m_long) ) )
+ {
+ kdDebug() << "is a dir" << endl;
+ }
+ break;
+ case TDEIO::UDS_ACCESS:
+ kdDebug() << "Access permissions : " << (*it).m_long << endl;
+ break;
+ case TDEIO::UDS_EXTENDED_ACL:
+ if( (*it).m_long == 1 )
+ kdDebug() << "Has extended ACL information." << endl;
+ break;
+ case TDEIO::UDS_ACL_STRING:
+ kdDebug() << "ACL: " << ( (*it).m_str.ascii() ) << endl;
+ printACL( (*it).m_str );
+ break;
+ case TDEIO::UDS_DEFAULT_ACL_STRING:
+ kdDebug() << "Default ACL: " << ( (*it).m_str.ascii() ) << endl;
+ printACL( (*it).m_str );
+ break;
+ case TDEIO::UDS_USER:
+ kdDebug() << "User : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_GROUP:
+ kdDebug() << "Group : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_NAME:
+ kdDebug() << "Name : " << ((*it).m_str.ascii() ) << endl;
+ //m_strText = decodeFileName( (*it).m_str );
+ break;
+ case TDEIO::UDS_URL:
+ kdDebug() << "URL : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_MIME_TYPE:
+ kdDebug() << "MimeType : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_LINK_DEST:
+ kdDebug() << "LinkDest : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_SIZE:
+ kdDebug() << "Size: " << TDEIO::convertSize((*it).m_long) << endl;
+ break;
+ }
+ }
+}
+
+void KioslaveTest::slotEntries(TDEIO::Job* job, const TDEIO::UDSEntryList& list) {
+
+ KURL url = static_cast<TDEIO::ListJob*>( job )->url();
+ KProtocolInfo::ExtraFieldList extraFields = KProtocolInfo::extraFields(url);
+ UDSEntryListConstIterator it=list.begin();
+ for (; it != list.end(); ++it) {
+ // For each file...
+ KProtocolInfo::ExtraFieldList::Iterator extraFieldsIt = extraFields.begin();
+ UDSEntry::ConstIterator it2 = (*it).begin();
+ for( ; it2 != (*it).end(); it2++ ) {
+ if ((*it2).m_uds == UDS_NAME)
+ kdDebug() << "" << ( *it2 ).m_str << endl;
+ else if ( (*it2).m_uds == UDS_EXTRA) {
+ Q_ASSERT( extraFieldsIt != extraFields.end() );
+ TQString column = (*extraFieldsIt).name;
+ //TQString type = (*extraFieldsIt).type;
+ kdDebug() << " Extra data (" << column << ") :" << ( *it2 ).m_str << endl;
+ ++extraFieldsIt;
+ }
+ }
+ }
+}
+
+void KioslaveTest::slotData(TDEIO::Job*, const TQByteArray &data)
+{
+ if (data.size() == 0)
+ {
+ kdDebug(0) << "Data: <End>" << endl;
+ }
+ else
+ {
+ kdDebug(0) << "Data: \"" << TQCString(data, data.size()+1) << "\"" << endl;
+ }
+}
+
+void KioslaveTest::slotDataReq(TDEIO::Job*, TQByteArray &data)
+{
+ const char *fileDataArray[] =
+ {
+ "Hello world\n",
+ "This is a test file\n",
+ "You can safely delete it.\n",
+ "BIG\n",
+ 0
+ };
+ const char *fileData = fileDataArray[putBuffer++];
+
+ if (!fileData)
+ {
+ kdDebug(0) << "DataReq: <End>" << endl;
+ return;
+ }
+ if (!strcmp(fileData, "BIG\n"))
+ data.fill(0, 29*1024*1024);
+ else
+ data.duplicate(fileData, strlen(fileData));
+ kdDebug(0) << "DataReq: \"" << fileData << "\"" << endl;
+}
+
+void KioslaveTest::stopJob() {
+ kdDebug() << "KioslaveTest::stopJob()" << endl;
+ job->kill();
+ job = 0L;
+
+ pbStop->setEnabled( false );
+ pbStart->setEnabled( true );
+}
+
+static const char version[] = "v0.0.0 0000"; // :-)
+static const char description[] = "Test for tdeioslaves";
+static KCmdLineOptions options[] =
+{
+ { "s", 0, 0 },
+ { "src <src>", "Source URL", "" },
+ { "d", 0, 0 },
+ { "dest <dest>", "Destination URL", "" },
+ { "o", 0, 0 },
+ { "operation <operation>", "Operation (list,listrecursive,stat,get,put,copy,move,del,shred,mkdir)", "copy" },
+ { "p", 0, 0 },
+ { "progress <progress>", "Progress Type (none,default,status)", "default" },
+ KCmdLineLastOption
+};
+
+int main(int argc, char **argv) {
+ TDECmdLineArgs::init( argc, argv, "tdeioslavetest", description, version );
+ TDECmdLineArgs::addCmdLineOptions( options );
+ TDEApplication app;
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ TQString src = args->getOption("src");
+ TQString dest = args->getOption("dest");
+
+ uint op = 0;
+ uint pr = 0;
+
+ TQString tmps;
+
+ tmps = args->getOption("operation");
+ if ( tmps == "list") {
+ op = KioslaveTest::List;
+ } else if ( tmps == "listrecursive") {
+ op = KioslaveTest::ListRecursive;
+ } else if ( tmps == "stat") {
+ op = KioslaveTest::Stat;
+ } else if ( tmps == "get") {
+ op = KioslaveTest::Get;
+ } else if ( tmps == "put") {
+ op = KioslaveTest::Put;
+ } else if ( tmps == "copy") {
+ op = KioslaveTest::Copy;
+ } else if ( tmps == "move") {
+ op = KioslaveTest::Move;
+ } else if ( tmps == "del") {
+ op = KioslaveTest::Delete;
+ } else if ( tmps == "shred") {
+ op = KioslaveTest::Shred;
+ } else if ( tmps == "mkdir") {
+ op = KioslaveTest::Mkdir;
+ } else TDECmdLineArgs::usage("unknown operation");
+
+ tmps = args->getOption("progress");
+ if ( tmps == "none") {
+ pr = KioslaveTest::ProgressNone;
+ } else if ( tmps == "default") {
+ pr = KioslaveTest::ProgressDefault;
+ } else if ( tmps == "status") {
+ pr = KioslaveTest::ProgressStatus;
+ } else TDECmdLineArgs::usage("unknown progress mode");
+
+ args->clear(); // Free up memory
+
+ KioslaveTest test( src, dest, op, pr );
+ test.show();
+ // Bug in KTMW / Qt / layouts ?
+ test.resize( test.sizeHint() );
+
+ app.setMainWidget(&test);
+ app.exec();
+}
+
+
+#include "tdeioslavetest.moc"
diff --git a/tdeio/tests/tdeioslavetest.h b/tdeio/tests/tdeioslavetest.h
new file mode 100644
index 000000000..f2cb32af1
--- /dev/null
+++ b/tdeio/tests/tdeioslavetest.h
@@ -0,0 +1,108 @@
+ /*
+ This file is or will be part of KDE desktop environment
+
+ Copyright 1999 Matt Koss <koss@miesto.sk>
+
+ It is licensed under GPL version 2.
+
+ If it is part of KDE libraries than this file is licensed under
+ LGPL version 2.
+ */
+
+#ifndef _KIOSLAVETEST_H
+#define _KIOSLAVETEST_H
+
+#include <tqlabel.h>
+#include <tqlineedit.h>
+#include <tqradiobutton.h>
+#include <tqpushbutton.h>
+#include <tqbuttongroup.h>
+#include <tqwidget.h>
+
+#include <kmainwindow.h>
+
+#include "tdeio/job.h"
+#include "tdeio/global.h"
+#include "tdeio/statusbarprogress.h"
+#include "tdeio/slave.h"
+
+class KioslaveTest : public KMainWindow {
+ Q_OBJECT
+
+public:
+ KioslaveTest( TQString src, TQString dest, uint op, uint pr );
+ ~KioslaveTest() {}
+
+ enum Operations { List, ListRecursive, Stat, Get, Put, Copy, Move, Delete, Shred, Mkdir, Mimetype };
+
+ enum ProgressModes { ProgressNone, ProgressDefault, ProgressStatus };
+
+protected:
+
+ void closeEvent( TQCloseEvent * );
+
+ void printUDSEntry( const TDEIO::UDSEntry & entry );
+
+ // info stuff
+ TQLabel *lb_from;
+ TQLineEdit *le_source;
+
+ TQLabel *lb_to;
+ TQLineEdit *le_dest;
+
+ // operation stuff
+ TQButtonGroup *opButtons;
+
+ TQRadioButton *rbList;
+ TQRadioButton *rbListRecursive;
+ TQRadioButton *rbStat;
+ TQRadioButton *rbGet;
+ TQRadioButton *rbPut;
+ TQRadioButton *rbCopy;
+ TQRadioButton *rbMove;
+ TQRadioButton *rbDelete;
+ TQRadioButton *rbShred;
+ TQRadioButton *rbMkdir;
+ TQRadioButton *rbMimetype;
+
+ // progress stuff
+ TQButtonGroup *progressButtons;
+
+ TQRadioButton *rbProgressNone;
+ TQRadioButton *rbProgressDefault;
+ TQRadioButton *rbProgressStatus;
+
+ TQPushButton *pbStart;
+ TQPushButton *pbStop;
+
+ TQPushButton *close;
+
+protected slots:
+ void changeOperation( int id );
+ void changeProgressMode( int id );
+
+ void startJob();
+ void stopJob();
+
+ void slotResult( TDEIO::Job * );
+ void slotEntries( TDEIO::Job *, const TDEIO::UDSEntryList& );
+ void slotData( TDEIO::Job *, const TQByteArray &data );
+ void slotDataReq( TDEIO::Job *, TQByteArray &data );
+
+ void slotQuit();
+ void slotSlaveConnected();
+ void slotSlaveError();
+
+private:
+ TDEIO::Job *job;
+ TQWidget *main_widget;
+
+ TDEIO::StatusbarProgress *statusProgress;
+
+ int selectedOperation;
+ int progressMode;
+ int putBuffer;
+ TDEIO::Slave *slave;
+};
+
+#endif // _KIOSLAVETEST_H
diff --git a/kio/tests/tdesycocatest.cpp b/tdeio/tests/tdesycocatest.cpp
index 45f94ac3c..45f94ac3c 100644
--- a/kio/tests/tdesycocatest.cpp
+++ b/tdeio/tests/tdesycocatest.cpp
diff --git a/kio/tests/tdesycocaupdatetest.cpp b/tdeio/tests/tdesycocaupdatetest.cpp
index e7778e056..e7778e056 100644
--- a/kio/tests/tdesycocaupdatetest.cpp
+++ b/tdeio/tests/tdesycocaupdatetest.cpp
diff --git a/tdeio/tests/tdetradertest.cpp b/tdeio/tests/tdetradertest.cpp
new file mode 100644
index 000000000..c0092f76d
--- /dev/null
+++ b/tdeio/tests/tdetradertest.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2002, 2003 David Faure <faure@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation;
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include <kcmdlineargs.h>
+#include <ktrader.h>
+#include <kmimetype.h>
+#include <kapplication.h>
+#include <stdio.h>
+
+static KCmdLineOptions options[] =
+{
+ { "+query", "the query", 0 },
+ { "+[genericServiceType]", "Application (default), or KParts/ReadOnlyPart", 0 },
+ { "+[constraint]", "constraint", 0 },
+ { "+[preference]", "preference", 0 },
+ KCmdLineLastOption
+};
+
+int main( int argc, char **argv )
+{
+ TDECmdLineArgs::init( argc, argv, "tdetradertest", "KTradertest", "A KTrader testing tool", "0.0" );
+
+ TDECmdLineArgs::addCmdLineOptions( options );
+
+ TDEApplication app( false, false ); // no GUI
+
+ TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();
+
+ if ( args->count() < 1 )
+ TDECmdLineArgs::usage();
+
+ TQString query = TQString::fromLocal8Bit( args->arg( 0 ) );
+
+ TQString genericServiceType, constraint, preference;
+
+ if ( args->count() >= 2 )
+ genericServiceType = TQString::fromLocal8Bit( args->arg( 1 ) );
+
+ if ( args->count() >= 3 )
+ constraint = TQString::fromLocal8Bit( args->arg( 2 ) );
+
+ if ( args->count() == 4 )
+ preference = TQString::fromLocal8Bit( args->arg( 3 ) );
+
+ printf( "query is : %s\n", query.local8Bit().data() );
+ printf( "genericServiceType is : %s\n", genericServiceType.local8Bit().data() );
+ printf( "constraint is : %s\n", constraint.local8Bit().data() );
+ printf( "preference is : %s\n", preference.local8Bit().data() );
+
+ KTrader::OfferList offers = KTrader::self()->query( query, genericServiceType, constraint, preference );
+
+ printf("got %d offers.\n", offers.count());
+
+ int i = 0;
+ KTrader::OfferList::ConstIterator it = offers.begin();
+ KTrader::OfferList::ConstIterator end = offers.end();
+ for (; it != end; ++it, ++i )
+ {
+ printf("---- Offer %d ----\n", i);
+ TQStringList props = (*it)->propertyNames();
+ TQStringList::ConstIterator propIt = props.begin();
+ TQStringList::ConstIterator propEnd = props.end();
+ for (; propIt != propEnd; ++propIt )
+ {
+ TQVariant prop = (*it)->property( *propIt );
+
+ if ( !prop.isValid() )
+ {
+ printf("Invalid property %s\n", (*propIt).local8Bit().data());
+ continue;
+ }
+
+ TQString outp = *propIt;
+ outp += " : '";
+
+ switch ( prop.type() )
+ {
+ case TQVariant::StringList:
+ outp += prop.toStringList().join(" - ");
+ break;
+ case TQVariant::Bool:
+ outp += prop.toBool() ? "TRUE" : "FALSE";
+ break;
+ default:
+ outp += prop.toString();
+ break;
+ }
+
+ if ( !outp.isEmpty() )
+ printf("%s'\n", outp.local8Bit().data());
+ }
+ }
+}
diff --git a/kio/tests/wronglocalsizes.zip b/tdeio/tests/wronglocalsizes.zip
index 3f76738ba..3f76738ba 100644
--- a/kio/tests/wronglocalsizes.zip
+++ b/tdeio/tests/wronglocalsizes.zip
Binary files differ
diff --git a/kio/useragent.pl b/tdeio/useragent.pl
index f31e31e1d..f31e31e1d 100755
--- a/kio/useragent.pl
+++ b/tdeio/useragent.pl
diff --git a/kioslave/CMakeLists.txt b/tdeioslave/CMakeLists.txt
index 4c7bfe1c4..4c7bfe1c4 100644
--- a/kioslave/CMakeLists.txt
+++ b/tdeioslave/CMakeLists.txt
diff --git a/kioslave/Mainpage.dox b/tdeioslave/Mainpage.dox
index 44979b667..44979b667 100644
--- a/kioslave/Mainpage.dox
+++ b/tdeioslave/Mainpage.dox
diff --git a/kioslave/Makefile.am b/tdeioslave/Makefile.am
index e6472a9c8..e6472a9c8 100644
--- a/kioslave/Makefile.am
+++ b/tdeioslave/Makefile.am
diff --git a/tdeioslave/bzip2/CMakeLists.txt b/tdeioslave/bzip2/CMakeLists.txt
new file mode 100644
index 000000000..22b904ffa
--- /dev/null
+++ b/tdeioslave/bzip2/CMakeLists.txt
@@ -0,0 +1,42 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install( FILES kbzip2filter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+##### kbzip2filter ##############################
+
+set( target kbzip2filter )
+
+set( ${target}_SRCS
+ kbzip2filter.cpp
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared ${BZIP2_LIBRARIES}
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/tdeioslave/bzip2/Makefile.am b/tdeioslave/bzip2/Makefile.am
new file mode 100644
index 000000000..963f27e31
--- /dev/null
+++ b/tdeioslave/bzip2/Makefile.am
@@ -0,0 +1,11 @@
+INCLUDES = -I$(top_srcdir)/tdeio $(all_includes)
+METASOURCES = AUTO
+
+kde_module_LTLIBRARIES = kbzip2filter.la
+
+kbzip2filter_la_SOURCES = kbzip2filter.cpp
+kbzip2filter_la_LIBADD = $(LIB_KIO) $(LIBBZ2) $(LIB_QT) $(LIB_TDECORE)
+kbzip2filter_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
+
+kde_services_DATA = kbzip2filter.desktop
+
diff --git a/kioslave/bzip2/configure.in.in b/tdeioslave/bzip2/configure.in.in
index 99392042d..99392042d 100644
--- a/kioslave/bzip2/configure.in.in
+++ b/tdeioslave/bzip2/configure.in.in
diff --git a/kioslave/bzip2/kbzip2filter.cpp b/tdeioslave/bzip2/kbzip2filter.cpp
index ae72990d8..ae72990d8 100644
--- a/kioslave/bzip2/kbzip2filter.cpp
+++ b/tdeioslave/bzip2/kbzip2filter.cpp
diff --git a/kioslave/bzip2/kbzip2filter.desktop b/tdeioslave/bzip2/kbzip2filter.desktop
index 51f1c0a84..51f1c0a84 100644
--- a/kioslave/bzip2/kbzip2filter.desktop
+++ b/tdeioslave/bzip2/kbzip2filter.desktop
diff --git a/kioslave/bzip2/kbzip2filter.h b/tdeioslave/bzip2/kbzip2filter.h
index 2a7b13cf3..2a7b13cf3 100644
--- a/kioslave/bzip2/kbzip2filter.h
+++ b/tdeioslave/bzip2/kbzip2filter.h
diff --git a/tdeioslave/file/CMakeLists.txt b/tdeioslave/file/CMakeLists.txt
new file mode 100644
index 000000000..0392de535
--- /dev/null
+++ b/tdeioslave/file/CMakeLists.txt
@@ -0,0 +1,55 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+add_definitions(
+ -D_LARGEFILE64_SOURCE
+)
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### headers ###################################
+
+install( FILES file.h DESTINATION ${INCLUDE_INSTALL_DIR}/tdeio )
+
+
+##### other data ################################
+
+install( FILES file.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+##### kio_file ##################################
+
+set( target kio_file )
+
+set( ${target}_SRCS
+ file.cc
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
+
diff --git a/tdeioslave/file/Makefile.am b/tdeioslave/file/Makefile.am
new file mode 100644
index 000000000..518b79f46
--- /dev/null
+++ b/tdeioslave/file/Makefile.am
@@ -0,0 +1,22 @@
+## Makefile.am of tdebase/tdeioslave/file
+
+AM_CPPFLAGS = -D_LARGEFILE64_SOURCE
+
+INCLUDES = $(all_includes)
+
+####### Files
+
+kde_module_LTLIBRARIES = kio_file.la
+
+kio_file_la_SOURCES = file.cc
+kio_file_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE) $(ACL_LIBS)
+kio_file_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN) $(top_builddir)/dcop/libDCOP.la
+noinst_HEADERS = file.h
+
+fileinclude_HEADERS = file.h
+fileincludedir = $(includedir)/tdeio
+
+METASOURCES = AUTO
+
+kdelnkdir = $(kde_servicesdir)
+kdelnk_DATA = file.protocol
diff --git a/tdeioslave/file/file.cc b/tdeioslave/file/file.cc
new file mode 100644
index 000000000..499a69330
--- /dev/null
+++ b/tdeioslave/file/file.cc
@@ -0,0 +1,1831 @@
+/*
+ Copyright (C) 2000-2002 Stephan Kulow <coolo@kde.org>
+ Copyright (C) 2000-2002 David Faure <faure@kde.org>
+ Copyright (C) 2000-2002 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License (LGPL) as published by the Free Software Foundation;
+ either version 2 of the License, or (at your option) any later
+ version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#include <config.h>
+
+#include <tqglobal.h> //for Q_OS_XXX
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+//sendfile has different semantics in different platforms
+#if defined HAVE_SENDFILE && defined Q_OS_LINUX
+#define USE_SENDFILE 1
+#endif
+
+#ifdef USE_SENDFILE
+#include <sys/sendfile.h>
+#endif
+
+#ifdef USE_POSIX_ACL
+#include <sys/acl.h>
+#ifdef HAVE_NON_POSIX_ACL_EXTENSIONS
+#include <acl/libacl.h>
+#else
+#include <posixacladdons.h>
+#endif
+#endif
+
+#include <assert.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <grp.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <time.h>
+#include <utime.h>
+#include <unistd.h>
+#ifdef HAVE_STRING_H
+#include <string.h>
+#endif
+
+#include <tqvaluelist.h>
+#include <tqregexp.h>
+
+#include <dcopref.h>
+#include <kshred.h>
+#include <kdebug.h>
+#include <kurl.h>
+#include <kinstance.h>
+#include <ksimpleconfig.h>
+#include <ktempfile.h>
+#include <klocale.h>
+#include <tqfile.h>
+#include <tqstrlist.h>
+#include "file.h"
+#include <limits.h>
+#include <kprocess.h>
+#include <kmountpoint.h>
+#include <kstandarddirs.h>
+
+#ifdef HAVE_VOLMGT
+#include <volmgt.h>
+#include <sys/mnttab.h>
+#endif
+
+#include <kstandarddirs.h>
+#include <tdeio/ioslave_defaults.h>
+#include <klargefile.h>
+#include <kglobal.h>
+#include <kmimetype.h>
+
+using namespace TDEIO;
+
+#define MAX_IPC_SIZE (1024*32)
+
+static TQString testLogFile( const char *_filename );
+#ifdef USE_POSIX_ACL
+static TQString aclAsString( acl_t p_acl );
+static bool isExtendedACL( acl_t p_acl );
+static void appendACLAtoms( const TQCString & path, UDSEntry& entry,
+ mode_t type, bool withACL );
+#endif
+
+extern "C" { KDE_EXPORT int kdemain(int argc, char **argv); }
+
+int kdemain( int argc, char **argv )
+{
+ KLocale::setMainCatalogue("tdelibs");
+ TDEInstance instance( "kio_file" );
+ ( void ) TDEGlobal::locale();
+
+ kdDebug(7101) << "Starting " << getpid() << endl;
+
+ if (argc != 4)
+ {
+ fprintf(stderr, "Usage: kio_file protocol domain-socket1 domain-socket2\n");
+ exit(-1);
+ }
+
+ FileProtocol slave(argv[2], argv[3]);
+ slave.dispatchLoop();
+
+ kdDebug(7101) << "Done" << endl;
+ return 0;
+}
+
+
+FileProtocol::FileProtocol( const TQCString &pool, const TQCString &app ) : SlaveBase( "file", pool, app )
+{
+ usercache.setAutoDelete( true );
+ groupcache.setAutoDelete( true );
+}
+
+
+int FileProtocol::setACL( const char *path, mode_t perm, bool directoryDefault )
+{
+ int ret = 0;
+#ifdef USE_POSIX_ACL
+
+ const TQString ACLString = metaData( "ACL_STRING" );
+ const TQString defaultACLString = metaData( "DEFAULT_ACL_STRING" );
+ // Empty strings mean leave as is
+ if ( !ACLString.isEmpty() ) {
+ acl_t acl = 0;
+ if ( ACLString == "ACL_DELETE" ) {
+ // user told us to delete the extended ACL, so let's write only
+ // the minimal (UNIX permission bits) part
+ acl = acl_from_mode( perm );
+ }
+ acl = acl_from_text( ACLString.latin1() );
+ if ( acl_valid( acl ) == 0 ) { // let's be safe
+ ret = acl_set_file( path, ACL_TYPE_ACCESS, acl );
+ kdDebug(7101) << "Set ACL on: " << path << " to: " << aclAsString( acl ) << endl;
+ }
+ acl_free( acl );
+ if ( ret != 0 ) return ret; // better stop trying right away
+ }
+
+ if ( directoryDefault && !defaultACLString.isEmpty() ) {
+ if ( defaultACLString == "ACL_DELETE" ) {
+ // user told us to delete the default ACL, do so
+ ret += acl_delete_def_file( path );
+ } else {
+ acl_t acl = acl_from_text( defaultACLString.latin1() );
+ if ( acl_valid( acl ) == 0 ) { // let's be safe
+ ret += acl_set_file( path, ACL_TYPE_DEFAULT, acl );
+ kdDebug(7101) << "Set Default ACL on: " << path << " to: " << aclAsString( acl ) << endl;
+ }
+ acl_free( acl );
+ }
+ }
+#endif
+ return ret;
+}
+
+void FileProtocol::chmod( const KURL& url, int permissions )
+{
+ TQCString _path( TQFile::encodeName(url.path()) );
+ /* FIXME: Should be atomic */
+ if ( ::chmod( _path.data(), permissions ) == -1 ||
+ ( setACL( _path.data(), permissions, false ) == -1 ) ||
+ /* if not a directory, cannot set default ACLs */
+ ( setACL( _path.data(), permissions, true ) == -1 && errno != ENOTDIR ) ) {
+
+ switch (errno) {
+ case EPERM:
+ case EACCES:
+ error( TDEIO::ERR_ACCESS_DENIED, url.path() );
+ break;
+ case ENOTSUP:
+ error( TDEIO::ERR_UNSUPPORTED_ACTION, url.path() );
+ break;
+ case ENOSPC:
+ error( TDEIO::ERR_DISK_FULL, url.path() );
+ break;
+ default:
+ error( TDEIO::ERR_CANNOT_CHMOD, url.path() );
+ }
+ } else
+ finished();
+}
+
+void FileProtocol::mkdir( const KURL& url, int permissions )
+{
+ TQCString _path( TQFile::encodeName(url.path()));
+
+ kdDebug(7101) << "mkdir(): " << _path << ", permission = " << permissions << endl;
+
+ KDE_struct_stat buff;
+ if ( KDE_stat( _path.data(), &buff ) == -1 ) {
+ if ( ::mkdir( _path.data(), 0777 /*umask will be applied*/ ) != 0 ) {
+ if ( errno == EACCES ) {
+ error( TDEIO::ERR_ACCESS_DENIED, url.path() );
+ return;
+ } else if ( errno == ENOSPC ) {
+ error( TDEIO::ERR_DISK_FULL, url.path() );
+ return;
+ } else {
+ error( TDEIO::ERR_COULD_NOT_MKDIR, url.path() );
+ return;
+ }
+ } else {
+ if ( permissions != -1 )
+ chmod( url, permissions );
+ else
+ finished();
+ return;
+ }
+ }
+
+ if ( S_ISDIR( buff.st_mode ) ) {
+ kdDebug(7101) << "ERR_DIR_ALREADY_EXIST" << endl;
+ error( TDEIO::ERR_DIR_ALREADY_EXIST, url.path() );
+ return;
+ }
+ error( TDEIO::ERR_FILE_ALREADY_EXIST, url.path() );
+ return;
+}
+
+void FileProtocol::get( const KURL& url )
+{
+ if (!url.isLocalFile()) {
+ KURL redir(url);
+ redir.setProtocol(config()->readEntry("DefaultRemoteProtocol", "smb"));
+ redirection(redir);
+ finished();
+ return;
+ }
+
+ TQCString _path( TQFile::encodeName(url.path()));
+ KDE_struct_stat buff;
+ if ( KDE_stat( _path.data(), &buff ) == -1 ) {
+ if ( errno == EACCES )
+ error( TDEIO::ERR_ACCESS_DENIED, url.path() );
+ else
+ error( TDEIO::ERR_DOES_NOT_EXIST, url.path() );
+ return;
+ }
+
+ if ( S_ISDIR( buff.st_mode ) ) {
+ error( TDEIO::ERR_IS_DIRECTORY, url.path() );
+ return;
+ }
+ if ( !S_ISREG( buff.st_mode ) ) {
+ error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, url.path() );
+ return;
+ }
+
+ int fd = KDE_open( _path.data(), O_RDONLY);
+ if ( fd < 0 ) {
+ error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, url.path() );
+ return;
+ }
+
+#ifdef HAVE_FADVISE
+ posix_fadvise( fd, 0, 0, POSIX_FADV_SEQUENTIAL);
+#endif
+
+ // Determine the mimetype of the file to be retrieved, and emit it.
+ // This is mandatory in all slaves (for KRun/BrowserRun to work).
+ KMimeType::Ptr mt = KMimeType::findByURL( url, buff.st_mode, true /* local URL */ );
+ emit mimeType( mt->name() );
+
+ TDEIO::filesize_t processed_size = 0;
+
+ TQString resumeOffset = metaData("resume");
+ if ( !resumeOffset.isEmpty() )
+ {
+ bool ok;
+ TDEIO::fileoffset_t offset = resumeOffset.toLongLong(&ok);
+ if (ok && (offset > 0) && (offset < buff.st_size))
+ {
+ if (KDE_lseek(fd, offset, SEEK_SET) == offset)
+ {
+ canResume ();
+ processed_size = offset;
+ kdDebug( 7101 ) << "Resume offset: " << TDEIO::number(offset) << endl;
+ }
+ }
+ }
+
+ totalSize( buff.st_size );
+
+ char buffer[ MAX_IPC_SIZE ];
+ TQByteArray array;
+
+ while( 1 )
+ {
+ int n = ::read( fd, buffer, MAX_IPC_SIZE );
+ if (n == -1)
+ {
+ if (errno == EINTR)
+ continue;
+ error( TDEIO::ERR_COULD_NOT_READ, url.path());
+ close(fd);
+ return;
+ }
+ if (n == 0)
+ break; // Finished
+
+ array.setRawData(buffer, n);
+ data( array );
+ array.resetRawData(buffer, n);
+
+ processed_size += n;
+ processedSize( processed_size );
+
+ //kdDebug( 7101 ) << "Processed: " << TDEIO::number (processed_size) << endl;
+ }
+
+ data( TQByteArray() );
+
+ close( fd );
+
+ processedSize( buff.st_size );
+ finished();
+}
+
+static int
+write_all(int fd, const char *buf, size_t len)
+{
+ while (len > 0)
+ {
+ ssize_t written = write(fd, buf, len);
+ if (written < 0)
+ {
+ if (errno == EINTR)
+ continue;
+ return -1;
+ }
+ buf += written;
+ len -= written;
+ }
+ return 0;
+}
+
+static bool
+same_inode(const KDE_struct_stat &src, const KDE_struct_stat &dest)
+{
+ if (src.st_ino == dest.st_ino &&
+ src.st_dev == dest.st_dev)
+ return true;
+
+ return false;
+}
+
+void FileProtocol::put( const KURL& url, int _mode, bool _overwrite, bool _resume )
+{
+ TQString dest_orig = url.path();
+ TQCString _dest_orig( TQFile::encodeName(dest_orig));
+
+ kdDebug(7101) << "put(): " << dest_orig << ", mode=" << _mode << endl;
+
+ TQString dest_part( dest_orig );
+ dest_part += TQString::fromLatin1(".part");
+ TQCString _dest_part( TQFile::encodeName(dest_part));
+
+ KDE_struct_stat buff_orig;
+ bool bOrigExists = (KDE_lstat( _dest_orig.data(), &buff_orig ) != -1);
+ bool bPartExists = false;
+ bool bMarkPartial = config()->readBoolEntry("MarkPartial", true);
+
+ if (bMarkPartial)
+ {
+ KDE_struct_stat buff_part;
+ bPartExists = (KDE_stat( _dest_part.data(), &buff_part ) != -1);
+
+ if (bPartExists && !_resume && !_overwrite && buff_part.st_size > 0 && S_ISREG(buff_part.st_mode))
+ {
+ kdDebug(7101) << "FileProtocol::put : calling canResume with "
+ << TDEIO::number(buff_part.st_size) << endl;
+
+ // Maybe we can use this partial file for resuming
+ // Tell about the size we have, and the app will tell us
+ // if it's ok to resume or not.
+ _resume = canResume( buff_part.st_size );
+
+ kdDebug(7101) << "FileProtocol::put got answer " << _resume << endl;
+ }
+ }
+
+ if ( bOrigExists && !_overwrite && !_resume)
+ {
+ if (S_ISDIR(buff_orig.st_mode))
+ error( TDEIO::ERR_DIR_ALREADY_EXIST, dest_orig );
+ else
+ error( TDEIO::ERR_FILE_ALREADY_EXIST, dest_orig );
+ return;
+ }
+
+ int result;
+ TQString dest;
+ TQCString _dest;
+
+ int fd = -1;
+
+ // Loop until we got 0 (end of data)
+ do
+ {
+ TQByteArray buffer;
+ dataReq(); // Request for data
+ result = readData( buffer );
+
+ if (result >= 0)
+ {
+ if (dest.isEmpty())
+ {
+ if (bMarkPartial)
+ {
+ kdDebug(7101) << "Appending .part extension to " << dest_orig << endl;
+ dest = dest_part;
+ if ( bPartExists && !_resume )
+ {
+ kdDebug(7101) << "Deleting partial file " << dest_part << endl;
+ remove( _dest_part.data() );
+ // Catch errors when we try to open the file.
+ }
+ }
+ else
+ {
+ dest = dest_orig;
+ if ( bOrigExists && !_resume )
+ {
+ kdDebug(7101) << "Deleting destination file " << dest_orig << endl;
+ remove( _dest_orig.data() );
+ // Catch errors when we try to open the file.
+ }
+ }
+
+ _dest = TQFile::encodeName(dest);
+
+ if ( _resume )
+ {
+ fd = KDE_open( _dest.data(), O_RDWR ); // append if resuming
+ KDE_lseek(fd, 0, SEEK_END); // Seek to end
+ }
+ else
+ {
+ // WABA: Make sure that we keep writing permissions ourselves,
+ // otherwise we can be in for a surprise on NFS.
+ mode_t initialMode;
+ if (_mode != -1)
+ initialMode = _mode | S_IWUSR | S_IRUSR;
+ else
+ initialMode = 0666;
+
+ fd = KDE_open(_dest.data(), O_CREAT | O_TRUNC | O_WRONLY, initialMode);
+ }
+
+ if ( fd < 0 )
+ {
+ kdDebug(7101) << "####################### COULD NOT WRITE " << dest << " _mode=" << _mode << endl;
+ kdDebug(7101) << "errno==" << errno << "(" << strerror(errno) << ")" << endl;
+ if ( errno == EACCES )
+ error( TDEIO::ERR_WRITE_ACCESS_DENIED, dest );
+ else
+ error( TDEIO::ERR_CANNOT_OPEN_FOR_WRITING, dest );
+ return;
+ }
+ }
+
+ if (write_all( fd, buffer.data(), buffer.size()))
+ {
+ if ( errno == ENOSPC ) // disk full
+ {
+ error( TDEIO::ERR_DISK_FULL, dest_orig);
+ result = -2; // means: remove dest file
+ }
+ else
+ {
+ kdWarning(7101) << "Couldn't write. Error:" << strerror(errno) << endl;
+ error( TDEIO::ERR_COULD_NOT_WRITE, dest_orig);
+ result = -1;
+ }
+ }
+ }
+ }
+ while ( result > 0 );
+
+ // An error occurred deal with it.
+ if (result < 0)
+ {
+ kdDebug(7101) << "Error during 'put'. Aborting." << endl;
+
+ if (fd != -1)
+ {
+ close(fd);
+
+ KDE_struct_stat buff;
+ if (bMarkPartial && KDE_stat( _dest.data(), &buff ) == 0)
+ {
+ int size = config()->readNumEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE);
+ if (buff.st_size < size)
+ remove(_dest.data());
+ }
+ }
+
+ ::exit(255);
+ }
+
+ if ( fd == -1 ) // we got nothing to write out, so we never opened the file
+ {
+ finished();
+ return;
+ }
+
+ if ( close(fd) )
+ {
+ kdWarning(7101) << "Error when closing file descriptor:" << strerror(errno) << endl;
+ error( TDEIO::ERR_COULD_NOT_WRITE, dest_orig);
+ return;
+ }
+
+ // after full download rename the file back to original name
+ if ( bMarkPartial )
+ {
+ // If the original URL is a symlink and we were asked to overwrite it,
+ // remove the symlink first. This ensures that we do not overwrite the
+ // current source if the symlink points to it.
+ if( _overwrite && S_ISLNK( buff_orig.st_mode ) )
+ remove( _dest_orig.data() );
+
+ if ( ::rename( _dest.data(), _dest_orig.data() ) )
+ {
+ kdWarning(7101) << " Couldn't rename " << _dest << " to " << _dest_orig << endl;
+ error( TDEIO::ERR_CANNOT_RENAME_PARTIAL, dest_orig );
+ return;
+ }
+ }
+
+ // set final permissions
+ if ( _mode != -1 && !_resume )
+ {
+ if (::chmod(_dest_orig.data(), _mode) != 0)
+ {
+ // couldn't chmod. Eat the error if the filesystem apparently doesn't support it.
+ if ( TDEIO::testFileSystemFlag( _dest_orig, TDEIO::SupportsChmod ) )
+ warning( i18n( "Could not change permissions for\n%1" ).arg( dest_orig ) );
+ }
+ }
+
+ // set modification time
+ const TQString mtimeStr = metaData( "modified" );
+ if ( !mtimeStr.isEmpty() ) {
+ TQDateTime dt = TQT_TQDATETIME_OBJECT(TQDateTime::fromString( mtimeStr, Qt::ISODate ));
+ if ( dt.isValid() ) {
+ KDE_struct_stat dest_statbuf;
+ if (KDE_stat( _dest_orig.data(), &dest_statbuf ) == 0) {
+ struct utimbuf utbuf;
+ utbuf.actime = dest_statbuf.st_atime; // access time, unchanged
+ utbuf.modtime = dt.toTime_t(); // modification time
+ kdDebug() << k_funcinfo << "setting modtime to " << utbuf.modtime << endl;
+ utime( _dest_orig.data(), &utbuf );
+ }
+ }
+
+ }
+
+ // We have done our job => finish
+ finished();
+}
+
+
+void FileProtocol::copy( const KURL &src, const KURL &dest,
+ int _mode, bool _overwrite )
+{
+ kdDebug(7101) << "copy(): " << src << " -> " << dest << ", mode=" << _mode << endl;
+
+ TQCString _src( TQFile::encodeName(src.path()));
+ TQCString _dest( TQFile::encodeName(dest.path()));
+ KDE_struct_stat buff_src;
+#ifdef USE_POSIX_ACL
+ acl_t acl;
+#endif
+
+ if ( KDE_stat( _src.data(), &buff_src ) == -1 ) {
+ if ( errno == EACCES )
+ error( TDEIO::ERR_ACCESS_DENIED, src.path() );
+ else
+ error( TDEIO::ERR_DOES_NOT_EXIST, src.path() );
+ return;
+ }
+
+ if ( S_ISDIR( buff_src.st_mode ) ) {
+ error( TDEIO::ERR_IS_DIRECTORY, src.path() );
+ return;
+ }
+ if ( S_ISFIFO( buff_src.st_mode ) || S_ISSOCK ( buff_src.st_mode ) ) {
+ error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, src.path() );
+ return;
+ }
+
+ KDE_struct_stat buff_dest;
+ bool dest_exists = ( KDE_lstat( _dest.data(), &buff_dest ) != -1 );
+ if ( dest_exists )
+ {
+ if (S_ISDIR(buff_dest.st_mode))
+ {
+ error( TDEIO::ERR_DIR_ALREADY_EXIST, dest.path() );
+ return;
+ }
+
+ if ( same_inode( buff_dest, buff_src) )
+ {
+ error( TDEIO::ERR_IDENTICAL_FILES, dest.path() );
+ return;
+ }
+
+ if (!_overwrite)
+ {
+ error( TDEIO::ERR_FILE_ALREADY_EXIST, dest.path() );
+ return;
+ }
+
+ // If the destination is a symlink and overwrite is TRUE,
+ // remove the symlink first to prevent the scenario where
+ // the symlink actually points to current source!
+ if (_overwrite && S_ISLNK(buff_dest.st_mode))
+ {
+ kdDebug(7101) << "copy(): LINK DESTINATION" << endl;
+ remove( _dest.data() );
+ }
+ }
+
+ int src_fd = KDE_open( _src.data(), O_RDONLY);
+ if ( src_fd < 0 ) {
+ error( TDEIO::ERR_CANNOT_OPEN_FOR_READING, src.path() );
+ return;
+ }
+
+#ifdef HAVE_FADVISE
+ posix_fadvise(src_fd,0,0,POSIX_FADV_SEQUENTIAL);
+#endif
+ // WABA: Make sure that we keep writing permissions ourselves,
+ // otherwise we can be in for a surprise on NFS.
+ mode_t initialMode;
+ if (_mode != -1)
+ initialMode = _mode | S_IWUSR;
+ else
+ initialMode = 0666;
+
+ int dest_fd = KDE_open(_dest.data(), O_CREAT | O_TRUNC | O_WRONLY, initialMode);
+ if ( dest_fd < 0 ) {
+ kdDebug(7101) << "###### COULD NOT WRITE " << dest.url() << endl;
+ if ( errno == EACCES ) {
+ error( TDEIO::ERR_WRITE_ACCESS_DENIED, dest.path() );
+ } else {
+ error( TDEIO::ERR_CANNOT_OPEN_FOR_WRITING, dest.path() );
+ }
+ close(src_fd);
+ return;
+ }
+
+#ifdef HAVE_FADVISE
+ posix_fadvise(dest_fd,0,0,POSIX_FADV_SEQUENTIAL);
+#endif
+
+#ifdef USE_POSIX_ACL
+ acl = acl_get_fd(src_fd);
+ if ( acl && !isExtendedACL( acl ) ) {
+ kdDebug(7101) << _dest.data() << " doesn't have extended ACL" << endl;
+ acl_free( acl );
+ acl = NULL;
+ }
+#endif
+ totalSize( buff_src.st_size );
+
+ TDEIO::filesize_t processed_size = 0;
+ char buffer[ MAX_IPC_SIZE ];
+ int n;
+#ifdef USE_SENDFILE
+ bool use_sendfile=buff_src.st_size < 0x7FFFFFFF;
+#endif
+ while( 1 )
+ {
+#ifdef USE_SENDFILE
+ if (use_sendfile) {
+ off_t sf = processed_size;
+ n = ::sendfile( dest_fd, src_fd, &sf, MAX_IPC_SIZE );
+ processed_size = sf;
+ if ( n == -1 && errno == EINVAL ) { //not all filesystems support sendfile()
+ kdDebug(7101) << "sendfile() not supported, falling back " << endl;
+ use_sendfile = false;
+ }
+ }
+ if (!use_sendfile)
+#endif
+ n = ::read( src_fd, buffer, MAX_IPC_SIZE );
+
+ if (n == -1)
+ {
+ if (errno == EINTR)
+ continue;
+#ifdef USE_SENDFILE
+ if ( use_sendfile ) {
+ kdDebug(7101) << "sendfile() error:" << strerror(errno) << endl;
+ if ( errno == ENOSPC ) // disk full
+ {
+ error( TDEIO::ERR_DISK_FULL, dest.path());
+ remove( _dest.data() );
+ }
+ else {
+ error( TDEIO::ERR_SLAVE_DEFINED,
+ i18n("Cannot copy file from %1 to %2. (Errno: %3)")
+ .arg( src.path() ).arg( dest.path() ).arg( errno ) );
+ }
+ } else
+#endif
+ error( TDEIO::ERR_COULD_NOT_READ, src.path());
+ close(src_fd);
+ close(dest_fd);
+#ifdef USE_POSIX_ACL
+ if (acl) acl_free(acl);
+#endif
+ return;
+ }
+ if (n == 0)
+ break; // Finished
+#ifdef USE_SENDFILE
+ if ( !use_sendfile ) {
+#endif
+ if (write_all( dest_fd, buffer, n))
+ {
+ close(src_fd);
+ close(dest_fd);
+
+ if ( errno == ENOSPC ) // disk full
+ {
+ error( TDEIO::ERR_DISK_FULL, dest.path());
+ remove( _dest.data() );
+ }
+ else
+ {
+ kdWarning(7101) << "Couldn't write[2]. Error:" << strerror(errno) << endl;
+ error( TDEIO::ERR_COULD_NOT_WRITE, dest.path());
+ }
+#ifdef USE_POSIX_ACL
+ if (acl) acl_free(acl);
+#endif
+ return;
+ }
+ processed_size += n;
+#ifdef USE_SENDFILE
+ }
+#endif
+ processedSize( processed_size );
+ }
+
+ close( src_fd );
+
+ if (close( dest_fd))
+ {
+ kdWarning(7101) << "Error when closing file descriptor[2]:" << strerror(errno) << endl;
+ error( TDEIO::ERR_COULD_NOT_WRITE, dest.path());
+#ifdef USE_POSIX_ACL
+ if (acl) acl_free(acl);
+#endif
+ return;
+ }
+
+ // set final permissions
+ if ( _mode != -1 )
+ {
+ if ( (::chmod(_dest.data(), _mode) != 0)
+#ifdef USE_POSIX_ACL
+ || (acl && acl_set_file(_dest.data(), ACL_TYPE_ACCESS, acl) != 0)
+#endif
+ )
+ {
+ // Eat the error if the filesystem apparently doesn't support chmod.
+ if ( TDEIO::testFileSystemFlag( _dest, TDEIO::SupportsChmod ) )
+ warning( i18n( "Could not change permissions for\n%1" ).arg( dest.path() ) );
+ }
+ }
+#ifdef USE_POSIX_ACL
+ if (acl) acl_free(acl);
+#endif
+
+ // copy access and modification time
+ struct utimbuf ut;
+ ut.actime = buff_src.st_atime;
+ ut.modtime = buff_src.st_mtime;
+ if ( ::utime( _dest.data(), &ut ) != 0 )
+ {
+ kdWarning() << TQString(TQString::fromLatin1("Couldn't preserve access and modification time for\n%1").arg( dest.path() )) << endl;
+ }
+
+ processedSize( buff_src.st_size );
+ finished();
+}
+
+void FileProtocol::rename( const KURL &src, const KURL &dest,
+ bool _overwrite )
+{
+ TQCString _src( TQFile::encodeName(src.path()));
+ TQCString _dest( TQFile::encodeName(dest.path()));
+ KDE_struct_stat buff_src;
+ if ( KDE_lstat( _src.data(), &buff_src ) == -1 ) {
+ if ( errno == EACCES )
+ error( TDEIO::ERR_ACCESS_DENIED, src.path() );
+ else
+ error( TDEIO::ERR_DOES_NOT_EXIST, src.path() );
+ return;
+ }
+
+ KDE_struct_stat buff_dest;
+ bool dest_exists = ( KDE_stat( _dest.data(), &buff_dest ) != -1 );
+ if ( dest_exists )
+ {
+ if (S_ISDIR(buff_dest.st_mode))
+ {
+ error( TDEIO::ERR_DIR_ALREADY_EXIST, dest.path() );
+ return;
+ }
+
+ if ( same_inode( buff_dest, buff_src) )
+ {
+ error( TDEIO::ERR_IDENTICAL_FILES, dest.path() );
+ return;
+ }
+
+ if (!_overwrite)
+ {
+ error( TDEIO::ERR_FILE_ALREADY_EXIST, dest.path() );
+ return;
+ }
+ }
+
+ if ( ::rename( _src.data(), _dest.data()))
+ {
+ if (( errno == EACCES ) || (errno == EPERM)) {
+ error( TDEIO::ERR_ACCESS_DENIED, dest.path() );
+ }
+ else if (errno == EXDEV) {
+ error( TDEIO::ERR_UNSUPPORTED_ACTION, TQString::fromLatin1("rename"));
+ }
+ else if (errno == EROFS) { // The file is on a read-only filesystem
+ error( TDEIO::ERR_CANNOT_DELETE, src.path() );
+ }
+ else {
+ error( TDEIO::ERR_CANNOT_RENAME, src.path() );
+ }
+ return;
+ }
+
+ finished();
+}
+
+void FileProtocol::symlink( const TQString &target, const KURL &dest, bool overwrite )
+{
+ // Assume dest is local too (wouldn't be here otherwise)
+ if ( ::symlink( TQFile::encodeName( target ), TQFile::encodeName( dest.path() ) ) == -1 )
+ {
+ // Does the destination already exist ?
+ if ( errno == EEXIST )
+ {
+ if ( overwrite )
+ {
+ // Try to delete the destination
+ if ( unlink( TQFile::encodeName( dest.path() ) ) != 0 )
+ {
+ error( TDEIO::ERR_CANNOT_DELETE, dest.path() );
+ return;
+ }
+ // Try again - this won't loop forever since unlink succeeded
+ symlink( target, dest, overwrite );
+ }
+ else
+ {
+ KDE_struct_stat buff_dest;
+ KDE_lstat( TQFile::encodeName( dest.path() ), &buff_dest );
+ if (S_ISDIR(buff_dest.st_mode))
+ error( TDEIO::ERR_DIR_ALREADY_EXIST, dest.path() );
+ else
+ error( TDEIO::ERR_FILE_ALREADY_EXIST, dest.path() );
+ return;
+ }
+ }
+ else
+ {
+ // Some error occurred while we tried to symlink
+ error( TDEIO::ERR_CANNOT_SYMLINK, dest.path() );
+ return;
+ }
+ }
+ finished();
+}
+
+void FileProtocol::del( const KURL& url, bool isfile)
+{
+ TQCString _path( TQFile::encodeName(url.path()));
+ /*****
+ * Delete files
+ *****/
+
+ if (isfile) {
+ kdDebug( 7101 ) << "Deleting file "<< url.url() << endl;
+
+ // TODO deletingFile( source );
+
+ if ( unlink( _path.data() ) == -1 ) {
+ if ((errno == EACCES) || (errno == EPERM))
+ error( TDEIO::ERR_ACCESS_DENIED, url.path());
+ else if (errno == EISDIR)
+ error( TDEIO::ERR_IS_DIRECTORY, url.path());
+ else
+ error( TDEIO::ERR_CANNOT_DELETE, url.path() );
+ return;
+ }
+ } else {
+
+ /*****
+ * Delete empty directory
+ *****/
+
+ kdDebug( 7101 ) << "Deleting directory " << url.url() << endl;
+
+ if ( ::rmdir( _path.data() ) == -1 ) {
+ if ((errno == EACCES) || (errno == EPERM))
+ error( TDEIO::ERR_ACCESS_DENIED, url.path());
+ else {
+ kdDebug( 7101 ) << "could not rmdir " << perror << endl;
+ error( TDEIO::ERR_COULD_NOT_RMDIR, url.path() );
+ return;
+ }
+ }
+ }
+
+ finished();
+}
+
+
+TQString FileProtocol::getUserName( uid_t uid )
+{
+ TQString *temp;
+ temp = usercache.find( uid );
+ if ( !temp ) {
+ struct passwd *user = getpwuid( uid );
+ if ( user ) {
+ usercache.insert( uid, new TQString(TQString::fromLatin1(user->pw_name)) );
+ return TQString::fromLatin1( user->pw_name );
+ }
+ else
+ return TQString::number( uid );
+ }
+ else
+ return *temp;
+}
+
+TQString FileProtocol::getGroupName( gid_t gid )
+{
+ TQString *temp;
+ temp = groupcache.find( gid );
+ if ( !temp ) {
+ struct group *grp = getgrgid( gid );
+ if ( grp ) {
+ groupcache.insert( gid, new TQString(TQString::fromLatin1(grp->gr_name)) );
+ return TQString::fromLatin1( grp->gr_name );
+ }
+ else
+ return TQString::number( gid );
+ }
+ else
+ return *temp;
+}
+
+
+
+bool FileProtocol::createUDSEntry( const TQString & filename, const TQCString & path, UDSEntry & entry,
+ short int details, bool withACL )
+{
+ assert(entry.count() == 0); // by contract :-)
+ // Note: details = 0 (only "file or directory or symlink or doesn't exist") isn't implemented
+ // because there's no real performance penalty in kio_file for returning the complete
+ // details. Please consider doing it in your tdeioslave if you're using this one as a model :)
+ UDSAtom atom;
+ atom.m_uds = TDEIO::UDS_NAME;
+ atom.m_str = filename;
+ entry.append( atom );
+
+ mode_t type;
+ mode_t access;
+ KDE_struct_stat buff;
+
+ if ( KDE_lstat( path.data(), &buff ) == 0 ) {
+
+ if (S_ISLNK(buff.st_mode)) {
+
+ char buffer2[ 1000 ];
+ int n = readlink( path.data(), buffer2, 1000 );
+ if ( n != -1 ) {
+ buffer2[ n ] = 0;
+ }
+
+ atom.m_uds = TDEIO::UDS_LINK_DEST;
+ atom.m_str = TQFile::decodeName( buffer2 );
+ entry.append( atom );
+
+ // A symlink -> follow it only if details>1
+ if ( details > 1 && KDE_stat( path.data(), &buff ) == -1 ) {
+ // It is a link pointing to nowhere
+ type = S_IFMT - 1;
+ access = S_IRWXU | S_IRWXG | S_IRWXO;
+
+ atom.m_uds = TDEIO::UDS_FILE_TYPE;
+ atom.m_long = type;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = access;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_SIZE;
+ atom.m_long = 0L;
+ entry.append( atom );
+
+ goto notype;
+
+ }
+ }
+ } else {
+ // kdWarning() << "lstat didn't work on " << path.data() << endl;
+ return false;
+ }
+
+ type = buff.st_mode & S_IFMT; // extract file type
+ access = buff.st_mode & 07777; // extract permissions
+
+ atom.m_uds = TDEIO::UDS_FILE_TYPE;
+ atom.m_long = type;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = access;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_SIZE;
+ atom.m_long = buff.st_size;
+ entry.append( atom );
+
+#ifdef USE_POSIX_ACL
+ /* Append an atom indicating whether the file has extended acl information
+ * and if withACL is specified also one with the acl itself. If it's a directory
+ * and it has a default ACL, also append that. */
+ appendACLAtoms( path, entry, type, withACL );
+#endif
+
+ notype:
+ atom.m_uds = TDEIO::UDS_MODIFICATION_TIME;
+ atom.m_long = buff.st_mtime;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_USER;
+ atom.m_str = getUserName( buff.st_uid );
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_GROUP;
+ atom.m_str = getGroupName( buff.st_gid );
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_ACCESS_TIME;
+ atom.m_long = buff.st_atime;
+ entry.append( atom );
+
+ // Note: buff.st_ctime isn't the creation time !
+ // We made that mistake for KDE 2.0, but it's in fact the
+ // "file status" change time, which we don't care about.
+
+ return true;
+}
+
+void FileProtocol::stat( const KURL & url )
+{
+ if (!url.isLocalFile()) {
+ KURL redir(url);
+ redir.setProtocol(config()->readEntry("DefaultRemoteProtocol", "smb"));
+ redirection(redir);
+ kdDebug(7101) << "redirecting to " << redir.url() << endl;
+ finished();
+ return;
+ }
+
+ /* directories may not have a slash at the end if
+ * we want to stat() them; it requires that we
+ * change into it .. which may not be allowed
+ * stat("/is/unaccessible") -> rwx------
+ * stat("/is/unaccessible/") -> EPERM H.Z.
+ * This is the reason for the -1
+ */
+ TQCString _path( TQFile::encodeName(url.path(-1)));
+
+ TQString sDetails = metaData(TQString::fromLatin1("details"));
+ int details = sDetails.isEmpty() ? 2 : sDetails.toInt();
+ kdDebug(7101) << "FileProtocol::stat details=" << details << endl;
+
+ UDSEntry entry;
+ if ( !createUDSEntry( url.fileName(), _path, entry, details, true /*with acls*/ ) )
+ {
+ error( TDEIO::ERR_DOES_NOT_EXIST, url.path(-1) );
+ return;
+ }
+#if 0
+///////// debug code
+ TDEIO::UDSEntry::ConstIterator it = entry.begin();
+ for( ; it != entry.end(); it++ ) {
+ switch ((*it).m_uds) {
+ case TDEIO::UDS_FILE_TYPE:
+ kdDebug(7101) << "File Type : " << (mode_t)((*it).m_long) << endl;
+ break;
+ case TDEIO::UDS_ACCESS:
+ kdDebug(7101) << "Access permissions : " << (mode_t)((*it).m_long) << endl;
+ break;
+ case TDEIO::UDS_USER:
+ kdDebug(7101) << "User : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_GROUP:
+ kdDebug(7101) << "Group : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_NAME:
+ kdDebug(7101) << "Name : " << ((*it).m_str.ascii() ) << endl;
+ //m_strText = decodeFileName( (*it).m_str );
+ break;
+ case TDEIO::UDS_URL:
+ kdDebug(7101) << "URL : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_MIME_TYPE:
+ kdDebug(7101) << "MimeType : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_LINK_DEST:
+ kdDebug(7101) << "LinkDest : " << ((*it).m_str.ascii() ) << endl;
+ break;
+ case TDEIO::UDS_EXTENDED_ACL:
+ kdDebug(7101) << "Contains extended ACL " << endl;
+ break;
+ }
+ }
+ MetaData::iterator it1 = mOutgoingMetaData.begin();
+ for ( ; it1 != mOutgoingMetaData.end(); it1++ ) {
+ kdDebug(7101) << it1.key() << " = " << it1.data() << endl;
+ }
+/////////
+#endif
+ statEntry( entry );
+
+ finished();
+}
+
+void FileProtocol::listDir( const KURL& url)
+{
+ kdDebug(7101) << "========= LIST " << url.url() << " =========" << endl;
+ if (!url.isLocalFile()) {
+ KURL redir(url);
+ redir.setProtocol(config()->readEntry("DefaultRemoteProtocol", "smb"));
+ redirection(redir);
+ kdDebug(7101) << "redirecting to " << redir.url() << endl;
+ finished();
+ return;
+ }
+
+ TQCString _path( TQFile::encodeName(url.path()));
+
+ KDE_struct_stat buff;
+ if ( KDE_stat( _path.data(), &buff ) == -1 ) {
+ error( TDEIO::ERR_DOES_NOT_EXIST, url.path() );
+ return;
+ }
+
+ if ( !S_ISDIR( buff.st_mode ) ) {
+ error( TDEIO::ERR_IS_FILE, url.path() );
+ return;
+ }
+
+ DIR *dp = 0L;
+ KDE_struct_dirent *ep;
+
+ dp = opendir( _path.data() );
+ if ( dp == 0 ) {
+ switch (errno)
+ {
+#ifdef ENOMEDIUM
+ case ENOMEDIUM:
+ error( ERR_SLAVE_DEFINED,
+ i18n( "No media in device for %1" ).arg( url.path() ) );
+ break;
+#endif
+ default:
+ error( TDEIO::ERR_CANNOT_ENTER_DIRECTORY, url.path() );
+ break;
+ }
+ return;
+ }
+
+ // Don't make this a TQStringList. The locale file name we get here
+ // should be passed intact to createUDSEntry to avoid problems with
+ // files where TQFile::encodeName(TQFile::decodeName(a)) != a.
+ TQStrList entryNames;
+
+ while ( ( ep = KDE_readdir( dp ) ) != 0L )
+ entryNames.append( ep->d_name );
+
+ closedir( dp );
+ totalSize( entryNames.count() );
+
+ /* set the current dir to the path to speed up
+ in not having to pass an absolute path.
+ We restore the path later to get out of the
+ path - the kernel wouldn't unmount or delete
+ directories we keep as active directory. And
+ as the slave runs in the background, it's hard
+ to see for the user what the problem would be */
+#if !defined(PATH_MAX) && defined(__GLIBC__)
+ char *path_buffer;
+ path_buffer = getcwd(NULL, 0);
+#else
+ char path_buffer[PATH_MAX];
+ (void) getcwd(path_buffer, PATH_MAX - 1);
+#endif
+ if ( chdir( _path.data() ) ) {
+ if (errno == EACCES)
+ error(ERR_ACCESS_DENIED, _path);
+ else
+ error(ERR_CANNOT_ENTER_DIRECTORY, _path);
+ finished();
+ }
+
+ UDSEntry entry;
+ TQStrListIterator it(entryNames);
+ for (; it.current(); ++it) {
+ entry.clear();
+ if ( createUDSEntry( TQFile::decodeName(*it),
+ *it /* we can use the filename as relative path*/,
+ entry, 2, true ) )
+ listEntry( entry, false);
+ //else
+ // ;//Well, this should never happen... but with wrong encoding names
+ }
+
+ listEntry( entry, true ); // ready
+
+ kdDebug(7101) << "============= COMPLETED LIST ============" << endl;
+
+ chdir(path_buffer);
+#if !defined(PATH_MAX) && defined(__GLIBC__)
+ free(path_buffer);
+#endif
+
+ finished();
+}
+
+/*
+void FileProtocol::testDir( const TQString& path )
+{
+ TQCString _path( TQFile::encodeName(path));
+ KDE_struct_stat buff;
+ if ( KDE_stat( _path.data(), &buff ) == -1 ) {
+ error( TDEIO::ERR_DOES_NOT_EXIST, path );
+ return;
+ }
+
+ if ( S_ISDIR( buff.st_mode ) )
+ isDirectory();
+ else
+ isFile();
+
+ finished();
+}
+*/
+
+void FileProtocol::special( const TQByteArray &data)
+{
+ int tmp;
+ TQDataStream stream(data, IO_ReadOnly);
+
+ stream >> tmp;
+ switch (tmp) {
+ case 1:
+ {
+ TQString fstype, dev, point;
+ TQ_INT8 iRo;
+
+ stream >> iRo >> fstype >> dev >> point;
+
+ bool ro = ( iRo != 0 );
+
+ kdDebug(7101) << "MOUNTING fstype=" << fstype << " dev=" << dev << " point=" << point << " ro=" << ro << endl;
+ bool ok = pmount( dev );
+ if (ok)
+ finished();
+ else
+ mount( ro, fstype.ascii(), dev, point );
+
+ }
+ break;
+ case 2:
+ {
+ TQString point;
+ stream >> point;
+ bool ok = pumount( point );
+ if (ok)
+ finished();
+ else
+ unmount( point );
+ }
+ break;
+
+ case 3:
+ {
+ TQString filename;
+ stream >> filename;
+ KShred shred( filename );
+ connect( &shred, TQT_SIGNAL( processedSize( TDEIO::filesize_t ) ),
+ this, TQT_SLOT( slotProcessedSize( TDEIO::filesize_t ) ) );
+ connect( &shred, TQT_SIGNAL( infoMessage( const TQString & ) ),
+ this, TQT_SLOT( slotInfoMessage( const TQString & ) ) );
+ if (!shred.shred())
+ error( TDEIO::ERR_CANNOT_DELETE, filename );
+ else
+ finished();
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+// Connected to KShred
+void FileProtocol::slotProcessedSize( TDEIO::filesize_t bytes )
+{
+ kdDebug(7101) << "FileProtocol::slotProcessedSize (" << (unsigned int) bytes << ")" << endl;
+ processedSize( bytes );
+}
+
+// Connected to KShred
+void FileProtocol::slotInfoMessage( const TQString & msg )
+{
+ kdDebug(7101) << "FileProtocol::slotInfoMessage (" << msg << ")" << endl;
+ infoMessage( msg );
+}
+
+void FileProtocol::mount( bool _ro, const char *_fstype, const TQString& _dev, const TQString& _point )
+{
+ kdDebug(7101) << "FileProtocol::mount _fstype=" << _fstype << endl;
+ TQCString buffer;
+
+#ifdef HAVE_VOLMGT
+ /*
+ * support for Solaris volume management
+ */
+ TQString err;
+ TQCString devname = TQFile::encodeName( _dev );
+
+ if( volmgt_running() ) {
+// kdDebug(7101) << "VOLMGT: vold ok." << endl;
+ if( volmgt_check( devname.data() ) == 0 ) {
+ kdDebug(7101) << "VOLMGT: no media in "
+ << devname.data() << endl;
+ err = i18n("No Media inserted or Media not recognized.");
+ error( TDEIO::ERR_COULD_NOT_MOUNT, err );
+ return;
+ } else {
+ kdDebug(7101) << "VOLMGT: " << devname.data()
+ << ": media ok" << endl;
+ finished();
+ return;
+ }
+ } else {
+ err = i18n("\"vold\" is not running.");
+ kdDebug(7101) << "VOLMGT: " << err << endl;
+ error( TDEIO::ERR_COULD_NOT_MOUNT, err );
+ return;
+ }
+#else
+
+
+ KTempFile tmpFile;
+ TQCString tmpFileC = TQFile::encodeName(tmpFile.name());
+ const char *tmp = tmpFileC.data();
+ TQCString dev;
+ if ( _dev.startsWith( "LABEL=" ) ) { // turn LABEL=foo into -L foo (#71430)
+ TQString labelName = _dev.mid( 6 );
+ dev = "-L ";
+ dev += TQFile::encodeName( TDEProcess::quote( labelName ) ); // is it correct to assume same encoding as filesystem?
+ } else if ( _dev.startsWith( "UUID=" ) ) { // and UUID=bar into -U bar
+ TQString uuidName = _dev.mid( 5 );
+ dev = "-U ";
+ dev += TQFile::encodeName( TDEProcess::quote( uuidName ) );
+ }
+ else
+ dev = TQFile::encodeName( TDEProcess::quote(_dev) ); // get those ready to be given to a shell
+
+ TQCString point = TQFile::encodeName( TDEProcess::quote(_point) );
+ bool fstype_empty = !_fstype || !*_fstype;
+ TQCString fstype = TDEProcess::quote(_fstype).latin1(); // good guess
+ TQCString readonly = _ro ? "-r" : "";
+ TQString epath = TQString::fromLatin1(getenv("PATH"));
+ TQString path = TQString::fromLatin1("/sbin:/bin");
+ if(!epath.isEmpty())
+ path += TQString::fromLatin1(":") + epath;
+ TQString mountProg = TDEGlobal::dirs()->findExe("mount", path);
+ if (mountProg.isEmpty()){
+ error( TDEIO::ERR_COULD_NOT_MOUNT, i18n("Could not find program \"mount\""));
+ return;
+ }
+
+ // Two steps, in case mount doesn't like it when we pass all options
+ for ( int step = 0 ; step <= 1 ; step++ )
+ {
+ // Mount using device only if no fstype nor mountpoint (KDE-1.x like)
+ if ( !_dev.isEmpty() && _point.isEmpty() && fstype_empty )
+ buffer.sprintf( "%s %s 2>%s", mountProg.latin1(), dev.data(), tmp );
+ else
+ // Mount using the mountpoint, if no fstype nor device (impossible in first step)
+ if ( !_point.isEmpty() && _dev.isEmpty() && fstype_empty )
+ buffer.sprintf( "%s %s 2>%s", mountProg.latin1(), point.data(), tmp );
+ else
+ // mount giving device + mountpoint but no fstype
+ if ( !_point.isEmpty() && !_dev.isEmpty() && fstype_empty )
+ buffer.sprintf( "%s %s %s %s 2>%s", mountProg.latin1(), readonly.data(), dev.data(), point.data(), tmp );
+ else
+ // mount giving device + mountpoint + fstype
+#if defined(__svr4__) && defined(__sun__) // MARCO for Solaris 8 and I
+ // believe this is true for SVR4 in general
+ buffer.sprintf( "%s -F %s %s %s %s 2>%s"
+ mountProg.latin1()
+ fstype.data()
+ _ro ? "-oro" : ""
+ dev.data()
+ point.data()
+ tmp );
+#else
+ buffer.sprintf( "%s %s -t %s %s %s 2>%s", mountProg.latin1(), readonly.data(),
+ fstype.data(), dev.data(), point.data(), tmp );
+#endif
+
+ kdDebug(7101) << buffer << endl;
+
+ int mount_ret = system( buffer.data() );
+
+ TQString err = testLogFile( tmp );
+ if ( err.isEmpty() && mount_ret == 0)
+ {
+ finished();
+ return;
+ }
+ else
+ {
+ // Didn't work - or maybe we just got a warning
+ TQString mp = TDEIO::findDeviceMountPoint( _dev );
+ // Is the device mounted ?
+ if ( !mp.isEmpty() && mount_ret == 0)
+ {
+ kdDebug(7101) << "mount got a warning: " << err << endl;
+ warning( err );
+ finished();
+ return;
+ }
+ else
+ {
+ if ( (step == 0) && !_point.isEmpty())
+ {
+ kdDebug(7101) << err << endl;
+ kdDebug(7101) << "Mounting with those options didn't work, trying with only mountpoint" << endl;
+ fstype = "";
+ fstype_empty = true;
+ dev = "";
+ // The reason for trying with only mountpoint (instead of
+ // only device) is that some people (hi Malte!) have the
+ // same device associated with two mountpoints
+ // for different fstypes, like /dev/fd0 /mnt/e2floppy and
+ // /dev/fd0 /mnt/dosfloppy.
+ // If the user has the same mountpoint associated with two
+ // different devices, well they shouldn't specify the
+ // mountpoint but just the device.
+ }
+ else
+ {
+ error( TDEIO::ERR_COULD_NOT_MOUNT, err );
+ return;
+ }
+ }
+ }
+ }
+#endif /* ! HAVE_VOLMGT */
+}
+
+
+void FileProtocol::unmount( const TQString& _point )
+{
+ TQCString buffer;
+
+ KTempFile tmpFile;
+ TQCString tmpFileC = TQFile::encodeName(tmpFile.name());
+ TQString err;
+ const char *tmp = tmpFileC.data();
+
+#ifdef HAVE_VOLMGT
+ /*
+ * support for Solaris volume management
+ */
+ char *devname;
+ char *ptr;
+ FILE *mnttab;
+ struct mnttab mnt;
+
+ if( volmgt_running() ) {
+ kdDebug(7101) << "VOLMGT: looking for "
+ << _point.local8Bit() << endl;
+
+ if( (mnttab = KDE_fopen( MNTTAB, "r" )) == NULL ) {
+ err = "couldn't open mnttab";
+ kdDebug(7101) << "VOLMGT: " << err << endl;
+ error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
+ return;
+ }
+
+ /*
+ * since there's no way to derive the device name from
+ * the mount point through the volmgt library (and
+ * media_findname() won't work in this case), we have to
+ * look ourselves...
+ */
+ devname = NULL;
+ rewind( mnttab );
+ while( getmntent( mnttab, &mnt ) == 0 ) {
+ if( strcmp( _point.local8Bit(), mnt.mnt_mountp ) == 0 ){
+ devname = mnt.mnt_special;
+ break;
+ }
+ }
+ fclose( mnttab );
+
+ if( devname == NULL ) {
+ err = "not in mnttab";
+ kdDebug(7101) << "VOLMGT: "
+ << TQFile::encodeName(_point).data()
+ << ": " << err << endl;
+ error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
+ return;
+ }
+
+ /*
+ * strip off the directory name (volume name)
+ * the eject(1) command will handle unmounting and
+ * physically eject the media (if possible)
+ */
+ ptr = strrchr( devname, '/' );
+ *ptr = '\0';
+ TQCString qdevname(TQFile::encodeName(TDEProcess::quote(TQFile::decodeName(TQCString(devname)))).data());
+ buffer.sprintf( "/usr/bin/eject %s 2>%s", qdevname.data(), tmp );
+ kdDebug(7101) << "VOLMGT: eject " << qdevname << endl;
+
+ /*
+ * from eject(1): exit status == 0 => need to manually eject
+ * exit status == 4 => media was ejected
+ */
+// if( WEXITSTATUS( system( buffer.local8Bit() )) == 4 ) {
+ if( WEXITSTATUS( system( buffer.data() )) == 4 ) { // Fix for TQString -> QCString?
+ /*
+ * this is not an error, so skip "testLogFile()"
+ * to avoid wrong/confusing error popup
+ */
+ unlink( tmp );
+ finished();
+ return;
+ }
+ } else {
+ /*
+ * eject(1) should do its job without vold(1M) running,
+ * so we probably could call eject anyway, but since the
+ * media is mounted now, vold must've died for some reason
+ * during the user's session, so it should be restarted...
+ */
+ err = i18n("\"vold\" is not running.");
+ kdDebug(7101) << "VOLMGT: " << err << endl;
+ error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
+ return;
+ }
+#else
+ TQString epath = getenv("PATH");
+ TQString path = TQString::fromLatin1("/sbin:/bin");
+ if (!epath.isEmpty())
+ path += ":" + epath;
+ TQString umountProg = TDEGlobal::dirs()->findExe("umount", path);
+
+ if (umountProg.isEmpty()) {
+ error( TDEIO::ERR_COULD_NOT_UNMOUNT, i18n("Could not find program \"umount\""));
+ return;
+ }
+ buffer.sprintf( "%s %s 2>%s", umountProg.latin1(), TQFile::encodeName(TDEProcess::quote(_point)).data(), tmp );
+ system( buffer.data() );
+#endif /* HAVE_VOLMGT */
+
+ err = testLogFile( tmp );
+
+ if (err.contains("fstab") || err.contains("root")) {
+ TQString olderr;
+ err = TQString::null;
+
+ DCOPRef d("kded", "mediamanager");
+ d.setDCOPClient ( dcopClient() );
+ DCOPReply reply = d.call("properties", _point);
+ TQString udi;
+
+ if ( reply.isValid() ) {
+ TQStringList list = reply;
+ if (list.size())
+ udi = list[0];
+ }
+
+ if (!udi.isEmpty())
+ reply = d.call("unmount", udi);
+
+ if (udi.isEmpty() || !reply.isValid())
+ err = olderr;
+ else if (reply.isValid())
+ reply.get(err);
+ }
+
+ if ( err.isEmpty() )
+ finished();
+ else
+ error( TDEIO::ERR_COULD_NOT_UNMOUNT, err );
+}
+
+/*************************************
+ *
+ * pmount handling
+ *
+ *************************************/
+
+bool FileProtocol::pmount(const TQString &dev)
+{
+ TQString epath = getenv("PATH");
+ TQString path = TQString::fromLatin1("/sbin:/bin");
+ if (!epath.isEmpty())
+ path += ":" + epath;
+ TQString pmountProg = TDEGlobal::dirs()->findExe("pmount", path);
+
+ if (pmountProg.isEmpty())
+ return false;
+
+ TQCString buffer;
+ buffer.sprintf( "%s %s", TQFile::encodeName(pmountProg).data(),
+ TQFile::encodeName(TDEProcess::quote(dev)).data() );
+
+ int res = system( buffer.data() );
+
+ return res==0;
+}
+
+bool FileProtocol::pumount(const TQString &point)
+{
+ TQString real_point = KStandardDirs::realPath(point);
+
+ KMountPoint::List mtab = KMountPoint::currentMountPoints();
+
+ KMountPoint::List::const_iterator it = mtab.begin();
+ KMountPoint::List::const_iterator end = mtab.end();
+
+ TQString dev;
+
+ for (; it!=end; ++it)
+ {
+ TQString tmp = (*it)->mountedFrom();
+ TQString mp = (*it)->mountPoint();
+ mp = KStandardDirs::realPath(mp);
+
+ if (mp==real_point)
+ dev = KStandardDirs::realPath(tmp);
+ }
+
+ if (dev.isEmpty()) return false;
+ if (dev.endsWith("/")) dev.truncate(dev.length()-1);
+
+ TQString epath = getenv("PATH");
+ TQString path = TQString::fromLatin1("/sbin:/bin");
+ if (!epath.isEmpty())
+ path += ":" + epath;
+ TQString pumountProg = TDEGlobal::dirs()->findExe("pumount", path);
+
+ if (pumountProg.isEmpty())
+ return false;
+
+ TQCString buffer;
+ buffer.sprintf( "%s %s", TQFile::encodeName(pumountProg).data(),
+ TQFile::encodeName(TDEProcess::quote(dev)).data() );
+
+ int res = system( buffer.data() );
+
+ return res==0;
+}
+
+/*************************************
+ *
+ * Utilities
+ *
+ *************************************/
+
+static TQString testLogFile( const char *_filename )
+{
+ char buffer[ 1024 ];
+ KDE_struct_stat buff;
+
+ TQString result;
+
+ KDE_stat( _filename, &buff );
+ int size = buff.st_size;
+ if ( size == 0 ) {
+ unlink( _filename );
+ return result;
+ }
+
+ FILE * f = KDE_fopen( _filename, "rb" );
+ if ( f == 0L ) {
+ unlink( _filename );
+ result = i18n("Could not read %1").arg(TQFile::decodeName(_filename));
+ return result;
+ }
+
+ result = "";
+ const char *p = "";
+ while ( p != 0L ) {
+ p = fgets( buffer, sizeof(buffer)-1, f );
+ if ( p != 0L )
+ result += TQString::fromLocal8Bit(buffer);
+ }
+
+ fclose( f );
+
+ unlink( _filename );
+
+ return result;
+}
+
+/*************************************
+ *
+ * ACL handling helpers
+ *
+ *************************************/
+#ifdef USE_POSIX_ACL
+
+static bool isExtendedACL( acl_t acl )
+{
+ return ( acl_equiv_mode( acl, 0 ) != 0 );
+}
+
+static TQString aclAsString( acl_t acl )
+{
+ char *aclString = acl_to_text( acl, 0 );
+ TQString ret = TQString::fromLatin1( aclString );
+ acl_free( (void*)aclString );
+ return ret;
+}
+
+static void appendACLAtoms( const TQCString & path, UDSEntry& entry, mode_t type, bool withACL )
+{
+ // first check for a noop
+#ifdef HAVE_NON_POSIX_ACL_EXTENSIONS
+ if ( acl_extended_file( path.data() ) == 0 ) return;
+#endif
+
+ acl_t acl = 0;
+ acl_t defaultAcl = 0;
+ UDSAtom atom;
+ bool isDir = S_ISDIR( type );
+ // do we have an acl for the file, and/or a default acl for the dir, if it is one?
+ if ( ( acl = acl_get_file( path.data(), ACL_TYPE_ACCESS ) ) ) {
+ if ( !isExtendedACL( acl ) ) {
+ acl_free( acl );
+ acl = 0;
+ }
+ }
+
+ /* Sadly libacl does not provided a means of checking for extended ACL and default
+ * ACL separately. Since a directory can have both, we need to check again. */
+ if ( isDir )
+ defaultAcl = acl_get_file( path.data(), ACL_TYPE_DEFAULT );
+
+ if ( acl || defaultAcl ) {
+ kdDebug(7101) << path.data() << " has extended ACL entries " << endl;
+ atom.m_uds = TDEIO::UDS_EXTENDED_ACL;
+ atom.m_long = 1;
+ entry.append( atom );
+ }
+ if ( withACL ) {
+ if ( acl ) {
+ atom.m_uds = TDEIO::UDS_ACL_STRING;
+ atom.m_str = aclAsString( acl );
+ entry.append( atom );
+ kdDebug(7101) << path.data() << "ACL: " << atom.m_str << endl;
+ }
+ if ( defaultAcl ) {
+ atom.m_uds = TDEIO::UDS_DEFAULT_ACL_STRING;
+ atom.m_str = aclAsString( defaultAcl );
+ entry.append( atom );
+ kdDebug(7101) << path.data() << "DEFAULT ACL: " << atom.m_str << endl;
+ }
+ }
+ if ( acl ) acl_free( acl );
+ if ( defaultAcl ) acl_free( defaultAcl );
+}
+#endif
+
+#include "file.moc"
diff --git a/tdeioslave/file/file.h b/tdeioslave/file/file.h
new file mode 100644
index 000000000..226e0a428
--- /dev/null
+++ b/tdeioslave/file/file.h
@@ -0,0 +1,98 @@
+/*
+ Copyright (C) 2000-2002 Stephan Kulow <coolo@kde.org>
+ Copyright (C) 2000-2002 David Faure <faure@kde.org>
+ Copyright (C) 2000-2002 Waldo Bastian <bastian@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License (LGPL) as published by the Free Software Foundation;
+ either version 2 of the License, or (at your option) any later
+ version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __file_h__
+#define __file_h__ "$Id$"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <stdio.h>
+#include <unistd.h>
+
+#include <tqobject.h>
+#include <tqintdict.h>
+#include <tqstring.h>
+#include <tqvaluelist.h>
+
+#include <tdeio/global.h>
+#include <tdeio/slavebase.h>
+
+// Note that this header file is installed, so think twice
+// before breaking binary compatibility (read: it is forbidden :)
+
+class FileProtocol : public TQObject, public TDEIO::SlaveBase
+{
+ Q_OBJECT
+public:
+ FileProtocol( const TQCString &pool, const TQCString &app);
+ virtual ~FileProtocol() { }
+
+ virtual void get( const KURL& url );
+ virtual void put( const KURL& url, int permissions,
+ bool overwrite, bool resume );
+ virtual void copy( const KURL &src, const KURL &dest,
+ int permissions, bool overwrite );
+ virtual void rename( const KURL &src, const KURL &dest,
+ bool overwrite );
+ virtual void symlink( const TQString &target, const KURL &dest,
+ bool overwrite );
+
+ virtual void stat( const KURL& url );
+ virtual void listDir( const KURL& url );
+ virtual void mkdir( const KURL& url, int permissions );
+ virtual void chmod( const KURL& url, int permissions );
+ virtual void del( const KURL& url, bool isfile);
+
+ /**
+ * Special commands supported by this slave:
+ * 1 - mount
+ * 2 - unmount
+ * 3 - shred
+ */
+ virtual void special( const TQByteArray &data);
+ void unmount( const TQString& point );
+ void mount( bool _ro, const char *_fstype, const TQString& dev, const TQString& point );
+ bool pumount( const TQString &point );
+ bool pmount( const TQString &dev );
+
+protected slots:
+ void slotProcessedSize( TDEIO::filesize_t _bytes );
+ void slotInfoMessage( const TQString & msg );
+
+protected:
+
+ bool createUDSEntry( const TQString & filename, const TQCString & path, TDEIO::UDSEntry & entry,
+ short int details, bool withACL );
+ int setACL( const char *path, mode_t perm, bool _directoryDefault );
+
+ TQString getUserName( uid_t uid );
+ TQString getGroupName( gid_t gid );
+
+ TQIntDict<TQString> usercache; // maps long ==> TQString *
+ TQIntDict<TQString> groupcache;
+
+ class FileProtocolPrivate;
+ FileProtocolPrivate *d;
+};
+
+#endif
diff --git a/tdeioslave/file/file.protocol b/tdeioslave/file/file.protocol
new file mode 100644
index 000000000..be7c5d587
--- /dev/null
+++ b/tdeioslave/file/file.protocol
@@ -0,0 +1,15 @@
+[Protocol]
+exec=kio_file
+protocol=file
+input=none
+output=filesystem
+listing=Name,Type,Size,Date,AccessDate,Access,Owner,Group,Link
+reading=true
+writing=true
+makedir=true
+deleting=true
+linking=true
+moving=true
+maxInstances=4
+DocPath=tdeioslave/file.html
+Class=:local
diff --git a/tdeioslave/ftp/CMakeLists.txt b/tdeioslave/ftp/CMakeLists.txt
new file mode 100644
index 000000000..9f9125fc3
--- /dev/null
+++ b/tdeioslave/ftp/CMakeLists.txt
@@ -0,0 +1,44 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore/network
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install( FILES ftp.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+##### kio_ftp ###################################
+
+set( target kio_ftp )
+
+set( ${target}_SRCS
+ ftp.cc
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/kioslave/ftp/Makefile.am b/tdeioslave/ftp/Makefile.am
index c062d6430..c062d6430 100644
--- a/kioslave/ftp/Makefile.am
+++ b/tdeioslave/ftp/Makefile.am
diff --git a/kioslave/ftp/configure.in.in b/tdeioslave/ftp/configure.in.in
index 0c94a9b9b..0c94a9b9b 100644
--- a/kioslave/ftp/configure.in.in
+++ b/tdeioslave/ftp/configure.in.in
diff --git a/tdeioslave/ftp/ftp.cc b/tdeioslave/ftp/ftp.cc
new file mode 100644
index 000000000..2099457f2
--- /dev/null
+++ b/tdeioslave/ftp/ftp.cc
@@ -0,0 +1,2675 @@
+// -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 2; -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+
+ Recommended reading explaining FTP details and quirks:
+ http://cr.yp.to/ftp.html (by D.J. Bernstein)
+*/
+
+
+#define KIO_FTP_PRIVATE_INCLUDE
+#include "ftp.h"
+
+#include <sys/stat.h>
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <netdb.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <signal.h>
+
+#if TIME_WITH_SYS_TIME
+#include <time.h>
+#endif
+
+#include <tqdir.h>
+
+#include <kdebug.h>
+#include <klocale.h>
+#include <kinstance.h>
+#include <kmimemagic.h>
+#include <kmimetype.h>
+#include <ksockaddr.h>
+#include <tdesocketaddress.h>
+#include <tdeio/ioslave_defaults.h>
+#include <tdeio/slaveconfig.h>
+#include <kremoteencoding.h>
+#include <klargefile.h>
+
+#ifdef HAVE_STRTOLL
+ #define charToLongLong(a) strtoll(a, 0, 10)
+#else
+ #define charToLongLong(a) strtol(a, 0, 10)
+#endif
+
+// JPF: a remark on coding style (2004-03-06):
+// Some calls to TQString::fromLatin1() were removed from the code. In most places
+// the KDE code relies on implicit creation of QStrings. Also Qt has a lot of
+// const char* overloads, so that using TQString::fromLatin1() can be ineffectient!
+
+#define FTP_LOGIN "anonymous"
+#define FTP_PASSWD "anonymous@"
+
+//#undef kdDebug
+#define ENABLE_CAN_RESUME
+
+// JPF: somebody should find a better solution for this or move this to KIO
+// JPF: anyhow, in KDE 3.2.0 I found diffent MAX_IPC_SIZE definitions!
+namespace TDEIO {
+ enum buffersizes
+ { /**
+ * largest buffer size that should be used to transfer data between
+ * KIO slaves using the data() function
+ */
+ maximumIpcSize = 32 * 1024,
+ /**
+ * this is a reasonable value for an initial read() that a KIO slave
+ * can do to obtain data via a slow network connection.
+ */
+ initialIpcSize = 2 * 1024,
+ /**
+ * recommended size of a data block passed to findBufferFileType()
+ */
+ mimimumMimeSize = 1024
+ };
+
+ // JPF: this helper was derived from write_all in file.cc (FileProtocol).
+ static // JPF: in ftp.cc we make it static
+ /**
+ * This helper handles some special issues (blocking and interrupted
+ * system call) when writing to a file handle.
+ *
+ * @return 0 on success or an error code on failure (ERR_COULD_NOT_WRITE,
+ * ERR_DISK_FULL, ERR_CONNECTION_BROKEN).
+ */
+ int WriteToFile(int fd, const char *buf, size_t len)
+ {
+ while (len > 0)
+ { // JPF: shouldn't there be a KDE_write?
+ ssize_t written = write(fd, buf, len);
+ if (written >= 0)
+ { buf += written;
+ len -= written;
+ continue;
+ }
+ switch(errno)
+ { case EINTR: continue;
+ case EPIPE: return ERR_CONNECTION_BROKEN;
+ case ENOSPC: return ERR_DISK_FULL;
+ default: return ERR_COULD_NOT_WRITE;
+ }
+ }
+ return 0;
+ }
+}
+
+TDEIO::filesize_t Ftp::UnknownSize = (TDEIO::filesize_t)-1;
+
+using namespace TDEIO;
+
+extern "C" { KDE_EXPORT int kdemain(int argc, char **argv); }
+
+int kdemain( int argc, char **argv )
+{
+ KLocale::setMainCatalogue("tdelibs");
+ TDEInstance instance( "kio_ftp" );
+ ( void ) TDEGlobal::locale();
+
+ kdDebug(7102) << "Starting " << getpid() << endl;
+
+ if (argc != 4)
+ {
+ fprintf(stderr, "Usage: kio_ftp protocol domain-socket1 domain-socket2\n");
+ exit(-1);
+ }
+
+ Ftp slave(argv[2], argv[3]);
+ slave.dispatchLoop();
+
+ kdDebug(7102) << "Done" << endl;
+ return 0;
+}
+
+//===============================================================================
+// FtpTextReader Read Text lines from a file (or socket)
+//===============================================================================
+
+void FtpTextReader::textClear()
+{ m_iTextLine = m_iTextBuff = 0;
+ m_szText[0] = 0;
+ m_bTextEOF = m_bTextTruncated = false;
+}
+
+int FtpTextReader::textRead(FtpSocket *pSock)
+{
+ // if we have still buffered data then move it to the left
+ char* pEOL;
+ if(m_iTextLine < m_iTextBuff)
+ { m_iTextBuff -= m_iTextLine;
+ memmove(m_szText, m_szText+m_iTextLine, m_iTextBuff);
+ pEOL = (char*)memchr(m_szText, '\n', m_iTextBuff); // have a complete line?
+ }
+ else
+ { m_iTextBuff = 0;
+ pEOL = NULL;
+ }
+ m_bTextEOF = m_bTextTruncated = false;
+
+ // read data from the control socket until a complete line is read
+ int nBytes;
+ while(pEOL == NULL)
+ {
+ if(m_iTextBuff > textReadLimit)
+ { m_bTextTruncated = true;
+ m_iTextBuff = textReadLimit;
+ }
+ nBytes = pSock->read(m_szText+m_iTextBuff, sizeof(m_szText)-m_iTextBuff);
+ if(nBytes <= 0)
+ {
+ // This error can occur after the server closed the connection (after a timeout)
+ if(nBytes < 0)
+ pSock->debugMessage("textRead failed");
+ m_bTextEOF = true;
+ pEOL = m_szText + m_iTextBuff;
+ }
+ else
+ {
+ m_iTextBuff += nBytes;
+ pEOL = (char*)memchr(m_szText, '\n', m_iTextBuff);
+ }
+ }
+
+ nBytes = pEOL - m_szText;
+ m_iTextLine = nBytes + 1;
+
+ if(nBytes > textReadLimit)
+ { m_bTextTruncated = true;
+ nBytes = textReadLimit;
+ }
+ if(nBytes && m_szText[nBytes-1] == '\r')
+ nBytes--;
+ m_szText[nBytes] = 0;
+ return nBytes;
+}
+
+//===============================================================================
+// FtpSocket Helper Class for Data or Control Connections
+//===============================================================================
+void FtpSocket::debugMessage(const char* pszMsg) const
+{
+ kdDebug(7102) << m_pszName << ": " << pszMsg << endl;
+}
+
+int FtpSocket::errorMessage(int iErrorCode, const char* pszMsg) const
+{
+ kdError(7102) << m_pszName << ": " << pszMsg << endl;
+ return iErrorCode;
+}
+
+int FtpSocket::connectSocket(int iTimeOutSec, bool bControl)
+{
+ closeSocket();
+
+ int iOpt = bControl ? KExtendedSocket::inetSocket
+ : KExtendedSocket::noResolve;
+ setSocketFlags(iOpt | socketFlags());
+ setTimeout(iTimeOutSec);
+
+ int iCon = KExtendedSocket::connect();
+ if(iCon < 0)
+ { int iErrorCode = (status() == IO_LookupError)
+ ? ERR_UNKNOWN_HOST : ERR_COULD_NOT_CONNECT;
+ TQString strMsg = KExtendedSocket::strError(status(), systemError());
+ strMsg.prepend("connect failed (code %1): ");
+ return errorMessage(iErrorCode, TQString(strMsg.arg(iCon)).latin1());
+ }
+ if( !setAddressReusable(true) )
+ return errorMessage(ERR_COULD_NOT_CREATE_SOCKET, "setAddressReusable failed");
+
+ if(!bControl)
+ { int on=1;
+ if( !setSocketOption(SO_KEEPALIVE, (char *)&on, sizeof(on)) )
+ errorMessage(0, "Keepalive not allowed");
+
+ struct linger lng = { 1, 120 };
+ if( !setSocketOption(SO_LINGER, (char *)&lng, sizeof (lng)) )
+ errorMessage(0, "Linger mode was not allowed.");
+ }
+
+ debugMessage("connected");
+ return 0;
+}
+
+void FtpSocket::closeSocket()
+{
+ if(m_server != -1 || fd() != -1)
+ debugMessage("disconnected");
+
+ if(m_server != -1)
+ {
+ ::shutdown(m_server, SHUT_RDWR);
+ ::close(m_server);
+ m_server = -1;
+ }
+ if(socketStatus() > nothing)
+ reset();
+ textClear();
+}
+
+bool FtpSocket::setSocketOption(int opt, char*arg, socklen_t len) const
+{
+ return (setsockopt(sock(), SOL_SOCKET, opt, arg, len) != -1);
+}
+
+//===============================================================================
+// Ftp
+//===============================================================================
+
+Ftp::Ftp( const TQCString &pool, const TQCString &app )
+ : SlaveBase( "ftp", pool, app )
+{
+ // init the socket data
+ m_data = m_control = NULL;
+ ftpCloseControlConnection();
+
+ // init other members
+ m_port = 0;
+ kdDebug(7102) << "Ftp::Ftp()" << endl;
+}
+
+
+Ftp::~Ftp()
+{
+ kdDebug(7102) << "Ftp::~Ftp()" << endl;
+ closeConnection();
+}
+
+/**
+ * This closes a data connection opened by ftpOpenDataConnection().
+ */
+void Ftp::ftpCloseDataConnection()
+{
+ if(m_data != NULL)
+ { delete m_data;
+ m_data = NULL;
+ }
+}
+
+/**
+ * This closes a control connection opened by ftpOpenControlConnection() and reinits the
+ * related states. This method gets called from the constructor with m_control = NULL.
+ */
+void Ftp::ftpCloseControlConnection()
+{
+ m_extControl = 0;
+ if(m_control)
+ delete m_control;
+ m_control = NULL;
+ m_cDataMode = 0;
+ m_bLoggedOn = false; // logon needs control connction
+ m_bTextMode = false;
+ m_bBusy = false;
+}
+
+/**
+ * Returns the last response from the server (iOffset >= 0) -or- reads a new response
+ * (iOffset < 0). The result is returned (with iOffset chars skipped for iOffset > 0).
+ */
+const char* Ftp::ftpResponse(int iOffset)
+{
+ assert(m_control != NULL); // must have control connection socket
+ const char *pTxt = m_control->textLine();
+
+ // read the next line ...
+ if(iOffset < 0)
+ {
+ int iMore = 0;
+ m_iRespCode = 0;
+
+ // If the server sends multiline responses "nnn-text" we loop here until
+ // a final "nnn text" line is reached. Only data from the final line will
+ // be stored. Some servers (OpenBSD) send a single "nnn-" followed by
+ // optional lines that start with a space and a final "nnn text" line.
+ do {
+ int nBytes = m_control->textRead();
+ int iCode = atoi(pTxt);
+ if(iCode > 0) m_iRespCode = iCode;
+
+ // ignore lines starting with a space in multiline response
+ if(iMore != 0 && pTxt[0] == 32)
+ ;
+ // otherwise the line should start with "nnn-" or "nnn "
+ else if(nBytes < 4 || iCode < 100)
+ iMore = 0;
+ // we got a valid line, now check for multiline responses ...
+ else if(iMore == 0 && pTxt[3] == '-')
+ iMore = iCode;
+ // "nnn " ends multiline mode ...
+ else if(iMore != 0 && (iMore != iCode || pTxt[3] != '-'))
+ iMore = 0;
+
+ if(iMore != 0)
+ kdDebug(7102) << " > " << pTxt << endl;
+ } while(iMore != 0);
+ kdDebug(7102) << "resp> " << pTxt << endl;
+
+ m_iRespType = (m_iRespCode > 0) ? m_iRespCode / 100 : 0;
+ }
+
+ // return text with offset ...
+ while(iOffset-- > 0 && pTxt[0])
+ pTxt++;
+ return pTxt;
+}
+
+
+void Ftp::closeConnection()
+{
+ if(m_control != NULL || m_data != NULL)
+ kdDebug(7102) << "Ftp::closeConnection m_bLoggedOn=" << m_bLoggedOn << " m_bBusy=" << m_bBusy << endl;
+
+ if(m_bBusy) // ftpCloseCommand not called
+ {
+ kdWarning(7102) << "Ftp::closeConnection Abandoned data stream" << endl;
+ ftpCloseDataConnection();
+ }
+
+ if(m_bLoggedOn) // send quit
+ {
+ if( !ftpSendCmd( "quit", 0 ) || (m_iRespType != 2) )
+ kdWarning(7102) << "Ftp::closeConnection QUIT returned error: " << m_iRespCode << endl;
+ }
+
+ // close the data and control connections ...
+ ftpCloseDataConnection();
+ ftpCloseControlConnection();
+}
+
+void Ftp::setHost( const TQString& _host, int _port, const TQString& _user,
+ const TQString& _pass )
+{
+ kdDebug(7102) << "Ftp::setHost (" << getpid() << "): " << _host << endl;
+
+ m_proxyURL = metaData("UseProxy");
+ m_bUseProxy = (m_proxyURL.isValid() && m_proxyURL.protocol() == "ftp");
+
+ if ( m_host != _host || m_port != _port ||
+ m_user != _user || m_pass != _pass )
+ closeConnection();
+
+ m_host = _host;
+ m_port = _port;
+ m_user = _user;
+ m_pass = _pass;
+}
+
+void Ftp::openConnection()
+{
+ ftpOpenConnection(loginExplicit);
+}
+
+bool Ftp::ftpOpenConnection (LoginMode loginMode)
+{
+ // check for implicit login if we are already logged on ...
+ if(loginMode == loginImplicit && m_bLoggedOn)
+ {
+ assert(m_control != NULL); // must have control connection socket
+ return true;
+ }
+
+ kdDebug(7102) << "ftpOpenConnection " << m_host << ":" << m_port << " "
+ << m_user << " [password hidden]" << endl;
+
+ infoMessage( i18n("Opening connection to host %1").arg(m_host) );
+
+ if ( m_host.isEmpty() )
+ {
+ error( ERR_UNKNOWN_HOST, TQString::null );
+ return false;
+ }
+
+ assert( !m_bLoggedOn );
+
+ m_initialPath = TQString::null;
+ m_currentPath = TQString::null;
+
+ TQString host = m_bUseProxy ? m_proxyURL.host() : m_host;
+ unsigned short int port = m_bUseProxy ? m_proxyURL.port() : m_port;
+
+ if (!ftpOpenControlConnection(host, port) )
+ return false; // error emitted by ftpOpenControlConnection
+ infoMessage( i18n("Connected to host %1").arg(m_host) );
+
+ if(loginMode != loginDefered)
+ {
+ m_bLoggedOn = ftpLogin();
+ if( !m_bLoggedOn )
+ return false; // error emitted by ftpLogin
+ }
+
+ m_bTextMode = config()->readBoolEntry("textmode", false);
+ connected();
+ return true;
+}
+
+
+/**
+ * Called by @ref openConnection. It opens the control connection to the ftp server.
+ *
+ * @return true on success.
+ */
+bool Ftp::ftpOpenControlConnection( const TQString &host, unsigned short int port )
+{
+ if ( port == 0 ) {
+ struct servent *pse;
+ if ( ( pse = getservbyname( "ftp", "tcp" ) ) == NULL )
+ port = 21;
+ else
+ port = ntohs(pse->s_port);
+ }
+
+ // implicitly close, then try to open a new connection ...
+ closeConnection();
+ int iErrorCode = ERR_OUT_OF_MEMORY;
+ TQString sErrorMsg;
+ m_control = new FtpSocket("CNTL");
+ if(m_control != NULL)
+ {
+ // now connect to the server and read the login message ...
+ m_control->setAddress(host, port);
+ iErrorCode = m_control->connectSocket(connectTimeout(), true);
+ sErrorMsg = host;
+
+ // on connect success try to read the server message...
+ if(iErrorCode == 0)
+ {
+ const char* psz = ftpResponse(-1);
+ if(m_iRespType != 2)
+ { // login not successful, do we have an message text?
+ if(psz[0])
+ sErrorMsg = i18n("%1.\n\nReason: %2").arg(host).arg(psz);
+ iErrorCode = ERR_COULD_NOT_CONNECT;
+ }
+ }
+ }
+
+ // if there was a problem - report it ...
+ if(iErrorCode == 0) // OK, return success
+ return true;
+ closeConnection(); // clean-up on error
+ error(iErrorCode, sErrorMsg);
+ return false;
+}
+
+/**
+ * Called by @ref openConnection. It logs us in.
+ * @ref m_initialPath is set to the current working directory
+ * if logging on was successful.
+ *
+ * @return true on success.
+ */
+bool Ftp::ftpLogin()
+{
+ infoMessage( i18n("Sending login information") );
+
+ assert( !m_bLoggedOn );
+
+ TQString user = m_user;
+ TQString pass = m_pass;
+
+ if ( config()->readBoolEntry("EnableAutoLogin") )
+ {
+ TQString au = config()->readEntry("autoLoginUser");
+ if ( !au.isEmpty() )
+ {
+ user = au;
+ pass = config()->readEntry("autoLoginPass");
+ }
+ }
+
+ // Try anonymous login if both username/password
+ // information is blank.
+ if (user.isEmpty() && pass.isEmpty())
+ {
+ user = FTP_LOGIN;
+ pass = FTP_PASSWD;
+ }
+
+ AuthInfo info;
+ info.url.setProtocol( "ftp" );
+ info.url.setHost( m_host );
+ info.url.setPort( m_port );
+ info.url.setUser( user );
+
+ TQCString tempbuf;
+ int failedAuth = 0;
+
+ do
+ {
+ // Check the cache and/or prompt user for password if 1st
+ // login attempt failed OR the user supplied a login name,
+ // but no password.
+ if ( failedAuth > 0 || (!user.isEmpty() && pass.isEmpty()) )
+ {
+ TQString errorMsg;
+ kdDebug(7102) << "Prompting user for login info..." << endl;
+
+ // Ask user if we should retry after when login fails!
+ if( failedAuth > 0 )
+ {
+ errorMsg = i18n("Message sent:\nLogin using username=%1 and "
+ "password=[hidden]\n\nServer replied:\n%2\n\n"
+ ).arg(user).arg(ftpResponse(0));
+ }
+
+ if ( user != FTP_LOGIN )
+ info.username = user;
+
+ info.prompt = i18n("You need to supply a username and a password "
+ "to access this site.");
+ info.commentLabel = i18n( "Site:" );
+ info.comment = i18n("<b>%1</b>").arg( m_host );
+ info.keepPassword = true; // Prompt the user for persistence as well.
+ info.readOnly = (!m_user.isEmpty() && m_user != FTP_LOGIN);
+
+ bool disablePassDlg = config()->readBoolEntry( "DisablePassDlg", false );
+ if ( disablePassDlg || !openPassDlg( info, errorMsg ) )
+ {
+ error( ERR_USER_CANCELED, m_host );
+ return false;
+ }
+ else
+ {
+ user = info.username;
+ pass = info.password;
+ }
+ }
+
+ tempbuf = "USER ";
+ tempbuf += user.latin1();
+ if ( m_bUseProxy )
+ {
+ tempbuf += '@';
+ tempbuf += m_host.latin1();
+ if ( m_port > 0 && m_port != DEFAULT_FTP_PORT )
+ {
+ tempbuf += ':';
+ tempbuf += TQString::number(m_port).latin1();
+ }
+ }
+
+ kdDebug(7102) << "Sending Login name: " << tempbuf << endl;
+
+ bool loggedIn = ( ftpSendCmd(tempbuf) && (m_iRespCode == 230) );
+ bool needPass = (m_iRespCode == 331);
+ // Prompt user for login info if we do not
+ // get back a "230" or "331".
+ if ( !loggedIn && !needPass )
+ {
+ kdDebug(7102) << "Login failed: " << ftpResponse(0) << endl;
+ ++failedAuth;
+ continue; // Well we failed, prompt the user please!!
+ }
+
+ if( needPass )
+ {
+ tempbuf = "pass ";
+ tempbuf += pass.latin1();
+ kdDebug(7102) << "Sending Login password: " << "[protected]" << endl;
+ loggedIn = ( ftpSendCmd(tempbuf) && (m_iRespCode == 230) );
+ }
+
+ if ( loggedIn )
+ {
+ // Do not cache the default login!!
+ if( user != FTP_LOGIN && pass != FTP_PASSWD )
+ cacheAuthentication( info );
+ failedAuth = -1;
+ }
+
+ } while( ++failedAuth );
+
+
+ kdDebug(7102) << "Login OK" << endl;
+ infoMessage( i18n("Login OK") );
+
+ // Okay, we're logged in. If this is IIS 4, switch dir listing style to Unix:
+ // Thanks to jk@soegaard.net (Jens Kristian Søgaard) for this hint
+ if( ftpSendCmd("SYST") && (m_iRespType == 2) )
+ {
+ if( !strncmp( ftpResponse(0), "215 Windows_NT", 14 ) ) // should do for any version
+ {
+ ftpSendCmd( "site dirstyle" );
+ // Check if it was already in Unix style
+ // Patch from Keith Refson <Keith.Refson@earth.ox.ac.uk>
+ if( !strncmp( ftpResponse(0), "200 MSDOS-like directory output is on", 37 ))
+ //It was in Unix style already!
+ ftpSendCmd( "site dirstyle" );
+ // windows won't support chmod before KDE konquers their desktop...
+ m_extControl |= chmodUnknown;
+ }
+ }
+ else
+ kdWarning(7102) << "SYST failed" << endl;
+
+ if ( config()->readBoolEntry ("EnableAutoLoginMacro") )
+ ftpAutoLoginMacro ();
+
+ // Get the current working directory
+ kdDebug(7102) << "Searching for pwd" << endl;
+ if( !ftpSendCmd("PWD") || (m_iRespType != 2) )
+ {
+ kdDebug(7102) << "Couldn't issue pwd command" << endl;
+ error( ERR_COULD_NOT_LOGIN, i18n("Could not login to %1.").arg(m_host) ); // or anything better ?
+ return false;
+ }
+
+ TQString sTmp = remoteEncoding()->decode( ftpResponse(3) );
+ int iBeg = sTmp.find('"');
+ int iEnd = sTmp.findRev('"');
+ if(iBeg > 0 && iBeg < iEnd)
+ {
+ m_initialPath = sTmp.mid(iBeg+1, iEnd-iBeg-1);
+ if(m_initialPath[0] != '/') m_initialPath.prepend('/');
+ kdDebug(7102) << "Initial path set to: " << m_initialPath << endl;
+ m_currentPath = m_initialPath;
+ }
+ return true;
+}
+
+void Ftp::ftpAutoLoginMacro ()
+{
+ TQString macro = metaData( "autoLoginMacro" );
+
+ if ( macro.isEmpty() )
+ return;
+
+ TQStringList list = TQStringList::split('\n', macro);
+
+ for(TQStringList::Iterator it = list.begin() ; it != list.end() ; ++it )
+ {
+ if ( (*it).startsWith("init") )
+ {
+ list = TQStringList::split( '\\', macro);
+ it = list.begin();
+ ++it; // ignore the macro name
+
+ for( ; it != list.end() ; ++it )
+ {
+ // TODO: Add support for arbitrary commands
+ // besides simply changing directory!!
+ if ( (*it).startsWith( "cwd" ) )
+ ftpFolder( (*it).mid(4).stripWhiteSpace(), false );
+ }
+
+ break;
+ }
+ }
+}
+
+
+/**
+ * ftpSendCmd - send a command (@p cmd) and read response
+ *
+ * @param maxretries number of time it should retry. Since it recursively
+ * calls itself if it can't read the answer (this happens especially after
+ * timeouts), we need to limit the recursiveness ;-)
+ *
+ * return true if any response received, false on error
+ */
+bool Ftp::ftpSendCmd( const TQCString& cmd, int maxretries )
+{
+ assert(m_control != NULL); // must have control connection socket
+
+ if ( cmd.find( '\r' ) != -1 || cmd.find( '\n' ) != -1)
+ {
+ kdWarning(7102) << "Invalid command received (contains CR or LF):"
+ << cmd.data() << endl;
+ error( ERR_UNSUPPORTED_ACTION, m_host );
+ return false;
+ }
+
+ // Don't print out the password...
+ bool isPassCmd = (cmd.left(4).lower() == "pass");
+ if ( !isPassCmd )
+ kdDebug(7102) << "send> " << cmd.data() << endl;
+ else
+ kdDebug(7102) << "send> pass [protected]" << endl;
+
+ // Send the message...
+ TQCString buf = cmd;
+ buf += "\r\n"; // Yes, must use CR/LF - see http://cr.yp.to/ftp/request.html
+ int num = m_control->write(buf.data(), buf.length());
+
+ // If we were able to successfully send the command, then we will
+ // attempt to read the response. Otherwise, take action to re-attempt
+ // the login based on the maximum number of retires specified...
+ if( num > 0 )
+ ftpResponse(-1);
+ else
+ { m_iRespType = m_iRespCode = 0;
+ m_control->textClear();
+ }
+
+ // If respCh is NULL or the response is 421 (Timed-out), we try to re-send
+ // the command based on the value of maxretries.
+ if( (m_iRespType <= 0) || (m_iRespCode == 421) )
+ {
+ // We have not yet logged on...
+ if (!m_bLoggedOn)
+ {
+ // The command was sent from the ftpLogin function, i.e. we are actually
+ // attempting to login in. NOTE: If we already sent the username, we
+ // return false and let the user decide whether (s)he wants to start from
+ // the beginning...
+ if (maxretries > 0 && !isPassCmd)
+ {
+ closeConnection ();
+ if( ftpOpenConnection(loginDefered) )
+ ftpSendCmd ( cmd, maxretries - 1 );
+ }
+
+ return false;
+ }
+ else
+ {
+ if ( maxretries < 1 )
+ return false;
+ else
+ {
+ kdDebug(7102) << "Was not able to communicate with " << m_host << endl
+ << "Attempting to re-establish connection." << endl;
+
+ closeConnection(); // Close the old connection...
+ openConnection(); // Attempt to re-establish a new connection...
+
+ if (!m_bLoggedOn)
+ {
+ if (m_control != NULL) // if openConnection succeeded ...
+ {
+ kdDebug(7102) << "Login failure, aborting" << endl;
+ error (ERR_COULD_NOT_LOGIN, m_host);
+ closeConnection ();
+ }
+ return false;
+ }
+
+ kdDebug(7102) << "Logged back in, re-issuing command" << endl;
+
+ // If we were able to login, resend the command...
+ if (maxretries)
+ maxretries--;
+
+ return ftpSendCmd( cmd, maxretries );
+ }
+ }
+ }
+
+ return true;
+}
+
+/*
+ * ftpOpenPASVDataConnection - set up data connection, using PASV mode
+ *
+ * return 1 if successful, 0 otherwise
+ * doesn't set error message, since non-pasv mode will always be tried if
+ * this one fails
+ */
+int Ftp::ftpOpenPASVDataConnection()
+{
+ assert(m_control != NULL); // must have control connection socket
+ assert(m_data == NULL); // ... but no data connection
+
+ // Check that we can do PASV
+ const TDESocketAddress *sa = m_control->peerAddress();
+ if (sa != NULL && sa->family() != PF_INET)
+ return ERR_INTERNAL; // no PASV for non-PF_INET connections
+
+ const KInetSocketAddress *sin = static_cast<const KInetSocketAddress*>(sa);
+
+ if (m_extControl & pasvUnknown)
+ return ERR_INTERNAL; // already tried and got "unknown command"
+
+ m_bPasv = true;
+
+ /* Let's PASsiVe*/
+ if( !ftpSendCmd("PASV") || (m_iRespType != 2) )
+ {
+ kdDebug(7102) << "PASV attempt failed" << endl;
+ // unknown command?
+ if( m_iRespType == 5 )
+ {
+ kdDebug(7102) << "disabling use of PASV" << endl;
+ m_extControl |= pasvUnknown;
+ }
+ return ERR_INTERNAL;
+ }
+
+ // The usual answer is '227 Entering Passive Mode. (160,39,200,55,6,245)'
+ // but anonftpd gives '227 =160,39,200,55,6,245'
+ int i[6];
+ const char *start = strchr(ftpResponse(3), '(');
+ if ( !start )
+ start = strchr(ftpResponse(3), '=');
+ if ( !start ||
+ ( sscanf(start, "(%d,%d,%d,%d,%d,%d)",&i[0], &i[1], &i[2], &i[3], &i[4], &i[5]) != 6 &&
+ sscanf(start, "=%d,%d,%d,%d,%d,%d", &i[0], &i[1], &i[2], &i[3], &i[4], &i[5]) != 6 ) )
+ {
+ kdError(7102) << "parsing IP and port numbers failed. String parsed: " << start << endl;
+ return ERR_INTERNAL;
+ }
+
+ // Make hostname and port number ...
+ int port = i[4] << 8 | i[5];
+
+ // we ignore the host part on purpose for two reasons
+ // a) it might be wrong anyway
+ // b) it would make us being suceptible to a port scanning attack
+
+ // now connect the data socket ...
+ m_data = new FtpSocket("PASV");
+ m_data->setAddress(sin->nodeName(), port);
+
+ kdDebug(7102) << "Connecting to " << sin->nodeName() << " on port " << port << endl;
+ return m_data->connectSocket(connectTimeout(), false);
+}
+
+/*
+ * ftpOpenEPSVDataConnection - opens a data connection via EPSV
+ */
+int Ftp::ftpOpenEPSVDataConnection()
+{
+ assert(m_control != NULL); // must have control connection socket
+ assert(m_data == NULL); // ... but no data connection
+
+ const TDESocketAddress *sa = m_control->peerAddress();
+ int portnum;
+ // we are sure sa is a KInetSocketAddress, because we asked for KExtendedSocket::inetSocket
+ // when we connected
+ const KInetSocketAddress *sin = static_cast<const KInetSocketAddress*>(sa);
+
+ if (m_extControl & epsvUnknown || sa == NULL)
+ return ERR_INTERNAL;
+
+ m_bPasv = true;
+ if( !ftpSendCmd("EPSV") || (m_iRespType != 2) )
+ {
+ // unknown command?
+ if( m_iRespType == 5 )
+ {
+ kdDebug(7102) << "disabling use of EPSV" << endl;
+ m_extControl |= epsvUnknown;
+ }
+ return ERR_INTERNAL;
+ }
+
+ const char *start = strchr(ftpResponse(3), '|');
+ if ( !start || sscanf(start, "|||%d|", &portnum) != 1)
+ return ERR_INTERNAL;
+
+ m_data = new FtpSocket("EPSV");
+ m_data->setAddress(sin->nodeName(), portnum);
+ return m_data->connectSocket(connectTimeout(), false) != 0;
+}
+
+/*
+ * ftpOpenEPRTDataConnection
+ * @return 0 on success, ERR_INTERNAL if mode not acceptable -or- a fatal error code
+ */
+int Ftp::ftpOpenEPRTDataConnection()
+{
+ assert(m_control != NULL); // must have control connection socket
+ assert(m_data == NULL); // ... but no data connection
+
+ // yes, we are sure this is a KInetSocketAddress
+ const KInetSocketAddress *sin = static_cast<const KInetSocketAddress*>(m_control->localAddress());
+ m_bPasv = false;
+ if (m_extControl & eprtUnknown || sin == NULL)
+ return ERR_INTERNAL;
+
+ m_data = new FtpSocket("EPRT");
+ m_data->setHost(sin->nodeName());
+ m_data->setPort(0); // setting port to 0 will make us bind to a random, free port
+ m_data->setSocketFlags(KExtendedSocket::noResolve | KExtendedSocket::passiveSocket |
+ KExtendedSocket::inetSocket);
+
+ if (m_data->listen(1) < 0)
+ return ERR_COULD_NOT_LISTEN;
+
+ sin = static_cast<const KInetSocketAddress*>(m_data->localAddress());
+ if (sin == NULL)
+ return ERR_INTERNAL;
+
+ // TQString command = TQString::fromLatin1("eprt |%1|%2|%3|").arg(sin->ianaFamily())
+ // .arg(sin->nodeName())
+ // .arg(sin->port());
+ TQCString command;
+ command.sprintf("eprt |%d|%s|%d|", sin->ianaFamily(),
+ sin->nodeName().latin1(), sin->port());
+
+ // FIXME! Encoding for hostnames?
+ if( ftpSendCmd(command) && (m_iRespType == 2) )
+ return 0;
+
+ // unknown command?
+ if( m_iRespType == 5 )
+ {
+ kdDebug(7102) << "disabling use of EPRT" << endl;
+ m_extControl |= eprtUnknown;
+ }
+ return ERR_INTERNAL;
+}
+
+/*
+ * ftpOpenDataConnection - set up data connection
+ *
+ * The routine calls several ftpOpenXxxxConnection() helpers to find
+ * the best connection mode. If a helper cannot connect if returns
+ * ERR_INTERNAL - so this is not really an error! All other error
+ * codes are treated as fatal, e.g. they are passed back to the caller
+ * who is responsible for calling error(). ftpOpenPortDataConnection
+ * can be called as last try and it does never return ERR_INTERNAL.
+ *
+ * @return 0 if successful, err code otherwise
+ */
+int Ftp::ftpOpenDataConnection()
+{
+ // make sure that we are logged on and have no data connection...
+ assert( m_bLoggedOn );
+ ftpCloseDataConnection();
+
+ int iErrCode = 0;
+ int iErrCodePASV = 0; // Remember error code from PASV
+
+ // First try passive (EPSV & PASV) modes
+ if( !config()->readBoolEntry("DisablePassiveMode", false) )
+ {
+ iErrCode = ftpOpenPASVDataConnection();
+ if(iErrCode == 0)
+ return 0; // success
+ iErrCodePASV = iErrCode;
+ ftpCloseDataConnection();
+
+ if( !config()->readBoolEntry("DisableEPSV", false) )
+ {
+ iErrCode = ftpOpenEPSVDataConnection();
+ if(iErrCode == 0)
+ return 0; // success
+ ftpCloseDataConnection();
+ }
+
+ // if we sent EPSV ALL already and it was accepted, then we can't
+ // use active connections any more
+ if (m_extControl & epsvAllSent)
+ return iErrCodePASV ? iErrCodePASV : iErrCode;
+ }
+
+ if( !config()->readBoolEntry("DisableEPRT", false) )
+ {
+ iErrCode = ftpOpenEPRTDataConnection();
+ if(iErrCode == 0)
+ return 0; // success
+ ftpCloseDataConnection();
+ }
+
+ // fall back to port mode
+ iErrCode = ftpOpenPortDataConnection();
+ if(iErrCode == 0)
+ return 0; // success
+
+ ftpCloseDataConnection();
+ // prefer to return the error code from PASV if any, since that's what should have worked in the first place
+ return iErrCodePASV ? iErrCodePASV : iErrCode;
+}
+
+/*
+ * ftpOpenPortDataConnection - set up data connection
+ *
+ * @return 0 if successfull, err code otherwise (but never ERR_INTERNAL
+ * because this is the last connection mode that is tried)
+ */
+int Ftp::ftpOpenPortDataConnection()
+{
+ assert(m_control != NULL); // must have control connection socket
+ assert(m_data == NULL); // ... but no data connection
+
+ m_bPasv = false;
+
+ // create a socket, bind it and let it listen ...
+ m_data = new FtpSocket("PORT");
+ m_data->setSocketFlags(KExtendedSocket::noResolve | KExtendedSocket::passiveSocket |
+ KExtendedSocket::inetSocket);
+
+ // yes, we are sure this is a KInetSocketAddress
+ const KInetSocketAddress* pAddr = static_cast<const KInetSocketAddress*>(m_control->localAddress());
+ m_data->setAddress(pAddr->nodeName(), "0");
+ m_data->setAddressReusable(true);
+
+ if(m_data->listen(1) < 0)
+ return ERR_COULD_NOT_LISTEN;
+ struct linger lng = { 0, 0 };
+ if ( !m_data->setSocketOption(SO_LINGER, (char*)&lng, sizeof(lng)) )
+ return ERR_COULD_NOT_CREATE_SOCKET;
+
+ // send the PORT command ...
+ pAddr = static_cast<const KInetSocketAddress*>(m_data->localAddress());
+ struct sockaddr* psa = (struct sockaddr*)pAddr->addressV4();
+ unsigned char* pData = (unsigned char*)(psa->sa_data);
+ TQCString portCmd;
+ portCmd.sprintf("port %d,%d,%d,%d,%d,%d",
+ pData[2], pData[3], pData[4], pData[5], pData[0], pData[1]);
+ if( ftpSendCmd(portCmd) && (m_iRespType == 2) )
+ return 0;
+ return ERR_COULD_NOT_CONNECT;
+}
+
+/*
+ * ftpAcceptConnect - wait for incoming connection
+ * Used by @ref ftpOpenCommand
+ *
+ * return false on error or timeout
+ */
+int Ftp::ftpAcceptConnect()
+{
+ assert(m_data != NULL);
+
+ if ( m_bPasv )
+ {
+ m_data->setServer(-1);
+ return true;
+ }
+
+ int sSock = m_data->fd();
+ struct sockaddr addr;
+ for(;;)
+ {
+ fd_set mask;
+ FD_ZERO(&mask);
+ FD_SET(sSock,&mask);
+ int r = KSocks::self()->select(sSock + 1, &mask, NULL, NULL, 0L);
+ if( r < 0 && errno != EINTR && errno != EAGAIN )
+ continue;
+ if( r > 0 )
+ break;
+ }
+
+ ksocklen_t l = sizeof(addr);
+ m_data->setServer( KSocks::self()->accept(sSock, &addr, &l) );
+ return (m_data->server() != -1);
+}
+
+bool Ftp::ftpOpenCommand( const char *_command, const TQString & _path, char _mode,
+ int errorcode, TDEIO::fileoffset_t _offset )
+{
+ int errCode = 0;
+ if( !ftpDataMode(_mode) )
+ errCode = ERR_COULD_NOT_CONNECT;
+ else
+ errCode = ftpOpenDataConnection();
+
+ if(errCode != 0)
+ {
+ error(errCode, m_host);
+ return false;
+ }
+
+ if ( _offset > 0 ) {
+ // send rest command if offset > 0, this applies to retr and stor commands
+ char buf[100];
+ sprintf(buf, "rest %lld", _offset);
+ if ( !ftpSendCmd( buf ) )
+ return false;
+ if( m_iRespType != 3 )
+ {
+ error( ERR_CANNOT_RESUME, _path ); // should never happen
+ return false;
+ }
+ }
+
+ TQCString tmp = _command;
+ TQString errormessage;
+
+ if ( !_path.isEmpty() ) {
+ tmp += " ";
+ tmp += remoteEncoding()->encode(_path);
+ }
+
+ if( !ftpSendCmd( tmp ) || (m_iRespType != 1) )
+ {
+ if( _offset > 0 && strcmp(_command, "retr") == 0 && (m_iRespType == 4) )
+ errorcode = ERR_CANNOT_RESUME;
+ // The error here depends on the command
+ errormessage = _path;
+ }
+
+ else
+ {
+ // Only now we know for sure that we can resume
+ if ( _offset > 0 && strcmp(_command, "retr") == 0 )
+ canResume();
+
+ if( ftpAcceptConnect() )
+ { m_bBusy = true; // cleared in ftpCloseCommand
+ return true;
+ }
+ errorcode = ERR_COULD_NOT_ACCEPT;
+ }
+
+ error(errorcode, errormessage);
+ return false;
+}
+
+
+bool Ftp::ftpCloseCommand()
+{
+ // first close data sockets (if opened), then read response that
+ // we got for whatever was used in ftpOpenCommand ( should be 226 )
+ if(m_data)
+ {
+ delete m_data;
+ m_data = NULL;
+ }
+ if(!m_bBusy)
+ return true;
+
+ kdDebug(7102) << "ftpCloseCommand: reading command result" << endl;
+ m_bBusy = false;
+
+ if(!ftpResponse(-1) || (m_iRespType != 2) )
+ {
+ kdDebug(7102) << "ftpCloseCommand: no transfer complete message" << endl;
+ return false;
+ }
+ return true;
+}
+
+void Ftp::mkdir( const KURL & url, int permissions )
+{
+ if( !ftpOpenConnection(loginImplicit) )
+ return;
+
+ TQString path = remoteEncoding()->encode(url);
+ TQCString buf = "mkd ";
+ buf += remoteEncoding()->encode(path);
+
+ if( !ftpSendCmd( buf ) || (m_iRespType != 2) )
+ {
+ TQString currentPath( m_currentPath );
+
+ // Check whether or not mkdir failed because
+ // the directory already exists...
+ if( ftpFolder( path, false ) )
+ {
+ error( ERR_DIR_ALREADY_EXIST, path );
+ // Change the directory back to what it was...
+ (void) ftpFolder( currentPath, false );
+ return;
+ }
+
+ error( ERR_COULD_NOT_MKDIR, path );
+ return;
+ }
+
+ if ( permissions != -1 )
+ {
+ // chmod the dir we just created, ignoring errors.
+ (void) ftpChmod( path, permissions );
+ }
+
+ finished();
+}
+
+void Ftp::rename( const KURL& src, const KURL& dst, bool overwrite )
+{
+ if( !ftpOpenConnection(loginImplicit) )
+ return;
+
+ // The actual functionality is in ftpRename because put needs it
+ if ( ftpRename( src.path(), dst.path(), overwrite ) )
+ finished();
+ else
+ error( ERR_CANNOT_RENAME, src.path() );
+}
+
+bool Ftp::ftpRename( const TQString & src, const TQString & dst, bool overwrite )
+{
+ assert( m_bLoggedOn );
+
+ // Must check if dst already exists, RNFR+RNTO overwrites by default (#127793).
+ if (!overwrite) {
+ if (ftpSize(dst, 'I')) {
+ error(ERR_FILE_ALREADY_EXIST, dst);
+ return false;
+ }
+ }
+ if (ftpFolder(dst, false)) {
+ error(ERR_DIR_ALREADY_EXIST, dst);
+ return false;
+ }
+
+ // Must check if dst already exists, RNFR+RNTO overwrites by default (#127793).
+ if (ftpFileExists(dst)) {
+ error(ERR_FILE_ALREADY_EXIST, dst);
+ return false;
+ }
+ if (ftpFolder(dst, false)) {
+ error(ERR_DIR_ALREADY_EXIST, dst);
+ return false;
+ }
+
+ int pos = src.findRev("/");
+ if( !ftpFolder(src.left(pos+1), false) )
+ return false;
+
+ TQCString from_cmd = "RNFR ";
+ from_cmd += remoteEncoding()->encode(src.mid(pos+1));
+ if( !ftpSendCmd( from_cmd ) || (m_iRespType != 3) )
+ return false;
+
+ TQCString to_cmd = "RNTO ";
+ to_cmd += remoteEncoding()->encode(dst);
+ if( !ftpSendCmd( to_cmd ) || (m_iRespType != 2) )
+ return false;
+
+ return true;
+}
+
+void Ftp::del( const KURL& url, bool isfile )
+{
+ if( !ftpOpenConnection(loginImplicit) )
+ return;
+
+ // When deleting a directory, we must exit from it first
+ // The last command probably went into it (to stat it)
+ if ( !isfile )
+ ftpFolder(remoteEncoding()->directory(url), false); // ignore errors
+
+ TQCString cmd = isfile ? "DELE " : "RMD ";
+ cmd += remoteEncoding()->encode(url);
+
+ if( !ftpSendCmd( cmd ) || (m_iRespType != 2) )
+ error( ERR_CANNOT_DELETE, url.path() );
+ else
+ finished();
+}
+
+bool Ftp::ftpChmod( const TQString & path, int permissions )
+{
+ assert( m_bLoggedOn );
+
+ if(m_extControl & chmodUnknown) // previous errors?
+ return false;
+
+ // we need to do bit AND 777 to get permissions, in case
+ // we were sent a full mode (unlikely)
+ TQCString cmd;
+ cmd.sprintf("SITE CHMOD %o ", permissions & 511 );
+ cmd += remoteEncoding()->encode(path);
+
+ ftpSendCmd(cmd);
+ if(m_iRespType == 2)
+ return true;
+
+ if(m_iRespCode == 500)
+ {
+ m_extControl |= chmodUnknown;
+ kdDebug(7102) << "ftpChmod: CHMOD not supported - disabling";
+ }
+ return false;
+}
+
+void Ftp::chmod( const KURL & url, int permissions )
+{
+ if( !ftpOpenConnection(loginImplicit) )
+ return;
+
+ if ( !ftpChmod( url.path(), permissions ) )
+ error( ERR_CANNOT_CHMOD, url.path() );
+ else
+ finished();
+}
+
+void Ftp::ftpCreateUDSEntry( const TQString & filename, FtpEntry& ftpEnt, UDSEntry& entry, bool isDir )
+{
+ assert(entry.count() == 0); // by contract :-)
+ UDSAtom atom;
+ atom.m_uds = UDS_NAME;
+ atom.m_str = filename;
+ entry.append( atom );
+
+ atom.m_uds = UDS_SIZE;
+ atom.m_long = ftpEnt.size;
+ entry.append( atom );
+
+ atom.m_uds = UDS_MODIFICATION_TIME;
+ atom.m_long = ftpEnt.date;
+ entry.append( atom );
+
+ atom.m_uds = UDS_ACCESS;
+ atom.m_long = ftpEnt.access;
+ entry.append( atom );
+
+ atom.m_uds = UDS_USER;
+ atom.m_str = ftpEnt.owner;
+ entry.append( atom );
+
+ if ( !ftpEnt.group.isEmpty() )
+ {
+ atom.m_uds = UDS_GROUP;
+ atom.m_str = ftpEnt.group;
+ entry.append( atom );
+ }
+
+ if ( !ftpEnt.link.isEmpty() )
+ {
+ atom.m_uds = UDS_LINK_DEST;
+ atom.m_str = ftpEnt.link;
+ entry.append( atom );
+
+ KMimeType::Ptr mime = KMimeType::findByURL( KURL("ftp://host/" + filename ) );
+ // Links on ftp sites are often links to dirs, and we have no way to check
+ // that. Let's do like Netscape : assume dirs generally.
+ // But we do this only when the mimetype can't be known from the filename.
+ // --> we do better than Netscape :-)
+ if ( mime->name() == KMimeType::defaultMimeType() )
+ {
+ kdDebug(7102) << "Setting guessed mime type to inode/directory for " << filename << endl;
+ atom.m_uds = UDS_GUESSED_MIME_TYPE;
+ atom.m_str = "inode/directory";
+ entry.append( atom );
+ isDir = true;
+ }
+ }
+
+ atom.m_uds = UDS_FILE_TYPE;
+ atom.m_long = isDir ? S_IFDIR : ftpEnt.type;
+ entry.append( atom );
+
+ /* atom.m_uds = UDS_ACCESS_TIME;
+ atom.m_long = buff.st_atime;
+ entry.append( atom );
+
+ atom.m_uds = UDS_CREATION_TIME;
+ atom.m_long = buff.st_ctime;
+ entry.append( atom ); */
+}
+
+
+void Ftp::ftpShortStatAnswer( const TQString& filename, bool isDir )
+{
+ UDSEntry entry;
+ UDSAtom atom;
+
+ atom.m_uds = TDEIO::UDS_NAME;
+ atom.m_str = filename;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_FILE_TYPE;
+ atom.m_long = isDir ? S_IFDIR : S_IFREG;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
+ entry.append( atom );
+
+ // No details about size, ownership, group, etc.
+
+ statEntry(entry);
+ finished();
+}
+
+void Ftp::ftpStatAnswerNotFound( const TQString & path, const TQString & filename )
+{
+ // Only do the 'hack' below if we want to download an existing file (i.e. when looking at the "source")
+ // When e.g. uploading a file, we still need stat() to return "not found"
+ // when the file doesn't exist.
+ TQString statSide = metaData("statSide");
+ kdDebug(7102) << "Ftp::stat statSide=" << statSide << endl;
+ if ( statSide == "source" )
+ {
+ kdDebug(7102) << "Not found, but assuming found, because some servers don't allow listing" << endl;
+ // MS Server is incapable of handling "list <blah>" in a case insensitive way
+ // But "retr <blah>" works. So lie in stat(), to get going...
+ //
+ // There's also the case of ftp://ftp2.3ddownloads.com/90380/linuxgames/loki/patches/ut/ut-patch-436.run
+ // where listing permissions are denied, but downloading is still possible.
+ ftpShortStatAnswer( filename, false /*file, not dir*/ );
+
+ return;
+ }
+
+ error( ERR_DOES_NOT_EXIST, path );
+}
+
+void Ftp::stat( const KURL &url)
+{
+ kdDebug(7102) << "Ftp::stat : path='" << url.path() << "'" << endl;
+ if( !ftpOpenConnection(loginImplicit) )
+ return;
+
+ TQString path = TQDir::cleanDirPath( url.path() );
+ kdDebug(7102) << "Ftp::stat : cleaned path='" << path << "'" << endl;
+
+ // We can't stat root, but we know it's a dir.
+ if( path.isEmpty() || path == "/" )
+ {
+ UDSEntry entry;
+ UDSAtom atom;
+
+ atom.m_uds = TDEIO::UDS_NAME;
+ atom.m_str = TQString::null;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_FILE_TYPE;
+ atom.m_long = S_IFDIR;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_USER;
+ atom.m_str = "root";
+ entry.append( atom );
+ atom.m_uds = TDEIO::UDS_GROUP;
+ entry.append( atom );
+
+ // no size
+
+ statEntry( entry );
+ finished();
+ return;
+ }
+
+ KURL tempurl( url );
+ tempurl.setPath( path ); // take the clean one
+ TQString listarg; // = tempurl.directory(false /*keep trailing slash*/);
+ TQString parentDir;
+ TQString filename = tempurl.fileName();
+ Q_ASSERT(!filename.isEmpty());
+ TQString search = filename;
+
+ // Try cwd into it, if it works it's a dir (and then we'll list the parent directory to get more info)
+ // if it doesn't work, it's a file (and then we'll use dir filename)
+ bool isDir = ftpFolder(path, false);
+
+ // if we're only interested in "file or directory", we should stop here
+ TQString sDetails = metaData("details");
+ int details = sDetails.isEmpty() ? 2 : sDetails.toInt();
+ kdDebug(7102) << "Ftp::stat details=" << details << endl;
+ if ( details == 0 )
+ {
+ if ( !isDir && !ftpSize( path, 'I' ) ) // ok, not a dir -> is it a file ?
+ { // no -> it doesn't exist at all
+ ftpStatAnswerNotFound( path, filename );
+ return;
+ }
+ ftpShortStatAnswer( filename, isDir ); // successfully found a dir or a file -> done
+ return;
+ }
+
+ if (!isDir)
+ {
+ // It is a file or it doesn't exist, try going to parent directory
+ parentDir = tempurl.directory(false /*keep trailing slash*/);
+ // With files we can do "LIST <filename>" to avoid listing the whole dir
+ listarg = filename;
+ }
+ else
+ {
+ // --- New implementation:
+ // Don't list the parent dir. Too slow, might not show it, etc.
+ // Just return that it's a dir.
+ UDSEntry entry;
+ UDSAtom atom;
+
+ atom.m_uds = TDEIO::UDS_NAME;
+ atom.m_str = filename;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_FILE_TYPE;
+ atom.m_long = S_IFDIR;
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
+ entry.append( atom );
+
+ // No clue about size, ownership, group, etc.
+
+ statEntry(entry);
+ finished();
+ return;
+
+ // --- Old implementation:
+#if 0
+ // It's a dir, remember that
+ // Reason: it could be a symlink to a dir, in which case ftpReadDir
+ // in the parent dir will have no idea about that. But we know better.
+ isDir = true;
+ // If the dir starts with '.', we'll need '-a' to see it in the listing.
+ if ( search[0] == '.' )
+ listarg = "-a";
+ parentDir = "..";
+#endif
+ }
+
+ // Now cwd the parent dir, to prepare for listing
+ if( !ftpFolder(parentDir, true) )
+ return;
+
+ if( !ftpOpenCommand( "list", listarg, 'I', ERR_DOES_NOT_EXIST ) )
+ {
+ kdError(7102) << "COULD NOT LIST" << endl;
+ return;
+ }
+ kdDebug(7102) << "Starting of list was ok" << endl;
+
+ Q_ASSERT( !search.isEmpty() && search != "/" );
+
+ bool bFound = false;
+ KURL linkURL;
+ FtpEntry ftpEnt;
+ while( ftpReadDir(ftpEnt) )
+ {
+ // We look for search or filename, since some servers (e.g. ftp.tuwien.ac.at)
+ // return only the filename when doing "dir /full/path/to/file"
+ if ( !bFound )
+ {
+ if ( ( search == ftpEnt.name || filename == ftpEnt.name ) ) {
+ if ( !filename.isEmpty() ) {
+ bFound = true;
+ UDSEntry entry;
+ ftpCreateUDSEntry( filename, ftpEnt, entry, isDir );
+ statEntry( entry );
+ }
+ } else if ( isDir && ( ftpEnt.name == listarg || ftpEnt.name+'/' == listarg ) ) {
+ // Damn, the dir we're trying to list is in fact a symlink
+ // Follow it and try again
+ if ( ftpEnt.link.isEmpty() )
+ kdWarning(7102) << "Got " << listarg << " as answer, but empty link!" << endl;
+ else
+ {
+ linkURL = url;
+ kdDebug(7102) << "ftpEnt.link=" << ftpEnt.link << endl;
+ if ( ftpEnt.link[0] == '/' )
+ linkURL.setPath( ftpEnt.link ); // Absolute link
+ else
+ {
+ // Relative link (stat will take care of cleaning ../.. etc.)
+ linkURL.setPath( listarg ); // this is what we were listing (the link)
+ linkURL.setPath( linkURL.directory() ); // go up one dir
+ linkURL.addPath( ftpEnt.link ); // replace link by its destination
+ kdDebug(7102) << "linkURL now " << linkURL.prettyURL() << endl;
+ }
+ // Re-add the filename we're looking for
+ linkURL.addPath( filename );
+ }
+ bFound = true;
+ }
+ }
+
+ // kdDebug(7102) << ftpEnt.name << endl;
+ }
+
+ ftpCloseCommand(); // closes the data connection only
+
+ if ( !bFound )
+ {
+ ftpStatAnswerNotFound( path, filename );
+ return;
+ }
+
+ if ( !linkURL.isEmpty() )
+ {
+ if ( linkURL == url || linkURL == tempurl )
+ {
+ error( ERR_CYCLIC_LINK, linkURL.prettyURL() );
+ return;
+ }
+ stat( linkURL );
+ return;
+ }
+
+ kdDebug(7102) << "stat : finished successfully" << endl;
+ finished();
+}
+
+
+void Ftp::listDir( const KURL &url )
+{
+ kdDebug(7102) << "Ftp::listDir " << url.prettyURL() << endl;
+ if( !ftpOpenConnection(loginImplicit) )
+ return;
+
+ // No path specified ?
+ TQString path = url.path();
+ if ( path.isEmpty() )
+ {
+ KURL realURL;
+ realURL.setProtocol( "ftp" );
+ if ( m_user != FTP_LOGIN )
+ realURL.setUser( m_user );
+ // We set the password, so that we don't ask for it if it was given
+ if ( m_pass != FTP_PASSWD )
+ realURL.setPass( m_pass );
+ realURL.setHost( m_host );
+ realURL.setPort( m_port );
+ if ( m_initialPath.isEmpty() )
+ m_initialPath = "/";
+ realURL.setPath( m_initialPath );
+ kdDebug(7102) << "REDIRECTION to " << realURL.prettyURL() << endl;
+ redirection( realURL );
+ finished();
+ return;
+ }
+
+ kdDebug(7102) << "hunting for path '" << path << "'" << endl;
+
+ if (!ftpOpenDir( path ) )
+ {
+ if ( ftpSize( path, 'I' ) ) // is it a file ?
+ {
+ error( ERR_IS_FILE, path );
+ return;
+ }
+ // not sure which to emit
+ //error( ERR_DOES_NOT_EXIST, path );
+ error( ERR_CANNOT_ENTER_DIRECTORY, path );
+ return;
+ }
+
+ UDSEntry entry;
+ FtpEntry ftpEnt;
+ while( ftpReadDir(ftpEnt) )
+ {
+ //kdDebug(7102) << ftpEnt.name << endl;
+ //Q_ASSERT( !ftpEnt.name.isEmpty() );
+ if ( !ftpEnt.name.isEmpty() )
+ {
+ //if ( S_ISDIR( (mode_t)ftpEnt.type ) )
+ // kdDebug(7102) << "is a dir" << endl;
+ //if ( !ftpEnt.link.isEmpty() )
+ // kdDebug(7102) << "is a link to " << ftpEnt.link << endl;
+ entry.clear();
+ ftpCreateUDSEntry( ftpEnt.name, ftpEnt, entry, false );
+ listEntry( entry, false );
+ }
+ }
+ listEntry( entry, true ); // ready
+ ftpCloseCommand(); // closes the data connection only
+ finished();
+}
+
+void Ftp::slave_status()
+{
+ kdDebug(7102) << "Got slave_status host = " << (m_host.ascii() ? m_host.ascii() : "[None]") << " [" << (m_bLoggedOn ? "Connected" : "Not connected") << "]" << endl;
+ slaveStatus( m_host, m_bLoggedOn );
+}
+
+bool Ftp::ftpOpenDir( const TQString & path )
+{
+ //TQString path( _url.path(-1) );
+
+ // We try to change to this directory first to see whether it really is a directory.
+ // (And also to follow symlinks)
+ TQString tmp = path.isEmpty() ? TQString("/") : path;
+
+ // We get '550', whether it's a file or doesn't exist...
+ if( !ftpFolder(tmp, false) )
+ return false;
+
+ // Don't use the path in the list command:
+ // We changed into this directory anyway - so it's enough just to send "list".
+ // We use '-a' because the application MAY be interested in dot files.
+ // The only way to really know would be to have a metadata flag for this...
+ // Since some windows ftp server seems not to support the -a argument, we use a fallback here.
+ // In fact we have to use -la otherwise -a removes the default -l (e.g. ftp.trolltech.com)
+ if( !ftpOpenCommand( "list -la", TQString::null, 'I', ERR_CANNOT_ENTER_DIRECTORY ) )
+ {
+ if ( !ftpOpenCommand( "list", TQString::null, 'I', ERR_CANNOT_ENTER_DIRECTORY ) )
+ {
+ kdWarning(7102) << "Can't open for listing" << endl;
+ return false;
+ }
+ }
+ kdDebug(7102) << "Starting of list was ok" << endl;
+ return true;
+}
+
+bool Ftp::ftpReadDir(FtpEntry& de)
+{
+ assert(m_data != NULL);
+
+ // get a line from the data connecetion ...
+ while( !m_data->textEOF() )
+ {
+ if(m_data->textRead() <= 0)
+ continue;
+ if(m_data->textTooLong())
+ kdWarning(7102) << "ftpReadDir line too long - truncated" << endl;
+
+ const char* buffer = m_data->textLine();
+ kdDebug(7102) << "dir > " << buffer << endl;
+
+ //Normally the listing looks like
+ // -rw-r--r-- 1 dfaure dfaure 102 Nov 9 12:30 log
+ // but on Netware servers like ftp://ci-1.ci.pwr.wroc.pl/ it looks like (#76442)
+ // d [RWCEAFMS] Admin 512 Oct 13 2004 PSI
+
+ // we should always get the following 5 fields ...
+ const char *p_access, *p_junk, *p_owner, *p_group, *p_size;
+ if( (p_access = strtok((char*)buffer," ")) == 0) continue;
+ if( (p_junk = strtok(NULL," ")) == 0) continue;
+ if( (p_owner = strtok(NULL," ")) == 0) continue;
+ if( (p_group = strtok(NULL," ")) == 0) continue;
+ if( (p_size = strtok(NULL," ")) == 0) continue;
+
+ //kdDebug(7102) << "p_access=" << p_access << " p_junk=" << p_junk << " p_owner=" << p_owner << " p_group=" << p_group << " p_size=" << p_size << endl;
+
+ de.access = 0;
+ if ( strlen( p_access ) == 1 && p_junk[0] == '[' ) { // Netware
+ de.access = S_IRWXU | S_IRWXG | S_IRWXO; // unknown -> give all permissions
+ }
+
+ const char *p_date_1, *p_date_2, *p_date_3, *p_name;
+
+ // A special hack for "/dev". A listing may look like this:
+ // crw-rw-rw- 1 root root 1, 5 Jun 29 1997 zero
+ // So we just ignore the number in front of the ",". Ok, its a hack :-)
+ if ( strchr( p_size, ',' ) != 0L )
+ {
+ //kdDebug(7102) << "Size contains a ',' -> reading size again (/dev hack)" << endl;
+ if ((p_size = strtok(NULL," ")) == 0)
+ continue;
+ }
+
+ // Check whether the size we just read was really the size
+ // or a month (this happens when the server lists no group)
+ // Used to be the case on sunsite.uio.no, but not anymore
+ // This is needed for the Netware case, too.
+ if ( !isdigit( *p_size ) )
+ {
+ p_date_1 = p_size;
+ p_size = p_group;
+ p_group = 0;
+ //kdDebug(7102) << "Size didn't have a digit -> size=" << p_size << " date_1=" << p_date_1 << endl;
+ }
+ else
+ {
+ p_date_1 = strtok(NULL," ");
+ //kdDebug(7102) << "Size has a digit -> ok. p_date_1=" << p_date_1 << endl;
+ }
+
+ if ( p_date_1 != 0 &&
+ (p_date_2 = strtok(NULL," ")) != 0 &&
+ (p_date_3 = strtok(NULL," ")) != 0 &&
+ (p_name = strtok(NULL,"\r\n")) != 0 )
+ {
+ {
+ TQCString tmp( p_name );
+ if ( p_access[0] == 'l' )
+ {
+ int i = tmp.findRev( " -> " );
+ if ( i != -1 ) {
+ de.link = remoteEncoding()->decode(p_name + i + 4);
+ tmp.truncate( i );
+ }
+ else
+ de.link = TQString::null;
+ }
+ else
+ de.link = TQString::null;
+
+ if ( tmp[0] == '/' ) // listing on ftp://ftp.gnupg.org/ starts with '/'
+ tmp.remove( 0, 1 );
+
+ if (tmp.find('/') != -1)
+ continue; // Don't trick us!
+ // Some sites put more than one space between the date and the name
+ // e.g. ftp://ftp.uni-marburg.de/mirror/
+ de.name = remoteEncoding()->decode(tmp.stripWhiteSpace());
+ }
+
+ de.type = S_IFREG;
+ switch ( p_access[0] ) {
+ case 'd':
+ de.type = S_IFDIR;
+ break;
+ case 's':
+ de.type = S_IFSOCK;
+ break;
+ case 'b':
+ de.type = S_IFBLK;
+ break;
+ case 'c':
+ de.type = S_IFCHR;
+ break;
+ case 'l':
+ de.type = S_IFREG;
+ // we don't set S_IFLNK here. de.link says it.
+ break;
+ default:
+ break;
+ }
+
+ if ( p_access[1] == 'r' )
+ de.access |= S_IRUSR;
+ if ( p_access[2] == 'w' )
+ de.access |= S_IWUSR;
+ if ( p_access[3] == 'x' || p_access[3] == 's' )
+ de.access |= S_IXUSR;
+ if ( p_access[4] == 'r' )
+ de.access |= S_IRGRP;
+ if ( p_access[5] == 'w' )
+ de.access |= S_IWGRP;
+ if ( p_access[6] == 'x' || p_access[6] == 's' )
+ de.access |= S_IXGRP;
+ if ( p_access[7] == 'r' )
+ de.access |= S_IROTH;
+ if ( p_access[8] == 'w' )
+ de.access |= S_IWOTH;
+ if ( p_access[9] == 'x' || p_access[9] == 't' )
+ de.access |= S_IXOTH;
+ if ( p_access[3] == 's' || p_access[3] == 'S' )
+ de.access |= S_ISUID;
+ if ( p_access[6] == 's' || p_access[6] == 'S' )
+ de.access |= S_ISGID;
+ if ( p_access[9] == 't' || p_access[9] == 'T' )
+ de.access |= S_ISVTX;
+
+ de.owner = remoteEncoding()->decode(p_owner);
+ de.group = remoteEncoding()->decode(p_group);
+ de.size = charToLongLong(p_size);
+
+ // Parsing the date is somewhat tricky
+ // Examples : "Oct 6 22:49", "May 13 1999"
+
+ // First get current time - we need the current month and year
+ time_t currentTime = time( 0L );
+ struct tm * tmptr = gmtime( &currentTime );
+ int currentMonth = tmptr->tm_mon;
+ //kdDebug(7102) << "Current time :" << asctime( tmptr ) << endl;
+ // Reset time fields
+ tmptr->tm_isdst = -1; // We do not know anything about day saving time (of any random day of the year)
+ tmptr->tm_sec = 0;
+ tmptr->tm_min = 0;
+ tmptr->tm_hour = 0;
+ // Get day number (always second field)
+ tmptr->tm_mday = atoi( p_date_2 );
+ // Get month from first field
+ // NOTE : no, we don't want to use KLocale here
+ // It seems all FTP servers use the English way
+ //kdDebug(7102) << "Looking for month " << p_date_1 << endl;
+ static const char * s_months[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
+ for ( int c = 0 ; c < 12 ; c ++ )
+ if ( !strcmp( p_date_1, s_months[c]) )
+ {
+ //kdDebug(7102) << "Found month " << c << " for " << p_date_1 << endl;
+ tmptr->tm_mon = c;
+ break;
+ }
+
+ // Parse third field
+ if ( strlen( p_date_3 ) == 4 ) // 4 digits, looks like a year
+ tmptr->tm_year = atoi( p_date_3 ) - 1900;
+ else
+ {
+ // otherwise, the year is implicit
+ // according to man ls, this happens when it is between than 6 months
+ // old and 1 hour in the future.
+ // So the year is : current year if tm_mon <= currentMonth+1
+ // otherwise current year minus one
+ // (The +1 is a security for the "+1 hour" at the end of the month issue)
+ if ( tmptr->tm_mon > currentMonth + 1 )
+ tmptr->tm_year--;
+
+ // and p_date_3 contains probably a time
+ char * semicolon;
+ if ( ( semicolon = const_cast<char*>(strchr( p_date_3, ':' )) ) )
+ {
+ *semicolon = '\0';
+ tmptr->tm_min = atoi( semicolon + 1 );
+ tmptr->tm_hour = atoi( p_date_3 );
+ }
+ else
+ kdWarning(7102) << "Can't parse third field " << p_date_3 << endl;
+ }
+
+ //kdDebug(7102) << asctime( tmptr ) << endl;
+ de.date = mktime( tmptr );
+ return true;
+ }
+ } // line invalid, loop to get another line
+ return false;
+}
+
+//===============================================================================
+// public: get download file from server
+// helper: ftpGet called from get() and copy()
+//===============================================================================
+void Ftp::get( const KURL & url )
+{
+ kdDebug(7102) << "Ftp::get " << url.url() << endl;
+ int iError = 0;
+ ftpGet(iError, -1, url, 0); // iError gets status
+ if(iError) // can have only server side errs
+ error(iError, url.path());
+ ftpCloseCommand(); // must close command!
+}
+
+Ftp::StatusCode Ftp::ftpGet(int& iError, int iCopyFile, const KURL& url, TDEIO::fileoffset_t llOffset)
+{
+ // Calls error() by itself!
+ if( !ftpOpenConnection(loginImplicit) )
+ return statusServerError;
+
+ // Try to find the size of the file (and check that it exists at
+ // the same time). If we get back a 550, "File does not exist"
+ // or "not a plain file", check if it is a directory. If it is a
+ // directory, return an error; otherwise simply try to retrieve
+ // the request...
+ if ( !ftpSize( url.path(), '?' ) && (m_iRespCode == 550) &&
+ ftpFolder(url.path(), false) )
+ {
+ // Ok it's a dir in fact
+ kdDebug(7102) << "ftpGet: it is a directory in fact" << endl;
+ iError = ERR_IS_DIRECTORY;
+ return statusServerError;
+ }
+
+ TQString resumeOffset = metaData("resume");
+ if ( !resumeOffset.isEmpty() )
+ {
+ llOffset = resumeOffset.toLongLong();
+ kdDebug(7102) << "ftpGet: got offset from metadata : " << llOffset << endl;
+ }
+
+ if( !ftpOpenCommand("retr", url.path(), '?', ERR_CANNOT_OPEN_FOR_READING, llOffset) )
+ {
+ kdWarning(7102) << "ftpGet: Can't open for reading" << endl;
+ return statusServerError;
+ }
+
+ // Read the size from the response string
+ if(m_size == UnknownSize)
+ {
+ const char* psz = strrchr( ftpResponse(4), '(' );
+ if(psz) m_size = charToLongLong(psz+1);
+ if (!m_size) m_size = UnknownSize;
+ }
+
+ TDEIO::filesize_t bytesLeft = 0;
+ if ( m_size != UnknownSize )
+ bytesLeft = m_size - llOffset;
+
+ kdDebug(7102) << "ftpGet: starting with offset=" << llOffset << endl;
+ TDEIO::fileoffset_t processed_size = llOffset;
+
+ TQByteArray array;
+ bool mimetypeEmitted = false;
+ char buffer[maximumIpcSize];
+ // start whith small data chunks in case of a slow data source (modem)
+ // - unfortunately this has a negative impact on performance for large
+ // - files - so we will increase the block size after a while ...
+ int iBlockSize = initialIpcSize;
+ int iBufferCur = 0;
+
+ while(m_size == UnknownSize || bytesLeft > 0)
+ { // let the buffer size grow if the file is larger 64kByte ...
+ if(processed_size-llOffset > 1024 * 64)
+ iBlockSize = maximumIpcSize;
+
+ // read the data and detect EOF or error ...
+ if(iBlockSize+iBufferCur > (int)sizeof(buffer))
+ iBlockSize = sizeof(buffer) - iBufferCur;
+ int n = m_data->read( buffer+iBufferCur, iBlockSize );
+ if(n <= 0)
+ { // this is how we detect EOF in case of unknown size
+ if( m_size == UnknownSize && n == 0 )
+ break;
+ // unexpected eof. Happens when the daemon gets killed.
+ iError = ERR_COULD_NOT_READ;
+ return statusServerError;
+ }
+ processed_size += n;
+
+ // collect very small data chunks in buffer before processing ...
+ if(m_size != UnknownSize)
+ {
+ bytesLeft -= n;
+ iBufferCur += n;
+ if(iBufferCur < mimimumMimeSize && bytesLeft > 0)
+ {
+ processedSize( processed_size );
+ continue;
+ }
+ n = iBufferCur;
+ iBufferCur = 0;
+ }
+
+ // get the mime type and set the total size ...
+ if(!mimetypeEmitted)
+ {
+ mimetypeEmitted = true;
+
+ // We need a KMimeType::findByNameAndContent(data,filename)
+ // For now we do: find by extension, and if not found (or extension not reliable)
+ // then find by content.
+ bool accurate = false;
+ KMimeType::Ptr mime = KMimeType::findByURL( url, 0, false, true, &accurate );
+ if ( !mime || mime->name() == KMimeType::defaultMimeType()
+ || !accurate )
+ {
+ array.setRawData(buffer, n);
+ KMimeMagicResult * result = KMimeMagic::self()->findBufferFileType(array, url.fileName());
+ array.resetRawData(buffer, n);
+ if ( result->mimeType() != KMimeType::defaultMimeType() )
+ mime = KMimeType::mimeType( result->mimeType() );
+ }
+
+ kdDebug(7102) << "ftpGet: Emitting mimetype " << mime->name() << endl;
+ mimeType( mime->name() );
+ if( m_size != UnknownSize ) // Emit total size AFTER mimetype
+ totalSize( m_size );
+ }
+
+ // write output file or pass to data pump ...
+ if(iCopyFile == -1)
+ {
+ array.setRawData(buffer, n);
+ data( array );
+ array.resetRawData(buffer, n);
+ }
+ else if( (iError = WriteToFile(iCopyFile, buffer, n)) != 0)
+ return statusClientError; // client side error
+ processedSize( processed_size );
+ }
+
+ kdDebug(7102) << "ftpGet: done" << endl;
+ if(iCopyFile == -1) // must signal EOF to data pump ...
+ data(array); // array is empty and must be empty!
+
+ processedSize( m_size == UnknownSize ? processed_size : m_size );
+ kdDebug(7102) << "ftpGet: emitting finished()" << endl;
+ finished();
+ return statusSuccess;
+}
+
+/*
+void Ftp::mimetype( const KURL& url )
+{
+ if( !ftpOpenConnection(loginImplicit) )
+ return;
+
+ if ( !ftpOpenCommand( "retr", url.path(), 'I', ERR_CANNOT_OPEN_FOR_READING, 0 ) ) {
+ kdWarning(7102) << "Can't open for reading" << endl;
+ return;
+ }
+ char buffer[ 2048 ];
+ TQByteArray array;
+ // Get one chunk of data only and send it, TDEIO::Job will determine the
+ // mimetype from it using KMimeMagic
+ int n = m_data->read( buffer, 2048 );
+ array.setRawData(buffer, n);
+ data( array );
+ array.resetRawData(buffer, n);
+
+ kdDebug(7102) << "aborting" << endl;
+ ftpAbortTransfer();
+
+ kdDebug(7102) << "finished" << endl;
+ finished();
+ kdDebug(7102) << "after finished" << endl;
+}
+
+void Ftp::ftpAbortTransfer()
+{
+ // RFC 959, page 34-35
+ // IAC (interpret as command) = 255 ; IP (interrupt process) = 254
+ // DM = 242 (data mark)
+ char msg[4];
+ // 1. User system inserts the Telnet "Interrupt Process" (IP) signal
+ // in the Telnet stream.
+ msg[0] = (char) 255; //IAC
+ msg[1] = (char) 254; //IP
+ (void) send(sControl, msg, 2, 0);
+ // 2. User system sends the Telnet "Sync" signal.
+ msg[0] = (char) 255; //IAC
+ msg[1] = (char) 242; //DM
+ if (send(sControl, msg, 2, MSG_OOB) != 2)
+ ; // error...
+
+ // Send ABOR
+ kdDebug(7102) << "send ABOR" << endl;
+ TQCString buf = "ABOR\r\n";
+ if ( KSocks::self()->write( sControl, buf.data(), buf.length() ) <= 0 ) {
+ error( ERR_COULD_NOT_WRITE, TQString::null );
+ return;
+ }
+
+ //
+ kdDebug(7102) << "read resp" << endl;
+ if ( readresp() != '2' )
+ {
+ error( ERR_COULD_NOT_READ, TQString::null );
+ return;
+ }
+
+ kdDebug(7102) << "close sockets" << endl;
+ closeSockets();
+}
+*/
+
+//===============================================================================
+// public: put upload file to server
+// helper: ftpPut called from put() and copy()
+//===============================================================================
+void Ftp::put(const KURL& url, int permissions, bool overwrite, bool resume)
+{
+ kdDebug(7102) << "Ftp::put " << url.url() << endl;
+ int iError = 0; // iError gets status
+ ftpPut(iError, -1, url, permissions, overwrite, resume);
+ if(iError) // can have only server side errs
+ error(iError, url.path());
+ ftpCloseCommand(); // must close command!
+}
+
+Ftp::StatusCode Ftp::ftpPut(int& iError, int iCopyFile, const KURL& dest_url,
+ int permissions, bool overwrite, bool resume)
+{
+ if( !ftpOpenConnection(loginImplicit) )
+ return statusServerError;
+
+ // Don't use mark partial over anonymous FTP.
+ // My incoming dir allows put but not rename...
+ bool bMarkPartial;
+ if (m_user.isEmpty () || m_user == FTP_LOGIN)
+ bMarkPartial = false;
+ else
+ bMarkPartial = config()->readBoolEntry("MarkPartial", true);
+
+ TQString dest_orig = dest_url.path();
+ TQString dest_part( dest_orig );
+ dest_part += ".part";
+
+ if ( ftpSize( dest_orig, 'I' ) )
+ {
+ if ( m_size == 0 )
+ { // delete files with zero size
+ TQCString cmd = "DELE ";
+ cmd += remoteEncoding()->encode(dest_orig);
+ if( !ftpSendCmd( cmd ) || (m_iRespType != 2) )
+ {
+ iError = ERR_CANNOT_DELETE_PARTIAL;
+ return statusServerError;
+ }
+ }
+ else if ( !overwrite && !resume )
+ {
+ iError = ERR_FILE_ALREADY_EXIST;
+ return statusServerError;
+ }
+ else if ( bMarkPartial )
+ { // when using mark partial, append .part extension
+ if ( !ftpRename( dest_orig, dest_part, true ) )
+ {
+ iError = ERR_CANNOT_RENAME_PARTIAL;
+ return statusServerError;
+ }
+ }
+ // Don't chmod an existing file
+ permissions = -1;
+ }
+ else if ( bMarkPartial && ftpSize( dest_part, 'I' ) )
+ { // file with extension .part exists
+ if ( m_size == 0 )
+ { // delete files with zero size
+ TQCString cmd = "DELE ";
+ cmd += remoteEncoding()->encode(dest_part);
+ if ( !ftpSendCmd( cmd ) || (m_iRespType != 2) )
+ {
+ iError = ERR_CANNOT_DELETE_PARTIAL;
+ return statusServerError;
+ }
+ }
+ else if ( !overwrite && !resume )
+ {
+ resume = canResume (m_size);
+ if (!resume)
+ {
+ iError = ERR_FILE_ALREADY_EXIST;
+ return statusServerError;
+ }
+ }
+ }
+ else
+ m_size = 0;
+
+ TQString dest;
+
+ // if we are using marking of partial downloads -> add .part extension
+ if ( bMarkPartial ) {
+ kdDebug(7102) << "Adding .part extension to " << dest_orig << endl;
+ dest = dest_part;
+ } else
+ dest = dest_orig;
+
+ TDEIO::fileoffset_t offset = 0;
+
+ // set the mode according to offset
+ if( resume && m_size > 0 )
+ {
+ offset = m_size;
+ if(iCopyFile != -1)
+ {
+ if( KDE_lseek(iCopyFile, offset, SEEK_SET) < 0 )
+ {
+ iError = ERR_CANNOT_RESUME;
+ return statusClientError;
+ }
+ }
+ }
+
+ if (! ftpOpenCommand( "stor", dest, '?', ERR_COULD_NOT_WRITE, offset ) )
+ return statusServerError;
+
+ kdDebug(7102) << "ftpPut: starting with offset=" << offset << endl;
+ TDEIO::fileoffset_t processed_size = offset;
+
+ TQByteArray buffer;
+ int result;
+ int iBlockSize = initialIpcSize;
+ // Loop until we got 'dataEnd'
+ do
+ {
+ if(iCopyFile == -1)
+ {
+ dataReq(); // Request for data
+ result = readData( buffer );
+ }
+ else
+ { // let the buffer size grow if the file is larger 64kByte ...
+ if(processed_size-offset > 1024 * 64)
+ iBlockSize = maximumIpcSize;
+ buffer.resize(iBlockSize);
+ result = ::read(iCopyFile, buffer.data(), buffer.size());
+ if(result < 0)
+ iError = ERR_COULD_NOT_WRITE;
+ else
+ buffer.resize(result);
+ }
+
+ if (result > 0)
+ {
+ m_data->write( buffer.data(), buffer.size() );
+ processed_size += result;
+ processedSize (processed_size);
+ }
+ }
+ while ( result > 0 );
+
+ if (result != 0) // error
+ {
+ ftpCloseCommand(); // don't care about errors
+ kdDebug(7102) << "Error during 'put'. Aborting." << endl;
+ if (bMarkPartial)
+ {
+ // Remove if smaller than minimum size
+ if ( ftpSize( dest, 'I' ) &&
+ ( processed_size < (unsigned long) config()->readNumEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE) ) )
+ {
+ TQCString cmd = "DELE ";
+ cmd += remoteEncoding()->encode(dest);
+ (void) ftpSendCmd( cmd );
+ }
+ }
+ return statusServerError;
+ }
+
+ if ( !ftpCloseCommand() )
+ {
+ iError = ERR_COULD_NOT_WRITE;
+ return statusServerError;
+ }
+
+ // after full download rename the file back to original name
+ if ( bMarkPartial )
+ {
+ kdDebug(7102) << "renaming dest (" << dest << ") back to dest_orig (" << dest_orig << ")" << endl;
+ if ( !ftpRename( dest, dest_orig, true ) )
+ {
+ iError = ERR_CANNOT_RENAME_PARTIAL;
+ return statusServerError;
+ }
+ }
+
+ // set final permissions
+ if ( permissions != -1 )
+ {
+ if ( m_user == FTP_LOGIN )
+ kdDebug(7102) << "Trying to chmod over anonymous FTP ???" << endl;
+ // chmod the file we just put
+ if ( ! ftpChmod( dest_orig, permissions ) )
+ {
+ // To be tested
+ //if ( m_user != FTP_LOGIN )
+ // warning( i18n( "Could not change permissions for\n%1" ).arg( dest_orig ) );
+ }
+ }
+
+ // We have done our job => finish
+ finished();
+ return statusSuccess;
+}
+
+
+/** Use the SIZE command to get the file size.
+ Warning : the size depends on the transfer mode, hence the second arg. */
+bool Ftp::ftpSize( const TQString & path, char mode )
+{
+ m_size = UnknownSize;
+ if( !ftpDataMode(mode) )
+ return false;
+
+ TQCString buf;
+ buf = "SIZE ";
+ buf += remoteEncoding()->encode(path);
+ if( !ftpSendCmd( buf ) || (m_iRespType != 2) )
+ return false;
+
+ // skip leading "213 " (response code)
+ const char* psz = ftpResponse(4);
+ if(!psz)
+ return false;
+ m_size = charToLongLong(psz);
+ if (!m_size) m_size = UnknownSize;
+ return true;
+}
+
+bool Ftp::ftpFileExists(const TQString& path)
+{
+ TQCString buf;
+ buf = "SIZE ";
+ buf += remoteEncoding()->encode(path);
+ if( !ftpSendCmd( buf ) || (m_iRespType != 2) )
+ return false;
+
+ // skip leading "213 " (response code)
+ const char* psz = ftpResponse(4);
+ return psz != 0;
+}
+
+// Today the differences between ASCII and BINARY are limited to
+// CR or CR/LF line terminators. Many servers ignore ASCII (like
+// win2003 -or- vsftp with default config). In the early days of
+// computing, when even text-files had structure, this stuff was
+// more important.
+// Theoretically "list" could return different results in ASCII
+// and BINARY mode. But again, most servers ignore ASCII here.
+bool Ftp::ftpDataMode(char cMode)
+{
+ if(cMode == '?') cMode = m_bTextMode ? 'A' : 'I';
+ else if(cMode == 'a') cMode = 'A';
+ else if(cMode != 'A') cMode = 'I';
+
+ kdDebug(7102) << "ftpDataMode: want '" << cMode << "' has '" << m_cDataMode << "'" << endl;
+ if(m_cDataMode == cMode)
+ return true;
+
+ TQCString buf;
+ buf.sprintf("TYPE %c", cMode);
+ if( !ftpSendCmd(buf) || (m_iRespType != 2) )
+ return false;
+ m_cDataMode = cMode;
+ return true;
+}
+
+
+bool Ftp::ftpFolder(const TQString& path, bool bReportError)
+{
+ TQString newPath = path;
+ int iLen = newPath.length();
+ if(iLen > 1 && newPath[iLen-1] == '/') newPath.truncate(iLen-1);
+
+ //kdDebug(7102) << "ftpFolder: want '" << newPath << "' has '" << m_currentPath << "'" << endl;
+ if(m_currentPath == newPath)
+ return true;
+
+ TQCString tmp = "cwd ";
+ tmp += remoteEncoding()->encode(newPath);
+ if( !ftpSendCmd(tmp) )
+ return false; // connection failure
+ if(m_iRespType != 2)
+ {
+ if(bReportError)
+ error(ERR_CANNOT_ENTER_DIRECTORY, path);
+ return false; // not a folder
+ }
+ m_currentPath = newPath;
+ return true;
+}
+
+
+//===============================================================================
+// public: copy don't use kio data pump if one side is a local file
+// helper: ftpCopyPut called from copy() on upload
+// helper: ftpCopyGet called from copy() on download
+//===============================================================================
+void Ftp::copy( const KURL &src, const KURL &dest, int permissions, bool overwrite )
+{
+ int iError = 0;
+ int iCopyFile = -1;
+ StatusCode cs = statusSuccess;
+ bool bSrcLocal = src.isLocalFile();
+ bool bDestLocal = dest.isLocalFile();
+ TQString sCopyFile;
+
+ if(bSrcLocal && !bDestLocal) // File -> Ftp
+ {
+ sCopyFile = src.path();
+ kdDebug(7102) << "Ftp::copy local file '" << sCopyFile << "' -> ftp '" << dest.path() << "'" << endl;
+ cs = ftpCopyPut(iError, iCopyFile, sCopyFile, dest, permissions, overwrite);
+ if( cs == statusServerError) sCopyFile = dest.url();
+ }
+ else if(!bSrcLocal && bDestLocal) // Ftp -> File
+ {
+ sCopyFile = dest.path();
+ kdDebug(7102) << "Ftp::copy ftp '" << src.path() << "' -> local file '" << sCopyFile << "'" << endl;
+ cs = ftpCopyGet(iError, iCopyFile, sCopyFile, src, permissions, overwrite);
+ if( cs == statusServerError ) sCopyFile = src.url();
+ }
+ else {
+ error( ERR_UNSUPPORTED_ACTION, TQString::null );
+ return;
+ }
+
+ // perform clean-ups and report error (if any)
+ if(iCopyFile != -1)
+ ::close(iCopyFile);
+ if(iError)
+ error(iError, sCopyFile);
+ ftpCloseCommand(); // must close command!
+}
+
+
+Ftp::StatusCode Ftp::ftpCopyPut(int& iError, int& iCopyFile, TQString sCopyFile,
+ const KURL& url, int permissions, bool overwrite)
+{
+ // check if source is ok ...
+ KDE_struct_stat buff;
+ TQCString sSrc( TQFile::encodeName(sCopyFile) );
+ bool bSrcExists = (KDE_stat( sSrc.data(), &buff ) != -1);
+ if(bSrcExists)
+ { if(S_ISDIR(buff.st_mode))
+ {
+ iError = ERR_IS_DIRECTORY;
+ return statusClientError;
+ }
+ }
+ else
+ {
+ iError = ERR_DOES_NOT_EXIST;
+ return statusClientError;
+ }
+
+ iCopyFile = KDE_open( sSrc.data(), O_RDONLY );
+ if(iCopyFile == -1)
+ {
+ iError = ERR_CANNOT_OPEN_FOR_READING;
+ return statusClientError;
+ }
+
+ // delegate the real work (iError gets status) ...
+ totalSize(buff.st_size);
+#ifdef ENABLE_CAN_RESUME
+ return ftpPut(iError, iCopyFile, url, permissions, overwrite, false);
+#else
+ return ftpPut(iError, iCopyFile, url, permissions, overwrite, true);
+#endif
+}
+
+
+Ftp::StatusCode Ftp::ftpCopyGet(int& iError, int& iCopyFile, const TQString sCopyFile,
+ const KURL& url, int permissions, bool overwrite)
+{
+ // check if destination is ok ...
+ KDE_struct_stat buff;
+ TQCString sDest( TQFile::encodeName(sCopyFile) );
+ bool bDestExists = (KDE_stat( sDest.data(), &buff ) != -1);
+ if(bDestExists)
+ { if(S_ISDIR(buff.st_mode))
+ {
+ iError = ERR_IS_DIRECTORY;
+ return statusClientError;
+ }
+ if(!overwrite)
+ {
+ iError = ERR_FILE_ALREADY_EXIST;
+ return statusClientError;
+ }
+ }
+
+ // do we have a ".part" file?
+ TQCString sPart = TQFile::encodeName(sCopyFile + ".part");
+ bool bResume = false;
+ bool bPartExists = (KDE_stat( sPart.data(), &buff ) != -1);
+ const bool bMarkPartial = config()->readBoolEntry("MarkPartial", true);
+
+ if(!bMarkPartial)
+ {
+ sPart = TQFile::encodeName(sCopyFile);
+ }
+ else if(bPartExists && buff.st_size > 0)
+ { // must not be a folder! please fix a similar bug in kio_file!!
+ if(S_ISDIR(buff.st_mode))
+ {
+ iError = ERR_DIR_ALREADY_EXIST;
+ return statusClientError; // client side error
+ }
+ //doesn't work for copy? -> design flaw?
+#ifdef ENABLE_CAN_RESUME
+ bResume = canResume( buff.st_size );
+#else
+ bResume = true;
+#endif
+ }
+
+ if(bPartExists && !bResume) // get rid of an unwanted ".part" file
+ remove(sPart.data());
+
+ // JPF: in kio_file overwrite disables ".part" operations. I do not believe
+ // JPF: that this is a good behaviour!
+ if(bDestExists) // must delete for overwrite
+ remove(sDest.data());
+
+ // WABA: Make sure that we keep writing permissions ourselves,
+ // otherwise we can be in for a surprise on NFS.
+ mode_t initialMode;
+ if (permissions != -1)
+ initialMode = permissions | S_IWUSR;
+ else
+ initialMode = 0666;
+
+ // open the output file ...
+ TDEIO::fileoffset_t hCopyOffset = 0;
+ if(bResume)
+ {
+ iCopyFile = KDE_open( sPart.data(), O_RDWR ); // append if resuming
+ hCopyOffset = KDE_lseek(iCopyFile, 0, SEEK_END);
+ if(hCopyOffset < 0)
+ {
+ iError = ERR_CANNOT_RESUME;
+ return statusClientError; // client side error
+ }
+ kdDebug(7102) << "copy: resuming at " << hCopyOffset << endl;
+ }
+ else
+ iCopyFile = KDE_open(sPart.data(), O_CREAT | O_TRUNC | O_WRONLY, initialMode);
+
+ if(iCopyFile == -1)
+ {
+ kdDebug(7102) << "copy: ### COULD NOT WRITE " << sCopyFile << endl;
+ iError = (errno == EACCES) ? ERR_WRITE_ACCESS_DENIED
+ : ERR_CANNOT_OPEN_FOR_WRITING;
+ return statusClientError;
+ }
+
+ // delegate the real work (iError gets status) ...
+ StatusCode iRes = ftpGet(iError, iCopyFile, url, hCopyOffset);
+ if( ::close(iCopyFile) && iRes == statusSuccess )
+ {
+ iError = ERR_COULD_NOT_WRITE;
+ iRes = statusClientError;
+ }
+
+ // handle renaming or deletion of a partial file ...
+ if(bMarkPartial)
+ {
+ if(iRes == statusSuccess)
+ { // rename ".part" on success
+ if ( ::rename( sPart.data(), sDest.data() ) )
+ {
+ kdDebug(7102) << "copy: cannot rename " << sPart << " to " << sDest << endl;
+ iError = ERR_CANNOT_RENAME_PARTIAL;
+ iRes = statusClientError;
+ }
+ }
+ else if(KDE_stat( sPart.data(), &buff ) == 0)
+ { // should a very small ".part" be deleted?
+ int size = config()->readNumEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE);
+ if (buff.st_size < size)
+ remove(sPart.data());
+ }
+ }
+ return iRes;
+}
diff --git a/tdeioslave/ftp/ftp.h b/tdeioslave/ftp/ftp.h
new file mode 100644
index 000000000..4b2a1891d
--- /dev/null
+++ b/tdeioslave/ftp/ftp.h
@@ -0,0 +1,603 @@
+// -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 2; -*-
+/* This file is part of the KDE libraries
+ Copyright (C) 2000 David Faure <faure@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#ifndef __ftp_h__
+#define __ftp_h__
+
+#include <config.h>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <tqcstring.h>
+#include <tqstring.h>
+
+#include <kurl.h>
+#include <tdeio/slavebase.h>
+#include <kextsock.h>
+#include <ksocks.h>
+
+struct FtpEntry
+{
+ TQString name;
+ TQString owner;
+ TQString group;
+ TQString link;
+
+ TDEIO::filesize_t size;
+ mode_t type;
+ mode_t access;
+ time_t date;
+};
+
+//===============================================================================
+// FtpTextReader A helper class to read text lines from a socket
+//===============================================================================
+
+#ifdef KIO_FTP_PRIVATE_INCLUDE
+class FtpSocket;
+
+class FtpTextReader
+{
+public:
+ FtpTextReader() { textClear(); }
+
+/**
+ * Resets the status of the object, also called from xtor
+ */
+ void textClear();
+
+/**
+ * Read a line from the socket into m_szText. Only the first RESP_READ_LIMIT
+ * characters are copied. If the server response is longer all extra data up to
+ * the new-line gets discarded. An ending CR gets stripped. The number of chars
+ * in the buffer is returned. Use textToLong() to check for truncation!
+ */
+ int textRead(FtpSocket *pSock);
+
+/**
+ * An accessor to the data read by textRead()
+ */
+ const char* textLine() const { return m_szText; }
+
+/**
+ * Returns true if the last textRead() resulted in a truncated line
+ */
+ bool textTooLong() const { return m_bTextTruncated; }
+
+/**
+ * Returns true if the last textRead() got an EOF or an error
+ */
+ bool textEOF() const { return m_bTextEOF; }
+
+ enum {
+
+ /**
+ * This is the physical size of m_szText. Only up to textReadLimit
+ * characters are used to store a server reply. If the server reply
+ * is longer, the stored line gets truncated - see textTooLong()!
+ */
+ textReadBuffer = 2048,
+
+/**
+ * Max number of chars returned from textLine(). If the server
+ * sends more all chars until the next new-line are discarded.
+ */
+ textReadLimit = 1024
+ };
+
+private:
+ /**
+ * textRead() sets this true on trucation (e.g. line too long)
+ */
+ bool m_bTextTruncated;
+
+ /**
+ * textRead() sets this true if the read returns 0 bytes or error
+ */
+ bool m_bTextEOF;
+
+ /**
+ * textRead() fills this buffer with data
+ */
+ char m_szText[textReadBuffer];
+
+ /**
+ * the number of bytes in the current response line
+ */
+ int m_iTextLine;
+
+ /**
+ * the number of bytes in the response buffer (includes m_iRespLine)
+ */
+ int m_iTextBuff;
+};
+#endif // KIO_FTP_PRIVATE_INCLUDE
+
+//===============================================================================
+// FtpSocket Helper Class for Data or Control Connections
+//===============================================================================
+#ifdef KIO_FTP_PRIVATE_INCLUDE
+class FtpSocket : public FtpTextReader, public KExtendedSocket
+{
+private:
+ // hide the default xtor
+ FtpSocket() {}
+public:
+/**
+ * The one and only public xtor. The string data passed to the
+ * xtor must remain valid during the object's lifetime - it is
+ * used in debug messages to identify the socket instance.
+ */
+ FtpSocket(const char* pszName)
+ {
+ m_pszName = pszName;
+ m_server = -1;
+ }
+
+ ~FtpSocket() { closeSocket(); }
+
+/**
+ * Resets the status of the object, also called from xtor
+ */
+ void closeSocket();
+
+/**
+ * We may have a server connection socket if not in passive mode. This
+ * routine returns the server socket set by setServer. The sock()
+ * function will return the server socket - if it is set.
+ */
+ int server() const { return m_server; }
+
+/**
+ * Set the server socket if arg >= 0, otherwise clear it.
+ */
+ void setServer(int i) { m_server = (i >= 0) ? i : -1; }
+
+/**
+ * returns the effective socket that user used for read/write. See server()
+ */
+ int sock() const { return (m_server != -1) ? m_server : fd(); }
+
+/**
+ * output an debug message via kdDebug
+ */
+ void debugMessage(const char* pszMsg) const;
+
+/**
+ * output an error message via kdError, returns iErrorCode
+ */
+ int errorMessage(int iErrorCode, const char* pszMsg) const;
+
+/**
+ * connect socket and set some options (reuse, keepalive, linger)
+ */
+ int connectSocket(int iTimeOutSec, bool bControl);
+
+/**
+ * utility to simplify calls to ::setsockopt(). Uses sock().
+ */
+ bool setSocketOption(int opt, char*arg, socklen_t len) const;
+
+/**
+ * utility to read data from the effective socket, see sock()
+ */
+ long read(void* pData, long iMaxlen)
+ {
+ return KSocks::self()->read(sock(), pData, iMaxlen);
+ }
+
+/**
+ * utility to write data to the effective socket, see sock()
+ */
+ long write(void* pData, long iMaxlen)
+ {
+ return KSocks::self()->write(sock(), pData, iMaxlen);
+ }
+
+/**
+ * Use the inherited FtpTextReader to read a line from the socket
+ */
+ int textRead()
+ {
+ return FtpTextReader::textRead(this);
+ }
+
+private:
+ const char* m_pszName; // set by the xtor, used for debug output
+ int m_server; // socket override, see setSock()
+};
+#else
+ class FtpSocket;
+#endif // KIO_FTP_PRIVATE_INCLUDE
+
+//===============================================================================
+// Ftp
+//===============================================================================
+class Ftp : public TDEIO::SlaveBase
+{
+ // Ftp() {}
+
+public:
+ Ftp( const TQCString &pool, const TQCString &app );
+ virtual ~Ftp();
+
+ virtual void setHost( const TQString& host, int port, const TQString& user, const TQString& pass );
+
+ /**
+ * Connects to a ftp server and logs us in
+ * m_bLoggedOn is set to true if logging on was successful.
+ * It is set to false if the connection becomes closed.
+ *
+ */
+ virtual void openConnection();
+
+ /**
+ * Closes the connection
+ */
+ virtual void closeConnection();
+
+ virtual void stat( const KURL &url );
+
+ virtual void listDir( const KURL & url );
+ virtual void mkdir( const KURL & url, int permissions );
+ virtual void rename( const KURL & src, const KURL & dest, bool overwrite );
+ virtual void del( const KURL & url, bool isfile );
+ virtual void chmod( const KURL & url, int permissions );
+
+ virtual void get( const KURL& url );
+ virtual void put( const KURL& url, int permissions, bool overwrite, bool resume);
+ //virtual void mimetype( const KURL& url );
+
+ virtual void slave_status();
+
+ /**
+ * Handles the case that one side of the job is a local file
+ */
+ virtual void copy( const KURL &src, const KURL &dest, int permissions, bool overwrite );
+
+private:
+ // ------------------------------------------------------------------------
+ // All the methods named ftpXyz are lowlevel methods that are not exported.
+ // The implement functionality used by the public high-level methods. Some
+ // low-level methods still use error() to emit errors. This behaviour is not
+ // recommended - please return a boolean status or an error code instead!
+ // ------------------------------------------------------------------------
+
+ /**
+ * Status Code returned from ftpPut() and ftpGet(), used to select
+ * source or destination url for error messages
+ */
+ typedef enum {
+ statusSuccess,
+ statusClientError,
+ statusServerError
+ } StatusCode;
+
+ /**
+ * Login Mode for ftpOpenConnection
+ */
+ typedef enum {
+ loginDefered,
+ loginExplicit,
+ loginImplicit
+ } LoginMode;
+
+ /**
+ * Connect and login to the FTP server.
+ *
+ * @param loginMode controls if login info should be sent<br>
+ * loginDefered - must not be logged on, no login info is sent<br>
+ * loginExplicit - must not be logged on, login info is sent<br>
+ * loginImplicit - login info is sent if not logged on
+ *
+ * @return true on success (a login failure would return false).
+ */
+ bool ftpOpenConnection (LoginMode loginMode);
+
+ /**
+ * Executes any auto login macro's as specified in a .netrc file.
+ */
+ void ftpAutoLoginMacro ();
+
+ /**
+ * Called by openConnection. It logs us in.
+ * m_initialPath is set to the current working directory
+ * if logging on was successful.
+ *
+ * @return true on success.
+ */
+ bool ftpLogin();
+
+ /**
+ * ftpSendCmd - send a command (@p cmd) and read response
+ *
+ * @param maxretries number of time it should retry. Since it recursively
+ * calls itself if it can't read the answer (this happens especially after
+ * timeouts), we need to limit the recursiveness ;-)
+ *
+ * return true if any response received, false on error
+ */
+ bool ftpSendCmd( const TQCString& cmd, int maxretries = 1 );
+
+ /**
+ * Use the SIZE command to get the file size.
+ * @param mode the size depends on the transfer mode, hence this arg.
+ * @return true on success
+ * Gets the size into m_size.
+ */
+ bool ftpSize( const TQString & path, char mode );
+
+ /**
+ * Set the current working directory, but only if not yet current
+ */
+ bool ftpFileExists(const TQString& path);
+
+ /**
+ * Set the current working directory, but only if not yet current
+ */
+ bool ftpFolder(const TQString& path, bool bReportError);
+
+ /**
+ * Runs a command on the ftp server like "list" or "retr". In contrast to
+ * ftpSendCmd a data connection is opened. The corresponding socket
+ * sData is available for reading/writing on success.
+ * The connection must be closed afterwards with ftpCloseCommand.
+ *
+ * @param mode is 'A' or 'I'. 'A' means ASCII transfer, 'I' means binary transfer.
+ * @param errorcode the command-dependent error code to emit on error
+ *
+ * @return true if the command was accepted by the server.
+ */
+ bool ftpOpenCommand( const char *command, const TQString & path, char mode,
+ int errorcode, TDEIO::fileoffset_t offset = 0 );
+
+ /**
+ * The counterpart to openCommand.
+ * Closes data sockets and then reads line sent by server at
+ * end of command.
+ * @return false on error (line doesn't start with '2')
+ */
+ bool ftpCloseCommand();
+
+ /**
+ * Send "TYPE I" or "TYPE A" only if required, see m_cDataMode.
+ *
+ * Use 'A' to select ASCII and 'I' to select BINARY mode. If
+ * cMode is '?' the m_bTextMode flag is used to choose a mode.
+ */
+ bool ftpDataMode(char cMode);
+
+ //void ftpAbortTransfer();
+
+ /**
+ * Used by ftpOpenCommand, return 0 on success or an error code
+ */
+ int ftpOpenDataConnection();
+
+ /**
+ * closes a data connection, see ftpOpenDataConnection()
+ */
+ void ftpCloseDataConnection();
+
+ /**
+ * Helper for ftpOpenDataConnection
+ */
+ int ftpOpenPASVDataConnection();
+ /**
+ * Helper for ftpOpenDataConnection
+ */
+ int ftpOpenEPSVDataConnection();
+ /**
+ * Helper for ftpOpenDataConnection
+ */
+ int ftpOpenEPRTDataConnection();
+ /**
+ * Helper for ftpOpenDataConnection
+ */
+ int ftpOpenPortDataConnection();
+
+ /**
+ * ftpAcceptConnect - wait for incoming connection
+ *
+ * return -2 on error or timeout
+ * otherwise returns socket descriptor
+ */
+ int ftpAcceptConnect();
+
+ bool ftpChmod( const TQString & path, int permissions );
+
+ // used by listDir
+ bool ftpOpenDir( const TQString & path );
+ /**
+ * Called to parse directory listings, call this until it returns false
+ */
+ bool ftpReadDir(FtpEntry& ftpEnt);
+
+ /**
+ * Helper to fill an UDSEntry
+ */
+ void ftpCreateUDSEntry( const TQString & filename, FtpEntry& ftpEnt, TDEIO::UDSEntry& entry, bool isDir );
+
+ void ftpShortStatAnswer( const TQString& filename, bool isDir );
+
+ void ftpStatAnswerNotFound( const TQString & path, const TQString & filename );
+
+ /**
+ * This is the internal implementation of rename() - set put().
+ *
+ * @return true on success.
+ */
+ bool ftpRename( const TQString & src, const TQString & dst, bool overwrite );
+
+ /**
+ * Called by openConnection. It opens the control connection to the ftp server.
+ *
+ * @return true on success.
+ */
+ bool ftpOpenControlConnection( const TQString & host, unsigned short int port );
+
+ /**
+ * closes the socket holding the control connection (see ftpOpenControlConnection)
+ */
+ void ftpCloseControlConnection();
+
+ /**
+ * read a response from the server (a trailing CR gets stripped)
+ * @param iOffset -1 to read a new line from the server<br>
+ * 0 to return the whole response string
+ * >0 to return the response with iOffset chars skipped
+ * @return the reponse message with iOffset chars skipped (or "" if iOffset points
+ * behind the available data)
+ */
+ const char* ftpResponse(int iOffset);
+
+ /**
+ * This is the internal implementation of get() - see copy().
+ *
+ * IMPORTANT: the caller should call ftpCloseCommand() on return.
+ * The function does not call error(), the caller should do this.
+ *
+ * @param iError set to an ERR_xxxx code on error
+ * @param iCopyFile -1 -or- handle of a local destination file
+ * @param hCopyOffset local file only: non-zero for resume
+ * @return 0 for success, -1 for server error, -2 for client error
+ */
+ StatusCode ftpGet(int& iError, int iCopyFile, const KURL& url, TDEIO::fileoffset_t hCopyOffset);
+
+ /**
+ * This is the internal implementation of put() - see copy().
+ *
+ * IMPORTANT: the caller should call ftpCloseCommand() on return.
+ * The function does not call error(), the caller should do this.
+ *
+ * @param iError set to an ERR_xxxx code on error
+ * @param iCopyFile -1 -or- handle of a local source file
+ * @return 0 for success, -1 for server error, -2 for client error
+ */
+ StatusCode ftpPut(int& iError, int iCopyFile, const KURL& url, int permissions, bool overwrite, bool resume);
+
+ /**
+ * helper called from copy() to implement FILE -> FTP transfers
+ *
+ * @param iError set to an ERR_xxxx code on error
+ * @param iCopyFile [out] handle of a local source file
+ * @param sCopyFile path of the local source file
+ * @return 0 for success, -1 for server error, -2 for client error
+ */
+ StatusCode ftpCopyPut(int& iError, int& iCopyFile, TQString sCopyFile, const KURL& url, int permissions, bool overwrite);
+
+ /**
+ * helper called from copy() to implement FTP -> FILE transfers
+ *
+ * @param iError set to an ERR_xxxx code on error
+ * @param iCopyFile [out] handle of a local source file
+ * @param sCopyFile path of the local destination file
+ * @return 0 for success, -1 for server error, -2 for client error
+ */
+ StatusCode ftpCopyGet(int& iError, int& iCopyFile, TQString sCopyFile, const KURL& url, int permissions, bool overwrite);
+
+private: // data members
+
+ TQString m_host;
+ unsigned short int m_port;
+ TQString m_user;
+ TQString m_pass;
+ /**
+ * Where we end up after connecting
+ */
+ TQString m_initialPath;
+ KURL m_proxyURL;
+
+ /**
+ * the current working directory - see ftpFolder
+ */
+ TQString m_currentPath;
+
+ /**
+ * the status returned by the FTP protocol, set in ftpResponse()
+ */
+ int m_iRespCode;
+
+ /**
+ * the status/100 returned by the FTP protocol, set in ftpResponse()
+ */
+ int m_iRespType;
+
+ /**
+ * This flag is maintained by ftpDataMode() and contains I or A after
+ * ftpDataMode() has successfully set the mode.
+ */
+ char m_cDataMode;
+
+ /**
+ * true if logged on (m_control should also be non-NULL)
+ */
+ bool m_bLoggedOn;
+
+ /**
+ * true if a "textmode" metadata key was found by ftpLogin(). This
+ * switches the ftp data transfer mode from binary to ASCII.
+ */
+ bool m_bTextMode;
+
+ /**
+ * true if a data stream is open, used in closeConnection().
+ *
+ * When the user cancels a get or put command the Ftp dtor will be called,
+ * which in turn calls closeConnection(). The later would try to send QUIT
+ * which won't work until timeout. ftpOpenCommand sets the m_bBusy flag so
+ * that the sockets will be closed immedeately - the server should be
+ * capable of handling this and return an error code on thru the control
+ * connection. The m_bBusy gets cleared by the ftpCloseCommand() routine.
+ */
+ bool m_bBusy;
+
+ bool m_bPasv;
+ bool m_bUseProxy;
+
+ TDEIO::filesize_t m_size;
+ static TDEIO::filesize_t UnknownSize;
+
+ enum
+ {
+ epsvUnknown = 0x01,
+ epsvAllUnknown = 0x02,
+ eprtUnknown = 0x04,
+ epsvAllSent = 0x10,
+ pasvUnknown = 0x20,
+ chmodUnknown = 0x100
+ };
+ int m_extControl;
+
+ /**
+ * control connection socket, only set if openControl() succeeded
+ */
+ FtpSocket *m_control;
+
+ /**
+ * data connection socket
+ */
+ FtpSocket *m_data;
+};
+
+#endif
diff --git a/tdeioslave/ftp/ftp.protocol b/tdeioslave/ftp/ftp.protocol
new file mode 100644
index 000000000..dfed878a8
--- /dev/null
+++ b/tdeioslave/ftp/ftp.protocol
@@ -0,0 +1,18 @@
+[Protocol]
+exec=kio_ftp
+protocol=ftp
+input=none
+output=filesystem
+copyToFile=true
+copyFromFile=true
+listing=Name,Type,Size,Date,Access,Owner,Group,Link,
+reading=true
+writing=true
+makedir=true
+deleting=true
+moving=true
+ProxiedBy=http
+Icon=ftp
+maxInstances=2
+DocPath=tdeioslave/ftp.html
+Class=:internet
diff --git a/tdeioslave/gzip/CMakeLists.txt b/tdeioslave/gzip/CMakeLists.txt
new file mode 100644
index 000000000..d08fc7e64
--- /dev/null
+++ b/tdeioslave/gzip/CMakeLists.txt
@@ -0,0 +1,41 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install( FILES kgzipfilter.desktop DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+##### kgzipfilter ###############################
+
+set( target kgzipfilter )
+
+set( ${target}_SRCS
+ kgzipfilter.cpp
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/tdeioslave/gzip/Makefile.am b/tdeioslave/gzip/Makefile.am
new file mode 100644
index 000000000..22918aef2
--- /dev/null
+++ b/tdeioslave/gzip/Makefile.am
@@ -0,0 +1,12 @@
+INCLUDES = -I$(top_srcdir)/tdeio $(all_includes)
+AM_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+METASOURCES = AUTO
+
+kde_module_LTLIBRARIES = kgzipfilter.la
+
+kgzipfilter_la_SOURCES = kgzipfilter.cpp
+kgzipfilter_la_LIBADD = $(LIB_KIO) $(LIBZ) $(LIB_QT) $(LIB_TDECORE)
+kgzipfilter_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
+
+kde_services_DATA = kgzipfilter.desktop
+
diff --git a/kioslave/gzip/kgzipfilter.cpp b/tdeioslave/gzip/kgzipfilter.cpp
index 375f9f9bc..375f9f9bc 100644
--- a/kioslave/gzip/kgzipfilter.cpp
+++ b/tdeioslave/gzip/kgzipfilter.cpp
diff --git a/kioslave/gzip/kgzipfilter.desktop b/tdeioslave/gzip/kgzipfilter.desktop
index a3b6c027b..a3b6c027b 100644
--- a/kioslave/gzip/kgzipfilter.desktop
+++ b/tdeioslave/gzip/kgzipfilter.desktop
diff --git a/kioslave/gzip/kgzipfilter.h b/tdeioslave/gzip/kgzipfilter.h
index 73b5173f3..73b5173f3 100644
--- a/kioslave/gzip/kgzipfilter.h
+++ b/tdeioslave/gzip/kgzipfilter.h
diff --git a/tdeioslave/http/CMakeLists.txt b/tdeioslave/http/CMakeLists.txt
new file mode 100644
index 000000000..64abe1adb
--- /dev/null
+++ b/tdeioslave/http/CMakeLists.txt
@@ -0,0 +1,69 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+add_subdirectory( kcookiejar )
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore/network
+ ${CMAKE_SOURCE_DIR}/interfaces
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/httpfilter
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install( FILES
+ http_cache_cleaner.desktop http.protocol https.protocol
+ webdav.protocol webdavs.protocol
+ DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+##### kio_http_cache_cleaner ####################
+
+set( target kio_http_cache_cleaner )
+
+set( ${target}_SRCS
+ http_cache_cleaner.cpp
+)
+
+tde_add_tdeinit_executable( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+)
+
+
+##### kio_http ##################################
+
+# FIXME GSSAPI support is not handled yet
+
+set( target kio_http )
+
+set( ${target}_SRCS
+ http.cc
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK httpfilter-static tdentlm-shared tdeio-shared
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/tdeioslave/http/Makefile.am b/tdeioslave/http/Makefile.am
new file mode 100644
index 000000000..184381b0f
--- /dev/null
+++ b/tdeioslave/http/Makefile.am
@@ -0,0 +1,31 @@
+# $Id$
+# Makefile.am of tdebase/tdeioslave/http
+
+SUBDIRS = kcookiejar
+
+INCLUDES= -I$(top_srcdir)/interfaces -I$(top_srcdir)/tdeio/httpfilter -I$(top_srcdir)/tdecore/network $(all_includes) $(GSSAPI_INCS)
+AM_LDFLAGS = $(all_libraries) $(GSSAPI_RPATH)
+
+####### Files
+
+bin_PROGRAMS=
+lib_LTLIBRARIES=
+tdeinit_LTLIBRARIES = kio_http_cache_cleaner.la
+kde_module_LTLIBRARIES = kio_http.la
+
+kio_http_la_SOURCES = http.cc
+kio_http_la_METASOURCES = AUTO
+kio_http_la_LIBADD = $(LIB_KIO) $(top_builddir)/tdeio/httpfilter/libhttpfilter.la $(LIB_QT) $(LIB_TDECORE) $(LIBZ) $(top_builddir)/dcop/libDCOP.la $(top_builddir)/tdeio/misc/tdentlm/libtdentlm.la
+kio_http_la_LDFLAGS = $(all_libraries) $(GSSAPI_RPATH) -module $(KDE_PLUGIN) $(GSSAPI_LIBS)
+
+kio_http_cache_cleaner_la_SOURCES = http_cache_cleaner.cpp
+kio_http_cache_cleaner_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la
+kio_http_cache_cleaner_la_LDFLAGS = -module -avoid-version
+
+noinst_HEADERS = http.h
+
+kdelnkdir = $(kde_servicesdir)
+kdelnk_DATA = http_cache_cleaner.desktop http.protocol https.protocol \
+ webdav.protocol webdavs.protocol
+
+include $(top_srcdir)/admin/Doxyfile.am
diff --git a/kioslave/http/README.http_cache_cleaner b/tdeioslave/http/README.http_cache_cleaner
index 7714bfba6..7714bfba6 100644
--- a/kioslave/http/README.http_cache_cleaner
+++ b/tdeioslave/http/README.http_cache_cleaner
diff --git a/kioslave/http/README.webdav b/tdeioslave/http/README.webdav
index c7ee900bb..c7ee900bb 100644
--- a/kioslave/http/README.webdav
+++ b/tdeioslave/http/README.webdav
diff --git a/tdeioslave/http/THOUGHTS b/tdeioslave/http/THOUGHTS
new file mode 100644
index 000000000..5fabc3fcb
--- /dev/null
+++ b/tdeioslave/http/THOUGHTS
@@ -0,0 +1,28 @@
+Here's a few ideas for those with blistered hands and nothing better to
+do:
+
+SSL certificate verification:
+We do establish SSL connections, but we never actually verify a
+certificate!
+
+HTTP/1.1 Persistant Connections:
+The header often specifies the timeout value used for connections.
+Close the connection ourselves when the timeout has expired. That way
+we don't loose time sending stuff to an already closed connection.
+
+Rating(s) support. http://www.w3.org/PICS
+This might involve an external program to parse the labels, and something
+to configure access.
+
+WebDAV support. MSIE5 calls it web folders support, and a similar
+approach would probably be a good idea. Perhaps with an exists()
+function.. one could tell if an http url was part of a WebDAV collection..
+and this could be used for some kind of integration with tdefile... to
+provide seamless integration. Uhm, also, this might entail an external
+program (xml parser and such).
+
+"Friendly" error messages. How often have you seen a useless 404 message?
+Again something I first notied in MSIE5, and that would be some sort of
+translation of what an error really means. Yes this would have to be
+i18n'd and easily turned off. But this could also be extended to all the
+slaves (ftp, pop3, etc, etc).
diff --git a/kioslave/http/TODO b/tdeioslave/http/TODO
index 9dbf60a3e..9dbf60a3e 100644
--- a/kioslave/http/TODO
+++ b/tdeioslave/http/TODO
diff --git a/kioslave/http/configure.in.bot b/tdeioslave/http/configure.in.bot
index 56d051424..56d051424 100644
--- a/kioslave/http/configure.in.bot
+++ b/tdeioslave/http/configure.in.bot
diff --git a/kioslave/http/configure.in.in b/tdeioslave/http/configure.in.in
index a7d1ca7cf..a7d1ca7cf 100644
--- a/kioslave/http/configure.in.in
+++ b/tdeioslave/http/configure.in.in
diff --git a/tdeioslave/http/http.cc b/tdeioslave/http/http.cc
new file mode 100644
index 000000000..d944364cc
--- /dev/null
+++ b/tdeioslave/http/http.cc
@@ -0,0 +1,6108 @@
+/*
+ Copyright (C) 2000-2003 Waldo Bastian <bastian@kde.org>
+ Copyright (C) 2000-2002 George Staikos <staikos@kde.org>
+ Copyright (C) 2000-2002 Dawit Alemayehu <adawit@kde.org>
+ Copyright (C) 2001,2002 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License (LGPL) as published by the Free Software Foundation;
+ either version 2 of the License, or (at your option) any later
+ version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include <config.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <utime.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <netinet/in.h> // Required for AIX
+#include <netinet/tcp.h>
+#include <unistd.h> // must be explicitly included for MacOSX
+
+/*
+#include <netdb.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+*/
+
+#include <tqdom.h>
+#include <tqfile.h>
+#include <tqregexp.h>
+#include <tqdatetime.h>
+#include <tqstringlist.h>
+#include <tqurl.h>
+
+#include <kurl.h>
+#include <kidna.h>
+#include <ksocks.h>
+#include <kdebug.h>
+#include <klocale.h>
+#include <tdeconfig.h>
+#include <kextsock.h>
+#include <kservice.h>
+#include <krfcdate.h>
+#include <kmdcodec.h>
+#include <kinstance.h>
+#include <kresolver.h>
+#include <kmimemagic.h>
+#include <dcopclient.h>
+#include <kdatastream.h>
+#include <kapplication.h>
+#include <kstandarddirs.h>
+#include <kstringhandler.h>
+#include <kremoteencoding.h>
+
+#include "tdeio/ioslave_defaults.h"
+#include "tdeio/http_slave_defaults.h"
+
+#include "httpfilter.h"
+#include "http.h"
+
+#ifdef HAVE_LIBGSSAPI
+#ifdef GSSAPI_MIT
+#include <gssapi/gssapi.h>
+#else
+#include <gssapi.h>
+#endif /* GSSAPI_MIT */
+
+// Catch uncompatible crap (BR86019)
+#if defined(GSS_RFC_COMPLIANT_OIDS) && (GSS_RFC_COMPLIANT_OIDS == 0)
+#include <gssapi/gssapi_generic.h>
+#define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
+#endif
+
+#endif /* HAVE_LIBGSSAPI */
+
+#include <misc/tdentlm/tdentlm.h>
+
+using namespace TDEIO;
+
+extern "C" {
+ KDE_EXPORT int kdemain(int argc, char **argv);
+}
+
+int kdemain( int argc, char **argv )
+{
+ KLocale::setMainCatalogue("tdelibs");
+ TDEInstance instance( "kio_http" );
+ ( void ) TDEGlobal::locale();
+
+ if (argc != 4)
+ {
+ fprintf(stderr, "Usage: kio_http protocol domain-socket1 domain-socket2\n");
+ exit(-1);
+ }
+
+ HTTPProtocol slave(argv[1], argv[2], argv[3]);
+ slave.dispatchLoop();
+ return 0;
+}
+
+/*********************************** Generic utility functions ********************/
+
+static char * trimLead (char *orig_string)
+{
+ while (*orig_string == ' ')
+ orig_string++;
+ return orig_string;
+}
+
+static bool isCrossDomainRequest( const TQString& fqdn, const TQString& originURL )
+{
+ if (originURL == "true") // Backwards compatibility
+ return true;
+
+ KURL url ( originURL );
+
+ // Document Origin domain
+ TQString a = url.host();
+
+ // Current request domain
+ TQString b = fqdn;
+
+ if (a == b)
+ return false;
+
+ TQStringList l1 = TQStringList::split('.', a);
+ TQStringList l2 = TQStringList::split('.', b);
+
+ while(l1.count() > l2.count())
+ l1.pop_front();
+
+ while(l2.count() > l1.count())
+ l2.pop_front();
+
+ while(l2.count() >= 2)
+ {
+ if (l1 == l2)
+ return false;
+
+ l1.pop_front();
+ l2.pop_front();
+ }
+
+ return true;
+}
+
+/*
+ Eliminates any custom header that could potentically alter the request
+*/
+static TQString sanitizeCustomHTTPHeader(const TQString& _header)
+{
+ TQString sanitizedHeaders;
+ TQStringList headers = TQStringList::split(TQRegExp("[\r\n]"), _header);
+
+ for(TQStringList::Iterator it = headers.begin(); it != headers.end(); ++it)
+ {
+ TQString header = (*it).lower();
+ // Do not allow Request line to be specified and ignore
+ // the other HTTP headers.
+ if (header.find(':') == -1 ||
+ header.startsWith("host") ||
+ header.startsWith("via"))
+ continue;
+
+ sanitizedHeaders += (*it);
+ sanitizedHeaders += "\r\n";
+ }
+
+ return sanitizedHeaders.stripWhiteSpace();
+}
+
+
+#define NO_SIZE ((TDEIO::filesize_t) -1)
+
+#ifdef HAVE_STRTOLL
+#define STRTOLL strtoll
+#else
+#define STRTOLL strtol
+#endif
+
+
+/************************************** HTTPProtocol **********************************************/
+
+HTTPProtocol::HTTPProtocol( const TQCString &protocol, const TQCString &pool,
+ const TQCString &app )
+ :TCPSlaveBase( 0, protocol , pool, app,
+ (protocol == "https" || protocol == "webdavs") )
+{
+ m_requestQueue.setAutoDelete(true);
+
+ m_bBusy = false;
+ m_bFirstRequest = false;
+ m_bProxyAuthValid = false;
+
+ m_iSize = NO_SIZE;
+ m_lineBufUnget = 0;
+
+ m_protocol = protocol;
+
+ m_maxCacheAge = DEFAULT_MAX_CACHE_AGE;
+ m_maxCacheSize = DEFAULT_MAX_CACHE_SIZE / 2;
+ m_remoteConnTimeout = DEFAULT_CONNECT_TIMEOUT;
+ m_remoteRespTimeout = DEFAULT_RESPONSE_TIMEOUT;
+ m_proxyConnTimeout = DEFAULT_PROXY_CONNECT_TIMEOUT;
+
+ m_pid = getpid();
+
+ setMultipleAuthCaching( true );
+ reparseConfiguration();
+}
+
+HTTPProtocol::~HTTPProtocol()
+{
+ httpClose(false);
+}
+
+void HTTPProtocol::reparseConfiguration()
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::reparseConfiguration" << endl;
+
+ m_strProxyRealm = TQString::null;
+ m_strProxyAuthorization = TQString::null;
+ ProxyAuthentication = AUTH_None;
+ m_bUseProxy = false;
+
+ if (m_protocol == "https" || m_protocol == "webdavs")
+ m_iDefaultPort = DEFAULT_HTTPS_PORT;
+ else if (m_protocol == "ftp")
+ m_iDefaultPort = DEFAULT_FTP_PORT;
+ else
+ m_iDefaultPort = DEFAULT_HTTP_PORT;
+}
+
+void HTTPProtocol::resetConnectionSettings()
+{
+ m_bEOF = false;
+ m_bError = false;
+ m_lineCount = 0;
+ m_iWWWAuthCount = 0;
+ m_lineCountUnget = 0;
+ m_iProxyAuthCount = 0;
+
+}
+
+void HTTPProtocol::resetResponseSettings()
+{
+ m_bRedirect = false;
+ m_redirectLocation = KURL();
+ m_bChunked = false;
+ m_iSize = NO_SIZE;
+
+ m_responseHeader.clear();
+ m_qContentEncodings.clear();
+ m_qTransferEncodings.clear();
+ m_sContentMD5 = TQString::null;
+ m_strMimeType = TQString::null;
+
+ setMetaData("request-id", m_request.id);
+}
+
+void HTTPProtocol::resetSessionSettings()
+{
+ // Do not reset the URL on redirection if the proxy
+ // URL, username or password has not changed!
+ KURL proxy ( config()->readEntry("UseProxy") );
+
+ if ( m_strProxyRealm.isEmpty() || !proxy.isValid() ||
+ m_proxyURL.host() != proxy.host() ||
+ (!proxy.user().isNull() && proxy.user() != m_proxyURL.user()) ||
+ (!proxy.pass().isNull() && proxy.pass() != m_proxyURL.pass()) )
+ {
+ m_bProxyAuthValid = false;
+ m_proxyURL = proxy;
+ m_bUseProxy = m_proxyURL.isValid();
+
+ kdDebug(7113) << "(" << m_pid << ") Using proxy: " << m_bUseProxy <<
+ " URL: " << m_proxyURL.url() <<
+ " Realm: " << m_strProxyRealm << endl;
+ }
+
+ m_bPersistentProxyConnection = config()->readBoolEntry("PersistentProxyConnection", false);
+ kdDebug(7113) << "(" << m_pid << ") Enable Persistent Proxy Connection: "
+ << m_bPersistentProxyConnection << endl;
+
+ m_request.bUseCookiejar = config()->readBoolEntry("Cookies");
+ m_request.bUseCache = config()->readBoolEntry("UseCache", true);
+ m_request.bErrorPage = config()->readBoolEntry("errorPage", true);
+ m_request.bNoAuth = config()->readBoolEntry("no-auth");
+ m_strCacheDir = config()->readPathEntry("CacheDir");
+ m_maxCacheAge = config()->readNumEntry("MaxCacheAge", DEFAULT_MAX_CACHE_AGE);
+ m_request.window = config()->readEntry("window-id");
+
+ kdDebug(7113) << "(" << m_pid << ") Window Id = " << m_request.window << endl;
+ kdDebug(7113) << "(" << m_pid << ") ssl_was_in_use = "
+ << metaData ("ssl_was_in_use") << endl;
+
+ m_request.referrer = TQString::null;
+ if ( config()->readBoolEntry("SendReferrer", true) &&
+ (m_protocol == "https" || m_protocol == "webdavs" ||
+ metaData ("ssl_was_in_use") != "TRUE" ) )
+ {
+ KURL referrerURL ( metaData("referrer") );
+ if (referrerURL.isValid())
+ {
+ // Sanitize
+ TQString protocol = referrerURL.protocol();
+ if (protocol.startsWith("webdav"))
+ {
+ protocol.replace(0, 6, "http");
+ referrerURL.setProtocol(protocol);
+ }
+
+ if (protocol.startsWith("http"))
+ {
+ referrerURL.setRef(TQString::null);
+ referrerURL.setUser(TQString::null);
+ referrerURL.setPass(TQString::null);
+ m_request.referrer = referrerURL.url();
+ }
+ }
+ }
+
+ if ( config()->readBoolEntry("SendLanguageSettings", true) )
+ {
+ m_request.charsets = config()->readEntry( "Charsets", "iso-8859-1" );
+
+ if ( !m_request.charsets.isEmpty() )
+ m_request.charsets += DEFAULT_PARTIAL_CHARSET_HEADER;
+
+ m_request.languages = config()->readEntry( "Languages", DEFAULT_LANGUAGE_HEADER );
+ }
+ else
+ {
+ m_request.charsets = TQString::null;
+ m_request.languages = TQString::null;
+ }
+
+ // Adjust the offset value based on the "resume" meta-data.
+ TQString resumeOffset = metaData("resume");
+ if ( !resumeOffset.isEmpty() )
+ m_request.offset = resumeOffset.toInt(); // TODO: Convert to 64 bit
+ else
+ m_request.offset = 0;
+
+ m_request.disablePassDlg = config()->readBoolEntry("DisablePassDlg", false);
+ m_request.allowCompressedPage = config()->readBoolEntry("AllowCompressedPage", true);
+ m_request.id = metaData("request-id");
+
+ // Store user agent for this host.
+ if ( config()->readBoolEntry("SendUserAgent", true) )
+ m_request.userAgent = metaData("UserAgent");
+ else
+ m_request.userAgent = TQString::null;
+
+ // Deal with cache cleaning.
+ // TODO: Find a smarter way to deal with cleaning the
+ // cache ?
+ if ( m_request.bUseCache )
+ cleanCache();
+
+ // Deal with HTTP tunneling
+ if ( m_bIsSSL && m_bUseProxy && m_proxyURL.protocol() != "https" &&
+ m_proxyURL.protocol() != "webdavs")
+ {
+ m_bNeedTunnel = true;
+ setRealHost( m_request.hostname );
+ kdDebug(7113) << "(" << m_pid << ") SSL tunnel: Setting real hostname to: "
+ << m_request.hostname << endl;
+ }
+ else
+ {
+ m_bNeedTunnel = false;
+ setRealHost( TQString::null);
+ }
+
+ m_responseCode = 0;
+ m_prevResponseCode = 0;
+
+ m_strRealm = TQString::null;
+ m_strAuthorization = TQString::null;
+ Authentication = AUTH_None;
+
+ // Obtain the proxy and remote server timeout values
+ m_proxyConnTimeout = proxyConnectTimeout();
+ m_remoteConnTimeout = connectTimeout();
+ m_remoteRespTimeout = responseTimeout();
+
+ // Set the SSL meta-data here...
+ setSSLMetaData();
+
+ // Bounce back the actual referrer sent
+ setMetaData("referrer", m_request.referrer);
+
+ // Follow HTTP/1.1 spec and enable keep-alive by default
+ // unless the remote side tells us otherwise or we determine
+ // the persistent link has been terminated by the remote end.
+ m_bKeepAlive = true;
+ m_keepAliveTimeout = 0;
+ m_bUnauthorized = false;
+
+ // A single request can require multiple exchanges with the remote
+ // server due to authentication challenges or SSL tunneling.
+ // m_bFirstRequest is a flag that indicates whether we are
+ // still processing the first request. This is important because we
+ // should not force a close of a keep-alive connection in the middle
+ // of the first request.
+ // m_bFirstRequest is set to "true" whenever a new connection is
+ // made in httpOpenConnection()
+ m_bFirstRequest = false;
+}
+
+void HTTPProtocol::setHost( const TQString& host, int port,
+ const TQString& user, const TQString& pass )
+{
+ // Reset the webdav-capable flags for this host
+ if ( m_request.hostname != host )
+ m_davHostOk = m_davHostUnsupported = false;
+
+ // is it an IPv6 address?
+ if (host.find(':') == -1)
+ {
+ m_request.hostname = host;
+ m_request.encoded_hostname = KIDNA::toAscii(host);
+ }
+ else
+ {
+ m_request.hostname = host;
+ int pos = host.find('%');
+ if (pos == -1)
+ m_request.encoded_hostname = '[' + host + ']';
+ else
+ // don't send the scope-id in IPv6 addresses to the server
+ m_request.encoded_hostname = '[' + host.left(pos) + ']';
+ }
+ m_request.port = (port == 0) ? m_iDefaultPort : port;
+ m_request.user = user;
+ m_request.passwd = pass;
+
+ m_bIsTunneled = false;
+
+ kdDebug(7113) << "(" << m_pid << ") Hostname is now: " << m_request.hostname <<
+ " (" << m_request.encoded_hostname << ")" <<endl;
+}
+
+bool HTTPProtocol::checkRequestURL( const KURL& u )
+{
+ kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::checkRequestURL: " << u.url() << endl;
+
+ m_request.url = u;
+
+ if (m_request.hostname.isEmpty())
+ {
+ error( TDEIO::ERR_UNKNOWN_HOST, i18n("No host specified."));
+ return false;
+ }
+
+ if (u.path().isEmpty())
+ {
+ KURL newUrl(u);
+ newUrl.setPath("/");
+ redirection(newUrl);
+ finished();
+ return false;
+ }
+
+ if ( m_protocol != u.protocol().latin1() )
+ {
+ short unsigned int oldDefaultPort = m_iDefaultPort;
+ m_protocol = u.protocol().latin1();
+ reparseConfiguration();
+ if ( m_iDefaultPort != oldDefaultPort &&
+ m_request.port == oldDefaultPort )
+ m_request.port = m_iDefaultPort;
+ }
+
+ resetSessionSettings();
+ return true;
+}
+
+void HTTPProtocol::retrieveContent( bool dataInternal /* = false */ )
+{
+ kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveContent " << endl;
+ if ( !retrieveHeader( false ) )
+ {
+ if ( m_bError )
+ return;
+ }
+ else
+ {
+ if ( !readBody( dataInternal ) && m_bError )
+ return;
+ }
+
+ httpClose(m_bKeepAlive);
+
+ // if data is required internally, don't finish,
+ // it is processed before we finish()
+ if ( !dataInternal )
+ {
+ if ((m_responseCode == 204) &&
+ ((m_request.method == HTTP_GET) || (m_request.method == HTTP_POST)))
+ error(ERR_NO_CONTENT, "");
+ else
+ finished();
+ }
+}
+
+bool HTTPProtocol::retrieveHeader( bool close_connection )
+{
+ kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::retrieveHeader " << endl;
+ while ( 1 )
+ {
+ if (!httpOpen())
+ return false;
+
+ resetResponseSettings();
+ if (!readHeader())
+ {
+ if ( m_bError )
+ return false;
+
+ if (m_bIsTunneled)
+ {
+ kdDebug(7113) << "(" << m_pid << ") Re-establishing SSL tunnel..." << endl;
+ httpCloseConnection();
+ }
+ }
+ else
+ {
+ // Do not save authorization if the current response code is
+ // 4xx (client error) or 5xx (server error).
+ kdDebug(7113) << "(" << m_pid << ") Previous Response: "
+ << m_prevResponseCode << endl;
+ kdDebug(7113) << "(" << m_pid << ") Current Response: "
+ << m_responseCode << endl;
+
+ if (isSSLTunnelEnabled() && m_bIsSSL && !m_bUnauthorized && !m_bError)
+ {
+ // If there is no error, disable tunneling
+ if ( m_responseCode < 400 )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Unset tunneling flag!" << endl;
+ setEnableSSLTunnel( false );
+ m_bIsTunneled = true;
+ // Reset the CONNECT response code...
+ m_responseCode = m_prevResponseCode;
+ continue;
+ }
+ else
+ {
+ if ( !m_request.bErrorPage )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Sending an error message!" << endl;
+ error( ERR_UNKNOWN_PROXY_HOST, m_proxyURL.host() );
+ return false;
+ }
+
+ kdDebug(7113) << "(" << m_pid << ") Sending an error page!" << endl;
+ }
+ }
+
+ if (m_responseCode < 400 && (m_prevResponseCode == 401 ||
+ m_prevResponseCode == 407))
+ saveAuthorization();
+ break;
+ }
+ }
+
+ // Clear of the temporary POST buffer if it is not empty...
+ if (!m_bufPOST.isEmpty())
+ {
+ m_bufPOST.resize(0);
+ kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
+ "buffer..." << endl;
+ }
+
+ if ( close_connection )
+ {
+ httpClose(m_bKeepAlive);
+ finished();
+ }
+
+ return true;
+}
+
+void HTTPProtocol::stat(const KURL& url)
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::stat " << url.prettyURL()
+ << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ if ( m_protocol != "webdav" && m_protocol != "webdavs" )
+ {
+ TQString statSide = metaData(TQString::fromLatin1("statSide"));
+ if ( statSide != "source" )
+ {
+ // When uploading we assume the file doesn't exit
+ error( ERR_DOES_NOT_EXIST, url.prettyURL() );
+ return;
+ }
+
+ // When downloading we assume it exists
+ UDSEntry entry;
+ UDSAtom atom;
+ atom.m_uds = TDEIO::UDS_NAME;
+ atom.m_str = url.fileName();
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_FILE_TYPE;
+ atom.m_long = S_IFREG; // a file
+ entry.append( atom );
+
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = S_IRUSR | S_IRGRP | S_IROTH; // readable by everybody
+ entry.append( atom );
+
+ statEntry( entry );
+ finished();
+ return;
+ }
+
+ davStatList( url );
+}
+
+void HTTPProtocol::listDir( const KURL& url )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::listDir " << url.url()
+ << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ if (!url.protocol().startsWith("webdav")) {
+ error(ERR_UNSUPPORTED_ACTION, url.prettyURL());
+ return;
+ }
+
+ davStatList( url, false );
+}
+
+void HTTPProtocol::davSetRequest( const TQCString& requestXML )
+{
+ // insert the document into the POST buffer, kill trailing zero byte
+ m_bufPOST = requestXML;
+
+ if (m_bufPOST.size())
+ m_bufPOST.truncate( m_bufPOST.size() - 1 );
+}
+
+void HTTPProtocol::davStatList( const KURL& url, bool stat )
+{
+ UDSEntry entry;
+ UDSAtom atom;
+
+ // check to make sure this host supports WebDAV
+ if ( !davHostOk() )
+ return;
+
+ // Maybe it's a disguised SEARCH...
+ TQString query = metaData("davSearchQuery");
+ if ( !query.isEmpty() )
+ {
+ TQCString request = "<?xml version=\"1.0\"?>\r\n";
+ request.append( "<D:searchrequest xmlns:D=\"DAV:\">\r\n" );
+ request.append( query.utf8() );
+ request.append( "</D:searchrequest>\r\n" );
+
+ davSetRequest( request );
+ } else {
+ // We are only after certain features...
+ TQCString request;
+ request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
+ "<D:propfind xmlns:D=\"DAV:\">";
+
+ // insert additional XML request from the davRequestResponse metadata
+ if ( hasMetaData( "davRequestResponse" ) )
+ request += metaData( "davRequestResponse" ).utf8();
+ else {
+ // No special request, ask for default properties
+ request += "<D:prop>"
+ "<D:creationdate/>"
+ "<D:getcontentlength/>"
+ "<D:displayname/>"
+ "<D:source/>"
+ "<D:getcontentlanguage/>"
+ "<D:getcontenttype/>"
+ "<D:executable/>"
+ "<D:getlastmodified/>"
+ "<D:getetag/>"
+ "<D:supportedlock/>"
+ "<D:lockdiscovery/>"
+ "<D:resourcetype/>"
+ "</D:prop>";
+ }
+ request += "</D:propfind>";
+
+ davSetRequest( request );
+ }
+
+ // WebDAV Stat or List...
+ m_request.method = query.isEmpty() ? DAV_PROPFIND : DAV_SEARCH;
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+ m_request.davData.depth = stat ? 0 : 1;
+ if (!stat)
+ m_request.url.adjustPath(+1);
+
+ retrieveContent( true );
+
+ // Has a redirection already been called? If so, we're done.
+ if (m_bRedirect) {
+ finished();
+ return;
+ }
+
+ TQDomDocument multiResponse;
+ multiResponse.setContent( m_bufWebDavData, true );
+
+ bool hasResponse = false;
+
+ for ( TQDomNode n = multiResponse.documentElement().firstChild();
+ !n.isNull(); n = n.nextSibling())
+ {
+ TQDomElement thisResponse = n.toElement();
+ if (thisResponse.isNull())
+ continue;
+
+ hasResponse = true;
+
+ TQDomElement href = thisResponse.namedItem( "href" ).toElement();
+ if ( !href.isNull() )
+ {
+ entry.clear();
+
+ TQString urlStr = href.text();
+#if 0
+ int encoding = remoteEncoding()->encodingMib();
+ if ((encoding == 106) && (!KStringHandler::isUtf8(KURL::decode_string(urlStr, 4).latin1())))
+ encoding = 4; // Use latin1 if the file is not actually utf-8
+#else
+ TQUrl::decode(urlStr);
+ int encoding = 106;
+#endif
+
+ KURL thisURL ( urlStr, encoding );
+
+ atom.m_uds = TDEIO::UDS_NAME;
+
+ if ( thisURL.isValid() ) {
+ // don't list the base dir of a listDir()
+ if ( !stat && thisURL.path(+1).length() == url.path(+1).length() )
+ continue;
+
+ atom.m_str = thisURL.fileName();
+ } else {
+ // This is a relative URL.
+ atom.m_str = href.text();
+ }
+
+ entry.append( atom );
+
+ TQDomNodeList propstats = thisResponse.elementsByTagName( "propstat" );
+
+ davParsePropstats( propstats, entry );
+
+ if ( stat )
+ {
+ // return an item
+ statEntry( entry );
+ finished();
+ return;
+ }
+ else
+ {
+ listEntry( entry, false );
+ }
+ }
+ else
+ {
+ kdDebug(7113) << "Error: no URL contained in response to PROPFIND on "
+ << url.prettyURL() << endl;
+ }
+ }
+
+ if ( stat || !hasResponse )
+ {
+ error( ERR_DOES_NOT_EXIST, url.prettyURL() );
+ }
+ else
+ {
+ listEntry( entry, true );
+ finished();
+ }
+}
+
+void HTTPProtocol::davGeneric( const KURL& url, TDEIO::HTTP_METHOD method )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davGeneric " << url.url()
+ << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ // check to make sure this host supports WebDAV
+ if ( !davHostOk() )
+ return;
+
+ // WebDAV method
+ m_request.method = method;
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveContent( false );
+}
+
+int HTTPProtocol::codeFromResponse( const TQString& response )
+{
+ int firstSpace = response.find( ' ' );
+ int secondSpace = response.find( ' ', firstSpace + 1 );
+ return response.mid( firstSpace + 1, secondSpace - firstSpace - 1 ).toInt();
+}
+
+void HTTPProtocol::davParsePropstats( const TQDomNodeList& propstats, UDSEntry& entry )
+{
+ TQString mimeType;
+ UDSAtom atom;
+ bool foundExecutable = false;
+ bool isDirectory = false;
+ uint lockCount = 0;
+ uint supportedLockCount = 0;
+
+ for ( uint i = 0; i < propstats.count(); i++)
+ {
+ TQDomElement propstat = propstats.item(i).toElement();
+
+ TQDomElement status = propstat.namedItem( "status" ).toElement();
+ if ( status.isNull() )
+ {
+ // error, no status code in this propstat
+ kdDebug(7113) << "Error, no status code in this propstat" << endl;
+ return;
+ }
+
+ int code = codeFromResponse( status.text() );
+
+ if ( code != 200 )
+ {
+ kdDebug(7113) << "Warning: status code " << code << " (this may mean that some properties are unavailable" << endl;
+ continue;
+ }
+
+ TQDomElement prop = propstat.namedItem( "prop" ).toElement();
+ if ( prop.isNull() )
+ {
+ kdDebug(7113) << "Error: no prop segment in this propstat." << endl;
+ return;
+ }
+
+ if ( hasMetaData( "davRequestResponse" ) )
+ {
+ atom.m_uds = TDEIO::UDS_XML_PROPERTIES;
+ TQDomDocument doc;
+ doc.appendChild(prop);
+ atom.m_str = doc.toString();
+ entry.append( atom );
+ }
+
+ for ( TQDomNode n = prop.firstChild(); !n.isNull(); n = n.nextSibling() )
+ {
+ TQDomElement property = n.toElement();
+ if (property.isNull())
+ continue;
+
+ if ( property.namespaceURI() != "DAV:" )
+ {
+ // break out - we're only interested in properties from the DAV namespace
+ continue;
+ }
+
+ if ( property.tagName() == "creationdate" )
+ {
+ // Resource creation date. Should be is ISO 8601 format.
+ atom.m_uds = TDEIO::UDS_CREATION_TIME;
+ atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
+ entry.append( atom );
+ }
+ else if ( property.tagName() == "getcontentlength" )
+ {
+ // Content length (file size)
+ atom.m_uds = TDEIO::UDS_SIZE;
+ atom.m_long = property.text().toULong();
+ entry.append( atom );
+ }
+ else if ( property.tagName() == "displayname" )
+ {
+ // Name suitable for presentation to the user
+ setMetaData( "davDisplayName", property.text() );
+ }
+ else if ( property.tagName() == "source" )
+ {
+ // Source template location
+ TQDomElement source = property.namedItem( "link" ).toElement()
+ .namedItem( "dst" ).toElement();
+ if ( !source.isNull() )
+ setMetaData( "davSource", source.text() );
+ }
+ else if ( property.tagName() == "getcontentlanguage" )
+ {
+ // equiv. to Content-Language header on a GET
+ setMetaData( "davContentLanguage", property.text() );
+ }
+ else if ( property.tagName() == "getcontenttype" )
+ {
+ // Content type (mime type)
+ // This may require adjustments for other server-side webdav implementations
+ // (tested with Apache + mod_dav 1.0.3)
+ if ( property.text() == "httpd/unix-directory" )
+ {
+ isDirectory = true;
+ }
+ else
+ {
+ mimeType = property.text();
+ }
+ }
+ else if ( property.tagName() == "executable" )
+ {
+ // File executable status
+ if ( property.text() == "T" )
+ foundExecutable = true;
+
+ }
+ else if ( property.tagName() == "getlastmodified" )
+ {
+ // Last modification date
+ atom.m_uds = TDEIO::UDS_MODIFICATION_TIME;
+ atom.m_long = parseDateTime( property.text(), property.attribute("dt") );
+ entry.append( atom );
+
+ }
+ else if ( property.tagName() == "getetag" )
+ {
+ // Entity tag
+ setMetaData( "davEntityTag", property.text() );
+ }
+ else if ( property.tagName() == "supportedlock" )
+ {
+ // Supported locking specifications
+ for ( TQDomNode n2 = property.firstChild(); !n2.isNull(); n2 = n2.nextSibling() )
+ {
+ TQDomElement lockEntry = n2.toElement();
+ if ( lockEntry.tagName() == "lockentry" )
+ {
+ TQDomElement lockScope = lockEntry.namedItem( "lockscope" ).toElement();
+ TQDomElement lockType = lockEntry.namedItem( "locktype" ).toElement();
+ if ( !lockScope.isNull() && !lockType.isNull() )
+ {
+ // Lock type was properly specified
+ supportedLockCount++;
+ TQString scope = lockScope.firstChild().toElement().tagName();
+ TQString type = lockType.firstChild().toElement().tagName();
+
+ setMetaData( TQString("davSupportedLockScope%1").arg(supportedLockCount), scope );
+ setMetaData( TQString("davSupportedLockType%1").arg(supportedLockCount), type );
+ }
+ }
+ }
+ }
+ else if ( property.tagName() == "lockdiscovery" )
+ {
+ // Lists the available locks
+ davParseActiveLocks( property.elementsByTagName( "activelock" ), lockCount );
+ }
+ else if ( property.tagName() == "resourcetype" )
+ {
+ // Resource type. "Specifies the nature of the resource."
+ if ( !property.namedItem( "collection" ).toElement().isNull() )
+ {
+ // This is a collection (directory)
+ isDirectory = true;
+ }
+ }
+ else
+ {
+ kdDebug(7113) << "Found unknown webdav property: " << property.tagName() << endl;
+ }
+ }
+ }
+
+ setMetaData( "davLockCount", TQString("%1").arg(lockCount) );
+ setMetaData( "davSupportedLockCount", TQString("%1").arg(supportedLockCount) );
+
+ atom.m_uds = TDEIO::UDS_FILE_TYPE;
+ atom.m_long = isDirectory ? S_IFDIR : S_IFREG;
+ entry.append( atom );
+
+ if ( foundExecutable || isDirectory )
+ {
+ // File was executable, or is a directory.
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = 0700;
+ entry.append(atom);
+ }
+ else
+ {
+ atom.m_uds = TDEIO::UDS_ACCESS;
+ atom.m_long = 0600;
+ entry.append(atom);
+ }
+
+ if ( !isDirectory && !mimeType.isEmpty() )
+ {
+ atom.m_uds = TDEIO::UDS_MIME_TYPE;
+ atom.m_str = mimeType;
+ entry.append( atom );
+ }
+}
+
+void HTTPProtocol::davParseActiveLocks( const TQDomNodeList& activeLocks,
+ uint& lockCount )
+{
+ for ( uint i = 0; i < activeLocks.count(); i++ )
+ {
+ TQDomElement activeLock = activeLocks.item(i).toElement();
+
+ lockCount++;
+ // required
+ TQDomElement lockScope = activeLock.namedItem( "lockscope" ).toElement();
+ TQDomElement lockType = activeLock.namedItem( "locktype" ).toElement();
+ TQDomElement lockDepth = activeLock.namedItem( "depth" ).toElement();
+ // optional
+ TQDomElement lockOwner = activeLock.namedItem( "owner" ).toElement();
+ TQDomElement lockTimeout = activeLock.namedItem( "timeout" ).toElement();
+ TQDomElement lockToken = activeLock.namedItem( "locktoken" ).toElement();
+
+ if ( !lockScope.isNull() && !lockType.isNull() && !lockDepth.isNull() )
+ {
+ // lock was properly specified
+ lockCount++;
+ TQString scope = lockScope.firstChild().toElement().tagName();
+ TQString type = lockType.firstChild().toElement().tagName();
+ TQString depth = lockDepth.text();
+
+ setMetaData( TQString("davLockScope%1").arg( lockCount ), scope );
+ setMetaData( TQString("davLockType%1").arg( lockCount ), type );
+ setMetaData( TQString("davLockDepth%1").arg( lockCount ), depth );
+
+ if ( !lockOwner.isNull() )
+ setMetaData( TQString("davLockOwner%1").arg( lockCount ), lockOwner.text() );
+
+ if ( !lockTimeout.isNull() )
+ setMetaData( TQString("davLockTimeout%1").arg( lockCount ), lockTimeout.text() );
+
+ if ( !lockToken.isNull() )
+ {
+ TQDomElement tokenVal = lockScope.namedItem( "href" ).toElement();
+ if ( !tokenVal.isNull() )
+ setMetaData( TQString("davLockToken%1").arg( lockCount ), tokenVal.text() );
+ }
+ }
+ }
+}
+
+long HTTPProtocol::parseDateTime( const TQString& input, const TQString& type )
+{
+ if ( type == "dateTime.tz" )
+ {
+ return KRFCDate::parseDateISO8601( input );
+ }
+ else if ( type == "dateTime.rfc1123" )
+ {
+ return KRFCDate::parseDate( input );
+ }
+
+ // format not advertised... try to parse anyway
+ time_t time = KRFCDate::parseDate( input );
+ if ( time != 0 )
+ return time;
+
+ return KRFCDate::parseDateISO8601( input );
+}
+
+TQString HTTPProtocol::davProcessLocks()
+{
+ if ( hasMetaData( "davLockCount" ) )
+ {
+ TQString response("If:");
+ int numLocks;
+ numLocks = metaData( "davLockCount" ).toInt();
+ bool bracketsOpen = false;
+ for ( int i = 0; i < numLocks; i++ )
+ {
+ if ( hasMetaData( TQString("davLockToken%1").arg(i) ) )
+ {
+ if ( hasMetaData( TQString("davLockURL%1").arg(i) ) )
+ {
+ if ( bracketsOpen )
+ {
+ response += ")";
+ bracketsOpen = false;
+ }
+ response += " <" + metaData( TQString("davLockURL%1").arg(i) ) + ">";
+ }
+
+ if ( !bracketsOpen )
+ {
+ response += " (";
+ bracketsOpen = true;
+ }
+ else
+ {
+ response += " ";
+ }
+
+ if ( hasMetaData( TQString("davLockNot%1").arg(i) ) )
+ response += "Not ";
+
+ response += "<" + metaData( TQString("davLockToken%1").arg(i) ) + ">";
+ }
+ }
+
+ if ( bracketsOpen )
+ response += ")";
+
+ response += "\r\n";
+ return response;
+ }
+
+ return TQString::null;
+}
+
+bool HTTPProtocol::davHostOk()
+{
+ // FIXME needs to be reworked. Switched off for now.
+ return true;
+
+ // cached?
+ if ( m_davHostOk )
+ {
+ kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " true" << endl;
+ return true;
+ }
+ else if ( m_davHostUnsupported )
+ {
+ kdDebug(7113) << "(" << m_pid << ") " << k_funcinfo << " false" << endl;
+ davError( -2 );
+ return false;
+ }
+
+ m_request.method = HTTP_OPTIONS;
+
+ // query the server's capabilities generally, not for a specific URL
+ m_request.path = "*";
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ // clear davVersions variable, which holds the response to the DAV: header
+ m_davCapabilities.clear();
+
+ retrieveHeader(false);
+
+ if (m_davCapabilities.count())
+ {
+ for (uint i = 0; i < m_davCapabilities.count(); i++)
+ {
+ bool ok;
+ uint verNo = m_davCapabilities[i].toUInt(&ok);
+ if (ok && verNo > 0 && verNo < 3)
+ {
+ m_davHostOk = true;
+ kdDebug(7113) << "Server supports DAV version " << verNo << "." << endl;
+ }
+ }
+
+ if ( m_davHostOk )
+ return true;
+ }
+
+ m_davHostUnsupported = true;
+ davError( -2 );
+ return false;
+}
+
+// This function is for closing retrieveHeader( false ); requests
+// Required because there may or may not be further info expected
+void HTTPProtocol::davFinished()
+{
+ // TODO: Check with the DAV extension developers
+ httpClose(m_bKeepAlive);
+ finished();
+}
+
+void HTTPProtocol::mkdir( const KURL& url, int )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mkdir " << url.url()
+ << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.method = DAV_MKCOL;
+ m_request.path = url.path();
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveHeader( false );
+
+ if ( m_responseCode == 201 )
+ davFinished();
+ else
+ davError();
+}
+
+void HTTPProtocol::get( const KURL& url )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::get " << url.url()
+ << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.method = HTTP_GET;
+ m_request.path = url.path();
+ m_request.query = url.query();
+
+ TQString tmp = metaData("cache");
+ if (!tmp.isEmpty())
+ m_request.cache = parseCacheControl(tmp);
+ else
+ m_request.cache = DEFAULT_CACHE_CONTROL;
+
+ m_request.passwd = url.pass();
+ m_request.user = url.user();
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveContent();
+}
+
+void HTTPProtocol::put( const KURL &url, int, bool overwrite, bool)
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put " << url.prettyURL()
+ << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ // Webdav hosts are capable of observing overwrite == false
+ if (!overwrite && m_protocol.left(6) == "webdav") {
+ // check to make sure this host supports WebDAV
+ if ( !davHostOk() )
+ return;
+
+ TQCString request;
+ request = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
+ "<D:propfind xmlns:D=\"DAV:\"><D:prop>"
+ "<D:creationdate/>"
+ "<D:getcontentlength/>"
+ "<D:displayname/>"
+ "<D:resourcetype/>"
+ "</D:prop></D:propfind>";
+
+ davSetRequest( request );
+
+ // WebDAV Stat or List...
+ m_request.method = DAV_PROPFIND;
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+ m_request.davData.depth = 0;
+
+ retrieveContent(true);
+
+ if (m_responseCode == 207) {
+ error(ERR_FILE_ALREADY_EXIST, TQString::null);
+ return;
+ }
+
+ m_bError = false;
+ }
+
+ m_request.method = HTTP_PUT;
+ m_request.path = url.path();
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveHeader( false );
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put error = " << m_bError << endl;
+ if (m_bError)
+ return;
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::put responseCode = " << m_responseCode << endl;
+
+ httpClose(false); // Always close connection.
+
+ if ( (m_responseCode >= 200) && (m_responseCode < 300) )
+ finished();
+ else
+ httpError();
+}
+
+void HTTPProtocol::copy( const KURL& src, const KURL& dest, int, bool overwrite )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::copy " << src.prettyURL()
+ << " -> " << dest.prettyURL() << endl;
+
+ if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
+ return;
+
+ // destination has to be "http(s)://..."
+ KURL newDest = dest;
+ if (newDest.protocol() == "webdavs")
+ newDest.setProtocol("https");
+ else
+ newDest.setProtocol("http");
+
+ m_request.method = DAV_COPY;
+ m_request.path = src.path();
+ m_request.davData.desturl = newDest.url();
+ m_request.davData.overwrite = overwrite;
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveHeader( false );
+
+ // The server returns a HTTP/1.1 201 Created or 204 No Content on successful completion
+ if ( m_responseCode == 201 || m_responseCode == 204 )
+ davFinished();
+ else
+ davError();
+}
+
+void HTTPProtocol::rename( const KURL& src, const KURL& dest, bool overwrite )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::rename " << src.prettyURL()
+ << " -> " << dest.prettyURL() << endl;
+
+ if ( !checkRequestURL( dest ) || !checkRequestURL( src ) )
+ return;
+
+ // destination has to be "http://..."
+ KURL newDest = dest;
+ if (newDest.protocol() == "webdavs")
+ newDest.setProtocol("https");
+ else
+ newDest.setProtocol("http");
+
+ m_request.method = DAV_MOVE;
+ m_request.path = src.path();
+ m_request.davData.desturl = newDest.url();
+ m_request.davData.overwrite = overwrite;
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveHeader( false );
+
+ if ( m_responseCode == 301 )
+ {
+ // Work around strict Apache-2 WebDAV implementation which refuses to cooperate
+ // with webdav://host/directory, instead requiring webdav://host/directory/
+ // (strangely enough it accepts Destination: without a trailing slash)
+
+ if (m_redirectLocation.protocol() == "https")
+ m_redirectLocation.setProtocol("webdavs");
+ else
+ m_redirectLocation.setProtocol("webdav");
+
+ if ( !checkRequestURL( m_redirectLocation ) )
+ return;
+
+ m_request.method = DAV_MOVE;
+ m_request.path = m_redirectLocation.path();
+ m_request.davData.desturl = newDest.url();
+ m_request.davData.overwrite = overwrite;
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveHeader( false );
+ }
+
+ if ( m_responseCode == 201 )
+ davFinished();
+ else
+ davError();
+}
+
+void HTTPProtocol::del( const KURL& url, bool )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::del " << url.prettyURL()
+ << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.method = HTTP_DELETE;
+ m_request.path = url.path();
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveHeader( false );
+
+ // The server returns a HTTP/1.1 200 Ok or HTTP/1.1 204 No Content
+ // on successful completion
+ if ( m_responseCode == 200 || m_responseCode == 204 )
+ davFinished();
+ else
+ davError();
+}
+
+void HTTPProtocol::post( const KURL& url )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::post "
+ << url.prettyURL() << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.method = HTTP_POST;
+ m_request.path = url.path();
+ m_request.query = url.query();
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveContent();
+}
+
+void HTTPProtocol::davLock( const KURL& url, const TQString& scope,
+ const TQString& type, const TQString& owner )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davLock "
+ << url.prettyURL() << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.method = DAV_LOCK;
+ m_request.path = url.path();
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ /* Create appropriate lock XML request. */
+ TQDomDocument lockReq;
+
+ TQDomElement lockInfo = lockReq.createElementNS( "DAV:", "lockinfo" );
+ lockReq.appendChild( lockInfo );
+
+ TQDomElement lockScope = lockReq.createElement( "lockscope" );
+ lockInfo.appendChild( lockScope );
+
+ lockScope.appendChild( lockReq.createElement( scope ) );
+
+ TQDomElement lockType = lockReq.createElement( "locktype" );
+ lockInfo.appendChild( lockType );
+
+ lockType.appendChild( lockReq.createElement( type ) );
+
+ if ( !owner.isNull() ) {
+ TQDomElement ownerElement = lockReq.createElement( "owner" );
+ lockReq.appendChild( ownerElement );
+
+ TQDomElement ownerHref = lockReq.createElement( "href" );
+ ownerElement.appendChild( ownerHref );
+
+ ownerHref.appendChild( lockReq.createTextNode( owner ) );
+ }
+
+ // insert the document into the POST buffer
+ m_bufPOST = lockReq.toCString();
+
+ retrieveContent( true );
+
+ if ( m_responseCode == 200 ) {
+ // success
+ TQDomDocument multiResponse;
+ multiResponse.setContent( m_bufWebDavData, true );
+
+ TQDomElement prop = multiResponse.documentElement().namedItem( "prop" ).toElement();
+
+ TQDomElement lockdiscovery = prop.namedItem( "lockdiscovery" ).toElement();
+
+ uint lockCount = 0;
+ davParseActiveLocks( lockdiscovery.elementsByTagName( "activelock" ), lockCount );
+
+ setMetaData( "davLockCount", TQString("%1").arg( lockCount ) );
+
+ finished();
+
+ } else
+ davError();
+}
+
+void HTTPProtocol::davUnlock( const KURL& url )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::davUnlock "
+ << url.prettyURL() << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.method = DAV_UNLOCK;
+ m_request.path = url.path();
+ m_request.query = TQString::null;
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveContent( true );
+
+ if ( m_responseCode == 200 )
+ finished();
+ else
+ davError();
+}
+
+TQString HTTPProtocol::davError( int code /* = -1 */, TQString url )
+{
+ bool callError = false;
+ if ( code == -1 ) {
+ code = m_responseCode;
+ callError = true;
+ }
+ if ( code == -2 ) {
+ callError = true;
+ }
+
+ if ( !url.isNull() )
+ url = m_request.url.url();
+
+ TQString action, errorString;
+ TDEIO::Error kError;
+
+ // for 412 Precondition Failed
+ TQString ow = i18n( "Otherwise, the request would have succeeded." );
+
+ switch ( m_request.method ) {
+ case DAV_PROPFIND:
+ action = i18n( "retrieve property values" );
+ break;
+ case DAV_PROPPATCH:
+ action = i18n( "set property values" );
+ break;
+ case DAV_MKCOL:
+ action = i18n( "create the requested folder" );
+ break;
+ case DAV_COPY:
+ action = i18n( "copy the specified file or folder" );
+ break;
+ case DAV_MOVE:
+ action = i18n( "move the specified file or folder" );
+ break;
+ case DAV_SEARCH:
+ action = i18n( "search in the specified folder" );
+ break;
+ case DAV_LOCK:
+ action = i18n( "lock the specified file or folder" );
+ break;
+ case DAV_UNLOCK:
+ action = i18n( "unlock the specified file or folder" );
+ break;
+ case HTTP_DELETE:
+ action = i18n( "delete the specified file or folder" );
+ break;
+ case HTTP_OPTIONS:
+ action = i18n( "query the server's capabilities" );
+ break;
+ case HTTP_GET:
+ action = i18n( "retrieve the contents of the specified file or folder" );
+ break;
+ case HTTP_PUT:
+ case HTTP_POST:
+ case HTTP_HEAD:
+ default:
+ // this should not happen, this function is for webdav errors only
+ Q_ASSERT(0);
+ }
+
+ // default error message if the following code fails
+ kError = ERR_INTERNAL;
+ errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
+ .arg( code ).arg( action );
+
+ switch ( code )
+ {
+ case -2:
+ // internal error: OPTIONS request did not specify DAV compliance
+ kError = ERR_UNSUPPORTED_PROTOCOL;
+ errorString = i18n("The server does not support the WebDAV protocol.");
+ break;
+ case 207:
+ // 207 Multi-status
+ {
+ // our error info is in the returned XML document.
+ // retrieve the XML document
+
+ // there was an error retrieving the XML document.
+ // ironic, eh?
+ if ( !readBody( true ) && m_bError )
+ return TQString::null;
+
+ TQStringList errors;
+ TQDomDocument multiResponse;
+
+ multiResponse.setContent( m_bufWebDavData, true );
+
+ TQDomElement multistatus = multiResponse.documentElement().namedItem( "multistatus" ).toElement();
+
+ TQDomNodeList responses = multistatus.elementsByTagName( "response" );
+
+ for (uint i = 0; i < responses.count(); i++)
+ {
+ int errCode;
+ TQString errUrl;
+
+ TQDomElement response = responses.item(i).toElement();
+ TQDomElement code = response.namedItem( "status" ).toElement();
+
+ if ( !code.isNull() )
+ {
+ errCode = codeFromResponse( code.text() );
+ TQDomElement href = response.namedItem( "href" ).toElement();
+ if ( !href.isNull() )
+ errUrl = href.text();
+ errors << davError( errCode, errUrl );
+ }
+ }
+
+ //kError = ERR_SLAVE_DEFINED;
+ errorString = i18n("An error occurred while attempting to %1, %2. A "
+ "summary of the reasons is below.<ul>").arg( action ).arg( url );
+
+ for ( TQStringList::Iterator it = errors.begin(); it != errors.end(); ++it )
+ errorString += "<li>" + *it + "</li>";
+
+ errorString += "</ul>";
+ }
+ case 403:
+ case 500: // hack: Apache mod_dav returns this instead of 403 (!)
+ // 403 Forbidden
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("Access was denied while attempting to %1.").arg( action );
+ break;
+ case 405:
+ // 405 Method Not Allowed
+ if ( m_request.method == DAV_MKCOL )
+ {
+ kError = ERR_DIR_ALREADY_EXIST;
+ errorString = i18n("The specified folder already exists.");
+ }
+ break;
+ case 409:
+ // 409 Conflict
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("A resource cannot be created at the destination "
+ "until one or more intermediate collections (folders) "
+ "have been created.");
+ break;
+ case 412:
+ // 412 Precondition failed
+ if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
+ {
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("The server was unable to maintain the liveness of "
+ "the properties listed in the propertybehavior XML "
+ "element or you attempted to overwrite a file while "
+ "requesting that files are not overwritten. %1")
+ .arg( ow );
+
+ }
+ else if ( m_request.method == DAV_LOCK )
+ {
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("The requested lock could not be granted. %1").arg( ow );
+ }
+ break;
+ case 415:
+ // 415 Unsupported Media Type
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("The server does not support the request type of the body.");
+ break;
+ case 423:
+ // 423 Locked
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
+ break;
+ case 425:
+ // 424 Failed Dependency
+ errorString = i18n("This action was prevented by another error.");
+ break;
+ case 502:
+ // 502 Bad Gateway
+ if ( m_request.method == DAV_COPY || m_request.method == DAV_MOVE )
+ {
+ kError = ERR_WRITE_ACCESS_DENIED;
+ errorString = i18n("Unable to %1 because the destination server refuses "
+ "to accept the file or folder.").arg( action );
+ }
+ break;
+ case 507:
+ // 507 Insufficient Storage
+ kError = ERR_DISK_FULL;
+ errorString = i18n("The destination resource does not have sufficient space "
+ "to record the state of the resource after the execution "
+ "of this method.");
+ break;
+ }
+
+ // if ( kError != ERR_SLAVE_DEFINED )
+ //errorString += " (" + url + ")";
+
+ if ( callError )
+ error( ERR_SLAVE_DEFINED, errorString );
+
+ return errorString;
+}
+
+void HTTPProtocol::httpError()
+{
+ TQString action, errorString;
+ TDEIO::Error kError;
+
+ switch ( m_request.method ) {
+ case HTTP_PUT:
+ action = i18n( "upload %1" ).arg(m_request.url.prettyURL());
+ break;
+ default:
+ // this should not happen, this function is for http errors only
+ Q_ASSERT(0);
+ }
+
+ // default error message if the following code fails
+ kError = ERR_INTERNAL;
+ errorString = i18n("An unexpected error (%1) occurred while attempting to %2.")
+ .arg( m_responseCode ).arg( action );
+
+ switch ( m_responseCode )
+ {
+ case 403:
+ case 405:
+ case 500: // hack: Apache mod_dav returns this instead of 403 (!)
+ // 403 Forbidden
+ // 405 Method Not Allowed
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("Access was denied while attempting to %1.").arg( action );
+ break;
+ case 409:
+ // 409 Conflict
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("A resource cannot be created at the destination "
+ "until one or more intermediate collections (folders) "
+ "have been created.");
+ break;
+ case 423:
+ // 423 Locked
+ kError = ERR_ACCESS_DENIED;
+ errorString = i18n("Unable to %1 because the resource is locked.").arg( action );
+ break;
+ case 502:
+ // 502 Bad Gateway
+ kError = ERR_WRITE_ACCESS_DENIED;
+ errorString = i18n("Unable to %1 because the destination server refuses "
+ "to accept the file or folder.").arg( action );
+ break;
+ case 507:
+ // 507 Insufficient Storage
+ kError = ERR_DISK_FULL;
+ errorString = i18n("The destination resource does not have sufficient space "
+ "to record the state of the resource after the execution "
+ "of this method.");
+ break;
+ }
+
+ // if ( kError != ERR_SLAVE_DEFINED )
+ //errorString += " (" + url + ")";
+
+ error( ERR_SLAVE_DEFINED, errorString );
+}
+
+bool HTTPProtocol::isOffline(const KURL &url)
+{
+ const int NetWorkStatusUnknown = 1;
+ const int NetWorkStatusOnline = 8;
+ TQCString replyType;
+ TQByteArray params;
+ TQByteArray reply;
+
+ TQDataStream stream(params, IO_WriteOnly);
+
+ if ( url.host() == TQString::fromLatin1("localhost") || url.host() == TQString::fromLatin1("127.0.0.1") || url.host() == TQString::fromLatin1("::") ) {
+ return false;
+ }
+ if ( dcopClient()->call( "kded", "networkstatus", "status()",
+ params, replyType, reply ) && (replyType == "int") )
+ {
+ int result;
+ TQDataStream stream2( reply, IO_ReadOnly );
+ stream2 >> result;
+ kdDebug(7113) << "(" << m_pid << ") networkstatus status = " << result << endl;
+ return (result != NetWorkStatusUnknown) && (result != NetWorkStatusOnline);
+ }
+ kdDebug(7113) << "(" << m_pid << ") networkstatus <unreachable>" << endl;
+ return false; // On error, assume we are online
+}
+
+void HTTPProtocol::multiGet(const TQByteArray &data)
+{
+ TQDataStream stream(data, IO_ReadOnly);
+ TQ_UINT32 n;
+ stream >> n;
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtcool::multiGet n = " << n << endl;
+
+ HTTPRequest saveRequest;
+ if (m_bBusy)
+ saveRequest = m_request;
+
+// m_requestQueue.clear();
+ for(unsigned i = 0; i < n; i++)
+ {
+ KURL url;
+ stream >> url >> mIncomingMetaData;
+
+ if ( !checkRequestURL( url ) )
+ continue;
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::multi_get " << url.url() << endl;
+
+ m_request.method = HTTP_GET;
+ m_request.path = url.path();
+ m_request.query = url.query();
+ TQString tmp = metaData("cache");
+ if (!tmp.isEmpty())
+ m_request.cache = parseCacheControl(tmp);
+ else
+ m_request.cache = DEFAULT_CACHE_CONTROL;
+
+ m_request.passwd = url.pass();
+ m_request.user = url.user();
+ m_request.doProxy = m_bUseProxy;
+
+ HTTPRequest *newRequest = new HTTPRequest(m_request);
+ m_requestQueue.append(newRequest);
+ }
+
+ if (m_bBusy)
+ m_request = saveRequest;
+
+ if (!m_bBusy)
+ {
+ m_bBusy = true;
+ while(!m_requestQueue.isEmpty())
+ {
+ HTTPRequest *request = m_requestQueue.take(0);
+ m_request = *request;
+ delete request;
+ retrieveContent();
+ }
+ m_bBusy = false;
+ }
+}
+
+ssize_t HTTPProtocol::write (const void *_buf, size_t nbytes)
+{
+ int bytes_sent = 0;
+ const char* buf = static_cast<const char*>(_buf);
+ while ( nbytes > 0 )
+ {
+ int n = TCPSlaveBase::write(buf, nbytes);
+
+ if ( n <= 0 )
+ {
+ // remote side closed connection ?
+ if ( n == 0 )
+ break;
+ // a valid exception(s) occurred, let's retry...
+ if (n < 0 && ((errno == EINTR) || (errno == EAGAIN)))
+ continue;
+ // some other error occurred ?
+ return -1;
+ }
+
+ nbytes -= n;
+ buf += n;
+ bytes_sent += n;
+ }
+
+ return bytes_sent;
+}
+
+void HTTPProtocol::setRewindMarker()
+{
+ m_rewindCount = 0;
+}
+
+void HTTPProtocol::rewind()
+{
+ m_linePtrUnget = m_rewindBuf,
+ m_lineCountUnget = m_rewindCount;
+ m_rewindCount = 0;
+}
+
+
+char *HTTPProtocol::gets (char *s, int size)
+{
+ int len=0;
+ char *buf=s;
+ char mybuf[2]={0,0};
+
+ while (len < size)
+ {
+ read(mybuf, 1);
+ if (m_bEOF)
+ break;
+
+ if (m_rewindCount < sizeof(m_rewindBuf))
+ m_rewindBuf[m_rewindCount++] = *mybuf;
+
+ if (*mybuf == '\r') // Ignore!
+ continue;
+
+ if ((*mybuf == '\n') || !*mybuf)
+ break;
+
+ *buf++ = *mybuf;
+ len++;
+ }
+
+ *buf=0;
+ return s;
+}
+
+ssize_t HTTPProtocol::read (void *b, size_t nbytes)
+{
+ ssize_t ret = 0;
+
+ if (m_lineCountUnget > 0)
+ {
+ ret = ( nbytes < m_lineCountUnget ? nbytes : m_lineCountUnget );
+ m_lineCountUnget -= ret;
+ memcpy(b, m_linePtrUnget, ret);
+ m_linePtrUnget += ret;
+
+ return ret;
+ }
+
+ if (m_lineCount > 0)
+ {
+ ret = ( nbytes < m_lineCount ? nbytes : m_lineCount );
+ m_lineCount -= ret;
+ memcpy(b, m_linePtr, ret);
+ m_linePtr += ret;
+ return ret;
+ }
+
+ if (nbytes == 1)
+ {
+ ret = read(m_lineBuf, 1024); // Read into buffer
+ m_linePtr = m_lineBuf;
+ if (ret <= 0)
+ {
+ m_lineCount = 0;
+ return ret;
+ }
+ m_lineCount = ret;
+ return read(b, 1); // Read from buffer
+ }
+
+ do
+ {
+ ret = TCPSlaveBase::read( b, nbytes);
+ if (ret == 0)
+ m_bEOF = true;
+
+ } while ((ret == -1) && (errno == EAGAIN || errno == EINTR));
+
+ return ret;
+}
+
+void HTTPProtocol::httpCheckConnection()
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCheckConnection: " <<
+ " Socket status: " << m_iSock <<
+ " Keep Alive: " << m_bKeepAlive <<
+ " First: " << m_bFirstRequest << endl;
+
+ if ( !m_bFirstRequest && (m_iSock != -1) )
+ {
+ bool closeDown = false;
+ if ( !isConnectionValid())
+ {
+ kdDebug(7113) << "(" << m_pid << ") Connection lost!" << endl;
+ closeDown = true;
+ }
+ else if ( m_request.method != HTTP_GET )
+ {
+ closeDown = true;
+ }
+ else if ( !m_state.doProxy && !m_request.doProxy )
+ {
+ if (m_state.hostname != m_request.hostname ||
+ m_state.port != m_request.port ||
+ m_state.user != m_request.user ||
+ m_state.passwd != m_request.passwd)
+ closeDown = true;
+ }
+ else
+ {
+ // Keep the connection to the proxy.
+ if ( !(m_request.doProxy && m_state.doProxy) )
+ closeDown = true;
+ }
+
+ if (closeDown)
+ httpCloseConnection();
+ }
+
+ // Let's update our current state
+ m_state.hostname = m_request.hostname;
+ m_state.encoded_hostname = m_request.encoded_hostname;
+ m_state.port = m_request.port;
+ m_state.user = m_request.user;
+ m_state.passwd = m_request.passwd;
+ m_state.doProxy = m_request.doProxy;
+}
+
+bool HTTPProtocol::httpOpenConnection()
+{
+ int errCode;
+ TQString errMsg;
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpenConnection" << endl;
+
+ setBlockConnection( true );
+ // kio_http uses its own proxying:
+ KSocks::self()->disableSocks();
+
+ if ( m_state.doProxy )
+ {
+ TQString proxy_host = m_proxyURL.host();
+ int proxy_port = m_proxyURL.port();
+
+ kdDebug(7113) << "(" << m_pid << ") Connecting to proxy server: "
+ << proxy_host << ", port: " << proxy_port << endl;
+
+ infoMessage( i18n("Connecting to %1...").arg(m_state.hostname) );
+
+ setConnectTimeout( m_proxyConnTimeout );
+
+ if ( !connectToHost(proxy_host, proxy_port, false) )
+ {
+ if (userAborted()) {
+ error(ERR_NO_CONTENT, "");
+ return false;
+ }
+
+ switch ( connectResult() )
+ {
+ case IO_LookupError:
+ errMsg = proxy_host;
+ errCode = ERR_UNKNOWN_PROXY_HOST;
+ break;
+ case IO_TimeOutError:
+ errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
+ errCode = ERR_SERVER_TIMEOUT;
+ break;
+ default:
+ errMsg = i18n("Proxy %1 at port %2").arg(proxy_host).arg(proxy_port);
+ errCode = ERR_COULD_NOT_CONNECT;
+ }
+ error( errCode, errMsg );
+ return false;
+ }
+ }
+ else
+ {
+ // Apparently we don't want a proxy. let's just connect directly
+ setConnectTimeout(m_remoteConnTimeout);
+
+ if ( !connectToHost(m_state.hostname, m_state.port, false ) )
+ {
+ if (userAborted()) {
+ error(ERR_NO_CONTENT, "");
+ return false;
+ }
+
+ switch ( connectResult() )
+ {
+ case IO_LookupError:
+ errMsg = m_state.hostname;
+ errCode = ERR_UNKNOWN_HOST;
+ break;
+ case IO_TimeOutError:
+ errMsg = i18n("Connection was to %1 at port %2").arg(m_state.hostname).arg(m_state.port);
+ errCode = ERR_SERVER_TIMEOUT;
+ break;
+ default:
+ errCode = ERR_COULD_NOT_CONNECT;
+ if (m_state.port != m_iDefaultPort)
+ errMsg = i18n("%1 (port %2)").arg(m_state.hostname).arg(m_state.port);
+ else
+ errMsg = m_state.hostname;
+ }
+ error( errCode, errMsg );
+ return false;
+ }
+ }
+
+ // Set our special socket option!!
+ int on = 1;
+ (void) setsockopt( m_iSock, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on) );
+
+ m_bFirstRequest = true;
+
+ connected();
+ return true;
+}
+
+
+/**
+ * This function is responsible for opening up the connection to the remote
+ * HTTP server and sending the header. If this requires special
+ * authentication or other such fun stuff, then it will handle it. This
+ * function will NOT receive anything from the server, however. This is in
+ * contrast to previous incarnations of 'httpOpen'.
+ *
+ * The reason for the change is due to one small fact: some requests require
+ * data to be sent in addition to the header (POST requests) and there is no
+ * way for this function to get that data. This function is called in the
+ * slotPut() or slotGet() functions which, in turn, are called (indirectly) as
+ * a result of a TDEIOJob::put() or TDEIOJob::get(). It is those latter functions
+ * which are responsible for starting up this ioslave in the first place.
+ * This means that 'httpOpen' is called (essentially) as soon as the ioslave
+ * is created -- BEFORE any data gets to this slave.
+ *
+ * The basic process now is this:
+ *
+ * 1) Open up the socket and port
+ * 2) Format our request/header
+ * 3) Send the header to the remote server
+ */
+bool HTTPProtocol::httpOpen()
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen" << endl;
+
+ // Cannot have an https request without the m_bIsSSL being set! This can
+ // only happen if TCPSlaveBase::InitializeSSL() function failed in which it
+ // means the current installation does not support SSL...
+ if ( (m_protocol == "https" || m_protocol == "webdavs") && !m_bIsSSL )
+ {
+ error( ERR_UNSUPPORTED_PROTOCOL, m_protocol );
+ return false;
+ }
+
+ m_request.fcache = 0;
+ m_request.bCachedRead = false;
+ m_request.bCachedWrite = false;
+ m_request.bMustRevalidate = false;
+ m_request.expireDate = 0;
+ m_request.creationDate = 0;
+
+ if (m_request.bUseCache)
+ {
+ m_request.fcache = checkCacheEntry( );
+
+ bool bCacheOnly = (m_request.cache == TDEIO::CC_CacheOnly);
+ bool bOffline = isOffline(m_request.doProxy ? m_proxyURL : m_request.url);
+ if (bOffline && (m_request.cache != TDEIO::CC_Reload))
+ m_request.cache = TDEIO::CC_CacheOnly;
+
+ if (m_request.cache == CC_Reload && m_request.fcache)
+ {
+ if (m_request.fcache)
+ fclose(m_request.fcache);
+ m_request.fcache = 0;
+ }
+ if ((m_request.cache == TDEIO::CC_CacheOnly) || (m_request.cache == TDEIO::CC_Cache))
+ m_request.bMustRevalidate = false;
+
+ m_request.bCachedWrite = true;
+
+ if (m_request.fcache && !m_request.bMustRevalidate)
+ {
+ // Cache entry is OK.
+ m_request.bCachedRead = true; // Cache hit.
+ return true;
+ }
+ else if (!m_request.fcache)
+ {
+ m_request.bMustRevalidate = false; // Cache miss
+ }
+ else
+ {
+ // Conditional cache hit. (Validate)
+ }
+
+ if (bCacheOnly && bOffline)
+ {
+ error( ERR_OFFLINE_MODE, m_request.url.url() );
+ return false;
+ }
+ if (bCacheOnly)
+ {
+ error( ERR_DOES_NOT_EXIST, m_request.url.url() );
+ return false;
+ }
+ if (bOffline)
+ {
+ error( ERR_OFFLINE_MODE, m_request.url.url() );
+ return false;
+ }
+ }
+
+ TQString header;
+ TQString davHeader;
+
+ bool moreData = false;
+ bool davData = false;
+
+ // Clear out per-connection settings...
+ resetConnectionSettings ();
+
+ // Check the validity of the current connection, if one exists.
+ httpCheckConnection();
+
+ if ( !m_bIsTunneled && m_bNeedTunnel )
+ {
+ setEnableSSLTunnel( true );
+ // We send a HTTP 1.0 header since some proxies refuse HTTP 1.1 and we don't
+ // need any HTTP 1.1 capabilities for CONNECT - Waba
+ header = TQString("CONNECT %1:%2 HTTP/1.0"
+ "\r\n").arg( m_request.encoded_hostname).arg(m_request.port);
+
+ // Identify who you are to the proxy server!
+ if (!m_request.userAgent.isEmpty())
+ header += "User-Agent: " + m_request.userAgent + "\r\n";
+
+ /* Add hostname information */
+ header += "Host: " + m_state.encoded_hostname;
+
+ if (m_state.port != m_iDefaultPort)
+ header += TQString(":%1").arg(m_state.port);
+ header += "\r\n";
+
+ header += proxyAuthenticationHeader();
+ }
+ else
+ {
+ // Determine if this is a POST or GET method
+ switch (m_request.method)
+ {
+ case HTTP_GET:
+ header = "GET ";
+ break;
+ case HTTP_PUT:
+ header = "PUT ";
+ moreData = true;
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case HTTP_POST:
+ header = "POST ";
+ moreData = true;
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case HTTP_HEAD:
+ header = "HEAD ";
+ break;
+ case HTTP_DELETE:
+ header = "DELETE ";
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case HTTP_OPTIONS:
+ header = "OPTIONS ";
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case DAV_PROPFIND:
+ header = "PROPFIND ";
+ davData = true;
+ davHeader = "Depth: ";
+ if ( hasMetaData( "davDepth" ) )
+ {
+ kdDebug(7113) << "Reading DAV depth from metadata: " << metaData( "davDepth" ) << endl;
+ davHeader += metaData( "davDepth" );
+ }
+ else
+ {
+ if ( m_request.davData.depth == 2 )
+ davHeader += "infinity";
+ else
+ davHeader += TQString("%1").arg( m_request.davData.depth );
+ }
+ davHeader += "\r\n";
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case DAV_PROPPATCH:
+ header = "PROPPATCH ";
+ davData = true;
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case DAV_MKCOL:
+ header = "MKCOL ";
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case DAV_COPY:
+ case DAV_MOVE:
+ header = ( m_request.method == DAV_COPY ) ? "COPY " : "MOVE ";
+ davHeader = "Destination: " + m_request.davData.desturl;
+ // infinity depth means copy recursively
+ // (optional for copy -> but is the desired action)
+ davHeader += "\r\nDepth: infinity\r\nOverwrite: ";
+ davHeader += m_request.davData.overwrite ? "T" : "F";
+ davHeader += "\r\n";
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case DAV_LOCK:
+ header = "LOCK ";
+ davHeader = "Timeout: ";
+ {
+ uint timeout = 0;
+ if ( hasMetaData( "davTimeout" ) )
+ timeout = metaData( "davTimeout" ).toUInt();
+ if ( timeout == 0 )
+ davHeader += "Infinite";
+ else
+ davHeader += TQString("Seconds-%1").arg(timeout);
+ }
+ davHeader += "\r\n";
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ davData = true;
+ break;
+ case DAV_UNLOCK:
+ header = "UNLOCK ";
+ davHeader = "Lock-token: " + metaData("davLockToken") + "\r\n";
+ m_request.bCachedWrite = false; // Do not put any result in the cache
+ break;
+ case DAV_SEARCH:
+ header = "SEARCH ";
+ davData = true;
+ m_request.bCachedWrite = false;
+ break;
+ case DAV_SUBSCRIBE:
+ header = "SUBSCRIBE ";
+ m_request.bCachedWrite = false;
+ break;
+ case DAV_UNSUBSCRIBE:
+ header = "UNSUBSCRIBE ";
+ m_request.bCachedWrite = false;
+ break;
+ case DAV_POLL:
+ header = "POLL ";
+ m_request.bCachedWrite = false;
+ break;
+ default:
+ error (ERR_UNSUPPORTED_ACTION, TQString::null);
+ return false;
+ }
+ // DAV_POLL; DAV_NOTIFY
+
+ // format the URI
+ if (m_state.doProxy && !m_bIsTunneled)
+ {
+ KURL u;
+
+ if (m_protocol == "webdav")
+ u.setProtocol( "http" );
+ else if (m_protocol == "webdavs" )
+ u.setProtocol( "https" );
+ else
+ u.setProtocol( m_protocol );
+
+ // For all protocols other than the once handled by this io-slave
+ // append the username. This fixes a long standing bug of ftp io-slave
+ // logging in anonymously in proxied connections even when the username
+ // is explicitly specified.
+ if (m_protocol != "http" && m_protocol != "https" &&
+ !m_state.user.isEmpty())
+ u.setUser (m_state.user);
+
+ u.setHost( m_state.hostname );
+ if (m_state.port != m_iDefaultPort)
+ u.setPort( m_state.port );
+ u.setEncodedPathAndQuery( m_request.url.encodedPathAndQuery(0,true) );
+ header += u.url();
+ }
+ else
+ {
+ header += m_request.url.encodedPathAndQuery(0, true);
+ }
+
+ header += " HTTP/1.1\r\n"; /* start header */
+
+ if (!m_request.userAgent.isEmpty())
+ {
+ header += "User-Agent: ";
+ header += m_request.userAgent;
+ header += "\r\n";
+ }
+
+ if (!m_request.referrer.isEmpty())
+ {
+ header += "Referer: "; //Don't try to correct spelling!
+ header += m_request.referrer;
+ header += "\r\n";
+ }
+
+ if ( m_request.offset > 0 )
+ {
+ header += TQString("Range: bytes=%1-\r\n").arg(TDEIO::number(m_request.offset));
+ kdDebug(7103) << "kio_http : Range = " << TDEIO::number(m_request.offset) << endl;
+ }
+
+ if ( m_request.cache == CC_Reload )
+ {
+ /* No caching for reload */
+ header += "Pragma: no-cache\r\n"; /* for HTTP/1.0 caches */
+ header += "Cache-control: no-cache\r\n"; /* for HTTP >=1.1 caches */
+ }
+
+ if (m_request.bMustRevalidate)
+ {
+ /* conditional get */
+ if (!m_request.etag.isEmpty())
+ header += "If-None-Match: "+m_request.etag+"\r\n";
+ if (!m_request.lastModified.isEmpty())
+ header += "If-Modified-Since: "+m_request.lastModified+"\r\n";
+ }
+
+ header += "Accept: ";
+ TQString acceptHeader = metaData("accept");
+ if (!acceptHeader.isEmpty())
+ header += acceptHeader;
+ else
+ header += DEFAULT_ACCEPT_HEADER;
+ header += "\r\n";
+
+#ifdef DO_GZIP
+ if (m_request.allowCompressedPage)
+ header += "Accept-Encoding: x-gzip, x-deflate, gzip, deflate\r\n";
+#endif
+
+ if (!m_request.charsets.isEmpty())
+ header += "Accept-Charset: " + m_request.charsets + "\r\n";
+
+ if (!m_request.languages.isEmpty())
+ header += "Accept-Language: " + m_request.languages + "\r\n";
+
+
+ /* support for virtual hosts and required by HTTP 1.1 */
+ header += "Host: " + m_state.encoded_hostname;
+
+ if (m_state.port != m_iDefaultPort)
+ header += TQString(":%1").arg(m_state.port);
+ header += "\r\n";
+
+ TQString cookieStr;
+ TQString cookieMode = metaData("cookies").lower();
+ if (cookieMode == "none")
+ {
+ m_request.cookieMode = HTTPRequest::CookiesNone;
+ }
+ else if (cookieMode == "manual")
+ {
+ m_request.cookieMode = HTTPRequest::CookiesManual;
+ cookieStr = metaData("setcookies");
+ }
+ else
+ {
+ m_request.cookieMode = HTTPRequest::CookiesAuto;
+ if (m_request.bUseCookiejar)
+ cookieStr = findCookies( m_request.url.url());
+ }
+
+ if (!cookieStr.isEmpty())
+ header += cookieStr + "\r\n";
+
+ TQString customHeader = metaData( "customHTTPHeader" );
+ if (!customHeader.isEmpty())
+ {
+ header += sanitizeCustomHTTPHeader(customHeader);
+ header += "\r\n";
+ }
+
+ if (m_request.method == HTTP_POST)
+ {
+ header += metaData("content-type");
+ header += "\r\n";
+ }
+
+ // Only check for a cached copy if the previous
+ // response was NOT a 401 or 407.
+ // no caching for Negotiate auth.
+ if ( !m_request.bNoAuth && m_responseCode != 401 && m_responseCode != 407 && Authentication != AUTH_Negotiate )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Calling checkCachedAuthentication " << endl;
+ AuthInfo info;
+ info.url = m_request.url;
+ info.verifyPath = true;
+ if ( !m_request.user.isEmpty() )
+ info.username = m_request.user;
+ if ( checkCachedAuthentication( info ) && !info.digestInfo.isEmpty() )
+ {
+ Authentication = info.digestInfo.startsWith("Basic") ? AUTH_Basic : info.digestInfo.startsWith("NTLM") ? AUTH_NTLM : info.digestInfo.startsWith("Negotiate") ? AUTH_Negotiate : AUTH_Digest ;
+ m_state.user = info.username;
+ m_state.passwd = info.password;
+ m_strRealm = info.realmValue;
+ if ( Authentication != AUTH_NTLM && Authentication != AUTH_Negotiate ) // don't use the cached challenge
+ m_strAuthorization = info.digestInfo;
+ }
+ }
+ else
+ {
+ kdDebug(7113) << "(" << m_pid << ") Not calling checkCachedAuthentication " << endl;
+ }
+
+ switch ( Authentication )
+ {
+ case AUTH_Basic:
+ header += createBasicAuth();
+ break;
+ case AUTH_Digest:
+ header += createDigestAuth();
+ break;
+#ifdef HAVE_LIBGSSAPI
+ case AUTH_Negotiate:
+ header += createNegotiateAuth();
+ break;
+#endif
+ case AUTH_NTLM:
+ header += createNTLMAuth();
+ break;
+ case AUTH_None:
+ default:
+ break;
+ }
+
+ /********* Only for debugging purpose *********/
+ if ( Authentication != AUTH_None )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Using Authentication: " << endl;
+ kdDebug(7113) << "(" << m_pid << ") HOST= " << m_state.hostname << endl;
+ kdDebug(7113) << "(" << m_pid << ") PORT= " << m_state.port << endl;
+ kdDebug(7113) << "(" << m_pid << ") USER= " << m_state.user << endl;
+ kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
+ kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strRealm << endl;
+ kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strAuthorization << endl;
+ }
+
+ // Do we need to authorize to the proxy server ?
+ if ( m_state.doProxy && !m_bIsTunneled )
+ header += proxyAuthenticationHeader();
+
+ // Support old HTTP/1.0 style keep-alive header for compatability
+ // purposes as well as performance improvements while giving end
+ // users the ability to disable this feature proxy servers that
+ // don't not support such feature, e.g. junkbuster proxy server.
+ if (!m_bUseProxy || m_bPersistentProxyConnection || m_bIsTunneled)
+ header += "Connection: Keep-Alive\r\n";
+ else
+ header += "Connection: close\r\n";
+
+ if ( m_protocol == "webdav" || m_protocol == "webdavs" )
+ {
+ header += davProcessLocks();
+
+ // add extra webdav headers, if supplied
+ TQString davExtraHeader = metaData("davHeader");
+ if ( !davExtraHeader.isEmpty() )
+ davHeader += davExtraHeader;
+
+ // Set content type of webdav data
+ if (davData)
+ davHeader += "Content-Type: text/xml; charset=utf-8\r\n";
+
+ // add extra header elements for WebDAV
+ if ( !davHeader.isNull() )
+ header += davHeader;
+ }
+ }
+
+ kdDebug(7103) << "(" << m_pid << ") ============ Sending Header:" << endl;
+
+ TQStringList headerOutput = TQStringList::split("\r\n", header);
+ TQStringList::Iterator it = headerOutput.begin();
+
+ for (; it != headerOutput.end(); it++)
+ kdDebug(7103) << "(" << m_pid << ") " << (*it) << endl;
+
+ if ( !moreData && !davData)
+ header += "\r\n"; /* end header */
+
+ // Now that we have our formatted header, let's send it!
+ // Create a new connection to the remote machine if we do
+ // not already have one...
+ if ( m_iSock == -1)
+ {
+ if (!httpOpenConnection())
+ return false;
+ }
+
+ // Send the data to the remote machine...
+ bool sendOk = (write(header.latin1(), header.length()) == (ssize_t) header.length());
+ if (!sendOk)
+ {
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: "
+ "Connection broken! (" << m_state.hostname << ")" << endl;
+
+ // With a Keep-Alive connection this can happen.
+ // Just reestablish the connection.
+ if (m_bKeepAlive)
+ {
+ httpCloseConnection();
+ return true; // Try again
+ }
+
+ if (!sendOk)
+ {
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpOpen: sendOk==false."
+ " Connnection broken !" << endl;
+ error( ERR_CONNECTION_BROKEN, m_state.hostname );
+ return false;
+ }
+ }
+
+ bool res = true;
+
+ if ( moreData || davData )
+ res = sendBody();
+
+ infoMessage(i18n("%1 contacted. Waiting for reply...").arg(m_request.hostname));
+
+ return res;
+}
+
+void HTTPProtocol::forwardHttpResponseHeader()
+{
+ // Send the response header if it was requested
+ if ( config()->readBoolEntry("PropagateHttpHeader", false) )
+ {
+ setMetaData("HTTP-Headers", m_responseHeader.join("\n"));
+ sendMetaData();
+ }
+ m_responseHeader.clear();
+}
+
+/**
+ * This function will read in the return header from the server. It will
+ * not read in the body of the return message. It will also not transmit
+ * the header to our client as the client doesn't need to know the gory
+ * details of HTTP headers.
+ */
+bool HTTPProtocol::readHeader()
+{
+try_again:
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader" << endl;
+
+ // Check
+ if (m_request.bCachedRead)
+ {
+ m_responseHeader << "HTTP-CACHE";
+ // Read header from cache...
+ char buffer[4097];
+ if (!fgets(buffer, 4096, m_request.fcache) )
+ {
+ // Error, delete cache entry
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
+ << "Could not access cache to obtain mimetype!" << endl;
+ error( ERR_CONNECTION_BROKEN, m_state.hostname );
+ return false;
+ }
+
+ m_strMimeType = TQString(TQString::fromUtf8( buffer)).stripWhiteSpace();
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: cached "
+ << "data mimetype: " << m_strMimeType << endl;
+
+ if (!fgets(buffer, 4096, m_request.fcache) )
+ {
+ // Error, delete cache entry
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
+ << "Could not access cached data! " << endl;
+ error( ERR_CONNECTION_BROKEN, m_state.hostname );
+ return false;
+ }
+
+ m_request.strCharset = TQString(TQString::fromUtf8( buffer)).stripWhiteSpace().lower();
+ setMetaData("charset", m_request.strCharset);
+ if (!m_request.lastModified.isEmpty())
+ setMetaData("modified", m_request.lastModified);
+ TQString tmp;
+ tmp.setNum(m_request.expireDate);
+ setMetaData("expire-date", tmp);
+ tmp.setNum(m_request.creationDate);
+ setMetaData("cache-creation-date", tmp);
+ mimeType(m_strMimeType);
+ forwardHttpResponseHeader();
+ return true;
+ }
+
+ TQCString locationStr; // In case we get a redirect.
+ TQCString cookieStr; // In case we get a cookie.
+
+ TQString dispositionType; // In case we get a Content-Disposition type
+ TQString dispositionFilename; // In case we get a Content-Disposition filename
+
+ TQString mediaValue;
+ TQString mediaAttribute;
+
+ TQStringList upgradeOffers;
+
+ bool upgradeRequired = false; // Server demands that we upgrade to something
+ // This is also true if we ask to upgrade and
+ // the server accepts, since we are now
+ // committed to doing so
+ bool canUpgrade = false; // The server offered an upgrade
+
+
+ m_request.etag = TQString::null;
+ m_request.lastModified = TQString::null;
+ m_request.strCharset = TQString::null;
+
+ time_t dateHeader = 0;
+ time_t expireDate = 0; // 0 = no info, 1 = already expired, > 1 = actual date
+ int currentAge = 0;
+ int maxAge = -1; // -1 = no max age, 0 already expired, > 0 = actual time
+ int maxHeaderSize = 64*1024; // 64Kb to catch DOS-attacks
+
+ // read in 8192 bytes at a time (HTTP cookies can be quite large.)
+ int len = 0;
+ char buffer[8193];
+ bool cont = false;
+ bool cacheValidated = false; // Revalidation was successful
+ bool mayCache = true;
+ bool hasCacheDirective = false;
+ bool bCanResume = false;
+
+ if (m_iSock == -1)
+ {
+ kdDebug(7113) << "HTTPProtocol::readHeader: No connection." << endl;
+ return false; // Restablish connection and try again
+ }
+
+ if (!waitForResponse(m_remoteRespTimeout))
+ {
+ // No response error
+ error( ERR_SERVER_TIMEOUT , m_state.hostname );
+ return false;
+ }
+
+ setRewindMarker();
+
+ gets(buffer, sizeof(buffer)-1);
+
+ if (m_bEOF || *buffer == '\0')
+ {
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readHeader: "
+ << "EOF while waiting for header start." << endl;
+ if (m_bKeepAlive) // Try to reestablish connection.
+ {
+ httpCloseConnection();
+ return false; // Reestablish connection and try again.
+ }
+
+ if (m_request.method == HTTP_HEAD)
+ {
+ // HACK
+ // Some web-servers fail to respond properly to a HEAD request.
+ // We compensate for their failure to properly implement the HTTP standard
+ // by assuming that they will be sending html.
+ kdDebug(7113) << "(" << m_pid << ") HTTPPreadHeader: HEAD -> returned "
+ << "mimetype: " << DEFAULT_MIME_TYPE << endl;
+ mimeType(TQString::fromLatin1(DEFAULT_MIME_TYPE));
+ return true;
+ }
+
+ kdDebug(7113) << "HTTPProtocol::readHeader: Connection broken !" << endl;
+ error( ERR_CONNECTION_BROKEN, m_state.hostname );
+ return false;
+ }
+
+ kdDebug(7103) << "(" << m_pid << ") ============ Received Response:"<< endl;
+
+ bool noHeader = true;
+ HTTP_REV httpRev = HTTP_None;
+ int headerSize = 0;
+
+ do
+ {
+ // strip off \r and \n if we have them
+ len = strlen(buffer);
+
+ while(len && (buffer[len-1] == '\n' || buffer[len-1] == '\r'))
+ buffer[--len] = 0;
+
+ // if there was only a newline then continue
+ if (!len)
+ {
+ kdDebug(7103) << "(" << m_pid << ") --empty--" << endl;
+ continue;
+ }
+
+ headerSize += len;
+
+ // We have a response header. This flag is a work around for
+ // servers that append a "\r\n" before the beginning of the HEADER
+ // response!!! It only catches x number of \r\n being placed at the
+ // top of the reponse...
+ noHeader = false;
+
+ kdDebug(7103) << "(" << m_pid << ") \"" << buffer << "\"" << endl;
+
+ // Save broken servers from damnation!!
+ char* buf = buffer;
+ while( *buf == ' ' )
+ buf++;
+
+
+ if (buf[0] == '<')
+ {
+ // We get XML / HTTP without a proper header
+ // put string back
+ kdDebug(7103) << "kio_http: No valid HTTP header found! Document starts with XML/HTML tag" << endl;
+
+ // Document starts with a tag, assume html instead of text/plain
+ m_strMimeType = "text/html";
+
+ rewind();
+ break;
+ }
+
+ // Store the the headers so they can be passed to the
+ // calling application later
+ m_responseHeader << TQString::fromLatin1(buf);
+
+ if ((strncasecmp(buf, "HTTP/", 5) == 0) ||
+ (strncasecmp(buf, "ICY ", 4) == 0)) // Shoutcast support
+ {
+ if (strncasecmp(buf, "ICY ", 4) == 0)
+ {
+ // Shoutcast support
+ httpRev = SHOUTCAST;
+ m_bKeepAlive = false;
+ }
+ else if (strncmp((buf + 5), "1.0",3) == 0)
+ {
+ httpRev = HTTP_10;
+ // For 1.0 servers, the server itself has to explicitly
+ // tell us whether it supports persistent connection or
+ // not. By default, we assume it does not, but we do
+ // send the old style header "Connection: Keep-Alive" to
+ // inform it that we support persistence.
+ m_bKeepAlive = false;
+ }
+ else if (strncmp((buf + 5), "1.1",3) == 0)
+ {
+ httpRev = HTTP_11;
+ }
+ else
+ {
+ httpRev = HTTP_Unknown;
+ }
+
+ if (m_responseCode)
+ m_prevResponseCode = m_responseCode;
+
+ const char* rptr = buf;
+ while ( *rptr && *rptr > ' ' )
+ ++rptr;
+ m_responseCode = atoi(rptr);
+
+ // server side errors
+ if (m_responseCode >= 500 && m_responseCode <= 599)
+ {
+ if (m_request.method == HTTP_HEAD)
+ {
+ ; // Ignore error
+ }
+ else
+ {
+ if (m_request.bErrorPage)
+ errorPage();
+ else
+ {
+ error(ERR_INTERNAL_SERVER, m_request.url.url());
+ return false;
+ }
+ }
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ }
+ // Unauthorized access
+ else if (m_responseCode == 401 || m_responseCode == 407)
+ {
+ // Double authorization requests, i.e. a proxy auth
+ // request followed immediately by a regular auth request.
+ if ( m_prevResponseCode != m_responseCode &&
+ (m_prevResponseCode == 401 || m_prevResponseCode == 407) )
+ saveAuthorization();
+
+ m_bUnauthorized = true;
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ }
+ //
+ else if (m_responseCode == 416) // Range not supported
+ {
+ m_request.offset = 0;
+ httpCloseConnection();
+ return false; // Try again.
+ }
+ // Upgrade Required
+ else if (m_responseCode == 426)
+ {
+ upgradeRequired = true;
+ }
+ // Any other client errors
+ else if (m_responseCode >= 400 && m_responseCode <= 499)
+ {
+ // Tell that we will only get an error page here.
+ if (m_request.bErrorPage)
+ errorPage();
+ else
+ {
+ error(ERR_DOES_NOT_EXIST, m_request.url.url());
+ return false;
+ }
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ }
+ else if (m_responseCode == 307)
+ {
+ // 307 Temporary Redirect
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ }
+ else if (m_responseCode == 304)
+ {
+ // 304 Not Modified
+ // The value in our cache is still valid.
+ cacheValidated = true;
+ }
+ else if (m_responseCode >= 301 && m_responseCode<= 303)
+ {
+ // 301 Moved permanently
+ if (m_responseCode == 301)
+ setMetaData("permanent-redirect", "true");
+
+ // 302 Found (temporary location)
+ // 303 See Other
+ if (m_request.method != HTTP_HEAD && m_request.method != HTTP_GET)
+ {
+#if 0
+ // Reset the POST buffer to avoid a double submit
+ // on redirection
+ if (m_request.method == HTTP_POST)
+ m_bufPOST.resize(0);
+#endif
+
+ // NOTE: This is wrong according to RFC 2616. However,
+ // because most other existing user agent implementations
+ // treat a 301/302 response as a 303 response and preform
+ // a GET action regardless of what the previous method was,
+ // many servers have simply adapted to this way of doing
+ // things!! Thus, we are forced to do the same thing or we
+ // won't be able to retrieve these pages correctly!! See RFC
+ // 2616 sections 10.3.[2/3/4/8]
+ m_request.method = HTTP_GET; // Force a GET
+ }
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ }
+ else if ( m_responseCode == 207 ) // Multi-status (for WebDav)
+ {
+
+ }
+ else if ( m_responseCode == 204 ) // No content
+ {
+ // error(ERR_NO_CONTENT, i18n("Data have been successfully sent."));
+ // Short circuit and do nothing!
+
+ // The original handling here was wrong, this is not an error: eg. in the
+ // example of a 204 No Content response to a PUT completing.
+ // m_bError = true;
+ // return false;
+ }
+ else if ( m_responseCode == 206 )
+ {
+ if ( m_request.offset )
+ bCanResume = true;
+ }
+ else if (m_responseCode == 102) // Processing (for WebDAV)
+ {
+ /***
+ * This status code is given when the server expects the
+ * command to take significant time to complete. So, inform
+ * the user.
+ */
+ infoMessage( i18n( "Server processing request, please wait..." ) );
+ cont = true;
+ }
+ else if (m_responseCode == 100)
+ {
+ // We got 'Continue' - ignore it
+ cont = true;
+ }
+ }
+
+ // are we allowd to resume? this will tell us
+ else if (strncasecmp(buf, "Accept-Ranges:", 14) == 0) {
+ if (strncasecmp(trimLead(buf + 14), "none", 4) == 0)
+ bCanResume = false;
+ }
+ // Keep Alive
+ else if (strncasecmp(buf, "Keep-Alive:", 11) == 0) {
+ TQStringList options = TQStringList::split(',',
+ TQString::fromLatin1(trimLead(buf+11)));
+ for(TQStringList::ConstIterator it = options.begin();
+ it != options.end();
+ it++)
+ {
+ TQString option = (*it).stripWhiteSpace().lower();
+ if (option.startsWith("timeout="))
+ {
+ m_keepAliveTimeout = option.mid(8).toInt();
+ }
+ }
+ }
+
+ // Cache control
+ else if (strncasecmp(buf, "Cache-Control:", 14) == 0) {
+ TQStringList cacheControls = TQStringList::split(',',
+ TQString::fromLatin1(trimLead(buf+14)));
+ for(TQStringList::ConstIterator it = cacheControls.begin();
+ it != cacheControls.end();
+ it++)
+ {
+ TQString cacheControl = (*it).stripWhiteSpace();
+ if (strncasecmp(cacheControl.latin1(), "no-cache", 8) == 0)
+ {
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ }
+ else if (strncasecmp(cacheControl.latin1(), "no-store", 8) == 0)
+ {
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ }
+ else if (strncasecmp(cacheControl.latin1(), "max-age=", 8) == 0)
+ {
+ TQString age = cacheControl.mid(8).stripWhiteSpace();
+ if (!age.isNull())
+ maxAge = STRTOLL(age.latin1(), 0, 10);
+ }
+ }
+ hasCacheDirective = true;
+ }
+
+ // get the size of our data
+ else if (strncasecmp(buf, "Content-length:", 15) == 0) {
+ char* len = trimLead(buf + 15);
+ if (len)
+ m_iSize = STRTOLL(len, 0, 10);
+ }
+
+ else if (strncasecmp(buf, "Content-location:", 17) == 0) {
+ setMetaData ("content-location",
+ TQString::fromLatin1(trimLead(buf+17)).stripWhiteSpace());
+ }
+
+ // what type of data do we have?
+ else if (strncasecmp(buf, "Content-type:", 13) == 0) {
+ char *start = trimLead(buf + 13);
+ char *pos = start;
+
+ // Increment until we encounter ";" or the end of the buffer
+ while ( *pos && *pos != ';' ) pos++;
+
+ // Assign the mime-type.
+ m_strMimeType = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
+ kdDebug(7113) << "(" << m_pid << ") Content-type: " << m_strMimeType << endl;
+
+ // If we still have text, then it means we have a mime-type with a
+ // parameter (eg: charset=iso-8851) ; so let's get that...
+ while (*pos)
+ {
+ start = ++pos;
+ while ( *pos && *pos != '=' ) pos++;
+
+ char *end = pos;
+ while ( *end && *end != ';' ) end++;
+
+ if (*pos)
+ {
+ mediaAttribute = TQString::fromLatin1(start, pos-start).stripWhiteSpace().lower();
+ mediaValue = TQString::fromLatin1(pos+1, end-pos-1).stripWhiteSpace();
+ pos = end;
+ if (mediaValue.length() &&
+ (mediaValue[0] == '"') &&
+ (mediaValue[mediaValue.length()-1] == '"'))
+ mediaValue = mediaValue.mid(1, mediaValue.length()-2);
+
+ kdDebug (7113) << "(" << m_pid << ") Media-Parameter Attribute: "
+ << mediaAttribute << endl;
+ kdDebug (7113) << "(" << m_pid << ") Media-Parameter Value: "
+ << mediaValue << endl;
+
+ if ( mediaAttribute == "charset")
+ {
+ mediaValue = mediaValue.lower();
+ m_request.strCharset = mediaValue;
+ }
+ else
+ {
+ setMetaData("media-"+mediaAttribute, mediaValue);
+ }
+ }
+ }
+ }
+
+ // Date
+ else if (strncasecmp(buf, "Date:", 5) == 0) {
+ dateHeader = KRFCDate::parseDate(trimLead(buf+5));
+ }
+
+ // Cache management
+ else if (strncasecmp(buf, "ETag:", 5) == 0) {
+ m_request.etag = trimLead(buf+5);
+ }
+
+ // Cache management
+ else if (strncasecmp(buf, "Expires:", 8) == 0) {
+ expireDate = KRFCDate::parseDate(trimLead(buf+8));
+ if (!expireDate)
+ expireDate = 1; // Already expired
+ }
+
+ // Cache management
+ else if (strncasecmp(buf, "Last-Modified:", 14) == 0) {
+ m_request.lastModified = (TQString::fromLatin1(trimLead(buf+14))).stripWhiteSpace();
+ }
+
+ // whoops.. we received a warning
+ else if (strncasecmp(buf, "Warning:", 8) == 0) {
+ //Don't use warning() here, no need to bother the user.
+ //Those warnings are mostly about caches.
+ infoMessage(trimLead(buf + 8));
+ }
+
+ // Cache management (HTTP 1.0)
+ else if (strncasecmp(buf, "Pragma:", 7) == 0) {
+ TQCString pragma = TQCString(trimLead(buf+7)).stripWhiteSpace().lower();
+ if (pragma == "no-cache")
+ {
+ m_request.bCachedWrite = false; // Don't put in cache
+ mayCache = false;
+ hasCacheDirective = true;
+ }
+ }
+
+ // The deprecated Refresh Response
+ else if (strncasecmp(buf,"Refresh:", 8) == 0) {
+ mayCache = false; // Do not cache page as it defeats purpose of Refresh tag!
+ setMetaData( "http-refresh", TQString::fromLatin1(trimLead(buf+8)).stripWhiteSpace() );
+ }
+
+ // In fact we should do redirection only if we got redirection code
+ else if (strncasecmp(buf, "Location:", 9) == 0) {
+ // Redirect only for 3xx status code, will ya! Thanks, pal!
+ if ( m_responseCode > 299 && m_responseCode < 400 )
+ locationStr = TQCString(trimLead(buf+9)).stripWhiteSpace();
+ }
+
+ // Check for cookies
+ else if (strncasecmp(buf, "Set-Cookie", 10) == 0) {
+ cookieStr += buf;
+ cookieStr += '\n';
+ }
+
+ // check for direct authentication
+ else if (strncasecmp(buf, "WWW-Authenticate:", 17) == 0) {
+ configAuth(trimLead(buf + 17), false);
+ }
+
+ // check for proxy-based authentication
+ else if (strncasecmp(buf, "Proxy-Authenticate:", 19) == 0) {
+ configAuth(trimLead(buf + 19), true);
+ }
+
+ else if (strncasecmp(buf, "Upgrade:", 8) == 0) {
+ // Now we have to check to see what is offered for the upgrade
+ TQString offered = &(buf[8]);
+ upgradeOffers = TQStringList::split(TQRegExp("[ \n,\r\t]"), offered);
+ }
+
+ // content?
+ else if (strncasecmp(buf, "Content-Encoding:", 17) == 0) {
+ // This is so wrong !! No wonder kio_http is stripping the
+ // gzip encoding from downloaded files. This solves multiple
+ // bug reports and caitoo's problem with downloads when such a
+ // header is encountered...
+
+ // A quote from RFC 2616:
+ // " When present, its (Content-Encoding) value indicates what additional
+ // content have been applied to the entity body, and thus what decoding
+ // mechanism must be applied to obtain the media-type referenced by the
+ // Content-Type header field. Content-Encoding is primarily used to allow
+ // a document to be compressed without loosing the identity of its underlying
+ // media type. Simply put if it is specified, this is the actual mime-type
+ // we should use when we pull the resource !!!
+ addEncoding(trimLead(buf + 17), m_qContentEncodings);
+ }
+ // Refer to RFC 2616 sec 15.5/19.5.1 and RFC 2183
+ else if(strncasecmp(buf, "Content-Disposition:", 20) == 0) {
+ char* dispositionBuf = trimLead(buf + 20);
+ while ( *dispositionBuf )
+ {
+ if ( strncasecmp( dispositionBuf, "filename", 8 ) == 0 )
+ {
+ dispositionBuf += 8;
+
+ while ( *dispositionBuf == ' ' || *dispositionBuf == '=' )
+ dispositionBuf++;
+
+ char* bufStart = dispositionBuf;
+
+ while ( *dispositionBuf && *dispositionBuf != ';' )
+ dispositionBuf++;
+
+ if ( dispositionBuf > bufStart )
+ {
+ // Skip any leading quotes...
+ while ( *bufStart == '"' )
+ bufStart++;
+
+ // Skip any trailing quotes as well as white spaces...
+ while ( *(dispositionBuf-1) == ' ' || *(dispositionBuf-1) == '"')
+ dispositionBuf--;
+
+ if ( dispositionBuf > bufStart )
+ dispositionFilename = TQString::fromLatin1( bufStart, dispositionBuf-bufStart );
+
+ break;
+ }
+ }
+ else
+ {
+ char *bufStart = dispositionBuf;
+
+ while ( *dispositionBuf && *dispositionBuf != ';' )
+ dispositionBuf++;
+
+ if ( dispositionBuf > bufStart )
+ dispositionType = TQString::fromLatin1( bufStart, dispositionBuf-bufStart ).stripWhiteSpace();
+
+ while ( *dispositionBuf == ';' || *dispositionBuf == ' ' )
+ dispositionBuf++;
+ }
+ }
+
+ // Content-Dispostion is not allowed to dictate directory
+ // path, thus we extract the filename only.
+ if ( !dispositionFilename.isEmpty() )
+ {
+ int pos = dispositionFilename.findRev( '/' );
+
+ if( pos > -1 )
+ dispositionFilename = dispositionFilename.mid(pos+1);
+
+ kdDebug(7113) << "(" << m_pid << ") Content-Disposition: filename="
+ << dispositionFilename<< endl;
+ }
+ }
+ else if(strncasecmp(buf, "Content-Language:", 17) == 0) {
+ TQString language = TQString::fromLatin1(trimLead(buf+17)).stripWhiteSpace();
+ if (!language.isEmpty())
+ setMetaData("content-language", language);
+ }
+ else if (strncasecmp(buf, "Proxy-Connection:", 17) == 0)
+ {
+ if (strncasecmp(trimLead(buf + 17), "Close", 5) == 0)
+ m_bKeepAlive = false;
+ else if (strncasecmp(trimLead(buf + 17), "Keep-Alive", 10)==0)
+ m_bKeepAlive = true;
+ }
+ else if (strncasecmp(buf, "Link:", 5) == 0) {
+ // We only support Link: <url>; rel="type" so far
+ TQStringList link = TQStringList::split(";", TQString(buf)
+ .replace(TQRegExp("^Link:[ ]*"),
+ ""));
+ if (link.count() == 2) {
+ TQString rel = link[1].stripWhiteSpace();
+ if (rel.startsWith("rel=\"")) {
+ rel = rel.mid(5, rel.length() - 6);
+ if (rel.lower() == "pageservices") {
+ TQString url = TQString(link[0].replace(TQRegExp("[<>]"),"")).stripWhiteSpace();
+ setMetaData("PageServices", url);
+ }
+ }
+ }
+ }
+ else if (strncasecmp(buf, "P3P:", 4) == 0) {
+ TQString p3pstr = buf;
+ p3pstr = p3pstr.mid(4).simplifyWhiteSpace();
+ TQStringList policyrefs, compact;
+ TQStringList policyfields = TQStringList::split(TQRegExp(",[ ]*"), p3pstr);
+ for (TQStringList::Iterator it = policyfields.begin();
+ it != policyfields.end();
+ ++it) {
+ TQStringList policy = TQStringList::split("=", *it);
+
+ if (policy.count() == 2) {
+ if (policy[0].lower() == "policyref") {
+ policyrefs << TQString(policy[1].replace(TQRegExp("[\"\']"), ""))
+ .stripWhiteSpace();
+ } else if (policy[0].lower() == "cp") {
+ // We convert to cp\ncp\ncp\n[...]\ncp to be consistent with
+ // other metadata sent in strings. This could be a bit more
+ // efficient but I'm going for correctness right now.
+ TQStringList cps = TQStringList::split(" ",
+ TQString(policy[1].replace(TQRegExp("[\"\']"), ""))
+ .simplifyWhiteSpace());
+
+ for (TQStringList::Iterator j = cps.begin(); j != cps.end(); ++j)
+ compact << *j;
+ }
+ }
+ }
+
+ if (!policyrefs.isEmpty())
+ setMetaData("PrivacyPolicy", policyrefs.join("\n"));
+
+ if (!compact.isEmpty())
+ setMetaData("PrivacyCompactPolicy", compact.join("\n"));
+ }
+ // let them tell us if we should stay alive or not
+ else if (strncasecmp(buf, "Connection:", 11) == 0)
+ {
+ if (strncasecmp(trimLead(buf + 11), "Close", 5) == 0)
+ m_bKeepAlive = false;
+ else if (strncasecmp(trimLead(buf + 11), "Keep-Alive", 10)==0)
+ m_bKeepAlive = true;
+ else if (strncasecmp(trimLead(buf + 11), "Upgrade", 7)==0)
+ {
+ if (m_responseCode == 101) {
+ // Ok, an upgrade was accepted, now we must do it
+ upgradeRequired = true;
+ } else if (upgradeRequired) { // 426
+ // Nothing to do since we did it above already
+ } else {
+ // Just an offer to upgrade - no need to take it
+ canUpgrade = true;
+ }
+ }
+ }
+ // continue only if we know that we're HTTP/1.1
+ else if ( httpRev == HTTP_11) {
+ // what kind of encoding do we have? transfer?
+ if (strncasecmp(buf, "Transfer-Encoding:", 18) == 0) {
+ // If multiple encodings have been applied to an entity, the
+ // transfer-codings MUST be listed in the order in which they
+ // were applied.
+ addEncoding(trimLead(buf + 18), m_qTransferEncodings);
+ }
+
+ // md5 signature
+ else if (strncasecmp(buf, "Content-MD5:", 12) == 0) {
+ m_sContentMD5 = TQString::fromLatin1(trimLead(buf + 12));
+ }
+
+ // *** Responses to the HTTP OPTIONS method follow
+ // WebDAV capabilities
+ else if (strncasecmp(buf, "DAV:", 4) == 0) {
+ if (m_davCapabilities.isEmpty()) {
+ m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
+ }
+ else {
+ m_davCapabilities << TQString::fromLatin1(trimLead(buf + 4));
+ }
+ }
+ // *** Responses to the HTTP OPTIONS method finished
+ }
+ else if ((httpRev == HTTP_None) && (strlen(buf) != 0))
+ {
+ // Remote server does not seem to speak HTTP at all
+ // Put the crap back into the buffer and hope for the best
+ rewind();
+ if (m_responseCode)
+ m_prevResponseCode = m_responseCode;
+
+ m_responseCode = 200; // Fake it
+ httpRev = HTTP_Unknown;
+ m_bKeepAlive = false;
+ break;
+ }
+ setRewindMarker();
+
+ // Clear out our buffer for further use.
+ memset(buffer, 0, sizeof(buffer));
+
+ } while (!m_bEOF && (len || noHeader) && (headerSize < maxHeaderSize) && (gets(buffer, sizeof(buffer)-1)));
+
+ // Now process the HTTP/1.1 upgrade
+ TQStringList::Iterator opt = upgradeOffers.begin();
+ for( ; opt != upgradeOffers.end(); ++opt) {
+ if (*opt == "TLS/1.0") {
+ if(upgradeRequired) {
+ if (!startTLS() && !usingTLS()) {
+ error(ERR_UPGRADE_REQUIRED, *opt);
+ return false;
+ }
+ }
+ } else if (*opt == "HTTP/1.1") {
+ httpRev = HTTP_11;
+ } else {
+ // unknown
+ if (upgradeRequired) {
+ error(ERR_UPGRADE_REQUIRED, *opt);
+ return false;
+ }
+ }
+ }
+
+ setMetaData("charset", m_request.strCharset);
+
+ // If we do not support the requested authentication method...
+ if ( (m_responseCode == 401 && Authentication == AUTH_None) ||
+ (m_responseCode == 407 && ProxyAuthentication == AUTH_None) )
+ {
+ m_bUnauthorized = false;
+ if (m_request.bErrorPage)
+ errorPage();
+ else
+ {
+ error( ERR_UNSUPPORTED_ACTION, "Unknown Authorization method!" );
+ return false;
+ }
+ }
+
+ // Fixup expire date for clock drift.
+ if (expireDate && (expireDate <= dateHeader))
+ expireDate = 1; // Already expired.
+
+ // Convert max-age into expireDate (overriding previous set expireDate)
+ if (maxAge == 0)
+ expireDate = 1; // Already expired.
+ else if (maxAge > 0)
+ {
+ if (currentAge)
+ maxAge -= currentAge;
+ if (maxAge <=0)
+ maxAge = 0;
+ expireDate = time(0) + maxAge;
+ }
+
+ if (!expireDate)
+ {
+ time_t lastModifiedDate = 0;
+ if (!m_request.lastModified.isEmpty())
+ lastModifiedDate = KRFCDate::parseDate(m_request.lastModified);
+
+ if (lastModifiedDate)
+ {
+ long diff = static_cast<long>(difftime(dateHeader, lastModifiedDate));
+ if (diff < 0)
+ expireDate = time(0) + 1;
+ else
+ expireDate = time(0) + (diff / 10);
+ }
+ else
+ {
+ expireDate = time(0) + DEFAULT_CACHE_EXPIRE;
+ }
+ }
+
+ // DONE receiving the header!
+ if (!cookieStr.isEmpty())
+ {
+ if ((m_request.cookieMode == HTTPRequest::CookiesAuto) && m_request.bUseCookiejar)
+ {
+ // Give cookies to the cookiejar.
+ TQString domain = config()->readEntry("cross-domain");
+ if (!domain.isEmpty() && isCrossDomainRequest(m_request.url.host(), domain))
+ cookieStr = "Cross-Domain\n" + cookieStr;
+ addCookies( m_request.url.url(), cookieStr );
+ }
+ else if (m_request.cookieMode == HTTPRequest::CookiesManual)
+ {
+ // Pass cookie to application
+ setMetaData("setcookies", cookieStr);
+ }
+ }
+
+ if (m_request.bMustRevalidate)
+ {
+ m_request.bMustRevalidate = false; // Reset just in case.
+ if (cacheValidated)
+ {
+ // Yippie, we can use the cached version.
+ // Update the cache with new "Expire" headers.
+ fclose(m_request.fcache);
+ m_request.fcache = 0;
+ updateExpireDate( expireDate, true );
+ m_request.fcache = checkCacheEntry( ); // Re-read cache entry
+
+ if (m_request.fcache)
+ {
+ m_request.bCachedRead = true;
+ goto try_again; // Read header again, but now from cache.
+ }
+ else
+ {
+ // Where did our cache entry go???
+ }
+ }
+ else
+ {
+ // Validation failed. Close cache.
+ fclose(m_request.fcache);
+ m_request.fcache = 0;
+ }
+ }
+
+ // We need to reread the header if we got a '100 Continue' or '102 Processing'
+ if ( cont )
+ {
+ goto try_again;
+ }
+
+ // Do not do a keep-alive connection if the size of the
+ // response is not known and the response is not Chunked.
+ if (!m_bChunked && (m_iSize == NO_SIZE))
+ m_bKeepAlive = false;
+
+ if ( m_responseCode == 204 )
+ {
+ return true;
+ }
+
+ // We need to try to login again if we failed earlier
+ if ( m_bUnauthorized )
+ {
+ if ( (m_responseCode == 401) ||
+ (m_bUseProxy && (m_responseCode == 407))
+ )
+ {
+ if ( getAuthorization() )
+ {
+ // for NTLM Authentication we have to keep the connection open!
+ if ( Authentication == AUTH_NTLM && m_strAuthorization.length() > 4 )
+ {
+ m_bKeepAlive = true;
+ readBody( true );
+ }
+ else if (ProxyAuthentication == AUTH_NTLM && m_strProxyAuthorization.length() > 4)
+ {
+ readBody( true );
+ }
+ else
+ httpCloseConnection();
+ return false; // Try again.
+ }
+
+ if (m_bError)
+ return false; // Error out
+
+ // Show error page...
+ }
+ m_bUnauthorized = false;
+ }
+
+ // We need to do a redirect
+ if (!locationStr.isEmpty())
+ {
+ KURL u(m_request.url, locationStr);
+ if(!u.isValid())
+ {
+ error(ERR_MALFORMED_URL, u.url());
+ return false;
+ }
+ if ((u.protocol() != "http") && (u.protocol() != "https") &&
+ (u.protocol() != "ftp") && (u.protocol() != "webdav") &&
+ (u.protocol() != "webdavs"))
+ {
+ redirection(u);
+ error(ERR_ACCESS_DENIED, u.url());
+ return false;
+ }
+
+ // preserve #ref: (bug 124654)
+ // if we were at http://host/resource1#ref, we sent a GET for "/resource1"
+ // if we got redirected to http://host/resource2, then we have to re-add
+ // the fragment:
+ if (m_request.url.hasRef() && !u.hasRef() &&
+ (m_request.url.host() == u.host()) &&
+ (m_request.url.protocol() == u.protocol()))
+ u.setRef(m_request.url.ref());
+
+ m_bRedirect = true;
+ m_redirectLocation = u;
+
+ if (!m_request.id.isEmpty())
+ {
+ sendMetaData();
+ }
+
+ kdDebug(7113) << "(" << m_pid << ") request.url: " << m_request.url.url()
+ << endl << "LocationStr: " << locationStr.data() << endl;
+
+ kdDebug(7113) << "(" << m_pid << ") Requesting redirection to: " << u.url()
+ << endl;
+
+ // If we're redirected to a http:// url, remember that we're doing webdav...
+ if (m_protocol == "webdav" || m_protocol == "webdavs")
+ u.setProtocol(m_protocol);
+
+ redirection(u);
+ m_request.bCachedWrite = false; // Turn off caching on re-direction (DA)
+ mayCache = false;
+ }
+
+ // Inform the job that we can indeed resume...
+ if ( bCanResume && m_request.offset )
+ canResume();
+ else
+ m_request.offset = 0;
+
+ // We don't cache certain text objects
+ if (m_strMimeType.startsWith("text/") &&
+ (m_strMimeType != "text/css") &&
+ (m_strMimeType != "text/x-javascript") &&
+ !hasCacheDirective)
+ {
+ // Do not cache secure pages or pages
+ // originating from password protected sites
+ // unless the webserver explicitly allows it.
+ if ( m_bIsSSL || (Authentication != AUTH_None) )
+ {
+ m_request.bCachedWrite = false;
+ mayCache = false;
+ }
+ }
+
+ // WABA: Correct for tgz files with a gzip-encoding.
+ // They really shouldn't put gzip in the Content-Encoding field!
+ // Web-servers really shouldn't do this: They let Content-Size refer
+ // to the size of the tgz file, not to the size of the tar file,
+ // while the Content-Type refers to "tar" instead of "tgz".
+ if (m_qContentEncodings.last() == "gzip")
+ {
+ if (m_strMimeType == "application/x-tar")
+ {
+ m_qContentEncodings.remove(m_qContentEncodings.fromLast());
+ m_strMimeType = TQString::fromLatin1("application/x-tgz");
+ }
+ else if (m_strMimeType == "application/postscript")
+ {
+ // LEONB: Adding another exception for psgz files.
+ // Could we use the mimelnk files instead of hardcoding all this?
+ m_qContentEncodings.remove(m_qContentEncodings.fromLast());
+ m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
+ }
+ else if ( m_request.allowCompressedPage &&
+ m_strMimeType != "application/x-tgz" &&
+ m_strMimeType != "application/x-targz" &&
+ m_strMimeType != "application/x-gzip" &&
+ m_request.url.path().right(6) == ".ps.gz" )
+ {
+ m_qContentEncodings.remove(m_qContentEncodings.fromLast());
+ m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
+ }
+ else if ( (m_request.allowCompressedPage &&
+ m_strMimeType == "text/html")
+ ||
+ (m_request.allowCompressedPage &&
+ m_strMimeType != "application/x-tgz" &&
+ m_strMimeType != "application/x-targz" &&
+ m_strMimeType != "application/x-gzip" &&
+ m_request.url.path().right(3) != ".gz")
+ )
+ {
+ // Unzip!
+ }
+ else
+ {
+ m_qContentEncodings.remove(m_qContentEncodings.fromLast());
+ m_strMimeType = TQString::fromLatin1("application/x-gzip");
+ }
+ }
+
+ // We can't handle "bzip2" encoding (yet). So if we get something with
+ // bzip2 encoding, we change the mimetype to "application/x-bzip2".
+ // Note for future changes: some web-servers send both "bzip2" as
+ // encoding and "application/x-bzip2" as mimetype. That is wrong.
+ // currently that doesn't bother us, because we remove the encoding
+ // and set the mimetype to x-bzip2 anyway.
+ if (m_qContentEncodings.last() == "bzip2")
+ {
+ m_qContentEncodings.remove(m_qContentEncodings.fromLast());
+ m_strMimeType = TQString::fromLatin1("application/x-bzip2");
+ }
+
+ // Convert some common mimetypes to standard KDE mimetypes
+ if (m_strMimeType == "application/x-targz")
+ m_strMimeType = TQString::fromLatin1("application/x-tgz");
+ else if (m_strMimeType == "application/zip")
+ m_strMimeType = TQString::fromLatin1("application/x-zip");
+ else if (m_strMimeType == "image/x-png")
+ m_strMimeType = TQString::fromLatin1("image/png");
+ else if (m_strMimeType == "image/bmp")
+ m_strMimeType = TQString::fromLatin1("image/x-bmp");
+ else if (m_strMimeType == "audio/mpeg" || m_strMimeType == "audio/x-mpeg" || m_strMimeType == "audio/mp3")
+ m_strMimeType = TQString::fromLatin1("audio/x-mp3");
+ else if (m_strMimeType == "audio/microsoft-wave")
+ m_strMimeType = TQString::fromLatin1("audio/x-wav");
+ else if (m_strMimeType == "audio/midi")
+ m_strMimeType = TQString::fromLatin1("audio/x-midi");
+ else if (m_strMimeType == "image/x-xpixmap")
+ m_strMimeType = TQString::fromLatin1("image/x-xpm");
+ else if (m_strMimeType == "application/rtf")
+ m_strMimeType = TQString::fromLatin1("text/rtf");
+
+ // Crypto ones....
+ else if (m_strMimeType == "application/pkix-cert" ||
+ m_strMimeType == "application/binary-certificate")
+ {
+ m_strMimeType = TQString::fromLatin1("application/x-x509-ca-cert");
+ }
+
+ // Prefer application/x-tgz or x-gzpostscript over application/x-gzip.
+ else if (m_strMimeType == "application/x-gzip")
+ {
+ if ((m_request.url.path().right(7) == ".tar.gz") ||
+ (m_request.url.path().right(4) == ".tar"))
+ m_strMimeType = TQString::fromLatin1("application/x-tgz");
+ if ((m_request.url.path().right(6) == ".ps.gz"))
+ m_strMimeType = TQString::fromLatin1("application/x-gzpostscript");
+ }
+
+ // Some webservers say "text/plain" when they mean "application/x-bzip2"
+ else if ((m_strMimeType == "text/plain") || (m_strMimeType == "application/octet-stream"))
+ {
+ TQString ext = m_request.url.path().right(4).upper();
+ if (ext == ".BZ2")
+ m_strMimeType = TQString::fromLatin1("application/x-bzip2");
+ else if (ext == ".PEM")
+ m_strMimeType = TQString::fromLatin1("application/x-x509-ca-cert");
+ else if (ext == ".SWF")
+ m_strMimeType = TQString::fromLatin1("application/x-shockwave-flash");
+ else if (ext == ".PLS")
+ m_strMimeType = TQString::fromLatin1("audio/x-scpls");
+ else if (ext == ".WMV")
+ m_strMimeType = TQString::fromLatin1("video/x-ms-wmv");
+ }
+
+#if 0
+ // Even if we can't rely on content-length, it seems that we should
+ // never get more data than content-length. Maybe less, if the
+ // content-length refers to the unzipped data.
+ if (!m_qContentEncodings.isEmpty())
+ {
+ // If we still have content encoding we can't rely on the Content-Length.
+ m_iSize = NO_SIZE;
+ }
+#endif
+
+ if( !dispositionType.isEmpty() )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition type to: "
+ << dispositionType << endl;
+ setMetaData("content-disposition-type", dispositionType);
+ }
+ if( !dispositionFilename.isEmpty() )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Setting Content-Disposition filename to: "
+ << dispositionFilename << endl;
+ // ### KDE4: setting content-disposition to filename for pre 3.5.2 compatability
+ setMetaData("content-disposition", dispositionFilename);
+ setMetaData("content-disposition-filename", dispositionFilename);
+ }
+
+ if (!m_request.lastModified.isEmpty())
+ setMetaData("modified", m_request.lastModified);
+
+ if (!mayCache)
+ {
+ setMetaData("no-cache", "true");
+ setMetaData("expire-date", "1"); // Expired
+ }
+ else
+ {
+ TQString tmp;
+ tmp.setNum(expireDate);
+ setMetaData("expire-date", tmp);
+ tmp.setNum(time(0)); // Cache entry will be created shortly.
+ setMetaData("cache-creation-date", tmp);
+ }
+
+ // Let the app know about the mime-type iff this is not
+ // a redirection and the mime-type string is not empty.
+ if (locationStr.isEmpty() && (!m_strMimeType.isEmpty() ||
+ m_request.method == HTTP_HEAD))
+ {
+ kdDebug(7113) << "(" << m_pid << ") Emitting mimetype " << m_strMimeType << endl;
+ mimeType( m_strMimeType );
+ }
+
+ // Do not move send response header before any redirection as it seems
+ // to screw up some sites. See BR# 150904.
+ forwardHttpResponseHeader();
+
+ if (m_request.method == HTTP_HEAD)
+ return true;
+
+ // Do we want to cache this request?
+ if (m_request.bUseCache)
+ {
+ ::unlink( TQFile::encodeName(m_request.cef));
+ if ( m_request.bCachedWrite && !m_strMimeType.isEmpty() )
+ {
+ // Check...
+ createCacheEntry(m_strMimeType, expireDate); // Create a cache entry
+ if (!m_request.fcache)
+ {
+ m_request.bCachedWrite = false; // Error creating cache entry.
+ kdDebug(7113) << "(" << m_pid << ") Error creating cache entry for " << m_request.url.url()<<"!\n";
+ }
+ m_request.expireDate = expireDate;
+ m_maxCacheSize = config()->readNumEntry("MaxCacheSize", DEFAULT_MAX_CACHE_SIZE) / 2;
+ }
+ }
+
+ if (m_request.bCachedWrite && !m_strMimeType.isEmpty())
+ kdDebug(7113) << "(" << m_pid << ") Cache, adding \"" << m_request.url.url() << "\"" << endl;
+ else if (m_request.bCachedWrite && m_strMimeType.isEmpty())
+ kdDebug(7113) << "(" << m_pid << ") Cache, pending \"" << m_request.url.url() << "\"" << endl;
+ else
+ kdDebug(7113) << "(" << m_pid << ") Cache, not adding \"" << m_request.url.url() << "\"" << endl;
+ return true;
+}
+
+
+void HTTPProtocol::addEncoding(TQString encoding, TQStringList &encs)
+{
+ encoding = encoding.stripWhiteSpace().lower();
+ // Identity is the same as no encoding
+ if (encoding == "identity") {
+ return;
+ } else if (encoding == "8bit") {
+ // Strange encoding returned by http://linac.ikp.physik.tu-darmstadt.de
+ return;
+ } else if (encoding == "chunked") {
+ m_bChunked = true;
+ // Anyone know of a better way to handle unknown sizes possibly/ideally with unsigned ints?
+ //if ( m_cmd != CMD_COPY )
+ m_iSize = NO_SIZE;
+ } else if ((encoding == "x-gzip") || (encoding == "gzip")) {
+ encs.append(TQString::fromLatin1("gzip"));
+ } else if ((encoding == "x-bzip2") || (encoding == "bzip2")) {
+ encs.append(TQString::fromLatin1("bzip2")); // Not yet supported!
+ } else if ((encoding == "x-deflate") || (encoding == "deflate")) {
+ encs.append(TQString::fromLatin1("deflate"));
+ } else {
+ kdDebug(7113) << "(" << m_pid << ") Unknown encoding encountered. "
+ << "Please write code. Encoding = \"" << encoding
+ << "\"" << endl;
+ }
+}
+
+bool HTTPProtocol::sendBody()
+{
+ int result=-1;
+ int length=0;
+
+ infoMessage( i18n( "Requesting data to send" ) );
+
+ // m_bufPOST will NOT be empty iff authentication was required before posting
+ // the data OR a re-connect is requested from ::readHeader because the
+ // connection was lost for some reason.
+ if ( !m_bufPOST.isNull() )
+ {
+ kdDebug(7113) << "(" << m_pid << ") POST'ing saved data..." << endl;
+
+ result = 0;
+ length = m_bufPOST.size();
+ }
+ else
+ {
+ kdDebug(7113) << "(" << m_pid << ") POST'ing live data..." << endl;
+
+ TQByteArray buffer;
+ int old_size;
+
+ m_bufPOST.resize(0);
+ do
+ {
+ dataReq(); // Request for data
+ result = readData( buffer );
+ if ( result > 0 )
+ {
+ length += result;
+ old_size = m_bufPOST.size();
+ m_bufPOST.resize( old_size+result );
+ memcpy( m_bufPOST.data()+ old_size, buffer.data(), buffer.size() );
+ buffer.resize(0);
+ }
+ } while ( result > 0 );
+ }
+
+ if ( result < 0 )
+ {
+ error( ERR_ABORTED, m_request.hostname );
+ return false;
+ }
+
+ infoMessage( i18n( "Sending data to %1" ).arg( m_request.hostname ) );
+
+ TQString size = TQString ("Content-Length: %1\r\n\r\n").arg(length);
+ kdDebug( 7113 ) << "(" << m_pid << ")" << size << endl;
+
+ // Send the content length...
+ bool sendOk = (write(size.latin1(), size.length()) == (ssize_t) size.length());
+ if (!sendOk)
+ {
+ kdDebug( 7113 ) << "(" << m_pid << ") Connection broken when sending "
+ << "content length: (" << m_state.hostname << ")" << endl;
+ error( ERR_CONNECTION_BROKEN, m_state.hostname );
+ return false;
+ }
+
+ // Send the data...
+ // kdDebug( 7113 ) << "(" << m_pid << ") POST DATA: " << TQCString(m_bufPOST) << endl;
+ sendOk = (write(m_bufPOST.data(), m_bufPOST.size()) == (ssize_t) m_bufPOST.size());
+ if (!sendOk)
+ {
+ kdDebug(7113) << "(" << m_pid << ") Connection broken when sending message body: ("
+ << m_state.hostname << ")" << endl;
+ error( ERR_CONNECTION_BROKEN, m_state.hostname );
+ return false;
+ }
+
+ return true;
+}
+
+void HTTPProtocol::httpClose( bool keepAlive )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose" << endl;
+
+ if (m_request.fcache)
+ {
+ fclose(m_request.fcache);
+ m_request.fcache = 0;
+ if (m_request.bCachedWrite)
+ {
+ TQString filename = m_request.cef + ".new";
+ ::unlink( TQFile::encodeName(filename) );
+ }
+ }
+
+ // Only allow persistent connections for GET requests.
+ // NOTE: we might even want to narrow this down to non-form
+ // based submit requests which will require a meta-data from
+ // tdehtml.
+ if (keepAlive && (!m_bUseProxy ||
+ m_bPersistentProxyConnection || m_bIsTunneled))
+ {
+ if (!m_keepAliveTimeout)
+ m_keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
+ else if (m_keepAliveTimeout > 2*DEFAULT_KEEP_ALIVE_TIMEOUT)
+ m_keepAliveTimeout = 2*DEFAULT_KEEP_ALIVE_TIMEOUT;
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpClose: keep alive (" << m_keepAliveTimeout << ")" << endl;
+ TQByteArray data;
+ TQDataStream stream( data, IO_WriteOnly );
+ stream << int(99); // special: Close connection
+ setTimeoutSpecialCommand(m_keepAliveTimeout, data);
+ return;
+ }
+
+ httpCloseConnection();
+}
+
+void HTTPProtocol::closeConnection()
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::closeConnection" << endl;
+ httpCloseConnection ();
+}
+
+void HTTPProtocol::httpCloseConnection ()
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::httpCloseConnection" << endl;
+ m_bIsTunneled = false;
+ m_bKeepAlive = false;
+ closeDescriptor();
+ setTimeoutSpecialCommand(-1); // Cancel any connection timeout
+}
+
+void HTTPProtocol::slave_status()
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::slave_status" << endl;
+
+ if ( m_iSock != -1 && !isConnectionValid() )
+ httpCloseConnection();
+
+ slaveStatus( m_state.hostname, (m_iSock != -1) );
+}
+
+void HTTPProtocol::mimetype( const KURL& url )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::mimetype: "
+ << url.prettyURL() << endl;
+
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.method = HTTP_HEAD;
+ m_request.path = url.path();
+ m_request.query = url.query();
+ m_request.cache = CC_Cache;
+ m_request.doProxy = m_bUseProxy;
+
+ retrieveHeader();
+
+ kdDebug(7113) << "(" << m_pid << ") http: mimetype = " << m_strMimeType
+ << endl;
+}
+
+void HTTPProtocol::special( const TQByteArray &data )
+{
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::special" << endl;
+
+ int tmp;
+ TQDataStream stream(data, IO_ReadOnly);
+
+ stream >> tmp;
+ switch (tmp) {
+ case 1: // HTTP POST
+ {
+ KURL url;
+ stream >> url;
+ post( url );
+ break;
+ }
+ case 2: // cache_update
+ {
+ KURL url;
+ bool no_cache;
+ time_t expireDate;
+ stream >> url >> no_cache >> expireDate;
+ cacheUpdate( url, no_cache, expireDate );
+ break;
+ }
+ case 5: // WebDAV lock
+ {
+ KURL url;
+ TQString scope, type, owner;
+ stream >> url >> scope >> type >> owner;
+ davLock( url, scope, type, owner );
+ break;
+ }
+ case 6: // WebDAV unlock
+ {
+ KURL url;
+ stream >> url;
+ davUnlock( url );
+ break;
+ }
+ case 7: // Generic WebDAV
+ {
+ KURL url;
+ int method;
+ stream >> url >> method;
+ davGeneric( url, (TDEIO::HTTP_METHOD) method );
+ break;
+ }
+ case 99: // Close Connection
+ {
+ httpCloseConnection();
+ break;
+ }
+ default:
+ // Some command we don't understand.
+ // Just ignore it, it may come from some future version of KDE.
+ break;
+ }
+}
+
+/**
+ * Read a chunk from the data stream.
+ */
+int HTTPProtocol::readChunked()
+{
+ if ((m_iBytesLeft == 0) || (m_iBytesLeft == NO_SIZE))
+ {
+ setRewindMarker();
+
+ m_bufReceive.resize(4096);
+
+ if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
+ {
+ kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
+ return -1;
+ }
+ // We could have got the CRLF of the previous chunk.
+ // If so, try again.
+ if (m_bufReceive[0] == '\0')
+ {
+ if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
+ {
+ kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk header" << endl;
+ return -1;
+ }
+ }
+
+ // m_bEOF is set to true when read called from gets returns 0. For chunked reading 0
+ // means end of chunked transfer and not error. See RFC 2615 section 3.6.1
+ #if 0
+ if (m_bEOF)
+ {
+ kdDebug(7113) << "(" << m_pid << ") EOF on Chunk header" << endl;
+ return -1;
+ }
+ #endif
+
+ long long trunkSize = STRTOLL(m_bufReceive.data(), 0, 16);
+ if (trunkSize < 0)
+ {
+ kdDebug(7113) << "(" << m_pid << ") Negative chunk size" << endl;
+ return -1;
+ }
+ m_iBytesLeft = trunkSize;
+
+ // kdDebug(7113) << "(" << m_pid << ") Chunk size = " << m_iBytesLeft << " bytes" << endl;
+
+ if (m_iBytesLeft == 0)
+ {
+ // Last chunk.
+ // Skip trailers.
+ do {
+ // Skip trailer of last chunk.
+ if (!gets(m_bufReceive.data(), m_bufReceive.size()-1))
+ {
+ kdDebug(7113) << "(" << m_pid << ") gets() failure on Chunk trailer" << endl;
+ return -1;
+ }
+ // kdDebug(7113) << "(" << m_pid << ") Chunk trailer = \"" << m_bufReceive.data() << "\"" << endl;
+ }
+ while (strlen(m_bufReceive.data()) != 0);
+
+ return 0;
+ }
+ }
+
+ int bytesReceived = readLimited();
+ if (!m_iBytesLeft)
+ m_iBytesLeft = NO_SIZE; // Don't stop, continue with next chunk
+
+ // kdDebug(7113) << "(" << m_pid << ") readChunked: BytesReceived=" << bytesReceived << endl;
+ return bytesReceived;
+}
+
+int HTTPProtocol::readLimited()
+{
+ if (!m_iBytesLeft)
+ return 0;
+
+ m_bufReceive.resize(4096);
+
+ int bytesReceived;
+ int bytesToReceive;
+
+ if (m_iBytesLeft > m_bufReceive.size())
+ bytesToReceive = m_bufReceive.size();
+ else
+ bytesToReceive = m_iBytesLeft;
+
+ bytesReceived = read(m_bufReceive.data(), bytesToReceive);
+
+ if (bytesReceived <= 0)
+ return -1; // Error: connection lost
+
+ m_iBytesLeft -= bytesReceived;
+ return bytesReceived;
+}
+
+int HTTPProtocol::readUnlimited()
+{
+ if (m_bKeepAlive)
+ {
+ kdDebug(7113) << "(" << m_pid << ") Unbounded datastream on a Keep "
+ << "alive connection!" << endl;
+ m_bKeepAlive = false;
+ }
+
+ m_bufReceive.resize(4096);
+
+ int result = read(m_bufReceive.data(), m_bufReceive.size());
+ if (result > 0)
+ return result;
+
+ m_bEOF = true;
+ m_iBytesLeft = 0;
+ return 0;
+}
+
+void HTTPProtocol::slotData(const TQByteArray &_d)
+{
+ if (!_d.size())
+ {
+ m_bEOD = true;
+ return;
+ }
+
+ if (m_iContentLeft != NO_SIZE)
+ {
+ if (m_iContentLeft >= _d.size())
+ m_iContentLeft -= _d.size();
+ else
+ m_iContentLeft = NO_SIZE;
+ }
+
+ TQByteArray d = _d;
+ if ( !m_dataInternal )
+ {
+ // If a broken server does not send the mime-type,
+ // we try to id it from the content before dealing
+ // with the content itself.
+ if ( m_strMimeType.isEmpty() && !m_bRedirect &&
+ !( m_responseCode >= 300 && m_responseCode <=399) )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Determining mime-type from content..." << endl;
+ int old_size = m_mimeTypeBuffer.size();
+ m_mimeTypeBuffer.resize( old_size + d.size() );
+ memcpy( m_mimeTypeBuffer.data() + old_size, d.data(), d.size() );
+ if ( (m_iBytesLeft != NO_SIZE) && (m_iBytesLeft > 0)
+ && (m_mimeTypeBuffer.size() < 1024) )
+ {
+ m_cpMimeBuffer = true;
+ return; // Do not send up the data since we do not yet know its mimetype!
+ }
+
+ kdDebug(7113) << "(" << m_pid << ") Mimetype buffer size: " << m_mimeTypeBuffer.size()
+ << endl;
+
+ KMimeMagicResult *result;
+ result = KMimeMagic::self()->findBufferFileType( m_mimeTypeBuffer,
+ m_request.url.fileName() );
+ if( result )
+ {
+ m_strMimeType = result->mimeType();
+ kdDebug(7113) << "(" << m_pid << ") Mimetype from content: "
+ << m_strMimeType << endl;
+ }
+
+ if ( m_strMimeType.isEmpty() )
+ {
+ m_strMimeType = TQString::fromLatin1( DEFAULT_MIME_TYPE );
+ kdDebug(7113) << "(" << m_pid << ") Using default mimetype: "
+ << m_strMimeType << endl;
+ }
+
+ if ( m_request.bCachedWrite )
+ {
+ createCacheEntry( m_strMimeType, m_request.expireDate );
+ if (!m_request.fcache)
+ m_request.bCachedWrite = false;
+ }
+
+ if ( m_cpMimeBuffer )
+ {
+ // Do not make any assumption about the state of the TQByteArray we received.
+ // Fix the crash described by BR# 130104.
+ d.detach();
+ d.resize(0);
+ d.resize(m_mimeTypeBuffer.size());
+ memcpy( d.data(), m_mimeTypeBuffer.data(),
+ d.size() );
+ }
+ mimeType(m_strMimeType);
+ m_mimeTypeBuffer.resize(0);
+ }
+
+ data( d );
+ if (m_request.bCachedWrite && m_request.fcache)
+ writeCacheEntry(d.data(), d.size());
+ }
+ else
+ {
+ uint old_size = m_bufWebDavData.size();
+ m_bufWebDavData.resize (old_size + d.size());
+ memcpy (m_bufWebDavData.data() + old_size, d.data(), d.size());
+ }
+}
+
+/**
+ * This function is our "receive" function. It is responsible for
+ * downloading the message (not the header) from the HTTP server. It
+ * is called either as a response to a client's TDEIOJob::dataEnd()
+ * (meaning that the client is done sending data) or by 'httpOpen()'
+ * (if we are in the process of a PUT/POST request). It can also be
+ * called by a webDAV function, to receive stat/list/property/etc.
+ * data; in this case the data is stored in m_bufWebDavData.
+ */
+bool HTTPProtocol::readBody( bool dataInternal /* = false */ )
+{
+ if (m_responseCode == 204)
+ return true;
+
+ m_bEOD = false;
+ // Note that when dataInternal is true, we are going to:
+ // 1) save the body data to a member variable, m_bufWebDavData
+ // 2) _not_ advertise the data, speed, size, etc., through the
+ // corresponding functions.
+ // This is used for returning data to WebDAV.
+ m_dataInternal = dataInternal;
+ if ( dataInternal )
+ m_bufWebDavData.resize (0);
+
+ // Check if we need to decode the data.
+ // If we are in copy mode, then use only transfer decoding.
+ bool useMD5 = !m_sContentMD5.isEmpty();
+
+ // Deal with the size of the file.
+ TDEIO::filesize_t sz = m_request.offset;
+ if ( sz )
+ m_iSize += sz;
+
+ // Update the application with total size except when
+ // it is compressed, or when the data is to be handled
+ // internally (webDAV). If compressed we have to wait
+ // until we uncompress to find out the actual data size
+ if ( !dataInternal ) {
+ if ( (m_iSize > 0) && (m_iSize != NO_SIZE)) {
+ totalSize(m_iSize);
+ infoMessage( i18n( "Retrieving %1 from %2...").arg(TDEIO::convertSize(m_iSize))
+ .arg( m_request.hostname ) );
+ }
+ else
+ {
+ totalSize ( 0 );
+ }
+ }
+ else
+ infoMessage( i18n( "Retrieving from %1..." ).arg( m_request.hostname ) );
+
+ if (m_request.bCachedRead)
+ {
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: read data from cache!" << endl;
+ m_request.bCachedWrite = false;
+
+ char buffer[ MAX_IPC_SIZE ];
+
+ m_iContentLeft = NO_SIZE;
+
+ // Jippie! It's already in the cache :-)
+ while (!feof(m_request.fcache) && !ferror(m_request.fcache))
+ {
+ int nbytes = fread( buffer, 1, MAX_IPC_SIZE, m_request.fcache);
+
+ if (nbytes > 0)
+ {
+ m_bufReceive.setRawData( buffer, nbytes);
+ slotData( m_bufReceive );
+ m_bufReceive.resetRawData( buffer, nbytes );
+ sz += nbytes;
+ }
+ }
+
+ m_bufReceive.resize( 0 );
+
+ if ( !dataInternal )
+ {
+ processedSize( sz );
+ data( TQByteArray() );
+ }
+
+ return true;
+ }
+
+
+ if (m_iSize != NO_SIZE)
+ m_iBytesLeft = m_iSize - sz;
+ else
+ m_iBytesLeft = NO_SIZE;
+
+ m_iContentLeft = m_iBytesLeft;
+
+ if (m_bChunked)
+ m_iBytesLeft = NO_SIZE;
+
+ kdDebug(7113) << "(" << m_pid << ") HTTPProtocol::readBody: retrieve data. "
+ << TDEIO::number(m_iBytesLeft) << " left." << endl;
+
+ // Main incoming loop... Gather everything while we can...
+ m_cpMimeBuffer = false;
+ m_mimeTypeBuffer.resize(0);
+ struct timeval last_tv;
+ gettimeofday( &last_tv, 0L );
+
+ HTTPFilterChain chain;
+
+ TQObject::connect(&chain, TQT_SIGNAL(output(const TQByteArray &)),
+ this, TQT_SLOT(slotData(const TQByteArray &)));
+ TQObject::connect(&chain, TQT_SIGNAL(error(int, const TQString &)),
+ this, TQT_SLOT(error(int, const TQString &)));
+
+ // decode all of the transfer encodings
+ while (!m_qTransferEncodings.isEmpty())
+ {
+ TQString enc = m_qTransferEncodings.last();
+ m_qTransferEncodings.remove(m_qTransferEncodings.fromLast());
+ if ( enc == "gzip" )
+ chain.addFilter(new HTTPFilterGZip);
+ else if ( enc == "deflate" )
+ chain.addFilter(new HTTPFilterDeflate);
+ }
+
+ // From HTTP 1.1 Draft 6:
+ // The MD5 digest is computed based on the content of the entity-body,
+ // including any content-coding that has been applied, but not including
+ // any transfer-encoding applied to the message-body. If the message is
+ // received with a transfer-encoding, that encoding MUST be removed
+ // prior to checking the Content-MD5 value against the received entity.
+ HTTPFilterMD5 *md5Filter = 0;
+ if ( useMD5 )
+ {
+ md5Filter = new HTTPFilterMD5;
+ chain.addFilter(md5Filter);
+ }
+
+ // now decode all of the content encodings
+ // -- Why ?? We are not
+ // -- a proxy server, be a client side implementation!! The applications
+ // -- are capable of determinig how to extract the encoded implementation.
+ // WB: That's a misunderstanding. We are free to remove the encoding.
+ // WB: Some braindead www-servers however, give .tgz files an encoding
+ // WB: of "gzip" (or even "x-gzip") and a content-type of "applications/tar"
+ // WB: They shouldn't do that. We can work around that though...
+ while (!m_qContentEncodings.isEmpty())
+ {
+ TQString enc = m_qContentEncodings.last();
+ m_qContentEncodings.remove(m_qContentEncodings.fromLast());
+ if ( enc == "gzip" )
+ chain.addFilter(new HTTPFilterGZip);
+ else if ( enc == "deflate" )
+ chain.addFilter(new HTTPFilterDeflate);
+ }
+
+ while (!m_bEOF)
+ {
+ int bytesReceived;
+
+ if (m_bChunked)
+ bytesReceived = readChunked();
+ else if (m_iSize != NO_SIZE)
+ bytesReceived = readLimited();
+ else
+ bytesReceived = readUnlimited();
+
+ // make sure that this wasn't an error, first
+ // kdDebug(7113) << "(" << (int) m_pid << ") readBody: bytesReceived: "
+ // << (int) bytesReceived << " m_iSize: " << (int) m_iSize << " Chunked: "
+ // << (int) m_bChunked << " BytesLeft: "<< (int) m_iBytesLeft << endl;
+ if (bytesReceived == -1)
+ {
+ if (m_iContentLeft == 0)
+ {
+ // gzip'ed data sometimes reports a too long content-length.
+ // (The length of the unzipped data)
+ m_iBytesLeft = 0;
+ break;
+ }
+ // Oh well... log an error and bug out
+ kdDebug(7113) << "(" << m_pid << ") readBody: bytesReceived==-1 sz=" << (int)sz
+ << " Connnection broken !" << endl;
+ error(ERR_CONNECTION_BROKEN, m_state.hostname);
+ return false;
+ }
+
+ // I guess that nbytes == 0 isn't an error.. but we certainly
+ // won't work with it!
+ if (bytesReceived > 0)
+ {
+ // Important: truncate the buffer to the actual size received!
+ // Otherwise garbage will be passed to the app
+ m_bufReceive.truncate( bytesReceived );
+
+ chain.slotInput(m_bufReceive);
+
+ if (m_bError)
+ return false;
+
+ sz += bytesReceived;
+ if (!dataInternal)
+ processedSize( sz );
+ }
+ m_bufReceive.resize(0); // res
+
+ if (m_iBytesLeft && m_bEOD && !m_bChunked)
+ {
+ // gzip'ed data sometimes reports a too long content-length.
+ // (The length of the unzipped data)
+ m_iBytesLeft = 0;
+ }
+
+ if (m_iBytesLeft == 0)
+ {
+ kdDebug(7113) << "("<<m_pid<<") EOD received! Left = "<< TDEIO::number(m_iBytesLeft) << endl;
+ break;
+ }
+ }
+ chain.slotInput(TQByteArray()); // Flush chain.
+
+ if ( useMD5 )
+ {
+ TQString calculatedMD5 = md5Filter->md5();
+
+ if ( m_sContentMD5 == calculatedMD5 )
+ kdDebug(7113) << "(" << m_pid << ") MD5 checksum MATCHED!!" << endl;
+ else
+ kdDebug(7113) << "(" << m_pid << ") MD5 checksum MISMATCH! Expected: "
+ << calculatedMD5 << ", Got: " << m_sContentMD5 << endl;
+ }
+
+ // Close cache entry
+ if (m_iBytesLeft == 0)
+ {
+ if (m_request.bCachedWrite && m_request.fcache)
+ closeCacheEntry();
+ else if (m_request.bCachedWrite)
+ kdDebug(7113) << "(" << m_pid << ") no cache file!\n";
+ }
+ else
+ {
+ kdDebug(7113) << "(" << m_pid << ") still "<< TDEIO::number(m_iBytesLeft)
+ << " bytes left! can't close cache entry!\n";
+ }
+
+ if (sz <= 1)
+ {
+ /* kdDebug(7113) << "(" << m_pid << ") readBody: sz = " << TDEIO::number(sz)
+ << ", responseCode =" << m_responseCode << endl; */
+ if (m_responseCode >= 500 && m_responseCode <= 599)
+ error(ERR_INTERNAL_SERVER, m_state.hostname);
+ else if (m_responseCode >= 400 && m_responseCode <= 499)
+ error(ERR_DOES_NOT_EXIST, m_state.hostname);
+ }
+
+ if (!dataInternal)
+ data( TQByteArray() );
+
+ return true;
+}
+
+
+void HTTPProtocol::error( int _err, const TQString &_text )
+{
+ httpClose(false);
+
+ if (!m_request.id.isEmpty())
+ {
+ forwardHttpResponseHeader();
+ sendMetaData();
+ }
+
+ // Clear of the temporary POST buffer if it is not empty...
+ if (!m_bufPOST.isEmpty())
+ {
+ m_bufPOST.resize(0);
+ kdDebug(7113) << "(" << m_pid << ") HTTP::retreiveHeader: Cleared POST "
+ "buffer..." << endl;
+ }
+
+ SlaveBase::error( _err, _text );
+ m_bError = true;
+}
+
+
+void HTTPProtocol::addCookies( const TQString &url, const TQCString &cookieHeader )
+{
+ long windowId = m_request.window.toLong();
+ TQByteArray params;
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << url << cookieHeader << windowId;
+
+ kdDebug(7113) << "(" << m_pid << ") " << cookieHeader << endl;
+ kdDebug(7113) << "(" << m_pid << ") " << "Window ID: "
+ << windowId << ", for host = " << url << endl;
+
+ if ( !dcopClient()->send( "kded", "kcookiejar", "addCookies(TQString,TQCString,long int)", params ) )
+ {
+ kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
+ }
+}
+
+TQString HTTPProtocol::findCookies( const TQString &url)
+{
+ TQCString replyType;
+ TQByteArray params;
+ TQByteArray reply;
+ TQString result;
+
+ long windowId = m_request.window.toLong();
+ result = TQString::null;
+ TQDataStream stream(params, IO_WriteOnly);
+ stream << url << windowId;
+
+ if ( !dcopClient()->call( "kded", "kcookiejar", "findCookies(TQString,long int)",
+ params, replyType, reply ) )
+ {
+ kdWarning(7113) << "(" << m_pid << ") Can't communicate with kded_kcookiejar!" << endl;
+ return result;
+ }
+ if ( replyType == "TQString" )
+ {
+ TQDataStream stream2( reply, IO_ReadOnly );
+ stream2 >> result;
+ }
+ else
+ {
+ kdError(7113) << "(" << m_pid << ") DCOP function findCookies(...) returns "
+ << replyType << ", expected TQString" << endl;
+ }
+ return result;
+}
+
+/******************************* CACHING CODE ****************************/
+
+
+void HTTPProtocol::cacheUpdate( const KURL& url, bool no_cache, time_t expireDate)
+{
+ if ( !checkRequestURL( url ) )
+ return;
+
+ m_request.path = url.path();
+ m_request.query = url.query();
+ m_request.cache = CC_Reload;
+ m_request.doProxy = m_bUseProxy;
+
+ if (no_cache)
+ {
+ m_request.fcache = checkCacheEntry( );
+ if (m_request.fcache)
+ {
+ fclose(m_request.fcache);
+ m_request.fcache = 0;
+ ::unlink( TQFile::encodeName(m_request.cef) );
+ }
+ }
+ else
+ {
+ updateExpireDate( expireDate );
+ }
+ finished();
+}
+
+// !START SYNC!
+// The following code should be kept in sync
+// with the code in http_cache_cleaner.cpp
+
+FILE* HTTPProtocol::checkCacheEntry( bool readWrite)
+{
+ const TQChar separator = '_';
+
+ TQString CEF = m_request.path;
+
+ int p = CEF.find('/');
+
+ while(p != -1)
+ {
+ CEF[p] = separator;
+ p = CEF.find('/', p);
+ }
+
+ TQString host = m_request.hostname.lower();
+ CEF = host + CEF + '_';
+
+ TQString dir = m_strCacheDir;
+ if (dir[dir.length()-1] != '/')
+ dir += "/";
+
+ int l = host.length();
+ for(int i = 0; i < l; i++)
+ {
+ if (host[i].isLetter() && (host[i] != 'w'))
+ {
+ dir += host[i];
+ break;
+ }
+ }
+ if (dir[dir.length()-1] == '/')
+ dir += "0";
+
+ unsigned long hash = 0x00000000;
+ TQCString u = m_request.url.url().latin1();
+ for(int i = u.length(); i--;)
+ {
+ hash = (hash * 12211 + static_cast<const char>(u.at(i))) % 2147483563;
+ }
+
+ TQString hashString;
+ hashString.sprintf("%08lx", hash);
+
+ CEF = CEF + hashString;
+
+ CEF = dir + "/" + CEF;
+
+ m_request.cef = CEF;
+
+ const char *mode = (readWrite ? "r+" : "r");
+
+ FILE *fs = fopen( TQFile::encodeName(CEF), mode); // Open for reading and writing
+ if (!fs)
+ return 0;
+
+ char buffer[401];
+ bool ok = true;
+
+ // CacheRevision
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok && (strcmp(buffer, CACHE_REVISION) != 0))
+ ok = false;
+
+ time_t date;
+ time_t currentDate = time(0);
+
+ // URL
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ int l = strlen(buffer);
+ if (l>0)
+ buffer[l-1] = 0; // Strip newline
+ if (m_request.url.url() != buffer)
+ {
+ ok = false; // Hash collision
+ }
+ }
+
+ // Creation Date
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ date = (time_t) strtoul(buffer, 0, 10);
+ m_request.creationDate = date;
+ if (m_maxCacheAge && (difftime(currentDate, date) > m_maxCacheAge))
+ {
+ m_request.bMustRevalidate = true;
+ m_request.expireDate = currentDate;
+ }
+ }
+
+ // Expiration Date
+ m_request.cacheExpireDateOffset = ftell(fs);
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ if (m_request.cache == CC_Verify)
+ {
+ date = (time_t) strtoul(buffer, 0, 10);
+ // After the expire date we need to revalidate.
+ if (!date || difftime(currentDate, date) >= 0)
+ m_request.bMustRevalidate = true;
+ m_request.expireDate = date;
+ }
+ else if (m_request.cache == CC_Refresh)
+ {
+ m_request.bMustRevalidate = true;
+ m_request.expireDate = currentDate;
+ }
+ }
+
+ // ETag
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ m_request.etag = TQString(buffer).stripWhiteSpace();
+ }
+
+ // Last-Modified
+ if (ok && (!fgets(buffer, 400, fs)))
+ ok = false;
+ if (ok)
+ {
+ m_request.lastModified = TQString(buffer).stripWhiteSpace();
+ }
+
+ if (ok)
+ return fs;
+
+ fclose(fs);
+ unlink( TQFile::encodeName(CEF));
+ return 0;
+}
+
+void HTTPProtocol::updateExpireDate(time_t expireDate, bool updateCreationDate)
+{
+ bool ok = true;
+
+ FILE *fs = checkCacheEntry(true);
+ if (fs)
+ {
+ TQString date;
+ char buffer[401];
+ time_t creationDate;
+
+ fseek(fs, 0, SEEK_SET);
+ if (ok && !fgets(buffer, 400, fs))
+ ok = false;
+ if (ok && !fgets(buffer, 400, fs))
+ ok = false;
+ long cacheCreationDateOffset = ftell(fs);
+ if (ok && !fgets(buffer, 400, fs))
+ ok = false;
+ creationDate = strtoul(buffer, 0, 10);
+ if (!creationDate)
+ ok = false;
+
+ if (updateCreationDate)
+ {
+ if (!ok || fseek(fs, cacheCreationDateOffset, SEEK_SET))
+ return;
+ TQString date;
+ date.setNum( time(0) );
+ date = date.leftJustify(16);
+ fputs(date.latin1(), fs); // Creation date
+ fputc('\n', fs);
+ }
+
+ if (expireDate>(30*365*24*60*60))
+ {
+ // expire date is a really a big number, it can't be
+ // a relative date.
+ date.setNum( expireDate );
+ }
+ else
+ {
+ // expireDate before 2000. those values must be
+ // interpreted as relative expiration dates from
+ // <META http-equiv="Expires"> tags.
+ // so we have to scan the creation time and add
+ // it to the expiryDate
+ date.setNum( creationDate + expireDate );
+ }
+ date = date.leftJustify(16);
+ if (!ok || fseek(fs, m_request.cacheExpireDateOffset, SEEK_SET))
+ return;
+ fputs(date.latin1(), fs); // Expire date
+ fseek(fs, 0, SEEK_END);
+ fclose(fs);
+ }
+}
+
+void HTTPProtocol::createCacheEntry( const TQString &mimetype, time_t expireDate)
+{
+ TQString dir = m_request.cef;
+ int p = dir.findRev('/');
+ if (p == -1) return; // Error.
+ dir.truncate(p);
+
+ // Create file
+ (void) ::mkdir( TQFile::encodeName(dir), 0700 );
+
+ TQString filename = m_request.cef + ".new"; // Create a new cache entryexpireDate
+
+// kdDebug( 7103 ) << "creating new cache entry: " << filename << endl;
+
+ m_request.fcache = fopen( TQFile::encodeName(filename), "w");
+ if (!m_request.fcache)
+ {
+ kdWarning(7113) << "(" << m_pid << ")createCacheEntry: opening " << filename << " failed." << endl;
+ return; // Error.
+ }
+
+ fputs(CACHE_REVISION, m_request.fcache); // Revision
+
+ fputs(m_request.url.url().latin1(), m_request.fcache); // Url
+ fputc('\n', m_request.fcache);
+
+ TQString date;
+ m_request.creationDate = time(0);
+ date.setNum( m_request.creationDate );
+ date = date.leftJustify(16);
+ fputs(date.latin1(), m_request.fcache); // Creation date
+ fputc('\n', m_request.fcache);
+
+ date.setNum( expireDate );
+ date = date.leftJustify(16);
+ fputs(date.latin1(), m_request.fcache); // Expire date
+ fputc('\n', m_request.fcache);
+
+ if (!m_request.etag.isEmpty())
+ fputs(m_request.etag.latin1(), m_request.fcache); //ETag
+ fputc('\n', m_request.fcache);
+
+ if (!m_request.lastModified.isEmpty())
+ fputs(m_request.lastModified.latin1(), m_request.fcache); // Last modified
+ fputc('\n', m_request.fcache);
+
+ fputs(mimetype.latin1(), m_request.fcache); // Mimetype
+ fputc('\n', m_request.fcache);
+
+ if (!m_request.strCharset.isEmpty())
+ fputs(m_request.strCharset.latin1(), m_request.fcache); // Charset
+ fputc('\n', m_request.fcache);
+
+ return;
+}
+// The above code should be kept in sync
+// with the code in http_cache_cleaner.cpp
+// !END SYNC!
+
+void HTTPProtocol::writeCacheEntry( const char *buffer, int nbytes)
+{
+ if (fwrite( buffer, nbytes, 1, m_request.fcache) != 1)
+ {
+ kdWarning(7113) << "(" << m_pid << ") writeCacheEntry: writing " << nbytes << " bytes failed." << endl;
+ fclose(m_request.fcache);
+ m_request.fcache = 0;
+ TQString filename = m_request.cef + ".new";
+ ::unlink( TQFile::encodeName(filename) );
+ return;
+ }
+ long file_pos = ftell( m_request.fcache ) / 1024;
+ if ( file_pos > m_maxCacheSize )
+ {
+ kdDebug(7113) << "writeCacheEntry: File size reaches " << file_pos
+ << "Kb, exceeds cache limits. (" << m_maxCacheSize << "Kb)" << endl;
+ fclose(m_request.fcache);
+ m_request.fcache = 0;
+ TQString filename = m_request.cef + ".new";
+ ::unlink( TQFile::encodeName(filename) );
+ return;
+ }
+}
+
+void HTTPProtocol::closeCacheEntry()
+{
+ TQString filename = m_request.cef + ".new";
+ int result = fclose( m_request.fcache);
+ m_request.fcache = 0;
+ if (result == 0)
+ {
+ if (::rename( TQFile::encodeName(filename), TQFile::encodeName(m_request.cef)) == 0)
+ return; // Success
+
+ kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error renaming "
+ << "cache entry. (" << filename << " -> " << m_request.cef
+ << ")" << endl;
+ }
+
+ kdWarning(7113) << "(" << m_pid << ") closeCacheEntry: error closing cache "
+ << "entry. (" << filename<< ")" << endl;
+}
+
+void HTTPProtocol::cleanCache()
+{
+ const time_t maxAge = DEFAULT_CLEAN_CACHE_INTERVAL; // 30 Minutes.
+ bool doClean = false;
+ TQString cleanFile = m_strCacheDir;
+ if (cleanFile[cleanFile.length()-1] != '/')
+ cleanFile += "/";
+ cleanFile += "cleaned";
+
+ struct stat stat_buf;
+
+ int result = ::stat(TQFile::encodeName(cleanFile), &stat_buf);
+ if (result == -1)
+ {
+ int fd = creat( TQFile::encodeName(cleanFile), 0600);
+ if (fd != -1)
+ {
+ doClean = true;
+ ::close(fd);
+ }
+ }
+ else
+ {
+ time_t age = (time_t) difftime( time(0), stat_buf.st_mtime );
+ if (age > maxAge) //
+ doClean = true;
+ }
+ if (doClean)
+ {
+ // Touch file.
+ utime(TQFile::encodeName(cleanFile), 0);
+ TDEApplication::startServiceByDesktopPath("http_cache_cleaner.desktop");
+ }
+}
+
+
+
+//************************** AUTHENTICATION CODE ********************/
+
+
+void HTTPProtocol::configAuth( char *p, bool isForProxy )
+{
+ HTTP_AUTH f = AUTH_None;
+ const char *strAuth = p;
+
+ if ( strncasecmp( p, "Basic", 5 ) == 0 )
+ {
+ f = AUTH_Basic;
+ p += 5;
+ strAuth = "Basic"; // Correct for upper-case variations.
+ }
+ else if ( strncasecmp (p, "Digest", 6) == 0 )
+ {
+ f = AUTH_Digest;
+ memcpy((void *)p, "Digest", 6); // Correct for upper-case variations.
+ p += 6;
+ }
+ else if (strncasecmp( p, "MBS_PWD_COOKIE", 14 ) == 0)
+ {
+ // Found on http://www.webscription.net/baen/default.asp
+ f = AUTH_Basic;
+ p += 14;
+ strAuth = "Basic";
+ }
+#ifdef HAVE_LIBGSSAPI
+ else if ( strncasecmp( p, "Negotiate", 9 ) == 0 )
+ {
+ // if we get two 401 in a row let's assume for now that
+ // Negotiate isn't working and ignore it
+ if ( !isForProxy && !(m_responseCode == 401 && m_prevResponseCode == 401) )
+ {
+ f = AUTH_Negotiate;
+ memcpy((void *)p, "Negotiate", 9); // Correct for upper-case variations.
+ p += 9;
+ };
+ }
+#endif
+ else if ( strncasecmp( p, "NTLM", 4 ) == 0 )
+ {
+ f = AUTH_NTLM;
+ memcpy((void *)p, "NTLM", 4); // Correct for upper-case variations.
+ p += 4;
+ m_strRealm = "NTLM"; // set a dummy realm
+ }
+ else
+ {
+ kdWarning(7113) << "(" << m_pid << ") Unsupported or invalid authorization "
+ << "type requested" << endl;
+ if (isForProxy)
+ kdWarning(7113) << "(" << m_pid << ") Proxy URL: " << m_proxyURL << endl;
+ else
+ kdWarning(7113) << "(" << m_pid << ") URL: " << m_request.url << endl;
+ kdWarning(7113) << "(" << m_pid << ") Request Authorization: " << p << endl;
+ }
+
+ /*
+ This check ensures the following:
+ 1.) Rejection of any unknown/unsupported authentication schemes
+ 2.) Usage of the strongest possible authentication schemes if
+ and when multiple Proxy-Authenticate or WWW-Authenticate
+ header field is sent.
+ */
+ if (isForProxy)
+ {
+ if ((f == AUTH_None) ||
+ ((m_iProxyAuthCount > 0) && (f < ProxyAuthentication)))
+ {
+ // Since I purposefully made the Proxy-Authentication settings
+ // persistent to reduce the number of round-trips to tdesud we
+ // have to take special care when an unknown/unsupported auth-
+ // scheme is received. This check accomplishes just that...
+ if ( m_iProxyAuthCount == 0)
+ ProxyAuthentication = f;
+ kdDebug(7113) << "(" << m_pid << ") Rejected proxy auth method: " << f << endl;
+ return;
+ }
+ m_iProxyAuthCount++;
+ kdDebug(7113) << "(" << m_pid << ") Accepted proxy auth method: " << f << endl;
+ }
+ else
+ {
+ if ((f == AUTH_None) ||
+ ((m_iWWWAuthCount > 0) && (f < Authentication)))
+ {
+ kdDebug(7113) << "(" << m_pid << ") Rejected auth method: " << f << endl;
+ return;
+ }
+ m_iWWWAuthCount++;
+ kdDebug(7113) << "(" << m_pid << ") Accepted auth method: " << f << endl;
+ }
+
+
+ while (*p)
+ {
+ int i = 0;
+ while( (*p == ' ') || (*p == ',') || (*p == '\t') ) { p++; }
+ if ( strncasecmp( p, "realm=", 6 ) == 0 )
+ {
+ //for sites like lib.homelinux.org
+ TQTextCodec* oldCodec=TQTextCodec::codecForCStrings();
+ if (TDEGlobal::locale()->language().contains("ru"))
+ TQTextCodec::setCodecForCStrings(TQTextCodec::codecForName("CP1251"));
+
+ p += 6;
+ if (*p == '"') p++;
+ while( p[i] && p[i] != '"' ) i++;
+ if( isForProxy )
+ m_strProxyRealm = TQString::fromAscii( p, i );
+ else
+ m_strRealm = TQString::fromAscii( p, i );
+
+ TQTextCodec::setCodecForCStrings(oldCodec);
+
+ if (!p[i]) break;
+ }
+ p+=(i+1);
+ }
+
+ if( isForProxy )
+ {
+ ProxyAuthentication = f;
+ m_strProxyAuthorization = TQString::fromLatin1( strAuth );
+ }
+ else
+ {
+ Authentication = f;
+ m_strAuthorization = TQString::fromLatin1( strAuth );
+ }
+}
+
+
+bool HTTPProtocol::retryPrompt()
+{
+ TQString prompt;
+ switch ( m_responseCode )
+ {
+ case 401:
+ prompt = i18n("Authentication Failed.");
+ break;
+ case 407:
+ prompt = i18n("Proxy Authentication Failed.");
+ break;
+ default:
+ break;
+ }
+ prompt += i18n(" Do you want to retry?");
+ return (messageBox(QuestionYesNo, prompt, i18n("Authentication")) == 3);
+}
+
+void HTTPProtocol::promptInfo( AuthInfo& info )
+{
+ if ( m_responseCode == 401 )
+ {
+ info.url = m_request.url;
+ if ( !m_state.user.isEmpty() )
+ info.username = m_state.user;
+ info.readOnly = !m_request.url.user().isEmpty();
+ info.prompt = i18n( "You need to supply a username and a "
+ "password to access this site." );
+ info.keepPassword = true; // Prompt the user for persistence as well.
+ if ( !m_strRealm.isEmpty() )
+ {
+ info.realmValue = m_strRealm;
+ info.verifyPath = false;
+ info.digestInfo = m_strAuthorization;
+ info.commentLabel = i18n( "Site:" );
+ info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( m_strRealm ).arg( m_request.hostname );
+ }
+ }
+ else if ( m_responseCode == 407 )
+ {
+ info.url = m_proxyURL;
+ info.username = m_proxyURL.user();
+ info.prompt = i18n( "You need to supply a username and a password for "
+ "the proxy server listed below before you are allowed "
+ "to access any sites." );
+ info.keepPassword = true;
+ if ( !m_strProxyRealm.isEmpty() )
+ {
+ info.realmValue = m_strProxyRealm;
+ info.verifyPath = false;
+ info.digestInfo = m_strProxyAuthorization;
+ info.commentLabel = i18n( "Proxy:" );
+ info.comment = i18n("<b>%1</b> at <b>%2</b>").arg( m_strProxyRealm ).arg( m_proxyURL.host() );
+ }
+ }
+}
+
+bool HTTPProtocol::getAuthorization()
+{
+ AuthInfo info;
+ bool result = false;
+
+ kdDebug (7113) << "(" << m_pid << ") HTTPProtocol::getAuthorization: "
+ << "Current Response: " << m_responseCode << ", "
+ << "Previous Response: " << m_prevResponseCode << ", "
+ << "Authentication: " << Authentication << ", "
+ << "ProxyAuthentication: " << ProxyAuthentication << endl;
+
+ if (m_request.bNoAuth)
+ {
+ if (m_request.bErrorPage)
+ errorPage();
+ else
+ error( ERR_COULD_NOT_LOGIN, i18n("Authentication needed for %1 but authentication is disabled.").arg(m_request.hostname));
+ return false;
+ }
+
+ bool repeatFailure = (m_prevResponseCode == m_responseCode);
+
+ TQString errorMsg;
+
+ if (repeatFailure)
+ {
+ bool prompt = true;
+ if ( Authentication == AUTH_Digest || ProxyAuthentication == AUTH_Digest )
+ {
+ bool isStaleNonce = false;
+ TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
+ int pos = auth.find("stale", 0, false);
+ if ( pos != -1 )
+ {
+ pos += 5;
+ int len = auth.length();
+ while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
+ if ( pos < len && auth.find("true", pos, false) != -1 )
+ {
+ isStaleNonce = true;
+ kdDebug(7113) << "(" << m_pid << ") Stale nonce value. "
+ << "Will retry using same info..." << endl;
+ }
+ }
+ if ( isStaleNonce )
+ {
+ prompt = false;
+ result = true;
+ if ( m_responseCode == 401 )
+ {
+ info.username = m_request.user;
+ info.password = m_request.passwd;
+ info.realmValue = m_strRealm;
+ info.digestInfo = m_strAuthorization;
+ }
+ else if ( m_responseCode == 407 )
+ {
+ info.username = m_proxyURL.user();
+ info.password = m_proxyURL.pass();
+ info.realmValue = m_strProxyRealm;
+ info.digestInfo = m_strProxyAuthorization;
+ }
+ }
+ }
+
+ if ( Authentication == AUTH_NTLM || ProxyAuthentication == AUTH_NTLM )
+ {
+ TQString auth = ( m_responseCode == 401 ) ? m_strAuthorization : m_strProxyAuthorization;
+ kdDebug(7113) << "auth: " << auth << endl;
+ if ( auth.length() > 4 )
+ {
+ prompt = false;
+ result = true;
+ kdDebug(7113) << "(" << m_pid << ") NTLM auth second phase, "
+ << "sending response..." << endl;
+ if ( m_responseCode == 401 )
+ {
+ info.username = m_request.user;
+ info.password = m_request.passwd;
+ info.realmValue = m_strRealm;
+ info.digestInfo = m_strAuthorization;
+ }
+ else if ( m_responseCode == 407 )
+ {
+ info.username = m_proxyURL.user();
+ info.password = m_proxyURL.pass();
+ info.realmValue = m_strProxyRealm;
+ info.digestInfo = m_strProxyAuthorization;
+ }
+ }
+ }
+
+ if ( prompt )
+ {
+ switch ( m_responseCode )
+ {
+ case 401:
+ errorMsg = i18n("Authentication Failed.");
+ break;
+ case 407:
+ errorMsg = i18n("Proxy Authentication Failed.");
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ else
+ {
+ // At this point we know more details, so use it to find
+ // out if we have a cached version and avoid a re-prompt!
+ // We also do not use verify path unlike the pre-emptive
+ // requests because we already know the realm value...
+
+ if (m_bProxyAuthValid)
+ {
+ // Reset cached proxy auth
+ m_bProxyAuthValid = false;
+ KURL proxy ( config()->readEntry("UseProxy") );
+ m_proxyURL.setUser(proxy.user());
+ m_proxyURL.setPass(proxy.pass());
+ }
+
+ info.verifyPath = false;
+ if ( m_responseCode == 407 )
+ {
+ info.url = m_proxyURL;
+ info.username = m_proxyURL.user();
+ info.password = m_proxyURL.pass();
+ info.realmValue = m_strProxyRealm;
+ info.digestInfo = m_strProxyAuthorization;
+ }
+ else
+ {
+ info.url = m_request.url;
+ info.username = m_request.user;
+ info.password = m_request.passwd;
+ info.realmValue = m_strRealm;
+ info.digestInfo = m_strAuthorization;
+ }
+
+ // If either username or password is not supplied
+ // with the request, check the password cache.
+ if ( info.username.isNull() ||
+ info.password.isNull() )
+ result = checkCachedAuthentication( info );
+
+ if ( Authentication == AUTH_Digest )
+ {
+ TQString auth;
+
+ if (m_responseCode == 401)
+ auth = m_strAuthorization;
+ else
+ auth = m_strProxyAuthorization;
+
+ int pos = auth.find("stale", 0, false);
+ if ( pos != -1 )
+ {
+ pos += 5;
+ int len = auth.length();
+ while( pos < len && (auth[pos] == ' ' || auth[pos] == '=') ) pos++;
+ if ( pos < len && auth.find("true", pos, false) != -1 )
+ {
+ info.digestInfo = (m_responseCode == 401) ? m_strAuthorization : m_strProxyAuthorization;
+ kdDebug(7113) << "(" << m_pid << ") Just a stale nonce value! "
+ << "Retrying using the new nonce sent..." << endl;
+ }
+ }
+ }
+ }
+
+ if (!result )
+ {
+ // Do not prompt if the username & password
+ // is already supplied and the login attempt
+ // did not fail before.
+ if ( !repeatFailure &&
+ !info.username.isNull() &&
+ !info.password.isNull() )
+ result = true;
+ else
+ {
+ if (Authentication == AUTH_Negotiate)
+ {
+ if (!repeatFailure)
+ result = true;
+ }
+ else if ( m_request.disablePassDlg == false )
+ {
+ kdDebug( 7113 ) << "(" << m_pid << ") Prompting the user for authorization..." << endl;
+ promptInfo( info );
+ result = openPassDlg( info, errorMsg );
+ }
+ }
+ }
+
+ if ( result )
+ {
+ switch (m_responseCode)
+ {
+ case 401: // Request-Authentication
+ m_request.user = info.username;
+ m_request.passwd = info.password;
+ m_strRealm = info.realmValue;
+ m_strAuthorization = info.digestInfo;
+ break;
+ case 407: // Proxy-Authentication
+ m_proxyURL.setUser( info.username );
+ m_proxyURL.setPass( info.password );
+ m_strProxyRealm = info.realmValue;
+ m_strProxyAuthorization = info.digestInfo;
+ break;
+ default:
+ break;
+ }
+ return true;
+ }
+
+ if (m_request.bErrorPage)
+ errorPage();
+ else
+ error( ERR_USER_CANCELED, TQString::null );
+ return false;
+}
+
+void HTTPProtocol::saveAuthorization()
+{
+ AuthInfo info;
+ if ( m_prevResponseCode == 407 )
+ {
+ if (!m_bUseProxy)
+ return;
+ m_bProxyAuthValid = true;
+ info.url = m_proxyURL;
+ info.username = m_proxyURL.user();
+ info.password = m_proxyURL.pass();
+ info.realmValue = m_strProxyRealm;
+ info.digestInfo = m_strProxyAuthorization;
+ cacheAuthentication( info );
+ }
+ else
+ {
+ info.url = m_request.url;
+ info.username = m_request.user;
+ info.password = m_request.passwd;
+ info.realmValue = m_strRealm;
+ info.digestInfo = m_strAuthorization;
+ cacheAuthentication( info );
+ }
+}
+
+#ifdef HAVE_LIBGSSAPI
+TQCString HTTPProtocol::gssError( int major_status, int minor_status )
+{
+ OM_uint32 new_status;
+ OM_uint32 msg_ctx = 0;
+ gss_buffer_desc major_string;
+ gss_buffer_desc minor_string;
+ OM_uint32 ret;
+ TQCString errorstr;
+
+ errorstr = "";
+
+ do {
+ ret = gss_display_status(&new_status, major_status, GSS_C_GSS_CODE, GSS_C_NULL_OID, &msg_ctx, &major_string);
+ errorstr += (const char *)major_string.value;
+ errorstr += " ";
+ ret = gss_display_status(&new_status, minor_status, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &minor_string);
+ errorstr += (const char *)minor_string.value;
+ errorstr += " ";
+ } while (!GSS_ERROR(ret) && msg_ctx != 0);
+
+ return errorstr;
+}
+
+TQString HTTPProtocol::createNegotiateAuth()
+{
+ TQString auth;
+ TQCString servicename;
+ TQByteArray input;
+ OM_uint32 major_status, minor_status;
+ OM_uint32 req_flags = 0;
+ gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER;
+ gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER;
+ gss_name_t server;
+ gss_ctx_id_t ctx;
+ gss_OID mech_oid;
+ static gss_OID_desc krb5_oid_desc = {9, (void *) "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"};
+ static gss_OID_desc spnego_oid_desc = {6, (void *) "\x2b\x06\x01\x05\x05\x02"};
+ int found = 0;
+ unsigned int i;
+ gss_OID_set mech_set;
+ gss_OID tmp_oid;
+
+ ctx = GSS_C_NO_CONTEXT;
+ mech_oid = &krb5_oid_desc;
+
+ // see whether we can use the SPNEGO mechanism
+ major_status = gss_indicate_mechs(&minor_status, &mech_set);
+ if (GSS_ERROR(major_status)) {
+ kdDebug(7113) << "(" << m_pid << ") gss_indicate_mechs failed: " << gssError(major_status, minor_status) << endl;
+ } else {
+ for (i=0; i<mech_set->count && !found; i++) {
+ tmp_oid = &mech_set->elements[i];
+ if (tmp_oid->length == spnego_oid_desc.length &&
+ !memcmp(tmp_oid->elements, spnego_oid_desc.elements, tmp_oid->length)) {
+ kdDebug(7113) << "(" << m_pid << ") createNegotiateAuth: found SPNEGO mech" << endl;
+ found = 1;
+ mech_oid = &spnego_oid_desc;
+ break;
+ }
+ }
+ gss_release_oid_set(&minor_status, &mech_set);
+ }
+
+ // the service name is "HTTP/f.q.d.n"
+ servicename = "HTTP@";
+ servicename += m_state.hostname.ascii();
+
+ input_token.value = (void *)servicename.data();
+ input_token.length = servicename.length() + 1;
+
+ major_status = gss_import_name(&minor_status, &input_token,
+ GSS_C_NT_HOSTBASED_SERVICE, &server);
+
+ input_token.value = NULL;
+ input_token.length = 0;
+
+ if (GSS_ERROR(major_status)) {
+ kdDebug(7113) << "(" << m_pid << ") gss_import_name failed: " << gssError(major_status, minor_status) << endl;
+ // reset the auth string so that subsequent methods aren't confused
+ m_strAuthorization = TQString::null;
+ return TQString::null;
+ }
+
+ major_status = gss_init_sec_context(&minor_status, GSS_C_NO_CREDENTIAL,
+ &ctx, server, mech_oid,
+ req_flags, GSS_C_INDEFINITE,
+ GSS_C_NO_CHANNEL_BINDINGS,
+ GSS_C_NO_BUFFER, NULL, &output_token,
+ NULL, NULL);
+
+
+ if (GSS_ERROR(major_status) || (output_token.length == 0)) {
+ kdDebug(7113) << "(" << m_pid << ") gss_init_sec_context failed: " << gssError(major_status, minor_status) << endl;
+ gss_release_name(&minor_status, &server);
+ if (ctx != GSS_C_NO_CONTEXT) {
+ gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
+ ctx = GSS_C_NO_CONTEXT;
+ }
+ // reset the auth string so that subsequent methods aren't confused
+ m_strAuthorization = TQString::null;
+ return TQString::null;
+ }
+
+ input.duplicate((const char *)output_token.value, output_token.length);
+ auth = "Authorization: Negotiate ";
+ auth += KCodecs::base64Encode( input );
+ auth += "\r\n";
+
+ // free everything
+ gss_release_name(&minor_status, &server);
+ if (ctx != GSS_C_NO_CONTEXT) {
+ gss_delete_sec_context(&minor_status, &ctx, GSS_C_NO_BUFFER);
+ ctx = GSS_C_NO_CONTEXT;
+ }
+ gss_release_buffer(&minor_status, &output_token);
+
+ return auth;
+}
+#else
+
+// Dummy
+TQCString HTTPProtocol::gssError( int, int )
+{
+ return "";
+}
+
+// Dummy
+TQString HTTPProtocol::createNegotiateAuth()
+{
+ return TQString::null;
+}
+#endif
+
+TQString HTTPProtocol::createNTLMAuth( bool isForProxy )
+{
+ uint len;
+ TQString auth, user, domain, passwd;
+ TQCString strauth;
+ TQByteArray buf;
+
+ if ( isForProxy )
+ {
+ auth = "Proxy-Connection: Keep-Alive\r\n";
+ auth += "Proxy-Authorization: NTLM ";
+ user = m_proxyURL.user();
+ passwd = m_proxyURL.pass();
+ strauth = m_strProxyAuthorization.latin1();
+ len = m_strProxyAuthorization.length();
+ }
+ else
+ {
+ auth = "Authorization: NTLM ";
+ user = m_state.user;
+ passwd = m_state.passwd;
+ strauth = m_strAuthorization.latin1();
+ len = m_strAuthorization.length();
+ }
+ if ( user.contains('\\') ) {
+ domain = user.section( '\\', 0, 0);
+ user = user.section( '\\', 1 );
+ }
+
+ kdDebug(7113) << "(" << m_pid << ") NTLM length: " << len << endl;
+ if ( user.isEmpty() || passwd.isEmpty() || len < 4 )
+ return TQString::null;
+
+ if ( len > 4 )
+ {
+ // create a response
+ TQByteArray challenge;
+ KCodecs::base64Decode( strauth.right( len - 5 ), challenge );
+ KNTLM::getAuth( buf, challenge, user, passwd, domain,
+ KNetwork::KResolver::localHostName(), false, false );
+ }
+ else
+ {
+ KNTLM::getNegotiate( buf );
+ }
+
+ // remove the challenge to prevent reuse
+ if ( isForProxy )
+ m_strProxyAuthorization = "NTLM";
+ else
+ m_strAuthorization = "NTLM";
+
+ auth += KCodecs::base64Encode( buf );
+ auth += "\r\n";
+
+ return auth;
+}
+
+TQString HTTPProtocol::createBasicAuth( bool isForProxy )
+{
+ TQString auth;
+ TQCString user, passwd;
+ if ( isForProxy )
+ {
+ auth = "Proxy-Authorization: Basic ";
+ user = m_proxyURL.user().latin1();
+ passwd = m_proxyURL.pass().latin1();
+ }
+ else
+ {
+ auth = "Authorization: Basic ";
+ user = m_state.user.latin1();
+ passwd = m_state.passwd.latin1();
+ }
+
+ if ( user.isEmpty() )
+ user = "";
+ if ( passwd.isEmpty() )
+ passwd = "";
+
+ user += ':';
+ user += passwd;
+ auth += KCodecs::base64Encode( user );
+ auth += "\r\n";
+
+ return auth;
+}
+
+void HTTPProtocol::calculateResponse( DigestAuthInfo& info, TQCString& Response )
+{
+ KMD5 md;
+ TQCString HA1;
+ TQCString HA2;
+
+ // Calculate H(A1)
+ TQCString authStr = info.username;
+ authStr += ':';
+ authStr += info.realm;
+ authStr += ':';
+ authStr += info.password;
+ md.update( authStr );
+
+ if ( info.algorithm.lower() == "md5-sess" )
+ {
+ authStr = md.hexDigest();
+ authStr += ':';
+ authStr += info.nonce;
+ authStr += ':';
+ authStr += info.cnonce;
+ md.reset();
+ md.update( authStr );
+ }
+ HA1 = md.hexDigest();
+
+ kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A1 => " << HA1 << endl;
+
+ // Calcualte H(A2)
+ authStr = info.method;
+ authStr += ':';
+ authStr += m_request.url.encodedPathAndQuery(0, true).latin1();
+ if ( info.qop == "auth-int" )
+ {
+ authStr += ':';
+ authStr += info.entityBody;
+ }
+ md.reset();
+ md.update( authStr );
+ HA2 = md.hexDigest();
+
+ kdDebug(7113) << "(" << m_pid << ") calculateResponse(): A2 => "
+ << HA2 << endl;
+
+ // Calcualte the response.
+ authStr = HA1;
+ authStr += ':';
+ authStr += info.nonce;
+ authStr += ':';
+ if ( !info.qop.isEmpty() )
+ {
+ authStr += info.nc;
+ authStr += ':';
+ authStr += info.cnonce;
+ authStr += ':';
+ authStr += info.qop;
+ authStr += ':';
+ }
+ authStr += HA2;
+ md.reset();
+ md.update( authStr );
+ Response = md.hexDigest();
+
+ kdDebug(7113) << "(" << m_pid << ") calculateResponse(): Response => "
+ << Response << endl;
+}
+
+TQString HTTPProtocol::createDigestAuth ( bool isForProxy )
+{
+ const char *p;
+
+ TQString auth;
+ TQCString opaque;
+ TQCString Response;
+
+ DigestAuthInfo info;
+
+ opaque = "";
+ if ( isForProxy )
+ {
+ auth = "Proxy-Authorization: Digest ";
+ info.username = m_proxyURL.user().latin1();
+ info.password = m_proxyURL.pass().latin1();
+ p = m_strProxyAuthorization.latin1();
+ }
+ else
+ {
+ auth = "Authorization: Digest ";
+ info.username = m_state.user.latin1();
+ info.password = m_state.passwd.latin1();
+ p = m_strAuthorization.latin1();
+ }
+ if (!p || !*p)
+ return TQString::null;
+
+ p += 6; // Skip "Digest"
+
+ if ( info.username.isEmpty() || info.password.isEmpty() || !p )
+ return TQString::null;
+
+ // info.entityBody = p; // FIXME: send digest of data for POST action ??
+ info.realm = "";
+ info.algorithm = "MD5";
+ info.nonce = "";
+ info.qop = "";
+
+ // cnonce is recommended to contain about 64 bits of entropy
+ info.cnonce = TDEApplication::randomString(16).latin1();
+
+ // HACK: Should be fixed according to RFC 2617 section 3.2.2
+ info.nc = "00000001";
+
+ // Set the method used...
+ switch ( m_request.method )
+ {
+ case HTTP_GET:
+ info.method = "GET";
+ break;
+ case HTTP_PUT:
+ info.method = "PUT";
+ break;
+ case HTTP_POST:
+ info.method = "POST";
+ break;
+ case HTTP_HEAD:
+ info.method = "HEAD";
+ break;
+ case HTTP_DELETE:
+ info.method = "DELETE";
+ break;
+ case DAV_PROPFIND:
+ info.method = "PROPFIND";
+ break;
+ case DAV_PROPPATCH:
+ info.method = "PROPPATCH";
+ break;
+ case DAV_MKCOL:
+ info.method = "MKCOL";
+ break;
+ case DAV_COPY:
+ info.method = "COPY";
+ break;
+ case DAV_MOVE:
+ info.method = "MOVE";
+ break;
+ case DAV_LOCK:
+ info.method = "LOCK";
+ break;
+ case DAV_UNLOCK:
+ info.method = "UNLOCK";
+ break;
+ case DAV_SEARCH:
+ info.method = "SEARCH";
+ break;
+ case DAV_SUBSCRIBE:
+ info.method = "SUBSCRIBE";
+ break;
+ case DAV_UNSUBSCRIBE:
+ info.method = "UNSUBSCRIBE";
+ break;
+ case DAV_POLL:
+ info.method = "POLL";
+ break;
+ default:
+ error( ERR_UNSUPPORTED_ACTION, i18n("Unsupported method: authentication will fail. Please submit a bug report."));
+ break;
+ }
+
+ // Parse the Digest response....
+ while (*p)
+ {
+ int i = 0;
+ while ( (*p == ' ') || (*p == ',') || (*p == '\t')) { p++; }
+ if (strncasecmp(p, "realm=", 6 )==0)
+ {
+ p+=6;
+ while ( *p == '"' ) p++; // Go past any number of " mark(s) first
+ while ( p[i] != '"' ) i++; // Read everything until the last " mark
+ info.realm = TQCString( p, i+1 );
+ }
+ else if (strncasecmp(p, "algorith=", 9)==0)
+ {
+ p+=9;
+ while ( *p == '"' ) p++; // Go past any number of " mark(s) first
+ while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
+ info.algorithm = TQCString(p, i+1);
+ }
+ else if (strncasecmp(p, "algorithm=", 10)==0)
+ {
+ p+=10;
+ while ( *p == '"' ) p++; // Go past any " mark(s) first
+ while ( ( p[i] != '"' ) && ( p[i] != ',' ) && ( p[i] != '\0' ) ) i++;
+ info.algorithm = TQCString(p,i+1);
+ }
+ else if (strncasecmp(p, "domain=", 7)==0)
+ {
+ p+=7;
+ while ( *p == '"' ) p++; // Go past any " mark(s) first
+ while ( p[i] != '"' ) i++; // Read everything until the last " mark
+ int pos;
+ int idx = 0;
+ TQCString uri = TQCString(p,i+1);
+ do
+ {
+ pos = uri.find( ' ', idx );
+ if ( pos != -1 )
+ {
+ KURL u (m_request.url, uri.mid(idx, pos-idx));
+ if (u.isValid ())
+ info.digestURI.append( u.url().latin1() );
+ }
+ else
+ {
+ KURL u (m_request.url, uri.mid(idx, uri.length()-idx));
+ if (u.isValid ())
+ info.digestURI.append( u.url().latin1() );
+ }
+ idx = pos+1;
+ } while ( pos != -1 );
+ }
+ else if (strncasecmp(p, "nonce=", 6)==0)
+ {
+ p+=6;
+ while ( *p == '"' ) p++; // Go past any " mark(s) first
+ while ( p[i] != '"' ) i++; // Read everything until the last " mark
+ info.nonce = TQCString(p,i+1);
+ }
+ else if (strncasecmp(p, "opaque=", 7)==0)
+ {
+ p+=7;
+ while ( *p == '"' ) p++; // Go past any " mark(s) first
+ while ( p[i] != '"' ) i++; // Read everything until the last " mark
+ opaque = TQCString(p,i+1);
+ }
+ else if (strncasecmp(p, "qop=", 4)==0)
+ {
+ p+=4;
+ while ( *p == '"' ) p++; // Go past any " mark(s) first
+ while ( p[i] != '"' ) i++; // Read everything until the last " mark
+ info.qop = TQCString(p,i+1);
+ }
+ p+=(i+1);
+ }
+
+ if (info.realm.isEmpty() || info.nonce.isEmpty())
+ return TQString::null;
+
+ // If the "domain" attribute was not specified and the current response code
+ // is authentication needed, add the current request url to the list over which
+ // this credential can be automatically applied.
+ if (info.digestURI.isEmpty() && (m_responseCode == 401 || m_responseCode == 407))
+ info.digestURI.append (m_request.url.url().latin1());
+ else
+ {
+ // Verify whether or not we should send a cached credential to the
+ // server based on the stored "domain" attribute...
+ bool send = true;
+
+ // Determine the path of the request url...
+ TQString requestPath = m_request.url.directory(false, false);
+ if (requestPath.isEmpty())
+ requestPath = "/";
+
+ int count = info.digestURI.count();
+
+ for (int i = 0; i < count; i++ )
+ {
+ KURL u ( info.digestURI.at(i) );
+
+ send &= (m_request.url.protocol().lower() == u.protocol().lower());
+ send &= (m_request.hostname.lower() == u.host().lower());
+
+ if (m_request.port > 0 && u.port() > 0)
+ send &= (m_request.port == u.port());
+
+ TQString digestPath = u.directory (false, false);
+ if (digestPath.isEmpty())
+ digestPath = "/";
+
+ send &= (requestPath.startsWith(digestPath));
+
+ if (send)
+ break;
+ }
+
+ kdDebug(7113) << "(" << m_pid << ") createDigestAuth(): passed digest "
+ "authentication credential test: " << send << endl;
+
+ if (!send)
+ return TQString::null;
+ }
+
+ kdDebug(7113) << "(" << m_pid << ") RESULT OF PARSING:" << endl;
+ kdDebug(7113) << "(" << m_pid << ") algorithm: " << info.algorithm << endl;
+ kdDebug(7113) << "(" << m_pid << ") realm: " << info.realm << endl;
+ kdDebug(7113) << "(" << m_pid << ") nonce: " << info.nonce << endl;
+ kdDebug(7113) << "(" << m_pid << ") opaque: " << opaque << endl;
+ kdDebug(7113) << "(" << m_pid << ") qop: " << info.qop << endl;
+
+ // Calculate the response...
+ calculateResponse( info, Response );
+
+ auth += "username=\"";
+ auth += info.username;
+
+ auth += "\", realm=\"";
+ auth += info.realm;
+ auth += "\"";
+
+ auth += ", nonce=\"";
+ auth += info.nonce;
+
+ auth += "\", uri=\"";
+ auth += m_request.url.encodedPathAndQuery(0, true);
+
+ auth += "\", algorithm=\"";
+ auth += info.algorithm;
+ auth +="\"";
+
+ if ( !info.qop.isEmpty() )
+ {
+ auth += ", qop=\"";
+ auth += info.qop;
+ auth += "\", cnonce=\"";
+ auth += info.cnonce;
+ auth += "\", nc=";
+ auth += info.nc;
+ }
+
+ auth += ", response=\"";
+ auth += Response;
+ if ( !opaque.isEmpty() )
+ {
+ auth += "\", opaque=\"";
+ auth += opaque;
+ }
+ auth += "\"\r\n";
+
+ return auth;
+}
+
+TQString HTTPProtocol::proxyAuthenticationHeader()
+{
+ TQString header;
+
+ // We keep proxy authentication locally until they are changed.
+ // Thus, no need to check with the password manager for every
+ // connection.
+ if ( m_strProxyRealm.isEmpty() )
+ {
+ AuthInfo info;
+ info.url = m_proxyURL;
+ info.username = m_proxyURL.user();
+ info.password = m_proxyURL.pass();
+ info.verifyPath = true;
+
+ // If the proxy URL already contains username
+ // and password simply attempt to retrieve it
+ // without prompting the user...
+ if ( !info.username.isNull() && !info.password.isNull() )
+ {
+ if( m_strProxyAuthorization.isEmpty() )
+ ProxyAuthentication = AUTH_None;
+ else if( m_strProxyAuthorization.startsWith("Basic") )
+ ProxyAuthentication = AUTH_Basic;
+ else if( m_strProxyAuthorization.startsWith("NTLM") )
+ ProxyAuthentication = AUTH_NTLM;
+ else
+ ProxyAuthentication = AUTH_Digest;
+ }
+ else
+ {
+ if ( checkCachedAuthentication(info) && !info.digestInfo.isEmpty() )
+ {
+ m_proxyURL.setUser( info.username );
+ m_proxyURL.setPass( info.password );
+ m_strProxyRealm = info.realmValue;
+ m_strProxyAuthorization = info.digestInfo;
+ if( m_strProxyAuthorization.startsWith("Basic") )
+ ProxyAuthentication = AUTH_Basic;
+ else if( m_strProxyAuthorization.startsWith("NTLM") )
+ ProxyAuthentication = AUTH_NTLM;
+ else
+ ProxyAuthentication = AUTH_Digest;
+ }
+ else
+ {
+ ProxyAuthentication = AUTH_None;
+ }
+ }
+ }
+
+ /********* Only for debugging purpose... *********/
+ if ( ProxyAuthentication != AUTH_None )
+ {
+ kdDebug(7113) << "(" << m_pid << ") Using Proxy Authentication: " << endl;
+ kdDebug(7113) << "(" << m_pid << ") HOST= " << m_proxyURL.host() << endl;
+ kdDebug(7113) << "(" << m_pid << ") PORT= " << m_proxyURL.port() << endl;
+ kdDebug(7113) << "(" << m_pid << ") USER= " << m_proxyURL.user() << endl;
+ kdDebug(7113) << "(" << m_pid << ") PASSWORD= [protected]" << endl;
+ kdDebug(7113) << "(" << m_pid << ") REALM= " << m_strProxyRealm << endl;
+ kdDebug(7113) << "(" << m_pid << ") EXTRA= " << m_strProxyAuthorization << endl;
+ }
+
+ switch ( ProxyAuthentication )
+ {
+ case AUTH_Basic:
+ header += createBasicAuth( true );
+ break;
+ case AUTH_Digest:
+ header += createDigestAuth( true );
+ break;
+ case AUTH_NTLM:
+ if ( m_bFirstRequest ) header += createNTLMAuth( true );
+ break;
+ case AUTH_None:
+ default:
+ break;
+ }
+
+ return header;
+}
+
+#include "http.moc"
diff --git a/tdeioslave/http/http.h b/tdeioslave/http/http.h
new file mode 100644
index 000000000..aacdf1d47
--- /dev/null
+++ b/tdeioslave/http/http.h
@@ -0,0 +1,577 @@
+/*
+ Copyright (C) 2000,2001 Dawit Alemayehu <adawit@kde.org>
+ Copyright (C) 2000,2001 Waldo Bastian <bastian@kde.org>
+ Copyright (C) 2000,2001 George Staikos <staikos@kde.org>
+ Copyright (C) 2001,2002 Hamish Rodda <rodda@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef HTTP_H_
+#define HTTP_H_
+
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <string.h>
+#include <stdio.h>
+#include <time.h>
+
+#include <tqptrlist.h>
+#include <tqstrlist.h>
+#include <tqstringlist.h>
+
+#include <kurl.h>
+#include "tdeio/tcpslavebase.h"
+#include "tdeio/http.h"
+
+class DCOPClient;
+class TQDomElement;
+class TQDomNodeList;
+
+namespace TDEIO {
+ class AuthInfo;
+}
+
+class HTTPProtocol : public TQObject, public TDEIO::TCPSlaveBase
+{
+ Q_OBJECT
+public:
+ HTTPProtocol( const TQCString &protocol, const TQCString &pool,
+ const TQCString &app );
+ virtual ~HTTPProtocol();
+
+ /** HTTP version **/
+ enum HTTP_REV {HTTP_None, HTTP_Unknown, HTTP_10, HTTP_11, SHOUTCAST};
+
+ /** Authorization method used **/
+ enum HTTP_AUTH {AUTH_None, AUTH_Basic, AUTH_NTLM, AUTH_Digest, AUTH_Negotiate};
+
+ /** HTTP / DAV method **/
+ // Removed to interfaces/tdeio/http.h
+ //enum HTTP_METHOD {HTTP_GET, HTTP_PUT, HTTP_POST, HTTP_HEAD, HTTP_DELETE,
+ // HTTP_OPTIONS, DAV_PROPFIND, DAV_PROPPATCH, DAV_MKCOL,
+ // DAV_COPY, DAV_MOVE, DAV_LOCK, DAV_UNLOCK, DAV_SEARCH };
+
+ /** State of the current Connection **/
+ struct HTTPState
+ {
+ HTTPState ()
+ {
+ port = 0;
+ doProxy = false;
+ }
+
+ TQString hostname;
+ TQString encoded_hostname;
+ short unsigned int port;
+ TQString user;
+ TQString passwd;
+ bool doProxy;
+ };
+
+ /** DAV-specific request elements for the current connection **/
+ struct DAVRequest
+ {
+ DAVRequest ()
+ {
+ overwrite = false;
+ depth = 0;
+ }
+
+ TQString desturl;
+ bool overwrite;
+ int depth;
+ };
+
+ /** The request for the current connection **/
+ struct HTTPRequest
+ {
+ HTTPRequest ()
+ {
+ port = 0;
+ method = TDEIO::HTTP_UNKNOWN;
+ offset = 0;
+ doProxy = false;
+ allowCompressedPage = false;
+ disablePassDlg = false;
+ bNoAuth = false;
+ bUseCache = false;
+ bCachedRead = false;
+ bCachedWrite = false;
+ fcache = 0;
+ bMustRevalidate = false;
+ cacheExpireDateOffset = 0;
+ bErrorPage = false;
+ bUseCookiejar = false;
+ expireDate = 0;
+ creationDate = 0;
+ }
+
+ TQString hostname;
+ TQString encoded_hostname;
+ short unsigned int port;
+ TQString user;
+ TQString passwd;
+ TQString path;
+ TQString query;
+ TDEIO::HTTP_METHOD method;
+ TDEIO::CacheControl cache;
+ TDEIO::filesize_t offset;
+ bool doProxy;
+ KURL url;
+ TQString window; // Window Id this request is related to.
+ TQString referrer;
+ TQString charsets;
+ TQString languages;
+ bool allowCompressedPage;
+ bool disablePassDlg;
+ TQString userAgent;
+ TQString id;
+ DAVRequest davData;
+
+ bool bNoAuth; // Do not authenticate
+
+ // Cache related
+ TQString cef; // Cache Entry File belonging to this URL.
+ bool bUseCache; // Whether the cache is active
+ bool bCachedRead; // Whether the file is to be read from m_fcache.
+ bool bCachedWrite; // Whether the file is to be written to m_fcache.
+ FILE* fcache; // File stream of a cache entry
+ TQString etag; // ETag header.
+ TQString lastModified; // Last modified.
+ bool bMustRevalidate; // Cache entry is expired.
+ long cacheExpireDateOffset; // Position in the cache entry where the
+ // 16 byte expire date is stored.
+ time_t expireDate; // Date when the cache entry will expire
+ time_t creationDate; // Date when the cache entry was created
+ TQString strCharset; // Charset
+
+ // Indicates whether an error-page or error-msg should is preferred.
+ bool bErrorPage;
+
+ // Cookie flags
+ bool bUseCookiejar;
+ enum { CookiesAuto, CookiesManual, CookiesNone } cookieMode;
+ };
+
+ struct DigestAuthInfo
+ {
+ TQCString nc;
+ TQCString qop;
+ TQCString realm;
+ TQCString nonce;
+ TQCString method;
+ TQCString cnonce;
+ TQCString username;
+ TQCString password;
+ TQStrList digestURI;
+ TQCString algorithm;
+ TQCString entityBody;
+ };
+
+//---------------------- Re-implemented methods ----------------
+ virtual void setHost(const TQString& host, int port, const TQString& user,
+ const TQString& pass);
+
+ virtual void slave_status();
+
+ virtual void get( const KURL& url );
+ virtual void put( const KURL& url, int permissions, bool overwrite,
+ bool resume );
+
+//----------------- Re-implemented methods for WebDAV -----------
+ virtual void listDir( const KURL& url );
+ virtual void mkdir( const KURL& url, int permissions );
+
+ virtual void rename( const KURL& src, const KURL& dest, bool overwrite );
+ virtual void copy( const KURL& src, const KURL& dest, int permissions, bool overwrite );
+ virtual void del( const KURL& url, bool isfile );
+
+ // ask the host whether it supports WebDAV & cache this info
+ bool davHostOk();
+
+ // send generic DAV request
+ void davGeneric( const KURL& url, TDEIO::HTTP_METHOD method );
+
+ // Send requests to lock and unlock resources
+ void davLock( const KURL& url, const TQString& scope,
+ const TQString& type, const TQString& owner );
+ void davUnlock( const KURL& url );
+
+ // Calls httpClose() and finished()
+ void davFinished();
+
+ // Handle error conditions
+ TQString davError( int code = -1, TQString url = TQString::null );
+//---------------------------- End WebDAV -----------------------
+
+ /**
+ * Special commands supported by this slave :
+ * 1 - HTTP POST
+ * 2 - Cache has been updated
+ * 3 - SSL Certificate Cache has been updated
+ * 4 - HTTP multi get
+ * 5 - DAV LOCK (see
+ * 6 - DAV UNLOCK README.webdav)
+ */
+ virtual void special( const TQByteArray &data );
+
+ virtual void mimetype( const KURL& url);
+
+ virtual void stat( const KURL& url );
+
+ virtual void reparseConfiguration();
+
+ virtual void closeConnection(); // Forced close of connection
+
+ void post( const KURL& url );
+ void multiGet(const TQByteArray &data);
+ bool checkRequestURL( const KURL& );
+ void cacheUpdate( const KURL &url, bool nocache, time_t expireDate);
+
+ void httpError(); // Generate error message based on response code
+
+ bool isOffline(const KURL &url); // Check network status
+
+protected slots:
+ void slotData(const TQByteArray &);
+ void error( int _errid, const TQString &_text );
+
+protected:
+ int readChunked(); // Read a chunk
+ int readLimited(); // Read maximum m_iSize bytes.
+ int readUnlimited(); // Read as much as possible.
+
+ /**
+ * A "smart" wrapper around write that will use SSL_write or
+ * write(2) depending on whether you've got an SSL connection or not.
+ * The only shortcomming is that it uses the "global" file handles and
+ * soforth. So you can't really use this on individual files/sockets.
+ */
+ ssize_t write(const void *buf, size_t nbytes);
+
+ /**
+ * Another "smart" wrapper, this time around read that will
+ * use SSL_read or read(2) depending on whether you've got an
+ * SSL connection or not.
+ */
+ ssize_t read (void *b, size_t nbytes);
+
+ char *gets (char *str, int size);
+
+ void setRewindMarker();
+ void rewind();
+
+ /**
+ * Add an encoding on to the appropriate stack this
+ * is nececesary because transfer encodings and
+ * content encodings must be handled separately.
+ */
+ void addEncoding(TQString, TQStringList &);
+
+ void configAuth( char *, bool );
+
+ bool httpOpen(); // Open transfer
+ void httpClose(bool keepAlive); // Close transfer
+
+ bool httpOpenConnection(); // Open connection
+ void httpCloseConnection(); // Close connection
+ void httpCheckConnection(); // Check whether to keep connection.
+
+ void forwardHttpResponseHeader();
+
+ bool readHeader();
+
+ bool sendBody();
+
+ // where dataInternal == true, the content is to be made available
+ // to an internal function.
+ bool readBody( bool dataInternal = false );
+
+ /**
+ * Performs a WebDAV stat or list
+ */
+ void davSetRequest( const TQCString& requestXML );
+ void davStatList( const KURL& url, bool stat = true );
+ void davParsePropstats( const TQDomNodeList& propstats, TDEIO::UDSEntry& entry );
+ void davParseActiveLocks( const TQDomNodeList& activeLocks,
+ uint& lockCount );
+
+ /**
+ * Parses a date & time string
+ */
+ long parseDateTime( const TQString& input, const TQString& type );
+
+ /**
+ * Returns the error code from a "HTTP/1.1 code Code Name" string
+ */
+ int codeFromResponse( const TQString& response );
+
+ /**
+ * Extracts locks from metadata
+ * Returns the appropriate If: header
+ */
+ TQString davProcessLocks();
+
+ /**
+ * Send a cookie to the cookiejar
+ */
+ void addCookies( const TQString &url, const TQCString &cookieHeader);
+
+ /**
+ * Look for cookies in the cookiejar
+ */
+ TQString findCookies( const TQString &url);
+
+ /**
+ * Do a cache lookup for the current url. (m_state.url)
+ *
+ * @param readWrite If true, file is opened read/write.
+ * If false, file is opened read-only.
+ *
+ * @return a file stream open for reading and at the start of
+ * the header section when the Cache entry exists and is valid.
+ * 0 if no cache entry could be found, or if the entry is not
+ * valid (any more).
+ */
+ FILE *checkCacheEntry(bool readWrite = false);
+
+ /**
+ * Create a cache entry for the current url. (m_state.url)
+ *
+ * Set the contents type of the cache entry to 'mimetype'.
+ */
+ void createCacheEntry(const TQString &mimetype, time_t expireDate);
+
+ /**
+ * Write data to cache.
+ *
+ * Write 'nbytes' from 'buffer' to the Cache Entry File
+ */
+ void writeCacheEntry( const char *buffer, int nbytes);
+
+ /**
+ * Close cache entry
+ */
+ void closeCacheEntry();
+
+ /**
+ * Update expire time of current cache entry.
+ */
+ void updateExpireDate(time_t expireDate, bool updateCreationDate=false);
+
+ /**
+ * Quick check whether the cache needs cleaning.
+ */
+ void cleanCache();
+
+ /**
+ * Performs a GET HTTP request.
+ */
+ // where dataInternal == true, the content is to be made available
+ // to an internal function.
+ void retrieveContent( bool dataInternal = false );
+
+ /**
+ * Performs a HEAD HTTP request.
+ */
+ bool retrieveHeader(bool close_connection = true);
+
+ /**
+ * Resets any per session settings.
+ */
+ void resetSessionSettings();
+
+ /**
+ * Resets settings related to parsing a response.
+ */
+ void resetResponseSettings();
+
+ /**
+ * Resets any per connection settings. These are different from
+ * per-session settings in that they must be invalidates every time
+ * a request is made, e.g. a retry to re-send the header to the
+ * server, as compared to only when a new request arrives.
+ */
+ void resetConnectionSettings();
+
+ /**
+ * Returns any pre-cached proxy authentication info
+ * info in HTTP header format.
+ */
+ TQString proxyAuthenticationHeader();
+
+ /**
+ * Retrieves authorization info from cache or user.
+ */
+ bool getAuthorization();
+
+ /**
+ * Saves valid authorization info in the cache daemon.
+ */
+ void saveAuthorization();
+
+ /**
+ * Creates the entity-header for Basic authentication.
+ */
+ TQString createBasicAuth( bool isForProxy = false );
+
+ /**
+ * Creates the entity-header for Digest authentication.
+ */
+ TQString createDigestAuth( bool isForProxy = false );
+
+ /**
+ * Creates the entity-header for NTLM authentication.
+ */
+ TQString createNTLMAuth( bool isForProxy = false );
+
+ /**
+ * Creates the entity-header for Negotiate authentication.
+ */
+ TQString createNegotiateAuth();
+
+ /**
+ * create GSS error string
+ */
+ TQCString gssError( int major_status, int minor_status );
+
+ /**
+ * Calcualtes the message digest response based on RFC 2617.
+ */
+ void calculateResponse( DigestAuthInfo &info, TQCString &Response );
+
+ /**
+ * Prompts the user for authorization retry.
+ */
+ bool retryPrompt();
+
+ /**
+ * Creates authorization prompt info.
+ */
+ void promptInfo( TDEIO::AuthInfo& info );
+
+protected:
+ HTTPState m_state;
+ HTTPRequest m_request;
+ TQPtrList<HTTPRequest> m_requestQueue;
+
+ bool m_bBusy; // Busy handling request queue.
+ bool m_bEOF;
+ bool m_bEOD;
+
+//--- Settings related to a single response only
+ TQStringList m_responseHeader; // All headers
+ KURL m_redirectLocation;
+ bool m_bRedirect; // Indicates current request is a redirection
+
+ // Processing related
+ bool m_bChunked; // Chunked tranfer encoding
+ TDEIO::filesize_t m_iSize; // Expected size of message
+ TDEIO::filesize_t m_iBytesLeft; // # of bytes left to receive in this message.
+ TDEIO::filesize_t m_iContentLeft; // # of content bytes left
+ TQByteArray m_bufReceive; // Receive buffer
+ bool m_dataInternal; // Data is for internal consumption
+ char m_lineBuf[1024];
+ char m_rewindBuf[8192];
+ size_t m_rewindCount;
+ char *m_linePtr;
+ size_t m_lineCount;
+ char *m_lineBufUnget;
+ char *m_linePtrUnget;
+ size_t m_lineCountUnget;
+
+ // Mimetype determination
+ bool m_cpMimeBuffer;
+ TQByteArray m_mimeTypeBuffer;
+
+ // Language/Encoding related
+ TQStringList m_qTransferEncodings;
+ TQStringList m_qContentEncodings;
+ TQString m_sContentMD5;
+ TQString m_strMimeType;
+
+
+//--- WebDAV
+ // Data structure to hold data which will be passed to an internal func.
+ TQByteArray m_bufWebDavData;
+ TQStringList m_davCapabilities;
+
+ bool m_davHostOk;
+ bool m_davHostUnsupported;
+//----------
+
+ // Holds the POST data so it won't get lost on if we
+ // happend to get a 401/407 response when submitting,
+ // a form.
+ TQByteArray m_bufPOST;
+
+ // Cache related
+ int m_maxCacheAge; // Maximum age of a cache entry.
+ long m_maxCacheSize; // Maximum cache size in Kb.
+ TQString m_strCacheDir; // Location of the cache.
+
+
+
+//--- Proxy related members
+ bool m_bUseProxy;
+ bool m_bNeedTunnel; // Whether we need to make a SSL tunnel
+ bool m_bIsTunneled; // Whether we have an active SSL tunnel
+ bool m_bProxyAuthValid;
+ int m_iProxyPort;
+ KURL m_proxyURL;
+ TQString m_strProxyRealm;
+
+ // Operation mode
+ TQCString m_protocol;
+
+ // Authentication
+ TQString m_strRealm;
+ TQString m_strAuthorization;
+ TQString m_strProxyAuthorization;
+ HTTP_AUTH Authentication;
+ HTTP_AUTH ProxyAuthentication;
+ bool m_bUnauthorized;
+ short unsigned int m_iProxyAuthCount;
+ short unsigned int m_iWWWAuthCount;
+
+ // First request on a connection
+ bool m_bFirstRequest;
+
+ // Persistent connections
+ bool m_bKeepAlive;
+ int m_keepAliveTimeout; // Timeout in seconds.
+
+ // Persistent proxy connections
+ bool m_bPersistentProxyConnection;
+
+
+ // Indicates whether there was some connection error.
+ bool m_bError;
+
+ // Previous and current response codes
+ unsigned int m_responseCode;
+ unsigned int m_prevResponseCode;
+
+ // Values that determine the remote connection timeouts.
+ int m_proxyConnTimeout;
+ int m_remoteConnTimeout;
+ int m_remoteRespTimeout;
+
+ int m_pid;
+};
+#endif
diff --git a/tdeioslave/http/http.protocol b/tdeioslave/http/http.protocol
new file mode 100644
index 000000000..60f85c451
--- /dev/null
+++ b/tdeioslave/http/http.protocol
@@ -0,0 +1,12 @@
+[Protocol]
+exec=kio_http
+protocol=http
+input=none
+output=filesystem
+reading=true
+defaultMimetype=application/octet-stream
+determineMimetypeFromExtension=false
+Icon=www
+maxInstances=3
+DocPath=tdeioslave/http.html
+Class=:internet
diff --git a/kioslave/http/http_cache_cleaner.cpp b/tdeioslave/http/http_cache_cleaner.cpp
index 554d221d5..554d221d5 100644
--- a/kioslave/http/http_cache_cleaner.cpp
+++ b/tdeioslave/http/http_cache_cleaner.cpp
diff --git a/kioslave/http/http_cache_cleaner.desktop b/tdeioslave/http/http_cache_cleaner.desktop
index 33cebb731..33cebb731 100644
--- a/kioslave/http/http_cache_cleaner.desktop
+++ b/tdeioslave/http/http_cache_cleaner.desktop
diff --git a/tdeioslave/http/https.protocol b/tdeioslave/http/https.protocol
new file mode 100644
index 000000000..5d456599c
--- /dev/null
+++ b/tdeioslave/http/https.protocol
@@ -0,0 +1,12 @@
+[Protocol]
+exec=kio_http
+protocol=https
+input=none
+output=filesystem
+reading=true
+defaultMimetype=application/octet-stream
+determineMimetypeFromExtension=false
+Icon=www
+config=http
+DocPath=tdeioslave/https.html
+Class=:internet
diff --git a/kioslave/http/kcookiejar/CMakeLists.txt b/tdeioslave/http/kcookiejar/CMakeLists.txt
index 289daa4f0..289daa4f0 100644
--- a/kioslave/http/kcookiejar/CMakeLists.txt
+++ b/tdeioslave/http/kcookiejar/CMakeLists.txt
diff --git a/tdeioslave/http/kcookiejar/Makefile.am b/tdeioslave/http/kcookiejar/Makefile.am
new file mode 100644
index 000000000..dc331a4aa
--- /dev/null
+++ b/tdeioslave/http/kcookiejar/Makefile.am
@@ -0,0 +1,31 @@
+# Makefile.am of tdebase/tdeioslave/http
+
+SUBDIRS=tests
+INCLUDES= $(all_includes)
+
+####### Files
+
+bin_PROGRAMS =
+lib_LTLIBRARIES =
+tdeinit_LTLIBRARIES = kcookiejar.la
+kde_module_LTLIBRARIES = kded_kcookiejar.la
+
+kcookiejar_la_SOURCES = main.cpp
+METASOURCES = AUTO
+kcookiejar_la_LDFLAGS = $(all_libraries) -module -avoid-version
+kcookiejar_la_LIBADD = $(LIB_TDECORE) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la
+
+kded_kcookiejar_la_SOURCES = kcookiejar.cpp kcookieserver.cpp \
+ kcookieserver.skel kcookiewin.cpp
+kded_kcookiejar_la_LDFLAGS = $(all_libraries) -module -avoid-version
+kded_kcookiejar_la_LIBADD = $(LIB_KDED) $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDECORE) $(LIB_X11) $(LIB_TDEUI) $(top_builddir)/kded/libtdeinit_kded.la
+
+kded_DATA = kcookiejar.desktop
+kdeddir = $(kde_servicesdir)/kded
+
+update_DATA = kcookiescfg.upd
+updatedir = $(kde_datadir)/tdeconf_update
+
+cookie_DATA = domain_info
+cookiedir = $(kde_datadir)/tdehtml
+
diff --git a/kioslave/http/kcookiejar/domain_info b/tdeioslave/http/kcookiejar/domain_info
index 94baf8dae..94baf8dae 100644
--- a/kioslave/http/kcookiejar/domain_info
+++ b/tdeioslave/http/kcookiejar/domain_info
diff --git a/tdeioslave/http/kcookiejar/kcookiejar.cpp b/tdeioslave/http/kcookiejar/kcookiejar.cpp
new file mode 100644
index 000000000..5cb8d9053
--- /dev/null
+++ b/tdeioslave/http/kcookiejar/kcookiejar.cpp
@@ -0,0 +1,1559 @@
+/* This file is part of the KDE File Manager
+
+ Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
+ Copyright (C) 2000,2001 Dawit Alemayehu (adawit@kde.org)
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, and/or sell copies of the
+ Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+//----------------------------------------------------------------------------
+//
+// KDE File Manager -- HTTP Cookies
+// $Id$
+
+//
+// The cookie protocol is a mess. RFC2109 is a joke since nobody seems to
+// use it. Apart from that it is badly written.
+// We try to implement Netscape Cookies and try to behave us according to
+// RFC2109 as much as we can.
+//
+// We assume cookies do not contain any spaces (Netscape spec.)
+// According to RFC2109 this is allowed though.
+//
+
+#include <config.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+
+#ifdef USE_SOLARIS
+#include <strings.h>
+#endif
+
+#include <stdlib.h>
+
+//#include <netinet/in.h>
+//#include <arpa/inet.h>
+
+#include <tqstring.h>
+#include <tqstrlist.h>
+#include <tqptrlist.h>
+#include <tqptrdict.h>
+#include <tqfile.h>
+#include <tqdir.h>
+#include <tqregexp.h>
+
+#include <kurl.h>
+#include <krfcdate.h>
+#include <tdeconfig.h>
+#include <ksavefile.h>
+#include <kdebug.h>
+
+#include "kcookiejar.h"
+
+
+// BR87227
+// Waba: Should the number of cookies be limited?
+// I am not convinced of the need of such limit
+// Mozilla seems to limit to 20 cookies / domain
+// but it is unclear which policy it uses to expire
+// cookies when it exceeds that amount
+#undef MAX_COOKIE_LIMIT
+
+#define MAX_COOKIES_PER_HOST 25
+#define READ_BUFFER_SIZE 8192
+#define IP_ADDRESS_EXPRESSION "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
+
+// Note with respect to TQString::fromLatin1( )
+// Cookies are stored as 8 bit data and passed to kio_http as
+// latin1 regardless of their actual encoding.
+
+// L1 is used to indicate latin1 constants
+#define L1(x) TQString::fromLatin1(x)
+
+template class TQPtrList<KHttpCookie>;
+template class TQPtrDict<KHttpCookieList>;
+
+TQString KCookieJar::adviceToStr(KCookieAdvice _advice)
+{
+ switch( _advice )
+ {
+ case KCookieAccept: return L1("Accept");
+ case KCookieReject: return L1("Reject");
+ case KCookieAsk: return L1("Ask");
+ default: return L1("Dunno");
+ }
+}
+
+KCookieAdvice KCookieJar::strToAdvice(const TQString &_str)
+{
+ if (_str.isEmpty())
+ return KCookieDunno;
+
+ TQCString advice = _str.lower().latin1();
+
+ if (advice == "accept")
+ return KCookieAccept;
+ else if (advice == "reject")
+ return KCookieReject;
+ else if (advice == "ask")
+ return KCookieAsk;
+
+ return KCookieDunno;
+}
+
+// KHttpCookie
+///////////////////////////////////////////////////////////////////////////
+
+//
+// Cookie constructor
+//
+KHttpCookie::KHttpCookie(const TQString &_host,
+ const TQString &_domain,
+ const TQString &_path,
+ const TQString &_name,
+ const TQString &_value,
+ time_t _expireDate,
+ int _protocolVersion,
+ bool _secure,
+ bool _httpOnly,
+ bool _explicitPath) :
+ mHost(_host),
+ mDomain(_domain),
+ mPath(_path.isEmpty() ? TQString::null : _path),
+ mName(_name),
+ mValue(_value),
+ mExpireDate(_expireDate),
+ mProtocolVersion(_protocolVersion),
+ mSecure(_secure),
+ mCrossDomain(false),
+ mHttpOnly(_httpOnly),
+ mExplicitPath(_explicitPath)
+{
+}
+
+//
+// Checks if a cookie has been expired
+//
+bool KHttpCookie::isExpired(time_t currentDate)
+{
+ return (mExpireDate != 0) && (mExpireDate < currentDate);
+}
+
+//
+// Returns a string for a HTTP-header
+//
+TQString KHttpCookie::cookieStr(bool useDOMFormat)
+{
+ TQString result;
+
+ if (useDOMFormat || (mProtocolVersion == 0))
+ {
+ if ( !mName.isEmpty() )
+ result = mName + '=';
+ result += mValue;
+ }
+ else
+ {
+ result = mName + '=' + mValue;
+ if (mExplicitPath)
+ result += L1("; $Path=\"") + mPath + L1("\"");
+ if (!mDomain.isEmpty())
+ result += L1("; $Domain=\"") + mDomain + L1("\"");
+ }
+ return result;
+}
+
+//
+// Returns whether this cookie should be send to this location.
+bool KHttpCookie::match(const TQString &fqdn, const TQStringList &domains,
+ const TQString &path)
+{
+ // Cookie domain match check
+ if (mDomain.isEmpty())
+ {
+ if (fqdn != mHost)
+ return false;
+ }
+ else if (!domains.contains(mDomain))
+ {
+ if (mDomain[0] == '.')
+ return false;
+
+ // Maybe the domain needs an extra dot.
+ TQString domain = '.' + mDomain;
+ if ( !domains.contains( domain ) )
+ if ( fqdn != mDomain )
+ return false;
+ }
+
+ // Cookie path match check
+ if (mPath.isEmpty())
+ return true;
+
+ // According to the netscape spec both http://www.acme.com/foobar,
+ // http://www.acme.com/foo.bar and http://www.acme.com/foo/bar
+ // match http://www.acme.com/foo.
+ // We only match http://www.acme.com/foo/bar
+
+ if( path.startsWith(mPath) &&
+ (
+ (path.length() == mPath.length() ) || // Paths are exact match
+ (path[mPath.length()-1] == '/') || // mPath ended with a slash
+ (path[mPath.length()] == '/') // A slash follows.
+ ))
+ return true; // Path of URL starts with cookie-path
+
+ return false;
+}
+
+// KHttpCookieList
+///////////////////////////////////////////////////////////////////////////
+
+int KHttpCookieList::compareItems( void * item1, void * item2)
+{
+ int pathLen1 = ((KHttpCookie *)item1)->path().length();
+ int pathLen2 = ((KHttpCookie *)item2)->path().length();
+ if (pathLen1 > pathLen2)
+ return -1;
+ if (pathLen1 < pathLen2)
+ return 1;
+ return 0;
+}
+
+
+// KCookieJar
+///////////////////////////////////////////////////////////////////////////
+
+//
+// Constructs a new cookie jar
+//
+// One jar should be enough for all cookies.
+//
+KCookieJar::KCookieJar()
+{
+ m_cookieDomains.setAutoDelete( true );
+ m_globalAdvice = KCookieDunno;
+ m_configChanged = false;
+ m_cookiesChanged = false;
+
+ TDEConfig cfg("tdehtml/domain_info", true, false, "data");
+ TQStringList countries = cfg.readListEntry("twoLevelTLD");
+ for(TQStringList::ConstIterator it = countries.begin();
+ it != countries.end(); ++it)
+ {
+ m_twoLevelTLD.replace(*it, (int *) 1);
+ }
+}
+
+//
+// Destructs the cookie jar
+//
+// Poor little cookies, they will all be eaten by the cookie monster!
+//
+KCookieJar::~KCookieJar()
+{
+ // Not much to do here
+}
+
+static void removeDuplicateFromList(KHttpCookieList *list, KHttpCookie *cookiePtr, bool nameMatchOnly=false, bool updateWindowId=false)
+{
+ TQString domain1 = cookiePtr->domain();
+ if (domain1.isEmpty())
+ domain1 = cookiePtr->host();
+
+ for ( KHttpCookiePtr cookie=list->first(); cookie != 0; )
+ {
+ TQString domain2 = cookie->domain();
+ if (domain2.isEmpty())
+ domain2 = cookie->host();
+
+ if (
+ (cookiePtr->name() == cookie->name()) &&
+ (
+ nameMatchOnly ||
+ ( (domain1 == domain2) && (cookiePtr->path() == cookie->path()) )
+ )
+ )
+ {
+ if (updateWindowId)
+ {
+ for(TQValueList<long>::ConstIterator it = cookie->windowIds().begin();
+ it != cookie->windowIds().end(); ++it)
+ {
+ long windowId = *it;
+ if (windowId && (cookiePtr->windowIds().find(windowId) == cookiePtr->windowIds().end()))
+ {
+ cookiePtr->windowIds().append(windowId);
+ }
+ }
+ }
+ KHttpCookiePtr old_cookie = cookie;
+ cookie = list->next();
+ list->removeRef( old_cookie );
+ break;
+ }
+ else
+ {
+ cookie = list->next();
+ }
+ }
+}
+
+
+//
+// Looks for cookies in the cookie jar which are appropriate for _url.
+// Returned is a string containing all appropriate cookies in a format
+// which can be added to a HTTP-header without any additional processing.
+//
+TQString KCookieJar::findCookies(const TQString &_url, bool useDOMFormat, long windowId, KHttpCookieList *pendingCookies)
+{
+ TQString cookieStr;
+ TQStringList domains;
+ TQString fqdn;
+ TQString path;
+ KHttpCookiePtr cookie;
+ KCookieAdvice advice = m_globalAdvice;
+
+ if (!parseURL(_url, fqdn, path))
+ return cookieStr;
+
+ bool secureRequest = (_url.find( L1("https://"), 0, false) == 0 ||
+ _url.find( L1("webdavs://"), 0, false) == 0);
+
+ // kdDebug(7104) << "findCookies: URL= " << _url << ", secure = " << secureRequest << endl;
+
+ extractDomains(fqdn, domains);
+
+ KHttpCookieList allCookies;
+
+ for(TQStringList::ConstIterator it = domains.begin();
+ true;
+ ++it)
+ {
+ KHttpCookieList *cookieList;
+ if (it == domains.end())
+ {
+ cookieList = pendingCookies; // Add pending cookies
+ pendingCookies = 0;
+ if (!cookieList)
+ break;
+ }
+ else
+ {
+ TQString key = (*it).isNull() ? L1("") : (*it);
+ cookieList = m_cookieDomains[key];
+ if (!cookieList)
+ continue; // No cookies for this domain
+ }
+
+ if (cookieList->getAdvice() != KCookieDunno)
+ advice = cookieList->getAdvice();
+
+ for ( cookie=cookieList->first(); cookie != 0; cookie=cookieList->next() )
+ {
+ // If the we are setup to automatically accept all session cookies and to
+ // treat all cookies as session cookies or the current cookie is a session
+ // cookie, then send the cookie back regardless of either policy.
+ if (advice == KCookieReject &&
+ !(m_autoAcceptSessionCookies &&
+ (m_ignoreCookieExpirationDate || cookie->expireDate() == 0)))
+ continue;
+
+ if (!cookie->match(fqdn, domains, path))
+ continue;
+
+ if( cookie->isSecure() && !secureRequest )
+ continue;
+
+ if( cookie->isHttpOnly() && useDOMFormat )
+ continue;
+
+ // Do not send expired cookies.
+ if ( cookie->isExpired (time(0)) )
+ {
+ // Note there is no need to actually delete the cookie here
+ // since the cookieserver will invoke ::saveCookieJar because
+ // of the state change below. This will then do the job of
+ // deleting the cookie for us.
+ m_cookiesChanged = true;
+ continue;
+ }
+
+ if (windowId && (cookie->windowIds().find(windowId) == cookie->windowIds().end()))
+ {
+ cookie->windowIds().append(windowId);
+ }
+
+ if (it == domains.end()) // Only needed when processing pending cookies
+ removeDuplicateFromList(&allCookies, cookie);
+
+ allCookies.append(cookie);
+ }
+ if (it == domains.end())
+ break; // Finished.
+ }
+
+ int cookieCount = 0;
+
+ int protVersion=0;
+ for ( cookie=allCookies.first(); cookie != 0; cookie=allCookies.next() )
+ {
+ if (cookie->protocolVersion() > protVersion)
+ protVersion = cookie->protocolVersion();
+ }
+
+ for ( cookie=allCookies.first(); cookie != 0; cookie=allCookies.next() )
+ {
+ if (useDOMFormat)
+ {
+ if (cookieCount > 0)
+ cookieStr += L1("; ");
+ cookieStr += cookie->cookieStr(true);
+ }
+ else
+ {
+ if (cookieCount == 0)
+ {
+ cookieStr += L1("Cookie: ");
+ if (protVersion > 0)
+ {
+ TQString version;
+ version.sprintf("$Version=%d; ", protVersion); // Without quotes
+ cookieStr += version;
+ }
+ }
+ else
+ {
+ cookieStr += L1("; ");
+ }
+ cookieStr += cookie->cookieStr(false);
+ }
+ cookieCount++;
+ }
+
+ return cookieStr;
+}
+
+//
+// This function parses a string like 'my_name="my_value";' and returns
+// 'my_name' in Name and 'my_value' in Value.
+//
+// A pointer to the end of the parsed part is returned.
+// This pointer points either to:
+// '\0' - The end of the string has reached.
+// ';' - Another my_name="my_value" pair follows
+// ',' - Another cookie follows
+// '\n' - Another header follows
+static const char * parseNameValue(const char *header,
+ TQString &Name,
+ TQString &Value,
+ bool keepQuotes=false,
+ bool rfcQuotes=false)
+{
+ const char *s = header;
+ // Parse 'my_name' part
+ for(; (*s != '='); s++)
+ {
+ if ((*s=='\0') || (*s==';') || (*s=='\n'))
+ {
+ // No '=' sign -> use string as the value, name is empty
+ // (behavior found in Mozilla and IE)
+ Name = "";
+ Value = TQString::fromLatin1(header);
+ Value.truncate( s - header );
+ Value = Value.stripWhiteSpace();
+ return (s);
+ }
+ }
+
+ Name = header;
+ Name.truncate( s - header );
+ Name = Name.stripWhiteSpace();
+
+ // *s == '='
+ s++;
+
+ // Skip any whitespace
+ for(; (*s == ' ') || (*s == '\t'); s++)
+ {
+ if ((*s=='\0') || (*s==';') || (*s=='\n'))
+ {
+ // End of Name
+ Value = "";
+ return (s);
+ }
+ }
+
+ if ((rfcQuotes || !keepQuotes) && (*s == '\"'))
+ {
+ // Parse '"my_value"' part (quoted value)
+ if (keepQuotes)
+ header = s++;
+ else
+ header = ++s; // skip "
+ for(;(*s != '\"');s++)
+ {
+ if ((*s=='\0') || (*s=='\n'))
+ {
+ // End of Name
+ Value = TQString::fromLatin1(header);
+ Value.truncate(s - header);
+ return (s);
+ }
+ }
+ Value = TQString::fromLatin1(header);
+ // *s == '\"';
+ if (keepQuotes)
+ Value.truncate( ++s - header );
+ else
+ Value.truncate( s++ - header );
+
+ // Skip any remaining garbage
+ for(;; s++)
+ {
+ if ((*s=='\0') || (*s==';') || (*s=='\n'))
+ break;
+ }
+ }
+ else
+ {
+ // Parse 'my_value' part (unquoted value)
+ header = s;
+ while ((*s != '\0') && (*s != ';') && (*s != '\n'))
+ s++;
+ // End of Name
+ Value = TQString::fromLatin1(header);
+ Value.truncate( s - header );
+ Value = Value.stripWhiteSpace();
+ }
+ return (s);
+
+}
+
+void KCookieJar::stripDomain(const TQString &_fqdn, TQString &_domain)
+{
+ TQStringList domains;
+ extractDomains(_fqdn, domains);
+ if (domains.count() > 3)
+ _domain = domains[3];
+ else
+ _domain = domains[0];
+}
+
+TQString KCookieJar::stripDomain( KHttpCookiePtr cookiePtr)
+{
+ TQString domain; // We file the cookie under this domain.
+ if (cookiePtr->domain().isEmpty())
+ stripDomain( cookiePtr->host(), domain);
+ else
+ stripDomain (cookiePtr->domain(), domain);
+ return domain;
+}
+
+bool KCookieJar::parseURL(const TQString &_url,
+ TQString &_fqdn,
+ TQString &_path)
+{
+ KURL kurl(_url);
+ if (!kurl.isValid())
+ return false;
+
+ _fqdn = kurl.host().lower();
+ if (kurl.port())
+ {
+ if (((kurl.protocol() == L1("http")) && (kurl.port() != 80)) ||
+ ((kurl.protocol() == L1("https")) && (kurl.port() != 443)))
+ {
+ _fqdn = L1("%1:%2").arg(kurl.port()).arg(_fqdn);
+ }
+ }
+
+ // Cookie spoofing protection. Since there is no way a path separator
+ // or escape encoded character is allowed in the hostname according
+ // to RFC 2396, reject attempts to include such things there!
+ if(_fqdn.find('/') > -1 || _fqdn.find('%') > -1)
+ {
+ return false; // deny everything!!
+ }
+
+ _path = kurl.path();
+ if (_path.isEmpty())
+ _path = L1("/");
+
+ TQRegExp exp(L1("[\\\\/]\\.\\.[\\\\/]"));
+ // Weird path, cookie stealing attempt?
+ if (exp.search(_path) != -1)
+ return false; // Deny everything!!
+
+ return true;
+}
+
+void KCookieJar::extractDomains(const TQString &_fqdn,
+ TQStringList &_domains)
+{
+ // Return numeric IPv6 addresses as is...
+ if (_fqdn[0] == '[')
+ {
+ _domains.append( _fqdn );
+ return;
+ }
+ // Return numeric IPv4 addresses as is...
+ if ((_fqdn.at(0) >= TQChar('0')) && (_fqdn.at(0) <= TQChar('9')))
+ {
+ if (_fqdn.find(TQRegExp(IP_ADDRESS_EXPRESSION)) > -1)
+ {
+ _domains.append( _fqdn );
+ return;
+ }
+ }
+
+ TQStringList partList = TQStringList::split('.', _fqdn, false);
+
+ if (partList.count())
+ partList.remove(partList.begin()); // Remove hostname
+
+ while(partList.count())
+ {
+
+ if (partList.count() == 1)
+ break; // We only have a TLD left.
+
+ if ((partList.count() == 2) && (m_twoLevelTLD[partList[1].lower()]))
+ {
+ // This domain uses two-level TLDs in the form xxxx.yy
+ break;
+ }
+
+ if ((partList.count() == 2) && (partList[1].length() == 2))
+ {
+ // If this is a TLD, we should stop. (e.g. co.uk)
+ // We assume this is a TLD if it ends with .xx.yy or .x.yy
+ if (partList[0].length() <= 2)
+ break; // This is a TLD.
+
+ // Catch some TLDs that we miss with the previous check
+ // e.g. com.au, org.uk, mil.co
+ TQCString t = partList[0].lower().utf8();
+ if ((t == "com") || (t == "net") || (t == "org") || (t == "gov") || (t == "edu") || (t == "mil") || (t == "int"))
+ break;
+ }
+
+ TQString domain = partList.join(L1("."));
+ _domains.append(domain);
+ _domains.append('.' + domain);
+ partList.remove(partList.begin()); // Remove part
+ }
+
+ // Always add the FQDN at the start of the list for
+ // hostname == cookie-domainname checks!
+ _domains.prepend( '.' + _fqdn );
+ _domains.prepend( _fqdn );
+}
+
+
+/*
+ Changes dates in from the following format
+
+ Wed Sep 12 07:00:00 2007 GMT
+ to
+ Wed Sep 12 2007 07:00:00 GMT
+
+ to allow KRFCDate::parseDate to properly parse expiration date formats
+ used in cookies by some servers such as amazon.com. See BR# 145244.
+*/
+static TQString fixupDateTime(const TQString& dt)
+{
+ const int index = dt.find(TQRegExp("[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}"));
+
+ if (index > -1)
+ {
+ TQStringList dateStrList = TQStringList::split(' ', dt.mid(index));
+ if (dateStrList.count() > 1)
+ {
+ TQString date = dateStrList[0];
+ dateStrList[0] = dateStrList[1];
+ dateStrList[1] = date;
+ date = dt;
+ return date.replace(index, date.length(), dateStrList.join(" "));
+ }
+ }
+
+ return dt;
+}
+
+//
+// This function parses cookie_headers and returns a linked list of
+// KHttpCookie objects for all cookies found in cookie_headers.
+// If no cookies could be found 0 is returned.
+//
+// cookie_headers should be a concatenation of all lines of a HTTP-header
+// which start with "Set-Cookie". The lines should be separated by '\n's.
+//
+KHttpCookieList KCookieJar::makeCookies(const TQString &_url,
+ const TQCString &cookie_headers,
+ long windowId)
+{
+ KHttpCookieList cookieList;
+ KHttpCookieList cookieList2;
+ KHttpCookiePtr lastCookie = 0;
+ const char *cookieStr = cookie_headers.data();
+ TQString Name;
+ TQString Value;
+ TQString fqdn;
+ TQString path;
+ bool crossDomain = false;
+
+ if (!parseURL(_url, fqdn, path))
+ {
+ // Error parsing _url
+ return KHttpCookieList();
+ }
+ TQString defaultPath;
+ int i = path.findRev('/');
+ if (i > 0)
+ defaultPath = path.left(i);
+
+ // The hard stuff :)
+ for(;;)
+ {
+ // check for "Set-Cookie"
+ if (strncmp(cookieStr, "Cross-Domain\n", 13) == 0)
+ {
+ cookieStr += 13;
+ crossDomain = true;
+ }
+ else if (strncasecmp(cookieStr, "Set-Cookie:", 11) == 0)
+ {
+ cookieStr = parseNameValue(cookieStr+11, Name, Value, true);
+
+ // Host = FQDN
+ // Default domain = ""
+ // Default path according to rfc2109
+
+ KHttpCookie *cookie = new KHttpCookie(fqdn, L1(""), defaultPath, Name, Value);
+ if (windowId)
+ cookie->mWindowIds.append(windowId);
+ cookie->mCrossDomain = crossDomain;
+
+ // Insert cookie in chain
+ cookieList.append(cookie);
+ lastCookie = cookie;
+ }
+ else if (strncasecmp(cookieStr, "Set-Cookie2:", 12) == 0)
+ {
+ // Attempt to follow rfc2965
+ cookieStr = parseNameValue(cookieStr+12, Name, Value, true, true);
+
+ // Host = FQDN
+ // Default domain = ""
+ // Default path according to rfc2965
+
+ KHttpCookie *cookie = new KHttpCookie(fqdn, L1(""), defaultPath, Name, Value);
+ if (windowId)
+ cookie->mWindowIds.append(windowId);
+ cookie->mCrossDomain = crossDomain;
+
+ // Insert cookie in chain
+ cookieList2.append(cookie);
+ lastCookie = cookie;
+ }
+ else
+ {
+ // This is not the start of a cookie header, skip till next line.
+ while (*cookieStr && *cookieStr != '\n')
+ cookieStr++;
+
+ if (*cookieStr == '\n')
+ cookieStr++;
+
+ if (!*cookieStr)
+ break; // End of cookie_headers
+ else
+ continue; // end of this header, continue with next.
+ }
+
+ while ((*cookieStr == ';') || (*cookieStr == ' '))
+ {
+ cookieStr++;
+
+ // Name-Value pair follows
+ cookieStr = parseNameValue(cookieStr, Name, Value);
+
+ TQCString cName = Name.lower().latin1();
+ if (cName == "domain")
+ {
+ TQString dom = Value.lower();
+ // RFC2965 3.2.2: If an explicitly specified value does not
+ // start with a dot, the user agent supplies a leading dot
+ if(dom.length() && dom[0] != '.')
+ dom.prepend(".");
+ // remove a trailing dot
+ if(dom.length() > 2 && dom[dom.length()-1] == '.')
+ dom = dom.left(dom.length()-1);
+
+ if(dom.contains('.') > 1 || dom == ".local")
+ lastCookie->mDomain = dom;
+ }
+ else if (cName == "max-age")
+ {
+ int max_age = Value.toInt();
+ if (max_age == 0)
+ lastCookie->mExpireDate = 1;
+ else
+ lastCookie->mExpireDate = time(0)+max_age;
+ }
+ else if (cName == "expires")
+ {
+ // Parse brain-dead netscape cookie-format
+ lastCookie->mExpireDate = KRFCDate::parseDate(Value);
+
+ // Workaround for servers that send the expiration date in
+ // 'Wed Sep 12 07:00:00 2007 GMT' format. See BR# 145244.
+ if (lastCookie->mExpireDate == 0)
+ lastCookie->mExpireDate = KRFCDate::parseDate(fixupDateTime(Value));
+ }
+ else if (cName == "path")
+ {
+ if (Value.isEmpty())
+ lastCookie->mPath = TQString::null; // Catch "" <> TQString::null
+ else
+ lastCookie->mPath = KURL::decode_string(Value);
+ lastCookie->mExplicitPath = true;
+ }
+ else if (cName == "version")
+ {
+ lastCookie->mProtocolVersion = Value.toInt();
+ }
+ else if ((cName == "secure") ||
+ (cName.isEmpty() && Value.lower() == L1("secure")))
+ {
+ lastCookie->mSecure = true;
+ }
+ else if ((cName == "httponly") ||
+ (cName.isEmpty() && Value.lower() == L1("httponly")))
+ {
+ lastCookie->mHttpOnly = true;
+ }
+ }
+
+ if (*cookieStr == '\0')
+ break; // End of header
+
+ // Skip ';' or '\n'
+ cookieStr++;
+ }
+
+ // RFC2965 cookies come last so that they override netscape cookies.
+ while( !cookieList2.isEmpty() && (lastCookie = cookieList2.take(0)) )
+ {
+ removeDuplicateFromList(&cookieList, lastCookie, true);
+ cookieList.append(lastCookie);
+ }
+
+ return cookieList;
+}
+
+/**
+* Parses cookie_domstr and returns a linked list of KHttpCookie objects.
+* cookie_domstr should be a semicolon-delimited list of "name=value"
+* pairs. Any whitespace before "name" or around '=' is discarded.
+* If no cookies are found, 0 is returned.
+*/
+KHttpCookieList KCookieJar::makeDOMCookies(const TQString &_url,
+ const TQCString &cookie_domstring,
+ long windowId)
+{
+ // A lot copied from above
+ KHttpCookieList cookieList;
+ KHttpCookiePtr lastCookie = 0;
+
+ const char *cookieStr = cookie_domstring.data();
+ TQString Name;
+ TQString Value;
+ TQString fqdn;
+ TQString path;
+
+ if (!parseURL(_url, fqdn, path))
+ {
+ // Error parsing _url
+ return KHttpCookieList();
+ }
+
+ // This time it's easy
+ while(*cookieStr)
+ {
+ cookieStr = parseNameValue(cookieStr, Name, Value);
+
+ // Host = FQDN
+ // Default domain = ""
+ // Default path = ""
+ KHttpCookie *cookie = new KHttpCookie(fqdn, TQString::null, TQString::null,
+ Name, Value );
+ if (windowId)
+ cookie->mWindowIds.append(windowId);
+
+ cookieList.append(cookie);
+ lastCookie = cookie;
+
+ if (*cookieStr != '\0')
+ cookieStr++; // Skip ';' or '\n'
+ }
+
+ return cookieList;
+}
+
+#ifdef MAX_COOKIE_LIMIT
+static void makeRoom(KHttpCookieList *cookieList, KHttpCookiePtr &cookiePtr)
+{
+ // Too much cookies: throw one away, try to be somewhat clever
+ KHttpCookiePtr lastCookie = 0;
+ for(KHttpCookiePtr cookie = cookieList->first(); cookie; cookie = cookieList->next())
+ {
+ if (cookieList->compareItems(cookie, cookiePtr) < 0)
+ break;
+ lastCookie = cookie;
+ }
+ if (!lastCookie)
+ lastCookie = cookieList->first();
+ cookieList->removeRef(lastCookie);
+}
+#endif
+
+//
+// This function hands a KHttpCookie object over to the cookie jar.
+//
+// On return cookiePtr is set to 0.
+//
+void KCookieJar::addCookie(KHttpCookiePtr &cookiePtr)
+{
+ TQStringList domains;
+ KHttpCookieList *cookieList = 0L;
+
+ // We always need to do this to make sure that the
+ // that cookies of type hostname == cookie-domainname
+ // are properly removed and/or updated as necessary!
+ extractDomains( cookiePtr->host(), domains );
+ for ( TQStringList::ConstIterator it = domains.begin();
+ (it != domains.end() && !cookieList);
+ ++it )
+ {
+ TQString key = (*it).isNull() ? L1("") : (*it);
+ KHttpCookieList *list= m_cookieDomains[key];
+ if ( !list ) continue;
+
+ removeDuplicateFromList(list, cookiePtr, false, true);
+ }
+
+ TQString domain = stripDomain( cookiePtr );
+ TQString key = domain.isNull() ? L1("") : domain;
+ cookieList = m_cookieDomains[ key ];
+ if (!cookieList)
+ {
+ // Make a new cookie list
+ cookieList = new KHttpCookieList();
+ cookieList->setAutoDelete(true);
+
+ // All cookies whose domain is not already
+ // known to us should be added with KCookieDunno.
+ // KCookieDunno means that we use the global policy.
+ cookieList->setAdvice( KCookieDunno );
+
+ m_cookieDomains.insert( domain, cookieList);
+
+ // Update the list of domains
+ m_domainList.append(domain);
+ }
+
+ // Add the cookie to the cookie list
+ // The cookie list is sorted 'longest path first'
+ if (!cookiePtr->isExpired(time(0)))
+ {
+#ifdef MAX_COOKIE_LIMIT
+ if (cookieList->count() >= MAX_COOKIES_PER_HOST)
+ makeRoom(cookieList, cookiePtr); // Delete a cookie
+#endif
+ cookieList->inSort( cookiePtr );
+ m_cookiesChanged = true;
+ }
+ else
+ {
+ delete cookiePtr;
+ }
+ cookiePtr = 0;
+}
+
+//
+// This function advices whether a single KHttpCookie object should
+// be added to the cookie jar.
+//
+KCookieAdvice KCookieJar::cookieAdvice(KHttpCookiePtr cookiePtr)
+{
+ if (m_rejectCrossDomainCookies && cookiePtr->isCrossDomain())
+ return KCookieReject;
+
+ TQStringList domains;
+
+ extractDomains(cookiePtr->host(), domains);
+
+ // If the cookie specifies a domain, check whether it is valid. Otherwise,
+ // accept the cookie anyways but remove the domain="" value to prevent
+ // cross-site cookie injection.
+ if (!cookiePtr->domain().isEmpty())
+ {
+ if (!domains.contains(cookiePtr->domain()) &&
+ !cookiePtr->domain().endsWith("."+cookiePtr->host()))
+ cookiePtr->fixDomain(TQString::null);
+ }
+
+ if (m_autoAcceptSessionCookies && (cookiePtr->expireDate() == 0 ||
+ m_ignoreCookieExpirationDate))
+ return KCookieAccept;
+
+ KCookieAdvice advice = KCookieDunno;
+ bool isFQDN = true; // First is FQDN
+ TQStringList::Iterator it = domains.begin(); // Start with FQDN which first in the list.
+ while( (advice == KCookieDunno) && (it != domains.end()))
+ {
+ TQString domain = *it;
+ // Check if a policy for the FQDN/domain is set.
+ if ( domain[0] == '.' || isFQDN )
+ {
+ isFQDN = false;
+ KHttpCookieList *cookieList = m_cookieDomains[domain];
+ if (cookieList)
+ advice = cookieList->getAdvice();
+ }
+ domains.remove(it);
+ it = domains.begin(); // Continue from begin of remaining list
+ }
+
+ if (advice == KCookieDunno)
+ advice = m_globalAdvice;
+
+ return advice;
+}
+
+//
+// This function gets the advice for all cookies originating from
+// _domain.
+//
+KCookieAdvice KCookieJar::getDomainAdvice(const TQString &_domain)
+{
+ KHttpCookieList *cookieList = m_cookieDomains[_domain];
+ KCookieAdvice advice;
+
+ if (cookieList)
+ {
+ advice = cookieList->getAdvice();
+ }
+ else
+ {
+ advice = KCookieDunno;
+ }
+
+ return advice;
+}
+
+//
+// This function sets the advice for all cookies originating from
+// _domain.
+//
+void KCookieJar::setDomainAdvice(const TQString &_domain, KCookieAdvice _advice)
+{
+ TQString domain(_domain);
+ KHttpCookieList *cookieList = m_cookieDomains[domain];
+
+ if (cookieList)
+ {
+ if (cookieList->getAdvice() != _advice)
+ {
+ m_configChanged = true;
+ // domain is already known
+ cookieList->setAdvice( _advice);
+ }
+
+ if ((cookieList->isEmpty()) &&
+ (_advice == KCookieDunno))
+ {
+ // This deletes cookieList!
+ m_cookieDomains.remove(domain);
+ m_domainList.remove(domain);
+ }
+ }
+ else
+ {
+ // domain is not yet known
+ if (_advice != KCookieDunno)
+ {
+ // We should create a domain entry
+ m_configChanged = true;
+ // Make a new cookie list
+ cookieList = new KHttpCookieList();
+ cookieList->setAutoDelete(true);
+ cookieList->setAdvice( _advice);
+ m_cookieDomains.insert( domain, cookieList);
+ // Update the list of domains
+ m_domainList.append( domain);
+ }
+ }
+}
+
+//
+// This function sets the advice for all cookies originating from
+// the same domain as _cookie
+//
+void KCookieJar::setDomainAdvice(KHttpCookiePtr cookiePtr, KCookieAdvice _advice)
+{
+ TQString domain;
+ stripDomain(cookiePtr->host(), domain); // We file the cookie under this domain.
+
+ setDomainAdvice(domain, _advice);
+}
+
+//
+// This function sets the global advice for cookies
+//
+void KCookieJar::setGlobalAdvice(KCookieAdvice _advice)
+{
+ if (m_globalAdvice != _advice)
+ m_configChanged = true;
+ m_globalAdvice = _advice;
+}
+
+//
+// Get a list of all domains known to the cookie jar.
+//
+const TQStringList& KCookieJar::getDomainList()
+{
+ return m_domainList;
+}
+
+//
+// Get a list of all cookies in the cookie jar originating from _domain.
+//
+const KHttpCookieList *KCookieJar::getCookieList(const TQString & _domain,
+ const TQString & _fqdn )
+{
+ TQString domain;
+
+ if (_domain.isEmpty())
+ stripDomain( _fqdn, domain );
+ else
+ domain = _domain;
+
+ return m_cookieDomains[domain];
+}
+
+//
+// Eat a cookie out of the jar.
+// cookiePtr should be one of the cookies returned by getCookieList()
+//
+void KCookieJar::eatCookie(KHttpCookiePtr cookiePtr)
+{
+ TQString domain = stripDomain(cookiePtr); // We file the cookie under this domain.
+ KHttpCookieList *cookieList = m_cookieDomains[domain];
+
+ if (cookieList)
+ {
+ // This deletes cookiePtr!
+ if (cookieList->removeRef( cookiePtr ))
+ m_cookiesChanged = true;
+
+ if ((cookieList->isEmpty()) &&
+ (cookieList->getAdvice() == KCookieDunno))
+ {
+ // This deletes cookieList!
+ m_cookieDomains.remove(domain);
+
+ m_domainList.remove(domain);
+ }
+ }
+}
+
+void KCookieJar::eatCookiesForDomain(const TQString &domain)
+{
+ KHttpCookieList *cookieList = m_cookieDomains[domain];
+ if (!cookieList || cookieList->isEmpty()) return;
+
+ cookieList->clear();
+ if (cookieList->getAdvice() == KCookieDunno)
+ {
+ // This deletes cookieList!
+ m_cookieDomains.remove(domain);
+ m_domainList.remove(domain);
+ }
+ m_cookiesChanged = true;
+}
+
+void KCookieJar::eatSessionCookies( long windowId )
+{
+ if (!windowId)
+ return;
+
+ TQStringList::Iterator it=m_domainList.begin();
+ for ( ; it != m_domainList.end(); ++it )
+ eatSessionCookies( *it, windowId, false );
+}
+
+void KCookieJar::eatAllCookies()
+{
+ for ( TQStringList::Iterator it=m_domainList.begin();
+ it != m_domainList.end();)
+ {
+ TQString domain = *it++;
+ // This might remove domain from domainList!
+ eatCookiesForDomain(domain);
+ }
+}
+
+void KCookieJar::eatSessionCookies( const TQString& fqdn, long windowId,
+ bool isFQDN )
+{
+ KHttpCookieList* cookieList;
+ if ( !isFQDN )
+ cookieList = m_cookieDomains[fqdn];
+ else
+ {
+ TQString domain;
+ stripDomain( fqdn, domain );
+ cookieList = m_cookieDomains[domain];
+ }
+
+ if ( cookieList )
+ {
+ KHttpCookiePtr cookie=cookieList->first();
+ for (; cookie != 0;)
+ {
+ if ((cookie->expireDate() != 0) && !m_ignoreCookieExpirationDate)
+ {
+ cookie = cookieList->next();
+ continue;
+ }
+
+ TQValueList<long> &ids = cookie->windowIds();
+ if (!ids.remove(windowId) || !ids.isEmpty())
+ {
+ cookie = cookieList->next();
+ continue;
+ }
+ KHttpCookiePtr old_cookie = cookie;
+ cookie = cookieList->next();
+ cookieList->removeRef( old_cookie );
+ }
+ }
+}
+
+//
+// Saves all cookies to the file '_filename'.
+// On succes 'true' is returned.
+// On failure 'false' is returned.
+bool KCookieJar::saveCookies(const TQString &_filename)
+{
+ KSaveFile saveFile(_filename, 0600);
+
+ if (saveFile.status() != 0)
+ return false;
+
+ FILE *fStream = saveFile.fstream();
+
+ time_t curTime = time(0);
+
+ fprintf(fStream, "# KDE Cookie File v2\n#\n");
+
+ fprintf(fStream, "%-20s %-20s %-12s %-10s %-4s %-20s %-4s %s\n",
+ "# Host", "Domain", "Path", "Exp.date", "Prot",
+ "Name", "Sec", "Value");
+
+ for ( TQStringList::Iterator it=m_domainList.begin(); it != m_domainList.end();
+ it++ )
+ {
+ const TQString &domain = *it;
+ bool domainPrinted = false;
+
+ KHttpCookieList *cookieList = m_cookieDomains[domain];
+ KHttpCookiePtr cookie=cookieList->last();
+
+ for (; cookie != 0;)
+ {
+ if (cookie->isExpired(curTime))
+ {
+ // Delete expired cookies
+ KHttpCookiePtr old_cookie = cookie;
+ cookie = cookieList->prev();
+ cookieList->removeRef( old_cookie );
+ }
+ else if (cookie->expireDate() != 0 && !m_ignoreCookieExpirationDate)
+ {
+ if (!domainPrinted)
+ {
+ domainPrinted = true;
+ fprintf(fStream, "[%s]\n", domain.local8Bit().data());
+ }
+ // Store persistent cookies
+ TQString path = L1("\"");
+ path += cookie->path();
+ path += '"';
+ TQString domain = L1("\"");
+ domain += cookie->domain();
+ domain += '"';
+ fprintf(fStream, "%-20s %-20s %-12s %10lu %3d %-20s %-4i %s\n",
+ cookie->host().latin1(), domain.latin1(),
+ path.latin1(), (unsigned long) cookie->expireDate(),
+ cookie->protocolVersion(),
+ cookie->name().isEmpty() ? cookie->value().latin1() : cookie->name().latin1(),
+ (cookie->isSecure() ? 1 : 0) + (cookie->isHttpOnly() ? 2 : 0) +
+ (cookie->hasExplicitPath() ? 4 : 0) + (cookie->name().isEmpty() ? 8 : 0),
+ cookie->value().latin1());
+ cookie = cookieList->prev();
+ }
+ else
+ {
+ // Skip session-only cookies
+ cookie = cookieList->prev();
+ }
+ }
+ }
+
+ return saveFile.close();
+}
+
+typedef char *charPtr;
+
+static const char *parseField(charPtr &buffer, bool keepQuotes=false)
+{
+ char *result;
+ if (!keepQuotes && (*buffer == '\"'))
+ {
+ // Find terminating "
+ buffer++;
+ result = buffer;
+ while((*buffer != '\"') && (*buffer))
+ buffer++;
+ }
+ else
+ {
+ // Find first white space
+ result = buffer;
+ while((*buffer != ' ') && (*buffer != '\t') && (*buffer != '\n') && (*buffer))
+ buffer++;
+ }
+
+ if (!*buffer)
+ return result; //
+ *buffer++ = '\0';
+
+ // Skip white-space
+ while((*buffer == ' ') || (*buffer == '\t') || (*buffer == '\n'))
+ buffer++;
+
+ return result;
+}
+
+
+//
+// Reloads all cookies from the file '_filename'.
+// On succes 'true' is returned.
+// On failure 'false' is returned.
+bool KCookieJar::loadCookies(const TQString &_filename)
+{
+ FILE *fStream = fopen( TQFile::encodeName(_filename), "r");
+ if (fStream == 0)
+ {
+ return false;
+ }
+
+ time_t curTime = time(0);
+
+ char *buffer = new char[READ_BUFFER_SIZE];
+
+ bool err = false;
+ err = (fgets(buffer, READ_BUFFER_SIZE, fStream) == 0);
+
+ int version = 1;
+ if (!err)
+ {
+ if (strcmp(buffer, "# KDE Cookie File\n") == 0)
+ {
+ // version 1
+ }
+ else if (sscanf(buffer, "# KDE Cookie File v%d\n", &version) != 1)
+ {
+ err = true;
+ }
+ }
+
+ if (!err)
+ {
+ while(fgets(buffer, READ_BUFFER_SIZE, fStream) != 0)
+ {
+ char *line = buffer;
+ // Skip lines which begin with '#' or '['
+ if ((line[0] == '#') || (line[0] == '['))
+ continue;
+
+ const char *host( parseField(line) );
+ const char *domain( parseField(line) );
+ const char *path( parseField(line) );
+ const char *expStr( parseField(line) );
+ if (!expStr) continue;
+ int expDate = (time_t) strtoul(expStr, 0, 10);
+ const char *verStr( parseField(line) );
+ if (!verStr) continue;
+ int protVer = (time_t) strtoul(verStr, 0, 10);
+ const char *name( parseField(line) );
+ bool keepQuotes = false;
+ bool secure = false;
+ bool httpOnly = false;
+ bool explicitPath = false;
+ const char *value = 0;
+ if ((version == 2) || (protVer >= 200))
+ {
+ if (protVer >= 200)
+ protVer -= 200;
+ int i = atoi( parseField(line) );
+ secure = i & 1;
+ httpOnly = i & 2;
+ explicitPath = i & 4;
+ if (i & 8)
+ name = "";
+ line[strlen(line)-1] = '\0'; // Strip LF.
+ value = line;
+ }
+ else
+ {
+ if (protVer >= 100)
+ {
+ protVer -= 100;
+ keepQuotes = true;
+ }
+ value = parseField(line, keepQuotes);
+ secure = atoi( parseField(line) );
+ }
+
+ // Parse error
+ if (!value) continue;
+
+ // Expired or parse error
+ if ((expDate == 0) || (expDate < curTime))
+ continue;
+
+ KHttpCookie *cookie = new KHttpCookie(TQString::fromLatin1(host),
+ TQString::fromLatin1(domain),
+ TQString::fromLatin1(path),
+ TQString::fromLatin1(name),
+ TQString::fromLatin1(value),
+ expDate, protVer,
+ secure, httpOnly, explicitPath);
+ addCookie(cookie);
+ }
+ }
+ delete [] buffer;
+ m_cookiesChanged = false;
+
+ fclose( fStream);
+ return err;
+}
+
+//
+// Save the cookie configuration
+//
+
+void KCookieJar::saveConfig(TDEConfig *_config)
+{
+ if (!m_configChanged)
+ return;
+
+ _config->setGroup("Cookie Dialog");
+ _config->writeEntry("PreferredPolicy", m_preferredPolicy);
+ _config->writeEntry("ShowCookieDetails", m_showCookieDetails );
+ _config->setGroup("Cookie Policy");
+ _config->writeEntry("CookieGlobalAdvice", adviceToStr( m_globalAdvice));
+
+ TQStringList domainSettings;
+ for ( TQStringList::Iterator it=m_domainList.begin();
+ it != m_domainList.end();
+ it++ )
+ {
+ const TQString &domain = *it;
+ KCookieAdvice advice = getDomainAdvice( domain);
+ if (advice != KCookieDunno)
+ {
+ TQString value(domain);
+ value += ':';
+ value += adviceToStr(advice);
+ domainSettings.append(value);
+ }
+ }
+ _config->writeEntry("CookieDomainAdvice", domainSettings);
+ _config->sync();
+ m_configChanged = false;
+}
+
+
+//
+// Load the cookie configuration
+//
+
+void KCookieJar::loadConfig(TDEConfig *_config, bool reparse )
+{
+ if ( reparse )
+ _config->reparseConfiguration();
+
+ _config->setGroup("Cookie Dialog");
+ m_showCookieDetails = _config->readBoolEntry( "ShowCookieDetails" );
+ m_preferredPolicy = _config->readNumEntry( "PreferredPolicy", 0 );
+
+ _config->setGroup("Cookie Policy");
+ TQStringList domainSettings = _config->readListEntry("CookieDomainAdvice");
+ m_rejectCrossDomainCookies = _config->readBoolEntry( "RejectCrossDomainCookies", true );
+ m_autoAcceptSessionCookies = _config->readBoolEntry( "AcceptSessionCookies", true );
+ m_ignoreCookieExpirationDate = _config->readBoolEntry( "IgnoreExpirationDate", false );
+ TQString value = _config->readEntry("CookieGlobalAdvice", L1("Ask"));
+ m_globalAdvice = strToAdvice(value);
+
+ // Reset current domain settings first.
+ for ( TQStringList::Iterator it=m_domainList.begin(); it != m_domainList.end(); )
+ {
+ // Make sure to update iterator before calling setDomainAdvice()
+ // setDomainAdvice() might delete the domain from domainList.
+ TQString domain = *it++;
+ setDomainAdvice(domain, KCookieDunno);
+ }
+
+ // Now apply the domain settings read from config file...
+ for ( TQStringList::Iterator it=domainSettings.begin();
+ it != domainSettings.end(); )
+ {
+ const TQString &value = *it++;
+
+ int sepPos = value.findRev(':');
+
+ if (sepPos <= 0)
+ continue;
+
+ TQString domain(value.left(sepPos));
+ KCookieAdvice advice = strToAdvice( value.mid(sepPos + 1) );
+ setDomainAdvice(domain, advice);
+ }
+}
diff --git a/kioslave/http/kcookiejar/kcookiejar.desktop b/tdeioslave/http/kcookiejar/kcookiejar.desktop
index ebc76e2f8..ebc76e2f8 100644
--- a/kioslave/http/kcookiejar/kcookiejar.desktop
+++ b/tdeioslave/http/kcookiejar/kcookiejar.desktop
diff --git a/kioslave/http/kcookiejar/kcookiejar.h b/tdeioslave/http/kcookiejar/kcookiejar.h
index bb16d75d3..bb16d75d3 100644
--- a/kioslave/http/kcookiejar/kcookiejar.h
+++ b/tdeioslave/http/kcookiejar/kcookiejar.h
diff --git a/kioslave/http/kcookiejar/kcookiescfg.upd b/tdeioslave/http/kcookiejar/kcookiescfg.upd
index 0ff26bde0..0ff26bde0 100644
--- a/kioslave/http/kcookiejar/kcookiescfg.upd
+++ b/tdeioslave/http/kcookiejar/kcookiescfg.upd
diff --git a/tdeioslave/http/kcookiejar/kcookieserver.cpp b/tdeioslave/http/kcookiejar/kcookieserver.cpp
new file mode 100644
index 000000000..ceb1df57f
--- /dev/null
+++ b/tdeioslave/http/kcookiejar/kcookieserver.cpp
@@ -0,0 +1,606 @@
+/*
+This file is part of KDE
+
+ Copyright (C) 1998-2000 Waldo Bastian (bastian@kde.org)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+//----------------------------------------------------------------------------
+//
+// KDE Cookie Server
+// $Id$
+
+#define SAVE_DELAY 3 // Save after 3 minutes
+
+#include <unistd.h>
+
+#include <tqtimer.h>
+#include <tqptrlist.h>
+#include <tqfile.h>
+
+#include <dcopclient.h>
+
+#include <tdeconfig.h>
+#include <kdebug.h>
+#include <kapplication.h>
+#include <kcmdlineargs.h>
+#include <kstandarddirs.h>
+
+#include "kcookiejar.h"
+#include "kcookiewin.h"
+#include "kcookieserver.h"
+
+extern "C" {
+ KDE_EXPORT KDEDModule *create_kcookiejar(const TQCString &name)
+ {
+ return new KCookieServer(name);
+ }
+}
+
+
+// Cookie field indexes
+enum CookieDetails { CF_DOMAIN=0, CF_PATH, CF_NAME, CF_HOST,
+ CF_VALUE, CF_EXPIRE, CF_PROVER, CF_SECURE };
+
+
+class CookieRequest {
+public:
+ DCOPClient *client;
+ DCOPClientTransaction *transaction;
+ TQString url;
+ bool DOM;
+ long windowId;
+};
+
+template class TQPtrList<CookieRequest>;
+
+class RequestList : public TQPtrList<CookieRequest>
+{
+public:
+ RequestList() : TQPtrList<CookieRequest>() { }
+};
+
+KCookieServer::KCookieServer(const TQCString &name)
+ :KDEDModule(name)
+{
+ mOldCookieServer = new DCOPClient(); // backwards compatibility.
+ mOldCookieServer->registerAs("kcookiejar", false);
+ mOldCookieServer->setDaemonMode( true );
+ mCookieJar = new KCookieJar;
+ mPendingCookies = new KHttpCookieList;
+ mPendingCookies->setAutoDelete(true);
+ mRequestList = new RequestList;
+ mAdvicePending = false;
+ mTimer = new TQTimer();
+ connect( mTimer, TQT_SIGNAL( timeout()), TQT_SLOT( slotSave()));
+ mConfig = new TDEConfig("kcookiejarrc");
+ mCookieJar->loadConfig( mConfig );
+
+ TQString filename = locateLocal("data", "kcookiejar/cookies");
+
+ // Stay backwards compatible!
+ TQString filenameOld = locate("data", "kfm/cookies");
+ if (!filenameOld.isEmpty())
+ {
+ mCookieJar->loadCookies( filenameOld );
+ if (mCookieJar->saveCookies( filename))
+ {
+ unlink(TQFile::encodeName(filenameOld)); // Remove old kfm cookie file
+ }
+ }
+ else
+ {
+ mCookieJar->loadCookies( filename);
+ }
+ connect(this, TQT_SIGNAL(windowUnregistered(long)),
+ this, TQT_SLOT(slotDeleteSessionCookies(long)));
+}
+
+KCookieServer::~KCookieServer()
+{
+ if (mCookieJar->changed())
+ slotSave();
+ delete mOldCookieServer;
+ delete mCookieJar;
+ delete mTimer;
+ delete mPendingCookies;
+ delete mConfig;
+}
+
+bool KCookieServer::cookiesPending( const TQString &url, KHttpCookieList *cookieList )
+{
+ TQString fqdn;
+ TQStringList domains;
+ TQString path;
+ // Check whether 'url' has cookies on the pending list
+ if (mPendingCookies->isEmpty())
+ return false;
+ if (!KCookieJar::parseURL(url, fqdn, path))
+ return false;
+
+ mCookieJar->extractDomains( fqdn, domains );
+ for( KHttpCookie *cookie = mPendingCookies->first();
+ cookie != 0L;
+ cookie = mPendingCookies->next())
+ {
+ if (cookie->match( fqdn, domains, path))
+ {
+ if (!cookieList)
+ return true;
+ cookieList->append(cookie);
+ }
+ }
+ if (!cookieList)
+ return false;
+ return cookieList->isEmpty();
+}
+
+void KCookieServer::addCookies( const TQString &url, const TQCString &cookieHeader,
+ long windowId, bool useDOMFormat )
+{
+ KHttpCookieList cookieList;
+ if (useDOMFormat)
+ cookieList = mCookieJar->makeDOMCookies(url, cookieHeader, windowId);
+ else
+ cookieList = mCookieJar->makeCookies(url, cookieHeader, windowId);
+
+ checkCookies(&cookieList);
+
+ for(KHttpCookiePtr cookie = cookieList.first(); cookie; cookie = cookieList.first())
+ mPendingCookies->append(cookieList.take());
+
+ if (!mAdvicePending)
+ {
+ mAdvicePending = true;
+ while (!mPendingCookies->isEmpty())
+ {
+ checkCookies(0);
+ }
+ mAdvicePending = false;
+ }
+}
+
+void KCookieServer::checkCookies( KHttpCookieList *cookieList)
+{
+ KHttpCookieList *list;
+
+ if (cookieList)
+ list = cookieList;
+ else
+ list = mPendingCookies;
+
+ KHttpCookiePtr cookie = list->first();
+ while (cookie)
+ {
+ kdDebug(7104) << "checkCookies: Asking cookie advice for " << cookie->host() << endl;
+ KCookieAdvice advice = mCookieJar->cookieAdvice(cookie);
+ switch(advice)
+ {
+ case KCookieAccept:
+ list->take();
+ mCookieJar->addCookie(cookie);
+ cookie = list->current();
+ break;
+
+ case KCookieReject:
+ list->take();
+ delete cookie;
+ cookie = list->current();
+ break;
+
+ default:
+ cookie = list->next();
+ break;
+ }
+ }
+
+ if (cookieList || list->isEmpty())
+ return;
+
+ KHttpCookiePtr currentCookie = mPendingCookies->first();
+
+ KHttpCookieList currentList;
+ currentList.append(currentCookie);
+ TQString currentHost = currentCookie->host();
+
+ cookie = mPendingCookies->next();
+ while (cookie)
+ {
+ if (cookie->host() == currentHost)
+ {
+ currentList.append(cookie);
+ }
+ cookie = mPendingCookies->next();
+ }
+
+ KCookieWin *kw = new KCookieWin( 0L, currentList,
+ mCookieJar->preferredDefaultPolicy(),
+ mCookieJar->showCookieDetails() );
+ KCookieAdvice userAdvice = kw->advice(mCookieJar, currentCookie);
+ delete kw;
+ // Save the cookie config if it has changed
+ mCookieJar->saveConfig( mConfig );
+
+ // Apply the user's choice to all cookies that are currently
+ // queued for this host.
+ cookie = mPendingCookies->first();
+ while (cookie)
+ {
+ if (cookie->host() == currentHost)
+ {
+ switch(userAdvice)
+ {
+ case KCookieAccept:
+ mPendingCookies->take();
+ mCookieJar->addCookie(cookie);
+ cookie = mPendingCookies->current();
+ break;
+
+ case KCookieReject:
+ mPendingCookies->take();
+ delete cookie;
+ cookie = mPendingCookies->current();
+ break;
+
+ default:
+ tqWarning(__FILE__":%d Problem!", __LINE__);
+ cookie = mPendingCookies->next();
+ break;
+ }
+ }
+ else
+ {
+ cookie = mPendingCookies->next();
+ }
+ }
+
+
+ // Check if we can handle any request
+ for ( CookieRequest *request = mRequestList->first(); request;)
+ {
+ if (!cookiesPending( request->url ))
+ {
+ TQCString replyType;
+ TQByteArray replyData;
+ TQString res = mCookieJar->findCookies( request->url, request->DOM, request->windowId );
+
+ TQDataStream stream2(replyData, IO_WriteOnly);
+ stream2 << res;
+ replyType = "TQString";
+ request->client->endTransaction( request->transaction,
+ replyType, replyData);
+ CookieRequest *tmp = request;
+ request = mRequestList->next();
+ mRequestList->removeRef( tmp );
+ delete tmp;
+ }
+ else
+ {
+ request = mRequestList->next();
+ }
+ }
+ if (mCookieJar->changed())
+ saveCookieJar();
+}
+
+void KCookieServer::slotSave()
+{
+ TQString filename = locateLocal("data", "kcookiejar/cookies");
+ mCookieJar->saveCookies(filename);
+}
+
+void KCookieServer::saveCookieJar()
+{
+ if( mTimer->isActive() )
+ return;
+
+ mTimer->start( 1000*60*SAVE_DELAY, true );
+}
+
+void KCookieServer::putCookie( TQStringList& out, KHttpCookie *cookie,
+ const TQValueList<int>& fields )
+{
+ TQValueList<int>::ConstIterator i = fields.begin();
+ for ( ; i != fields.end(); ++i )
+ {
+ switch(*i)
+ {
+ case CF_DOMAIN :
+ out << cookie->domain();
+ break;
+ case CF_NAME :
+ out << cookie->name();
+ break;
+ case CF_PATH :
+ out << cookie->path();
+ break;
+ case CF_HOST :
+ out << cookie->host();
+ break;
+ case CF_VALUE :
+ out << cookie->value();
+ break;
+ case CF_EXPIRE :
+ out << TQString::number(cookie->expireDate());
+ break;
+ case CF_PROVER :
+ out << TQString::number(cookie->protocolVersion());
+ break;
+ case CF_SECURE :
+ out << TQString::number( cookie->isSecure() ? 1 : 0 );
+ break;
+ default :
+ out << TQString::null;
+ }
+ }
+}
+
+bool KCookieServer::cookieMatches( KHttpCookiePtr c,
+ TQString domain, TQString fqdn,
+ TQString path, TQString name )
+{
+ if( c )
+ {
+ bool hasDomain = !domain.isEmpty();
+ return
+ ((hasDomain && c->domain() == domain) ||
+ fqdn == c->host()) &&
+ (c->path() == path) &&
+ (c->name() == name) &&
+ (!c->isExpired(time(0)));
+ }
+ return false;
+}
+
+// DCOP function
+TQString
+KCookieServer::findCookies(TQString url)
+{
+ return findCookies(url, 0);
+}
+
+// DCOP function
+TQString
+KCookieServer::findCookies(TQString url, long windowId)
+{
+ if (cookiesPending(url))
+ {
+ CookieRequest *request = new CookieRequest;
+ request->client = callingDcopClient();
+ request->transaction = request->client->beginTransaction();
+ request->url = url;
+ request->DOM = false;
+ request->windowId = windowId;
+ mRequestList->append( request );
+ return TQString::null; // Talk to you later :-)
+ }
+
+ TQString cookies = mCookieJar->findCookies(url, false, windowId);
+
+ if (mCookieJar->changed())
+ saveCookieJar();
+
+ return cookies;
+}
+
+// DCOP function
+TQStringList
+KCookieServer::findDomains()
+{
+ TQStringList result;
+ const TQStringList domains = mCookieJar->getDomainList();
+ for ( TQStringList::ConstIterator domIt = domains.begin();
+ domIt != domains.end(); ++domIt )
+ {
+ // Ignore domains that have policy set for but contain
+ // no cookies whatsoever...
+ const KHttpCookieList* list = mCookieJar->getCookieList(*domIt, "");
+ if ( list && !list->isEmpty() )
+ result << *domIt;
+ }
+ return result;
+}
+
+// DCOP function
+TQStringList
+KCookieServer::findCookies(TQValueList<int> fields,
+ TQString domain,
+ TQString fqdn,
+ TQString path,
+ TQString name)
+{
+ TQStringList result;
+ bool allDomCookies = name.isEmpty();
+
+ const KHttpCookieList* list = mCookieJar->getCookieList(domain, fqdn);
+ if ( list && !list->isEmpty() )
+ {
+ TQPtrListIterator<KHttpCookie>it( *list );
+ for ( ; it.current(); ++it )
+ {
+ if ( !allDomCookies )
+ {
+ if ( cookieMatches(it.current(), domain, fqdn, path, name) )
+ {
+ putCookie(result, it.current(), fields);
+ break;
+ }
+ }
+ else
+ putCookie(result, it.current(), fields);
+ }
+ }
+ return result;
+}
+
+// DCOP function
+TQString
+KCookieServer::findDOMCookies(TQString url)
+{
+ return findDOMCookies(url, 0);
+}
+
+// DCOP function
+TQString
+KCookieServer::findDOMCookies(TQString url, long windowId)
+{
+ // We don't wait for pending cookies because it locks up konqueror
+ // which can cause a deadlock if it happens to have a popup-menu up.
+ // Instead we just return pending cookies as if they had been accepted already.
+ KHttpCookieList pendingCookies;
+ cookiesPending(url, &pendingCookies);
+
+ return mCookieJar->findCookies(url, true, windowId, &pendingCookies);
+}
+
+// DCOP function
+void
+KCookieServer::addCookies(TQString arg1, TQCString arg2, long arg3)
+{
+ addCookies(arg1, arg2, arg3, false);
+}
+
+// DCOP function
+void
+KCookieServer::deleteCookie(TQString domain, TQString fqdn,
+ TQString path, TQString name)
+{
+ const KHttpCookieList* list = mCookieJar->getCookieList( domain, fqdn );
+ if ( list && !list->isEmpty() )
+ {
+ TQPtrListIterator<KHttpCookie>it (*list);
+ for ( ; it.current(); ++it )
+ {
+ if( cookieMatches(it.current(), domain, fqdn, path, name) )
+ {
+ mCookieJar->eatCookie( it.current() );
+ saveCookieJar();
+ break;
+ }
+ }
+ }
+}
+
+// DCOP function
+void
+KCookieServer::deleteCookiesFromDomain(TQString domain)
+{
+ mCookieJar->eatCookiesForDomain(domain);
+ saveCookieJar();
+}
+
+
+// Qt function
+void
+KCookieServer::slotDeleteSessionCookies( long windowId )
+{
+ deleteSessionCookies(windowId);
+}
+
+// DCOP function
+void
+KCookieServer::deleteSessionCookies( long windowId )
+{
+ mCookieJar->eatSessionCookies( windowId );
+ saveCookieJar();
+}
+
+void
+KCookieServer::deleteSessionCookiesFor(TQString fqdn, long windowId)
+{
+ mCookieJar->eatSessionCookies( fqdn, windowId );
+ saveCookieJar();
+}
+
+// DCOP function
+void
+KCookieServer::deleteAllCookies()
+{
+ mCookieJar->eatAllCookies();
+ saveCookieJar();
+}
+
+// DCOP function
+void
+KCookieServer::addDOMCookies(TQString arg1, TQCString arg2, long arg3)
+{
+ addCookies(arg1, arg2, arg3, true);
+}
+
+// DCOP function
+void
+KCookieServer::setDomainAdvice(TQString url, TQString advice)
+{
+ TQString fqdn;
+ TQString dummy;
+ if (KCookieJar::parseURL(url, fqdn, dummy))
+ {
+ TQStringList domains;
+ mCookieJar->extractDomains(fqdn, domains);
+
+ mCookieJar->setDomainAdvice(domains[domains.count() > 3 ? 3 : 0],
+ KCookieJar::strToAdvice(advice));
+ // Save the cookie config if it has changed
+ mCookieJar->saveConfig( mConfig );
+ }
+}
+
+// DCOP function
+TQString
+KCookieServer::getDomainAdvice(TQString url)
+{
+ KCookieAdvice advice = KCookieDunno;
+ TQString fqdn;
+ TQString dummy;
+ if (KCookieJar::parseURL(url, fqdn, dummy))
+ {
+ TQStringList domains;
+ mCookieJar->extractDomains(fqdn, domains);
+
+ TQStringList::ConstIterator it = domains.begin();
+ while ( (advice == KCookieDunno) && (it != domains.end()) )
+ {
+ // Always check advice in both ".domain" and "domain". Note
+ // that we only want to check "domain" if it matches the
+ // fqdn of the requested URL.
+ if ( (*it)[0] == '.' || (*it) == fqdn )
+ advice = mCookieJar->getDomainAdvice(*it);
+ ++it;
+ }
+ if (advice == KCookieDunno)
+ advice = mCookieJar->getGlobalAdvice();
+ }
+ return KCookieJar::adviceToStr(advice);
+}
+
+// DCOP function
+void
+KCookieServer::reloadPolicy()
+{
+ mCookieJar->loadConfig( mConfig, true );
+}
+
+// DCOP function
+void
+KCookieServer::shutdown()
+{
+ deleteLater();
+}
+
+#include "kcookieserver.moc"
+
diff --git a/kioslave/http/kcookiejar/kcookieserver.h b/tdeioslave/http/kcookiejar/kcookieserver.h
index 2cbb9ccf1..2cbb9ccf1 100644
--- a/kioslave/http/kcookiejar/kcookieserver.h
+++ b/tdeioslave/http/kcookiejar/kcookieserver.h
diff --git a/kioslave/http/kcookiejar/kcookiewin.cpp b/tdeioslave/http/kcookiejar/kcookiewin.cpp
index 57a22f62c..57a22f62c 100644
--- a/kioslave/http/kcookiejar/kcookiewin.cpp
+++ b/tdeioslave/http/kcookiejar/kcookiewin.cpp
diff --git a/kioslave/http/kcookiejar/kcookiewin.h b/tdeioslave/http/kcookiejar/kcookiewin.h
index d739732dc..d739732dc 100644
--- a/kioslave/http/kcookiejar/kcookiewin.h
+++ b/tdeioslave/http/kcookiejar/kcookiewin.h
diff --git a/kioslave/http/kcookiejar/main.cpp b/tdeioslave/http/kcookiejar/main.cpp
index e24112888..e24112888 100644
--- a/kioslave/http/kcookiejar/main.cpp
+++ b/tdeioslave/http/kcookiejar/main.cpp
diff --git a/kioslave/http/kcookiejar/netscape_cookie_spec.html b/tdeioslave/http/kcookiejar/netscape_cookie_spec.html
index eb190f2e3..eb190f2e3 100644
--- a/kioslave/http/kcookiejar/netscape_cookie_spec.html
+++ b/tdeioslave/http/kcookiejar/netscape_cookie_spec.html
diff --git a/kioslave/http/kcookiejar/rfc2109 b/tdeioslave/http/kcookiejar/rfc2109
index 432fdcc6e..432fdcc6e 100644
--- a/kioslave/http/kcookiejar/rfc2109
+++ b/tdeioslave/http/kcookiejar/rfc2109
diff --git a/kioslave/http/kcookiejar/rfc2965 b/tdeioslave/http/kcookiejar/rfc2965
index 8a4d02b17..8a4d02b17 100644
--- a/kioslave/http/kcookiejar/rfc2965
+++ b/tdeioslave/http/kcookiejar/rfc2965
diff --git a/tdeioslave/http/kcookiejar/tests/Makefile.am b/tdeioslave/http/kcookiejar/tests/Makefile.am
new file mode 100644
index 000000000..3af4677f1
--- /dev/null
+++ b/tdeioslave/http/kcookiejar/tests/Makefile.am
@@ -0,0 +1,18 @@
+# $Id$
+# Makefile.am of tdebase/tdeioslave/http
+
+INCLUDES= $(all_includes)
+
+####### Files
+
+check_PROGRAMS = kcookiejartest
+
+kcookiejartest_SOURCES = kcookiejartest.cpp
+kcookiejartest_LDADD = $(LIB_KIO)
+kcookiejartest_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+
+check-local: kcookiejartest
+ ./kcookiejartest $(srcdir)/cookie.test
+ ./kcookiejartest $(srcdir)/cookie_rfc.test
+ ./kcookiejartest $(srcdir)/cookie_saving.test
+ ./kcookiejartest $(srcdir)/cookie_settings.test
diff --git a/kioslave/http/kcookiejar/tests/cookie.test b/tdeioslave/http/kcookiejar/tests/cookie.test
index 6619bf82d..6619bf82d 100644
--- a/kioslave/http/kcookiejar/tests/cookie.test
+++ b/tdeioslave/http/kcookiejar/tests/cookie.test
diff --git a/kioslave/http/kcookiejar/tests/cookie_rfc.test b/tdeioslave/http/kcookiejar/tests/cookie_rfc.test
index e1d8a40de..e1d8a40de 100644
--- a/kioslave/http/kcookiejar/tests/cookie_rfc.test
+++ b/tdeioslave/http/kcookiejar/tests/cookie_rfc.test
diff --git a/kioslave/http/kcookiejar/tests/cookie_saving.test b/tdeioslave/http/kcookiejar/tests/cookie_saving.test
index cb9f34c42..cb9f34c42 100644
--- a/kioslave/http/kcookiejar/tests/cookie_saving.test
+++ b/tdeioslave/http/kcookiejar/tests/cookie_saving.test
diff --git a/kioslave/http/kcookiejar/tests/cookie_settings.test b/tdeioslave/http/kcookiejar/tests/cookie_settings.test
index 7fc1a03a7..7fc1a03a7 100644
--- a/kioslave/http/kcookiejar/tests/cookie_settings.test
+++ b/tdeioslave/http/kcookiejar/tests/cookie_settings.test
diff --git a/kioslave/http/kcookiejar/tests/kcookiejartest.cpp b/tdeioslave/http/kcookiejar/tests/kcookiejartest.cpp
index 236e2406b..236e2406b 100644
--- a/kioslave/http/kcookiejar/tests/kcookiejartest.cpp
+++ b/tdeioslave/http/kcookiejar/tests/kcookiejartest.cpp
diff --git a/kioslave/http/rfc2518.txt b/tdeioslave/http/rfc2518.txt
index 34d2e942a..34d2e942a 100644
--- a/kioslave/http/rfc2518.txt
+++ b/tdeioslave/http/rfc2518.txt
diff --git a/kioslave/http/rfc2616.txt b/tdeioslave/http/rfc2616.txt
index 7be662a97..7be662a97 100644
--- a/kioslave/http/rfc2616.txt
+++ b/tdeioslave/http/rfc2616.txt
diff --git a/kioslave/http/rfc2617.txt b/tdeioslave/http/rfc2617.txt
index da74cc63a..da74cc63a 100644
--- a/kioslave/http/rfc2617.txt
+++ b/tdeioslave/http/rfc2617.txt
diff --git a/kioslave/http/rfc2817.txt b/tdeioslave/http/rfc2817.txt
index a29dfc44b..a29dfc44b 100644
--- a/kioslave/http/rfc2817.txt
+++ b/tdeioslave/http/rfc2817.txt
diff --git a/kioslave/http/rfc2818.txt b/tdeioslave/http/rfc2818.txt
index fff91b1a9..fff91b1a9 100644
--- a/kioslave/http/rfc2818.txt
+++ b/tdeioslave/http/rfc2818.txt
diff --git a/kioslave/http/rfc3229.txt b/tdeioslave/http/rfc3229.txt
index 54a19b685..54a19b685 100644
--- a/kioslave/http/rfc3229.txt
+++ b/tdeioslave/http/rfc3229.txt
diff --git a/kioslave/http/rfc3253.txt b/tdeioslave/http/rfc3253.txt
index 9968eea02..9968eea02 100644
--- a/kioslave/http/rfc3253.txt
+++ b/tdeioslave/http/rfc3253.txt
diff --git a/kioslave/http/shoutcast-icecast.txt b/tdeioslave/http/shoutcast-icecast.txt
index f7bdcf1e7..f7bdcf1e7 100644
--- a/kioslave/http/shoutcast-icecast.txt
+++ b/tdeioslave/http/shoutcast-icecast.txt
diff --git a/tdeioslave/http/webdav.protocol b/tdeioslave/http/webdav.protocol
new file mode 100644
index 000000000..3fd6287f9
--- /dev/null
+++ b/tdeioslave/http/webdav.protocol
@@ -0,0 +1,18 @@
+[Protocol]
+exec=kio_http
+protocol=webdav
+input=none
+output=filesystem
+listing=Name,Type,Size,Date,AccessDate,Access
+reading=true
+writing=true
+makedir=true
+deleting=true
+moving=true
+deleteRecursive=true
+defaultMimetype=application/octet-stream
+determineMimetypeFromExtension=false
+Icon=www
+maxInstances=3
+DocPath=tdeioslave/webdav.html
+Class=:internet
diff --git a/tdeioslave/http/webdavs.protocol b/tdeioslave/http/webdavs.protocol
new file mode 100644
index 000000000..12d97499a
--- /dev/null
+++ b/tdeioslave/http/webdavs.protocol
@@ -0,0 +1,18 @@
+[Protocol]
+exec=kio_http
+protocol=webdavs
+input=none
+output=filesystem
+listing=Name,Type,Size,Date,AccessDate,Access
+reading=true
+writing=true
+makedir=true
+deleting=true
+moving=true
+deleteRecursive=true
+defaultMimetype=application/octet-stream
+determineMimetypeFromExtension=false
+Icon=www
+config=webdav
+DocPath=tdeioslave/webdavs.html
+Class=:internet
diff --git a/tdeioslave/iso/CMakeLists.txt b/tdeioslave/iso/CMakeLists.txt
new file mode 100644
index 000000000..df3bfeee1
--- /dev/null
+++ b/tdeioslave/iso/CMakeLists.txt
@@ -0,0 +1,51 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+add_subdirectory( libisofs )
+
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install( FILES iso.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
+install( FILES isoservice.desktop DESTINATION ${DATA_INSTALL_DIR}/konqueror/servicemenus )
+install( FILES kio_isorc DESTINATION ${CONFIG_INSTALL_DIR} )
+install( FILES kio_iso.desktop DESTINATION ${APPS_INSTALL_DIR} )
+
+
+##### kio_iso ###################################
+
+set( target kio_iso )
+
+set( ${target}_SRCS
+ kisodirectory.cpp kisofile.cpp qfilehack.cpp
+ kiso.cpp iso.cpp
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK isofs-static tdeio-shared
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/tdeioslave/iso/Makefile.am b/tdeioslave/iso/Makefile.am
new file mode 100644
index 000000000..bc1c7b3ea
--- /dev/null
+++ b/tdeioslave/iso/Makefile.am
@@ -0,0 +1,67 @@
+kde_module_LTLIBRARIES = kio_iso.la
+
+
+INCLUDES = $(all_includes)
+
+
+#LDFLAGS =
+
+kio_iso_la_METASOURCES=AUTO
+
+kio_iso_la_SOURCES = kisodirectory.cpp kisofile.cpp qfilehack.cpp kiso.cpp iso.cpp
+kio_iso_la_LIBADD = libisofs/libisofs.la $(LIB_QT) $(LIB_TDECORE) $(LIB_KIO)
+
+kio_iso_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
+
+
+SUBDIRS = libisofs
+
+noinst_HEADERS = iso.h kiso.h qfilehack.h kisofile.h kisodirectory.h
+EXTRA_DIST = iso.protocol isoservice.desktop kio_iso.desktop
+
+install-data-local:
+ $(mkinstalldirs) $(DESTDIR)$(kde_servicesdir)/
+ $(INSTALL_DATA) $(srcdir)/iso.protocol $(DESTDIR)$(kde_servicesdir)/iso.protocol
+ $(mkinstalldirs) $(DESTDIR)$(kde_datadir)/konqueror/servicemenus/
+ $(INSTALL_DATA) $(srcdir)/isoservice.desktop $(DESTDIR)$(kde_datadir)/konqueror/servicemenus/isoservice.desktop
+ $(mkinstalldirs) $(DESTDIR)$(kde_confdir)/
+ $(INSTALL_DATA) $(srcdir)/tdeio_isorc $(DESTDIR)$(kde_confdir)/tdeio_isorc
+ $(mkinstalldirs) $(DESTDIR)$(kde_appsdir)/
+ $(INSTALL_DATA) $(srcdir)/tdeio_iso.desktop $(DESTDIR)$(kde_appsdir)/tdeio_iso.desktop
+
+uninstall-local:
+ -rm -f $(DESTDIR)$(kde_servicesdir)/iso.protocol
+ -rm -f $(DESTDIR)$(kde_datadir)/konqueror/servicemenus/isoservice.desktop
+ -rm -f $(DESTDIR)$(kde_confdir)/tdeio_isorc
+ -rm -f $(DESTDIR)$(kde_appsdir)/tdeio_iso.desktop
+
+# These paths are KDE specific. Use them:
+# kde_appsdir Where your application's menu entry (.desktop) should go to.
+# kde_icondir Where your icon should go to - better use KDE_ICON.
+# kde_sounddir Where your sounds should go to.
+# kde_htmldir Where your docs should go to. (contains lang subdirs)
+# kde_datadir Where you install application data. (Use a subdir)
+# kde_locale Where translation files should go to. (contains lang subdirs)
+# kde_cgidir Where cgi-bin executables should go to.
+# kde_confdir Where config files should go to (system-wide ones with default values).
+# kde_mimedir Where mimetypes .desktop files should go to.
+# kde_servicesdir Where services .desktop files should go to.
+# kde_servicetypesdir Where servicetypes .desktop files should go to.
+# kde_toolbardir Where general toolbar icons should go to (deprecated, use KDE_ICON).
+# kde_wallpaperdir Where general wallpapers should go to.
+# kde_templatesdir Where templates for the "New" menu (Konqueror/KDesktop) should go to.
+# kde_bindir Where executables should go to. Use bin_PROGRAMS or bin_SCRIPTS.
+# kde_libdir Where shared libraries should go to. Use lib_LTLIBRARIES.
+# kde_moduledir Where modules (e.g. parts) should go to. Use kde_module_LTLIBRARIES.
+# kde_styledir Where Qt/KDE widget styles should go to (new in KDE 3).
+# kde_designerdir Where Qt Designer plugins should go to (new in KDE 3).
+
+
+# make messages.po. Move this one to ../po/ and "make merge" in po
+# the -x is for skipping messages already translated in tdelibs
+messages:
+ LIST=`find . -name \*.h -o -name \*.hh -o -name \*.H -o -name \*.hxx -o -name \*.hpp -o -name \*.cpp -o -name \*.cc -o -name \*.cxx -o -name \*.ecpp -o -name \*.C`; \
+ if test -n "$$LIST"; then \
+ $(XGETTEXT) -C -ki18n -x $(kde_includes)/kde.pot $$LIST -o ../po/iso.pot; \
+ fi
+
diff --git a/kioslave/iso/iso.cpp b/tdeioslave/iso/iso.cpp
index 59f5f781e..59f5f781e 100644
--- a/kioslave/iso/iso.cpp
+++ b/tdeioslave/iso/iso.cpp
diff --git a/tdeioslave/iso/iso.h b/tdeioslave/iso/iso.h
new file mode 100644
index 000000000..f0393d7cb
--- /dev/null
+++ b/tdeioslave/iso/iso.h
@@ -0,0 +1,51 @@
+/***************************************************************************
+ iso.h
+ -------------------
+ begin : Oct 25 2002
+ copyright : (C) 2002 by Szombathelyi György
+ email : gyurco@users.sourceforge.net
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 file is heavily based on tar.h from tdebase
+ * (c) David Faure <faure@kde.org>
+ */
+
+#ifndef _ISO_H
+#define _ISO_H
+
+#include <tdeio/slavebase.h>
+#include <sys/types.h>
+#include "kisofile.h"
+
+class KIso;
+
+class kio_isoProtocol : public TDEIO::SlaveBase
+{
+public:
+ kio_isoProtocol( const TQCString &pool, const TQCString &app );
+ virtual ~kio_isoProtocol();
+
+ virtual void listDir( const KURL & url );
+ virtual void stat( const KURL & url );
+ virtual void get( const KURL & url );
+
+protected:
+ void getFile( const KIsoFile *isoFileEntry, const TQString &path );
+ void createUDSEntry( const KArchiveEntry * isoEntry, TDEIO::UDSEntry & entry );
+ bool checkNewFile( TQString fullPath, TQString & path, int startsec );
+
+ KIso * m_isoFile;
+ time_t m_mtime;
+ int m_mode;
+};
+
+#endif
diff --git a/tdeioslave/iso/iso.protocol b/tdeioslave/iso/iso.protocol
new file mode 100644
index 000000000..cd2d1d28b
--- /dev/null
+++ b/tdeioslave/iso/iso.protocol
@@ -0,0 +1,11 @@
+[Protocol]
+exec=kio_iso
+protocol=iso
+listing=Name,Type,Size,Date,AccessDate,CreationDate,Access,Owner,Group,Link
+input=filesystem
+output=filesystem
+reading=true
+source=true
+Icon=cd
+Description=A tdeioslave for ISO9660 filesystems
+MimeType=application/x-iso
diff --git a/kioslave/iso/isoservice.desktop b/tdeioslave/iso/isoservice.desktop
index 00093709b..00093709b 100644
--- a/kioslave/iso/isoservice.desktop
+++ b/tdeioslave/iso/isoservice.desktop
diff --git a/kioslave/iso/kio_iso.desktop b/tdeioslave/iso/kio_iso.desktop
index 8578f44b4..8578f44b4 100644
--- a/kioslave/iso/kio_iso.desktop
+++ b/tdeioslave/iso/kio_iso.desktop
diff --git a/kioslave/iso/kio_isorc b/tdeioslave/iso/kio_isorc
index 3a874172e..3a874172e 100644
--- a/kioslave/iso/kio_isorc
+++ b/tdeioslave/iso/kio_isorc
diff --git a/tdeioslave/iso/kiso.cpp b/tdeioslave/iso/kiso.cpp
new file mode 100644
index 000000000..7556a3350
--- /dev/null
+++ b/tdeioslave/iso/kiso.cpp
@@ -0,0 +1,460 @@
+/***************************************************************************
+ kiso.cpp
+ -------------------
+ begin : Oct 25 2002
+ copyright : (C) 2002 by Szombathelyi Gy�gy
+ email : gyurco@users.sourceforge.net
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * 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 file is heavily based on ktar.cpp from tdelibs (c) David Faure */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <unistd.h>
+#include <grp.h>
+#include <pwd.h>
+#include <assert.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <tqcstring.h>
+#include <tqdir.h>
+#include <tqfile.h>
+#include <kdebug.h>
+#include <kurl.h>
+#include <kmimetype.h>
+#include <tdeconfig.h>
+#include <kfilterdev.h>
+#include <kfilterbase.h>
+
+#include "kiso.h"
+#include "libisofs/isofs.h"
+#include "qfilehack.h"
+
+
+#ifdef __linux__
+#undef __STRICT_ANSI__
+#include <linux/cdrom.h>
+#define __STRICT_ANSI__
+#include <sys/ioctl.h>
+#include <fcntl.h>
+#endif
+
+////////////////////////////////////////////////////////////////////////
+/////////////////////////// KIso ///////////////////////////////////
+////////////////////////////////////////////////////////////////////////
+
+/**
+ * puts the track layout of the device 'fname' into 'tracks'
+ * tracks structure: start sector, track number, ...
+ * tracks should be 100*2 entry long (this is the maximum in the CD-ROM standard)
+ * currently it's linux only, porters are welcome
+ */
+static int getTracks(const char *fname,int *tracks) {
+ int ret=0;
+ memset(tracks,0,200*sizeof(int));
+
+#ifdef __linux__
+ int fd,i;
+ struct cdrom_tochdr tochead;
+ struct cdrom_tocentry tocentry;
+
+ kdDebug() << "getTracks open:" << fname << endl;
+ fd=open(fname, O_RDONLY | O_NONBLOCK);
+ if (fd > 0) {
+ if (ioctl(fd,CDROMREADTOCHDR,&tochead)!=-1) {
+ kdDebug() << "getTracks first track:" << tochead.cdth_trk0
+ << " last track " << tochead.cdth_trk1 << endl;
+ for (i=tochead.cdth_trk0;i<=tochead.cdth_trk1;i++) {
+ if (ret>99) break;
+ memset(&tocentry,0,sizeof(struct cdrom_tocentry));
+ tocentry.cdte_track=i;
+ tocentry.cdte_format=CDROM_LBA;
+ if (ioctl(fd,CDROMREADTOCENTRY,&tocentry)<0) break;
+ kdDebug() << "getTracks got track " << i << " starting at: " <<
+ tocentry.cdte_addr.lba << endl;
+ if ((tocentry.cdte_ctrl & 0x4) == 0x4) {
+ tracks[ret<<1]=tocentry.cdte_addr.lba;
+ tracks[(ret<<1)+1]=i;
+ ret++;
+ }
+ }
+ }
+ close(fd);
+ }
+
+#endif
+
+ return ret;
+}
+
+class KIso::KIsoPrivate
+{
+public:
+ KIsoPrivate() {}
+ TQStringList dirList;
+};
+
+KIso::KIso( const TQString& filename, const TQString & _mimetype )
+ : KArchive( 0L )
+{
+ m_startsec = -1;
+ m_filename = filename;
+ d = new KIsoPrivate;
+ TQString mimetype( _mimetype );
+ bool forced = true;
+ if ( mimetype.isEmpty() )
+ {
+ mimetype = KMimeType::findByFileContent( filename )->name();
+ kdDebug() << "KIso::KIso mimetype=" << mimetype << endl;
+
+ // Don't move to prepareDevice - the other constructor theoretically allows ANY filter
+ if ( mimetype == "application/x-tgz" || mimetype == "application/x-targz" || // the latter is deprecated but might still be around
+ mimetype == "application/x-webarchive" )
+ // that's a gzipped tar file, so ask for gzip filter
+ mimetype = "application/x-gzip";
+ else if ( mimetype == "application/x-tbz" ) // that's a bzipped2 tar file, so ask for bz2 filter
+ mimetype = "application/x-bzip2";
+ else
+ {
+ // Something else. Check if it's not really gzip though (e.g. for KOffice docs)
+ TQFile file( filename );
+ if ( file.open( IO_ReadOnly ) )
+ {
+ unsigned char firstByte = file.getch();
+ unsigned char secondByte = file.getch();
+ unsigned char thirdByte = file.getch();
+ if ( firstByte == 0037 && secondByte == 0213 )
+ mimetype = "application/x-gzip";
+ else if ( firstByte == 'B' && secondByte == 'Z' && thirdByte == 'h' )
+ mimetype = "application/x-bzip2";
+ else if ( firstByte == 'P' && secondByte == 'K' && thirdByte == 3 )
+ {
+ unsigned char fourthByte = file.getch();
+ if ( fourthByte == 4 )
+ mimetype = "application/x-zip";
+ }
+ }
+ }
+ forced = false;
+ }
+
+ prepareDevice( filename, mimetype, forced );
+}
+
+void KIso::prepareDevice( const TQString & filename,
+ const TQString & mimetype, bool forced )
+{
+ /* 'hack' for Qt's false assumption that only S_ISREG is seekable */
+ if( "inode/blockdevice" == mimetype )
+ setDevice( TQT_TQIODEVICE(new QFileHack( filename )) );
+ else
+ {
+ if( "application/x-gzip" == mimetype
+ || "application/x-bzip2" == mimetype)
+ forced = true;
+
+ TQIODevice *dev = KFilterDev::deviceForFile( filename, mimetype, forced );
+ if( dev )
+ setDevice( dev );
+ }
+
+}
+
+KIso::KIso( TQIODevice * dev )
+ : KArchive( dev )
+{
+ d = new KIsoPrivate;
+}
+
+KIso::~KIso()
+{
+ // mjarrett: Closes to prevent ~KArchive from aborting w/o device
+ if( isOpened() )
+ close();
+ if ( !m_filename.isEmpty() )
+ delete device(); // we created it ourselves
+ delete d;
+}
+
+/* callback function for libisofs */
+static int readf(char *buf, long long start, long long len,void *udata) {
+
+ TQIODevice* dev = ( static_cast<KIso*> (udata) )->device();
+
+ if (dev->at(start<<11)) {
+ if ((dev->readBlock(buf, len<<11)) != -1) return (len);
+ }
+ kdDebug() << "KIso::ReadRequest failed start: " << start << " len: " << len << endl;
+
+ return -1;
+}
+
+/* callback function for libisofs */
+static int mycallb(struct iso_directory_record *idr,void *udata) {
+
+ KIso *iso = static_cast<KIso*> (udata);
+ TQString path,user,group,symlink;
+ int i;
+ int access;
+ int time,cdate,adate;
+ rr_entry rr;
+ bool special=false;
+ KArchiveEntry *entry=NULL,*oldentry=NULL;
+ char z_algo[2],z_params[2];
+ long long z_size=0;
+
+ if ((idr->flags[0] & 1) && !iso->showhidden) return 0;
+ if (iso->level) {
+ if (isonum_711(idr->name_len)==1) {
+ switch (idr->name[0]) {
+ case 0:
+ path+=(".");
+ special=true;
+ break;
+ case 1:
+ path+=("..");
+ special=true;
+ break;
+ }
+ }
+ if (iso->showrr && ParseRR(idr,&rr)>0) {
+ if (!special) path=rr.name;
+ symlink=rr.sl;
+ access=rr.mode;
+ time=rr.t_mtime;
+ adate=rr.t_atime;
+ cdate=rr.t_ctime;
+ user.setNum(rr.uid);
+ group.setNum(rr.gid);
+ z_algo[0]=rr.z_algo[0];z_algo[1]=rr.z_algo[1];
+ z_params[0]=rr.z_params[0];z_params[1]=rr.z_params[1];
+ z_size=rr.z_size;
+ } else {
+ access=iso->dirent->permissions() & ~S_IFMT;
+ adate=cdate=time=isodate_915(idr->date,0);
+ user=iso->dirent->user();
+ group=iso->dirent->group();
+ if (idr->flags[0] & 2) access |= S_IFDIR; else access |= S_IFREG;
+ if (!special) {
+ if (iso->joliet) {
+ for (i=0;i<(isonum_711(idr->name_len)-1);i+=2) {
+ TQChar ch( be2me_16(*((ushort*)&(idr->name[i]))) );
+ if (ch==';') break;
+ path+=ch;
+ }
+ } else {
+ for (i=0;i<isonum_711(idr->name_len);i++) {
+ if (idr->name[i]==';') break;
+ if (idr->name[i]) path+=(idr->name[i]);
+ }
+ }
+ if (path.endsWith(".")) path.setLength(path.length()-1);
+ }
+ }
+ if (iso->showrr) FreeRR(&rr);
+ if (idr->flags[0] & 2) {
+ entry = new KIsoDirectory( iso, path, access | S_IFDIR, time, adate, cdate,
+ user, group, symlink );
+ } else {
+ entry = new KIsoFile( iso, path, access, time, adate, cdate,
+ user, group, symlink, isonum_733(idr->extent)<<11,isonum_733(idr->size) );
+ if (z_size) (static_cast <KIsoFile*> (entry))->setZF(z_algo,z_params,z_size);
+
+ }
+ iso->dirent->addEntry(entry);
+ }
+ if ( (idr->flags[0] & 2) && (iso->level==0 || !special) ) {
+ if (iso->level) {
+ oldentry=iso->dirent;
+ iso->dirent=static_cast<KIsoDirectory*> (entry);
+ }
+ iso->level++;
+ ProcessDir(&readf,isonum_733(idr->extent),isonum_733(idr->size),&mycallb,udata);
+ iso->level--;
+ if (iso->level) iso->dirent=static_cast<KIsoDirectory*> (oldentry);
+ }
+ return 0;
+}
+
+void KIso::addBoot(struct el_torito_boot_descriptor* bootdesc) {
+
+ int i;
+ long long size;
+ boot_head boot;
+ boot_entry *be;
+ TQString path;
+ KIsoFile *entry;
+
+ entry=new KIsoFile( this, "Catalog", dirent->permissions() & ~S_IFDIR,
+ dirent->date(), dirent->adate(), dirent->cdate(),
+ dirent->user(), dirent->group(), TQString::null,
+ isonum_731(bootdesc->boot_catalog)<<11, 2048 );
+ dirent->addEntry(entry);
+ if (!ReadBootTable(&readf,isonum_731(bootdesc->boot_catalog),&boot,this)) {
+ i=1;
+ be=boot.defentry;
+ while (be) {
+ size=BootImageSize( isonum_711((reinterpret_cast<struct default_entry*>(be->data))->media),
+ isonum_721((reinterpret_cast<struct default_entry*>(be->data))->seccount));
+ path="Default Image";
+ if (i>1) path += " (" + TQString::number(i) + ")";
+ entry=new KIsoFile( this, path, dirent->permissions() & ~S_IFDIR,
+ dirent->date(), dirent->adate(), dirent->cdate(),
+ dirent->user(), dirent->group(), TQString::null,
+ isonum_731((reinterpret_cast<struct default_entry*>(be->data))->start)<<11, size<<9 );
+ dirent->addEntry(entry);
+ be=be->next;
+ i++;
+ }
+
+ FreeBootTable(&boot);
+ }
+}
+
+void KIso::readParams()
+{
+ TDEConfig *config;
+
+ config = new TDEConfig("kio_isorc");
+
+ showhidden=config->readBoolEntry("showhidden",false);
+ showrr=config->readBoolEntry("showrr",true);
+ delete config;
+}
+
+bool KIso::openArchive( int mode )
+{
+ iso_vol_desc *desc;
+ TQString path,tmp,uid,gid;
+ struct stat buf;
+ int tracks[2*100],trackno=0,i,access,c_b,c_i,c_j;
+ KArchiveDirectory *root;
+ struct iso_directory_record* idr;
+ struct el_torito_boot_descriptor* bootdesc;
+
+ if ( mode == IO_WriteOnly )
+ return false;
+
+ readParams();
+ d->dirList.clear();
+
+ tracks[0]=0;
+ if (m_startsec>0) tracks[0]=m_startsec;
+ kdDebug() << " m_startsec: " << m_startsec << endl;
+ /* We'll use the permission and user/group of the 'host' file except
+ * in Rock Ridge, where the permissions are stored on the file system
+ */
+ if (::stat( m_filename.local8Bit(), &buf )<0) {
+ /* defaults, if stat fails */
+ memset(&buf,0,sizeof(struct stat));
+ buf.st_mode=0777;
+ } else {
+ /* If it's a block device, try to query the track layout (for multisession) */
+ if (m_startsec == -1 && S_ISBLK(buf.st_mode))
+ trackno=getTracks(m_filename.latin1(),(int*) &tracks);
+ }
+ uid.setNum(buf.st_uid);
+ gid.setNum(buf.st_gid);
+ access = buf.st_mode & ~S_IFMT;
+
+ kdDebug() << "KIso::openArchive number of tracks: " << trackno << endl;
+
+ if (trackno==0) trackno=1;
+ for (i=0;i<trackno;i++) {
+
+ c_b=1;c_i=1;c_j=1;
+ root=rootDir();
+ if (trackno>1) {
+ path=TQString::null;
+ TQTextOStream(&path) << "Track " << tracks[(i<<1)+1];
+ root = new KIsoDirectory( this, path, access | S_IFDIR,
+ buf.st_mtime, buf.st_atime, buf.st_ctime, uid, gid, TQString::null );
+ rootDir()->addEntry(root);
+ }
+
+ desc=ReadISO9660(&readf,tracks[i<<1],this);
+ if (!desc) {
+ kdDebug() << "KIso::openArchive no volume descriptors" << endl;
+ continue;
+ }
+
+ while (desc) {
+ switch (isonum_711(desc->data.type)) {
+ case ISO_VD_BOOT:
+
+ bootdesc=(struct el_torito_boot_descriptor*) &(desc->data);
+ if ( !memcmp(EL_TORITO_ID,bootdesc->system_id,ISODCL(8,39)) ) {
+ path="El Torito Boot";
+ if (c_b>1) path += " (" + TQString::number(c_b) + ")";
+
+ dirent = new KIsoDirectory( this, path, access | S_IFDIR,
+ buf.st_mtime, buf.st_atime, buf.st_ctime, uid, gid, TQString::null );
+ root->addEntry(dirent);
+
+ addBoot(bootdesc);
+ c_b++;
+ }
+ break;
+
+ case ISO_VD_PRIMARY:
+ case ISO_VD_SUPPLEMENTARY:
+ idr=(struct iso_directory_record*) &( ((struct iso_primary_descriptor*) &desc->data)->root_directory_record);
+ joliet = JolietLevel(&desc->data);
+ if (joliet) {
+ TQTextOStream(&path) << "Joliet level " << joliet;
+ if (c_j>1) path += " (" + TQString::number(c_j) + ")";
+ } else {
+ path = "ISO9660";
+ if (c_i>1) path += " (" + TQString::number(c_i) + ")";
+ }
+ dirent = new KIsoDirectory( this, path, access | S_IFDIR,
+ buf.st_mtime, buf.st_atime, buf.st_ctime, uid, gid, TQString::null );
+ root->addEntry(dirent);
+ level=0;
+ mycallb(idr, this );
+ if (joliet) c_j++; else c_i++;
+ break;
+ }
+ desc=desc->next;
+ }
+ free(desc);
+ }
+ device()->close();
+ return true;
+}
+
+bool KIso::closeArchive()
+{
+ d->dirList.clear();
+ return true;
+}
+
+bool KIso::writeDir( const TQString&, const TQString&, const TQString& )
+{
+ return false;
+}
+
+bool KIso::prepareWriting( const TQString&, const TQString&, const TQString&, uint)
+{
+ return false;
+}
+
+bool KIso::doneWriting( uint )
+{
+ return false;
+}
+
+void KIso::virtual_hook( int id, void* data )
+{ KArchive::virtual_hook( id, data ); }
+
diff --git a/kioslave/iso/kiso.h b/tdeioslave/iso/kiso.h
index de0f06dca..de0f06dca 100644
--- a/kioslave/iso/kiso.h
+++ b/tdeioslave/iso/kiso.h
diff --git a/kioslave/iso/kisodirectory.cpp b/tdeioslave/iso/kisodirectory.cpp
index 74987a232..74987a232 100644
--- a/kioslave/iso/kisodirectory.cpp
+++ b/tdeioslave/iso/kisodirectory.cpp
diff --git a/kioslave/iso/kisodirectory.h b/tdeioslave/iso/kisodirectory.h
index 74045ac75..74045ac75 100644
--- a/kioslave/iso/kisodirectory.h
+++ b/tdeioslave/iso/kisodirectory.h
diff --git a/kioslave/iso/kisofile.cpp b/tdeioslave/iso/kisofile.cpp
index ffae0d3bc..ffae0d3bc 100644
--- a/kioslave/iso/kisofile.cpp
+++ b/tdeioslave/iso/kisofile.cpp
diff --git a/kioslave/iso/kisofile.h b/tdeioslave/iso/kisofile.h
index 696a8c191..696a8c191 100644
--- a/kioslave/iso/kisofile.h
+++ b/tdeioslave/iso/kisofile.h
diff --git a/kioslave/iso/libisofs/CMakeLists.txt b/tdeioslave/iso/libisofs/CMakeLists.txt
index a9ef936a8..a9ef936a8 100644
--- a/kioslave/iso/libisofs/CMakeLists.txt
+++ b/tdeioslave/iso/libisofs/CMakeLists.txt
diff --git a/kioslave/iso/libisofs/COPYING b/tdeioslave/iso/libisofs/COPYING
index c7aea1896..c7aea1896 100644
--- a/kioslave/iso/libisofs/COPYING
+++ b/tdeioslave/iso/libisofs/COPYING
diff --git a/kioslave/iso/libisofs/ChangeLog b/tdeioslave/iso/libisofs/ChangeLog
index fb46b8056..fb46b8056 100644
--- a/kioslave/iso/libisofs/ChangeLog
+++ b/tdeioslave/iso/libisofs/ChangeLog
diff --git a/kioslave/iso/libisofs/Makefile.am b/tdeioslave/iso/libisofs/Makefile.am
index a1278ff41..a1278ff41 100644
--- a/kioslave/iso/libisofs/Makefile.am
+++ b/tdeioslave/iso/libisofs/Makefile.am
diff --git a/kioslave/iso/libisofs/README b/tdeioslave/iso/libisofs/README
index 45d3bff04..45d3bff04 100644
--- a/kioslave/iso/libisofs/README
+++ b/tdeioslave/iso/libisofs/README
diff --git a/kioslave/iso/libisofs/bswap.h b/tdeioslave/iso/libisofs/bswap.h
index 95520c6ef..95520c6ef 100644
--- a/kioslave/iso/libisofs/bswap.h
+++ b/tdeioslave/iso/libisofs/bswap.h
diff --git a/kioslave/iso/libisofs/el_torito.h b/tdeioslave/iso/libisofs/el_torito.h
index cba83f785..cba83f785 100644
--- a/kioslave/iso/libisofs/el_torito.h
+++ b/tdeioslave/iso/libisofs/el_torito.h
diff --git a/kioslave/iso/libisofs/iso_fs.h b/tdeioslave/iso/libisofs/iso_fs.h
index 43353b0d9..43353b0d9 100644
--- a/kioslave/iso/libisofs/iso_fs.h
+++ b/tdeioslave/iso/libisofs/iso_fs.h
diff --git a/kioslave/iso/libisofs/isofs.c b/tdeioslave/iso/libisofs/isofs.c
index f1db4427c..f1db4427c 100644
--- a/kioslave/iso/libisofs/isofs.c
+++ b/tdeioslave/iso/libisofs/isofs.c
diff --git a/kioslave/iso/libisofs/isofs.h b/tdeioslave/iso/libisofs/isofs.h
index 1d17de4bb..1d17de4bb 100644
--- a/kioslave/iso/libisofs/isofs.h
+++ b/tdeioslave/iso/libisofs/isofs.h
diff --git a/kioslave/iso/libisofs/rock.h b/tdeioslave/iso/libisofs/rock.h
index e85919261..e85919261 100644
--- a/kioslave/iso/libisofs/rock.h
+++ b/tdeioslave/iso/libisofs/rock.h
diff --git a/kioslave/iso/qfilehack.cpp b/tdeioslave/iso/qfilehack.cpp
index f4f788f25..f4f788f25 100644
--- a/kioslave/iso/qfilehack.cpp
+++ b/tdeioslave/iso/qfilehack.cpp
diff --git a/kioslave/iso/qfilehack.h b/tdeioslave/iso/qfilehack.h
index 3f0b1f6a6..3f0b1f6a6 100644
--- a/kioslave/iso/qfilehack.h
+++ b/tdeioslave/iso/qfilehack.h
diff --git a/tdeioslave/metainfo/CMakeLists.txt b/tdeioslave/metainfo/CMakeLists.txt
new file mode 100644
index 000000000..9b27a8652
--- /dev/null
+++ b/tdeioslave/metainfo/CMakeLists.txt
@@ -0,0 +1,43 @@
+#################################################
+#
+# (C) 2010 Serghei Amelian
+# serghei (DOT) amelian (AT) gmail.com
+#
+# Improvements and feedback are welcome
+#
+# This file is released under GPL >= 2
+#
+#################################################
+
+include_directories(
+ ${TQT_INCLUDE_DIRS}
+ ${CMAKE_BINARY_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/dcop
+ ${CMAKE_SOURCE_DIR}/tdecore
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+)
+
+link_directories(
+ ${TQT_LIBRARY_DIRS}
+)
+
+
+##### other data ################################
+
+install( FILES metainfo.protocol DESTINATION ${SERVICES_INSTALL_DIR} )
+
+
+##### kio_metainfo ##############################
+
+set( target kio_metainfo )
+
+set( ${target}_SRCS
+ metainfo.cpp
+)
+
+tde_add_kpart( ${target} AUTOMOC
+ SOURCES ${${target}_SRCS}
+ LINK tdeio-shared
+ DESTINATION ${PLUGIN_INSTALL_DIR}
+)
diff --git a/tdeioslave/metainfo/Makefile.am b/tdeioslave/metainfo/Makefile.am
new file mode 100644
index 000000000..a5575d9ff
--- /dev/null
+++ b/tdeioslave/metainfo/Makefile.am
@@ -0,0 +1,24 @@
+## $Id$
+## Makefile.am of tdebase/tdeioslave/metainfo
+
+INCLUDES = $(all_includes)
+AM_LDFLAGS = $(all_libraries) $(KDE_RPATH) $(LIB_QT) -lDCOP $(LIB_TDECORE) $(LIB_TDEUI) -ltdefx $(LIB_KIO) -ltdetexteditor
+METASOURCES = AUTO
+
+kde_module_LTLIBRARIES = kio_metainfo.la
+
+kio_metainfo_la_SOURCES = metainfo.cpp
+kio_metainfo_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDECORE)
+kio_metainfo_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
+
+noinst_HEADERS = metainfo.h
+
+kdelnk_DATA = metainfo.protocol
+kdelnkdir = $(kde_servicesdir)
+
+#servicetypes_DATA = thumbcreator.desktop
+#servicetypesdir = $(kde_servicetypesdir)
+
+#services_DATA = imagethumbnail.desktop textthumbnail.desktop
+# htmlthumbnail.desktop gsthumbnail.desktop
+#servicesdir = $(kde_servicesdir)
diff --git a/tdeioslave/metainfo/metainfo.cpp b/tdeioslave/metainfo/metainfo.cpp
new file mode 100644
index 000000000..abc5cdd96
--- /dev/null
+++ b/tdeioslave/metainfo/metainfo.cpp
@@ -0,0 +1,103 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Rolf Magnus <ramagnus@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation version 2.0
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#include <kdatastream.h> // Do not remove, needed for correct bool serialization
+#include <kurl.h>
+#include <kapplication.h>
+#include <kmimetype.h>
+#include <kdebug.h>
+#include <tdefilemetainfo.h>
+#include <klocale.h>
+#include <stdlib.h>
+
+#include "metainfo.h"
+
+// Recognized metadata entries:
+// mimeType - the mime type of the file, so we need not extra determine it
+// what - what to load
+
+using namespace TDEIO;
+
+extern "C"
+{
+ KDE_EXPORT int kdemain(int argc, char **argv);
+}
+
+int kdemain(int argc, char **argv)
+{
+ TDEApplication app(argc, argv, "kio_metainfo", false, true);
+
+ if (argc != 4)
+ {
+ kdError() << "Usage: kio_metainfo protocol domain-socket1 domain-socket2" << endl;
+ exit(-1);
+ }
+
+ MetaInfoProtocol slave(argv[2], argv[3]);
+ slave.dispatchLoop();
+
+ return 0;
+}
+
+MetaInfoProtocol::MetaInfoProtocol(const TQCString &pool, const TQCString &app)
+ : SlaveBase("metainfo", pool, app)
+{
+}
+
+MetaInfoProtocol::~MetaInfoProtocol()
+{
+}
+
+void MetaInfoProtocol::get(const KURL &url)
+{
+ TQString mimeType = metaData("mimeType");
+ KFileMetaInfo info(url.path(), mimeType);
+
+ TQByteArray arr;
+ TQDataStream stream(arr, IO_WriteOnly);
+
+ stream << info;
+
+ data(arr);
+ finished();
+}
+
+void MetaInfoProtocol::put(const KURL& url, int, bool, bool)
+{
+ TQString mimeType = metaData("mimeType");
+ KFileMetaInfo info;
+
+ TQByteArray arr;
+ readData(arr);
+ TQDataStream stream(arr, IO_ReadOnly);
+
+ stream >> info;
+
+ if (info.isValid())
+ {
+ info.applyChanges();
+ }
+ else
+ {
+ error(ERR_NO_CONTENT, i18n("No metainfo for %1").arg(url.path()));
+ return;
+ }
+ finished();
+}
diff --git a/tdeioslave/metainfo/metainfo.h b/tdeioslave/metainfo/metainfo.h
new file mode 100644
index 000000000..cc179cc98
--- /dev/null
+++ b/tdeioslave/metainfo/metainfo.h
@@ -0,0 +1,38 @@
+/* This file is part of the KDE libraries
+ Copyright (C) 2002 Rolf Magnus <ramagnus@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation version 2.0
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+// $Id$
+
+#ifndef _METAINFO_H_
+#define _METAINFO_H_
+
+#include <tdeio/slavebase.h>
+
+class MetaInfoProtocol : public TDEIO::SlaveBase
+{
+public:
+ MetaInfoProtocol(const TQCString &pool, const TQCString &app);
+ virtual ~MetaInfoProtocol();
+
+ virtual void get(const KURL &url);
+ virtual void put(const KURL& url, int permissions,
+ bool overwrite, bool resume);
+
+};
+
+#endif
diff --git a/kioslave/metainfo/metainfo.protocol b/tdeioslave/metainfo/metainfo.protocol
index f1fa9adac..f1fa9adac 100644
--- a/kioslave/metainfo/metainfo.protocol
+++ b/tdeioslave/metainfo/metainfo.protocol
diff --git a/tdemdi/tdemdi/dockcontainer.cpp b/tdemdi/tdemdi/dockcontainer.cpp
index 5dfe82d64..db29c293f 100644
--- a/tdemdi/tdemdi/dockcontainer.cpp
+++ b/tdemdi/tdemdi/dockcontainer.cpp
@@ -34,7 +34,7 @@
#include <kdebug.h>
#include <kiconloader.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
//TODO: Well, this is already defined in tdeui/kdockwidget.cpp
diff --git a/tdemdi/tdemdi/guiclient.cpp b/tdemdi/tdemdi/guiclient.cpp
index 490eb2b43..2d1e6a68a 100644
--- a/tdemdi/tdemdi/guiclient.cpp
+++ b/tdemdi/tdemdi/guiclient.cpp
@@ -23,7 +23,7 @@
#include <tqpopupmenu.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ktoolbar.h>
#include <klocale.h>
#include <kaction.h>
diff --git a/tdemdi/tdemdichildarea.cpp b/tdemdi/tdemdichildarea.cpp
index ed5b0e009..9370bbbe7 100644
--- a/tdemdi/tdemdichildarea.cpp
+++ b/tdemdi/tdemdichildarea.cpp
@@ -30,7 +30,7 @@
#include "tdemdidefines.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalsettings.h>
diff --git a/tdemdi/tdemdidockcontainer.cpp b/tdemdi/tdemdidockcontainer.cpp
index 3eb3bce44..17f4dcf8a 100644
--- a/tdemdi/tdemdidockcontainer.cpp
+++ b/tdemdi/tdemdidockcontainer.cpp
@@ -33,7 +33,7 @@
#include <kdebug.h>
#include <kiconloader.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
//TODO: Well, this is already defined in tdeui/kdockwidget.cpp
diff --git a/tdemdi/tdemdiguiclient.cpp b/tdemdi/tdemdiguiclient.cpp
index 1bb00faf1..51c693f6e 100644
--- a/tdemdi/tdemdiguiclient.cpp
+++ b/tdemdi/tdemdiguiclient.cpp
@@ -22,7 +22,7 @@
#include <tqpopupmenu.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ktoolbar.h>
#include <kmainwindow.h>
#include <klocale.h>
diff --git a/tdeparts/CMakeLists.txt b/tdeparts/CMakeLists.txt
index 267d64655..341734461 100644
--- a/tdeparts/CMakeLists.txt
+++ b/tdeparts/CMakeLists.txt
@@ -18,9 +18,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
@@ -59,6 +59,6 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 2.1.0
- LINK kio-shared
+ LINK tdeio-shared
DESTINATION ${LIB_INSTALL_DIR}
)
diff --git a/tdeparts/COMMENTS b/tdeparts/COMMENTS
index abf24ca84..32f0be1d9 100644
--- a/tdeparts/COMMENTS
+++ b/tdeparts/COMMENTS
@@ -255,7 +255,7 @@ changes.
<dfaure> ok :-)
<weis> dfaure: Can you have a look at tdeparts/COMMENTS ?
--
-<dfaure> weis: you should have come before. coolo is talking about re-writing libkio.
+<dfaure> weis: you should have come before. coolo is talking about re-writing libtdeio.
<dfaure> well in fact he started the rewrite
dfaure having a look
<weis> dfaure: Unfortunately I am not paid for KDE but for Qt hacking :-( So I fear I have no time for kio anyway.
diff --git a/tdeparts/Makefile.am b/tdeparts/Makefile.am
index 8fea0f517..6796745a9 100644
--- a/tdeparts/Makefile.am
+++ b/tdeparts/Makefile.am
@@ -2,8 +2,8 @@
AM_LDFLAGS = $(LDFLAGS_AS_NEEDED)
-INCLUDES= -I$(srcdir)/../ -I$(top_srcdir)/kio/ -I$(top_srcdir)/libltdl \
- -I$(top_srcdir)/kfile $(all_includes)
+INCLUDES= -I$(srcdir)/../ -I$(top_srcdir)/tdeio/ -I$(top_srcdir)/libltdl \
+ -I$(top_srcdir)/tdefile $(all_includes)
libtdeparts_la_LDFLAGS = $(KDE_MT_LDFLAGS) -version-info 3:0:1 -no-undefined
libtdeparts_la_LIBADD = $(LIB_KIO) $(LIB_QT) $(LIB_TDEUI) $(LIB_TDECORE) $(top_builddir)/dcop/libDCOP.la
diff --git a/tdeparts/browserrun.cpp b/tdeparts/browserrun.cpp
index 4cff3f8a4..f0951b382 100644
--- a/tdeparts/browserrun.cpp
+++ b/tdeparts/browserrun.cpp
@@ -18,9 +18,9 @@
#include "browserrun.h"
#include <kmessagebox.h>
-#include <kfiledialog.h>
-#include <kio/job.h>
-#include <kio/scheduler.h>
+#include <tdefiledialog.h>
+#include <tdeio/job.h>
+#include <tdeio/scheduler.h>
#include <klocale.h>
#include <kprocess.h>
#include <kstringhandler.h>
diff --git a/tdeparts/part.cpp b/tdeparts/part.cpp
index 94d096db5..e0fd4e138 100644
--- a/tdeparts/part.cpp
+++ b/tdeparts/part.cpp
@@ -36,9 +36,9 @@
#include <klocale.h>
#include <ktempfile.h>
#include <kmessagebox.h>
-#include <kio/job.h>
+#include <tdeio/job.h>
#include <kstandarddirs.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kdirnotify_stub.h>
#include <stdio.h>
diff --git a/tdeparts/part.h b/tdeparts/part.h
index 6b2051f72..530da61c3 100644
--- a/tdeparts/part.h
+++ b/tdeparts/part.h
@@ -668,7 +668,7 @@ protected:
* On failure the function should inform the user about the
* problem with an appropriate message box. Standard error
* messages can be constructed using TDEIO::buildErrorString()
- * in combination with the error codes defined in kio/global.h
+ * in combination with the error codes defined in tdeio/global.h
*/
virtual bool saveFile() = 0;
diff --git a/tdeparts/plugin.cpp b/tdeparts/plugin.cpp
index 457caa71f..e1469ad1c 100644
--- a/tdeparts/plugin.cpp
+++ b/tdeparts/plugin.cpp
@@ -35,7 +35,7 @@
#include <kdebug.h>
#include <kxmlguifactory.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ksimpleconfig.h>
using namespace KParts;
diff --git a/tdeparts/tests/Makefile.am b/tdeparts/tests/Makefile.am
index df0a2a5be..0e77c3e4c 100644
--- a/tdeparts/tests/Makefile.am
+++ b/tdeparts/tests/Makefile.am
@@ -1,5 +1,5 @@
-INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/libltdl -I$(top_srcdir)/kfile -I$(top_srcdir)/kio $(all_includes)
+INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/libltdl -I$(top_srcdir)/tdefile -I$(top_srcdir)/tdeio $(all_includes)
AM_LDFLAGS = $(all_libraries)
LDADD = $(LIB_KPARTS)
diff --git a/tdeparts/tests/ghostview.cpp b/tdeparts/tests/ghostview.cpp
index 5d1bbe5b3..d63002d53 100644
--- a/tdeparts/tests/ghostview.cpp
+++ b/tdeparts/tests/ghostview.cpp
@@ -3,7 +3,7 @@
#include <kapplication.h>
#include <kaction.h>
#include <klocale.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kmessagebox.h>
#include <kcmdlineargs.h>
#include <klibloader.h>
diff --git a/tdeprint/CMakeLists.txt b/tdeprint/CMakeLists.txt
index a7a97809f..724b0a0cb 100644
--- a/tdeprint/CMakeLists.txt
+++ b/tdeprint/CMakeLists.txt
@@ -32,9 +32,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdefx
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
${CMAKE_SOURCE_DIR}/kded
)
@@ -84,7 +84,7 @@ set( ${target}_SRCS
tde_add_kpart( ${target} AUTOMOC
SOURCES ${${target}_SRCS}
- LINK kio-shared tdeinit_kded-shared
+ LINK tdeio-shared tdeinit_kded-shared
DEPENDENCIES dcopidl dcopidl2cpp
DESTINATION ${PLUGIN_INSTALL_DIR}
)
@@ -104,7 +104,7 @@ set( ${target}_SRCS
kpgeneralpage.cpp kpqtpage.cpp kmthreadjob.cpp
kpipeprocess.cpp kpfilterpage.cpp kmspecialmanager.cpp
tdeprintcheck.cpp plugincombobox.cpp kpreloadobject.cpp
- kfilelist.cpp kprintaction.cpp kpfileselectpage.cpp
+ tdefilelist.cpp kprintaction.cpp kpfileselectpage.cpp
treecombobox.cpp kxmlcommand.cpp util.cpp printerfilter.cpp
marginpreview.cpp marginvaluewidget.cpp marginwidget.cpp
kpmarginpage.cpp messagewindow.cpp posterpreview.cpp
@@ -116,7 +116,7 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 4.2.0
- LINK kio-shared
+ LINK tdeio-shared
DEPENDENCIES dcopidl dcopidl2cpp
DESTINATION ${LIB_INSTALL_DIR}
)
diff --git a/tdeprint/Makefile.am b/tdeprint/Makefile.am
index b70e46e93..7ea8df12a 100644
--- a/tdeprint/Makefile.am
+++ b/tdeprint/Makefile.am
@@ -23,7 +23,7 @@ libtdeprint_la_SOURCES = kmfactory.cpp kmjob.cpp kmjobmanager.cpp kmmanager.cpp
kprintpreview.cpp kprintdialog.cpp kprinter.cpp kprinterimpl.cpp kprintdialogpage.cpp \
kpcopiespage.cpp kpdriverpage.cpp kprinterpropertydialog.cpp kpgeneralpage.cpp kpqtpage.cpp \
kmthreadjob.cpp kpipeprocess.cpp kpfilterpage.cpp \
- kmspecialmanager.cpp tdeprintcheck.cpp plugincombobox.cpp kpreloadobject.cpp kfilelist.cpp \
+ kmspecialmanager.cpp tdeprintcheck.cpp plugincombobox.cpp kpreloadobject.cpp tdefilelist.cpp \
kprintaction.cpp kpfileselectpage.cpp treecombobox.cpp kmfactory.skel kxmlcommand.cpp \
util.cpp printerfilter.cpp marginpreview.cpp marginvaluewidget.cpp marginwidget.cpp \
kpmarginpage.cpp messagewindow.cpp posterpreview.cpp kpposterpage.cpp foomatic2loader.cpp \
@@ -40,7 +40,7 @@ noinst_HEADERS = kmdbentry.h kmfactory.h \
kpcopiespage.h kpdriverpage.h kprinterpropertydialog.h kpgeneralpage.h \
kpqtpage.h kprintprocess.h kmthreadjob.h kpipeprocess.h tdeprintd.h \
kpfilterpage.h kmspecialmanager.h tdeprintcheck.h plugincombobox.h \
- kfilelist.h kpfileselectpage.h treecombobox.h kxmlcommand.h \
+ tdefilelist.h kpfileselectpage.h treecombobox.h kxmlcommand.h \
util.h driverparse.h printerfilter.h marginpreview.h marginwidget.h \
marginvaluewidget.h kpmarginpage.h messagewindow.h \
posterpreview.h kpposterpage.h foomatic2loader.h ppdloader.h
@@ -104,7 +104,7 @@ noinst_LIBRARIES = libdriverparse.a
libdriverparse_a_SOURCES = driverparse.c
update_DATA = tdeprintrc.upd
-updatedir = $(kde_datadir)/kconf_update
+updatedir = $(kde_datadir)/tdeconf_update
messages: rc.cpp
$(EXTRACTRC) `find . -name "*.rc" -o -name "*.ui" | grep -v /cupsdconf` >> rc.cpp
diff --git a/tdeprint/cups/CMakeLists.txt b/tdeprint/cups/CMakeLists.txt
index 62c48618c..aa882ca7e 100644
--- a/tdeprint/cups/CMakeLists.txt
+++ b/tdeprint/cups/CMakeLists.txt
@@ -26,9 +26,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdecore/network
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
${CMAKE_SOURCE_DIR}/tdeprint
${CMAKE_SOURCE_DIR}/tdeprint/management
)
diff --git a/tdeprint/cups/Makefile.am b/tdeprint/cups/Makefile.am
index 64e8b997d..cdbb0b92c 100644
--- a/tdeprint/cups/Makefile.am
+++ b/tdeprint/cups/Makefile.am
@@ -2,7 +2,7 @@ AM_CPPFLAGS = -D_TDEPRINT_COMPILE
SUBDIRS = cupsdconf2
-INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/kio -I$(top_srcdir)/kfile -I$(top_srcdir)/tdeprint -I$(top_srcdir)/tdeprint/management -I$(top_srcdir)/tdecore/network $(all_includes)
+INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/tdeio -I$(top_srcdir)/tdefile -I$(top_srcdir)/tdeprint -I$(top_srcdir)/tdeprint/management -I$(top_srcdir)/tdecore/network $(all_includes)
kde_module_LTLIBRARIES = tdeprint_cups.la
diff --git a/tdeprint/cups/cupsaddsmb2.cpp b/tdeprint/cups/cupsaddsmb2.cpp
index f0057235e..685ce6e7e 100644
--- a/tdeprint/cups/cupsaddsmb2.cpp
+++ b/tdeprint/cups/cupsaddsmb2.cpp
@@ -30,7 +30,7 @@
#include <kmessagebox.h>
#include <tqmessagebox.h>
#include <tqfile.h>
-#include <kio/passdlg.h>
+#include <tdeio/passdlg.h>
#include <kdebug.h>
#include <kseparator.h>
#include <kactivelabel.h>
diff --git a/tdeprint/cups/cupsdconf2/CMakeLists.txt b/tdeprint/cups/cupsdconf2/CMakeLists.txt
index ceee1bc47..749d84182 100644
--- a/tdeprint/cups/cupsdconf2/CMakeLists.txt
+++ b/tdeprint/cups/cupsdconf2/CMakeLists.txt
@@ -17,9 +17,9 @@ include_directories(
${CMAKE_BINARY_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
@@ -50,5 +50,5 @@ set( ${target}_SRCS
tde_add_tdeinit_executable( ${target} AUTOMOC
SOURCES ${${target}_SRCS}
- LINK kio-shared ${CUPS_LIBRARIES}
+ LINK tdeio-shared ${CUPS_LIBRARIES}
)
diff --git a/tdeprint/cups/cupsdconf2/Makefile.am b/tdeprint/cups/cupsdconf2/Makefile.am
index eb7e42159..b0c111bf8 100644
--- a/tdeprint/cups/cupsdconf2/Makefile.am
+++ b/tdeprint/cups/cupsdconf2/Makefile.am
@@ -1,6 +1,6 @@
#$Id$
-INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/kio -I$(top_srcdir)/kfile $(all_includes)
+INCLUDES= -I$(top_srcdir) -I$(top_srcdir)/tdeio -I$(top_srcdir)/tdefile $(all_includes)
bin_PROGRAMS =
lib_LTLIBRARIES =
diff --git a/tdeprint/cups/cupsdconf2/cupsdconf.cpp b/tdeprint/cups/cupsdconf2/cupsdconf.cpp
index a05e44d6f..102ead1c8 100644
--- a/tdeprint/cups/cupsdconf2/cupsdconf.cpp
+++ b/tdeprint/cups/cupsdconf2/cupsdconf.cpp
@@ -24,7 +24,7 @@
#include <tqregexp.h>
#include <klocale.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <stdlib.h>
#include <cups/cups.h>
diff --git a/tdeprint/cups/cupsdconf2/cupsddialog.cpp b/tdeprint/cups/cupsdconf2/cupsddialog.cpp
index ada83d362..d221f2f04 100644
--- a/tdeprint/cups/cupsdconf2/cupsddialog.cpp
+++ b/tdeprint/cups/cupsdconf2/cupsddialog.cpp
@@ -41,7 +41,7 @@
#include <kiconloader.h>
#include <tqstringlist.h>
#include <tqwhatsthis.h>
-#include <kio/passdlg.h>
+#include <tdeio/passdlg.h>
#include <kguiitem.h>
#include <kprocess.h>
diff --git a/tdeprint/cups/cupsdconf2/cupsdlogpage.cpp b/tdeprint/cups/cupsdconf2/cupsdlogpage.cpp
index 61a89f933..00972e368 100644
--- a/tdeprint/cups/cupsdconf2/cupsdlogpage.cpp
+++ b/tdeprint/cups/cupsdconf2/cupsdlogpage.cpp
@@ -28,7 +28,7 @@
#include <tqwhatsthis.h>
#include <klocale.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
CupsdLogPage::CupsdLogPage(TQWidget *parent, const char *name)
: CupsdPage(parent, name)
diff --git a/tdeprint/cups/cupsdconf2/qdirlineedit.cpp b/tdeprint/cups/cupsdconf2/qdirlineedit.cpp
index 7cf0ea74e..25c984ec4 100644
--- a/tdeprint/cups/cupsdconf2/qdirlineedit.cpp
+++ b/tdeprint/cups/cupsdconf2/qdirlineedit.cpp
@@ -22,7 +22,7 @@
#include <tqlineedit.h>
#include <tqlayout.h>
#include <kpushbutton.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kiconloader.h>
QDirLineEdit::QDirLineEdit(bool file, TQWidget *parent, const char *name)
diff --git a/tdeprint/cups/cupsdconf2/qdirmultilineedit.cpp b/tdeprint/cups/cupsdconf2/qdirmultilineedit.cpp
index b1bd96ee6..c2fcaab7b 100644
--- a/tdeprint/cups/cupsdconf2/qdirmultilineedit.cpp
+++ b/tdeprint/cups/cupsdconf2/qdirmultilineedit.cpp
@@ -24,7 +24,7 @@
#include <tqpushbutton.h>
#include <klistview.h>
#include <klocale.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kiconloader.h>
QDirMultiLineEdit::QDirMultiLineEdit(TQWidget *parent, const char *name)
diff --git a/tdeprint/cups/cupsinfos.cpp b/tdeprint/cups/cupsinfos.cpp
index 7962b13ef..5013b57cc 100644
--- a/tdeprint/cups/cupsinfos.cpp
+++ b/tdeprint/cups/cupsinfos.cpp
@@ -22,10 +22,10 @@
#include "kmtimer.h"
#include "messagewindow.h"
-#include <kio/passdlg.h>
-#include <kio/authinfo.h>
+#include <tdeio/passdlg.h>
+#include <tdeio/authinfo.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kapplication.h>
#include <dcopclient.h>
#include <kdebug.h>
diff --git a/tdeprint/cups/kmconfigcups.cpp b/tdeprint/cups/kmconfigcups.cpp
index 55a96d9d5..1b0ccdaea 100644
--- a/tdeprint/cups/kmconfigcups.cpp
+++ b/tdeprint/cups/kmconfigcups.cpp
@@ -21,7 +21,7 @@
#include "kmcupsconfigwidget.h"
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdialog.h>
#include <tqlayout.h>
diff --git a/tdeprint/cups/kmconfigcupsdir.cpp b/tdeprint/cups/kmconfigcupsdir.cpp
index 2fe66d787..6f16f5dfa 100644
--- a/tdeprint/cups/kmconfigcupsdir.cpp
+++ b/tdeprint/cups/kmconfigcupsdir.cpp
@@ -23,7 +23,7 @@
#include <kurlrequester.h>
#include <klocale.h>
#include <kdialog.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqgroupbox.h>
#include <tqlayout.h>
#include <kcursor.h>
diff --git a/tdeprint/cups/kmcupsconfigwidget.cpp b/tdeprint/cups/kmcupsconfigwidget.cpp
index ce005fc3b..a62583b1b 100644
--- a/tdeprint/cups/kmcupsconfigwidget.cpp
+++ b/tdeprint/cups/kmcupsconfigwidget.cpp
@@ -30,7 +30,7 @@
#include <klocale.h>
#include <kcursor.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstringhandler.h>
class PortValidator : public TQIntValidator
diff --git a/tdeprint/cups/kmcupsmanager.cpp b/tdeprint/cups/kmcupsmanager.cpp
index e5d45a42a..d444db1f2 100644
--- a/tdeprint/cups/kmcupsmanager.cpp
+++ b/tdeprint/cups/kmcupsmanager.cpp
@@ -43,7 +43,7 @@
#include <kdebug.h>
#include <kapplication.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstandarddirs.h>
#include <tdesocketbase.h>
#include <klibloader.h>
diff --git a/tdeprint/ext/kextprinterimpl.cpp b/tdeprint/ext/kextprinterimpl.cpp
index c976f54e0..8959aa3e8 100644
--- a/tdeprint/ext/kextprinterimpl.cpp
+++ b/tdeprint/ext/kextprinterimpl.cpp
@@ -22,7 +22,7 @@
#include <tqfile.h>
#include <kstandarddirs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
KExtPrinterImpl::KExtPrinterImpl(TQObject *parent, const char *name, const TQStringList & /*args*/)
diff --git a/tdeprint/kfilelist.cpp b/tdeprint/kfilelist.cpp
deleted file mode 100644
index 44bd13a87..000000000
--- a/tdeprint/kfilelist.cpp
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (c) 2001 Michael Goffioul <tdeprint@swing.be>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License version 2 as published by the Free Software Foundation.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- **/
-
-#include "kfilelist.h"
-
-#include <tqtoolbutton.h>
-#include <tqlabel.h>
-#include <tqlayout.h>
-#include <tqtooltip.h>
-#include <tqheader.h>
-#include <tqwhatsthis.h>
-
-#include <kio/netaccess.h>
-#include <kurldrag.h>
-#include <kfiledialog.h>
-#include <klocale.h>
-#include <kiconloader.h>
-#include <klistview.h>
-#include <krun.h>
-#include <kmimetype.h>
-
-KFileList::KFileList(TQWidget *parent, const char *name)
-: TQWidget(parent, name)
-{
- //WhatsThis strings.... (added by pfeifle@kde.org)
- TQString whatsThisAddFileButton = i18n( " <qt> <b>Add File button</b>"
- " <p>This button calls the <em>'File Open'</em> dialog to let you"
- " select a file for printing. Note, that "
- " <ul><li>you can select ASCII or International Text, PDF,"
- " PostScript, JPEG, TIFF, PNG, GIF and many other graphic"
- " formats."
- " <li>you can select various files from different paths"
- " and send them as one \"multi-file job\" to the printing"
- " system."
- " </ul>"
- " </qt>" );
-
- TQString whatsThisRemoveFileButton = i18n(" <qt> <b>Remove File button</b>"
- " <p>This button removes the highlighted file from the"
- " list of to-be-printed files."
- " </qt>" );
-
- TQString whatsThisMoveFileUpButton = i18n(" <qt> <b>Move File Up button</b>"
- " <p>This button moves the highlighted file up in the list"
- " of files to be printed.</p>"
- " <p>In effect, this changes the order"
- " of the files' printout.</p>"
- " </qt>" );
-
- TQString whatsThisMoveFileDownButton = i18n(" <qt> <b>Move File Down button</b>"
- " <p>This button moves the highlighted file down in the list"
- " of files to be printed.</p>"
- " <p>In effect, this changes the order"
- " of the files' printout.</p>"
- " </qt>" );
-
- TQString whatsThisOpenFileButton = i18n( " <qt> <b>File Open button</b>"
- " <p>This button tries to open the highlighted file, so"
- " you can view or edit it before you send it to the printing"
- " system.</p>"
- " <p>If you open"
- " files, TDEPrint will use the application matching the MIME type of"
- " the file.</p>"
- " </qt>" );
-
- TQString whatsThisFileSelectionListview = i18n( " <qt> <b>File List view</b>"
- " <p>This list displays all the files you selected for printing."
- " You can see the file name(s), file path(s) and the file"
- " (MIME) type(s) as determined by TDEPrint. You may re-arrange the "
- " initial order of the list "
- " with the help of the arrow buttons on the right.</p>"
- " <p>The files will be printed as a single job,"
- " in the same order as displayed in the list.</p>"
- " <p><b>Note:</b> You can select multiple files. The files may be in multiple"
- " locations. The files may be of multiple MIME types. The buttons on the right"
- " side let you add more files, remove already selected files from the list, "
- " re-order the list (by moving files up or down), and open files. If you open"
- " files, TDEPrint will use the application matching the MIME type of"
- " the file.</p>"
- " </qt>" );
-
- m_block = false;
-
- m_files = new KListView(this);
- m_files->addColumn(i18n("Name"));
- m_files->addColumn(i18n("Type"));
- m_files->addColumn(i18n("Path"));
- m_files->setAllColumnsShowFocus(true);
- m_files->setSorting(-1);
- m_files->setAcceptDrops(false);
- m_files->setSelectionMode(TQListView::Extended);
- m_files->header()->setStretchEnabled(true, 2);
- TQWhatsThis::add(m_files, whatsThisFileSelectionListview);
- connect(m_files, TQT_SIGNAL(selectionChanged()), TQT_SLOT(slotSelectionChanged()));
-
- m_add = new TQToolButton(this);
- m_add->setIconSet(SmallIconSet("fileopen"));
- connect(m_add, TQT_SIGNAL(clicked()), TQT_SLOT(slotAddFile()));
- TQToolTip::add(m_add, i18n("Add file"));
- TQWhatsThis::add(m_add, whatsThisAddFileButton);
-
- m_remove = new TQToolButton(this);
- m_remove->setIconSet(SmallIconSet("remove"));
- connect(m_remove, TQT_SIGNAL(clicked()), TQT_SLOT(slotRemoveFile()));
- TQToolTip::add(m_remove, i18n("Remove file"));
- TQWhatsThis::add(m_remove, whatsThisRemoveFileButton);
- m_remove->setEnabled(false);
-
- m_open = new TQToolButton(this);
- m_open->setIconSet(SmallIconSet("filefind"));
- connect(m_open, TQT_SIGNAL(clicked()), TQT_SLOT(slotOpenFile()));
- TQToolTip::add(m_open, i18n("Open file"));
- TQWhatsThis::add(m_open, whatsThisOpenFileButton);
- m_open->setEnabled(false);
-
- m_up = new TQToolButton(this);
- m_up->setIconSet(SmallIconSet("up"));
- connect(m_up, TQT_SIGNAL(clicked()), TQT_SLOT(slotUp()));
- TQToolTip::add(m_up, i18n("Move up"));
- TQWhatsThis::add(m_up, whatsThisMoveFileUpButton);
- m_up->setEnabled(false);
-
- m_down = new TQToolButton(this);
- m_down->setIconSet(SmallIconSet("down"));
- connect(m_down, TQT_SIGNAL(clicked()), TQT_SLOT(slotDown()));
- TQToolTip::add(m_down, i18n("Move down"));
- TQWhatsThis::add(m_down, whatsThisMoveFileDownButton);
- m_down->setEnabled(false);
-
- setAcceptDrops(true);
-
- TQToolTip::add(m_files, i18n(
- "Drag file(s) here or use the button to open a file dialog. "
- "Leave empty for <b>&lt;STDIN&gt;</b>."));
-
- TQHBoxLayout *l0 = new TQHBoxLayout(this, 0, KDialog::spacingHint());
- TQVBoxLayout *l1 = new TQVBoxLayout(0, 0, 1);
- l0->addWidget(m_files);
- l0->addLayout(l1);
- l1->addWidget(m_add);
- l1->addWidget(m_remove);
- l1->addWidget(m_open);
- l1->addSpacing(10);
- l1->addWidget(m_up);
- l1->addWidget(m_down);
- l1->addStretch(1);
-}
-
-KFileList::~KFileList()
-{
-}
-
-void KFileList::dragEnterEvent(TQDragEnterEvent *e)
-{
- e->accept(KURLDrag::canDecode(e));
-}
-
-void KFileList::dropEvent(TQDropEvent *e)
-{
- KURL::List files;
- if (KURLDrag::decode(e, files))
- {
- addFiles(files);
- }
-}
-
-void KFileList::addFiles(const KURL::List& files)
-{
- if (files.count() > 0)
- {
- // search last item in current list, to add new ones at the end
- TQListViewItem *item = m_files->firstChild();
- while (item && item->nextSibling())
- item = item->nextSibling();
-
- for (KURL::List::ConstIterator it=files.begin(); it!=files.end(); ++it)
- {
- KMimeType::Ptr mime = KMimeType::findByURL( *it, 0, true, false);
- item = new TQListViewItem(m_files, item, (*it).fileName(), mime->comment(), (*it).url());
- item->setPixmap(0, mime->pixmap(*it, KIcon::Small));
- }
-
- slotSelectionChanged();
- /*
- if (m_files->childCount() > 0)
- {
- m_remove->setEnabled(true);
- m_open->setEnabled(true);
- if (m_files->currentItem() == 0)
- m_files->setSelected(m_files->firstChild(), true);
- }
- */
- }
-}
-
-void KFileList::setFileList(const TQStringList& files)
-{
- m_files->clear();
- TQListViewItem *item = 0;
- for (TQStringList::ConstIterator it=files.begin(); it!=files.end(); ++it)
- {
- KURL url = KURL::fromPathOrURL( *it );
- KMimeType::Ptr mime = KMimeType::findByURL(url, 0, true, false);
- item = new TQListViewItem(m_files, item, url.fileName(), mime->comment(), url.url());
- item->setPixmap(0, mime->pixmap(url, KIcon::Small));
- }
- slotSelectionChanged();
-}
-
-TQStringList KFileList::fileList() const
-{
- TQStringList l;
- TQListViewItem *item = m_files->firstChild();
- while (item)
- {
- l << item->text(2);
- item = item->nextSibling();
- }
- return l;
-}
-
-void KFileList::slotAddFile()
-{
- KURL::List fnames = KFileDialog::getOpenURLs(TQString::null, TQString::null, this);
- if (!fnames.empty())
- addFiles(fnames);
-}
-
-void KFileList::slotRemoveFile()
-{
- TQPtrList<TQListViewItem> l;
- selection(l);
- l.setAutoDelete(true);
- m_block = true;
- l.clear();
- m_block = false;
- slotSelectionChanged();
-}
-
-void KFileList::slotOpenFile()
-{
- TQListViewItem *item = m_files->currentItem();
- if (item)
- {
- KURL url( item->text( 2 ) );
- new KRun(url);
- }
-}
-
-TQSize KFileList::sizeHint() const
-{
- return TQSize(100, 100);
-}
-
-void KFileList::selection(TQPtrList<TQListViewItem>& l)
-{
- l.setAutoDelete(false);
- TQListViewItem *item = m_files->firstChild();
- while (item)
- {
- if (item->isSelected())
- l.append(item);
- item = item->nextSibling();
- }
-}
-
-void KFileList::slotSelectionChanged()
-{
- if (m_block)
- return;
-
- TQPtrList<TQListViewItem> l;
- selection(l);
- m_remove->setEnabled(l.count() > 0);
- m_open->setEnabled(l.count() == 1);
- m_up->setEnabled(l.count() == 1 && l.first()->itemAbove());
- m_down->setEnabled(l.count() == 1 && l.first()->itemBelow());
-}
-
-void KFileList::slotUp()
-{
- TQPtrList<TQListViewItem> l;
- selection(l);
- if (l.count() == 1 && l.first()->itemAbove())
- {
- TQListViewItem *item(l.first()), *clone;
- clone = new TQListViewItem(m_files, item->itemAbove()->itemAbove(), item->text(0), item->text(1), item->text(2));
- clone->setPixmap(0, *(item->pixmap(0)));
- delete item;
- m_files->setCurrentItem(clone);
- m_files->setSelected(clone, true);
- }
-}
-
-void KFileList::slotDown()
-{
- TQPtrList<TQListViewItem> l;
- selection(l);
- if (l.count() == 1 && l.first()->itemBelow())
- {
- TQListViewItem *item(l.first()), *clone;
- clone = new TQListViewItem(m_files, item->itemBelow(), item->text(0), item->text(1), item->text(2));
- clone->setPixmap(0, *(item->pixmap(0)));
- delete item;
- m_files->setCurrentItem(clone);
- m_files->setSelected(clone, true);
- }
-}
-
-#include "kfilelist.moc"
diff --git a/tdeprint/kmfactory.cpp b/tdeprint/kmfactory.cpp
index a1b4ad4ee..7d972cbf8 100644
--- a/tdeprint/kmfactory.cpp
+++ b/tdeprint/kmfactory.cpp
@@ -32,7 +32,7 @@
#include <tqsettings.h>
#include <klibloader.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <kdebug.h>
@@ -43,7 +43,7 @@
#include <kapplication.h>
#include <dcopclient.h>
#include <dcopref.h>
-#include <kio/authinfo.h>
+#include <tdeio/authinfo.h>
#include <unistd.h>
diff --git a/tdeprint/kmjobmanager.cpp b/tdeprint/kmjobmanager.cpp
index 3496cdb1d..2a0e2ae50 100644
--- a/tdeprint/kmjobmanager.cpp
+++ b/tdeprint/kmjobmanager.cpp
@@ -24,7 +24,7 @@
#include <kaction.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
KMJobManager::KMJobManager(TQObject *parent, const char *name)
: TQObject(parent,name)
diff --git a/tdeprint/kmmanager.cpp b/tdeprint/kmmanager.cpp
index 57e06994d..a597b94b6 100644
--- a/tdeprint/kmmanager.cpp
+++ b/tdeprint/kmmanager.cpp
@@ -29,7 +29,7 @@
#include <zlib.h>
#include <tqfile.h>
#include <kstandarddirs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
#include <kdebug.h>
#include <kapplication.h>
diff --git a/tdeprint/kmprinter.cpp b/tdeprint/kmprinter.cpp
index b18116ef8..22fc9d970 100644
--- a/tdeprint/kmprinter.cpp
+++ b/tdeprint/kmprinter.cpp
@@ -22,7 +22,7 @@
#include "driver.h"
#include <klocale.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
KMPrinter::KMPrinter()
: KMObject()
diff --git a/tdeprint/kpfileselectpage.cpp b/tdeprint/kpfileselectpage.cpp
index f3131717a..6847ade2b 100644
--- a/tdeprint/kpfileselectpage.cpp
+++ b/tdeprint/kpfileselectpage.cpp
@@ -18,7 +18,7 @@
**/
#include "kpfileselectpage.h"
-#include "kfilelist.h"
+#include "tdefilelist.h"
#include <tqlayout.h>
#include <tqstringlist.h>
diff --git a/tdeprint/kprintdialog.cpp b/tdeprint/kprintdialog.cpp
index 06a61e1c0..518f544f6 100644
--- a/tdeprint/kprintdialog.cpp
+++ b/tdeprint/kprintdialog.cpp
@@ -53,16 +53,16 @@
#include <klocale.h>
#include <kiconloader.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kurlrequester.h>
#include <klineedit.h>
#include <kdebug.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kguiitem.h>
#include <kstdguiitem.h>
#include <kapplication.h>
-#include <kio/renamedlg.h>
+#include <tdeio/renamedlg.h>
#include <time.h>
diff --git a/tdeprint/kprinter.cpp b/tdeprint/kprinter.cpp
index 3664b4157..4d34280a0 100644
--- a/tdeprint/kprinter.cpp
+++ b/tdeprint/kprinter.cpp
@@ -36,7 +36,7 @@
#include <kapplication.h>
#include <kstandarddirs.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <krun.h>
#include <knotifyclient.h>
#include <kdebug.h>
diff --git a/tdeprint/kprinterimpl.cpp b/tdeprint/kprinterimpl.cpp
index 5c3d840a0..fd05024a3 100644
--- a/tdeprint/kprinterimpl.cpp
+++ b/tdeprint/kprinterimpl.cpp
@@ -41,7 +41,7 @@
#include <kmimemagic.h>
#include <kmessagebox.h>
#include <kprocess.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <stdlib.h>
diff --git a/tdeprint/kprintpreview.cpp b/tdeprint/kprintpreview.cpp
index d5102ed3c..e81a23b08 100644
--- a/tdeprint/kprintpreview.cpp
+++ b/tdeprint/kprintpreview.cpp
@@ -37,7 +37,7 @@
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ktoolbar.h>
#include <kmimetype.h>
diff --git a/tdeprint/lpd/kmlpdmanager.cpp b/tdeprint/lpd/kmlpdmanager.cpp
index 5251b990a..a11f79304 100644
--- a/tdeprint/lpd/kmlpdmanager.cpp
+++ b/tdeprint/lpd/kmlpdmanager.cpp
@@ -34,7 +34,7 @@
#include <klocale.h>
#include <kstandarddirs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kprocess.h>
#include <pwd.h>
diff --git a/tdeprint/lpr/kmconfiglpr.cpp b/tdeprint/lpr/kmconfiglpr.cpp
index b5c43ebef..8a6988188 100644
--- a/tdeprint/lpr/kmconfiglpr.cpp
+++ b/tdeprint/lpr/kmconfiglpr.cpp
@@ -25,7 +25,7 @@
#include <tqlayout.h>
#include <tqgroupbox.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
KMConfigLpr::KMConfigLpr(TQWidget *parent, const char *name)
: KMConfigPage(parent, name)
diff --git a/tdeprint/lpr/lprsettings.cpp b/tdeprint/lpr/lprsettings.cpp
index 30b650c17..a539f4160 100644
--- a/tdeprint/lpr/lprsettings.cpp
+++ b/tdeprint/lpr/lprsettings.cpp
@@ -21,7 +21,7 @@
#include "kmmanager.h"
#include "kmfactory.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqfile.h>
#include <tqtextstream.h>
diff --git a/tdeprint/management/CMakeLists.txt b/tdeprint/management/CMakeLists.txt
index ccaf2a70a..47dcda996 100644
--- a/tdeprint/management/CMakeLists.txt
+++ b/tdeprint/management/CMakeLists.txt
@@ -24,9 +24,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdefx
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
${CMAKE_SOURCE_DIR}/tdeprint
)
diff --git a/tdeprint/management/Makefile.am b/tdeprint/management/Makefile.am
index f0d1acd9f..f9f5c0ce4 100644
--- a/tdeprint/management/Makefile.am
+++ b/tdeprint/management/Makefile.am
@@ -1,6 +1,6 @@
AM_CPPFLAGS = -D_TDEPRINT_COMPILE
-INCLUDES= -I$(top_srcdir)/tdefx -I$(top_srcdir)/tdeprint -I$(top_builddir)/tdeprint -I$(top_srcdir)/kio -I$(top_srcdir)/kfile -I$(top_srcdir) $(all_includes)
+INCLUDES= -I$(top_srcdir)/tdefx -I$(top_srcdir)/tdeprint -I$(top_builddir)/tdeprint -I$(top_srcdir)/tdeio -I$(top_srcdir)/tdefile -I$(top_srcdir) $(all_includes)
lib_LTLIBRARIES = libtdeprint_management.la
kde_module_LTLIBRARIES = libtdeprint_management_module.la
diff --git a/tdeprint/management/kmconfigdialog.cpp b/tdeprint/management/kmconfigdialog.cpp
index ee63e9eeb..b3ef6e329 100644
--- a/tdeprint/management/kmconfigdialog.cpp
+++ b/tdeprint/management/kmconfigdialog.cpp
@@ -32,7 +32,7 @@
#include <tqlayout.h>
#include <klocale.h>
#include <kiconloader.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
KMConfigDialog::KMConfigDialog(TQWidget *parent, const char *name)
: KDialogBase(IconList,i18n("TDE Print Configuration"),Ok|Cancel,Ok,parent,name,true,true)
diff --git a/tdeprint/management/kmconfigfilter.cpp b/tdeprint/management/kmconfigfilter.cpp
index 2eea53b0e..bcbe1b0f7 100644
--- a/tdeprint/management/kmconfigfilter.cpp
+++ b/tdeprint/management/kmconfigfilter.cpp
@@ -29,7 +29,7 @@
#include <tqapplication.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kiconloader.h>
#include <klistbox.h>
#include <kdialog.h>
diff --git a/tdeprint/management/kmconfigfonts.cpp b/tdeprint/management/kmconfigfonts.cpp
index b933cab00..91861f5ca 100644
--- a/tdeprint/management/kmconfigfonts.cpp
+++ b/tdeprint/management/kmconfigfonts.cpp
@@ -29,10 +29,10 @@
#include <tqwhatsthis.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kiconloader.h>
#include <kurlrequester.h>
-#include <kfile.h>
+#include <tdefile.h>
#include <klistview.h>
#include <kdialog.h>
diff --git a/tdeprint/management/kmconfiggeneral.cpp b/tdeprint/management/kmconfiggeneral.cpp
index f02cfa854..b7c0a1522 100644
--- a/tdeprint/management/kmconfiggeneral.cpp
+++ b/tdeprint/management/kmconfiggeneral.cpp
@@ -30,7 +30,7 @@
#include <kurlrequester.h>
#include <krun.h>
#include <kmimemagic.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <knuminput.h>
#include <kmessagebox.h>
#include <kcursor.h>
diff --git a/tdeprint/management/kmconfigjobs.cpp b/tdeprint/management/kmconfigjobs.cpp
index 0fb40fb7b..667b40381 100644
--- a/tdeprint/management/kmconfigjobs.cpp
+++ b/tdeprint/management/kmconfigjobs.cpp
@@ -24,7 +24,7 @@
#include <knuminput.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdialog.h>
KMConfigJobs::KMConfigJobs(TQWidget *parent, const char *name)
diff --git a/tdeprint/management/kmconfigpreview.cpp b/tdeprint/management/kmconfigpreview.cpp
index 548968701..3d084f735 100644
--- a/tdeprint/management/kmconfigpreview.cpp
+++ b/tdeprint/management/kmconfigpreview.cpp
@@ -26,7 +26,7 @@
#include <klocale.h>
#include <kurlrequester.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdialog.h>
KMConfigPreview::KMConfigPreview(TQWidget *parent, const char *name)
diff --git a/tdeprint/management/kmdriverdbwidget.cpp b/tdeprint/management/kmdriverdbwidget.cpp
index 704a20db5..1b05f8e9c 100644
--- a/tdeprint/management/kmdriverdbwidget.cpp
+++ b/tdeprint/management/kmdriverdbwidget.cpp
@@ -35,9 +35,9 @@
#include <klocale.h>
#include <kcursor.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kguiitem.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
KMDriverDbWidget::KMDriverDbWidget(TQWidget *parent, const char *name)
: TQWidget(parent,name)
diff --git a/tdeprint/management/kmjobviewer.cpp b/tdeprint/management/kmjobviewer.cpp
index da8a98016..5e4561c19 100644
--- a/tdeprint/management/kmjobviewer.cpp
+++ b/tdeprint/management/kmjobviewer.cpp
@@ -44,7 +44,7 @@
#include <kmenubar.h>
#include <kdebug.h>
#include <twin.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
#include <tqtimer.h>
#include <tqlayout.h>
#include <stdlib.h>
@@ -52,7 +52,7 @@
#include <kdialogbase.h>
#include <tqcheckbox.h>
#include <kurldrag.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#undef m_manager
#define m_manager KMFactory::self()->jobManager()
diff --git a/tdeprint/management/kmmainview.cpp b/tdeprint/management/kmmainview.cpp
index daafbff97..858fca0fc 100644
--- a/tdeprint/management/kmmainview.cpp
+++ b/tdeprint/management/kmmainview.cpp
@@ -45,7 +45,7 @@
#include <kmessagebox.h>
#include <kaction.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ktoolbar.h>
#include <ktoolbarbutton.h>
#include <kdebug.h>
diff --git a/tdeprint/management/kmspecialprinterdlg.cpp b/tdeprint/management/kmspecialprinterdlg.cpp
index 9e3775c14..ba6801769 100644
--- a/tdeprint/management/kmspecialprinterdlg.cpp
+++ b/tdeprint/management/kmspecialprinterdlg.cpp
@@ -37,7 +37,7 @@
#include <klocale.h>
#include <kmessagebox.h>
#include <kicondialog.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kseparator.h>
KMSpecialPrinterDlg::KMSpecialPrinterDlg(TQWidget *parent, const char *name)
diff --git a/tdeprint/management/kmtimer.cpp b/tdeprint/management/kmtimer.cpp
index 5acc27351..a45a9caa0 100644
--- a/tdeprint/management/kmtimer.cpp
+++ b/tdeprint/management/kmtimer.cpp
@@ -20,7 +20,7 @@
#include "kmtimer.h"
#include "kmfactory.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
KMTimer* KMTimer::m_self = 0;
diff --git a/tdeprint/management/kmwdrivertest.cpp b/tdeprint/management/kmwdrivertest.cpp
index 0e0cd306b..4f57762aa 100644
--- a/tdeprint/management/kmwdrivertest.cpp
+++ b/tdeprint/management/kmwdrivertest.cpp
@@ -32,7 +32,7 @@
#include <kapplication.h>
#include <kmessagebox.h>
#include <kguiitem.h>
-#include <kio/netaccess.h>
+#include <tdeio/netaccess.h>
KMWDriverTest::KMWDriverTest(TQWidget *parent, const char *name)
: KMWizardPage(parent,name)
diff --git a/tdeprint/management/kmwfile.cpp b/tdeprint/management/kmwfile.cpp
index 1fbaf45ff..f3b54dcdc 100644
--- a/tdeprint/management/kmwfile.cpp
+++ b/tdeprint/management/kmwfile.cpp
@@ -26,7 +26,7 @@
#include <kurlrequester.h>
#include <klocale.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
KMWFile::KMWFile(TQWidget *parent, const char *name)
: KMWizardPage(parent,name)
diff --git a/tdeprint/management/kxmlcommandselector.cpp b/tdeprint/management/kxmlcommandselector.cpp
index 6f2b4485e..093d2a909 100644
--- a/tdeprint/management/kxmlcommandselector.cpp
+++ b/tdeprint/management/kxmlcommandselector.cpp
@@ -33,7 +33,7 @@
#include <klocale.h>
#include <kiconloader.h>
#include <kmessagebox.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kseparator.h>
#include <kguiitem.h>
#include <kactivelabel.h>
diff --git a/tdeprint/printerfilter.cpp b/tdeprint/printerfilter.cpp
index c30409e66..d1889dd1c 100644
--- a/tdeprint/printerfilter.cpp
+++ b/tdeprint/printerfilter.cpp
@@ -21,7 +21,7 @@
#include "kmprinter.h"
#include "kmfactory.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kdebug.h>
diff --git a/tdeprint/rlpr/kmproxywidget.cpp b/tdeprint/rlpr/kmproxywidget.cpp
index 763282ecd..a2a3e6a85 100644
--- a/tdeprint/rlpr/kmproxywidget.cpp
+++ b/tdeprint/rlpr/kmproxywidget.cpp
@@ -25,7 +25,7 @@
#include <tqlayout.h>
#include <tqvalidator.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kcursor.h>
KMProxyWidget::KMProxyWidget(TQWidget *parent, const char *name)
diff --git a/tdeprint/rlpr/krlprprinterimpl.cpp b/tdeprint/rlpr/krlprprinterimpl.cpp
index 628205a31..5e927a940 100644
--- a/tdeprint/rlpr/krlprprinterimpl.cpp
+++ b/tdeprint/rlpr/krlprprinterimpl.cpp
@@ -25,7 +25,7 @@
#include <tqfile.h>
#include <kstandarddirs.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
KRlprPrinterImpl::KRlprPrinterImpl(TQObject *parent, const char *name, const TQStringList & /*args*/)
diff --git a/tdeprint/specials.desktop b/tdeprint/specials.desktop
index f6edcea32..467a26d7e 100644
--- a/tdeprint/specials.desktop
+++ b/tdeprint/specials.desktop
@@ -768,7 +768,7 @@ Extension=
Require=exec:/tdeprintfax
[Printer 3]
-Command=ps2pdf -sPAPERSIZE=%psl %in %out && kmailservice 'mailto:?attachment=file:%out' && sleep 15 && rm -f %out
+Command=ps2pdf -sPAPERSIZE=%psl %in %out && tdemailservice 'mailto:?attachment=file:%out' && sleep 15 && rm -f %out
Comment=Attachment for KMail Composer
Comment[af]=Aanhegsel vir Kpos Saamsteller
Comment[ar]=مرÙقات كاتب KMail
diff --git a/tdeprint/tdefilelist.cpp b/tdeprint/tdefilelist.cpp
new file mode 100644
index 000000000..9d02b77f6
--- /dev/null
+++ b/tdeprint/tdefilelist.cpp
@@ -0,0 +1,326 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (c) 2001 Michael Goffioul <tdeprint@swing.be>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License version 2 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ **/
+
+#include "tdefilelist.h"
+
+#include <tqtoolbutton.h>
+#include <tqlabel.h>
+#include <tqlayout.h>
+#include <tqtooltip.h>
+#include <tqheader.h>
+#include <tqwhatsthis.h>
+
+#include <tdeio/netaccess.h>
+#include <kurldrag.h>
+#include <tdefiledialog.h>
+#include <klocale.h>
+#include <kiconloader.h>
+#include <klistview.h>
+#include <krun.h>
+#include <kmimetype.h>
+
+KFileList::KFileList(TQWidget *parent, const char *name)
+: TQWidget(parent, name)
+{
+ //WhatsThis strings.... (added by pfeifle@kde.org)
+ TQString whatsThisAddFileButton = i18n( " <qt> <b>Add File button</b>"
+ " <p>This button calls the <em>'File Open'</em> dialog to let you"
+ " select a file for printing. Note, that "
+ " <ul><li>you can select ASCII or International Text, PDF,"
+ " PostScript, JPEG, TIFF, PNG, GIF and many other graphic"
+ " formats."
+ " <li>you can select various files from different paths"
+ " and send them as one \"multi-file job\" to the printing"
+ " system."
+ " </ul>"
+ " </qt>" );
+
+ TQString whatsThisRemoveFileButton = i18n(" <qt> <b>Remove File button</b>"
+ " <p>This button removes the highlighted file from the"
+ " list of to-be-printed files."
+ " </qt>" );
+
+ TQString whatsThisMoveFileUpButton = i18n(" <qt> <b>Move File Up button</b>"
+ " <p>This button moves the highlighted file up in the list"
+ " of files to be printed.</p>"
+ " <p>In effect, this changes the order"
+ " of the files' printout.</p>"
+ " </qt>" );
+
+ TQString whatsThisMoveFileDownButton = i18n(" <qt> <b>Move File Down button</b>"
+ " <p>This button moves the highlighted file down in the list"
+ " of files to be printed.</p>"
+ " <p>In effect, this changes the order"
+ " of the files' printout.</p>"
+ " </qt>" );
+
+ TQString whatsThisOpenFileButton = i18n( " <qt> <b>File Open button</b>"
+ " <p>This button tries to open the highlighted file, so"
+ " you can view or edit it before you send it to the printing"
+ " system.</p>"
+ " <p>If you open"
+ " files, TDEPrint will use the application matching the MIME type of"
+ " the file.</p>"
+ " </qt>" );
+
+ TQString whatsThisFileSelectionListview = i18n( " <qt> <b>File List view</b>"
+ " <p>This list displays all the files you selected for printing."
+ " You can see the file name(s), file path(s) and the file"
+ " (MIME) type(s) as determined by TDEPrint. You may re-arrange the "
+ " initial order of the list "
+ " with the help of the arrow buttons on the right.</p>"
+ " <p>The files will be printed as a single job,"
+ " in the same order as displayed in the list.</p>"
+ " <p><b>Note:</b> You can select multiple files. The files may be in multiple"
+ " locations. The files may be of multiple MIME types. The buttons on the right"
+ " side let you add more files, remove already selected files from the list, "
+ " re-order the list (by moving files up or down), and open files. If you open"
+ " files, TDEPrint will use the application matching the MIME type of"
+ " the file.</p>"
+ " </qt>" );
+
+ m_block = false;
+
+ m_files = new KListView(this);
+ m_files->addColumn(i18n("Name"));
+ m_files->addColumn(i18n("Type"));
+ m_files->addColumn(i18n("Path"));
+ m_files->setAllColumnsShowFocus(true);
+ m_files->setSorting(-1);
+ m_files->setAcceptDrops(false);
+ m_files->setSelectionMode(TQListView::Extended);
+ m_files->header()->setStretchEnabled(true, 2);
+ TQWhatsThis::add(m_files, whatsThisFileSelectionListview);
+ connect(m_files, TQT_SIGNAL(selectionChanged()), TQT_SLOT(slotSelectionChanged()));
+
+ m_add = new TQToolButton(this);
+ m_add->setIconSet(SmallIconSet("fileopen"));
+ connect(m_add, TQT_SIGNAL(clicked()), TQT_SLOT(slotAddFile()));
+ TQToolTip::add(m_add, i18n("Add file"));
+ TQWhatsThis::add(m_add, whatsThisAddFileButton);
+
+ m_remove = new TQToolButton(this);
+ m_remove->setIconSet(SmallIconSet("remove"));
+ connect(m_remove, TQT_SIGNAL(clicked()), TQT_SLOT(slotRemoveFile()));
+ TQToolTip::add(m_remove, i18n("Remove file"));
+ TQWhatsThis::add(m_remove, whatsThisRemoveFileButton);
+ m_remove->setEnabled(false);
+
+ m_open = new TQToolButton(this);
+ m_open->setIconSet(SmallIconSet("filefind"));
+ connect(m_open, TQT_SIGNAL(clicked()), TQT_SLOT(slotOpenFile()));
+ TQToolTip::add(m_open, i18n("Open file"));
+ TQWhatsThis::add(m_open, whatsThisOpenFileButton);
+ m_open->setEnabled(false);
+
+ m_up = new TQToolButton(this);
+ m_up->setIconSet(SmallIconSet("up"));
+ connect(m_up, TQT_SIGNAL(clicked()), TQT_SLOT(slotUp()));
+ TQToolTip::add(m_up, i18n("Move up"));
+ TQWhatsThis::add(m_up, whatsThisMoveFileUpButton);
+ m_up->setEnabled(false);
+
+ m_down = new TQToolButton(this);
+ m_down->setIconSet(SmallIconSet("down"));
+ connect(m_down, TQT_SIGNAL(clicked()), TQT_SLOT(slotDown()));
+ TQToolTip::add(m_down, i18n("Move down"));
+ TQWhatsThis::add(m_down, whatsThisMoveFileDownButton);
+ m_down->setEnabled(false);
+
+ setAcceptDrops(true);
+
+ TQToolTip::add(m_files, i18n(
+ "Drag file(s) here or use the button to open a file dialog. "
+ "Leave empty for <b>&lt;STDIN&gt;</b>."));
+
+ TQHBoxLayout *l0 = new TQHBoxLayout(this, 0, KDialog::spacingHint());
+ TQVBoxLayout *l1 = new TQVBoxLayout(0, 0, 1);
+ l0->addWidget(m_files);
+ l0->addLayout(l1);
+ l1->addWidget(m_add);
+ l1->addWidget(m_remove);
+ l1->addWidget(m_open);
+ l1->addSpacing(10);
+ l1->addWidget(m_up);
+ l1->addWidget(m_down);
+ l1->addStretch(1);
+}
+
+KFileList::~KFileList()
+{
+}
+
+void KFileList::dragEnterEvent(TQDragEnterEvent *e)
+{
+ e->accept(KURLDrag::canDecode(e));
+}
+
+void KFileList::dropEvent(TQDropEvent *e)
+{
+ KURL::List files;
+ if (KURLDrag::decode(e, files))
+ {
+ addFiles(files);
+ }
+}
+
+void KFileList::addFiles(const KURL::List& files)
+{
+ if (files.count() > 0)
+ {
+ // search last item in current list, to add new ones at the end
+ TQListViewItem *item = m_files->firstChild();
+ while (item && item->nextSibling())
+ item = item->nextSibling();
+
+ for (KURL::List::ConstIterator it=files.begin(); it!=files.end(); ++it)
+ {
+ KMimeType::Ptr mime = KMimeType::findByURL( *it, 0, true, false);
+ item = new TQListViewItem(m_files, item, (*it).fileName(), mime->comment(), (*it).url());
+ item->setPixmap(0, mime->pixmap(*it, KIcon::Small));
+ }
+
+ slotSelectionChanged();
+ /*
+ if (m_files->childCount() > 0)
+ {
+ m_remove->setEnabled(true);
+ m_open->setEnabled(true);
+ if (m_files->currentItem() == 0)
+ m_files->setSelected(m_files->firstChild(), true);
+ }
+ */
+ }
+}
+
+void KFileList::setFileList(const TQStringList& files)
+{
+ m_files->clear();
+ TQListViewItem *item = 0;
+ for (TQStringList::ConstIterator it=files.begin(); it!=files.end(); ++it)
+ {
+ KURL url = KURL::fromPathOrURL( *it );
+ KMimeType::Ptr mime = KMimeType::findByURL(url, 0, true, false);
+ item = new TQListViewItem(m_files, item, url.fileName(), mime->comment(), url.url());
+ item->setPixmap(0, mime->pixmap(url, KIcon::Small));
+ }
+ slotSelectionChanged();
+}
+
+TQStringList KFileList::fileList() const
+{
+ TQStringList l;
+ TQListViewItem *item = m_files->firstChild();
+ while (item)
+ {
+ l << item->text(2);
+ item = item->nextSibling();
+ }
+ return l;
+}
+
+void KFileList::slotAddFile()
+{
+ KURL::List fnames = KFileDialog::getOpenURLs(TQString::null, TQString::null, this);
+ if (!fnames.empty())
+ addFiles(fnames);
+}
+
+void KFileList::slotRemoveFile()
+{
+ TQPtrList<TQListViewItem> l;
+ selection(l);
+ l.setAutoDelete(true);
+ m_block = true;
+ l.clear();
+ m_block = false;
+ slotSelectionChanged();
+}
+
+void KFileList::slotOpenFile()
+{
+ TQListViewItem *item = m_files->currentItem();
+ if (item)
+ {
+ KURL url( item->text( 2 ) );
+ new KRun(url);
+ }
+}
+
+TQSize KFileList::sizeHint() const
+{
+ return TQSize(100, 100);
+}
+
+void KFileList::selection(TQPtrList<TQListViewItem>& l)
+{
+ l.setAutoDelete(false);
+ TQListViewItem *item = m_files->firstChild();
+ while (item)
+ {
+ if (item->isSelected())
+ l.append(item);
+ item = item->nextSibling();
+ }
+}
+
+void KFileList::slotSelectionChanged()
+{
+ if (m_block)
+ return;
+
+ TQPtrList<TQListViewItem> l;
+ selection(l);
+ m_remove->setEnabled(l.count() > 0);
+ m_open->setEnabled(l.count() == 1);
+ m_up->setEnabled(l.count() == 1 && l.first()->itemAbove());
+ m_down->setEnabled(l.count() == 1 && l.first()->itemBelow());
+}
+
+void KFileList::slotUp()
+{
+ TQPtrList<TQListViewItem> l;
+ selection(l);
+ if (l.count() == 1 && l.first()->itemAbove())
+ {
+ TQListViewItem *item(l.first()), *clone;
+ clone = new TQListViewItem(m_files, item->itemAbove()->itemAbove(), item->text(0), item->text(1), item->text(2));
+ clone->setPixmap(0, *(item->pixmap(0)));
+ delete item;
+ m_files->setCurrentItem(clone);
+ m_files->setSelected(clone, true);
+ }
+}
+
+void KFileList::slotDown()
+{
+ TQPtrList<TQListViewItem> l;
+ selection(l);
+ if (l.count() == 1 && l.first()->itemBelow())
+ {
+ TQListViewItem *item(l.first()), *clone;
+ clone = new TQListViewItem(m_files, item->itemBelow(), item->text(0), item->text(1), item->text(2));
+ clone->setPixmap(0, *(item->pixmap(0)));
+ delete item;
+ m_files->setCurrentItem(clone);
+ m_files->setSelected(clone, true);
+ }
+}
+
+#include "tdefilelist.moc"
diff --git a/tdeprint/kfilelist.h b/tdeprint/tdefilelist.h
index d5ef3ada1..d5ef3ada1 100644
--- a/tdeprint/kfilelist.h
+++ b/tdeprint/tdefilelist.h
diff --git a/tdeprint/tdeprintcheck.h b/tdeprint/tdeprintcheck.h
index bb839063f..7ffdf8d6c 100644
--- a/tdeprint/tdeprintcheck.h
+++ b/tdeprint/tdeprintcheck.h
@@ -22,7 +22,7 @@
#include <tqstring.h>
#include <tqstringlist.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kurl.h>
class TDEPRINT_EXPORT KdeprintChecker
diff --git a/tdeprint/tdeprintd.cpp b/tdeprint/tdeprintd.cpp
index 617fddf8f..02d32ab77 100644
--- a/tdeprint/tdeprintd.cpp
+++ b/tdeprint/tdeprintd.cpp
@@ -26,8 +26,8 @@
#include <kmessagebox.h>
#include <kdebug.h>
#include <dcopclient.h>
-#include <kio/passdlg.h>
-#include <kio/authinfo.h>
+#include <tdeio/passdlg.h>
+#include <tdeio/authinfo.h>
#include <tqlabel.h>
#include <kpushbutton.h>
#include <kiconloader.h>
diff --git a/tderandr/libtderandr.h b/tderandr/libtderandr.h
index b2b362a90..d597999d8 100644
--- a/tderandr/libtderandr.h
+++ b/tderandr/libtderandr.h
@@ -31,7 +31,7 @@
#include <tqfile.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <ksimpleconfig.h>
#include <tdelibs_export.h>
diff --git a/tderandr/randr.h b/tderandr/randr.h
index af3712e71..eb77b03aa 100644
--- a/tderandr/randr.h
+++ b/tderandr/randr.h
@@ -24,7 +24,7 @@
#include <tqptrlist.h>
#include <tdecmodule.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
class KTimerDialog;
class RandRScreenPrivate;
diff --git a/tderesources/CMakeLists.txt b/tderesources/CMakeLists.txt
index 05ea5a5af..bb4e957e0 100644
--- a/tderesources/CMakeLists.txt
+++ b/tderesources/CMakeLists.txt
@@ -17,9 +17,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
)
link_directories(
@@ -57,7 +57,7 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 1.2.0
- LINK kio-shared
+ LINK tdeio-shared
DESTINATION ${LIB_INSTALL_DIR}
DEPENDENCIES dcopidl
)
diff --git a/tderesources/configwidget.h b/tderesources/configwidget.h
index 30ebf2a5a..a5b114344 100644
--- a/tderesources/configwidget.h
+++ b/tderesources/configwidget.h
@@ -24,7 +24,7 @@
#include "resource.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqwidget.h>
diff --git a/tderesources/factory.h b/tderesources/factory.h
index e4b9f0af1..6bb075a88 100644
--- a/tderesources/factory.h
+++ b/tderesources/factory.h
@@ -27,7 +27,7 @@
#include <tqdict.h>
#include <tqstring.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klibloader.h>
#include <ktrader.h>
@@ -48,7 +48,7 @@ namespace KRES {
* KABC::Factory *factory = KABC::Factory::self( "contact" );
*
* // to allow a transparent configuration of resources, we have
- * // to use a kconfig object.
+ * // to use a tdeconfig object.
* TDEConfig config( "tst" );
* config.writePathEntry( "FileName", "/home/foobar/test.vcf" );// resource dependend
* config.writeEntry( "FileFormat", "vcard" ); // resource dependend
diff --git a/tderesources/managerimpl.cpp b/tderesources/managerimpl.cpp
index 43c39964e..467f049e9 100644
--- a/tderesources/managerimpl.cpp
+++ b/tderesources/managerimpl.cpp
@@ -26,7 +26,7 @@
#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstandarddirs.h>
#include "resource.h"
diff --git a/tderesources/resource.cpp b/tderesources/resource.cpp
index 00cdb8768..2a16ee159 100644
--- a/tderesources/resource.cpp
+++ b/tderesources/resource.cpp
@@ -23,7 +23,7 @@
#include <kdebug.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
#include "resource.h"
diff --git a/tderesources/resource.h b/tderesources/resource.h
index 65578bcd1..506ef0eaf 100644
--- a/tderesources/resource.h
+++ b/tderesources/resource.h
@@ -66,7 +66,7 @@ class ConfigWidget;
<B>resourceexample.h</B>:
\code
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tderesources/resource.h>
class ResourceExample : public KRES::Resource
@@ -84,7 +84,7 @@ class ResourceExample : public KRES::Resource
<B>resourceexample.cpp</B>:
\code
-#include <kconfig.h>
+#include <tdeconfig.h>
#include "resourceexample.h"
diff --git a/tderesources/tderesources.desktop b/tderesources/tderesources.desktop
index 0d907e0e0..245981de7 100644
--- a/tderesources/tderesources.desktop
+++ b/tderesources/tderesources.desktop
@@ -1,5 +1,5 @@
[Desktop Entry]
-Exec=kcmshell tderesources
+Exec=tdecmshell tderesources
Icon=about_kde
Type=Application
Terminal=false
diff --git a/tdersync/CMakeLists.txt b/tdersync/CMakeLists.txt
index 20ea5b777..1ccc3220a 100644
--- a/tdersync/CMakeLists.txt
+++ b/tdersync/CMakeLists.txt
@@ -18,8 +18,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
${CMAKE_SOURCE_DIR}/tdefx
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
link_directories(
@@ -45,6 +45,6 @@ set( ${target}_SRCS
tde_add_library( ${target} SHARED AUTOMOC
SOURCES ${${target}_SRCS}
VERSION 0.0.1
- LINK tdeui-shared kio-shared
+ LINK tdeui-shared tdeio-shared
DESTINATION ${LIB_INSTALL_DIR}
)
diff --git a/tdersync/rsyncconfigdialog.cpp b/tdersync/rsyncconfigdialog.cpp
index 0c1cd532a..ac8d32fa3 100644
--- a/tdersync/rsyncconfigdialog.cpp
+++ b/tdersync/rsyncconfigdialog.cpp
@@ -83,7 +83,7 @@
#include <kpassdlg.h>
#include <klistview.h>
#include <kapplication.h>
-#include <kconfigdialog.h>
+#include <tdeconfigdialog.h>
#include <kdirlister.h>
#include <kstandarddirs.h>
diff --git a/tdersync/rsyncconfigdialog.h b/tdersync/rsyncconfigdialog.h
index 3da9e6f79..2ce05b8db 100644
--- a/tdersync/rsyncconfigdialog.h
+++ b/tdersync/rsyncconfigdialog.h
@@ -27,7 +27,7 @@
#include <kurl.h>
#include <kprocess.h>
-#include <kfileitem.h>
+#include <tdefileitem.h>
#include <klibloader.h>
#include <kdialogbase.h>
diff --git a/tdersync/tdersync.cpp b/tdersync/tdersync.cpp
index 3e9e49981..d940fd7a3 100644
--- a/tdersync/tdersync.cpp
+++ b/tdersync/tdersync.cpp
@@ -50,8 +50,8 @@
#include <util.h>
#endif
-#include <kio/global.h>
-#include <kio/slavebase.h>
+#include <tdeio/global.h>
+#include <tdeio/slavebase.h>
#include "tdersync.h"
#include "rsyncconfigdialog.h"
diff --git a/tdersync/tdersync.h b/tdersync/tdersync.h
index c0af479f2..1e11cb959 100644
--- a/tdersync/tdersync.h
+++ b/tdersync/tdersync.h
@@ -24,11 +24,11 @@
#include <kurl.h>
#include <kprocess.h>
-#include <kfileitem.h>
+#include <tdefileitem.h>
#include <klibloader.h>
#include <tdeparts/plugin.h>
-#include <kio/global.h>
-#include <kio/slavebase.h>
+#include <tdeio/global.h>
+#include <tdeio/slavebase.h>
#include <tqfile.h>
#include <tqtimer.h>
@@ -62,7 +62,7 @@
#include <kpassdlg.h>
#include <klistview.h>
#include <kapplication.h>
-#include <kconfigdialog.h>
+#include <tdeconfigdialog.h>
#include <kdirlister.h>
#include <kstandarddirs.h>
diff --git a/tdespell2/CMakeLists.txt b/tdespell2/CMakeLists.txt
index ffd852066..01b910862 100644
--- a/tdespell2/CMakeLists.txt
+++ b/tdespell2/CMakeLists.txt
@@ -21,8 +21,8 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
${CMAKE_SOURCE_DIR}/tdeutils
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
link_directories(
diff --git a/tdespell2/broker.cpp b/tdespell2/broker.cpp
index 4dfc0f211..a5df8178c 100644
--- a/tdespell2/broker.cpp
+++ b/tdespell2/broker.cpp
@@ -30,7 +30,7 @@
#include <kplugininfo.h>
#include <ktrader.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
diff --git a/tdespell2/plugins/ispell/ispell_checker.cpp b/tdespell2/plugins/ispell/ispell_checker.cpp
index c07d9a55f..2bcf7ec92 100644
--- a/tdespell2/plugins/ispell/ispell_checker.cpp
+++ b/tdespell2/plugins/ispell/ispell_checker.cpp
@@ -197,7 +197,7 @@ ISpellChecker::ISpellChecker()
m_chartypes(NULL),
m_infile(NULL),
m_outfile(NULL),
- m_askfilename(NULL),
+ m_astdefilename(NULL),
m_Trynum(0),
m_translate_in(0)
{
diff --git a/tdespell2/plugins/ispell/ispell_checker.h b/tdespell2/plugins/ispell/ispell_checker.h
index 84faa34f9..b9d02c177 100644
--- a/tdespell2/plugins/ispell/ispell_checker.h
+++ b/tdespell2/plugins/ispell/ispell_checker.h
@@ -245,7 +245,7 @@ private:
FILE * m_infile; /* File being corrected */
FILE * m_outfile; /* Corrected copy of infile */
- char * m_askfilename; /* File specified in -f option */
+ char * m_astdefilename; /* File specified in -f option */
int m_changes; /* NZ if changes made to cur. file */
int m_readonly; /* NZ if current file is readonly */
diff --git a/tdespell2/settings.cpp b/tdespell2/settings.cpp
index 63b45e89d..d1d050ce7 100644
--- a/tdespell2/settings.cpp
+++ b/tdespell2/settings.cpp
@@ -25,7 +25,7 @@
#include <kglobal.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <tqmap.h>
diff --git a/tdespell2/ui/dialog.cpp b/tdespell2/ui/dialog.cpp
index 82548a406..a0ff36c01 100644
--- a/tdespell2/ui/dialog.cpp
+++ b/tdespell2/ui/dialog.cpp
@@ -27,7 +27,7 @@
#include "dictionary.h"
#include "settings.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
#include <kdebug.h>
diff --git a/tdespell2/ui/highlighter.cpp b/tdespell2/ui/highlighter.cpp
index 2d185462d..176d69232 100644
--- a/tdespell2/ui/highlighter.cpp
+++ b/tdespell2/ui/highlighter.cpp
@@ -24,7 +24,7 @@
#include "dictionary.h"
#include "settings.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <tqtextedit.h>
diff --git a/tdesu/Makefile.am b/tdesu/Makefile.am
index 926f3df5d..beec69d29 100644
--- a/tdesu/Makefile.am
+++ b/tdesu/Makefile.am
@@ -1,6 +1,6 @@
## Makefile.am for libtdesu
-INCLUDES = -I$(top_srcdir)/kio/ $(all_includes)
+INCLUDES = -I$(top_srcdir)/tdeio/ $(all_includes)
lib_LTLIBRARIES = libtdesu.la
libtdesu_la_SOURCES = client.cpp process.cpp kcookie.cpp su.cpp ssh.cpp stub.cpp tdesu_pty.cpp
diff --git a/tdesu/process.cpp b/tdesu/process.cpp
index 2d8e9a14f..a8d2478a5 100644
--- a/tdesu/process.cpp
+++ b/tdesu/process.cpp
@@ -48,7 +48,7 @@
#include <tqcstring.h>
#include <tqfile.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kstandarddirs.h>
diff --git a/tdesu/su.cpp b/tdesu/su.cpp
index 60a1abeb6..d75970dd8 100644
--- a/tdesu/su.cpp
+++ b/tdesu/su.cpp
@@ -33,7 +33,7 @@
#include <tqcstring.h>
#include <tqfile.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstandarddirs.h>
diff --git a/tdeui/CMakeLists.txt b/tdeui/CMakeLists.txt
index e738e7be3..a42f8e208 100644
--- a/tdeui/CMakeLists.txt
+++ b/tdeui/CMakeLists.txt
@@ -25,9 +25,9 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdefx
- ${CMAKE_SOURCE_DIR}/kio
- ${CMAKE_SOURCE_DIR}/kio/kio
- ${CMAKE_SOURCE_DIR}/kio/kfile
+ ${CMAKE_SOURCE_DIR}/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdefile
${FREETYPE_INCLUDE_DIRS}
)
@@ -73,7 +73,7 @@ install( FILES
ktextedit.h kpassivepopup.h
kdatetimewidget.h ktimewidget.h ktimezonewidget.h kscrollview.h
tdespell.h ksconfig.h tdespelldlg.h ksyntaxhighlighter.h
- ktabbar.h ktabwidget.h ksplashscreen.h kconfigdialog.h
+ ktabbar.h ktabwidget.h ksplashscreen.h tdeconfigdialog.h
kactionselector.h klanguagebutton.h klistviewsearchline.h
kpixmapregionselectorwidget.h kpixmapregionselectordialog.h
kiconviewsearchline.h ktoolbarlabelaction.h kshortcutdialog.h
@@ -138,7 +138,7 @@ set( ${target}_SRCS
ktoolbarhandler.cpp kdatetimewidget.cpp ktimewidget.cpp ktimezonewidget.cpp
ksconfig.cpp tdespelldlg.cpp
tdespell.cpp ksyntaxhighlighter.cpp ktabbar.cpp ktabwidget.cpp
- ksplashscreen.cpp tdespellui.ui kconfigdialog.cpp
+ ksplashscreen.cpp tdespellui.ui tdeconfigdialog.cpp
kactionselector.cpp klanguagebutton.cpp klistviewsearchline.cpp
kpixmapregionselectorwidget.cpp kpixmapregionselectordialog.cpp
kwhatsthismanager.cpp kiconviewsearchline.cpp
diff --git a/tdeui/Makefile.am b/tdeui/Makefile.am
index f3ccef8b7..13d5b3c4f 100644
--- a/tdeui/Makefile.am
+++ b/tdeui/Makefile.am
@@ -70,7 +70,7 @@ include_HEADERS = kprogressbox.h kprogress.h kcolordlg.h \
ktextedit.h kpassivepopup.h \
kdatetimewidget.h ktimewidget.h ktimezonewidget.h kscrollview.h \
tdespell.h ksconfig.h tdespelldlg.h ksyntaxhighlighter.h \
- ktabbar.h ktabwidget.h ksplashscreen.h kconfigdialog.h \
+ ktabbar.h ktabwidget.h ksplashscreen.h tdeconfigdialog.h \
kactionselector.h klanguagebutton.h klistviewsearchline.h \
kpixmapregionselectorwidget.h kpixmapregionselectordialog.h \
kiconviewsearchline.h ktoolbarlabelaction.h kshortcutdialog.h
@@ -119,7 +119,7 @@ libtdeui_la_SOURCES = \
ktoolbarhandler.cpp kdatetimewidget.cpp ktimewidget.cpp ktimezonewidget.cpp \
ksconfig.cpp tdespelldlg.cpp \
tdespell.cpp ksyntaxhighlighter.cpp ktabbar.cpp ktabwidget.cpp \
- ksplashscreen.cpp tdespellui.ui kconfigdialog.cpp \
+ ksplashscreen.cpp tdespellui.ui tdeconfigdialog.cpp \
kactionselector.cpp klanguagebutton.cpp klistviewsearchline.cpp \
kpixmapregionselectorwidget.cpp kpixmapregionselectordialog.cpp \
kwhatsthismanager.cpp kiconviewsearchline.cpp \
diff --git a/tdeui/kactionclasses.cpp b/tdeui/kactionclasses.cpp
index 605ac8379..52b3441c2 100644
--- a/tdeui/kactionclasses.cpp
+++ b/tdeui/kactionclasses.cpp
@@ -43,7 +43,7 @@
#include <dcopref.h>
#include <kaccel.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kfontcombo.h>
#include <kfontdialog.h>
diff --git a/tdeui/kbugreport.cpp b/tdeui/kbugreport.cpp
index ab36f83d7..1812487c1 100644
--- a/tdeui/kbugreport.cpp
+++ b/tdeui/kbugreport.cpp
@@ -28,7 +28,7 @@
#include <kaboutdata.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <klineedit.h>
#include <klocale.h>
@@ -319,11 +319,11 @@ void KBugReport::slotConfigureEmail()
{
if (m_process) return;
m_process = new TDEProcess;
- *m_process << TQString::fromLatin1("kcmshell") << TQString::fromLatin1("kcm_useraccount");
+ *m_process << TQString::fromLatin1("tdecmshell") << TQString::fromLatin1("kcm_useraccount");
connect(m_process, TQT_SIGNAL(processExited(TDEProcess *)), TQT_SLOT(slotSetFrom()));
if (!m_process->start())
{
- kdDebug() << "Couldn't start kcmshell.." << endl;
+ kdDebug() << "Couldn't start tdecmshell.." << endl;
delete m_process;
m_process = 0;
return;
@@ -489,9 +489,9 @@ bool KBugReport::sendBugReport()
TQString::fromLatin1("submit@bugs.pearsoncomputing.net") );
TQString command;
- command = locate("exe", "ksendbugmail");
+ command = locate("exe", "tdesendbugmail");
if (command.isEmpty())
- command = KStandardDirs::findExe( TQString::fromLatin1("ksendbugmail") );
+ command = KStandardDirs::findExe( TQString::fromLatin1("tdesendbugmail") );
KTempFile outputfile;
outputfile.close();
diff --git a/tdeui/kbugreport.h b/tdeui/kbugreport.h
index b8ddd39f7..aec61d668 100644
--- a/tdeui/kbugreport.h
+++ b/tdeui/kbugreport.h
@@ -57,7 +57,7 @@ public:
protected slots:
/**
- * "Configure email" has been clicked - this calls kcmshell System/email
+ * "Configure email" has been clicked - this calls tdecmshell System/email
*/
virtual void slotConfigureEmail();
/**
diff --git a/tdeui/kcmenumngr.cpp b/tdeui/kcmenumngr.cpp
index 5af7b6de6..f71a88f79 100644
--- a/tdeui/kcmenumngr.cpp
+++ b/tdeui/kcmenumngr.cpp
@@ -22,7 +22,7 @@
#include <tqpopupmenu.h>
#include "kcmenumngr.h"
#include "kglobal.h"
-#include "kconfig.h"
+#include "tdeconfig.h"
#include "kshortcut.h"
#undef KeyPress
diff --git a/tdeui/kcolorcombo.cpp b/tdeui/kcolorcombo.cpp
index a7dd90ac7..52291f762 100644
--- a/tdeui/kcolorcombo.cpp
+++ b/tdeui/kcolorcombo.cpp
@@ -45,7 +45,7 @@
#include <tqtimer.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
diff --git a/tdeui/kcolordialog.cpp b/tdeui/kcolordialog.cpp
index 2651fd05d..7182e9ddc 100644
--- a/tdeui/kcolordialog.cpp
+++ b/tdeui/kcolordialog.cpp
@@ -46,7 +46,7 @@
#include <tqtimer.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
diff --git a/tdeui/kcombobox.h b/tdeui/kcombobox.h
index e0ff8e6e4..247217aaf 100644
--- a/tdeui/kcombobox.h
+++ b/tdeui/kcombobox.h
@@ -654,7 +654,7 @@ public:
* KPixmapProvider is just an abstract class with the one pure virtual
* method KPixmapProvider::pixmapFor(). This method is called whenever
* an item is added to the KHistoryComboBox. Implement it to return your
- * own custom pixmaps, or use the KURLPixmapProvider from libkio,
+ * own custom pixmaps, or use the KURLPixmapProvider from libtdeio,
* which uses KMimeType::pixmapForURL to resolve icons.
*
* Set @p prov to 0L if you want to disable pixmaps. Default no pixmaps.
diff --git a/tdeui/kcompletionbox.cpp b/tdeui/kcompletionbox.cpp
index efcda9ebe..2e63cb21f 100644
--- a/tdeui/kcompletionbox.cpp
+++ b/tdeui/kcompletionbox.cpp
@@ -27,7 +27,7 @@
#include <tqstyle.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <knotifyclient.h>
#include <kglobalsettings.h>
diff --git a/tdeui/kconfigdialog.cpp b/tdeui/kconfigdialog.cpp
deleted file mode 100644
index 9707bc26a..000000000
--- a/tdeui/kconfigdialog.cpp
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * This file is part of the KDE libraries
- * Copyright (C) 2003 Benjamin C Meyer (ben+tdelibs at meyerhome dot net)
- * Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
- * Copyright (C) 2004 Michael Brade <brade@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library 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
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-#include "kconfigdialog.h"
-
-#include <kconfigskeleton.h>
-#include <kconfigdialogmanager.h>
-#include <klocale.h>
-#include <kiconloader.h>
-#include <kdebug.h>
-
-#include <tqlayout.h>
-#include <tqvbox.h>
-#include <tqmap.h>
-
-TQAsciiDict<TDEConfigDialog> TDEConfigDialog::openDialogs;
-
-// This class is here purly so we don't break binary compatibility down the road.
-class TDEConfigDialog::TDEConfigDialogPrivate
-{
-public:
- TDEConfigDialogPrivate(KDialogBase::DialogType t)
- : shown(false), type(t), manager(0) { }
-
- bool shown;
- KDialogBase::DialogType type;
- TDEConfigDialogManager *manager;
- TQMap<TQWidget *, TDEConfigDialogManager *> managerForPage;
-};
-
-TDEConfigDialog::TDEConfigDialog( TQWidget *parent, const char *name,
- TDEConfigSkeleton *config,
- DialogType dialogType,
- int dialogButtons,
- ButtonCode defaultButton,
- bool modal ) :
- KDialogBase( dialogType, (WFlags)TQt::WStyle_DialogBorder,
- parent, name, modal, i18n("Configure"), dialogButtons, defaultButton ),
- d(new TDEConfigDialogPrivate(dialogType))
-{
- if ( name ) {
- openDialogs.insert(name, this);
- } else {
- TQCString genericName;
- genericName.sprintf("SettingsDialog-%p", this);
- openDialogs.insert(genericName, this);
- setName(genericName);
- }
-
- connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(updateSettings()));
- connect(this, TQT_SIGNAL(applyClicked()), this, TQT_SLOT(updateSettings()));
- connect(this, TQT_SIGNAL(applyClicked()), this, TQT_SLOT(updateButtons()));
- connect(this, TQT_SIGNAL(defaultClicked()), this, TQT_SLOT(updateWidgetsDefault()));
- connect(this, TQT_SIGNAL(defaultClicked()), this, TQT_SLOT(updateButtons()));
-
- d->manager = new TDEConfigDialogManager(this, config);
- setupManagerConnections(d->manager);
-
- enableButton(Apply, false);
-}
-
-TDEConfigDialog::~TDEConfigDialog()
-{
- openDialogs.remove(name());
- delete d;
-}
-
-void TDEConfigDialog::addPage(TQWidget *page,
- const TQString &itemName,
- const TQString &pixmapName,
- const TQString &header,
- bool manage)
-{
- addPageInternal(page, itemName, pixmapName, header);
- if(manage)
- d->manager->addWidget(page);
-}
-
-void TDEConfigDialog::addPage(TQWidget *page,
- TDEConfigSkeleton *config,
- const TQString &itemName,
- const TQString &pixmapName,
- const TQString &header)
-{
- addPageInternal(page, itemName, pixmapName, header);
- d->managerForPage[page] = new TDEConfigDialogManager(page, config);
- setupManagerConnections(d->managerForPage[page]);
-}
-
-void TDEConfigDialog::addPageInternal(TQWidget *page,
- const TQString &itemName,
- const TQString &pixmapName,
- const TQString &header)
-{
- if(d->shown)
- {
- kdDebug(240) << "TDEConfigDialog::addPage: can not add a page after the dialog has been shown.";
- return;
- }
- switch(d->type)
- {
- case TreeList:
- case IconList:
- case Tabbed: {
- TQVBox *frame = addVBoxPage(itemName, header, SmallIcon(pixmapName, 32));
- frame->setSpacing( 0 );
- frame->setMargin( 0 );
- page->reparent(((TQWidget*)frame), 0, TQPoint());
- }
- break;
-
- case Swallow:
- {
- page->reparent(this, 0, TQPoint());
- setMainWidget(page);
- }
- break;
-
- case Plain:
- {
- TQFrame *main = plainPage();
- TQVBoxLayout *topLayout = new TQVBoxLayout( main, 0, 0 );
- page->reparent(((TQWidget*)main), 0, TQPoint());
- topLayout->addWidget( page );
- }
- break;
-
- default:
- kdDebug(240) << "TDEConfigDialog::addpage: unknown type.";
- }
-}
-
-void TDEConfigDialog::setupManagerConnections(TDEConfigDialogManager *manager)
-{
- connect(manager, TQT_SIGNAL(settingsChanged()), this, TQT_SLOT(settingsChangedSlot()));
- connect(manager, TQT_SIGNAL(widgetModified()), this, TQT_SLOT(updateButtons()));
-
- connect(this, TQT_SIGNAL(okClicked()), manager, TQT_SLOT(updateSettings()));
- connect(this, TQT_SIGNAL(applyClicked()), manager, TQT_SLOT(updateSettings()));
- connect(this, TQT_SIGNAL(defaultClicked()), manager, TQT_SLOT(updateWidgetsDefault()));
-}
-
-TDEConfigDialog* TDEConfigDialog::exists(const char* name)
-{
- return openDialogs.find(name);
-}
-
-bool TDEConfigDialog::showDialog(const char* name)
-{
- TDEConfigDialog *dialog = exists(name);
- if(dialog)
- dialog->show();
- return (dialog != NULL);
-}
-
-void TDEConfigDialog::updateButtons()
-{
- static bool only_once = false;
- if (only_once) return;
- only_once = true;
-
- TQMap<TQWidget *, TDEConfigDialogManager *>::iterator it;
-
- bool has_changed = d->manager->hasChanged() || hasChanged();
- for (it = d->managerForPage.begin();
- it != d->managerForPage.end() && !has_changed;
- ++it)
- {
- has_changed |= (*it)->hasChanged();
- }
-
- enableButton(Apply, has_changed);
-
- bool is_default = d->manager->isDefault() && isDefault();
- for (it = d->managerForPage.begin();
- it != d->managerForPage.end() && is_default;
- ++it)
- {
- is_default &= (*it)->isDefault();
- }
-
- enableButton(Default, !is_default);
-
- emit widgetModified();
- only_once = false;
-}
-
-void TDEConfigDialog::settingsChangedSlot()
-{
- // Update the buttons
- updateButtons();
- emit settingsChanged();
- emit settingsChanged(name());
-}
-
-void TDEConfigDialog::show()
-{
- TQMap<TQWidget *, TDEConfigDialogManager *>::iterator it;
-
- updateWidgets();
- d->manager->updateWidgets();
- for (it = d->managerForPage.begin(); it != d->managerForPage.end(); ++it)
- (*it)->updateWidgets();
-
- bool has_changed = d->manager->hasChanged() || hasChanged();
- for (it = d->managerForPage.begin();
- it != d->managerForPage.end() && !has_changed;
- ++it)
- {
- has_changed |= (*it)->hasChanged();
- }
-
- enableButton(Apply, has_changed);
-
- bool is_default = d->manager->isDefault() && isDefault();
- for (it = d->managerForPage.begin();
- it != d->managerForPage.end() && is_default;
- ++it)
- {
- is_default &= (*it)->isDefault();
- }
-
- enableButton(Default, !is_default);
- d->shown = true;
- KDialogBase::show();
-}
-
-void TDEConfigDialog::updateSettings()
-{
-}
-
-void TDEConfigDialog::updateWidgets()
-{
-}
-
-void TDEConfigDialog::updateWidgetsDefault()
-{
-}
-
-
-#include "kconfigdialog.moc"
diff --git a/tdeui/kcursor.cpp b/tdeui/kcursor.cpp
index 4bd337c35..3cc224f4a 100644
--- a/tdeui/kcursor.cpp
+++ b/tdeui/kcursor.cpp
@@ -31,7 +31,7 @@
#include <tqwidget.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqscrollview.h>
#include "kcursor_private.h"
diff --git a/tdeui/kdatetbl.cpp b/tdeui/kdatetbl.cpp
index 632c7deea..b73b8b4eb 100644
--- a/tdeui/kdatetbl.cpp
+++ b/tdeui/kdatetbl.cpp
@@ -32,7 +32,7 @@
// When a date is selected by the user, it emits a signal:
// dateSelected(TQDate)
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kapplication.h>
diff --git a/tdeui/kdepackages.h b/tdeui/kdepackages.h
index 58ea0f867..fa07e627d 100644
--- a/tdeui/kdepackages.h
+++ b/tdeui/kdepackages.h
@@ -306,8 +306,8 @@ const char * const packages[] = {
"kchart/usability",
"kchat",
"kcoloredit",
-"kconfigeditor",
-"kconfigure",
+"tdeconfigeditor",
+"tdeconfigure",
"kcontrol",
"kcontrol/kcmaccess",
"kcontrol/kcmaccessibility",
@@ -362,7 +362,7 @@ const char * const packages[] = {
"kcontrol/kcmproxy",
"kcontrol/kcmsamba",
"kcontrol/kcmscreensaver",
-"kcontrol/kcmshell",
+"kcontrol/tdecmshell",
"kcontrol/kcmsmserver",
"kcontrol/kcmspellchecking",
"kcontrol/kcmstyle",
@@ -388,9 +388,9 @@ const char * const packages[] = {
"kde-bluetooth/kbtserialchat",
"kde-bluetooth/khciconfig",
"kde-bluetooth/kinputwizard",
-"kde-bluetooth/kio_bluetooth",
-"kde-bluetooth/kio_obex",
-"kde-bluetooth/kio_sdp",
+"kde-bluetooth/tdeio_bluetooth",
+"kde-bluetooth/tdeio_obex",
+"kde-bluetooth/tdeio_sdp",
"kde-windows",
"kde-windows/buildsystem",
"kde-windows/gui",
@@ -421,7 +421,7 @@ const char * const packages[] = {
"tdelibs/tdeui",
"tdelibs/kedittoolbar",
"tdelibs/kimgio",
-"tdelibs/klauncher",
+"tdelibs/tdelauncher",
"tdelibs/klocale",
"tdelibs/tdemdi",
"tdelibs/knetwork",
@@ -572,21 +572,21 @@ const char * const packages[] = {
"kexi/Usability",
"keystone",
"kfax",
-"kfile-plugins",
-"kfile-plugins/OOo",
-"kfile-plugins/PNG",
-"kfile-plugins/avi",
-"kfile-plugins/exr",
-"kfile-plugins/jpeg",
-"kfile-plugins/mp3",
-"kfile-plugins/mpeg",
-"kfile-plugins/ogg",
-"kfile-plugins/pdf",
-"kfile-plugins/ps",
-"kfile-plugins/wav",
-"kfile",
-"kfile/kfileplacesview",
-"kfilereplace",
+"tdefile-plugins",
+"tdefile-plugins/OOo",
+"tdefile-plugins/PNG",
+"tdefile-plugins/avi",
+"tdefile-plugins/exr",
+"tdefile-plugins/jpeg",
+"tdefile-plugins/mp3",
+"tdefile-plugins/mpeg",
+"tdefile-plugins/ogg",
+"tdefile-plugins/pdf",
+"tdefile-plugins/ps",
+"tdefile-plugins/wav",
+"tdefile",
+"tdefile/tdefileplacesview",
+"tdefilereplace",
"kfind",
"kfinger",
"kfloppy",
@@ -638,7 +638,7 @@ const char * const packages[] = {
"kicker/minipagerapplet",
"kicker/multiscreen",
"kicker/naughtyapplet",
-"kicker/quicklauncher",
+"kicker/quictdelauncher",
"kicker/sidebar",
"kicker/systemtray",
"kicker/taskbarapplet",
@@ -654,46 +654,46 @@ const char * const packages[] = {
"kimdaba",
"kinkatta",
"kio",
-"kio/audiocd",
-"kio/cgi",
-"kio/devices",
-"kio/file",
-"kio/fish",
-"kio/floppy",
-"kio/ftp",
-"kio/gopher",
-"kio/help",
-"kio/home",
-"kio/http",
-"kio/imap",
-"kio/info",
-"kio/kamera",
-"kio/kfile",
-"kio/kioslave",
-"kio/kssl",
-"kio/man",
-"kio/media",
-"kio/nfs",
-"kio/nntp",
-"kio/pop3",
-"kio/remote",
-"kio/settings",
-"kio/sftp",
-"kio/sieve",
-"kio/smb",
-"kio/smbro",
-"kio/smtp",
-"kio/svn",
-"kio/system",
-"kio/tar",
-"kio/thumbnail",
-"kio/trash",
-"kio/uiserver",
-"kio/webdav",
-"kio/zeroconf",
-"kio/zip",
+"tdeio/audiocd",
+"tdeio/cgi",
+"tdeio/devices",
+"tdeio/file",
+"tdeio/fish",
+"tdeio/floppy",
+"tdeio/ftp",
+"tdeio/gopher",
+"tdeio/help",
+"tdeio/home",
+"tdeio/http",
+"tdeio/imap",
+"tdeio/info",
+"tdeio/kamera",
+"tdeio/tdefile",
+"tdeio/tdeioslave",
+"tdeio/kssl",
+"tdeio/man",
+"tdeio/media",
+"tdeio/nfs",
+"tdeio/nntp",
+"tdeio/pop3",
+"tdeio/remote",
+"tdeio/settings",
+"tdeio/sftp",
+"tdeio/sieve",
+"tdeio/smb",
+"tdeio/smbro",
+"tdeio/smtp",
+"tdeio/svn",
+"tdeio/system",
+"tdeio/tar",
+"tdeio/thumbnail",
+"tdeio/trash",
+"tdeio/uiserver",
+"tdeio/webdav",
+"tdeio/zeroconf",
+"tdeio/zip",
"kiosk",
-"kiosk/kiosktool",
+"kiosk/tdeiosktool",
"kipiplugins",
"kipiplugins/GPSSync",
"kipiplugins/HTMLExport",
@@ -815,7 +815,7 @@ const char * const packages[] = {
"knetload",
"knetload/Linux Statistics",
"knetwalk",
-"knetworkconf",
+"knetwortdeconf",
"knetworkmanager",
"knetworkmanager/802.1x",
"knetworkmanager/cellular",
diff --git a/tdeui/kdialog.cpp b/tdeui/kdialog.cpp
index 3821e6a26..53d7b4f05 100644
--- a/tdeui/kdialog.cpp
+++ b/tdeui/kdialog.cpp
@@ -18,7 +18,7 @@
* Boston, MA 02110-1301, USA.
*/
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kapplication.h>
#include <kdialog.h>
#include <kwhatsthismanager_p.h>
diff --git a/tdeui/kdialogbase.cpp b/tdeui/kdialogbase.cpp
index 3a7be7a94..46d0697d5 100644
--- a/tdeui/kdialogbase.cpp
+++ b/tdeui/kdialogbase.cpp
@@ -35,7 +35,7 @@
#include <kapplication.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kiconloader.h>
#include <kglobal.h>
#include <kglobalsettings.h>
diff --git a/tdeui/kdockwidget.cpp b/tdeui/kdockwidget.cpp
index a1ef8aad1..0bfebe0ab 100644
--- a/tdeui/kdockwidget.cpp
+++ b/tdeui/kdockwidget.cpp
@@ -33,7 +33,7 @@
#include <tqstyle.h>
#ifndef NO_KDE2
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <klocale.h>
#include <ktoolbar.h>
diff --git a/tdeui/kedittoolbar.cpp b/tdeui/kedittoolbar.cpp
index 563b007c0..63c4bc2b2 100644
--- a/tdeui/kedittoolbar.cpp
+++ b/tdeui/kedittoolbar.cpp
@@ -40,7 +40,7 @@
#include <kmessagebox.h>
#include <kxmlguifactory.h>
#include <kseparator.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klistview.h>
#include <kdebug.h>
#include <kpushbutton.h>
@@ -1373,8 +1373,8 @@ void KEditToolbarWidget::updateLocal(TQDomElement& elem)
void KEditToolbarWidget::slotChangeIcon()
{
- // We can't use KIconChooser here, since it's in libkio
- // ##### KDE4: reconsider this, e.g. move KEditToolbar to libkio
+ // We can't use KIconChooser here, since it's in libtdeio
+ // ##### KDE4: reconsider this, e.g. move KEditToolbar to libtdeio
//if the process is already running (e.g. when somebody clicked the change button twice (see #127149)) - do nothing...
//otherwise m_kdialogProcess will be overwritten and set to zero in slotProcessExited()...crash!
diff --git a/tdeui/kfontcombo.cpp b/tdeui/kfontcombo.cpp
index 1923f6cb9..f36b18510 100644
--- a/tdeui/kfontcombo.cpp
+++ b/tdeui/kfontcombo.cpp
@@ -23,7 +23,7 @@
#include <tqregexp.h>
#include <kcharsets.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kfontdialog.h>
diff --git a/tdeui/kfontdialog.cpp b/tdeui/kfontdialog.cpp
index 01073521d..97f43544c 100644
--- a/tdeui/kfontdialog.cpp
+++ b/tdeui/kfontdialog.cpp
@@ -43,7 +43,7 @@
#include <kapplication.h>
#include <kcharsets.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kglobalsettings.h>
diff --git a/tdeui/kiconview.cpp b/tdeui/kiconview.cpp
index 430a23fa0..185450880 100644
--- a/tdeui/kiconview.cpp
+++ b/tdeui/kiconview.cpp
@@ -25,7 +25,7 @@
#include "kiconview.h"
#include "kwordwrap.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalsettings.h>
diff --git a/tdeui/kkeydialog.cpp b/tdeui/kkeydialog.cpp
index b83cc6d53..8de6a6e59 100644
--- a/tdeui/kkeydialog.cpp
+++ b/tdeui/kkeydialog.cpp
@@ -40,7 +40,7 @@
#include <kaccelaction.h>
#include <kactionshortcutlist.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kglobalaccel.h>
diff --git a/tdeui/klineedit.cpp b/tdeui/klineedit.cpp
index d70485b09..f6fa42611 100644
--- a/tdeui/klineedit.cpp
+++ b/tdeui/klineedit.cpp
@@ -29,7 +29,7 @@
#include <tqpainter.h>
#include <tqtimer.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqtooltip.h>
#include <kcursor.h>
#include <klocale.h>
diff --git a/tdeui/klistview.cpp b/tdeui/klistview.cpp
index b604658f1..24c5f3a4b 100644
--- a/tdeui/klistview.cpp
+++ b/tdeui/klistview.cpp
@@ -28,7 +28,7 @@
#include <tqpainter.h>
#include <kglobalsettings.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kcursor.h>
#include <kapplication.h>
#include <kipc.h>
diff --git a/tdeui/kmainwindow.cpp b/tdeui/kmainwindow.cpp
index 14f6f6bea..de9bb8f8f 100644
--- a/tdeui/kmainwindow.cpp
+++ b/tdeui/kmainwindow.cpp
@@ -37,7 +37,7 @@
#include <kaccel.h>
#include <kaction.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <khelpmenu.h>
#include <kmenubar.h>
diff --git a/tdeui/kmainwindow.h b/tdeui/kmainwindow.h
index a66eb8327..5ddb669ee 100644
--- a/tdeui/kmainwindow.h
+++ b/tdeui/kmainwindow.h
@@ -873,7 +873,7 @@ protected:
* invoked when the session manager requests your application
* to save its state.
*
- * You @em must @em not change the group of the @p kconfig object, since
+ * You @em must @em not change the group of the @p tdeconfig object, since
* KMainWindow uses one group for each window. Please
* reimplement these function in childclasses.
*
diff --git a/tdeui/kmenubar.cpp b/tdeui/kmenubar.cpp
index f6cac81ab..d2b97f3b0 100644
--- a/tdeui/kmenubar.cpp
+++ b/tdeui/kmenubar.cpp
@@ -32,7 +32,7 @@
#include <tqstyle.h>
#include <tqtimer.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobalsettings.h>
#include <kmenubar.h>
#include <kapplication.h>
diff --git a/tdeui/kmessagebox.cpp b/tdeui/kmessagebox.cpp
index 524636089..d0c4f0a11 100644
--- a/tdeui/kmessagebox.cpp
+++ b/tdeui/kmessagebox.cpp
@@ -32,7 +32,7 @@
#include <tqlayout.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kdialogbase.h>
#include <kguiitem.h>
diff --git a/tdeui/kpanelapplet.cpp b/tdeui/kpanelapplet.cpp
index 7ca2999f1..d38f36980 100644
--- a/tdeui/kpanelapplet.cpp
+++ b/tdeui/kpanelapplet.cpp
@@ -26,7 +26,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "kpanelapplet.h"
#include "kpanelapplet.moc"
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
class KPanelApplet::KPanelAppletPrivate
{
diff --git a/tdeui/kpanelapplet.h b/tdeui/kpanelapplet.h
index 2ef893927..43c7221aa 100644
--- a/tdeui/kpanelapplet.h
+++ b/tdeui/kpanelapplet.h
@@ -25,7 +25,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define __kpanelapplet_h__
#include <tqframe.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
class TDEConfig;
class TQPopupMenu;
diff --git a/tdeui/kpanelextension.cpp b/tdeui/kpanelextension.cpp
index aae989c2e..31fbd4343 100644
--- a/tdeui/kpanelextension.cpp
+++ b/tdeui/kpanelextension.cpp
@@ -23,7 +23,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <tqpopupmenu.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include "kpanelextension.h"
#include "kpanelextension.moc"
diff --git a/tdeui/kpanelmenu.cpp b/tdeui/kpanelmenu.cpp
index 101d2aba0..a995661c3 100644
--- a/tdeui/kpanelmenu.cpp
+++ b/tdeui/kpanelmenu.cpp
@@ -23,7 +23,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************/
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqtimer.h>
#include "kpanelmenu.h"
diff --git a/tdeui/kpassdlg.cpp b/tdeui/kpassdlg.cpp
index 5803ca477..46a8cccde 100644
--- a/tdeui/kpassdlg.cpp
+++ b/tdeui/kpassdlg.cpp
@@ -41,7 +41,7 @@
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kaboutdialog.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kstandarddirs.h>
#include <kprogress.h>
diff --git a/tdeui/kpassivepopup.cpp b/tdeui/kpassivepopup.cpp
index fe2414a67..8892ce153 100644
--- a/tdeui/kpassivepopup.cpp
+++ b/tdeui/kpassivepopup.cpp
@@ -6,7 +6,7 @@
* email : sascha.cunz@tiscali.de
*/
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqapplication.h>
#include <tqlabel.h>
diff --git a/tdeui/kpixmapio.cpp b/tdeui/kpixmapio.cpp
index 004a51349..7ce3a1be2 100644
--- a/tdeui/kpixmapio.cpp
+++ b/tdeui/kpixmapio.cpp
@@ -19,7 +19,7 @@
#include <tqglobal.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <sys/types.h>
diff --git a/tdeui/kpushbutton.cpp b/tdeui/kpushbutton.cpp
index c61d140dd..35bf0928f 100644
--- a/tdeui/kpushbutton.cpp
+++ b/tdeui/kpushbutton.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include <kglobalsettings.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kipc.h>
#include <kapplication.h>
diff --git a/tdeui/ksconfig.cpp b/tdeui/ksconfig.cpp
index d74a40706..363a9b8b4 100644
--- a/tdeui/ksconfig.cpp
+++ b/tdeui/ksconfig.cpp
@@ -26,10 +26,10 @@
#include <tqtimer.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kdialog.h>
-#include <kfiledialog.h>
+#include <tdefiledialog.h>
#include <kglobal.h>
#include <klineedit.h>
#include <klocale.h>
diff --git a/tdeui/kscrollview.cpp b/tdeui/kscrollview.cpp
index fe865d31e..997de84b3 100644
--- a/tdeui/kscrollview.cpp
+++ b/tdeui/kscrollview.cpp
@@ -24,7 +24,7 @@
#include "kscrollview.h"
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
struct KScrollView::KScrollViewPrivate {
diff --git a/tdeui/kshortcutdialog.cpp b/tdeui/kshortcutdialog.cpp
index c93194e77..db5e32322 100644
--- a/tdeui/kshortcutdialog.cpp
+++ b/tdeui/kshortcutdialog.cpp
@@ -53,7 +53,7 @@
#include <tqvbox.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kiconloader.h>
diff --git a/tdeui/ksplashscreen.cpp b/tdeui/ksplashscreen.cpp
index b88be8e06..a45a579bb 100644
--- a/tdeui/ksplashscreen.cpp
+++ b/tdeui/ksplashscreen.cpp
@@ -17,7 +17,7 @@
Boston, MA 02110-1301, USA.
*/
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
#include <kglobalsettings.h>
diff --git a/tdeui/kstatusbar.cpp b/tdeui/kstatusbar.cpp
index 7d7856a34..134d7f1a5 100644
--- a/tdeui/kstatusbar.cpp
+++ b/tdeui/kstatusbar.cpp
@@ -20,7 +20,7 @@
#include <kdebug.h>
#include <kstatusbar.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kglobal.h>
diff --git a/tdeui/kswitchlanguagedialog.cpp b/tdeui/kswitchlanguagedialog.cpp
index f86083d0a..57f1dee15 100644
--- a/tdeui/kswitchlanguagedialog.cpp
+++ b/tdeui/kswitchlanguagedialog.cpp
@@ -27,7 +27,7 @@
#include <tqmap.h>
#include <klanguagebutton.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
diff --git a/tdeui/ksyntaxhighlighter.cpp b/tdeui/ksyntaxhighlighter.cpp
index 866bcfce1..07ddf93c4 100644
--- a/tdeui/ksyntaxhighlighter.cpp
+++ b/tdeui/ksyntaxhighlighter.cpp
@@ -27,7 +27,7 @@
#include <tqtimer.h>
#include <klocale.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <tdespell.h>
diff --git a/tdeui/ksystemtray.cpp b/tdeui/ksystemtray.cpp
index 717d5c574..3b68d583a 100644
--- a/tdeui/ksystemtray.cpp
+++ b/tdeui/ksystemtray.cpp
@@ -36,7 +36,7 @@
#include <kimageeffect.h>
#include <kiconloader.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <tqapplication.h>
#include <tqbitmap.h>
diff --git a/tdeui/ktabwidget.cpp b/tdeui/ktabwidget.cpp
index e447eab26..5eef3dd73 100644
--- a/tdeui/ktabwidget.cpp
+++ b/tdeui/ktabwidget.cpp
@@ -22,7 +22,7 @@
#include <tqstyle.h>
#include <tqstylesheet.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kiconloader.h>
#include <kstringhandler.h>
diff --git a/tdeui/ktimezonewidget.cpp b/tdeui/ktimezonewidget.cpp
index a9a73a4f5..5db720a68 100644
--- a/tdeui/ktimezonewidget.cpp
+++ b/tdeui/ktimezonewidget.cpp
@@ -19,7 +19,7 @@
#include <kdialog.h>
#include <kdebug.h>
-#include <kfile.h>
+#include <tdefile.h>
#include <klistview.h>
#include <klocale.h>
#include <kstandarddirs.h>
diff --git a/tdeui/ktip.cpp b/tdeui/ktip.cpp
index 085aba857..7be804565 100644
--- a/tdeui/ktip.cpp
+++ b/tdeui/ktip.cpp
@@ -35,7 +35,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <kaboutdata.h>
#include <kapplication.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kiconloader.h>
diff --git a/tdeui/ktoolbar.cpp b/tdeui/ktoolbar.cpp
index 41d416f01..8c64dfdc6 100644
--- a/tdeui/ktoolbar.cpp
+++ b/tdeui/ktoolbar.cpp
@@ -51,7 +51,7 @@
#include <kaction.h>
#include <kstdaction.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kiconloader.h>
#include <kcombobox.h>
#include <kpopupmenu.h>
diff --git a/tdeui/tdecmodule.cpp b/tdeui/tdecmodule.cpp
index 0b1b4f5fb..85a23341e 100644
--- a/tdeui/tdecmodule.cpp
+++ b/tdeui/tdecmodule.cpp
@@ -24,8 +24,8 @@
#include <tqlayout.h>
#include <kaboutdata.h>
-#include <kconfigskeleton.h>
-#include <kconfigdialogmanager.h>
+#include <tdeconfigskeleton.h>
+#include <tdeconfigdialogmanager.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kinstance.h>
diff --git a/tdeui/tdecmodule.h b/tdeui/tdecmodule.h
index 41d8d095e..12a10fac9 100644
--- a/tdeui/tdecmodule.h
+++ b/tdeui/tdecmodule.h
@@ -300,9 +300,9 @@ protected:
* Help: shows a "Help" button.
* Default: shows a "Use Defaults" button
* Apply: in kcontrol this will show an "Apply" and "Reset" button
- * in kcmshell this will show an "Ok", "Apply" and "Cancel" button
+ * in tdecmshell this will show an "Ok", "Apply" and "Cancel" button
*
- * If Apply is not specified, kcmshell will show a "Close" button.
+ * If Apply is not specified, tdecmshell will show a "Close" button.
*
* @see TDECModule::buttons
*/
diff --git a/tdeui/tdeconfigdialog.cpp b/tdeui/tdeconfigdialog.cpp
new file mode 100644
index 000000000..c8e848fa3
--- /dev/null
+++ b/tdeui/tdeconfigdialog.cpp
@@ -0,0 +1,259 @@
+/*
+ * This file is part of the KDE libraries
+ * Copyright (C) 2003 Benjamin C Meyer (ben+tdelibs at meyerhome dot net)
+ * Copyright (C) 2003 Waldo Bastian <bastian@kde.org>
+ * Copyright (C) 2004 Michael Brade <brade@kde.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+#include "tdeconfigdialog.h"
+
+#include <tdeconfigskeleton.h>
+#include <tdeconfigdialogmanager.h>
+#include <klocale.h>
+#include <kiconloader.h>
+#include <kdebug.h>
+
+#include <tqlayout.h>
+#include <tqvbox.h>
+#include <tqmap.h>
+
+TQAsciiDict<TDEConfigDialog> TDEConfigDialog::openDialogs;
+
+// This class is here purly so we don't break binary compatibility down the road.
+class TDEConfigDialog::TDEConfigDialogPrivate
+{
+public:
+ TDEConfigDialogPrivate(KDialogBase::DialogType t)
+ : shown(false), type(t), manager(0) { }
+
+ bool shown;
+ KDialogBase::DialogType type;
+ TDEConfigDialogManager *manager;
+ TQMap<TQWidget *, TDEConfigDialogManager *> managerForPage;
+};
+
+TDEConfigDialog::TDEConfigDialog( TQWidget *parent, const char *name,
+ TDEConfigSkeleton *config,
+ DialogType dialogType,
+ int dialogButtons,
+ ButtonCode defaultButton,
+ bool modal ) :
+ KDialogBase( dialogType, (WFlags)TQt::WStyle_DialogBorder,
+ parent, name, modal, i18n("Configure"), dialogButtons, defaultButton ),
+ d(new TDEConfigDialogPrivate(dialogType))
+{
+ if ( name ) {
+ openDialogs.insert(name, this);
+ } else {
+ TQCString genericName;
+ genericName.sprintf("SettingsDialog-%p", this);
+ openDialogs.insert(genericName, this);
+ setName(genericName);
+ }
+
+ connect(this, TQT_SIGNAL(okClicked()), this, TQT_SLOT(updateSettings()));
+ connect(this, TQT_SIGNAL(applyClicked()), this, TQT_SLOT(updateSettings()));
+ connect(this, TQT_SIGNAL(applyClicked()), this, TQT_SLOT(updateButtons()));
+ connect(this, TQT_SIGNAL(defaultClicked()), this, TQT_SLOT(updateWidgetsDefault()));
+ connect(this, TQT_SIGNAL(defaultClicked()), this, TQT_SLOT(updateButtons()));
+
+ d->manager = new TDEConfigDialogManager(this, config);
+ setupManagerConnections(d->manager);
+
+ enableButton(Apply, false);
+}
+
+TDEConfigDialog::~TDEConfigDialog()
+{
+ openDialogs.remove(name());
+ delete d;
+}
+
+void TDEConfigDialog::addPage(TQWidget *page,
+ const TQString &itemName,
+ const TQString &pixmapName,
+ const TQString &header,
+ bool manage)
+{
+ addPageInternal(page, itemName, pixmapName, header);
+ if(manage)
+ d->manager->addWidget(page);
+}
+
+void TDEConfigDialog::addPage(TQWidget *page,
+ TDEConfigSkeleton *config,
+ const TQString &itemName,
+ const TQString &pixmapName,
+ const TQString &header)
+{
+ addPageInternal(page, itemName, pixmapName, header);
+ d->managerForPage[page] = new TDEConfigDialogManager(page, config);
+ setupManagerConnections(d->managerForPage[page]);
+}
+
+void TDEConfigDialog::addPageInternal(TQWidget *page,
+ const TQString &itemName,
+ const TQString &pixmapName,
+ const TQString &header)
+{
+ if(d->shown)
+ {
+ kdDebug(240) << "TDEConfigDialog::addPage: can not add a page after the dialog has been shown.";
+ return;
+ }
+ switch(d->type)
+ {
+ case TreeList:
+ case IconList:
+ case Tabbed: {
+ TQVBox *frame = addVBoxPage(itemName, header, SmallIcon(pixmapName, 32));
+ frame->setSpacing( 0 );
+ frame->setMargin( 0 );
+ page->reparent(((TQWidget*)frame), 0, TQPoint());
+ }
+ break;
+
+ case Swallow:
+ {
+ page->reparent(this, 0, TQPoint());
+ setMainWidget(page);
+ }
+ break;
+
+ case Plain:
+ {
+ TQFrame *main = plainPage();
+ TQVBoxLayout *topLayout = new TQVBoxLayout( main, 0, 0 );
+ page->reparent(((TQWidget*)main), 0, TQPoint());
+ topLayout->addWidget( page );
+ }
+ break;
+
+ default:
+ kdDebug(240) << "TDEConfigDialog::addpage: unknown type.";
+ }
+}
+
+void TDEConfigDialog::setupManagerConnections(TDEConfigDialogManager *manager)
+{
+ connect(manager, TQT_SIGNAL(settingsChanged()), this, TQT_SLOT(settingsChangedSlot()));
+ connect(manager, TQT_SIGNAL(widgetModified()), this, TQT_SLOT(updateButtons()));
+
+ connect(this, TQT_SIGNAL(okClicked()), manager, TQT_SLOT(updateSettings()));
+ connect(this, TQT_SIGNAL(applyClicked()), manager, TQT_SLOT(updateSettings()));
+ connect(this, TQT_SIGNAL(defaultClicked()), manager, TQT_SLOT(updateWidgetsDefault()));
+}
+
+TDEConfigDialog* TDEConfigDialog::exists(const char* name)
+{
+ return openDialogs.find(name);
+}
+
+bool TDEConfigDialog::showDialog(const char* name)
+{
+ TDEConfigDialog *dialog = exists(name);
+ if(dialog)
+ dialog->show();
+ return (dialog != NULL);
+}
+
+void TDEConfigDialog::updateButtons()
+{
+ static bool only_once = false;
+ if (only_once) return;
+ only_once = true;
+
+ TQMap<TQWidget *, TDEConfigDialogManager *>::iterator it;
+
+ bool has_changed = d->manager->hasChanged() || hasChanged();
+ for (it = d->managerForPage.begin();
+ it != d->managerForPage.end() && !has_changed;
+ ++it)
+ {
+ has_changed |= (*it)->hasChanged();
+ }
+
+ enableButton(Apply, has_changed);
+
+ bool is_default = d->manager->isDefault() && isDefault();
+ for (it = d->managerForPage.begin();
+ it != d->managerForPage.end() && is_default;
+ ++it)
+ {
+ is_default &= (*it)->isDefault();
+ }
+
+ enableButton(Default, !is_default);
+
+ emit widgetModified();
+ only_once = false;
+}
+
+void TDEConfigDialog::settingsChangedSlot()
+{
+ // Update the buttons
+ updateButtons();
+ emit settingsChanged();
+ emit settingsChanged(name());
+}
+
+void TDEConfigDialog::show()
+{
+ TQMap<TQWidget *, TDEConfigDialogManager *>::iterator it;
+
+ updateWidgets();
+ d->manager->updateWidgets();
+ for (it = d->managerForPage.begin(); it != d->managerForPage.end(); ++it)
+ (*it)->updateWidgets();
+
+ bool has_changed = d->manager->hasChanged() || hasChanged();
+ for (it = d->managerForPage.begin();
+ it != d->managerForPage.end() && !has_changed;
+ ++it)
+ {
+ has_changed |= (*it)->hasChanged();
+ }
+
+ enableButton(Apply, has_changed);
+
+ bool is_default = d->manager->isDefault() && isDefault();
+ for (it = d->managerForPage.begin();
+ it != d->managerForPage.end() && is_default;
+ ++it)
+ {
+ is_default &= (*it)->isDefault();
+ }
+
+ enableButton(Default, !is_default);
+ d->shown = true;
+ KDialogBase::show();
+}
+
+void TDEConfigDialog::updateSettings()
+{
+}
+
+void TDEConfigDialog::updateWidgets()
+{
+}
+
+void TDEConfigDialog::updateWidgetsDefault()
+{
+}
+
+
+#include "tdeconfigdialog.moc"
diff --git a/tdeui/kconfigdialog.h b/tdeui/tdeconfigdialog.h
index f7cc10e26..f7cc10e26 100644
--- a/tdeui/kconfigdialog.h
+++ b/tdeui/tdeconfigdialog.h
diff --git a/tdeui/tests/itemcontainertest.cpp b/tdeui/tests/itemcontainertest.cpp
index 9e92fb47e..bb0c0338b 100644
--- a/tdeui/tests/itemcontainertest.cpp
+++ b/tdeui/tests/itemcontainertest.cpp
@@ -18,7 +18,7 @@
#include <kapplication.h>
#include <kglobal.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kiconview.h>
#include <klistview.h>
#include <klistbox.h>
diff --git a/tdeui/tests/kcolordlgtest.cpp b/tdeui/tests/kcolordlgtest.cpp
index a6dadcfd3..1a506cbc0 100644
--- a/tdeui/tests/kcolordlgtest.cpp
+++ b/tdeui/tests/kcolordlgtest.cpp
@@ -19,7 +19,7 @@
#include <kapplication.h>
#include "kcolordialog.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <klocale.h>
int main( int argc, char *argv[] )
diff --git a/tdeui/tests/kdockwidgetdemo.cpp b/tdeui/tests/kdockwidgetdemo.cpp
index 8b2ecb829..c252c7cf8 100644
--- a/tdeui/tests/kdockwidgetdemo.cpp
+++ b/tdeui/tests/kdockwidgetdemo.cpp
@@ -19,7 +19,7 @@
#include <tqstrlist.h>
#include <tqpainter.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kapplication.h>
//#include <kimgio.h>
#include <stdlib.h>
diff --git a/tdeui/tests/kfontdialogtest.cpp b/tdeui/tests/kfontdialogtest.cpp
index 14edee074..0b3d4eb30 100644
--- a/tdeui/tests/kfontdialogtest.cpp
+++ b/tdeui/tests/kfontdialogtest.cpp
@@ -26,7 +26,7 @@
#include <kapplication.h>
#include "kfontdialog.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
int main( int argc, char **argv )
diff --git a/tdeutils/CMakeLists.txt b/tdeutils/CMakeLists.txt
index 6f647a2b5..1e1982da4 100644
--- a/tdeutils/CMakeLists.txt
+++ b/tdeutils/CMakeLists.txt
@@ -19,7 +19,7 @@ include_directories(
${CMAKE_SOURCE_DIR}/dcop
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
${CMAKE_SOURCE_DIR}/tdeutils
${CMAKE_SOURCE_DIR}/interfaces/kregexpeditor
)
diff --git a/tdeutils/Makefile.am b/tdeutils/Makefile.am
index 5ba725545..9bc3e2e49 100644
--- a/tdeutils/Makefile.am
+++ b/tdeutils/Makefile.am
@@ -4,7 +4,7 @@ INCLUDES = -I$(top_srcdir)/interfaces/kregexpeditor $(all_includes)
lib_LTLIBRARIES = libtdeutils.la
libtdeutils_la_LDFLAGS = $(all_libraries) -no-undefined -version-info 3:0:2
# Needs KTrader
-libtdeutils_la_LIBADD = ../kio/libkio.la ksettings/libksettings.la $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDEUI) $(LIB_TDECORE) $(LIB_X11)
+libtdeutils_la_LIBADD = ../tdeio/libtdeio.la ksettings/libksettings.la $(LIB_QT) $(top_builddir)/dcop/libDCOP.la $(LIB_TDEUI) $(LIB_TDECORE) $(LIB_X11)
libtdeutils_la_SOURCES = kfind.cpp kfinddialog.cpp kreplace.cpp \
kreplacedialog.cpp tdecmoduleinfo.cpp tdecmoduleloader.cpp \
diff --git a/tdeutils/kplugininfo.cpp b/tdeutils/kplugininfo.cpp
index aec0a095c..2b4079bb8 100644
--- a/tdeutils/kplugininfo.cpp
+++ b/tdeutils/kplugininfo.cpp
@@ -21,7 +21,7 @@
#include <ksimpleconfig.h>
#include <ktrader.h>
#include <kdebug.h>
-#include <kconfigbase.h>
+#include <tdeconfigbase.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kdesktopfile.h>
diff --git a/tdeutils/ksettings/CMakeLists.txt b/tdeutils/ksettings/CMakeLists.txt
index 7a1d5034d..b495c90db 100644
--- a/tdeutils/ksettings/CMakeLists.txt
+++ b/tdeutils/ksettings/CMakeLists.txt
@@ -16,7 +16,7 @@ include_directories(
${CMAKE_SOURCE_DIR}/tdeutils
${CMAKE_SOURCE_DIR}/tdecore
${CMAKE_SOURCE_DIR}/tdeui
- ${CMAKE_SOURCE_DIR}/kio/kio
+ ${CMAKE_SOURCE_DIR}/tdeio/tdeio
)
##### headers ###################################
diff --git a/tdeutils/ksettings/componentsdialog.cpp b/tdeutils/ksettings/componentsdialog.cpp
index 097d1f6d7..89a5e2cd7 100644
--- a/tdeutils/ksettings/componentsdialog.cpp
+++ b/tdeutils/ksettings/componentsdialog.cpp
@@ -26,7 +26,7 @@
#include <kplugininfo.h>
#include <kiconloader.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kseparator.h>
namespace KSettings
diff --git a/tdeutils/ksettings/dispatcher.cpp b/tdeutils/ksettings/dispatcher.cpp
index 590ca7e3c..3a423422f 100644
--- a/tdeutils/ksettings/dispatcher.cpp
+++ b/tdeutils/ksettings/dispatcher.cpp
@@ -23,7 +23,7 @@
#include <kstaticdeleter.h>
#include <kdebug.h>
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <assert.h>
namespace KSettings
diff --git a/tdeutils/tdecmoduleloader.cpp b/tdeutils/tdecmoduleloader.cpp
index 73f6983d3..3627e1777 100644
--- a/tdeutils/tdecmoduleloader.cpp
+++ b/tdeutils/tdecmoduleloader.cpp
@@ -170,9 +170,9 @@ TDECModule* TDECModuleLoader::loadModule(const TDECModuleInfo &mod, ErrorReporti
/*
* Ok, we could not load the library.
* Try to run it as an executable.
- * This must not be done when calling from kcmshell, or you'll
+ * This must not be done when calling from tdecmshell, or you'll
* have infinite recursion
- * (startService calls kcmshell which calls modloader which calls startService...)
+ * (startService calls tdecmshell which calls modloader which calls startService...)
*
*/
if(withfallback)
diff --git a/tdeutils/tdecmoduleproxy.cpp b/tdeutils/tdecmoduleproxy.cpp
index 673074c16..d124db091 100644
--- a/tdeutils/tdecmoduleproxy.cpp
+++ b/tdeutils/tdecmoduleproxy.cpp
@@ -151,7 +151,7 @@ TDECModule * TDECModuleProxy::realModule() const
if( d->kcm )
return d->kcm;
- /* /We/ have no kcm, but kcmshell running with root prevs does.. */
+ /* /We/ have no kcm, but tdecmshell running with root prevs does.. */
if( d->rootMode )
return 0;
@@ -329,7 +329,7 @@ void TDECModuleProxy::runAsRoot()
lblBusy->show();
deleteClient();
- /* The DCOP registration is now gone, and it will occur again when kcmshell soon
+ /* The DCOP registration is now gone, and it will occur again when tdecmshell soon
* registers. Here's a race condition in other words, but how likely is that?
*
* - It's a user initiated action, which means the user have to do weird stuff, very
@@ -340,7 +340,7 @@ void TDECModuleProxy::runAsRoot()
* the DCOP object is established.
*/
- /* Prepare the process to run the kcmshell */
+ /* Prepare the process to run the tdecmshell */
TQString cmd = moduleInfo().service()->exec().stripWhiteSpace();
if (cmd.left(5) == "tdesu")
{
@@ -351,7 +351,7 @@ void TDECModuleProxy::runAsRoot()
cmd = TQString(cmd.remove( 0, cmd.find( ' ' ) )).stripWhiteSpace();
}
- if (cmd.left(8) == "kcmshell")
+ if (cmd.left(8) == "tdecmshell")
cmd = TQString(cmd.remove(0,8)).stripWhiteSpace();
/* Run the process */
@@ -364,7 +364,7 @@ void TDECModuleProxy::runAsRoot()
*d->rootProcess << tdesu;
*d->rootProcess << "--nonewdcop" << "-n" << "-d" << TQString( "-i%1" ).arg(moduleInfo().icon());
- *d->rootProcess << TQString("%1 %2 --embed-proxy %3 --lang %4").arg(locate("exe", "kcmshell"))
+ *d->rootProcess << TQString("%1 %2 --embed-proxy %3 --lang %4").arg(locate("exe", "tdecmshell"))
.arg(cmd).arg(d->embedWidget->winId()).arg(TDEGlobal::locale()->language());
connect(d->rootProcess, TQT_SIGNAL(processExited(TDEProcess*)), TQT_SLOT(rootExited()));
diff --git a/tdeutils/tdecmoduleproxyIface.h b/tdeutils/tdecmoduleproxyIface.h
index 22bfa8e52..79d7a68ac 100644
--- a/tdeutils/tdecmoduleproxyIface.h
+++ b/tdeutils/tdecmoduleproxyIface.h
@@ -93,9 +93,9 @@ k_dcop_signals:
* @ingroup tdecmodule
* @brief DCOP interface for communicating with the real module running in root mode.
*
- * When a TDECModuleProxy tells kcmshell to load "itself" and embed into the
+ * When a TDECModuleProxy tells tdecmshell to load "itself" and embed into the
* TDECModuleProxy, this DCOP interface is used to communicate to the real TDECModuleProxy, since
- * the TDECModuleProxy which told kcmshell to load itself, is nothing but a shell.
+ * the TDECModuleProxy which told tdecmshell to load itself, is nothing but a shell.
*
* Currently is only the changed signal routed, but it's possible to proxy
* the rest of the TDECModuleProxy API, if it turns out necessary.
diff --git a/tdeutils/tdecmoduleproxyIfaceImpl.cpp b/tdeutils/tdecmoduleproxyIfaceImpl.cpp
index 53019f72f..127831b02 100644
--- a/tdeutils/tdecmoduleproxyIfaceImpl.cpp
+++ b/tdeutils/tdecmoduleproxyIfaceImpl.cpp
@@ -100,7 +100,7 @@ TDECModuleProxyRootCommunicatorImpl::TDECModuleProxyRootCommunicatorImpl
p( const_cast<TDECModuleProxy *>( client ))
{
/*
- * Connect kcmshell's TDECModuleProxy's change signal
+ * Connect tdecmshell's TDECModuleProxy's change signal
* to us, such that we act as a proxy for
* TDECModuleProxy's API.
*/
diff --git a/tdewallet/client/tdewallet.cc b/tdewallet/client/tdewallet.cc
index 73b423cbc..add75c93d 100644
--- a/tdewallet/client/tdewallet.cc
+++ b/tdewallet/client/tdewallet.cc
@@ -20,7 +20,7 @@
#include "tdewallettypes.h"
#include "tdewallet.h"
-#include <kconfig.h>
+#include <tdeconfig.h>
#include <kdebug.h>
#include <tdeversion.h>
#include <dcopclient.h>
diff --git a/win/pro_files/kate/part/part.pro b/win/pro_files/kate/part/part.pro
index ad3acfee7..65d87e323 100644
--- a/win/pro_files/kate/part/part.pro
+++ b/win/pro_files/kate/part/part.pro
@@ -12,7 +12,7 @@ LIBS += $$KDELIBDESTDIR/katepartinterfaces$$KDELIB_SUFFIX \
$$KDELIBDESTDIR/tdetexteditor$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdecore$$KDELIB_SUFFIX \
$$KDELIBDESTDIR/tdeui$$KDELIB_SUFFIX \
$$KDELIBDESTDIR/tdeutils$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeparts$$KDELIB_SUFFIX \
- $$KDELIBDESTDIR/dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR/kio$$KDELIB_SUFFIX
+ $$KDELIBDESTDIR/dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeio$$KDELIB_SUFFIX
INCLUDEPATH += $(KDELIBS)/interfaces $(KDELIBS)/interfaces/kregexpeditor \
$(KDELIBS)/tdeutils $(KDELIBS)/tdeprint
diff --git a/win/pro_files/kded/kded.pro b/win/pro_files/kded/kded.pro
index 05f2455cc..ee8de94d2 100644
--- a/win/pro_files/kded/kded.pro
+++ b/win/pro_files/kded/kded.pro
@@ -5,7 +5,7 @@ include( $(KDELIBS)/win/common.pro )
LIBS += $$KDELIBDESTDIR\dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR\kio$$KDELIB_SUFFIX
# icon
-LIBS+=$(KDELIBS)/win/resources/kbuildsycoca.res
+LIBS+=$(KDELIBS)/win/resources/tdebuildsycoca.res
INCLUDEPATH += $(KDELIBS)/kded
@@ -13,15 +13,15 @@ system( bash kmoc )
!contains(CONFIG,GUI) {
!contains(KW_CONFIG,release) {
- TARGET = kbuildsycoca_d
+ TARGET = tdebuildsycoca_d
}
contains(KW_CONFIG,release) {
- TARGET = kbuildsycoca
+ TARGET = tdebuildsycoca
}
}
SOURCES = \
-kbuildsycoca.cpp \
+tdebuildsycoca.cpp \
kbuildimageiofactory.cpp \
kbuildprotocolinfofactory.cpp \
kbuildservicefactory.cpp \
@@ -32,5 +32,5 @@ vfolder_menu.cpp
HEADERS =
-TRANSLATIONS = kbuildsycoca_pl.ts
+TRANSLATIONS = tdebuildsycoca_pl.ts
diff --git a/win/pro_files/kded/kded_rel.pro b/win/pro_files/kded/kded_rel.pro
index a878305ba..b17e1f3c7 100644
--- a/win/pro_files/kded/kded_rel.pro
+++ b/win/pro_files/kded/kded_rel.pro
@@ -9,4 +9,4 @@ QMAKE_CXXFLAGS += -DKBUILDSYCOCA_GUI
include( "kded.pro" )
-TARGET = kbuildsycocaw #gui version
+TARGET = tdebuildsycocaw #gui version
diff --git a/win/pro_files/kdewidgets/kdewidgets.pro b/win/pro_files/kdewidgets/kdewidgets.pro
index 8bbf93cd9..435087785 100644
--- a/win/pro_files/kdewidgets/kdewidgets.pro
+++ b/win/pro_files/kdewidgets/kdewidgets.pro
@@ -11,7 +11,7 @@ TARGET = kdewidgets
DESTDIR = $$KDELIBDESTDIR/trinity/plugins/designer
-LIBS += $$KDELIBDESTDIR/tdecore$$KDELIB_SUFFIX $$KDELIBDESTDIR/kio$$KDELIB_SUFFIX \
+LIBS += $$KDELIBDESTDIR/tdecore$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeio$$KDELIB_SUFFIX \
$$KDELIBDESTDIR/tdeui$$KDELIB_SUFFIX \
$$KDELIBDESTDIR/kabc$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeutils$$KDELIB_SUFFIX \
$$KDELIBDESTDIR/tderesources$$KDELIB_SUFFIX
diff --git a/win/pro_files/kio/kfile/tests/kfiletreeviewtest.pro b/win/pro_files/kio/kfile/tests/kfiletreeviewtest.pro
deleted file mode 100644
index c2d4afa73..000000000
--- a/win/pro_files/kio/kfile/tests/kfiletreeviewtest.pro
+++ /dev/null
@@ -1,29 +0,0 @@
-TEMPLATE = app
-
-include( $(KDELIBS)/win/common.pro )
-
-
-#allow to select target independently from debug information
-tdebase_release:CONFIG -= console
-tdebase_release:CONFIG += windows
-tdebase_release:QMAKE_MAKEFILE = Makefile.release
-
-
-TARGET = kfiletreeviewtest
-
-LIBS += $$KDELIBDESTDIR/tdefx$$KDELIB_SUFFIX \
- $$KDELIBDESTDIR/kio$$KDELIB_SUFFIX \
- $$KDELIBDESTDIR/tdeparts$$KDELIB_SUFFIX \
- $$KDELIBDESTDIR/dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR/kio$$KDELIB_SUFFIX
-
-# icon
-LIBS+=$(KDELIBS)/win/resources/kfind.res
-
-system( bash kmoc )
-
-SOURCES = \
-kfiletreeviewtest.cpp
-
-HEADERS =
-
-
diff --git a/win/pro_files/kio/kio.pro b/win/pro_files/kio/kio.pro
index 179de7086..15056d021 100644
--- a/win/pro_files/kio/kio.pro
+++ b/win/pro_files/kio/kio.pro
@@ -9,17 +9,17 @@ DEFINES += MAKE_KIO_LIB
LIBS += $$KDELIBDESTDIR\tdecore$$KDELIB_SUFFIX $$KDELIBDESTDIR\tdeui$$KDELIB_SUFFIX \
$$KDELIBDESTDIR\dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR\kdewin32$$KDELIB_SUFFIX
-system( bash kmoc kio kfile misc bookmarks kssl )
+system( bash kmoc kio tdefile misc bookmarks kssl )
TARGET = kio$$KDEBUG
-INCLUDEPATH += $(KDELIBS)/tdecore/network $(KDELIBS)/kio/kio $(KDELIBS)/kio/misc $(KDELIBS)/kio/bookmarks \
- $(KDELIBS)/kio/kssl \
+INCLUDEPATH += $(KDELIBS)/tdecore/network $(KDELIBS)/tdeio/tdeio $(KDELIBS)/tdeio/misc $(KDELIBS)/tdeio/bookmarks \
+ $(KDELIBS)/tdeio/kssl \
$(KDELIBS)/libltdl $(KDELIBS)/interfaces \
- $(KDELIBS)/kio/kio/moc $(KDELIBS)/kio/misc/moc $(KDELIBS)/kio/kfile/moc \
- $(KDELIBS)/kio/misc/moc \
- $(KDELIBS)/kio/bookmarks/moc \
- $(KDELIBS)/kio/kssl/moc $(KDELIBS)/tdewallet/client
+ $(KDELIBS)/tdeio/tdeio/moc $(KDELIBS)/tdeio/misc/moc $(KDELIBS)/tdeio/tdefile/moc \
+ $(KDELIBS)/tdeio/misc/moc \
+ $(KDELIBS)/tdeio/bookmarks/moc \
+ $(KDELIBS)/tdeio/kssl/moc $(KDELIBS)/tdewallet/client
system( cd kio && dcopidl kdirnotify.h > kdirnotify.kidl && dcopidl2cpp --no-stub kdirnotify.kidl )
system( cd kio && dcopidl observer.h > observer.kidl && dcopidl2cpp observer.kidl )
@@ -29,78 +29,78 @@ system( cd misc && dcopidl uiserver.h > uiserver.kidl && dcopidl2cpp uiserver.ki
SOURCES = \
-kio/authinfo.cpp \
-kio/chmodjob.cpp \
-kio/connection.cpp \
-kio/dataprotocol.cpp \
-kio/dataslave.cpp \
-kio/davjob.cpp \
-kio/defaultprogress.cpp \
-kio/global.cpp \
-kio/job.cpp \
-kio/kacl.cpp \
-kio/kar.cpp \
-kio/karchive.cpp \
-kio/kdatatool.cpp \
-kio/kdcopservicestarter.cpp \
-kio/kdirlister.cpp \
-kio/kdirnotify.cpp \
-kio/kdirwatch.cpp \
-kio/kemailsettings.cpp \
-kio/kfilefilter.cpp \
-kio/kfileitem.cpp \
-kio/kfilemetainfo.cpp \
-kio/kfileshare.cpp \
-kio/kfilterbase.cpp \
-kio/kfilterdev.cpp \
-kio/kimageio.cpp \
-kio/kmimemagic.cpp \
-kio/kmimetype.cpp \
-kio/kmimetypechooser.cpp \
-kio/knfsshare.cpp \
-kio/kprotocolinfo.cpp \
-kio/kprotocolmanager.cpp \
-kio/kremoteencoding.cpp \
-kio/krun.cpp \
-kio/ksambashare.cpp \
-kio/kscan.cpp \
-kio/kservice.cpp \
-kio/kservicefactory.cpp \
-kio/kservicegroup.cpp \
-kio/kservicegroupfactory.cpp \
-kio/kservicetype.cpp \
-kio/kservicetypefactory.cpp \
-kio/kshellcompletion.cpp \
-kio/kshred.cpp \
-kio/ktar.cpp \
-kio/ktrader.cpp \
-kio/ktraderparse.cpp \
-kio/ktraderparsetree.cpp \
-kio/kurifilter.cpp \
-kio/kurlcompletion.cpp \
-kio/kurlpixmapprovider.cpp \
-kio/kuserprofile.cpp \
-kio/kzip.cpp \
-kio/lex.c \
-kio/metainfojob.cpp \
-kio/netaccess.cpp \
-kio/observer.cpp \
-kio/passdlg.cpp \
-kio/paste.cpp \
-kio/pastedialog.cpp \
-kio/previewjob.cpp \
-kio/progressbase.cpp \
-kio/renamedlg.cpp \
-kio/scheduler.cpp \
-kio/sessiondata.cpp \
-kio/skipdlg.cpp \
-kio/slave.cpp \
-kio/slavebase.cpp \
-kio/slaveconfig.cpp \
-kio/slaveinterface.cpp \
-kio/statusbarprogress.cpp \
-kio/tcpslavebase.cpp \
-kio/yacc.c \
+tdeio/authinfo.cpp \
+tdeio/chmodjob.cpp \
+tdeio/connection.cpp \
+tdeio/dataprotocol.cpp \
+tdeio/dataslave.cpp \
+tdeio/davjob.cpp \
+tdeio/defaultprogress.cpp \
+tdeio/global.cpp \
+tdeio/job.cpp \
+tdeio/kacl.cpp \
+tdeio/kar.cpp \
+tdeio/karchive.cpp \
+tdeio/kdatatool.cpp \
+tdeio/kdcopservicestarter.cpp \
+tdeio/kdirlister.cpp \
+tdeio/kdirnotify.cpp \
+tdeio/kdirwatch.cpp \
+tdeio/kemailsettings.cpp \
+tdeio/tdefilefilter.cpp \
+tdeio/tdefileitem.cpp \
+tdeio/tdefilemetainfo.cpp \
+tdeio/tdefileshare.cpp \
+tdeio/kfilterbase.cpp \
+tdeio/kfilterdev.cpp \
+tdeio/kimageio.cpp \
+tdeio/kmimemagic.cpp \
+tdeio/kmimetype.cpp \
+tdeio/kmimetypechooser.cpp \
+tdeio/knfsshare.cpp \
+tdeio/kprotocolinfo.cpp \
+tdeio/kprotocolmanager.cpp \
+tdeio/kremoteencoding.cpp \
+tdeio/krun.cpp \
+tdeio/ksambashare.cpp \
+tdeio/kscan.cpp \
+tdeio/kservice.cpp \
+tdeio/kservicefactory.cpp \
+tdeio/kservicegroup.cpp \
+tdeio/kservicegroupfactory.cpp \
+tdeio/kservicetype.cpp \
+tdeio/kservicetypefactory.cpp \
+tdeio/kshellcompletion.cpp \
+tdeio/kshred.cpp \
+tdeio/ktar.cpp \
+tdeio/ktrader.cpp \
+tdeio/ktraderparse.cpp \
+tdeio/ktraderparsetree.cpp \
+tdeio/kurifilter.cpp \
+tdeio/kurlcompletion.cpp \
+tdeio/kurlpixmapprovider.cpp \
+tdeio/kuserprofile.cpp \
+tdeio/kzip.cpp \
+tdeio/lex.c \
+tdeio/metainfojob.cpp \
+tdeio/netaccess.cpp \
+tdeio/observer.cpp \
+tdeio/passdlg.cpp \
+tdeio/paste.cpp \
+tdeio/pastedialog.cpp \
+tdeio/previewjob.cpp \
+tdeio/progressbase.cpp \
+tdeio/renamedlg.cpp \
+tdeio/scheduler.cpp \
+tdeio/sessiondata.cpp \
+tdeio/skipdlg.cpp \
+tdeio/slave.cpp \
+tdeio/slavebase.cpp \
+tdeio/slaveconfig.cpp \
+tdeio/slaveinterface.cpp \
+tdeio/statusbarprogress.cpp \
+tdeio/tcpslavebase.cpp \
+tdeio/yacc.c \
\
bookmarks/kbookmark.cc \
bookmarks/kbookmarkbar.cc \
@@ -116,41 +116,41 @@ bookmarks/kbookmarkimporter_opera.cc \
bookmarks/kbookmarkmanager.cc \
bookmarks/kbookmarkmenu.cc \
\
-kfile/kcombiview.cpp \
-kfile/kcustommenueditor.cpp \
-kfile/kdiroperator.cpp \
-kfile/kdirselectdialog.cpp \
-kfile/kdirsize.cpp \
-kfile/kdiskfreesp.cpp \
-kfile/kencodingfiledialog.cpp \
-kfile/kfilebookmarkhandler.cpp \
-kfile/kfiledetailview.cpp \
-kfile/kfiledialog.cpp \
-kfile/kfilefiltercombo.cpp \
-kfile/kfileiconview.cpp \
-kfile/kfilemetainfowidget.cpp \
-kfile/kfilemetapreview.cpp \
-kfile/kfilepreview.cpp \
-kfile/kfilesharedlg.cpp \
-kfile/kfilespeedbar.cpp \
-kfile/kfiletreebranch.cpp \
-kfile/kfiletreeview.cpp \
-kfile/kfiletreeviewitem.cpp \
-kfile/kfileview.cpp \
-kfile/kicondialog.cpp \
-kfile/kimagefilepreview.cpp \
-kfile/kmetaprops.cpp \
-kfile/knotifydialog.cpp \
-kfile/kopenwith.cpp \
-kfile/kpreviewprops.cpp \
-kfile/kpreviewwidgetbase.cpp \
-kfile/kpropertiesdialog.cpp \
-kfile/krecentdirs.cpp \
-kfile/krecentdocument.cpp \
-kfile/kurlbar.cpp \
-kfile/kurlcombobox.cpp \
-kfile/kurlrequester.cpp \
-kfile/kurlrequesterdlg.cpp \
+tdefile/kcombiview.cpp \
+tdefile/kcustommenueditor.cpp \
+tdefile/kdiroperator.cpp \
+tdefile/kdirselectdialog.cpp \
+tdefile/kdirsize.cpp \
+tdefile/kdiskfreesp.cpp \
+tdefile/kencodingfiledialog.cpp \
+tdefile/tdefilebookmarkhandler.cpp \
+tdefile/tdefiledetailview.cpp \
+tdefile/tdefiledialog.cpp \
+tdefile/tdefilefiltercombo.cpp \
+tdefile/tdefileiconview.cpp \
+tdefile/tdefilemetainfowidget.cpp \
+tdefile/tdefilemetapreview.cpp \
+tdefile/tdefilepreview.cpp \
+tdefile/tdefilesharedlg.cpp \
+tdefile/tdefilespeedbar.cpp \
+tdefile/tdefiletreebranch.cpp \
+tdefile/tdefiletreeview.cpp \
+tdefile/tdefiletreeviewitem.cpp \
+tdefile/tdefileview.cpp \
+tdefile/kicondialog.cpp \
+tdefile/kimagefilepreview.cpp \
+tdefile/kmetaprops.cpp \
+tdefile/knotifydialog.cpp \
+tdefile/kopenwith.cpp \
+tdefile/kpreviewprops.cpp \
+tdefile/kpreviewwidgetbase.cpp \
+tdefile/kpropertiesdialog.cpp \
+tdefile/krecentdirs.cpp \
+tdefile/krecentdocument.cpp \
+tdefile/kurlbar.cpp \
+tdefile/kurlcombobox.cpp \
+tdefile/kurlrequester.cpp \
+tdefile/kurlrequesterdlg.cpp \
\
misc/uiserver.cpp \
\
@@ -176,7 +176,7 @@ kssl/ksslpeerinfo.cc \
kssl/kopenssl.cc \
kssl/ksmimecrypto.cc
-#removed kio/kautomount.cpp \
+#removed tdeio/kautomount.cpp \
SOURCES += \
../tdecore/kprotocolinfo_tdecore.cpp
@@ -189,10 +189,10 @@ SOURCES += \
# generated:
SOURCES += \
-kio/kdirnotify_stub.cpp \
-kio/kdirnotify_skel.cpp \
-kio/observer_stub.cpp \
-kio/observer_skel.cpp \
+tdeio/kdirnotify_stub.cpp \
+tdeio/kdirnotify_skel.cpp \
+tdeio/observer_stub.cpp \
+tdeio/observer_skel.cpp \
\
bookmarks/kbookmarknotifier_stub.cpp \
bookmarks/kbookmarknotifier_skel.cpp \
@@ -206,7 +206,7 @@ misc/uiserver_skel.cpp
FORMS = \
kssl/keygenwizard.ui \
kssl/keygenwizard2.ui \
-kfile/knotifywidgetbase.ui \
-kfile/kpropertiesdesktopadvbase.ui \
-kfile/kpropertiesdesktopbase.ui \
-kfile/kpropertiesmimetypebase.ui
+tdefile/knotifywidgetbase.ui \
+tdefile/kpropertiesdesktopadvbase.ui \
+tdefile/kpropertiesdesktopbase.ui \
+tdefile/kpropertiesmimetypebase.ui
diff --git a/win/pro_files/kio/tdefile/tests/tdefiletreeviewtest.pro b/win/pro_files/kio/tdefile/tests/tdefiletreeviewtest.pro
new file mode 100644
index 000000000..58f334806
--- /dev/null
+++ b/win/pro_files/kio/tdefile/tests/tdefiletreeviewtest.pro
@@ -0,0 +1,29 @@
+TEMPLATE = app
+
+include( $(KDELIBS)/win/common.pro )
+
+
+#allow to select target independently from debug information
+tdebase_release:CONFIG -= console
+tdebase_release:CONFIG += windows
+tdebase_release:QMAKE_MAKEFILE = Makefile.release
+
+
+TARGET = tdefiletreeviewtest
+
+LIBS += $$KDELIBDESTDIR/tdefx$$KDELIB_SUFFIX \
+ $$KDELIBDESTDIR/tdeio$$KDELIB_SUFFIX \
+ $$KDELIBDESTDIR/tdeparts$$KDELIB_SUFFIX \
+ $$KDELIBDESTDIR/dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeio$$KDELIB_SUFFIX
+
+# icon
+LIBS+=$(KDELIBS)/win/resources/kfind.res
+
+system( bash kmoc )
+
+SOURCES = \
+tdefiletreeviewtest.cpp
+
+HEADERS =
+
+
diff --git a/win/pro_files/kioslave/common.pro b/win/pro_files/kioslave/common.pro
deleted file mode 100644
index e1a63c761..000000000
--- a/win/pro_files/kioslave/common.pro
+++ /dev/null
@@ -1,8 +0,0 @@
-TEMPLATE = lib
-
-CONFIG += trinitylib #this is a dynamic kde library
-
-include( $(KDELIBS)/win/common.pro )
-
-LIBS += $$KDELIBDESTDIR/tdecore$$KDELIB_SUFFIX $$KDELIBDESTDIR/kio$$KDELIB_SUFFIX
-
diff --git a/win/pro_files/tdecore/kconfig_compiler/kconfig_compiler.pro b/win/pro_files/tdecore/kconfig_compiler/kconfig_compiler.pro
deleted file mode 100644
index 5b8272185..000000000
--- a/win/pro_files/tdecore/kconfig_compiler/kconfig_compiler.pro
+++ /dev/null
@@ -1,18 +0,0 @@
-TEMPLATE = app
-
-include( $(KDELIBS)/win/common.pro )
-
-TARGET = kconfig_compiler
-
-win32 {
-#CONFIG -= console
-#CONFIG += windows
-}
-
-#system( bash kmoc )
-
-SOURCES = kconfig_compiler.cpp
-
-HEADERS =
-
-
diff --git a/win/pro_files/tdecore/tdeconfig_compiler/tdeconfig_compiler.pro b/win/pro_files/tdecore/tdeconfig_compiler/tdeconfig_compiler.pro
new file mode 100644
index 000000000..b8f175369
--- /dev/null
+++ b/win/pro_files/tdecore/tdeconfig_compiler/tdeconfig_compiler.pro
@@ -0,0 +1,18 @@
+TEMPLATE = app
+
+include( $(KDELIBS)/win/common.pro )
+
+TARGET = tdeconfig_compiler
+
+win32 {
+#CONFIG -= console
+#CONFIG += windows
+}
+
+#system( bash kmoc )
+
+SOURCES = tdeconfig_compiler.cpp
+
+HEADERS =
+
+
diff --git a/win/pro_files/tdecore/tdecore.pro b/win/pro_files/tdecore/tdecore.pro
index ed6662391..0e868d6f9 100644
--- a/win/pro_files/tdecore/tdecore.pro
+++ b/win/pro_files/tdecore/tdecore.pro
@@ -46,17 +46,17 @@ kurl.cpp \
kidna.cpp \
kstaticdeleter.cpp \
kstandarddirs.cpp \
-kconfig.cpp \
-kconfigdialogmanager.cpp \
+tdeconfig.cpp \
+tdeconfigdialogmanager.cpp \
kcharsets.cpp \
kglobal.cpp \
kdebug.cpp \
ktempfile.cpp \
ktempdir.cpp \
ksavefile.cpp \
-kconfigbackend.cpp \
-kconfigbase.cpp \
-kconfigskeleton.cpp \
+tdeconfigbackend.cpp \
+tdeconfigbase.cpp \
+tdeconfigskeleton.cpp \
klockfile.cpp \
kstdaccel.cpp \
kcheckaccelerators.cpp \
@@ -96,7 +96,7 @@ kmdcodec.cpp \
kdcoppropertyproxy.cpp \
klibloader.cpp \
kprotocolinfo_tdecore.cpp \
-../kio/kio/kprotocolinfo.cpp \
+../tdeio/tdeio/kprotocolinfo.cpp \
kprotocolinfofactory.cpp \
kmountpoint.cpp \
kmacroexpander.cpp \
diff --git a/win/pro_files/kioslave/bzip2/bzip2.pro b/win/pro_files/tdeioslave/bzip2/bzip2.pro
index ba76a95a4..ba76a95a4 100644
--- a/win/pro_files/kioslave/bzip2/bzip2.pro
+++ b/win/pro_files/tdeioslave/bzip2/bzip2.pro
diff --git a/win/pro_files/tdeioslave/common.pro b/win/pro_files/tdeioslave/common.pro
new file mode 100644
index 000000000..6b6ee9d54
--- /dev/null
+++ b/win/pro_files/tdeioslave/common.pro
@@ -0,0 +1,8 @@
+TEMPLATE = lib
+
+CONFIG += trinitylib #this is a dynamic kde library
+
+include( $(KDELIBS)/win/common.pro )
+
+LIBS += $$KDELIBDESTDIR/tdecore$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeio$$KDELIB_SUFFIX
+
diff --git a/win/pro_files/kioslave/gzip/gzip.pro b/win/pro_files/tdeioslave/gzip/gzip.pro
index fb09f18c3..fb09f18c3 100644
--- a/win/pro_files/kioslave/gzip/gzip.pro
+++ b/win/pro_files/tdeioslave/gzip/gzip.pro
diff --git a/win/pro_files/kioslave/kioslave.pro b/win/pro_files/tdeioslave/tdeioslave.pro
index a28199480..a28199480 100644
--- a/win/pro_files/kioslave/kioslave.pro
+++ b/win/pro_files/tdeioslave/tdeioslave.pro
diff --git a/win/pro_files/tdeparts/tdeparts.pro b/win/pro_files/tdeparts/tdeparts.pro
index 5e724cd1f..e26516544 100644
--- a/win/pro_files/tdeparts/tdeparts.pro
+++ b/win/pro_files/tdeparts/tdeparts.pro
@@ -9,9 +9,9 @@ DEFINES += MAKE_KPARTS_LIB
TARGET = tdeparts$$KDEBUG
LIBS += $$KDELIBDESTDIR/tdecore$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeui$$KDELIB_SUFFIX \
- $$KDELIBDESTDIR/dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR/kio$$KDELIB_SUFFIX
+ $$KDELIBDESTDIR/dcop$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeio$$KDELIB_SUFFIX
-INCLUDEPATH += $(KDELIBS)/kio/kfile
+INCLUDEPATH += $(KDELIBS)/tdeio/tdefile
system( bash kmoc )
diff --git a/win/pro_files/tdeui/tdeui.pro b/win/pro_files/tdeui/tdeui.pro
index 0c8733d55..b6a0a44d2 100644
--- a/win/pro_files/tdeui/tdeui.pro
+++ b/win/pro_files/tdeui/tdeui.pro
@@ -38,7 +38,7 @@ kcolordrag.cpp \
kcombobox.cpp \
kcommand.cpp \
kcompletionbox.cpp \
-kconfigdialog.cpp \
+tdeconfigdialog.cpp \
kcursor.cpp \
kdatepicker.cpp \
kdatetbl.cpp \
diff --git a/win/pro_files/tdeutils/tdeutils.pro b/win/pro_files/tdeutils/tdeutils.pro
index f8e035d72..6507132ee 100644
--- a/win/pro_files/tdeutils/tdeutils.pro
+++ b/win/pro_files/tdeutils/tdeutils.pro
@@ -9,7 +9,7 @@ DEFINES += MAKE_KUTILS_LIB
TARGET = tdeutils$$KDEBUG
LIBS += $$KDELIBDESTDIR/tdecore$$KDELIB_SUFFIX $$KDELIBDESTDIR/tdeui$$KDELIB_SUFFIX \
- $$KDELIBDESTDIR/kio$$KDELIB_SUFFIX
+ $$KDELIBDESTDIR/tdeio$$KDELIB_SUFFIX
INCLUDEPATH += $(KDELIBS)/interfaces/kregexpeditor
diff --git a/win/resources/kbuildsycoca.res b/win/resources/tdebuildsycoca.res
index b26e2349c..b26e2349c 100644
--- a/win/resources/kbuildsycoca.res
+++ b/win/resources/tdebuildsycoca.res
Binary files differ
diff --git a/win/tools/build_tdelibs_dbg b/win/tools/build_tdelibs_dbg
index 5a6c31512..3fcfe0c20 100644
--- a/win/tools/build_tdelibs_dbg
+++ b/win/tools/build_tdelibs_dbg
@@ -53,8 +53,8 @@ kabc \
tdeutils \
tdeparts \
tdemdi \
-kioslave/gzip \
-kioslave/bzip2 \
+tdeioslave/gzip \
+tdeioslave/bzip2 \
interfaces/tdetexteditor \
kate/interfaces \
kate/part \
diff --git a/win/tools/build_tdelibs_rel b/win/tools/build_tdelibs_rel
index 2cd412542..399dcadda 100644
--- a/win/tools/build_tdelibs_rel
+++ b/win/tools/build_tdelibs_rel
@@ -53,8 +53,8 @@ kabc \
tdeutils \
tdeparts \
tdemdi \
-kioslave/gzip \
-kioslave/bzip2 \
+tdeioslave/gzip \
+tdeioslave/bzip2 \
interfaces/tdetexteditor \
kate/interfaces \
kate/part \
diff --git a/win/tools/kde_env b/win/tools/kde_env
index 0fbf1410c..c8e630de3 100755
--- a/win/tools/kde_env
+++ b/win/tools/kde_env
@@ -14,7 +14,7 @@ fi
# Generic settings
export KDELIBS=$KDEWIN\\tdelibs # KDElibs/win32 source directory
-export INCLUDE="$KDELIBS\\win;$KDELIBS;$KDELIBS\\tdecore;$KDELIBS\\tdefx;$KDELIBS\\tdeprint;$KDELIBS\\tdeui;$KDELIBS\\tdemdi;$KDELIBS\\dcop;$KDELIBS\\kio;$KDELIBS\\kio\\kio;$KDELIBS\\kio\\kfile;$INCLUDE"
+export INCLUDE="$KDELIBS\\win;$KDELIBS;$KDELIBS\\tdecore;$KDELIBS\\tdefx;$KDELIBS\\tdeprint;$KDELIBS\\tdeui;$KDELIBS\\tdemdi;$KDELIBS\\dcop;$KDELIBS\\kio;$KDELIBS\\kio\\kio;$KDELIBS\\kio\\tdefile;$INCLUDE"
# Version information for binaries
# We're changing this from time to time
diff --git a/win/win32_utils.h b/win/win32_utils.h
index a0702c84c..1f18264cc 100644
--- a/win/win32_utils.h
+++ b/win/win32_utils.h
@@ -81,7 +81,7 @@ bool showWin32FilePropertyDialog(const TQString& fileName);
/**
\return two-letter locale name (like "en" or "pl") taken from MS Windows native registry.
Useful when we don't want to rely on KSyCoCa.
- Used e.g. by kbuildsycoca application.
+ Used e.g. by tdebuildsycoca application.
*/
KDEWIN32_EXPORT
TQCString getWin32LocaleName();