]> git.lyx.org Git - lyx.git/blob - src/VCBackend.cpp
Compile fix.
[lyx.git] / src / VCBackend.cpp
1 /**
2  * \file VCBackend.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Pavel Sanda
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "VCBackend.h"
15 #include "Buffer.h"
16 #include "LyX.h"
17 #include "FuncRequest.h"
18
19 #include "frontends/alert.h"
20 #include "frontends/Application.h"
21
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/filetools.h"
25 #include "support/gettext.h"
26 #include "support/lstrings.h"
27 #include "support/Path.h"
28 #include "support/Systemcall.h"
29 #include "support/regex.h"
30
31 #include <fstream>
32
33 using namespace std;
34 using namespace lyx::support;
35
36
37
38 namespace lyx {
39
40
41 int VCS::doVCCommandCall(string const & cmd, FileName const & path)
42 {
43         LYXERR(Debug::LYXVC, "doVCCommandCall: " << cmd);
44         Systemcall one;
45         support::PathChanger p(path);
46         return one.startscript(Systemcall::Wait, cmd, false);
47 }
48
49
50 int VCS::doVCCommand(string const & cmd, FileName const & path, bool reportError)
51 {
52         if (owner_)
53                 owner_->setBusy(true);
54
55         int const ret = doVCCommandCall(cmd, path);
56
57         if (owner_)
58                 owner_->setBusy(false);
59         if (ret && reportError)
60                 frontend::Alert::error(_("Revision control error."),
61                         bformat(_("Some problem occured while running the command:\n"
62                                   "'%1$s'."),
63                         from_utf8(cmd)));
64         return ret;
65 }
66
67
68 /////////////////////////////////////////////////////////////////////
69 //
70 // RCS
71 //
72 /////////////////////////////////////////////////////////////////////
73
74 RCS::RCS(FileName const & m)
75 {
76         master_ = m;
77         scanMaster();
78 }
79
80
81 FileName const RCS::findFile(FileName const & file)
82 {
83         // Check if *,v exists.
84         FileName tmp(file.absFileName() + ",v");
85         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
86         if (tmp.isReadableFile()) {
87                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
88                 return tmp;
89         }
90
91         // Check if RCS/*,v exists.
92         tmp = FileName(addName(addPath(onlyPath(file.absFileName()), "RCS"), file.absFileName()) + ",v");
93         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
94         if (tmp.isReadableFile()) {
95                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
96                 return tmp;
97         }
98
99         return FileName();
100 }
101
102
103 void RCS::retrieve(FileName const & file)
104 {
105         LYXERR(Debug::LYXVC, "LyXVC::RCS: retrieve.\n\t" << file);
106         doVCCommandCall("co -q -r " + quoteName(file.toFilesystemEncoding()),
107                          FileName());
108 }
109
110
111 void RCS::scanMaster()
112 {
113         if (master_.empty())
114                 return;
115
116         LYXERR(Debug::LYXVC, "LyXVC::RCS: scanMaster: " << master_);
117
118         ifstream ifs(master_.toFilesystemEncoding().c_str());
119
120         string token;
121         bool read_enough = false;
122
123         while (!read_enough && ifs >> token) {
124                 LYXERR(Debug::LYXVC, "LyXVC::scanMaster: current lex text: `"
125                         << token << '\'');
126
127                 if (token.empty())
128                         continue;
129                 else if (token == "head") {
130                         // get version here
131                         string tmv;
132                         ifs >> tmv;
133                         tmv = rtrim(tmv, ";");
134                         version_ = tmv;
135                         LYXERR(Debug::LYXVC, "LyXVC: version found to be " << tmv);
136                 } else if (contains(token, "access")
137                            || contains(token, "symbols")
138                            || contains(token, "strict")) {
139                         // nothing
140                 } else if (contains(token, "locks")) {
141                         // get locker here
142                         if (contains(token, ';')) {
143                                 locker_ = "Unlocked";
144                                 vcstatus = UNLOCKED;
145                                 continue;
146                         }
147                         string tmpt;
148                         string s1;
149                         string s2;
150                         do {
151                                 ifs >> tmpt;
152                                 s1 = rtrim(tmpt, ";");
153                                 // tmp is now in the format <user>:<version>
154                                 s1 = split(s1, s2, ':');
155                                 // s2 is user, and s1 is version
156                                 if (s1 == version_) {
157                                         locker_ = s2;
158                                         vcstatus = LOCKED;
159                                         break;
160                                 }
161                         } while (!contains(tmpt, ';'));
162
163                 } else if (token == "comment") {
164                         // we don't need to read any further than this.
165                         read_enough = true;
166                 } else {
167                         // unexpected
168                         LYXERR(Debug::LYXVC, "LyXVC::scanMaster(): unexpected token");
169                 }
170         }
171 }
172
173
174 void RCS::registrer(string const & msg)
175 {
176         string cmd = "ci -q -u -i -t-\"";
177         cmd += msg;
178         cmd += "\" ";
179         cmd += quoteName(onlyFileName(owner_->absFileName()));
180         doVCCommand(cmd, FileName(owner_->filePath()));
181 }
182
183
184 string RCS::checkIn(string const & msg)
185 {
186         int ret = doVCCommand("ci -q -u -m\"" + msg + "\" "
187                     + quoteName(onlyFileName(owner_->absFileName())),
188                     FileName(owner_->filePath()));
189         return ret ? string() : "RCS: Proceeded";
190 }
191
192
193 bool RCS::checkInEnabled()
194 {
195         return owner_ && !owner_->isReadonly();
196 }
197
198 bool RCS::isCheckInWithConfirmation()
199 {
200         //FIXME diff
201         return true;
202 }
203
204
205 string RCS::checkOut()
206 {
207         owner_->markClean();
208         int ret = doVCCommand("co -q -l " + quoteName(onlyFileName(owner_->absFileName())),
209                     FileName(owner_->filePath()));
210         return ret ? string() : "RCS: Proceeded";
211 }
212
213
214 bool RCS::checkOutEnabled()
215 {
216         return owner_ && owner_->isReadonly();
217 }
218
219
220 string RCS::repoUpdate()
221 {
222         lyxerr << "Sorry, not implemented." << endl;
223         return string();
224 }
225
226
227 bool RCS::repoUpdateEnabled()
228 {
229         return false;
230 }
231
232
233 string RCS::lockingToggle()
234 {
235         lyxerr << "Sorry, not implemented." << endl;
236         return string();
237 }
238
239
240 bool RCS::lockingToggleEnabled()
241 {
242         return false;
243 }
244
245
246 void RCS::revert()
247 {
248         doVCCommand("co -f -u" + version_ + " "
249                     + quoteName(onlyFileName(owner_->absFileName())),
250                     FileName(owner_->filePath()));
251         // We ignore changes and just reload!
252         owner_->markClean();
253 }
254
255
256 bool RCS::isRevertWithConfirmation()
257 {
258         //FIXME owner && diff ?
259         return true;
260 }
261
262
263 void RCS::undoLast()
264 {
265         LYXERR(Debug::LYXVC, "LyXVC: undoLast");
266         doVCCommand("rcs -o" + version_ + " "
267                     + quoteName(onlyFileName(owner_->absFileName())),
268                     FileName(owner_->filePath()));
269 }
270
271
272 bool RCS::undoLastEnabled()
273 {
274         return true;
275 }
276
277
278 void RCS::getLog(FileName const & tmpf)
279 {
280         doVCCommand("rlog " + quoteName(onlyFileName(owner_->absFileName()))
281                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
282                     FileName(owner_->filePath()));
283 }
284
285
286 bool RCS::toggleReadOnlyEnabled()
287 {
288         // This got broken somewhere along lfuns dispatch reorganization.
289         // reloadBuffer would be needed after this, but thats problematic
290         // since we are inside Buffer::dispatch.
291         // return true;
292         return false;
293 }
294
295 string RCS::revisionInfo(LyXVC::RevisionInfo const info)
296 {
297         if (info == LyXVC::File)
298                 return version_;
299         return string();
300 }
301
302
303 bool RCS::prepareFileRevision(string const &revis, string & f)
304 {
305         string rev = revis;
306
307         if (isStrInt(rev)) {
308                 int back = convert<int>(rev);
309                 // if positive use as the last number in the whole revision string
310                 if (back > 0) {
311                         string base;
312                         rsplit(version_, base , '.' );
313                         rev = base + "." + rev;
314                 }
315                 if (back == 0)
316                         rev = version_;
317                 // we care about the last number from revision string
318                 // in case of backward indexing
319                 if (back < 0) {
320                         string cur, base;
321                         cur = rsplit(version_, base , '.' );
322                         if (!isStrInt(cur))
323                                 return false;
324                         int want = convert<int>(cur) + back;
325                         if (want <= 0)
326                                 return false;
327
328                         rev = base + "." + convert<string>(want);
329                 }
330         }
331
332         FileName tmpf = FileName::tempName("lyxvcrev_" + rev + "_");
333         if (tmpf.empty()) {
334                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
335                 return N_("Error: Could not generate logfile.");
336         }
337
338         doVCCommand("co -p" + rev + " "
339                       + quoteName(onlyFileName(owner_->absFileName()))
340                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
341                 FileName(owner_->filePath()));
342         if (tmpf.isFileEmpty())
343                 return false;
344
345         f = tmpf.absFileName();
346         return true;
347 }
348
349
350 bool RCS::prepareFileRevisionEnabled()
351 {
352         return true;
353 }
354
355
356 /////////////////////////////////////////////////////////////////////
357 //
358 // CVS
359 //
360 /////////////////////////////////////////////////////////////////////
361
362 CVS::CVS(FileName const & m, FileName const & f)
363 {
364         master_ = m;
365         file_ = f;
366         scanMaster();
367 }
368
369
370 FileName const CVS::findFile(FileName const & file)
371 {
372         // First we look for the CVS/Entries in the same dir
373         // where we have file.
374         FileName const entries(onlyPath(file.absFileName()) + "/CVS/Entries");
375         string const tmpf = '/' + onlyFileName(file.absFileName()) + '/';
376         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under cvs in `" << entries
377                              << "' for `" << tmpf << '\'');
378         if (entries.isReadableFile()) {
379                 // Ok we are at least in a CVS dir. Parse the CVS/Entries
380                 // and see if we can find this file. We do a fast and
381                 // dirty parse here.
382                 ifstream ifs(entries.toFilesystemEncoding().c_str());
383                 string line;
384                 while (getline(ifs, line)) {
385                         LYXERR(Debug::LYXVC, "\tEntries: " << line);
386                         if (contains(line, tmpf))
387                                 return entries;
388                 }
389         }
390         return FileName();
391 }
392
393
394 void CVS::scanMaster()
395 {
396         LYXERR(Debug::LYXVC, "LyXVC::CVS: scanMaster. \n     Checking: " << master_);
397         // Ok now we do the real scan...
398         ifstream ifs(master_.toFilesystemEncoding().c_str());
399         string name = onlyFileName(file_.absFileName());
400         string tmpf = '/' + name + '/';
401         LYXERR(Debug::LYXVC, "\tlooking for `" << tmpf << '\'');
402         string line;
403         static regex const reg("/(.*)/(.*)/(.*)/(.*)/(.*)");
404         while (getline(ifs, line)) {
405                 LYXERR(Debug::LYXVC, "\t  line: " << line);
406                 if (contains(line, tmpf)) {
407                         // Ok extract the fields.
408                         smatch sm;
409
410                         regex_match(line, sm, reg);
411
412                         //sm[0]; // whole matched string
413                         //sm[1]; // filename
414                         version_ = sm.str(2);
415                         string const file_date = sm.str(3);
416
417                         //sm[4]; // options
418                         //sm[5]; // tag or tagdate
419                         if (file_.isReadableFile()) {
420                                 time_t mod = file_.lastModified();
421                                 string mod_date = rtrim(asctime(gmtime(&mod)), "\n");
422                                 LYXERR(Debug::LYXVC, "Date in Entries: `" << file_date
423                                         << "'\nModification date of file: `" << mod_date << '\'');
424                                 if (file_.isReadOnly()) {
425                                         // readonly checkout is unlocked
426                                         vcstatus = UNLOCKED;
427                                 } else {
428                                         FileName bdir(addPath(master_.onlyPath().absFileName(),"Base"));
429                                         FileName base(addName(bdir.absFileName(),name));
430                                         // if base version is existent "cvs edit" was used to lock
431                                         vcstatus = base.isReadableFile() ? LOCKED : NOLOCKING;
432                                 }
433                         } else {
434                                 vcstatus = NOLOCKING;
435                         }
436                         break;
437                 }
438         }
439 }
440
441
442 string const CVS::getTarget(OperationMode opmode) const
443 {
444         switch(opmode) {
445         case Directory:
446                 // in client server mode CVS does not like full path operand for directory operation
447                 // since LyX switches to the repo dir "." is good enough as target
448                 return ".";
449         case File:
450                 return quoteName(onlyFileName(owner_->absFileName()));
451         }
452         return string();
453 }
454
455
456 docstring CVS::toString(CvsStatus status) const
457 {
458         switch (status) {
459         case UpToDate:
460                 return _("Up-to-date");
461         case LocallyModified:
462                 return _("Locally Modified");
463         case LocallyAdded:
464                 return _("Locally Added");
465         case NeedsMerge:
466                 return _("Needs Merge");
467         case NeedsCheckout:
468                 return _("Needs Checkout");
469         case NoCvsFile:
470                 return _("No CVS file");
471         case StatusError:
472                 return _("Cannot retrieve CVS status");
473         }
474         return 0;
475 }
476
477
478 CVS::CvsStatus CVS::getStatus()
479 {
480         FileName tmpf = FileName::tempName("lyxvcout");
481         if (tmpf.empty()) {
482                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
483                 return StatusError;
484         }
485
486         if (doVCCommand("cvs status " + getTarget(File)
487                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
488                 FileName(owner_->filePath()))) {
489                 tmpf.removeFile();
490                 return StatusError;
491         }
492
493         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
494         CvsStatus status = NoCvsFile;
495
496         while (ifs) {
497                 string line;
498                 getline(ifs, line);
499                 LYXERR(Debug::LYXVC, line << "\n");
500                 if (prefixIs(line, "File:")) {
501                         if (contains(line, "Up-to-date"))
502                                 status = UpToDate;
503                         else if (contains(line, "Locally Modified"))
504                                 status = LocallyModified;
505                         else if (contains(line, "Locally Added"))
506                                 status = LocallyAdded;
507                         else if (contains(line, "Needs Merge"))
508                                 status = NeedsMerge;
509                         else if (contains(line, "Needs Checkout"))
510                                 status = NeedsCheckout;
511                 }
512         }
513         tmpf.removeFile();
514         return status;
515 }
516
517
518 void CVS::registrer(string const & msg)
519 {
520         doVCCommand("cvs -q add -m \"" + msg + "\" "
521                 + getTarget(File),
522                 FileName(owner_->filePath()));
523 }
524
525
526 void CVS::getDiff(OperationMode opmode, FileName const & tmpf)
527 {
528         doVCCommand("cvs diff " + getTarget(opmode)
529                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
530                 FileName(owner_->filePath()), false);
531 }
532
533
534 int CVS::edit()
535 {
536         vcstatus = LOCKED;
537         return doVCCommand("cvs -q edit " + getTarget(File),
538                 FileName(owner_->filePath()));
539 }
540
541
542 int CVS::unedit()
543 {
544         vcstatus = UNLOCKED;
545         return doVCCommand("cvs -q unedit " + getTarget(File),
546                 FileName(owner_->filePath()));
547 }
548
549
550 int CVS::update(OperationMode opmode, FileName const & tmpf)
551 {
552         string const redirection = tmpf.empty() ? ""
553                 : " > " + quoteName(tmpf.toFilesystemEncoding());
554
555         return doVCCommand("cvs -q update "
556                 + getTarget(opmode) + redirection,
557                 FileName(owner_->filePath()));
558 }
559
560
561 string CVS::scanLogFile(FileName const & f, string & status)
562 {
563         ifstream ifs(f.toFilesystemEncoding().c_str());
564
565         while (ifs) {
566                 string line;
567                 getline(ifs, line);
568                 LYXERR(Debug::LYXVC, line << "\n");
569                 if (!line.empty())
570                         status += line + "; ";
571                 if (prefixIs(line, "C ")) {
572                         ifs.close();
573                         return line;
574                 }
575         }
576         ifs.close();
577         return string();
578 }
579         
580         
581 string CVS::checkIn(string const & msg)
582 {
583         CvsStatus status = getStatus();
584         switch (status) {
585         case UpToDate:
586                 if (vcstatus != NOLOCKING)
587                         unedit();
588                 return "CVS: Proceeded";
589         case LocallyModified:
590         case LocallyAdded: {
591                 int rc = doVCCommand("cvs -q commit -m \"" + msg + "\" "
592                         + getTarget(File),
593                     FileName(owner_->filePath()));
594                 return rc ? string() : "CVS: Proceeded";
595         }
596         case NeedsMerge:
597         case NeedsCheckout:
598                 frontend::Alert::error(_("Revision control error."),
599                         _("The repository version is newer then the current check out.\n"
600                           "You have to update from repository first or revert your changes.")) ;
601                 break;
602         default:
603                 frontend::Alert::error(_("Revision control error."),
604                         bformat(_("Bad status when checking in changes.\n"
605                                           "\n'%1$s'\n\n"),
606                                 toString(status)));
607                 break;
608         }
609         return string();
610 }
611
612
613 bool CVS::isLocked() const
614 {
615         FileName fn(owner_->absFileName());
616         fn.refresh();
617         return !fn.isReadOnly();
618 }
619
620
621 bool CVS::checkInEnabled()
622 {
623         if (vcstatus != NOLOCKING)
624                 return isLocked();
625         else
626                 return true;
627 }
628
629
630 bool CVS::isCheckInWithConfirmation()
631 {
632         CvsStatus status = getStatus();
633         return status == LocallyModified || status == LocallyAdded;
634 }
635
636
637 string CVS::checkOut()
638 {
639         if (vcstatus != NOLOCKING && edit())
640                 return string();
641         FileName tmpf = FileName::tempName("lyxvcout");
642         if (tmpf.empty()) {
643                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
644                 return string();
645         }
646         
647         int rc = update(File, tmpf);
648         string log;
649         string const res = scanLogFile(tmpf, log);
650         if (!res.empty())
651                 frontend::Alert::error(_("Revision control error."),
652                         bformat(_("Error when updating from repository.\n"
653                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
654                                 "After pressing OK, LyX will try to reopen the resolved document."),
655                                 from_local8bit(res)));
656         
657         tmpf.erase();
658         return rc ? string() : log.empty() ? "CVS: Proceeded" : "CVS: " + log;
659 }
660
661
662 bool CVS::checkOutEnabled()
663 {
664         if (vcstatus != NOLOCKING)
665                 return !isLocked();
666         else
667                 return true;
668 }
669
670
671 string CVS::repoUpdate()
672 {
673         FileName tmpf = FileName::tempName("lyxvcout");
674         if (tmpf.empty()) {
675                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
676                 return string();
677         }
678         
679         getDiff(Directory, tmpf);
680         docstring res = tmpf.fileContents("UTF-8");
681         if (!res.empty()) {
682                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
683                 docstring const file = from_utf8(owner_->filePath());
684                 docstring text = bformat(_("There were detected changes "
685                                 "in the working directory:\n%1$s\n\n"
686                                 "In case of file conflict you have to resolve them "
687                                 "manually or revert to repository version later."), file);
688                 int ret = frontend::Alert::prompt(_("Changes detected"),
689                                 text, 0, 1, _("&Continue"), _("&Abort"), _("View &Log ..."));
690                 if (ret == 2 ) {
691                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
692                         ret = frontend::Alert::prompt(_("Changes detected"),
693                                 text, 0, 1, _("&Continue"), _("&Abort"));
694                         hideDialogs("file", 0);
695                 }
696                 if (ret == 1 ) {
697                         tmpf.removeFile();
698                         return string();
699                 }
700         }
701
702         int rc = update(Directory, tmpf);
703         res += "Update log:\n" + tmpf.fileContents("UTF-8");
704         tmpf.removeFile();
705
706         LYXERR(Debug::LYXVC, res);
707         return rc ? string() : "CVS: Proceeded" ;
708 }
709
710
711 bool CVS::repoUpdateEnabled()
712 {
713         return true;
714 }
715
716
717 string CVS::lockingToggle()
718 {
719         lyxerr << "Sorry, not implemented." << endl;
720         return string();
721 }
722
723
724 bool CVS::lockingToggleEnabled()
725 {
726         return false;
727 }
728
729
730 bool CVS::isRevertWithConfirmation()
731 {
732         CvsStatus status = getStatus();
733         return !owner_->isClean() || status == LocallyModified || status == NeedsMerge;
734 }
735
736
737 void CVS::revert()
738 {
739         // Reverts to the version in CVS repository and
740         // gets the updated version from the repository.
741         CvsStatus status = getStatus();
742         switch (status) {
743         case UpToDate:
744                 if (vcstatus != NOLOCKING)
745                         unedit();
746                 break;
747         case NeedsMerge:
748         case NeedsCheckout:
749         case LocallyModified: {
750                 FileName f(owner_->absFileName());
751                 f.removeFile();
752                 update(File, FileName());
753                 owner_->markClean();
754                 break;
755         }
756         case LocallyAdded: {
757                 docstring const file = owner_->fileName().displayName(20);
758                 frontend::Alert::error(_("Revision control error."),
759                         bformat(_("The document %1$s is not in repository.\n"
760                                   "You have to check in the first revision before you can revert."),
761                                 file)) ;
762                 break;
763         }
764         default: {
765                 docstring const file = owner_->fileName().displayName(20);
766                 frontend::Alert::error(_("Revision control error."),
767                         bformat(_("Cannot revert document %1$s to repository version.\n"
768                                   "The status '%2$s' is unexpected."),
769                                 file, toString(status)));
770                 break;
771                 }
772         }
773 }
774
775
776 void CVS::undoLast()
777 {
778         // merge the current with the previous version
779         // in a reverse patch kind of way, so that the
780         // result is to revert the last changes.
781         lyxerr << "Sorry, not implemented." << endl;
782 }
783
784
785 bool CVS::undoLastEnabled()
786 {
787         return false;
788 }
789
790
791 void CVS::getLog(FileName const & tmpf)
792 {
793         doVCCommand("cvs log " + getTarget(File)
794                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
795                     FileName(owner_->filePath()));
796 }
797
798
799 bool CVS::toggleReadOnlyEnabled()
800 {
801         return false;
802 }
803
804
805 string CVS::revisionInfo(LyXVC::RevisionInfo const info)
806 {
807         if (info == LyXVC::File)
808                 return version_;
809         return string();
810 }
811
812
813 bool CVS::prepareFileRevision(string const &, string &)
814 {
815         return false;
816 }
817
818
819 bool CVS::prepareFileRevisionEnabled()
820 {
821         return false;
822 }
823
824
825 /////////////////////////////////////////////////////////////////////
826 //
827 // SVN
828 //
829 /////////////////////////////////////////////////////////////////////
830
831 SVN::SVN(FileName const & m, FileName const & f)
832 {
833         owner_ = 0;
834         master_ = m;
835         file_ = f;
836         locked_mode_ = 0;
837         scanMaster();
838 }
839
840
841 FileName const SVN::findFile(FileName const & file)
842 {
843         // First we look for the .svn/entries in the same dir
844         // where we have file.
845         FileName const entries(onlyPath(file.absFileName()) + "/.svn/entries");
846         string const tmpf = onlyFileName(file.absFileName());
847         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under svn in `" << entries
848                              << "' for `" << tmpf << '\'');
849         if (entries.isReadableFile()) {
850                 // Ok we are at least in a SVN dir. Parse the .svn/entries
851                 // and see if we can find this file. We do a fast and
852                 // dirty parse here.
853                 ifstream ifs(entries.toFilesystemEncoding().c_str());
854                 string line, oldline;
855                 while (getline(ifs, line)) {
856                         if (line == "dir" || line == "file")
857                                 LYXERR(Debug::LYXVC, "\tEntries: " << oldline);
858                         if (oldline == tmpf && line == "file")
859                                 return entries;
860                         oldline = line;
861                 }
862         }
863         return FileName();
864 }
865
866
867 void SVN::scanMaster()
868 {
869         // vcstatus code is somewhat superflous, until we want
870         // to implement read-only toggle for svn.
871         vcstatus = NOLOCKING;
872         if (checkLockMode()) {
873                 if (isLocked()) {
874                         vcstatus = LOCKED;
875                 } else {
876                         vcstatus = UNLOCKED;
877                 }
878         }
879 }
880
881
882 bool SVN::checkLockMode()
883 {
884         FileName tmpf = FileName::tempName("lyxvcout");
885         if (tmpf.empty()){
886                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
887                 return N_("Error: Could not generate logfile.");
888         }
889
890         LYXERR(Debug::LYXVC, "Detecting locking mode...");
891         if (doVCCommandCall("svn proplist " + quoteName(file_.onlyFileName())
892                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
893                     file_.onlyPath()))
894                 return false;
895
896         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
897         string line;
898         bool ret = false;
899
900         while (ifs) {
901                 getline(ifs, line);
902                 LYXERR(Debug::LYXVC, line);
903                 if (contains(line, "svn:needs-lock"))
904                         ret = true;
905         }
906         LYXERR(Debug::LYXVC, "Locking enabled: " << ret);
907         ifs.close();
908         locked_mode_ = ret;
909         return ret;
910
911 }
912
913
914 bool SVN::isLocked() const
915 {
916         file_.refresh();
917         return !file_.isReadOnly();
918 }
919
920
921 void SVN::registrer(string const & /*msg*/)
922 {
923         doVCCommand("svn add -q " + quoteName(onlyFileName(owner_->absFileName())),
924                     FileName(owner_->filePath()));
925 }
926
927
928 string SVN::checkIn(string const & msg)
929 {
930         FileName tmpf = FileName::tempName("lyxvcout");
931         if (tmpf.empty()){
932                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
933                 return N_("Error: Could not generate logfile.");
934         }
935
936         doVCCommand("svn commit -m \"" + msg + "\" "
937                     + quoteName(onlyFileName(owner_->absFileName()))
938                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
939                     FileName(owner_->filePath()));
940
941         string log;
942         string res = scanLogFile(tmpf, log);
943         if (!res.empty())
944                 frontend::Alert::error(_("Revision control error."),
945                                 _("Error when committing to repository.\n"
946                                 "You have to manually resolve the problem.\n"
947                                 "LyX will reopen the document after you press OK."));
948         else
949                 fileLock(false, tmpf, log);
950
951         tmpf.erase();
952         return log.empty() ? string() : "SVN: " + log;
953 }
954
955
956 bool SVN::checkInEnabled()
957 {
958         if (locked_mode_)
959                 return isLocked();
960         else
961                 return true;
962 }
963
964
965 bool SVN::isCheckInWithConfirmation()
966 {
967         //FIXME diff
968         return true;
969 }
970
971
972 // FIXME Correctly return code should be checked instead of this.
973 // This would need another solution than just plain startscript.
974 // Hint from Andre': QProcess::readAllStandardError()...
975 string SVN::scanLogFile(FileName const & f, string & status)
976 {
977         ifstream ifs(f.toFilesystemEncoding().c_str());
978         string line;
979
980         while (ifs) {
981                 getline(ifs, line);
982                 LYXERR(Debug::LYXVC, line << "\n");
983                 if (!line.empty()) 
984                         status += line + "; ";
985                 if (prefixIs(line, "C ") || prefixIs(line, "CU ")
986                                          || contains(line, "Commit failed")) {
987                         ifs.close();
988                         return line;
989                 }
990                 if (contains(line, "svn:needs-lock")) {
991                         ifs.close();
992                         return line;
993                 }
994         }
995         ifs.close();
996         return string();
997 }
998
999
1000 void SVN::fileLock(bool lock, FileName const & tmpf, string &status)
1001 {
1002         if (!locked_mode_ || (isLocked() == lock))
1003                 return;
1004
1005         string const arg = lock ? "lock " : "unlock ";
1006         doVCCommand("svn "+ arg + quoteName(onlyFileName(owner_->absFileName()))
1007                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1008                     FileName(owner_->filePath()));
1009
1010         // Lock error messages go unfortunately on stderr and are unreachible this way.
1011         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1012         string line;
1013         while (ifs) {
1014                 getline(ifs, line);
1015                 if (!line.empty()) status += line + "; ";
1016         }
1017         ifs.close();
1018
1019         if (!isLocked() && lock)
1020                 frontend::Alert::error(_("Revision control error."),
1021                         _("Error while acquiring write lock.\n"
1022                         "Another user is most probably editing\n"
1023                         "the current document now!\n"
1024                         "Also check the access to the repository."));
1025         if (isLocked() && !lock)
1026                 frontend::Alert::error(_("Revision control error."),
1027                         _("Error while releasing write lock.\n"
1028                         "Check the access to the repository."));
1029 }
1030
1031
1032 string SVN::checkOut()
1033 {
1034         FileName tmpf = FileName::tempName("lyxvcout");
1035         if (tmpf.empty()) {
1036                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1037                 return N_("Error: Could not generate logfile.");
1038         }
1039
1040         doVCCommand("svn update --non-interactive " + quoteName(onlyFileName(owner_->absFileName()))
1041                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1042                     FileName(owner_->filePath()));
1043
1044         string log;
1045         string const res = scanLogFile(tmpf, log);
1046         if (!res.empty())
1047                 frontend::Alert::error(_("Revision control error."),
1048                         bformat(_("Error when updating from repository.\n"
1049                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
1050                                 "After pressing OK, LyX will try to reopen the resolved document."),
1051                         from_local8bit(res)));
1052
1053         fileLock(true, tmpf, log);
1054
1055         tmpf.erase();
1056         return log.empty() ? string() : "SVN: " + log;
1057 }
1058
1059
1060 bool SVN::checkOutEnabled()
1061 {
1062         if (locked_mode_)
1063                 return !isLocked();
1064         else
1065                 return true;
1066 }
1067
1068
1069 string SVN::repoUpdate()
1070 {
1071         FileName tmpf = FileName::tempName("lyxvcout");
1072         if (tmpf.empty()) {
1073                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1074                 return N_("Error: Could not generate logfile.");
1075         }
1076
1077         doVCCommand("svn diff " + quoteName(owner_->filePath())
1078                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1079                 FileName(owner_->filePath()));
1080         docstring res = tmpf.fileContents("UTF-8");
1081         if (!res.empty()) {
1082                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
1083                 docstring const file = from_utf8(owner_->filePath());
1084                 docstring text = bformat(_("There were detected changes "
1085                                 "in the working directory:\n%1$s\n\n"
1086                                 "In case of file conflict version of the local directory files "
1087                                 "will be preferred."
1088                                 "\n\nContinue?"), file);
1089                 int ret = frontend::Alert::prompt(_("Changes detected"),
1090                                 text, 0, 1, _("&Yes"), _("&No"), _("View &Log ..."));
1091                 if (ret == 2 ) {
1092                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
1093                         ret = frontend::Alert::prompt(_("Changes detected"),
1094                                 text, 0, 1, _("&Yes"), _("&No"));
1095                         hideDialogs("file", 0);
1096                 }
1097                 if (ret == 1 ) {
1098                         tmpf.erase();
1099                         return string();
1100                 }
1101         }
1102
1103         // Reverting looks too harsh, see bug #6255.
1104         // doVCCommand("svn revert -R " + quoteName(owner_->filePath())
1105         // + " > " + quoteName(tmpf.toFilesystemEncoding()),
1106         // FileName(owner_->filePath()));
1107         // res = "Revert log:\n" + tmpf.fileContents("UTF-8");
1108         doVCCommand("svn update --accept mine-full " + quoteName(owner_->filePath())
1109                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
1110                 FileName(owner_->filePath()));
1111         res += "Update log:\n" + tmpf.fileContents("UTF-8");
1112
1113         LYXERR(Debug::LYXVC, res);
1114         tmpf.erase();
1115         return to_utf8(res);
1116 }
1117
1118
1119 bool SVN::repoUpdateEnabled()
1120 {
1121         return true;
1122 }
1123
1124
1125 string SVN::lockingToggle()
1126 {
1127         FileName tmpf = FileName::tempName("lyxvcout");
1128         if (tmpf.empty()) {
1129                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1130                 return N_("Error: Could not generate logfile.");
1131         }
1132
1133         int ret = doVCCommand("svn proplist " + quoteName(onlyFileName(owner_->absFileName()))
1134                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1135                     FileName(owner_->filePath()));
1136         if (ret)
1137                 return string();
1138
1139         string log;
1140         string res = scanLogFile(tmpf, log);
1141         bool locking = contains(res, "svn:needs-lock");
1142         if (!locking)
1143                 ret = doVCCommand("svn propset svn:needs-lock ON "
1144                     + quoteName(onlyFileName(owner_->absFileName()))
1145                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1146                     FileName(owner_->filePath()));
1147         else
1148                 ret = doVCCommand("svn propdel svn:needs-lock "
1149                     + quoteName(onlyFileName(owner_->absFileName()))
1150                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1151                     FileName(owner_->filePath()));
1152         if (ret)
1153                 return string();
1154
1155         tmpf.erase();
1156         frontend::Alert::warning(_("VCN File Locking"),
1157                 (locking ? _("Locking property unset.") : _("Locking property set.")) + "\n"
1158                 + _("Do not forget to commit the locking property into the repository."),
1159                 true);
1160
1161         return string("SVN: ") +  N_("Locking property set.");
1162 }
1163
1164
1165 bool SVN::lockingToggleEnabled()
1166 {
1167         return true;
1168 }
1169
1170
1171 void SVN::revert()
1172 {
1173         // Reverts to the version in SVN repository and
1174         // gets the updated version from the repository.
1175         string const fil = quoteName(onlyFileName(owner_->absFileName()));
1176
1177         doVCCommand("svn revert -q " + fil,
1178                     FileName(owner_->filePath()));
1179         owner_->markClean();
1180 }
1181
1182
1183 bool SVN::isRevertWithConfirmation()
1184 {
1185         //FIXME owner && diff
1186         return true;
1187 }
1188
1189
1190 void SVN::undoLast()
1191 {
1192         // merge the current with the previous version
1193         // in a reverse patch kind of way, so that the
1194         // result is to revert the last changes.
1195         lyxerr << "Sorry, not implemented." << endl;
1196 }
1197
1198
1199 bool SVN::undoLastEnabled()
1200 {
1201         return false;
1202 }
1203
1204
1205 string SVN::revisionInfo(LyXVC::RevisionInfo const info)
1206 {
1207         if (info == LyXVC::Tree) {
1208                         if (rev_tree_cache_.empty())
1209                                 if (!getTreeRevisionInfo())
1210                                         rev_tree_cache_ = "?";
1211                         if (rev_tree_cache_ == "?")
1212                                 return string();
1213
1214                         return rev_tree_cache_;
1215         }
1216
1217         // fill the rest of the attributes for a single file
1218         if (rev_file_cache_.empty())
1219                 if (!getFileRevisionInfo())
1220                         rev_file_cache_ = "?";
1221
1222         switch (info) {
1223                 case LyXVC::File:
1224                         if (rev_file_cache_ == "?")
1225                                 return string();
1226                         return rev_file_cache_;
1227                 case LyXVC::Author:
1228                         return rev_author_cache_;
1229                 case LyXVC::Date:
1230                         return rev_date_cache_;
1231                 case LyXVC::Time:
1232                         return rev_time_cache_;
1233                 default: ;
1234
1235         }
1236
1237         return string();
1238 }
1239
1240
1241 bool SVN::getFileRevisionInfo()
1242 {
1243         FileName tmpf = FileName::tempName("lyxvcout");
1244         if (tmpf.empty()) {
1245                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1246                 return N_("Error: Could not generate logfile.");
1247         }
1248
1249         doVCCommand("svn info --xml " + quoteName(onlyFileName(owner_->absFileName()))
1250                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1251                     FileName(owner_->filePath()));
1252
1253         if (tmpf.empty())
1254                 return false;
1255
1256         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1257         string line;
1258         // commit log part
1259         bool c = false;
1260         string rev;
1261
1262         while (ifs) {
1263                 getline(ifs, line);
1264                 LYXERR(Debug::LYXVC, line);
1265                 if (prefixIs(line, "<commit"))
1266                         c = true;
1267                 if (c && prefixIs(line, "   revision=\"") && suffixIs(line, "\">")) {
1268                         string l1 = subst(line, "revision=\"", "");
1269                         string l2 = trim(subst(l1, "\">", ""));
1270                         if (isStrInt(l2))
1271                                 rev_file_cache_ = rev = l2;
1272                 }
1273                 if (c && prefixIs(line, "<author>") && suffixIs(line, "</author>")) {
1274                         string l1 = subst(line, "<author>", "");
1275                         string l2 = subst(l1, "</author>", "");
1276                         rev_author_cache_ = l2;
1277                 }
1278                 if (c && prefixIs(line, "<date>") && suffixIs(line, "</date>")) {
1279                         string l1 = subst(line, "<date>", "");
1280                         string l2 = subst(l1, "</date>", "");
1281                         l2 = split(l2, l1, 'T');
1282                         rev_date_cache_ = l1;
1283                         l2 = split(l2, l1, '.');
1284                         rev_time_cache_ = l1;
1285                 }
1286         }
1287
1288         ifs.close();
1289         tmpf.erase();
1290         return !rev.empty();
1291 }
1292
1293
1294 bool SVN::getTreeRevisionInfo()
1295 {
1296         FileName tmpf = FileName::tempName("lyxvcout");
1297         if (tmpf.empty()) {
1298                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1299                 return N_("Error: Could not generate logfile.");
1300         }
1301
1302         doVCCommand("svnversion -n . > " + quoteName(tmpf.toFilesystemEncoding()),
1303                     FileName(owner_->filePath()));
1304
1305         if (tmpf.empty())
1306                 return false;
1307
1308         // only first line in case something bad happens.
1309         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1310         string line;
1311         getline(ifs, line);
1312         ifs.close();
1313         tmpf.erase();
1314
1315         rev_tree_cache_ = line;
1316         return !line.empty();
1317 }
1318
1319
1320 void SVN::getLog(FileName const & tmpf)
1321 {
1322         doVCCommand("svn log " + quoteName(onlyFileName(owner_->absFileName()))
1323                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1324                     FileName(owner_->filePath()));
1325 }
1326
1327
1328 bool SVN::prepareFileRevision(string const & revis, string & f)
1329 {
1330         if (!isStrInt(revis))
1331                 return false;
1332
1333         int rev = convert<int>(revis);
1334         if (rev <= 0)
1335                 if (!getFileRevisionInfo())
1336                         return false;
1337         if (rev == 0)
1338                 rev = convert<int>(rev_file_cache_);
1339         // go back for minus rev
1340         else if (rev < 0) {
1341                 rev = rev + convert<int>(rev_file_cache_);
1342                 if (rev < 1)
1343                         return false;
1344         }
1345
1346         string revname = convert<string>(rev);
1347         FileName tmpf = FileName::tempName("lyxvcrev_" + revname + "_");
1348         if (tmpf.empty()) {
1349                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1350                 return N_("Error: Could not generate logfile.");
1351         }
1352
1353         doVCCommand("svn cat -r " + revname + " "
1354                       + quoteName(onlyFileName(owner_->absFileName()))
1355                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
1356                 FileName(owner_->filePath()));
1357         if (tmpf.isFileEmpty())
1358                 return false;
1359
1360         f = tmpf.absFileName();
1361         return true;
1362 }
1363
1364
1365 bool SVN::prepareFileRevisionEnabled()
1366 {
1367         return true;
1368 }
1369
1370
1371
1372 bool SVN::toggleReadOnlyEnabled()
1373 {
1374         return false;
1375 }
1376
1377
1378 } // namespace lyx