App_Main.py 454 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import shutil
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Diverse
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM Objects
  45. from defaults import FlatCAMDefaults
  46. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  47. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  48. from AppObjects.ObjectCollection import *
  49. from AppObjects.FlatCAMObj import FlatCAMObj
  50. from AppObjects.AppObject import AppObject
  51. # FlatCAM Parsing files
  52. from AppParsers.ParseExcellon import Excellon
  53. from AppParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM AppGUI
  56. from AppGUI.PlotCanvas import *
  57. from AppGUI.PlotCanvasLegacy import *
  58. from AppGUI.MainGUI import *
  59. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  60. # FlatCAM Pre-processors
  61. from AppPreProcessor import load_preprocessors
  62. # FlatCAM AppEditors
  63. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from AppEditors.FlatCAMTextEditor import TextEditor
  67. from AppParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from AppProcess import *
  70. from AppWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from AppTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import AppTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. from win32comext.shell import shell, shellcon
  80. fcTranslate.apply_language('strings')
  81. if '_' not in builtins.__dict__:
  82. _ = gettext.gettext
  83. class App(QtCore.QObject):
  84. """
  85. The main application class. The constructor starts the AppGUI.
  86. """
  87. # ###############################################################################################################
  88. # ########################################## App ################################################################
  89. # ###############################################################################################################
  90. # ###############################################################################################################
  91. # ######################################### LOGGING #############################################################
  92. # ###############################################################################################################
  93. log = logging.getLogger('base')
  94. log.setLevel(logging.DEBUG)
  95. # log.setLevel(logging.WARNING)
  96. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  97. handler = logging.StreamHandler()
  98. handler.setFormatter(formatter)
  99. log.addHandler(handler)
  100. # ###############################################################################################################
  101. # #################################### Get Cmd Line Options #####################################################
  102. # ###############################################################################################################
  103. cmd_line_shellfile = ''
  104. cmd_line_shellvar = ''
  105. cmd_line_headless = None
  106. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  107. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  108. "FlatCam.py --headless=1"
  109. try:
  110. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  111. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  112. "shellvar=",
  113. "headless=",
  114. "multiprocessing-fork="])
  115. except getopt.GetoptError:
  116. print(cmd_line_help)
  117. sys.exit(2)
  118. for opt, arg in cmd_line_options:
  119. if opt == '-h':
  120. print(cmd_line_help)
  121. sys.exit()
  122. elif opt == '--shellfile':
  123. cmd_line_shellfile = arg
  124. elif opt == '--shellvar':
  125. cmd_line_shellvar = arg
  126. elif opt == '--headless':
  127. try:
  128. cmd_line_headless = eval(arg)
  129. except NameError:
  130. pass
  131. # ###############################################################################################################
  132. # ################################### Version and VERSION DATE ##################################################
  133. # ###############################################################################################################
  134. version = 8.993
  135. version_date = "2020/08/01"
  136. beta = True
  137. engine = '3D'
  138. # current date now
  139. date = str(datetime.today()).rpartition('.')[0]
  140. date = ''.join(c for c in date if c not in ':-')
  141. date = date.replace(' ', '_')
  142. # ###############################################################################################################
  143. # ############################################ URLS's ###########################################################
  144. # ###############################################################################################################
  145. # URL for update checks and statistics
  146. version_url = "http://flatcam.org/version"
  147. # App URL
  148. app_url = "http://flatcam.org"
  149. # Manual URL
  150. manual_url = "http://flatcam.org/manual/index.html"
  151. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  152. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  153. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  154. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  155. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  156. # this variable will hold the project status
  157. # if True it will mean that the project was modified and not saved
  158. should_we_save = False
  159. # flag is True if saving action has been triggered
  160. save_in_progress = False
  161. # ###############################################################################################################
  162. # ####################################### APP Signals ######################################################
  163. # ###############################################################################################################
  164. # Inform the user
  165. # Handled by:
  166. # * App.info() --> Print on the status bar
  167. inform = QtCore.pyqtSignal(str)
  168. app_quit = QtCore.pyqtSignal()
  169. # General purpose background task
  170. worker_task = QtCore.pyqtSignal(dict)
  171. # File opened
  172. # Handled by:
  173. # * register_folder()
  174. # * register_recent()
  175. # Note: Setting the parameters to unicode does not seem
  176. # to have an effect. Then are received as Qstring
  177. # anyway.
  178. # File type and filename
  179. file_opened = QtCore.pyqtSignal(str, str)
  180. # File type and filename
  181. file_saved = QtCore.pyqtSignal(str, str)
  182. # Percentage of progress
  183. progress = QtCore.pyqtSignal(int)
  184. # Emitted when a new object has been added or deleted from/to the collection
  185. object_status_changed = QtCore.pyqtSignal(object, str, str)
  186. message = QtCore.pyqtSignal(str, str, str)
  187. # Emmited when shell command is finished(one command only)
  188. shell_command_finished = QtCore.pyqtSignal(object)
  189. # Emitted when multiprocess pool has been recreated
  190. pool_recreated = QtCore.pyqtSignal(object)
  191. # Emitted when an unhandled exception happens
  192. # in the worker task.
  193. thread_exception = QtCore.pyqtSignal(object)
  194. # used to signal that there are arguments for the app
  195. args_at_startup = QtCore.pyqtSignal(list)
  196. # a reusable signal to replot a list of objects
  197. # should be disconnected after use so it can be reused
  198. replot_signal = pyqtSignal(list)
  199. # signal emitted when jumping
  200. jump_signal = pyqtSignal(tuple)
  201. # signal emitted when jumping
  202. locate_signal = pyqtSignal(tuple, str)
  203. # close app signal
  204. close_app_signal = pyqtSignal()
  205. # will perform the cleanup operation after a Graceful Exit
  206. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  207. # graphic residues behind
  208. cleanup = pyqtSignal()
  209. def __init__(self, user_defaults=True):
  210. """
  211. Starts the application.
  212. :return: app
  213. :rtype: App
  214. """
  215. super().__init__()
  216. App.log.info("FlatCAM Starting...")
  217. self.main_thread = QtWidgets.QApplication.instance().thread()
  218. # ############################################################################################################
  219. # ################# Setup the listening thread for another instance launching with args ######################
  220. # ############################################################################################################
  221. if sys.platform == 'win32' or sys.platform == 'linux':
  222. # make sure the thread is stored by using a self. otherwise it's garbage collected
  223. self.th = QtCore.QThread()
  224. self.th.start(priority=QtCore.QThread.LowestPriority)
  225. self.new_launch = ArgsThread()
  226. self.new_launch.open_signal[list].connect(self.on_startup_args)
  227. self.new_launch.moveToThread(self.th)
  228. self.new_launch.start.emit()
  229. # ############################################################################################################
  230. # # ######################################## OS-specific #####################################################
  231. # ############################################################################################################
  232. portable = False
  233. # Folder for user settings.
  234. if sys.platform == 'win32':
  235. if platform.architecture()[0] == '32bit':
  236. App.log.debug("Win32!")
  237. else:
  238. App.log.debug("Win64!")
  239. # #######################################################################################################
  240. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  241. # #######################################################################################################
  242. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  243. try:
  244. with open(config_file, 'r'):
  245. pass
  246. except FileNotFoundError:
  247. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  248. try:
  249. with open(config_file, 'r') as f:
  250. try:
  251. for line in f:
  252. param = str(line).replace('\n', '').rpartition('=')
  253. if param[0] == 'portable':
  254. try:
  255. portable = eval(param[2])
  256. except NameError:
  257. portable = False
  258. if param[0] == 'headless':
  259. if param[2].lower() == 'true':
  260. self.cmd_line_headless = 1
  261. else:
  262. self.cmd_line_headless = None
  263. except Exception as e:
  264. log.debug('App.__init__() -->%s' % str(e))
  265. return
  266. except FileNotFoundError as e:
  267. log.debug(str(e))
  268. pass
  269. if portable is False:
  270. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  271. else:
  272. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  273. self.os = 'windows'
  274. else: # Linux/Unix/MacOS
  275. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  276. self.os = 'unix'
  277. # ############################################################################################################
  278. # ################################# Setup folders and files ##################################################
  279. # ############################################################################################################
  280. if not os.path.exists(self.data_path):
  281. os.makedirs(self.data_path)
  282. App.log.debug('Created data folder: ' + self.data_path)
  283. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  284. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  285. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  286. if not os.path.exists(self.preprocessorpaths):
  287. os.makedirs(self.preprocessorpaths)
  288. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  289. # create geo_tools_db.FlatDB file if there is none
  290. try:
  291. f = open(self.data_path + '/geo_tools_db.FlatDB')
  292. f.close()
  293. except IOError:
  294. App.log.debug('Creating empty geo_tool_db.FlatDB')
  295. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  296. json.dump({}, f)
  297. f.close()
  298. # create current_defaults.FlatConfig file if there is none
  299. try:
  300. f = open(self.data_path + '/current_defaults.FlatConfig')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty current_defaults.FlatConfig')
  304. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # Write factory_defaults.FlatConfig file to disk
  308. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  309. # create a recent files json file if there is none
  310. try:
  311. f = open(self.data_path + '/recent.json')
  312. f.close()
  313. except IOError:
  314. App.log.debug('Creating empty recent.json')
  315. f = open(self.data_path + '/recent.json', 'w')
  316. json.dump([], f)
  317. f.close()
  318. # create a recent projects json file if there is none
  319. try:
  320. fp = open(self.data_path + '/recent_projects.json')
  321. fp.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent_projects.json')
  324. fp = open(self.data_path + '/recent_projects.json', 'w')
  325. json.dump([], fp)
  326. fp.close()
  327. # Application directory. CHDIR to it. Otherwise, trying to load
  328. # GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. App.log.debug("Application path is " + self.app_home)
  332. App.log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. self.ui = MainGUI(self)
  397. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  398. if theme_settings.contains("theme"):
  399. theme = theme_settings.value('theme', type=str)
  400. else:
  401. theme = 'white'
  402. if self.defaults["global_cursor_color_enabled"]:
  403. self.cursor_color_3D = self.defaults["global_cursor_color"]
  404. else:
  405. if theme == 'white':
  406. self.cursor_color_3D = 'black'
  407. else:
  408. self.cursor_color_3D = 'gray'
  409. # update the defaults dict with the setting in QSetting
  410. self.defaults['global_theme'] = theme
  411. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  412. self.ui.final_save.connect(self.final_save)
  413. # set FlatCAM units in the Status bar
  414. self.set_screen_units(self.defaults['units'])
  415. # ###########################################################################################################
  416. # ########################################### AUTOSAVE SETUP ################################################
  417. # ###########################################################################################################
  418. self.block_autosave = False
  419. self.autosave_timer = QtCore.QTimer(self)
  420. self.save_project_auto_update()
  421. self.autosave_timer.timeout.connect(self.save_project_auto)
  422. # ###########################################################################################################
  423. # #################################### LOAD PREPROCESSORS ###################################################
  424. # ###########################################################################################################
  425. # ----------------------------------------- WARNING --------------------------------------------------------
  426. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  427. # That's because the number of preprocessors can vary and here the comboboxes are populated
  428. # -----------------------------------------------------------------------------------------------------------
  429. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  430. # the preprocessor file
  431. self.preprocessors = load_preprocessors(self)
  432. # make sure that always the 'default' preprocessor is the first item in the dictionary
  433. if 'default' in self.preprocessors.keys():
  434. new_ppp_dict = {}
  435. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  436. default_pp = self.preprocessors.pop('default')
  437. new_ppp_dict['default'] = default_pp
  438. # then add the rest of the keys
  439. for name, val_class in self.preprocessors.items():
  440. new_ppp_dict[name] = val_class
  441. # and now put back the ordered dict with 'default' key first
  442. self.preprocessors = new_ppp_dict
  443. for name in list(self.preprocessors.keys()):
  444. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  445. if name.partition('_')[0] == 'Paste':
  446. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  447. continue
  448. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  449. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  450. if name == 'hpgl':
  451. continue
  452. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  453. # ###########################################################################################################
  454. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  455. # ###########################################################################################################
  456. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  457. inform=self.inform)
  458. self.preferencesUiManager.defaults_write_form()
  459. # When the self.defaults dictionary changes will update the Preferences GUI forms
  460. self.defaults.set_change_callback(self.on_defaults_dict_change)
  461. # ###########################################################################################################
  462. # ##################################### FIRST RUN SECTION ###################################################
  463. # ################################ It's done only once after install #####################################
  464. # ###########################################################################################################
  465. if self.defaults["first_run"] is True:
  466. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  467. initial_lay = 'minimal'
  468. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  469. # Set the combobox in Preferences to the current layout
  470. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  471. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  472. # after the first run, this object should be False
  473. self.defaults["first_run"] = False
  474. self.preferencesUiManager.save_defaults(silent=True)
  475. # ###########################################################################################################
  476. # ############################################ Data #########################################################
  477. # ###########################################################################################################
  478. self.recent = []
  479. self.recent_projects = []
  480. self.clipboard = QtWidgets.QApplication.clipboard()
  481. self.project_filename = None
  482. self.toggle_units_ignore = False
  483. # ###########################################################################################################
  484. # ########################################## LOAD LANGUAGES ################################################
  485. # ###########################################################################################################
  486. self.languages = fcTranslate.load_languages()
  487. for name in sorted(self.languages.values()):
  488. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  489. # ###########################################################################################################
  490. # ####################################### APPLY APP LANGUAGE ################################################
  491. # ###########################################################################################################
  492. ret_val = fcTranslate.apply_language('strings')
  493. if ret_val == "no language":
  494. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  495. log.debug("Could not find the Language files. The App strings are missing.")
  496. else:
  497. # make the current language the current selection on the language combobox
  498. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  499. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  500. # ###########################################################################################################
  501. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  502. # ###########################################################################################################
  503. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  504. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  505. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  506. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  507. self.defaults.propagate_defaults()
  508. # ###########################################################################################################
  509. # ######################################## UPDATE THE OPTIONS ###############################################
  510. # ###########################################################################################################
  511. self.options = LoudDict()
  512. # -----------------------------------------------------------------------------------------------------------
  513. # Update the self.options from the self.defaults
  514. # The self.defaults holds the application defaults while the self.options holds the object defaults
  515. # -----------------------------------------------------------------------------------------------------------
  516. # Copy app defaults to project options
  517. for def_key, def_val in self.defaults.items():
  518. self.options[def_key] = deepcopy(def_val)
  519. self.preferencesUiManager.show_preferences_gui()
  520. # ### End of Data ####
  521. # ###########################################################################################################
  522. # #################################### SETUP OBJECT COLLECTION ##############################################
  523. # ###########################################################################################################
  524. self.collection = ObjectCollection(app=self)
  525. self.ui.project_tab_layout.addWidget(self.collection.view)
  526. self.app_obj = AppObject(app=self)
  527. # ### Adjust tabs width ## ##
  528. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  529. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  530. self.collection.view.setMinimumWidth(290)
  531. self.log.debug("Finished creating Object Collection.")
  532. # ###########################################################################################################
  533. # ######################################## SETUP Plot Area ##################################################
  534. # ###########################################################################################################
  535. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  536. if self.defaults["global_graphic_engine"] == '3D':
  537. self.is_legacy = False
  538. else:
  539. self.is_legacy = True
  540. # Event signals disconnect id holders
  541. self.mp = None
  542. self.mm = None
  543. self.mr = None
  544. self.mdc = None
  545. self.mp_zc = None
  546. self.kp = None
  547. # Matplotlib axis
  548. self.axes = None
  549. if show_splash:
  550. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  551. "Canvas initialization started."),
  552. alignment=Qt.AlignBottom | Qt.AlignLeft,
  553. color=QtGui.QColor("gray"))
  554. start_plot_time = time.time() # debug
  555. self.plotcanvas = None
  556. self.app_cursor = None
  557. self.hover_shapes = None
  558. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  559. # setup the PlotCanvas
  560. self.on_plotcanvas_setup()
  561. end_plot_time = time.time()
  562. self.used_time = end_plot_time - start_plot_time
  563. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  564. if show_splash:
  565. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  566. "Canvas initialization started.\n"
  567. "Canvas initialization finished in"), '%.2f' % self.used_time),
  568. alignment=Qt.AlignBottom | Qt.AlignLeft,
  569. color=QtGui.QColor("gray"))
  570. self.ui.splitter.setStretchFactor(1, 2)
  571. # ###########################################################################################################
  572. # ############################################### SYS TRAY ##################################################
  573. # ###########################################################################################################
  574. if self.defaults["global_systray_icon"]:
  575. self.parent_w = QtWidgets.QWidget()
  576. if self.cmd_line_headless == 1:
  577. self.trayIcon = FlatCAMSystemTray(app=self,
  578. icon=QtGui.QIcon(self.resource_location +
  579. '/flatcam_icon32_green.png'),
  580. headless=True,
  581. parent=self.parent_w)
  582. else:
  583. self.trayIcon = FlatCAMSystemTray(app=self,
  584. icon=QtGui.QIcon(self.resource_location +
  585. '/flatcam_icon32_green.png'),
  586. parent=self.parent_w)
  587. # ###########################################################################################################
  588. # ############################################### Worker SETUP ##############################################
  589. # ###########################################################################################################
  590. if self.defaults["global_worker_number"]:
  591. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  592. else:
  593. self.workers = WorkerStack(workers_number=2)
  594. self.worker_task.connect(self.workers.add_task)
  595. self.log.debug("Finished creating Workers crew.")
  596. # ###########################################################################################################
  597. # ############################################# Activity Monitor ###########################################
  598. # ###########################################################################################################
  599. self.activity_view = FlatCAMActivityView(app=self)
  600. self.ui.infobar.addWidget(self.activity_view)
  601. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  602. # ###########################################################################################################
  603. # ############################################# Signal handling #############################################
  604. # ###########################################################################################################
  605. # ########################################## Custom signals ################################################
  606. # signal for displaying messages in status bar
  607. self.inform.connect(self.info)
  608. # signal to be called when the app is quiting
  609. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  610. self.message.connect(lambda: message_dialog(parent=self.ui))
  611. # self.progress.connect(self.set_progress_bar)
  612. # signals emitted when file state change
  613. self.file_opened.connect(self.register_recent)
  614. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  615. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  616. # ########################################## Standard signals ###############################################
  617. # ### Menu
  618. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  619. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  620. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  621. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  622. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  623. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  624. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  625. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  626. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  627. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  628. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  629. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  630. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  631. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  632. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  633. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  634. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  635. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  636. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  637. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  638. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  639. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  640. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  641. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  642. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  643. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  644. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  645. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  646. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  647. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  648. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  649. self.ui.menufile_exit.triggered.connect(self.final_save)
  650. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  651. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  652. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  653. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  654. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  655. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  656. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  657. self.ui.menueditdelete.triggered.connect(self.on_delete)
  658. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  659. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  660. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  661. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  662. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  663. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  664. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  665. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  666. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  667. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  668. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  669. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  670. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  671. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  672. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  673. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  674. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  675. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  676. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  677. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  678. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  679. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  680. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  681. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  682. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  683. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  684. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  685. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  686. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  687. self.ui.menuview_replot.triggered.connect(self.plot_all)
  688. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  689. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  690. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  691. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  692. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  693. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  694. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  695. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  696. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  697. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  698. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  699. self.ui.menuhelp_about.triggered.connect(self.on_about)
  700. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  701. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  702. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  703. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  704. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  705. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  706. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  707. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  708. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  709. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  710. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  711. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  712. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  713. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  714. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  715. # ToolBar signals
  716. self.connect_toolbar_signals()
  717. # Notebook and Plot Tab Area signals
  718. # make the right click on the notebook tab and plot tab area tab raise a menu
  719. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  721. self.on_tab_setup_context_menu()
  722. # activate initial state
  723. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  724. # Context Menu
  725. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  726. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  727. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  728. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  729. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  730. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  731. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  732. self.ui.clearplot.triggered.connect(self.clear_plots)
  733. self.ui.replot.triggered.connect(self.plot_all)
  734. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  735. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  736. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  737. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  738. self.ui.popmenu_move.triggered.connect(self.obj_move)
  739. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  740. # Project Context Menu -> Color Setting
  741. for act in self.ui.menuprojectcolor.actions():
  742. act.triggered.connect(self.on_set_color_action_triggered)
  743. # ###########################################################################################################
  744. # #################################### GUI PREFERENCES SIGNALS ##############################################
  745. # ###########################################################################################################
  746. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  747. lambda: self.on_toggle_units(no_pref=False))
  748. # ##################################### Workspace Setting Signals ###########################################
  749. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  750. self.on_workspace_modified)
  751. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  752. self.on_workspace_modified
  753. )
  754. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  755. # ###########################################################################################################
  756. # ######################################## GUI SETTINGS SIGNALS #############################################
  757. # ###########################################################################################################
  758. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  759. # ######################################## Tools related signals ############################################
  760. # Film Tool
  761. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  762. self.on_film_color_entry)
  763. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  764. self.on_film_color_button)
  765. # QRCode Tool
  766. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  767. self.on_qrcode_fill_color_entry)
  768. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  769. self.on_qrcode_fill_color_button)
  770. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  771. self.on_qrcode_back_color_entry)
  772. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  773. self.on_qrcode_back_color_button)
  774. # portability changed signal
  775. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  776. # Object list
  777. self.object_status_changed.connect(self.collection.on_collection_updated)
  778. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  779. # Export Excellon parameters.
  780. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  781. self.on_update_exc_export
  782. )
  783. # call it once to make sure it is updated at startup
  784. self.on_update_exc_export(state=self.defaults["excellon_update"])
  785. # when there are arguments at application startup this get launched
  786. self.args_at_startup[list].connect(self.on_startup_args)
  787. # ###########################################################################################################
  788. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  789. # ###########################################################################################################
  790. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  791. lambda: self.restore_extensions(ext_type='excellon'))
  792. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  793. lambda: self.restore_extensions(ext_type='gcode'))
  794. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  795. lambda: self.restore_extensions(ext_type='gerber'))
  796. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  797. lambda: self.delete_all_extensions(ext_type='excellon'))
  798. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  799. lambda: self.delete_all_extensions(ext_type='gcode'))
  800. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  801. lambda: self.delete_all_extensions(ext_type='gerber'))
  802. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  803. lambda: self.add_extension(ext_type='excellon'))
  804. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  805. lambda: self.add_extension(ext_type='gcode'))
  806. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='gerber'))
  808. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  809. lambda: self.del_extension(ext_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  811. lambda: self.del_extension(ext_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  813. lambda: self.del_extension(ext_type='gerber'))
  814. # connect the 'Apply' buttons from the Preferences/File Associations
  815. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  816. lambda: self.on_register_files(obj_type='excellon'))
  817. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  818. lambda: self.on_register_files(obj_type='gcode'))
  819. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  820. lambda: self.on_register_files(obj_type='gerber'))
  821. # ###########################################################################################################
  822. # ########################################### KEYWORDS SIGNALS ##############################################
  823. # ###########################################################################################################
  824. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  825. lambda: self.restore_extensions(ext_type='keyword'))
  826. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  827. lambda: self.delete_all_extensions(ext_type='keyword'))
  828. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  829. lambda: self.add_extension(ext_type='keyword'))
  830. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  831. lambda: self.del_extension(ext_type='keyword'))
  832. # connect the abort_all_tasks related slots to the related signals
  833. self.proc_container.idle_flag.connect(self.app_is_idle)
  834. # signal emitted when a tab is closed in the Plot Area
  835. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  836. # signal to close the application
  837. self.close_app_signal.connect(self.kill_app)
  838. # ################################# FINISHED CONNECTING SIGNALS #############################################
  839. # ###########################################################################################################
  840. # ###########################################################################################################
  841. # ###########################################################################################################
  842. self.log.debug("Finished connecting Signals.")
  843. # ###########################################################################################################
  844. # ########################################## Other setups ###################################################
  845. # ###########################################################################################################
  846. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  847. # depending on from where those tools are called different actions can be done
  848. self.call_source = 'app'
  849. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  850. self.tool_tab_locked = False
  851. # decide if to show or hide the Notebook side of the screen at startup
  852. if self.defaults["global_project_at_startup"] is True:
  853. self.ui.splitter.setSizes([1, 1])
  854. else:
  855. self.ui.splitter.setSizes([0, 1])
  856. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  857. self.setup_component_editor()
  858. # ###########################################################################################################
  859. # ####################################### Auto-complete KEYWORDS ############################################
  860. # ###########################################################################################################
  861. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  862. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  863. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  864. 'export_exc',
  865. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  866. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  867. 'interiors', 'isolate', 'join_excellon',
  868. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  869. 'mirror', 'ncc',
  870. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  871. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  872. 'options', 'origin',
  873. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  874. 'save', 'save_project',
  875. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  876. 'skew', 'subtract_poly', 'subtract_rectangle',
  877. 'version', 'write_gcode'
  878. ]
  879. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  880. 'Paste_1',
  881. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  882. 'Toolchange_manual', 'True', 'Users',
  883. 'all', 'auto', 'axis',
  884. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  885. 'contour', 'default',
  886. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  887. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  888. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  889. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  890. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  891. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  892. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  893. 'spacing_columns',
  894. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  895. 'toolchange_xy', 'toolchangez', 'travelz',
  896. 'tooldia', 'use_threads', 'value',
  897. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  898. ]
  899. self.tcl_keywords = [
  900. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  901. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  902. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  903. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  904. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  905. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  906. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  907. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  908. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  909. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  910. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  911. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  912. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  913. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  914. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  915. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  916. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  917. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  918. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  919. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  920. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  921. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  922. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  923. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  924. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  925. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  926. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  927. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  928. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  929. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  930. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  931. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  932. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  933. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  934. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  935. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  936. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  937. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  938. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  939. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  940. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  941. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  942. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  943. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  944. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  945. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  946. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  947. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  948. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  949. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  950. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  951. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  952. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  953. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  954. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  955. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  956. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  957. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  958. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  959. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  960. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  961. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  962. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  963. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  964. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  965. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  966. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  967. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  968. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  969. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  970. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  971. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  972. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  973. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  974. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  975. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  976. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  977. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  978. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  979. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  980. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  981. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  982. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  983. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  984. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  985. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  986. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  987. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  988. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  989. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  990. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  991. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  992. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  993. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  994. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  995. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  996. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  997. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  998. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  999. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1000. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1001. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1002. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1003. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1004. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1005. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1006. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1007. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1008. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1009. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1010. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1011. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1012. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1013. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1014. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1015. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1016. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1017. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1018. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1019. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1020. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1021. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1022. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1023. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1024. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1025. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1026. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1027. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1028. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1029. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1030. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1031. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1032. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1033. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1034. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1035. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1036. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1037. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1038. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1039. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1040. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1041. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1042. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1043. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1044. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1045. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1046. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1047. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1048. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1049. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1050. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1051. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1052. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1053. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1054. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1055. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1056. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1057. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1058. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1059. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1060. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1061. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1062. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1063. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1064. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1065. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1066. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1067. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1068. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1069. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1070. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1071. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1072. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1073. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1074. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1075. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1076. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1077. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1078. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1079. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1080. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1081. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1082. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1083. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1084. ]
  1085. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1086. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1087. # ###########################################################################################################
  1088. # ############################################## Shell SETUP ################################################
  1089. # ###########################################################################################################
  1090. self.shell = FCShell(app=self, version=self.version)
  1091. self.ui.shell_dock.setWidget(self.shell)
  1092. self.log.debug("TCL Shell has been initialized.")
  1093. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1094. if self.defaults["global_shell_at_startup"]:
  1095. self.ui.shell_dock.show()
  1096. else:
  1097. self.ui.shell_dock.hide()
  1098. # ###########################################################################################################
  1099. # ########################################## Tools and Plugins ##############################################
  1100. # ###########################################################################################################
  1101. self.dblsidedtool = None
  1102. self.distance_tool = None
  1103. self.distance_min_tool = None
  1104. self.panelize_tool = None
  1105. self.film_tool = None
  1106. self.paste_tool = None
  1107. self.calculator_tool = None
  1108. self.rules_tool = None
  1109. self.sub_tool = None
  1110. self.move_tool = None
  1111. self.cutout_tool = None
  1112. self.ncclear_tool = None
  1113. self.optimal_tool = None
  1114. self.paint_tool = None
  1115. self.transform_tool = None
  1116. self.properties_tool = None
  1117. self.pdf_tool = None
  1118. self.image_tool = None
  1119. self.pcb_wizard_tool = None
  1120. self.cal_exc_tool = None
  1121. self.qrcode_tool = None
  1122. self.copper_thieving_tool = None
  1123. self.fiducial_tool = None
  1124. self.edrills_tool = None
  1125. self.align_objects_tool = None
  1126. self.punch_tool = None
  1127. self.invert_tool = None
  1128. self.corners_tool = None
  1129. self.etch_tool = None
  1130. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1131. try:
  1132. self.install_tools()
  1133. except AttributeError as e:
  1134. log.debug("App.__init__() install tools() --> %s" % str(e))
  1135. # ###########################################################################################################
  1136. # ############################################ SETUP RECENT ITEMS ###########################################
  1137. # ###########################################################################################################
  1138. self.setup_recent_items()
  1139. # ###########################################################################################################
  1140. # ######################################### BookMarks Manager ###############################################
  1141. # ###########################################################################################################
  1142. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1143. self.install_bookmarks()
  1144. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1145. # ###########################################################################################################
  1146. # ########################################### Tools Database ################################################
  1147. # ###########################################################################################################
  1148. self.tools_db_tab = None
  1149. # ### System Font Parsing ###
  1150. # self.f_parse = ParseFont(self)
  1151. # self.parse_system_fonts()
  1152. # ###########################################################################################################
  1153. # ######################################### Check for updates ###############################################
  1154. # ###########################################################################################################
  1155. # Separate thread (Not worker)
  1156. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1157. if (self.beta is False or self.beta is None) and \
  1158. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1159. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1160. # self.thr2 = QtCore.QThread()
  1161. self.worker_task.emit({'fcn': self.version_check,
  1162. 'params': []})
  1163. # self.thr2.start(QtCore.QThread.LowPriority)
  1164. # ###########################################################################################################
  1165. # ##################################### Register files with FlatCAM; #######################################
  1166. # ################################### It works only for Windows for now ####################################
  1167. # ###########################################################################################################
  1168. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1169. self.on_register_files()
  1170. # ###########################################################################################################
  1171. # ######################################## Variables for global usage #######################################
  1172. # ###########################################################################################################
  1173. # hold the App units
  1174. self.units = 'MM'
  1175. # coordinates for relative position display
  1176. self.rel_point1 = (0, 0)
  1177. self.rel_point2 = (0, 0)
  1178. # variable to store coordinates
  1179. self.pos = (0, 0)
  1180. self.pos_canvas = (0, 0)
  1181. self.pos_jump = (0, 0)
  1182. # variable to store mouse coordinates
  1183. self.mouse = [0, 0]
  1184. # variable to store the delta positions on cavnas
  1185. self.dx = 0
  1186. self.dy = 0
  1187. # decide if we have a double click or single click
  1188. self.doubleclick = False
  1189. # store here the is_dragging value
  1190. self.event_is_dragging = False
  1191. # variable to store if a command is active (then the var is not None) and which one it is
  1192. self.command_active = None
  1193. # variable to store the status of moving selection action
  1194. # None value means that it's not an selection action
  1195. # True value = a selection from left to right
  1196. # False value = a selection from right to left
  1197. self.selection_type = None
  1198. # List to store the objects that are currently loaded in FlatCAM
  1199. # This list is updated on each object creation or object delete
  1200. self.all_objects_list = []
  1201. self.objects_under_the_click_list = []
  1202. # List to store the objects that are selected
  1203. self.sel_objects_list = []
  1204. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1205. self.key_modifiers = None
  1206. # Variable to hold the status of the axis
  1207. self.toggle_axis = True
  1208. # Variable to hold the status of the grid lines
  1209. self.toggle_grid_lines = True
  1210. # Variable to store the status of the code editor
  1211. self.toggle_codeeditor = False
  1212. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1213. self.click_noproject = False
  1214. self.cursor = None
  1215. # Variable to store the GCODE that was edited
  1216. self.gcode_edited = ""
  1217. self.text_editor_tab = None
  1218. # reference for the self.ui.code_editor
  1219. self.reference_code_editor = None
  1220. self.script_code = ''
  1221. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1222. self.tools_db_changed_flag = False
  1223. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1224. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1225. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1226. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1227. 'tsm']
  1228. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1229. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1230. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1231. 'sbp', 'tap', 'xpi']
  1232. self.svg_list = ['svg']
  1233. self.dxf_list = ['dxf']
  1234. self.pdf_list = ['pdf']
  1235. self.prj_list = ['flatprj']
  1236. self.conf_list = ['flatconfig']
  1237. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1238. # flag for polygons not cleared
  1239. self.poly_not_cleared = False
  1240. # VisPy visuals
  1241. self.isHovering = False
  1242. self.notHovering = True
  1243. # Window geometry
  1244. self.x_pos = None
  1245. self.y_pos = None
  1246. self.width = None
  1247. self.height = None
  1248. # when True, the app has to return from any thread
  1249. self.abort_flag = False
  1250. # set the value used in the Windows Title
  1251. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1252. # this holds a widget that is installed in the Plot Area when View Source option is used
  1253. self.source_editor_tab = None
  1254. self.pagesize = {}
  1255. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1256. # VisPy visuals
  1257. if self.is_legacy is False:
  1258. try:
  1259. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1260. except AttributeError:
  1261. self.tool_shapes = None
  1262. else:
  1263. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1264. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1265. # used in the delayed shutdown self.start_delayed_quit() method
  1266. self.save_timer = None
  1267. # ###########################################################################################################
  1268. # ################################## ADDING FlatCAM EDITORS section #########################################
  1269. # ###########################################################################################################
  1270. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1271. # at the first launch of the App , the editors will not be functional.
  1272. try:
  1273. self.geo_editor = FlatCAMGeoEditor(self)
  1274. except AttributeError:
  1275. pass
  1276. try:
  1277. self.exc_editor = FlatCAMExcEditor(self)
  1278. except AttributeError:
  1279. pass
  1280. try:
  1281. self.grb_editor = FlatCAMGrbEditor(self)
  1282. except AttributeError:
  1283. pass
  1284. self.log.debug("Finished adding FlatCAM Editor's.")
  1285. self.set_ui_title(name=_("New Project - Not saved"))
  1286. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1287. current_platform = platform.architecture()[0]
  1288. if current_platform != '64bit':
  1289. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1290. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1291. # ###########################################################################################################
  1292. # ########################################### EXCLUSION AREAS ###############################################
  1293. # ###########################################################################################################
  1294. self.exc_areas = ExclusionAreas(app=self)
  1295. # ###########################################################################################################
  1296. # ##################################### Finished the CONSTRUCTOR ############################################
  1297. # ###########################################################################################################
  1298. App.log.debug("END of constructor. Releasing control.")
  1299. # ###########################################################################################################
  1300. # ########################################## SHOW GUI #######################################################
  1301. # ###########################################################################################################
  1302. # if the app is not started as headless, show it
  1303. if self.cmd_line_headless != 1:
  1304. if show_splash:
  1305. # finish the splash
  1306. self.splash.finish(self.ui)
  1307. mgui_settings = QSettings("Open Source", "FlatCAM")
  1308. if mgui_settings.contains("maximized_gui"):
  1309. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1310. if maximized_ui is True:
  1311. self.ui.showMaximized()
  1312. else:
  1313. self.ui.show()
  1314. else:
  1315. self.ui.show()
  1316. if self.defaults["global_systray_icon"]:
  1317. self.trayIcon.show()
  1318. else:
  1319. log.warning("******************* RUNNING HEADLESS *******************")
  1320. # ###########################################################################################################
  1321. # ######################################## START-UP ARGUMENTS ###############################################
  1322. # ###########################################################################################################
  1323. # test if the program was started with a script as parameter
  1324. if self.cmd_line_shellvar:
  1325. try:
  1326. cnt = 0
  1327. command_tcl = 0
  1328. for i in self.cmd_line_shellvar.split(','):
  1329. if i is not None:
  1330. # noinspection PyBroadException
  1331. try:
  1332. command_tcl = eval(i)
  1333. except Exception:
  1334. command_tcl = i
  1335. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1336. cnt += 1
  1337. # if there are Windows paths then replace the path separator with a Unix like one
  1338. if sys.platform == 'win32':
  1339. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1340. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1341. except Exception as ext:
  1342. print("ERROR: ", ext)
  1343. sys.exit(2)
  1344. if self.cmd_line_shellfile:
  1345. if self.cmd_line_headless != 1:
  1346. if self.ui.shell_dock.isHidden():
  1347. self.ui.shell_dock.show()
  1348. try:
  1349. with open(self.cmd_line_shellfile, "r") as myfile:
  1350. # if show_splash:
  1351. # self.splash.showMessage('%s: %ssec\n%s' % (
  1352. # _("Canvas initialization started.\n"
  1353. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1354. # _("Executing Tcl Script ...")),
  1355. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1356. # color=QtGui.QColor("gray"))
  1357. cmd_line_shellfile_text = myfile.read()
  1358. if self.cmd_line_headless != 1:
  1359. self.shell.exec_command(cmd_line_shellfile_text)
  1360. else:
  1361. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1362. except Exception as ext:
  1363. print("ERROR: ", ext)
  1364. sys.exit(2)
  1365. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1366. # the path/file_name must be enclosed in quotes if it contain spaces
  1367. if App.args:
  1368. self.args_at_startup.emit(App.args)
  1369. if self.defaults.old_defaults_found is True:
  1370. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1371. "Please reboot the application to update."))
  1372. self.defaults.old_defaults_found = False
  1373. # ######################################### INIT FINISHED #######################################################
  1374. # #################################################################################################################
  1375. # #################################################################################################################
  1376. # #################################################################################################################
  1377. # #################################################################################################################
  1378. # #################################################################################################################
  1379. @staticmethod
  1380. def copy_and_overwrite(from_path, to_path):
  1381. """
  1382. From here:
  1383. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1384. :param from_path: source path
  1385. :param to_path: destination path
  1386. :return: None
  1387. """
  1388. if os.path.exists(to_path):
  1389. shutil.rmtree(to_path)
  1390. try:
  1391. shutil.copytree(from_path, to_path)
  1392. except FileNotFoundError:
  1393. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1394. shutil.copytree(from_new_path, to_path)
  1395. def on_startup_args(self, args, silent=False):
  1396. """
  1397. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1398. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1399. :param args: a list containing the application args at startup
  1400. :return: None
  1401. """
  1402. if args is not None:
  1403. args_to_process = args
  1404. else:
  1405. args_to_process = App.args
  1406. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1407. for argument in args_to_process:
  1408. if '.FlatPrj'.lower() in argument.lower():
  1409. try:
  1410. project_name = str(argument)
  1411. if project_name == "":
  1412. if silent is False:
  1413. self.inform.emit(_("Cancelled."))
  1414. else:
  1415. # self.open_project(project_name)
  1416. run_from_arg = True
  1417. # self.worker_task.emit({'fcn': self.open_project,
  1418. # 'params': [project_name, run_from_arg]})
  1419. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1420. except Exception as e:
  1421. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1422. elif '.FlatConfig'.lower() in argument.lower():
  1423. try:
  1424. file_name = str(argument)
  1425. if file_name == "":
  1426. if silent is False:
  1427. self.inform.emit(_("Open Config file failed."))
  1428. else:
  1429. run_from_arg = True
  1430. # self.worker_task.emit({'fcn': self.open_config_file,
  1431. # 'params': [file_name, run_from_arg]})
  1432. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1433. except Exception as e:
  1434. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1435. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1436. try:
  1437. file_name = str(argument)
  1438. if file_name == "":
  1439. if silent is False:
  1440. self.inform.emit(_("Open Script file failed."))
  1441. else:
  1442. if silent is False:
  1443. self.on_fileopenscript(name=file_name)
  1444. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1445. self.on_filerunscript(name=file_name)
  1446. except Exception as e:
  1447. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1448. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1449. log.debug("App.on_startup_args() --> Quit event.")
  1450. sys.exit()
  1451. elif 'save'.lower() in argument.lower():
  1452. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1453. self.preferencesUiManager.save_defaults()
  1454. else:
  1455. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1456. proc_arg = argument.lower()
  1457. for ext in exc_list:
  1458. proc_ext = ext.replace(' ', '')
  1459. proc_ext = '.%s' % proc_ext
  1460. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1461. file_name = str(argument)
  1462. if file_name == "":
  1463. if silent is False:
  1464. self.inform.emit(_("Open Excellon file failed."))
  1465. else:
  1466. self.on_fileopenexcellon(name=file_name, signal=None)
  1467. return
  1468. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1469. for ext in gco_list:
  1470. proc_ext = ext.replace(' ', '')
  1471. proc_ext = '.%s' % proc_ext
  1472. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1473. file_name = str(argument)
  1474. if file_name == "":
  1475. if silent is False:
  1476. self.inform.emit(_("Open GCode file failed."))
  1477. else:
  1478. self.on_fileopengcode(name=file_name, signal=None)
  1479. return
  1480. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1481. for ext in grb_list:
  1482. proc_ext = ext.replace(' ', '')
  1483. proc_ext = '.%s' % proc_ext
  1484. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1485. file_name = str(argument)
  1486. if file_name == "":
  1487. if silent is False:
  1488. self.inform.emit(_("Open Gerber file failed."))
  1489. else:
  1490. self.on_fileopengerber(name=file_name, signal=None)
  1491. return
  1492. # if it reached here without already returning then the app was registered with a file that it does not
  1493. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1494. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1495. # for arg in args_to_process:
  1496. # if 'FlatCAM.exe' in arg:
  1497. # continue
  1498. # else:
  1499. # sys.exit(2)
  1500. def set_ui_title(self, name):
  1501. """
  1502. Sets the title of the main window.
  1503. :param name: String that store the project path and project name
  1504. :return: None
  1505. """
  1506. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1507. (self.version,
  1508. ('BETA' if self.beta else ''),
  1509. platform.architecture()[0],
  1510. self.engine,
  1511. name)
  1512. )
  1513. def on_app_restart(self):
  1514. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1515. # be left in the SySTray
  1516. try:
  1517. self.trayIcon.hide()
  1518. except Exception:
  1519. pass
  1520. fcTranslate.restart_program(app=self)
  1521. def clear_pool(self):
  1522. """
  1523. Clear the multiprocessing pool and calls garbage collector.
  1524. :return: None
  1525. """
  1526. self.pool.close()
  1527. self.pool = Pool()
  1528. self.pool_recreated.emit(self.pool)
  1529. gc.collect()
  1530. def install_tools(self):
  1531. """
  1532. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1533. Instantiation of the Tools classes.
  1534. The order that the tools are installed is important as they can depend on each other install position.
  1535. :return: None
  1536. """
  1537. self.distance_tool = Distance(self)
  1538. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1539. before=self.ui.menueditorigin,
  1540. separator=False)
  1541. self.distance_min_tool = DistanceMin(self)
  1542. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1543. pos=self.ui.menuedit,
  1544. before=self.ui.menueditorigin,
  1545. separator=True)
  1546. self.dblsidedtool = DblSidedTool(self)
  1547. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1548. self.cal_exc_tool = ToolCalibration(self)
  1549. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1550. before=self.dblsidedtool.menuAction,
  1551. separator=False)
  1552. self.align_objects_tool = AlignObjects(self)
  1553. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1554. self.edrills_tool = ToolExtractDrills(self)
  1555. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1556. self.panelize_tool = Panelize(self)
  1557. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1558. self.film_tool = Film(self)
  1559. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1560. self.paste_tool = SolderPaste(self)
  1561. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1562. self.calculator_tool = ToolCalculator(self)
  1563. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1564. self.sub_tool = ToolSub(self)
  1565. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1566. pos=self.ui.menutool, separator=True)
  1567. self.rules_tool = RulesCheck(self)
  1568. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1569. pos=self.ui.menutool, separator=False)
  1570. self.optimal_tool = ToolOptimal(self)
  1571. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1572. pos=self.ui.menutool, separator=True)
  1573. self.move_tool = ToolMove(self)
  1574. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1575. before=self.ui.menueditorigin, separator=True)
  1576. self.cutout_tool = CutOut(self)
  1577. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1578. before=self.sub_tool.menuAction)
  1579. self.ncclear_tool = NonCopperClear(self)
  1580. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1581. before=self.sub_tool.menuAction, separator=True)
  1582. self.paint_tool = ToolPaint(self)
  1583. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1584. before=self.sub_tool.menuAction, separator=True)
  1585. self.copper_thieving_tool = ToolCopperThieving(self)
  1586. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1587. pos=self.ui.menutool)
  1588. self.fiducial_tool = ToolFiducials(self)
  1589. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1590. pos=self.ui.menutool)
  1591. self.qrcode_tool = QRCode(self)
  1592. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1593. pos=self.ui.menutool)
  1594. self.punch_tool = ToolPunchGerber(self)
  1595. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1596. self.invert_tool = ToolInvertGerber(self)
  1597. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1598. self.corners_tool = ToolCorners(self)
  1599. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1600. self.etch_tool = ToolEtchCompensation(self)
  1601. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etcg_32.png'), pos=self.ui.menutool)
  1602. self.transform_tool = ToolTransform(self)
  1603. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1604. pos=self.ui.menuoptions, separator=True)
  1605. self.properties_tool = Properties(self)
  1606. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1607. pos=self.ui.menuoptions)
  1608. self.pdf_tool = ToolPDF(self)
  1609. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1610. pos=self.ui.menufileimport,
  1611. separator=True)
  1612. self.image_tool = ToolImage(self)
  1613. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1614. pos=self.ui.menufileimport,
  1615. separator=True)
  1616. self.pcb_wizard_tool = PcbWizard(self)
  1617. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1618. pos=self.ui.menufileimport)
  1619. self.log.debug("Tools are installed.")
  1620. def remove_tools(self):
  1621. """
  1622. Will remove all the actions in the Tool menu.
  1623. :return: None
  1624. """
  1625. for act in self.ui.menutool.actions():
  1626. self.ui.menutool.removeAction(act)
  1627. def init_tools(self):
  1628. """
  1629. Initialize the Tool tab in the notebook side of the central widget.
  1630. Remove the actions in the Tools menu.
  1631. Instantiate again the FlatCAM tools (plugins).
  1632. All this is required when changing the layout: standard, compact etc.
  1633. :return: None
  1634. """
  1635. log.debug("init_tools()")
  1636. # delete the data currently in the Tools Tab and the Tab itself
  1637. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1638. if widget is not None:
  1639. widget.deleteLater()
  1640. self.ui.notebook.removeTab(2)
  1641. # rebuild the Tools Tab
  1642. self.ui.tool_tab = QtWidgets.QWidget()
  1643. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1644. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1645. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1646. self.ui.tool_scroll_area = VerticalScrollArea()
  1647. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1648. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1649. # first remove all of them
  1650. self.remove_tools()
  1651. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1652. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1653. '&Command Line\tS')
  1654. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1655. # third install all of them
  1656. try:
  1657. self.install_tools()
  1658. except AttributeError:
  1659. pass
  1660. self.log.debug("Tools are initialized.")
  1661. # def parse_system_fonts(self):
  1662. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1663. # 'params': []})
  1664. def connect_toolbar_signals(self):
  1665. """
  1666. Reconnect the signals to the actions in the toolbar.
  1667. This has to be done each time after the FlatCAM tools are removed/installed.
  1668. :return: None
  1669. """
  1670. # Toolbar
  1671. # File Toolbar Signals
  1672. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1673. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1674. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1675. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1676. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1677. # View Toolbar Signals
  1678. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1679. self.ui.replot_btn.triggered.connect(self.plot_all)
  1680. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1681. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1682. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1683. # Edit Toolbar Signals
  1684. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1685. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1686. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1687. self.ui.delete_btn.triggered.connect(self.on_delete)
  1688. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1689. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1690. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1691. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1692. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1693. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1694. # Scripting Toolbar Signals
  1695. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1696. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1697. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1698. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1699. # Tools Toolbar Signals
  1700. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1701. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1702. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1703. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1704. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1705. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1706. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1707. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1708. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1709. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1710. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1711. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1712. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1713. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1714. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1715. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1716. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1717. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1718. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1719. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1720. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1721. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1722. def object2editor(self):
  1723. """
  1724. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1725. :return: None
  1726. """
  1727. self.defaults.report_usage("object2editor()")
  1728. # disable the objects menu as it may interfere with the AppEditors
  1729. self.ui.menuobjects.setDisabled(True)
  1730. edited_object = self.collection.get_active()
  1731. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1732. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1733. pass
  1734. else:
  1735. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1736. return
  1737. if isinstance(edited_object, GeometryObject):
  1738. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1739. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1740. # we set the notebook to hidden
  1741. # self.ui.splitter.setSizes([0, 1])
  1742. if edited_object.multigeo is True:
  1743. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1744. if len(sel_rows) > 1:
  1745. self.inform.emit('[WARNING_NOTCL] %s' %
  1746. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1747. "is not possible.\n"
  1748. "Edit only one geometry at a time."))
  1749. # determine the tool dia of the selected tool
  1750. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1751. # now find the key in the edited_object.tools that has this tooldia
  1752. multi_tool = 1
  1753. for tool in edited_object.tools:
  1754. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1755. multi_tool = tool
  1756. break
  1757. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1758. else:
  1759. self.geo_editor.edit_fcgeometry(edited_object)
  1760. # set call source to the Editor we go into
  1761. self.call_source = 'geo_editor'
  1762. elif isinstance(edited_object, ExcellonObject):
  1763. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1764. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1765. if self.ui.splitter.sizes()[0] == 0:
  1766. self.ui.splitter.setSizes([1, 1])
  1767. self.exc_editor.edit_fcexcellon(edited_object)
  1768. # set call source to the Editor we go into
  1769. self.call_source = 'exc_editor'
  1770. elif isinstance(edited_object, GerberObject):
  1771. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1772. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1773. if self.ui.splitter.sizes()[0] == 0:
  1774. self.ui.splitter.setSizes([1, 1])
  1775. self.grb_editor.edit_fcgerber(edited_object)
  1776. # set call source to the Editor we go into
  1777. self.call_source = 'grb_editor'
  1778. # reset the following variables so the UI is built again after edit
  1779. edited_object.ui_build = False
  1780. edited_object.build_aperture_storage = False
  1781. elif isinstance(edited_object, CNCJobObject):
  1782. if self.ui.splitter.sizes()[0] == 0:
  1783. self.ui.splitter.setSizes([1, 1])
  1784. edited_object.on_edit_code_click()
  1785. return
  1786. # make sure that we can't select another object while in Editor Mode:
  1787. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1788. self.ui.project_frame.setDisabled(True)
  1789. # delete any selection shape that might be active as they are not relevant in Editor
  1790. self.delete_selection_shape()
  1791. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1792. self.ui.plot_tab_area.protectTab(0)
  1793. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1794. self.should_we_save = True
  1795. def editor2object(self, cleanup=None):
  1796. """
  1797. Transfers the Geometry or Excellon from it's editor to the current object.
  1798. :return: None
  1799. """
  1800. self.defaults.report_usage("editor2object()")
  1801. # re-enable the objects menu that was disabled on entry in Editor mode
  1802. self.ui.menuobjects.setDisabled(False)
  1803. # do not update a geometry or excellon object unless it comes out of an editor
  1804. if self.call_source != 'app':
  1805. edited_obj = self.collection.get_active()
  1806. if cleanup is None:
  1807. msgbox = QtWidgets.QMessageBox()
  1808. msgbox.setText(_("Do you want to save the edited object?"))
  1809. msgbox.setWindowTitle(_("Close Editor"))
  1810. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1811. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1812. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1813. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1814. msgbox.setDefaultButton(bt_yes)
  1815. msgbox.exec_()
  1816. response = msgbox.clickedButton()
  1817. if response == bt_yes:
  1818. # clean the Tools Tab
  1819. self.ui.tool_scroll_area.takeWidget()
  1820. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1821. self.ui.notebook.setTabText(2, "Tool")
  1822. if isinstance(edited_obj, GeometryObject):
  1823. obj_type = "Geometry"
  1824. if cleanup is None:
  1825. self.geo_editor.update_fcgeometry(edited_obj)
  1826. # self.geo_editor.update_options(edited_obj)
  1827. self.geo_editor.deactivate()
  1828. # restore GUI to the Selected TAB
  1829. # Remove anything else in the AppGUI
  1830. self.ui.tool_scroll_area.takeWidget()
  1831. # update the geo object options so it is including the bounding box values
  1832. try:
  1833. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1834. edited_obj.options['xmin'] = xmin
  1835. edited_obj.options['ymin'] = ymin
  1836. edited_obj.options['xmax'] = xmax
  1837. edited_obj.options['ymax'] = ymax
  1838. except AttributeError as e:
  1839. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1840. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1841. edited_obj.build_ui()
  1842. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1843. elif isinstance(edited_obj, GerberObject):
  1844. obj_type = "Gerber"
  1845. if cleanup is None:
  1846. self.grb_editor.update_fcgerber()
  1847. self.grb_editor.update_options(edited_obj)
  1848. self.grb_editor.deactivate_grb_editor()
  1849. # delete the old object (the source object) if it was an empty one
  1850. try:
  1851. if len(edited_obj.solid_geometry) == 0:
  1852. old_name = edited_obj.options['name']
  1853. self.collection.set_active(old_name)
  1854. self.collection.delete_active()
  1855. except TypeError:
  1856. # if the solid_geometry is a single Polygon the len() will not work
  1857. # in any case, falling here means that we have something in the solid_geometry, even if only
  1858. # a single Polygon, therefore we pass this
  1859. pass
  1860. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1861. # restore GUI to the Selected TAB
  1862. # Remove anything else in the AppGUI
  1863. self.ui.selected_scroll_area.takeWidget()
  1864. elif isinstance(edited_obj, ExcellonObject):
  1865. obj_type = "Excellon"
  1866. if cleanup is None:
  1867. self.exc_editor.update_fcexcellon(edited_obj)
  1868. # self.exc_editor.update_options(edited_obj)
  1869. self.exc_editor.deactivate()
  1870. # restore GUI to the Selected TAB
  1871. # Remove anything else in the AppGUI
  1872. self.ui.tool_scroll_area.takeWidget()
  1873. # delete the old object (the source object) if it was an empty one
  1874. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1875. old_name = edited_obj.options['name']
  1876. self.collection.delete_by_name(name=old_name)
  1877. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1878. else:
  1879. self.inform.emit('[WARNING_NOTCL] %s' %
  1880. _("Select a Gerber, Geometry or Excellon Object to update."))
  1881. return
  1882. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1883. elif response == bt_no:
  1884. # clean the Tools Tab
  1885. self.ui.tool_scroll_area.takeWidget()
  1886. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1887. self.ui.notebook.setTabText(2, "Tool")
  1888. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1889. if isinstance(edited_obj, GeometryObject):
  1890. self.geo_editor.deactivate()
  1891. edited_obj.build_ui()
  1892. elif isinstance(edited_obj, GerberObject):
  1893. self.grb_editor.deactivate_grb_editor()
  1894. edited_obj.build_ui()
  1895. elif isinstance(edited_obj, ExcellonObject):
  1896. self.exc_editor.deactivate()
  1897. edited_obj.build_ui()
  1898. else:
  1899. self.inform.emit('[WARNING_NOTCL] %s' %
  1900. _("Select a Gerber, Geometry or Excellon Object to update."))
  1901. return
  1902. elif response == bt_cancel:
  1903. return
  1904. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1905. # edited_obj.build_ui()
  1906. # Switch notebook to Selected page
  1907. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1908. else:
  1909. if isinstance(edited_obj, GeometryObject):
  1910. self.geo_editor.deactivate()
  1911. elif isinstance(edited_obj, GerberObject):
  1912. self.grb_editor.deactivate_grb_editor()
  1913. elif isinstance(edited_obj, ExcellonObject):
  1914. self.exc_editor.deactivate()
  1915. else:
  1916. self.inform.emit('[WARNING_NOTCL] %s' %
  1917. _("Select a Gerber, Geometry or Excellon Object to update."))
  1918. return
  1919. # if notebook is hidden we show it
  1920. if self.ui.splitter.sizes()[0] == 0:
  1921. self.ui.splitter.setSizes([1, 1])
  1922. # restore the call_source to app
  1923. self.call_source = 'app'
  1924. edited_obj.plot()
  1925. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1926. self.ui.plot_tab_area.protectTab(0)
  1927. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1928. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1929. self.ui.project_frame.setDisabled(False)
  1930. def get_last_folder(self):
  1931. """
  1932. Get the folder path from where the last file was opened.
  1933. :return: String, last opened folder path
  1934. """
  1935. return self.defaults["global_last_folder"]
  1936. def get_last_save_folder(self):
  1937. """
  1938. Get the folder path from where the last file was saved.
  1939. :return: String, last saved folder path
  1940. """
  1941. loc = self.defaults["global_last_save_folder"]
  1942. if loc is None:
  1943. loc = self.defaults["global_last_folder"]
  1944. if loc is None:
  1945. loc = os.path.dirname(__file__)
  1946. return loc
  1947. def info(self, msg):
  1948. """
  1949. Informs the user. Normally on the status bar, optionally
  1950. also on the shell.
  1951. :param msg: Text to write.
  1952. :return: None
  1953. """
  1954. # Type of message in brackets at the beginning of the message.
  1955. match = re.search(r"\[(.*)\](.*)", msg)
  1956. if match:
  1957. level = match.group(1)
  1958. msg_ = match.group(2)
  1959. self.ui.fcinfo.set_status(str(msg_), level=level)
  1960. if level.lower() == "error":
  1961. self.shell_message(msg, error=True, show=True)
  1962. elif level.lower() == "warning":
  1963. self.shell_message(msg, warning=True, show=True)
  1964. elif level.lower() == "error_notcl":
  1965. self.shell_message(msg, error=True, show=False)
  1966. elif level.lower() == "warning_notcl":
  1967. self.shell_message(msg, warning=True, show=False)
  1968. elif level.lower() == "success":
  1969. self.shell_message(msg, success=True, show=False)
  1970. elif level.lower() == "selected":
  1971. self.shell_message(msg, selected=True, show=False)
  1972. else:
  1973. self.shell_message(msg, show=False)
  1974. else:
  1975. self.ui.fcinfo.set_status(str(msg), level="info")
  1976. # make sure that if the message is to clear the infobar with a space
  1977. # is not printed over and over on the shell
  1978. if msg != '':
  1979. self.shell_message(msg)
  1980. def on_import_preferences(self):
  1981. """
  1982. Loads the application default settings from a saved file into
  1983. ``self.defaults`` dictionary.
  1984. :return: None
  1985. """
  1986. self.defaults.report_usage("on_import_preferences")
  1987. App.log.debug("App.on_import_preferences()")
  1988. # Show file chooser
  1989. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1990. try:
  1991. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1992. directory=self.data_path,
  1993. filter=filter_)
  1994. except TypeError:
  1995. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1996. filter=filter_)
  1997. filename = str(filename)
  1998. if filename == "":
  1999. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2000. return
  2001. # Load in the defaults from the chosen file
  2002. self.defaults.load(filename=filename)
  2003. self.preferencesUiManager.on_preferences_edited()
  2004. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2005. def on_export_preferences(self):
  2006. """
  2007. Save the defaults dictionary to a file.
  2008. :return: None
  2009. """
  2010. self.defaults.report_usage("on_export_preferences")
  2011. App.log.debug("on_export_preferences()")
  2012. # defaults_file_content = None
  2013. # Show file chooser
  2014. date = str(datetime.today()).rpartition('.')[0]
  2015. date = ''.join(c for c in date if c not in ':-')
  2016. date = date.replace(' ', '_')
  2017. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2018. try:
  2019. filename, _f = FCFileSaveDialog.get_saved_filename(
  2020. caption=_("Export FlatCAM Preferences"),
  2021. directory=self.data_path + '/preferences_' + date,
  2022. filter=filter__
  2023. )
  2024. except TypeError:
  2025. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2026. filename = str(filename)
  2027. if filename == "":
  2028. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2029. return
  2030. # Update options
  2031. self.preferencesUiManager.defaults_read_form()
  2032. self.defaults.propagate_defaults()
  2033. # Save update options
  2034. try:
  2035. self.defaults.write(filename=filename)
  2036. except Exception:
  2037. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2038. return
  2039. if self.defaults["global_open_style"] is False:
  2040. self.file_opened.emit("preferences", filename)
  2041. self.file_saved.emit("preferences", filename)
  2042. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2043. def save_to_file(self, content_to_save, txt_content):
  2044. """
  2045. Save something to a file.
  2046. :return: None
  2047. """
  2048. self.defaults.report_usage("save_to_file")
  2049. App.log.debug("save_to_file()")
  2050. self.date = str(datetime.today()).rpartition('.')[0]
  2051. self.date = ''.join(c for c in self.date if c not in ':-')
  2052. self.date = self.date.replace(' ', '_')
  2053. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2054. path_to_save = self.defaults["global_last_save_folder"] if \
  2055. self.defaults["global_last_save_folder"] is not None else self.data_path
  2056. try:
  2057. filename, _f = FCFileSaveDialog.get_saved_filename(
  2058. caption=_("Save to file"),
  2059. directory=path_to_save + '/file_' + self.date,
  2060. filter=filter__
  2061. )
  2062. except TypeError:
  2063. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2064. filename = str(filename)
  2065. if filename == "":
  2066. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2067. return
  2068. else:
  2069. try:
  2070. with open(filename, 'w') as f:
  2071. ___ = f.read()
  2072. except PermissionError:
  2073. self.inform.emit('[WARNING] %s' %
  2074. _("Permission denied, saving not possible.\n"
  2075. "Most likely another app is holding the file open and not accessible."))
  2076. return
  2077. except IOError:
  2078. App.log.debug('Creating a new file ...')
  2079. f = open(filename, 'w')
  2080. f.close()
  2081. except Exception:
  2082. e = sys.exc_info()[0]
  2083. App.log.error("Could not load the file.")
  2084. App.log.error(str(e))
  2085. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2086. return
  2087. # Save content
  2088. if filename.rpartition('.')[2].lower() == 'html':
  2089. file_content = content_to_save
  2090. else:
  2091. file_content = txt_content
  2092. try:
  2093. with open(filename, "w") as f:
  2094. f.write(file_content)
  2095. except Exception:
  2096. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2097. return
  2098. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2099. def save_geometry(self, x, y, width, height, notebook_width):
  2100. """
  2101. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2102. launch of the application.
  2103. :param x: X position of the main window
  2104. :param y: Y position of the main window
  2105. :param width: width of the main window
  2106. :param height: height of the main window
  2107. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2108. :return: None
  2109. """
  2110. self.defaults["global_def_win_x"] = x
  2111. self.defaults["global_def_win_y"] = y
  2112. self.defaults["global_def_win_w"] = width
  2113. self.defaults["global_def_win_h"] = height
  2114. self.defaults["global_def_notebook_width"] = notebook_width
  2115. self.preferencesUiManager.save_defaults()
  2116. def register_recent(self, kind, filename):
  2117. """
  2118. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2119. dictionary.
  2120. :param kind: type of file that was opened
  2121. :param filename: the path and file name for the file that was opened
  2122. :return:
  2123. """
  2124. self.log.debug("register_recent()")
  2125. self.log.debug(" %s" % kind)
  2126. self.log.debug(" %s" % filename)
  2127. record = {'kind': str(kind), 'filename': str(filename)}
  2128. if record in self.recent:
  2129. return
  2130. if record in self.recent_projects:
  2131. return
  2132. if record['kind'] == 'project':
  2133. self.recent_projects.insert(0, record)
  2134. else:
  2135. self.recent.insert(0, record)
  2136. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2137. self.recent.pop()
  2138. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2139. self.recent_projects.pop()
  2140. try:
  2141. f = open(self.data_path + '/recent.json', 'w')
  2142. except IOError:
  2143. App.log.error("Failed to open recent items file for writing.")
  2144. self.inform.emit('[ERROR_NOTCL] %s' %
  2145. _('Failed to open recent files file for writing.'))
  2146. return
  2147. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2148. f.close()
  2149. try:
  2150. fp = open(self.data_path + '/recent_projects.json', 'w')
  2151. except IOError:
  2152. App.log.error("Failed to open recent items file for writing.")
  2153. self.inform.emit('[ERROR_NOTCL] %s' %
  2154. _('Failed to open recent projects file for writing.'))
  2155. return
  2156. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2157. fp.close()
  2158. # Re-build the recent items menu
  2159. self.setup_recent_items()
  2160. def on_about(self):
  2161. """
  2162. Displays the "about" dialog found in the Menu --> Help.
  2163. :return: None
  2164. """
  2165. self.defaults.report_usage("on_about")
  2166. version = self.version
  2167. version_date = self.version_date
  2168. beta = self.beta
  2169. class AboutDialog(QtWidgets.QDialog):
  2170. def __init__(self, app, parent=None):
  2171. QtWidgets.QDialog.__init__(self, parent)
  2172. self.app = app
  2173. # Icon and title
  2174. self.setWindowIcon(parent.app_icon)
  2175. self.setWindowTitle(_("About FlatCAM"))
  2176. self.resize(600, 200)
  2177. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2178. # self.setStyleSheet(
  2179. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2180. # "background-attachment: fixed"
  2181. # )
  2182. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2183. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2184. # palette = QtGui.QPalette()
  2185. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2186. # self.setPalette(palette)
  2187. logo = QtWidgets.QLabel()
  2188. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2189. title = QtWidgets.QLabel(
  2190. "<font size=8><B>FlatCAM</B></font><BR>"
  2191. "{title}<BR>"
  2192. "<BR>"
  2193. "<BR>"
  2194. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2195. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2196. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2197. "<B>{issue}</B></a><BR>".format(
  2198. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2199. devel=_("Development"),
  2200. down=_("DOWNLOAD"),
  2201. issue=_("Issue tracker"))
  2202. )
  2203. title.setOpenExternalLinks(True)
  2204. closebtn = QtWidgets.QPushButton(_("Close"))
  2205. tab_widget = QtWidgets.QTabWidget()
  2206. description_label = QtWidgets.QLabel(
  2207. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2208. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2209. version=version,
  2210. beta=('BETA' if beta else ''),
  2211. date=version_date,
  2212. arch=platform.architecture()[0])
  2213. )
  2214. description_label.setOpenExternalLinks(True)
  2215. lic_lbl_header = QtWidgets.QLabel(
  2216. '%s:<br>%s<br>' % (
  2217. _('Licensed under the MIT license'),
  2218. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2219. "http://www.opensource.org/licenses/mit-license.php</a>"
  2220. )
  2221. )
  2222. lic_lbl_header.setOpenExternalLinks(True)
  2223. lic_lbl_body = QtWidgets.QLabel(
  2224. _(
  2225. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2226. 'of this software and associated documentation files (the "Software"), to deal\n'
  2227. 'in the Software without restriction, including without limitation the rights\n'
  2228. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2229. 'copies of the Software, and to permit persons to whom the Software is\n'
  2230. 'furnished to do so, subject to the following conditions:\n\n'
  2231. 'The above copyright notice and this permission notice shall be included in\n'
  2232. 'all copies or substantial portions of the Software.\n\n'
  2233. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2234. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2235. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2236. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2237. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2238. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2239. 'THE SOFTWARE.'
  2240. )
  2241. )
  2242. attributions_label = QtWidgets.QLabel(
  2243. _(
  2244. 'Some of the icons used are from the following sources:<br>'
  2245. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2246. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2247. 'title="Flaticon">www.flaticon.com</a></div>'
  2248. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2249. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2250. )
  2251. )
  2252. attributions_label.setOpenExternalLinks(True)
  2253. # layouts
  2254. layout1 = QtWidgets.QVBoxLayout()
  2255. layout1_1 = QtWidgets.QHBoxLayout()
  2256. layout1_2 = QtWidgets.QHBoxLayout()
  2257. layout2 = QtWidgets.QHBoxLayout()
  2258. layout3 = QtWidgets.QHBoxLayout()
  2259. self.setLayout(layout1)
  2260. layout1.addLayout(layout1_1)
  2261. layout1.addLayout(layout1_2)
  2262. layout1.addLayout(layout2)
  2263. layout1.addLayout(layout3)
  2264. layout1_1.addStretch()
  2265. layout1_1.addWidget(description_label)
  2266. layout1_2.addWidget(tab_widget)
  2267. self.splash_tab = QtWidgets.QWidget()
  2268. self.splash_tab.setObjectName("splash_about")
  2269. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2270. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2271. tab_widget.addTab(self.splash_tab, _("Splash"))
  2272. self.programmmers_tab = QtWidgets.QWidget()
  2273. self.programmmers_tab.setObjectName("programmers_about")
  2274. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2275. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2276. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2277. self.translators_tab = QtWidgets.QWidget()
  2278. self.translators_tab.setObjectName("translators_about")
  2279. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2280. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2281. tab_widget.addTab(self.translators_tab, _("Translators"))
  2282. self.license_tab = QtWidgets.QWidget()
  2283. self.license_tab.setObjectName("license_about")
  2284. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2285. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2286. tab_widget.addTab(self.license_tab, _("License"))
  2287. self.attributions_tab = QtWidgets.QWidget()
  2288. self.attributions_tab.setObjectName("attributions_about")
  2289. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2290. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2291. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2292. self.splash_tab_layout.addWidget(logo, stretch=0)
  2293. self.splash_tab_layout.addWidget(title, stretch=1)
  2294. pal = QtGui.QPalette()
  2295. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2296. self.prog_grid_lay = QtWidgets.QGridLayout()
  2297. self.prog_grid_lay.setHorizontalSpacing(20)
  2298. self.prog_grid_lay.setColumnStretch(0, 0)
  2299. self.prog_grid_lay.setColumnStretch(2, 1)
  2300. prog_widget = QtWidgets.QWidget()
  2301. prog_widget.setLayout(self.prog_grid_lay)
  2302. prog_scroll = QtWidgets.QScrollArea()
  2303. prog_scroll.setWidget(prog_widget)
  2304. prog_scroll.setWidgetResizable(True)
  2305. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2306. prog_scroll.setPalette(pal)
  2307. self.programmmers_tab_layout.addWidget(prog_scroll)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2355. self.translator_grid_lay = QtWidgets.QGridLayout()
  2356. self.translator_grid_lay.setColumnStretch(0, 0)
  2357. self.translator_grid_lay.setColumnStretch(1, 0)
  2358. self.translator_grid_lay.setColumnStretch(2, 1)
  2359. self.translator_grid_lay.setColumnStretch(3, 0)
  2360. # trans_widget = QtWidgets.QWidget()
  2361. # trans_widget.setLayout(self.translator_grid_lay)
  2362. # self.translators_tab_layout.addWidget(trans_widget)
  2363. # self.translators_tab_layout.addStretch()
  2364. trans_widget = QtWidgets.QWidget()
  2365. trans_widget.setLayout(self.translator_grid_lay)
  2366. trans_scroll = QtWidgets.QScrollArea()
  2367. trans_scroll.setWidget(trans_widget)
  2368. trans_scroll.setWidgetResizable(True)
  2369. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2370. trans_scroll.setPalette(pal)
  2371. self.translators_tab_layout.addWidget(trans_scroll)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2401. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2403. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2404. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2405. self.translator_grid_lay.setColumnStretch(0, 0)
  2406. self.translators_tab_layout.addStretch()
  2407. self.license_tab_layout.addWidget(lic_lbl_header)
  2408. self.license_tab_layout.addWidget(lic_lbl_body)
  2409. self.license_tab_layout.addStretch()
  2410. self.attributions_tab_layout.addWidget(attributions_label)
  2411. self.attributions_tab_layout.addStretch()
  2412. layout3.addStretch()
  2413. layout3.addWidget(closebtn)
  2414. closebtn.clicked.connect(self.accept)
  2415. AboutDialog(app=self, parent=self.ui).exec_()
  2416. def install_bookmarks(self, book_dict=None):
  2417. """
  2418. Install the bookmarks actions in the Help menu -> Bookmarks
  2419. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2420. :return: None
  2421. """
  2422. if book_dict is None:
  2423. self.defaults["global_bookmarks"].update(
  2424. {
  2425. '1': ['FlatCAM', "http://flatcam.org"],
  2426. '2': ['Backup Site', ""]
  2427. }
  2428. )
  2429. else:
  2430. self.defaults["global_bookmarks"].clear()
  2431. self.defaults["global_bookmarks"].update(book_dict)
  2432. # first try to disconnect if somehow they get connected from elsewhere
  2433. for act in self.ui.menuhelp_bookmarks.actions():
  2434. try:
  2435. act.triggered.disconnect()
  2436. except TypeError:
  2437. pass
  2438. # clear all actions except the last one who is the Bookmark manager
  2439. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2440. pass
  2441. else:
  2442. self.ui.menuhelp_bookmarks.removeAction(act)
  2443. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2444. if self.defaults["global_bookmarks"]:
  2445. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2446. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2447. # the JSON is first making the keys as strings (therefore I have to use strings too
  2448. # or do the conversion :(
  2449. # )
  2450. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2451. # the '10' entry jsut after '1' therefore ordering as strings
  2452. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2453. key=lambda x: int(x[0]))
  2454. for entry, bookmark in sorted_bookmarks:
  2455. title = bookmark[0]
  2456. weblink = bookmark[1]
  2457. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2458. act.setText(title)
  2459. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2460. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2461. if title == 'Backup Site' and weblink == "":
  2462. act.triggered.connect(self.on_backup_site)
  2463. else:
  2464. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2465. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2466. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2467. def on_bookmarks_manager(self):
  2468. """
  2469. Adds the bookmark manager in a Tab in Plot Area
  2470. :return:
  2471. """
  2472. for idx in range(self.ui.plot_tab_area.count()):
  2473. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2474. # there can be only one instance of Bookmark Manager at one time
  2475. return
  2476. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2477. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2478. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2479. # add the tab if it was closed
  2480. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2481. # delete the absolute and relative position and messages in the infobar
  2482. self.ui.position_label.setText("")
  2483. # self.ui.rel_position_label.setText("")
  2484. # Switch plot_area to preferences page
  2485. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2486. def on_backup_site(self):
  2487. msgbox = QtWidgets.QMessageBox()
  2488. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2489. "1. FlatCAM.org website is down\n"
  2490. "2. Someone forked FlatCAM project and wants to point\n"
  2491. "to his own website\n\n"
  2492. "If you can't get any informations about FlatCAM beta\n"
  2493. "use the YouTube channel link from the Help menu."))
  2494. msgbox.setWindowTitle(_("Alternative website"))
  2495. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2496. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2497. msgbox.setDefaultButton(bt_yes)
  2498. msgbox.exec_()
  2499. # response = msgbox.clickedButton()
  2500. def on_file_savedefaults(self):
  2501. """
  2502. Callback for menu item File->Save Defaults. Saves application default options
  2503. ``self.defaults`` to current_defaults.FlatConfig.
  2504. :return: None
  2505. """
  2506. self.preferencesUiManager.save_defaults()
  2507. def final_save(self):
  2508. """
  2509. Callback for doing a preferences save to file whenever the application is about to quit.
  2510. If the project has changes, it will ask the user to save the project.
  2511. :return: None
  2512. """
  2513. if self.save_in_progress:
  2514. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2515. return
  2516. if self.should_we_save and self.collection.get_list():
  2517. msgbox = QtWidgets.QMessageBox()
  2518. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2519. "\n"
  2520. "Do you want to Save the project?"))
  2521. msgbox.setWindowTitle(_("Save changes"))
  2522. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2523. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2524. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2525. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2526. msgbox.setDefaultButton(bt_yes)
  2527. msgbox.exec_()
  2528. response = msgbox.clickedButton()
  2529. if response == bt_yes:
  2530. try:
  2531. self.trayIcon.hide()
  2532. except Exception:
  2533. pass
  2534. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2535. elif response == bt_no:
  2536. try:
  2537. self.trayIcon.hide()
  2538. except Exception:
  2539. pass
  2540. self.quit_application()
  2541. elif response == bt_cancel:
  2542. return
  2543. else:
  2544. try:
  2545. self.trayIcon.hide()
  2546. except Exception:
  2547. pass
  2548. self.quit_application()
  2549. def quit_application(self):
  2550. """
  2551. Called (as a pyslot or not) when the application is quit.
  2552. :return: None
  2553. """
  2554. self.preferencesUiManager.save_defaults(silent=True)
  2555. log.debug("App.quit_application() --> App Defaults saved.")
  2556. if self.cmd_line_headless != 1:
  2557. # save app state to file
  2558. stgs = QSettings("Open Source", "FlatCAM")
  2559. stgs.setValue('saved_gui_state', self.ui.saveState())
  2560. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2561. stgs.setValue(
  2562. 'language',
  2563. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2564. )
  2565. stgs.setValue(
  2566. 'notebook_font_size',
  2567. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2568. )
  2569. stgs.setValue(
  2570. 'axis_font_size',
  2571. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2572. )
  2573. stgs.setValue(
  2574. 'textbox_font_size',
  2575. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2576. )
  2577. stgs.setValue(
  2578. 'hud_font_size',
  2579. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2580. )
  2581. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2582. stgs.setValue(
  2583. 'machinist',
  2584. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2585. )
  2586. # This will write the setting to the platform specific storage.
  2587. del stgs
  2588. log.debug("App.quit_application() --> App UI state saved.")
  2589. # try to quit the Socket opened by ArgsThread class
  2590. try:
  2591. self.new_launch.stop.emit()
  2592. except Exception as err:
  2593. log.debug("App.quit_application() --> %s" % str(err))
  2594. # try to quit the QThread that run ArgsThread class
  2595. try:
  2596. self.th.quit()
  2597. except Exception as e:
  2598. log.debug("App.quit_application() --> %s" % str(e))
  2599. # terminate workers
  2600. self.workers.__del__()
  2601. # quit app by signalling for self.kill_app() method
  2602. # self.close_app_signal.emit()
  2603. QtWidgets.qApp.quit()
  2604. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2605. # we use the following command
  2606. minor_v = sys.version_info.minor
  2607. if minor_v < 8:
  2608. sys.exit(0)
  2609. else:
  2610. os._exit(0) # fix to work with Python 3.8
  2611. @staticmethod
  2612. def kill_app():
  2613. QtWidgets.qApp.quit()
  2614. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2615. # we use the following command
  2616. sys.exit(0)
  2617. def on_portable_checked(self, state):
  2618. """
  2619. Callback called when the checkbox in Preferences GUI is checked.
  2620. It will set the application as portable by creating the preferences and recent files in the
  2621. 'config' folder found in the FlatCAM installation folder.
  2622. :param state: boolean, the state of the checkbox when clicked/checked
  2623. :return:
  2624. """
  2625. line_no = 0
  2626. data = None
  2627. if sys.platform != 'win32':
  2628. # this won't work in Linux or MacOS
  2629. return
  2630. # test if the app was frozen and choose the path for the configuration file
  2631. if getattr(sys, "frozen", False) is True:
  2632. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2633. else:
  2634. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2635. config_file = current_data_path + '\\configuration.txt'
  2636. try:
  2637. with open(config_file, 'r') as f:
  2638. try:
  2639. data = f.readlines()
  2640. except Exception as e:
  2641. log.debug('App.__init__() -->%s' % str(e))
  2642. return
  2643. except FileNotFoundError:
  2644. pass
  2645. for line in data:
  2646. line = line.strip('\n')
  2647. param = str(line).rpartition('=')
  2648. if param[0] == 'portable':
  2649. break
  2650. line_no += 1
  2651. if state:
  2652. data[line_no] = 'portable=True\n'
  2653. # create the new defauults files
  2654. # create current_defaults.FlatConfig file if there is none
  2655. try:
  2656. f = open(current_data_path + '/current_defaults.FlatConfig')
  2657. f.close()
  2658. except IOError:
  2659. App.log.debug('Creating empty current_defaults.FlatConfig')
  2660. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2661. json.dump({}, f)
  2662. f.close()
  2663. # create factory_defaults.FlatConfig file if there is none
  2664. try:
  2665. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2666. f.close()
  2667. except IOError:
  2668. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2669. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2670. json.dump({}, f)
  2671. f.close()
  2672. try:
  2673. f = open(current_data_path + '/recent.json')
  2674. f.close()
  2675. except IOError:
  2676. App.log.debug('Creating empty recent.json')
  2677. f = open(current_data_path + '/recent.json', 'w')
  2678. json.dump([], f)
  2679. f.close()
  2680. try:
  2681. fp = open(current_data_path + '/recent_projects.json')
  2682. fp.close()
  2683. except IOError:
  2684. App.log.debug('Creating empty recent_projects.json')
  2685. fp = open(current_data_path + '/recent_projects.json', 'w')
  2686. json.dump([], fp)
  2687. fp.close()
  2688. # save the current defaults to the new defaults file
  2689. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2690. else:
  2691. data[line_no] = 'portable=False\n'
  2692. with open(config_file, 'w') as f:
  2693. f.writelines(data)
  2694. def on_register_files(self, obj_type=None):
  2695. """
  2696. Called whenever there is a need to register file extensions with FlatCAM.
  2697. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2698. :param obj_type: the type of object to be register for.
  2699. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2700. :return: None
  2701. """
  2702. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2703. new_reg_path = 'Software\\Classes\\'
  2704. # find if the current user is admin
  2705. try:
  2706. is_admin = os.getuid() == 0
  2707. except AttributeError:
  2708. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2709. if is_admin is True:
  2710. root_path = winreg.HKEY_LOCAL_MACHINE
  2711. else:
  2712. root_path = winreg.HKEY_CURRENT_USER
  2713. # create the keys
  2714. def set_reg(name, root_pth, new_reg_path, value):
  2715. try:
  2716. winreg.CreateKey(root_pth, new_reg_path)
  2717. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2718. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2719. return True
  2720. except WindowsError:
  2721. return False
  2722. # delete key in registry
  2723. def delete_reg(root_pth, reg_path, key_to_del):
  2724. key_to_del_path = reg_path + key_to_del
  2725. try:
  2726. winreg.DeleteKey(root_pth, key_to_del_path)
  2727. return True
  2728. except WindowsError:
  2729. return False
  2730. if obj_type is None or obj_type == 'excellon':
  2731. exc_list = \
  2732. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2733. exc_list = [x for x in exc_list if x != '']
  2734. # register all keys in the Preferences window
  2735. for ext in exc_list:
  2736. new_k = new_reg_path + '.%s' % ext
  2737. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2738. # and unregister those that are no longer in the Preferences windows but are in the file
  2739. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2740. if ext not in exc_list:
  2741. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2742. # now write the updated extensions to the self.defaults
  2743. # new_ext = ''
  2744. # for ext in exc_list:
  2745. # new_ext = new_ext + ext + ', '
  2746. # self.defaults["fa_excellon"] = new_ext
  2747. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2748. if obj_type is None or obj_type == 'gcode':
  2749. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2750. gco_list = [x for x in gco_list if x != '']
  2751. # register all keys in the Preferences window
  2752. for ext in gco_list:
  2753. new_k = new_reg_path + '.%s' % ext
  2754. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2755. # and unregister those that are no longer in the Preferences windows but are in the file
  2756. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2757. if ext not in gco_list:
  2758. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2759. # now write the updated extensions to the self.defaults
  2760. # new_ext = ''
  2761. # for ext in gco_list:
  2762. # new_ext = new_ext + ext + ', '
  2763. # self.defaults["fa_gcode"] = new_ext
  2764. self.inform.emit('[success] %s' %
  2765. _("Selected GCode file extensions registered with FlatCAM."))
  2766. if obj_type is None or obj_type == 'gerber':
  2767. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2768. grb_list = [x for x in grb_list if x != '']
  2769. # register all keys in the Preferences window
  2770. for ext in grb_list:
  2771. new_k = new_reg_path + '.%s' % ext
  2772. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2773. # and unregister those that are no longer in the Preferences windows but are in the file
  2774. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2775. if ext not in grb_list:
  2776. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2777. # now write the updated extensions to the self.defaults
  2778. # new_ext = ''
  2779. # for ext in grb_list:
  2780. # new_ext = new_ext + ext + ', '
  2781. # self.defaults["fa_gerber"] = new_ext
  2782. self.inform.emit('[success] %s' %
  2783. _("Selected Gerber file extensions registered with FlatCAM."))
  2784. def add_extension(self, ext_type):
  2785. """
  2786. Add a file extension to the list for a specific object
  2787. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2788. :return:
  2789. """
  2790. if ext_type == 'excellon':
  2791. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2792. if new_ext == '':
  2793. return
  2794. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2795. if new_ext in old_val:
  2796. return
  2797. old_val.append(new_ext)
  2798. old_val.sort()
  2799. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2800. if ext_type == 'gcode':
  2801. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2802. if new_ext == '':
  2803. return
  2804. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2805. if new_ext in old_val:
  2806. return
  2807. old_val.append(new_ext)
  2808. old_val.sort()
  2809. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2810. if ext_type == 'gerber':
  2811. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2812. if new_ext == '':
  2813. return
  2814. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2815. if new_ext in old_val:
  2816. return
  2817. old_val.append(new_ext)
  2818. old_val.sort()
  2819. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2820. if ext_type == 'keyword':
  2821. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2822. if new_kw == '':
  2823. return
  2824. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2825. if new_kw in old_val:
  2826. return
  2827. old_val.append(new_kw)
  2828. old_val.sort()
  2829. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2830. # update the self.myKeywords so the model is updated
  2831. self.autocomplete_kw_list = \
  2832. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2833. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2834. self.shell._edit.set_model_data(self.myKeywords)
  2835. def del_extension(self, ext_type):
  2836. """
  2837. Remove a file extension from the list for a specific object
  2838. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2839. :return:
  2840. """
  2841. if ext_type == 'excellon':
  2842. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2843. if new_ext == '':
  2844. return
  2845. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2846. if new_ext not in old_val:
  2847. return
  2848. old_val.remove(new_ext)
  2849. old_val.sort()
  2850. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2851. if ext_type == 'gcode':
  2852. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2853. if new_ext == '':
  2854. return
  2855. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2856. if new_ext not in old_val:
  2857. return
  2858. old_val.remove(new_ext)
  2859. old_val.sort()
  2860. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2861. if ext_type == 'gerber':
  2862. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2863. if new_ext == '':
  2864. return
  2865. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2866. if new_ext not in old_val:
  2867. return
  2868. old_val.remove(new_ext)
  2869. old_val.sort()
  2870. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2871. if ext_type == 'keyword':
  2872. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2873. if new_kw == '':
  2874. return
  2875. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2876. if new_kw not in old_val:
  2877. return
  2878. old_val.remove(new_kw)
  2879. old_val.sort()
  2880. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2881. # update the self.myKeywords so the model is updated
  2882. self.autocomplete_kw_list = \
  2883. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2884. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2885. self.shell._edit.set_model_data(self.myKeywords)
  2886. def restore_extensions(self, ext_type):
  2887. """
  2888. Restore all file extensions associations with FlatCAM, for a specific object
  2889. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2890. :return:
  2891. """
  2892. if ext_type == 'excellon':
  2893. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2894. # for the ability to open Excellon files with .txt extension
  2895. new_exc_list = deepcopy(self.exc_list)
  2896. try:
  2897. new_exc_list.remove('txt')
  2898. except ValueError:
  2899. pass
  2900. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2901. if ext_type == 'gcode':
  2902. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2903. if ext_type == 'gerber':
  2904. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2905. if ext_type == 'keyword':
  2906. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2907. # update the self.myKeywords so the model is updated
  2908. self.autocomplete_kw_list = self.default_keywords
  2909. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2910. self.shell._edit.set_model_data(self.myKeywords)
  2911. def delete_all_extensions(self, ext_type):
  2912. """
  2913. Delete all file extensions associations with FlatCAM, for a specific object
  2914. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2915. :return:
  2916. """
  2917. if ext_type == 'excellon':
  2918. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2919. if ext_type == 'gcode':
  2920. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2921. if ext_type == 'gerber':
  2922. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2923. if ext_type == 'keyword':
  2924. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2925. # update the self.myKeywords so the model is updated
  2926. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2927. self.shell._edit.set_model_data(self.myKeywords)
  2928. def on_edit_join(self, name=None):
  2929. """
  2930. Callback for Edit->Join. Joins the selected geometry objects into
  2931. a new one.
  2932. :return: None
  2933. """
  2934. self.defaults.report_usage("on_edit_join()")
  2935. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2936. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2937. geo_type_set = set()
  2938. objs = self.collection.get_selected()
  2939. if len(objs) < 2:
  2940. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2941. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2942. return 'fail'
  2943. for obj in objs:
  2944. geo_type_set.add(obj.multigeo)
  2945. # if len(geo_type_list) == 1 means that all list elements are the same
  2946. if len(geo_type_set) != 1:
  2947. self.inform.emit('[ERROR] %s' %
  2948. _("Failed join. The Geometry objects are of different types.\n"
  2949. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2950. "convert from one to another and retry joining \n"
  2951. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2952. "the result may not be what was expected. \n"
  2953. "Check the generated GCODE."))
  2954. return
  2955. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2956. if True in geo_type_set:
  2957. def initialize(geo_obj, app):
  2958. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2959. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2960. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2961. for v in geo_obj.tools.values():
  2962. v['data']['name'] = obj_name_multi
  2963. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2964. else:
  2965. def initialize(geo_obj, app):
  2966. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2967. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2968. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2969. for v in geo_obj.tools.values():
  2970. v['data']['name'] = obj_name_single
  2971. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2972. self.should_we_save = True
  2973. def on_edit_join_exc(self):
  2974. """
  2975. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  2976. a new Excellon.
  2977. :return: None
  2978. """
  2979. self.defaults.report_usage("on_edit_join_exc()")
  2980. objs = self.collection.get_selected()
  2981. for obj in objs:
  2982. if not isinstance(obj, ExcellonObject):
  2983. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  2984. return
  2985. if len(objs) < 2:
  2986. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2987. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2988. return 'fail'
  2989. def initialize(exc_obj, app):
  2990. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  2991. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  2992. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  2993. self.should_we_save = True
  2994. def on_edit_join_grb(self):
  2995. """
  2996. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2997. a new Gerber object.
  2998. :return: None
  2999. """
  3000. self.defaults.report_usage("on_edit_join_grb()")
  3001. objs = self.collection.get_selected()
  3002. for obj in objs:
  3003. if not isinstance(obj, GerberObject):
  3004. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3005. return
  3006. if len(objs) < 2:
  3007. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3008. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3009. return 'fail'
  3010. def initialize(grb_obj, app):
  3011. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3012. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3013. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3014. self.should_we_save = True
  3015. def on_convert_singlegeo_to_multigeo(self):
  3016. """
  3017. Called for converting a Geometry object from single-geo to multi-geo.
  3018. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3019. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3020. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3021. the solid-geometry of that tool.
  3022. :return: None
  3023. """
  3024. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3025. obj = self.collection.get_active()
  3026. if obj is None:
  3027. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3028. return
  3029. if not isinstance(obj, GeometryObject):
  3030. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3031. return
  3032. obj.multigeo = True
  3033. for tooluid, dict_value in obj.tools.items():
  3034. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3035. if not isinstance(obj.solid_geometry, list):
  3036. obj.solid_geometry = [obj.solid_geometry]
  3037. # obj.solid_geometry[:] = []
  3038. obj.plot()
  3039. self.should_we_save = True
  3040. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3041. def on_convert_multigeo_to_singlegeo(self):
  3042. """
  3043. Called for converting a Geometry object from multi-geo to single-geo.
  3044. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3045. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3046. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3047. the solid-geometry of that tool.
  3048. :return: None
  3049. """
  3050. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3051. obj = self.collection.get_active()
  3052. if obj is None:
  3053. self.inform.emit('[ERROR_NOTCL] %s' %
  3054. _("Failed. Select a Geometry Object and try again."))
  3055. return
  3056. if not isinstance(obj, GeometryObject):
  3057. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3058. (_("Expected a GeometryObject, got"), type(obj)))
  3059. return
  3060. obj.multigeo = False
  3061. total_solid_geometry = []
  3062. for tooluid, dict_value in obj.tools.items():
  3063. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3064. # clear the original geometry
  3065. dict_value['solid_geometry'][:] = []
  3066. obj.solid_geometry = deepcopy(total_solid_geometry)
  3067. obj.plot()
  3068. self.should_we_save = True
  3069. self.inform.emit('[success] %s' %
  3070. _("A Geometry object was converted to SingleGeo type."))
  3071. def on_defaults_dict_change(self, field):
  3072. """
  3073. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3074. Edit -> Preferences tab window.
  3075. :param field: the key of the self.defaults dictionary that was changed.
  3076. :return: None
  3077. """
  3078. self.preferencesUiManager.defaults_write_form_field(field=field)
  3079. if field == "units":
  3080. self.set_screen_units(self.defaults['units'])
  3081. def set_screen_units(self, units):
  3082. """
  3083. Set the FlatCAM units on the status bar.
  3084. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3085. :return: None
  3086. """
  3087. self.ui.units_label.setText("[" + units.lower() + "]")
  3088. def on_toggle_units_click(self):
  3089. try:
  3090. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3091. except (TypeError, AttributeError):
  3092. pass
  3093. if self.defaults["units"] == 'MM':
  3094. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3095. else:
  3096. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3097. self.on_toggle_units(no_pref=True)
  3098. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3099. lambda: self.on_toggle_units(no_pref=False))
  3100. def on_toggle_units(self, no_pref=False):
  3101. """
  3102. Callback for the Units radio-button change in the Preferences tab.
  3103. Changes the application's default units adn for the project too.
  3104. If changing the project's units, the change propagates to all of
  3105. the objects in the project.
  3106. :return: None
  3107. """
  3108. self.defaults.report_usage("on_toggle_units")
  3109. if self.toggle_units_ignore:
  3110. return
  3111. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3112. # If option is the same, then ignore
  3113. if new_units == self.defaults["units"].upper():
  3114. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3115. return
  3116. # Keys in self.defaults for which to scale their values
  3117. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3118. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3119. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3120. "gerber_editor_ma_high",
  3121. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3122. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3123. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3124. "excellon_feedrate_probe", "excellon_milling_dia",
  3125. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3126. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3127. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3128. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3129. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3130. "geometry_extracut_length", "geometry_z_pdepth",
  3131. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3132. 'cncjob_tooldia',
  3133. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3134. "tools_paintnewdia",
  3135. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3136. "tools_nccnewdia", "tools_ncc_offset_value",
  3137. "tools_2sided_drilldia",
  3138. "tools_film_boundary", "tools_film_scale_stroke",
  3139. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3140. "tools_cutout_depthperpass",
  3141. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3142. "tools_panelize_spacing_rows",
  3143. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3144. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3145. "tools_transform_buffer_dis",
  3146. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3147. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3148. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3149. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3150. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3151. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3152. "tools_cr_h2h_val", "tools_cr_dh_val",
  3153. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3154. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3155. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3156. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3157. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3158. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3159. "tools_copper_thieving_mask_clearance",
  3160. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3161. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3162. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3163. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3164. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3165. "tools_invert_margin",
  3166. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3167. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3168. def scale_defaults(sfactor):
  3169. for dim in dimensions:
  3170. if dim in [
  3171. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3172. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3173. 'tools_transform_mirror_point'
  3174. ]:
  3175. if self.defaults[dim] is None or self.defaults[dim] == '':
  3176. continue
  3177. try:
  3178. coordinates = self.defaults[dim].split(",")
  3179. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3180. coords_xy[0] *= sfactor
  3181. coords_xy[1] *= sfactor
  3182. self.defaults[dim] = "%.*f, %.*f" % (
  3183. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3184. except Exception as e:
  3185. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3186. elif dim in [
  3187. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3188. ]:
  3189. if self.defaults[dim] is None or self.defaults[dim] == '':
  3190. continue
  3191. try:
  3192. self.defaults[dim] = float(self.defaults[dim])
  3193. tools_diameters = [self.defaults[dim]]
  3194. except ValueError:
  3195. try:
  3196. tools_string = self.defaults[dim].split(",")
  3197. tools_diameters = [eval(a) for a in tools_string if a != '']
  3198. except Exception as e:
  3199. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3200. continue
  3201. self.defaults[dim] = ''
  3202. td_len = len(tools_diameters)
  3203. if td_len > 1:
  3204. for t in range(td_len):
  3205. tools_diameters[t] *= sfactor
  3206. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3207. else:
  3208. tools_diameters[0] *= sfactor
  3209. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3210. elif dim in ['global_gridx', 'global_gridy']:
  3211. # format the number of decimals to the one specified in self.decimals
  3212. try:
  3213. val = float(self.defaults[dim]) * sfactor
  3214. except Exception as e:
  3215. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3216. continue
  3217. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3218. else:
  3219. # the number of decimals for the rest is kept unchanged
  3220. if self.defaults[dim]:
  3221. try:
  3222. val = float(self.defaults[dim]) * sfactor
  3223. except Exception as e:
  3224. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3225. continue
  3226. self.defaults[dim] = val
  3227. # The scaling factor depending on choice of units.
  3228. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3229. # Changing project units. Warn user.
  3230. msgbox = QtWidgets.QMessageBox()
  3231. msgbox.setWindowTitle(_("Toggle Units"))
  3232. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3233. msgbox.setText(_("Changing the units of the project\n"
  3234. "will scale all objects.\n\n"
  3235. "Do you want to continue?"))
  3236. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3237. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3238. msgbox.setDefaultButton(bt_ok)
  3239. msgbox.exec_()
  3240. response = msgbox.clickedButton()
  3241. if response == bt_ok:
  3242. if no_pref is False:
  3243. self.preferencesUiManager.defaults_read_form()
  3244. scale_defaults(factor)
  3245. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3246. self.defaults["units"] = new_units
  3247. # update the defaults from form, some may assume that the conversion is enough and it's not
  3248. self.on_options_app2project()
  3249. # update the objects
  3250. for obj in self.collection.get_list():
  3251. obj.convert_units(new_units)
  3252. # make that the properties stored in the object are also updated
  3253. self.app_obj.object_changed.emit(obj)
  3254. # rebuild the object UI
  3255. obj.build_ui()
  3256. # change this only if the workspace is active
  3257. if self.defaults['global_workspace'] is True:
  3258. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3259. # adjust the grid values on the main toolbar
  3260. val_x = float(self.defaults['global_gridx']) * factor
  3261. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3262. current = self.collection.get_active()
  3263. if current is not None:
  3264. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3265. if not isinstance(current, GeometryObject):
  3266. current.to_form()
  3267. # replot all objects
  3268. self.plot_all()
  3269. # set the status labels to reflect the current FlatCAM units
  3270. self.set_screen_units(new_units)
  3271. # signal to the app that we changed the object properties and it should save the project
  3272. self.should_we_save = True
  3273. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3274. else:
  3275. # Undo toggling
  3276. self.toggle_units_ignore = True
  3277. if self.defaults['units'].upper() == 'MM':
  3278. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3279. else:
  3280. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3281. self.toggle_units_ignore = False
  3282. # store the grid values so they are not changed in the next step
  3283. val_x = float(self.defaults['global_gridx'])
  3284. val_y = float(self.defaults['global_gridy'])
  3285. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3286. self.preferencesUiManager.defaults_read_form()
  3287. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3288. # in self.defaults from the GUI elements but
  3289. # I don't want it for the grid values, so I update them here
  3290. self.defaults['global_gridx'] = val_x
  3291. self.defaults['global_gridy'] = val_y
  3292. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3293. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3294. def on_toggle_axis(self):
  3295. self.defaults.report_usage("on_toggle_axis()")
  3296. if self.toggle_axis is False:
  3297. if self.is_legacy is False:
  3298. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3299. parent=self.plotcanvas.view.scene)
  3300. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3301. parent=self.plotcanvas.view.scene)
  3302. else:
  3303. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3304. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3305. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3306. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3307. self.plotcanvas.canvas.draw()
  3308. self.toggle_axis = True
  3309. else:
  3310. if self.is_legacy is False:
  3311. self.plotcanvas.v_line.parent = None
  3312. self.plotcanvas.h_line.parent = None
  3313. else:
  3314. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3315. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3316. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3317. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3318. self.plotcanvas.canvas.draw()
  3319. self.toggle_axis = False
  3320. def on_toggle_hud(self):
  3321. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3322. def on_toggle_grid_lines(self):
  3323. self.defaults.report_usage("on_toggle_grd_lines()")
  3324. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3325. if tt_settings.contains("theme"):
  3326. theme = tt_settings.value('theme', type=str)
  3327. else:
  3328. theme = 'white'
  3329. if self.toggle_grid_lines is False:
  3330. if self.is_legacy is False:
  3331. if theme == 'white':
  3332. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3333. else:
  3334. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3335. else:
  3336. self.plotcanvas.axes.grid(True)
  3337. try:
  3338. self.plotcanvas.canvas.draw()
  3339. except IndexError:
  3340. pass
  3341. pass
  3342. self.toggle_grid_lines = True
  3343. else:
  3344. if self.is_legacy is False:
  3345. if theme == 'white':
  3346. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3347. else:
  3348. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3349. else:
  3350. self.plotcanvas.axes.grid(False)
  3351. try:
  3352. self.plotcanvas.canvas.draw()
  3353. except IndexError:
  3354. pass
  3355. self.toggle_grid_lines = False
  3356. if self.is_legacy is False:
  3357. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3358. # - perhaps is a bug in VisPy implementation
  3359. if self.grid_status():
  3360. self.app_cursor.enabled = False
  3361. self.app_cursor.enabled = True
  3362. else:
  3363. self.app_cursor.enabled = True
  3364. self.app_cursor.enabled = False
  3365. def on_update_exc_export(self, state):
  3366. """
  3367. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3368. if the update_excellon_cb checkbox is checked
  3369. :param state: state of the checkbox whose signals is tied to his slot
  3370. :return:
  3371. """
  3372. if state:
  3373. # first try to disconnect
  3374. try:
  3375. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3376. disconnect(self.on_excellon_format_changed)
  3377. except TypeError:
  3378. pass
  3379. try:
  3380. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3381. disconnect(self.on_excellon_format_changed)
  3382. except TypeError:
  3383. pass
  3384. try:
  3385. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3386. disconnect(self.on_excellon_format_changed)
  3387. except TypeError:
  3388. pass
  3389. try:
  3390. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3391. disconnect(self.on_excellon_format_changed)
  3392. except TypeError:
  3393. pass
  3394. try:
  3395. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3396. disconnect(self.on_excellon_zeros_changed)
  3397. except TypeError:
  3398. pass
  3399. try:
  3400. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3401. disconnect(self.on_excellon_zeros_changed)
  3402. except TypeError:
  3403. pass
  3404. # the connect them
  3405. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3406. self.on_excellon_format_changed)
  3407. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3408. self.on_excellon_format_changed)
  3409. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3410. self.on_excellon_format_changed)
  3411. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3412. self.on_excellon_format_changed)
  3413. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3414. self.on_excellon_zeros_changed)
  3415. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3416. self.on_excellon_units_changed)
  3417. else:
  3418. # disconnect the signals
  3419. try:
  3420. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3421. disconnect(self.on_excellon_format_changed)
  3422. except TypeError:
  3423. pass
  3424. try:
  3425. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3426. disconnect(self.on_excellon_format_changed)
  3427. except TypeError:
  3428. pass
  3429. try:
  3430. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3431. disconnect(self.on_excellon_format_changed)
  3432. except TypeError:
  3433. pass
  3434. try:
  3435. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3436. disconnect(self.on_excellon_format_changed)
  3437. except TypeError:
  3438. pass
  3439. try:
  3440. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3441. disconnect(self.on_excellon_zeros_changed)
  3442. except TypeError:
  3443. pass
  3444. try:
  3445. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3446. disconnect(self.on_excellon_zeros_changed)
  3447. except TypeError:
  3448. pass
  3449. def on_excellon_format_changed(self):
  3450. """
  3451. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3452. :return: None
  3453. """
  3454. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3455. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3456. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3457. )
  3458. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3459. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3460. )
  3461. else:
  3462. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3463. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3464. )
  3465. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3466. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3467. )
  3468. def on_excellon_zeros_changed(self):
  3469. """
  3470. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3471. :return: None
  3472. """
  3473. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3474. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3475. )
  3476. def on_excellon_units_changed(self):
  3477. """
  3478. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3479. :return: None
  3480. """
  3481. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3482. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3483. )
  3484. self.on_excellon_format_changed()
  3485. def on_film_color_entry(self):
  3486. self.defaults['tools_film_color'] = \
  3487. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3488. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3489. "background-color:%s;"
  3490. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3491. )
  3492. def on_film_color_button(self):
  3493. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3494. c_dialog = QtWidgets.QColorDialog()
  3495. film_color = c_dialog.getColor(initial=current_color)
  3496. if film_color.isValid() is False:
  3497. return
  3498. # if new color is different then mark that the Preferences are changed
  3499. if film_color != current_color:
  3500. self.preferencesUiManager.on_preferences_edited()
  3501. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3502. "background-color:%s;"
  3503. "border-color: dimgray" % str(film_color.name())
  3504. )
  3505. new_val_sel = str(film_color.name())
  3506. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3507. self.defaults['tools_film_color'] = new_val_sel
  3508. def on_qrcode_fill_color_entry(self):
  3509. self.defaults['tools_qrcode_fill_color'] = \
  3510. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3511. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3512. "background-color:%s;"
  3513. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3514. )
  3515. def on_qrcode_fill_color_button(self):
  3516. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3517. c_dialog = QtWidgets.QColorDialog()
  3518. fill_color = c_dialog.getColor(initial=current_color)
  3519. if fill_color.isValid() is False:
  3520. return
  3521. # if new color is different then mark that the Preferences are changed
  3522. if fill_color != current_color:
  3523. self.preferencesUiManager.on_preferences_edited()
  3524. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3525. "background-color:%s;"
  3526. "border-color: dimgray" % str(fill_color.name())
  3527. )
  3528. new_val_sel = str(fill_color.name())
  3529. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3530. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3531. def on_qrcode_back_color_entry(self):
  3532. self.defaults['tools_qrcode_back_color'] = \
  3533. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3534. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3535. "background-color:%s;"
  3536. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3537. )
  3538. def on_qrcode_back_color_button(self):
  3539. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3540. c_dialog = QtWidgets.QColorDialog()
  3541. back_color = c_dialog.getColor(initial=current_color)
  3542. if back_color.isValid() is False:
  3543. return
  3544. # if new color is different then mark that the Preferences are changed
  3545. if back_color != current_color:
  3546. self.preferencesUiManager.on_preferences_edited()
  3547. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3548. "background-color:%s;"
  3549. "border-color: dimgray" % str(back_color.name())
  3550. )
  3551. new_val_sel = str(back_color.name())
  3552. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3553. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3554. def on_tab_rmb_click(self, checked):
  3555. self.ui.notebook.set_detachable(val=checked)
  3556. self.defaults["global_tabs_detachable"] = checked
  3557. self.ui.plot_tab_area.set_detachable(val=checked)
  3558. self.defaults["global_tabs_detachable"] = checked
  3559. def on_tab_setup_context_menu(self):
  3560. initial_checked = self.defaults["global_tabs_detachable"]
  3561. action_name = str(_("Detachable Tabs"))
  3562. action = QtWidgets.QAction(self)
  3563. action.setCheckable(True)
  3564. action.setText(action_name)
  3565. action.setChecked(initial_checked)
  3566. self.ui.notebook.tabBar.addAction(action)
  3567. self.ui.plot_tab_area.tabBar.addAction(action)
  3568. try:
  3569. action.triggered.disconnect()
  3570. except TypeError:
  3571. pass
  3572. action.triggered.connect(self.on_tab_rmb_click)
  3573. def on_deselect_all(self):
  3574. self.collection.set_all_inactive()
  3575. self.delete_selection_shape()
  3576. def on_workspace_modified(self):
  3577. # self.save_defaults(silent=True)
  3578. self.plotcanvas.delete_workspace()
  3579. self.preferencesUiManager.defaults_read_form()
  3580. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3581. def on_workspace(self):
  3582. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3583. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3584. self.inform.emit(_("Workspace enabled."))
  3585. else:
  3586. self.plotcanvas.delete_workspace()
  3587. self.inform.emit(_("Workspace disabled."))
  3588. self.preferencesUiManager.defaults_read_form()
  3589. # self.save_defaults(silent=True)
  3590. def on_workspace_toggle(self):
  3591. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3592. try:
  3593. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3594. except TypeError:
  3595. pass
  3596. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3597. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3598. self.on_workspace()
  3599. def on_cursor_type(self, val):
  3600. """
  3601. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3602. :return: None
  3603. """
  3604. self.app_cursor.enabled = False
  3605. if val == 'small':
  3606. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3607. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3608. self.app_cursor = self.plotcanvas.new_cursor()
  3609. else:
  3610. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3611. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3612. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3613. if self.ui.grid_snap_btn.isChecked():
  3614. self.app_cursor.enabled = True
  3615. else:
  3616. self.app_cursor.enabled = False
  3617. def on_tool_add_keypress(self):
  3618. # ## Current application units in Upper Case
  3619. self.units = self.defaults['units'].upper()
  3620. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3621. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3622. if notebook_widget_name == 'selected_tab':
  3623. if self.collection.get_active().kind == 'geometry':
  3624. # Tool add works for Geometry only if Advanced is True in Preferences
  3625. if self.defaults["global_app_level"] == 'a':
  3626. tool_add_popup = FCInputDialog(title="New Tool ...",
  3627. text='Enter a Tool Diameter:',
  3628. min=0.0000, max=99.9999, decimals=4)
  3629. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3630. val, ok = tool_add_popup.get_value()
  3631. if ok:
  3632. if float(val) == 0:
  3633. self.inform.emit('[WARNING_NOTCL] %s' %
  3634. _("Please enter a tool diameter with non-zero value, in Float format."))
  3635. return
  3636. self.collection.get_active().on_tool_add(dia=float(val))
  3637. else:
  3638. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3639. else:
  3640. msgbox = QtWidgets.QMessageBox()
  3641. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3642. "Go to Preferences -> General - Show Advanced Options."))
  3643. msgbox.setWindowTitle("Tool adding ...")
  3644. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3645. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3646. msgbox.setDefaultButton(bt_ok)
  3647. msgbox.exec_()
  3648. # work only if the notebook tab on focus is the Tools_Tab
  3649. if notebook_widget_name == 'tool_tab':
  3650. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3651. # and only if the tool is NCC Tool
  3652. if tool_widget == self.ncclear_tool.toolName:
  3653. self.ncclear_tool.on_add_tool_by_key()
  3654. # and only if the tool is Paint Area Tool
  3655. elif tool_widget == self.paint_tool.toolName:
  3656. self.paint_tool.on_add_tool_by_key()
  3657. # and only if the tool is Solder Paste Dispensing Tool
  3658. elif tool_widget == self.paste_tool.toolName:
  3659. self.paste_tool.on_add_tool_by_key()
  3660. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3661. # See description below.
  3662. def on_delete_keypress(self):
  3663. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3664. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3665. if notebook_widget_name == 'selected_tab':
  3666. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3667. self.collection.get_active().on_tool_delete()
  3668. # work only if the notebook tab on focus is the Tools_Tab
  3669. elif notebook_widget_name == 'tool_tab':
  3670. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3671. # and only if the tool is NCC Tool
  3672. if tool_widget == self.ncclear_tool.toolName:
  3673. self.ncclear_tool.on_tool_delete()
  3674. # and only if the tool is Paint Tool
  3675. elif tool_widget == self.paint_tool.toolName:
  3676. self.paint_tool.on_tool_delete()
  3677. # and only if the tool is Solder Paste Dispensing Tool
  3678. elif tool_widget == self.paste_tool.toolName:
  3679. self.paste_tool.on_tool_delete()
  3680. else:
  3681. self.on_delete()
  3682. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3683. # some screens you have to be careful where you hover with your mouse.
  3684. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3685. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3686. # Complicated, I know :)
  3687. def on_delete(self, force_deletion=False):
  3688. """
  3689. Delete the currently selected FlatCAMObjs.
  3690. :param force_deletion: used by Tcl command
  3691. :return: None
  3692. """
  3693. self.defaults.report_usage("on_delete()")
  3694. response = None
  3695. bt_ok = None
  3696. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3697. # a geometry object before we update it.
  3698. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3699. and self.grb_editor.editor_active is False:
  3700. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3701. msgbox = QtWidgets.QMessageBox()
  3702. msgbox.setWindowTitle(_("Delete objects"))
  3703. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3704. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3705. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3706. "the selected objects?"))
  3707. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3708. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3709. msgbox.setDefaultButton(bt_ok)
  3710. msgbox.exec_()
  3711. response = msgbox.clickedButton()
  3712. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3713. response = bt_ok
  3714. if response == bt_ok:
  3715. if self.collection.get_active():
  3716. self.log.debug("App.on_delete()")
  3717. for obj_active in self.collection.get_selected():
  3718. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3719. if obj_active.kind == 'gerber':
  3720. for el in obj_active.mark_shapes:
  3721. obj_active.mark_shapes[el].clear(update=True)
  3722. obj_active.mark_shapes[el].enabled = False
  3723. # obj_active.mark_shapes[el] = None
  3724. del el
  3725. elif isinstance(obj_active, CNCJobObject):
  3726. try:
  3727. obj_active.text_col.enabled = False
  3728. del obj_active.text_col
  3729. obj_active.annotation.clear(update=True)
  3730. del obj_active.annotation
  3731. except AttributeError as e:
  3732. log.debug(
  3733. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3734. )
  3735. while self.collection.get_selected():
  3736. self.delete_first_selected()
  3737. self.inform.emit('%s...' % _("Object(s) deleted"))
  3738. # make sure that the selection shape is deleted, too
  3739. self.delete_selection_shape()
  3740. # if there are no longer objects delete also the exclusion areas shapes
  3741. if not self.collection.get_list():
  3742. self.exc_areas.clear_shapes()
  3743. else:
  3744. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3745. else:
  3746. self.inform.emit(_("Save the work in Editor and try again ..."))
  3747. def delete_first_selected(self):
  3748. # Keep this for later
  3749. try:
  3750. sel_obj = self.collection.get_active()
  3751. name = sel_obj.options["name"]
  3752. isPlotted = sel_obj.options["plot"]
  3753. except AttributeError:
  3754. self.log.debug("Nothing selected for deletion")
  3755. return
  3756. if self.is_legacy is True:
  3757. # Remove plot only if the object was plotted otherwise delaxes will fail
  3758. if isPlotted:
  3759. try:
  3760. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3761. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3762. except Exception as e:
  3763. log.debug("App.delete_first_selected() --> %s" % str(e))
  3764. self.plotcanvas.auto_adjust_axes()
  3765. # Remove from dictionary
  3766. self.collection.delete_active()
  3767. # Clear form
  3768. self.setup_component_editor()
  3769. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3770. def on_set_origin(self):
  3771. """
  3772. Set the origin to the left mouse click position
  3773. :return: None
  3774. """
  3775. # display the message for the user
  3776. # and ask him to click on the desired position
  3777. self.defaults.report_usage("on_set_origin()")
  3778. def origin_replot():
  3779. def worker_task():
  3780. with self.proc_container.new('%s...' % _("Plotting")):
  3781. for obj in self.collection.get_list():
  3782. obj.plot()
  3783. self.plotcanvas.fit_view()
  3784. if self.is_legacy:
  3785. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3786. else:
  3787. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3788. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3789. self.inform.emit(_('Click to set the origin ...'))
  3790. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3791. # first disconnect it as it may have been used by something else
  3792. try:
  3793. self.replot_signal.disconnect()
  3794. except TypeError:
  3795. pass
  3796. self.replot_signal[list].connect(origin_replot)
  3797. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3798. """
  3799. :param event:
  3800. :param location:
  3801. :param noplot:
  3802. :param use_thread:
  3803. :return:
  3804. """
  3805. noplot_sig = noplot
  3806. def worker_task():
  3807. with self.proc_container.new(_("Setting Origin...")):
  3808. obj_list = self.collection.get_list()
  3809. for obj in obj_list:
  3810. obj.offset((x, y))
  3811. self.app_obj.object_changed.emit(obj)
  3812. # Update the object bounding box options
  3813. a, b, c, d = obj.bounds()
  3814. obj.options['xmin'] = a
  3815. obj.options['ymin'] = b
  3816. obj.options['xmax'] = c
  3817. obj.options['ymax'] = d
  3818. self.inform.emit('[success] %s...' % _('Origin set'))
  3819. for obj in obj_list:
  3820. out_name = obj.options["name"]
  3821. if obj.kind == 'gerber':
  3822. obj.source_file = self.export_gerber(
  3823. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3824. elif obj.kind == 'excellon':
  3825. obj.source_file = self.export_excellon(
  3826. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3827. if noplot_sig is False:
  3828. self.replot_signal.emit([])
  3829. if location is not None:
  3830. if len(location) != 2:
  3831. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3832. return 'fail'
  3833. x, y = location
  3834. if use_thread is True:
  3835. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3836. else:
  3837. worker_task()
  3838. self.should_we_save = True
  3839. return
  3840. if event is not None and event.button == 1:
  3841. if self.is_legacy is False:
  3842. event_pos = event.pos
  3843. else:
  3844. event_pos = (event.xdata, event.ydata)
  3845. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3846. if self.grid_status():
  3847. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3848. else:
  3849. pos = pos_canvas
  3850. x = 0 - pos[0]
  3851. y = 0 - pos[1]
  3852. if use_thread is True:
  3853. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3854. else:
  3855. worker_task()
  3856. self.should_we_save = True
  3857. def on_move2origin(self, use_thread=True):
  3858. """
  3859. Move selected objects to origin.
  3860. :param use_thread: Control if to use threaded operation. Boolean.
  3861. :return:
  3862. """
  3863. def worker_task():
  3864. with self.proc_container.new(_("Moving to Origin...")):
  3865. obj_list = self.collection.get_selected()
  3866. if not obj_list:
  3867. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3868. return
  3869. xminlist = []
  3870. yminlist = []
  3871. # first get a bounding box to fit all
  3872. for obj in obj_list:
  3873. xmin, ymin, xmax, ymax = obj.bounds()
  3874. xminlist.append(xmin)
  3875. yminlist.append(ymin)
  3876. # get the minimum x,y for all objects selected
  3877. x = min(xminlist)
  3878. y = min(yminlist)
  3879. for obj in obj_list:
  3880. obj.offset((-x, -y))
  3881. self.app_obj.object_changed.emit(obj)
  3882. # Update the object bounding box options
  3883. a, b, c, d = obj.bounds()
  3884. obj.options['xmin'] = a
  3885. obj.options['ymin'] = b
  3886. obj.options['xmax'] = c
  3887. obj.options['ymax'] = d
  3888. for obj in obj_list:
  3889. obj.plot()
  3890. for obj in obj_list:
  3891. out_name = obj.options["name"]
  3892. if obj.kind == 'gerber':
  3893. obj.source_file = self.export_gerber(
  3894. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3895. elif obj.kind == 'excellon':
  3896. obj.source_file = self.export_excellon(
  3897. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3898. self.inform.emit('[success] %s...' % _('Origin set'))
  3899. if use_thread is True:
  3900. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3901. else:
  3902. worker_task()
  3903. self.should_we_save = True
  3904. def on_jump_to(self, custom_location=None, fit_center=True):
  3905. """
  3906. Jump to a location by setting the mouse cursor location.
  3907. :param custom_location: Jump to a specified point. (x, y) tuple.
  3908. :param fit_center: If to fit view. Boolean.
  3909. :return:
  3910. """
  3911. self.defaults.report_usage("on_jump_to()")
  3912. if not custom_location:
  3913. dia_box_location = None
  3914. try:
  3915. dia_box_location = eval(self.clipboard.text())
  3916. except Exception:
  3917. pass
  3918. if type(dia_box_location) == tuple:
  3919. dia_box_location = str(dia_box_location)
  3920. else:
  3921. dia_box_location = None
  3922. # dia_box = Dialog_box(title=_("Jump to ..."),
  3923. # label=_("Enter the coordinates in format X,Y:"),
  3924. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3925. # initial_text=dia_box_location)
  3926. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3927. label=_("Enter the coordinates in format X,Y:"),
  3928. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3929. initial_text=dia_box_location,
  3930. reference=self.defaults['global_jump_ref'])
  3931. if dia_box.ok is True:
  3932. try:
  3933. location = eval(dia_box.location)
  3934. if not isinstance(location, tuple):
  3935. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3936. return
  3937. if dia_box.reference == 'rel':
  3938. rel_x = self.mouse[0] + location[0]
  3939. rel_y = self.mouse[1] + location[1]
  3940. location = (rel_x, rel_y)
  3941. self.defaults['global_jump_ref'] = dia_box.reference
  3942. except Exception:
  3943. return
  3944. else:
  3945. return
  3946. else:
  3947. location = custom_location
  3948. self.jump_signal.emit(location)
  3949. if fit_center:
  3950. self.plotcanvas.fit_center(loc=location)
  3951. cursor = QtGui.QCursor()
  3952. if self.is_legacy is False:
  3953. # I don't know where those differences come from but they are constant for the current
  3954. # execution of the application and they are multiples of a value around 0.0263mm.
  3955. # In a random way sometimes they are more sometimes they are less
  3956. # if units == 'MM':
  3957. # cal_factor = 0.0263
  3958. # else:
  3959. # cal_factor = 0.0263 / 25.4
  3960. cal_location = (location[0], location[1])
  3961. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3962. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3963. j_pos = (
  3964. int(canvas_origin.x() + round(jump_loc[0])),
  3965. int(canvas_origin.y() + round(jump_loc[1]))
  3966. )
  3967. cursor.setPos(j_pos[0], j_pos[1])
  3968. else:
  3969. # find the canvas origin which is in the top left corner
  3970. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3971. # determine the coordinates for the lowest left point of the canvas
  3972. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3973. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3974. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3975. # canvas) and the point (width, height) is in the top-right location
  3976. loc = self.plotcanvas.axes.transData.transform_point(location)
  3977. j_pos = (
  3978. int(x0 + loc[0]),
  3979. int(y0 - loc[1])
  3980. )
  3981. cursor.setPos(j_pos[0], j_pos[1])
  3982. self.plotcanvas.mouse = [location[0], location[1]]
  3983. if self.defaults["global_cursor_color_enabled"] is True:
  3984. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3985. else:
  3986. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3987. if self.grid_status():
  3988. # Update cursor
  3989. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3990. symbol='++', edge_color=self.cursor_color_3D,
  3991. edge_width=self.defaults["global_cursor_width"],
  3992. size=self.defaults["global_cursor_size"])
  3993. # Set the relative position label
  3994. dx = location[0] - float(self.rel_point1[0])
  3995. dy = location[1] - float(self.rel_point1[1])
  3996. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3997. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3998. # # Set the position label
  3999. #
  4000. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4001. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4002. units = self.defaults["units"].lower()
  4003. self.plotcanvas.text_hud.text = \
  4004. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4005. dx, units, dy, units, location[0], units, location[1], units)
  4006. self.inform.emit('[success] %s' % _("Done."))
  4007. return location
  4008. def on_locate(self, obj, fit_center=True):
  4009. """
  4010. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4011. :param obj: The object on which to locate certain points
  4012. :param fit_center: If to fit view. Boolean.
  4013. :return: A point location. (x, y) tuple.
  4014. """
  4015. self.defaults.report_usage("on_locate()")
  4016. if obj is None:
  4017. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4018. return 'fail'
  4019. class DialogBoxChoice(QtWidgets.QDialog):
  4020. def __init__(self, title=None, icon=None, choice='bl'):
  4021. """
  4022. :param title: string with the window title
  4023. """
  4024. super(DialogBoxChoice, self).__init__()
  4025. self.ok = False
  4026. self.setWindowIcon(icon)
  4027. self.setWindowTitle(str(title))
  4028. self.form = QtWidgets.QFormLayout(self)
  4029. self.ref_radio = RadioSet([
  4030. {"label": _("Bottom-Left"), "value": "bl"},
  4031. {"label": _("Top-Left"), "value": "tl"},
  4032. {"label": _("Bottom-Right"), "value": "br"},
  4033. {"label": _("Top-Right"), "value": "tr"},
  4034. {"label": _("Center"), "value": "c"}
  4035. ], orientation='vertical', stretch=False)
  4036. self.ref_radio.set_value(choice)
  4037. self.form.addRow(self.ref_radio)
  4038. self.button_box = QtWidgets.QDialogButtonBox(
  4039. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4040. Qt.Horizontal, parent=self)
  4041. self.form.addRow(self.button_box)
  4042. self.button_box.accepted.connect(self.accept)
  4043. self.button_box.rejected.connect(self.reject)
  4044. if self.exec_() == QtWidgets.QDialog.Accepted:
  4045. self.ok = True
  4046. self.location_point = self.ref_radio.get_value()
  4047. else:
  4048. self.ok = False
  4049. self.location_point = None
  4050. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4051. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4052. choice=self.defaults['global_locate_pt'])
  4053. if dia_box.ok is True:
  4054. try:
  4055. location_point = dia_box.location_point
  4056. self.defaults['global_locate_pt'] = dia_box.location_point
  4057. except Exception:
  4058. return
  4059. else:
  4060. return
  4061. loc_b = obj.bounds()
  4062. if location_point == 'bl':
  4063. location = (loc_b[0], loc_b[1])
  4064. elif location_point == 'tl':
  4065. location = (loc_b[0], loc_b[3])
  4066. elif location_point == 'br':
  4067. location = (loc_b[2], loc_b[1])
  4068. elif location_point == 'tr':
  4069. location = (loc_b[2], loc_b[3])
  4070. else:
  4071. # center
  4072. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4073. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4074. location = (cx, cy)
  4075. self.locate_signal.emit(location, location_point)
  4076. if fit_center:
  4077. self.plotcanvas.fit_center(loc=location)
  4078. cursor = QtGui.QCursor()
  4079. if self.is_legacy is False:
  4080. # I don't know where those differences come from but they are constant for the current
  4081. # execution of the application and they are multiples of a value around 0.0263mm.
  4082. # In a random way sometimes they are more sometimes they are less
  4083. # if units == 'MM':
  4084. # cal_factor = 0.0263
  4085. # else:
  4086. # cal_factor = 0.0263 / 25.4
  4087. cal_location = (location[0], location[1])
  4088. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4089. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4090. j_pos = (
  4091. int(canvas_origin.x() + round(jump_loc[0])),
  4092. int(canvas_origin.y() + round(jump_loc[1]))
  4093. )
  4094. cursor.setPos(j_pos[0], j_pos[1])
  4095. else:
  4096. # find the canvas origin which is in the top left corner
  4097. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4098. # determine the coordinates for the lowest left point of the canvas
  4099. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4100. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4101. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4102. # canvas) and the point (width, height) is in the top-right location
  4103. loc = self.plotcanvas.axes.transData.transform_point(location)
  4104. j_pos = (
  4105. int(x0 + loc[0]),
  4106. int(y0 - loc[1])
  4107. )
  4108. cursor.setPos(j_pos[0], j_pos[1])
  4109. self.plotcanvas.mouse = [location[0], location[1]]
  4110. if self.defaults["global_cursor_color_enabled"] is True:
  4111. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4112. else:
  4113. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4114. if self.grid_status():
  4115. # Update cursor
  4116. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4117. symbol='++', edge_color=self.cursor_color_3D,
  4118. edge_width=self.defaults["global_cursor_width"],
  4119. size=self.defaults["global_cursor_size"])
  4120. # Set the relative position label
  4121. self.dx = location[0] - float(self.rel_point1[0])
  4122. self.dy = location[1] - float(self.rel_point1[1])
  4123. # Set the position label
  4124. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4125. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4126. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4127. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4128. units = self.defaults["units"].lower()
  4129. self.plotcanvas.text_hud.text = \
  4130. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4131. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4132. self.inform.emit('[success] %s' % _("Done."))
  4133. return location
  4134. def on_copy_command(self):
  4135. """
  4136. Will copy a selection of objects, creating new objects.
  4137. :return:
  4138. """
  4139. self.defaults.report_usage("on_copy_command()")
  4140. def initialize(obj_init, app):
  4141. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4142. try:
  4143. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4144. except AttributeError:
  4145. pass
  4146. try:
  4147. obj_init.apertures = deepcopy(obj.apertures)
  4148. except AttributeError:
  4149. pass
  4150. try:
  4151. if obj.tools:
  4152. obj_init.tools = deepcopy(obj.tools)
  4153. except Exception as err:
  4154. log.debug("App.on_copy_command() --> %s" % str(err))
  4155. try:
  4156. obj_init.source_file = deepcopy(obj.source_file)
  4157. except (AttributeError, TypeError):
  4158. pass
  4159. def initialize_excellon(obj_init, app):
  4160. obj_init.source_file = deepcopy(obj.source_file)
  4161. obj_init.tools = deepcopy(obj.tools)
  4162. # drills are offset, so they need to be deep copied
  4163. obj_init.drills = deepcopy(obj.drills)
  4164. # slots are offset, so they need to be deep copied
  4165. obj_init.slots = deepcopy(obj.slots)
  4166. obj_init.create_geometry()
  4167. def initialize_script(obj_init, app_obj):
  4168. obj_init.source_file = deepcopy(obj.source_file)
  4169. def initialize_document(obj_init, app_obj):
  4170. obj_init.source_file = deepcopy(obj.source_file)
  4171. for obj in self.collection.get_selected():
  4172. obj_name = obj.options["name"]
  4173. try:
  4174. if isinstance(obj, ExcellonObject):
  4175. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4176. elif isinstance(obj, GerberObject):
  4177. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4178. elif isinstance(obj, GeometryObject):
  4179. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4180. elif isinstance(obj, ScriptObject):
  4181. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4182. elif isinstance(obj, DocumentObject):
  4183. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4184. except Exception as e:
  4185. return "Operation failed: %s" % str(e)
  4186. def on_copy_object2(self, custom_name):
  4187. def initialize_geometry(obj_init, app):
  4188. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4189. try:
  4190. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4191. except AttributeError:
  4192. pass
  4193. try:
  4194. obj_init.apertures = deepcopy(obj.apertures)
  4195. except AttributeError:
  4196. pass
  4197. try:
  4198. if obj.tools:
  4199. obj_init.tools = deepcopy(obj.tools)
  4200. except Exception as ee:
  4201. log.debug("on_copy_object2() --> %s" % str(ee))
  4202. def initialize_gerber(obj_init, app):
  4203. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4204. obj_init.apertures = deepcopy(obj.apertures)
  4205. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4206. def initialize_excellon(obj_init, app):
  4207. obj_init.tools = deepcopy(obj.tools)
  4208. # drills are offset, so they need to be deep copied
  4209. obj_init.drills = deepcopy(obj.drills)
  4210. # slots are offset, so they need to be deep copied
  4211. obj_init.slots = deepcopy(obj.slots)
  4212. obj_init.create_geometry()
  4213. for obj in self.collection.get_selected():
  4214. obj_name = obj.options["name"]
  4215. try:
  4216. if isinstance(obj, ExcellonObject):
  4217. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4218. elif isinstance(obj, GerberObject):
  4219. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4220. elif isinstance(obj, GeometryObject):
  4221. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4222. except Exception as er:
  4223. return "Operation failed: %s" % str(er)
  4224. def on_rename_object(self, text):
  4225. """
  4226. Will rename an object.
  4227. :param text: New name for the object.
  4228. :return:
  4229. """
  4230. self.defaults.report_usage("on_rename_object()")
  4231. named_obj = self.collection.get_active()
  4232. for obj in named_obj:
  4233. if obj is list:
  4234. self.on_rename_object(text)
  4235. else:
  4236. try:
  4237. obj.options['name'] = text
  4238. except Exception as e:
  4239. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4240. def convert_any2geo(self):
  4241. """
  4242. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4243. :return:
  4244. """
  4245. self.defaults.report_usage("convert_any2geo()")
  4246. def initialize(obj_init, app):
  4247. obj_init.solid_geometry = obj.solid_geometry
  4248. try:
  4249. obj_init.follow_geometry = obj.follow_geometry
  4250. except AttributeError:
  4251. pass
  4252. try:
  4253. obj_init.apertures = obj.apertures
  4254. except AttributeError:
  4255. pass
  4256. try:
  4257. if obj.tools:
  4258. obj_init.tools = obj.tools
  4259. except AttributeError:
  4260. pass
  4261. def initialize_excellon(obj_init, app):
  4262. # objs = self.collection.get_selected()
  4263. # GeometryObject.merge(objs, obj)
  4264. solid_geo = []
  4265. for tool in obj.tools:
  4266. for geo in obj.tools[tool]['solid_geometry']:
  4267. solid_geo.append(geo)
  4268. obj_init.solid_geometry = deepcopy(solid_geo)
  4269. if not self.collection.get_selected():
  4270. log.warning("App.convert_any2geo --> No object selected")
  4271. self.inform.emit('[WARNING_NOTCL] %s' %
  4272. _("No object is selected. Select an object and try again."))
  4273. return
  4274. for obj in self.collection.get_selected():
  4275. obj_name = obj.options["name"]
  4276. try:
  4277. if isinstance(obj, ExcellonObject):
  4278. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4279. else:
  4280. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4281. except Exception as e:
  4282. return "Operation failed: %s" % str(e)
  4283. def convert_any2gerber(self):
  4284. """
  4285. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4286. :return:
  4287. """
  4288. self.defaults.report_usage("convert_any2gerber()")
  4289. def initialize_geometry(obj_init, app):
  4290. apertures = {}
  4291. apid = 0
  4292. apertures[str(apid)] = {}
  4293. apertures[str(apid)]['geometry'] = []
  4294. for obj_orig in obj.solid_geometry:
  4295. new_elem = {}
  4296. new_elem['solid'] = obj_orig
  4297. try:
  4298. new_elem['follow'] = obj_orig.exterior
  4299. except AttributeError:
  4300. pass
  4301. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4302. apertures[str(apid)]['size'] = 0.0
  4303. apertures[str(apid)]['type'] = 'C'
  4304. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4305. obj_init.apertures = deepcopy(apertures)
  4306. def initialize_excellon(obj_init, app):
  4307. apertures = {}
  4308. apid = 10
  4309. for tool in obj.tools:
  4310. apertures[str(apid)] = {}
  4311. apertures[str(apid)]['geometry'] = []
  4312. for geo in obj.tools[tool]['solid_geometry']:
  4313. new_el = {}
  4314. new_el['solid'] = geo
  4315. new_el['follow'] = geo.exterior
  4316. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4317. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4318. apertures[str(apid)]['type'] = 'C'
  4319. apid += 1
  4320. # create solid_geometry
  4321. solid_geometry = []
  4322. for apid in apertures:
  4323. for geo_el in apertures[apid]['geometry']:
  4324. solid_geometry.append(geo_el['solid'])
  4325. solid_geometry = MultiPolygon(solid_geometry)
  4326. solid_geometry = solid_geometry.buffer(0.0000001)
  4327. obj_init.solid_geometry = deepcopy(solid_geometry)
  4328. obj_init.apertures = deepcopy(apertures)
  4329. # clear the working objects (perhaps not necessary due of Python GC)
  4330. apertures.clear()
  4331. if not self.collection.get_selected():
  4332. log.warning("App.convert_any2gerber --> No object selected")
  4333. self.inform.emit('[WARNING_NOTCL] %s' %
  4334. _("No object is selected. Select an object and try again."))
  4335. return
  4336. for obj in self.collection.get_selected():
  4337. obj_name = obj.options["name"]
  4338. try:
  4339. if isinstance(obj, ExcellonObject):
  4340. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4341. elif isinstance(obj, GeometryObject):
  4342. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4343. else:
  4344. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4345. except Exception as e:
  4346. return "Operation failed: %s" % str(e)
  4347. def abort_all_tasks(self):
  4348. """
  4349. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4350. on the first possible occasion.
  4351. :return:
  4352. """
  4353. if self.abort_flag is False:
  4354. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4355. self.abort_flag = True
  4356. self.cleanup.emit()
  4357. def app_is_idle(self):
  4358. if self.abort_flag:
  4359. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4360. self.abort_flag = False
  4361. def on_selectall(self):
  4362. """
  4363. Will draw a selection box shape around the selected objects.
  4364. :return:
  4365. """
  4366. self.defaults.report_usage("on_selectall()")
  4367. # delete the possible selection box around a possible selected object
  4368. self.delete_selection_shape()
  4369. for name in self.collection.get_names():
  4370. self.collection.set_active(name)
  4371. curr_sel_obj = self.collection.get_by_name(name)
  4372. # create the selection box around the selected object
  4373. if self.defaults['global_selection_shape'] is True:
  4374. self.draw_selection_shape(curr_sel_obj)
  4375. def on_preferences(self):
  4376. """
  4377. Adds the Preferences in a Tab in Plot Area
  4378. :return:
  4379. """
  4380. # add the tab if it was closed
  4381. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4382. # delete the absolute and relative position and messages in the infobar
  4383. self.ui.position_label.setText("")
  4384. # self.ui.rel_position_label.setText("")
  4385. # Switch plot_area to preferences page
  4386. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4387. # self.ui.show()
  4388. # detect changes in the preferences
  4389. for idx in range(self.ui.pref_tab_area.count()):
  4390. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4391. try:
  4392. try:
  4393. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4394. except (TypeError, AttributeError):
  4395. pass
  4396. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4397. except AttributeError:
  4398. pass
  4399. try:
  4400. try:
  4401. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4402. except (TypeError, AttributeError):
  4403. pass
  4404. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4405. except AttributeError:
  4406. pass
  4407. try:
  4408. try:
  4409. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4410. except (TypeError, AttributeError):
  4411. pass
  4412. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4413. except AttributeError:
  4414. pass
  4415. try:
  4416. try:
  4417. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4418. except (TypeError, AttributeError):
  4419. pass
  4420. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4421. except AttributeError:
  4422. pass
  4423. try:
  4424. try:
  4425. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4426. except (TypeError, AttributeError):
  4427. pass
  4428. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4429. except AttributeError:
  4430. pass
  4431. def on_tools_database(self, source='app'):
  4432. """
  4433. Adds the Tools Database in a Tab in Plot Area.
  4434. :return:
  4435. """
  4436. for idx in range(self.ui.plot_tab_area.count()):
  4437. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4438. # there can be only one instance of Tools Database at one time
  4439. return
  4440. if source == 'app':
  4441. self.tools_db_tab = ToolsDB2(
  4442. app=self,
  4443. parent=self.ui,
  4444. callback_on_edited=self.on_tools_db_edited,
  4445. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4446. )
  4447. elif source == 'ncc':
  4448. self.tools_db_tab = ToolsDB2(
  4449. app=self,
  4450. parent=self.ui,
  4451. callback_on_edited=self.on_tools_db_edited,
  4452. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4453. )
  4454. elif source == 'paint':
  4455. self.tools_db_tab = ToolsDB2(
  4456. app=self,
  4457. parent=self.ui,
  4458. callback_on_edited=self.on_tools_db_edited,
  4459. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4460. )
  4461. # add the tab if it was closed
  4462. try:
  4463. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4464. self.tools_db_tab.setObjectName("database_tab")
  4465. except Exception as e:
  4466. log.debug("App.on_tools_database() --> %s" % str(e))
  4467. return
  4468. # delete the absolute and relative position and messages in the infobar
  4469. self.ui.position_label.setText("")
  4470. # self.ui.rel_position_label.setText("")
  4471. # Switch plot_area to preferences page
  4472. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4473. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4474. self.tools_db_tab.ui_connect()
  4475. def on_tools_db_edited(self):
  4476. """
  4477. Executed whenever a tool is edited in Tools Database.
  4478. Will color the text of the Tools Database tab to Red color.
  4479. :return:
  4480. """
  4481. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4482. for idx in range(self.ui.plot_tab_area.count()):
  4483. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4484. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4485. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4486. self.tools_db_changed_flag = True
  4487. def on_geometry_tool_add_from_db_executed(self, tool):
  4488. """
  4489. Here add the tool from DB in the selected geometry object.
  4490. :return:
  4491. """
  4492. tool_from_db = deepcopy(tool)
  4493. obj = self.collection.get_active()
  4494. if isinstance(obj, GeometryObject):
  4495. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4496. # close the tab and delete it
  4497. for idx in range(self.ui.plot_tab_area.count()):
  4498. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4499. wdg = self.ui.plot_tab_area.widget(idx)
  4500. wdg.deleteLater()
  4501. self.ui.plot_tab_area.removeTab(idx)
  4502. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4503. else:
  4504. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4505. def on_plot_area_tab_closed(self, tab_obj_name):
  4506. """
  4507. Executed whenever a QTab is closed in the Plot Area.
  4508. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4509. :return:
  4510. """
  4511. if tab_obj_name == "preferences_tab":
  4512. self.preferencesUiManager.on_close_preferences_tab()
  4513. elif tab_obj_name == "database_tab":
  4514. # disconnect the signals from the table widget in tab
  4515. self.tools_db_tab.ui_disconnect()
  4516. if self.tools_db_changed_flag is True:
  4517. msgbox = QtWidgets.QMessageBox()
  4518. msgbox.setText(_("One or more Tools are edited.\n"
  4519. "Do you want to update the Tools Database?"))
  4520. msgbox.setWindowTitle(_("Save Tools Database"))
  4521. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4522. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4523. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4524. msgbox.setDefaultButton(bt_yes)
  4525. msgbox.exec_()
  4526. response = msgbox.clickedButton()
  4527. if response == bt_yes:
  4528. self.tools_db_tab.on_save_tools_db()
  4529. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4530. else:
  4531. self.tools_db_changed_flag = False
  4532. self.inform.emit('')
  4533. return
  4534. self.tools_db_tab.deleteLater()
  4535. elif tab_obj_name == "text_editor_tab":
  4536. self.toggle_codeeditor = False
  4537. elif tab_obj_name == "bookmarks_tab":
  4538. self.book_dialog_tab.rebuild_actions()
  4539. self.book_dialog_tab.deleteLater()
  4540. else:
  4541. return
  4542. # def on_plotarea_tab_closed(self, tab_idx):
  4543. # """
  4544. #
  4545. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4546. # :return:
  4547. # """
  4548. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4549. #
  4550. # if widget is not None:
  4551. # widget.deleteLater()
  4552. # self.ui.plot_tab_area.removeTab(tab_idx)
  4553. def on_flipy(self):
  4554. """
  4555. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4556. :return:
  4557. """
  4558. self.defaults.report_usage("on_flipy()")
  4559. obj_list = self.collection.get_selected()
  4560. xminlist = []
  4561. yminlist = []
  4562. xmaxlist = []
  4563. ymaxlist = []
  4564. if not obj_list:
  4565. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4566. else:
  4567. try:
  4568. # first get a bounding box to fit all
  4569. for obj in obj_list:
  4570. xmin, ymin, xmax, ymax = obj.bounds()
  4571. xminlist.append(xmin)
  4572. yminlist.append(ymin)
  4573. xmaxlist.append(xmax)
  4574. ymaxlist.append(ymax)
  4575. # get the minimum x,y and maximum x,y for all objects selected
  4576. xminimal = min(xminlist)
  4577. yminimal = min(yminlist)
  4578. xmaximal = max(xmaxlist)
  4579. ymaximal = max(ymaxlist)
  4580. px = 0.5 * (xminimal + xmaximal)
  4581. py = 0.5 * (yminimal + ymaximal)
  4582. # execute mirroring
  4583. for obj in obj_list:
  4584. obj.mirror('X', [px, py])
  4585. obj.plot()
  4586. self.app_obj.object_changed.emit(obj)
  4587. self.inform.emit('[success] %s' %
  4588. _("Flip on Y axis done."))
  4589. except Exception as e:
  4590. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4591. return
  4592. def on_flipx(self):
  4593. """
  4594. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4595. :return:
  4596. """
  4597. self.defaults.report_usage("on_flipx()")
  4598. obj_list = self.collection.get_selected()
  4599. xminlist = []
  4600. yminlist = []
  4601. xmaxlist = []
  4602. ymaxlist = []
  4603. if not obj_list:
  4604. self.inform.emit('[WARNING_NOTCL] %s' %
  4605. _("No object selected to Flip on X axis."))
  4606. else:
  4607. try:
  4608. # first get a bounding box to fit all
  4609. for obj in obj_list:
  4610. xmin, ymin, xmax, ymax = obj.bounds()
  4611. xminlist.append(xmin)
  4612. yminlist.append(ymin)
  4613. xmaxlist.append(xmax)
  4614. ymaxlist.append(ymax)
  4615. # get the minimum x,y and maximum x,y for all objects selected
  4616. xminimal = min(xminlist)
  4617. yminimal = min(yminlist)
  4618. xmaximal = max(xmaxlist)
  4619. ymaximal = max(ymaxlist)
  4620. px = 0.5 * (xminimal + xmaximal)
  4621. py = 0.5 * (yminimal + ymaximal)
  4622. # execute mirroring
  4623. for obj in obj_list:
  4624. obj.mirror('Y', [px, py])
  4625. obj.plot()
  4626. self.app_obj.object_changed.emit(obj)
  4627. self.inform.emit('[success] %s' %
  4628. _("Flip on X axis done."))
  4629. except Exception as e:
  4630. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4631. return
  4632. def on_rotate(self, silent=False, preset=None):
  4633. """
  4634. Executed when Options -> Rotate Selection menu entry is clicked.
  4635. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4636. :param preset: A value to be used as predefined angle for rotation.
  4637. :return:
  4638. """
  4639. self.defaults.report_usage("on_rotate()")
  4640. obj_list = self.collection.get_selected()
  4641. xminlist = []
  4642. yminlist = []
  4643. xmaxlist = []
  4644. ymaxlist = []
  4645. if not obj_list:
  4646. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4647. else:
  4648. if silent is False:
  4649. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4650. min=-360, max=360, decimals=4,
  4651. init_val=float(self.defaults['tools_transform_rotate']))
  4652. num, ok = rotatebox.get_value()
  4653. else:
  4654. num = preset
  4655. ok = True
  4656. if ok:
  4657. try:
  4658. # first get a bounding box to fit all
  4659. for obj in obj_list:
  4660. xmin, ymin, xmax, ymax = obj.bounds()
  4661. xminlist.append(xmin)
  4662. yminlist.append(ymin)
  4663. xmaxlist.append(xmax)
  4664. ymaxlist.append(ymax)
  4665. # get the minimum x,y and maximum x,y for all objects selected
  4666. xminimal = min(xminlist)
  4667. yminimal = min(yminlist)
  4668. xmaximal = max(xmaxlist)
  4669. ymaximal = max(ymaxlist)
  4670. px = 0.5 * (xminimal + xmaximal)
  4671. py = 0.5 * (yminimal + ymaximal)
  4672. for sel_obj in obj_list:
  4673. sel_obj.rotate(-float(num), point=(px, py))
  4674. sel_obj.plot()
  4675. self.app_obj.object_changed.emit(sel_obj)
  4676. self.inform.emit('[success] %s' % _("Rotation done."))
  4677. except Exception as e:
  4678. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4679. return
  4680. def on_skewx(self):
  4681. """
  4682. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4683. :return:
  4684. """
  4685. self.defaults.report_usage("on_skewx()")
  4686. obj_list = self.collection.get_selected()
  4687. xminlist = []
  4688. yminlist = []
  4689. if not obj_list:
  4690. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4691. else:
  4692. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4693. min=-360, max=360, decimals=4,
  4694. init_val=float(self.defaults['tools_transform_skew_x']))
  4695. num, ok = skewxbox.get_value()
  4696. if ok:
  4697. # first get a bounding box to fit all
  4698. for obj in obj_list:
  4699. xmin, ymin, xmax, ymax = obj.bounds()
  4700. xminlist.append(xmin)
  4701. yminlist.append(ymin)
  4702. # get the minimum x,y and maximum x,y for all objects selected
  4703. xminimal = min(xminlist)
  4704. yminimal = min(yminlist)
  4705. for obj in obj_list:
  4706. obj.skew(num, 0, point=(xminimal, yminimal))
  4707. obj.plot()
  4708. self.app_obj.object_changed.emit(obj)
  4709. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4710. def on_skewy(self):
  4711. """
  4712. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4713. :return:
  4714. """
  4715. self.defaults.report_usage("on_skewy()")
  4716. obj_list = self.collection.get_selected()
  4717. xminlist = []
  4718. yminlist = []
  4719. if not obj_list:
  4720. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4721. else:
  4722. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4723. min=-360, max=360, decimals=4,
  4724. init_val=float(self.defaults['tools_transform_skew_y']))
  4725. num, ok = skewybox.get_value()
  4726. if ok:
  4727. # first get a bounding box to fit all
  4728. for obj in obj_list:
  4729. xmin, ymin, xmax, ymax = obj.bounds()
  4730. xminlist.append(xmin)
  4731. yminlist.append(ymin)
  4732. # get the minimum x,y and maximum x,y for all objects selected
  4733. xminimal = min(xminlist)
  4734. yminimal = min(yminlist)
  4735. for obj in obj_list:
  4736. obj.skew(0, num, point=(xminimal, yminimal))
  4737. obj.plot()
  4738. self.app_obj.object_changed.emit(obj)
  4739. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4740. def on_plots_updated(self):
  4741. """
  4742. Callback used to report when the plots have changed.
  4743. Adjust axes and zooms to fit.
  4744. :return: None
  4745. """
  4746. if self.is_legacy is False:
  4747. self.plotcanvas.update()
  4748. else:
  4749. self.plotcanvas.auto_adjust_axes()
  4750. self.on_zoom_fit()
  4751. self.collection.update_view()
  4752. # self.inform.emit(_("Plots updated ..."))
  4753. def on_toolbar_replot(self):
  4754. """
  4755. Callback for toolbar button. Re-plots all objects.
  4756. :return: None
  4757. """
  4758. self.defaults.report_usage("on_toolbar_replot")
  4759. self.log.debug("on_toolbar_replot()")
  4760. try:
  4761. self.collection.get_active().read_form()
  4762. except AttributeError:
  4763. self.log.debug("on_toolbar_replot(): AttributeError")
  4764. pass
  4765. self.plot_all()
  4766. def grid_status(self):
  4767. return True if self.ui.grid_snap_btn.isChecked() else False
  4768. def populate_cmenu_grids(self):
  4769. units = self.defaults['units'].lower()
  4770. # for act in self.ui.cmenu_gridmenu.actions():
  4771. # act.triggered.disconnect()
  4772. self.ui.cmenu_gridmenu.clear()
  4773. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4774. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4775. _("Grid On/Off"))
  4776. grid_toggle.setCheckable(True)
  4777. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4778. self.ui.cmenu_gridmenu.addSeparator()
  4779. for grid in sorted_list:
  4780. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4781. "%s" % str(grid))
  4782. action.triggered.connect(self.set_grid)
  4783. self.ui.cmenu_gridmenu.addSeparator()
  4784. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4785. _("Add"))
  4786. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4787. _("Delete"))
  4788. grid_add.triggered.connect(self.on_grid_add)
  4789. grid_delete.triggered.connect(self.on_grid_delete)
  4790. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4791. def set_grid(self):
  4792. menu_action = self.sender()
  4793. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4794. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4795. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4796. def on_grid_add(self):
  4797. # ## Current application units in lower Case
  4798. units = self.defaults['units'].lower()
  4799. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4800. text=_('Enter a Grid Value:'),
  4801. min=0.0000, max=99.9999, decimals=4)
  4802. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4803. val, ok = grid_add_popup.get_value()
  4804. if ok:
  4805. if float(val) == 0:
  4806. self.inform.emit('[WARNING_NOTCL] %s' %
  4807. _("Please enter a grid value with non-zero value, in Float format."))
  4808. return
  4809. else:
  4810. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4811. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4812. self.inform.emit('[success] %s...' % _("New Grid added"))
  4813. else:
  4814. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4815. else:
  4816. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4817. def on_grid_delete(self):
  4818. # ## Current application units in lower Case
  4819. units = self.defaults['units'].lower()
  4820. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4821. text='Enter a Grid Value:',
  4822. min=0.0000, max=99.9999, decimals=4)
  4823. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4824. val, ok = grid_del_popup.get_value()
  4825. if ok:
  4826. if float(val) == 0:
  4827. self.inform.emit('[WARNING_NOTCL] %s' %
  4828. _("Please enter a grid value with non-zero value, in Float format."))
  4829. return
  4830. else:
  4831. try:
  4832. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4833. except ValueError:
  4834. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4835. return
  4836. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4837. else:
  4838. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4839. def on_shortcut_list(self):
  4840. self.defaults.report_usage("on_shortcut_list()")
  4841. # add the tab if it was closed
  4842. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4843. # delete the absolute and relative position and messages in the infobar
  4844. self.ui.position_label.setText("")
  4845. # self.ui.rel_position_label.setText("")
  4846. # Switch plot_area to preferences page
  4847. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4848. # self.ui.show()
  4849. def on_select_tab(self, name):
  4850. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4851. if self.ui.splitter.sizes()[0] == 0:
  4852. self.ui.splitter.setSizes([1, 1])
  4853. else:
  4854. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4855. self.ui.splitter.setSizes([0, 1])
  4856. if name == 'project':
  4857. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4858. elif name == 'selected':
  4859. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4860. elif name == 'tool':
  4861. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4862. def on_copy_name(self):
  4863. self.defaults.report_usage("on_copy_name()")
  4864. obj = self.collection.get_active()
  4865. try:
  4866. name = obj.options["name"]
  4867. except AttributeError:
  4868. log.debug("on_copy_name() --> No object selected to copy it's name")
  4869. self.inform.emit('[WARNING_NOTCL]%s' %
  4870. _(" No object selected to copy it's name"))
  4871. return
  4872. self.clipboard.setText(name)
  4873. self.inform.emit(_("Name copied on clipboard ..."))
  4874. def on_mouse_click_over_plot(self, event):
  4875. """
  4876. Default actions are:
  4877. :param event: Contains information about the event, like which button
  4878. was clicked, the pixel coordinates and the axes coordinates.
  4879. :return: None
  4880. """
  4881. self.pos = []
  4882. if self.is_legacy is False:
  4883. event_pos = event.pos
  4884. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4885. # # Set the mouse button for panning
  4886. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4887. else:
  4888. event_pos = (event.xdata, event.ydata)
  4889. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4890. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4891. # So it can receive key presses
  4892. self.plotcanvas.native.setFocus()
  4893. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4894. if self.grid_status():
  4895. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4896. else:
  4897. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4898. try:
  4899. if event.button == 1:
  4900. # Reset here the relative coordinates so there is a new reference on the click position
  4901. if self.rel_point1 is None:
  4902. self.rel_point1 = self.pos
  4903. else:
  4904. self.rel_point2 = copy(self.rel_point1)
  4905. self.rel_point1 = self.pos
  4906. self.on_mouse_move_over_plot(event, origin_click=True)
  4907. except Exception as e:
  4908. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4909. def on_mouse_double_click_over_plot(self, event):
  4910. if event.button == 1:
  4911. self.doubleclick = True
  4912. def on_mouse_move_over_plot(self, event, origin_click=None):
  4913. """
  4914. Callback for the mouse motion event over the plot.
  4915. :param event: Contains information about the event.
  4916. :param origin_click
  4917. :return: None
  4918. """
  4919. if self.is_legacy is False:
  4920. event_pos = event.pos
  4921. if self.defaults["global_pan_button"] == '2':
  4922. pan_button = 2
  4923. else:
  4924. pan_button = 3
  4925. self.event_is_dragging = event.is_dragging
  4926. else:
  4927. event_pos = (event.xdata, event.ydata)
  4928. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4929. if self.defaults["global_pan_button"] == '2':
  4930. pan_button = 3
  4931. else:
  4932. pan_button = 2
  4933. self.event_is_dragging = self.plotcanvas.is_dragging
  4934. # So it can receive key presses but not when the Tcl Shell is active
  4935. if not self.ui.shell_dock.isVisible():
  4936. if not self.plotcanvas.native.hasFocus():
  4937. self.plotcanvas.native.setFocus()
  4938. self.pos_jump = event_pos
  4939. self.ui.popMenu.mouse_is_panning = False
  4940. if origin_click is None:
  4941. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4942. if event.button == pan_button and self.event_is_dragging == 1:
  4943. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4944. if self.ui.popMenu.popup_active:
  4945. self.ui.popMenu.popup_active = False
  4946. return
  4947. self.ui.popMenu.mouse_is_panning = True
  4948. return
  4949. if self.rel_point1 is not None:
  4950. try: # May fail in case mouse not within axes
  4951. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4952. if pos_canvas[0] is None or pos_canvas[1] is None:
  4953. return
  4954. if self.grid_status():
  4955. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4956. # Update cursor
  4957. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4958. symbol='++', edge_color=self.cursor_color_3D,
  4959. edge_width=self.defaults["global_cursor_width"],
  4960. size=self.defaults["global_cursor_size"])
  4961. else:
  4962. pos = (pos_canvas[0], pos_canvas[1])
  4963. self.dx = pos[0] - float(self.rel_point1[0])
  4964. self.dy = pos[1] - float(self.rel_point1[1])
  4965. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4966. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4967. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4968. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4969. units = self.defaults["units"].lower()
  4970. self.plotcanvas.text_hud.text = \
  4971. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4972. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4973. self.mouse = [pos[0], pos[1]]
  4974. # if the mouse is moved and the LMB is clicked then the action is a selection
  4975. if self.event_is_dragging == 1 and event.button == 1:
  4976. self.delete_selection_shape()
  4977. if self.dx < 0:
  4978. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4979. face_color=self.defaults['global_alt_sel_fill'])
  4980. self.selection_type = False
  4981. elif self.dx >= 0:
  4982. self.draw_moving_selection_shape(self.pos, pos)
  4983. self.selection_type = True
  4984. else:
  4985. self.selection_type = None
  4986. else:
  4987. self.selection_type = None
  4988. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4989. if self.defaults['global_hover']:
  4990. for obj in self.collection.get_list():
  4991. try:
  4992. # select the object(s) only if it is enabled (plotted)
  4993. if obj.options['plot']:
  4994. if obj not in self.collection.get_selected():
  4995. poly_obj = Polygon(
  4996. [(obj.options['xmin'], obj.options['ymin']),
  4997. (obj.options['xmax'], obj.options['ymin']),
  4998. (obj.options['xmax'], obj.options['ymax']),
  4999. (obj.options['xmin'], obj.options['ymax'])]
  5000. )
  5001. if Point(pos).within(poly_obj):
  5002. if obj.isHovering is False:
  5003. obj.isHovering = True
  5004. obj.notHovering = True
  5005. # create the selection box around the selected object
  5006. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5007. else:
  5008. if obj.notHovering is True:
  5009. obj.notHovering = False
  5010. obj.isHovering = False
  5011. self.delete_hover_shape()
  5012. except Exception:
  5013. # the Exception here will happen if we try to select on screen and we have an
  5014. # newly (and empty) just created Geometry or Excellon object that do not have the
  5015. # xmin, xmax, ymin, ymax options.
  5016. # In this case poly_obj creation (see above) will fail
  5017. pass
  5018. except Exception as e:
  5019. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5020. self.ui.position_label.setText("")
  5021. # self.ui.rel_position_label.setText("")
  5022. self.mouse = None
  5023. def on_mouse_click_release_over_plot(self, event):
  5024. """
  5025. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5026. and has been registered in ''self.__init__()''.
  5027. :param event: contains information about the event.
  5028. :return:
  5029. """
  5030. if self.is_legacy is False:
  5031. event_pos = event.pos
  5032. right_button = 2
  5033. else:
  5034. event_pos = (event.xdata, event.ydata)
  5035. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5036. right_button = 3
  5037. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5038. if self.grid_status():
  5039. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5040. else:
  5041. pos = (pos_canvas[0], pos_canvas[1])
  5042. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5043. # canvas menu
  5044. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5045. self.ui.popMenu.mouse_is_panning = False
  5046. self.cursor = QtGui.QCursor()
  5047. self.populate_cmenu_grids()
  5048. self.ui.popMenu.popup(self.cursor.pos())
  5049. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5050. # selection and then select a type of selection ("enclosing" or "touching")
  5051. if event.button == 1: # left click
  5052. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5053. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5054. if modifiers == QtCore.Qt.ShiftModifier:
  5055. # do not auto open the Project Tab
  5056. self.click_noproject = True
  5057. self.clipboard.setText(
  5058. self.defaults["global_point_clipboard_format"] %
  5059. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5060. )
  5061. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5062. return
  5063. if self.doubleclick is True:
  5064. self.doubleclick = False
  5065. if self.collection.get_selected():
  5066. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5067. if self.ui.splitter.sizes()[0] == 0:
  5068. self.ui.splitter.setSizes([1, 1])
  5069. try:
  5070. # delete the selection shape(S) as it may be in the way
  5071. self.delete_selection_shape()
  5072. self.delete_hover_shape()
  5073. except Exception as e:
  5074. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5075. return
  5076. else:
  5077. # WORKAROUND for LEGACY MODE
  5078. if self.is_legacy is True:
  5079. # if there is no move on canvas then we have no dragging selection
  5080. if self.dx == 0 or self.dy == 0:
  5081. self.selection_type = None
  5082. if self.selection_type is not None:
  5083. try:
  5084. self.selection_area_handler(self.pos, pos, self.selection_type)
  5085. self.selection_type = None
  5086. except Exception as e:
  5087. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5088. return
  5089. else:
  5090. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5091. if key_modifier == QtCore.Qt.ShiftModifier:
  5092. mod_key = 'Shift'
  5093. elif key_modifier == QtCore.Qt.ControlModifier:
  5094. mod_key = 'Control'
  5095. else:
  5096. mod_key = None
  5097. try:
  5098. if self.command_active is None:
  5099. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5100. # deselect, and if it's not selected then it will be selected
  5101. # If there is no active command (self.command_active is None) then we check if we clicked
  5102. # on a object by checking the bounding limits against mouse click position
  5103. if mod_key == self.defaults["global_mselect_key"]:
  5104. self.select_objects(key='multisel')
  5105. else:
  5106. # If there is no active command (self.command_active is None) then we check if
  5107. # we clicked on a object by checking the bounding limits against mouse click position
  5108. self.select_objects()
  5109. self.delete_hover_shape()
  5110. except Exception as e:
  5111. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5112. return
  5113. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5114. """
  5115. :param start_pos: mouse position when the selection LMB click was done
  5116. :param end_pos: mouse position when the left mouse button is released
  5117. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5118. :return:
  5119. """
  5120. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5121. # delete previous selection shape
  5122. self.delete_selection_shape()
  5123. # make all objects inactive
  5124. self.collection.set_all_inactive()
  5125. for obj in self.collection.get_list():
  5126. try:
  5127. # select the object(s) only if it is enabled (plotted)
  5128. if obj.options['plot']:
  5129. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5130. (obj.options['xmax'], obj.options['ymin']),
  5131. (obj.options['xmax'], obj.options['ymax']),
  5132. (obj.options['xmin'], obj.options['ymax'])])
  5133. if sel_type is True:
  5134. if poly_obj.within(poly_selection):
  5135. # create the selection box around the selected object
  5136. if self.defaults['global_selection_shape'] is True:
  5137. self.draw_selection_shape(obj)
  5138. self.collection.set_active(obj.options['name'])
  5139. else:
  5140. if poly_selection.intersects(poly_obj):
  5141. # create the selection box around the selected object
  5142. if self.defaults['global_selection_shape'] is True:
  5143. self.draw_selection_shape(obj)
  5144. self.collection.set_active(obj.options['name'])
  5145. obj.selection_shape_drawn = True
  5146. except Exception as e:
  5147. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5148. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5149. # In this case poly_obj creation (see above) will fail
  5150. log.debug("App.selection_area_handler() --> %s" % str(e))
  5151. def select_objects(self, key=None):
  5152. """
  5153. Will select objects clicked on canvas
  5154. :param key: for future use in cumulative selection
  5155. :return:
  5156. """
  5157. # list where we store the overlapped objects under our mouse left click position
  5158. if key is None:
  5159. self.objects_under_the_click_list = []
  5160. # Populate the list with the overlapped objects on the click position
  5161. curr_x, curr_y = self.pos
  5162. for obj in self.all_objects_list:
  5163. # ScriptObject and DocumentObject objects can't be selected
  5164. if obj.kind == 'script' or obj.kind == 'document':
  5165. continue
  5166. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5167. continue
  5168. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5169. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5170. if obj.options['name'] not in self.objects_under_the_click_list:
  5171. if obj.options['plot']:
  5172. # add objects to the objects_under_the_click list only if the object is plotted
  5173. # (active and not disabled)
  5174. self.objects_under_the_click_list.append(obj.options['name'])
  5175. try:
  5176. if self.objects_under_the_click_list:
  5177. curr_sel_obj = self.collection.get_active()
  5178. # case when there is only an object under the click and we toggle it
  5179. if len(self.objects_under_the_click_list) == 1:
  5180. if curr_sel_obj is None:
  5181. self.collection.set_active(self.objects_under_the_click_list[0])
  5182. curr_sel_obj = self.collection.get_active()
  5183. # create the selection box around the selected object
  5184. if self.defaults['global_selection_shape'] is True:
  5185. self.draw_selection_shape(curr_sel_obj)
  5186. curr_sel_obj.selection_shape_drawn = True
  5187. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5188. self.collection.on_objects_selection(False)
  5189. self.delete_selection_shape()
  5190. curr_sel_obj.selection_shape_drawn = False
  5191. self.collection.set_active(self.objects_under_the_click_list[0])
  5192. curr_sel_obj = self.collection.get_active()
  5193. # create the selection box around the selected object
  5194. if self.defaults['global_selection_shape'] is True:
  5195. self.draw_selection_shape(curr_sel_obj)
  5196. curr_sel_obj.selection_shape_drawn = True
  5197. self.selected_message(curr_sel_obj=curr_sel_obj)
  5198. elif curr_sel_obj.selection_shape_drawn is False:
  5199. if self.defaults['global_selection_shape'] is True:
  5200. self.draw_selection_shape(curr_sel_obj)
  5201. curr_sel_obj.selection_shape_drawn = True
  5202. else:
  5203. self.collection.on_objects_selection(False)
  5204. self.delete_selection_shape()
  5205. if self.call_source != 'app':
  5206. self.call_source = 'app'
  5207. self.selected_message(curr_sel_obj=curr_sel_obj)
  5208. else:
  5209. # If there is no selected object
  5210. # make active the first element of the overlapped objects list
  5211. if self.collection.get_active() is None:
  5212. self.collection.set_active(self.objects_under_the_click_list[0])
  5213. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5214. name_sel_obj = self.collection.get_active().options['name']
  5215. # In case that there is a selected object but it is not in the overlapped object list
  5216. # make that object inactive and activate the first element in the overlapped object list
  5217. if name_sel_obj not in self.objects_under_the_click_list:
  5218. self.collection.set_inactive(name_sel_obj)
  5219. name_sel_obj = self.objects_under_the_click_list[0]
  5220. self.collection.set_active(name_sel_obj)
  5221. else:
  5222. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5223. self.collection.set_all_inactive()
  5224. self.collection.set_active(
  5225. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5226. curr_sel_obj = self.collection.get_active()
  5227. # delete the possible selection box around a possible selected object
  5228. self.delete_selection_shape()
  5229. curr_sel_obj.selection_shape_drawn = False
  5230. # create the selection box around the selected object
  5231. if self.defaults['global_selection_shape'] is True:
  5232. self.draw_selection_shape(curr_sel_obj)
  5233. curr_sel_obj.selection_shape_drawn = True
  5234. self.selected_message(curr_sel_obj=curr_sel_obj)
  5235. else:
  5236. # deselect everything
  5237. self.collection.on_objects_selection(False)
  5238. # delete the possible selection box around a possible selected object
  5239. self.delete_selection_shape()
  5240. for o in self.collection.get_list():
  5241. o.selection_shape_drawn = False
  5242. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5243. # only when working on App
  5244. if self.call_source == 'app':
  5245. if self.click_noproject is False:
  5246. # if the Tool Tab is in focus don't change focus to Project Tab
  5247. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5248. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5249. else:
  5250. # restore auto open the Project Tab
  5251. self.click_noproject = False
  5252. # delete any text in the status bar, implicitly the last object name that was selected
  5253. # self.inform.emit("")
  5254. else:
  5255. self.call_source = 'app'
  5256. except Exception as e:
  5257. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5258. def selected_message(self, curr_sel_obj):
  5259. if curr_sel_obj:
  5260. if curr_sel_obj.kind == 'gerber':
  5261. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5262. color='green',
  5263. name=str(curr_sel_obj.options['name']),
  5264. tx=_("selected"))
  5265. )
  5266. elif curr_sel_obj.kind == 'excellon':
  5267. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5268. color='brown',
  5269. name=str(curr_sel_obj.options['name']),
  5270. tx=_("selected"))
  5271. )
  5272. elif curr_sel_obj.kind == 'cncjob':
  5273. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5274. color='blue',
  5275. name=str(curr_sel_obj.options['name']),
  5276. tx=_("selected"))
  5277. )
  5278. elif curr_sel_obj.kind == 'geometry':
  5279. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5280. color='red',
  5281. name=str(curr_sel_obj.options['name']),
  5282. tx=_("selected"))
  5283. )
  5284. def delete_hover_shape(self):
  5285. self.hover_shapes.clear()
  5286. self.hover_shapes.redraw()
  5287. def draw_hover_shape(self, sel_obj, color=None):
  5288. """
  5289. :param sel_obj: The object for which the hover shape must be drawn
  5290. :param color: The color of the hover shape
  5291. :return: None
  5292. """
  5293. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5294. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5295. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5296. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5297. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5298. if self.defaults['units'].upper() == 'MM':
  5299. hover_rect = hover_rect.buffer(-0.1)
  5300. hover_rect = hover_rect.buffer(0.2)
  5301. else:
  5302. hover_rect = hover_rect.buffer(-0.00393)
  5303. hover_rect = hover_rect.buffer(0.00787)
  5304. # if color:
  5305. # face = Color(color)
  5306. # face.alpha = 0.2
  5307. # outline = Color(color, alpha=0.8)
  5308. # else:
  5309. # face = Color(self.defaults['global_sel_fill'])
  5310. # face.alpha = 0.2
  5311. # outline = self.defaults['global_sel_line']
  5312. if color:
  5313. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5314. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5315. else:
  5316. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5317. outline = self.defaults['global_sel_line']
  5318. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5319. if self.is_legacy is True:
  5320. self.hover_shapes.redraw()
  5321. def delete_selection_shape(self):
  5322. self.move_tool.sel_shapes.clear()
  5323. self.move_tool.sel_shapes.redraw()
  5324. def draw_selection_shape(self, sel_obj, color=None):
  5325. """
  5326. Will draw a selection shape around the selected object.
  5327. :param sel_obj: The object for which the selection shape must be drawn
  5328. :param color: The color for the selection shape.
  5329. :return: None
  5330. """
  5331. if sel_obj is None:
  5332. return
  5333. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5334. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5335. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5336. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5337. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5338. if self.defaults['units'].upper() == 'MM':
  5339. sel_rect = sel_rect.buffer(-0.1)
  5340. sel_rect = sel_rect.buffer(0.2)
  5341. else:
  5342. sel_rect = sel_rect.buffer(-0.00393)
  5343. sel_rect = sel_rect.buffer(0.00787)
  5344. if color:
  5345. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5346. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5347. else:
  5348. if self.is_legacy is False:
  5349. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5350. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5351. else:
  5352. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5353. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5354. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5355. color=outline,
  5356. face_color=face,
  5357. update=True,
  5358. layer=0,
  5359. tolerance=None))
  5360. if self.is_legacy is True:
  5361. self.move_tool.sel_shapes.redraw()
  5362. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5363. """
  5364. Will draw a selection shape when dragging mouse on canvas.
  5365. :param old_coords: Old coordinates
  5366. :param coords: New coordinates
  5367. :param kwargs: Keyword arguments
  5368. :return:
  5369. """
  5370. if 'color' in kwargs:
  5371. color = kwargs['color']
  5372. else:
  5373. color = self.defaults['global_sel_line']
  5374. if 'face_color' in kwargs:
  5375. face_color = kwargs['face_color']
  5376. else:
  5377. face_color = self.defaults['global_sel_fill']
  5378. if 'face_alpha' in kwargs:
  5379. face_alpha = kwargs['face_alpha']
  5380. else:
  5381. face_alpha = 0.3
  5382. x0, y0 = old_coords
  5383. x1, y1 = coords
  5384. pt1 = (x0, y0)
  5385. pt2 = (x1, y0)
  5386. pt3 = (x1, y1)
  5387. pt4 = (x0, y1)
  5388. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5389. # color_t = Color(face_color)
  5390. # color_t.alpha = face_alpha
  5391. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5392. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5393. layer=0, tolerance=None)
  5394. if self.is_legacy is True:
  5395. self.move_tool.sel_shapes.redraw()
  5396. def on_file_new_click(self):
  5397. """
  5398. Callback for menu item File -> New.
  5399. Executed on clicking the Menu -> File -> New Project
  5400. :return:
  5401. """
  5402. if self.collection.get_list() and self.should_we_save:
  5403. msgbox = QtWidgets.QMessageBox()
  5404. # msgbox.setText("<B>Save changes ...</B>")
  5405. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5406. "Creating a New project will delete them.\n"
  5407. "Do you want to Save the project?"))
  5408. msgbox.setWindowTitle(_("Save changes"))
  5409. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5410. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5411. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5412. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5413. msgbox.setDefaultButton(bt_yes)
  5414. msgbox.exec_()
  5415. response = msgbox.clickedButton()
  5416. if response == bt_yes:
  5417. self.on_file_saveprojectas()
  5418. elif response == bt_cancel:
  5419. return
  5420. elif response == bt_no:
  5421. self.on_file_new()
  5422. else:
  5423. self.on_file_new()
  5424. self.inform.emit('[success] %s...' % _("New Project created"))
  5425. def on_file_new(self, cli=None):
  5426. """
  5427. Returns the application to its startup state. This method is thread-safe.
  5428. :param cli: Boolean. If True this method was run from command line
  5429. :return: None
  5430. """
  5431. self.defaults.report_usage("on_file_new")
  5432. # Remove everything from memory
  5433. App.log.debug("on_file_new()")
  5434. # close any editor that might be open
  5435. if self.call_source != 'app':
  5436. self.editor2object(cleanup=True)
  5437. # ## EDITOR section
  5438. self.geo_editor = FlatCAMGeoEditor(self)
  5439. self.exc_editor = FlatCAMExcEditor(self)
  5440. self.grb_editor = FlatCAMGrbEditor(self)
  5441. # Clear pool
  5442. self.clear_pool()
  5443. for obj in self.collection.get_list():
  5444. # delete shapes left drawn from mark shape_collections, if any
  5445. if isinstance(obj, GerberObject):
  5446. try:
  5447. for el in obj.mark_shapes:
  5448. obj.mark_shapes[el].clear(update=True)
  5449. obj.mark_shapes[el].enabled = False
  5450. del el
  5451. except AttributeError:
  5452. pass
  5453. # also delete annotation shapes, if any
  5454. elif isinstance(obj, CNCJobObject):
  5455. try:
  5456. obj.text_col.enabled = False
  5457. del obj.text_col
  5458. obj.annotation.clear(update=True)
  5459. del obj.annotation
  5460. except AttributeError:
  5461. pass
  5462. # delete the exclusion areas
  5463. self.exc_areas.clear_shapes()
  5464. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5465. self.shell.init_tcl()
  5466. # delete any selection shape on canvas
  5467. self.delete_selection_shape()
  5468. # delete all FlatCAM objects
  5469. self.collection.delete_all()
  5470. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5471. self.setup_component_editor()
  5472. # Clear project filename
  5473. self.project_filename = None
  5474. # Load the application defaults
  5475. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5476. # Re-fresh project options
  5477. self.on_options_app2project()
  5478. # Init FlatCAMTools
  5479. self.init_tools()
  5480. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5481. if cli is None:
  5482. # we need to go in reverse because once we remove a tab then the index changes
  5483. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5484. # and so on. Therefore the deletion should be done in reverse
  5485. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5486. for index in range(wdg_count, -1, -1):
  5487. try:
  5488. self.ui.plot_tab_area.closeTab(index)
  5489. except Exception as e:
  5490. log.debug("App.on_file_new() --> %s" % str(e))
  5491. # # And then add again the Plot Area
  5492. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5493. self.ui.plot_tab_area.protectTab(0)
  5494. # take the focus of the Notebook on Project Tab.
  5495. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5496. self.set_ui_title(name=_("New Project - Not saved"))
  5497. def obj_properties(self):
  5498. """
  5499. Will launch the object Properties Tool
  5500. :return:
  5501. """
  5502. self.defaults.report_usage("obj_properties()")
  5503. self.properties_tool.run(toggle=False)
  5504. def on_project_context_save(self):
  5505. """
  5506. Wrapper, will save the object function of it's type
  5507. :return:
  5508. """
  5509. obj = self.collection.get_active()
  5510. if type(obj) == GeometryObject:
  5511. self.on_file_exportdxf()
  5512. elif type(obj) == ExcellonObject:
  5513. self.on_file_saveexcellon()
  5514. elif type(obj) == CNCJobObject:
  5515. obj.on_exportgcode_button_click()
  5516. elif type(obj) == GerberObject:
  5517. self.on_file_savegerber()
  5518. elif type(obj) == ScriptObject:
  5519. self.on_file_savescript()
  5520. elif type(obj) == DocumentObject:
  5521. self.on_file_savedocument()
  5522. def obj_move(self):
  5523. """
  5524. Callback for the Move menu entry in various Context Menu's.
  5525. :return:
  5526. """
  5527. self.defaults.report_usage("obj_move()")
  5528. self.move_tool.run(toggle=False)
  5529. def on_fileopengerber(self, signal, name=None):
  5530. """
  5531. File menu callback for opening a Gerber.
  5532. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5533. :param name:
  5534. :return: None
  5535. """
  5536. self.defaults.report_usage("on_fileopengerber")
  5537. App.log.debug("on_fileopengerber()")
  5538. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5539. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5540. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5541. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5542. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5543. "*.mil);;" \
  5544. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5545. "Allegro Files (*.art);;" \
  5546. "Mentor Files (*.pho *.gdo);;" \
  5547. "All Files (*.*)"
  5548. if name is None:
  5549. try:
  5550. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5551. directory=self.get_last_folder(),
  5552. filter=_filter_)
  5553. except TypeError:
  5554. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5555. filenames = [str(filename) for filename in filenames]
  5556. else:
  5557. filenames = [name]
  5558. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5559. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5560. _("Opening Gerber file.")),
  5561. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5562. color=QtGui.QColor("gray"))
  5563. if len(filenames) == 0:
  5564. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5565. else:
  5566. for filename in filenames:
  5567. if filename != '':
  5568. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5569. def on_fileopenexcellon(self, signal, name=None):
  5570. """
  5571. File menu callback for opening an Excellon file.
  5572. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5573. :param name:
  5574. :return: None
  5575. """
  5576. self.defaults.report_usage("on_fileopenexcellon")
  5577. App.log.debug("on_fileopenexcellon()")
  5578. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5579. "All Files (*.*)"
  5580. if name is None:
  5581. try:
  5582. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5583. directory=self.get_last_folder(),
  5584. filter=_filter_)
  5585. except TypeError:
  5586. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5587. filenames = [str(filename) for filename in filenames]
  5588. else:
  5589. filenames = [str(name)]
  5590. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5591. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5592. _("Opening Excellon file.")),
  5593. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5594. color=QtGui.QColor("gray"))
  5595. if len(filenames) == 0:
  5596. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5597. else:
  5598. for filename in filenames:
  5599. if filename != '':
  5600. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5601. def on_fileopengcode(self, signal, name=None):
  5602. """
  5603. File menu call back for opening gcode.
  5604. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5605. :param name:
  5606. :return:
  5607. """
  5608. self.defaults.report_usage("on_fileopengcode")
  5609. App.log.debug("on_fileopengcode()")
  5610. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5611. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5612. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5613. "All Files (*.*)"
  5614. if name is None:
  5615. try:
  5616. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5617. directory=self.get_last_folder(),
  5618. filter=_filter_)
  5619. except TypeError:
  5620. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5621. filenames = [str(filename) for filename in filenames]
  5622. else:
  5623. filenames = [name]
  5624. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5625. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5626. _("Opening G-Code file.")),
  5627. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5628. color=QtGui.QColor("gray"))
  5629. if len(filenames) == 0:
  5630. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5631. else:
  5632. for filename in filenames:
  5633. if filename != '':
  5634. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5635. def on_file_openproject(self, signal):
  5636. """
  5637. File menu callback for opening a project.
  5638. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5639. :return: None
  5640. """
  5641. self.defaults.report_usage("on_file_openproject")
  5642. App.log.debug("on_file_openproject()")
  5643. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5644. try:
  5645. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5646. directory=self.get_last_folder(), filter=_filter_)
  5647. except TypeError:
  5648. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5649. # The Qt methods above will return a QString which can cause problems later.
  5650. # So far json.dump() will fail to serialize it.
  5651. # TODO: Improve the serialization methods and remove this fix.
  5652. filename = str(filename)
  5653. if filename == "":
  5654. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5655. else:
  5656. # self.worker_task.emit({'fcn': self.open_project,
  5657. # 'params': [filename]})
  5658. # The above was failing because open_project() is not
  5659. # thread safe. The new_project()
  5660. self.open_project(filename)
  5661. def on_fileopenhpgl2(self, signal, name=None):
  5662. """
  5663. File menu callback for opening a HPGL2.
  5664. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5665. :param name:
  5666. :return: None
  5667. """
  5668. self.defaults.report_usage("on_fileopenhpgl2")
  5669. App.log.debug("on_fileopenhpgl2()")
  5670. _filter_ = "HPGL2 Files (*.plt);;" \
  5671. "All Files (*.*)"
  5672. if name is None:
  5673. try:
  5674. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5675. directory=self.get_last_folder(),
  5676. filter=_filter_)
  5677. except TypeError:
  5678. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5679. filenames = [str(filename) for filename in filenames]
  5680. else:
  5681. filenames = [name]
  5682. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5683. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5684. _("Opening HPGL2 file.")),
  5685. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5686. color=QtGui.QColor("gray"))
  5687. if len(filenames) == 0:
  5688. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5689. else:
  5690. for filename in filenames:
  5691. if filename != '':
  5692. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5693. def on_file_openconfig(self, signal):
  5694. """
  5695. File menu callback for opening a config file.
  5696. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5697. :return: None
  5698. """
  5699. self.defaults.report_usage("on_file_openconfig")
  5700. App.log.debug("on_file_openconfig()")
  5701. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5702. try:
  5703. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5704. directory=self.data_path, filter=_filter_)
  5705. except TypeError:
  5706. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5707. filter=_filter_)
  5708. if filename == "":
  5709. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5710. else:
  5711. self.open_config_file(filename)
  5712. def on_file_exportsvg(self):
  5713. """
  5714. Callback for menu item File->Export SVG.
  5715. :return: None
  5716. """
  5717. self.defaults.report_usage("on_file_exportsvg")
  5718. App.log.debug("on_file_exportsvg()")
  5719. obj = self.collection.get_active()
  5720. if obj is None:
  5721. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5722. msg = _("Please Select a Geometry object to export")
  5723. msgbox = QtWidgets.QMessageBox()
  5724. msgbox.setInformativeText(msg)
  5725. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5726. msgbox.setDefaultButton(bt_ok)
  5727. msgbox.exec_()
  5728. return
  5729. # Check for more compatible types and add as required
  5730. if (not isinstance(obj, GeometryObject)
  5731. and not isinstance(obj, GerberObject)
  5732. and not isinstance(obj, CNCJobObject)
  5733. and not isinstance(obj, ExcellonObject)):
  5734. msg = '[ERROR_NOTCL] %s' % \
  5735. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5736. msgbox = QtWidgets.QMessageBox()
  5737. msgbox.setInformativeText(msg)
  5738. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5739. msgbox.setDefaultButton(bt_ok)
  5740. msgbox.exec_()
  5741. return
  5742. name = obj.options["name"]
  5743. _filter = "SVG File (*.svg);;All Files (*.*)"
  5744. try:
  5745. filename, _f = FCFileSaveDialog.get_saved_filename(
  5746. caption=_("Export SVG"),
  5747. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5748. filter=_filter)
  5749. except TypeError:
  5750. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5751. filename = str(filename)
  5752. if filename == "":
  5753. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5754. return
  5755. else:
  5756. self.export_svg(name, filename)
  5757. if self.defaults["global_open_style"] is False:
  5758. self.file_opened.emit("SVG", filename)
  5759. self.file_saved.emit("SVG", filename)
  5760. def on_file_exportpng(self):
  5761. self.defaults.report_usage("on_file_exportpng")
  5762. App.log.debug("on_file_exportpng()")
  5763. self.date = str(datetime.today()).rpartition('.')[0]
  5764. self.date = ''.join(c for c in self.date if c not in ':-')
  5765. self.date = self.date.replace(' ', '_')
  5766. if self.is_legacy is False:
  5767. image = _screenshot()
  5768. data = np.asarray(image)
  5769. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5770. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5771. return
  5772. filter_ = "PNG File (*.png);;All Files (*.*)"
  5773. try:
  5774. filename, _f = FCFileSaveDialog.get_saved_filename(
  5775. caption=_("Export PNG Image"),
  5776. directory=self.get_last_save_folder() + '/png_' + self.date,
  5777. filter=filter_)
  5778. except TypeError:
  5779. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5780. filename = str(filename)
  5781. if filename == "":
  5782. self.inform.emit(_("Cancelled."))
  5783. return
  5784. else:
  5785. if self.is_legacy is False:
  5786. write_png(filename, data)
  5787. else:
  5788. self.plotcanvas.figure.savefig(filename)
  5789. if self.defaults["global_open_style"] is False:
  5790. self.file_opened.emit("png", filename)
  5791. self.file_saved.emit("png", filename)
  5792. def on_file_savegerber(self):
  5793. """
  5794. Callback for menu item in Project context menu.
  5795. :return: None
  5796. """
  5797. self.defaults.report_usage("on_file_savegerber")
  5798. App.log.debug("on_file_savegerber()")
  5799. obj = self.collection.get_active()
  5800. if obj is None:
  5801. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5802. return
  5803. # Check for more compatible types and add as required
  5804. if not isinstance(obj, GerberObject):
  5805. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5806. return
  5807. name = self.collection.get_active().options["name"]
  5808. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5809. try:
  5810. filename, _f = FCFileSaveDialog.get_saved_filename(
  5811. caption="Save Gerber source file",
  5812. directory=self.get_last_save_folder() + '/' + name,
  5813. filter=_filter)
  5814. except TypeError:
  5815. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5816. filename = str(filename)
  5817. if filename == "":
  5818. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5819. return
  5820. else:
  5821. self.save_source_file(name, filename)
  5822. if self.defaults["global_open_style"] is False:
  5823. self.file_opened.emit("Gerber", filename)
  5824. self.file_saved.emit("Gerber", filename)
  5825. def on_file_savescript(self):
  5826. """
  5827. Callback for menu item in Project context menu.
  5828. :return: None
  5829. """
  5830. self.defaults.report_usage("on_file_savescript")
  5831. App.log.debug("on_file_savescript()")
  5832. obj = self.collection.get_active()
  5833. if obj is None:
  5834. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5835. return
  5836. # Check for more compatible types and add as required
  5837. if not isinstance(obj, ScriptObject):
  5838. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5839. return
  5840. name = self.collection.get_active().options["name"]
  5841. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5842. try:
  5843. filename, _f = FCFileSaveDialog.get_saved_filename(
  5844. caption="Save Script source file",
  5845. directory=self.get_last_save_folder() + '/' + name,
  5846. filter=_filter)
  5847. except TypeError:
  5848. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5849. filename = str(filename)
  5850. if filename == "":
  5851. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5852. return
  5853. else:
  5854. self.save_source_file(name, filename)
  5855. if self.defaults["global_open_style"] is False:
  5856. self.file_opened.emit("Script", filename)
  5857. self.file_saved.emit("Script", filename)
  5858. def on_file_savedocument(self):
  5859. """
  5860. Callback for menu item in Project context menu.
  5861. :return: None
  5862. """
  5863. self.defaults.report_usage("on_file_savedocument")
  5864. App.log.debug("on_file_savedocument()")
  5865. obj = self.collection.get_active()
  5866. if obj is None:
  5867. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5868. return
  5869. # Check for more compatible types and add as required
  5870. if not isinstance(obj, ScriptObject):
  5871. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5872. return
  5873. name = self.collection.get_active().options["name"]
  5874. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5875. try:
  5876. filename, _f = FCFileSaveDialog.get_saved_filename(
  5877. caption="Save Document source file",
  5878. directory=self.get_last_save_folder() + '/' + name,
  5879. filter=_filter)
  5880. except TypeError:
  5881. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5882. filename = str(filename)
  5883. if filename == "":
  5884. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5885. return
  5886. else:
  5887. self.save_source_file(name, filename)
  5888. if self.defaults["global_open_style"] is False:
  5889. self.file_opened.emit("Document", filename)
  5890. self.file_saved.emit("Document", filename)
  5891. def on_file_saveexcellon(self):
  5892. """
  5893. Callback for menu item in project context menu.
  5894. :return: None
  5895. """
  5896. self.defaults.report_usage("on_file_saveexcellon")
  5897. App.log.debug("on_file_saveexcellon()")
  5898. obj = self.collection.get_active()
  5899. if obj is None:
  5900. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5901. return
  5902. # Check for more compatible types and add as required
  5903. if not isinstance(obj, ExcellonObject):
  5904. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5905. return
  5906. name = self.collection.get_active().options["name"]
  5907. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5908. try:
  5909. filename, _f = FCFileSaveDialog.get_saved_filename(
  5910. caption=_("Save Excellon source file"),
  5911. directory=self.get_last_save_folder() + '/' + name,
  5912. filter=_filter)
  5913. except TypeError:
  5914. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5915. filename = str(filename)
  5916. if filename == "":
  5917. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5918. return
  5919. else:
  5920. self.save_source_file(name, filename)
  5921. if self.defaults["global_open_style"] is False:
  5922. self.file_opened.emit("Excellon", filename)
  5923. self.file_saved.emit("Excellon", filename)
  5924. def on_file_exportexcellon(self):
  5925. """
  5926. Callback for menu item File->Export->Excellon.
  5927. :return: None
  5928. """
  5929. self.defaults.report_usage("on_file_exportexcellon")
  5930. App.log.debug("on_file_exportexcellon()")
  5931. obj = self.collection.get_active()
  5932. if obj is None:
  5933. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5934. return
  5935. # Check for more compatible types and add as required
  5936. if not isinstance(obj, ExcellonObject):
  5937. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5938. return
  5939. name = self.collection.get_active().options["name"]
  5940. _filter = self.defaults["excellon_save_filters"]
  5941. try:
  5942. filename, _f = FCFileSaveDialog.get_saved_filename(
  5943. caption=_("Export Excellon"),
  5944. directory=self.get_last_save_folder() + '/' + name,
  5945. filter=_filter)
  5946. except TypeError:
  5947. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5948. filename = str(filename)
  5949. if filename == "":
  5950. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5951. return
  5952. else:
  5953. used_extension = filename.rpartition('.')[2]
  5954. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5955. self.export_excellon(name, filename)
  5956. if self.defaults["global_open_style"] is False:
  5957. self.file_opened.emit("Excellon", filename)
  5958. self.file_saved.emit("Excellon", filename)
  5959. def on_file_exportgerber(self):
  5960. """
  5961. Callback for menu item File->Export->Gerber.
  5962. :return: None
  5963. """
  5964. self.defaults.report_usage("on_file_exportgerber")
  5965. App.log.debug("on_file_exportgerber()")
  5966. obj = self.collection.get_active()
  5967. if obj is None:
  5968. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5969. return
  5970. # Check for more compatible types and add as required
  5971. if not isinstance(obj, GerberObject):
  5972. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5973. return
  5974. name = self.collection.get_active().options["name"]
  5975. _filter_ = self.defaults['gerber_save_filters']
  5976. try:
  5977. filename, _f = FCFileSaveDialog.get_saved_filename(
  5978. caption=_("Export Gerber"),
  5979. directory=self.get_last_save_folder() + '/' + name,
  5980. filter=_filter_)
  5981. except TypeError:
  5982. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5983. filename = str(filename)
  5984. if filename == "":
  5985. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5986. return
  5987. else:
  5988. used_extension = filename.rpartition('.')[2]
  5989. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5990. self.export_gerber(name, filename)
  5991. if self.defaults["global_open_style"] is False:
  5992. self.file_opened.emit("Gerber", filename)
  5993. self.file_saved.emit("Gerber", filename)
  5994. def on_file_exportdxf(self):
  5995. """
  5996. Callback for menu item File->Export DXF.
  5997. :return: None
  5998. """
  5999. self.defaults.report_usage("on_file_exportdxf")
  6000. App.log.debug("on_file_exportdxf()")
  6001. obj = self.collection.get_active()
  6002. if obj is None:
  6003. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6004. msg = _("Please Select a Geometry object to export")
  6005. msgbox = QtWidgets.QMessageBox()
  6006. msgbox.setInformativeText(msg)
  6007. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6008. msgbox.setDefaultButton(bt_ok)
  6009. msgbox.exec_()
  6010. return
  6011. # Check for more compatible types and add as required
  6012. if not isinstance(obj, GeometryObject):
  6013. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6014. msgbox = QtWidgets.QMessageBox()
  6015. msgbox.setInformativeText(msg)
  6016. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6017. msgbox.setDefaultButton(bt_ok)
  6018. msgbox.exec_()
  6019. return
  6020. name = self.collection.get_active().options["name"]
  6021. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6022. try:
  6023. filename, _f = FCFileSaveDialog.get_saved_filename(
  6024. caption=_("Export DXF"),
  6025. directory=self.get_last_save_folder() + '/' + name,
  6026. filter=_filter_)
  6027. except TypeError:
  6028. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6029. filename = str(filename)
  6030. if filename == "":
  6031. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6032. return
  6033. else:
  6034. self.export_dxf(name, filename)
  6035. if self.defaults["global_open_style"] is False:
  6036. self.file_opened.emit("DXF", filename)
  6037. self.file_saved.emit("DXF", filename)
  6038. def on_file_importsvg(self, type_of_obj):
  6039. """
  6040. Callback for menu item File->Import SVG.
  6041. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6042. :type type_of_obj: str
  6043. :return: None
  6044. """
  6045. self.defaults.report_usage("on_file_importsvg")
  6046. App.log.debug("on_file_importsvg()")
  6047. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6048. try:
  6049. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6050. directory=self.get_last_folder(), filter=_filter_)
  6051. except TypeError:
  6052. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6053. filter=_filter_)
  6054. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6055. type_of_obj = "geometry"
  6056. filenames = [str(filename) for filename in filenames]
  6057. if len(filenames) == 0:
  6058. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6059. else:
  6060. for filename in filenames:
  6061. if filename != '':
  6062. self.worker_task.emit({'fcn': self.import_svg,
  6063. 'params': [filename, type_of_obj]})
  6064. def on_file_importdxf(self, type_of_obj):
  6065. """
  6066. Callback for menu item File->Import DXF.
  6067. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6068. :type type_of_obj: str
  6069. :return: None
  6070. """
  6071. self.defaults.report_usage("on_file_importdxf")
  6072. App.log.debug("on_file_importdxf()")
  6073. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6074. try:
  6075. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6076. directory=self.get_last_folder(),
  6077. filter=_filter_)
  6078. except TypeError:
  6079. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6080. filter=_filter_)
  6081. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6082. type_of_obj = "geometry"
  6083. filenames = [str(filename) for filename in filenames]
  6084. if len(filenames) == 0:
  6085. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6086. else:
  6087. for filename in filenames:
  6088. if filename != '':
  6089. self.worker_task.emit({'fcn': self.import_dxf,
  6090. 'params': [filename, type_of_obj]})
  6091. # ###############################################################################################################
  6092. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6093. # ###############################################################################################################
  6094. def init_code_editor(self, name):
  6095. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6096. # add the tab if it was closed
  6097. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6098. self.text_editor_tab.setObjectName('text_editor_tab')
  6099. # delete the absolute and relative position and messages in the infobar
  6100. self.ui.position_label.setText("")
  6101. # self.ui.rel_position_label.setText("")
  6102. # first clear previous text in text editor (if any)
  6103. self.text_editor_tab.code_editor.clear()
  6104. self.text_editor_tab.code_editor.setReadOnly(False)
  6105. self.toggle_codeeditor = True
  6106. self.text_editor_tab.code_editor.completer_enable = False
  6107. self.text_editor_tab.buttonRun.hide()
  6108. # make sure to keep a reference to the code editor
  6109. self.reference_code_editor = self.text_editor_tab.code_editor
  6110. # Switch plot_area to CNCJob tab
  6111. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6112. def on_view_source(self):
  6113. """
  6114. Called when the user wants to see the source file of the selected object
  6115. :return:
  6116. """
  6117. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6118. self.proc_container.view.set_busy(_("Loading..."))
  6119. try:
  6120. obj = self.collection.get_active()
  6121. except Exception as e:
  6122. log.debug("App.on_view_source() --> %s" % str(e))
  6123. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6124. return 'fail'
  6125. if obj is None:
  6126. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6127. return 'fail'
  6128. flt = "All Files (*.*)"
  6129. if obj.kind == 'gerber':
  6130. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6131. elif obj.kind == 'excellon':
  6132. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6133. elif obj.kind == 'cncjob':
  6134. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6135. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6136. # add the tab if it was closed
  6137. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6138. self.source_editor_tab.setObjectName('source_editor_tab')
  6139. # delete the absolute and relative position and messages in the infobar
  6140. self.ui.position_label.setText("")
  6141. # self.ui.rel_position_label.setText("")
  6142. # first clear previous text in text editor (if any)
  6143. self.source_editor_tab.code_editor.clear()
  6144. self.source_editor_tab.code_editor.setReadOnly(False)
  6145. self.source_editor_tab.code_editor.completer_enable = False
  6146. self.source_editor_tab.buttonRun.hide()
  6147. # Switch plot_area to CNCJob tab
  6148. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6149. try:
  6150. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6151. except TypeError:
  6152. pass
  6153. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6154. try:
  6155. self.source_editor_tab.buttonSave.clicked.disconnect()
  6156. except TypeError:
  6157. pass
  6158. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6159. # then append the text from GCode to the text editor
  6160. if obj.kind == 'cncjob':
  6161. try:
  6162. file = obj.export_gcode(
  6163. preamble=self.defaults["cncjob_prepend"],
  6164. postamble=self.defaults["cncjob_append"],
  6165. to_file=True)
  6166. if file == 'fail':
  6167. return 'fail'
  6168. except AttributeError:
  6169. self.inform.emit('[WARNING_NOTCL] %s' %
  6170. _("There is no selected object for which to see it's source file code."))
  6171. return 'fail'
  6172. else:
  6173. try:
  6174. file = StringIO(obj.source_file)
  6175. except (AttributeError, TypeError):
  6176. self.inform.emit('[WARNING_NOTCL] %s' %
  6177. _("There is no selected object for which to see it's source file code."))
  6178. return 'fail'
  6179. self.source_editor_tab.t_frame.hide()
  6180. try:
  6181. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6182. # for line in file:
  6183. # QtWidgets.QApplication.processEvents()
  6184. # proc_line = str(line).strip('\n')
  6185. # self.source_editor_tab.code_editor.append(proc_line)
  6186. except Exception as e:
  6187. log.debug('App.on_view_source() -->%s' % str(e))
  6188. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6189. return
  6190. self.source_editor_tab.handleTextChanged()
  6191. self.source_editor_tab.t_frame.show()
  6192. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6193. self.proc_container.view.set_idle()
  6194. # self.ui.show()
  6195. def on_toggle_code_editor(self):
  6196. self.defaults.report_usage("on_toggle_code_editor()")
  6197. if self.toggle_codeeditor is False:
  6198. self.init_code_editor(name=_("Code Editor"))
  6199. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6200. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6201. self.text_editor_tab.buttonSave.clicked.disconnect()
  6202. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6203. else:
  6204. for idx in range(self.ui.plot_tab_area.count()):
  6205. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6206. self.ui.plot_tab_area.closeTab(idx)
  6207. break
  6208. self.toggle_codeeditor = False
  6209. def on_code_editor_close(self):
  6210. self.toggle_codeeditor = False
  6211. def goto_text_line(self):
  6212. """
  6213. Will scroll a text to the specified text line.
  6214. :return: None
  6215. """
  6216. dia_box = Dialog_box(title=_("Go to Line ..."),
  6217. label=_("Line:"),
  6218. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6219. initial_text='')
  6220. try:
  6221. line = int(dia_box.location) - 1
  6222. except (ValueError, TypeError):
  6223. line = 0
  6224. if dia_box.ok:
  6225. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6226. # at the top of the window
  6227. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6228. # get the document() of the TextEditor
  6229. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6230. # create a Text Cursor based on the searched line
  6231. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6232. # set cursor of the code editor with the cursor at the searcehd line
  6233. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6234. def on_filenewscript(self, silent=False):
  6235. """
  6236. Will create a new script file and open it in the Code Editor
  6237. :param silent: if True will not display status messages
  6238. :return: None
  6239. """
  6240. if silent is False:
  6241. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6242. # delete the absolute and relative position and messages in the infobar
  6243. self.ui.position_label.setText("")
  6244. # self.ui.rel_position_label.setText("")
  6245. self.app_obj.new_script_object()
  6246. # script_text = script_obj.source_file
  6247. #
  6248. # self.proc_container.view.set_busy(_("Loading..."))
  6249. # script_obj.script_editor_tab.t_frame.hide()
  6250. #
  6251. # script_obj.script_editor_tab.t_frame.show()
  6252. # self.proc_container.view.set_idle()
  6253. def on_fileopenscript(self, name=None, silent=False):
  6254. """
  6255. Will open a Tcl script file into the Code Editor
  6256. :param silent: if True will not display status messages
  6257. :param name: name of a Tcl script file to open
  6258. :return: None
  6259. """
  6260. self.defaults.report_usage("on_fileopenscript")
  6261. App.log.debug("on_fileopenscript()")
  6262. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6263. "All Files (*.*)"
  6264. if name:
  6265. filenames = [name]
  6266. else:
  6267. try:
  6268. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6269. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6270. except TypeError:
  6271. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6272. if len(filenames) == 0:
  6273. if silent is False:
  6274. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6275. else:
  6276. for filename in filenames:
  6277. if filename != '':
  6278. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6279. def on_fileopenscript_example(self, name=None, silent=False):
  6280. """
  6281. Will open a Tcl script file into the Code Editor
  6282. :param silent: if True will not display status messages
  6283. :param name: name of a Tcl script file to open
  6284. :return:
  6285. """
  6286. self.defaults.report_usage("on_fileopenscript_example")
  6287. log.debug("on_fileopenscript_example()")
  6288. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6289. "All Files (*.*)"
  6290. # test if the app was frozen and choose the path for the configuration file
  6291. if getattr(sys, "frozen", False) is True:
  6292. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6293. else:
  6294. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6295. if name:
  6296. filenames = [name]
  6297. else:
  6298. try:
  6299. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6300. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6301. except TypeError:
  6302. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6303. if len(filenames) == 0:
  6304. if silent is False:
  6305. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6306. else:
  6307. for filename in filenames:
  6308. if filename != '':
  6309. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6310. def on_filerunscript(self, name=None, silent=False):
  6311. """
  6312. File menu callback for loading and running a TCL script.
  6313. :param silent: if True will not display status messages
  6314. :param name: name of a Tcl script file to be run by FlatCAM
  6315. :return: None
  6316. """
  6317. self.defaults.report_usage("on_filerunscript")
  6318. App.log.debug("on_file_runscript()")
  6319. if name:
  6320. filename = name
  6321. if self.cmd_line_headless != 1:
  6322. self.splash.showMessage('%s: %ssec\n%s' %
  6323. (_("Canvas initialization started.\n"
  6324. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6325. _("Executing ScriptObject file.")
  6326. ),
  6327. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6328. color=QtGui.QColor("gray"))
  6329. else:
  6330. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6331. "All Files (*.*)"
  6332. try:
  6333. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6334. directory=self.get_last_folder(), filter=_filter_)
  6335. except TypeError:
  6336. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6337. # The Qt methods above will return a QString which can cause problems later.
  6338. # So far json.dump() will fail to serialize it.
  6339. filename = str(filename)
  6340. if filename == "":
  6341. if silent is False:
  6342. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6343. else:
  6344. if self.cmd_line_headless != 1:
  6345. if self.ui.shell_dock.isHidden():
  6346. self.ui.shell_dock.show()
  6347. try:
  6348. with open(filename, "r") as tcl_script:
  6349. cmd_line_shellfile_content = tcl_script.read()
  6350. if self.cmd_line_headless != 1:
  6351. self.shell.exec_command(cmd_line_shellfile_content)
  6352. else:
  6353. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6354. if silent is False:
  6355. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6356. except Exception as e:
  6357. log.debug("App.on_filerunscript() -> %s" % str(e))
  6358. sys.exit(2)
  6359. def on_file_saveproject(self, silent=False):
  6360. """
  6361. Callback for menu item File->Save Project. Saves the project to
  6362. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6363. if set to None. The project is saved by calling ``self.save_project()``.
  6364. :param silent: if True will not display status messages
  6365. :return: None
  6366. """
  6367. self.defaults.report_usage("on_file_saveproject")
  6368. if self.project_filename is None:
  6369. self.on_file_saveprojectas()
  6370. else:
  6371. self.worker_task.emit({'fcn': self.save_project,
  6372. 'params': [self.project_filename, silent]})
  6373. if self.defaults["global_open_style"] is False:
  6374. self.file_opened.emit("project", self.project_filename)
  6375. self.file_saved.emit("project", self.project_filename)
  6376. self.set_ui_title(name=self.project_filename)
  6377. self.should_we_save = False
  6378. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6379. """
  6380. Callback for menu item File->Save Project As... Opens a file
  6381. chooser and saves the project to the given file via
  6382. ``self.save_project()``.
  6383. :param make_copy if to be create a copy of the project; boolean
  6384. :param use_thread: if to be run in a separate thread; boolean
  6385. :param quit_action: if to be followed by quiting the application; boolean
  6386. :return: None
  6387. """
  6388. self.defaults.report_usage("on_file_saveprojectas")
  6389. self.date = str(datetime.today()).rpartition('.')[0]
  6390. self.date = ''.join(c for c in self.date if c not in ':-')
  6391. self.date = self.date.replace(' ', '_')
  6392. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6393. try:
  6394. filename, _f = FCFileSaveDialog.get_saved_filename(
  6395. caption=_("Save Project As ..."),
  6396. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6397. proj=_("Project")),
  6398. filter=filter_
  6399. )
  6400. except TypeError:
  6401. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6402. filename = str(filename)
  6403. if filename == '':
  6404. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6405. return
  6406. if use_thread is True:
  6407. self.worker_task.emit({'fcn': self.save_project,
  6408. 'params': [filename, quit_action]})
  6409. else:
  6410. self.save_project(filename, quit_action)
  6411. # self.save_project(filename)
  6412. if self.defaults["global_open_style"] is False:
  6413. self.file_opened.emit("project", filename)
  6414. self.file_saved.emit("project", filename)
  6415. if not make_copy:
  6416. self.project_filename = filename
  6417. self.set_ui_title(name=self.project_filename)
  6418. self.should_we_save = False
  6419. def on_file_save_objects_pdf(self, use_thread=True):
  6420. self.date = str(datetime.today()).rpartition('.')[0]
  6421. self.date = ''.join(c for c in self.date if c not in ':-')
  6422. self.date = self.date.replace(' ', '_')
  6423. try:
  6424. obj_selection = self.collection.get_selected()
  6425. if len(obj_selection) == 1:
  6426. obj_name = str(obj_selection[0].options['name'])
  6427. else:
  6428. obj_name = _("FlatCAM objects print")
  6429. except AttributeError as err:
  6430. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6431. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6432. return
  6433. if not obj_selection:
  6434. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6435. return
  6436. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6437. try:
  6438. filename, _f = FCFileSaveDialog.get_saved_filename(
  6439. caption=_("Save Object as PDF ..."),
  6440. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6441. obj_name=obj_name,
  6442. date=self.date),
  6443. filter=filter_
  6444. )
  6445. except TypeError:
  6446. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6447. filename = str(filename)
  6448. if filename == '':
  6449. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6450. return
  6451. if use_thread is True:
  6452. self.proc_container.new(_("Printing PDF ... Please wait."))
  6453. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6454. else:
  6455. self.save_pdf(filename, obj_selection)
  6456. # self.save_project(filename)
  6457. if self.defaults["global_open_style"] is False:
  6458. self.file_opened.emit("pdf", filename)
  6459. self.file_saved.emit("pdf", filename)
  6460. def save_pdf(self, file_name, obj_selection):
  6461. p_size = self.defaults['global_workspaceT']
  6462. orientation = self.defaults['global_workspace_orientation']
  6463. color = 'black'
  6464. transparency_level = 1.0
  6465. self.pagesize = {}
  6466. self.pagesize.update(
  6467. {
  6468. 'Bounds': None,
  6469. 'A0': (841 * mm, 1189 * mm),
  6470. 'A1': (594 * mm, 841 * mm),
  6471. 'A2': (420 * mm, 594 * mm),
  6472. 'A3': (297 * mm, 420 * mm),
  6473. 'A4': (210 * mm, 297 * mm),
  6474. 'A5': (148 * mm, 210 * mm),
  6475. 'A6': (105 * mm, 148 * mm),
  6476. 'A7': (74 * mm, 105 * mm),
  6477. 'A8': (52 * mm, 74 * mm),
  6478. 'A9': (37 * mm, 52 * mm),
  6479. 'A10': (26 * mm, 37 * mm),
  6480. 'B0': (1000 * mm, 1414 * mm),
  6481. 'B1': (707 * mm, 1000 * mm),
  6482. 'B2': (500 * mm, 707 * mm),
  6483. 'B3': (353 * mm, 500 * mm),
  6484. 'B4': (250 * mm, 353 * mm),
  6485. 'B5': (176 * mm, 250 * mm),
  6486. 'B6': (125 * mm, 176 * mm),
  6487. 'B7': (88 * mm, 125 * mm),
  6488. 'B8': (62 * mm, 88 * mm),
  6489. 'B9': (44 * mm, 62 * mm),
  6490. 'B10': (31 * mm, 44 * mm),
  6491. 'C0': (917 * mm, 1297 * mm),
  6492. 'C1': (648 * mm, 917 * mm),
  6493. 'C2': (458 * mm, 648 * mm),
  6494. 'C3': (324 * mm, 458 * mm),
  6495. 'C4': (229 * mm, 324 * mm),
  6496. 'C5': (162 * mm, 229 * mm),
  6497. 'C6': (114 * mm, 162 * mm),
  6498. 'C7': (81 * mm, 114 * mm),
  6499. 'C8': (57 * mm, 81 * mm),
  6500. 'C9': (40 * mm, 57 * mm),
  6501. 'C10': (28 * mm, 40 * mm),
  6502. # American paper sizes
  6503. 'LETTER': (8.5 * inch, 11 * inch),
  6504. 'LEGAL': (8.5 * inch, 14 * inch),
  6505. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6506. # From https://en.wikipedia.org/wiki/Paper_size
  6507. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6508. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6509. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6510. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6511. 'LEDGER': (17 * inch, 11 * inch),
  6512. }
  6513. )
  6514. exported_svg = []
  6515. for obj in obj_selection:
  6516. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6517. scale_factor_x=None, scale_factor_y=None,
  6518. skew_factor_x=None, skew_factor_y=None,
  6519. mirror=None)
  6520. if obj.kind.lower() == 'gerber':
  6521. # color = self.defaults["gerber_plot_fill"][:-2]
  6522. color = obj.fill_color[:-2]
  6523. elif obj.kind.lower() == 'excellon':
  6524. color = '#C40000'
  6525. elif obj.kind.lower() == 'geometry':
  6526. color = self.defaults["global_draw_color"]
  6527. # Change the attributes of the exported SVG
  6528. # We don't need stroke-width
  6529. # We set opacity to maximum
  6530. # We set the colour to WHITE
  6531. root = ET.fromstring(svg_obj)
  6532. for child in root:
  6533. child.set('fill', str(color))
  6534. child.set('opacity', str(transparency_level))
  6535. child.set('stroke', str(color))
  6536. exported_svg.append(ET.tostring(root))
  6537. xmin = Inf
  6538. ymin = Inf
  6539. xmax = -Inf
  6540. ymax = -Inf
  6541. for obj in obj_selection:
  6542. try:
  6543. gxmin, gymin, gxmax, gymax = obj.bounds()
  6544. xmin = min([xmin, gxmin])
  6545. ymin = min([ymin, gymin])
  6546. xmax = max([xmax, gxmax])
  6547. ymax = max([ymax, gymax])
  6548. except Exception as e:
  6549. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6550. # Determine bounding area for svg export
  6551. bounds = [xmin, ymin, xmax, ymax]
  6552. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6553. # This contain the measure units
  6554. uom = obj_selection[0].units.lower()
  6555. # Define a boundary around SVG of about 1.0mm (~39mils)
  6556. if uom in "mm":
  6557. boundary = 1.0
  6558. else:
  6559. boundary = 0.0393701
  6560. # Convert everything to strings for use in the xml doc
  6561. svgwidth = str(size[0] + (2 * boundary))
  6562. svgheight = str(size[1] + (2 * boundary))
  6563. minx = str(bounds[0] - boundary)
  6564. miny = str(bounds[1] + boundary + size[1])
  6565. # Add a SVG Header and footer to the svg output from shapely
  6566. # The transform flips the Y Axis so that everything renders
  6567. # properly within svg apps such as inkscape
  6568. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6569. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6570. svg_header += 'width="' + svgwidth + uom + '" '
  6571. svg_header += 'height="' + svgheight + uom + '" '
  6572. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6573. svg_header += '>'
  6574. svg_header += '<g transform="scale(1,-1)">'
  6575. svg_footer = '</g> </svg>'
  6576. svg_elem = str(svg_header)
  6577. for svg_item in exported_svg:
  6578. svg_elem += str(svg_item)
  6579. svg_elem += str(svg_footer)
  6580. # Parse the xml through a xml parser just to add line feeds
  6581. # and to make it look more pretty for the output
  6582. doc = parse_xml_string(svg_elem)
  6583. doc_final = doc.toprettyxml()
  6584. try:
  6585. if self.defaults['units'].upper() == 'IN':
  6586. unit = inch
  6587. else:
  6588. unit = mm
  6589. doc_final = StringIO(doc_final)
  6590. drawing = svg2rlg(doc_final)
  6591. if p_size == 'Bounds':
  6592. renderPDF.drawToFile(drawing, file_name)
  6593. else:
  6594. if orientation == 'p':
  6595. page_size = portrait(self.pagesize[p_size])
  6596. else:
  6597. page_size = landscape(self.pagesize[p_size])
  6598. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6599. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6600. renderPDF.draw(drawing, my_canvas, 0, 0)
  6601. my_canvas.save()
  6602. except Exception as e:
  6603. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6604. return 'fail'
  6605. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6606. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6607. """
  6608. Exports a Geometry Object to an SVG file.
  6609. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6610. :param filename: Path to the SVG file to save to.
  6611. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6612. :return:
  6613. """
  6614. self.defaults.report_usage("export_svg()")
  6615. if filename is None:
  6616. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6617. is not None else self.defaults["global_last_folder"]
  6618. self.log.debug("export_svg()")
  6619. try:
  6620. obj = self.collection.get_by_name(str(obj_name))
  6621. except Exception:
  6622. # TODO: The return behavior has not been established... should raise exception?
  6623. return "Could not retrieve object: %s" % obj_name
  6624. with self.proc_container.new(_("Exporting SVG")) as proc:
  6625. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6626. # Determine bounding area for svg export
  6627. bounds = obj.bounds()
  6628. size = obj.size()
  6629. # Convert everything to strings for use in the xml doc
  6630. svgwidth = str(size[0])
  6631. svgheight = str(size[1])
  6632. minx = str(bounds[0])
  6633. miny = str(bounds[1] - size[1])
  6634. uom = obj.units.lower()
  6635. # Add a SVG Header and footer to the svg output from shapely
  6636. # The transform flips the Y Axis so that everything renders
  6637. # properly within svg apps such as inkscape
  6638. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6639. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6640. svg_header += 'width="' + svgwidth + uom + '" '
  6641. svg_header += 'height="' + svgheight + uom + '" '
  6642. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6643. svg_header += '<g transform="scale(1,-1)">'
  6644. svg_footer = '</g> </svg>'
  6645. svg_elem = svg_header + exported_svg + svg_footer
  6646. # Parse the xml through a xml parser just to add line feeds
  6647. # and to make it look more pretty for the output
  6648. svgcode = parse_xml_string(svg_elem)
  6649. svgcode = svgcode.toprettyxml()
  6650. try:
  6651. with open(filename, 'w') as fp:
  6652. fp.write(svgcode)
  6653. except PermissionError:
  6654. self.inform.emit('[WARNING] %s' %
  6655. _("Permission denied, saving not possible.\n"
  6656. "Most likely another app is holding the file open and not accessible."))
  6657. return 'fail'
  6658. if self.defaults["global_open_style"] is False:
  6659. self.file_opened.emit("SVG", filename)
  6660. self.file_saved.emit("SVG", filename)
  6661. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6662. def save_source_file(self, obj_name, filename, use_thread=True):
  6663. """
  6664. Exports a FlatCAM Object to an Gerber/Excellon file.
  6665. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6666. :param filename: Path to the Gerber file to save to.
  6667. :param use_thread: if to be run in a separate thread
  6668. :return:
  6669. """
  6670. self.defaults.report_usage("save source file()")
  6671. if filename is None:
  6672. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6673. is not None else self.defaults["global_last_folder"]
  6674. self.log.debug("save source file()")
  6675. obj = self.collection.get_by_name(obj_name)
  6676. file_string = StringIO(obj.source_file)
  6677. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6678. if file_string.getvalue() == '':
  6679. self.inform.emit('[ERROR_NOTCL] %s' %
  6680. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6681. return 'fail'
  6682. try:
  6683. with open(filename, 'w') as file:
  6684. file.writelines('G04*\n')
  6685. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6686. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6687. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6688. file.writelines('G04 Created on : %s*\n' % time_string)
  6689. for line in file_string:
  6690. file.writelines(line)
  6691. except PermissionError:
  6692. self.inform.emit('[WARNING] %s' %
  6693. _("Permission denied, saving not possible.\n"
  6694. "Most likely another app is holding the file open and not accessible."))
  6695. return 'fail'
  6696. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6697. """
  6698. Exports a Excellon Object to an Excellon file.
  6699. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6700. :param filename: Path to the Excellon file to save to.
  6701. :param local_use:
  6702. :param use_thread: if to be run in a separate thread
  6703. :return:
  6704. """
  6705. self.defaults.report_usage("export_excellon()")
  6706. if filename is None:
  6707. if self.defaults["global_last_save_folder"]:
  6708. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6709. else:
  6710. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6711. self.log.debug("export_excellon()")
  6712. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6713. self.defaults["excellon_exp_decimals"]
  6714. )
  6715. if local_use is None:
  6716. try:
  6717. obj = self.collection.get_by_name(str(obj_name))
  6718. except Exception:
  6719. return "Could not retrieve object: %s" % obj_name
  6720. else:
  6721. obj = local_use
  6722. if not isinstance(obj, ExcellonObject):
  6723. self.inform.emit('[ERROR_NOTCL] %s' %
  6724. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6725. return
  6726. # updated units
  6727. eunits = self.defaults["excellon_exp_units"]
  6728. ewhole = self.defaults["excellon_exp_integer"]
  6729. efract = self.defaults["excellon_exp_decimals"]
  6730. ezeros = self.defaults["excellon_exp_zeros"]
  6731. eformat = self.defaults["excellon_exp_format"]
  6732. slot_type = self.defaults["excellon_exp_slot_type"]
  6733. fc_units = self.defaults['units'].upper()
  6734. if fc_units == 'MM':
  6735. factor = 1 if eunits == 'METRIC' else 0.03937
  6736. else:
  6737. factor = 25.4 if eunits == 'METRIC' else 1
  6738. def make_excellon():
  6739. try:
  6740. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6741. header = 'M48\n'
  6742. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6743. (str(self.version), str(self.version_date))
  6744. header += ';Filename: %s' % str(obj_name) + '\n'
  6745. header += ';Created on : %s' % time_str + '\n'
  6746. if eformat == 'dec':
  6747. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6748. header += eunits + '\n'
  6749. for tool in obj.tools:
  6750. if eunits == 'METRIC':
  6751. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6752. tool=str(tool),
  6753. dec=2)
  6754. else:
  6755. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6756. tool=str(tool),
  6757. dec=4)
  6758. else:
  6759. if ezeros == 'LZ':
  6760. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6761. form='ndec', e_zeros='LZ', factor=factor,
  6762. slot_type=slot_type)
  6763. header += '%s,%s\n' % (eunits, 'LZ')
  6764. header += format_exc
  6765. for tool in obj.tools:
  6766. if eunits == 'METRIC':
  6767. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6768. tool=str(tool),
  6769. dec=2)
  6770. else:
  6771. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6772. tool=str(tool),
  6773. dec=4)
  6774. else:
  6775. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6776. form='ndec', e_zeros='TZ', factor=factor,
  6777. slot_type=slot_type)
  6778. header += '%s,%s\n' % (eunits, 'TZ')
  6779. header += format_exc
  6780. for tool in obj.tools:
  6781. if eunits == 'METRIC':
  6782. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6783. tool=str(tool),
  6784. dec=2)
  6785. else:
  6786. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6787. tool=str(tool),
  6788. dec=4)
  6789. header += '%\n'
  6790. footer = 'M30\n'
  6791. exported_excellon = header
  6792. exported_excellon += excellon_code
  6793. exported_excellon += footer
  6794. if local_use is None:
  6795. try:
  6796. with open(filename, 'w') as fp:
  6797. fp.write(exported_excellon)
  6798. except PermissionError:
  6799. self.inform.emit('[WARNING] %s' %
  6800. _("Permission denied, saving not possible.\n"
  6801. "Most likely another app is holding the file open and not accessible."))
  6802. return 'fail'
  6803. if self.defaults["global_open_style"] is False:
  6804. self.file_opened.emit("Excellon", filename)
  6805. self.file_saved.emit("Excellon", filename)
  6806. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6807. else:
  6808. return exported_excellon
  6809. except Exception as e:
  6810. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6811. return 'fail'
  6812. if use_thread is True:
  6813. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6814. def job_thread_exc(app_obj):
  6815. ret = make_excellon()
  6816. if ret == 'fail':
  6817. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6818. return
  6819. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6820. else:
  6821. eret = make_excellon()
  6822. if eret == 'fail':
  6823. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6824. return 'fail'
  6825. if local_use is not None:
  6826. return eret
  6827. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6828. """
  6829. Exports a Gerber Object to an Gerber file.
  6830. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6831. :param filename: Path to the Gerber file to save to.
  6832. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6833. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6834. :param use_thread: if to be run in a separate thread
  6835. :return:
  6836. """
  6837. self.defaults.report_usage("export_gerber()")
  6838. if filename is None:
  6839. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6840. is not None else self.defaults["global_last_folder"]
  6841. self.log.debug("export_gerber()")
  6842. if local_use is None:
  6843. try:
  6844. obj = self.collection.get_by_name(str(obj_name))
  6845. except Exception:
  6846. return "Could not retrieve object: %s" % obj_name
  6847. else:
  6848. obj = local_use
  6849. # updated units
  6850. gunits = self.defaults["gerber_exp_units"]
  6851. gwhole = self.defaults["gerber_exp_integer"]
  6852. gfract = self.defaults["gerber_exp_decimals"]
  6853. gzeros = self.defaults["gerber_exp_zeros"]
  6854. fc_units = self.defaults['units'].upper()
  6855. if fc_units == 'MM':
  6856. factor = 1 if gunits == 'MM' else 0.03937
  6857. else:
  6858. factor = 25.4 if gunits == 'MM' else 1
  6859. def make_gerber():
  6860. try:
  6861. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6862. header = 'G04*\n'
  6863. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6864. (str(self.version), str(self.version_date))
  6865. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6866. header += 'G04 Created on : %s*' % time_str + '\n'
  6867. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6868. header += "%MO{units}*%\n".format(units=gunits)
  6869. for apid in obj.apertures:
  6870. if obj.apertures[apid]['type'] == 'C':
  6871. header += "%ADD{apid}{type},{size}*%\n".format(
  6872. apid=str(apid),
  6873. type='C',
  6874. size=(factor * obj.apertures[apid]['size'])
  6875. )
  6876. elif obj.apertures[apid]['type'] == 'R':
  6877. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6878. apid=str(apid),
  6879. type='R',
  6880. width=(factor * obj.apertures[apid]['width']),
  6881. height=(factor * obj.apertures[apid]['height'])
  6882. )
  6883. elif obj.apertures[apid]['type'] == 'O':
  6884. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6885. apid=str(apid),
  6886. type='O',
  6887. width=(factor * obj.apertures[apid]['width']),
  6888. height=(factor * obj.apertures[apid]['height'])
  6889. )
  6890. header += '\n'
  6891. # obsolete units but some software may need it
  6892. if gunits == 'IN':
  6893. header += 'G70*\n'
  6894. else:
  6895. header += 'G71*\n'
  6896. # Absolute Mode
  6897. header += 'G90*\n'
  6898. header += 'G01*\n'
  6899. # positive polarity
  6900. header += '%LPD*%\n'
  6901. footer = 'M02*\n'
  6902. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6903. exported_gerber = header
  6904. exported_gerber += gerber_code
  6905. exported_gerber += footer
  6906. if local_use is None:
  6907. try:
  6908. with open(filename, 'w') as fp:
  6909. fp.write(exported_gerber)
  6910. except PermissionError:
  6911. self.inform.emit('[WARNING] %s' %
  6912. _("Permission denied, saving not possible.\n"
  6913. "Most likely another app is holding the file open and not accessible."))
  6914. return 'fail'
  6915. if self.defaults["global_open_style"] is False:
  6916. self.file_opened.emit("Gerber", filename)
  6917. self.file_saved.emit("Gerber", filename)
  6918. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6919. else:
  6920. return exported_gerber
  6921. except Exception as e:
  6922. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6923. return 'fail'
  6924. if use_thread is True:
  6925. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6926. def job_thread_grb(app_obj):
  6927. ret = make_gerber()
  6928. if ret == 'fail':
  6929. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6930. return
  6931. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6932. else:
  6933. gret = make_gerber()
  6934. if gret == 'fail':
  6935. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6936. return 'fail'
  6937. if local_use is not None:
  6938. return gret
  6939. def export_dxf(self, obj_name, filename, use_thread=True):
  6940. """
  6941. Exports a Geometry Object to an DXF file.
  6942. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6943. :param filename: Path to the DXF file to save to.
  6944. :param use_thread: if to be run in a separate thread
  6945. :return:
  6946. """
  6947. self.defaults.report_usage("export_dxf()")
  6948. if filename is None:
  6949. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6950. is not None else self.defaults["global_last_folder"]
  6951. self.log.debug("export_dxf()")
  6952. try:
  6953. obj = self.collection.get_by_name(str(obj_name))
  6954. except Exception:
  6955. # TODO: The return behavior has not been established... should raise exception?
  6956. return "Could not retrieve object: %s" % obj_name
  6957. def make_dxf():
  6958. try:
  6959. dxf_code = obj.export_dxf()
  6960. dxf_code.saveas(filename)
  6961. if self.defaults["global_open_style"] is False:
  6962. self.file_opened.emit("DXF", filename)
  6963. self.file_saved.emit("DXF", filename)
  6964. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6965. except Exception:
  6966. return 'fail'
  6967. if use_thread is True:
  6968. with self.proc_container.new(_("Exporting DXF")) as proc:
  6969. def job_thread_exc(app_obj):
  6970. ret_dxf_val = make_dxf()
  6971. if ret_dxf_val == 'fail':
  6972. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6973. return
  6974. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6975. else:
  6976. ret = make_dxf()
  6977. if ret == 'fail':
  6978. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6979. return
  6980. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6981. """
  6982. Adds a new Geometry Object to the projects and populates
  6983. it with shapes extracted from the SVG file.
  6984. :param plot: If True then the resulting object will be plotted on canvas
  6985. :param filename: Path to the SVG file.
  6986. :param geo_type: Type of FlatCAM object that will be created from SVG
  6987. :param outname: The name given to the resulting FlatCAM object
  6988. :return:
  6989. """
  6990. self.defaults.report_usage("import_svg()")
  6991. log.debug("App.import_svg()")
  6992. obj_type = ""
  6993. if geo_type is None or geo_type == "geometry":
  6994. obj_type = "geometry"
  6995. elif geo_type == "gerber":
  6996. obj_type = "gerber"
  6997. else:
  6998. self.inform.emit('[ERROR_NOTCL] %s' %
  6999. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7000. return
  7001. units = self.defaults['units'].upper()
  7002. def obj_init(geo_obj, app_obj):
  7003. geo_obj.import_svg(filename, obj_type, units=units)
  7004. geo_obj.multigeo = False
  7005. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7006. with self.proc_container.new(_("Importing SVG")) as proc:
  7007. # Object name
  7008. name = outname or filename.split('/')[-1].split('\\')[-1]
  7009. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7010. if ret == 'fail':
  7011. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7012. return 'fail'
  7013. # Register recent file
  7014. self.file_opened.emit("svg", filename)
  7015. # AppGUI feedback
  7016. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7017. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7018. """
  7019. Adds a new Geometry Object to the projects and populates
  7020. it with shapes extracted from the DXF file.
  7021. :param filename: Path to the DXF file.
  7022. :param geo_type: Type of FlatCAM object that will be created from DXF
  7023. :param outname: Name for the imported Geometry
  7024. :param plot: If True then the resulting object will be plotted on canvas
  7025. :return:
  7026. """
  7027. self.defaults.report_usage("import_dxf()")
  7028. obj_type = ""
  7029. if geo_type is None or geo_type == "geometry":
  7030. obj_type = "geometry"
  7031. elif geo_type == "gerber":
  7032. obj_type = geo_type
  7033. else:
  7034. self.inform.emit('[ERROR_NOTCL] %s' %
  7035. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7036. return
  7037. units = self.defaults['units'].upper()
  7038. def obj_init(geo_obj, app_obj):
  7039. geo_obj.import_dxf(filename, obj_type, units=units)
  7040. geo_obj.multigeo = False
  7041. with self.proc_container.new(_("Importing DXF")):
  7042. # Object name
  7043. name = outname or filename.split('/')[-1].split('\\')[-1]
  7044. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7045. if ret == 'fail':
  7046. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7047. return 'fail'
  7048. # Register recent file
  7049. self.file_opened.emit("dxf", filename)
  7050. # AppGUI feedback
  7051. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7052. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7053. """
  7054. Opens a Gerber file, parses it and creates a new object for
  7055. it in the program. Thread-safe.
  7056. :param outname: Name of the resulting object. None causes the
  7057. name to be that of the file. Str.
  7058. :param filename: Gerber file filename
  7059. :type filename: str
  7060. :param plot: boolean, to plot or not the resulting object
  7061. :param from_tcl: True if run from Tcl Shell
  7062. :return: None
  7063. """
  7064. # How the object should be initialized
  7065. def obj_init(gerber_obj, app_obj):
  7066. assert isinstance(gerber_obj, GerberObject), \
  7067. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7068. # Opening the file happens here
  7069. try:
  7070. gerber_obj.parse_file(filename)
  7071. except IOError:
  7072. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7073. return "fail"
  7074. except ParseError as err:
  7075. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7076. app_obj.log.error(str(err))
  7077. return "fail"
  7078. except Exception as e:
  7079. log.debug("App.open_gerber() --> %s" % str(e))
  7080. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7081. msg += traceback.format_exc()
  7082. app_obj.inform.emit(msg)
  7083. return "fail"
  7084. if gerber_obj.is_empty():
  7085. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7086. _("Object is not Gerber file or empty. Aborting object creation."))
  7087. return "fail"
  7088. App.log.debug("open_gerber()")
  7089. with self.proc_container.new(_("Opening Gerber")):
  7090. # Object name
  7091. name = outname or filename.split('/')[-1].split('\\')[-1]
  7092. # # ## Object creation # ##
  7093. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7094. if ret_val == 'fail':
  7095. if from_tcl:
  7096. filename = self.defaults['global_tcl_path'] + '/' + name
  7097. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7098. if ret_val == 'fail':
  7099. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7100. return 'fail'
  7101. # Register recent file
  7102. self.file_opened.emit("gerber", filename)
  7103. # AppGUI feedback
  7104. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7105. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7106. """
  7107. Opens an Excellon file, parses it and creates a new object for
  7108. it in the program. Thread-safe.
  7109. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7110. :param filename: Excellon file filename
  7111. :type filename: str
  7112. :param plot: boolean, to plot or not the resulting object
  7113. :param from_tcl: True if run from Tcl Shell
  7114. :return: None
  7115. """
  7116. App.log.debug("open_excellon()")
  7117. # How the object should be initialized
  7118. def obj_init(excellon_obj, app_obj):
  7119. try:
  7120. ret = excellon_obj.parse_file(filename=filename)
  7121. if ret == "fail":
  7122. log.debug("Excellon parsing failed.")
  7123. self.inform.emit('[ERROR_NOTCL] %s' %
  7124. _("This is not Excellon file."))
  7125. return "fail"
  7126. except IOError:
  7127. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7128. (_("Cannot open file"), filename))
  7129. log.debug("Could not open Excellon object.")
  7130. return "fail"
  7131. except Exception:
  7132. msg = '[ERROR_NOTCL] %s' % \
  7133. _("An internal error has occurred. See shell.\n")
  7134. msg += traceback.format_exc()
  7135. app_obj.inform.emit(msg)
  7136. return "fail"
  7137. ret = excellon_obj.create_geometry()
  7138. if ret == 'fail':
  7139. log.debug("Could not create geometry for Excellon object.")
  7140. return "fail"
  7141. for tool in excellon_obj.tools:
  7142. if excellon_obj.tools[tool]['solid_geometry']:
  7143. return
  7144. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7145. return "fail"
  7146. with self.proc_container.new(_("Opening Excellon.")):
  7147. # Object name
  7148. name = outname or filename.split('/')[-1].split('\\')[-1]
  7149. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7150. if ret_val == 'fail':
  7151. if from_tcl:
  7152. filename = self.defaults['global_tcl_path'] + '/' + name
  7153. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7154. if ret_val == 'fail':
  7155. self.inform.emit('[ERROR_NOTCL] %s' %
  7156. _('Open Excellon file failed. Probable not an Excellon file.'))
  7157. return
  7158. # Register recent file
  7159. self.file_opened.emit("excellon", filename)
  7160. # AppGUI feedback
  7161. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7162. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7163. """
  7164. Opens a G-gcode file, parses it and creates a new object for
  7165. it in the program. Thread-safe.
  7166. :param filename: G-code file filename
  7167. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7168. :param force_parsing:
  7169. :param plot: If True plot the object on canvas
  7170. :param from_tcl: True if run from Tcl Shell
  7171. :return: None
  7172. """
  7173. App.log.debug("open_gcode()")
  7174. # How the object should be initialized
  7175. def obj_init(job_obj, app_obj_):
  7176. """
  7177. :param job_obj: the resulting object
  7178. :type app_obj_: App
  7179. """
  7180. assert isinstance(app_obj_, App), \
  7181. "Initializer expected App, got %s" % type(app_obj_)
  7182. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7183. try:
  7184. f = open(filename)
  7185. gcode = f.read()
  7186. f.close()
  7187. except IOError:
  7188. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7189. return "fail"
  7190. job_obj.gcode = gcode
  7191. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7192. if gcode_ret == "fail":
  7193. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7194. return "fail"
  7195. job_obj.create_geometry()
  7196. with self.proc_container.new(_("Opening G-Code.")):
  7197. # Object name
  7198. name = outname or filename.split('/')[-1].split('\\')[-1]
  7199. # New object creation and file processing
  7200. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7201. if ret_val == 'fail':
  7202. if from_tcl:
  7203. filename = self.defaults['global_tcl_path'] + '/' + name
  7204. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7205. if ret_val == 'fail':
  7206. self.inform.emit('[ERROR_NOTCL] %s' %
  7207. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7208. "Try to load it from File menu.\n "
  7209. "Attempting to create a FlatCAM CNCJob Object from "
  7210. "G-Code file failed during processing"))
  7211. return "fail"
  7212. # Register recent file
  7213. self.file_opened.emit("cncjob", filename)
  7214. # AppGUI feedback
  7215. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7216. def open_hpgl2(self, filename, outname=None):
  7217. """
  7218. Opens a HPGL2 file, parses it and creates a new object for
  7219. it in the program. Thread-safe.
  7220. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7221. :param filename: HPGL2 file filename
  7222. :return: None
  7223. """
  7224. filename = filename
  7225. # How the object should be initialized
  7226. def obj_init(geo_obj, app_obj):
  7227. assert isinstance(geo_obj, GeometryObject), \
  7228. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7229. # Opening the file happens here
  7230. obj = HPGL2(self)
  7231. try:
  7232. HPGL2.parse_file(obj, filename)
  7233. except IOError:
  7234. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7235. return "fail"
  7236. except ParseError as err:
  7237. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7238. app_obj.log.error(str(err))
  7239. return "fail"
  7240. except Exception as e:
  7241. log.debug("App.open_hpgl2() --> %s" % str(e))
  7242. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7243. msg += traceback.format_exc()
  7244. app_obj.inform.emit(msg)
  7245. return "fail"
  7246. geo_obj.multigeo = True
  7247. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7248. geo_obj.tools = deepcopy(obj.tools)
  7249. geo_obj.source_file = deepcopy(obj.source_file)
  7250. del obj
  7251. if not geo_obj.solid_geometry:
  7252. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7253. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7254. return "fail"
  7255. App.log.debug("open_hpgl2()")
  7256. with self.proc_container.new(_("Opening HPGL2")):
  7257. # Object name
  7258. name = outname or filename.split('/')[-1].split('\\')[-1]
  7259. # # ## Object creation # ##
  7260. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7261. if ret == 'fail':
  7262. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7263. return 'fail'
  7264. # Register recent file
  7265. self.file_opened.emit("geometry", filename)
  7266. # AppGUI feedback
  7267. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7268. def open_script(self, filename, outname=None, silent=False):
  7269. """
  7270. Opens a Script file, parses it and creates a new object for
  7271. it in the program. Thread-safe.
  7272. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7273. :param filename: Script file filename
  7274. :param silent: If True there will be no messages printed to StatusBar
  7275. :return: None
  7276. """
  7277. def obj_init(script_obj, app_obj):
  7278. assert isinstance(script_obj, ScriptObject), \
  7279. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7280. if silent is False:
  7281. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7282. try:
  7283. script_obj.parse_file(filename)
  7284. except IOError:
  7285. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7286. return "fail"
  7287. except ParseError as err:
  7288. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7289. app_obj.log.error(str(err))
  7290. return "fail"
  7291. except Exception as e:
  7292. log.debug("App.open_script() -> %s" % str(e))
  7293. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7294. msg += traceback.format_exc()
  7295. app_obj.inform.emit(msg)
  7296. return "fail"
  7297. App.log.debug("open_script()")
  7298. with self.proc_container.new(_("Opening TCL Script...")):
  7299. # Object name
  7300. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7301. # Object creation
  7302. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7303. if ret_val == 'fail':
  7304. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7305. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7306. if ret_val == 'fail':
  7307. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7308. return 'fail'
  7309. # Register recent file
  7310. self.file_opened.emit("script", filename)
  7311. # AppGUI feedback
  7312. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7313. def open_config_file(self, filename, run_from_arg=None):
  7314. """
  7315. Loads a config file from the specified file.
  7316. :param filename: Name of the file from which to load.
  7317. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7318. :return: None
  7319. """
  7320. App.log.debug("Opening config file: " + filename)
  7321. if run_from_arg:
  7322. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7323. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7324. _("Opening FlatCAM Config file.")),
  7325. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7326. color=QtGui.QColor("gray"))
  7327. # # add the tab if it was closed
  7328. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7329. # # first clear previous text in text editor (if any)
  7330. # self.ui.text_editor_tab.code_editor.clear()
  7331. #
  7332. # # Switch plot_area to CNCJob tab
  7333. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7334. # close the Code editor if already open
  7335. if self.toggle_codeeditor:
  7336. self.on_toggle_code_editor()
  7337. self.on_toggle_code_editor()
  7338. try:
  7339. if filename:
  7340. f = QtCore.QFile(filename)
  7341. if f.open(QtCore.QIODevice.ReadOnly):
  7342. stream = QtCore.QTextStream(f)
  7343. code_edited = stream.readAll()
  7344. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7345. f.close()
  7346. except IOError:
  7347. App.log.error("Failed to open config file: %s" % filename)
  7348. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7349. (_("Failed to open config file"), filename))
  7350. return
  7351. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7352. """
  7353. Loads a project from the specified file.
  7354. 1) Loads and parses file
  7355. 2) Registers the file as recently opened.
  7356. 3) Calls on_file_new()
  7357. 4) Updates options
  7358. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7359. 6) Calls plot_all() if plot=True
  7360. :param filename: Name of the file from which to load.
  7361. :param run_from_arg: True if run for arguments
  7362. :param plot: If True plot all objects in the project
  7363. :param cli: Run from command line
  7364. :param from_tcl: True if run from Tcl Sehll
  7365. :return: None
  7366. """
  7367. App.log.debug("Opening project: " + filename)
  7368. # block autosaving while a project is loaded
  7369. self.block_autosave = True
  7370. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7371. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7372. if cli is None:
  7373. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7374. if run_from_arg:
  7375. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7376. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7377. _("Opening FlatCAM Project file.")),
  7378. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7379. color=QtGui.QColor("gray"))
  7380. # Open and parse an uncompressed Project file
  7381. try:
  7382. f = open(filename, 'r')
  7383. except IOError:
  7384. if from_tcl:
  7385. name = filename.split('/')[-1].split('\\')[-1]
  7386. filename = self.defaults['global_tcl_path'] + '/' + name
  7387. try:
  7388. f = open(filename, 'r')
  7389. except IOError:
  7390. log.error("Failed to open project file: %s" % filename)
  7391. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7392. return
  7393. else:
  7394. log.error("Failed to open project file: %s" % filename)
  7395. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7396. return
  7397. try:
  7398. d = json.load(f, object_hook=dict2obj)
  7399. except Exception as e:
  7400. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7401. (filename, str(e)))
  7402. f.close()
  7403. # Open and parse a compressed Project file
  7404. try:
  7405. with lzma.open(filename) as f:
  7406. file_content = f.read().decode('utf-8')
  7407. d = json.loads(file_content, object_hook=dict2obj)
  7408. except Exception as e:
  7409. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7410. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7411. return
  7412. # Clear the current project
  7413. # # NOT THREAD SAFE # ##
  7414. if run_from_arg is True:
  7415. pass
  7416. elif cli is True:
  7417. self.delete_selection_shape()
  7418. else:
  7419. self.on_file_new()
  7420. # Project options
  7421. self.options.update(d['options'])
  7422. self.project_filename = filename
  7423. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7424. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7425. if cli is None:
  7426. self.set_screen_units(self.options["units"])
  7427. # Re create objects
  7428. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7429. for obj in d['objs']:
  7430. try:
  7431. def obj_init(obj_inst, app_inst):
  7432. obj_inst.from_dict(obj)
  7433. App.log.debug("Recreating from opened project an %s object: %s" %
  7434. (obj['kind'].capitalize(), obj['options']['name']))
  7435. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7436. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7437. if cli is None:
  7438. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7439. obj['kind'].upper(),
  7440. obj['options']['name']
  7441. )
  7442. )
  7443. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7444. except Exception as e:
  7445. print('App.open_project() --> ' + str(e))
  7446. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7447. self.should_we_save = False
  7448. self.file_opened.emit("project", filename)
  7449. # restore autosaving after a project was loaded
  7450. self.block_autosave = False
  7451. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7452. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7453. if cli is None:
  7454. self.set_ui_title(name=self.project_filename)
  7455. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7456. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7457. """
  7458. Re-generates all plots from all objects.
  7459. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7460. :param muted: if True don't print messages
  7461. :param use_thread: if True will use threading for plotting the objects
  7462. :return: None
  7463. """
  7464. self.log.debug("Plot_all()")
  7465. if muted is not True:
  7466. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7467. for plot_obj in self.collection.get_list():
  7468. def worker_task(obj):
  7469. with self.proc_container.new("Plotting"):
  7470. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7471. if fit_view is True:
  7472. self.app_obj.object_plotted.emit(obj)
  7473. if use_thread is True:
  7474. # Send to worker
  7475. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7476. else:
  7477. worker_task(plot_obj)
  7478. def register_folder(self, filename):
  7479. """
  7480. Register the last folder used by the app to open something
  7481. :param filename: the last folder is extracted from the filename
  7482. :return: None
  7483. """
  7484. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7485. def register_save_folder(self, filename):
  7486. """
  7487. Register the last folder used by the app to save something
  7488. :param filename: the last folder is extracted from the filename
  7489. :return: None
  7490. """
  7491. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7492. # def set_progress_bar(self, percentage, text=""):
  7493. # """
  7494. # Set a progress bar to a value (percentage)
  7495. #
  7496. # :param percentage: Value set to the progressbar
  7497. # :param text: Not used
  7498. # :return: None
  7499. # """
  7500. # self.ui.progress_bar.setValue(int(percentage))
  7501. def setup_recent_items(self):
  7502. """
  7503. Setup a dictionary with the recent files accessed, organized by type
  7504. :return:
  7505. """
  7506. icons = {
  7507. "gerber": self.resource_location + "/flatcam_icon16.png",
  7508. "excellon": self.resource_location + "/drill16.png",
  7509. 'geometry': self.resource_location + "/geometry16.png",
  7510. "cncjob": self.resource_location + "/cnc16.png",
  7511. "script": self.resource_location + "/script_new24.png",
  7512. "document": self.resource_location + "/notes16_1.png",
  7513. "project": self.resource_location + "/project16.png",
  7514. "svg": self.resource_location + "/geometry16.png",
  7515. "dxf": self.resource_location + "/dxf16.png",
  7516. "pdf": self.resource_location + "/pdf32.png",
  7517. "image": self.resource_location + "/image16.png"
  7518. }
  7519. try:
  7520. image_opener = self.image_tool.import_image
  7521. except AttributeError:
  7522. image_opener = None
  7523. openers = {
  7524. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7525. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7526. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7527. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7528. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7529. "document": None,
  7530. 'project': self.open_project,
  7531. 'svg': self.import_svg,
  7532. 'dxf': self.import_dxf,
  7533. 'image': image_opener,
  7534. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7535. }
  7536. # Open recent file for files
  7537. try:
  7538. f = open(self.data_path + '/recent.json')
  7539. except IOError:
  7540. App.log.error("Failed to load recent item list.")
  7541. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7542. return
  7543. try:
  7544. self.recent = json.load(f)
  7545. except json.errors.JSONDecodeError:
  7546. App.log.error("Failed to parse recent item list.")
  7547. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7548. f.close()
  7549. return
  7550. f.close()
  7551. # Open recent file for projects
  7552. try:
  7553. fp = open(self.data_path + '/recent_projects.json')
  7554. except IOError:
  7555. App.log.error("Failed to load recent project item list.")
  7556. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7557. return
  7558. try:
  7559. self.recent_projects = json.load(fp)
  7560. except json.errors.JSONDecodeError:
  7561. App.log.error("Failed to parse recent project item list.")
  7562. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7563. fp.close()
  7564. return
  7565. fp.close()
  7566. # Closure needed to create callbacks in a loop.
  7567. # Otherwise late binding occurs.
  7568. def make_callback(func, fname):
  7569. def opener():
  7570. func(fname)
  7571. return opener
  7572. def reset_recent_files():
  7573. # Reset menu
  7574. self.ui.recent.clear()
  7575. self.recent = []
  7576. try:
  7577. ff = open(self.data_path + '/recent.json', 'w')
  7578. except IOError:
  7579. App.log.error("Failed to open recent items file for writing.")
  7580. return
  7581. json.dump(self.recent, ff)
  7582. def reset_recent_projects():
  7583. # Reset menu
  7584. self.ui.recent_projects.clear()
  7585. self.recent_projects = []
  7586. try:
  7587. frp = open(self.data_path + '/recent_projects.json', 'w')
  7588. except IOError:
  7589. App.log.error("Failed to open recent projects items file for writing.")
  7590. return
  7591. json.dump(self.recent, frp)
  7592. # Reset menu
  7593. self.ui.recent.clear()
  7594. self.ui.recent_projects.clear()
  7595. # Create menu items for projects
  7596. for recent in self.recent_projects:
  7597. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7598. if recent['kind'] == 'project':
  7599. try:
  7600. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7601. # Attach callback
  7602. o = make_callback(openers[recent["kind"]], recent['filename'])
  7603. action.triggered.connect(o)
  7604. self.ui.recent_projects.addAction(action)
  7605. except KeyError:
  7606. App.log.error("Unsupported file type: %s" % recent["kind"])
  7607. # Last action in Recent Files menu is one that Clear the content
  7608. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7609. (_("Clear Recent projects")), self)
  7610. clear_action_proj.triggered.connect(reset_recent_projects)
  7611. self.ui.recent_projects.addSeparator()
  7612. self.ui.recent_projects.addAction(clear_action_proj)
  7613. # Create menu items for files
  7614. for recent in self.recent:
  7615. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7616. if recent['kind'] != 'project':
  7617. try:
  7618. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7619. # Attach callback
  7620. o = make_callback(openers[recent["kind"]], recent['filename'])
  7621. action.triggered.connect(o)
  7622. self.ui.recent.addAction(action)
  7623. except KeyError:
  7624. App.log.error("Unsupported file type: %s" % recent["kind"])
  7625. # Last action in Recent Files menu is one that Clear the content
  7626. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7627. (_("Clear Recent files")), self)
  7628. clear_action.triggered.connect(reset_recent_files)
  7629. self.ui.recent.addSeparator()
  7630. self.ui.recent.addAction(clear_action)
  7631. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7632. # self.ui.menufilerecent.set_submenu(recent_menu)
  7633. # recent_menu.show_all()
  7634. # self.ui.recent.show()
  7635. self.log.debug("Recent items list has been populated.")
  7636. def setup_component_editor(self):
  7637. """
  7638. Default text for the Selected tab when is not taken by the Object UI.
  7639. :return:
  7640. """
  7641. # label = QtWidgets.QLabel("Choose an item from Project")
  7642. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7643. sel_title = QtWidgets.QTextEdit(
  7644. _('<b>Shortcut Key List</b>'))
  7645. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7646. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7647. f_settings = QSettings("Open Source", "FlatCAM")
  7648. if f_settings.contains("notebook_font_size"):
  7649. fsize = f_settings.value('notebook_font_size', type=int)
  7650. else:
  7651. fsize = 12
  7652. tsize = fsize + int(fsize / 2)
  7653. # selected_text = (_('''
  7654. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7655. # </p>
  7656. #
  7657. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7658. # The normal flow when working in FlatCAM is the following:</span></p>
  7659. #
  7660. # <ol>
  7661. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7662. # file into
  7663. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7664. # even dragging and dropping the files on the AppGUI.<br />
  7665. # <br />
  7666. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7667. # drop of the
  7668. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7669. # &nbsp;</li>
  7670. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7671. # and then
  7672. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7673. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7674. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7675. # <br />
  7676. # If the selection of the object is done on the canvas by single click instead, and the
  7677. # <strong>SELECTED TAB</strong>
  7678. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7679. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7680. # it even if it was out of focus.<br />
  7681. # <br />
  7682. # You can change the parameters in this screen and the flow direction is like this:<br />
  7683. # <br />
  7684. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7685. # <strong> Geometry Object
  7686. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7687. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7688. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7689. # </ol>
  7690. #
  7691. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7692. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7693. # <strong>F3</strong>.</span></p>
  7694. #
  7695. # ''').format(fsize=fsize, tsize=tsize))
  7696. selected_text = '''
  7697. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7698. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7699. {s1}</span></p>
  7700. <ol>
  7701. <li><span style="font-size:{fsize}px">{s2}<br />
  7702. <br />
  7703. {s3}</span><br />
  7704. &nbsp;</li>
  7705. <li><span style="font-size:{fsize}px">{s4}<br />
  7706. &nbsp;</li>
  7707. <br />
  7708. <li><span style="font-size:{fsize}px">{s5}<br />
  7709. &nbsp;</li>
  7710. <br />
  7711. <li><span style="font-size:{fsize}px">{s6}<br />
  7712. <br />
  7713. {s7}</span></li>
  7714. </ol>
  7715. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7716. '''.format(
  7717. title=_("Selected Tab - Choose an Item from Project Tab"),
  7718. subtitle=_("Details"),
  7719. s1=_("The normal flow when working in FlatCAM is the following:"),
  7720. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7721. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7722. "files on the AppGUI."),
  7723. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7724. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7725. "actions offered within the app."),
  7726. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7727. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7728. "SELECTED TAB will be updated with the object properties according to its kind: "
  7729. "Gerber, Excellon, Geometry or CNCJob object."),
  7730. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7731. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7732. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7733. "the SELECTED TAB and populate it even if it was out of focus."),
  7734. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7735. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7736. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7737. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7738. "(again, done in SELECTED TAB) --> Save GCode."),
  7739. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7740. "or through its own key shortcut: <b>F3</b>."),
  7741. tsize=tsize,
  7742. fsize=fsize
  7743. )
  7744. sel_title.setText(selected_text)
  7745. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7746. self.ui.selected_scroll_area.setWidget(sel_title)
  7747. def setup_obj_classes(self):
  7748. """
  7749. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7750. class.
  7751. :return: None
  7752. """
  7753. FlatCAMObj.app = self
  7754. ObjectCollection.app = self
  7755. Gerber.app = self
  7756. Excellon.app = self
  7757. Geometry.app = self
  7758. CNCjob.app = self
  7759. FCProcess.app = self
  7760. FCProcessContainer.app = self
  7761. OptionsGroupUI.app = self
  7762. def version_check(self):
  7763. """
  7764. Checks for the latest version of the program. Alerts the
  7765. user if theirs is outdated. This method is meant to be run
  7766. in a separate thread.
  7767. :return: None
  7768. """
  7769. self.log.debug("version_check()")
  7770. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7771. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7772. App.version_url,
  7773. str(self.defaults['global_serial']),
  7774. str(self.version),
  7775. str(self.os),
  7776. urllib.parse.urlencode(self.defaults["global_stats"])
  7777. )
  7778. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7779. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7780. # urllib.parse.urlencode(self.defaults["global_stats"])
  7781. else:
  7782. # no_stats dict; just so it won't break things on website
  7783. no_ststs_dict = {}
  7784. no_ststs_dict["global_ststs"] = {}
  7785. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7786. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7787. App.log.debug("Checking for updates @ %s" % full_url)
  7788. # ## Get the data
  7789. try:
  7790. f = urllib.request.urlopen(full_url)
  7791. except Exception:
  7792. # App.log.warning("Failed checking for latest version. Could not connect.")
  7793. self.log.warning("Failed checking for latest version. Could not connect.")
  7794. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7795. return
  7796. try:
  7797. data = json.load(f)
  7798. except Exception as e:
  7799. App.log.error("Could not parse information about latest version.")
  7800. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7801. App.log.debug("json.load(): %s" % str(e))
  7802. f.close()
  7803. return
  7804. f.close()
  7805. # ## Latest version?
  7806. if self.version >= data["version"]:
  7807. App.log.debug("FlatCAM is up to date!")
  7808. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7809. return
  7810. App.log.debug("Newer version available.")
  7811. self.message.emit(
  7812. _("Newer Version Available"),
  7813. '%s<br><br>><b>%s</b><br>%s' % (
  7814. _("There is a newer version of FlatCAM available for download:"),
  7815. str(data["name"]),
  7816. str(data["message"])
  7817. ),
  7818. _("info")
  7819. )
  7820. def on_plotcanvas_setup(self, container=None):
  7821. """
  7822. This is doing the setup for the plot area (canvas).
  7823. :param container: QT Widget where to install the canvas
  7824. :return: None
  7825. """
  7826. if container:
  7827. plot_container = container
  7828. else:
  7829. plot_container = self.ui.right_layout
  7830. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7831. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7832. self.is_legacy = True
  7833. self.defaults["global_graphic_engine"] = "2D"
  7834. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7835. else:
  7836. try:
  7837. self.plotcanvas = PlotCanvas(plot_container, self)
  7838. except Exception as er:
  7839. msg_txt = traceback.format_exc()
  7840. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7841. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7842. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7843. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7844. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7845. msg += msg_txt
  7846. self.inform.emit(msg)
  7847. return 'fail'
  7848. # So it can receive key presses
  7849. self.plotcanvas.native.setFocus()
  7850. if self.is_legacy is False:
  7851. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7852. # Set the mouse button for panning
  7853. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7854. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7855. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7856. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7857. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7858. # Keys over plot enabled
  7859. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7860. if self.defaults['global_cursor_type'] == 'small':
  7861. self.app_cursor = self.plotcanvas.new_cursor()
  7862. else:
  7863. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7864. if self.ui.grid_snap_btn.isChecked():
  7865. self.app_cursor.enabled = True
  7866. else:
  7867. self.app_cursor.enabled = False
  7868. if self.is_legacy is False:
  7869. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7870. else:
  7871. # will use the default Matplotlib axes
  7872. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7873. def on_zoom_fit(self):
  7874. """
  7875. Callback for zoom-fit request. This can be either from the corresponding
  7876. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7877. with axes limits from the geometry bounds of all objects.
  7878. :return: None
  7879. """
  7880. if self.is_legacy is False:
  7881. self.plotcanvas.fit_view()
  7882. else:
  7883. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7884. width = xmax - xmin
  7885. height = ymax - ymin
  7886. xmin -= 0.05 * width
  7887. xmax += 0.05 * width
  7888. ymin -= 0.05 * height
  7889. ymax += 0.05 * height
  7890. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7891. def on_zoom_in(self):
  7892. """
  7893. Callback for zoom-in request.
  7894. :return:
  7895. """
  7896. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7897. def on_zoom_out(self):
  7898. """
  7899. Callback for zoom-out request.
  7900. :return:
  7901. """
  7902. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7903. def disable_all_plots(self):
  7904. self.defaults.report_usage("disable_all_plots()")
  7905. self.disable_plots(self.collection.get_list())
  7906. self.inform.emit('[success] %s' %
  7907. _("All plots disabled."))
  7908. def disable_other_plots(self):
  7909. self.defaults.report_usage("disable_other_plots()")
  7910. self.disable_plots(self.collection.get_non_selected())
  7911. self.inform.emit('[success] %s' %
  7912. _("All non selected plots disabled."))
  7913. def enable_all_plots(self):
  7914. self.defaults.report_usage("enable_all_plots()")
  7915. self.enable_plots(self.collection.get_list())
  7916. self.inform.emit('[success] %s' %
  7917. _("All plots enabled."))
  7918. def on_enable_sel_plots(self):
  7919. log.debug("App.on_enable_sel_plot()")
  7920. object_list = self.collection.get_selected()
  7921. self.enable_plots(objects=object_list)
  7922. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7923. def on_disable_sel_plots(self):
  7924. log.debug("App.on_disable_sel_plot()")
  7925. # self.inform.emit(_("Disabling plots ..."))
  7926. object_list = self.collection.get_selected()
  7927. self.disable_plots(objects=object_list)
  7928. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7929. def enable_plots(self, objects):
  7930. """
  7931. Enable plots
  7932. :param objects: list of Objects to be enabled
  7933. :return:
  7934. """
  7935. log.debug("Enabling plots ...")
  7936. # self.inform.emit(_("Working ..."))
  7937. for obj in objects:
  7938. if obj.options['plot'] is False:
  7939. obj.options.set_change_callback(lambda x: None)
  7940. obj.options['plot'] = True
  7941. try:
  7942. # only the Gerber obj has on_plot_cb_click() method
  7943. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7944. # disable this cb while disconnected,
  7945. # in case the operation takes time the user is not allowed to change it
  7946. obj.ui.plot_cb.setDisabled(True)
  7947. except AttributeError:
  7948. pass
  7949. obj.set_form_item("plot")
  7950. try:
  7951. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7952. obj.ui.plot_cb.setDisabled(False)
  7953. except AttributeError:
  7954. pass
  7955. obj.options.set_change_callback(obj.on_options_change)
  7956. def worker_task(objs):
  7957. with self.proc_container.new(_("Enabling plots ...")):
  7958. for plot_obj in objs:
  7959. # obj.options['plot'] = True
  7960. if isinstance(plot_obj, CNCJobObject):
  7961. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7962. else:
  7963. plot_obj.plot(visible=True)
  7964. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7965. def disable_plots(self, objects):
  7966. """
  7967. Disables plots
  7968. :param objects: list of Objects to be disabled
  7969. :return:
  7970. """
  7971. # if no objects selected then do nothing
  7972. if not self.collection.get_selected():
  7973. return
  7974. log.debug("Disabling plots ...")
  7975. # self.inform.emit(_("Working ..."))
  7976. for obj in objects:
  7977. if obj.options['plot'] is True:
  7978. obj.options.set_change_callback(lambda x: None)
  7979. obj.options['plot'] = False
  7980. try:
  7981. # only the Gerber obj has on_plot_cb_click() method
  7982. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7983. obj.ui.plot_cb.setDisabled(True)
  7984. except AttributeError:
  7985. pass
  7986. obj.set_form_item("plot")
  7987. try:
  7988. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7989. obj.ui.plot_cb.setDisabled(False)
  7990. except AttributeError:
  7991. pass
  7992. obj.options.set_change_callback(obj.on_options_change)
  7993. try:
  7994. self.delete_selection_shape()
  7995. except Exception as e:
  7996. log.debug("App.disable_plots() --> %s" % str(e))
  7997. def worker_task(objs):
  7998. with self.proc_container.new(_("Disabling plots ...")):
  7999. for plot_obj in objs:
  8000. # obj.options['plot'] = True
  8001. if isinstance(plot_obj, CNCJobObject):
  8002. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8003. else:
  8004. plot_obj.plot(visible=False)
  8005. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8006. def toggle_plots(self, objects):
  8007. """
  8008. Toggle plots visibility
  8009. :param objects: list of Objects for which to be toggled the visibility
  8010. :return: None
  8011. """
  8012. # if no objects selected then do nothing
  8013. if not self.collection.get_selected():
  8014. return
  8015. log.debug("Toggling plots ...")
  8016. self.inform.emit(_("Working ..."))
  8017. for obj in objects:
  8018. if obj.options['plot'] is False:
  8019. obj.options['plot'] = True
  8020. else:
  8021. obj.options['plot'] = False
  8022. self.app_obj.plots_updated.emit()
  8023. def clear_plots(self):
  8024. """
  8025. Clear the plots
  8026. :return: None
  8027. """
  8028. objects = self.collection.get_list()
  8029. for obj in objects:
  8030. obj.clear(obj == objects[-1])
  8031. # Clear pool to free memory
  8032. self.clear_pool()
  8033. def on_set_color_action_triggered(self):
  8034. """
  8035. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8036. :return:
  8037. """
  8038. new_color = self.defaults['gerber_plot_fill']
  8039. clicked_action = self.sender()
  8040. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8041. act_name = clicked_action.text()
  8042. sel_obj_list = self.collection.get_selected()
  8043. if not sel_obj_list:
  8044. return
  8045. # a default value, I just chose this one
  8046. alpha_level = 'BF'
  8047. for sel_obj in sel_obj_list:
  8048. if sel_obj.kind == 'excellon':
  8049. alpha_level = str(hex(
  8050. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8051. elif sel_obj.kind == 'gerber':
  8052. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8053. elif sel_obj.kind == 'geometry':
  8054. alpha_level = 'FF'
  8055. else:
  8056. log.debug(
  8057. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8058. continue
  8059. sel_obj.alpha_level = alpha_level
  8060. if act_name == _('Red'):
  8061. new_color = '#FF0000' + alpha_level
  8062. if act_name == _('Blue'):
  8063. new_color = '#0000FF' + alpha_level
  8064. if act_name == _('Yellow'):
  8065. new_color = '#FFDF00' + alpha_level
  8066. if act_name == _('Green'):
  8067. new_color = '#00FF00' + alpha_level
  8068. if act_name == _('Purple'):
  8069. new_color = '#FF00FF' + alpha_level
  8070. if act_name == _('Brown'):
  8071. new_color = '#A52A2A' + alpha_level
  8072. if act_name == _('White'):
  8073. new_color = '#FFFFFF' + alpha_level
  8074. if act_name == _('Black'):
  8075. new_color = '#000000' + alpha_level
  8076. if act_name == _('Custom'):
  8077. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8078. c_dialog = QtWidgets.QColorDialog()
  8079. plot_fill_color = c_dialog.getColor(initial=new_color)
  8080. if plot_fill_color.isValid() is False:
  8081. return
  8082. new_color = str(plot_fill_color.name()) + alpha_level
  8083. if act_name == _("Default"):
  8084. for sel_obj in sel_obj_list:
  8085. if sel_obj.kind == 'excellon':
  8086. new_color = self.defaults['excellon_plot_fill']
  8087. new_line_color = self.defaults['excellon_plot_line']
  8088. elif sel_obj.kind == 'gerber':
  8089. new_color = self.defaults['gerber_plot_fill']
  8090. new_line_color = self.defaults['gerber_plot_line']
  8091. elif sel_obj.kind == 'geometry':
  8092. new_color = self.defaults['geometry_plot_line']
  8093. new_line_color = self.defaults['geometry_plot_line']
  8094. else:
  8095. log.debug(
  8096. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8097. continue
  8098. sel_obj.fill_color = new_color
  8099. sel_obj.outline_color = new_line_color
  8100. sel_obj.shapes.redraw(
  8101. update_colors=(new_color, new_line_color)
  8102. )
  8103. return
  8104. if act_name == _("Opacity"):
  8105. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8106. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8107. if ok_button:
  8108. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8109. for sel_obj in sel_obj_list:
  8110. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8111. sel_obj.shapes.redraw(
  8112. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8113. )
  8114. return
  8115. new_line_color = color_variant(new_color[:7], 0.7)
  8116. if act_name == _("White"):
  8117. new_line_color = color_variant("#dedede", 0.7)
  8118. for sel_obj in sel_obj_list:
  8119. sel_obj.fill_color = new_color
  8120. sel_obj.outline_color = new_line_color
  8121. sel_obj.shapes.redraw(
  8122. update_colors=(new_color, new_line_color)
  8123. )
  8124. def generate_cnc_job(self, objects):
  8125. """
  8126. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8127. :param objects: Selected objects in the Project Tab
  8128. :return:
  8129. """
  8130. self.defaults.report_usage("generate_cnc_job()")
  8131. # for obj in objects:
  8132. # obj.generatecncjob()
  8133. for obj in objects:
  8134. obj.on_generatecnc_button_click()
  8135. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8136. """
  8137. Saves the current project to the specified file.
  8138. :param filename: Name of the file in which to save.
  8139. :type filename: str
  8140. :param quit_action: if the project saving will be followed by an app quit; boolean
  8141. :param silent: if True will not display status messages
  8142. :param from_tcl True is run from Tcl Shell
  8143. :return: None
  8144. """
  8145. self.log.debug("save_project()")
  8146. self.save_in_progress = True
  8147. with self.proc_container.new(_("Saving FlatCAM Project")):
  8148. # Capture the latest changes
  8149. # Current object
  8150. try:
  8151. current_object = self.collection.get_active()
  8152. if current_object:
  8153. current_object.read_form()
  8154. except Exception as e:
  8155. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8156. pass
  8157. # Serialize the whole project
  8158. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8159. "options": self.options,
  8160. "version": self.version}
  8161. if self.defaults["global_save_compressed"] is True:
  8162. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8163. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8164. # # Write
  8165. f.write(g)
  8166. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8167. else:
  8168. # Open file
  8169. try:
  8170. f = open(filename, 'w')
  8171. except IOError:
  8172. App.log.error("Failed to open file for saving: %s", filename)
  8173. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8174. return
  8175. # Write
  8176. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8177. f.close()
  8178. # verification of the saved project
  8179. # Open and parse
  8180. try:
  8181. saved_f = open(filename, 'r')
  8182. except IOError:
  8183. if silent is False:
  8184. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8185. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8186. return
  8187. try:
  8188. saved_d = json.load(saved_f, object_hook=dict2obj)
  8189. except Exception:
  8190. if silent is False:
  8191. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8192. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8193. f.close()
  8194. return
  8195. saved_f.close()
  8196. if silent is False:
  8197. if 'version' in saved_d:
  8198. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8199. else:
  8200. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8201. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8202. tb_settings = QSettings("Open Source", "FlatCAM")
  8203. lock_state = self.ui.lock_action.isChecked()
  8204. tb_settings.setValue('toolbar_lock', lock_state)
  8205. # This will write the setting to the platform specific storage.
  8206. del tb_settings
  8207. # if quit:
  8208. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8209. # t.start()
  8210. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8211. def start_delayed_quit(self, delay, filename, should_quit=None):
  8212. """
  8213. :param delay: period of checking if project file size is more than zero; in seconds
  8214. :param filename: the name of the project file to be checked periodically for size more than zero
  8215. :param should_quit: if the task finished will be followed by an app quit; boolean
  8216. :return:
  8217. """
  8218. to_quit = should_quit
  8219. self.save_timer = QtCore.QTimer()
  8220. self.save_timer.setInterval(delay)
  8221. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8222. self.save_timer.start()
  8223. def check_project_file_size(self, filename, should_quit=None):
  8224. """
  8225. :param filename: the name of the project file to be checked periodically for size more than zero
  8226. :param should_quit: will quit the app if True; boolean
  8227. :return:
  8228. """
  8229. try:
  8230. if os.stat(filename).st_size > 0:
  8231. self.save_in_progress = False
  8232. self.save_timer.stop()
  8233. if should_quit:
  8234. self.app_quit.emit()
  8235. except Exception:
  8236. traceback.print_exc()
  8237. def save_project_auto(self):
  8238. """
  8239. Called periodically to save the project.
  8240. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8241. # progress.
  8242. :return:
  8243. """
  8244. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8245. self.on_file_saveproject()
  8246. def save_project_auto_update(self):
  8247. """
  8248. Update the auto save time interval value.
  8249. :return:
  8250. """
  8251. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8252. try:
  8253. if self.autosave_timer.isActive():
  8254. self.autosave_timer.stop()
  8255. except Exception:
  8256. pass
  8257. if self.defaults['global_autosave'] is True:
  8258. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8259. self.autosave_timer.start()
  8260. def on_options_app2project(self):
  8261. """
  8262. Callback for Options->Transfer Options->App=>Project. Copies options
  8263. from application defaults to project defaults.
  8264. :return: None
  8265. """
  8266. self.defaults.report_usage("on_options_app2project")
  8267. self.preferencesUiManager.defaults_read_form()
  8268. self.options.update(self.defaults)
  8269. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8270. """
  8271. Shows a message on the FlatCAM Shell
  8272. :param msg: Message to display.
  8273. :param show: Opens the shell.
  8274. :param error: Shows the message as an error.
  8275. :param warning: Shows the message as an warning.
  8276. :param success: Shows the message as an success.
  8277. :param selected: Indicate that something was selected on canvas
  8278. :return: None
  8279. """
  8280. if show:
  8281. self.ui.shell_dock.show()
  8282. try:
  8283. if error:
  8284. self.shell.append_error(msg + "\n")
  8285. elif warning:
  8286. self.shell.append_warning(msg + "\n")
  8287. elif success:
  8288. self.shell.append_success(msg + "\n")
  8289. elif selected:
  8290. self.shell.append_selected(msg + "\n")
  8291. else:
  8292. self.shell.append_output(msg + "\n")
  8293. except AttributeError:
  8294. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8295. class ArgsThread(QtCore.QObject):
  8296. open_signal = pyqtSignal(list)
  8297. start = pyqtSignal()
  8298. stop = pyqtSignal()
  8299. if sys.platform == 'win32':
  8300. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8301. else:
  8302. address = ('/tmp/testipc', 'AF_UNIX')
  8303. def __init__(self):
  8304. super(ArgsThread, self).__init__()
  8305. self.listener = None
  8306. self.thread_exit = False
  8307. self.start.connect(self.run)
  8308. self.stop.connect(self.close_listener)
  8309. def my_loop(self, address):
  8310. try:
  8311. self.listener = Listener(*address)
  8312. while self.thread_exit is False:
  8313. conn = self.listener.accept()
  8314. self.serve(conn)
  8315. except socket.error:
  8316. try:
  8317. conn = Client(*address)
  8318. conn.send(sys.argv)
  8319. conn.send('close')
  8320. # close the current instance only if there are args
  8321. if len(sys.argv) > 1:
  8322. try:
  8323. self.listener.close()
  8324. except Exception:
  8325. pass
  8326. sys.exit()
  8327. except ConnectionRefusedError:
  8328. if sys.platform == 'win32':
  8329. pass
  8330. else:
  8331. os.system('rm /tmp/testipc')
  8332. self.listener = Listener(*address)
  8333. while True:
  8334. conn = self.listener.accept()
  8335. self.serve(conn)
  8336. def serve(self, conn):
  8337. while self.thread_exit is False:
  8338. msg = conn.recv()
  8339. if msg == 'close':
  8340. break
  8341. self.open_signal.emit(msg)
  8342. conn.close()
  8343. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8344. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8345. @pyqtSlot()
  8346. def run(self):
  8347. self.my_loop(self.address)
  8348. @pyqtSlot()
  8349. def close_listener(self):
  8350. self.thread_exit = True
  8351. self.listener.close()
  8352. # end of file