App_Main.py 443 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910
  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. # portability changed signal
  761. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  762. # Object list
  763. self.object_status_changed.connect(self.collection.on_collection_updated)
  764. # when there are arguments at application startup this get launched
  765. self.args_at_startup[list].connect(self.on_startup_args)
  766. # ###########################################################################################################
  767. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  768. # ###########################################################################################################
  769. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  770. lambda: self.restore_extensions(ext_type='excellon'))
  771. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  772. lambda: self.restore_extensions(ext_type='gcode'))
  773. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  774. lambda: self.restore_extensions(ext_type='gerber'))
  775. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  776. lambda: self.delete_all_extensions(ext_type='excellon'))
  777. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  778. lambda: self.delete_all_extensions(ext_type='gcode'))
  779. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  780. lambda: self.delete_all_extensions(ext_type='gerber'))
  781. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  782. lambda: self.add_extension(ext_type='excellon'))
  783. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  784. lambda: self.add_extension(ext_type='gcode'))
  785. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  786. lambda: self.add_extension(ext_type='gerber'))
  787. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  788. lambda: self.del_extension(ext_type='excellon'))
  789. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  790. lambda: self.del_extension(ext_type='gcode'))
  791. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  792. lambda: self.del_extension(ext_type='gerber'))
  793. # connect the 'Apply' buttons from the Preferences/File Associations
  794. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  795. lambda: self.on_register_files(obj_type='excellon'))
  796. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  797. lambda: self.on_register_files(obj_type='gcode'))
  798. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  799. lambda: self.on_register_files(obj_type='gerber'))
  800. # ###########################################################################################################
  801. # ########################################### KEYWORDS SIGNALS ##############################################
  802. # ###########################################################################################################
  803. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  804. lambda: self.restore_extensions(ext_type='keyword'))
  805. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  806. lambda: self.delete_all_extensions(ext_type='keyword'))
  807. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  808. lambda: self.add_extension(ext_type='keyword'))
  809. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  810. lambda: self.del_extension(ext_type='keyword'))
  811. # connect the abort_all_tasks related slots to the related signals
  812. self.proc_container.idle_flag.connect(self.app_is_idle)
  813. # signal emitted when a tab is closed in the Plot Area
  814. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  815. # signal to close the application
  816. self.close_app_signal.connect(self.kill_app)
  817. # ################################# FINISHED CONNECTING SIGNALS #############################################
  818. # ###########################################################################################################
  819. # ###########################################################################################################
  820. # ###########################################################################################################
  821. self.log.debug("Finished connecting Signals.")
  822. # ###########################################################################################################
  823. # ########################################## Other setups ###################################################
  824. # ###########################################################################################################
  825. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  826. # depending on from where those tools are called different actions can be done
  827. self.call_source = 'app'
  828. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  829. self.tool_tab_locked = False
  830. # decide if to show or hide the Notebook side of the screen at startup
  831. if self.defaults["global_project_at_startup"] is True:
  832. self.ui.splitter.setSizes([1, 1])
  833. else:
  834. self.ui.splitter.setSizes([0, 1])
  835. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  836. self.setup_component_editor()
  837. # ###########################################################################################################
  838. # ####################################### Auto-complete KEYWORDS ############################################
  839. # ###########################################################################################################
  840. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  841. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  842. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  843. 'export_exc',
  844. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  845. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  846. 'interiors', 'isolate', 'join_excellon',
  847. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  848. 'mirror', 'ncc',
  849. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  850. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  851. 'options', 'origin',
  852. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  853. 'save', 'save_project',
  854. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  855. 'skew', 'subtract_poly', 'subtract_rectangle',
  856. 'version', 'write_gcode'
  857. ]
  858. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  859. 'Paste_1',
  860. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  861. 'Toolchange_manual', 'True', 'Users',
  862. 'all', 'auto', 'axis',
  863. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  864. 'contour', 'default',
  865. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  866. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  867. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  868. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  869. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  870. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  871. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  872. 'spacing_columns',
  873. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  874. 'toolchange_xy', 'toolchangez', 'travelz',
  875. 'tooldia', 'use_threads', 'value',
  876. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  877. ]
  878. self.tcl_keywords = [
  879. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  880. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  881. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  882. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  883. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  884. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  885. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  886. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  887. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  888. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  889. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  890. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  891. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  892. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  893. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  894. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  895. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  896. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  897. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  898. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  899. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  900. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  901. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  902. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  903. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  904. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  905. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  906. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  907. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  908. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  909. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  910. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  911. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  912. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  913. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  914. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  915. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  916. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  917. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  918. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  919. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  920. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  921. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  922. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  923. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  924. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  925. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  926. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  927. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  928. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  929. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  930. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  931. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  932. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  933. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  934. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  935. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  936. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  937. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  938. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  939. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  940. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  941. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  942. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  943. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  944. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  945. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  946. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  947. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  948. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  949. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  950. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  951. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  952. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  953. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  954. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  955. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  956. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  957. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  958. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  959. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  960. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  961. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  962. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  963. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  964. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  965. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  966. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  967. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  968. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  969. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  970. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  971. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  972. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  973. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  974. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  975. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  976. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  977. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  978. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  979. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  980. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  981. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  982. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  983. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  984. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  985. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  986. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  987. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  988. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  989. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  990. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  991. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  992. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  993. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  994. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  995. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  996. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  997. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  998. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  999. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1000. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1001. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1002. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1003. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1004. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1005. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1006. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1007. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1008. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1009. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1010. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1011. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1012. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1013. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1014. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1015. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1016. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1017. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1018. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1019. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1020. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1021. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1022. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1023. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1024. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1025. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1026. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1027. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1028. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1029. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1030. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1031. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1032. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1033. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1034. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1035. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1036. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1037. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1038. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1039. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1040. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1041. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1042. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1043. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1044. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1045. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1046. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1047. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1048. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1049. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1050. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1051. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1052. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1053. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1054. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1055. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1056. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1057. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1058. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1059. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1060. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1061. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1062. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1063. ]
  1064. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1065. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1066. # ###########################################################################################################
  1067. # ############################################## Shell SETUP ################################################
  1068. # ###########################################################################################################
  1069. self.shell = FCShell(app=self, version=self.version)
  1070. self.ui.shell_dock.setWidget(self.shell)
  1071. self.log.debug("TCL Shell has been initialized.")
  1072. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1073. if self.defaults["global_shell_at_startup"]:
  1074. self.ui.shell_dock.show()
  1075. else:
  1076. self.ui.shell_dock.hide()
  1077. # ###########################################################################################################
  1078. # ########################################## Tools and Plugins ##############################################
  1079. # ###########################################################################################################
  1080. self.dblsidedtool = None
  1081. self.distance_tool = None
  1082. self.distance_min_tool = None
  1083. self.panelize_tool = None
  1084. self.film_tool = None
  1085. self.paste_tool = None
  1086. self.calculator_tool = None
  1087. self.rules_tool = None
  1088. self.sub_tool = None
  1089. self.move_tool = None
  1090. self.cutout_tool = None
  1091. self.ncclear_tool = None
  1092. self.optimal_tool = None
  1093. self.paint_tool = None
  1094. self.transform_tool = None
  1095. self.properties_tool = None
  1096. self.pdf_tool = None
  1097. self.image_tool = None
  1098. self.pcb_wizard_tool = None
  1099. self.cal_exc_tool = None
  1100. self.qrcode_tool = None
  1101. self.copper_thieving_tool = None
  1102. self.fiducial_tool = None
  1103. self.edrills_tool = None
  1104. self.align_objects_tool = None
  1105. self.punch_tool = None
  1106. self.invert_tool = None
  1107. self.corners_tool = None
  1108. self.etch_tool = None
  1109. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1110. try:
  1111. self.install_tools()
  1112. except AttributeError as e:
  1113. log.debug("App.__init__() install tools() --> %s" % str(e))
  1114. # ###########################################################################################################
  1115. # ############################################ SETUP RECENT ITEMS ###########################################
  1116. # ###########################################################################################################
  1117. self.setup_recent_items()
  1118. # ###########################################################################################################
  1119. # ######################################### BookMarks Manager ###############################################
  1120. # ###########################################################################################################
  1121. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1122. self.install_bookmarks()
  1123. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1124. # ###########################################################################################################
  1125. # ########################################### Tools Database ################################################
  1126. # ###########################################################################################################
  1127. self.tools_db_tab = None
  1128. # ### System Font Parsing ###
  1129. # self.f_parse = ParseFont(self)
  1130. # self.parse_system_fonts()
  1131. # ###########################################################################################################
  1132. # ######################################### Check for updates ###############################################
  1133. # ###########################################################################################################
  1134. # Separate thread (Not worker)
  1135. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1136. if (self.beta is False or self.beta is None) and \
  1137. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1138. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1139. # self.thr2 = QtCore.QThread()
  1140. self.worker_task.emit({'fcn': self.version_check,
  1141. 'params': []})
  1142. # self.thr2.start(QtCore.QThread.LowPriority)
  1143. # ###########################################################################################################
  1144. # ##################################### Register files with FlatCAM; #######################################
  1145. # ################################### It works only for Windows for now ####################################
  1146. # ###########################################################################################################
  1147. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1148. self.on_register_files()
  1149. # ###########################################################################################################
  1150. # ######################################## Variables for global usage #######################################
  1151. # ###########################################################################################################
  1152. # hold the App units
  1153. self.units = 'MM'
  1154. # coordinates for relative position display
  1155. self.rel_point1 = (0, 0)
  1156. self.rel_point2 = (0, 0)
  1157. # variable to store coordinates
  1158. self.pos = (0, 0)
  1159. self.pos_canvas = (0, 0)
  1160. self.pos_jump = (0, 0)
  1161. # variable to store mouse coordinates
  1162. self.mouse = [0, 0]
  1163. # variable to store the delta positions on cavnas
  1164. self.dx = 0
  1165. self.dy = 0
  1166. # decide if we have a double click or single click
  1167. self.doubleclick = False
  1168. # store here the is_dragging value
  1169. self.event_is_dragging = False
  1170. # variable to store if a command is active (then the var is not None) and which one it is
  1171. self.command_active = None
  1172. # variable to store the status of moving selection action
  1173. # None value means that it's not an selection action
  1174. # True value = a selection from left to right
  1175. # False value = a selection from right to left
  1176. self.selection_type = None
  1177. # List to store the objects that are currently loaded in FlatCAM
  1178. # This list is updated on each object creation or object delete
  1179. self.all_objects_list = []
  1180. self.objects_under_the_click_list = []
  1181. # List to store the objects that are selected
  1182. self.sel_objects_list = []
  1183. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1184. self.key_modifiers = None
  1185. # Variable to hold the status of the axis
  1186. self.toggle_axis = True
  1187. # Variable to hold the status of the grid lines
  1188. self.toggle_grid_lines = True
  1189. # Variable to store the status of the code editor
  1190. self.toggle_codeeditor = False
  1191. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1192. self.click_noproject = False
  1193. self.cursor = None
  1194. # Variable to store the GCODE that was edited
  1195. self.gcode_edited = ""
  1196. self.text_editor_tab = None
  1197. # reference for the self.ui.code_editor
  1198. self.reference_code_editor = None
  1199. self.script_code = ''
  1200. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1201. self.tools_db_changed_flag = False
  1202. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1203. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1204. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1205. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1206. 'tsm']
  1207. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1208. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1209. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1210. 'sbp', 'tap', 'xpi']
  1211. self.svg_list = ['svg']
  1212. self.dxf_list = ['dxf']
  1213. self.pdf_list = ['pdf']
  1214. self.prj_list = ['flatprj']
  1215. self.conf_list = ['flatconfig']
  1216. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1217. # flag for polygons not cleared
  1218. self.poly_not_cleared = False
  1219. # VisPy visuals
  1220. self.isHovering = False
  1221. self.notHovering = True
  1222. # Window geometry
  1223. self.x_pos = None
  1224. self.y_pos = None
  1225. self.width = None
  1226. self.height = None
  1227. # when True, the app has to return from any thread
  1228. self.abort_flag = False
  1229. # set the value used in the Windows Title
  1230. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1231. # this holds a widget that is installed in the Plot Area when View Source option is used
  1232. self.source_editor_tab = None
  1233. self.pagesize = {}
  1234. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1235. # VisPy visuals
  1236. if self.is_legacy is False:
  1237. try:
  1238. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1239. except AttributeError:
  1240. self.tool_shapes = None
  1241. else:
  1242. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1243. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1244. # used in the delayed shutdown self.start_delayed_quit() method
  1245. self.save_timer = None
  1246. # ###########################################################################################################
  1247. # ################################## ADDING FlatCAM EDITORS section #########################################
  1248. # ###########################################################################################################
  1249. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1250. # at the first launch of the App , the editors will not be functional.
  1251. try:
  1252. self.geo_editor = FlatCAMGeoEditor(self)
  1253. except AttributeError:
  1254. pass
  1255. try:
  1256. self.exc_editor = FlatCAMExcEditor(self)
  1257. except AttributeError:
  1258. pass
  1259. try:
  1260. self.grb_editor = FlatCAMGrbEditor(self)
  1261. except AttributeError:
  1262. pass
  1263. self.log.debug("Finished adding FlatCAM Editor's.")
  1264. self.set_ui_title(name=_("New Project - Not saved"))
  1265. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1266. current_platform = platform.architecture()[0]
  1267. if current_platform != '64bit':
  1268. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1270. # ###########################################################################################################
  1271. # ########################################### EXCLUSION AREAS ###############################################
  1272. # ###########################################################################################################
  1273. self.exc_areas = ExclusionAreas(app=self)
  1274. # ###########################################################################################################
  1275. # ##################################### Finished the CONSTRUCTOR ############################################
  1276. # ###########################################################################################################
  1277. App.log.debug("END of constructor. Releasing control.")
  1278. # ###########################################################################################################
  1279. # ########################################## SHOW GUI #######################################################
  1280. # ###########################################################################################################
  1281. # if the app is not started as headless, show it
  1282. if self.cmd_line_headless != 1:
  1283. if show_splash:
  1284. # finish the splash
  1285. self.splash.finish(self.ui)
  1286. mgui_settings = QSettings("Open Source", "FlatCAM")
  1287. if mgui_settings.contains("maximized_gui"):
  1288. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1289. if maximized_ui is True:
  1290. self.ui.showMaximized()
  1291. else:
  1292. self.ui.show()
  1293. else:
  1294. self.ui.show()
  1295. if self.defaults["global_systray_icon"]:
  1296. self.trayIcon.show()
  1297. else:
  1298. log.warning("******************* RUNNING HEADLESS *******************")
  1299. # ###########################################################################################################
  1300. # ######################################## START-UP ARGUMENTS ###############################################
  1301. # ###########################################################################################################
  1302. # test if the program was started with a script as parameter
  1303. if self.cmd_line_shellvar:
  1304. try:
  1305. cnt = 0
  1306. command_tcl = 0
  1307. for i in self.cmd_line_shellvar.split(','):
  1308. if i is not None:
  1309. # noinspection PyBroadException
  1310. try:
  1311. command_tcl = eval(i)
  1312. except Exception:
  1313. command_tcl = i
  1314. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1315. cnt += 1
  1316. # if there are Windows paths then replace the path separator with a Unix like one
  1317. if sys.platform == 'win32':
  1318. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1319. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1320. except Exception as ext:
  1321. print("ERROR: ", ext)
  1322. sys.exit(2)
  1323. if self.cmd_line_shellfile:
  1324. if self.cmd_line_headless != 1:
  1325. if self.ui.shell_dock.isHidden():
  1326. self.ui.shell_dock.show()
  1327. try:
  1328. with open(self.cmd_line_shellfile, "r") as myfile:
  1329. # if show_splash:
  1330. # self.splash.showMessage('%s: %ssec\n%s' % (
  1331. # _("Canvas initialization started.\n"
  1332. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1333. # _("Executing Tcl Script ...")),
  1334. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1335. # color=QtGui.QColor("gray"))
  1336. cmd_line_shellfile_text = myfile.read()
  1337. if self.cmd_line_headless != 1:
  1338. self.shell.exec_command(cmd_line_shellfile_text)
  1339. else:
  1340. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1341. except Exception as ext:
  1342. print("ERROR: ", ext)
  1343. sys.exit(2)
  1344. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1345. # the path/file_name must be enclosed in quotes if it contain spaces
  1346. if App.args:
  1347. self.args_at_startup.emit(App.args)
  1348. if self.defaults.old_defaults_found is True:
  1349. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1350. "Please reboot the application to update."))
  1351. self.defaults.old_defaults_found = False
  1352. # ######################################### INIT FINISHED #######################################################
  1353. # #################################################################################################################
  1354. # #################################################################################################################
  1355. # #################################################################################################################
  1356. # #################################################################################################################
  1357. # #################################################################################################################
  1358. @staticmethod
  1359. def copy_and_overwrite(from_path, to_path):
  1360. """
  1361. From here:
  1362. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1363. :param from_path: source path
  1364. :param to_path: destination path
  1365. :return: None
  1366. """
  1367. if os.path.exists(to_path):
  1368. shutil.rmtree(to_path)
  1369. try:
  1370. shutil.copytree(from_path, to_path)
  1371. except FileNotFoundError:
  1372. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1373. shutil.copytree(from_new_path, to_path)
  1374. def on_startup_args(self, args, silent=False):
  1375. """
  1376. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1377. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1378. :param args: a list containing the application args at startup
  1379. :return: None
  1380. """
  1381. if args is not None:
  1382. args_to_process = args
  1383. else:
  1384. args_to_process = App.args
  1385. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1386. for argument in args_to_process:
  1387. if '.FlatPrj'.lower() in argument.lower():
  1388. try:
  1389. project_name = str(argument)
  1390. if project_name == "":
  1391. if silent is False:
  1392. self.inform.emit(_("Cancelled."))
  1393. else:
  1394. # self.open_project(project_name)
  1395. run_from_arg = True
  1396. # self.worker_task.emit({'fcn': self.open_project,
  1397. # 'params': [project_name, run_from_arg]})
  1398. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1399. except Exception as e:
  1400. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1401. elif '.FlatConfig'.lower() in argument.lower():
  1402. try:
  1403. file_name = str(argument)
  1404. if file_name == "":
  1405. if silent is False:
  1406. self.inform.emit(_("Open Config file failed."))
  1407. else:
  1408. run_from_arg = True
  1409. # self.worker_task.emit({'fcn': self.open_config_file,
  1410. # 'params': [file_name, run_from_arg]})
  1411. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1412. except Exception as e:
  1413. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1414. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1415. try:
  1416. file_name = str(argument)
  1417. if file_name == "":
  1418. if silent is False:
  1419. self.inform.emit(_("Open Script file failed."))
  1420. else:
  1421. if silent is False:
  1422. self.on_fileopenscript(name=file_name)
  1423. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1424. self.on_filerunscript(name=file_name)
  1425. except Exception as e:
  1426. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1427. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1428. log.debug("App.on_startup_args() --> Quit event.")
  1429. sys.exit()
  1430. elif 'save'.lower() in argument.lower():
  1431. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1432. self.preferencesUiManager.save_defaults()
  1433. else:
  1434. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1435. proc_arg = argument.lower()
  1436. for ext in exc_list:
  1437. proc_ext = ext.replace(' ', '')
  1438. proc_ext = '.%s' % proc_ext
  1439. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1440. file_name = str(argument)
  1441. if file_name == "":
  1442. if silent is False:
  1443. self.inform.emit(_("Open Excellon file failed."))
  1444. else:
  1445. self.on_fileopenexcellon(name=file_name, signal=None)
  1446. return
  1447. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1448. for ext in gco_list:
  1449. proc_ext = ext.replace(' ', '')
  1450. proc_ext = '.%s' % proc_ext
  1451. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1452. file_name = str(argument)
  1453. if file_name == "":
  1454. if silent is False:
  1455. self.inform.emit(_("Open GCode file failed."))
  1456. else:
  1457. self.on_fileopengcode(name=file_name, signal=None)
  1458. return
  1459. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1460. for ext in grb_list:
  1461. proc_ext = ext.replace(' ', '')
  1462. proc_ext = '.%s' % proc_ext
  1463. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1464. file_name = str(argument)
  1465. if file_name == "":
  1466. if silent is False:
  1467. self.inform.emit(_("Open Gerber file failed."))
  1468. else:
  1469. self.on_fileopengerber(name=file_name, signal=None)
  1470. return
  1471. # if it reached here without already returning then the app was registered with a file that it does not
  1472. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1473. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1474. # for arg in args_to_process:
  1475. # if 'FlatCAM.exe' in arg:
  1476. # continue
  1477. # else:
  1478. # sys.exit(2)
  1479. def set_ui_title(self, name):
  1480. """
  1481. Sets the title of the main window.
  1482. :param name: String that store the project path and project name
  1483. :return: None
  1484. """
  1485. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1486. (self.version,
  1487. ('BETA' if self.beta else ''),
  1488. platform.architecture()[0],
  1489. self.engine,
  1490. name)
  1491. )
  1492. def on_app_restart(self):
  1493. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1494. # be left in the SySTray
  1495. try:
  1496. self.trayIcon.hide()
  1497. except Exception:
  1498. pass
  1499. fcTranslate.restart_program(app=self)
  1500. def clear_pool(self):
  1501. """
  1502. Clear the multiprocessing pool and calls garbage collector.
  1503. :return: None
  1504. """
  1505. self.pool.close()
  1506. self.pool = Pool()
  1507. self.pool_recreated.emit(self.pool)
  1508. gc.collect()
  1509. def install_tools(self):
  1510. """
  1511. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1512. Instantiation of the Tools classes.
  1513. The order that the tools are installed is important as they can depend on each other install position.
  1514. :return: None
  1515. """
  1516. self.distance_tool = Distance(self)
  1517. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1518. before=self.ui.menueditorigin,
  1519. separator=False)
  1520. self.distance_min_tool = DistanceMin(self)
  1521. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1522. pos=self.ui.menuedit,
  1523. before=self.ui.menueditorigin,
  1524. separator=True)
  1525. self.dblsidedtool = DblSidedTool(self)
  1526. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1527. self.cal_exc_tool = ToolCalibration(self)
  1528. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1529. before=self.dblsidedtool.menuAction,
  1530. separator=False)
  1531. self.align_objects_tool = AlignObjects(self)
  1532. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1533. self.edrills_tool = ToolExtractDrills(self)
  1534. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1535. self.panelize_tool = Panelize(self)
  1536. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1537. self.film_tool = Film(self)
  1538. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1539. self.paste_tool = SolderPaste(self)
  1540. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1541. self.calculator_tool = ToolCalculator(self)
  1542. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1543. self.sub_tool = ToolSub(self)
  1544. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1545. pos=self.ui.menutool, separator=True)
  1546. self.rules_tool = RulesCheck(self)
  1547. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1548. pos=self.ui.menutool, separator=False)
  1549. self.optimal_tool = ToolOptimal(self)
  1550. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1551. pos=self.ui.menutool, separator=True)
  1552. self.move_tool = ToolMove(self)
  1553. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1554. before=self.ui.menueditorigin, separator=True)
  1555. self.cutout_tool = CutOut(self)
  1556. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1557. before=self.sub_tool.menuAction)
  1558. self.ncclear_tool = NonCopperClear(self)
  1559. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1560. before=self.sub_tool.menuAction, separator=True)
  1561. self.paint_tool = ToolPaint(self)
  1562. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1563. before=self.sub_tool.menuAction, separator=True)
  1564. self.copper_thieving_tool = ToolCopperThieving(self)
  1565. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1566. pos=self.ui.menutool)
  1567. self.fiducial_tool = ToolFiducials(self)
  1568. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1569. pos=self.ui.menutool)
  1570. self.qrcode_tool = QRCode(self)
  1571. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1572. pos=self.ui.menutool)
  1573. self.punch_tool = ToolPunchGerber(self)
  1574. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1575. self.invert_tool = ToolInvertGerber(self)
  1576. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1577. self.corners_tool = ToolCorners(self)
  1578. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1579. self.etch_tool = ToolEtchCompensation(self)
  1580. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etcg_32.png'), pos=self.ui.menutool)
  1581. self.transform_tool = ToolTransform(self)
  1582. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1583. pos=self.ui.menuoptions, separator=True)
  1584. self.properties_tool = Properties(self)
  1585. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1586. pos=self.ui.menuoptions)
  1587. self.pdf_tool = ToolPDF(self)
  1588. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1589. pos=self.ui.menufileimport,
  1590. separator=True)
  1591. self.image_tool = ToolImage(self)
  1592. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1593. pos=self.ui.menufileimport,
  1594. separator=True)
  1595. self.pcb_wizard_tool = PcbWizard(self)
  1596. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1597. pos=self.ui.menufileimport)
  1598. self.log.debug("Tools are installed.")
  1599. def remove_tools(self):
  1600. """
  1601. Will remove all the actions in the Tool menu.
  1602. :return: None
  1603. """
  1604. for act in self.ui.menutool.actions():
  1605. self.ui.menutool.removeAction(act)
  1606. def init_tools(self):
  1607. """
  1608. Initialize the Tool tab in the notebook side of the central widget.
  1609. Remove the actions in the Tools menu.
  1610. Instantiate again the FlatCAM tools (plugins).
  1611. All this is required when changing the layout: standard, compact etc.
  1612. :return: None
  1613. """
  1614. log.debug("init_tools()")
  1615. # delete the data currently in the Tools Tab and the Tab itself
  1616. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1617. if widget is not None:
  1618. widget.deleteLater()
  1619. self.ui.notebook.removeTab(2)
  1620. # rebuild the Tools Tab
  1621. self.ui.tool_tab = QtWidgets.QWidget()
  1622. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1623. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1624. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1625. self.ui.tool_scroll_area = VerticalScrollArea()
  1626. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1627. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1628. # first remove all of them
  1629. self.remove_tools()
  1630. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1631. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1632. '&Command Line\tS')
  1633. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1634. # third install all of them
  1635. try:
  1636. self.install_tools()
  1637. except AttributeError:
  1638. pass
  1639. self.log.debug("Tools are initialized.")
  1640. # def parse_system_fonts(self):
  1641. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1642. # 'params': []})
  1643. def connect_toolbar_signals(self):
  1644. """
  1645. Reconnect the signals to the actions in the toolbar.
  1646. This has to be done each time after the FlatCAM tools are removed/installed.
  1647. :return: None
  1648. """
  1649. # Toolbar
  1650. # File Toolbar Signals
  1651. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1652. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1653. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1654. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1655. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1656. # View Toolbar Signals
  1657. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1658. self.ui.replot_btn.triggered.connect(self.plot_all)
  1659. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1660. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1661. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1662. # Edit Toolbar Signals
  1663. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1664. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1665. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1666. self.ui.delete_btn.triggered.connect(self.on_delete)
  1667. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1668. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1669. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1670. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1671. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1672. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1673. # Scripting Toolbar Signals
  1674. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1675. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1676. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1677. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1678. # Tools Toolbar Signals
  1679. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1680. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1681. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1682. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1683. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1684. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1685. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1686. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1687. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1688. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1689. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1690. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1691. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1692. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1693. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1694. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1695. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1696. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1697. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1698. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1699. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1700. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1701. def object2editor(self):
  1702. """
  1703. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1704. :return: None
  1705. """
  1706. self.defaults.report_usage("object2editor()")
  1707. # disable the objects menu as it may interfere with the AppEditors
  1708. self.ui.menuobjects.setDisabled(True)
  1709. edited_object = self.collection.get_active()
  1710. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1711. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1712. pass
  1713. else:
  1714. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1715. return
  1716. if isinstance(edited_object, GeometryObject):
  1717. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1718. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1719. # we set the notebook to hidden
  1720. # self.ui.splitter.setSizes([0, 1])
  1721. if edited_object.multigeo is True:
  1722. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1723. if len(sel_rows) > 1:
  1724. self.inform.emit('[WARNING_NOTCL] %s' %
  1725. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1726. "is not possible.\n"
  1727. "Edit only one geometry at a time."))
  1728. # determine the tool dia of the selected tool
  1729. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1730. # now find the key in the edited_object.tools that has this tooldia
  1731. multi_tool = 1
  1732. for tool in edited_object.tools:
  1733. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1734. multi_tool = tool
  1735. break
  1736. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1737. else:
  1738. self.geo_editor.edit_fcgeometry(edited_object)
  1739. # set call source to the Editor we go into
  1740. self.call_source = 'geo_editor'
  1741. elif isinstance(edited_object, ExcellonObject):
  1742. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1743. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1744. if self.ui.splitter.sizes()[0] == 0:
  1745. self.ui.splitter.setSizes([1, 1])
  1746. self.exc_editor.edit_fcexcellon(edited_object)
  1747. # set call source to the Editor we go into
  1748. self.call_source = 'exc_editor'
  1749. elif isinstance(edited_object, GerberObject):
  1750. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1751. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1752. if self.ui.splitter.sizes()[0] == 0:
  1753. self.ui.splitter.setSizes([1, 1])
  1754. self.grb_editor.edit_fcgerber(edited_object)
  1755. # set call source to the Editor we go into
  1756. self.call_source = 'grb_editor'
  1757. # reset the following variables so the UI is built again after edit
  1758. edited_object.ui_build = False
  1759. edited_object.build_aperture_storage = False
  1760. elif isinstance(edited_object, CNCJobObject):
  1761. if self.ui.splitter.sizes()[0] == 0:
  1762. self.ui.splitter.setSizes([1, 1])
  1763. edited_object.on_edit_code_click()
  1764. return
  1765. # make sure that we can't select another object while in Editor Mode:
  1766. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1767. self.ui.project_frame.setDisabled(True)
  1768. # delete any selection shape that might be active as they are not relevant in Editor
  1769. self.delete_selection_shape()
  1770. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1771. self.ui.plot_tab_area.protectTab(0)
  1772. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1773. self.should_we_save = True
  1774. def editor2object(self, cleanup=None):
  1775. """
  1776. Transfers the Geometry or Excellon from it's editor to the current object.
  1777. :return: None
  1778. """
  1779. self.defaults.report_usage("editor2object()")
  1780. # re-enable the objects menu that was disabled on entry in Editor mode
  1781. self.ui.menuobjects.setDisabled(False)
  1782. # do not update a geometry or excellon object unless it comes out of an editor
  1783. if self.call_source != 'app':
  1784. edited_obj = self.collection.get_active()
  1785. if cleanup is None:
  1786. msgbox = QtWidgets.QMessageBox()
  1787. msgbox.setText(_("Do you want to save the edited object?"))
  1788. msgbox.setWindowTitle(_("Close Editor"))
  1789. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1790. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1791. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1792. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1793. msgbox.setDefaultButton(bt_yes)
  1794. msgbox.exec_()
  1795. response = msgbox.clickedButton()
  1796. if response == bt_yes:
  1797. # clean the Tools Tab
  1798. self.ui.tool_scroll_area.takeWidget()
  1799. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1800. self.ui.notebook.setTabText(2, "Tool")
  1801. if isinstance(edited_obj, GeometryObject):
  1802. obj_type = "Geometry"
  1803. if cleanup is None:
  1804. self.geo_editor.update_fcgeometry(edited_obj)
  1805. # self.geo_editor.update_options(edited_obj)
  1806. self.geo_editor.deactivate()
  1807. # restore GUI to the Selected TAB
  1808. # Remove anything else in the AppGUI
  1809. self.ui.tool_scroll_area.takeWidget()
  1810. # update the geo object options so it is including the bounding box values
  1811. try:
  1812. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1813. edited_obj.options['xmin'] = xmin
  1814. edited_obj.options['ymin'] = ymin
  1815. edited_obj.options['xmax'] = xmax
  1816. edited_obj.options['ymax'] = ymax
  1817. except AttributeError as e:
  1818. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1819. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1820. edited_obj.build_ui()
  1821. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1822. elif isinstance(edited_obj, GerberObject):
  1823. obj_type = "Gerber"
  1824. if cleanup is None:
  1825. self.grb_editor.update_fcgerber()
  1826. self.grb_editor.update_options(edited_obj)
  1827. self.grb_editor.deactivate_grb_editor()
  1828. # delete the old object (the source object) if it was an empty one
  1829. try:
  1830. if len(edited_obj.solid_geometry) == 0:
  1831. old_name = edited_obj.options['name']
  1832. self.collection.set_active(old_name)
  1833. self.collection.delete_active()
  1834. except TypeError:
  1835. # if the solid_geometry is a single Polygon the len() will not work
  1836. # in any case, falling here means that we have something in the solid_geometry, even if only
  1837. # a single Polygon, therefore we pass this
  1838. pass
  1839. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1840. # restore GUI to the Selected TAB
  1841. # Remove anything else in the AppGUI
  1842. self.ui.selected_scroll_area.takeWidget()
  1843. elif isinstance(edited_obj, ExcellonObject):
  1844. obj_type = "Excellon"
  1845. if cleanup is None:
  1846. self.exc_editor.update_fcexcellon(edited_obj)
  1847. # self.exc_editor.update_options(edited_obj)
  1848. self.exc_editor.deactivate()
  1849. # restore GUI to the Selected TAB
  1850. # Remove anything else in the AppGUI
  1851. self.ui.tool_scroll_area.takeWidget()
  1852. # delete the old object (the source object) if it was an empty one
  1853. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1854. old_name = edited_obj.options['name']
  1855. self.collection.delete_by_name(name=old_name)
  1856. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1857. else:
  1858. self.inform.emit('[WARNING_NOTCL] %s' %
  1859. _("Select a Gerber, Geometry or Excellon Object to update."))
  1860. return
  1861. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1862. elif response == bt_no:
  1863. # clean the Tools Tab
  1864. self.ui.tool_scroll_area.takeWidget()
  1865. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1866. self.ui.notebook.setTabText(2, "Tool")
  1867. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1868. if isinstance(edited_obj, GeometryObject):
  1869. self.geo_editor.deactivate()
  1870. edited_obj.build_ui()
  1871. elif isinstance(edited_obj, GerberObject):
  1872. self.grb_editor.deactivate_grb_editor()
  1873. edited_obj.build_ui()
  1874. elif isinstance(edited_obj, ExcellonObject):
  1875. self.exc_editor.deactivate()
  1876. edited_obj.build_ui()
  1877. else:
  1878. self.inform.emit('[WARNING_NOTCL] %s' %
  1879. _("Select a Gerber, Geometry or Excellon Object to update."))
  1880. return
  1881. elif response == bt_cancel:
  1882. return
  1883. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1884. # edited_obj.build_ui()
  1885. # Switch notebook to Selected page
  1886. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1887. else:
  1888. if isinstance(edited_obj, GeometryObject):
  1889. self.geo_editor.deactivate()
  1890. elif isinstance(edited_obj, GerberObject):
  1891. self.grb_editor.deactivate_grb_editor()
  1892. elif isinstance(edited_obj, ExcellonObject):
  1893. self.exc_editor.deactivate()
  1894. else:
  1895. self.inform.emit('[WARNING_NOTCL] %s' %
  1896. _("Select a Gerber, Geometry or Excellon Object to update."))
  1897. return
  1898. # if notebook is hidden we show it
  1899. if self.ui.splitter.sizes()[0] == 0:
  1900. self.ui.splitter.setSizes([1, 1])
  1901. # restore the call_source to app
  1902. self.call_source = 'app'
  1903. edited_obj.plot()
  1904. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1905. self.ui.plot_tab_area.protectTab(0)
  1906. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1907. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1908. self.ui.project_frame.setDisabled(False)
  1909. def get_last_folder(self):
  1910. """
  1911. Get the folder path from where the last file was opened.
  1912. :return: String, last opened folder path
  1913. """
  1914. return self.defaults["global_last_folder"]
  1915. def get_last_save_folder(self):
  1916. """
  1917. Get the folder path from where the last file was saved.
  1918. :return: String, last saved folder path
  1919. """
  1920. loc = self.defaults["global_last_save_folder"]
  1921. if loc is None:
  1922. loc = self.defaults["global_last_folder"]
  1923. if loc is None:
  1924. loc = os.path.dirname(__file__)
  1925. return loc
  1926. def info(self, msg):
  1927. """
  1928. Informs the user. Normally on the status bar, optionally
  1929. also on the shell.
  1930. :param msg: Text to write.
  1931. :return: None
  1932. """
  1933. # Type of message in brackets at the beginning of the message.
  1934. match = re.search(r"\[(.*)\](.*)", msg)
  1935. if match:
  1936. level = match.group(1)
  1937. msg_ = match.group(2)
  1938. self.ui.fcinfo.set_status(str(msg_), level=level)
  1939. if level.lower() == "error":
  1940. self.shell_message(msg, error=True, show=True)
  1941. elif level.lower() == "warning":
  1942. self.shell_message(msg, warning=True, show=True)
  1943. elif level.lower() == "error_notcl":
  1944. self.shell_message(msg, error=True, show=False)
  1945. elif level.lower() == "warning_notcl":
  1946. self.shell_message(msg, warning=True, show=False)
  1947. elif level.lower() == "success":
  1948. self.shell_message(msg, success=True, show=False)
  1949. elif level.lower() == "selected":
  1950. self.shell_message(msg, selected=True, show=False)
  1951. else:
  1952. self.shell_message(msg, show=False)
  1953. else:
  1954. self.ui.fcinfo.set_status(str(msg), level="info")
  1955. # make sure that if the message is to clear the infobar with a space
  1956. # is not printed over and over on the shell
  1957. if msg != '':
  1958. self.shell_message(msg)
  1959. def on_import_preferences(self):
  1960. """
  1961. Loads the application default settings from a saved file into
  1962. ``self.defaults`` dictionary.
  1963. :return: None
  1964. """
  1965. self.defaults.report_usage("on_import_preferences")
  1966. App.log.debug("App.on_import_preferences()")
  1967. # Show file chooser
  1968. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1969. try:
  1970. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1971. directory=self.data_path,
  1972. filter=filter_)
  1973. except TypeError:
  1974. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1975. filter=filter_)
  1976. filename = str(filename)
  1977. if filename == "":
  1978. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1979. return
  1980. # Load in the defaults from the chosen file
  1981. self.defaults.load(filename=filename)
  1982. self.preferencesUiManager.on_preferences_edited()
  1983. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1984. def on_export_preferences(self):
  1985. """
  1986. Save the defaults dictionary to a file.
  1987. :return: None
  1988. """
  1989. self.defaults.report_usage("on_export_preferences")
  1990. App.log.debug("on_export_preferences()")
  1991. # defaults_file_content = None
  1992. # Show file chooser
  1993. date = str(datetime.today()).rpartition('.')[0]
  1994. date = ''.join(c for c in date if c not in ':-')
  1995. date = date.replace(' ', '_')
  1996. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  1997. try:
  1998. filename, _f = FCFileSaveDialog.get_saved_filename(
  1999. caption=_("Export FlatCAM Preferences"),
  2000. directory=self.data_path + '/preferences_' + date,
  2001. filter=filter__
  2002. )
  2003. except TypeError:
  2004. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2005. filename = str(filename)
  2006. if filename == "":
  2007. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2008. return
  2009. # Update options
  2010. self.preferencesUiManager.defaults_read_form()
  2011. self.defaults.propagate_defaults()
  2012. # Save update options
  2013. try:
  2014. self.defaults.write(filename=filename)
  2015. except Exception:
  2016. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2017. return
  2018. if self.defaults["global_open_style"] is False:
  2019. self.file_opened.emit("preferences", filename)
  2020. self.file_saved.emit("preferences", filename)
  2021. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2022. def save_to_file(self, content_to_save, txt_content):
  2023. """
  2024. Save something to a file.
  2025. :return: None
  2026. """
  2027. self.defaults.report_usage("save_to_file")
  2028. App.log.debug("save_to_file()")
  2029. self.date = str(datetime.today()).rpartition('.')[0]
  2030. self.date = ''.join(c for c in self.date if c not in ':-')
  2031. self.date = self.date.replace(' ', '_')
  2032. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2033. path_to_save = self.defaults["global_last_save_folder"] if \
  2034. self.defaults["global_last_save_folder"] is not None else self.data_path
  2035. try:
  2036. filename, _f = FCFileSaveDialog.get_saved_filename(
  2037. caption=_("Save to file"),
  2038. directory=path_to_save + '/file_' + self.date,
  2039. filter=filter__
  2040. )
  2041. except TypeError:
  2042. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2043. filename = str(filename)
  2044. if filename == "":
  2045. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2046. return
  2047. else:
  2048. try:
  2049. with open(filename, 'w') as f:
  2050. ___ = f.read()
  2051. except PermissionError:
  2052. self.inform.emit('[WARNING] %s' %
  2053. _("Permission denied, saving not possible.\n"
  2054. "Most likely another app is holding the file open and not accessible."))
  2055. return
  2056. except IOError:
  2057. App.log.debug('Creating a new file ...')
  2058. f = open(filename, 'w')
  2059. f.close()
  2060. except Exception:
  2061. e = sys.exc_info()[0]
  2062. App.log.error("Could not load the file.")
  2063. App.log.error(str(e))
  2064. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2065. return
  2066. # Save content
  2067. if filename.rpartition('.')[2].lower() == 'html':
  2068. file_content = content_to_save
  2069. else:
  2070. file_content = txt_content
  2071. try:
  2072. with open(filename, "w") as f:
  2073. f.write(file_content)
  2074. except Exception:
  2075. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2076. return
  2077. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2078. def save_geometry(self, x, y, width, height, notebook_width):
  2079. """
  2080. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2081. launch of the application.
  2082. :param x: X position of the main window
  2083. :param y: Y position of the main window
  2084. :param width: width of the main window
  2085. :param height: height of the main window
  2086. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2087. :return: None
  2088. """
  2089. self.defaults["global_def_win_x"] = x
  2090. self.defaults["global_def_win_y"] = y
  2091. self.defaults["global_def_win_w"] = width
  2092. self.defaults["global_def_win_h"] = height
  2093. self.defaults["global_def_notebook_width"] = notebook_width
  2094. self.preferencesUiManager.save_defaults()
  2095. def register_recent(self, kind, filename):
  2096. """
  2097. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2098. dictionary.
  2099. :param kind: type of file that was opened
  2100. :param filename: the path and file name for the file that was opened
  2101. :return:
  2102. """
  2103. self.log.debug("register_recent()")
  2104. self.log.debug(" %s" % kind)
  2105. self.log.debug(" %s" % filename)
  2106. record = {'kind': str(kind), 'filename': str(filename)}
  2107. if record in self.recent:
  2108. return
  2109. if record in self.recent_projects:
  2110. return
  2111. if record['kind'] == 'project':
  2112. self.recent_projects.insert(0, record)
  2113. else:
  2114. self.recent.insert(0, record)
  2115. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2116. self.recent.pop()
  2117. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2118. self.recent_projects.pop()
  2119. try:
  2120. f = open(self.data_path + '/recent.json', 'w')
  2121. except IOError:
  2122. App.log.error("Failed to open recent items file for writing.")
  2123. self.inform.emit('[ERROR_NOTCL] %s' %
  2124. _('Failed to open recent files file for writing.'))
  2125. return
  2126. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2127. f.close()
  2128. try:
  2129. fp = open(self.data_path + '/recent_projects.json', 'w')
  2130. except IOError:
  2131. App.log.error("Failed to open recent items file for writing.")
  2132. self.inform.emit('[ERROR_NOTCL] %s' %
  2133. _('Failed to open recent projects file for writing.'))
  2134. return
  2135. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2136. fp.close()
  2137. # Re-build the recent items menu
  2138. self.setup_recent_items()
  2139. def on_about(self):
  2140. """
  2141. Displays the "about" dialog found in the Menu --> Help.
  2142. :return: None
  2143. """
  2144. self.defaults.report_usage("on_about")
  2145. version = self.version
  2146. version_date = self.version_date
  2147. beta = self.beta
  2148. class AboutDialog(QtWidgets.QDialog):
  2149. def __init__(self, app, parent=None):
  2150. QtWidgets.QDialog.__init__(self, parent)
  2151. self.app = app
  2152. # Icon and title
  2153. self.setWindowIcon(parent.app_icon)
  2154. self.setWindowTitle(_("About FlatCAM"))
  2155. self.resize(600, 200)
  2156. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2157. # self.setStyleSheet(
  2158. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2159. # "background-attachment: fixed"
  2160. # )
  2161. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2162. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2163. # palette = QtGui.QPalette()
  2164. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2165. # self.setPalette(palette)
  2166. logo = QtWidgets.QLabel()
  2167. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2168. title = QtWidgets.QLabel(
  2169. "<font size=8><B>FlatCAM</B></font><BR>"
  2170. "{title}<BR>"
  2171. "<BR>"
  2172. "<BR>"
  2173. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2174. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2175. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2176. "<B>{issue}</B></a><BR>".format(
  2177. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2178. devel=_("Development"),
  2179. down=_("DOWNLOAD"),
  2180. issue=_("Issue tracker"))
  2181. )
  2182. title.setOpenExternalLinks(True)
  2183. closebtn = QtWidgets.QPushButton(_("Close"))
  2184. tab_widget = QtWidgets.QTabWidget()
  2185. description_label = QtWidgets.QLabel(
  2186. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2187. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2188. version=version,
  2189. beta=('BETA' if beta else ''),
  2190. date=version_date,
  2191. arch=platform.architecture()[0])
  2192. )
  2193. description_label.setOpenExternalLinks(True)
  2194. lic_lbl_header = QtWidgets.QLabel(
  2195. '%s:<br>%s<br>' % (
  2196. _('Licensed under the MIT license'),
  2197. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2198. "http://www.opensource.org/licenses/mit-license.php</a>"
  2199. )
  2200. )
  2201. lic_lbl_header.setOpenExternalLinks(True)
  2202. lic_lbl_body = QtWidgets.QLabel(
  2203. _(
  2204. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2205. 'of this software and associated documentation files (the "Software"), to deal\n'
  2206. 'in the Software without restriction, including without limitation the rights\n'
  2207. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2208. 'copies of the Software, and to permit persons to whom the Software is\n'
  2209. 'furnished to do so, subject to the following conditions:\n\n'
  2210. 'The above copyright notice and this permission notice shall be included in\n'
  2211. 'all copies or substantial portions of the Software.\n\n'
  2212. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2213. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2214. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2215. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2216. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2217. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2218. 'THE SOFTWARE.'
  2219. )
  2220. )
  2221. attributions_label = QtWidgets.QLabel(
  2222. _(
  2223. 'Some of the icons used are from the following sources:<br>'
  2224. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2225. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2226. 'title="Flaticon">www.flaticon.com</a></div>'
  2227. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2228. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2229. )
  2230. )
  2231. attributions_label.setOpenExternalLinks(True)
  2232. # layouts
  2233. layout1 = QtWidgets.QVBoxLayout()
  2234. layout1_1 = QtWidgets.QHBoxLayout()
  2235. layout1_2 = QtWidgets.QHBoxLayout()
  2236. layout2 = QtWidgets.QHBoxLayout()
  2237. layout3 = QtWidgets.QHBoxLayout()
  2238. self.setLayout(layout1)
  2239. layout1.addLayout(layout1_1)
  2240. layout1.addLayout(layout1_2)
  2241. layout1.addLayout(layout2)
  2242. layout1.addLayout(layout3)
  2243. layout1_1.addStretch()
  2244. layout1_1.addWidget(description_label)
  2245. layout1_2.addWidget(tab_widget)
  2246. self.splash_tab = QtWidgets.QWidget()
  2247. self.splash_tab.setObjectName("splash_about")
  2248. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2249. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2250. tab_widget.addTab(self.splash_tab, _("Splash"))
  2251. self.programmmers_tab = QtWidgets.QWidget()
  2252. self.programmmers_tab.setObjectName("programmers_about")
  2253. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2254. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2255. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2256. self.translators_tab = QtWidgets.QWidget()
  2257. self.translators_tab.setObjectName("translators_about")
  2258. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2259. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2260. tab_widget.addTab(self.translators_tab, _("Translators"))
  2261. self.license_tab = QtWidgets.QWidget()
  2262. self.license_tab.setObjectName("license_about")
  2263. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2264. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2265. tab_widget.addTab(self.license_tab, _("License"))
  2266. self.attributions_tab = QtWidgets.QWidget()
  2267. self.attributions_tab.setObjectName("attributions_about")
  2268. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2269. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2270. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2271. self.splash_tab_layout.addWidget(logo, stretch=0)
  2272. self.splash_tab_layout.addWidget(title, stretch=1)
  2273. pal = QtGui.QPalette()
  2274. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2275. self.prog_grid_lay = QtWidgets.QGridLayout()
  2276. self.prog_grid_lay.setHorizontalSpacing(20)
  2277. self.prog_grid_lay.setColumnStretch(0, 0)
  2278. self.prog_grid_lay.setColumnStretch(2, 1)
  2279. prog_widget = QtWidgets.QWidget()
  2280. prog_widget.setLayout(self.prog_grid_lay)
  2281. prog_scroll = QtWidgets.QScrollArea()
  2282. prog_scroll.setWidget(prog_widget)
  2283. prog_scroll.setWidgetResizable(True)
  2284. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2285. prog_scroll.setPalette(pal)
  2286. self.programmmers_tab_layout.addWidget(prog_scroll)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2334. self.translator_grid_lay = QtWidgets.QGridLayout()
  2335. self.translator_grid_lay.setColumnStretch(0, 0)
  2336. self.translator_grid_lay.setColumnStretch(1, 0)
  2337. self.translator_grid_lay.setColumnStretch(2, 1)
  2338. self.translator_grid_lay.setColumnStretch(3, 0)
  2339. # trans_widget = QtWidgets.QWidget()
  2340. # trans_widget.setLayout(self.translator_grid_lay)
  2341. # self.translators_tab_layout.addWidget(trans_widget)
  2342. # self.translators_tab_layout.addStretch()
  2343. trans_widget = QtWidgets.QWidget()
  2344. trans_widget.setLayout(self.translator_grid_lay)
  2345. trans_scroll = QtWidgets.QScrollArea()
  2346. trans_scroll.setWidget(trans_widget)
  2347. trans_scroll.setWidgetResizable(True)
  2348. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2349. trans_scroll.setPalette(pal)
  2350. self.translators_tab_layout.addWidget(trans_scroll)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2364. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2365. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2366. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2367. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2368. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2369. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2370. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2384. self.translator_grid_lay.setColumnStretch(0, 0)
  2385. self.translators_tab_layout.addStretch()
  2386. self.license_tab_layout.addWidget(lic_lbl_header)
  2387. self.license_tab_layout.addWidget(lic_lbl_body)
  2388. self.license_tab_layout.addStretch()
  2389. self.attributions_tab_layout.addWidget(attributions_label)
  2390. self.attributions_tab_layout.addStretch()
  2391. layout3.addStretch()
  2392. layout3.addWidget(closebtn)
  2393. closebtn.clicked.connect(self.accept)
  2394. AboutDialog(app=self, parent=self.ui).exec_()
  2395. def install_bookmarks(self, book_dict=None):
  2396. """
  2397. Install the bookmarks actions in the Help menu -> Bookmarks
  2398. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2399. :return: None
  2400. """
  2401. if book_dict is None:
  2402. self.defaults["global_bookmarks"].update(
  2403. {
  2404. '1': ['FlatCAM', "http://flatcam.org"],
  2405. '2': ['Backup Site', ""]
  2406. }
  2407. )
  2408. else:
  2409. self.defaults["global_bookmarks"].clear()
  2410. self.defaults["global_bookmarks"].update(book_dict)
  2411. # first try to disconnect if somehow they get connected from elsewhere
  2412. for act in self.ui.menuhelp_bookmarks.actions():
  2413. try:
  2414. act.triggered.disconnect()
  2415. except TypeError:
  2416. pass
  2417. # clear all actions except the last one who is the Bookmark manager
  2418. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2419. pass
  2420. else:
  2421. self.ui.menuhelp_bookmarks.removeAction(act)
  2422. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2423. if self.defaults["global_bookmarks"]:
  2424. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2425. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2426. # the JSON is first making the keys as strings (therefore I have to use strings too
  2427. # or do the conversion :(
  2428. # )
  2429. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2430. # the '10' entry jsut after '1' therefore ordering as strings
  2431. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2432. key=lambda x: int(x[0]))
  2433. for entry, bookmark in sorted_bookmarks:
  2434. title = bookmark[0]
  2435. weblink = bookmark[1]
  2436. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2437. act.setText(title)
  2438. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2439. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2440. if title == 'Backup Site' and weblink == "":
  2441. act.triggered.connect(self.on_backup_site)
  2442. else:
  2443. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2444. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2445. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2446. def on_bookmarks_manager(self):
  2447. """
  2448. Adds the bookmark manager in a Tab in Plot Area
  2449. :return:
  2450. """
  2451. for idx in range(self.ui.plot_tab_area.count()):
  2452. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2453. # there can be only one instance of Bookmark Manager at one time
  2454. return
  2455. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2456. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2457. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2458. # add the tab if it was closed
  2459. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2460. # delete the absolute and relative position and messages in the infobar
  2461. self.ui.position_label.setText("")
  2462. # self.ui.rel_position_label.setText("")
  2463. # Switch plot_area to preferences page
  2464. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2465. def on_backup_site(self):
  2466. msgbox = QtWidgets.QMessageBox()
  2467. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2468. "1. FlatCAM.org website is down\n"
  2469. "2. Someone forked FlatCAM project and wants to point\n"
  2470. "to his own website\n\n"
  2471. "If you can't get any informations about FlatCAM beta\n"
  2472. "use the YouTube channel link from the Help menu."))
  2473. msgbox.setWindowTitle(_("Alternative website"))
  2474. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2475. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2476. msgbox.setDefaultButton(bt_yes)
  2477. msgbox.exec_()
  2478. # response = msgbox.clickedButton()
  2479. def on_file_savedefaults(self):
  2480. """
  2481. Callback for menu item File->Save Defaults. Saves application default options
  2482. ``self.defaults`` to current_defaults.FlatConfig.
  2483. :return: None
  2484. """
  2485. self.preferencesUiManager.save_defaults()
  2486. def final_save(self):
  2487. """
  2488. Callback for doing a preferences save to file whenever the application is about to quit.
  2489. If the project has changes, it will ask the user to save the project.
  2490. :return: None
  2491. """
  2492. if self.save_in_progress:
  2493. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2494. return
  2495. if self.should_we_save and self.collection.get_list():
  2496. msgbox = QtWidgets.QMessageBox()
  2497. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2498. "\n"
  2499. "Do you want to Save the project?"))
  2500. msgbox.setWindowTitle(_("Save changes"))
  2501. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2502. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2503. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2504. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2505. msgbox.setDefaultButton(bt_yes)
  2506. msgbox.exec_()
  2507. response = msgbox.clickedButton()
  2508. if response == bt_yes:
  2509. try:
  2510. self.trayIcon.hide()
  2511. except Exception:
  2512. pass
  2513. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2514. elif response == bt_no:
  2515. try:
  2516. self.trayIcon.hide()
  2517. except Exception:
  2518. pass
  2519. self.quit_application()
  2520. elif response == bt_cancel:
  2521. return
  2522. else:
  2523. try:
  2524. self.trayIcon.hide()
  2525. except Exception:
  2526. pass
  2527. self.quit_application()
  2528. def quit_application(self):
  2529. """
  2530. Called (as a pyslot or not) when the application is quit.
  2531. :return: None
  2532. """
  2533. self.preferencesUiManager.save_defaults(silent=True)
  2534. log.debug("App.quit_application() --> App Defaults saved.")
  2535. if self.cmd_line_headless != 1:
  2536. # save app state to file
  2537. stgs = QSettings("Open Source", "FlatCAM")
  2538. stgs.setValue('saved_gui_state', self.ui.saveState())
  2539. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2540. stgs.setValue(
  2541. 'language',
  2542. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2543. )
  2544. stgs.setValue(
  2545. 'notebook_font_size',
  2546. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2547. )
  2548. stgs.setValue(
  2549. 'axis_font_size',
  2550. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2551. )
  2552. stgs.setValue(
  2553. 'textbox_font_size',
  2554. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2555. )
  2556. stgs.setValue(
  2557. 'hud_font_size',
  2558. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2559. )
  2560. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2561. stgs.setValue(
  2562. 'machinist',
  2563. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2564. )
  2565. # This will write the setting to the platform specific storage.
  2566. del stgs
  2567. log.debug("App.quit_application() --> App UI state saved.")
  2568. # try to quit the Socket opened by ArgsThread class
  2569. try:
  2570. self.new_launch.stop.emit()
  2571. except Exception as err:
  2572. log.debug("App.quit_application() --> %s" % str(err))
  2573. # try to quit the QThread that run ArgsThread class
  2574. try:
  2575. self.th.quit()
  2576. except Exception as e:
  2577. log.debug("App.quit_application() --> %s" % str(e))
  2578. # terminate workers
  2579. self.workers.__del__()
  2580. # quit app by signalling for self.kill_app() method
  2581. # self.close_app_signal.emit()
  2582. QtWidgets.qApp.quit()
  2583. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2584. # we use the following command
  2585. minor_v = sys.version_info.minor
  2586. if minor_v < 8:
  2587. sys.exit(0)
  2588. else:
  2589. os._exit(0) # fix to work with Python 3.8
  2590. @staticmethod
  2591. def kill_app():
  2592. QtWidgets.qApp.quit()
  2593. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2594. # we use the following command
  2595. sys.exit(0)
  2596. def on_portable_checked(self, state):
  2597. """
  2598. Callback called when the checkbox in Preferences GUI is checked.
  2599. It will set the application as portable by creating the preferences and recent files in the
  2600. 'config' folder found in the FlatCAM installation folder.
  2601. :param state: boolean, the state of the checkbox when clicked/checked
  2602. :return:
  2603. """
  2604. line_no = 0
  2605. data = None
  2606. if sys.platform != 'win32':
  2607. # this won't work in Linux or MacOS
  2608. return
  2609. # test if the app was frozen and choose the path for the configuration file
  2610. if getattr(sys, "frozen", False) is True:
  2611. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2612. else:
  2613. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2614. config_file = current_data_path + '\\configuration.txt'
  2615. try:
  2616. with open(config_file, 'r') as f:
  2617. try:
  2618. data = f.readlines()
  2619. except Exception as e:
  2620. log.debug('App.__init__() -->%s' % str(e))
  2621. return
  2622. except FileNotFoundError:
  2623. pass
  2624. for line in data:
  2625. line = line.strip('\n')
  2626. param = str(line).rpartition('=')
  2627. if param[0] == 'portable':
  2628. break
  2629. line_no += 1
  2630. if state:
  2631. data[line_no] = 'portable=True\n'
  2632. # create the new defauults files
  2633. # create current_defaults.FlatConfig file if there is none
  2634. try:
  2635. f = open(current_data_path + '/current_defaults.FlatConfig')
  2636. f.close()
  2637. except IOError:
  2638. App.log.debug('Creating empty current_defaults.FlatConfig')
  2639. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2640. json.dump({}, f)
  2641. f.close()
  2642. # create factory_defaults.FlatConfig file if there is none
  2643. try:
  2644. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2645. f.close()
  2646. except IOError:
  2647. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2648. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2649. json.dump({}, f)
  2650. f.close()
  2651. try:
  2652. f = open(current_data_path + '/recent.json')
  2653. f.close()
  2654. except IOError:
  2655. App.log.debug('Creating empty recent.json')
  2656. f = open(current_data_path + '/recent.json', 'w')
  2657. json.dump([], f)
  2658. f.close()
  2659. try:
  2660. fp = open(current_data_path + '/recent_projects.json')
  2661. fp.close()
  2662. except IOError:
  2663. App.log.debug('Creating empty recent_projects.json')
  2664. fp = open(current_data_path + '/recent_projects.json', 'w')
  2665. json.dump([], fp)
  2666. fp.close()
  2667. # save the current defaults to the new defaults file
  2668. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2669. else:
  2670. data[line_no] = 'portable=False\n'
  2671. with open(config_file, 'w') as f:
  2672. f.writelines(data)
  2673. def on_register_files(self, obj_type=None):
  2674. """
  2675. Called whenever there is a need to register file extensions with FlatCAM.
  2676. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2677. :param obj_type: the type of object to be register for.
  2678. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2679. :return: None
  2680. """
  2681. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2682. new_reg_path = 'Software\\Classes\\'
  2683. # find if the current user is admin
  2684. try:
  2685. is_admin = os.getuid() == 0
  2686. except AttributeError:
  2687. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2688. if is_admin is True:
  2689. root_path = winreg.HKEY_LOCAL_MACHINE
  2690. else:
  2691. root_path = winreg.HKEY_CURRENT_USER
  2692. # create the keys
  2693. def set_reg(name, root_pth, new_reg_path, value):
  2694. try:
  2695. winreg.CreateKey(root_pth, new_reg_path)
  2696. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2697. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2698. return True
  2699. except WindowsError:
  2700. return False
  2701. # delete key in registry
  2702. def delete_reg(root_pth, reg_path, key_to_del):
  2703. key_to_del_path = reg_path + key_to_del
  2704. try:
  2705. winreg.DeleteKey(root_pth, key_to_del_path)
  2706. return True
  2707. except WindowsError:
  2708. return False
  2709. if obj_type is None or obj_type == 'excellon':
  2710. exc_list = \
  2711. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2712. exc_list = [x for x in exc_list if x != '']
  2713. # register all keys in the Preferences window
  2714. for ext in exc_list:
  2715. new_k = new_reg_path + '.%s' % ext
  2716. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2717. # and unregister those that are no longer in the Preferences windows but are in the file
  2718. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2719. if ext not in exc_list:
  2720. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2721. # now write the updated extensions to the self.defaults
  2722. # new_ext = ''
  2723. # for ext in exc_list:
  2724. # new_ext = new_ext + ext + ', '
  2725. # self.defaults["fa_excellon"] = new_ext
  2726. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2727. if obj_type is None or obj_type == 'gcode':
  2728. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2729. gco_list = [x for x in gco_list if x != '']
  2730. # register all keys in the Preferences window
  2731. for ext in gco_list:
  2732. new_k = new_reg_path + '.%s' % ext
  2733. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2734. # and unregister those that are no longer in the Preferences windows but are in the file
  2735. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2736. if ext not in gco_list:
  2737. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2738. # now write the updated extensions to the self.defaults
  2739. # new_ext = ''
  2740. # for ext in gco_list:
  2741. # new_ext = new_ext + ext + ', '
  2742. # self.defaults["fa_gcode"] = new_ext
  2743. self.inform.emit('[success] %s' %
  2744. _("Selected GCode file extensions registered with FlatCAM."))
  2745. if obj_type is None or obj_type == 'gerber':
  2746. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2747. grb_list = [x for x in grb_list if x != '']
  2748. # register all keys in the Preferences window
  2749. for ext in grb_list:
  2750. new_k = new_reg_path + '.%s' % ext
  2751. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2752. # and unregister those that are no longer in the Preferences windows but are in the file
  2753. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2754. if ext not in grb_list:
  2755. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2756. # now write the updated extensions to the self.defaults
  2757. # new_ext = ''
  2758. # for ext in grb_list:
  2759. # new_ext = new_ext + ext + ', '
  2760. # self.defaults["fa_gerber"] = new_ext
  2761. self.inform.emit('[success] %s' %
  2762. _("Selected Gerber file extensions registered with FlatCAM."))
  2763. def add_extension(self, ext_type):
  2764. """
  2765. Add a file extension to the list for a specific object
  2766. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2767. :return:
  2768. """
  2769. if ext_type == 'excellon':
  2770. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2771. if new_ext == '':
  2772. return
  2773. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2774. if new_ext in old_val:
  2775. return
  2776. old_val.append(new_ext)
  2777. old_val.sort()
  2778. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2779. if ext_type == 'gcode':
  2780. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2781. if new_ext == '':
  2782. return
  2783. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2784. if new_ext in old_val:
  2785. return
  2786. old_val.append(new_ext)
  2787. old_val.sort()
  2788. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2789. if ext_type == 'gerber':
  2790. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2791. if new_ext == '':
  2792. return
  2793. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2794. if new_ext in old_val:
  2795. return
  2796. old_val.append(new_ext)
  2797. old_val.sort()
  2798. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2799. if ext_type == 'keyword':
  2800. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2801. if new_kw == '':
  2802. return
  2803. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2804. if new_kw in old_val:
  2805. return
  2806. old_val.append(new_kw)
  2807. old_val.sort()
  2808. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2809. # update the self.myKeywords so the model is updated
  2810. self.autocomplete_kw_list = \
  2811. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2812. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2813. self.shell._edit.set_model_data(self.myKeywords)
  2814. def del_extension(self, ext_type):
  2815. """
  2816. Remove a file extension from the list for a specific object
  2817. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2818. :return:
  2819. """
  2820. if ext_type == 'excellon':
  2821. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2822. if new_ext == '':
  2823. return
  2824. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2825. if new_ext not in old_val:
  2826. return
  2827. old_val.remove(new_ext)
  2828. old_val.sort()
  2829. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2830. if ext_type == 'gcode':
  2831. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2832. if new_ext == '':
  2833. return
  2834. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2835. if new_ext not in old_val:
  2836. return
  2837. old_val.remove(new_ext)
  2838. old_val.sort()
  2839. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2840. if ext_type == 'gerber':
  2841. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2842. if new_ext == '':
  2843. return
  2844. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2845. if new_ext not in old_val:
  2846. return
  2847. old_val.remove(new_ext)
  2848. old_val.sort()
  2849. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2850. if ext_type == 'keyword':
  2851. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2852. if new_kw == '':
  2853. return
  2854. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2855. if new_kw not in old_val:
  2856. return
  2857. old_val.remove(new_kw)
  2858. old_val.sort()
  2859. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2860. # update the self.myKeywords so the model is updated
  2861. self.autocomplete_kw_list = \
  2862. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2863. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2864. self.shell._edit.set_model_data(self.myKeywords)
  2865. def restore_extensions(self, ext_type):
  2866. """
  2867. Restore all file extensions associations with FlatCAM, for a specific object
  2868. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2869. :return:
  2870. """
  2871. if ext_type == 'excellon':
  2872. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2873. # for the ability to open Excellon files with .txt extension
  2874. new_exc_list = deepcopy(self.exc_list)
  2875. try:
  2876. new_exc_list.remove('txt')
  2877. except ValueError:
  2878. pass
  2879. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2880. if ext_type == 'gcode':
  2881. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2882. if ext_type == 'gerber':
  2883. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2884. if ext_type == 'keyword':
  2885. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2886. # update the self.myKeywords so the model is updated
  2887. self.autocomplete_kw_list = self.default_keywords
  2888. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2889. self.shell._edit.set_model_data(self.myKeywords)
  2890. def delete_all_extensions(self, ext_type):
  2891. """
  2892. Delete all file extensions associations with FlatCAM, for a specific object
  2893. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2894. :return:
  2895. """
  2896. if ext_type == 'excellon':
  2897. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2898. if ext_type == 'gcode':
  2899. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2900. if ext_type == 'gerber':
  2901. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2902. if ext_type == 'keyword':
  2903. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2904. # update the self.myKeywords so the model is updated
  2905. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2906. self.shell._edit.set_model_data(self.myKeywords)
  2907. def on_edit_join(self, name=None):
  2908. """
  2909. Callback for Edit->Join. Joins the selected geometry objects into
  2910. a new one.
  2911. :return: None
  2912. """
  2913. self.defaults.report_usage("on_edit_join()")
  2914. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2915. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2916. geo_type_set = set()
  2917. objs = self.collection.get_selected()
  2918. if len(objs) < 2:
  2919. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2920. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2921. return 'fail'
  2922. for obj in objs:
  2923. geo_type_set.add(obj.multigeo)
  2924. # if len(geo_type_list) == 1 means that all list elements are the same
  2925. if len(geo_type_set) != 1:
  2926. self.inform.emit('[ERROR] %s' %
  2927. _("Failed join. The Geometry objects are of different types.\n"
  2928. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2929. "convert from one to another and retry joining \n"
  2930. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2931. "the result may not be what was expected. \n"
  2932. "Check the generated GCODE."))
  2933. return
  2934. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2935. if True in geo_type_set:
  2936. def initialize(geo_obj, app):
  2937. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2938. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2939. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2940. for v in geo_obj.tools.values():
  2941. v['data']['name'] = obj_name_multi
  2942. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2943. else:
  2944. def initialize(geo_obj, app):
  2945. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2946. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2947. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2948. for v in geo_obj.tools.values():
  2949. v['data']['name'] = obj_name_single
  2950. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2951. self.should_we_save = True
  2952. def on_edit_join_exc(self):
  2953. """
  2954. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  2955. a new Excellon.
  2956. :return: None
  2957. """
  2958. self.defaults.report_usage("on_edit_join_exc()")
  2959. objs = self.collection.get_selected()
  2960. for obj in objs:
  2961. if not isinstance(obj, ExcellonObject):
  2962. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  2963. return
  2964. if len(objs) < 2:
  2965. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2966. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2967. return 'fail'
  2968. def initialize(exc_obj, app):
  2969. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  2970. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  2971. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  2972. self.should_we_save = True
  2973. def on_edit_join_grb(self):
  2974. """
  2975. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2976. a new Gerber object.
  2977. :return: None
  2978. """
  2979. self.defaults.report_usage("on_edit_join_grb()")
  2980. objs = self.collection.get_selected()
  2981. for obj in objs:
  2982. if not isinstance(obj, GerberObject):
  2983. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber 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(grb_obj, app):
  2990. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  2991. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  2992. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  2993. self.should_we_save = True
  2994. def on_convert_singlegeo_to_multigeo(self):
  2995. """
  2996. Called for converting a Geometry object from single-geo to multi-geo.
  2997. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  2998. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  2999. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3000. the solid-geometry of that tool.
  3001. :return: None
  3002. """
  3003. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3004. obj = self.collection.get_active()
  3005. if obj is None:
  3006. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3007. return
  3008. if not isinstance(obj, GeometryObject):
  3009. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3010. return
  3011. obj.multigeo = True
  3012. for tooluid, dict_value in obj.tools.items():
  3013. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3014. if not isinstance(obj.solid_geometry, list):
  3015. obj.solid_geometry = [obj.solid_geometry]
  3016. # obj.solid_geometry[:] = []
  3017. obj.plot()
  3018. self.should_we_save = True
  3019. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3020. def on_convert_multigeo_to_singlegeo(self):
  3021. """
  3022. Called for converting a Geometry object from multi-geo to single-geo.
  3023. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3024. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3025. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3026. the solid-geometry of that tool.
  3027. :return: None
  3028. """
  3029. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3030. obj = self.collection.get_active()
  3031. if obj is None:
  3032. self.inform.emit('[ERROR_NOTCL] %s' %
  3033. _("Failed. Select a Geometry Object and try again."))
  3034. return
  3035. if not isinstance(obj, GeometryObject):
  3036. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3037. (_("Expected a GeometryObject, got"), type(obj)))
  3038. return
  3039. obj.multigeo = False
  3040. total_solid_geometry = []
  3041. for tooluid, dict_value in obj.tools.items():
  3042. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3043. # clear the original geometry
  3044. dict_value['solid_geometry'][:] = []
  3045. obj.solid_geometry = deepcopy(total_solid_geometry)
  3046. obj.plot()
  3047. self.should_we_save = True
  3048. self.inform.emit('[success] %s' %
  3049. _("A Geometry object was converted to SingleGeo type."))
  3050. def on_defaults_dict_change(self, field):
  3051. """
  3052. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3053. Edit -> Preferences tab window.
  3054. :param field: the key of the self.defaults dictionary that was changed.
  3055. :return: None
  3056. """
  3057. self.preferencesUiManager.defaults_write_form_field(field=field)
  3058. if field == "units":
  3059. self.set_screen_units(self.defaults['units'])
  3060. def set_screen_units(self, units):
  3061. """
  3062. Set the FlatCAM units on the status bar.
  3063. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3064. :return: None
  3065. """
  3066. self.ui.units_label.setText("[" + units.lower() + "]")
  3067. def on_toggle_units_click(self):
  3068. try:
  3069. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3070. except (TypeError, AttributeError):
  3071. pass
  3072. if self.defaults["units"] == 'MM':
  3073. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3074. else:
  3075. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3076. self.on_toggle_units(no_pref=True)
  3077. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3078. lambda: self.on_toggle_units(no_pref=False))
  3079. def on_toggle_units(self, no_pref=False):
  3080. """
  3081. Callback for the Units radio-button change in the Preferences tab.
  3082. Changes the application's default units adn for the project too.
  3083. If changing the project's units, the change propagates to all of
  3084. the objects in the project.
  3085. :return: None
  3086. """
  3087. self.defaults.report_usage("on_toggle_units")
  3088. if self.toggle_units_ignore:
  3089. return
  3090. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3091. # If option is the same, then ignore
  3092. if new_units == self.defaults["units"].upper():
  3093. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3094. return
  3095. # Keys in self.defaults for which to scale their values
  3096. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3097. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3098. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3099. "gerber_editor_ma_high",
  3100. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3101. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3102. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3103. "excellon_feedrate_probe", "excellon_milling_dia",
  3104. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3105. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3106. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3107. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3108. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3109. "geometry_extracut_length", "geometry_z_pdepth",
  3110. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3111. 'cncjob_tooldia',
  3112. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3113. "tools_paintnewdia",
  3114. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3115. "tools_nccnewdia", "tools_ncc_offset_value",
  3116. "tools_2sided_drilldia",
  3117. "tools_film_boundary", "tools_film_scale_stroke",
  3118. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3119. "tools_cutout_depthperpass",
  3120. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3121. "tools_panelize_spacing_rows",
  3122. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3123. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3124. "tools_transform_buffer_dis",
  3125. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3126. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3127. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3128. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3129. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3130. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3131. "tools_cr_h2h_val", "tools_cr_dh_val",
  3132. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3133. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3134. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3135. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3136. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3137. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3138. "tools_copper_thieving_mask_clearance",
  3139. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3140. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3141. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3142. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3143. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3144. "tools_invert_margin",
  3145. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3146. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3147. def scale_defaults(sfactor):
  3148. for dim in dimensions:
  3149. if dim in [
  3150. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3151. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3152. 'tools_transform_mirror_point'
  3153. ]:
  3154. if self.defaults[dim] is None or self.defaults[dim] == '':
  3155. continue
  3156. try:
  3157. coordinates = self.defaults[dim].split(",")
  3158. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3159. coords_xy[0] *= sfactor
  3160. coords_xy[1] *= sfactor
  3161. self.defaults[dim] = "%.*f, %.*f" % (
  3162. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3163. except Exception as e:
  3164. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3165. elif dim in [
  3166. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3167. ]:
  3168. if self.defaults[dim] is None or self.defaults[dim] == '':
  3169. continue
  3170. try:
  3171. self.defaults[dim] = float(self.defaults[dim])
  3172. tools_diameters = [self.defaults[dim]]
  3173. except ValueError:
  3174. try:
  3175. tools_string = self.defaults[dim].split(",")
  3176. tools_diameters = [eval(a) for a in tools_string if a != '']
  3177. except Exception as e:
  3178. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3179. continue
  3180. self.defaults[dim] = ''
  3181. td_len = len(tools_diameters)
  3182. if td_len > 1:
  3183. for t in range(td_len):
  3184. tools_diameters[t] *= sfactor
  3185. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3186. else:
  3187. tools_diameters[0] *= sfactor
  3188. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3189. elif dim in ['global_gridx', 'global_gridy']:
  3190. # format the number of decimals to the one specified in self.decimals
  3191. try:
  3192. val = float(self.defaults[dim]) * sfactor
  3193. except Exception as e:
  3194. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3195. continue
  3196. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3197. else:
  3198. # the number of decimals for the rest is kept unchanged
  3199. if self.defaults[dim]:
  3200. try:
  3201. val = float(self.defaults[dim]) * sfactor
  3202. except Exception as e:
  3203. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3204. continue
  3205. self.defaults[dim] = val
  3206. # The scaling factor depending on choice of units.
  3207. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3208. # Changing project units. Warn user.
  3209. msgbox = QtWidgets.QMessageBox()
  3210. msgbox.setWindowTitle(_("Toggle Units"))
  3211. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3212. msgbox.setText(_("Changing the units of the project\n"
  3213. "will scale all objects.\n\n"
  3214. "Do you want to continue?"))
  3215. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3216. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3217. msgbox.setDefaultButton(bt_ok)
  3218. msgbox.exec_()
  3219. response = msgbox.clickedButton()
  3220. if response == bt_ok:
  3221. if no_pref is False:
  3222. self.preferencesUiManager.defaults_read_form()
  3223. scale_defaults(factor)
  3224. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3225. self.defaults["units"] = new_units
  3226. # update the defaults from form, some may assume that the conversion is enough and it's not
  3227. self.on_options_app2project()
  3228. # update the objects
  3229. for obj in self.collection.get_list():
  3230. obj.convert_units(new_units)
  3231. # make that the properties stored in the object are also updated
  3232. self.app_obj.object_changed.emit(obj)
  3233. # rebuild the object UI
  3234. obj.build_ui()
  3235. # change this only if the workspace is active
  3236. if self.defaults['global_workspace'] is True:
  3237. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3238. # adjust the grid values on the main toolbar
  3239. val_x = float(self.defaults['global_gridx']) * factor
  3240. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3241. current = self.collection.get_active()
  3242. if current is not None:
  3243. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3244. if not isinstance(current, GeometryObject):
  3245. current.to_form()
  3246. # replot all objects
  3247. self.plot_all()
  3248. # set the status labels to reflect the current FlatCAM units
  3249. self.set_screen_units(new_units)
  3250. # signal to the app that we changed the object properties and it should save the project
  3251. self.should_we_save = True
  3252. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3253. else:
  3254. # Undo toggling
  3255. self.toggle_units_ignore = True
  3256. if self.defaults['units'].upper() == 'MM':
  3257. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3258. else:
  3259. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3260. self.toggle_units_ignore = False
  3261. # store the grid values so they are not changed in the next step
  3262. val_x = float(self.defaults['global_gridx'])
  3263. val_y = float(self.defaults['global_gridy'])
  3264. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3265. self.preferencesUiManager.defaults_read_form()
  3266. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3267. # in self.defaults from the GUI elements but
  3268. # I don't want it for the grid values, so I update them here
  3269. self.defaults['global_gridx'] = val_x
  3270. self.defaults['global_gridy'] = val_y
  3271. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3272. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3273. def on_toggle_axis(self):
  3274. self.defaults.report_usage("on_toggle_axis()")
  3275. if self.toggle_axis is False:
  3276. if self.is_legacy is False:
  3277. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3278. parent=self.plotcanvas.view.scene)
  3279. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3280. parent=self.plotcanvas.view.scene)
  3281. else:
  3282. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3283. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3284. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3285. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3286. self.plotcanvas.canvas.draw()
  3287. self.toggle_axis = True
  3288. else:
  3289. if self.is_legacy is False:
  3290. self.plotcanvas.v_line.parent = None
  3291. self.plotcanvas.h_line.parent = None
  3292. else:
  3293. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3294. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3295. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3296. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3297. self.plotcanvas.canvas.draw()
  3298. self.toggle_axis = False
  3299. def on_toggle_hud(self):
  3300. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3301. def on_toggle_grid_lines(self):
  3302. self.defaults.report_usage("on_toggle_grd_lines()")
  3303. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3304. if tt_settings.contains("theme"):
  3305. theme = tt_settings.value('theme', type=str)
  3306. else:
  3307. theme = 'white'
  3308. if self.toggle_grid_lines is False:
  3309. if self.is_legacy is False:
  3310. if theme == 'white':
  3311. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3312. else:
  3313. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3314. else:
  3315. self.plotcanvas.axes.grid(True)
  3316. try:
  3317. self.plotcanvas.canvas.draw()
  3318. except IndexError:
  3319. pass
  3320. pass
  3321. self.toggle_grid_lines = True
  3322. else:
  3323. if self.is_legacy is False:
  3324. if theme == 'white':
  3325. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3326. else:
  3327. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3328. else:
  3329. self.plotcanvas.axes.grid(False)
  3330. try:
  3331. self.plotcanvas.canvas.draw()
  3332. except IndexError:
  3333. pass
  3334. self.toggle_grid_lines = False
  3335. if self.is_legacy is False:
  3336. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3337. # - perhaps is a bug in VisPy implementation
  3338. if self.grid_status():
  3339. self.app_cursor.enabled = False
  3340. self.app_cursor.enabled = True
  3341. else:
  3342. self.app_cursor.enabled = True
  3343. self.app_cursor.enabled = False
  3344. def on_tab_rmb_click(self, checked):
  3345. self.ui.notebook.set_detachable(val=checked)
  3346. self.defaults["global_tabs_detachable"] = checked
  3347. self.ui.plot_tab_area.set_detachable(val=checked)
  3348. self.defaults["global_tabs_detachable"] = checked
  3349. def on_tab_setup_context_menu(self):
  3350. initial_checked = self.defaults["global_tabs_detachable"]
  3351. action_name = str(_("Detachable Tabs"))
  3352. action = QtWidgets.QAction(self)
  3353. action.setCheckable(True)
  3354. action.setText(action_name)
  3355. action.setChecked(initial_checked)
  3356. self.ui.notebook.tabBar.addAction(action)
  3357. self.ui.plot_tab_area.tabBar.addAction(action)
  3358. try:
  3359. action.triggered.disconnect()
  3360. except TypeError:
  3361. pass
  3362. action.triggered.connect(self.on_tab_rmb_click)
  3363. def on_deselect_all(self):
  3364. self.collection.set_all_inactive()
  3365. self.delete_selection_shape()
  3366. def on_workspace_modified(self):
  3367. # self.save_defaults(silent=True)
  3368. self.plotcanvas.delete_workspace()
  3369. self.preferencesUiManager.defaults_read_form()
  3370. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3371. def on_workspace(self):
  3372. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3373. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3374. self.inform.emit(_("Workspace enabled."))
  3375. else:
  3376. self.plotcanvas.delete_workspace()
  3377. self.inform.emit(_("Workspace disabled."))
  3378. self.preferencesUiManager.defaults_read_form()
  3379. # self.save_defaults(silent=True)
  3380. def on_workspace_toggle(self):
  3381. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3382. try:
  3383. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3384. except TypeError:
  3385. pass
  3386. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3387. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3388. self.on_workspace()
  3389. def on_cursor_type(self, val):
  3390. """
  3391. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3392. :return: None
  3393. """
  3394. self.app_cursor.enabled = False
  3395. if val == 'small':
  3396. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3397. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3398. self.app_cursor = self.plotcanvas.new_cursor()
  3399. else:
  3400. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3401. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3402. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3403. if self.ui.grid_snap_btn.isChecked():
  3404. self.app_cursor.enabled = True
  3405. else:
  3406. self.app_cursor.enabled = False
  3407. def on_tool_add_keypress(self):
  3408. # ## Current application units in Upper Case
  3409. self.units = self.defaults['units'].upper()
  3410. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3411. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3412. if notebook_widget_name == 'selected_tab':
  3413. if self.collection.get_active().kind == 'geometry':
  3414. # Tool add works for Geometry only if Advanced is True in Preferences
  3415. if self.defaults["global_app_level"] == 'a':
  3416. tool_add_popup = FCInputDialog(title="New Tool ...",
  3417. text='Enter a Tool Diameter:',
  3418. min=0.0000, max=99.9999, decimals=4)
  3419. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3420. val, ok = tool_add_popup.get_value()
  3421. if ok:
  3422. if float(val) == 0:
  3423. self.inform.emit('[WARNING_NOTCL] %s' %
  3424. _("Please enter a tool diameter with non-zero value, in Float format."))
  3425. return
  3426. self.collection.get_active().on_tool_add(dia=float(val))
  3427. else:
  3428. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3429. else:
  3430. msgbox = QtWidgets.QMessageBox()
  3431. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3432. "Go to Preferences -> General - Show Advanced Options."))
  3433. msgbox.setWindowTitle("Tool adding ...")
  3434. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3435. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3436. msgbox.setDefaultButton(bt_ok)
  3437. msgbox.exec_()
  3438. # work only if the notebook tab on focus is the Tools_Tab
  3439. if notebook_widget_name == 'tool_tab':
  3440. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3441. # and only if the tool is NCC Tool
  3442. if tool_widget == self.ncclear_tool.toolName:
  3443. self.ncclear_tool.on_add_tool_by_key()
  3444. # and only if the tool is Paint Area Tool
  3445. elif tool_widget == self.paint_tool.toolName:
  3446. self.paint_tool.on_add_tool_by_key()
  3447. # and only if the tool is Solder Paste Dispensing Tool
  3448. elif tool_widget == self.paste_tool.toolName:
  3449. self.paste_tool.on_add_tool_by_key()
  3450. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3451. # See description below.
  3452. def on_delete_keypress(self):
  3453. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3454. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3455. if notebook_widget_name == 'selected_tab':
  3456. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3457. self.collection.get_active().on_tool_delete()
  3458. # work only if the notebook tab on focus is the Tools_Tab
  3459. elif notebook_widget_name == 'tool_tab':
  3460. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3461. # and only if the tool is NCC Tool
  3462. if tool_widget == self.ncclear_tool.toolName:
  3463. self.ncclear_tool.on_tool_delete()
  3464. # and only if the tool is Paint Tool
  3465. elif tool_widget == self.paint_tool.toolName:
  3466. self.paint_tool.on_tool_delete()
  3467. # and only if the tool is Solder Paste Dispensing Tool
  3468. elif tool_widget == self.paste_tool.toolName:
  3469. self.paste_tool.on_tool_delete()
  3470. else:
  3471. self.on_delete()
  3472. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3473. # some screens you have to be careful where you hover with your mouse.
  3474. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3475. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3476. # Complicated, I know :)
  3477. def on_delete(self, force_deletion=False):
  3478. """
  3479. Delete the currently selected FlatCAMObjs.
  3480. :param force_deletion: used by Tcl command
  3481. :return: None
  3482. """
  3483. self.defaults.report_usage("on_delete()")
  3484. response = None
  3485. bt_ok = None
  3486. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3487. # a geometry object before we update it.
  3488. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3489. and self.grb_editor.editor_active is False:
  3490. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3491. msgbox = QtWidgets.QMessageBox()
  3492. msgbox.setWindowTitle(_("Delete objects"))
  3493. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3494. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3495. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3496. "the selected objects?"))
  3497. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3498. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3499. msgbox.setDefaultButton(bt_ok)
  3500. msgbox.exec_()
  3501. response = msgbox.clickedButton()
  3502. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3503. response = bt_ok
  3504. if response == bt_ok:
  3505. if self.collection.get_active():
  3506. self.log.debug("App.on_delete()")
  3507. for obj_active in self.collection.get_selected():
  3508. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3509. if obj_active.kind == 'gerber':
  3510. for el in obj_active.mark_shapes:
  3511. obj_active.mark_shapes[el].clear(update=True)
  3512. obj_active.mark_shapes[el].enabled = False
  3513. # obj_active.mark_shapes[el] = None
  3514. del el
  3515. elif isinstance(obj_active, CNCJobObject):
  3516. try:
  3517. obj_active.text_col.enabled = False
  3518. del obj_active.text_col
  3519. obj_active.annotation.clear(update=True)
  3520. del obj_active.annotation
  3521. except AttributeError as e:
  3522. log.debug(
  3523. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3524. )
  3525. while self.collection.get_selected():
  3526. self.delete_first_selected()
  3527. self.inform.emit('%s...' % _("Object(s) deleted"))
  3528. # make sure that the selection shape is deleted, too
  3529. self.delete_selection_shape()
  3530. # if there are no longer objects delete also the exclusion areas shapes
  3531. if not self.collection.get_list():
  3532. self.exc_areas.clear_shapes()
  3533. else:
  3534. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3535. else:
  3536. self.inform.emit(_("Save the work in Editor and try again ..."))
  3537. def delete_first_selected(self):
  3538. # Keep this for later
  3539. try:
  3540. sel_obj = self.collection.get_active()
  3541. name = sel_obj.options["name"]
  3542. isPlotted = sel_obj.options["plot"]
  3543. except AttributeError:
  3544. self.log.debug("Nothing selected for deletion")
  3545. return
  3546. if self.is_legacy is True:
  3547. # Remove plot only if the object was plotted otherwise delaxes will fail
  3548. if isPlotted:
  3549. try:
  3550. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3551. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3552. except Exception as e:
  3553. log.debug("App.delete_first_selected() --> %s" % str(e))
  3554. self.plotcanvas.auto_adjust_axes()
  3555. # Remove from dictionary
  3556. self.collection.delete_active()
  3557. # Clear form
  3558. self.setup_component_editor()
  3559. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3560. def on_set_origin(self):
  3561. """
  3562. Set the origin to the left mouse click position
  3563. :return: None
  3564. """
  3565. # display the message for the user
  3566. # and ask him to click on the desired position
  3567. self.defaults.report_usage("on_set_origin()")
  3568. def origin_replot():
  3569. def worker_task():
  3570. with self.proc_container.new('%s...' % _("Plotting")):
  3571. for obj in self.collection.get_list():
  3572. obj.plot()
  3573. self.plotcanvas.fit_view()
  3574. if self.is_legacy:
  3575. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3576. else:
  3577. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3578. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3579. self.inform.emit(_('Click to set the origin ...'))
  3580. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3581. # first disconnect it as it may have been used by something else
  3582. try:
  3583. self.replot_signal.disconnect()
  3584. except TypeError:
  3585. pass
  3586. self.replot_signal[list].connect(origin_replot)
  3587. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3588. """
  3589. :param event:
  3590. :param location:
  3591. :param noplot:
  3592. :param use_thread:
  3593. :return:
  3594. """
  3595. noplot_sig = noplot
  3596. def worker_task():
  3597. with self.proc_container.new(_("Setting Origin...")):
  3598. obj_list = self.collection.get_list()
  3599. for obj in obj_list:
  3600. obj.offset((x, y))
  3601. self.app_obj.object_changed.emit(obj)
  3602. # Update the object bounding box options
  3603. a, b, c, d = obj.bounds()
  3604. obj.options['xmin'] = a
  3605. obj.options['ymin'] = b
  3606. obj.options['xmax'] = c
  3607. obj.options['ymax'] = d
  3608. self.inform.emit('[success] %s...' % _('Origin set'))
  3609. for obj in obj_list:
  3610. out_name = obj.options["name"]
  3611. if obj.kind == 'gerber':
  3612. obj.source_file = self.export_gerber(
  3613. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3614. elif obj.kind == 'excellon':
  3615. obj.source_file = self.export_excellon(
  3616. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3617. if noplot_sig is False:
  3618. self.replot_signal.emit([])
  3619. if location is not None:
  3620. if len(location) != 2:
  3621. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3622. return 'fail'
  3623. x, y = location
  3624. if use_thread is True:
  3625. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3626. else:
  3627. worker_task()
  3628. self.should_we_save = True
  3629. return
  3630. if event is not None and event.button == 1:
  3631. if self.is_legacy is False:
  3632. event_pos = event.pos
  3633. else:
  3634. event_pos = (event.xdata, event.ydata)
  3635. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3636. if self.grid_status():
  3637. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3638. else:
  3639. pos = pos_canvas
  3640. x = 0 - pos[0]
  3641. y = 0 - pos[1]
  3642. if use_thread is True:
  3643. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3644. else:
  3645. worker_task()
  3646. self.should_we_save = True
  3647. def on_move2origin(self, use_thread=True):
  3648. """
  3649. Move selected objects to origin.
  3650. :param use_thread: Control if to use threaded operation. Boolean.
  3651. :return:
  3652. """
  3653. def worker_task():
  3654. with self.proc_container.new(_("Moving to Origin...")):
  3655. obj_list = self.collection.get_selected()
  3656. if not obj_list:
  3657. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3658. return
  3659. xminlist = []
  3660. yminlist = []
  3661. # first get a bounding box to fit all
  3662. for obj in obj_list:
  3663. xmin, ymin, xmax, ymax = obj.bounds()
  3664. xminlist.append(xmin)
  3665. yminlist.append(ymin)
  3666. # get the minimum x,y for all objects selected
  3667. x = min(xminlist)
  3668. y = min(yminlist)
  3669. for obj in obj_list:
  3670. obj.offset((-x, -y))
  3671. self.app_obj.object_changed.emit(obj)
  3672. # Update the object bounding box options
  3673. a, b, c, d = obj.bounds()
  3674. obj.options['xmin'] = a
  3675. obj.options['ymin'] = b
  3676. obj.options['xmax'] = c
  3677. obj.options['ymax'] = d
  3678. for obj in obj_list:
  3679. obj.plot()
  3680. for obj in obj_list:
  3681. out_name = obj.options["name"]
  3682. if obj.kind == 'gerber':
  3683. obj.source_file = self.export_gerber(
  3684. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3685. elif obj.kind == 'excellon':
  3686. obj.source_file = self.export_excellon(
  3687. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3688. self.inform.emit('[success] %s...' % _('Origin set'))
  3689. if use_thread is True:
  3690. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3691. else:
  3692. worker_task()
  3693. self.should_we_save = True
  3694. def on_jump_to(self, custom_location=None, fit_center=True):
  3695. """
  3696. Jump to a location by setting the mouse cursor location.
  3697. :param custom_location: Jump to a specified point. (x, y) tuple.
  3698. :param fit_center: If to fit view. Boolean.
  3699. :return:
  3700. """
  3701. self.defaults.report_usage("on_jump_to()")
  3702. if not custom_location:
  3703. dia_box_location = None
  3704. try:
  3705. dia_box_location = eval(self.clipboard.text())
  3706. except Exception:
  3707. pass
  3708. if type(dia_box_location) == tuple:
  3709. dia_box_location = str(dia_box_location)
  3710. else:
  3711. dia_box_location = None
  3712. # dia_box = Dialog_box(title=_("Jump to ..."),
  3713. # label=_("Enter the coordinates in format X,Y:"),
  3714. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3715. # initial_text=dia_box_location)
  3716. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3717. label=_("Enter the coordinates in format X,Y:"),
  3718. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3719. initial_text=dia_box_location,
  3720. reference=self.defaults['global_jump_ref'])
  3721. if dia_box.ok is True:
  3722. try:
  3723. location = eval(dia_box.location)
  3724. if not isinstance(location, tuple):
  3725. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3726. return
  3727. if dia_box.reference == 'rel':
  3728. rel_x = self.mouse[0] + location[0]
  3729. rel_y = self.mouse[1] + location[1]
  3730. location = (rel_x, rel_y)
  3731. self.defaults['global_jump_ref'] = dia_box.reference
  3732. except Exception:
  3733. return
  3734. else:
  3735. return
  3736. else:
  3737. location = custom_location
  3738. self.jump_signal.emit(location)
  3739. if fit_center:
  3740. self.plotcanvas.fit_center(loc=location)
  3741. cursor = QtGui.QCursor()
  3742. if self.is_legacy is False:
  3743. # I don't know where those differences come from but they are constant for the current
  3744. # execution of the application and they are multiples of a value around 0.0263mm.
  3745. # In a random way sometimes they are more sometimes they are less
  3746. # if units == 'MM':
  3747. # cal_factor = 0.0263
  3748. # else:
  3749. # cal_factor = 0.0263 / 25.4
  3750. cal_location = (location[0], location[1])
  3751. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3752. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3753. j_pos = (
  3754. int(canvas_origin.x() + round(jump_loc[0])),
  3755. int(canvas_origin.y() + round(jump_loc[1]))
  3756. )
  3757. cursor.setPos(j_pos[0], j_pos[1])
  3758. else:
  3759. # find the canvas origin which is in the top left corner
  3760. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3761. # determine the coordinates for the lowest left point of the canvas
  3762. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3763. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3764. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3765. # canvas) and the point (width, height) is in the top-right location
  3766. loc = self.plotcanvas.axes.transData.transform_point(location)
  3767. j_pos = (
  3768. int(x0 + loc[0]),
  3769. int(y0 - loc[1])
  3770. )
  3771. cursor.setPos(j_pos[0], j_pos[1])
  3772. self.plotcanvas.mouse = [location[0], location[1]]
  3773. if self.defaults["global_cursor_color_enabled"] is True:
  3774. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3775. else:
  3776. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3777. if self.grid_status():
  3778. # Update cursor
  3779. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3780. symbol='++', edge_color=self.cursor_color_3D,
  3781. edge_width=self.defaults["global_cursor_width"],
  3782. size=self.defaults["global_cursor_size"])
  3783. # Set the relative position label
  3784. dx = location[0] - float(self.rel_point1[0])
  3785. dy = location[1] - float(self.rel_point1[1])
  3786. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3787. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3788. # # Set the position label
  3789. #
  3790. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3791. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3792. units = self.defaults["units"].lower()
  3793. self.plotcanvas.text_hud.text = \
  3794. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3795. dx, units, dy, units, location[0], units, location[1], units)
  3796. self.inform.emit('[success] %s' % _("Done."))
  3797. return location
  3798. def on_locate(self, obj, fit_center=True):
  3799. """
  3800. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3801. :param obj: The object on which to locate certain points
  3802. :param fit_center: If to fit view. Boolean.
  3803. :return: A point location. (x, y) tuple.
  3804. """
  3805. self.defaults.report_usage("on_locate()")
  3806. if obj is None:
  3807. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3808. return 'fail'
  3809. class DialogBoxChoice(QtWidgets.QDialog):
  3810. def __init__(self, title=None, icon=None, choice='bl'):
  3811. """
  3812. :param title: string with the window title
  3813. """
  3814. super(DialogBoxChoice, self).__init__()
  3815. self.ok = False
  3816. self.setWindowIcon(icon)
  3817. self.setWindowTitle(str(title))
  3818. self.form = QtWidgets.QFormLayout(self)
  3819. self.ref_radio = RadioSet([
  3820. {"label": _("Bottom-Left"), "value": "bl"},
  3821. {"label": _("Top-Left"), "value": "tl"},
  3822. {"label": _("Bottom-Right"), "value": "br"},
  3823. {"label": _("Top-Right"), "value": "tr"},
  3824. {"label": _("Center"), "value": "c"}
  3825. ], orientation='vertical', stretch=False)
  3826. self.ref_radio.set_value(choice)
  3827. self.form.addRow(self.ref_radio)
  3828. self.button_box = QtWidgets.QDialogButtonBox(
  3829. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3830. Qt.Horizontal, parent=self)
  3831. self.form.addRow(self.button_box)
  3832. self.button_box.accepted.connect(self.accept)
  3833. self.button_box.rejected.connect(self.reject)
  3834. if self.exec_() == QtWidgets.QDialog.Accepted:
  3835. self.ok = True
  3836. self.location_point = self.ref_radio.get_value()
  3837. else:
  3838. self.ok = False
  3839. self.location_point = None
  3840. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3841. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3842. choice=self.defaults['global_locate_pt'])
  3843. if dia_box.ok is True:
  3844. try:
  3845. location_point = dia_box.location_point
  3846. self.defaults['global_locate_pt'] = dia_box.location_point
  3847. except Exception:
  3848. return
  3849. else:
  3850. return
  3851. loc_b = obj.bounds()
  3852. if location_point == 'bl':
  3853. location = (loc_b[0], loc_b[1])
  3854. elif location_point == 'tl':
  3855. location = (loc_b[0], loc_b[3])
  3856. elif location_point == 'br':
  3857. location = (loc_b[2], loc_b[1])
  3858. elif location_point == 'tr':
  3859. location = (loc_b[2], loc_b[3])
  3860. else:
  3861. # center
  3862. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3863. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3864. location = (cx, cy)
  3865. self.locate_signal.emit(location, location_point)
  3866. if fit_center:
  3867. self.plotcanvas.fit_center(loc=location)
  3868. cursor = QtGui.QCursor()
  3869. if self.is_legacy is False:
  3870. # I don't know where those differences come from but they are constant for the current
  3871. # execution of the application and they are multiples of a value around 0.0263mm.
  3872. # In a random way sometimes they are more sometimes they are less
  3873. # if units == 'MM':
  3874. # cal_factor = 0.0263
  3875. # else:
  3876. # cal_factor = 0.0263 / 25.4
  3877. cal_location = (location[0], location[1])
  3878. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3879. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3880. j_pos = (
  3881. int(canvas_origin.x() + round(jump_loc[0])),
  3882. int(canvas_origin.y() + round(jump_loc[1]))
  3883. )
  3884. cursor.setPos(j_pos[0], j_pos[1])
  3885. else:
  3886. # find the canvas origin which is in the top left corner
  3887. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3888. # determine the coordinates for the lowest left point of the canvas
  3889. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3890. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3891. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3892. # canvas) and the point (width, height) is in the top-right location
  3893. loc = self.plotcanvas.axes.transData.transform_point(location)
  3894. j_pos = (
  3895. int(x0 + loc[0]),
  3896. int(y0 - loc[1])
  3897. )
  3898. cursor.setPos(j_pos[0], j_pos[1])
  3899. self.plotcanvas.mouse = [location[0], location[1]]
  3900. if self.defaults["global_cursor_color_enabled"] is True:
  3901. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3902. else:
  3903. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3904. if self.grid_status():
  3905. # Update cursor
  3906. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3907. symbol='++', edge_color=self.cursor_color_3D,
  3908. edge_width=self.defaults["global_cursor_width"],
  3909. size=self.defaults["global_cursor_size"])
  3910. # Set the relative position label
  3911. self.dx = location[0] - float(self.rel_point1[0])
  3912. self.dy = location[1] - float(self.rel_point1[1])
  3913. # Set the position label
  3914. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3915. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3916. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3917. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3918. units = self.defaults["units"].lower()
  3919. self.plotcanvas.text_hud.text = \
  3920. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3921. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3922. self.inform.emit('[success] %s' % _("Done."))
  3923. return location
  3924. def on_copy_command(self):
  3925. """
  3926. Will copy a selection of objects, creating new objects.
  3927. :return:
  3928. """
  3929. self.defaults.report_usage("on_copy_command()")
  3930. def initialize(obj_init, app):
  3931. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3932. try:
  3933. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3934. except AttributeError:
  3935. pass
  3936. try:
  3937. obj_init.apertures = deepcopy(obj.apertures)
  3938. except AttributeError:
  3939. pass
  3940. try:
  3941. if obj.tools:
  3942. obj_init.tools = deepcopy(obj.tools)
  3943. except Exception as err:
  3944. log.debug("App.on_copy_command() --> %s" % str(err))
  3945. try:
  3946. obj_init.source_file = deepcopy(obj.source_file)
  3947. except (AttributeError, TypeError):
  3948. pass
  3949. def initialize_excellon(obj_init, app):
  3950. obj_init.source_file = deepcopy(obj.source_file)
  3951. obj_init.tools = deepcopy(obj.tools)
  3952. # drills are offset, so they need to be deep copied
  3953. obj_init.drills = deepcopy(obj.drills)
  3954. # slots are offset, so they need to be deep copied
  3955. obj_init.slots = deepcopy(obj.slots)
  3956. obj_init.create_geometry()
  3957. def initialize_script(obj_init, app_obj):
  3958. obj_init.source_file = deepcopy(obj.source_file)
  3959. def initialize_document(obj_init, app_obj):
  3960. obj_init.source_file = deepcopy(obj.source_file)
  3961. for obj in self.collection.get_selected():
  3962. obj_name = obj.options["name"]
  3963. try:
  3964. if isinstance(obj, ExcellonObject):
  3965. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3966. elif isinstance(obj, GerberObject):
  3967. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  3968. elif isinstance(obj, GeometryObject):
  3969. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  3970. elif isinstance(obj, ScriptObject):
  3971. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  3972. elif isinstance(obj, DocumentObject):
  3973. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  3974. except Exception as e:
  3975. return "Operation failed: %s" % str(e)
  3976. def on_copy_object2(self, custom_name):
  3977. def initialize_geometry(obj_init, app):
  3978. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3979. try:
  3980. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3981. except AttributeError:
  3982. pass
  3983. try:
  3984. obj_init.apertures = deepcopy(obj.apertures)
  3985. except AttributeError:
  3986. pass
  3987. try:
  3988. if obj.tools:
  3989. obj_init.tools = deepcopy(obj.tools)
  3990. except Exception as ee:
  3991. log.debug("on_copy_object2() --> %s" % str(ee))
  3992. def initialize_gerber(obj_init, app):
  3993. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3994. obj_init.apertures = deepcopy(obj.apertures)
  3995. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3996. def initialize_excellon(obj_init, app):
  3997. obj_init.tools = deepcopy(obj.tools)
  3998. # drills are offset, so they need to be deep copied
  3999. obj_init.drills = deepcopy(obj.drills)
  4000. # slots are offset, so they need to be deep copied
  4001. obj_init.slots = deepcopy(obj.slots)
  4002. obj_init.create_geometry()
  4003. for obj in self.collection.get_selected():
  4004. obj_name = obj.options["name"]
  4005. try:
  4006. if isinstance(obj, ExcellonObject):
  4007. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4008. elif isinstance(obj, GerberObject):
  4009. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4010. elif isinstance(obj, GeometryObject):
  4011. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4012. except Exception as er:
  4013. return "Operation failed: %s" % str(er)
  4014. def on_rename_object(self, text):
  4015. """
  4016. Will rename an object.
  4017. :param text: New name for the object.
  4018. :return:
  4019. """
  4020. self.defaults.report_usage("on_rename_object()")
  4021. named_obj = self.collection.get_active()
  4022. for obj in named_obj:
  4023. if obj is list:
  4024. self.on_rename_object(text)
  4025. else:
  4026. try:
  4027. obj.options['name'] = text
  4028. except Exception as e:
  4029. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4030. def convert_any2geo(self):
  4031. """
  4032. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4033. :return:
  4034. """
  4035. self.defaults.report_usage("convert_any2geo()")
  4036. def initialize(obj_init, app):
  4037. obj_init.solid_geometry = obj.solid_geometry
  4038. try:
  4039. obj_init.follow_geometry = obj.follow_geometry
  4040. except AttributeError:
  4041. pass
  4042. try:
  4043. obj_init.apertures = obj.apertures
  4044. except AttributeError:
  4045. pass
  4046. try:
  4047. if obj.tools:
  4048. obj_init.tools = obj.tools
  4049. except AttributeError:
  4050. pass
  4051. def initialize_excellon(obj_init, app):
  4052. # objs = self.collection.get_selected()
  4053. # GeometryObject.merge(objs, obj)
  4054. solid_geo = []
  4055. for tool in obj.tools:
  4056. for geo in obj.tools[tool]['solid_geometry']:
  4057. solid_geo.append(geo)
  4058. obj_init.solid_geometry = deepcopy(solid_geo)
  4059. if not self.collection.get_selected():
  4060. log.warning("App.convert_any2geo --> No object selected")
  4061. self.inform.emit('[WARNING_NOTCL] %s' %
  4062. _("No object is selected. Select an object and try again."))
  4063. return
  4064. for obj in self.collection.get_selected():
  4065. obj_name = obj.options["name"]
  4066. try:
  4067. if isinstance(obj, ExcellonObject):
  4068. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4069. else:
  4070. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4071. except Exception as e:
  4072. return "Operation failed: %s" % str(e)
  4073. def convert_any2gerber(self):
  4074. """
  4075. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4076. :return:
  4077. """
  4078. self.defaults.report_usage("convert_any2gerber()")
  4079. def initialize_geometry(obj_init, app):
  4080. apertures = {}
  4081. apid = 0
  4082. apertures[str(apid)] = {}
  4083. apertures[str(apid)]['geometry'] = []
  4084. for obj_orig in obj.solid_geometry:
  4085. new_elem = {}
  4086. new_elem['solid'] = obj_orig
  4087. try:
  4088. new_elem['follow'] = obj_orig.exterior
  4089. except AttributeError:
  4090. pass
  4091. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4092. apertures[str(apid)]['size'] = 0.0
  4093. apertures[str(apid)]['type'] = 'C'
  4094. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4095. obj_init.apertures = deepcopy(apertures)
  4096. def initialize_excellon(obj_init, app):
  4097. apertures = {}
  4098. apid = 10
  4099. for tool in obj.tools:
  4100. apertures[str(apid)] = {}
  4101. apertures[str(apid)]['geometry'] = []
  4102. for geo in obj.tools[tool]['solid_geometry']:
  4103. new_el = {}
  4104. new_el['solid'] = geo
  4105. new_el['follow'] = geo.exterior
  4106. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4107. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4108. apertures[str(apid)]['type'] = 'C'
  4109. apid += 1
  4110. # create solid_geometry
  4111. solid_geometry = []
  4112. for apid in apertures:
  4113. for geo_el in apertures[apid]['geometry']:
  4114. solid_geometry.append(geo_el['solid'])
  4115. solid_geometry = MultiPolygon(solid_geometry)
  4116. solid_geometry = solid_geometry.buffer(0.0000001)
  4117. obj_init.solid_geometry = deepcopy(solid_geometry)
  4118. obj_init.apertures = deepcopy(apertures)
  4119. # clear the working objects (perhaps not necessary due of Python GC)
  4120. apertures.clear()
  4121. if not self.collection.get_selected():
  4122. log.warning("App.convert_any2gerber --> No object selected")
  4123. self.inform.emit('[WARNING_NOTCL] %s' %
  4124. _("No object is selected. Select an object and try again."))
  4125. return
  4126. for obj in self.collection.get_selected():
  4127. obj_name = obj.options["name"]
  4128. try:
  4129. if isinstance(obj, ExcellonObject):
  4130. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4131. elif isinstance(obj, GeometryObject):
  4132. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4133. else:
  4134. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4135. except Exception as e:
  4136. return "Operation failed: %s" % str(e)
  4137. def abort_all_tasks(self):
  4138. """
  4139. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4140. on the first possible occasion.
  4141. :return:
  4142. """
  4143. if self.abort_flag is False:
  4144. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4145. self.abort_flag = True
  4146. self.cleanup.emit()
  4147. def app_is_idle(self):
  4148. if self.abort_flag:
  4149. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4150. self.abort_flag = False
  4151. def on_selectall(self):
  4152. """
  4153. Will draw a selection box shape around the selected objects.
  4154. :return:
  4155. """
  4156. self.defaults.report_usage("on_selectall()")
  4157. # delete the possible selection box around a possible selected object
  4158. self.delete_selection_shape()
  4159. for name in self.collection.get_names():
  4160. self.collection.set_active(name)
  4161. curr_sel_obj = self.collection.get_by_name(name)
  4162. # create the selection box around the selected object
  4163. if self.defaults['global_selection_shape'] is True:
  4164. self.draw_selection_shape(curr_sel_obj)
  4165. def on_preferences(self):
  4166. """
  4167. Adds the Preferences in a Tab in Plot Area
  4168. :return:
  4169. """
  4170. # add the tab if it was closed
  4171. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4172. # delete the absolute and relative position and messages in the infobar
  4173. self.ui.position_label.setText("")
  4174. # self.ui.rel_position_label.setText("")
  4175. # Switch plot_area to preferences page
  4176. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4177. # self.ui.show()
  4178. # detect changes in the preferences
  4179. for idx in range(self.ui.pref_tab_area.count()):
  4180. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4181. try:
  4182. try:
  4183. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4184. except (TypeError, AttributeError):
  4185. pass
  4186. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4187. except AttributeError:
  4188. pass
  4189. try:
  4190. try:
  4191. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4192. except (TypeError, AttributeError):
  4193. pass
  4194. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4195. except AttributeError:
  4196. pass
  4197. try:
  4198. try:
  4199. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4200. except (TypeError, AttributeError):
  4201. pass
  4202. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4203. except AttributeError:
  4204. pass
  4205. try:
  4206. try:
  4207. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4208. except (TypeError, AttributeError):
  4209. pass
  4210. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4211. except AttributeError:
  4212. pass
  4213. try:
  4214. try:
  4215. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4216. except (TypeError, AttributeError):
  4217. pass
  4218. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4219. except AttributeError:
  4220. pass
  4221. def on_tools_database(self, source='app'):
  4222. """
  4223. Adds the Tools Database in a Tab in Plot Area.
  4224. :return:
  4225. """
  4226. for idx in range(self.ui.plot_tab_area.count()):
  4227. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4228. # there can be only one instance of Tools Database at one time
  4229. return
  4230. if source == 'app':
  4231. self.tools_db_tab = ToolsDB2(
  4232. app=self,
  4233. parent=self.ui,
  4234. callback_on_edited=self.on_tools_db_edited,
  4235. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4236. )
  4237. elif source == 'ncc':
  4238. self.tools_db_tab = ToolsDB2(
  4239. app=self,
  4240. parent=self.ui,
  4241. callback_on_edited=self.on_tools_db_edited,
  4242. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4243. )
  4244. elif source == 'paint':
  4245. self.tools_db_tab = ToolsDB2(
  4246. app=self,
  4247. parent=self.ui,
  4248. callback_on_edited=self.on_tools_db_edited,
  4249. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4250. )
  4251. # add the tab if it was closed
  4252. try:
  4253. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4254. self.tools_db_tab.setObjectName("database_tab")
  4255. except Exception as e:
  4256. log.debug("App.on_tools_database() --> %s" % str(e))
  4257. return
  4258. # delete the absolute and relative position and messages in the infobar
  4259. self.ui.position_label.setText("")
  4260. # self.ui.rel_position_label.setText("")
  4261. # Switch plot_area to preferences page
  4262. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4263. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4264. self.tools_db_tab.ui_connect()
  4265. def on_tools_db_edited(self):
  4266. """
  4267. Executed whenever a tool is edited in Tools Database.
  4268. Will color the text of the Tools Database tab to Red color.
  4269. :return:
  4270. """
  4271. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4272. for idx in range(self.ui.plot_tab_area.count()):
  4273. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4274. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4275. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4276. self.tools_db_changed_flag = True
  4277. def on_geometry_tool_add_from_db_executed(self, tool):
  4278. """
  4279. Here add the tool from DB in the selected geometry object.
  4280. :return:
  4281. """
  4282. tool_from_db = deepcopy(tool)
  4283. obj = self.collection.get_active()
  4284. if isinstance(obj, GeometryObject):
  4285. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4286. # close the tab and delete it
  4287. for idx in range(self.ui.plot_tab_area.count()):
  4288. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4289. wdg = self.ui.plot_tab_area.widget(idx)
  4290. wdg.deleteLater()
  4291. self.ui.plot_tab_area.removeTab(idx)
  4292. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4293. else:
  4294. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4295. def on_plot_area_tab_closed(self, tab_obj_name):
  4296. """
  4297. Executed whenever a QTab is closed in the Plot Area.
  4298. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4299. :return:
  4300. """
  4301. if tab_obj_name == "preferences_tab":
  4302. self.preferencesUiManager.on_close_preferences_tab()
  4303. elif tab_obj_name == "database_tab":
  4304. # disconnect the signals from the table widget in tab
  4305. self.tools_db_tab.ui_disconnect()
  4306. if self.tools_db_changed_flag is True:
  4307. msgbox = QtWidgets.QMessageBox()
  4308. msgbox.setText(_("One or more Tools are edited.\n"
  4309. "Do you want to update the Tools Database?"))
  4310. msgbox.setWindowTitle(_("Save Tools Database"))
  4311. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4312. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4313. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4314. msgbox.setDefaultButton(bt_yes)
  4315. msgbox.exec_()
  4316. response = msgbox.clickedButton()
  4317. if response == bt_yes:
  4318. self.tools_db_tab.on_save_tools_db()
  4319. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4320. else:
  4321. self.tools_db_changed_flag = False
  4322. self.inform.emit('')
  4323. return
  4324. self.tools_db_tab.deleteLater()
  4325. elif tab_obj_name == "text_editor_tab":
  4326. self.toggle_codeeditor = False
  4327. elif tab_obj_name == "bookmarks_tab":
  4328. self.book_dialog_tab.rebuild_actions()
  4329. self.book_dialog_tab.deleteLater()
  4330. else:
  4331. return
  4332. # def on_plotarea_tab_closed(self, tab_idx):
  4333. # """
  4334. #
  4335. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4336. # :return:
  4337. # """
  4338. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4339. #
  4340. # if widget is not None:
  4341. # widget.deleteLater()
  4342. # self.ui.plot_tab_area.removeTab(tab_idx)
  4343. def on_flipy(self):
  4344. """
  4345. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4346. :return:
  4347. """
  4348. self.defaults.report_usage("on_flipy()")
  4349. obj_list = self.collection.get_selected()
  4350. xminlist = []
  4351. yminlist = []
  4352. xmaxlist = []
  4353. ymaxlist = []
  4354. if not obj_list:
  4355. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4356. else:
  4357. try:
  4358. # first get a bounding box to fit all
  4359. for obj in obj_list:
  4360. xmin, ymin, xmax, ymax = obj.bounds()
  4361. xminlist.append(xmin)
  4362. yminlist.append(ymin)
  4363. xmaxlist.append(xmax)
  4364. ymaxlist.append(ymax)
  4365. # get the minimum x,y and maximum x,y for all objects selected
  4366. xminimal = min(xminlist)
  4367. yminimal = min(yminlist)
  4368. xmaximal = max(xmaxlist)
  4369. ymaximal = max(ymaxlist)
  4370. px = 0.5 * (xminimal + xmaximal)
  4371. py = 0.5 * (yminimal + ymaximal)
  4372. # execute mirroring
  4373. for obj in obj_list:
  4374. obj.mirror('X', [px, py])
  4375. obj.plot()
  4376. self.app_obj.object_changed.emit(obj)
  4377. self.inform.emit('[success] %s' %
  4378. _("Flip on Y axis done."))
  4379. except Exception as e:
  4380. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4381. return
  4382. def on_flipx(self):
  4383. """
  4384. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4385. :return:
  4386. """
  4387. self.defaults.report_usage("on_flipx()")
  4388. obj_list = self.collection.get_selected()
  4389. xminlist = []
  4390. yminlist = []
  4391. xmaxlist = []
  4392. ymaxlist = []
  4393. if not obj_list:
  4394. self.inform.emit('[WARNING_NOTCL] %s' %
  4395. _("No object selected to Flip on X axis."))
  4396. else:
  4397. try:
  4398. # first get a bounding box to fit all
  4399. for obj in obj_list:
  4400. xmin, ymin, xmax, ymax = obj.bounds()
  4401. xminlist.append(xmin)
  4402. yminlist.append(ymin)
  4403. xmaxlist.append(xmax)
  4404. ymaxlist.append(ymax)
  4405. # get the minimum x,y and maximum x,y for all objects selected
  4406. xminimal = min(xminlist)
  4407. yminimal = min(yminlist)
  4408. xmaximal = max(xmaxlist)
  4409. ymaximal = max(ymaxlist)
  4410. px = 0.5 * (xminimal + xmaximal)
  4411. py = 0.5 * (yminimal + ymaximal)
  4412. # execute mirroring
  4413. for obj in obj_list:
  4414. obj.mirror('Y', [px, py])
  4415. obj.plot()
  4416. self.app_obj.object_changed.emit(obj)
  4417. self.inform.emit('[success] %s' %
  4418. _("Flip on X axis done."))
  4419. except Exception as e:
  4420. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4421. return
  4422. def on_rotate(self, silent=False, preset=None):
  4423. """
  4424. Executed when Options -> Rotate Selection menu entry is clicked.
  4425. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4426. :param preset: A value to be used as predefined angle for rotation.
  4427. :return:
  4428. """
  4429. self.defaults.report_usage("on_rotate()")
  4430. obj_list = self.collection.get_selected()
  4431. xminlist = []
  4432. yminlist = []
  4433. xmaxlist = []
  4434. ymaxlist = []
  4435. if not obj_list:
  4436. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4437. else:
  4438. if silent is False:
  4439. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4440. min=-360, max=360, decimals=4,
  4441. init_val=float(self.defaults['tools_transform_rotate']))
  4442. num, ok = rotatebox.get_value()
  4443. else:
  4444. num = preset
  4445. ok = True
  4446. if ok:
  4447. try:
  4448. # first get a bounding box to fit all
  4449. for obj in obj_list:
  4450. xmin, ymin, xmax, ymax = obj.bounds()
  4451. xminlist.append(xmin)
  4452. yminlist.append(ymin)
  4453. xmaxlist.append(xmax)
  4454. ymaxlist.append(ymax)
  4455. # get the minimum x,y and maximum x,y for all objects selected
  4456. xminimal = min(xminlist)
  4457. yminimal = min(yminlist)
  4458. xmaximal = max(xmaxlist)
  4459. ymaximal = max(ymaxlist)
  4460. px = 0.5 * (xminimal + xmaximal)
  4461. py = 0.5 * (yminimal + ymaximal)
  4462. for sel_obj in obj_list:
  4463. sel_obj.rotate(-float(num), point=(px, py))
  4464. sel_obj.plot()
  4465. self.app_obj.object_changed.emit(sel_obj)
  4466. self.inform.emit('[success] %s' % _("Rotation done."))
  4467. except Exception as e:
  4468. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4469. return
  4470. def on_skewx(self):
  4471. """
  4472. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4473. :return:
  4474. """
  4475. self.defaults.report_usage("on_skewx()")
  4476. obj_list = self.collection.get_selected()
  4477. xminlist = []
  4478. yminlist = []
  4479. if not obj_list:
  4480. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4481. else:
  4482. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4483. min=-360, max=360, decimals=4,
  4484. init_val=float(self.defaults['tools_transform_skew_x']))
  4485. num, ok = skewxbox.get_value()
  4486. if ok:
  4487. # first get a bounding box to fit all
  4488. for obj in obj_list:
  4489. xmin, ymin, xmax, ymax = obj.bounds()
  4490. xminlist.append(xmin)
  4491. yminlist.append(ymin)
  4492. # get the minimum x,y and maximum x,y for all objects selected
  4493. xminimal = min(xminlist)
  4494. yminimal = min(yminlist)
  4495. for obj in obj_list:
  4496. obj.skew(num, 0, point=(xminimal, yminimal))
  4497. obj.plot()
  4498. self.app_obj.object_changed.emit(obj)
  4499. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4500. def on_skewy(self):
  4501. """
  4502. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4503. :return:
  4504. """
  4505. self.defaults.report_usage("on_skewy()")
  4506. obj_list = self.collection.get_selected()
  4507. xminlist = []
  4508. yminlist = []
  4509. if not obj_list:
  4510. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4511. else:
  4512. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4513. min=-360, max=360, decimals=4,
  4514. init_val=float(self.defaults['tools_transform_skew_y']))
  4515. num, ok = skewybox.get_value()
  4516. if ok:
  4517. # first get a bounding box to fit all
  4518. for obj in obj_list:
  4519. xmin, ymin, xmax, ymax = obj.bounds()
  4520. xminlist.append(xmin)
  4521. yminlist.append(ymin)
  4522. # get the minimum x,y and maximum x,y for all objects selected
  4523. xminimal = min(xminlist)
  4524. yminimal = min(yminlist)
  4525. for obj in obj_list:
  4526. obj.skew(0, num, point=(xminimal, yminimal))
  4527. obj.plot()
  4528. self.app_obj.object_changed.emit(obj)
  4529. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4530. def on_plots_updated(self):
  4531. """
  4532. Callback used to report when the plots have changed.
  4533. Adjust axes and zooms to fit.
  4534. :return: None
  4535. """
  4536. if self.is_legacy is False:
  4537. self.plotcanvas.update()
  4538. else:
  4539. self.plotcanvas.auto_adjust_axes()
  4540. self.on_zoom_fit()
  4541. self.collection.update_view()
  4542. # self.inform.emit(_("Plots updated ..."))
  4543. def on_toolbar_replot(self):
  4544. """
  4545. Callback for toolbar button. Re-plots all objects.
  4546. :return: None
  4547. """
  4548. self.defaults.report_usage("on_toolbar_replot")
  4549. self.log.debug("on_toolbar_replot()")
  4550. try:
  4551. self.collection.get_active().read_form()
  4552. except AttributeError:
  4553. self.log.debug("on_toolbar_replot(): AttributeError")
  4554. pass
  4555. self.plot_all()
  4556. def grid_status(self):
  4557. return True if self.ui.grid_snap_btn.isChecked() else False
  4558. def populate_cmenu_grids(self):
  4559. units = self.defaults['units'].lower()
  4560. # for act in self.ui.cmenu_gridmenu.actions():
  4561. # act.triggered.disconnect()
  4562. self.ui.cmenu_gridmenu.clear()
  4563. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4564. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4565. _("Grid On/Off"))
  4566. grid_toggle.setCheckable(True)
  4567. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4568. self.ui.cmenu_gridmenu.addSeparator()
  4569. for grid in sorted_list:
  4570. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4571. "%s" % str(grid))
  4572. action.triggered.connect(self.set_grid)
  4573. self.ui.cmenu_gridmenu.addSeparator()
  4574. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4575. _("Add"))
  4576. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4577. _("Delete"))
  4578. grid_add.triggered.connect(self.on_grid_add)
  4579. grid_delete.triggered.connect(self.on_grid_delete)
  4580. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4581. def set_grid(self):
  4582. menu_action = self.sender()
  4583. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4584. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4585. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4586. def on_grid_add(self):
  4587. # ## Current application units in lower Case
  4588. units = self.defaults['units'].lower()
  4589. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4590. text=_('Enter a Grid Value:'),
  4591. min=0.0000, max=99.9999, decimals=4)
  4592. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4593. val, ok = grid_add_popup.get_value()
  4594. if ok:
  4595. if float(val) == 0:
  4596. self.inform.emit('[WARNING_NOTCL] %s' %
  4597. _("Please enter a grid value with non-zero value, in Float format."))
  4598. return
  4599. else:
  4600. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4601. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4602. self.inform.emit('[success] %s...' % _("New Grid added"))
  4603. else:
  4604. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4605. else:
  4606. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4607. def on_grid_delete(self):
  4608. # ## Current application units in lower Case
  4609. units = self.defaults['units'].lower()
  4610. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4611. text='Enter a Grid Value:',
  4612. min=0.0000, max=99.9999, decimals=4)
  4613. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4614. val, ok = grid_del_popup.get_value()
  4615. if ok:
  4616. if float(val) == 0:
  4617. self.inform.emit('[WARNING_NOTCL] %s' %
  4618. _("Please enter a grid value with non-zero value, in Float format."))
  4619. return
  4620. else:
  4621. try:
  4622. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4623. except ValueError:
  4624. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4625. return
  4626. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4627. else:
  4628. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4629. def on_shortcut_list(self):
  4630. self.defaults.report_usage("on_shortcut_list()")
  4631. # add the tab if it was closed
  4632. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4633. # delete the absolute and relative position and messages in the infobar
  4634. self.ui.position_label.setText("")
  4635. # self.ui.rel_position_label.setText("")
  4636. # Switch plot_area to preferences page
  4637. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4638. # self.ui.show()
  4639. def on_select_tab(self, name):
  4640. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4641. if self.ui.splitter.sizes()[0] == 0:
  4642. self.ui.splitter.setSizes([1, 1])
  4643. else:
  4644. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4645. self.ui.splitter.setSizes([0, 1])
  4646. if name == 'project':
  4647. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4648. elif name == 'selected':
  4649. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4650. elif name == 'tool':
  4651. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4652. def on_copy_name(self):
  4653. self.defaults.report_usage("on_copy_name()")
  4654. obj = self.collection.get_active()
  4655. try:
  4656. name = obj.options["name"]
  4657. except AttributeError:
  4658. log.debug("on_copy_name() --> No object selected to copy it's name")
  4659. self.inform.emit('[WARNING_NOTCL]%s' %
  4660. _(" No object selected to copy it's name"))
  4661. return
  4662. self.clipboard.setText(name)
  4663. self.inform.emit(_("Name copied on clipboard ..."))
  4664. def on_mouse_click_over_plot(self, event):
  4665. """
  4666. Default actions are:
  4667. :param event: Contains information about the event, like which button
  4668. was clicked, the pixel coordinates and the axes coordinates.
  4669. :return: None
  4670. """
  4671. self.pos = []
  4672. if self.is_legacy is False:
  4673. event_pos = event.pos
  4674. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4675. # # Set the mouse button for panning
  4676. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4677. else:
  4678. event_pos = (event.xdata, event.ydata)
  4679. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4680. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4681. # So it can receive key presses
  4682. self.plotcanvas.native.setFocus()
  4683. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4684. if self.grid_status():
  4685. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4686. else:
  4687. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4688. try:
  4689. if event.button == 1:
  4690. # Reset here the relative coordinates so there is a new reference on the click position
  4691. if self.rel_point1 is None:
  4692. self.rel_point1 = self.pos
  4693. else:
  4694. self.rel_point2 = copy(self.rel_point1)
  4695. self.rel_point1 = self.pos
  4696. self.on_mouse_move_over_plot(event, origin_click=True)
  4697. except Exception as e:
  4698. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4699. def on_mouse_double_click_over_plot(self, event):
  4700. if event.button == 1:
  4701. self.doubleclick = True
  4702. def on_mouse_move_over_plot(self, event, origin_click=None):
  4703. """
  4704. Callback for the mouse motion event over the plot.
  4705. :param event: Contains information about the event.
  4706. :param origin_click
  4707. :return: None
  4708. """
  4709. if self.is_legacy is False:
  4710. event_pos = event.pos
  4711. if self.defaults["global_pan_button"] == '2':
  4712. pan_button = 2
  4713. else:
  4714. pan_button = 3
  4715. self.event_is_dragging = event.is_dragging
  4716. else:
  4717. event_pos = (event.xdata, event.ydata)
  4718. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4719. if self.defaults["global_pan_button"] == '2':
  4720. pan_button = 3
  4721. else:
  4722. pan_button = 2
  4723. self.event_is_dragging = self.plotcanvas.is_dragging
  4724. # So it can receive key presses but not when the Tcl Shell is active
  4725. if not self.ui.shell_dock.isVisible():
  4726. if not self.plotcanvas.native.hasFocus():
  4727. self.plotcanvas.native.setFocus()
  4728. self.pos_jump = event_pos
  4729. self.ui.popMenu.mouse_is_panning = False
  4730. if origin_click is None:
  4731. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4732. if event.button == pan_button and self.event_is_dragging == 1:
  4733. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4734. if self.ui.popMenu.popup_active:
  4735. self.ui.popMenu.popup_active = False
  4736. return
  4737. self.ui.popMenu.mouse_is_panning = True
  4738. return
  4739. if self.rel_point1 is not None:
  4740. try: # May fail in case mouse not within axes
  4741. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4742. if pos_canvas[0] is None or pos_canvas[1] is None:
  4743. return
  4744. if self.grid_status():
  4745. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4746. # Update cursor
  4747. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4748. symbol='++', edge_color=self.cursor_color_3D,
  4749. edge_width=self.defaults["global_cursor_width"],
  4750. size=self.defaults["global_cursor_size"])
  4751. else:
  4752. pos = (pos_canvas[0], pos_canvas[1])
  4753. self.dx = pos[0] - float(self.rel_point1[0])
  4754. self.dy = pos[1] - float(self.rel_point1[1])
  4755. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4756. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4757. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4758. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4759. units = self.defaults["units"].lower()
  4760. self.plotcanvas.text_hud.text = \
  4761. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4762. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4763. self.mouse = [pos[0], pos[1]]
  4764. # if the mouse is moved and the LMB is clicked then the action is a selection
  4765. if self.event_is_dragging == 1 and event.button == 1:
  4766. self.delete_selection_shape()
  4767. if self.dx < 0:
  4768. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4769. face_color=self.defaults['global_alt_sel_fill'])
  4770. self.selection_type = False
  4771. elif self.dx >= 0:
  4772. self.draw_moving_selection_shape(self.pos, pos)
  4773. self.selection_type = True
  4774. else:
  4775. self.selection_type = None
  4776. else:
  4777. self.selection_type = None
  4778. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4779. if self.defaults['global_hover']:
  4780. for obj in self.collection.get_list():
  4781. try:
  4782. # select the object(s) only if it is enabled (plotted)
  4783. if obj.options['plot']:
  4784. if obj not in self.collection.get_selected():
  4785. poly_obj = Polygon(
  4786. [(obj.options['xmin'], obj.options['ymin']),
  4787. (obj.options['xmax'], obj.options['ymin']),
  4788. (obj.options['xmax'], obj.options['ymax']),
  4789. (obj.options['xmin'], obj.options['ymax'])]
  4790. )
  4791. if Point(pos).within(poly_obj):
  4792. if obj.isHovering is False:
  4793. obj.isHovering = True
  4794. obj.notHovering = True
  4795. # create the selection box around the selected object
  4796. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4797. else:
  4798. if obj.notHovering is True:
  4799. obj.notHovering = False
  4800. obj.isHovering = False
  4801. self.delete_hover_shape()
  4802. except Exception:
  4803. # the Exception here will happen if we try to select on screen and we have an
  4804. # newly (and empty) just created Geometry or Excellon object that do not have the
  4805. # xmin, xmax, ymin, ymax options.
  4806. # In this case poly_obj creation (see above) will fail
  4807. pass
  4808. except Exception as e:
  4809. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4810. self.ui.position_label.setText("")
  4811. # self.ui.rel_position_label.setText("")
  4812. self.mouse = None
  4813. def on_mouse_click_release_over_plot(self, event):
  4814. """
  4815. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4816. and has been registered in ''self.__init__()''.
  4817. :param event: contains information about the event.
  4818. :return:
  4819. """
  4820. if self.is_legacy is False:
  4821. event_pos = event.pos
  4822. right_button = 2
  4823. else:
  4824. event_pos = (event.xdata, event.ydata)
  4825. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4826. right_button = 3
  4827. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4828. if self.grid_status():
  4829. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4830. else:
  4831. pos = (pos_canvas[0], pos_canvas[1])
  4832. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4833. # canvas menu
  4834. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4835. self.ui.popMenu.mouse_is_panning = False
  4836. self.cursor = QtGui.QCursor()
  4837. self.populate_cmenu_grids()
  4838. self.ui.popMenu.popup(self.cursor.pos())
  4839. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4840. # selection and then select a type of selection ("enclosing" or "touching")
  4841. if event.button == 1: # left click
  4842. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4843. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4844. if modifiers == QtCore.Qt.ShiftModifier:
  4845. # do not auto open the Project Tab
  4846. self.click_noproject = True
  4847. self.clipboard.setText(
  4848. self.defaults["global_point_clipboard_format"] %
  4849. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4850. )
  4851. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4852. return
  4853. if self.doubleclick is True:
  4854. self.doubleclick = False
  4855. if self.collection.get_selected():
  4856. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4857. if self.ui.splitter.sizes()[0] == 0:
  4858. self.ui.splitter.setSizes([1, 1])
  4859. try:
  4860. # delete the selection shape(S) as it may be in the way
  4861. self.delete_selection_shape()
  4862. self.delete_hover_shape()
  4863. except Exception as e:
  4864. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4865. return
  4866. else:
  4867. # WORKAROUND for LEGACY MODE
  4868. if self.is_legacy is True:
  4869. # if there is no move on canvas then we have no dragging selection
  4870. if self.dx == 0 or self.dy == 0:
  4871. self.selection_type = None
  4872. if self.selection_type is not None:
  4873. try:
  4874. self.selection_area_handler(self.pos, pos, self.selection_type)
  4875. self.selection_type = None
  4876. except Exception as e:
  4877. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4878. return
  4879. else:
  4880. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4881. if key_modifier == QtCore.Qt.ShiftModifier:
  4882. mod_key = 'Shift'
  4883. elif key_modifier == QtCore.Qt.ControlModifier:
  4884. mod_key = 'Control'
  4885. else:
  4886. mod_key = None
  4887. try:
  4888. if self.command_active is None:
  4889. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4890. # deselect, and if it's not selected then it will be selected
  4891. # If there is no active command (self.command_active is None) then we check if we clicked
  4892. # on a object by checking the bounding limits against mouse click position
  4893. if mod_key == self.defaults["global_mselect_key"]:
  4894. self.select_objects(key='multisel')
  4895. else:
  4896. # If there is no active command (self.command_active is None) then we check if
  4897. # we clicked on a object by checking the bounding limits against mouse click position
  4898. self.select_objects()
  4899. self.delete_hover_shape()
  4900. except Exception as e:
  4901. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4902. return
  4903. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4904. """
  4905. :param start_pos: mouse position when the selection LMB click was done
  4906. :param end_pos: mouse position when the left mouse button is released
  4907. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4908. :return:
  4909. """
  4910. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4911. # delete previous selection shape
  4912. self.delete_selection_shape()
  4913. # make all objects inactive
  4914. self.collection.set_all_inactive()
  4915. for obj in self.collection.get_list():
  4916. try:
  4917. # select the object(s) only if it is enabled (plotted)
  4918. if obj.options['plot']:
  4919. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4920. (obj.options['xmax'], obj.options['ymin']),
  4921. (obj.options['xmax'], obj.options['ymax']),
  4922. (obj.options['xmin'], obj.options['ymax'])])
  4923. if sel_type is True:
  4924. if poly_obj.within(poly_selection):
  4925. # create the selection box around the selected object
  4926. if self.defaults['global_selection_shape'] is True:
  4927. self.draw_selection_shape(obj)
  4928. self.collection.set_active(obj.options['name'])
  4929. else:
  4930. if poly_selection.intersects(poly_obj):
  4931. # create the selection box around the selected object
  4932. if self.defaults['global_selection_shape'] is True:
  4933. self.draw_selection_shape(obj)
  4934. self.collection.set_active(obj.options['name'])
  4935. obj.selection_shape_drawn = True
  4936. except Exception as e:
  4937. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4938. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4939. # In this case poly_obj creation (see above) will fail
  4940. log.debug("App.selection_area_handler() --> %s" % str(e))
  4941. def select_objects(self, key=None):
  4942. """
  4943. Will select objects clicked on canvas
  4944. :param key: for future use in cumulative selection
  4945. :return:
  4946. """
  4947. # list where we store the overlapped objects under our mouse left click position
  4948. if key is None:
  4949. self.objects_under_the_click_list = []
  4950. # Populate the list with the overlapped objects on the click position
  4951. curr_x, curr_y = self.pos
  4952. for obj in self.all_objects_list:
  4953. # ScriptObject and DocumentObject objects can't be selected
  4954. if obj.kind == 'script' or obj.kind == 'document':
  4955. continue
  4956. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  4957. continue
  4958. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4959. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4960. if obj.options['name'] not in self.objects_under_the_click_list:
  4961. if obj.options['plot']:
  4962. # add objects to the objects_under_the_click list only if the object is plotted
  4963. # (active and not disabled)
  4964. self.objects_under_the_click_list.append(obj.options['name'])
  4965. try:
  4966. if self.objects_under_the_click_list:
  4967. curr_sel_obj = self.collection.get_active()
  4968. # case when there is only an object under the click and we toggle it
  4969. if len(self.objects_under_the_click_list) == 1:
  4970. if curr_sel_obj is None:
  4971. self.collection.set_active(self.objects_under_the_click_list[0])
  4972. curr_sel_obj = self.collection.get_active()
  4973. # create the selection box around the selected object
  4974. if self.defaults['global_selection_shape'] is True:
  4975. self.draw_selection_shape(curr_sel_obj)
  4976. curr_sel_obj.selection_shape_drawn = True
  4977. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  4978. self.collection.on_objects_selection(False)
  4979. self.delete_selection_shape()
  4980. curr_sel_obj.selection_shape_drawn = False
  4981. self.collection.set_active(self.objects_under_the_click_list[0])
  4982. curr_sel_obj = self.collection.get_active()
  4983. # create the selection box around the selected object
  4984. if self.defaults['global_selection_shape'] is True:
  4985. self.draw_selection_shape(curr_sel_obj)
  4986. curr_sel_obj.selection_shape_drawn = True
  4987. self.selected_message(curr_sel_obj=curr_sel_obj)
  4988. elif curr_sel_obj.selection_shape_drawn is False:
  4989. if self.defaults['global_selection_shape'] is True:
  4990. self.draw_selection_shape(curr_sel_obj)
  4991. curr_sel_obj.selection_shape_drawn = True
  4992. else:
  4993. self.collection.on_objects_selection(False)
  4994. self.delete_selection_shape()
  4995. if self.call_source != 'app':
  4996. self.call_source = 'app'
  4997. self.selected_message(curr_sel_obj=curr_sel_obj)
  4998. else:
  4999. # If there is no selected object
  5000. # make active the first element of the overlapped objects list
  5001. if self.collection.get_active() is None:
  5002. self.collection.set_active(self.objects_under_the_click_list[0])
  5003. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5004. name_sel_obj = self.collection.get_active().options['name']
  5005. # In case that there is a selected object but it is not in the overlapped object list
  5006. # make that object inactive and activate the first element in the overlapped object list
  5007. if name_sel_obj not in self.objects_under_the_click_list:
  5008. self.collection.set_inactive(name_sel_obj)
  5009. name_sel_obj = self.objects_under_the_click_list[0]
  5010. self.collection.set_active(name_sel_obj)
  5011. else:
  5012. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5013. self.collection.set_all_inactive()
  5014. self.collection.set_active(
  5015. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5016. curr_sel_obj = self.collection.get_active()
  5017. # delete the possible selection box around a possible selected object
  5018. self.delete_selection_shape()
  5019. curr_sel_obj.selection_shape_drawn = False
  5020. # create the selection box around the selected object
  5021. if self.defaults['global_selection_shape'] is True:
  5022. self.draw_selection_shape(curr_sel_obj)
  5023. curr_sel_obj.selection_shape_drawn = True
  5024. self.selected_message(curr_sel_obj=curr_sel_obj)
  5025. else:
  5026. # deselect everything
  5027. self.collection.on_objects_selection(False)
  5028. # delete the possible selection box around a possible selected object
  5029. self.delete_selection_shape()
  5030. for o in self.collection.get_list():
  5031. o.selection_shape_drawn = False
  5032. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5033. # only when working on App
  5034. if self.call_source == 'app':
  5035. if self.click_noproject is False:
  5036. # if the Tool Tab is in focus don't change focus to Project Tab
  5037. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5038. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5039. else:
  5040. # restore auto open the Project Tab
  5041. self.click_noproject = False
  5042. # delete any text in the status bar, implicitly the last object name that was selected
  5043. # self.inform.emit("")
  5044. else:
  5045. self.call_source = 'app'
  5046. except Exception as e:
  5047. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5048. def selected_message(self, curr_sel_obj):
  5049. if curr_sel_obj:
  5050. if curr_sel_obj.kind == 'gerber':
  5051. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5052. color='green',
  5053. name=str(curr_sel_obj.options['name']),
  5054. tx=_("selected"))
  5055. )
  5056. elif curr_sel_obj.kind == 'excellon':
  5057. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5058. color='brown',
  5059. name=str(curr_sel_obj.options['name']),
  5060. tx=_("selected"))
  5061. )
  5062. elif curr_sel_obj.kind == 'cncjob':
  5063. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5064. color='blue',
  5065. name=str(curr_sel_obj.options['name']),
  5066. tx=_("selected"))
  5067. )
  5068. elif curr_sel_obj.kind == 'geometry':
  5069. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5070. color='red',
  5071. name=str(curr_sel_obj.options['name']),
  5072. tx=_("selected"))
  5073. )
  5074. def delete_hover_shape(self):
  5075. self.hover_shapes.clear()
  5076. self.hover_shapes.redraw()
  5077. def draw_hover_shape(self, sel_obj, color=None):
  5078. """
  5079. :param sel_obj: The object for which the hover shape must be drawn
  5080. :param color: The color of the hover shape
  5081. :return: None
  5082. """
  5083. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5084. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5085. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5086. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5087. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5088. if self.defaults['units'].upper() == 'MM':
  5089. hover_rect = hover_rect.buffer(-0.1)
  5090. hover_rect = hover_rect.buffer(0.2)
  5091. else:
  5092. hover_rect = hover_rect.buffer(-0.00393)
  5093. hover_rect = hover_rect.buffer(0.00787)
  5094. # if color:
  5095. # face = Color(color)
  5096. # face.alpha = 0.2
  5097. # outline = Color(color, alpha=0.8)
  5098. # else:
  5099. # face = Color(self.defaults['global_sel_fill'])
  5100. # face.alpha = 0.2
  5101. # outline = self.defaults['global_sel_line']
  5102. if color:
  5103. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5104. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5105. else:
  5106. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5107. outline = self.defaults['global_sel_line']
  5108. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5109. if self.is_legacy is True:
  5110. self.hover_shapes.redraw()
  5111. def delete_selection_shape(self):
  5112. self.move_tool.sel_shapes.clear()
  5113. self.move_tool.sel_shapes.redraw()
  5114. def draw_selection_shape(self, sel_obj, color=None):
  5115. """
  5116. Will draw a selection shape around the selected object.
  5117. :param sel_obj: The object for which the selection shape must be drawn
  5118. :param color: The color for the selection shape.
  5119. :return: None
  5120. """
  5121. if sel_obj is None:
  5122. return
  5123. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5124. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5125. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5126. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5127. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5128. if self.defaults['units'].upper() == 'MM':
  5129. sel_rect = sel_rect.buffer(-0.1)
  5130. sel_rect = sel_rect.buffer(0.2)
  5131. else:
  5132. sel_rect = sel_rect.buffer(-0.00393)
  5133. sel_rect = sel_rect.buffer(0.00787)
  5134. if color:
  5135. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5136. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5137. else:
  5138. if self.is_legacy is False:
  5139. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5140. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5141. else:
  5142. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5143. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5144. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5145. color=outline,
  5146. face_color=face,
  5147. update=True,
  5148. layer=0,
  5149. tolerance=None))
  5150. if self.is_legacy is True:
  5151. self.move_tool.sel_shapes.redraw()
  5152. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5153. """
  5154. Will draw a selection shape when dragging mouse on canvas.
  5155. :param old_coords: Old coordinates
  5156. :param coords: New coordinates
  5157. :param kwargs: Keyword arguments
  5158. :return:
  5159. """
  5160. if 'color' in kwargs:
  5161. color = kwargs['color']
  5162. else:
  5163. color = self.defaults['global_sel_line']
  5164. if 'face_color' in kwargs:
  5165. face_color = kwargs['face_color']
  5166. else:
  5167. face_color = self.defaults['global_sel_fill']
  5168. if 'face_alpha' in kwargs:
  5169. face_alpha = kwargs['face_alpha']
  5170. else:
  5171. face_alpha = 0.3
  5172. x0, y0 = old_coords
  5173. x1, y1 = coords
  5174. pt1 = (x0, y0)
  5175. pt2 = (x1, y0)
  5176. pt3 = (x1, y1)
  5177. pt4 = (x0, y1)
  5178. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5179. # color_t = Color(face_color)
  5180. # color_t.alpha = face_alpha
  5181. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5182. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5183. layer=0, tolerance=None)
  5184. if self.is_legacy is True:
  5185. self.move_tool.sel_shapes.redraw()
  5186. def on_file_new_click(self):
  5187. """
  5188. Callback for menu item File -> New.
  5189. Executed on clicking the Menu -> File -> New Project
  5190. :return:
  5191. """
  5192. if self.collection.get_list() and self.should_we_save:
  5193. msgbox = QtWidgets.QMessageBox()
  5194. # msgbox.setText("<B>Save changes ...</B>")
  5195. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5196. "Creating a New project will delete them.\n"
  5197. "Do you want to Save the project?"))
  5198. msgbox.setWindowTitle(_("Save changes"))
  5199. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5200. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5201. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5202. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5203. msgbox.setDefaultButton(bt_yes)
  5204. msgbox.exec_()
  5205. response = msgbox.clickedButton()
  5206. if response == bt_yes:
  5207. self.on_file_saveprojectas()
  5208. elif response == bt_cancel:
  5209. return
  5210. elif response == bt_no:
  5211. self.on_file_new()
  5212. else:
  5213. self.on_file_new()
  5214. self.inform.emit('[success] %s...' % _("New Project created"))
  5215. def on_file_new(self, cli=None):
  5216. """
  5217. Returns the application to its startup state. This method is thread-safe.
  5218. :param cli: Boolean. If True this method was run from command line
  5219. :return: None
  5220. """
  5221. self.defaults.report_usage("on_file_new")
  5222. # Remove everything from memory
  5223. App.log.debug("on_file_new()")
  5224. # close any editor that might be open
  5225. if self.call_source != 'app':
  5226. self.editor2object(cleanup=True)
  5227. # ## EDITOR section
  5228. self.geo_editor = FlatCAMGeoEditor(self)
  5229. self.exc_editor = FlatCAMExcEditor(self)
  5230. self.grb_editor = FlatCAMGrbEditor(self)
  5231. # Clear pool
  5232. self.clear_pool()
  5233. for obj in self.collection.get_list():
  5234. # delete shapes left drawn from mark shape_collections, if any
  5235. if isinstance(obj, GerberObject):
  5236. try:
  5237. for el in obj.mark_shapes:
  5238. obj.mark_shapes[el].clear(update=True)
  5239. obj.mark_shapes[el].enabled = False
  5240. del el
  5241. except AttributeError:
  5242. pass
  5243. # also delete annotation shapes, if any
  5244. elif isinstance(obj, CNCJobObject):
  5245. try:
  5246. obj.text_col.enabled = False
  5247. del obj.text_col
  5248. obj.annotation.clear(update=True)
  5249. del obj.annotation
  5250. except AttributeError:
  5251. pass
  5252. # delete the exclusion areas
  5253. self.exc_areas.clear_shapes()
  5254. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5255. self.shell.init_tcl()
  5256. # delete any selection shape on canvas
  5257. self.delete_selection_shape()
  5258. # delete all FlatCAM objects
  5259. self.collection.delete_all()
  5260. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5261. self.setup_component_editor()
  5262. # Clear project filename
  5263. self.project_filename = None
  5264. # Load the application defaults
  5265. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5266. # Re-fresh project options
  5267. self.on_options_app2project()
  5268. # Init FlatCAMTools
  5269. self.init_tools()
  5270. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5271. if cli is None:
  5272. # we need to go in reverse because once we remove a tab then the index changes
  5273. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5274. # and so on. Therefore the deletion should be done in reverse
  5275. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5276. for index in range(wdg_count, -1, -1):
  5277. try:
  5278. self.ui.plot_tab_area.closeTab(index)
  5279. except Exception as e:
  5280. log.debug("App.on_file_new() --> %s" % str(e))
  5281. # # And then add again the Plot Area
  5282. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5283. self.ui.plot_tab_area.protectTab(0)
  5284. # take the focus of the Notebook on Project Tab.
  5285. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5286. self.set_ui_title(name=_("New Project - Not saved"))
  5287. def obj_properties(self):
  5288. """
  5289. Will launch the object Properties Tool
  5290. :return:
  5291. """
  5292. self.defaults.report_usage("obj_properties()")
  5293. self.properties_tool.run(toggle=False)
  5294. def on_project_context_save(self):
  5295. """
  5296. Wrapper, will save the object function of it's type
  5297. :return:
  5298. """
  5299. obj = self.collection.get_active()
  5300. if type(obj) == GeometryObject:
  5301. self.on_file_exportdxf()
  5302. elif type(obj) == ExcellonObject:
  5303. self.on_file_saveexcellon()
  5304. elif type(obj) == CNCJobObject:
  5305. obj.on_exportgcode_button_click()
  5306. elif type(obj) == GerberObject:
  5307. self.on_file_savegerber()
  5308. elif type(obj) == ScriptObject:
  5309. self.on_file_savescript()
  5310. elif type(obj) == DocumentObject:
  5311. self.on_file_savedocument()
  5312. def obj_move(self):
  5313. """
  5314. Callback for the Move menu entry in various Context Menu's.
  5315. :return:
  5316. """
  5317. self.defaults.report_usage("obj_move()")
  5318. self.move_tool.run(toggle=False)
  5319. def on_fileopengerber(self, signal, name=None):
  5320. """
  5321. File menu callback for opening a Gerber.
  5322. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5323. :param name:
  5324. :return: None
  5325. """
  5326. self.defaults.report_usage("on_fileopengerber")
  5327. App.log.debug("on_fileopengerber()")
  5328. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5329. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5330. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5331. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5332. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5333. "*.mil);;" \
  5334. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5335. "Allegro Files (*.art);;" \
  5336. "Mentor Files (*.pho *.gdo);;" \
  5337. "All Files (*.*)"
  5338. if name is None:
  5339. try:
  5340. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5341. directory=self.get_last_folder(),
  5342. filter=_filter_)
  5343. except TypeError:
  5344. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5345. filenames = [str(filename) for filename in filenames]
  5346. else:
  5347. filenames = [name]
  5348. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5349. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5350. _("Opening Gerber file.")),
  5351. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5352. color=QtGui.QColor("gray"))
  5353. if len(filenames) == 0:
  5354. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5355. else:
  5356. for filename in filenames:
  5357. if filename != '':
  5358. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5359. def on_fileopenexcellon(self, signal, name=None):
  5360. """
  5361. File menu callback for opening an Excellon file.
  5362. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5363. :param name:
  5364. :return: None
  5365. """
  5366. self.defaults.report_usage("on_fileopenexcellon")
  5367. App.log.debug("on_fileopenexcellon()")
  5368. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5369. "All Files (*.*)"
  5370. if name is None:
  5371. try:
  5372. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5373. directory=self.get_last_folder(),
  5374. filter=_filter_)
  5375. except TypeError:
  5376. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5377. filenames = [str(filename) for filename in filenames]
  5378. else:
  5379. filenames = [str(name)]
  5380. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5381. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5382. _("Opening Excellon file.")),
  5383. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5384. color=QtGui.QColor("gray"))
  5385. if len(filenames) == 0:
  5386. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5387. else:
  5388. for filename in filenames:
  5389. if filename != '':
  5390. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5391. def on_fileopengcode(self, signal, name=None):
  5392. """
  5393. File menu call back for opening gcode.
  5394. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5395. :param name:
  5396. :return:
  5397. """
  5398. self.defaults.report_usage("on_fileopengcode")
  5399. App.log.debug("on_fileopengcode()")
  5400. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5401. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5402. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5403. "All Files (*.*)"
  5404. if name is None:
  5405. try:
  5406. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5407. directory=self.get_last_folder(),
  5408. filter=_filter_)
  5409. except TypeError:
  5410. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5411. filenames = [str(filename) for filename in filenames]
  5412. else:
  5413. filenames = [name]
  5414. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5415. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5416. _("Opening G-Code file.")),
  5417. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5418. color=QtGui.QColor("gray"))
  5419. if len(filenames) == 0:
  5420. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5421. else:
  5422. for filename in filenames:
  5423. if filename != '':
  5424. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5425. def on_file_openproject(self, signal):
  5426. """
  5427. File menu callback for opening a project.
  5428. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5429. :return: None
  5430. """
  5431. self.defaults.report_usage("on_file_openproject")
  5432. App.log.debug("on_file_openproject()")
  5433. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5434. try:
  5435. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5436. directory=self.get_last_folder(), filter=_filter_)
  5437. except TypeError:
  5438. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5439. # The Qt methods above will return a QString which can cause problems later.
  5440. # So far json.dump() will fail to serialize it.
  5441. # TODO: Improve the serialization methods and remove this fix.
  5442. filename = str(filename)
  5443. if filename == "":
  5444. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5445. else:
  5446. # self.worker_task.emit({'fcn': self.open_project,
  5447. # 'params': [filename]})
  5448. # The above was failing because open_project() is not
  5449. # thread safe. The new_project()
  5450. self.open_project(filename)
  5451. def on_fileopenhpgl2(self, signal, name=None):
  5452. """
  5453. File menu callback for opening a HPGL2.
  5454. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5455. :param name:
  5456. :return: None
  5457. """
  5458. self.defaults.report_usage("on_fileopenhpgl2")
  5459. App.log.debug("on_fileopenhpgl2()")
  5460. _filter_ = "HPGL2 Files (*.plt);;" \
  5461. "All Files (*.*)"
  5462. if name is None:
  5463. try:
  5464. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5465. directory=self.get_last_folder(),
  5466. filter=_filter_)
  5467. except TypeError:
  5468. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5469. filenames = [str(filename) for filename in filenames]
  5470. else:
  5471. filenames = [name]
  5472. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5473. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5474. _("Opening HPGL2 file.")),
  5475. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5476. color=QtGui.QColor("gray"))
  5477. if len(filenames) == 0:
  5478. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5479. else:
  5480. for filename in filenames:
  5481. if filename != '':
  5482. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5483. def on_file_openconfig(self, signal):
  5484. """
  5485. File menu callback for opening a config file.
  5486. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5487. :return: None
  5488. """
  5489. self.defaults.report_usage("on_file_openconfig")
  5490. App.log.debug("on_file_openconfig()")
  5491. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5492. try:
  5493. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5494. directory=self.data_path, filter=_filter_)
  5495. except TypeError:
  5496. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5497. filter=_filter_)
  5498. if filename == "":
  5499. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5500. else:
  5501. self.open_config_file(filename)
  5502. def on_file_exportsvg(self):
  5503. """
  5504. Callback for menu item File->Export SVG.
  5505. :return: None
  5506. """
  5507. self.defaults.report_usage("on_file_exportsvg")
  5508. App.log.debug("on_file_exportsvg()")
  5509. obj = self.collection.get_active()
  5510. if obj is None:
  5511. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5512. msg = _("Please Select a Geometry object to export")
  5513. msgbox = QtWidgets.QMessageBox()
  5514. msgbox.setInformativeText(msg)
  5515. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5516. msgbox.setDefaultButton(bt_ok)
  5517. msgbox.exec_()
  5518. return
  5519. # Check for more compatible types and add as required
  5520. if (not isinstance(obj, GeometryObject)
  5521. and not isinstance(obj, GerberObject)
  5522. and not isinstance(obj, CNCJobObject)
  5523. and not isinstance(obj, ExcellonObject)):
  5524. msg = '[ERROR_NOTCL] %s' % \
  5525. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5526. msgbox = QtWidgets.QMessageBox()
  5527. msgbox.setInformativeText(msg)
  5528. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5529. msgbox.setDefaultButton(bt_ok)
  5530. msgbox.exec_()
  5531. return
  5532. name = obj.options["name"]
  5533. _filter = "SVG File (*.svg);;All Files (*.*)"
  5534. try:
  5535. filename, _f = FCFileSaveDialog.get_saved_filename(
  5536. caption=_("Export SVG"),
  5537. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5538. filter=_filter)
  5539. except TypeError:
  5540. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5541. filename = str(filename)
  5542. if filename == "":
  5543. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5544. return
  5545. else:
  5546. self.export_svg(name, filename)
  5547. if self.defaults["global_open_style"] is False:
  5548. self.file_opened.emit("SVG", filename)
  5549. self.file_saved.emit("SVG", filename)
  5550. def on_file_exportpng(self):
  5551. self.defaults.report_usage("on_file_exportpng")
  5552. App.log.debug("on_file_exportpng()")
  5553. self.date = str(datetime.today()).rpartition('.')[0]
  5554. self.date = ''.join(c for c in self.date if c not in ':-')
  5555. self.date = self.date.replace(' ', '_')
  5556. if self.is_legacy is False:
  5557. image = _screenshot()
  5558. data = np.asarray(image)
  5559. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5560. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5561. return
  5562. filter_ = "PNG File (*.png);;All Files (*.*)"
  5563. try:
  5564. filename, _f = FCFileSaveDialog.get_saved_filename(
  5565. caption=_("Export PNG Image"),
  5566. directory=self.get_last_save_folder() + '/png_' + self.date,
  5567. filter=filter_)
  5568. except TypeError:
  5569. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5570. filename = str(filename)
  5571. if filename == "":
  5572. self.inform.emit(_("Cancelled."))
  5573. return
  5574. else:
  5575. if self.is_legacy is False:
  5576. write_png(filename, data)
  5577. else:
  5578. self.plotcanvas.figure.savefig(filename)
  5579. if self.defaults["global_open_style"] is False:
  5580. self.file_opened.emit("png", filename)
  5581. self.file_saved.emit("png", filename)
  5582. def on_file_savegerber(self):
  5583. """
  5584. Callback for menu item in Project context menu.
  5585. :return: None
  5586. """
  5587. self.defaults.report_usage("on_file_savegerber")
  5588. App.log.debug("on_file_savegerber()")
  5589. obj = self.collection.get_active()
  5590. if obj is None:
  5591. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5592. return
  5593. # Check for more compatible types and add as required
  5594. if not isinstance(obj, GerberObject):
  5595. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5596. return
  5597. name = self.collection.get_active().options["name"]
  5598. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5599. try:
  5600. filename, _f = FCFileSaveDialog.get_saved_filename(
  5601. caption="Save Gerber source file",
  5602. directory=self.get_last_save_folder() + '/' + name,
  5603. filter=_filter)
  5604. except TypeError:
  5605. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5606. filename = str(filename)
  5607. if filename == "":
  5608. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5609. return
  5610. else:
  5611. self.save_source_file(name, filename)
  5612. if self.defaults["global_open_style"] is False:
  5613. self.file_opened.emit("Gerber", filename)
  5614. self.file_saved.emit("Gerber", filename)
  5615. def on_file_savescript(self):
  5616. """
  5617. Callback for menu item in Project context menu.
  5618. :return: None
  5619. """
  5620. self.defaults.report_usage("on_file_savescript")
  5621. App.log.debug("on_file_savescript()")
  5622. obj = self.collection.get_active()
  5623. if obj is None:
  5624. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5625. return
  5626. # Check for more compatible types and add as required
  5627. if not isinstance(obj, ScriptObject):
  5628. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5629. return
  5630. name = self.collection.get_active().options["name"]
  5631. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5632. try:
  5633. filename, _f = FCFileSaveDialog.get_saved_filename(
  5634. caption="Save Script source file",
  5635. directory=self.get_last_save_folder() + '/' + name,
  5636. filter=_filter)
  5637. except TypeError:
  5638. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5639. filename = str(filename)
  5640. if filename == "":
  5641. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5642. return
  5643. else:
  5644. self.save_source_file(name, filename)
  5645. if self.defaults["global_open_style"] is False:
  5646. self.file_opened.emit("Script", filename)
  5647. self.file_saved.emit("Script", filename)
  5648. def on_file_savedocument(self):
  5649. """
  5650. Callback for menu item in Project context menu.
  5651. :return: None
  5652. """
  5653. self.defaults.report_usage("on_file_savedocument")
  5654. App.log.debug("on_file_savedocument()")
  5655. obj = self.collection.get_active()
  5656. if obj is None:
  5657. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5658. return
  5659. # Check for more compatible types and add as required
  5660. if not isinstance(obj, ScriptObject):
  5661. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5662. return
  5663. name = self.collection.get_active().options["name"]
  5664. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5665. try:
  5666. filename, _f = FCFileSaveDialog.get_saved_filename(
  5667. caption="Save Document source file",
  5668. directory=self.get_last_save_folder() + '/' + name,
  5669. filter=_filter)
  5670. except TypeError:
  5671. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5672. filename = str(filename)
  5673. if filename == "":
  5674. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5675. return
  5676. else:
  5677. self.save_source_file(name, filename)
  5678. if self.defaults["global_open_style"] is False:
  5679. self.file_opened.emit("Document", filename)
  5680. self.file_saved.emit("Document", filename)
  5681. def on_file_saveexcellon(self):
  5682. """
  5683. Callback for menu item in project context menu.
  5684. :return: None
  5685. """
  5686. self.defaults.report_usage("on_file_saveexcellon")
  5687. App.log.debug("on_file_saveexcellon()")
  5688. obj = self.collection.get_active()
  5689. if obj is None:
  5690. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5691. return
  5692. # Check for more compatible types and add as required
  5693. if not isinstance(obj, ExcellonObject):
  5694. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5695. return
  5696. name = self.collection.get_active().options["name"]
  5697. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5698. try:
  5699. filename, _f = FCFileSaveDialog.get_saved_filename(
  5700. caption=_("Save Excellon source file"),
  5701. directory=self.get_last_save_folder() + '/' + name,
  5702. filter=_filter)
  5703. except TypeError:
  5704. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5705. filename = str(filename)
  5706. if filename == "":
  5707. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5708. return
  5709. else:
  5710. self.save_source_file(name, filename)
  5711. if self.defaults["global_open_style"] is False:
  5712. self.file_opened.emit("Excellon", filename)
  5713. self.file_saved.emit("Excellon", filename)
  5714. def on_file_exportexcellon(self):
  5715. """
  5716. Callback for menu item File->Export->Excellon.
  5717. :return: None
  5718. """
  5719. self.defaults.report_usage("on_file_exportexcellon")
  5720. App.log.debug("on_file_exportexcellon()")
  5721. obj = self.collection.get_active()
  5722. if obj is None:
  5723. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5724. return
  5725. # Check for more compatible types and add as required
  5726. if not isinstance(obj, ExcellonObject):
  5727. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5728. return
  5729. name = self.collection.get_active().options["name"]
  5730. _filter = self.defaults["excellon_save_filters"]
  5731. try:
  5732. filename, _f = FCFileSaveDialog.get_saved_filename(
  5733. caption=_("Export Excellon"),
  5734. directory=self.get_last_save_folder() + '/' + name,
  5735. filter=_filter)
  5736. except TypeError:
  5737. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5738. filename = str(filename)
  5739. if filename == "":
  5740. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5741. return
  5742. else:
  5743. used_extension = filename.rpartition('.')[2]
  5744. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5745. self.export_excellon(name, filename)
  5746. if self.defaults["global_open_style"] is False:
  5747. self.file_opened.emit("Excellon", filename)
  5748. self.file_saved.emit("Excellon", filename)
  5749. def on_file_exportgerber(self):
  5750. """
  5751. Callback for menu item File->Export->Gerber.
  5752. :return: None
  5753. """
  5754. self.defaults.report_usage("on_file_exportgerber")
  5755. App.log.debug("on_file_exportgerber()")
  5756. obj = self.collection.get_active()
  5757. if obj is None:
  5758. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5759. return
  5760. # Check for more compatible types and add as required
  5761. if not isinstance(obj, GerberObject):
  5762. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5763. return
  5764. name = self.collection.get_active().options["name"]
  5765. _filter_ = self.defaults['gerber_save_filters']
  5766. try:
  5767. filename, _f = FCFileSaveDialog.get_saved_filename(
  5768. caption=_("Export Gerber"),
  5769. directory=self.get_last_save_folder() + '/' + name,
  5770. filter=_filter_)
  5771. except TypeError:
  5772. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5773. filename = str(filename)
  5774. if filename == "":
  5775. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5776. return
  5777. else:
  5778. used_extension = filename.rpartition('.')[2]
  5779. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5780. self.export_gerber(name, filename)
  5781. if self.defaults["global_open_style"] is False:
  5782. self.file_opened.emit("Gerber", filename)
  5783. self.file_saved.emit("Gerber", filename)
  5784. def on_file_exportdxf(self):
  5785. """
  5786. Callback for menu item File->Export DXF.
  5787. :return: None
  5788. """
  5789. self.defaults.report_usage("on_file_exportdxf")
  5790. App.log.debug("on_file_exportdxf()")
  5791. obj = self.collection.get_active()
  5792. if obj is None:
  5793. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5794. msg = _("Please Select a Geometry object to export")
  5795. msgbox = QtWidgets.QMessageBox()
  5796. msgbox.setInformativeText(msg)
  5797. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5798. msgbox.setDefaultButton(bt_ok)
  5799. msgbox.exec_()
  5800. return
  5801. # Check for more compatible types and add as required
  5802. if not isinstance(obj, GeometryObject):
  5803. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5804. msgbox = QtWidgets.QMessageBox()
  5805. msgbox.setInformativeText(msg)
  5806. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5807. msgbox.setDefaultButton(bt_ok)
  5808. msgbox.exec_()
  5809. return
  5810. name = self.collection.get_active().options["name"]
  5811. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5812. try:
  5813. filename, _f = FCFileSaveDialog.get_saved_filename(
  5814. caption=_("Export DXF"),
  5815. directory=self.get_last_save_folder() + '/' + name,
  5816. filter=_filter_)
  5817. except TypeError:
  5818. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  5819. filename = str(filename)
  5820. if filename == "":
  5821. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5822. return
  5823. else:
  5824. self.export_dxf(name, filename)
  5825. if self.defaults["global_open_style"] is False:
  5826. self.file_opened.emit("DXF", filename)
  5827. self.file_saved.emit("DXF", filename)
  5828. def on_file_importsvg(self, type_of_obj):
  5829. """
  5830. Callback for menu item File->Import SVG.
  5831. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5832. :type type_of_obj: str
  5833. :return: None
  5834. """
  5835. self.defaults.report_usage("on_file_importsvg")
  5836. App.log.debug("on_file_importsvg()")
  5837. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5838. try:
  5839. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5840. directory=self.get_last_folder(), filter=_filter_)
  5841. except TypeError:
  5842. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5843. filter=_filter_)
  5844. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5845. type_of_obj = "geometry"
  5846. filenames = [str(filename) for filename in filenames]
  5847. if len(filenames) == 0:
  5848. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5849. else:
  5850. for filename in filenames:
  5851. if filename != '':
  5852. self.worker_task.emit({'fcn': self.import_svg,
  5853. 'params': [filename, type_of_obj]})
  5854. def on_file_importdxf(self, type_of_obj):
  5855. """
  5856. Callback for menu item File->Import DXF.
  5857. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5858. :type type_of_obj: str
  5859. :return: None
  5860. """
  5861. self.defaults.report_usage("on_file_importdxf")
  5862. App.log.debug("on_file_importdxf()")
  5863. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5864. try:
  5865. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5866. directory=self.get_last_folder(),
  5867. filter=_filter_)
  5868. except TypeError:
  5869. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5870. filter=_filter_)
  5871. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5872. type_of_obj = "geometry"
  5873. filenames = [str(filename) for filename in filenames]
  5874. if len(filenames) == 0:
  5875. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5876. else:
  5877. for filename in filenames:
  5878. if filename != '':
  5879. self.worker_task.emit({'fcn': self.import_dxf,
  5880. 'params': [filename, type_of_obj]})
  5881. # ###############################################################################################################
  5882. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5883. # ###############################################################################################################
  5884. def init_code_editor(self, name):
  5885. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5886. # add the tab if it was closed
  5887. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5888. self.text_editor_tab.setObjectName('text_editor_tab')
  5889. # delete the absolute and relative position and messages in the infobar
  5890. self.ui.position_label.setText("")
  5891. # self.ui.rel_position_label.setText("")
  5892. # first clear previous text in text editor (if any)
  5893. self.text_editor_tab.code_editor.clear()
  5894. self.text_editor_tab.code_editor.setReadOnly(False)
  5895. self.toggle_codeeditor = True
  5896. self.text_editor_tab.code_editor.completer_enable = False
  5897. self.text_editor_tab.buttonRun.hide()
  5898. # make sure to keep a reference to the code editor
  5899. self.reference_code_editor = self.text_editor_tab.code_editor
  5900. # Switch plot_area to CNCJob tab
  5901. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5902. def on_view_source(self):
  5903. """
  5904. Called when the user wants to see the source file of the selected object
  5905. :return:
  5906. """
  5907. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5908. self.proc_container.view.set_busy(_("Loading..."))
  5909. try:
  5910. obj = self.collection.get_active()
  5911. except Exception as e:
  5912. log.debug("App.on_view_source() --> %s" % str(e))
  5913. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5914. return 'fail'
  5915. if obj is None:
  5916. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5917. return 'fail'
  5918. flt = "All Files (*.*)"
  5919. if obj.kind == 'gerber':
  5920. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5921. elif obj.kind == 'excellon':
  5922. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5923. elif obj.kind == 'cncjob':
  5924. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5925. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  5926. # add the tab if it was closed
  5927. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5928. self.source_editor_tab.setObjectName('source_editor_tab')
  5929. # delete the absolute and relative position and messages in the infobar
  5930. self.ui.position_label.setText("")
  5931. # self.ui.rel_position_label.setText("")
  5932. # first clear previous text in text editor (if any)
  5933. self.source_editor_tab.code_editor.clear()
  5934. self.source_editor_tab.code_editor.setReadOnly(False)
  5935. self.source_editor_tab.code_editor.completer_enable = False
  5936. self.source_editor_tab.buttonRun.hide()
  5937. # Switch plot_area to CNCJob tab
  5938. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5939. try:
  5940. self.source_editor_tab.buttonOpen.clicked.disconnect()
  5941. except TypeError:
  5942. pass
  5943. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  5944. try:
  5945. self.source_editor_tab.buttonSave.clicked.disconnect()
  5946. except TypeError:
  5947. pass
  5948. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  5949. # then append the text from GCode to the text editor
  5950. if obj.kind == 'cncjob':
  5951. try:
  5952. file = obj.export_gcode(
  5953. preamble=self.defaults["cncjob_prepend"],
  5954. postamble=self.defaults["cncjob_append"],
  5955. to_file=True)
  5956. if file == 'fail':
  5957. return 'fail'
  5958. except AttributeError:
  5959. self.inform.emit('[WARNING_NOTCL] %s' %
  5960. _("There is no selected object for which to see it's source file code."))
  5961. return 'fail'
  5962. else:
  5963. try:
  5964. file = StringIO(obj.source_file)
  5965. except (AttributeError, TypeError):
  5966. self.inform.emit('[WARNING_NOTCL] %s' %
  5967. _("There is no selected object for which to see it's source file code."))
  5968. return 'fail'
  5969. self.source_editor_tab.t_frame.hide()
  5970. try:
  5971. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  5972. # for line in file:
  5973. # QtWidgets.QApplication.processEvents()
  5974. # proc_line = str(line).strip('\n')
  5975. # self.source_editor_tab.code_editor.append(proc_line)
  5976. except Exception as e:
  5977. log.debug('App.on_view_source() -->%s' % str(e))
  5978. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  5979. return
  5980. self.source_editor_tab.handleTextChanged()
  5981. self.source_editor_tab.t_frame.show()
  5982. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5983. self.proc_container.view.set_idle()
  5984. # self.ui.show()
  5985. def on_toggle_code_editor(self):
  5986. self.defaults.report_usage("on_toggle_code_editor()")
  5987. if self.toggle_codeeditor is False:
  5988. self.init_code_editor(name=_("Code Editor"))
  5989. self.text_editor_tab.buttonOpen.clicked.disconnect()
  5990. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  5991. self.text_editor_tab.buttonSave.clicked.disconnect()
  5992. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  5993. else:
  5994. for idx in range(self.ui.plot_tab_area.count()):
  5995. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  5996. self.ui.plot_tab_area.closeTab(idx)
  5997. break
  5998. self.toggle_codeeditor = False
  5999. def on_code_editor_close(self):
  6000. self.toggle_codeeditor = False
  6001. def goto_text_line(self):
  6002. """
  6003. Will scroll a text to the specified text line.
  6004. :return: None
  6005. """
  6006. dia_box = Dialog_box(title=_("Go to Line ..."),
  6007. label=_("Line:"),
  6008. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6009. initial_text='')
  6010. try:
  6011. line = int(dia_box.location) - 1
  6012. except (ValueError, TypeError):
  6013. line = 0
  6014. if dia_box.ok:
  6015. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6016. # at the top of the window
  6017. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6018. # get the document() of the TextEditor
  6019. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6020. # create a Text Cursor based on the searched line
  6021. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6022. # set cursor of the code editor with the cursor at the searcehd line
  6023. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6024. def on_filenewscript(self, silent=False):
  6025. """
  6026. Will create a new script file and open it in the Code Editor
  6027. :param silent: if True will not display status messages
  6028. :return: None
  6029. """
  6030. if silent is False:
  6031. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6032. # delete the absolute and relative position and messages in the infobar
  6033. self.ui.position_label.setText("")
  6034. # self.ui.rel_position_label.setText("")
  6035. self.app_obj.new_script_object()
  6036. # script_text = script_obj.source_file
  6037. #
  6038. # self.proc_container.view.set_busy(_("Loading..."))
  6039. # script_obj.script_editor_tab.t_frame.hide()
  6040. #
  6041. # script_obj.script_editor_tab.t_frame.show()
  6042. # self.proc_container.view.set_idle()
  6043. def on_fileopenscript(self, name=None, silent=False):
  6044. """
  6045. Will open a Tcl script file into the Code Editor
  6046. :param silent: if True will not display status messages
  6047. :param name: name of a Tcl script file to open
  6048. :return: None
  6049. """
  6050. self.defaults.report_usage("on_fileopenscript")
  6051. App.log.debug("on_fileopenscript()")
  6052. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6053. "All Files (*.*)"
  6054. if name:
  6055. filenames = [name]
  6056. else:
  6057. try:
  6058. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6059. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6060. except TypeError:
  6061. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6062. if len(filenames) == 0:
  6063. if silent is False:
  6064. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6065. else:
  6066. for filename in filenames:
  6067. if filename != '':
  6068. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6069. def on_fileopenscript_example(self, name=None, silent=False):
  6070. """
  6071. Will open a Tcl script file into the Code Editor
  6072. :param silent: if True will not display status messages
  6073. :param name: name of a Tcl script file to open
  6074. :return:
  6075. """
  6076. self.defaults.report_usage("on_fileopenscript_example")
  6077. log.debug("on_fileopenscript_example()")
  6078. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6079. "All Files (*.*)"
  6080. # test if the app was frozen and choose the path for the configuration file
  6081. if getattr(sys, "frozen", False) is True:
  6082. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6083. else:
  6084. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6085. if name:
  6086. filenames = [name]
  6087. else:
  6088. try:
  6089. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6090. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6091. except TypeError:
  6092. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6093. if len(filenames) == 0:
  6094. if silent is False:
  6095. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6096. else:
  6097. for filename in filenames:
  6098. if filename != '':
  6099. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6100. def on_filerunscript(self, name=None, silent=False):
  6101. """
  6102. File menu callback for loading and running a TCL script.
  6103. :param silent: if True will not display status messages
  6104. :param name: name of a Tcl script file to be run by FlatCAM
  6105. :return: None
  6106. """
  6107. self.defaults.report_usage("on_filerunscript")
  6108. App.log.debug("on_file_runscript()")
  6109. if name:
  6110. filename = name
  6111. if self.cmd_line_headless != 1:
  6112. self.splash.showMessage('%s: %ssec\n%s' %
  6113. (_("Canvas initialization started.\n"
  6114. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6115. _("Executing ScriptObject file.")
  6116. ),
  6117. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6118. color=QtGui.QColor("gray"))
  6119. else:
  6120. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6121. "All Files (*.*)"
  6122. try:
  6123. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6124. directory=self.get_last_folder(), filter=_filter_)
  6125. except TypeError:
  6126. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6127. # The Qt methods above will return a QString which can cause problems later.
  6128. # So far json.dump() will fail to serialize it.
  6129. filename = str(filename)
  6130. if filename == "":
  6131. if silent is False:
  6132. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6133. else:
  6134. if self.cmd_line_headless != 1:
  6135. if self.ui.shell_dock.isHidden():
  6136. self.ui.shell_dock.show()
  6137. try:
  6138. with open(filename, "r") as tcl_script:
  6139. cmd_line_shellfile_content = tcl_script.read()
  6140. if self.cmd_line_headless != 1:
  6141. self.shell.exec_command(cmd_line_shellfile_content)
  6142. else:
  6143. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6144. if silent is False:
  6145. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6146. except Exception as e:
  6147. log.debug("App.on_filerunscript() -> %s" % str(e))
  6148. sys.exit(2)
  6149. def on_file_saveproject(self, silent=False):
  6150. """
  6151. Callback for menu item File->Save Project. Saves the project to
  6152. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6153. if set to None. The project is saved by calling ``self.save_project()``.
  6154. :param silent: if True will not display status messages
  6155. :return: None
  6156. """
  6157. self.defaults.report_usage("on_file_saveproject")
  6158. if self.project_filename is None:
  6159. self.on_file_saveprojectas()
  6160. else:
  6161. self.worker_task.emit({'fcn': self.save_project,
  6162. 'params': [self.project_filename, silent]})
  6163. if self.defaults["global_open_style"] is False:
  6164. self.file_opened.emit("project", self.project_filename)
  6165. self.file_saved.emit("project", self.project_filename)
  6166. self.set_ui_title(name=self.project_filename)
  6167. self.should_we_save = False
  6168. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6169. """
  6170. Callback for menu item File->Save Project As... Opens a file
  6171. chooser and saves the project to the given file via
  6172. ``self.save_project()``.
  6173. :param make_copy if to be create a copy of the project; boolean
  6174. :param use_thread: if to be run in a separate thread; boolean
  6175. :param quit_action: if to be followed by quiting the application; boolean
  6176. :return: None
  6177. """
  6178. self.defaults.report_usage("on_file_saveprojectas")
  6179. self.date = str(datetime.today()).rpartition('.')[0]
  6180. self.date = ''.join(c for c in self.date if c not in ':-')
  6181. self.date = self.date.replace(' ', '_')
  6182. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6183. try:
  6184. filename, _f = FCFileSaveDialog.get_saved_filename(
  6185. caption=_("Save Project As ..."),
  6186. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6187. proj=_("Project")),
  6188. filter=filter_
  6189. )
  6190. except TypeError:
  6191. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6192. filename = str(filename)
  6193. if filename == '':
  6194. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6195. return
  6196. if use_thread is True:
  6197. self.worker_task.emit({'fcn': self.save_project,
  6198. 'params': [filename, quit_action]})
  6199. else:
  6200. self.save_project(filename, quit_action)
  6201. # self.save_project(filename)
  6202. if self.defaults["global_open_style"] is False:
  6203. self.file_opened.emit("project", filename)
  6204. self.file_saved.emit("project", filename)
  6205. if not make_copy:
  6206. self.project_filename = filename
  6207. self.set_ui_title(name=self.project_filename)
  6208. self.should_we_save = False
  6209. def on_file_save_objects_pdf(self, use_thread=True):
  6210. self.date = str(datetime.today()).rpartition('.')[0]
  6211. self.date = ''.join(c for c in self.date if c not in ':-')
  6212. self.date = self.date.replace(' ', '_')
  6213. try:
  6214. obj_selection = self.collection.get_selected()
  6215. if len(obj_selection) == 1:
  6216. obj_name = str(obj_selection[0].options['name'])
  6217. else:
  6218. obj_name = _("FlatCAM objects print")
  6219. except AttributeError as err:
  6220. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6221. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6222. return
  6223. if not obj_selection:
  6224. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6225. return
  6226. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6227. try:
  6228. filename, _f = FCFileSaveDialog.get_saved_filename(
  6229. caption=_("Save Object as PDF ..."),
  6230. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6231. obj_name=obj_name,
  6232. date=self.date),
  6233. filter=filter_
  6234. )
  6235. except TypeError:
  6236. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6237. filename = str(filename)
  6238. if filename == '':
  6239. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6240. return
  6241. if use_thread is True:
  6242. self.proc_container.new(_("Printing PDF ... Please wait."))
  6243. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6244. else:
  6245. self.save_pdf(filename, obj_selection)
  6246. # self.save_project(filename)
  6247. if self.defaults["global_open_style"] is False:
  6248. self.file_opened.emit("pdf", filename)
  6249. self.file_saved.emit("pdf", filename)
  6250. def save_pdf(self, file_name, obj_selection):
  6251. p_size = self.defaults['global_workspaceT']
  6252. orientation = self.defaults['global_workspace_orientation']
  6253. color = 'black'
  6254. transparency_level = 1.0
  6255. self.pagesize = {}
  6256. self.pagesize.update(
  6257. {
  6258. 'Bounds': None,
  6259. 'A0': (841 * mm, 1189 * mm),
  6260. 'A1': (594 * mm, 841 * mm),
  6261. 'A2': (420 * mm, 594 * mm),
  6262. 'A3': (297 * mm, 420 * mm),
  6263. 'A4': (210 * mm, 297 * mm),
  6264. 'A5': (148 * mm, 210 * mm),
  6265. 'A6': (105 * mm, 148 * mm),
  6266. 'A7': (74 * mm, 105 * mm),
  6267. 'A8': (52 * mm, 74 * mm),
  6268. 'A9': (37 * mm, 52 * mm),
  6269. 'A10': (26 * mm, 37 * mm),
  6270. 'B0': (1000 * mm, 1414 * mm),
  6271. 'B1': (707 * mm, 1000 * mm),
  6272. 'B2': (500 * mm, 707 * mm),
  6273. 'B3': (353 * mm, 500 * mm),
  6274. 'B4': (250 * mm, 353 * mm),
  6275. 'B5': (176 * mm, 250 * mm),
  6276. 'B6': (125 * mm, 176 * mm),
  6277. 'B7': (88 * mm, 125 * mm),
  6278. 'B8': (62 * mm, 88 * mm),
  6279. 'B9': (44 * mm, 62 * mm),
  6280. 'B10': (31 * mm, 44 * mm),
  6281. 'C0': (917 * mm, 1297 * mm),
  6282. 'C1': (648 * mm, 917 * mm),
  6283. 'C2': (458 * mm, 648 * mm),
  6284. 'C3': (324 * mm, 458 * mm),
  6285. 'C4': (229 * mm, 324 * mm),
  6286. 'C5': (162 * mm, 229 * mm),
  6287. 'C6': (114 * mm, 162 * mm),
  6288. 'C7': (81 * mm, 114 * mm),
  6289. 'C8': (57 * mm, 81 * mm),
  6290. 'C9': (40 * mm, 57 * mm),
  6291. 'C10': (28 * mm, 40 * mm),
  6292. # American paper sizes
  6293. 'LETTER': (8.5 * inch, 11 * inch),
  6294. 'LEGAL': (8.5 * inch, 14 * inch),
  6295. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6296. # From https://en.wikipedia.org/wiki/Paper_size
  6297. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6298. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6299. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6300. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6301. 'LEDGER': (17 * inch, 11 * inch),
  6302. }
  6303. )
  6304. exported_svg = []
  6305. for obj in obj_selection:
  6306. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6307. scale_factor_x=None, scale_factor_y=None,
  6308. skew_factor_x=None, skew_factor_y=None,
  6309. mirror=None)
  6310. if obj.kind.lower() == 'gerber':
  6311. # color = self.defaults["gerber_plot_fill"][:-2]
  6312. color = obj.fill_color[:-2]
  6313. elif obj.kind.lower() == 'excellon':
  6314. color = '#C40000'
  6315. elif obj.kind.lower() == 'geometry':
  6316. color = self.defaults["global_draw_color"]
  6317. # Change the attributes of the exported SVG
  6318. # We don't need stroke-width
  6319. # We set opacity to maximum
  6320. # We set the colour to WHITE
  6321. root = ET.fromstring(svg_obj)
  6322. for child in root:
  6323. child.set('fill', str(color))
  6324. child.set('opacity', str(transparency_level))
  6325. child.set('stroke', str(color))
  6326. exported_svg.append(ET.tostring(root))
  6327. xmin = Inf
  6328. ymin = Inf
  6329. xmax = -Inf
  6330. ymax = -Inf
  6331. for obj in obj_selection:
  6332. try:
  6333. gxmin, gymin, gxmax, gymax = obj.bounds()
  6334. xmin = min([xmin, gxmin])
  6335. ymin = min([ymin, gymin])
  6336. xmax = max([xmax, gxmax])
  6337. ymax = max([ymax, gymax])
  6338. except Exception as e:
  6339. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6340. # Determine bounding area for svg export
  6341. bounds = [xmin, ymin, xmax, ymax]
  6342. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6343. # This contain the measure units
  6344. uom = obj_selection[0].units.lower()
  6345. # Define a boundary around SVG of about 1.0mm (~39mils)
  6346. if uom in "mm":
  6347. boundary = 1.0
  6348. else:
  6349. boundary = 0.0393701
  6350. # Convert everything to strings for use in the xml doc
  6351. svgwidth = str(size[0] + (2 * boundary))
  6352. svgheight = str(size[1] + (2 * boundary))
  6353. minx = str(bounds[0] - boundary)
  6354. miny = str(bounds[1] + boundary + size[1])
  6355. # Add a SVG Header and footer to the svg output from shapely
  6356. # The transform flips the Y Axis so that everything renders
  6357. # properly within svg apps such as inkscape
  6358. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6359. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6360. svg_header += 'width="' + svgwidth + uom + '" '
  6361. svg_header += 'height="' + svgheight + uom + '" '
  6362. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6363. svg_header += '>'
  6364. svg_header += '<g transform="scale(1,-1)">'
  6365. svg_footer = '</g> </svg>'
  6366. svg_elem = str(svg_header)
  6367. for svg_item in exported_svg:
  6368. svg_elem += str(svg_item)
  6369. svg_elem += str(svg_footer)
  6370. # Parse the xml through a xml parser just to add line feeds
  6371. # and to make it look more pretty for the output
  6372. doc = parse_xml_string(svg_elem)
  6373. doc_final = doc.toprettyxml()
  6374. try:
  6375. if self.defaults['units'].upper() == 'IN':
  6376. unit = inch
  6377. else:
  6378. unit = mm
  6379. doc_final = StringIO(doc_final)
  6380. drawing = svg2rlg(doc_final)
  6381. if p_size == 'Bounds':
  6382. renderPDF.drawToFile(drawing, file_name)
  6383. else:
  6384. if orientation == 'p':
  6385. page_size = portrait(self.pagesize[p_size])
  6386. else:
  6387. page_size = landscape(self.pagesize[p_size])
  6388. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6389. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6390. renderPDF.draw(drawing, my_canvas, 0, 0)
  6391. my_canvas.save()
  6392. except Exception as e:
  6393. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6394. return 'fail'
  6395. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6396. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6397. """
  6398. Exports a Geometry Object to an SVG file.
  6399. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6400. :param filename: Path to the SVG file to save to.
  6401. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6402. :return:
  6403. """
  6404. self.defaults.report_usage("export_svg()")
  6405. if filename is None:
  6406. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6407. is not None else self.defaults["global_last_folder"]
  6408. self.log.debug("export_svg()")
  6409. try:
  6410. obj = self.collection.get_by_name(str(obj_name))
  6411. except Exception:
  6412. # TODO: The return behavior has not been established... should raise exception?
  6413. return "Could not retrieve object: %s" % obj_name
  6414. with self.proc_container.new(_("Exporting SVG")) as proc:
  6415. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6416. # Determine bounding area for svg export
  6417. bounds = obj.bounds()
  6418. size = obj.size()
  6419. # Convert everything to strings for use in the xml doc
  6420. svgwidth = str(size[0])
  6421. svgheight = str(size[1])
  6422. minx = str(bounds[0])
  6423. miny = str(bounds[1] - size[1])
  6424. uom = obj.units.lower()
  6425. # Add a SVG Header and footer to the svg output from shapely
  6426. # The transform flips the Y Axis so that everything renders
  6427. # properly within svg apps such as inkscape
  6428. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6429. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6430. svg_header += 'width="' + svgwidth + uom + '" '
  6431. svg_header += 'height="' + svgheight + uom + '" '
  6432. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6433. svg_header += '<g transform="scale(1,-1)">'
  6434. svg_footer = '</g> </svg>'
  6435. svg_elem = svg_header + exported_svg + svg_footer
  6436. # Parse the xml through a xml parser just to add line feeds
  6437. # and to make it look more pretty for the output
  6438. svgcode = parse_xml_string(svg_elem)
  6439. svgcode = svgcode.toprettyxml()
  6440. try:
  6441. with open(filename, 'w') as fp:
  6442. fp.write(svgcode)
  6443. except PermissionError:
  6444. self.inform.emit('[WARNING] %s' %
  6445. _("Permission denied, saving not possible.\n"
  6446. "Most likely another app is holding the file open and not accessible."))
  6447. return 'fail'
  6448. if self.defaults["global_open_style"] is False:
  6449. self.file_opened.emit("SVG", filename)
  6450. self.file_saved.emit("SVG", filename)
  6451. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6452. def save_source_file(self, obj_name, filename, use_thread=True):
  6453. """
  6454. Exports a FlatCAM Object to an Gerber/Excellon file.
  6455. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6456. :param filename: Path to the Gerber file to save to.
  6457. :param use_thread: if to be run in a separate thread
  6458. :return:
  6459. """
  6460. self.defaults.report_usage("save source file()")
  6461. if filename is None:
  6462. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6463. is not None else self.defaults["global_last_folder"]
  6464. self.log.debug("save source file()")
  6465. obj = self.collection.get_by_name(obj_name)
  6466. file_string = StringIO(obj.source_file)
  6467. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6468. if file_string.getvalue() == '':
  6469. self.inform.emit('[ERROR_NOTCL] %s' %
  6470. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6471. return 'fail'
  6472. try:
  6473. with open(filename, 'w') as file:
  6474. file.writelines('G04*\n')
  6475. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6476. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6477. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6478. file.writelines('G04 Created on : %s*\n' % time_string)
  6479. for line in file_string:
  6480. file.writelines(line)
  6481. except PermissionError:
  6482. self.inform.emit('[WARNING] %s' %
  6483. _("Permission denied, saving not possible.\n"
  6484. "Most likely another app is holding the file open and not accessible."))
  6485. return 'fail'
  6486. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6487. """
  6488. Exports a Excellon Object to an Excellon file.
  6489. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6490. :param filename: Path to the Excellon file to save to.
  6491. :param local_use:
  6492. :param use_thread: if to be run in a separate thread
  6493. :return:
  6494. """
  6495. self.defaults.report_usage("export_excellon()")
  6496. if filename is None:
  6497. if self.defaults["global_last_save_folder"]:
  6498. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6499. else:
  6500. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6501. self.log.debug("export_excellon()")
  6502. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6503. self.defaults["excellon_exp_decimals"]
  6504. )
  6505. if local_use is None:
  6506. try:
  6507. obj = self.collection.get_by_name(str(obj_name))
  6508. except Exception:
  6509. return "Could not retrieve object: %s" % obj_name
  6510. else:
  6511. obj = local_use
  6512. if not isinstance(obj, ExcellonObject):
  6513. self.inform.emit('[ERROR_NOTCL] %s' %
  6514. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6515. return
  6516. # updated units
  6517. eunits = self.defaults["excellon_exp_units"]
  6518. ewhole = self.defaults["excellon_exp_integer"]
  6519. efract = self.defaults["excellon_exp_decimals"]
  6520. ezeros = self.defaults["excellon_exp_zeros"]
  6521. eformat = self.defaults["excellon_exp_format"]
  6522. slot_type = self.defaults["excellon_exp_slot_type"]
  6523. fc_units = self.defaults['units'].upper()
  6524. if fc_units == 'MM':
  6525. factor = 1 if eunits == 'METRIC' else 0.03937
  6526. else:
  6527. factor = 25.4 if eunits == 'METRIC' else 1
  6528. def make_excellon():
  6529. try:
  6530. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6531. header = 'M48\n'
  6532. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6533. (str(self.version), str(self.version_date))
  6534. header += ';Filename: %s' % str(obj_name) + '\n'
  6535. header += ';Created on : %s' % time_str + '\n'
  6536. if eformat == 'dec':
  6537. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6538. header += eunits + '\n'
  6539. for tool in obj.tools:
  6540. if eunits == 'METRIC':
  6541. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6542. tool=str(tool),
  6543. dec=2)
  6544. else:
  6545. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6546. tool=str(tool),
  6547. dec=4)
  6548. else:
  6549. if ezeros == 'LZ':
  6550. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6551. form='ndec', e_zeros='LZ', factor=factor,
  6552. slot_type=slot_type)
  6553. header += '%s,%s\n' % (eunits, 'LZ')
  6554. header += format_exc
  6555. for tool in obj.tools:
  6556. if eunits == 'METRIC':
  6557. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6558. tool=str(tool),
  6559. dec=2)
  6560. else:
  6561. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6562. tool=str(tool),
  6563. dec=4)
  6564. else:
  6565. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6566. form='ndec', e_zeros='TZ', factor=factor,
  6567. slot_type=slot_type)
  6568. header += '%s,%s\n' % (eunits, 'TZ')
  6569. header += format_exc
  6570. for tool in obj.tools:
  6571. if eunits == 'METRIC':
  6572. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6573. tool=str(tool),
  6574. dec=2)
  6575. else:
  6576. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6577. tool=str(tool),
  6578. dec=4)
  6579. header += '%\n'
  6580. footer = 'M30\n'
  6581. exported_excellon = header
  6582. exported_excellon += excellon_code
  6583. exported_excellon += footer
  6584. if local_use is None:
  6585. try:
  6586. with open(filename, 'w') as fp:
  6587. fp.write(exported_excellon)
  6588. except PermissionError:
  6589. self.inform.emit('[WARNING] %s' %
  6590. _("Permission denied, saving not possible.\n"
  6591. "Most likely another app is holding the file open and not accessible."))
  6592. return 'fail'
  6593. if self.defaults["global_open_style"] is False:
  6594. self.file_opened.emit("Excellon", filename)
  6595. self.file_saved.emit("Excellon", filename)
  6596. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6597. else:
  6598. return exported_excellon
  6599. except Exception as e:
  6600. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6601. return 'fail'
  6602. if use_thread is True:
  6603. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6604. def job_thread_exc(app_obj):
  6605. ret = make_excellon()
  6606. if ret == 'fail':
  6607. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6608. return
  6609. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6610. else:
  6611. eret = make_excellon()
  6612. if eret == 'fail':
  6613. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6614. return 'fail'
  6615. if local_use is not None:
  6616. return eret
  6617. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6618. """
  6619. Exports a Gerber Object to an Gerber file.
  6620. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6621. :param filename: Path to the Gerber file to save to.
  6622. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6623. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6624. :param use_thread: if to be run in a separate thread
  6625. :return:
  6626. """
  6627. self.defaults.report_usage("export_gerber()")
  6628. if filename is None:
  6629. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6630. is not None else self.defaults["global_last_folder"]
  6631. self.log.debug("export_gerber()")
  6632. if local_use is None:
  6633. try:
  6634. obj = self.collection.get_by_name(str(obj_name))
  6635. except Exception:
  6636. return "Could not retrieve object: %s" % obj_name
  6637. else:
  6638. obj = local_use
  6639. # updated units
  6640. gunits = self.defaults["gerber_exp_units"]
  6641. gwhole = self.defaults["gerber_exp_integer"]
  6642. gfract = self.defaults["gerber_exp_decimals"]
  6643. gzeros = self.defaults["gerber_exp_zeros"]
  6644. fc_units = self.defaults['units'].upper()
  6645. if fc_units == 'MM':
  6646. factor = 1 if gunits == 'MM' else 0.03937
  6647. else:
  6648. factor = 25.4 if gunits == 'MM' else 1
  6649. def make_gerber():
  6650. try:
  6651. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6652. header = 'G04*\n'
  6653. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6654. (str(self.version), str(self.version_date))
  6655. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6656. header += 'G04 Created on : %s*' % time_str + '\n'
  6657. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6658. header += "%MO{units}*%\n".format(units=gunits)
  6659. for apid in obj.apertures:
  6660. if obj.apertures[apid]['type'] == 'C':
  6661. header += "%ADD{apid}{type},{size}*%\n".format(
  6662. apid=str(apid),
  6663. type='C',
  6664. size=(factor * obj.apertures[apid]['size'])
  6665. )
  6666. elif obj.apertures[apid]['type'] == 'R':
  6667. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6668. apid=str(apid),
  6669. type='R',
  6670. width=(factor * obj.apertures[apid]['width']),
  6671. height=(factor * obj.apertures[apid]['height'])
  6672. )
  6673. elif obj.apertures[apid]['type'] == 'O':
  6674. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6675. apid=str(apid),
  6676. type='O',
  6677. width=(factor * obj.apertures[apid]['width']),
  6678. height=(factor * obj.apertures[apid]['height'])
  6679. )
  6680. header += '\n'
  6681. # obsolete units but some software may need it
  6682. if gunits == 'IN':
  6683. header += 'G70*\n'
  6684. else:
  6685. header += 'G71*\n'
  6686. # Absolute Mode
  6687. header += 'G90*\n'
  6688. header += 'G01*\n'
  6689. # positive polarity
  6690. header += '%LPD*%\n'
  6691. footer = 'M02*\n'
  6692. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6693. exported_gerber = header
  6694. exported_gerber += gerber_code
  6695. exported_gerber += footer
  6696. if local_use is None:
  6697. try:
  6698. with open(filename, 'w') as fp:
  6699. fp.write(exported_gerber)
  6700. except PermissionError:
  6701. self.inform.emit('[WARNING] %s' %
  6702. _("Permission denied, saving not possible.\n"
  6703. "Most likely another app is holding the file open and not accessible."))
  6704. return 'fail'
  6705. if self.defaults["global_open_style"] is False:
  6706. self.file_opened.emit("Gerber", filename)
  6707. self.file_saved.emit("Gerber", filename)
  6708. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6709. else:
  6710. return exported_gerber
  6711. except Exception as e:
  6712. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6713. return 'fail'
  6714. if use_thread is True:
  6715. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6716. def job_thread_grb(app_obj):
  6717. ret = make_gerber()
  6718. if ret == 'fail':
  6719. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6720. return
  6721. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6722. else:
  6723. gret = make_gerber()
  6724. if gret == 'fail':
  6725. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6726. return 'fail'
  6727. if local_use is not None:
  6728. return gret
  6729. def export_dxf(self, obj_name, filename, use_thread=True):
  6730. """
  6731. Exports a Geometry Object to an DXF file.
  6732. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6733. :param filename: Path to the DXF file to save to.
  6734. :param use_thread: if to be run in a separate thread
  6735. :return:
  6736. """
  6737. self.defaults.report_usage("export_dxf()")
  6738. if filename is None:
  6739. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6740. is not None else self.defaults["global_last_folder"]
  6741. self.log.debug("export_dxf()")
  6742. try:
  6743. obj = self.collection.get_by_name(str(obj_name))
  6744. except Exception:
  6745. # TODO: The return behavior has not been established... should raise exception?
  6746. return "Could not retrieve object: %s" % obj_name
  6747. def make_dxf():
  6748. try:
  6749. dxf_code = obj.export_dxf()
  6750. dxf_code.saveas(filename)
  6751. if self.defaults["global_open_style"] is False:
  6752. self.file_opened.emit("DXF", filename)
  6753. self.file_saved.emit("DXF", filename)
  6754. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6755. except Exception:
  6756. return 'fail'
  6757. if use_thread is True:
  6758. with self.proc_container.new(_("Exporting DXF")) as proc:
  6759. def job_thread_exc(app_obj):
  6760. ret_dxf_val = make_dxf()
  6761. if ret_dxf_val == 'fail':
  6762. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6763. return
  6764. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6765. else:
  6766. ret = make_dxf()
  6767. if ret == 'fail':
  6768. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6769. return
  6770. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6771. """
  6772. Adds a new Geometry Object to the projects and populates
  6773. it with shapes extracted from the SVG file.
  6774. :param plot: If True then the resulting object will be plotted on canvas
  6775. :param filename: Path to the SVG file.
  6776. :param geo_type: Type of FlatCAM object that will be created from SVG
  6777. :param outname: The name given to the resulting FlatCAM object
  6778. :return:
  6779. """
  6780. self.defaults.report_usage("import_svg()")
  6781. log.debug("App.import_svg()")
  6782. obj_type = ""
  6783. if geo_type is None or geo_type == "geometry":
  6784. obj_type = "geometry"
  6785. elif geo_type == "gerber":
  6786. obj_type = "gerber"
  6787. else:
  6788. self.inform.emit('[ERROR_NOTCL] %s' %
  6789. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6790. return
  6791. units = self.defaults['units'].upper()
  6792. def obj_init(geo_obj, app_obj):
  6793. geo_obj.import_svg(filename, obj_type, units=units)
  6794. geo_obj.multigeo = False
  6795. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6796. with self.proc_container.new(_("Importing SVG")) as proc:
  6797. # Object name
  6798. name = outname or filename.split('/')[-1].split('\\')[-1]
  6799. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6800. if ret == 'fail':
  6801. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6802. return 'fail'
  6803. # Register recent file
  6804. self.file_opened.emit("svg", filename)
  6805. # AppGUI feedback
  6806. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6807. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6808. """
  6809. Adds a new Geometry Object to the projects and populates
  6810. it with shapes extracted from the DXF file.
  6811. :param filename: Path to the DXF file.
  6812. :param geo_type: Type of FlatCAM object that will be created from DXF
  6813. :param outname: Name for the imported Geometry
  6814. :param plot: If True then the resulting object will be plotted on canvas
  6815. :return:
  6816. """
  6817. self.defaults.report_usage("import_dxf()")
  6818. obj_type = ""
  6819. if geo_type is None or geo_type == "geometry":
  6820. obj_type = "geometry"
  6821. elif geo_type == "gerber":
  6822. obj_type = geo_type
  6823. else:
  6824. self.inform.emit('[ERROR_NOTCL] %s' %
  6825. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6826. return
  6827. units = self.defaults['units'].upper()
  6828. def obj_init(geo_obj, app_obj):
  6829. geo_obj.import_dxf(filename, obj_type, units=units)
  6830. geo_obj.multigeo = False
  6831. with self.proc_container.new(_("Importing DXF")):
  6832. # Object name
  6833. name = outname or filename.split('/')[-1].split('\\')[-1]
  6834. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6835. if ret == 'fail':
  6836. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6837. return 'fail'
  6838. # Register recent file
  6839. self.file_opened.emit("dxf", filename)
  6840. # AppGUI feedback
  6841. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6842. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6843. """
  6844. Opens a Gerber file, parses it and creates a new object for
  6845. it in the program. Thread-safe.
  6846. :param outname: Name of the resulting object. None causes the
  6847. name to be that of the file. Str.
  6848. :param filename: Gerber file filename
  6849. :type filename: str
  6850. :param plot: boolean, to plot or not the resulting object
  6851. :param from_tcl: True if run from Tcl Shell
  6852. :return: None
  6853. """
  6854. # How the object should be initialized
  6855. def obj_init(gerber_obj, app_obj):
  6856. assert isinstance(gerber_obj, GerberObject), \
  6857. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6858. # Opening the file happens here
  6859. try:
  6860. gerber_obj.parse_file(filename)
  6861. except IOError:
  6862. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6863. return "fail"
  6864. except ParseError as err:
  6865. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6866. app_obj.log.error(str(err))
  6867. return "fail"
  6868. except Exception as e:
  6869. log.debug("App.open_gerber() --> %s" % str(e))
  6870. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6871. msg += traceback.format_exc()
  6872. app_obj.inform.emit(msg)
  6873. return "fail"
  6874. if gerber_obj.is_empty():
  6875. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6876. _("Object is not Gerber file or empty. Aborting object creation."))
  6877. return "fail"
  6878. App.log.debug("open_gerber()")
  6879. with self.proc_container.new(_("Opening Gerber")):
  6880. # Object name
  6881. name = outname or filename.split('/')[-1].split('\\')[-1]
  6882. # # ## Object creation # ##
  6883. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6884. if ret_val == 'fail':
  6885. if from_tcl:
  6886. filename = self.defaults['global_tcl_path'] + '/' + name
  6887. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6888. if ret_val == 'fail':
  6889. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6890. return 'fail'
  6891. # Register recent file
  6892. self.file_opened.emit("gerber", filename)
  6893. # AppGUI feedback
  6894. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6895. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6896. """
  6897. Opens an Excellon file, parses it and creates a new object for
  6898. it in the program. Thread-safe.
  6899. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6900. :param filename: Excellon file filename
  6901. :type filename: str
  6902. :param plot: boolean, to plot or not the resulting object
  6903. :param from_tcl: True if run from Tcl Shell
  6904. :return: None
  6905. """
  6906. App.log.debug("open_excellon()")
  6907. # How the object should be initialized
  6908. def obj_init(excellon_obj, app_obj):
  6909. try:
  6910. ret = excellon_obj.parse_file(filename=filename)
  6911. if ret == "fail":
  6912. log.debug("Excellon parsing failed.")
  6913. self.inform.emit('[ERROR_NOTCL] %s' %
  6914. _("This is not Excellon file."))
  6915. return "fail"
  6916. except IOError:
  6917. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6918. (_("Cannot open file"), filename))
  6919. log.debug("Could not open Excellon object.")
  6920. return "fail"
  6921. except Exception:
  6922. msg = '[ERROR_NOTCL] %s' % \
  6923. _("An internal error has occurred. See shell.\n")
  6924. msg += traceback.format_exc()
  6925. app_obj.inform.emit(msg)
  6926. return "fail"
  6927. ret = excellon_obj.create_geometry()
  6928. if ret == 'fail':
  6929. log.debug("Could not create geometry for Excellon object.")
  6930. return "fail"
  6931. for tool in excellon_obj.tools:
  6932. if excellon_obj.tools[tool]['solid_geometry']:
  6933. return
  6934. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  6935. return "fail"
  6936. with self.proc_container.new(_("Opening Excellon.")):
  6937. # Object name
  6938. name = outname or filename.split('/')[-1].split('\\')[-1]
  6939. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6940. if ret_val == 'fail':
  6941. if from_tcl:
  6942. filename = self.defaults['global_tcl_path'] + '/' + name
  6943. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  6944. if ret_val == 'fail':
  6945. self.inform.emit('[ERROR_NOTCL] %s' %
  6946. _('Open Excellon file failed. Probable not an Excellon file.'))
  6947. return
  6948. # Register recent file
  6949. self.file_opened.emit("excellon", filename)
  6950. # AppGUI feedback
  6951. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6952. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  6953. """
  6954. Opens a G-gcode file, parses it and creates a new object for
  6955. it in the program. Thread-safe.
  6956. :param filename: G-code file filename
  6957. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6958. :param force_parsing:
  6959. :param plot: If True plot the object on canvas
  6960. :param from_tcl: True if run from Tcl Shell
  6961. :return: None
  6962. """
  6963. App.log.debug("open_gcode()")
  6964. # How the object should be initialized
  6965. def obj_init(job_obj, app_obj_):
  6966. """
  6967. :param job_obj: the resulting object
  6968. :type app_obj_: App
  6969. """
  6970. assert isinstance(app_obj_, App), \
  6971. "Initializer expected App, got %s" % type(app_obj_)
  6972. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  6973. try:
  6974. f = open(filename)
  6975. gcode = f.read()
  6976. f.close()
  6977. except IOError:
  6978. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  6979. return "fail"
  6980. job_obj.gcode = gcode
  6981. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  6982. if gcode_ret == "fail":
  6983. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  6984. return "fail"
  6985. job_obj.create_geometry()
  6986. with self.proc_container.new(_("Opening G-Code.")):
  6987. # Object name
  6988. name = outname or filename.split('/')[-1].split('\\')[-1]
  6989. # New object creation and file processing
  6990. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  6991. if ret_val == 'fail':
  6992. if from_tcl:
  6993. filename = self.defaults['global_tcl_path'] + '/' + name
  6994. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  6995. if ret_val == 'fail':
  6996. self.inform.emit('[ERROR_NOTCL] %s' %
  6997. _("Failed to create CNCJob Object. Probable not a GCode file. "
  6998. "Try to load it from File menu.\n "
  6999. "Attempting to create a FlatCAM CNCJob Object from "
  7000. "G-Code file failed during processing"))
  7001. return "fail"
  7002. # Register recent file
  7003. self.file_opened.emit("cncjob", filename)
  7004. # AppGUI feedback
  7005. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7006. def open_hpgl2(self, filename, outname=None):
  7007. """
  7008. Opens a HPGL2 file, parses it and creates a new object for
  7009. it in the program. Thread-safe.
  7010. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7011. :param filename: HPGL2 file filename
  7012. :return: None
  7013. """
  7014. filename = filename
  7015. # How the object should be initialized
  7016. def obj_init(geo_obj, app_obj):
  7017. assert isinstance(geo_obj, GeometryObject), \
  7018. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7019. # Opening the file happens here
  7020. obj = HPGL2(self)
  7021. try:
  7022. HPGL2.parse_file(obj, filename)
  7023. except IOError:
  7024. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7025. return "fail"
  7026. except ParseError as err:
  7027. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7028. app_obj.log.error(str(err))
  7029. return "fail"
  7030. except Exception as e:
  7031. log.debug("App.open_hpgl2() --> %s" % str(e))
  7032. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7033. msg += traceback.format_exc()
  7034. app_obj.inform.emit(msg)
  7035. return "fail"
  7036. geo_obj.multigeo = True
  7037. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7038. geo_obj.tools = deepcopy(obj.tools)
  7039. geo_obj.source_file = deepcopy(obj.source_file)
  7040. del obj
  7041. if not geo_obj.solid_geometry:
  7042. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7043. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7044. return "fail"
  7045. App.log.debug("open_hpgl2()")
  7046. with self.proc_container.new(_("Opening HPGL2")):
  7047. # Object name
  7048. name = outname or filename.split('/')[-1].split('\\')[-1]
  7049. # # ## Object creation # ##
  7050. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7051. if ret == 'fail':
  7052. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7053. return 'fail'
  7054. # Register recent file
  7055. self.file_opened.emit("geometry", filename)
  7056. # AppGUI feedback
  7057. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7058. def open_script(self, filename, outname=None, silent=False):
  7059. """
  7060. Opens a Script file, parses it and creates a new object for
  7061. it in the program. Thread-safe.
  7062. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7063. :param filename: Script file filename
  7064. :param silent: If True there will be no messages printed to StatusBar
  7065. :return: None
  7066. """
  7067. def obj_init(script_obj, app_obj):
  7068. assert isinstance(script_obj, ScriptObject), \
  7069. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7070. if silent is False:
  7071. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7072. try:
  7073. script_obj.parse_file(filename)
  7074. except IOError:
  7075. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7076. return "fail"
  7077. except ParseError as err:
  7078. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7079. app_obj.log.error(str(err))
  7080. return "fail"
  7081. except Exception as e:
  7082. log.debug("App.open_script() -> %s" % str(e))
  7083. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7084. msg += traceback.format_exc()
  7085. app_obj.inform.emit(msg)
  7086. return "fail"
  7087. App.log.debug("open_script()")
  7088. with self.proc_container.new(_("Opening TCL Script...")):
  7089. # Object name
  7090. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7091. # Object creation
  7092. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7093. if ret_val == 'fail':
  7094. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7095. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7096. if ret_val == 'fail':
  7097. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7098. return 'fail'
  7099. # Register recent file
  7100. self.file_opened.emit("script", filename)
  7101. # AppGUI feedback
  7102. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7103. def open_config_file(self, filename, run_from_arg=None):
  7104. """
  7105. Loads a config file from the specified file.
  7106. :param filename: Name of the file from which to load.
  7107. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7108. :return: None
  7109. """
  7110. App.log.debug("Opening config file: " + filename)
  7111. if run_from_arg:
  7112. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7113. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7114. _("Opening FlatCAM Config file.")),
  7115. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7116. color=QtGui.QColor("gray"))
  7117. # # add the tab if it was closed
  7118. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7119. # # first clear previous text in text editor (if any)
  7120. # self.ui.text_editor_tab.code_editor.clear()
  7121. #
  7122. # # Switch plot_area to CNCJob tab
  7123. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7124. # close the Code editor if already open
  7125. if self.toggle_codeeditor:
  7126. self.on_toggle_code_editor()
  7127. self.on_toggle_code_editor()
  7128. try:
  7129. if filename:
  7130. f = QtCore.QFile(filename)
  7131. if f.open(QtCore.QIODevice.ReadOnly):
  7132. stream = QtCore.QTextStream(f)
  7133. code_edited = stream.readAll()
  7134. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7135. f.close()
  7136. except IOError:
  7137. App.log.error("Failed to open config file: %s" % filename)
  7138. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7139. (_("Failed to open config file"), filename))
  7140. return
  7141. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7142. """
  7143. Loads a project from the specified file.
  7144. 1) Loads and parses file
  7145. 2) Registers the file as recently opened.
  7146. 3) Calls on_file_new()
  7147. 4) Updates options
  7148. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7149. 6) Calls plot_all() if plot=True
  7150. :param filename: Name of the file from which to load.
  7151. :param run_from_arg: True if run for arguments
  7152. :param plot: If True plot all objects in the project
  7153. :param cli: Run from command line
  7154. :param from_tcl: True if run from Tcl Sehll
  7155. :return: None
  7156. """
  7157. App.log.debug("Opening project: " + filename)
  7158. # block autosaving while a project is loaded
  7159. self.block_autosave = True
  7160. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7161. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7162. if cli is None:
  7163. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7164. if run_from_arg:
  7165. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7166. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7167. _("Opening FlatCAM Project file.")),
  7168. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7169. color=QtGui.QColor("gray"))
  7170. # Open and parse an uncompressed Project file
  7171. try:
  7172. f = open(filename, 'r')
  7173. except IOError:
  7174. if from_tcl:
  7175. name = filename.split('/')[-1].split('\\')[-1]
  7176. filename = self.defaults['global_tcl_path'] + '/' + name
  7177. try:
  7178. f = open(filename, 'r')
  7179. except IOError:
  7180. log.error("Failed to open project file: %s" % filename)
  7181. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7182. return
  7183. else:
  7184. log.error("Failed to open project file: %s" % filename)
  7185. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7186. return
  7187. try:
  7188. d = json.load(f, object_hook=dict2obj)
  7189. except Exception as e:
  7190. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7191. (filename, str(e)))
  7192. f.close()
  7193. # Open and parse a compressed Project file
  7194. try:
  7195. with lzma.open(filename) as f:
  7196. file_content = f.read().decode('utf-8')
  7197. d = json.loads(file_content, object_hook=dict2obj)
  7198. except Exception as e:
  7199. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7200. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7201. return
  7202. # Clear the current project
  7203. # # NOT THREAD SAFE # ##
  7204. if run_from_arg is True:
  7205. pass
  7206. elif cli is True:
  7207. self.delete_selection_shape()
  7208. else:
  7209. self.on_file_new()
  7210. # Project options
  7211. self.options.update(d['options'])
  7212. self.project_filename = filename
  7213. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7214. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7215. if cli is None:
  7216. self.set_screen_units(self.options["units"])
  7217. # Re create objects
  7218. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7219. for obj in d['objs']:
  7220. try:
  7221. def obj_init(obj_inst, app_inst):
  7222. obj_inst.from_dict(obj)
  7223. App.log.debug("Recreating from opened project an %s object: %s" %
  7224. (obj['kind'].capitalize(), obj['options']['name']))
  7225. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7226. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7227. if cli is None:
  7228. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7229. obj['kind'].upper(),
  7230. obj['options']['name']
  7231. )
  7232. )
  7233. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7234. except Exception as e:
  7235. print('App.open_project() --> ' + str(e))
  7236. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7237. self.should_we_save = False
  7238. self.file_opened.emit("project", filename)
  7239. # restore autosaving after a project was loaded
  7240. self.block_autosave = False
  7241. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7242. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7243. if cli is None:
  7244. self.set_ui_title(name=self.project_filename)
  7245. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7246. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7247. """
  7248. Re-generates all plots from all objects.
  7249. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7250. :param muted: if True don't print messages
  7251. :param use_thread: if True will use threading for plotting the objects
  7252. :return: None
  7253. """
  7254. self.log.debug("Plot_all()")
  7255. if muted is not True:
  7256. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7257. for plot_obj in self.collection.get_list():
  7258. def worker_task(obj):
  7259. with self.proc_container.new("Plotting"):
  7260. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7261. if fit_view is True:
  7262. self.app_obj.object_plotted.emit(obj)
  7263. if use_thread is True:
  7264. # Send to worker
  7265. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7266. else:
  7267. worker_task(plot_obj)
  7268. def register_folder(self, filename):
  7269. """
  7270. Register the last folder used by the app to open something
  7271. :param filename: the last folder is extracted from the filename
  7272. :return: None
  7273. """
  7274. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7275. def register_save_folder(self, filename):
  7276. """
  7277. Register the last folder used by the app to save something
  7278. :param filename: the last folder is extracted from the filename
  7279. :return: None
  7280. """
  7281. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7282. # def set_progress_bar(self, percentage, text=""):
  7283. # """
  7284. # Set a progress bar to a value (percentage)
  7285. #
  7286. # :param percentage: Value set to the progressbar
  7287. # :param text: Not used
  7288. # :return: None
  7289. # """
  7290. # self.ui.progress_bar.setValue(int(percentage))
  7291. def setup_recent_items(self):
  7292. """
  7293. Setup a dictionary with the recent files accessed, organized by type
  7294. :return:
  7295. """
  7296. icons = {
  7297. "gerber": self.resource_location + "/flatcam_icon16.png",
  7298. "excellon": self.resource_location + "/drill16.png",
  7299. 'geometry': self.resource_location + "/geometry16.png",
  7300. "cncjob": self.resource_location + "/cnc16.png",
  7301. "script": self.resource_location + "/script_new24.png",
  7302. "document": self.resource_location + "/notes16_1.png",
  7303. "project": self.resource_location + "/project16.png",
  7304. "svg": self.resource_location + "/geometry16.png",
  7305. "dxf": self.resource_location + "/dxf16.png",
  7306. "pdf": self.resource_location + "/pdf32.png",
  7307. "image": self.resource_location + "/image16.png"
  7308. }
  7309. try:
  7310. image_opener = self.image_tool.import_image
  7311. except AttributeError:
  7312. image_opener = None
  7313. openers = {
  7314. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7315. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7316. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7317. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7318. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7319. "document": None,
  7320. 'project': self.open_project,
  7321. 'svg': self.import_svg,
  7322. 'dxf': self.import_dxf,
  7323. 'image': image_opener,
  7324. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7325. }
  7326. # Open recent file for files
  7327. try:
  7328. f = open(self.data_path + '/recent.json')
  7329. except IOError:
  7330. App.log.error("Failed to load recent item list.")
  7331. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7332. return
  7333. try:
  7334. self.recent = json.load(f)
  7335. except json.errors.JSONDecodeError:
  7336. App.log.error("Failed to parse recent item list.")
  7337. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7338. f.close()
  7339. return
  7340. f.close()
  7341. # Open recent file for projects
  7342. try:
  7343. fp = open(self.data_path + '/recent_projects.json')
  7344. except IOError:
  7345. App.log.error("Failed to load recent project item list.")
  7346. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7347. return
  7348. try:
  7349. self.recent_projects = json.load(fp)
  7350. except json.errors.JSONDecodeError:
  7351. App.log.error("Failed to parse recent project item list.")
  7352. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7353. fp.close()
  7354. return
  7355. fp.close()
  7356. # Closure needed to create callbacks in a loop.
  7357. # Otherwise late binding occurs.
  7358. def make_callback(func, fname):
  7359. def opener():
  7360. func(fname)
  7361. return opener
  7362. def reset_recent_files():
  7363. # Reset menu
  7364. self.ui.recent.clear()
  7365. self.recent = []
  7366. try:
  7367. ff = open(self.data_path + '/recent.json', 'w')
  7368. except IOError:
  7369. App.log.error("Failed to open recent items file for writing.")
  7370. return
  7371. json.dump(self.recent, ff)
  7372. def reset_recent_projects():
  7373. # Reset menu
  7374. self.ui.recent_projects.clear()
  7375. self.recent_projects = []
  7376. try:
  7377. frp = open(self.data_path + '/recent_projects.json', 'w')
  7378. except IOError:
  7379. App.log.error("Failed to open recent projects items file for writing.")
  7380. return
  7381. json.dump(self.recent, frp)
  7382. # Reset menu
  7383. self.ui.recent.clear()
  7384. self.ui.recent_projects.clear()
  7385. # Create menu items for projects
  7386. for recent in self.recent_projects:
  7387. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7388. if recent['kind'] == 'project':
  7389. try:
  7390. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7391. # Attach callback
  7392. o = make_callback(openers[recent["kind"]], recent['filename'])
  7393. action.triggered.connect(o)
  7394. self.ui.recent_projects.addAction(action)
  7395. except KeyError:
  7396. App.log.error("Unsupported file type: %s" % recent["kind"])
  7397. # Last action in Recent Files menu is one that Clear the content
  7398. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7399. (_("Clear Recent projects")), self)
  7400. clear_action_proj.triggered.connect(reset_recent_projects)
  7401. self.ui.recent_projects.addSeparator()
  7402. self.ui.recent_projects.addAction(clear_action_proj)
  7403. # Create menu items for files
  7404. for recent in self.recent:
  7405. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7406. if recent['kind'] != 'project':
  7407. try:
  7408. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7409. # Attach callback
  7410. o = make_callback(openers[recent["kind"]], recent['filename'])
  7411. action.triggered.connect(o)
  7412. self.ui.recent.addAction(action)
  7413. except KeyError:
  7414. App.log.error("Unsupported file type: %s" % recent["kind"])
  7415. # Last action in Recent Files menu is one that Clear the content
  7416. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7417. (_("Clear Recent files")), self)
  7418. clear_action.triggered.connect(reset_recent_files)
  7419. self.ui.recent.addSeparator()
  7420. self.ui.recent.addAction(clear_action)
  7421. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7422. # self.ui.menufilerecent.set_submenu(recent_menu)
  7423. # recent_menu.show_all()
  7424. # self.ui.recent.show()
  7425. self.log.debug("Recent items list has been populated.")
  7426. def setup_component_editor(self):
  7427. """
  7428. Default text for the Selected tab when is not taken by the Object UI.
  7429. :return:
  7430. """
  7431. # label = QtWidgets.QLabel("Choose an item from Project")
  7432. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7433. sel_title = QtWidgets.QTextEdit(
  7434. _('<b>Shortcut Key List</b>'))
  7435. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7436. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7437. f_settings = QSettings("Open Source", "FlatCAM")
  7438. if f_settings.contains("notebook_font_size"):
  7439. fsize = f_settings.value('notebook_font_size', type=int)
  7440. else:
  7441. fsize = 12
  7442. tsize = fsize + int(fsize / 2)
  7443. # selected_text = (_('''
  7444. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7445. # </p>
  7446. #
  7447. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7448. # The normal flow when working in FlatCAM is the following:</span></p>
  7449. #
  7450. # <ol>
  7451. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7452. # file into
  7453. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7454. # even dragging and dropping the files on the AppGUI.<br />
  7455. # <br />
  7456. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7457. # drop of the
  7458. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7459. # &nbsp;</li>
  7460. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7461. # and then
  7462. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7463. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7464. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7465. # <br />
  7466. # If the selection of the object is done on the canvas by single click instead, and the
  7467. # <strong>SELECTED TAB</strong>
  7468. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7469. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7470. # it even if it was out of focus.<br />
  7471. # <br />
  7472. # You can change the parameters in this screen and the flow direction is like this:<br />
  7473. # <br />
  7474. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7475. # <strong> Geometry Object
  7476. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7477. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7478. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7479. # </ol>
  7480. #
  7481. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7482. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7483. # <strong>F3</strong>.</span></p>
  7484. #
  7485. # ''').format(fsize=fsize, tsize=tsize))
  7486. selected_text = '''
  7487. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7488. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7489. {s1}</span></p>
  7490. <ol>
  7491. <li><span style="font-size:{fsize}px">{s2}<br />
  7492. <br />
  7493. {s3}</span><br />
  7494. &nbsp;</li>
  7495. <li><span style="font-size:{fsize}px">{s4}<br />
  7496. &nbsp;</li>
  7497. <br />
  7498. <li><span style="font-size:{fsize}px">{s5}<br />
  7499. &nbsp;</li>
  7500. <br />
  7501. <li><span style="font-size:{fsize}px">{s6}<br />
  7502. <br />
  7503. {s7}</span></li>
  7504. </ol>
  7505. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7506. '''.format(
  7507. title=_("Selected Tab - Choose an Item from Project Tab"),
  7508. subtitle=_("Details"),
  7509. s1=_("The normal flow when working in FlatCAM is the following:"),
  7510. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7511. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7512. "files on the AppGUI."),
  7513. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7514. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7515. "actions offered within the app."),
  7516. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7517. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7518. "SELECTED TAB will be updated with the object properties according to its kind: "
  7519. "Gerber, Excellon, Geometry or CNCJob object."),
  7520. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7521. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7522. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7523. "the SELECTED TAB and populate it even if it was out of focus."),
  7524. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7525. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7526. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7527. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7528. "(again, done in SELECTED TAB) --> Save GCode."),
  7529. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7530. "or through its own key shortcut: <b>F3</b>."),
  7531. tsize=tsize,
  7532. fsize=fsize
  7533. )
  7534. sel_title.setText(selected_text)
  7535. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7536. self.ui.selected_scroll_area.setWidget(sel_title)
  7537. def setup_obj_classes(self):
  7538. """
  7539. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7540. class.
  7541. :return: None
  7542. """
  7543. FlatCAMObj.app = self
  7544. ObjectCollection.app = self
  7545. Gerber.app = self
  7546. Excellon.app = self
  7547. Geometry.app = self
  7548. CNCjob.app = self
  7549. FCProcess.app = self
  7550. FCProcessContainer.app = self
  7551. OptionsGroupUI.app = self
  7552. def version_check(self):
  7553. """
  7554. Checks for the latest version of the program. Alerts the
  7555. user if theirs is outdated. This method is meant to be run
  7556. in a separate thread.
  7557. :return: None
  7558. """
  7559. self.log.debug("version_check()")
  7560. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7561. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7562. App.version_url,
  7563. str(self.defaults['global_serial']),
  7564. str(self.version),
  7565. str(self.os),
  7566. urllib.parse.urlencode(self.defaults["global_stats"])
  7567. )
  7568. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7569. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7570. # urllib.parse.urlencode(self.defaults["global_stats"])
  7571. else:
  7572. # no_stats dict; just so it won't break things on website
  7573. no_ststs_dict = {}
  7574. no_ststs_dict["global_ststs"] = {}
  7575. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7576. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7577. App.log.debug("Checking for updates @ %s" % full_url)
  7578. # ## Get the data
  7579. try:
  7580. f = urllib.request.urlopen(full_url)
  7581. except Exception:
  7582. # App.log.warning("Failed checking for latest version. Could not connect.")
  7583. self.log.warning("Failed checking for latest version. Could not connect.")
  7584. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7585. return
  7586. try:
  7587. data = json.load(f)
  7588. except Exception as e:
  7589. App.log.error("Could not parse information about latest version.")
  7590. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7591. App.log.debug("json.load(): %s" % str(e))
  7592. f.close()
  7593. return
  7594. f.close()
  7595. # ## Latest version?
  7596. if self.version >= data["version"]:
  7597. App.log.debug("FlatCAM is up to date!")
  7598. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7599. return
  7600. App.log.debug("Newer version available.")
  7601. self.message.emit(
  7602. _("Newer Version Available"),
  7603. '%s<br><br>><b>%s</b><br>%s' % (
  7604. _("There is a newer version of FlatCAM available for download:"),
  7605. str(data["name"]),
  7606. str(data["message"])
  7607. ),
  7608. _("info")
  7609. )
  7610. def on_plotcanvas_setup(self, container=None):
  7611. """
  7612. This is doing the setup for the plot area (canvas).
  7613. :param container: QT Widget where to install the canvas
  7614. :return: None
  7615. """
  7616. if container:
  7617. plot_container = container
  7618. else:
  7619. plot_container = self.ui.right_layout
  7620. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7621. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7622. self.is_legacy = True
  7623. self.defaults["global_graphic_engine"] = "2D"
  7624. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7625. else:
  7626. try:
  7627. self.plotcanvas = PlotCanvas(plot_container, self)
  7628. except Exception as er:
  7629. msg_txt = traceback.format_exc()
  7630. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7631. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7632. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7633. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7634. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7635. msg += msg_txt
  7636. self.inform.emit(msg)
  7637. return 'fail'
  7638. # So it can receive key presses
  7639. self.plotcanvas.native.setFocus()
  7640. if self.is_legacy is False:
  7641. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7642. # Set the mouse button for panning
  7643. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7644. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7645. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7646. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7647. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7648. # Keys over plot enabled
  7649. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7650. if self.defaults['global_cursor_type'] == 'small':
  7651. self.app_cursor = self.plotcanvas.new_cursor()
  7652. else:
  7653. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7654. if self.ui.grid_snap_btn.isChecked():
  7655. self.app_cursor.enabled = True
  7656. else:
  7657. self.app_cursor.enabled = False
  7658. if self.is_legacy is False:
  7659. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7660. else:
  7661. # will use the default Matplotlib axes
  7662. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7663. def on_zoom_fit(self):
  7664. """
  7665. Callback for zoom-fit request. This can be either from the corresponding
  7666. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7667. with axes limits from the geometry bounds of all objects.
  7668. :return: None
  7669. """
  7670. if self.is_legacy is False:
  7671. self.plotcanvas.fit_view()
  7672. else:
  7673. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7674. width = xmax - xmin
  7675. height = ymax - ymin
  7676. xmin -= 0.05 * width
  7677. xmax += 0.05 * width
  7678. ymin -= 0.05 * height
  7679. ymax += 0.05 * height
  7680. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7681. def on_zoom_in(self):
  7682. """
  7683. Callback for zoom-in request.
  7684. :return:
  7685. """
  7686. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7687. def on_zoom_out(self):
  7688. """
  7689. Callback for zoom-out request.
  7690. :return:
  7691. """
  7692. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7693. def disable_all_plots(self):
  7694. self.defaults.report_usage("disable_all_plots()")
  7695. self.disable_plots(self.collection.get_list())
  7696. self.inform.emit('[success] %s' %
  7697. _("All plots disabled."))
  7698. def disable_other_plots(self):
  7699. self.defaults.report_usage("disable_other_plots()")
  7700. self.disable_plots(self.collection.get_non_selected())
  7701. self.inform.emit('[success] %s' %
  7702. _("All non selected plots disabled."))
  7703. def enable_all_plots(self):
  7704. self.defaults.report_usage("enable_all_plots()")
  7705. self.enable_plots(self.collection.get_list())
  7706. self.inform.emit('[success] %s' %
  7707. _("All plots enabled."))
  7708. def on_enable_sel_plots(self):
  7709. log.debug("App.on_enable_sel_plot()")
  7710. object_list = self.collection.get_selected()
  7711. self.enable_plots(objects=object_list)
  7712. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7713. def on_disable_sel_plots(self):
  7714. log.debug("App.on_disable_sel_plot()")
  7715. # self.inform.emit(_("Disabling plots ..."))
  7716. object_list = self.collection.get_selected()
  7717. self.disable_plots(objects=object_list)
  7718. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7719. def enable_plots(self, objects):
  7720. """
  7721. Enable plots
  7722. :param objects: list of Objects to be enabled
  7723. :return:
  7724. """
  7725. log.debug("Enabling plots ...")
  7726. # self.inform.emit(_("Working ..."))
  7727. for obj in objects:
  7728. if obj.options['plot'] is False:
  7729. obj.options.set_change_callback(lambda x: None)
  7730. obj.options['plot'] = True
  7731. try:
  7732. # only the Gerber obj has on_plot_cb_click() method
  7733. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7734. # disable this cb while disconnected,
  7735. # in case the operation takes time the user is not allowed to change it
  7736. obj.ui.plot_cb.setDisabled(True)
  7737. except AttributeError:
  7738. pass
  7739. obj.set_form_item("plot")
  7740. try:
  7741. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7742. obj.ui.plot_cb.setDisabled(False)
  7743. except AttributeError:
  7744. pass
  7745. obj.options.set_change_callback(obj.on_options_change)
  7746. def worker_task(objs):
  7747. with self.proc_container.new(_("Enabling plots ...")):
  7748. for plot_obj in objs:
  7749. # obj.options['plot'] = True
  7750. if isinstance(plot_obj, CNCJobObject):
  7751. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7752. else:
  7753. plot_obj.plot(visible=True)
  7754. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7755. def disable_plots(self, objects):
  7756. """
  7757. Disables plots
  7758. :param objects: list of Objects to be disabled
  7759. :return:
  7760. """
  7761. # if no objects selected then do nothing
  7762. if not self.collection.get_selected():
  7763. return
  7764. log.debug("Disabling plots ...")
  7765. # self.inform.emit(_("Working ..."))
  7766. for obj in objects:
  7767. if obj.options['plot'] is True:
  7768. obj.options.set_change_callback(lambda x: None)
  7769. obj.options['plot'] = False
  7770. try:
  7771. # only the Gerber obj has on_plot_cb_click() method
  7772. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7773. obj.ui.plot_cb.setDisabled(True)
  7774. except AttributeError:
  7775. pass
  7776. obj.set_form_item("plot")
  7777. try:
  7778. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7779. obj.ui.plot_cb.setDisabled(False)
  7780. except AttributeError:
  7781. pass
  7782. obj.options.set_change_callback(obj.on_options_change)
  7783. try:
  7784. self.delete_selection_shape()
  7785. except Exception as e:
  7786. log.debug("App.disable_plots() --> %s" % str(e))
  7787. def worker_task(objs):
  7788. with self.proc_container.new(_("Disabling plots ...")):
  7789. for plot_obj in objs:
  7790. # obj.options['plot'] = True
  7791. if isinstance(plot_obj, CNCJobObject):
  7792. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7793. else:
  7794. plot_obj.plot(visible=False)
  7795. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7796. def toggle_plots(self, objects):
  7797. """
  7798. Toggle plots visibility
  7799. :param objects: list of Objects for which to be toggled the visibility
  7800. :return: None
  7801. """
  7802. # if no objects selected then do nothing
  7803. if not self.collection.get_selected():
  7804. return
  7805. log.debug("Toggling plots ...")
  7806. self.inform.emit(_("Working ..."))
  7807. for obj in objects:
  7808. if obj.options['plot'] is False:
  7809. obj.options['plot'] = True
  7810. else:
  7811. obj.options['plot'] = False
  7812. self.app_obj.plots_updated.emit()
  7813. def clear_plots(self):
  7814. """
  7815. Clear the plots
  7816. :return: None
  7817. """
  7818. objects = self.collection.get_list()
  7819. for obj in objects:
  7820. obj.clear(obj == objects[-1])
  7821. # Clear pool to free memory
  7822. self.clear_pool()
  7823. def on_set_color_action_triggered(self):
  7824. """
  7825. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7826. :return:
  7827. """
  7828. new_color = self.defaults['gerber_plot_fill']
  7829. clicked_action = self.sender()
  7830. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7831. act_name = clicked_action.text()
  7832. sel_obj_list = self.collection.get_selected()
  7833. if not sel_obj_list:
  7834. return
  7835. # a default value, I just chose this one
  7836. alpha_level = 'BF'
  7837. for sel_obj in sel_obj_list:
  7838. if sel_obj.kind == 'excellon':
  7839. alpha_level = str(hex(
  7840. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7841. elif sel_obj.kind == 'gerber':
  7842. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7843. elif sel_obj.kind == 'geometry':
  7844. alpha_level = 'FF'
  7845. else:
  7846. log.debug(
  7847. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7848. continue
  7849. sel_obj.alpha_level = alpha_level
  7850. if act_name == _('Red'):
  7851. new_color = '#FF0000' + alpha_level
  7852. if act_name == _('Blue'):
  7853. new_color = '#0000FF' + alpha_level
  7854. if act_name == _('Yellow'):
  7855. new_color = '#FFDF00' + alpha_level
  7856. if act_name == _('Green'):
  7857. new_color = '#00FF00' + alpha_level
  7858. if act_name == _('Purple'):
  7859. new_color = '#FF00FF' + alpha_level
  7860. if act_name == _('Brown'):
  7861. new_color = '#A52A2A' + alpha_level
  7862. if act_name == _('White'):
  7863. new_color = '#FFFFFF' + alpha_level
  7864. if act_name == _('Black'):
  7865. new_color = '#000000' + alpha_level
  7866. if act_name == _('Custom'):
  7867. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7868. c_dialog = QtWidgets.QColorDialog()
  7869. plot_fill_color = c_dialog.getColor(initial=new_color)
  7870. if plot_fill_color.isValid() is False:
  7871. return
  7872. new_color = str(plot_fill_color.name()) + alpha_level
  7873. if act_name == _("Default"):
  7874. for sel_obj in sel_obj_list:
  7875. if sel_obj.kind == 'excellon':
  7876. new_color = self.defaults['excellon_plot_fill']
  7877. new_line_color = self.defaults['excellon_plot_line']
  7878. elif sel_obj.kind == 'gerber':
  7879. new_color = self.defaults['gerber_plot_fill']
  7880. new_line_color = self.defaults['gerber_plot_line']
  7881. elif sel_obj.kind == 'geometry':
  7882. new_color = self.defaults['geometry_plot_line']
  7883. new_line_color = self.defaults['geometry_plot_line']
  7884. else:
  7885. log.debug(
  7886. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7887. continue
  7888. sel_obj.fill_color = new_color
  7889. sel_obj.outline_color = new_line_color
  7890. sel_obj.shapes.redraw(
  7891. update_colors=(new_color, new_line_color)
  7892. )
  7893. return
  7894. if act_name == _("Opacity"):
  7895. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7896. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7897. if ok_button:
  7898. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7899. for sel_obj in sel_obj_list:
  7900. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7901. sel_obj.shapes.redraw(
  7902. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7903. )
  7904. return
  7905. new_line_color = color_variant(new_color[:7], 0.7)
  7906. if act_name == _("White"):
  7907. new_line_color = color_variant("#dedede", 0.7)
  7908. for sel_obj in sel_obj_list:
  7909. sel_obj.fill_color = new_color
  7910. sel_obj.outline_color = new_line_color
  7911. sel_obj.shapes.redraw(
  7912. update_colors=(new_color, new_line_color)
  7913. )
  7914. def generate_cnc_job(self, objects):
  7915. """
  7916. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7917. :param objects: Selected objects in the Project Tab
  7918. :return:
  7919. """
  7920. self.defaults.report_usage("generate_cnc_job()")
  7921. # for obj in objects:
  7922. # obj.generatecncjob()
  7923. for obj in objects:
  7924. obj.on_generatecnc_button_click()
  7925. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  7926. """
  7927. Saves the current project to the specified file.
  7928. :param filename: Name of the file in which to save.
  7929. :type filename: str
  7930. :param quit_action: if the project saving will be followed by an app quit; boolean
  7931. :param silent: if True will not display status messages
  7932. :param from_tcl True is run from Tcl Shell
  7933. :return: None
  7934. """
  7935. self.log.debug("save_project()")
  7936. self.save_in_progress = True
  7937. with self.proc_container.new(_("Saving FlatCAM Project")):
  7938. # Capture the latest changes
  7939. # Current object
  7940. try:
  7941. current_object = self.collection.get_active()
  7942. if current_object:
  7943. current_object.read_form()
  7944. except Exception as e:
  7945. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  7946. pass
  7947. # Serialize the whole project
  7948. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7949. "options": self.options,
  7950. "version": self.version}
  7951. if self.defaults["global_save_compressed"] is True:
  7952. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7953. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7954. # # Write
  7955. f.write(g)
  7956. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7957. else:
  7958. # Open file
  7959. try:
  7960. f = open(filename, 'w')
  7961. except IOError:
  7962. App.log.error("Failed to open file for saving: %s", filename)
  7963. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  7964. return
  7965. # Write
  7966. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7967. f.close()
  7968. # verification of the saved project
  7969. # Open and parse
  7970. try:
  7971. saved_f = open(filename, 'r')
  7972. except IOError:
  7973. if silent is False:
  7974. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7975. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  7976. return
  7977. try:
  7978. saved_d = json.load(saved_f, object_hook=dict2obj)
  7979. except Exception:
  7980. if silent is False:
  7981. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7982. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  7983. f.close()
  7984. return
  7985. saved_f.close()
  7986. if silent is False:
  7987. if 'version' in saved_d:
  7988. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  7989. else:
  7990. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  7991. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  7992. tb_settings = QSettings("Open Source", "FlatCAM")
  7993. lock_state = self.ui.lock_action.isChecked()
  7994. tb_settings.setValue('toolbar_lock', lock_state)
  7995. # This will write the setting to the platform specific storage.
  7996. del tb_settings
  7997. # if quit:
  7998. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  7999. # t.start()
  8000. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8001. def start_delayed_quit(self, delay, filename, should_quit=None):
  8002. """
  8003. :param delay: period of checking if project file size is more than zero; in seconds
  8004. :param filename: the name of the project file to be checked periodically for size more than zero
  8005. :param should_quit: if the task finished will be followed by an app quit; boolean
  8006. :return:
  8007. """
  8008. to_quit = should_quit
  8009. self.save_timer = QtCore.QTimer()
  8010. self.save_timer.setInterval(delay)
  8011. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8012. self.save_timer.start()
  8013. def check_project_file_size(self, filename, should_quit=None):
  8014. """
  8015. :param filename: the name of the project file to be checked periodically for size more than zero
  8016. :param should_quit: will quit the app if True; boolean
  8017. :return:
  8018. """
  8019. try:
  8020. if os.stat(filename).st_size > 0:
  8021. self.save_in_progress = False
  8022. self.save_timer.stop()
  8023. if should_quit:
  8024. self.app_quit.emit()
  8025. except Exception:
  8026. traceback.print_exc()
  8027. def save_project_auto(self):
  8028. """
  8029. Called periodically to save the project.
  8030. 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
  8031. # progress.
  8032. :return:
  8033. """
  8034. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8035. self.on_file_saveproject()
  8036. def save_project_auto_update(self):
  8037. """
  8038. Update the auto save time interval value.
  8039. :return:
  8040. """
  8041. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8042. try:
  8043. if self.autosave_timer.isActive():
  8044. self.autosave_timer.stop()
  8045. except Exception:
  8046. pass
  8047. if self.defaults['global_autosave'] is True:
  8048. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8049. self.autosave_timer.start()
  8050. def on_options_app2project(self):
  8051. """
  8052. Callback for Options->Transfer Options->App=>Project. Copies options
  8053. from application defaults to project defaults.
  8054. :return: None
  8055. """
  8056. self.defaults.report_usage("on_options_app2project")
  8057. self.preferencesUiManager.defaults_read_form()
  8058. self.options.update(self.defaults)
  8059. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8060. """
  8061. Shows a message on the FlatCAM Shell
  8062. :param msg: Message to display.
  8063. :param show: Opens the shell.
  8064. :param error: Shows the message as an error.
  8065. :param warning: Shows the message as an warning.
  8066. :param success: Shows the message as an success.
  8067. :param selected: Indicate that something was selected on canvas
  8068. :return: None
  8069. """
  8070. if show:
  8071. self.ui.shell_dock.show()
  8072. try:
  8073. if error:
  8074. self.shell.append_error(msg + "\n")
  8075. elif warning:
  8076. self.shell.append_warning(msg + "\n")
  8077. elif success:
  8078. self.shell.append_success(msg + "\n")
  8079. elif selected:
  8080. self.shell.append_selected(msg + "\n")
  8081. else:
  8082. self.shell.append_output(msg + "\n")
  8083. except AttributeError:
  8084. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8085. class ArgsThread(QtCore.QObject):
  8086. open_signal = pyqtSignal(list)
  8087. start = pyqtSignal()
  8088. stop = pyqtSignal()
  8089. if sys.platform == 'win32':
  8090. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8091. else:
  8092. address = ('/tmp/testipc', 'AF_UNIX')
  8093. def __init__(self):
  8094. super(ArgsThread, self).__init__()
  8095. self.listener = None
  8096. self.thread_exit = False
  8097. self.start.connect(self.run)
  8098. self.stop.connect(self.close_listener)
  8099. def my_loop(self, address):
  8100. try:
  8101. self.listener = Listener(*address)
  8102. while self.thread_exit is False:
  8103. conn = self.listener.accept()
  8104. self.serve(conn)
  8105. except socket.error:
  8106. try:
  8107. conn = Client(*address)
  8108. conn.send(sys.argv)
  8109. conn.send('close')
  8110. # close the current instance only if there are args
  8111. if len(sys.argv) > 1:
  8112. try:
  8113. self.listener.close()
  8114. except Exception:
  8115. pass
  8116. sys.exit()
  8117. except ConnectionRefusedError:
  8118. if sys.platform == 'win32':
  8119. pass
  8120. else:
  8121. os.system('rm /tmp/testipc')
  8122. self.listener = Listener(*address)
  8123. while True:
  8124. conn = self.listener.accept()
  8125. self.serve(conn)
  8126. def serve(self, conn):
  8127. while self.thread_exit is False:
  8128. msg = conn.recv()
  8129. if msg == 'close':
  8130. break
  8131. self.open_signal.emit(msg)
  8132. conn.close()
  8133. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8134. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8135. @pyqtSlot()
  8136. def run(self):
  8137. self.my_loop(self.address)
  8138. @pyqtSlot()
  8139. def close_listener(self):
  8140. self.thread_exit = True
  8141. self.listener.close()
  8142. # end of file