1/*
2 * Copyright (c) 1998-2007 Matthijs Hollemans
3 * All rights reserved. Distributed under the terms of the MIT License.
4 */
5
6#include "GrepApp.h"
7
8#include <stdio.h>
9
10#include <Entry.h>
11
12#include "GlobalDefs.h"
13#include "GrepWindow.h"
14#include "Model.h"
15
16
17GrepApp::GrepApp()
18	: BApplication(APP_SIGNATURE),
19	  fGotArgvOnStartup(false),
20	  fGotRefsOnStartup(false),
21	  fQuitter(NULL)
22{
23}
24
25
26GrepApp::~GrepApp()
27{
28	delete fQuitter;
29}
30
31
32void
33GrepApp::ArgvReceived(int32 argc, char** argv)
34{
35	fGotArgvOnStartup = true;
36
37	BMessage message(B_REFS_RECEIVED);
38	int32 refCount = 0;
39
40	for (int32 i = 1; i < argc; i++) {
41		BEntry entry(argv[i]);
42		entry_ref ref;
43		entry.GetRef(&ref);
44
45		if (entry.Exists()) {
46			message.AddRef("refs", &ref);
47			refCount += 1;
48		} else
49			printf("%s: File not found: %s\n", argv[0], argv[i]);
50	}
51
52	if (refCount > 0)
53		RefsReceived(&message);
54}
55
56
57void
58GrepApp::RefsReceived(BMessage* message)
59{
60	if (IsLaunching())
61		fGotRefsOnStartup = true;
62
63	new GrepWindow(message);
64}
65
66
67void
68GrepApp::ReadyToRun()
69{
70	if (!fGotArgvOnStartup && !fGotRefsOnStartup)
71		_NewUnfocusedGrepWindow();
72
73	// TODO: stippi: I don't understand what this is supposed to do:
74	if (fGotArgvOnStartup && !fGotRefsOnStartup)
75		PostMessage(B_QUIT_REQUESTED);
76}
77
78
79void
80GrepApp::MessageReceived(BMessage* message)
81{
82	switch (message->what) {
83		case B_SILENT_RELAUNCH:
84			_NewUnfocusedGrepWindow();
85			break;
86
87		case MSG_TRY_QUIT:
88			_TryQuit();
89			break;
90
91		default:
92			BApplication::MessageReceived(message);
93			break;
94	}
95}
96
97
98void
99GrepApp::_TryQuit()
100{
101	if (CountWindows() == 0)
102		PostMessage(B_QUIT_REQUESTED);
103
104	if (CountWindows() == 1 && fQuitter == NULL) {
105		fQuitter = new BMessageRunner(be_app_messenger,
106			new BMessage(MSG_TRY_QUIT), 200000, -1);
107	}
108}
109
110
111void
112GrepApp::_NewUnfocusedGrepWindow()
113{
114	BMessage emptyMessage;
115	new GrepWindow(&emptyMessage);
116}
117