summaryrefslogtreecommitdiffstats
path: root/cloud_print/service/win/cloud_print_service_config.cc
blob: bad7111e5013148b29dff492c5f81e83ad3ed599 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <atlbase.h>
#include <atlapp.h>  // NOLINT

#include "base/at_exit.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string16.h"
#include "base/threading/thread.h"
#include "chrome/common/chrome_constants.h"
#include "cloud_print/common/win/cloud_print_utils.h"
#include "cloud_print/resources.h"
#include "cloud_print/service/service_state.h"
#include "cloud_print/service/win/chrome_launcher.h"
#include "cloud_print/service/win/service_controller.h"
#include "cloud_print/service/win/service_utils.h"
#include "cloud_print/service/win/setup_listener.h"

using cloud_print::LoadLocalString;
using cloud_print::GetErrorMessage;

class SetupDialog : public base::RefCounted<SetupDialog>,
                    public ATL::CDialogImpl<SetupDialog> {
 public:
  // Enables accelerators.
  class MessageFilter : public base::MessageLoopForUI::MessageFilter {
   public:
    explicit MessageFilter(SetupDialog* dialog) : dialog_(dialog){}
    virtual ~MessageFilter() {};

    // MessageLoopForUI::MessageFilter
    virtual bool ProcessMessage(const MSG& msg) OVERRIDE {
      MSG msg2 = msg;
      return dialog_->IsDialogMessage(&msg2) != FALSE;
    }

   private:
    scoped_refptr<SetupDialog> dialog_;
  };

  typedef ATL::CDialogImpl<SetupDialog> Base;
  enum { IDD = IDD_SETUP_DIALOG };

  BEGIN_MSG_MAP(SetupDialog)
    MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
    MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnCtrColor)
    MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
    COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
    COMMAND_ID_HANDLER(IDC_START, OnStart)
    COMMAND_ID_HANDLER(IDC_INSTALL, OnInstall)
    COMMAND_ID_HANDLER(IDC_LOGGING, OnLogging)
  END_MSG_MAP()

  SetupDialog();
 private:
  // Window Message Handlers
  LRESULT OnInitDialog(UINT message, WPARAM wparam, LPARAM lparam,
                       BOOL& handled);
  LRESULT OnCtrColor(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled);
  LRESULT OnCancel(UINT, INT nIdentifier, HWND, BOOL& handled);
  LRESULT OnStart(UINT, INT nIdentifier, HWND, BOOL& handled);
  LRESULT OnInstall(UINT, INT nIdentifier, HWND, BOOL& handled);
  LRESULT OnLogging(UINT, INT nIdentifier, HWND, BOOL& handled);
  LRESULT OnDestroy(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled);

  void PostUITask(const base::Closure& task);
  void PostIOTask(const base::Closure& task);

  // UI Calls.

  // Disables all controls after users actions.
  void DisableControls();
  // Updates state of controls after when we received service status.
  void SetState(ServiceController::State state, const string16& user,
                 bool is_logging_enabled);
  // Show message box with error.
  void ShowErrorMessageBox(const string16& error_message);
  // Show use message box instructions how to deal with opened Chrome window.
  void AskToCloseChrome();
  string16 GetDlgItemText(int id) const;
  string16 GetUser() const;
  string16 GetPassword() const;
  bool IsLoggingEnabled() const;
  bool IsInstalled() const {
    return state_ > ServiceController::STATE_NOT_FOUND;
  }

  // IO Calls.
  // Installs service.
  void Install(const string16& user, const string16& password,
               bool enable_logging);
  // Starts service.
  void Start();
  // Stops service.
  void Stop();
  // Uninstall service.
  void Uninstall();
  // Update service state.
  void UpdateState();
  // Posts task to UI thread to show error using string id.
  void ShowError(int string_id);
  // Posts task to UI thread to show error using string.
  void ShowError(const string16& error_message);
  // Posts task to UI thread to show error using error code.
  void ShowError(HRESULT hr);

  ServiceController::State state_;
  base::Thread worker_;

  base::MessageLoop* ui_loop_;
  base::MessageLoop* io_loop_;

  ServiceController controller_;
};

SetupDialog::SetupDialog()
    : state_(ServiceController::STATE_NOT_FOUND),
      worker_("worker") {
  ui_loop_ = base::MessageLoop::current();
  DCHECK(ui_loop_->IsType(base::MessageLoop::TYPE_UI));

  worker_.StartWithOptions(
      base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
  io_loop_ = worker_.message_loop();
  DCHECK(io_loop_->IsType(base::MessageLoop::TYPE_IO));
}

void SetupDialog::PostUITask(const base::Closure& task) {
  ui_loop_->PostTask(FROM_HERE, task);
}

void SetupDialog::PostIOTask(const base::Closure& task) {
  io_loop_->PostTask(FROM_HERE, task);
}

void SetupDialog::ShowErrorMessageBox(const string16& error_message) {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_UI));
  MessageBox(error_message.c_str(),
             LoadLocalString(IDS_OPERATION_FAILED_TITLE).c_str(),
             MB_ICONERROR | MB_OK);
}

void SetupDialog::AskToCloseChrome() {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_UI));
  MessageBox(LoadLocalString(IDS_ADD_PRINTERS_USING_CHROME).c_str(),
             LoadLocalString(IDS_CONTINUE_IN_CHROME_TITLE).c_str(),
             MB_OK);
}

void SetupDialog::SetState(ServiceController::State status,
                           const string16& user,
                           bool is_logging_enabled) {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_UI));
  state_ = status;

  DWORD status_string = 0;
  switch(status) {
  case ServiceController::STATE_NOT_FOUND:
    status_string = IDS_SERVICE_NOT_FOUND;
    break;
  case ServiceController::STATE_STOPPED:
    status_string = IDS_SERVICE_STOPPED;
    break;
  case ServiceController::STATE_RUNNING:
    status_string = IDS_SERVICE_RUNNING;
    break;
  }
  SetDlgItemText(IDC_STATUS,
                 status_string ? LoadLocalString(status_string).c_str() : L"");
  if (IsInstalled()) {
    SetDlgItemText(IDC_USER, user.c_str());
    CheckDlgButton(IDC_LOGGING,
                   is_logging_enabled ? BST_CHECKED : BST_UNCHECKED);
  }

  ATL::CWindow start_button = GetDlgItem(IDC_START);
  DWORD start_string = (status == ServiceController::STATE_STOPPED) ?
                       IDS_SERVICE_START : IDS_SERVICE_STOP;
  start_button.SetWindowText(LoadLocalString(start_string).c_str());
  start_button.ShowWindow(IsInstalled() ? SW_SHOW : SW_HIDE);
  start_button.EnableWindow(TRUE);

  ATL::CWindow install_button = GetDlgItem(IDC_INSTALL);
  DWORD install_string = IsInstalled() ? IDS_SERVICE_UNINSTALL :
                                         IDS_SERVICE_INSTALL;
  install_button.SetWindowText(LoadLocalString(install_string).c_str());
  install_button.ShowWindow(SW_SHOW);
  install_button.EnableWindow(TRUE);

  if (!IsInstalled()) {
    GetDlgItem(IDC_USER).EnableWindow(TRUE);
    GetDlgItem(IDC_PASSWORD).EnableWindow(TRUE);
    GetDlgItem(IDC_LOGGING).EnableWindow(TRUE);
  }
}

LRESULT SetupDialog::OnInitDialog(UINT message, WPARAM wparam, LPARAM lparam,
                                  BOOL& handled) {
  ATLVERIFY(CenterWindow());

  WTL::CIcon icon;
  if (icon.LoadIcon(MAKEINTRESOURCE(IDI_ICON))) {
    SetIcon(icon);
  }

  SetWindowText(LoadLocalString(IDS_SETUP_PROGRAM_NAME).c_str());
  SetDlgItemText(IDC_STATE_LABEL, LoadLocalString(IDS_STATE_LABEL).c_str());
  SetDlgItemText(IDC_USER_LABEL, LoadLocalString(IDS_USER_LABEL).c_str());
  SetDlgItemText(IDC_PASSWORD_LABEL,
                 LoadLocalString(IDS_PASSWORD_LABEL).c_str());
  SetDlgItemText(IDC_LOGGING, LoadLocalString(IDS_LOGGING_LABEL).c_str());
  SetDlgItemText(IDCANCEL, LoadLocalString(IDS_CLOSE).c_str());

  SetState(ServiceController::STATE_UNKNOWN, L"", false);
  DisableControls();

  SetDlgItemText(IDC_USER, GetCurrentUserName().c_str());

  PostIOTask(base::Bind(&SetupDialog::UpdateState, this));

  return 0;
}

LRESULT SetupDialog::OnCtrColor(UINT message, WPARAM wparam, LPARAM lparam,
                                BOOL& handled) {
  HWND window = reinterpret_cast<HWND>(lparam);
  if (GetDlgItem(IDC_LOGO).m_hWnd == window) {
    return reinterpret_cast<LRESULT>(::GetStockObject(WHITE_BRUSH));
  }
  return 0;
}

LRESULT SetupDialog::OnStart(UINT, INT nIdentifier, HWND, BOOL& handled) {
  DisableControls();
  DCHECK(IsInstalled());
  if (state_ == ServiceController::STATE_RUNNING)
    PostIOTask(base::Bind(&SetupDialog::Stop, this));
  else
    PostIOTask(base::Bind(&SetupDialog::Start, this));
  return 0;
}

LRESULT SetupDialog::OnInstall(UINT, INT nIdentifier, HWND, BOOL& handled) {
  DisableControls();
  if (IsInstalled()) {
    PostIOTask(base::Bind(&SetupDialog::Uninstall, this));
  } else {
    PostIOTask(base::Bind(&SetupDialog::Install, this, GetUser(),
                          GetPassword(), IsLoggingEnabled()));
  }
  return 0;
}

LRESULT SetupDialog::OnLogging(UINT, INT nIdentifier, HWND, BOOL& handled) {
  CheckDlgButton(IDC_LOGGING, IsLoggingEnabled()? BST_UNCHECKED : BST_CHECKED);
  return 0;
}

LRESULT SetupDialog::OnCancel(UINT, INT nIdentifier, HWND, BOOL& handled) {
  DestroyWindow();
  return 0;
}

LRESULT SetupDialog::OnDestroy(UINT message, WPARAM wparam, LPARAM lparam,
                               BOOL& handled) {
  base::MessageLoop::current()->PostTask(FROM_HERE,
                                         base::MessageLoop::QuitClosure());
  return 1;
}

void SetupDialog::DisableControls() {
  GetDlgItem(IDC_START).EnableWindow(FALSE);
  GetDlgItem(IDC_INSTALL).EnableWindow(FALSE);
  GetDlgItem(IDC_USER).EnableWindow(FALSE);
  GetDlgItem(IDC_PASSWORD).EnableWindow(FALSE);
  GetDlgItem(IDC_LOGGING).EnableWindow(FALSE);
}

string16 SetupDialog::GetDlgItemText(int id) const {
  const ATL::CWindow& item = GetDlgItem(id);
  size_t length = item.GetWindowTextLength();
  string16 result(length + 1, L'\0');
  result.resize(item.GetWindowText(&result[0], result.size()));
  return result;
}

string16 SetupDialog::GetUser() const {
  return GetDlgItemText(IDC_USER);
}

string16 SetupDialog::GetPassword() const{
  return GetDlgItemText(IDC_PASSWORD);
}

bool SetupDialog::IsLoggingEnabled() const{
  return IsDlgButtonChecked(IDC_LOGGING) == BST_CHECKED;
}

void SetupDialog::UpdateState() {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_IO));
  controller_.UpdateState();
  PostUITask(base::Bind(&SetupDialog::SetState, this, controller_.state(),
                        controller_.user(), controller_.is_logging_enabled()));
}

void SetupDialog::ShowError(const string16& error_message) {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_IO));
  PostUITask(base::Bind(&SetupDialog::SetState,
                        this,
                        ServiceController::STATE_UNKNOWN,
                        L"",
                        false));
  PostUITask(base::Bind(&SetupDialog::ShowErrorMessageBox, this,
                        error_message));
  LOG(ERROR) << error_message;
}

void SetupDialog::ShowError(int string_id) {
  ShowError(cloud_print::LoadLocalString(string_id));
}

void SetupDialog::ShowError(HRESULT hr) {
  ShowError(GetErrorMessage(hr));
}

void SetupDialog::Install(const string16& user, const string16& password,
                          bool enable_logging) {
  // Don't forget to update state on exit.
  base::ScopedClosureRunner scoped_update_status(
        base::Bind(&SetupDialog::UpdateState, this));

  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_IO));

  SetupListener setup(GetUser());
  HRESULT hr = controller_.InstallCheckService(user, password,
                                               base::FilePath());
  if (FAILED(hr))
    return ShowError(hr);

  {
    // Always uninstall service after requirements check.
    base::ScopedClosureRunner scoped_uninstall(
        base::Bind(base::IgnoreResult(&ServiceController::UninstallService),
                   base::Unretained(&controller_)));

    hr = controller_.StartService();
    if (FAILED(hr))
      return ShowError(hr);

    if (!setup.WaitResponce(base::TimeDelta::FromSeconds(30)))
      return ShowError(IDS_ERROR_FAILED_START_SERVICE);
  }

  if (setup.user_data_dir().empty())
    return ShowError(IDS_ERROR_NO_DATA_DIR);

  if (setup.chrome_path().empty())
    return ShowError(IDS_ERROR_NO_CHROME);

  if (!setup.is_xps_available())
    return ShowError(IDS_ERROR_NO_XPS);

  base::FilePath file = setup.user_data_dir();
  file = file.Append(chrome::kServiceStateFileName);

  std::string proxy_id;
  std::string contents;

  if (file_util::ReadFileToString(file, &contents)) {
    ServiceState service_state;
    if (service_state.FromString(contents))
      proxy_id = service_state.proxy_id();
  }
  PostUITask(base::Bind(&SetupDialog::AskToCloseChrome, this));
  contents = ChromeLauncher::CreateServiceStateFile(proxy_id, setup.printers());

  if (contents.empty())
    return ShowError(IDS_ERROR_FAILED_CREATE_CONFIG);

  size_t written = file_util::WriteFile(file, contents.c_str(),
                                        contents.size());
  if (written != contents.size()) {
    DWORD last_error = GetLastError();
    if (!last_error)
      return ShowError(IDS_ERROR_FAILED_CREATE_CONFIG);
    return ShowError(HRESULT_FROM_WIN32(last_error));
  }

  hr = controller_.InstallConnectorService(user, password, base::FilePath(),
                                           enable_logging);
  if (FAILED(hr))
    return ShowError(hr);

  hr = controller_.StartService();
  if (FAILED(hr))
    return ShowError(hr);
}

void SetupDialog::Start() {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_IO));
  HRESULT hr = controller_.StartService();
  if (FAILED(hr))
    ShowError(hr);
  UpdateState();
}

void SetupDialog::Stop() {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_IO));
  HRESULT hr = controller_.StopService();
  if (FAILED(hr))
    ShowError(hr);
  UpdateState();
}

void SetupDialog::Uninstall() {
  DCHECK(base::MessageLoop::current()->IsType(base::MessageLoop::TYPE_IO));
  HRESULT hr = controller_.UninstallService();
  if (FAILED(hr))
    ShowError(hr);
  UpdateState();
}

class CloudPrintServiceConfigModule
    : public ATL::CAtlExeModuleT<CloudPrintServiceConfigModule> {
};

CloudPrintServiceConfigModule _AtlModule;

int WINAPI WinMain(__in  HINSTANCE hInstance,
                   __in  HINSTANCE hPrevInstance,
                   __in  LPSTR lpCmdLine,
                   __in  int nCmdShow) {
  base::AtExitManager at_exit;
  CommandLine::Init(0, NULL);

  base::MessageLoopForUI loop;
  scoped_refptr<SetupDialog> dialog(new SetupDialog());
  dialog->Create(NULL);
  dialog->ShowWindow(SW_SHOW);
  scoped_ptr<SetupDialog::MessageFilter> filter(
      new SetupDialog::MessageFilter(dialog));
  loop.SetMessageFilter(filter.Pass());

  loop.Run();
  return 0;
}