xref: /haiku/src/apps/screenshot/Screenshot.cpp (revision a5bf12376daeded4049521eb17a6cc41192250d9)
1 /*
2  * Copyright 2010 Wim van der Meer <WPJvanderMeer@gmail.com>
3  * Copyright Karsten Heimrich, host.haiku@gmx.de. All rights reserved.
4  * Distributed under the terms of the MIT License.
5  *
6  * Authors:
7  *		Karsten Heimrich
8  *		Fredrik Modéen
9  *		Christophe Huriaux
10  *		Wim van der Meer
11  */
12 
13 
14 #include "Screenshot.h"
15 
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 
20 #include <AppDefs.h>
21 #include <Bitmap.h>
22 #include <Locale.h>
23 #include <Roster.h>
24 #include <Screen.h>
25 #include <TranslatorFormats.h>
26 
27 #include <WindowInfo.h>
28 
29 #include "Utility.h"
30 
31 
32 Screenshot::Screenshot()
33 	:
34 	BApplication("application/x-vnd.haiku-screenshot-cli"),
35 	fUtility(new Utility()),
36 	fLaunchGui(true)
37 {
38 	be_locale->GetAppCatalog(&fCatalog);
39 }
40 
41 
42 Screenshot::~Screenshot()
43 {
44 	delete fUtility;
45 }
46 
47 
48 void
49 Screenshot::ArgvReceived(int32 argc, char** argv)
50 {
51 	bigtime_t delay = 0;
52 	const char* outputFilename = NULL;
53 	bool includeBorder = false;
54 	bool includeCursor = false;
55 	bool grabActiveWindow = false;
56 	bool saveScreenshotSilent = false;
57 	bool copyToClipboard = false;
58 	uint32 imageFileType = B_PNG_FORMAT;
59 
60 	for (int32 i = 0; i < argc; i++) {
61 		if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
62 			_ShowHelp();
63 		else if (strcmp(argv[i], "-b") == 0
64 			|| strcmp(argv[i], "--border") == 0)
65 			includeBorder = true;
66 		else if (strcmp(argv[i], "-m") == 0
67 			|| strcmp(argv[i], "--mouse-pointer") == 0)
68 			includeCursor = true;
69 		else if (strcmp(argv[i], "-w") == 0
70 			|| strcmp(argv[i], "--window") == 0)
71 			grabActiveWindow = true;
72 		else if (strcmp(argv[i], "-s") == 0
73 			|| strcmp(argv[i], "--silent") == 0)
74 			saveScreenshotSilent = true;
75 		else if (strcmp(argv[i], "-f") == 0
76 			|| strncmp(argv[i], "--format", 6) == 0
77 			|| strncmp(argv[i], "--format=", 7) == 0)
78 			imageFileType = _GetImageType(argv[i + 1]);
79 		else if (strcmp(argv[i], "-d") == 0
80 			|| strncmp(argv[i], "--delay", 7) == 0
81 			|| strncmp(argv[i], "--delay=", 8) == 0) {
82 			int32 seconds = -1;
83 			if (argc > i + 1)
84 				seconds = atoi(argv[i + 1]);
85 			if (seconds >= 0) {
86 				delay = seconds * 1000000;
87 				i++;
88 			} else {
89 				printf("Screenshot: option requires an argument -- %s\n",
90 					argv[i]);
91 				fLaunchGui = false;
92 				return;
93 			}
94 		} else if (strcmp(argv[i], "-c") == 0
95 			|| strcmp(argv[i], "--clipboard") == 0)
96 			copyToClipboard = true;
97 		else if (i == argc - 1)
98 			outputFilename = argv[i];
99 	}
100 
101 	if (argc > 1)
102 		_New(delay);
103 
104 	if (copyToClipboard || saveScreenshotSilent) {
105 		fLaunchGui = false;
106 
107 		BBitmap* screenshot = fUtility->MakeScreenshot(includeCursor,
108 			grabActiveWindow, includeBorder);
109 
110 		if (screenshot == NULL)
111 			return;
112 
113 		if (copyToClipboard)
114 			fUtility->CopyToClipboard(*screenshot);
115 
116 		if (saveScreenshotSilent)
117 			fUtility->Save(&screenshot, outputFilename, imageFileType);
118 
119 		delete screenshot;
120 	}
121 }
122 
123 
124 void
125 Screenshot::ReadyToRun()
126 {
127 	if (fLaunchGui) {
128 		// Launch the GUI application
129 		if (fUtility->wholeScreen == NULL) {
130 			// No command line parameters were given
131 			be_roster->Launch("application/x-vnd.haiku-screenshot");
132 		} else {
133 			// Send the utility data and the command line settings to the GUI
134 			BMessage message;
135 			message.what = SS_UTILITY_DATA;
136 
137 			BMessage* bitmap = new BMessage();
138 			fUtility->wholeScreen->Archive(bitmap);
139 			message.AddMessage("wholeScreen", bitmap);
140 
141 			bitmap = new BMessage();
142 			fUtility->cursorBitmap->Archive(bitmap);
143 			message.AddMessage("cursorBitmap", bitmap);
144 
145 			bitmap = new BMessage();
146 			fUtility->cursorAreaBitmap->Archive(bitmap);
147 			message.AddMessage("cursorAreaBitmap", bitmap);
148 
149 			message.AddPoint("cursorPosition", fUtility->cursorPosition);
150 			message.AddRect("activeWindowFrame", fUtility->activeWindowFrame);
151 			message.AddRect("tabFrame", fUtility->tabFrame);
152 			message.AddFloat("borderSize", fUtility->borderSize);
153 
154 			be_roster->Launch("application/x-vnd.haiku-screenshot",
155 				&message);
156 		}
157 	}
158 
159 	be_app->PostMessage(B_QUIT_REQUESTED);
160 }
161 
162 
163 void
164 Screenshot::_ShowHelp()
165 {
166 	printf("Screenshot [OPTIONS] [FILE]  Creates a bitmap of the current "
167 		"screen\n\n");
168 	printf("FILE is the optional output path / filename used in silent mode. "
169 		"An exisiting\nfile with the same name will be overwritten without "
170 		"warning. If FILE is not\ngiven the screenshot will be saved to a "
171 		"file with the default filename in the\nuser's home directory.\n\n");
172 	printf("OPTIONS\n");
173 	printf("  -m, --mouse-pointer   Include the mouse pointer\n");
174 	printf("  -b, --border          Include the window border\n");
175 	printf("  -w, --window          Capture the active window instead of the "
176 		"entire screen\n");
177 	printf("  -d, --delay=seconds   Take screenshot after the specified delay "
178 		"[in seconds]\n");
179 	printf("  -s, --silent          Saves the screenshot without showing the "
180 		"application\n                        window\n");
181 	printf("  -f, --format=image	Give the image format you like to save "
182 		"as\n");
183 	printf("                        [bmp], [gif], [jpg], [png], [ppm], "
184 		"[tga], [tif]\n");
185 	printf("  -c, --clipboard       Copies the screenshot to the system "
186 		"clipboard without\n                        showing the application "
187 		"window\n");
188 	printf("\n");
189 	printf("Note: OPTION -b, --border takes only effect when used with -w, "
190 		"--window\n");
191 
192 	fLaunchGui = false;
193 }
194 
195 
196 void
197 Screenshot::_New(bigtime_t delay)
198 {
199 	delete fUtility->wholeScreen;
200 	delete fUtility->cursorBitmap;
201 	delete fUtility->cursorAreaBitmap;
202 
203 	if (delay > 0)
204 		snooze(delay);
205 
206 	_GetActiveWindowFrame();
207 
208 	// There is a bug in the drawEngine code that prevents the drawCursor
209 	// flag from hiding the cursor when GetBitmap is called, so we need to hide
210 	// the cursor by ourselves. Refer to trac tickets #2988 and #2997
211 	bool cursorIsHidden = IsCursorHidden();
212 	if (!cursorIsHidden)
213 		HideCursor();
214 	if (BScreen().GetBitmap(&fUtility->wholeScreen, false) != B_OK)
215 		return;
216 	if (!cursorIsHidden)
217 		ShowCursor();
218 
219 	// Get the current cursor position, bitmap, and hotspot
220 	BPoint cursorHotSpot;
221 	get_mouse(&fUtility->cursorPosition, NULL);
222 	get_mouse_bitmap(&fUtility->cursorBitmap, &cursorHotSpot);
223 	fUtility->cursorPosition -= cursorHotSpot;
224 
225 	// Put the mouse area in a bitmap
226 	BRect bounds = fUtility->cursorBitmap->Bounds();
227 	int cursorWidth = bounds.IntegerWidth() + 1;
228 	int cursorHeight = bounds.IntegerHeight() + 1;
229 	fUtility->cursorAreaBitmap = new BBitmap(bounds, B_RGBA32);
230 
231 	fUtility->cursorAreaBitmap->ImportBits(fUtility->wholeScreen->Bits(),
232 		fUtility->wholeScreen->BitsLength(),
233 		fUtility->wholeScreen->BytesPerRow(),
234 		fUtility->wholeScreen->ColorSpace(),
235 		fUtility->cursorPosition, BPoint(0, 0),
236 		cursorWidth, cursorHeight);
237 
238 	// Fill in the background of the mouse bitmap
239 	uint8* bits = (uint8*)fUtility->cursorBitmap->Bits();
240 	uint8* areaBits = (uint8*)fUtility->cursorAreaBitmap->Bits();
241 	for (int32 i = 0; i < cursorHeight; i++) {
242 		for (int32 j = 0; j < cursorWidth; j++) {
243 			uint8 alpha = 255 - bits[3];
244 			bits[0] = ((areaBits[0] * alpha) >> 8) + bits[0];
245 			bits[1] = ((areaBits[1] * alpha) >> 8) + bits[1];
246 			bits[2] = ((areaBits[2] * alpha) >> 8) + bits[2];
247 			bits[3] = 255;
248 			areaBits += 4;
249 			bits += 4;
250 		}
251 	}
252 }
253 
254 
255 status_t
256 Screenshot::_GetActiveWindowFrame()
257 {
258 	fUtility->activeWindowFrame.Set(0, 0, -1, -1);
259 
260 	// Create a messenger to communicate with the active application
261 	app_info appInfo;
262 	status_t status = be_roster->GetActiveAppInfo(&appInfo);
263 	if (status != B_OK)
264 		return status;
265 	BMessenger messenger(appInfo.signature, appInfo.team);
266 	if (!messenger.IsValid())
267 		return B_ERROR;
268 
269 	// Loop through the windows of the active application to find out which
270 	// window is active
271 	int32 tokenCount;
272 	int32* tokens = get_token_list(appInfo.team, &tokenCount);
273 	bool foundActiveWindow = false;
274 	BMessage message;
275 	BMessage reply;
276 	int32 index = 0;
277 	int32 token = -1;
278 	client_window_info* windowInfo = NULL;
279 	bool modalWindow = false;
280 	while (true) {
281 		message.MakeEmpty();
282 		reply.MakeEmpty();
283 
284 		message.what = B_GET_PROPERTY;
285 		message.AddSpecifier("Active");
286 		message.AddSpecifier("Window", index);
287 		messenger.SendMessage(&message, &reply, B_INFINITE_TIMEOUT, 50000);
288 
289 		if (reply.what == B_MESSAGE_NOT_UNDERSTOOD)
290 			break;
291 
292 		if (!reply.what) {
293 			// Reply timout, this probably means that we have a modal window
294 			// so we'll just get the window frame of the top most window
295 			modalWindow = true;
296 			free(tokens);
297 			status_t status = BPrivate::get_window_order(current_workspace(),
298 				&tokens, &tokenCount);
299 			if (status != B_OK || !tokens || tokenCount < 1)
300 				return B_ERROR;
301 			foundActiveWindow = true;
302 		} else if (reply.FindBool("result", &foundActiveWindow) != B_OK)
303 			foundActiveWindow = false;
304 
305 		if (foundActiveWindow) {
306 			// Get the client_window_info of the active window
307 			foundActiveWindow = false;
308 			for (int i = 0; i < tokenCount; i++) {
309 				token = tokens[i];
310 				windowInfo = get_window_info(token);
311 				if (!windowInfo->is_mini && !windowInfo->show_hide_level > 0) {
312 					foundActiveWindow = true;
313 					break;
314 				}
315 				free(windowInfo);
316 			}
317 			if (foundActiveWindow)
318 				break;
319 		}
320 		index++;
321 	}
322 	free(tokens);
323 
324 	if (!foundActiveWindow)
325 		return B_ERROR;
326 
327 	// Get the TabFrame using the scripting interface
328 	if (!modalWindow) {
329 		message.MakeEmpty();
330 		message.what = B_GET_PROPERTY;
331 		message.AddSpecifier("TabFrame");
332 		message.AddSpecifier("Window", index);
333 		reply.MakeEmpty();
334 		messenger.SendMessage(&message, &reply);
335 
336 		if (reply.FindRect("result", &fUtility->tabFrame) != B_OK)
337 			return B_ERROR;
338 	} else
339 		fUtility->tabFrame.Set(0, 0, 0, 0);
340 
341 	// Get the active window frame from the client_window_info
342 	fUtility->activeWindowFrame.left = windowInfo->window_left;
343 	fUtility->activeWindowFrame.top = windowInfo->window_top;
344 	fUtility->activeWindowFrame.right = windowInfo->window_right;
345 	fUtility->activeWindowFrame.bottom = windowInfo->window_bottom;
346 	fUtility->borderSize = windowInfo->border_size;
347 
348 	free(windowInfo);
349 
350 	// Make sure that fActiveWindowFrame doesn't extend beyond the screen frame
351 	BRect screenFrame(BScreen().Frame());
352 	if (fUtility->activeWindowFrame.left < screenFrame.left)
353 		fUtility->activeWindowFrame.left = screenFrame.left;
354 	if (fUtility->activeWindowFrame.top < screenFrame.top)
355 		fUtility->activeWindowFrame.top = screenFrame.top;
356 	if (fUtility->activeWindowFrame.right > screenFrame.right)
357 		fUtility->activeWindowFrame.right = screenFrame.right;
358 	if (fUtility->activeWindowFrame.bottom > screenFrame.bottom)
359 		fUtility->activeWindowFrame.bottom = screenFrame.bottom;
360 
361 	return B_OK;
362 }
363 
364 
365 int32
366 Screenshot::_GetImageType(const char* name) const
367 {
368 	if (strcmp(name, "bmp") == 0)
369 		return B_BMP_FORMAT;
370 	else if (strcmp(name, "gif") == 0)
371 		return B_GIF_FORMAT;
372 	else if (strcmp(name, "jpg") == 0 || strcmp(name, "jpeg") == 0)
373 		return B_JPEG_FORMAT;
374 	else if (strcmp(name, "ppm") == 0)
375 		return B_PPM_FORMAT;
376 	else if (strcmp(name, "tga") == 0 || strcmp(name, "targa") == 0)
377 		return B_TGA_FORMAT;
378 	else if (strcmp(name, "tif") == 0 || strcmp(name, "tiff") == 0)
379 		return B_TIFF_FORMAT;
380 	else {
381 		return B_PNG_FORMAT;
382 	}
383 }
384 
385 
386 int
387 main()
388 {
389 	Screenshot screenshot;
390 	return screenshot.Run();
391 }
392